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 { 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 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: AvatarModel.unscoped(),
140 const base: FindOptions = {
141 attributes: [ 'id', 'name', 'description', 'actorId' ]
144 if (options.withAccount === true) {
146 model: AccountModel.scope({
147 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
153 base.include = include
157 [ScopeNames.WITH_ACCOUNT]: {
165 [ScopeNames.WITH_ACTOR]: {
170 [ScopeNames.WITH_VIDEOS]: {
175 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
176 const daysPrior = parseInt(options.daysPrior + '', 10)
182 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
188 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
192 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
193 `date_trunc('day', now()), '1 day'::interval) AS day ` +
195 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
198 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
199 'AND "video"."channelId" = "VideoChannelModel"."id"' +
200 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
214 tableName: 'videoChannel',
216 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
219 fields: [ 'accountId' ]
222 fields: [ 'actorId' ]
226 export class VideoChannelModel extends Model {
229 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
235 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
236 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
241 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
242 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
251 @ForeignKey(() => ActorModel)
255 @BelongsTo(() => ActorModel, {
263 @ForeignKey(() => AccountModel)
267 @BelongsTo(() => AccountModel, {
273 Account: AccountModel
275 @HasMany(() => VideoModel, {
285 @HasMany(() => VideoPlaylistModel, {
292 VideoPlaylists: VideoPlaylistModel[]
295 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
296 if (!instance.Actor) {
297 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
300 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
302 if (instance.Actor.isOwned()) {
303 return sendDeleteActor(instance.Actor, options.transaction)
309 static countByAccount (accountId: number) {
316 return VideoChannelModel.count(query)
319 static listForApi (parameters: {
325 const { actorId } = parameters
328 offset: parameters.start,
329 limit: parameters.count,
330 order: getSort(parameters.sort)
333 return VideoChannelModel
335 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
337 .findAndCountAll(query)
338 .then(({ rows, count }) => {
339 return { total: count, data: rows }
343 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
347 order: getSort(sort),
350 attributes: [ 'preferredUsername', 'serverId' ],
351 model: ActorModel.unscoped(),
359 return VideoChannelModel
364 static searchForApi (options: {
371 const attributesInclude = []
372 const escapedSearch = VideoModel.sequelize.escape(options.search)
373 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
374 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
378 include: attributesInclude
380 offset: options.start,
381 limit: options.count,
382 order: getSort(options.sort),
386 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
389 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
395 return VideoChannelModel
397 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
399 .findAndCountAll(query)
400 .then(({ rows, count }) => {
401 return { total: count, data: rows }
405 static listByAccount (options: {
413 const escapedSearch = VideoModel.sequelize.escape(options.search)
414 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
415 const where = options.search
419 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
422 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
429 offset: options.start,
430 limit: options.count,
431 order: getSort(options.sort),
436 id: options.accountId
444 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
446 if (options.withStats === true) {
448 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
452 return VideoChannelModel
454 .findAndCountAll(query)
455 .then(({ rows, count }) => {
456 return { total: count, data: rows }
460 static loadByIdAndPopulateAccount (id: number): Promise<MChannelAccountDefault> {
461 return VideoChannelModel.unscoped()
462 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
466 static loadByIdAndAccount (id: number, accountId: number): Promise<MChannelAccountDefault> {
474 return VideoChannelModel.unscoped()
475 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
479 static loadAndPopulateAccount (id: number): Promise<MChannelAccountDefault> {
480 return VideoChannelModel.unscoped()
481 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
485 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelAccountDefault> {
498 return VideoChannelModel
499 .scope([ ScopeNames.WITH_ACCOUNT ])
503 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
504 const [ name, host ] = nameWithHost.split('@')
506 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
508 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
511 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelAccountDefault> {
518 preferredUsername: name,
525 return VideoChannelModel.unscoped()
526 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
530 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelAccountDefault> {
537 preferredUsername: name
550 return VideoChannelModel.unscoped()
551 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
555 static loadAndPopulateAccountAndVideos (id: number): Promise<MChannelActorAccountDefaultVideos> {
562 return VideoChannelModel.unscoped()
563 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
564 .findByPk(id, options)
567 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
568 const actor = this.Actor.toFormattedSummaryJSON()
573 displayName: this.getDisplayName(),
580 toFormattedJSON (this: MChannelFormattable): VideoChannel {
581 const viewsPerDayString = this.get('viewsPerDay') as string
582 const videosCount = this.get('videosCount') as number
584 let viewsPerDay: { date: Date, views: number }[]
586 if (viewsPerDayString) {
587 viewsPerDay = viewsPerDayString.split(',')
589 const [ dateString, amount ] = v.split('|')
592 date: new Date(dateString),
598 const actor = this.Actor.toFormattedJSON()
599 const videoChannel = {
601 displayName: this.getDisplayName(),
602 description: this.description,
603 support: this.support,
604 isLocal: this.Actor.isOwned(),
605 createdAt: this.createdAt,
606 updatedAt: this.updatedAt,
607 ownerAccount: undefined,
612 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
614 return Object.assign(actor, videoChannel)
617 toActivityPubObject (this: MChannelAP): ActivityPubActor {
618 const obj = this.Actor.toActivityPubObject(this.name)
620 return Object.assign(obj, {
621 summary: this.description,
622 support: this.support,
625 type: 'Person' as 'Person',
626 id: this.Account.Actor.url
632 getLocalUrl (this: MAccountActor | MChannelActor) {
633 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
641 return this.Actor.isOutdated()