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 }) => ({
175 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
179 `SELECT generate_series(date_trunc('day', now()) - '${options.daysPrior} day'::interval, ` +
180 `date_trunc('day', now()), '1 day'::interval) AS day ` +
184 'FROM "videoView" ' +
185 'WHERE "videoView"."videoId" IN ( ' +
186 'SELECT "video"."id" ' +
188 '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) ` +
207 tableName: 'videoChannel',
209 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
212 fields: [ 'accountId' ]
215 fields: [ 'actorId' ]
219 export class VideoChannelModel extends Model<VideoChannelModel> {
222 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
228 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
229 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
234 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
235 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
244 @ForeignKey(() => ActorModel)
248 @BelongsTo(() => ActorModel, {
256 @ForeignKey(() => AccountModel)
260 @BelongsTo(() => AccountModel, {
266 Account: AccountModel
268 @HasMany(() => VideoModel, {
278 @HasMany(() => VideoPlaylistModel, {
285 VideoPlaylists: VideoPlaylistModel[]
288 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
289 if (!instance.Actor) {
290 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
293 if (instance.Actor.isOwned()) {
294 return sendDeleteActor(instance.Actor, options.transaction)
300 static countByAccount (accountId: number) {
307 return VideoChannelModel.count(query)
310 static listForApi (actorId: number, start: number, count: number, sort: string) {
318 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
320 return VideoChannelModel
322 .findAndCountAll(query)
323 .then(({ rows, count }) => {
324 return { total: count, data: rows }
328 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
332 order: getSort(sort),
335 attributes: [ 'preferredUsername', 'serverId' ],
336 model: ActorModel.unscoped(),
344 return VideoChannelModel
349 static searchForApi (options: {
356 const attributesInclude = []
357 const escapedSearch = VideoModel.sequelize.escape(options.search)
358 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
359 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
363 include: attributesInclude
365 offset: options.start,
366 limit: options.count,
367 order: getSort(options.sort),
371 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
374 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
381 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
383 return VideoChannelModel
385 .findAndCountAll(query)
386 .then(({ rows, count }) => {
387 return { total: count, data: rows }
391 static listByAccount (options: {
399 offset: options.start,
400 limit: options.count,
401 order: getSort(options.sort),
406 id: options.accountId
413 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
415 if (options.withStats) {
417 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
421 return VideoChannelModel
423 .findAndCountAll(query)
424 .then(({ rows, count }) => {
425 return { total: count, data: rows }
429 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
430 return VideoChannelModel.unscoped()
431 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
435 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
443 return VideoChannelModel.unscoped()
444 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
448 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
449 return VideoChannelModel.unscoped()
450 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
454 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
467 return VideoChannelModel
468 .scope([ ScopeNames.WITH_ACCOUNT ])
472 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
473 const [ name, host ] = nameWithHost.split('@')
475 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
477 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
480 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
487 preferredUsername: name,
494 return VideoChannelModel.unscoped()
495 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
499 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
506 preferredUsername: name
519 return VideoChannelModel.unscoped()
520 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
524 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
531 return VideoChannelModel.unscoped()
532 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
533 .findByPk(id, options)
536 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
537 const actor = this.Actor.toFormattedSummaryJSON()
542 displayName: this.getDisplayName(),
549 toFormattedJSON (this: MChannelFormattable): VideoChannel {
550 const viewsPerDay = this.get('viewsPerDay') as string
552 const actor = this.Actor.toFormattedJSON()
553 const videoChannel = {
555 displayName: this.getDisplayName(),
556 description: this.description,
557 support: this.support,
558 isLocal: this.Actor.isOwned(),
559 createdAt: this.createdAt,
560 updatedAt: this.updatedAt,
561 ownerAccount: undefined,
562 viewsPerDay: viewsPerDay !== undefined
563 ? viewsPerDay.split(',').map(v => {
564 const o = v.split('|')
566 date: new Date(o[0]),
573 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
575 return Object.assign(actor, videoChannel)
578 toActivityPubObject (this: MChannelAP): ActivityPubActor {
579 const obj = this.Actor.toActivityPubObject(this.name)
581 return Object.assign(obj, {
582 summary: this.description,
583 support: this.support,
586 type: 'Person' as 'Person',
587 id: this.Account.Actor.url
598 return this.Actor.isOutdated()