1 import { ActivityLike } from '../../../../shared/models/activitypub'
2 import { retryTransactionWrapper } from '../../../helpers/database-utils'
3 import { sequelizeTypescript } from '../../../initializers'
4 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
5 import { forwardVideoRelatedActivity } from '../send/utils'
6 import { getOrCreateVideoAndAccountAndChannel } from '../videos'
7 import { getVideoLikeActivityPubUrl } from '../url'
8 import { getAPId } from '../../../helpers/activitypub'
9 import { APProcessorOptions } from '../../../typings/activitypub-processor.model'
10 import { MActorSignature } from '../../../typings/models'
12 async function processLikeActivity (options: APProcessorOptions<ActivityLike>) {
13 const { activity, byActor } = options
14 return retryTransactionWrapper(processLikeVideo, byActor, activity)
17 // ---------------------------------------------------------------------------
23 // ---------------------------------------------------------------------------
25 async function processLikeVideo (byActor: MActorSignature, activity: ActivityLike) {
26 const videoUrl = getAPId(activity.object)
28 const byAccount = byActor.Account
29 if (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)
31 const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: videoUrl })
33 return sequelizeTypescript.transaction(async t => {
34 const url = getVideoLikeActivityPubUrl(byActor, video)
36 const existingRate = await AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, url)
37 if (existingRate && existingRate.type === 'like') return
39 if (existingRate && existingRate.type === 'dislike') {
40 await video.decrement('dislikes', { transaction: t })
43 await video.increment('likes', { transaction: t })
45 const rate = existingRate || new AccountVideoRateModel()
47 rate.videoId = video.id
48 rate.accountId = byAccount.id
51 await rate.save({ transaction: t })
53 if (video.isOwned()) {
54 // Don't resend the activity to the sender
55 const exceptions = [ byActor ]
57 await forwardVideoRelatedActivity(activity, t, exceptions, video)