1 import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { MAccountActor } from '@server/types/models'
21 import { AttributesOnly } from '@shared/core-utils'
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 { setAsUpdated } from '../shared'
44 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
45 import { VideoModel } from './video'
46 import { VideoPlaylistModel } from './video-playlist'
48 export enum ScopeNames {
51 WITH_ACCOUNT = 'WITH_ACCOUNT',
52 WITH_ACTOR = 'WITH_ACTOR',
53 WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
54 WITH_VIDEOS = 'WITH_VIDEOS',
55 WITH_STATS = 'WITH_STATS'
58 type AvailableForListOptions = {
65 type AvailableWithStatsOptions = {
69 export type SummaryOptions = {
70 actorRequired?: boolean // Default: true
71 withAccount?: boolean // Default: false
72 withAccountBlockerIds?: number[]
75 @DefaultScope(() => ({
84 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
85 // Only list local channels OR channels that are on an instance followed by actorId
86 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
88 const whereActorAnd: WhereOptions[] = [
96 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
103 let serverRequired = false
104 let whereServer: WhereOptions
106 if (options.host && options.host !== WEBSERVER.HOST) {
107 serverRequired = true
108 whereServer = { host: options.host }
111 if (options.host === WEBSERVER.HOST) {
120 [Op.in]: options.names
129 exclude: unusedActorAttributesForAPI
133 [Op.and]: whereActorAnd
138 required: serverRequired,
142 model: ActorImageModel,
147 model: ActorImageModel,
159 exclude: unusedActorAttributesForAPI
161 model: ActorModel, // Default scope includes avatar and server
169 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
170 const include: Includeable[] = [
172 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
173 model: ActorModel.unscoped(),
174 required: options.actorRequired ?? true,
177 attributes: [ 'host' ],
178 model: ServerModel.unscoped(),
182 model: ActorImageModel.unscoped(),
190 const base: FindOptions = {
191 attributes: [ 'id', 'name', 'description', 'actorId' ]
194 if (options.withAccount === true) {
196 model: AccountModel.scope({
197 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
203 base.include = include
207 [ScopeNames.WITH_ACCOUNT]: {
215 [ScopeNames.WITH_ACTOR]: {
220 [ScopeNames.WITH_ACTOR_BANNER]: {
226 model: ActorImageModel,
234 [ScopeNames.WITH_VIDEOS]: {
239 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
240 const daysPrior = parseInt(options.daysPrior + '', 10)
246 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
252 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
256 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
257 `date_trunc('day', now()), '1 day'::interval) AS day ` +
259 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
262 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
263 'AND "video"."channelId" = "VideoChannelModel"."id"' +
264 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
278 tableName: 'videoChannel',
280 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
283 fields: [ 'accountId' ]
286 fields: [ 'actorId' ]
290 export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
293 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
299 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
300 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
305 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
306 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
315 @ForeignKey(() => ActorModel)
319 @BelongsTo(() => ActorModel, {
327 @ForeignKey(() => AccountModel)
331 @BelongsTo(() => AccountModel, {
336 Account: AccountModel
338 @HasMany(() => VideoModel, {
348 @HasMany(() => VideoPlaylistModel, {
355 VideoPlaylists: VideoPlaylistModel[]
358 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
359 if (!instance.Actor) {
360 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
363 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
365 if (instance.Actor.isOwned()) {
366 return sendDeleteActor(instance.Actor, options.transaction)
372 static countByAccount (accountId: number) {
379 return VideoChannelModel.count(query)
382 static async getStats () {
384 function getActiveVideoChannels (days: number) {
386 type: QueryTypes.SELECT as QueryTypes.SELECT,
391 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
392 FROM "videoChannel" AS "VideoChannelModel"
393 INNER JOIN "video" AS "Videos"
394 ON "VideoChannelModel"."id" = "Videos"."channelId"
395 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
396 INNER JOIN "account" AS "Account"
397 ON "VideoChannelModel"."accountId" = "Account"."id"
398 INNER JOIN "actor" AS "Account->Actor"
399 ON "Account"."actorId" = "Account->Actor"."id"
400 AND "Account->Actor"."serverId" IS NULL
401 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
402 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
404 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
405 .then(r => parseInt(r[0].count, 10))
408 const totalLocalVideoChannels = await VideoChannelModel.count()
409 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
410 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
411 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
412 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
415 totalLocalVideoChannels,
416 totalLocalDailyActiveVideoChannels,
417 totalLocalWeeklyActiveVideoChannels,
418 totalLocalMonthlyActiveVideoChannels,
419 totalHalfYearActiveVideoChannels
423 static listForApi (parameters: {
429 const { actorId } = parameters
432 offset: parameters.start,
433 limit: parameters.count,
434 order: getSort(parameters.sort)
437 return VideoChannelModel
439 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
441 .findAndCountAll(query)
442 .then(({ rows, count }) => {
443 return { total: count, data: rows }
447 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
451 order: getSort(sort),
454 attributes: [ 'preferredUsername', 'serverId' ],
455 model: ActorModel.unscoped(),
463 return VideoChannelModel
468 static searchForApi (options: {
478 let attributesInclude: any[] = [ literal('0 as similarity') ]
479 let where: WhereOptions
481 if (options.search) {
482 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
483 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
484 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
489 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
492 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
500 include: attributesInclude
502 offset: options.start,
503 limit: options.count,
504 order: getSort(options.sort),
508 return VideoChannelModel
510 method: [ ScopeNames.FOR_API, { actorId: options.actorId, host: options.host, names: options.names } as AvailableForListOptions ]
512 .findAndCountAll(query)
513 .then(({ rows, count }) => {
514 return { total: count, data: rows }
518 static listByAccount (options: {
526 const escapedSearch = VideoModel.sequelize.escape(options.search)
527 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
528 const where = options.search
532 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
535 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
542 offset: options.start,
543 limit: options.count,
544 order: getSort(options.sort),
549 id: options.accountId
557 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
559 if (options.withStats === true) {
561 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
565 return VideoChannelModel
567 .findAndCountAll(query)
568 .then(({ rows, count }) => {
569 return { total: count, data: rows }
573 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
574 return VideoChannelModel.unscoped()
575 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
576 .findByPk(id, { transaction })
579 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
590 model: ActorImageModel,
599 return VideoChannelModel
600 .scope([ ScopeNames.WITH_ACCOUNT ])
604 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
605 const [ name, host ] = nameWithHost.split('@')
607 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
609 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
612 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
619 preferredUsername: name,
624 model: ActorImageModel,
633 return VideoChannelModel.unscoped()
634 .scope([ ScopeNames.WITH_ACCOUNT ])
638 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
645 preferredUsername: name
654 model: ActorImageModel,
663 return VideoChannelModel.unscoped()
664 .scope([ ScopeNames.WITH_ACCOUNT ])
668 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
669 const actor = this.Actor.toFormattedSummaryJSON()
674 displayName: this.getDisplayName(),
681 toFormattedJSON (this: MChannelFormattable): VideoChannel {
682 const viewsPerDayString = this.get('viewsPerDay') as string
683 const videosCount = this.get('videosCount') as number
685 let viewsPerDay: { date: Date, views: number }[]
687 if (viewsPerDayString) {
688 viewsPerDay = viewsPerDayString.split(',')
690 const [ dateString, amount ] = v.split('|')
693 date: new Date(dateString),
699 const actor = this.Actor.toFormattedJSON()
700 const videoChannel = {
702 displayName: this.getDisplayName(),
703 description: this.description,
704 support: this.support,
705 isLocal: this.Actor.isOwned(),
706 updatedAt: this.updatedAt,
707 ownerAccount: undefined,
712 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
714 return Object.assign(actor, videoChannel)
717 toActivityPubObject (this: MChannelAP): ActivityPubActor {
718 const obj = this.Actor.toActivityPubObject(this.name)
720 return Object.assign(obj, {
721 summary: this.description,
722 support: this.support,
725 type: 'Person' as 'Person',
726 id: this.Account.Actor.url
732 getLocalUrl (this: MAccountActor | MChannelActor) {
733 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
741 return this.Actor.isOutdated()
744 setAsUpdated (transaction: Transaction) {
745 return setAsUpdated('videoChannel', this.id, transaction)