1 import * as Bluebird from 'bluebird'
2 import { FindOptions, literal, Op, ScopeOptions } from 'sequelize'
20 } from 'sequelize-typescript'
21 import { MAccountActor } from '@server/types/models'
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'
32 MChannelAccountDefault,
34 MChannelActorAccountDefaultVideos,
37 MChannelSummaryFormattable
38 } from '../../types/models/video'
39 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
40 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
41 import { ActorFollowModel } from '../activitypub/actor-follow'
42 import { AvatarModel } from '../avatar/avatar'
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_VIDEOS = 'WITH_VIDEOS',
54 WITH_STATS = 'WITH_STATS'
57 type AvailableForListOptions = {
62 type AvailableWithStatsOptions = {
66 export type SummaryOptions = {
67 actorRequired?: boolean // Default: true
68 withAccount?: boolean // Default: false
69 withAccountBlockerIds?: number[]
72 @DefaultScope(() => ({
81 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
82 // Only list local channels OR channels that are on an instance followed by actorId
83 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
89 exclude: unusedActorAttributesForAPI
99 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
111 exclude: unusedActorAttributesForAPI
113 model: ActorModel, // Default scope includes avatar and server
121 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
122 const base: FindOptions = {
123 attributes: [ 'id', 'name', 'description', 'actorId' ],
126 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
127 model: ActorModel.unscoped(),
128 required: options.actorRequired ?? true,
131 attributes: [ 'host' ],
132 model: ServerModel.unscoped(),
136 model: AvatarModel.unscoped(),
144 if (options.withAccount === true) {
146 model: AccountModel.scope({
147 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
155 [ScopeNames.WITH_ACCOUNT]: {
163 [ScopeNames.WITH_ACTOR]: {
168 [ScopeNames.WITH_VIDEOS]: {
173 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
174 const daysPrior = parseInt(options.daysPrior + '', 10)
180 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
186 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
190 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
191 `date_trunc('day', now()), '1 day'::interval) AS day ` +
193 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
196 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
197 'AND "video"."channelId" = "VideoChannelModel"."id"' +
198 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
212 tableName: 'videoChannel',
214 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
217 fields: [ 'accountId' ]
220 fields: [ 'actorId' ]
224 export class VideoChannelModel extends Model<VideoChannelModel> {
227 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
233 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
234 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
239 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
240 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
249 @ForeignKey(() => ActorModel)
253 @BelongsTo(() => ActorModel, {
261 @ForeignKey(() => AccountModel)
265 @BelongsTo(() => AccountModel, {
271 Account: AccountModel
273 @HasMany(() => VideoModel, {
283 @HasMany(() => VideoPlaylistModel, {
290 VideoPlaylists: VideoPlaylistModel[]
293 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
294 if (!instance.Actor) {
295 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
298 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
300 if (instance.Actor.isOwned()) {
301 return sendDeleteActor(instance.Actor, options.transaction)
307 static countByAccount (accountId: number) {
314 return VideoChannelModel.count(query)
317 static listForApi (parameters: {
323 const { actorId } = parameters
326 offset: parameters.start,
327 limit: parameters.count,
328 order: getSort(parameters.sort)
332 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
334 return VideoChannelModel
336 .findAndCountAll(query)
337 .then(({ rows, count }) => {
338 return { total: count, data: rows }
342 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
346 order: getSort(sort),
349 attributes: [ 'preferredUsername', 'serverId' ],
350 model: ActorModel.unscoped(),
358 return VideoChannelModel
363 static searchForApi (options: {
370 const attributesInclude = []
371 const escapedSearch = VideoModel.sequelize.escape(options.search)
372 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
373 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
377 include: attributesInclude
379 offset: options.start,
380 limit: options.count,
381 order: getSort(options.sort),
385 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
388 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
395 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
397 return VideoChannelModel
399 .findAndCountAll(query)
400 .then(({ rows, count }) => {
401 return { total: count, data: rows }
405 static listByAccount (options: {
413 const escapedSearch = VideoModel.sequelize.escape(options.search)
414 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
415 const where = options.search
419 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
422 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
429 offset: options.start,
430 limit: options.count,
431 order: getSort(options.sort),
436 id: options.accountId
444 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
446 if (options.withStats === true) {
448 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
452 return VideoChannelModel
454 .findAndCountAll(query)
455 .then(({ rows, count }) => {
456 return { total: count, data: rows }
460 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
461 return VideoChannelModel.unscoped()
462 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
466 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
474 return VideoChannelModel.unscoped()
475 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
479 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
480 return VideoChannelModel.unscoped()
481 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
485 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
498 return VideoChannelModel
499 .scope([ ScopeNames.WITH_ACCOUNT ])
503 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
504 const [ name, host ] = nameWithHost.split('@')
506 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
508 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
511 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
518 preferredUsername: name,
525 return VideoChannelModel.unscoped()
526 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
530 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
537 preferredUsername: name
550 return VideoChannelModel.unscoped()
551 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
555 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
562 return VideoChannelModel.unscoped()
563 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
564 .findByPk(id, options)
567 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
568 const actor = this.Actor.toFormattedSummaryJSON()
573 displayName: this.getDisplayName(),
580 toFormattedJSON (this: MChannelFormattable): VideoChannel {
581 const viewsPerDayString = this.get('viewsPerDay') as string
582 const videosCount = this.get('videosCount') as number
584 let viewsPerDay: { date: Date, views: number }[]
586 if (viewsPerDayString) {
587 viewsPerDay = viewsPerDayString.split(',')
589 const [ dateString, amount ] = v.split('|')
592 date: new Date(dateString),
598 const actor = this.Actor.toFormattedJSON()
599 const videoChannel = {
601 displayName: this.getDisplayName(),
602 description: this.description,
603 support: this.support,
604 isLocal: this.Actor.isOwned(),
605 createdAt: this.createdAt,
606 updatedAt: this.updatedAt,
607 ownerAccount: undefined,
612 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
614 return Object.assign(actor, videoChannel)
617 toActivityPubObject (this: MChannelAP): ActivityPubActor {
618 const obj = this.Actor.toActivityPubObject(this.name)
620 return Object.assign(obj, {
621 summary: this.description,
622 support: this.support,
625 type: 'Person' as 'Person',
626 id: this.Account.Actor.url
632 getLocalUrl (this: MAccountActor | MChannelActor) {
633 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
641 return this.Actor.isOutdated()