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 = {
64 type AvailableWithStatsOptions = {
68 export type SummaryOptions = {
69 actorRequired?: boolean // Default: true
70 withAccount?: boolean // Default: false
71 withAccountBlockerIds?: number[]
74 @DefaultScope(() => ({
83 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
84 // Only list local channels OR channels that are on an instance followed by actorId
85 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
94 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
100 let serverRequired = false
101 let whereServer: WhereOptions
103 if (options.host && options.host !== WEBSERVER.HOST) {
104 serverRequired = true
105 whereServer = { host: options.host }
108 if (options.host === WEBSERVER.HOST) {
109 Object.assign(whereActor, {
110 [Op.and]: [ { serverId: null } ]
118 exclude: unusedActorAttributesForAPI
125 required: serverRequired,
129 model: ActorImageModel,
134 model: ActorImageModel,
146 exclude: unusedActorAttributesForAPI
148 model: ActorModel, // Default scope includes avatar and server
156 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
157 const include: Includeable[] = [
159 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
160 model: ActorModel.unscoped(),
161 required: options.actorRequired ?? true,
164 attributes: [ 'host' ],
165 model: ServerModel.unscoped(),
169 model: ActorImageModel.unscoped(),
177 const base: FindOptions = {
178 attributes: [ 'id', 'name', 'description', 'actorId' ]
181 if (options.withAccount === true) {
183 model: AccountModel.scope({
184 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
190 base.include = include
194 [ScopeNames.WITH_ACCOUNT]: {
202 [ScopeNames.WITH_ACTOR]: {
207 [ScopeNames.WITH_ACTOR_BANNER]: {
213 model: ActorImageModel,
221 [ScopeNames.WITH_VIDEOS]: {
226 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
227 const daysPrior = parseInt(options.daysPrior + '', 10)
233 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
239 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
243 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
244 `date_trunc('day', now()), '1 day'::interval) AS day ` +
246 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
249 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
250 'AND "video"."channelId" = "VideoChannelModel"."id"' +
251 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
265 tableName: 'videoChannel',
267 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
270 fields: [ 'accountId' ]
273 fields: [ 'actorId' ]
277 export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
280 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
286 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
287 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
292 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
293 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
302 @ForeignKey(() => ActorModel)
306 @BelongsTo(() => ActorModel, {
314 @ForeignKey(() => AccountModel)
318 @BelongsTo(() => AccountModel, {
323 Account: AccountModel
325 @HasMany(() => VideoModel, {
335 @HasMany(() => VideoPlaylistModel, {
342 VideoPlaylists: VideoPlaylistModel[]
345 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
346 if (!instance.Actor) {
347 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
350 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
352 if (instance.Actor.isOwned()) {
353 return sendDeleteActor(instance.Actor, options.transaction)
359 static countByAccount (accountId: number) {
366 return VideoChannelModel.count(query)
369 static async getStats () {
371 function getActiveVideoChannels (days: number) {
373 type: QueryTypes.SELECT as QueryTypes.SELECT,
378 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
379 FROM "videoChannel" AS "VideoChannelModel"
380 INNER JOIN "video" AS "Videos"
381 ON "VideoChannelModel"."id" = "Videos"."channelId"
382 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
383 INNER JOIN "account" AS "Account"
384 ON "VideoChannelModel"."accountId" = "Account"."id"
385 INNER JOIN "actor" AS "Account->Actor"
386 ON "Account"."actorId" = "Account->Actor"."id"
387 AND "Account->Actor"."serverId" IS NULL
388 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
389 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
391 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
392 .then(r => parseInt(r[0].count, 10))
395 const totalLocalVideoChannels = await VideoChannelModel.count()
396 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
397 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
398 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
399 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
402 totalLocalVideoChannels,
403 totalLocalDailyActiveVideoChannels,
404 totalLocalWeeklyActiveVideoChannels,
405 totalLocalMonthlyActiveVideoChannels,
406 totalHalfYearActiveVideoChannels
410 static listForApi (parameters: {
416 const { actorId } = parameters
419 offset: parameters.start,
420 limit: parameters.count,
421 order: getSort(parameters.sort)
424 return VideoChannelModel
426 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
428 .findAndCountAll(query)
429 .then(({ rows, count }) => {
430 return { total: count, data: rows }
434 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
438 order: getSort(sort),
441 attributes: [ 'preferredUsername', 'serverId' ],
442 model: ActorModel.unscoped(),
450 return VideoChannelModel
455 static searchForApi (options: {
464 const attributesInclude = []
465 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
466 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
467 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
471 include: attributesInclude
473 offset: options.start,
474 limit: options.count,
475 order: getSort(options.sort),
479 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
482 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
488 return VideoChannelModel
490 method: [ ScopeNames.FOR_API, { actorId: options.actorId, host: options.host } as AvailableForListOptions ]
492 .findAndCountAll(query)
493 .then(({ rows, count }) => {
494 return { total: count, data: rows }
498 static listByAccount (options: {
506 const escapedSearch = VideoModel.sequelize.escape(options.search)
507 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
508 const where = options.search
512 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
515 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
522 offset: options.start,
523 limit: options.count,
524 order: getSort(options.sort),
529 id: options.accountId
537 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
539 if (options.withStats === true) {
541 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
545 return VideoChannelModel
547 .findAndCountAll(query)
548 .then(({ rows, count }) => {
549 return { total: count, data: rows }
553 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
554 return VideoChannelModel.unscoped()
555 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
556 .findByPk(id, { transaction })
559 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
570 model: ActorImageModel,
579 return VideoChannelModel
580 .scope([ ScopeNames.WITH_ACCOUNT ])
584 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
585 const [ name, host ] = nameWithHost.split('@')
587 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
589 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
592 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
599 preferredUsername: name,
604 model: ActorImageModel,
613 return VideoChannelModel.unscoped()
614 .scope([ ScopeNames.WITH_ACCOUNT ])
618 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
625 preferredUsername: name
634 model: ActorImageModel,
643 return VideoChannelModel.unscoped()
644 .scope([ ScopeNames.WITH_ACCOUNT ])
648 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
649 const actor = this.Actor.toFormattedSummaryJSON()
654 displayName: this.getDisplayName(),
661 toFormattedJSON (this: MChannelFormattable): VideoChannel {
662 const viewsPerDayString = this.get('viewsPerDay') as string
663 const videosCount = this.get('videosCount') as number
665 let viewsPerDay: { date: Date, views: number }[]
667 if (viewsPerDayString) {
668 viewsPerDay = viewsPerDayString.split(',')
670 const [ dateString, amount ] = v.split('|')
673 date: new Date(dateString),
679 const actor = this.Actor.toFormattedJSON()
680 const videoChannel = {
682 displayName: this.getDisplayName(),
683 description: this.description,
684 support: this.support,
685 isLocal: this.Actor.isOwned(),
686 updatedAt: this.updatedAt,
687 ownerAccount: undefined,
692 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
694 return Object.assign(actor, videoChannel)
697 toActivityPubObject (this: MChannelAP): ActivityPubActor {
698 const obj = this.Actor.toActivityPubObject(this.name)
700 return Object.assign(obj, {
701 summary: this.description,
702 support: this.support,
705 type: 'Person' as 'Person',
706 id: this.Account.Actor.url
712 getLocalUrl (this: MAccountActor | MChannelActor) {
713 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
721 return this.Actor.isOutdated()
724 setAsUpdated (transaction: Transaction) {
725 return setAsUpdated('videoChannel', this.id, transaction)