]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/video-channels.ts
Fix bad to/cc when undo dislike
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / video-channels.ts
CommitLineData
892211e8
C
1import { VideoChannelObject } from '../../../shared/models/activitypub/objects/video-channel-object'
2import { isVideoChannelObjectValid } from '../../helpers/custom-validators/activitypub/video-channels'
3import { logger } from '../../helpers/logger'
4import { doRequest } from '../../helpers/requests'
5import { database as db } from '../../initializers'
6import { ACTIVITY_PUB } from '../../initializers/constants'
7import { AccountInstance } from '../../models/account/account-interface'
8import { videoChannelActivityObjectToDBAttributes } from './process/misc'
9
10async 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
25async 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
57export {
58 getOrCreateVideoChannel,
59 fetchRemoteVideoChannel
60}