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, ModelIndexesOptions, Op } 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 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
47 const indexes: ModelIndexesOptions[] = [
48 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
51 fields: [ 'accountId' ]
58 export enum ScopeNames {
60 WITH_ACCOUNT = 'WITH_ACCOUNT',
61 WITH_ACTOR = 'WITH_ACTOR',
62 WITH_VIDEOS = 'WITH_VIDEOS',
66 type AvailableForListOptions = {
70 export type SummaryOptions = {
71 withAccount?: boolean // Default: false
72 withAccountBlockerIds?: number[]
75 @DefaultScope(() => ({
84 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
85 const base: FindOptions = {
86 attributes: [ 'id', 'name', 'description', 'actorId' ],
89 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
90 model: ActorModel.unscoped(),
94 attributes: [ 'host' ],
95 model: ServerModel.unscoped(),
99 model: AvatarModel.unscoped(),
107 if (options.withAccount === true) {
109 model: AccountModel.scope({
110 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
118 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
119 // Only list local channels OR channels that are on an instance followed by actorId
120 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
126 exclude: unusedActorAttributesForAPI
136 [ Op.in ]: Sequelize.literal(inQueryInstanceFollow)
148 exclude: unusedActorAttributesForAPI
150 model: ActorModel, // Default scope includes avatar and server
158 [ScopeNames.WITH_ACCOUNT]: {
166 [ScopeNames.WITH_VIDEOS]: {
171 [ScopeNames.WITH_ACTOR]: {
178 tableName: 'videoChannel',
181 export class VideoChannelModel extends Model<VideoChannelModel> {
184 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
190 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
191 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
196 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
197 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
206 @ForeignKey(() => ActorModel)
210 @BelongsTo(() => ActorModel, {
218 @ForeignKey(() => AccountModel)
222 @BelongsTo(() => AccountModel, {
228 Account: AccountModel
230 @HasMany(() => VideoModel, {
240 @HasMany(() => VideoPlaylistModel, {
247 VideoPlaylists: VideoPlaylistModel[]
250 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
251 if (!instance.Actor) {
252 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
255 if (instance.Actor.isOwned()) {
256 return sendDeleteActor(instance.Actor, options.transaction)
262 static countByAccount (accountId: number) {
269 return VideoChannelModel.count(query)
272 static listForApi (actorId: number, start: number, count: number, sort: string) {
280 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
282 return VideoChannelModel
284 .findAndCountAll(query)
285 .then(({ rows, count }) => {
286 return { total: count, data: rows }
290 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
294 order: getSort(sort),
297 attributes: [ 'preferredUsername', 'serverId' ],
298 model: ActorModel.unscoped(),
306 return VideoChannelModel
311 static searchForApi (options: {
318 const attributesInclude = []
319 const escapedSearch = VideoModel.sequelize.escape(options.search)
320 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
321 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
325 include: attributesInclude
327 offset: options.start,
328 limit: options.count,
329 order: getSort(options.sort),
333 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
336 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
343 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
345 return VideoChannelModel
347 .findAndCountAll(query)
348 .then(({ rows, count }) => {
349 return { total: count, data: rows }
353 static listByAccount (options: {
360 offset: options.start,
361 limit: options.count,
362 order: getSort(options.sort),
367 id: options.accountId
374 return VideoChannelModel
375 .findAndCountAll(query)
376 .then(({ rows, count }) => {
377 return { total: count, data: rows }
381 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
382 return VideoChannelModel.unscoped()
383 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
387 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
395 return VideoChannelModel.unscoped()
396 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
400 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
401 return VideoChannelModel.unscoped()
402 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
406 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
419 return VideoChannelModel
420 .scope([ ScopeNames.WITH_ACCOUNT ])
424 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
425 const [ name, host ] = nameWithHost.split('@')
427 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
429 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
432 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
439 preferredUsername: name,
446 return VideoChannelModel.unscoped()
447 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
451 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
458 preferredUsername: name
471 return VideoChannelModel.unscoped()
472 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
476 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
483 return VideoChannelModel.unscoped()
484 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
485 .findByPk(id, options)
488 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
489 const actor = this.Actor.toFormattedSummaryJSON()
494 displayName: this.getDisplayName(),
501 toFormattedJSON (this: MChannelFormattable): VideoChannel {
502 const actor = this.Actor.toFormattedJSON()
503 const videoChannel = {
505 displayName: this.getDisplayName(),
506 description: this.description,
507 support: this.support,
508 isLocal: this.Actor.isOwned(),
509 createdAt: this.createdAt,
510 updatedAt: this.updatedAt,
511 ownerAccount: undefined
514 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
516 return Object.assign(actor, videoChannel)
519 toActivityPubObject (this: MChannelAP): ActivityPubActor {
520 const obj = this.Actor.toActivityPubObject(this.name)
522 return Object.assign(obj, {
523 summary: this.description,
524 support: this.support,
527 type: 'Person' as 'Person',
528 id: this.Account.Actor.url
539 return this.Actor.isOutdated()