]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-channel.ts
Optimize channel search query
[github/Chocobozzz/PeerTube.git] / server / models / video / video-channel.ts
CommitLineData
3fd3ab2d 1import {
06a05d5f
C
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,
f37dc0dd 15 Sequelize,
06a05d5f
C
16 Table,
17 UpdatedAt
3fd3ab2d 18} from 'sequelize-typescript'
50d6de9c 19import { ActivityPubActor } from '../../../shared/models/activitypub'
2422c46b
C
20import { VideoChannel } from '../../../shared/models/videos'
21import {
06a05d5f
C
22 isVideoChannelDescriptionValid,
23 isVideoChannelNameValid,
2422c46b
C
24 isVideoChannelSupportValid
25} from '../../helpers/custom-validators/video-channels'
c5a893d5 26import { sendDeleteActor } from '../../lib/activitypub/send'
3fd3ab2d 27import { AccountModel } from '../account/account'
f37dc0dd
C
28import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
3fd3ab2d 30import { VideoModel } from './video'
a10fc78b 31import { CONSTRAINTS_FIELDS } from '../../initializers'
8a19bee1 32import { ServerModel } from '../server/server'
f37dc0dd
C
33import { 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
36const indexes: DefineIndexesOptions[] = [
37 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
38
39 {
40 fields: [ 'accountId' ]
41 },
42 {
43 fields: [ 'actorId' ]
44 }
45]
3fd3ab2d 46
d48ff09d 47enum ScopeNames {
f37dc0dd 48 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
d48ff09d 49 WITH_ACCOUNT = 'WITH_ACCOUNT',
50d6de9c 50 WITH_ACTOR = 'WITH_ACTOR',
d48ff09d
C
51 WITH_VIDEOS = 'WITH_VIDEOS'
52}
53
f37dc0dd
C
54type AvailableForListOptions = {
55 actorId: number
56}
57
50d6de9c
C
58@DefaultScope({
59 include: [
60 {
61 model: () => ActorModel,
62 required: true
63 }
64 ]
65})
d48ff09d 66@Scopes({
f37dc0dd
C
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 = '(' +
c3c2ab1c
C
72 'SELECT "actor"."serverId" FROM "actorFollow" ' +
73 'INNER JOIN "actor" ON actor.id= "actorFollow"."targetActorId" ' +
74 'WHERE "actor"."id" = ' + actorIdNumber +
f37dc0dd
C
75 ')'
76
77 return {
78 include: [
79 {
80 attributes: {
81 exclude: unusedActorAttributesForAPI
82 },
83 model: ActorModel,
84 where: {
85 [Sequelize.Op.or]: [
c305467c 86 {
f37dc0dd
C
87 serverId: null
88 },
89 {
90 serverId: {
91 [ Sequelize.Op.in ]: Sequelize.literal(inQueryInstanceFollow)
92 }
c305467c
C
93 }
94 ]
50d6de9c 95 }
f37dc0dd
C
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
d48ff09d
C
118 }
119 ]
120 },
121 [ScopeNames.WITH_VIDEOS]: {
122 include: [
123 () => VideoModel
124 ]
50d6de9c
C
125 },
126 [ScopeNames.WITH_ACTOR]: {
127 include: [
128 () => ActorModel
129 ]
d48ff09d
C
130 }
131})
3fd3ab2d
C
132@Table({
133 tableName: 'videoChannel',
f37dc0dd 134 indexes
3fd3ab2d
C
135})
136export class VideoChannelModel extends Model<VideoChannelModel> {
72c7248b 137
3fd3ab2d
C
138 @AllowNull(false)
139 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
140 @Column
141 name: string
72c7248b 142
3fd3ab2d 143 @AllowNull(true)
2422c46b 144 @Default(null)
3fd3ab2d 145 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description'))
a10fc78b 146 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
3fd3ab2d 147 description: string
72c7248b 148
2422c46b
C
149 @AllowNull(true)
150 @Default(null)
151 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support'))
a10fc78b 152 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
2422c46b
C
153 support: string
154
3fd3ab2d
C
155 @CreatedAt
156 createdAt: Date
72c7248b 157
3fd3ab2d
C
158 @UpdatedAt
159 updatedAt: Date
4e50b6a1 160
fadf619a
C
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
3fd3ab2d
C
173 @ForeignKey(() => AccountModel)
174 @Column
175 accountId: number
4e50b6a1 176
3fd3ab2d
C
177 @BelongsTo(() => AccountModel, {
178 foreignKey: {
179 allowNull: false
180 },
6b738c7a 181 hooks: true
3fd3ab2d
C
182 })
183 Account: AccountModel
72c7248b 184
3fd3ab2d 185 @HasMany(() => VideoModel, {
72c7248b 186 foreignKey: {
3fd3ab2d 187 name: 'channelId',
72c7248b
C
188 allowNull: false
189 },
f05a1c30
C
190 onDelete: 'CASCADE',
191 hooks: true
72c7248b 192 })
3fd3ab2d 193 Videos: VideoModel[]
72c7248b 194
f05a1c30
C
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
c5a893d5 201 if (instance.Actor.isOwned()) {
c5a893d5
C
202 return sendDeleteActor(instance.Actor, options.transaction)
203 }
204
205 return undefined
3fd3ab2d 206 }
72c7248b 207
3fd3ab2d
C
208 static countByAccount (accountId: number) {
209 const query = {
210 where: {
211 accountId
212 }
72c7248b 213 }
3fd3ab2d
C
214
215 return VideoChannelModel.count(query)
72c7248b
C
216 }
217
f37dc0dd 218 static listForApi (actorId: number, start: number, count: number, sort: string) {
3fd3ab2d
C
219 const query = {
220 offset: start,
221 limit: count,
3bb6c526 222 order: getSort(sort)
3fd3ab2d 223 }
72c7248b 224
f37dc0dd
C
225 const scopes = {
226 method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId } as AvailableForListOptions ]
227 }
50d6de9c 228 return VideoChannelModel
f37dc0dd
C
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: {
c3c2ab1c
C
256 [Sequelize.Op.or]: [
257 Sequelize.literal(
258 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
259 ),
260 Sequelize.literal(
261 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
f37dc0dd 262 )
c3c2ab1c 263 ]
f37dc0dd
C
264 }
265 }
266
267 const scopes = {
268 method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId: options.actorId } as AvailableForListOptions ]
269 }
270 return VideoChannelModel
271 .scope(scopes)
50d6de9c 272 .findAndCountAll(query)
3fd3ab2d
C
273 .then(({ rows, count }) => {
274 return { total: count, data: rows }
275 })
72c7248b
C
276 }
277
3fd3ab2d
C
278 static listByAccount (accountId: number) {
279 const query = {
3bb6c526 280 order: getSort('createdAt'),
3fd3ab2d
C
281 include: [
282 {
283 model: AccountModel,
284 where: {
285 id: accountId
286 },
50d6de9c 287 required: true
3fd3ab2d
C
288 }
289 ]
290 }
72c7248b 291
50d6de9c
C
292 return VideoChannelModel
293 .findAndCountAll(query)
3fd3ab2d
C
294 .then(({ rows, count }) => {
295 return { total: count, data: rows }
296 })
72c7248b
C
297 }
298
3fd3ab2d 299 static loadByIdAndAccount (id: number, accountId: number) {
8a19bee1 300 const query = {
3fd3ab2d
C
301 where: {
302 id,
303 accountId
d48ff09d 304 }
571389d4 305 }
3fd3ab2d 306
50d6de9c
C
307 return VideoChannelModel
308 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
8a19bee1 309 .findOne(query)
0d0e8dd0
C
310 }
311
3fd3ab2d 312 static loadAndPopulateAccount (id: number) {
50d6de9c
C
313 return VideoChannelModel
314 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
315 .findById(id)
3fd3ab2d 316 }
0d0e8dd0 317
3fd3ab2d 318 static loadByUUIDAndPopulateAccount (uuid: string) {
8a19bee1 319 const query = {
50d6de9c
C
320 include: [
321 {
322 model: ActorModel,
323 required: true,
324 where: {
325 uuid
326 }
327 }
328 ]
3fd3ab2d
C
329 }
330
50d6de9c 331 return VideoChannelModel
f37dc0dd
C
332 .scope([ ScopeNames.WITH_ACCOUNT ])
333 .findOne(query)
334 }
335
336 static loadByUrlAndPopulateAccount (url: string) {
337 const query = {
338 include: [
339 {
340 model: ActorModel,
341 required: true,
342 where: {
343 url
344 }
345 }
346 ]
347 }
348
349 return VideoChannelModel
350 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 351 .findOne(query)
72c7248b
C
352 }
353
8a19bee1
C
354 static loadLocalByNameAndPopulateAccount (name: string) {
355 const query = {
3fd3ab2d 356 include: [
8a19bee1
C
357 {
358 model: ActorModel,
359 required: true,
360 where: {
361 preferredUsername: name,
362 serverId: null
363 }
364 }
3fd3ab2d
C
365 ]
366 }
72c7248b 367
50d6de9c 368 return VideoChannelModel
8a19bee1
C
369 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
370 .findOne(query)
72c7248b
C
371 }
372
8a19bee1 373 static loadByNameAndHostAndPopulateAccount (name: string, host: string) {
06a05d5f
C
374 const query = {
375 include: [
376 {
377 model: ActorModel,
378 required: true,
379 where: {
8a19bee1
C
380 preferredUsername: name
381 },
382 include: [
383 {
384 model: ServerModel,
385 required: true,
386 where: { host }
387 }
388 ]
06a05d5f
C
389 }
390 ]
391 }
392
8a19bee1
C
393 return VideoChannelModel
394 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
395 .findOne(query)
396 }
397
398 static loadAndPopulateAccountAndVideos (id: number) {
399 const options = {
400 include: [
401 VideoModel
402 ]
403 }
404
405 return VideoChannelModel
406 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
407 .findById(id, options)
06a05d5f
C
408 }
409
2422c46b 410 toFormattedJSON (): VideoChannel {
50d6de9c 411 const actor = this.Actor.toFormattedJSON()
6b738c7a 412 const videoChannel = {
3fd3ab2d 413 id: this.id,
749c7247 414 displayName: this.getDisplayName(),
3fd3ab2d 415 description: this.description,
2422c46b 416 support: this.support,
50d6de9c 417 isLocal: this.Actor.isOwned(),
3fd3ab2d 418 createdAt: this.createdAt,
6b738c7a 419 updatedAt: this.updatedAt,
06a05d5f 420 ownerAccount: undefined
6b738c7a
C
421 }
422
a4f99a76 423 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
72c7248b 424
6b738c7a 425 return Object.assign(actor, videoChannel)
72c7248b
C
426 }
427
50d6de9c
C
428 toActivityPubObject (): ActivityPubActor {
429 const obj = this.Actor.toActivityPubObject(this.name, 'VideoChannel')
430
431 return Object.assign(obj, {
432 summary: this.description,
2422c46b 433 support: this.support,
50d6de9c
C
434 attributedTo: [
435 {
436 type: 'Person' as 'Person',
437 id: this.Account.Actor.url
438 }
439 ]
440 })
72c7248b 441 }
749c7247
C
442
443 getDisplayName () {
444 return this.name
445 }
72c7248b 446}