]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video-query-builder.ts
Fix languageOneOf filter with only _unknown
[github/Chocobozzz/PeerTube.git] / server / models / video / video-query-builder.ts
1 import { VideoFilter, VideoPrivacy, VideoState } from '@shared/models'
2 import { buildDirectionAndField, createSafeIn } from '@server/models/utils'
3 import { Model } from 'sequelize-typescript'
4 import { MUserAccountId, MUserId } from '@server/typings/models'
5 import validator from 'validator'
6 import { exists } from '@server/helpers/custom-validators/misc'
7
8 export type BuildVideosQueryOptions = {
9 attributes?: string[]
10
11 serverAccountId: number
12 followerActorId: number
13 includeLocalVideos: boolean
14
15 count: number
16 start: number
17 sort: string
18
19 filter?: VideoFilter
20 categoryOneOf?: number[]
21 nsfw?: boolean
22 licenceOneOf?: number[]
23 languageOneOf?: string[]
24 tagsOneOf?: string[]
25 tagsAllOf?: string[]
26
27 withFiles?: boolean
28
29 accountId?: number
30 videoChannelId?: number
31
32 videoPlaylistId?: number
33
34 trendingDays?: number
35 user?: MUserAccountId
36 historyOfUser?: MUserId
37
38 startDate?: string // ISO 8601
39 endDate?: string // ISO 8601
40 originallyPublishedStartDate?: string
41 originallyPublishedEndDate?: string
42
43 durationMin?: number // seconds
44 durationMax?: number // seconds
45
46 search?: string
47
48 isCount?: boolean
49
50 group?: string
51 having?: string
52 }
53
54 function buildListQuery (model: typeof Model, options: BuildVideosQueryOptions) {
55 const and: string[] = []
56 const joins: string[] = []
57 const replacements: any = {}
58 const cte: string[] = []
59
60 let attributes: string[] = options.attributes || [ '"video"."id"' ]
61 let group = options.group || ''
62 const having = options.having || ''
63
64 joins.push(
65 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId"' +
66 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId"' +
67 'INNER JOIN "actor" "accountActor" ON "account"."actorId" = "accountActor"."id"'
68 )
69
70 and.push('"video"."id" NOT IN (SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")')
71
72 if (options.serverAccountId) {
73 const blockerIds = [ options.serverAccountId ]
74 if (options.user) blockerIds.push(options.user.Account.id)
75
76 const inClause = createSafeIn(model, blockerIds)
77
78 and.push(
79 'NOT EXISTS (' +
80 ' SELECT 1 FROM "accountBlocklist" ' +
81 ' WHERE "accountBlocklist"."accountId" IN (' + inClause + ') ' +
82 ' AND "accountBlocklist"."targetAccountId" = "account"."id" ' +
83 ')' +
84 'AND NOT EXISTS (' +
85 ' SELECT 1 FROM "serverBlocklist" WHERE "serverBlocklist"."accountId" IN (' + inClause + ') ' +
86 ' AND "serverBlocklist"."targetServerId" = "accountActor"."serverId"' +
87 ')'
88 )
89 }
90
91 // Only list public/published videos
92 if (!options.filter || options.filter !== 'all-local') {
93 and.push(
94 `("video"."state" = ${VideoState.PUBLISHED} OR ` +
95 `("video"."state" = ${VideoState.TO_TRANSCODE} AND "video"."waitTranscoding" IS false))`
96 )
97
98 if (options.user) {
99 and.push(
100 `("video"."privacy" = ${VideoPrivacy.PUBLIC} OR "video"."privacy" = ${VideoPrivacy.INTERNAL})`
101 )
102 } else { // Or only public videos
103 and.push(
104 `"video"."privacy" = ${VideoPrivacy.PUBLIC}`
105 )
106 }
107 }
108
109 if (options.videoPlaylistId) {
110 joins.push(
111 'INNER JOIN "videoPlaylistElement" "video"."id" = "videoPlaylistElement"."videoId" ' +
112 'AND "videoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
113 )
114
115 replacements.videoPlaylistId = options.videoPlaylistId
116 }
117
118 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
119 and.push('"video"."remote" IS FALSE')
120 }
121
122 if (options.accountId) {
123 and.push('"account"."id" = :accountId')
124 replacements.accountId = options.accountId
125 }
126
127 if (options.videoChannelId) {
128 and.push('"videoChannel"."id" = :videoChannelId')
129 replacements.videoChannelId = options.videoChannelId
130 }
131
132 if (options.followerActorId) {
133 let query =
134 '(' +
135 ' EXISTS (' +
136 ' SELECT 1 FROM "videoShare" ' +
137 ' INNER JOIN "actorFollow" "actorFollowShare" ON "actorFollowShare"."targetActorId" = "videoShare"."actorId" ' +
138 ' AND "actorFollowShare"."actorId" = :followerActorId WHERE "videoShare"."videoId" = "video"."id"' +
139 ' )' +
140 ' OR' +
141 ' EXISTS (' +
142 ' SELECT 1 from "actorFollow" ' +
143 ' WHERE "actorFollow"."targetActorId" = "videoChannel"."actorId" AND "actorFollow"."actorId" = :followerActorId' +
144 ' )'
145
146 if (options.includeLocalVideos) {
147 query += ' OR "video"."remote" IS FALSE'
148 }
149
150 query += ')'
151
152 and.push(query)
153 replacements.followerActorId = options.followerActorId
154 }
155
156 if (options.withFiles === true) {
157 and.push('EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id")')
158 }
159
160 if (options.tagsOneOf) {
161 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
162
163 and.push(
164 'EXISTS (' +
165 ' SELECT 1 FROM "videoTag" ' +
166 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
167 ' WHERE lower("tag"."name") IN (' + createSafeIn(model, tagsOneOfLower) + ') ' +
168 ' AND "video"."id" = "videoTag"."videoId"' +
169 ')'
170 )
171 }
172
173 if (options.tagsAllOf) {
174 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
175
176 and.push(
177 'EXISTS (' +
178 ' SELECT 1 FROM "videoTag" ' +
179 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
180 ' WHERE lower("tag"."name") IN (' + createSafeIn(model, tagsAllOfLower) + ') ' +
181 ' AND "video"."id" = "videoTag"."videoId" ' +
182 ' GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
183 ')'
184 )
185 }
186
187 if (options.nsfw === true) {
188 and.push('"video"."nsfw" IS TRUE')
189 }
190
191 if (options.nsfw === false) {
192 and.push('"video"."nsfw" IS FALSE')
193 }
194
195 if (options.categoryOneOf) {
196 and.push('"video"."category" IN (:categoryOneOf)')
197 replacements.categoryOneOf = options.categoryOneOf
198 }
199
200 if (options.licenceOneOf) {
201 and.push('"video"."licence" IN (:licenceOneOf)')
202 replacements.licenceOneOf = options.licenceOneOf
203 }
204
205 if (options.languageOneOf) {
206 const languages = options.languageOneOf.filter(l => l && l !== '_unknown')
207 const languagesQueryParts: string[] = []
208
209 if (languages.length !== 0) {
210 languagesQueryParts.push('("video"."language" IN (:languageOneOf)')
211 replacements.languageOneOf = languages
212
213 languagesQueryParts.push(
214 ' EXISTS (' +
215 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
216 ' IN (' + createSafeIn(model, languages) + ') AND ' +
217 ' "videoCaption"."videoId" = "video"."id"' +
218 ' )' +
219 ')'
220 )
221 }
222
223 if (options.languageOneOf.includes('_unknown')) {
224 languagesQueryParts.push('"video"."language" IS NULL')
225 }
226
227 and.push(languagesQueryParts.join(' OR '))
228 }
229
230 // We don't exclude results in this if so if we do a count we don't need to add this complex clauses
231 if (options.trendingDays && options.isCount !== true) {
232 const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * options.trendingDays)
233
234 joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
235 replacements.viewsGteDate = viewsGteDate
236
237 attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "videoViewsSum"')
238
239 group = 'GROUP BY "video"."id"'
240 }
241
242 if (options.historyOfUser) {
243 joins.push('INNER JOIN "userVideoHistory" on "video"."id" = "userVideoHistory"."videoId"')
244
245 and.push('"userVideoHistory"."userId" = :historyOfUser')
246 replacements.historyOfUser = options.historyOfUser.id
247 }
248
249 if (options.startDate) {
250 and.push('"video"."publishedAt" >= :startDate')
251 replacements.startDate = options.startDate
252 }
253
254 if (options.endDate) {
255 and.push('"video"."publishedAt" <= :endDate')
256 replacements.endDate = options.endDate
257 }
258
259 if (options.originallyPublishedStartDate) {
260 and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
261 replacements.originallyPublishedStartDate = options.originallyPublishedStartDate
262 }
263
264 if (options.originallyPublishedEndDate) {
265 and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
266 replacements.originallyPublishedEndDate = options.originallyPublishedEndDate
267 }
268
269 if (options.durationMin) {
270 and.push('"video"."duration" >= :durationMin')
271 replacements.durationMin = options.durationMin
272 }
273
274 if (options.durationMax) {
275 and.push('"video"."duration" <= :durationMax')
276 replacements.durationMax = options.durationMax
277 }
278
279 if (options.search) {
280 const escapedSearch = model.sequelize.escape(options.search)
281 const escapedLikeSearch = model.sequelize.escape('%' + options.search + '%')
282
283 cte.push(
284 '"trigramSearch" AS (' +
285 ' SELECT "video"."id", ' +
286 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
287 ' FROM "video" ' +
288 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
289 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
290 ')'
291 )
292
293 joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
294
295 let base = '(' +
296 ' "trigramSearch"."id" IS NOT NULL OR ' +
297 ' EXISTS (' +
298 ' SELECT 1 FROM "videoTag" ' +
299 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
300 ` WHERE lower("tag"."name") = ${escapedSearch} ` +
301 ' AND "video"."id" = "videoTag"."videoId"' +
302 ' )'
303
304 if (validator.isUUID(options.search)) {
305 base += ` OR "video"."uuid" = ${escapedSearch}`
306 }
307
308 base += ')'
309 and.push(base)
310
311 attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
312 } else {
313 attributes.push('0 as similarity')
314 }
315
316 if (options.isCount === true) attributes = [ 'COUNT(*) as "total"' ]
317
318 let suffix = ''
319 let order = ''
320 if (options.isCount !== true) {
321
322 if (exists(options.sort)) {
323 order = buildOrder(model, options.sort)
324 suffix += `${order} `
325 }
326
327 if (exists(options.count)) {
328 const count = parseInt(options.count + '', 10)
329 suffix += `LIMIT ${count} `
330 }
331
332 if (exists(options.start)) {
333 const start = parseInt(options.start + '', 10)
334 suffix += `OFFSET ${start} `
335 }
336 }
337
338 const cteString = cte.length !== 0
339 ? `WITH ${cte.join(', ')} `
340 : ''
341
342 const query = cteString +
343 'SELECT ' + attributes.join(', ') + ' ' +
344 'FROM "video" ' + joins.join(' ') + ' ' +
345 'WHERE ' + and.join(' AND ') + ' ' +
346 group + ' ' +
347 having + ' ' +
348 suffix
349
350 return { query, replacements, order }
351 }
352
353 function buildOrder (model: typeof Model, value: string) {
354 const { direction, field } = buildDirectionAndField(value)
355 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
356
357 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
358
359 if (field.toLowerCase() === 'trending') { // Sort by aggregation
360 return `ORDER BY "videoViewsSum" ${direction}, "video"."views" ${direction}`
361 }
362
363 let firstSort: string
364
365 if (field.toLowerCase() === 'match') { // Search
366 firstSort = '"similarity"'
367 } else if (field.includes('.')) {
368 firstSort = field
369 } else {
370 firstSort = `"video"."${field}"`
371 }
372
373 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
374 }
375
376 function wrapForAPIResults (baseQuery: string, replacements: any, options: BuildVideosQueryOptions, order: string) {
377 const attributes = {
378 '"video".*': '',
379 '"VideoChannel"."id"': '"VideoChannel.id"',
380 '"VideoChannel"."name"': '"VideoChannel.name"',
381 '"VideoChannel"."description"': '"VideoChannel.description"',
382 '"VideoChannel"."actorId"': '"VideoChannel.actorId"',
383 '"VideoChannel->Actor"."id"': '"VideoChannel.Actor.id"',
384 '"VideoChannel->Actor"."preferredUsername"': '"VideoChannel.Actor.preferredUsername"',
385 '"VideoChannel->Actor"."url"': '"VideoChannel.Actor.url"',
386 '"VideoChannel->Actor"."serverId"': '"VideoChannel.Actor.serverId"',
387 '"VideoChannel->Actor"."avatarId"': '"VideoChannel.Actor.avatarId"',
388 '"VideoChannel->Account"."id"': '"VideoChannel.Account.id"',
389 '"VideoChannel->Account"."name"': '"VideoChannel.Account.name"',
390 '"VideoChannel->Account->Actor"."id"': '"VideoChannel.Account.Actor.id"',
391 '"VideoChannel->Account->Actor"."preferredUsername"': '"VideoChannel.Account.Actor.preferredUsername"',
392 '"VideoChannel->Account->Actor"."url"': '"VideoChannel.Account.Actor.url"',
393 '"VideoChannel->Account->Actor"."serverId"': '"VideoChannel.Account.Actor.serverId"',
394 '"VideoChannel->Account->Actor"."avatarId"': '"VideoChannel.Account.Actor.avatarId"',
395 '"VideoChannel->Actor->Server"."id"': '"VideoChannel.Actor.Server.id"',
396 '"VideoChannel->Actor->Server"."host"': '"VideoChannel.Actor.Server.host"',
397 '"VideoChannel->Actor->Avatar"."id"': '"VideoChannel.Actor.Avatar.id"',
398 '"VideoChannel->Actor->Avatar"."filename"': '"VideoChannel.Actor.Avatar.filename"',
399 '"VideoChannel->Actor->Avatar"."fileUrl"': '"VideoChannel.Actor.Avatar.fileUrl"',
400 '"VideoChannel->Actor->Avatar"."onDisk"': '"VideoChannel.Actor.Avatar.onDisk"',
401 '"VideoChannel->Actor->Avatar"."createdAt"': '"VideoChannel.Actor.Avatar.createdAt"',
402 '"VideoChannel->Actor->Avatar"."updatedAt"': '"VideoChannel.Actor.Avatar.updatedAt"',
403 '"VideoChannel->Account->Actor->Server"."id"': '"VideoChannel.Account.Actor.Server.id"',
404 '"VideoChannel->Account->Actor->Server"."host"': '"VideoChannel.Account.Actor.Server.host"',
405 '"VideoChannel->Account->Actor->Avatar"."id"': '"VideoChannel.Account.Actor.Avatar.id"',
406 '"VideoChannel->Account->Actor->Avatar"."filename"': '"VideoChannel.Account.Actor.Avatar.filename"',
407 '"VideoChannel->Account->Actor->Avatar"."fileUrl"': '"VideoChannel.Account.Actor.Avatar.fileUrl"',
408 '"VideoChannel->Account->Actor->Avatar"."onDisk"': '"VideoChannel.Account.Actor.Avatar.onDisk"',
409 '"VideoChannel->Account->Actor->Avatar"."createdAt"': '"VideoChannel.Account.Actor.Avatar.createdAt"',
410 '"VideoChannel->Account->Actor->Avatar"."updatedAt"': '"VideoChannel.Account.Actor.Avatar.updatedAt"',
411 '"Thumbnails"."id"': '"Thumbnails.id"',
412 '"Thumbnails"."type"': '"Thumbnails.type"',
413 '"Thumbnails"."filename"': '"Thumbnails.filename"'
414 }
415
416 const joins = [
417 'INNER JOIN "video" ON "tmp"."id" = "video"."id"',
418
419 'INNER JOIN "videoChannel" AS "VideoChannel" ON "video"."channelId" = "VideoChannel"."id"',
420 'INNER JOIN "actor" AS "VideoChannel->Actor" ON "VideoChannel"."actorId" = "VideoChannel->Actor"."id"',
421 'INNER JOIN "account" AS "VideoChannel->Account" ON "VideoChannel"."accountId" = "VideoChannel->Account"."id"',
422 'INNER JOIN "actor" AS "VideoChannel->Account->Actor" ON "VideoChannel->Account"."actorId" = "VideoChannel->Account->Actor"."id"',
423
424 'LEFT OUTER JOIN "server" AS "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id"',
425 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Actor->Avatar" ON "VideoChannel->Actor"."avatarId" = "VideoChannel->Actor->Avatar"."id"',
426
427 'LEFT OUTER JOIN "server" AS "VideoChannel->Account->Actor->Server" ' +
428 'ON "VideoChannel->Account->Actor"."serverId" = "VideoChannel->Account->Actor->Server"."id"',
429
430 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Account->Actor->Avatar" ' +
431 'ON "VideoChannel->Account->Actor"."avatarId" = "VideoChannel->Account->Actor->Avatar"."id"',
432
433 'LEFT OUTER JOIN "thumbnail" AS "Thumbnails" ON "video"."id" = "Thumbnails"."videoId"'
434 ]
435
436 if (options.withFiles) {
437 joins.push('INNER JOIN "videoFile" AS "VideoFiles" ON "VideoFiles"."videoId" = "video"."id"')
438
439 Object.assign(attributes, {
440 '"VideoFiles"."id"': '"VideoFiles.id"',
441 '"VideoFiles"."createdAt"': '"VideoFiles.createdAt"',
442 '"VideoFiles"."updatedAt"': '"VideoFiles.updatedAt"',
443 '"VideoFiles"."resolution"': '"VideoFiles.resolution"',
444 '"VideoFiles"."size"': '"VideoFiles.size"',
445 '"VideoFiles"."extname"': '"VideoFiles.extname"',
446 '"VideoFiles"."infoHash"': '"VideoFiles.infoHash"',
447 '"VideoFiles"."fps"': '"VideoFiles.fps"',
448 '"VideoFiles"."videoId"': '"VideoFiles.videoId"'
449 })
450 }
451
452 if (options.user) {
453 joins.push(
454 'LEFT OUTER JOIN "userVideoHistory" ' +
455 'ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :userVideoHistoryId'
456 )
457 replacements.userVideoHistoryId = options.user.id
458
459 Object.assign(attributes, {
460 '"userVideoHistory"."id"': '"userVideoHistory.id"',
461 '"userVideoHistory"."currentTime"': '"userVideoHistory.currentTime"'
462 })
463 }
464
465 if (options.videoPlaylistId) {
466 joins.push(
467 'INNER JOIN "videoPlaylistElement" as "VideoPlaylistElement" ON "videoPlaylistElement"."videoId" = "video"."id" ' +
468 'AND "VideoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
469 )
470 replacements.videoPlaylistId = options.videoPlaylistId
471
472 Object.assign(attributes, {
473 '"VideoPlaylistElement"."createdAt"': '"VideoPlaylistElement.createdAt"',
474 '"VideoPlaylistElement"."updatedAt"': '"VideoPlaylistElement.updatedAt"',
475 '"VideoPlaylistElement"."url"': '"VideoPlaylistElement.url"',
476 '"VideoPlaylistElement"."position"': '"VideoPlaylistElement.position"',
477 '"VideoPlaylistElement"."startTimestamp"': '"VideoPlaylistElement.startTimestamp"',
478 '"VideoPlaylistElement"."stopTimestamp"': '"VideoPlaylistElement.stopTimestamp"',
479 '"VideoPlaylistElement"."videoPlaylistId"': '"VideoPlaylistElement.videoPlaylistId"'
480 })
481 }
482
483 const select = 'SELECT ' + Object.keys(attributes).map(key => {
484 const value = attributes[key]
485 if (value) return `${key} AS ${value}`
486
487 return key
488 }).join(', ')
489
490 return `${select} FROM (${baseQuery}) AS "tmp" ${joins.join(' ')} ${order}`
491 }
492
493 export {
494 buildListQuery,
495 wrapForAPIResults
496 }