Merge branch 'release/v1.0.0' into develop
[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 { VideoShareModel } from '../../../models/video/video-share'
6 import { forwardVideoRelatedActivity } from '../send/utils'
7 import { getOrCreateVideoAndAccountAndChannel } from '../videos'
8
9 async function processAnnounceActivity (activity: ActivityAnnounce, actorAnnouncer: ActorModel) {
10   return retryTransactionWrapper(processVideoShare, actorAnnouncer, activity)
11 }
12
13 // ---------------------------------------------------------------------------
14
15 export {
16   processAnnounceActivity
17 }
18
19 // ---------------------------------------------------------------------------
20
21 async function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
22   const objectUri = typeof activity.object === 'string' ? activity.object : activity.object.id
23
24   const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: objectUri })
25
26   return sequelizeTypescript.transaction(async t => {
27     // Add share entry
28
29     const share = {
30       actorId: actorAnnouncer.id,
31       videoId: video.id,
32       url: activity.id
33     }
34
35     const [ , created ] = await VideoShareModel.findOrCreate({
36       where: {
37         url: activity.id
38       },
39       defaults: share,
40       transaction: t
41     })
42
43     if (video.isOwned() && created === true) {
44       // Don't resend the activity to the sender
45       const exceptions = [ actorAnnouncer ]
46
47       await forwardVideoRelatedActivity(activity, t, exceptions, video)
48     }
49
50     return undefined
51   })
52 }