1 import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { setAsUpdated } from '@server/helpers/database-utils'
21 import { MAccountActor } from '@server/types/models'
22 import { ActivityPubActor } from '../../../shared/models/activitypub'
23 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
25 isVideoChannelDescriptionValid,
26 isVideoChannelNameValid,
27 isVideoChannelSupportValid
28 } from '../../helpers/custom-validators/video-channels'
29 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
30 import { sendDeleteActor } from '../../lib/activitypub/send'
34 MChannelBannerAccountDefault,
36 MChannelSummaryFormattable
37 } from '../../types/models/video'
38 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
39 import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor'
40 import { ActorFollowModel } from '../actor/actor-follow'
41 import { ActorImageModel } from '../actor/actor-image'
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_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
53 WITH_VIDEOS = 'WITH_VIDEOS',
54 WITH_STATS = 'WITH_STATS'
57 type AvailableForListOptions = {
62 type AvailableWithStatsOptions = {
66 export type SummaryOptions = {
67 actorRequired?: boolean // Default: true
68 withAccount?: boolean // Default: false
69 withAccountBlockerIds?: number[]
72 @DefaultScope(() => ({
81 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
82 // Only list local channels OR channels that are on an instance followed by actorId
83 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
89 exclude: unusedActorAttributesForAPI
99 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
106 model: ActorImageModel,
118 exclude: unusedActorAttributesForAPI
120 model: ActorModel, // Default scope includes avatar and server
128 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
129 const include: Includeable[] = [
131 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
132 model: ActorModel.unscoped(),
133 required: options.actorRequired ?? true,
136 attributes: [ 'host' ],
137 model: ServerModel.unscoped(),
141 model: ActorImageModel.unscoped(),
149 const base: FindOptions = {
150 attributes: [ 'id', 'name', 'description', 'actorId' ]
153 if (options.withAccount === true) {
155 model: AccountModel.scope({
156 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
162 base.include = include
166 [ScopeNames.WITH_ACCOUNT]: {
174 [ScopeNames.WITH_ACTOR]: {
179 [ScopeNames.WITH_ACTOR_BANNER]: {
185 model: ActorImageModel,
193 [ScopeNames.WITH_VIDEOS]: {
198 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
199 const daysPrior = parseInt(options.daysPrior + '', 10)
205 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
211 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
215 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
216 `date_trunc('day', now()), '1 day'::interval) AS day ` +
218 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
221 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
222 'AND "video"."channelId" = "VideoChannelModel"."id"' +
223 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
237 tableName: 'videoChannel',
239 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
242 fields: [ 'accountId' ]
245 fields: [ 'actorId' ]
249 export class VideoChannelModel extends Model {
252 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
258 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
259 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
264 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
265 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
274 @ForeignKey(() => ActorModel)
278 @BelongsTo(() => ActorModel, {
286 @ForeignKey(() => AccountModel)
290 @BelongsTo(() => AccountModel, {
296 Account: AccountModel
298 @HasMany(() => VideoModel, {
308 @HasMany(() => VideoPlaylistModel, {
315 VideoPlaylists: VideoPlaylistModel[]
318 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
319 if (!instance.Actor) {
320 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
323 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
325 if (instance.Actor.isOwned()) {
326 return sendDeleteActor(instance.Actor, options.transaction)
332 static countByAccount (accountId: number) {
339 return VideoChannelModel.count(query)
342 static async getStats () {
344 function getActiveVideoChannels (days: number) {
346 type: QueryTypes.SELECT as QueryTypes.SELECT,
351 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
352 FROM "videoChannel" AS "VideoChannelModel"
353 INNER JOIN "video" AS "Videos"
354 ON "VideoChannelModel"."id" = "Videos"."channelId"
355 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
356 INNER JOIN "account" AS "Account"
357 ON "VideoChannelModel"."accountId" = "Account"."id"
358 INNER JOIN "actor" AS "Account->Actor"
359 ON "Account"."actorId" = "Account->Actor"."id"
360 AND "Account->Actor"."serverId" IS NULL
361 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
362 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
364 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
365 .then(r => parseInt(r[0].count, 10))
368 const totalLocalVideoChannels = await VideoChannelModel.count()
369 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
370 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
371 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
372 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
375 totalLocalVideoChannels,
376 totalLocalDailyActiveVideoChannels,
377 totalLocalWeeklyActiveVideoChannels,
378 totalLocalMonthlyActiveVideoChannels,
379 totalHalfYearActiveVideoChannels
383 static listForApi (parameters: {
389 const { actorId } = parameters
392 offset: parameters.start,
393 limit: parameters.count,
394 order: getSort(parameters.sort)
397 return VideoChannelModel
399 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
401 .findAndCountAll(query)
402 .then(({ rows, count }) => {
403 return { total: count, data: rows }
407 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
411 order: getSort(sort),
414 attributes: [ 'preferredUsername', 'serverId' ],
415 model: ActorModel.unscoped(),
423 return VideoChannelModel
428 static searchForApi (options: {
435 const attributesInclude = []
436 const escapedSearch = VideoModel.sequelize.escape(options.search)
437 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
438 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
442 include: attributesInclude
444 offset: options.start,
445 limit: options.count,
446 order: getSort(options.sort),
450 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
453 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
459 return VideoChannelModel
461 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
463 .findAndCountAll(query)
464 .then(({ rows, count }) => {
465 return { total: count, data: rows }
469 static listByAccount (options: {
477 const escapedSearch = VideoModel.sequelize.escape(options.search)
478 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
479 const where = options.search
483 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
486 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
493 offset: options.start,
494 limit: options.count,
495 order: getSort(options.sort),
500 id: options.accountId
508 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
510 if (options.withStats === true) {
512 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
516 return VideoChannelModel
518 .findAndCountAll(query)
519 .then(({ rows, count }) => {
520 return { total: count, data: rows }
524 static loadAndPopulateAccount (id: number): Promise<MChannelBannerAccountDefault> {
525 return VideoChannelModel.unscoped()
526 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
530 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
541 model: ActorImageModel,
550 return VideoChannelModel
551 .scope([ ScopeNames.WITH_ACCOUNT ])
555 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
556 const [ name, host ] = nameWithHost.split('@')
558 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
560 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
563 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
570 preferredUsername: name,
575 model: ActorImageModel,
584 return VideoChannelModel.unscoped()
585 .scope([ ScopeNames.WITH_ACCOUNT ])
589 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
596 preferredUsername: name
605 model: ActorImageModel,
614 return VideoChannelModel.unscoped()
615 .scope([ ScopeNames.WITH_ACCOUNT ])
619 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
620 const actor = this.Actor.toFormattedSummaryJSON()
625 displayName: this.getDisplayName(),
632 toFormattedJSON (this: MChannelFormattable): VideoChannel {
633 const viewsPerDayString = this.get('viewsPerDay') as string
634 const videosCount = this.get('videosCount') as number
636 let viewsPerDay: { date: Date, views: number }[]
638 if (viewsPerDayString) {
639 viewsPerDay = viewsPerDayString.split(',')
641 const [ dateString, amount ] = v.split('|')
644 date: new Date(dateString),
650 const actor = this.Actor.toFormattedJSON()
651 const videoChannel = {
653 displayName: this.getDisplayName(),
654 description: this.description,
655 support: this.support,
656 isLocal: this.Actor.isOwned(),
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()
695 setAsUpdated (transaction: Transaction) {
696 return setAsUpdated('videoChannel', this.id, transaction)