1 import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { setAsUpdated } from '@server/helpers/database-utils'
21 import { MAccountActor } from '@server/types/models'
22 import { AttributesOnly } from '@shared/core-utils'
23 import { ActivityPubActor } from '../../../shared/models/activitypub'
24 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
26 isVideoChannelDescriptionValid,
27 isVideoChannelNameValid,
28 isVideoChannelSupportValid
29 } from '../../helpers/custom-validators/video-channels'
30 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
31 import { sendDeleteActor } from '../../lib/activitypub/send'
35 MChannelBannerAccountDefault,
37 MChannelSummaryFormattable
38 } from '../../types/models/video'
39 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
40 import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor'
41 import { ActorFollowModel } from '../actor/actor-follow'
42 import { ActorImageModel } from '../actor/actor-image'
43 import { ServerModel } from '../server/server'
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 = {
63 type AvailableWithStatsOptions = {
67 export type SummaryOptions = {
68 actorRequired?: boolean // Default: true
69 withAccount?: boolean // Default: false
70 withAccountBlockerIds?: number[]
73 @DefaultScope(() => ({
82 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
83 // Only list local channels OR channels that are on an instance followed by actorId
84 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
90 exclude: unusedActorAttributesForAPI
100 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
107 model: ActorImageModel,
119 exclude: unusedActorAttributesForAPI
121 model: ActorModel, // Default scope includes avatar and server
129 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
130 const include: Includeable[] = [
132 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
133 model: ActorModel.unscoped(),
134 required: options.actorRequired ?? true,
137 attributes: [ 'host' ],
138 model: ServerModel.unscoped(),
142 model: ActorImageModel.unscoped(),
150 const base: FindOptions = {
151 attributes: [ 'id', 'name', 'description', 'actorId' ]
154 if (options.withAccount === true) {
156 model: AccountModel.scope({
157 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
163 base.include = include
167 [ScopeNames.WITH_ACCOUNT]: {
175 [ScopeNames.WITH_ACTOR]: {
180 [ScopeNames.WITH_ACTOR_BANNER]: {
186 model: ActorImageModel,
194 [ScopeNames.WITH_VIDEOS]: {
199 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
200 const daysPrior = parseInt(options.daysPrior + '', 10)
206 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
212 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
216 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
217 `date_trunc('day', now()), '1 day'::interval) AS day ` +
219 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
222 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
223 'AND "video"."channelId" = "VideoChannelModel"."id"' +
224 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
238 tableName: 'videoChannel',
240 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
243 fields: [ 'accountId' ]
246 fields: [ 'actorId' ]
250 export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
253 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
259 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
260 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
265 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
266 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
275 @ForeignKey(() => ActorModel)
279 @BelongsTo(() => ActorModel, {
287 @ForeignKey(() => AccountModel)
291 @BelongsTo(() => AccountModel, {
297 Account: AccountModel
299 @HasMany(() => VideoModel, {
309 @HasMany(() => VideoPlaylistModel, {
316 VideoPlaylists: VideoPlaylistModel[]
319 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
320 if (!instance.Actor) {
321 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
324 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
326 if (instance.Actor.isOwned()) {
327 return sendDeleteActor(instance.Actor, options.transaction)
333 static countByAccount (accountId: number) {
340 return VideoChannelModel.count(query)
343 static async getStats () {
345 function getActiveVideoChannels (days: number) {
347 type: QueryTypes.SELECT as QueryTypes.SELECT,
352 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
353 FROM "videoChannel" AS "VideoChannelModel"
354 INNER JOIN "video" AS "Videos"
355 ON "VideoChannelModel"."id" = "Videos"."channelId"
356 AND ("Videos"."publishedAt" > Now() - interval '${days}d')
357 INNER JOIN "account" AS "Account"
358 ON "VideoChannelModel"."accountId" = "Account"."id"
359 INNER JOIN "actor" AS "Account->Actor"
360 ON "Account"."actorId" = "Account->Actor"."id"
361 AND "Account->Actor"."serverId" IS NULL
362 LEFT OUTER JOIN "server" AS "Account->Actor->Server"
363 ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
365 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
366 .then(r => parseInt(r[0].count, 10))
369 const totalLocalVideoChannels = await VideoChannelModel.count()
370 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
371 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
372 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
373 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
376 totalLocalVideoChannels,
377 totalLocalDailyActiveVideoChannels,
378 totalLocalWeeklyActiveVideoChannels,
379 totalLocalMonthlyActiveVideoChannels,
380 totalHalfYearActiveVideoChannels
384 static listForApi (parameters: {
390 const { actorId } = parameters
393 offset: parameters.start,
394 limit: parameters.count,
395 order: getSort(parameters.sort)
398 return VideoChannelModel
400 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
402 .findAndCountAll(query)
403 .then(({ rows, count }) => {
404 return { total: count, data: rows }
408 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
412 order: getSort(sort),
415 attributes: [ 'preferredUsername', 'serverId' ],
416 model: ActorModel.unscoped(),
424 return VideoChannelModel
429 static searchForApi (options: {
436 const attributesInclude = []
437 const escapedSearch = VideoModel.sequelize.escape(options.search)
438 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
439 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
443 include: attributesInclude
445 offset: options.start,
446 limit: options.count,
447 order: getSort(options.sort),
451 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
454 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
460 return VideoChannelModel
462 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
464 .findAndCountAll(query)
465 .then(({ rows, count }) => {
466 return { total: count, data: rows }
470 static listByAccount (options: {
478 const escapedSearch = VideoModel.sequelize.escape(options.search)
479 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
480 const where = options.search
484 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
487 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
494 offset: options.start,
495 limit: options.count,
496 order: getSort(options.sort),
501 id: options.accountId
509 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
511 if (options.withStats === true) {
513 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
517 return VideoChannelModel
519 .findAndCountAll(query)
520 .then(({ rows, count }) => {
521 return { total: count, data: rows }
525 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
526 return VideoChannelModel.unscoped()
527 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
528 .findByPk(id, { transaction })
531 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
542 model: ActorImageModel,
551 return VideoChannelModel
552 .scope([ ScopeNames.WITH_ACCOUNT ])
556 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
557 const [ name, host ] = nameWithHost.split('@')
559 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
561 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
564 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
571 preferredUsername: name,
576 model: ActorImageModel,
585 return VideoChannelModel.unscoped()
586 .scope([ ScopeNames.WITH_ACCOUNT ])
590 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
597 preferredUsername: name
606 model: ActorImageModel,
615 return VideoChannelModel.unscoped()
616 .scope([ ScopeNames.WITH_ACCOUNT ])
620 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
621 const actor = this.Actor.toFormattedSummaryJSON()
626 displayName: this.getDisplayName(),
633 toFormattedJSON (this: MChannelFormattable): VideoChannel {
634 const viewsPerDayString = this.get('viewsPerDay') as string
635 const videosCount = this.get('videosCount') as number
637 let viewsPerDay: { date: Date, views: number }[]
639 if (viewsPerDayString) {
640 viewsPerDay = viewsPerDayString.split(',')
642 const [ dateString, amount ] = v.split('|')
645 date: new Date(dateString),
651 const actor = this.Actor.toFormattedJSON()
652 const videoChannel = {
654 displayName: this.getDisplayName(),
655 description: this.description,
656 support: this.support,
657 isLocal: this.Actor.isOwned(),
658 updatedAt: this.updatedAt,
659 ownerAccount: undefined,
664 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
666 return Object.assign(actor, videoChannel)
669 toActivityPubObject (this: MChannelAP): ActivityPubActor {
670 const obj = this.Actor.toActivityPubObject(this.name)
672 return Object.assign(obj, {
673 summary: this.description,
674 support: this.support,
677 type: 'Person' as 'Person',
678 id: this.Account.Actor.url
684 getLocalUrl (this: MAccountActor | MChannelActor) {
685 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
693 return this.Actor.isOutdated()
696 setAsUpdated (transaction: Transaction) {
697 return setAsUpdated('videoChannel', this.id, transaction)