Fix video announces 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 { forwardActivity } from '../send/misc'
9 import { getOrCreateAccountAndVideoAndChannel } from '../videos'
10
11 async function processAnnounceActivity (activity: ActivityAnnounce) {
12   const actorAnnouncer = await getOrCreateActorAndServerAndModel(activity.actor)
13
14   return processVideoShare(actorAnnouncer, activity)
15 }
16
17 // ---------------------------------------------------------------------------
18
19 export {
20   processAnnounceActivity
21 }
22
23 // ---------------------------------------------------------------------------
24
25 function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
26   const options = {
27     arguments: [ actorAnnouncer, activity ],
28     errorMessage: 'Cannot share the video activity with many retries.'
29   }
30
31   return retryTransactionWrapper(shareVideo, options)
32 }
33
34 async function shareVideo (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
35   const objectUri = typeof activity.object === 'string' ? activity.object : activity.object.id
36   let video: VideoModel
37
38   const res = await getOrCreateAccountAndVideoAndChannel(objectUri)
39   video = res.video
40
41   return sequelizeTypescript.transaction(async t => {
42     // Add share entry
43
44     const share = {
45       actorId: actorAnnouncer.id,
46       videoId: video.id,
47       url: activity.id
48     }
49
50     const [ , created ] = await VideoShareModel.findOrCreate({
51       where: {
52         url: activity.id
53       },
54       defaults: share,
55       transaction: t
56     })
57
58     if (video.isOwned() && created === true) {
59       // Don't resend the activity to the sender
60       const exceptions = [ actorAnnouncer ]
61       await forwardActivity(activity, t, exceptions)
62     }
63
64     return undefined
65   })
66 }