18 } from 'sequelize-typescript'
19 import { ActivityPubActor } from '../../../shared/models/activitypub'
20 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
22 isVideoChannelDescriptionValid,
23 isVideoChannelNameValid,
24 isVideoChannelSupportValid
25 } from '../../helpers/custom-validators/video-channels'
26 import { sendDeleteActor } from '../../lib/activitypub/send'
27 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
28 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
30 import { VideoModel } from './video'
31 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
32 import { ServerModel } from '../server/server'
33 import { FindOptions, Op, literal, ScopeOptions } from 'sequelize'
34 import { AvatarModel } from '../avatar/avatar'
35 import { VideoPlaylistModel } from './video-playlist'
36 import * as Bluebird from 'bluebird'
38 MChannelAccountDefault,
40 MChannelActorAccountDefaultVideos,
43 MChannelSummaryFormattable
44 } from '../../typings/models/video'
46 export enum ScopeNames {
49 WITH_ACCOUNT = 'WITH_ACCOUNT',
50 WITH_ACTOR = 'WITH_ACTOR',
51 WITH_VIDEOS = 'WITH_VIDEOS',
52 WITH_STATS = 'WITH_STATS'
55 type AvailableForListOptions = {
59 type AvailableWithStatsOptions = {
63 export type SummaryOptions = {
64 withAccount?: boolean // Default: false
65 withAccountBlockerIds?: number[]
68 @DefaultScope(() => ({
77 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
78 // Only list local channels OR channels that are on an instance followed by actorId
79 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
85 exclude: unusedActorAttributesForAPI
95 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
107 exclude: unusedActorAttributesForAPI
109 model: ActorModel, // Default scope includes avatar and server
117 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
118 const base: FindOptions = {
119 attributes: [ 'id', 'name', 'description', 'actorId' ],
122 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
123 model: ActorModel.unscoped(),
127 attributes: [ 'host' ],
128 model: ServerModel.unscoped(),
132 model: AvatarModel.unscoped(),
140 if (options.withAccount === true) {
142 model: AccountModel.scope({
143 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
151 [ScopeNames.WITH_ACCOUNT]: {
159 [ScopeNames.WITH_ACTOR]: {
164 [ScopeNames.WITH_VIDEOS]: {
169 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
170 const daysPrior = parseInt(options.daysPrior + '', 10)
178 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
182 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
183 `date_trunc('day', now()), '1 day'::interval) AS day ` +
187 'FROM "videoView" AS v ' +
188 'INNER JOIN "video" ON "video"."id" = v."videoId" ' +
189 'WHERE "video"."channelId" = "VideoChannelModel"."id" ' +
191 'SELECT days.day AS day, ' +
192 'COALESCE(SUM(views.views), 0) AS views ' +
194 `LEFT JOIN views ON date_trunc('day', "views"."startDate") = date_trunc('day', days.day) ` +
208 tableName: 'videoChannel',
210 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
213 fields: [ 'accountId' ]
216 fields: [ 'actorId' ]
220 export class VideoChannelModel extends Model<VideoChannelModel> {
223 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
229 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
230 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
235 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
236 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
245 @ForeignKey(() => ActorModel)
249 @BelongsTo(() => ActorModel, {
257 @ForeignKey(() => AccountModel)
261 @BelongsTo(() => AccountModel, {
267 Account: AccountModel
269 @HasMany(() => VideoModel, {
279 @HasMany(() => VideoPlaylistModel, {
286 VideoPlaylists: VideoPlaylistModel[]
289 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
290 if (!instance.Actor) {
291 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
294 if (instance.Actor.isOwned()) {
295 return sendDeleteActor(instance.Actor, options.transaction)
301 static countByAccount (accountId: number) {
308 return VideoChannelModel.count(query)
311 static listForApi (actorId: number, start: number, count: number, sort: string) {
319 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
321 return VideoChannelModel
323 .findAndCountAll(query)
324 .then(({ rows, count }) => {
325 return { total: count, data: rows }
329 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
333 order: getSort(sort),
336 attributes: [ 'preferredUsername', 'serverId' ],
337 model: ActorModel.unscoped(),
345 return VideoChannelModel
350 static searchForApi (options: {
357 const attributesInclude = []
358 const escapedSearch = VideoModel.sequelize.escape(options.search)
359 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
360 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
364 include: attributesInclude
366 offset: options.start,
367 limit: options.count,
368 order: getSort(options.sort),
372 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
375 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
382 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
384 return VideoChannelModel
386 .findAndCountAll(query)
387 .then(({ rows, count }) => {
388 return { total: count, data: rows }
392 static listByAccount (options: {
400 offset: options.start,
401 limit: options.count,
402 order: getSort(options.sort),
407 id: options.accountId
414 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
416 if (options.withStats) {
418 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
422 return VideoChannelModel
424 .findAndCountAll(query)
425 .then(({ rows, count }) => {
426 return { total: count, data: rows }
430 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
431 return VideoChannelModel.unscoped()
432 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
436 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
444 return VideoChannelModel.unscoped()
445 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
449 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
450 return VideoChannelModel.unscoped()
451 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
455 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
468 return VideoChannelModel
469 .scope([ ScopeNames.WITH_ACCOUNT ])
473 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
474 const [ name, host ] = nameWithHost.split('@')
476 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
478 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
481 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
488 preferredUsername: name,
495 return VideoChannelModel.unscoped()
496 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
500 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
507 preferredUsername: name
520 return VideoChannelModel.unscoped()
521 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
525 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
532 return VideoChannelModel.unscoped()
533 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
534 .findByPk(id, options)
537 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
538 const actor = this.Actor.toFormattedSummaryJSON()
543 displayName: this.getDisplayName(),
550 toFormattedJSON (this: MChannelFormattable): VideoChannel {
551 const viewsPerDay = this.get('viewsPerDay') as string
553 const actor = this.Actor.toFormattedJSON()
554 const videoChannel = {
556 displayName: this.getDisplayName(),
557 description: this.description,
558 support: this.support,
559 isLocal: this.Actor.isOwned(),
560 createdAt: this.createdAt,
561 updatedAt: this.updatedAt,
562 ownerAccount: undefined,
563 viewsPerDay: viewsPerDay !== undefined
564 ? viewsPerDay.split(',').map(v => {
565 const o = v.split('|')
567 date: new Date(o[0]),
574 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
576 return Object.assign(actor, videoChannel)
579 toActivityPubObject (this: MChannelAP): ActivityPubActor {
580 const obj = this.Actor.toActivityPubObject(this.name)
582 return Object.assign(obj, {
583 summary: this.description,
584 support: this.support,
587 type: 'Person' as 'Person',
588 id: this.Account.Actor.url
599 return this.Actor.isOutdated()