1 import { FindOptions, Includeable, literal, Op, QueryTypes, 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 async getStats () {
343 function getActiveVideoChannels (days: number) {
345 type: QueryTypes.SELECT as QueryTypes.SELECT,
350 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
351 FROM "videoChannel" AS "VideoChannelModel"
352 INNER JOIN "video" AS "Videos"
353 ON "VideoChannelModel"."id" = "Videos"."channelId"
354 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
355 INNER JOIN "account" AS "Account"
356 ON "VideoChannelModel"."accountId" = "Account"."id"
357 INNER JOIN "actor" AS "Account->Actor"
358 ON "Account"."actorId" = "Account->Actor"."id"
359 AND "Account->Actor"."serverId" IS NULL
360 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
361 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
363 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
364 .then(r => parseInt(r[0].count, 10))
367 const totalLocalVideoChannels = await VideoChannelModel.count()
368 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
369 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
370 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
371 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
374 totalLocalVideoChannels,
375 totalLocalDailyActiveVideoChannels,
376 totalLocalWeeklyActiveVideoChannels,
377 totalLocalMonthlyActiveVideoChannels,
378 totalHalfYearActiveVideoChannels
382 static listForApi (parameters: {
388 const { actorId } = parameters
391 offset: parameters.start,
392 limit: parameters.count,
393 order: getSort(parameters.sort)
396 return VideoChannelModel
398 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
400 .findAndCountAll(query)
401 .then(({ rows, count }) => {
402 return { total: count, data: rows }
406 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
410 order: getSort(sort),
413 attributes: [ 'preferredUsername', 'serverId' ],
414 model: ActorModel.unscoped(),
422 return VideoChannelModel
427 static searchForApi (options: {
434 const attributesInclude = []
435 const escapedSearch = VideoModel.sequelize.escape(options.search)
436 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
437 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
441 include: attributesInclude
443 offset: options.start,
444 limit: options.count,
445 order: getSort(options.sort),
449 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
452 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
458 return VideoChannelModel
460 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
462 .findAndCountAll(query)
463 .then(({ rows, count }) => {
464 return { total: count, data: rows }
468 static listByAccount (options: {
476 const escapedSearch = VideoModel.sequelize.escape(options.search)
477 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
478 const where = options.search
482 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
485 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
492 offset: options.start,
493 limit: options.count,
494 order: getSort(options.sort),
499 id: options.accountId
507 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
509 if (options.withStats === true) {
511 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
515 return VideoChannelModel
517 .findAndCountAll(query)
518 .then(({ rows, count }) => {
519 return { total: count, data: rows }
523 static loadAndPopulateAccount (id: number): Promise<MChannelBannerAccountDefault> {
524 return VideoChannelModel.unscoped()
525 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
529 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
540 model: ActorImageModel,
549 return VideoChannelModel
550 .scope([ ScopeNames.WITH_ACCOUNT ])
554 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
555 const [ name, host ] = nameWithHost.split('@')
557 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
559 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
562 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
569 preferredUsername: name,
574 model: ActorImageModel,
583 return VideoChannelModel.unscoped()
584 .scope([ ScopeNames.WITH_ACCOUNT ])
588 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
595 preferredUsername: name
604 model: ActorImageModel,
613 return VideoChannelModel.unscoped()
614 .scope([ ScopeNames.WITH_ACCOUNT ])
618 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
619 const actor = this.Actor.toFormattedSummaryJSON()
624 displayName: this.getDisplayName(),
631 toFormattedJSON (this: MChannelFormattable): VideoChannel {
632 const viewsPerDayString = this.get('viewsPerDay') as string
633 const videosCount = this.get('videosCount') as number
635 let viewsPerDay: { date: Date, views: number }[]
637 if (viewsPerDayString) {
638 viewsPerDay = viewsPerDayString.split(',')
640 const [ dateString, amount ] = v.split('|')
643 date: new Date(dateString),
649 const actor = this.Actor.toFormattedJSON()
650 const videoChannel = {
652 displayName: this.getDisplayName(),
653 description: this.description,
654 support: this.support,
655 isLocal: this.Actor.isOwned(),
656 createdAt: this.createdAt,
657 updatedAt: this.updatedAt,
658 ownerAccount: undefined,
663 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
665 return Object.assign(actor, videoChannel)
668 toActivityPubObject (this: MChannelAP): ActivityPubActor {
669 const obj = this.Actor.toActivityPubObject(this.name)
671 return Object.assign(obj, {
672 summary: this.description,
673 support: this.support,
676 type: 'Person' as 'Person',
677 id: this.Account.Actor.url
683 getLocalUrl (this: MAccountActor | MChannelActor) {
684 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
692 return this.Actor.isOutdated()