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