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 { forceNumber, 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 = forceNumber(options.daysPrior)
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 getLocalVideoChannelStats (days?: number) {
439 type: QueryTypes.SELECT as QueryTypes.SELECT,
443 const videoJoin = days
444 ? `INNER JOIN "video" AS "Videos" ON "VideoChannelModel"."id" = "Videos"."channelId" ` +
445 `AND ("Videos"."publishedAt" > Now() - interval '${days}d')`
449 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
450 FROM "videoChannel" AS "VideoChannelModel"
452 INNER JOIN "account" AS "Account" ON "VideoChannelModel"."accountId" = "Account"."id"
453 INNER JOIN "actor" AS "Account->Actor" ON "Account"."actorId" = "Account->Actor"."id"
454 AND "Account->Actor"."serverId" IS NULL`
456 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
457 .then(r => parseInt(r[0].count, 10))
460 const totalLocalVideoChannels = await getLocalVideoChannelStats()
461 const totalLocalDailyActiveVideoChannels = await getLocalVideoChannelStats(1)
462 const totalLocalWeeklyActiveVideoChannels = await getLocalVideoChannelStats(7)
463 const totalLocalMonthlyActiveVideoChannels = await getLocalVideoChannelStats(30)
464 const totalLocalHalfYearActiveVideoChannels = await getLocalVideoChannelStats(180)
467 totalLocalVideoChannels,
468 totalLocalDailyActiveVideoChannels,
469 totalLocalWeeklyActiveVideoChannels,
470 totalLocalMonthlyActiveVideoChannels,
471 totalLocalHalfYearActiveVideoChannels
475 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
479 order: getSort(sort),
482 attributes: [ 'preferredUsername', 'serverId' ],
483 model: ActorModel.unscoped(),
491 return VideoChannelModel
496 static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & {
501 const { actorId } = parameters
504 offset: parameters.start,
505 limit: parameters.count,
506 order: getSort(parameters.sort)
509 const getScope = (forCount: boolean) => {
510 return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }
514 VideoChannelModel.scope(getScope(true)).count(),
515 VideoChannelModel.scope(getScope(false)).findAll(query)
516 ]).then(([ total, data ]) => ({ total, data }))
519 static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {
524 let attributesInclude: any[] = [ literal('0 as similarity') ]
525 let where: WhereOptions
527 if (options.search) {
528 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
529 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
530 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
535 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
538 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
546 include: attributesInclude
548 offset: options.start,
549 limit: options.count,
550 order: getSort(options.sort),
554 const getScope = (forCount: boolean) => {
557 ScopeNames.FOR_API, {
558 ...pick(options, [ 'actorId', 'host', 'handles' ]),
561 } as AvailableForListOptions
567 VideoChannelModel.scope(getScope(true)).count(query),
568 VideoChannelModel.scope(getScope(false)).findAll(query)
569 ]).then(([ total, data ]) => ({ total, data }))
572 static listByAccountForAPI (options: {
580 const escapedSearch = VideoModel.sequelize.escape(options.search)
581 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
582 const where = options.search
586 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
589 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
595 const getQuery = (forCount: boolean) => {
596 const accountModel = forCount
597 ? AccountModel.unscoped()
601 offset: options.start,
602 limit: options.count,
603 order: getSort(options.sort),
608 id: options.accountId
617 const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
619 if (options.withStats === true) {
621 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
626 VideoChannelModel.unscoped().count(getQuery(true)),
627 VideoChannelModel.scope(findScopes).findAll(getQuery(false))
628 ]).then(([ total, data ]) => ({ total, data }))
631 static listAllByAccount (accountId: number): Promise<MChannel[]> {
633 limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
637 model: AccountModel.unscoped(),
646 return VideoChannelModel.findAll(query)
649 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
650 return VideoChannelModel.unscoped()
651 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
652 .findByPk(id, { transaction })
655 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
666 model: ActorImageModel,
675 return VideoChannelModel
676 .scope([ ScopeNames.WITH_ACCOUNT ])
680 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
681 const [ name, host ] = nameWithHost.split('@')
683 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
685 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
688 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
695 preferredUsername: name,
700 model: ActorImageModel,
709 return VideoChannelModel.unscoped()
710 .scope([ ScopeNames.WITH_ACCOUNT ])
714 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
721 preferredUsername: name
730 model: ActorImageModel,
739 return VideoChannelModel.unscoped()
740 .scope([ ScopeNames.WITH_ACCOUNT ])
744 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
745 const actor = this.Actor.toFormattedSummaryJSON()
750 displayName: this.getDisplayName(),
753 avatars: actor.avatars,
755 // TODO: remove, deprecated in 4.2
760 toFormattedJSON (this: MChannelFormattable): VideoChannel {
761 const viewsPerDayString = this.get('viewsPerDay') as string
762 const videosCount = this.get('videosCount') as number
764 let viewsPerDay: { date: Date, views: number }[]
766 if (viewsPerDayString) {
767 viewsPerDay = viewsPerDayString.split(',')
769 const [ dateString, amount ] = v.split('|')
772 date: new Date(dateString),
778 const totalViews = this.get('totalViews') as number
780 const actor = this.Actor.toFormattedJSON()
781 const videoChannel = {
783 displayName: this.getDisplayName(),
784 description: this.description,
785 support: this.support,
786 isLocal: this.Actor.isOwned(),
787 updatedAt: this.updatedAt,
789 ownerAccount: undefined,
795 avatars: actor.avatars,
797 // TODO: remove, deprecated in 4.2
801 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
803 return Object.assign(actor, videoChannel)
806 toActivityPubObject (this: MChannelAP): ActivityPubActor {
807 const obj = this.Actor.toActivityPubObject(this.name)
809 return Object.assign(obj, {
810 summary: this.description,
811 support: this.support,
814 type: 'Person' as 'Person',
815 id: this.Account.Actor.url
821 getLocalUrl (this: MAccountActor | MChannelActor) {
822 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
830 return this.Actor.isOutdated()
833 setAsUpdated (transaction?: Transaction) {
834 return setAsUpdated('videoChannel', this.id, transaction)