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'
33 MChannelBannerAccountDefault,
35 MChannelSummaryFormattable
36 } from '../../types/models/video'
37 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
38 import { ActorImageModel } from '../account/actor-image'
39 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
40 import { ActorFollowModel } from '../activitypub/actor-follow'
41 import { ServerModel } from '../server/server'
42 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
43 import { VideoModel } from './video'
44 import { VideoPlaylistModel } from './video-playlist'
46 export enum ScopeNames {
49 WITH_ACCOUNT = 'WITH_ACCOUNT',
50 WITH_ACTOR = 'WITH_ACTOR',
51 WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
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)
105 model: ActorImageModel,
117 exclude: unusedActorAttributesForAPI
119 model: ActorModel, // Default scope includes avatar and server
127 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
128 const include: Includeable[] = [
130 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
131 model: ActorModel.unscoped(),
132 required: options.actorRequired ?? true,
135 attributes: [ 'host' ],
136 model: ServerModel.unscoped(),
140 model: ActorImageModel.unscoped(),
148 const base: FindOptions = {
149 attributes: [ 'id', 'name', 'description', 'actorId' ]
152 if (options.withAccount === true) {
154 model: AccountModel.scope({
155 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
161 base.include = include
165 [ScopeNames.WITH_ACCOUNT]: {
173 [ScopeNames.WITH_ACTOR]: {
178 [ScopeNames.WITH_ACTOR_BANNER]: {
184 model: ActorImageModel,
192 [ScopeNames.WITH_VIDEOS]: {
197 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
198 const daysPrior = parseInt(options.daysPrior + '', 10)
204 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
210 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
214 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
215 `date_trunc('day', now()), '1 day'::interval) AS day ` +
217 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
220 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
221 'AND "video"."channelId" = "VideoChannelModel"."id"' +
222 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
236 tableName: 'videoChannel',
238 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
241 fields: [ 'accountId' ]
244 fields: [ 'actorId' ]
248 export class VideoChannelModel extends Model {
251 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
257 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
258 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
263 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
264 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
273 @ForeignKey(() => ActorModel)
277 @BelongsTo(() => ActorModel, {
285 @ForeignKey(() => AccountModel)
289 @BelongsTo(() => AccountModel, {
295 Account: AccountModel
297 @HasMany(() => VideoModel, {
307 @HasMany(() => VideoPlaylistModel, {
314 VideoPlaylists: VideoPlaylistModel[]
317 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
318 if (!instance.Actor) {
319 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
322 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
324 if (instance.Actor.isOwned()) {
325 return sendDeleteActor(instance.Actor, options.transaction)
331 static countByAccount (accountId: number) {
338 return VideoChannelModel.count(query)
341 static listForApi (parameters: {
347 const { actorId } = parameters
350 offset: parameters.start,
351 limit: parameters.count,
352 order: getSort(parameters.sort)
355 return VideoChannelModel
357 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
359 .findAndCountAll(query)
360 .then(({ rows, count }) => {
361 return { total: count, data: rows }
365 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
369 order: getSort(sort),
372 attributes: [ 'preferredUsername', 'serverId' ],
373 model: ActorModel.unscoped(),
381 return VideoChannelModel
386 static searchForApi (options: {
393 const attributesInclude = []
394 const escapedSearch = VideoModel.sequelize.escape(options.search)
395 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
396 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
400 include: attributesInclude
402 offset: options.start,
403 limit: options.count,
404 order: getSort(options.sort),
408 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
411 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
417 return VideoChannelModel
419 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
421 .findAndCountAll(query)
422 .then(({ rows, count }) => {
423 return { total: count, data: rows }
427 static listByAccount (options: {
435 const escapedSearch = VideoModel.sequelize.escape(options.search)
436 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
437 const where = options.search
441 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
444 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
451 offset: options.start,
452 limit: options.count,
453 order: getSort(options.sort),
458 id: options.accountId
466 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
468 if (options.withStats === true) {
470 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
474 return VideoChannelModel
476 .findAndCountAll(query)
477 .then(({ rows, count }) => {
478 return { total: count, data: rows }
482 static loadAndPopulateAccount (id: number): Promise<MChannelBannerAccountDefault> {
483 return VideoChannelModel.unscoped()
484 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
488 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
499 model: ActorImageModel,
508 return VideoChannelModel
509 .scope([ ScopeNames.WITH_ACCOUNT ])
513 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
514 const [ name, host ] = nameWithHost.split('@')
516 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
518 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
521 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
528 preferredUsername: name,
533 model: ActorImageModel,
542 return VideoChannelModel.unscoped()
543 .scope([ ScopeNames.WITH_ACCOUNT ])
547 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
554 preferredUsername: name
563 model: ActorImageModel,
572 return VideoChannelModel.unscoped()
573 .scope([ ScopeNames.WITH_ACCOUNT ])
577 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
578 const actor = this.Actor.toFormattedSummaryJSON()
583 displayName: this.getDisplayName(),
590 toFormattedJSON (this: MChannelFormattable): VideoChannel {
591 const viewsPerDayString = this.get('viewsPerDay') as string
592 const videosCount = this.get('videosCount') as number
594 let viewsPerDay: { date: Date, views: number }[]
596 if (viewsPerDayString) {
597 viewsPerDay = viewsPerDayString.split(',')
599 const [ dateString, amount ] = v.split('|')
602 date: new Date(dateString),
608 const actor = this.Actor.toFormattedJSON()
609 const videoChannel = {
611 displayName: this.getDisplayName(),
612 description: this.description,
613 support: this.support,
614 isLocal: this.Actor.isOwned(),
615 createdAt: this.createdAt,
616 updatedAt: this.updatedAt,
617 ownerAccount: undefined,
622 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
624 return Object.assign(actor, videoChannel)
627 toActivityPubObject (this: MChannelAP): ActivityPubActor {
628 const obj = this.Actor.toActivityPubObject(this.name)
630 return Object.assign(obj, {
631 summary: this.description,
632 support: this.support,
635 type: 'Person' as 'Person',
636 id: this.Account.Actor.url
642 getLocalUrl (this: MAccountActor | MChannelActor) {
643 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
651 return this.Actor.isOutdated()