aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/activitypub/video-channels.ts
blob: c05a46f95ba7b60ed1d4bfe82d810d5a412a8942 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { VideoChannelObject } from '../../../shared/models/activitypub/objects'
import { doRequest, logger } from '../../helpers'
import { isVideoChannelObjectValid } from '../../helpers/custom-validators/activitypub'
import { ACTIVITY_PUB } from '../../initializers'
import { AccountModel } from '../../models/account/account'
import { VideoChannelModel } from '../../models/video/video-channel'
import { videoChannelActivityObjectToDBAttributes } from './process/misc'

async function getOrCreateVideoChannel (ownerAccount: AccountModel, videoChannelUrl: string) {
  let videoChannel = await VideoChannelModel.loadByUrl(videoChannelUrl)

  // We don't have this account in our database, fetch it on remote
  if (!videoChannel) {
    videoChannel = await fetchRemoteVideoChannel(ownerAccount, videoChannelUrl)
    if (videoChannel === undefined) throw new Error('Cannot fetch remote video channel.')

    // Save our new video channel in database
    await videoChannel.save()
  }

  return videoChannel
}

async function fetchRemoteVideoChannel (ownerAccount: AccountModel, videoChannelUrl: string) {
  const options = {
    uri: videoChannelUrl,
    method: 'GET',
    headers: {
      'Accept': ACTIVITY_PUB.ACCEPT_HEADER
    }
  }

  logger.info('Fetching remote video channel %s.', videoChannelUrl)

  let requestResult
  try {
    requestResult = await doRequest(options)
  } catch (err) {
    logger.warn('Cannot fetch remote video channel %s.', videoChannelUrl, err)
    return undefined
  }

  const videoChannelJSON: VideoChannelObject = JSON.parse(requestResult.body)
  if (isVideoChannelObjectValid(videoChannelJSON) === false) {
    logger.debug('Remote video channel JSON is not valid.', { videoChannelJSON })
    return undefined
  }

  const videoChannelAttributes = videoChannelActivityObjectToDBAttributes(videoChannelJSON, ownerAccount)
  const videoChannel = new VideoChannelModel(videoChannelAttributes)
  videoChannel.Account = ownerAccount

  return videoChannel
}

export {
  getOrCreateVideoChannel,
  fetchRemoteVideoChannel
}