Optimize video view AP processing
[oweals/peertube.git] / server / lib / activitypub / process / process-announce.ts
1 import { ActivityAnnounce } from '../../../../shared/models/activitypub'
2 import { retryTransactionWrapper } from '../../../helpers/database-utils'
3 import { sequelizeTypescript } from '../../../initializers'
4 import { ActorModel } from '../../../models/activitypub/actor'
5 import { VideoModel } from '../../../models/video/video'
6 import { VideoShareModel } from '../../../models/video/video-share'
7 import { getOrCreateActorAndServerAndModel } from '../actor'
8 import { forwardVideoRelatedActivity } from '../send/utils'
9 import { getOrCreateVideoAndAccountAndChannel } from '../videos'
10
11 async function processAnnounceActivity (activity: ActivityAnnounce) {
12   const actorAnnouncer = await getOrCreateActorAndServerAndModel(activity.actor)
13
14   return retryTransactionWrapper(processVideoShare, actorAnnouncer, activity)
15 }
16
17 // ---------------------------------------------------------------------------
18
19 export {
20   processAnnounceActivity
21 }
22
23 // ---------------------------------------------------------------------------
24
25 async function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
26   const objectUri = typeof activity.object === 'string' ? activity.object : activity.object.id
27
28   const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: objectUri })
29
30   return sequelizeTypescript.transaction(async t => {
31     // Add share entry
32
33     const share = {
34       actorId: actorAnnouncer.id,
35       videoId: video.id,
36       url: activity.id
37     }
38
39     const [ , created ] = await VideoShareModel.findOrCreate({
40       where: {
41         url: activity.id
42       },
43       defaults: share,
44       transaction: t
45     })
46
47     if (video.isOwned() && created === true) {
48       // Don't resend the activity to the sender
49       const exceptions = [ actorAnnouncer ]
50
51       await forwardVideoRelatedActivity(activity, t, exceptions, video)
52     }
53
54     return undefined
55   })
56 }