05545bd9d6f9d6e925d0b4f7a1f78065a2a6d6f7
[oweals/peertube.git] / server / models / video / video-channel.ts
1 import {
2   AllowNull,
3   BeforeDestroy,
4   BelongsTo,
5   Column,
6   CreatedAt,
7   DataType,
8   Default,
9   DefaultScope,
10   ForeignKey,
11   HasMany,
12   Is,
13   Model,
14   Scopes,
15   Sequelize,
16   Table,
17   UpdatedAt
18 } from 'sequelize-typescript'
19 import { ActivityPubActor } from '../../../shared/models/activitypub'
20 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
21 import {
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'
37 import {
38   MChannelAccountDefault,
39   MChannelActor,
40   MChannelActorAccountDefaultVideos,
41   MChannelAP,
42   MChannelFormattable,
43   MChannelSummaryFormattable
44 } from '../../typings/models/video'
45
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'),
49
50   {
51     fields: [ 'accountId' ]
52   },
53   {
54     fields: [ 'actorId' ]
55   }
56 ]
57
58 export enum ScopeNames {
59   FOR_API = 'FOR_API',
60   WITH_ACCOUNT = 'WITH_ACCOUNT',
61   WITH_ACTOR = 'WITH_ACTOR',
62   WITH_VIDEOS = 'WITH_VIDEOS',
63   SUMMARY = 'SUMMARY'
64 }
65
66 type AvailableForListOptions = {
67   actorId: number
68 }
69
70 export type SummaryOptions = {
71   withAccount?: boolean // Default: false
72   withAccountBlockerIds?: number[]
73 }
74
75 @DefaultScope(() => ({
76   include: [
77     {
78       model: ActorModel,
79       required: true
80     }
81   ]
82 }))
83 @Scopes(() => ({
84   [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
85     const base: FindOptions = {
86       attributes: [ 'id', 'name', 'description', 'actorId' ],
87       include: [
88         {
89           attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
90           model: ActorModel.unscoped(),
91           required: true,
92           include: [
93             {
94               attributes: [ 'host' ],
95               model: ServerModel.unscoped(),
96               required: false
97             },
98             {
99               model: AvatarModel.unscoped(),
100               required: false
101             }
102           ]
103         }
104       ]
105     }
106
107     if (options.withAccount === true) {
108       base.include.push({
109         model: AccountModel.scope({
110           method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
111         }),
112         required: true
113       })
114     }
115
116     return base
117   },
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)
121
122     return {
123       include: [
124         {
125           attributes: {
126             exclude: unusedActorAttributesForAPI
127           },
128           model: ActorModel,
129           where: {
130             [Op.or]: [
131               {
132                 serverId: null
133               },
134               {
135                 serverId: {
136                   [ Op.in ]: Sequelize.literal(inQueryInstanceFollow)
137                 }
138               }
139             ]
140           }
141         },
142         {
143           model: AccountModel,
144           required: true,
145           include: [
146             {
147               attributes: {
148                 exclude: unusedActorAttributesForAPI
149               },
150               model: ActorModel, // Default scope includes avatar and server
151               required: true
152             }
153           ]
154         }
155       ]
156     }
157   },
158   [ScopeNames.WITH_ACCOUNT]: {
159     include: [
160       {
161         model: AccountModel,
162         required: true
163       }
164     ]
165   },
166   [ScopeNames.WITH_VIDEOS]: {
167     include: [
168       VideoModel
169     ]
170   },
171   [ScopeNames.WITH_ACTOR]: {
172     include: [
173       ActorModel
174     ]
175   }
176 }))
177 @Table({
178   tableName: 'videoChannel',
179   indexes
180 })
181 export class VideoChannelModel extends Model<VideoChannelModel> {
182
183   @AllowNull(false)
184   @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
185   @Column
186   name: string
187
188   @AllowNull(true)
189   @Default(null)
190   @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
191   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
192   description: string
193
194   @AllowNull(true)
195   @Default(null)
196   @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
197   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
198   support: string
199
200   @CreatedAt
201   createdAt: Date
202
203   @UpdatedAt
204   updatedAt: Date
205
206   @ForeignKey(() => ActorModel)
207   @Column
208   actorId: number
209
210   @BelongsTo(() => ActorModel, {
211     foreignKey: {
212       allowNull: false
213     },
214     onDelete: 'cascade'
215   })
216   Actor: ActorModel
217
218   @ForeignKey(() => AccountModel)
219   @Column
220   accountId: number
221
222   @BelongsTo(() => AccountModel, {
223     foreignKey: {
224       allowNull: false
225     },
226     hooks: true
227   })
228   Account: AccountModel
229
230   @HasMany(() => VideoModel, {
231     foreignKey: {
232       name: 'channelId',
233       allowNull: false
234     },
235     onDelete: 'CASCADE',
236     hooks: true
237   })
238   Videos: VideoModel[]
239
240   @HasMany(() => VideoPlaylistModel, {
241     foreignKey: {
242       allowNull: true
243     },
244     onDelete: 'CASCADE',
245     hooks: true
246   })
247   VideoPlaylists: VideoPlaylistModel[]
248
249   @BeforeDestroy
250   static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
251     if (!instance.Actor) {
252       instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) as ActorModel
253     }
254
255     if (instance.Actor.isOwned()) {
256       return sendDeleteActor(instance.Actor, options.transaction)
257     }
258
259     return undefined
260   }
261
262   static countByAccount (accountId: number) {
263     const query = {
264       where: {
265         accountId
266       }
267     }
268
269     return VideoChannelModel.count(query)
270   }
271
272   static listForApi (actorId: number, start: number, count: number, sort: string) {
273     const query = {
274       offset: start,
275       limit: count,
276       order: getSort(sort)
277     }
278
279     const scopes = {
280       method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
281     }
282     return VideoChannelModel
283       .scope(scopes)
284       .findAndCountAll(query)
285       .then(({ rows, count }) => {
286         return { total: count, data: rows }
287       })
288   }
289
290   static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
291     const query = {
292       attributes: [ ],
293       offset: 0,
294       order: getSort(sort),
295       include: [
296         {
297           attributes: [ 'preferredUsername', 'serverId' ],
298           model: ActorModel.unscoped(),
299           where: {
300             serverId: null
301           }
302         }
303       ]
304     }
305
306     return VideoChannelModel
307       .unscoped()
308       .findAll(query)
309   }
310
311   static searchForApi (options: {
312     actorId: number
313     search: string
314     start: number
315     count: number
316     sort: string
317   }) {
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))
322
323     const query = {
324       attributes: {
325         include: attributesInclude
326       },
327       offset: options.start,
328       limit: options.count,
329       order: getSort(options.sort),
330       where: {
331         [Op.or]: [
332           Sequelize.literal(
333             'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
334           ),
335           Sequelize.literal(
336             'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
337           )
338         ]
339       }
340     }
341
342     const scopes = {
343       method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
344     }
345     return VideoChannelModel
346       .scope(scopes)
347       .findAndCountAll(query)
348       .then(({ rows, count }) => {
349         return { total: count, data: rows }
350       })
351   }
352
353   static listByAccount (options: {
354     accountId: number,
355     start: number,
356     count: number,
357     sort: string
358   }) {
359     const query = {
360       offset: options.start,
361       limit: options.count,
362       order: getSort(options.sort),
363       include: [
364         {
365           model: AccountModel,
366           where: {
367             id: options.accountId
368           },
369           required: true
370         }
371       ]
372     }
373
374     return VideoChannelModel
375       .findAndCountAll(query)
376       .then(({ rows, count }) => {
377         return { total: count, data: rows }
378       })
379   }
380
381   static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
382     return VideoChannelModel.unscoped()
383       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
384       .findByPk(id)
385   }
386
387   static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
388     const query = {
389       where: {
390         id,
391         accountId
392       }
393     }
394
395     return VideoChannelModel.unscoped()
396       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
397       .findOne(query)
398   }
399
400   static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
401     return VideoChannelModel.unscoped()
402       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
403       .findByPk(id)
404   }
405
406   static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
407     const query = {
408       include: [
409         {
410           model: ActorModel,
411           required: true,
412           where: {
413             url
414           }
415         }
416       ]
417     }
418
419     return VideoChannelModel
420       .scope([ ScopeNames.WITH_ACCOUNT ])
421       .findOne(query)
422   }
423
424   static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
425     const [ name, host ] = nameWithHost.split('@')
426
427     if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
428
429     return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
430   }
431
432   static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
433     const query = {
434       include: [
435         {
436           model: ActorModel,
437           required: true,
438           where: {
439             preferredUsername: name,
440             serverId: null
441           }
442         }
443       ]
444     }
445
446     return VideoChannelModel.unscoped()
447       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
448       .findOne(query)
449   }
450
451   static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
452     const query = {
453       include: [
454         {
455           model: ActorModel,
456           required: true,
457           where: {
458             preferredUsername: name
459           },
460           include: [
461             {
462               model: ServerModel,
463               required: true,
464               where: { host }
465             }
466           ]
467         }
468       ]
469     }
470
471     return VideoChannelModel.unscoped()
472       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
473       .findOne(query)
474   }
475
476   static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
477     const options = {
478       include: [
479         VideoModel
480       ]
481     }
482
483     return VideoChannelModel.unscoped()
484       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
485       .findByPk(id, options)
486   }
487
488   toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
489     const actor = this.Actor.toFormattedSummaryJSON()
490
491     return {
492       id: this.id,
493       name: actor.name,
494       displayName: this.getDisplayName(),
495       url: actor.url,
496       host: actor.host,
497       avatar: actor.avatar
498     }
499   }
500
501   toFormattedJSON (this: MChannelFormattable): VideoChannel {
502     const actor = this.Actor.toFormattedJSON()
503     const videoChannel = {
504       id: this.id,
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
512     }
513
514     if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
515
516     return Object.assign(actor, videoChannel)
517   }
518
519   toActivityPubObject (this: MChannelAP): ActivityPubActor {
520     const obj = this.Actor.toActivityPubObject(this.name)
521
522     return Object.assign(obj, {
523       summary: this.description,
524       support: this.support,
525       attributedTo: [
526         {
527           type: 'Person' as 'Person',
528           id: this.Account.Actor.url
529         }
530       ]
531     })
532   }
533
534   getDisplayName () {
535     return this.name
536   }
537
538   isOutdated () {
539     return this.Actor.isOutdated()
540   }
541 }