Add shares forward and collection on videos/video channels
[oweals/peertube.git] / server / lib / activitypub / video-channels.ts
1 import { VideoChannelObject } from '../../../shared/models/activitypub/objects/video-channel-object'
2 import { isVideoChannelObjectValid } from '../../helpers/custom-validators/activitypub/video-channels'
3 import { logger } from '../../helpers/logger'
4 import { doRequest } from '../../helpers/requests'
5 import { database as db } from '../../initializers'
6 import { ACTIVITY_PUB } from '../../initializers/constants'
7 import { AccountInstance } from '../../models/account/account-interface'
8 import { videoChannelActivityObjectToDBAttributes } from './process/misc'
9
10 async function getOrCreateVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
11   let videoChannel = await db.VideoChannel.loadByUrl(videoChannelUrl)
12
13   // We don't have this account in our database, fetch it on remote
14   if (!videoChannel) {
15     videoChannel = await fetchRemoteVideoChannel(ownerAccount, videoChannelUrl)
16     if (videoChannel === undefined) throw new Error('Cannot fetch remote video channel.')
17
18     // Save our new video channel in database
19     await videoChannel.save()
20   }
21
22   return videoChannel
23 }
24
25 async function fetchRemoteVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
26   const options = {
27     uri: videoChannelUrl,
28     method: 'GET',
29     headers: {
30       'Accept': ACTIVITY_PUB.ACCEPT_HEADER
31     }
32   }
33
34   logger.info('Fetching remote video channel %s.', videoChannelUrl)
35
36   let requestResult
37   try {
38     requestResult = await doRequest(options)
39   } catch (err) {
40     logger.warn('Cannot fetch remote video channel %s.', videoChannelUrl, err)
41     return undefined
42   }
43
44   const videoChannelJSON: VideoChannelObject = JSON.parse(requestResult.body)
45   if (isVideoChannelObjectValid(videoChannelJSON) === false) {
46     logger.debug('Remote video channel JSON is not valid.', { videoChannelJSON })
47     return undefined
48   }
49
50   const videoChannelAttributes = videoChannelActivityObjectToDBAttributes(videoChannelJSON, ownerAccount)
51   const videoChannel = db.VideoChannel.build(videoChannelAttributes)
52   videoChannel.Account = ownerAccount
53
54   return videoChannel
55 }
56
57 export {
58   getOrCreateVideoChannel,
59   fetchRemoteVideoChannel
60 }