]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/process/process-like.ts
Refactor AP playlists
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / process / process-like.ts
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 { getOrCreateAPVideo } from '../videos'
10
11 async function processLikeActivity (options: APProcessorOptions<ActivityLike>) {
12 const { activity, byActor } = options
13 return retryTransactionWrapper(processLikeVideo, byActor, activity)
14 }
15
16 // ---------------------------------------------------------------------------
17
18 export {
19 processLikeActivity
20 }
21
22 // ---------------------------------------------------------------------------
23
24 async function processLikeVideo (byActor: MActorSignature, activity: ActivityLike) {
25 const videoUrl = getAPId(activity.object)
26
27 const byAccount = byActor.Account
28 if (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)
29
30 const { video } = await getOrCreateAPVideo({ videoObject: videoUrl })
31
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
35
36 if (existingRate && existingRate.type === 'dislike') {
37 await video.decrement('dislikes', { transaction: t })
38 }
39
40 await video.increment('likes', { transaction: t })
41
42 const rate = existingRate || new AccountVideoRateModel()
43 rate.type = 'like'
44 rate.videoId = video.id
45 rate.accountId = byAccount.id
46 rate.url = activity.id
47
48 await rate.save({ transaction: t })
49
50 if (video.isOwned()) {
51 // Don't resend the activity to the sender
52 const exceptions = [ byActor ]
53
54 await forwardVideoRelatedActivity(activity, t, exceptions, video)
55 }
56 })
57 }