]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/process/process-announce.ts
5568ff538d21ae7f9e290d6627fe6c09ca33da8d
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / process / process-announce.ts
1 import { ActivityAnnounce, ActivityCreate } 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 (typeof announcedActivity === 'string') {
16 return processVideoShare(actorAnnouncer, activity)
17 } else if (announcedActivity.type === 'Create' && announcedActivity.object.type === 'Video') {
18 return processVideoShare(actorAnnouncer, activity)
19 }
20
21 logger.warn(
22 'Unknown activity object type %s -> %s when announcing activity.', announcedActivity.type, announcedActivity.object.type,
23 { activity: activity.id }
24 )
25
26 return undefined
27 }
28
29 // ---------------------------------------------------------------------------
30
31 export {
32 processAnnounceActivity
33 }
34
35 // ---------------------------------------------------------------------------
36
37 function processVideoShare (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
38 const options = {
39 arguments: [ actorAnnouncer, activity ],
40 errorMessage: 'Cannot share the video activity with many retries.'
41 }
42
43 return retryTransactionWrapper(shareVideo, options)
44 }
45
46 function shareVideo (actorAnnouncer: ActorModel, activity: ActivityAnnounce) {
47 const announced = activity.object
48
49 return sequelizeTypescript.transaction(async t => {
50 // Add share entry
51 let video: VideoModel
52
53 if (typeof announced === 'string') {
54 video = await VideoModel.loadByUrlAndPopulateAccount(announced as string)
55 if (!video) throw new Error('Unknown video to share ' + announced)
56 } else {
57 video = await processCreateActivity(announced as ActivityCreate)
58 }
59
60 const share = {
61 actorId: actorAnnouncer.id,
62 videoId: video.id
63 }
64
65 const [ , created ] = await VideoShareModel.findOrCreate({
66 where: share,
67 defaults: share,
68 transaction: t
69 })
70
71 if (video.isOwned() && created === true) {
72 // Don't resend the activity to the sender
73 const exceptions = [ actorAnnouncer ]
74 await forwardActivity(activity, t, exceptions)
75 }
76
77 return undefined
78 })
79 }