]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/process/process-like.ts
Fix preview 404
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / process / process-like.ts
1 import { ActivityLike } from '../../../../shared/models/activitypub'
2 import { retryTransactionWrapper } from '../../../helpers'
3 import { sequelizeTypescript } from '../../../initializers'
4 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
5 import { ActorModel } from '../../../models/activitypub/actor'
6 import { VideoModel } from '../../../models/video/video'
7 import { getOrCreateActorAndServerAndModel } from '../actor'
8 import { forwardActivity } from '../send/misc'
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 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 return sequelizeTypescript.transaction(async t => {
40 const video = await VideoModel.loadByUrlAndPopulateAccount(videoUrl)
41
42 if (!video) throw new Error('Unknown video ' + videoUrl)
43
44 const rate = {
45 type: 'like' as 'like',
46 videoId: video.id,
47 accountId: byAccount.id
48 }
49 const [ , created ] = await AccountVideoRateModel.findOrCreate({
50 where: rate,
51 defaults: rate,
52 transaction: t
53 })
54 if (created === true) await video.increment('likes', { transaction: t })
55
56 if (video.isOwned() && created === true) {
57 // Don't resend the activity to the sender
58 const exceptions = [ byActor ]
59 await forwardActivity(activity, t, exceptions)
60 }
61 })
62 }