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