18 } from 'sequelize-typescript'
19 import { ActivityPubActor } from '../../../shared/models/activitypub'
20 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
22 isVideoChannelDescriptionValid,
23 isVideoChannelNameValid,
24 isVideoChannelSupportValid
25 } from '../../helpers/custom-validators/video-channels'
26 import { sendDeleteActor } from '../../lib/activitypub/send'
27 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
28 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
30 import { VideoModel } from './video'
31 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
32 import { ServerModel } from '../server/server'
33 import { FindOptions, Op, literal, ScopeOptions } from 'sequelize'
34 import { AvatarModel } from '../avatar/avatar'
35 import { VideoPlaylistModel } from './video-playlist'
36 import * as Bluebird from 'bluebird'
38 MChannelAccountDefault,
40 MChannelActorAccountDefaultVideos,
43 MChannelSummaryFormattable
44 } from '../../types/models/video'
46 export enum ScopeNames {
49 WITH_ACCOUNT = 'WITH_ACCOUNT',
50 WITH_ACTOR = 'WITH_ACTOR',
51 WITH_VIDEOS = 'WITH_VIDEOS',
52 WITH_STATS = 'WITH_STATS'
55 type AvailableForListOptions = {
60 type AvailableWithStatsOptions = {
64 export type SummaryOptions = {
65 actorRequired?: boolean // Default: true
66 withAccount?: boolean // Default: false
67 withAccountBlockerIds?: number[]
70 @DefaultScope(() => ({
79 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
80 // Only list local channels OR channels that are on an instance followed by actorId
81 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
87 exclude: unusedActorAttributesForAPI
97 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
109 exclude: unusedActorAttributesForAPI
111 model: ActorModel, // Default scope includes avatar and server
119 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
120 const base: FindOptions = {
121 attributes: [ 'id', 'name', 'description', 'actorId' ],
124 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
125 model: ActorModel.unscoped(),
126 required: options.actorRequired ?? true,
129 attributes: [ 'host' ],
130 model: ServerModel.unscoped(),
134 model: AvatarModel.unscoped(),
142 if (options.withAccount === true) {
144 model: AccountModel.scope({
145 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
153 [ScopeNames.WITH_ACCOUNT]: {
161 [ScopeNames.WITH_ACTOR]: {
166 [ScopeNames.WITH_VIDEOS]: {
171 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
172 const daysPrior = parseInt(options.daysPrior + '', 10)
178 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
184 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
188 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
189 `date_trunc('day', now()), '1 day'::interval) AS day ` +
191 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
194 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
195 'AND "video"."channelId" = "VideoChannelModel"."id"' +
196 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
210 tableName: 'videoChannel',
212 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
215 fields: [ 'accountId' ]
218 fields: [ 'actorId' ]
222 export class VideoChannelModel extends Model<VideoChannelModel> {
225 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
231 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
232 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
237 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
238 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
247 @ForeignKey(() => ActorModel)
251 @BelongsTo(() => ActorModel, {
259 @ForeignKey(() => AccountModel)
263 @BelongsTo(() => AccountModel, {
269 Account: AccountModel
271 @HasMany(() => VideoModel, {
281 @HasMany(() => VideoPlaylistModel, {
288 VideoPlaylists: VideoPlaylistModel[]
291 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
292 if (!instance.Actor) {
293 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
296 if (instance.Actor.isOwned()) {
297 return sendDeleteActor(instance.Actor, options.transaction)
303 static countByAccount (accountId: number) {
310 return VideoChannelModel.count(query)
313 static listForApi (parameters: {
319 const { actorId } = parameters
322 offset: parameters.start,
323 limit: parameters.count,
324 order: getSort(parameters.sort)
328 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
330 return VideoChannelModel
332 .findAndCountAll(query)
333 .then(({ rows, count }) => {
334 return { total: count, data: rows }
338 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
342 order: getSort(sort),
345 attributes: [ 'preferredUsername', 'serverId' ],
346 model: ActorModel.unscoped(),
354 return VideoChannelModel
359 static searchForApi (options: {
366 const attributesInclude = []
367 const escapedSearch = VideoModel.sequelize.escape(options.search)
368 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
369 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
373 include: attributesInclude
375 offset: options.start,
376 limit: options.count,
377 order: getSort(options.sort),
381 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
384 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
391 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
393 return VideoChannelModel
395 .findAndCountAll(query)
396 .then(({ rows, count }) => {
397 return { total: count, data: rows }
401 static listByAccount (options: {
409 const escapedSearch = VideoModel.sequelize.escape(options.search)
410 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
411 const where = options.search
415 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
418 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
425 offset: options.start,
426 limit: options.count,
427 order: getSort(options.sort),
432 id: options.accountId
440 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
442 if (options.withStats === true) {
444 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
448 return VideoChannelModel
450 .findAndCountAll(query)
451 .then(({ rows, count }) => {
452 return { total: count, data: rows }
456 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
457 return VideoChannelModel.unscoped()
458 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
462 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
470 return VideoChannelModel.unscoped()
471 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
475 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
476 return VideoChannelModel.unscoped()
477 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
481 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
494 return VideoChannelModel
495 .scope([ ScopeNames.WITH_ACCOUNT ])
499 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
500 const [ name, host ] = nameWithHost.split('@')
502 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
504 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
507 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
514 preferredUsername: name,
521 return VideoChannelModel.unscoped()
522 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
526 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
533 preferredUsername: name
546 return VideoChannelModel.unscoped()
547 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
551 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
558 return VideoChannelModel.unscoped()
559 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
560 .findByPk(id, options)
563 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
564 const actor = this.Actor.toFormattedSummaryJSON()
569 displayName: this.getDisplayName(),
576 toFormattedJSON (this: MChannelFormattable): VideoChannel {
577 const viewsPerDayString = this.get('viewsPerDay') as string
578 const videosCount = this.get('videosCount') as number
580 let viewsPerDay: { date: Date, views: number }[]
582 if (viewsPerDayString) {
583 viewsPerDay = viewsPerDayString.split(',')
585 const [ dateString, amount ] = v.split('|')
588 date: new Date(dateString),
594 const actor = this.Actor.toFormattedJSON()
595 const videoChannel = {
597 displayName: this.getDisplayName(),
598 description: this.description,
599 support: this.support,
600 isLocal: this.Actor.isOwned(),
601 createdAt: this.createdAt,
602 updatedAt: this.updatedAt,
603 ownerAccount: undefined,
608 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
610 return Object.assign(actor, videoChannel)
613 toActivityPubObject (this: MChannelAP): ActivityPubActor {
614 const obj = this.Actor.toActivityPubObject(this.name)
616 return Object.assign(obj, {
617 summary: this.description,
618 support: this.support,
621 type: 'Person' as 'Person',
622 id: this.Account.Actor.url
633 return this.Actor.isOutdated()