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 = {
59 type AvailableWithStatsOptions = {
63 export type SummaryOptions = {
64 actorRequired?: boolean // Default: true
65 withAccount?: boolean // Default: false
66 withAccountBlockerIds?: number[]
69 @DefaultScope(() => ({
78 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
79 // Only list local channels OR channels that are on an instance followed by actorId
80 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
86 exclude: unusedActorAttributesForAPI
96 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
108 exclude: unusedActorAttributesForAPI
110 model: ActorModel, // Default scope includes avatar and server
118 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
119 const base: FindOptions = {
120 attributes: [ 'id', 'name', 'description', 'actorId' ],
123 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
124 model: ActorModel.unscoped(),
125 required: options.actorRequired ?? true,
128 attributes: [ 'host' ],
129 model: ServerModel.unscoped(),
133 model: AvatarModel.unscoped(),
141 if (options.withAccount === true) {
143 model: AccountModel.scope({
144 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
152 [ScopeNames.WITH_ACCOUNT]: {
160 [ScopeNames.WITH_ACTOR]: {
165 [ScopeNames.WITH_VIDEOS]: {
170 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
171 const daysPrior = parseInt(options.daysPrior + '', 10)
177 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
183 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
187 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
188 `date_trunc('day', now()), '1 day'::interval) AS day ` +
190 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
193 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
194 'AND "video"."channelId" = "VideoChannelModel"."id"' +
195 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
209 tableName: 'videoChannel',
211 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
214 fields: [ 'accountId' ]
217 fields: [ 'actorId' ]
221 export class VideoChannelModel extends Model<VideoChannelModel> {
224 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
230 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
231 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
236 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
237 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
246 @ForeignKey(() => ActorModel)
250 @BelongsTo(() => ActorModel, {
258 @ForeignKey(() => AccountModel)
262 @BelongsTo(() => AccountModel, {
268 Account: AccountModel
270 @HasMany(() => VideoModel, {
280 @HasMany(() => VideoPlaylistModel, {
287 VideoPlaylists: VideoPlaylistModel[]
290 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
291 if (!instance.Actor) {
292 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
295 if (instance.Actor.isOwned()) {
296 return sendDeleteActor(instance.Actor, options.transaction)
302 static countByAccount (accountId: number) {
309 return VideoChannelModel.count(query)
312 static listForApi (actorId: number, start: number, count: number, sort: string) {
320 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
322 return VideoChannelModel
324 .findAndCountAll(query)
325 .then(({ rows, count }) => {
326 return { total: count, data: rows }
330 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
334 order: getSort(sort),
337 attributes: [ 'preferredUsername', 'serverId' ],
338 model: ActorModel.unscoped(),
346 return VideoChannelModel
351 static searchForApi (options: {
358 const attributesInclude = []
359 const escapedSearch = VideoModel.sequelize.escape(options.search)
360 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
361 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
365 include: attributesInclude
367 offset: options.start,
368 limit: options.count,
369 order: getSort(options.sort),
373 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
376 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
383 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
385 return VideoChannelModel
387 .findAndCountAll(query)
388 .then(({ rows, count }) => {
389 return { total: count, data: rows }
393 static listByAccount (options: {
401 offset: options.start,
402 limit: options.count,
403 order: getSort(options.sort),
408 id: options.accountId
415 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
417 if (options.withStats === true) {
419 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
423 return VideoChannelModel
425 .findAndCountAll(query)
426 .then(({ rows, count }) => {
427 return { total: count, data: rows }
431 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
432 return VideoChannelModel.unscoped()
433 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
437 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
445 return VideoChannelModel.unscoped()
446 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
450 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
451 return VideoChannelModel.unscoped()
452 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
456 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
469 return VideoChannelModel
470 .scope([ ScopeNames.WITH_ACCOUNT ])
474 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
475 const [ name, host ] = nameWithHost.split('@')
477 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
479 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
482 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
489 preferredUsername: name,
496 return VideoChannelModel.unscoped()
497 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
501 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
508 preferredUsername: name
521 return VideoChannelModel.unscoped()
522 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
526 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
533 return VideoChannelModel.unscoped()
534 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
535 .findByPk(id, options)
538 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
539 const actor = this.Actor.toFormattedSummaryJSON()
544 displayName: this.getDisplayName(),
551 toFormattedJSON (this: MChannelFormattable): VideoChannel {
552 const viewsPerDayString = this.get('viewsPerDay') as string
553 const videosCount = this.get('videosCount') as number
555 let viewsPerDay: { date: Date, views: number }[]
557 if (viewsPerDayString) {
558 viewsPerDay = viewsPerDayString.split(',')
560 const [ dateString, amount ] = v.split('|')
563 date: new Date(dateString),
569 const actor = this.Actor.toFormattedJSON()
570 const videoChannel = {
572 displayName: this.getDisplayName(),
573 description: this.description,
574 support: this.support,
575 isLocal: this.Actor.isOwned(),
576 createdAt: this.createdAt,
577 updatedAt: this.updatedAt,
578 ownerAccount: undefined,
583 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
585 return Object.assign(actor, videoChannel)
588 toActivityPubObject (this: MChannelAP): ActivityPubActor {
589 const obj = this.Actor.toActivityPubObject(this.name)
591 return Object.assign(obj, {
592 summary: this.description,
593 support: this.support,
596 type: 'Person' as 'Person',
597 id: this.Account.Actor.url
608 return this.Actor.isOutdated()