Fix lint
[oweals/peertube.git] / server / lib / activitypub / share.ts
1 import { Transaction } from 'sequelize'
2 import { VideoPrivacy } from '../../../shared/models/videos'
3 import { getServerActor } from '../../helpers/utils'
4 import { VideoModel } from '../../models/video/video'
5 import { VideoShareModel } from '../../models/video/video-share'
6 import { sendUndoAnnounce, sendVideoAnnounce } from './send'
7 import { getAnnounceActivityPubUrl } from './url'
8 import { VideoChannelModel } from '../../models/video/video-channel'
9
10 async function shareVideoByServerAndChannel (video: VideoModel, t: Transaction) {
11   if (video.privacy === VideoPrivacy.PRIVATE) return undefined
12
13   return Promise.all([
14     shareByServer(video, t),
15     shareByVideoChannel(video, t)
16   ])
17 }
18
19 async function changeVideoChannelShare (video: VideoModel, oldVideoChannel: VideoChannelModel, t: Transaction) {
20   await undoShareByVideoChannel(video, oldVideoChannel, t)
21
22   await shareByVideoChannel(video, t)
23 }
24
25 export {
26   changeVideoChannelShare,
27   shareVideoByServerAndChannel
28 }
29
30 // ---------------------------------------------------------------------------
31
32 async function shareByServer (video: VideoModel, t: Transaction) {
33   const serverActor = await getServerActor()
34
35   const serverShareUrl = getAnnounceActivityPubUrl(video.url, serverActor)
36   return VideoShareModel.findOrCreate({
37     defaults: {
38       actorId: serverActor.id,
39       videoId: video.id,
40       url: serverShareUrl
41     },
42     where: {
43       url: serverShareUrl
44     },
45     transaction: t
46   }).then(([ serverShare, created ]) => {
47     if (created) return sendVideoAnnounce(serverActor, serverShare, video, t)
48
49     return undefined
50   })
51 }
52
53 async function shareByVideoChannel (video: VideoModel, t: Transaction) {
54   const videoChannelShareUrl = getAnnounceActivityPubUrl(video.url, video.VideoChannel.Actor)
55   return VideoShareModel.findOrCreate({
56     defaults: {
57       actorId: video.VideoChannel.actorId,
58       videoId: video.id,
59       url: videoChannelShareUrl
60     },
61     where: {
62       url: videoChannelShareUrl
63     },
64     transaction: t
65   }).then(([ videoChannelShare, created ]) => {
66     if (created) return sendVideoAnnounce(video.VideoChannel.Actor, videoChannelShare, video, t)
67
68     return undefined
69   })
70 }
71
72 async function undoShareByVideoChannel (video: VideoModel, oldVideoChannel: VideoChannelModel, t: Transaction) {
73   // Load old share
74   const oldShare = await VideoShareModel.load(oldVideoChannel.actorId, video.id, t)
75   if (!oldShare) return new Error('Cannot find old video channel share ' + oldVideoChannel.actorId + ' for video ' + video.id)
76
77   await sendUndoAnnounce(oldVideoChannel.Actor, oldShare, video, t)
78   await oldShare.destroy({ transaction: t })
79 }