1 import { FindOptions, Includeable, literal, Op, ScopeOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { MAccountActor } from '@server/types/models'
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 { ActorImageModel } from '../account/actor-image'
40 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
41 import { ActorFollowModel } from '../activitypub/actor-follow'
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 include: Includeable[] = [
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: ActorImageModel.unscoped(),
141 const base: FindOptions = {
142 attributes: [ 'id', 'name', 'description', 'actorId' ]
145 if (options.withAccount === true) {
147 model: AccountModel.scope({
148 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
154 base.include = include
158 [ScopeNames.WITH_ACCOUNT]: {
166 [ScopeNames.WITH_ACTOR]: {
171 [ScopeNames.WITH_VIDEOS]: {
176 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
177 const daysPrior = parseInt(options.daysPrior + '', 10)
183 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
189 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
193 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
194 `date_trunc('day', now()), '1 day'::interval) AS day ` +
196 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
199 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
200 'AND "video"."channelId" = "VideoChannelModel"."id"' +
201 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
215 tableName: 'videoChannel',
217 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
220 fields: [ 'accountId' ]
223 fields: [ 'actorId' ]
227 export class VideoChannelModel extends Model {
230 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
236 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
237 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
242 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
243 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
252 @ForeignKey(() => ActorModel)
256 @BelongsTo(() => ActorModel, {
264 @ForeignKey(() => AccountModel)
268 @BelongsTo(() => AccountModel, {
274 Account: AccountModel
276 @HasMany(() => VideoModel, {
286 @HasMany(() => VideoPlaylistModel, {
293 VideoPlaylists: VideoPlaylistModel[]
296 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
297 if (!instance.Actor) {
298 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
301 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
303 if (instance.Actor.isOwned()) {
304 return sendDeleteActor(instance.Actor, options.transaction)
310 static countByAccount (accountId: number) {
317 return VideoChannelModel.count(query)
320 static listForApi (parameters: {
326 const { actorId } = parameters
329 offset: parameters.start,
330 limit: parameters.count,
331 order: getSort(parameters.sort)
334 return VideoChannelModel
336 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
338 .findAndCountAll(query)
339 .then(({ rows, count }) => {
340 return { total: count, data: rows }
344 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
348 order: getSort(sort),
351 attributes: [ 'preferredUsername', 'serverId' ],
352 model: ActorModel.unscoped(),
360 return VideoChannelModel
365 static searchForApi (options: {
372 const attributesInclude = []
373 const escapedSearch = VideoModel.sequelize.escape(options.search)
374 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
375 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
379 include: attributesInclude
381 offset: options.start,
382 limit: options.count,
383 order: getSort(options.sort),
387 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
390 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
396 return VideoChannelModel
398 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
400 .findAndCountAll(query)
401 .then(({ rows, count }) => {
402 return { total: count, data: rows }
406 static listByAccount (options: {
414 const escapedSearch = VideoModel.sequelize.escape(options.search)
415 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
416 const where = options.search
420 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
423 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
430 offset: options.start,
431 limit: options.count,
432 order: getSort(options.sort),
437 id: options.accountId
445 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
447 if (options.withStats === true) {
449 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
453 return VideoChannelModel
455 .findAndCountAll(query)
456 .then(({ rows, count }) => {
457 return { total: count, data: rows }
461 static loadByIdAndPopulateAccount (id: number): Promise<MChannelAccountDefault> {
462 return VideoChannelModel.unscoped()
463 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
467 static loadByIdAndAccount (id: number, accountId: number): Promise<MChannelAccountDefault> {
475 return VideoChannelModel.unscoped()
476 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
480 static loadAndPopulateAccount (id: number): Promise<MChannelAccountDefault> {
481 return VideoChannelModel.unscoped()
482 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
486 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelAccountDefault> {
499 return VideoChannelModel
500 .scope([ ScopeNames.WITH_ACCOUNT ])
504 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
505 const [ name, host ] = nameWithHost.split('@')
507 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
509 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
512 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelAccountDefault> {
519 preferredUsername: name,
526 return VideoChannelModel.unscoped()
527 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
531 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelAccountDefault> {
538 preferredUsername: name
551 return VideoChannelModel.unscoped()
552 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
556 static loadAndPopulateAccountAndVideos (id: number): Promise<MChannelActorAccountDefaultVideos> {
563 return VideoChannelModel.unscoped()
564 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
565 .findByPk(id, options)
568 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
569 const actor = this.Actor.toFormattedSummaryJSON()
574 displayName: this.getDisplayName(),
581 toFormattedJSON (this: MChannelFormattable): VideoChannel {
582 const viewsPerDayString = this.get('viewsPerDay') as string
583 const videosCount = this.get('videosCount') as number
585 let viewsPerDay: { date: Date, views: number }[]
587 if (viewsPerDayString) {
588 viewsPerDay = viewsPerDayString.split(',')
590 const [ dateString, amount ] = v.split('|')
593 date: new Date(dateString),
599 const actor = this.Actor.toFormattedJSON()
600 const videoChannel = {
602 displayName: this.getDisplayName(),
603 description: this.description,
604 support: this.support,
605 isLocal: this.Actor.isOwned(),
606 createdAt: this.createdAt,
607 updatedAt: this.updatedAt,
608 ownerAccount: undefined,
613 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
615 return Object.assign(actor, videoChannel)
618 toActivityPubObject (this: MChannelAP): ActivityPubActor {
619 const obj = this.Actor.toActivityPubObject(this.name)
621 return Object.assign(obj, {
622 summary: this.description,
623 support: this.support,
626 type: 'Person' as 'Person',
627 id: this.Account.Actor.url
633 getLocalUrl (this: MAccountActor | MChannelActor) {
634 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
642 return this.Actor.isOutdated()