1 import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { CONFIG } from '@server/initializers/config'
21 import { MAccountActor } from '@server/types/models'
22 import { pick } from '@shared/core-utils'
23 import { AttributesOnly } from '@shared/typescript-utils'
24 import { ActivityPubActor } from '../../../shared/models/activitypub'
25 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
27 isVideoChannelDescriptionValid,
28 isVideoChannelDisplayNameValid,
29 isVideoChannelSupportValid
30 } from '../../helpers/custom-validators/video-channels'
31 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
32 import { sendDeleteActor } from '../../lib/activitypub/send'
37 MChannelBannerAccountDefault,
39 MChannelSummaryFormattable
40 } from '../../types/models/video'
41 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
42 import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor'
43 import { ActorFollowModel } from '../actor/actor-follow'
44 import { ActorImageModel } from '../actor/actor-image'
45 import { ServerModel } from '../server/server'
46 import { setAsUpdated } from '../shared'
47 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
48 import { VideoModel } from './video'
49 import { VideoPlaylistModel } from './video-playlist'
51 export enum ScopeNames {
54 WITH_ACCOUNT = 'WITH_ACCOUNT',
55 WITH_ACTOR = 'WITH_ACTOR',
56 WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
57 WITH_VIDEOS = 'WITH_VIDEOS',
58 WITH_STATS = 'WITH_STATS'
61 type AvailableForListOptions = {
69 type AvailableWithStatsOptions = {
73 export type SummaryOptions = {
74 actorRequired?: boolean // Default: true
75 withAccount?: boolean // Default: false
76 withAccountBlockerIds?: number[]
79 @DefaultScope(() => ({
88 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
89 // Only list local channels OR channels that are on an instance followed by actorId
90 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
92 const whereActorAnd: WhereOptions[] = [
100 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
107 let serverRequired = false
108 let whereServer: WhereOptions
110 if (options.host && options.host !== WEBSERVER.HOST) {
111 serverRequired = true
112 whereServer = { host: options.host }
115 if (options.host === WEBSERVER.HOST) {
121 if (Array.isArray(options.handles) && options.handles.length !== 0) {
122 const or: string[] = []
124 for (const handle of options.handles || []) {
125 const [ preferredUsername, host ] = handle.split('@')
127 if (!host || host === WEBSERVER.HOST) {
128 or.push(`("preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} AND "serverId" IS NULL)`)
132 `"preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} ` +
133 `AND "host" = ${VideoChannelModel.sequelize.escape(host)}` +
141 [Op.in]: literal(`(SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" WHERE ${or.join(' OR ')})`)
146 const channelActorInclude: Includeable[] = []
147 const accountActorInclude: Includeable[] = []
149 if (options.forCount !== true) {
150 accountActorInclude.push({
155 accountActorInclude.push({
156 model: ActorImageModel,
161 channelActorInclude.push({
162 model: ActorImageModel,
167 channelActorInclude.push({
168 model: ActorImageModel,
174 if (options.forCount !== true || serverRequired) {
175 channelActorInclude.push({
178 required: serverRequired,
187 exclude: unusedActorAttributesForAPI
189 model: ActorModel.unscoped(),
191 [Op.and]: whereActorAnd
193 include: channelActorInclude
196 model: AccountModel.unscoped(),
201 exclude: unusedActorAttributesForAPI
203 model: ActorModel.unscoped(),
205 include: accountActorInclude
212 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
213 const include: Includeable[] = [
215 attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
216 model: ActorModel.unscoped(),
217 required: options.actorRequired ?? true,
220 attributes: [ 'host' ],
221 model: ServerModel.unscoped(),
225 model: ActorImageModel,
233 const base: FindOptions = {
234 attributes: [ 'id', 'name', 'description', 'actorId' ]
237 if (options.withAccount === true) {
239 model: AccountModel.scope({
240 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
246 base.include = include
250 [ScopeNames.WITH_ACCOUNT]: {
258 [ScopeNames.WITH_ACTOR]: {
263 [ScopeNames.WITH_ACTOR_BANNER]: {
269 model: ActorImageModel,
277 [ScopeNames.WITH_VIDEOS]: {
282 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
283 const daysPrior = parseInt(options.daysPrior + '', 10)
289 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
295 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
299 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
300 `date_trunc('day', now()), '1 day'::interval) AS day ` +
302 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
305 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
306 'AND "video"."channelId" = "VideoChannelModel"."id"' +
307 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
318 'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' +
320 'WHERE "video"."channelId" = "VideoChannelModel"."id"' +
331 tableName: 'videoChannel',
333 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
336 fields: [ 'accountId' ]
339 fields: [ 'actorId' ]
343 export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
346 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name'))
352 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
353 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
358 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
359 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
368 @ForeignKey(() => ActorModel)
372 @BelongsTo(() => ActorModel, {
380 @ForeignKey(() => AccountModel)
384 @BelongsTo(() => AccountModel, {
389 Account: AccountModel
391 @HasMany(() => VideoModel, {
401 @HasMany(() => VideoPlaylistModel, {
408 VideoPlaylists: VideoPlaylistModel[]
411 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
412 if (!instance.Actor) {
413 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
416 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
418 if (instance.Actor.isOwned()) {
419 return sendDeleteActor(instance.Actor, options.transaction)
425 static countByAccount (accountId: number) {
432 return VideoChannelModel.unscoped().count(query)
435 static async getStats () {
437 function getActiveVideoChannels (days: number) {
439 type: QueryTypes.SELECT as QueryTypes.SELECT,
444 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
445 FROM "videoChannel" AS "VideoChannelModel"
446 INNER JOIN "video" AS "Videos"
447 ON "VideoChannelModel"."id" = "Videos"."channelId"
448 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
449 INNER JOIN "account" AS "Account"
450 ON "VideoChannelModel"."accountId" = "Account"."id"
451 INNER JOIN "actor" AS "Account->Actor"
452 ON "Account"."actorId" = "Account->Actor"."id"
453 AND "Account->Actor"."serverId" IS NULL
454 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
455 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
457 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
458 .then(r => parseInt(r[0].count, 10))
461 const totalLocalVideoChannels = await VideoChannelModel.count()
462 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
463 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
464 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
465 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
468 totalLocalVideoChannels,
469 totalLocalDailyActiveVideoChannels,
470 totalLocalWeeklyActiveVideoChannels,
471 totalLocalMonthlyActiveVideoChannels,
472 totalHalfYearActiveVideoChannels
476 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
480 order: getSort(sort),
483 attributes: [ 'preferredUsername', 'serverId' ],
484 model: ActorModel.unscoped(),
492 return VideoChannelModel
497 static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & {
502 const { actorId } = parameters
505 offset: parameters.start,
506 limit: parameters.count,
507 order: getSort(parameters.sort)
510 const getScope = (forCount: boolean) => {
511 return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }
515 VideoChannelModel.scope(getScope(true)).count(),
516 VideoChannelModel.scope(getScope(false)).findAll(query)
517 ]).then(([ total, data ]) => ({ total, data }))
520 static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {
525 let attributesInclude: any[] = [ literal('0 as similarity') ]
526 let where: WhereOptions
528 if (options.search) {
529 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
530 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
531 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
536 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
539 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
547 include: attributesInclude
549 offset: options.start,
550 limit: options.count,
551 order: getSort(options.sort),
555 const getScope = (forCount: boolean) => {
558 ScopeNames.FOR_API, {
559 ...pick(options, [ 'actorId', 'host', 'handles' ]),
562 } as AvailableForListOptions
568 VideoChannelModel.scope(getScope(true)).count(query),
569 VideoChannelModel.scope(getScope(false)).findAll(query)
570 ]).then(([ total, data ]) => ({ total, data }))
573 static listByAccountForAPI (options: {
581 const escapedSearch = VideoModel.sequelize.escape(options.search)
582 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
583 const where = options.search
587 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
590 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
596 const getQuery = (forCount: boolean) => {
597 const accountModel = forCount
598 ? AccountModel.unscoped()
602 offset: options.start,
603 limit: options.count,
604 order: getSort(options.sort),
609 id: options.accountId
618 const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
620 if (options.withStats === true) {
622 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
627 VideoChannelModel.unscoped().count(getQuery(true)),
628 VideoChannelModel.scope(findScopes).findAll(getQuery(false))
629 ]).then(([ total, data ]) => ({ total, data }))
632 static listAllByAccount (accountId: number): Promise<MChannel[]> {
634 limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
638 model: AccountModel.unscoped(),
647 return VideoChannelModel.findAll(query)
650 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
651 return VideoChannelModel.unscoped()
652 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
653 .findByPk(id, { transaction })
656 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
667 model: ActorImageModel,
676 return VideoChannelModel
677 .scope([ ScopeNames.WITH_ACCOUNT ])
681 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
682 const [ name, host ] = nameWithHost.split('@')
684 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
686 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
689 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
696 preferredUsername: name,
701 model: ActorImageModel,
710 return VideoChannelModel.unscoped()
711 .scope([ ScopeNames.WITH_ACCOUNT ])
715 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
722 preferredUsername: name
731 model: ActorImageModel,
740 return VideoChannelModel.unscoped()
741 .scope([ ScopeNames.WITH_ACCOUNT ])
745 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
746 const actor = this.Actor.toFormattedSummaryJSON()
751 displayName: this.getDisplayName(),
754 avatars: actor.avatars,
756 // TODO: remove, deprecated in 4.2
761 toFormattedJSON (this: MChannelFormattable): VideoChannel {
762 const viewsPerDayString = this.get('viewsPerDay') as string
763 const videosCount = this.get('videosCount') as number
765 let viewsPerDay: { date: Date, views: number }[]
767 if (viewsPerDayString) {
768 viewsPerDay = viewsPerDayString.split(',')
770 const [ dateString, amount ] = v.split('|')
773 date: new Date(dateString),
779 const totalViews = this.get('totalViews') as number
781 const actor = this.Actor.toFormattedJSON()
782 const videoChannel = {
784 displayName: this.getDisplayName(),
785 description: this.description,
786 support: this.support,
787 isLocal: this.Actor.isOwned(),
788 updatedAt: this.updatedAt,
790 ownerAccount: undefined,
796 avatars: actor.avatars,
798 // TODO: remove, deprecated in 4.2
802 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
804 return Object.assign(actor, videoChannel)
807 toActivityPubObject (this: MChannelAP): ActivityPubActor {
808 const obj = this.Actor.toActivityPubObject(this.name)
810 return Object.assign(obj, {
811 summary: this.description,
812 support: this.support,
815 type: 'Person' as 'Person',
816 id: this.Account.Actor.url
822 getLocalUrl (this: MAccountActor | MChannelActor) {
823 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
831 return this.Actor.isOutdated()
834 setAsUpdated (transaction?: Transaction) {
835 return setAsUpdated('videoChannel', this.id, transaction)