1 import * as Bluebird from 'bluebird'
2 import { FindOptions, literal, Op, ScopeOptions } from 'sequelize'
20 } from 'sequelize-typescript'
21 import { ActivityPubActor } from '../../../shared/models/activitypub'
22 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
24 isVideoChannelDescriptionValid,
25 isVideoChannelNameValid,
26 isVideoChannelSupportValid
27 } from '../../helpers/custom-validators/video-channels'
28 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
29 import { sendDeleteActor } from '../../lib/activitypub/send'
31 MChannelAccountDefault,
33 MChannelActorAccountDefaultVideos,
36 MChannelSummaryFormattable
37 } from '../../types/models/video'
38 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
39 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
40 import { ActorFollowModel } from '../activitypub/actor-follow'
41 import { AvatarModel } from '../avatar/avatar'
42 import { ServerModel } from '../server/server'
43 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
44 import { VideoModel } from './video'
45 import { VideoPlaylistModel } from './video-playlist'
47 export enum ScopeNames {
50 WITH_ACCOUNT = 'WITH_ACCOUNT',
51 WITH_ACTOR = 'WITH_ACTOR',
52 WITH_VIDEOS = 'WITH_VIDEOS',
53 WITH_STATS = 'WITH_STATS'
56 type AvailableForListOptions = {
61 type AvailableWithStatsOptions = {
65 export type SummaryOptions = {
66 actorRequired?: boolean // Default: true
67 withAccount?: boolean // Default: false
68 withAccountBlockerIds?: number[]
71 @DefaultScope(() => ({
80 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
81 // Only list local channels OR channels that are on an instance followed by actorId
82 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
88 exclude: unusedActorAttributesForAPI
98 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
110 exclude: unusedActorAttributesForAPI
112 model: ActorModel, // Default scope includes avatar and server
120 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
121 const base: FindOptions = {
122 attributes: [ 'id', 'name', 'description', 'actorId' ],
125 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
126 model: ActorModel.unscoped(),
127 required: options.actorRequired ?? true,
130 attributes: [ 'host' ],
131 model: ServerModel.unscoped(),
135 model: AvatarModel.unscoped(),
143 if (options.withAccount === true) {
145 model: AccountModel.scope({
146 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
154 [ScopeNames.WITH_ACCOUNT]: {
162 [ScopeNames.WITH_ACTOR]: {
167 [ScopeNames.WITH_VIDEOS]: {
172 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
173 const daysPrior = parseInt(options.daysPrior + '', 10)
179 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
185 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
189 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
190 `date_trunc('day', now()), '1 day'::interval) AS day ` +
192 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
195 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
196 'AND "video"."channelId" = "VideoChannelModel"."id"' +
197 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
211 tableName: 'videoChannel',
213 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
216 fields: [ 'accountId' ]
219 fields: [ 'actorId' ]
223 export class VideoChannelModel extends Model<VideoChannelModel> {
226 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
232 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
233 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
238 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
239 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
248 @ForeignKey(() => ActorModel)
252 @BelongsTo(() => ActorModel, {
260 @ForeignKey(() => AccountModel)
264 @BelongsTo(() => AccountModel, {
270 Account: AccountModel
272 @HasMany(() => VideoModel, {
282 @HasMany(() => VideoPlaylistModel, {
289 VideoPlaylists: VideoPlaylistModel[]
292 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
293 if (!instance.Actor) {
294 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
297 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
299 if (instance.Actor.isOwned()) {
300 return sendDeleteActor(instance.Actor, options.transaction)
306 static countByAccount (accountId: number) {
313 return VideoChannelModel.count(query)
316 static listForApi (parameters: {
322 const { actorId } = parameters
325 offset: parameters.start,
326 limit: parameters.count,
327 order: getSort(parameters.sort)
331 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
333 return VideoChannelModel
335 .findAndCountAll(query)
336 .then(({ rows, count }) => {
337 return { total: count, data: rows }
341 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
345 order: getSort(sort),
348 attributes: [ 'preferredUsername', 'serverId' ],
349 model: ActorModel.unscoped(),
357 return VideoChannelModel
362 static searchForApi (options: {
369 const attributesInclude = []
370 const escapedSearch = VideoModel.sequelize.escape(options.search)
371 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
372 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
376 include: attributesInclude
378 offset: options.start,
379 limit: options.count,
380 order: getSort(options.sort),
384 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
387 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
394 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
396 return VideoChannelModel
398 .findAndCountAll(query)
399 .then(({ rows, count }) => {
400 return { total: count, data: rows }
404 static listByAccount (options: {
412 const escapedSearch = VideoModel.sequelize.escape(options.search)
413 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
414 const where = options.search
418 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
421 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
428 offset: options.start,
429 limit: options.count,
430 order: getSort(options.sort),
435 id: options.accountId
443 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
445 if (options.withStats === true) {
447 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
451 return VideoChannelModel
453 .findAndCountAll(query)
454 .then(({ rows, count }) => {
455 return { total: count, data: rows }
459 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
460 return VideoChannelModel.unscoped()
461 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
465 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
473 return VideoChannelModel.unscoped()
474 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
478 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
479 return VideoChannelModel.unscoped()
480 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
484 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
497 return VideoChannelModel
498 .scope([ ScopeNames.WITH_ACCOUNT ])
502 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
503 const [ name, host ] = nameWithHost.split('@')
505 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
507 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
510 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
517 preferredUsername: name,
524 return VideoChannelModel.unscoped()
525 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
529 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
536 preferredUsername: name
549 return VideoChannelModel.unscoped()
550 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
554 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
561 return VideoChannelModel.unscoped()
562 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
563 .findByPk(id, options)
566 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
567 const actor = this.Actor.toFormattedSummaryJSON()
572 displayName: this.getDisplayName(),
579 toFormattedJSON (this: MChannelFormattable): VideoChannel {
580 const viewsPerDayString = this.get('viewsPerDay') as string
581 const videosCount = this.get('videosCount') as number
583 let viewsPerDay: { date: Date, views: number }[]
585 if (viewsPerDayString) {
586 viewsPerDay = viewsPerDayString.split(',')
588 const [ dateString, amount ] = v.split('|')
591 date: new Date(dateString),
597 const actor = this.Actor.toFormattedJSON()
598 const videoChannel = {
600 displayName: this.getDisplayName(),
601 description: this.description,
602 support: this.support,
603 isLocal: this.Actor.isOwned(),
604 createdAt: this.createdAt,
605 updatedAt: this.updatedAt,
606 ownerAccount: undefined,
611 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
613 return Object.assign(actor, videoChannel)
616 toActivityPubObject (this: MChannelAP): ActivityPubActor {
617 const obj = this.Actor.toActivityPubObject(this.name)
619 return Object.assign(obj, {
620 summary: this.description,
621 support: this.support,
624 type: 'Person' as 'Person',
625 id: this.Account.Actor.url
636 return this.Actor.isOutdated()