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)
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_ACTOR_BANNER]: {
177 model: ActorImageModel,
185 [ScopeNames.WITH_VIDEOS]: {
190 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
191 const daysPrior = parseInt(options.daysPrior + '', 10)
197 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
203 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
207 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
208 `date_trunc('day', now()), '1 day'::interval) AS day ` +
210 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
213 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
214 'AND "video"."channelId" = "VideoChannelModel"."id"' +
215 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
229 tableName: 'videoChannel',
231 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
234 fields: [ 'accountId' ]
237 fields: [ 'actorId' ]
241 export class VideoChannelModel extends Model {
244 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
250 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
251 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
256 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
257 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
266 @ForeignKey(() => ActorModel)
270 @BelongsTo(() => ActorModel, {
278 @ForeignKey(() => AccountModel)
282 @BelongsTo(() => AccountModel, {
288 Account: AccountModel
290 @HasMany(() => VideoModel, {
300 @HasMany(() => VideoPlaylistModel, {
307 VideoPlaylists: VideoPlaylistModel[]
310 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
311 if (!instance.Actor) {
312 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
315 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
317 if (instance.Actor.isOwned()) {
318 return sendDeleteActor(instance.Actor, options.transaction)
324 static countByAccount (accountId: number) {
331 return VideoChannelModel.count(query)
334 static listForApi (parameters: {
340 const { actorId } = parameters
343 offset: parameters.start,
344 limit: parameters.count,
345 order: getSort(parameters.sort)
348 return VideoChannelModel
350 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
352 .findAndCountAll(query)
353 .then(({ rows, count }) => {
354 return { total: count, data: rows }
358 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
362 order: getSort(sort),
365 attributes: [ 'preferredUsername', 'serverId' ],
366 model: ActorModel.unscoped(),
374 return VideoChannelModel
379 static searchForApi (options: {
386 const attributesInclude = []
387 const escapedSearch = VideoModel.sequelize.escape(options.search)
388 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
389 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
393 include: attributesInclude
395 offset: options.start,
396 limit: options.count,
397 order: getSort(options.sort),
401 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
404 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
410 return VideoChannelModel
412 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
414 .findAndCountAll(query)
415 .then(({ rows, count }) => {
416 return { total: count, data: rows }
420 static listByAccount (options: {
428 const escapedSearch = VideoModel.sequelize.escape(options.search)
429 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
430 const where = options.search
434 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
437 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
444 offset: options.start,
445 limit: options.count,
446 order: getSort(options.sort),
451 id: options.accountId
459 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
461 if (options.withStats === true) {
463 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
467 return VideoChannelModel
469 .findAndCountAll(query)
470 .then(({ rows, count }) => {
471 return { total: count, data: rows }
475 static loadAndPopulateAccount (id: number): Promise<MChannelBannerAccountDefault> {
476 return VideoChannelModel.unscoped()
477 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
481 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
492 model: ActorImageModel,
501 return VideoChannelModel
502 .scope([ ScopeNames.WITH_ACCOUNT ])
506 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
507 const [ name, host ] = nameWithHost.split('@')
509 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
511 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
514 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
521 preferredUsername: name,
526 model: ActorImageModel,
535 return VideoChannelModel.unscoped()
536 .scope([ ScopeNames.WITH_ACCOUNT ])
540 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
547 preferredUsername: name
556 model: ActorImageModel,
565 return VideoChannelModel.unscoped()
566 .scope([ ScopeNames.WITH_ACCOUNT ])
570 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
571 const actor = this.Actor.toFormattedSummaryJSON()
576 displayName: this.getDisplayName(),
583 toFormattedJSON (this: MChannelFormattable): VideoChannel {
584 const viewsPerDayString = this.get('viewsPerDay') as string
585 const videosCount = this.get('videosCount') as number
587 let viewsPerDay: { date: Date, views: number }[]
589 if (viewsPerDayString) {
590 viewsPerDay = viewsPerDayString.split(',')
592 const [ dateString, amount ] = v.split('|')
595 date: new Date(dateString),
601 const actor = this.Actor.toFormattedJSON()
602 const videoChannel = {
604 displayName: this.getDisplayName(),
605 description: this.description,
606 support: this.support,
607 isLocal: this.Actor.isOwned(),
608 createdAt: this.createdAt,
609 updatedAt: this.updatedAt,
610 ownerAccount: undefined,
615 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
617 return Object.assign(actor, videoChannel)
620 toActivityPubObject (this: MChannelAP): ActivityPubActor {
621 const obj = this.Actor.toActivityPubObject(this.name)
623 return Object.assign(obj, {
624 summary: this.description,
625 support: this.support,
628 type: 'Person' as 'Person',
629 id: this.Account.Actor.url
635 getLocalUrl (this: MAccountActor | MChannelActor) {
636 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
644 return this.Actor.isOutdated()