1 import { VideoModel } from '@server/models/video/video'
2 import { ActivityLike } from '../../../../shared/models/activitypub'
3 import { retryTransactionWrapper } from '../../../helpers/database-utils'
4 import { sequelizeTypescript } from '../../../initializers/database'
5 import { getAPId } from '../../../lib/activitypub/activity'
6 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
7 import { APProcessorOptions } from '../../../types/activitypub-processor.model'
8 import { MActorSignature } from '../../../types/models'
9 import { federateVideoIfNeeded, getOrCreateAPVideo } from '../videos'
11 async function processLikeActivity (options: APProcessorOptions<ActivityLike>) {
12 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: onlyVideo } = await getOrCreateAPVideo({ videoObject: videoUrl, fetchType: 'only-video' })
33 // We don't care about likes of remote videos
34 if (!onlyVideo.isOwned()) return
36 return sequelizeTypescript.transaction(async t => {
37 const video = await VideoModel.loadFull(onlyVideo.id, t)
39 const existingRate = await AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, activity.id, t)
40 if (existingRate && existingRate.type === 'like') return
42 if (existingRate && existingRate.type === 'dislike') {
43 await video.decrement('dislikes', { transaction: t })
47 await video.increment('likes', { transaction: t })
50 const rate = existingRate || new AccountVideoRateModel()
52 rate.videoId = video.id
53 rate.accountId = byAccount.id
54 rate.url = activity.id
56 await rate.save({ transaction: t })
58 await federateVideoIfNeeded(video, false, t)