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: {
320 const { actorId, search } = parameters
323 offset: parameters.start,
324 limit: parameters.count,
325 order: getSort(parameters.sort)
329 method: [ ScopeNames.FOR_API, { actorId, search } as AvailableForListOptions ]
331 return VideoChannelModel
333 .findAndCountAll(query)
334 .then(({ rows, count }) => {
335 return { total: count, data: rows }
339 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
343 order: getSort(sort),
346 attributes: [ 'preferredUsername', 'serverId' ],
347 model: ActorModel.unscoped(),
355 return VideoChannelModel
360 static searchForApi (options: {
367 const attributesInclude = []
368 const escapedSearch = VideoModel.sequelize.escape(options.search)
369 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
370 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
374 include: attributesInclude
376 offset: options.start,
377 limit: options.count,
378 order: getSort(options.sort),
382 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
385 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
392 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
394 return VideoChannelModel
396 .findAndCountAll(query)
397 .then(({ rows, count }) => {
398 return { total: count, data: rows }
402 static listByAccount (options: {
410 offset: options.start,
411 limit: options.count,
412 order: getSort(options.sort),
417 id: options.accountId
424 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
426 if (options.withStats === true) {
428 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
432 return VideoChannelModel
434 .findAndCountAll(query)
435 .then(({ rows, count }) => {
436 return { total: count, data: rows }
440 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
441 return VideoChannelModel.unscoped()
442 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
446 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
454 return VideoChannelModel.unscoped()
455 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
459 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
460 return VideoChannelModel.unscoped()
461 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
465 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
478 return VideoChannelModel
479 .scope([ ScopeNames.WITH_ACCOUNT ])
483 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
484 const [ name, host ] = nameWithHost.split('@')
486 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
488 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
491 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
498 preferredUsername: name,
505 return VideoChannelModel.unscoped()
506 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
510 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
517 preferredUsername: name
530 return VideoChannelModel.unscoped()
531 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
535 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
542 return VideoChannelModel.unscoped()
543 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
544 .findByPk(id, options)
547 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
548 const actor = this.Actor.toFormattedSummaryJSON()
553 displayName: this.getDisplayName(),
560 toFormattedJSON (this: MChannelFormattable): VideoChannel {
561 const viewsPerDayString = this.get('viewsPerDay') as string
562 const videosCount = this.get('videosCount') as number
564 let viewsPerDay: { date: Date, views: number }[]
566 if (viewsPerDayString) {
567 viewsPerDay = viewsPerDayString.split(',')
569 const [ dateString, amount ] = v.split('|')
572 date: new Date(dateString),
578 const actor = this.Actor.toFormattedJSON()
579 const videoChannel = {
581 displayName: this.getDisplayName(),
582 description: this.description,
583 support: this.support,
584 isLocal: this.Actor.isOwned(),
585 createdAt: this.createdAt,
586 updatedAt: this.updatedAt,
587 ownerAccount: undefined,
592 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
594 return Object.assign(actor, videoChannel)
597 toActivityPubObject (this: MChannelAP): ActivityPubActor {
598 const obj = this.Actor.toActivityPubObject(this.name)
600 return Object.assign(obj, {
601 summary: this.description,
602 support: this.support,
605 type: 'Person' as 'Person',
606 id: this.Account.Actor.url
617 return this.Actor.isOutdated()