Fix player play exception on chromium
[oweals/peertube.git] / server / lib / activitypub / process / process-announce.ts
1 import { ActivityAnnounce } from '../../../../shared/models/activitypub'
2 import { logger, retryTransactionWrapper } from '../../../helpers'
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 { processCreateActivity } from './process-create'
10
11 async function processAnnounceActivity (activity: ActivityAnnounce) {
12   const announcedActivity = activity.object
13   const actorAnnouncer = await getOrCreateActorAndServerAndModel(activity.actor)
14
15   if (announcedActivity.type === 'Create' && announcedActivity.object.type === 'Video') {
16     return processVideoShare(actorAnnouncer, activity)
17   }
18
19   logger.warn(
20     'Unknown activity object type %s -> %s when announcing activity.', announcedActivity.type, announcedActivity.object.type,
21     { activity: activity.id }
22   )
23
24   return undefined
25 }
26
27 // ---------------------------------------------------------------------------
28
29 export {
30   processAnnounceActivity
31 }
32
33 // ---------------------------------------------------------------------------
34
35 function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
36   const options = {
37     arguments: [ actorAnnouncer, activity ],
38     errorMessage: 'Cannot share the video with many retries.'
39   }
40
41   return retryTransactionWrapper(shareVideo, options)
42 }
43
44 function shareVideo (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
45   const announcedActivity = activity.object
46
47   return sequelizeTypescript.transaction(async t => {
48     // Add share entry
49     const video: VideoModel = await processCreateActivity(announcedActivity)
50
51     const share = {
52       actorId: actorAnnouncer.id,
53       videoId: video.id
54     }
55
56     const [ , created ] = await VideoShareModel.findOrCreate({
57       where: share,
58       defaults: share,
59       transaction: t
60     })
61
62     if (video.isOwned() && created === true) {
63       // Don't resend the activity to the sender
64       const exceptions = [ actorAnnouncer ]
65       await forwardActivity(activity, t, exceptions)
66     }
67
68     return undefined
69   })
70 }