Split types and typings
[oweals/peertube.git] / server / lib / activitypub / process / process-like.ts
1 import { ActivityLike } from '../../../../shared/models/activitypub'
2 import { retryTransactionWrapper } from '../../../helpers/database-utils'
3 import { sequelizeTypescript } from '../../../initializers/database'
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 '../../../types/activitypub-processor.model'
10 import { MActorSignature } from '../../../types/models'
11
12 async function processLikeActivity (options: APProcessorOptions<ActivityLike>) {
13   const { activity, byActor } = options
14   return retryTransactionWrapper(processLikeVideo, byActor, activity)
15 }
16
17 // ---------------------------------------------------------------------------
18
19 export {
20   processLikeActivity
21 }
22
23 // ---------------------------------------------------------------------------
24
25 async function processLikeVideo (byActor: MActorSignature, activity: ActivityLike) {
26   const videoUrl = getAPId(activity.object)
27
28   const byAccount = byActor.Account
29   if (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)
30
31   const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: videoUrl })
32
33   return sequelizeTypescript.transaction(async t => {
34     const url = getVideoLikeActivityPubUrl(byActor, video)
35
36     const existingRate = await AccountVideoRateModel.loadByAccountAndVideoOrUrl(byAccount.id, video.id, url)
37     if (existingRate && existingRate.type === 'like') return
38
39     if (existingRate && existingRate.type === 'dislike') {
40       await video.decrement('dislikes', { transaction: t })
41     }
42
43     await video.increment('likes', { transaction: t })
44
45     const rate = existingRate || new AccountVideoRateModel()
46     rate.type = 'like'
47     rate.videoId = video.id
48     rate.accountId = byAccount.id
49     rate.url = url
50
51     await rate.save({ transaction: t })
52
53     if (video.isOwned()) {
54       // Don't resend the activity to the sender
55       const exceptions = [ byActor ]
56
57       await forwardVideoRelatedActivity(activity, t, exceptions, video)
58     }
59   })
60 }