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