Litte SQL optimzation in videos list
[oweals/peertube.git] / server / lib / video-channel.ts
1 import * as Sequelize from 'sequelize'
2 import * as uuidv4 from 'uuid/v4'
3 import { VideoChannelCreate } from '../../shared/models'
4 import { VideoChannelModel } from '../models/video/video-channel'
5 import { buildActorInstance, federateVideoIfNeeded, getVideoChannelActivityPubUrl } from './activitypub'
6 import { VideoModel } from '../models/video/video'
7 import { MAccountId, MChannelDefault, MChannelId } from '../typings/models'
8
9 type CustomVideoChannelModelAccount <T extends MAccountId> = MChannelDefault &
10   { Account?: T }
11
12 async function createLocalVideoChannel <T extends MAccountId> (
13   videoChannelInfo: VideoChannelCreate,
14   account: T,
15   t: Sequelize.Transaction
16 ): Promise<CustomVideoChannelModelAccount<T>> {
17   const uuid = uuidv4()
18   const url = getVideoChannelActivityPubUrl(videoChannelInfo.name)
19   const actorInstance = buildActorInstance('Group', url, videoChannelInfo.name, uuid)
20
21   const actorInstanceCreated = await actorInstance.save({ transaction: t })
22
23   const videoChannelData = {
24     name: videoChannelInfo.displayName,
25     description: videoChannelInfo.description,
26     support: videoChannelInfo.support,
27     accountId: account.id,
28     actorId: actorInstanceCreated.id
29   }
30
31   const videoChannel = new VideoChannelModel(videoChannelData)
32
33   const options = { transaction: t }
34   const videoChannelCreated: CustomVideoChannelModelAccount<T> = await videoChannel.save(options) as MChannelDefault
35
36   // Do not forget to add Account/Actor information to the created video channel
37   videoChannelCreated.Account = account
38   videoChannelCreated.Actor = actorInstanceCreated
39
40   // No need to seed this empty video channel to followers
41   return videoChannelCreated
42 }
43
44 async function federateAllVideosOfChannel (videoChannel: MChannelId) {
45   const videoIds = await VideoModel.getAllIdsFromChannel(videoChannel)
46
47   for (const videoId of videoIds) {
48     const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
49
50     await federateVideoIfNeeded(video, false)
51   }
52 }
53
54 // ---------------------------------------------------------------------------
55
56 export {
57   createLocalVideoChannel,
58   federateAllVideosOfChannel
59 }