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'
47 buildServerIdsFollowedBy,
48 buildTrigramSearchIndex,
49 createSimilarityAttribute,
54 import { VideoModel } from './video'
55 import { VideoPlaylistModel } from './video-playlist'
57 export enum ScopeNames {
60 WITH_ACCOUNT = 'WITH_ACCOUNT',
61 WITH_ACTOR = 'WITH_ACTOR',
62 WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
63 WITH_VIDEOS = 'WITH_VIDEOS',
64 WITH_STATS = 'WITH_STATS'
67 type AvailableForListOptions = {
75 type AvailableWithStatsOptions = {
79 export type SummaryOptions = {
80 actorRequired?: boolean // Default: true
81 withAccount?: boolean // Default: false
82 withAccountBlockerIds?: number[]
85 @DefaultScope(() => ({
94 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
95 // Only list local channels OR channels that are on an instance followed by actorId
96 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
98 const whereActorAnd: WhereOptions[] = [
106 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
113 let serverRequired = false
114 let whereServer: WhereOptions
116 if (options.host && options.host !== WEBSERVER.HOST) {
117 serverRequired = true
118 whereServer = { host: options.host }
121 if (options.host === WEBSERVER.HOST) {
127 if (Array.isArray(options.handles) && options.handles.length !== 0) {
128 const or: string[] = []
130 for (const handle of options.handles || []) {
131 const [ preferredUsername, host ] = handle.split('@')
133 if (!host || host === WEBSERVER.HOST) {
134 or.push(`("preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} AND "serverId" IS NULL)`)
138 `"preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} ` +
139 `AND "host" = ${VideoChannelModel.sequelize.escape(host)}` +
147 [Op.in]: literal(`(SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" WHERE ${or.join(' OR ')})`)
152 const channelActorInclude: Includeable[] = []
153 const accountActorInclude: Includeable[] = []
155 if (options.forCount !== true) {
156 accountActorInclude.push({
161 accountActorInclude.push({
162 model: ActorImageModel,
167 channelActorInclude.push({
168 model: ActorImageModel,
173 channelActorInclude.push({
174 model: ActorImageModel,
180 if (options.forCount !== true || serverRequired) {
181 channelActorInclude.push({
184 required: serverRequired,
193 exclude: unusedActorAttributesForAPI
195 model: ActorModel.unscoped(),
197 [Op.and]: whereActorAnd
199 include: channelActorInclude
202 model: AccountModel.unscoped(),
207 exclude: unusedActorAttributesForAPI
209 model: ActorModel.unscoped(),
211 include: accountActorInclude
218 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
219 const include: Includeable[] = [
221 attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
222 model: ActorModel.unscoped(),
223 required: options.actorRequired ?? true,
226 attributes: [ 'host' ],
227 model: ServerModel.unscoped(),
231 model: ActorImageModel,
239 const base: FindOptions = {
240 attributes: [ 'id', 'name', 'description', 'actorId' ]
243 if (options.withAccount === true) {
245 model: AccountModel.scope({
246 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
252 base.include = include
256 [ScopeNames.WITH_ACCOUNT]: {
264 [ScopeNames.WITH_ACTOR]: {
269 [ScopeNames.WITH_ACTOR_BANNER]: {
275 model: ActorImageModel,
283 [ScopeNames.WITH_VIDEOS]: {
288 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
289 const daysPrior = forceNumber(options.daysPrior)
295 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
301 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
305 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
306 `date_trunc('day', now()), '1 day'::interval) AS day ` +
308 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
311 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
312 'AND "video"."channelId" = "VideoChannelModel"."id"' +
313 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
324 'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' +
326 'WHERE "video"."channelId" = "VideoChannelModel"."id"' +
337 tableName: 'videoChannel',
339 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
342 fields: [ 'accountId' ]
345 fields: [ 'actorId' ]
349 export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
352 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name'))
358 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
359 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
364 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
365 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
374 @ForeignKey(() => ActorModel)
378 @BelongsTo(() => ActorModel, {
386 @ForeignKey(() => AccountModel)
390 @BelongsTo(() => AccountModel, {
395 Account: AccountModel
397 @HasMany(() => VideoModel, {
407 @HasMany(() => VideoPlaylistModel, {
414 VideoPlaylists: VideoPlaylistModel[]
417 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
418 if (!instance.Actor) {
419 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
422 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
424 if (instance.Actor.isOwned()) {
425 return sendDeleteActor(instance.Actor, options.transaction)
431 static countByAccount (accountId: number) {
438 return VideoChannelModel.unscoped().count(query)
441 static async getStats () {
443 function getLocalVideoChannelStats (days?: number) {
445 type: QueryTypes.SELECT as QueryTypes.SELECT,
449 const videoJoin = days
450 ? `INNER JOIN "video" AS "Videos" ON "VideoChannelModel"."id" = "Videos"."channelId" ` +
451 `AND ("Videos"."publishedAt" > Now() - interval '${days}d')`
455 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
456 FROM "videoChannel" AS "VideoChannelModel"
458 INNER JOIN "account" AS "Account" ON "VideoChannelModel"."accountId" = "Account"."id"
459 INNER JOIN "actor" AS "Account->Actor" ON "Account"."actorId" = "Account->Actor"."id"
460 AND "Account->Actor"."serverId" IS NULL`
462 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
463 .then(r => parseInt(r[0].count, 10))
466 const totalLocalVideoChannels = await getLocalVideoChannelStats()
467 const totalLocalDailyActiveVideoChannels = await getLocalVideoChannelStats(1)
468 const totalLocalWeeklyActiveVideoChannels = await getLocalVideoChannelStats(7)
469 const totalLocalMonthlyActiveVideoChannels = await getLocalVideoChannelStats(30)
470 const totalLocalHalfYearActiveVideoChannels = await getLocalVideoChannelStats(180)
473 totalLocalVideoChannels,
474 totalLocalDailyActiveVideoChannels,
475 totalLocalWeeklyActiveVideoChannels,
476 totalLocalMonthlyActiveVideoChannels,
477 totalLocalHalfYearActiveVideoChannels
481 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
485 order: getSort(sort),
488 attributes: [ 'preferredUsername', 'serverId' ],
489 model: ActorModel.unscoped(),
497 return VideoChannelModel
502 static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & {
507 const { actorId } = parameters
510 offset: parameters.start,
511 limit: parameters.count,
512 order: getSort(parameters.sort)
515 const getScope = (forCount: boolean) => {
516 return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }
520 VideoChannelModel.scope(getScope(true)).count(),
521 VideoChannelModel.scope(getScope(false)).findAll(query)
522 ]).then(([ total, data ]) => ({ total, data }))
525 static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {
530 let attributesInclude: any[] = [ literal('0 as similarity') ]
531 let where: WhereOptions
533 if (options.search) {
534 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
535 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
536 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
541 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
544 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
552 include: attributesInclude
554 offset: options.start,
555 limit: options.count,
556 order: getSort(options.sort),
560 const getScope = (forCount: boolean) => {
563 ScopeNames.FOR_API, {
564 ...pick(options, [ 'actorId', 'host', 'handles' ]),
567 } as AvailableForListOptions
573 VideoChannelModel.scope(getScope(true)).count(query),
574 VideoChannelModel.scope(getScope(false)).findAll(query)
575 ]).then(([ total, data ]) => ({ total, data }))
578 static listByAccountForAPI (options: {
586 const escapedSearch = VideoModel.sequelize.escape(options.search)
587 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
588 const where = options.search
592 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
595 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
601 const getQuery = (forCount: boolean) => {
602 const accountModel = forCount
603 ? AccountModel.unscoped()
607 offset: options.start,
608 limit: options.count,
609 order: getSort(options.sort),
614 id: options.accountId
623 const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
625 if (options.withStats === true) {
627 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
632 VideoChannelModel.unscoped().count(getQuery(true)),
633 VideoChannelModel.scope(findScopes).findAll(getQuery(false))
634 ]).then(([ total, data ]) => ({ total, data }))
637 static listAllByAccount (accountId: number): Promise<MChannel[]> {
639 limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
643 model: AccountModel.unscoped(),
652 return VideoChannelModel.findAll(query)
655 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
656 return VideoChannelModel.unscoped()
657 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
658 .findByPk(id, { transaction })
661 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
672 model: ActorImageModel,
681 return VideoChannelModel
682 .scope([ ScopeNames.WITH_ACCOUNT ])
686 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
687 const [ name, host ] = nameWithHost.split('@')
689 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
691 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
694 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
701 preferredUsername: name,
706 model: ActorImageModel,
715 return VideoChannelModel.unscoped()
716 .scope([ ScopeNames.WITH_ACCOUNT ])
720 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
727 preferredUsername: name
736 model: ActorImageModel,
745 return VideoChannelModel.unscoped()
746 .scope([ ScopeNames.WITH_ACCOUNT ])
750 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
751 const actor = this.Actor.toFormattedSummaryJSON()
756 displayName: this.getDisplayName(),
759 avatars: actor.avatars,
761 // TODO: remove, deprecated in 4.2
766 toFormattedJSON (this: MChannelFormattable): VideoChannel {
767 const viewsPerDayString = this.get('viewsPerDay') as string
768 const videosCount = this.get('videosCount') as number
770 let viewsPerDay: { date: Date, views: number }[]
772 if (viewsPerDayString) {
773 viewsPerDay = viewsPerDayString.split(',')
775 const [ dateString, amount ] = v.split('|')
778 date: new Date(dateString),
784 const totalViews = this.get('totalViews') as number
786 const actor = this.Actor.toFormattedJSON()
787 const videoChannel = {
789 displayName: this.getDisplayName(),
790 description: this.description,
791 support: this.support,
792 isLocal: this.Actor.isOwned(),
793 updatedAt: this.updatedAt,
795 ownerAccount: undefined,
801 avatars: actor.avatars,
803 // TODO: remove, deprecated in 4.2
807 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
809 return Object.assign(actor, videoChannel)
812 toActivityPubObject (this: MChannelAP): ActivityPubActor {
813 const obj = this.Actor.toActivityPubObject(this.name)
815 return Object.assign(obj, {
816 summary: this.description,
817 support: this.support,
820 type: 'Person' as 'Person',
821 id: this.Account.Actor.url
827 getLocalUrl (this: MAccountActor | MChannelActor) {
828 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
836 return this.Actor.isOutdated()
839 setAsUpdated (transaction?: Transaction) {
840 return setAsUpdated({ sequelize: this.sequelize, table: 'videoChannel', id: this.id, transaction })