Fix video announces processing
[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'
4 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
5 import { ActorModel } from '../../../models/activitypub/actor'
6 import { getOrCreateActorAndServerAndModel } from '../actor'
7 import { forwardActivity } from '../send/misc'
8 import { getOrCreateAccountAndVideoAndChannel } from '../videos'
9
10 async function processLikeActivity (activity: ActivityLike) {
11   const actor = await getOrCreateActorAndServerAndModel(activity.actor)
12
13   return processLikeVideo(actor, activity)
14 }
15
16 // ---------------------------------------------------------------------------
17
18 export {
19   processLikeActivity
20 }
21
22 // ---------------------------------------------------------------------------
23
24 async function processLikeVideo (actor: ActorModel, activity: ActivityLike) {
25   const options = {
26     arguments: [ actor, activity ],
27     errorMessage: 'Cannot like the video with many retries.'
28   }
29
30   return retryTransactionWrapper(createVideoLike, options)
31 }
32
33 async function createVideoLike (byActor: ActorModel, activity: ActivityLike) {
34   const videoUrl = activity.object
35
36   const byAccount = byActor.Account
37   if (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)
38
39   const { video } = await getOrCreateAccountAndVideoAndChannel(videoUrl)
40
41   return sequelizeTypescript.transaction(async t => {
42     const rate = {
43       type: 'like' as 'like',
44       videoId: video.id,
45       accountId: byAccount.id
46     }
47     const [ , created ] = await AccountVideoRateModel.findOrCreate({
48       where: rate,
49       defaults: rate,
50       transaction: t
51     })
52     if (created === true) await video.increment('likes', { transaction: t })
53
54     if (video.isOwned() && created === true) {
55       // Don't resend the activity to the sender
56       const exceptions = [ byActor ]
57       await forwardActivity(activity, t, exceptions)
58     }
59   })
60 }