Add ability to search video channels
[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 } 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 } from '../account/account'
28 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
30 import { VideoModel } from './video'
31 import { CONSTRAINTS_FIELDS } from '../../initializers'
32 import { ServerModel } from '../server/server'
33 import { DefineIndexesOptions } from 'sequelize'
34
35 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
36 const indexes: DefineIndexesOptions[] = [
37   buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
38
39   {
40     fields: [ 'accountId' ]
41   },
42   {
43     fields: [ 'actorId' ]
44   }
45 ]
46
47 enum ScopeNames {
48   AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
49   WITH_ACCOUNT = 'WITH_ACCOUNT',
50   WITH_ACTOR = 'WITH_ACTOR',
51   WITH_VIDEOS = 'WITH_VIDEOS'
52 }
53
54 type AvailableForListOptions = {
55   actorId: number
56 }
57
58 @DefaultScope({
59   include: [
60     {
61       model: () => ActorModel,
62       required: true
63     }
64   ]
65 })
66 @Scopes({
67   [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
68     const actorIdNumber = parseInt(options.actorId + '', 10)
69
70     // Only list local channels OR channels that are on an instance followed by actorId
71     const inQueryInstanceFollow = '(' +
72       'SELECT "actor"."serverId" FROM "actor" ' +
73       'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = actor.id ' +
74       'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
75     ')'
76
77     return {
78       include: [
79         {
80           attributes: {
81             exclude: unusedActorAttributesForAPI
82           },
83           model: ActorModel,
84           where: {
85             [Sequelize.Op.or]: [
86               {
87                 serverId: null
88               },
89               {
90                 serverId: {
91                   [ Sequelize.Op.in ]: Sequelize.literal(inQueryInstanceFollow)
92                 }
93               }
94             ]
95           }
96         },
97         {
98           model: AccountModel,
99           required: true,
100           include: [
101             {
102               attributes: {
103                 exclude: unusedActorAttributesForAPI
104               },
105               model: ActorModel, // Default scope includes avatar and server
106               required: true
107             }
108           ]
109         }
110       ]
111     }
112   },
113   [ScopeNames.WITH_ACCOUNT]: {
114     include: [
115       {
116         model: () => AccountModel,
117         required: true
118       }
119     ]
120   },
121   [ScopeNames.WITH_VIDEOS]: {
122     include: [
123       () => VideoModel
124     ]
125   },
126   [ScopeNames.WITH_ACTOR]: {
127     include: [
128       () => ActorModel
129     ]
130   }
131 })
132 @Table({
133   tableName: 'videoChannel',
134   indexes
135 })
136 export class VideoChannelModel extends Model<VideoChannelModel> {
137
138   @AllowNull(false)
139   @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
140   @Column
141   name: string
142
143   @AllowNull(true)
144   @Default(null)
145   @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description'))
146   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
147   description: string
148
149   @AllowNull(true)
150   @Default(null)
151   @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support'))
152   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
153   support: string
154
155   @CreatedAt
156   createdAt: Date
157
158   @UpdatedAt
159   updatedAt: Date
160
161   @ForeignKey(() => ActorModel)
162   @Column
163   actorId: number
164
165   @BelongsTo(() => ActorModel, {
166     foreignKey: {
167       allowNull: false
168     },
169     onDelete: 'cascade'
170   })
171   Actor: ActorModel
172
173   @ForeignKey(() => AccountModel)
174   @Column
175   accountId: number
176
177   @BelongsTo(() => AccountModel, {
178     foreignKey: {
179       allowNull: false
180     },
181     hooks: true
182   })
183   Account: AccountModel
184
185   @HasMany(() => VideoModel, {
186     foreignKey: {
187       name: 'channelId',
188       allowNull: false
189     },
190     onDelete: 'CASCADE',
191     hooks: true
192   })
193   Videos: VideoModel[]
194
195   @BeforeDestroy
196   static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
197     if (!instance.Actor) {
198       instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) as ActorModel
199     }
200
201     if (instance.Actor.isOwned()) {
202       return sendDeleteActor(instance.Actor, options.transaction)
203     }
204
205     return undefined
206   }
207
208   static countByAccount (accountId: number) {
209     const query = {
210       where: {
211         accountId
212       }
213     }
214
215     return VideoChannelModel.count(query)
216   }
217
218   static listForApi (actorId: number, start: number, count: number, sort: string) {
219     const query = {
220       offset: start,
221       limit: count,
222       order: getSort(sort)
223     }
224
225     const scopes = {
226       method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId } as AvailableForListOptions ]
227     }
228     return VideoChannelModel
229       .scope(scopes)
230       .findAndCountAll(query)
231       .then(({ rows, count }) => {
232         return { total: count, data: rows }
233       })
234   }
235
236   static searchForApi (options: {
237     actorId: number
238     search: string
239     start: number
240     count: number
241     sort: string
242   }) {
243     const attributesInclude = []
244     const escapedSearch = VideoModel.sequelize.escape(options.search)
245     const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
246     attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
247
248     const query = {
249       attributes: {
250         include: attributesInclude
251       },
252       offset: options.start,
253       limit: options.count,
254       order: getSort(options.sort),
255       where: {
256         id: {
257           [ Sequelize.Op.in ]: Sequelize.literal(
258             '(' +
259               'SELECT id FROM "videoChannel" WHERE ' +
260               'lower(immutable_unaccent("name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
261               'lower(immutable_unaccent("name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
262             ')'
263           )
264         }
265       }
266     }
267
268     const scopes = {
269       method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId: options.actorId } as AvailableForListOptions ]
270     }
271     return VideoChannelModel
272       .scope(scopes)
273       .findAndCountAll(query)
274       .then(({ rows, count }) => {
275         return { total: count, data: rows }
276       })
277   }
278
279   static listByAccount (accountId: number) {
280     const query = {
281       order: getSort('createdAt'),
282       include: [
283         {
284           model: AccountModel,
285           where: {
286             id: accountId
287           },
288           required: true
289         }
290       ]
291     }
292
293     return VideoChannelModel
294       .findAndCountAll(query)
295       .then(({ rows, count }) => {
296         return { total: count, data: rows }
297       })
298   }
299
300   static loadByIdAndAccount (id: number, accountId: number) {
301     const query = {
302       where: {
303         id,
304         accountId
305       }
306     }
307
308     return VideoChannelModel
309       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
310       .findOne(query)
311   }
312
313   static loadAndPopulateAccount (id: number) {
314     return VideoChannelModel
315       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
316       .findById(id)
317   }
318
319   static loadByUUIDAndPopulateAccount (uuid: string) {
320     const query = {
321       include: [
322         {
323           model: ActorModel,
324           required: true,
325           where: {
326             uuid
327           }
328         }
329       ]
330     }
331
332     return VideoChannelModel
333       .scope([ ScopeNames.WITH_ACCOUNT ])
334       .findOne(query)
335   }
336
337   static loadByUrlAndPopulateAccount (url: string) {
338     const query = {
339       include: [
340         {
341           model: ActorModel,
342           required: true,
343           where: {
344             url
345           }
346         }
347       ]
348     }
349
350     return VideoChannelModel
351       .scope([ ScopeNames.WITH_ACCOUNT ])
352       .findOne(query)
353   }
354
355   static loadLocalByNameAndPopulateAccount (name: string) {
356     const query = {
357       include: [
358         {
359           model: ActorModel,
360           required: true,
361           where: {
362             preferredUsername: name,
363             serverId: null
364           }
365         }
366       ]
367     }
368
369     return VideoChannelModel
370       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
371       .findOne(query)
372   }
373
374   static loadByNameAndHostAndPopulateAccount (name: string, host: string) {
375     const query = {
376       include: [
377         {
378           model: ActorModel,
379           required: true,
380           where: {
381             preferredUsername: name
382           },
383           include: [
384             {
385               model: ServerModel,
386               required: true,
387               where: { host }
388             }
389           ]
390         }
391       ]
392     }
393
394     return VideoChannelModel
395       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
396       .findOne(query)
397   }
398
399   static loadAndPopulateAccountAndVideos (id: number) {
400     const options = {
401       include: [
402         VideoModel
403       ]
404     }
405
406     return VideoChannelModel
407       .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
408       .findById(id, options)
409   }
410
411   toFormattedJSON (): VideoChannel {
412     const actor = this.Actor.toFormattedJSON()
413     const videoChannel = {
414       id: this.id,
415       displayName: this.getDisplayName(),
416       description: this.description,
417       support: this.support,
418       isLocal: this.Actor.isOwned(),
419       createdAt: this.createdAt,
420       updatedAt: this.updatedAt,
421       ownerAccount: undefined
422     }
423
424     if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
425
426     return Object.assign(actor, videoChannel)
427   }
428
429   toActivityPubObject (): ActivityPubActor {
430     const obj = this.Actor.toActivityPubObject(this.name, 'VideoChannel')
431
432     return Object.assign(obj, {
433       summary: this.description,
434       support: this.support,
435       attributedTo: [
436         {
437           type: 'Person' as 'Person',
438           id: this.Account.Actor.url
439         }
440       ]
441     })
442   }
443
444   getDisplayName () {
445     return this.name
446   }
447 }