Fix lint
[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 { logger } from '../../../helpers/logger'
4 import { sequelizeTypescript } from '../../../initializers'
5 import { ActorModel } from '../../../models/activitypub/actor'
6 import { VideoModel } from '../../../models/video/video'
7 import { VideoShareModel } from '../../../models/video/video-share'
8 import { getOrCreateActorAndServerAndModel } from '../actor'
9 import { forwardActivity } from '../send/misc'
10 import { getOrCreateAccountAndVideoAndChannel } from '../videos'
11 import { processCreateActivity } from './process-create'
12
13 async function processAnnounceActivity (activity: ActivityAnnounce) {
14   const announcedActivity = activity.object
15   const actorAnnouncer = await getOrCreateActorAndServerAndModel(activity.actor)
16
17   if (typeof announcedActivity === 'string') {
18     return processVideoShare(actorAnnouncer, activity)
19   } else if (announcedActivity.type === 'Create' && announcedActivity.object.type === 'Video') {
20     return processVideoShare(actorAnnouncer, activity)
21   }
22
23   logger.warn(
24     'Unknown activity object type %s -> %s when announcing activity.', announcedActivity.type, announcedActivity.object.type,
25     { activity: activity.id }
26   )
27
28   return undefined
29 }
30
31 // ---------------------------------------------------------------------------
32
33 export {
34   processAnnounceActivity
35 }
36
37 // ---------------------------------------------------------------------------
38
39 function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
40   const options = {
41     arguments: [ actorAnnouncer, activity ],
42     errorMessage: 'Cannot share the video activity with many retries.'
43   }
44
45   return retryTransactionWrapper(shareVideo, options)
46 }
47
48 async function shareVideo (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
49   const announced = activity.object
50   let video: VideoModel
51
52   if (typeof announced === 'string') {
53     const res = await getOrCreateAccountAndVideoAndChannel(announced)
54     video = res.video
55   } else {
56     video = await processCreateActivity(announced)
57   }
58
59   return sequelizeTypescript.transaction(async t => {
60     // Add share entry
61
62     const share = {
63       actorId: actorAnnouncer.id,
64       videoId: video.id
65     }
66
67     const [ , created ] = await VideoShareModel.findOrCreate({
68       where: share,
69       defaults: share,
70       transaction: t
71     })
72
73     if (video.isOwned() && created === true) {
74       // Don't resend the activity to the sender
75       const exceptions = [ actorAnnouncer ]
76       await forwardActivity(activity, t, exceptions)
77     }
78
79     return undefined
80   })
81 }