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