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 ` +
185 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
188 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
189 'AND "video"."channelId" = "VideoChannelModel"."id"' +
190 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
204 tableName: 'videoChannel',
206 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
209 fields: [ 'accountId' ]
212 fields: [ 'actorId' ]
216 export class VideoChannelModel extends Model<VideoChannelModel> {
219 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
225 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
226 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
231 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
232 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
241 @ForeignKey(() => ActorModel)
245 @BelongsTo(() => ActorModel, {
253 @ForeignKey(() => AccountModel)
257 @BelongsTo(() => AccountModel, {
263 Account: AccountModel
265 @HasMany(() => VideoModel, {
275 @HasMany(() => VideoPlaylistModel, {
282 VideoPlaylists: VideoPlaylistModel[]
285 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
286 if (!instance.Actor) {
287 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
290 if (instance.Actor.isOwned()) {
291 return sendDeleteActor(instance.Actor, options.transaction)
297 static countByAccount (accountId: number) {
304 return VideoChannelModel.count(query)
307 static listForApi (actorId: number, start: number, count: number, sort: string) {
315 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
317 return VideoChannelModel
319 .findAndCountAll(query)
320 .then(({ rows, count }) => {
321 return { total: count, data: rows }
325 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
329 order: getSort(sort),
332 attributes: [ 'preferredUsername', 'serverId' ],
333 model: ActorModel.unscoped(),
341 return VideoChannelModel
346 static searchForApi (options: {
353 const attributesInclude = []
354 const escapedSearch = VideoModel.sequelize.escape(options.search)
355 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
356 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
360 include: attributesInclude
362 offset: options.start,
363 limit: options.count,
364 order: getSort(options.sort),
368 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
371 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
378 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
380 return VideoChannelModel
382 .findAndCountAll(query)
383 .then(({ rows, count }) => {
384 return { total: count, data: rows }
388 static listByAccount (options: {
396 offset: options.start,
397 limit: options.count,
398 order: getSort(options.sort),
403 id: options.accountId
410 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
412 if (options.withStats === true) {
414 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
418 return VideoChannelModel
420 .findAndCountAll(query)
421 .then(({ rows, count }) => {
422 return { total: count, data: rows }
426 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
427 return VideoChannelModel.unscoped()
428 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
432 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
440 return VideoChannelModel.unscoped()
441 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
445 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
446 return VideoChannelModel.unscoped()
447 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
451 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
464 return VideoChannelModel
465 .scope([ ScopeNames.WITH_ACCOUNT ])
469 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
470 const [ name, host ] = nameWithHost.split('@')
472 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
474 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
477 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
484 preferredUsername: name,
491 return VideoChannelModel.unscoped()
492 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
496 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
503 preferredUsername: name
516 return VideoChannelModel.unscoped()
517 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
521 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
528 return VideoChannelModel.unscoped()
529 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
530 .findByPk(id, options)
533 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
534 const actor = this.Actor.toFormattedSummaryJSON()
539 displayName: this.getDisplayName(),
546 toFormattedJSON (this: MChannelFormattable): VideoChannel {
547 const viewsPerDay = this.get('viewsPerDay') as string
549 const actor = this.Actor.toFormattedJSON()
550 const videoChannel = {
552 displayName: this.getDisplayName(),
553 description: this.description,
554 support: this.support,
555 isLocal: this.Actor.isOwned(),
556 createdAt: this.createdAt,
557 updatedAt: this.updatedAt,
558 ownerAccount: undefined,
559 viewsPerDay: viewsPerDay
560 ? viewsPerDay.split(',').map(v => {
561 const o = v.split('|')
563 date: new Date(o[0]),
570 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
572 return Object.assign(actor, videoChannel)
575 toActivityPubObject (this: MChannelAP): ActivityPubActor {
576 const obj = this.Actor.toActivityPubObject(this.name)
578 return Object.assign(obj, {
579 summary: this.description,
580 support: this.support,
583 type: 'Person' as 'Person',
584 id: this.Account.Actor.url
595 return this.Actor.isOutdated()