]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-query-builder.ts
Add ability to sort by originallyPublishedAt
[github/Chocobozzz/PeerTube.git] / server / models / video / video-query-builder.ts
CommitLineData
5f3e2425
C
1import { VideoFilter, VideoPrivacy, VideoState } from '@shared/models'
2import { buildDirectionAndField, createSafeIn } from '@server/models/utils'
3import { Model } from 'sequelize-typescript'
4import { MUserAccountId, MUserId } from '@server/typings/models'
5import validator from 'validator'
fab67463 6import { exists } from '@server/helpers/custom-validators/misc'
5f3e2425
C
7
8export 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
54function buildListQuery (model: typeof Model, options: BuildVideosQueryOptions) {
55 const and: string[] = []
5f3e2425
C
56 const joins: string[] = []
57 const replacements: any = {}
6b842050 58 const cte: string[] = []
5f3e2425
C
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"' +
6b842050 67 'INNER JOIN "actor" "accountActor" ON "account"."actorId" = "accountActor"."id"'
5f3e2425
C
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
6b842050 76 const inClause = createSafeIn(model, blockerIds)
5f3e2425
C
77
78 and.push(
6b842050
C
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 ')'
5f3e2425 88 )
5f3e2425
C
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" ' +
6b842050 143 ' WHERE "actorFollow"."targetActorId" = "videoChannel"."actorId" AND "actorFollow"."actorId" = :followerActorId' +
5f3e2425
C
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) {
14cbb9a6
C
206 const languages = options.languageOneOf.filter(l => l && l !== '_unknown')
207 const languagesQueryParts: string[] = []
208
209 if (languages.length !== 0) {
8f31261f 210 languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
14cbb9a6
C
211 replacements.languageOneOf = languages
212
213 languagesQueryParts.push(
8f31261f
C
214 'EXISTS (' +
215 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
216 ' IN (' + createSafeIn(model, languages) + ') AND ' +
217 ' "videoCaption"."videoId" = "video"."id"' +
14cbb9a6
C
218 ')'
219 )
220 }
5f3e2425
C
221
222 if (options.languageOneOf.includes('_unknown')) {
14cbb9a6 223 languagesQueryParts.push('"video"."language" IS NULL')
5f3e2425
C
224 }
225
8f31261f
C
226 if (languagesQueryParts.length !== 0) {
227 and.push('(' + languagesQueryParts.join(' OR ') + ')')
228 }
5f3e2425
C
229 }
230
231 // We don't exclude results in this if so if we do a count we don't need to add this complex clauses
232 if (options.trendingDays && options.isCount !== true) {
233 const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * options.trendingDays)
234
235 joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
236 replacements.viewsGteDate = viewsGteDate
237
6b842050
C
238 attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "videoViewsSum"')
239
5f3e2425
C
240 group = 'GROUP BY "video"."id"'
241 }
242
243 if (options.historyOfUser) {
244 joins.push('INNER JOIN "userVideoHistory" on "video"."id" = "userVideoHistory"."videoId"')
245
246 and.push('"userVideoHistory"."userId" = :historyOfUser')
6b842050 247 replacements.historyOfUser = options.historyOfUser.id
5f3e2425
C
248 }
249
250 if (options.startDate) {
251 and.push('"video"."publishedAt" >= :startDate')
252 replacements.startDate = options.startDate
253 }
254
255 if (options.endDate) {
256 and.push('"video"."publishedAt" <= :endDate')
257 replacements.endDate = options.endDate
258 }
259
260 if (options.originallyPublishedStartDate) {
261 and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
262 replacements.originallyPublishedStartDate = options.originallyPublishedStartDate
263 }
264
265 if (options.originallyPublishedEndDate) {
266 and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
267 replacements.originallyPublishedEndDate = options.originallyPublishedEndDate
268 }
269
270 if (options.durationMin) {
271 and.push('"video"."duration" >= :durationMin')
272 replacements.durationMin = options.durationMin
273 }
274
275 if (options.durationMax) {
276 and.push('"video"."duration" <= :durationMax')
277 replacements.durationMax = options.durationMax
278 }
279
280 if (options.search) {
281 const escapedSearch = model.sequelize.escape(options.search)
282 const escapedLikeSearch = model.sequelize.escape('%' + options.search + '%')
283
6b842050
C
284 cte.push(
285 '"trigramSearch" AS (' +
286 ' SELECT "video"."id", ' +
287 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
288 ' FROM "video" ' +
289 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
290 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
291 ')'
292 )
293
294 joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
295
5f3e2425 296 let base = '(' +
6b842050 297 ' "trigramSearch"."id" IS NOT NULL OR ' +
5f3e2425
C
298 ' EXISTS (' +
299 ' SELECT 1 FROM "videoTag" ' +
300 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
301 ` WHERE lower("tag"."name") = ${escapedSearch} ` +
302 ' AND "video"."id" = "videoTag"."videoId"' +
303 ' )'
304
305 if (validator.isUUID(options.search)) {
306 base += ` OR "video"."uuid" = ${escapedSearch}`
307 }
308
309 base += ')'
310 and.push(base)
311
6b842050 312 attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
5f3e2425
C
313 } else {
314 attributes.push('0 as similarity')
315 }
316
317 if (options.isCount === true) attributes = [ 'COUNT(*) as "total"' ]
318
6b842050
C
319 let suffix = ''
320 let order = ''
5f3e2425 321 if (options.isCount !== true) {
5f3e2425 322
fab67463 323 if (exists(options.sort)) {
2fd59d7d
C
324 if (options.sort === '-originallyPublishedAt' || options.sort === 'originallyPublishedAt') {
325 attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
326 }
327
fab67463
C
328 order = buildOrder(model, options.sort)
329 suffix += `${order} `
330 }
331
332 if (exists(options.count)) {
333 const count = parseInt(options.count + '', 10)
334 suffix += `LIMIT ${count} `
335 }
6b842050 336
fab67463
C
337 if (exists(options.start)) {
338 const start = parseInt(options.start + '', 10)
339 suffix += `OFFSET ${start} `
340 }
5f3e2425
C
341 }
342
6b842050
C
343 const cteString = cte.length !== 0
344 ? `WITH ${cte.join(', ')} `
345 : ''
346
347 const query = cteString +
348 'SELECT ' + attributes.join(', ') + ' ' +
349 'FROM "video" ' + joins.join(' ') + ' ' +
350 'WHERE ' + and.join(' AND ') + ' ' +
351 group + ' ' +
352 having + ' ' +
353 suffix
354
355 return { query, replacements, order }
5f3e2425
C
356}
357
358function buildOrder (model: typeof Model, value: string) {
359 const { direction, field } = buildDirectionAndField(value)
6b842050 360 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
5f3e2425
C
361
362 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
363
364 if (field.toLowerCase() === 'trending') { // Sort by aggregation
6b842050 365 return `ORDER BY "videoViewsSum" ${direction}, "video"."views" ${direction}`
5f3e2425
C
366 }
367
368 let firstSort: string
369
370 if (field.toLowerCase() === 'match') { // Search
371 firstSort = '"similarity"'
2fd59d7d
C
372 } else if (field === 'originallyPublishedAt') {
373 firstSort = '"publishedAtForOrder"'
6b842050
C
374 } else if (field.includes('.')) {
375 firstSort = field
5f3e2425
C
376 } else {
377 firstSort = `"video"."${field}"`
378 }
379
380 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
381}
382
6b842050
C
383function wrapForAPIResults (baseQuery: string, replacements: any, options: BuildVideosQueryOptions, order: string) {
384 const attributes = {
385 '"video".*': '',
386 '"VideoChannel"."id"': '"VideoChannel.id"',
387 '"VideoChannel"."name"': '"VideoChannel.name"',
388 '"VideoChannel"."description"': '"VideoChannel.description"',
389 '"VideoChannel"."actorId"': '"VideoChannel.actorId"',
390 '"VideoChannel->Actor"."id"': '"VideoChannel.Actor.id"',
391 '"VideoChannel->Actor"."preferredUsername"': '"VideoChannel.Actor.preferredUsername"',
392 '"VideoChannel->Actor"."url"': '"VideoChannel.Actor.url"',
393 '"VideoChannel->Actor"."serverId"': '"VideoChannel.Actor.serverId"',
394 '"VideoChannel->Actor"."avatarId"': '"VideoChannel.Actor.avatarId"',
395 '"VideoChannel->Account"."id"': '"VideoChannel.Account.id"',
396 '"VideoChannel->Account"."name"': '"VideoChannel.Account.name"',
397 '"VideoChannel->Account->Actor"."id"': '"VideoChannel.Account.Actor.id"',
398 '"VideoChannel->Account->Actor"."preferredUsername"': '"VideoChannel.Account.Actor.preferredUsername"',
399 '"VideoChannel->Account->Actor"."url"': '"VideoChannel.Account.Actor.url"',
400 '"VideoChannel->Account->Actor"."serverId"': '"VideoChannel.Account.Actor.serverId"',
401 '"VideoChannel->Account->Actor"."avatarId"': '"VideoChannel.Account.Actor.avatarId"',
402 '"VideoChannel->Actor->Server"."id"': '"VideoChannel.Actor.Server.id"',
403 '"VideoChannel->Actor->Server"."host"': '"VideoChannel.Actor.Server.host"',
404 '"VideoChannel->Actor->Avatar"."id"': '"VideoChannel.Actor.Avatar.id"',
405 '"VideoChannel->Actor->Avatar"."filename"': '"VideoChannel.Actor.Avatar.filename"',
406 '"VideoChannel->Actor->Avatar"."fileUrl"': '"VideoChannel.Actor.Avatar.fileUrl"',
407 '"VideoChannel->Actor->Avatar"."onDisk"': '"VideoChannel.Actor.Avatar.onDisk"',
408 '"VideoChannel->Actor->Avatar"."createdAt"': '"VideoChannel.Actor.Avatar.createdAt"',
409 '"VideoChannel->Actor->Avatar"."updatedAt"': '"VideoChannel.Actor.Avatar.updatedAt"',
410 '"VideoChannel->Account->Actor->Server"."id"': '"VideoChannel.Account.Actor.Server.id"',
411 '"VideoChannel->Account->Actor->Server"."host"': '"VideoChannel.Account.Actor.Server.host"',
412 '"VideoChannel->Account->Actor->Avatar"."id"': '"VideoChannel.Account.Actor.Avatar.id"',
413 '"VideoChannel->Account->Actor->Avatar"."filename"': '"VideoChannel.Account.Actor.Avatar.filename"',
414 '"VideoChannel->Account->Actor->Avatar"."fileUrl"': '"VideoChannel.Account.Actor.Avatar.fileUrl"',
415 '"VideoChannel->Account->Actor->Avatar"."onDisk"': '"VideoChannel.Account.Actor.Avatar.onDisk"',
416 '"VideoChannel->Account->Actor->Avatar"."createdAt"': '"VideoChannel.Account.Actor.Avatar.createdAt"',
417 '"VideoChannel->Account->Actor->Avatar"."updatedAt"': '"VideoChannel.Account.Actor.Avatar.updatedAt"',
418 '"Thumbnails"."id"': '"Thumbnails.id"',
419 '"Thumbnails"."type"': '"Thumbnails.type"',
420 '"Thumbnails"."filename"': '"Thumbnails.filename"'
421 }
422
423 const joins = [
424 'INNER JOIN "video" ON "tmp"."id" = "video"."id"',
425
426 'INNER JOIN "videoChannel" AS "VideoChannel" ON "video"."channelId" = "VideoChannel"."id"',
427 'INNER JOIN "actor" AS "VideoChannel->Actor" ON "VideoChannel"."actorId" = "VideoChannel->Actor"."id"',
428 'INNER JOIN "account" AS "VideoChannel->Account" ON "VideoChannel"."accountId" = "VideoChannel->Account"."id"',
429 'INNER JOIN "actor" AS "VideoChannel->Account->Actor" ON "VideoChannel->Account"."actorId" = "VideoChannel->Account->Actor"."id"',
430
431 'LEFT OUTER JOIN "server" AS "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id"',
432 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Actor->Avatar" ON "VideoChannel->Actor"."avatarId" = "VideoChannel->Actor->Avatar"."id"',
433
434 'LEFT OUTER JOIN "server" AS "VideoChannel->Account->Actor->Server" ' +
435 'ON "VideoChannel->Account->Actor"."serverId" = "VideoChannel->Account->Actor->Server"."id"',
436
437 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Account->Actor->Avatar" ' +
438 'ON "VideoChannel->Account->Actor"."avatarId" = "VideoChannel->Account->Actor->Avatar"."id"',
439
440 'LEFT OUTER JOIN "thumbnail" AS "Thumbnails" ON "video"."id" = "Thumbnails"."videoId"'
441 ]
442
443 if (options.withFiles) {
444 joins.push('INNER JOIN "videoFile" AS "VideoFiles" ON "VideoFiles"."videoId" = "video"."id"')
445
446 Object.assign(attributes, {
447 '"VideoFiles"."id"': '"VideoFiles.id"',
448 '"VideoFiles"."createdAt"': '"VideoFiles.createdAt"',
449 '"VideoFiles"."updatedAt"': '"VideoFiles.updatedAt"',
450 '"VideoFiles"."resolution"': '"VideoFiles.resolution"',
451 '"VideoFiles"."size"': '"VideoFiles.size"',
452 '"VideoFiles"."extname"': '"VideoFiles.extname"',
453 '"VideoFiles"."infoHash"': '"VideoFiles.infoHash"',
454 '"VideoFiles"."fps"': '"VideoFiles.fps"',
455 '"VideoFiles"."videoId"': '"VideoFiles.videoId"'
456 })
457 }
458
459 if (options.user) {
460 joins.push(
461 'LEFT OUTER JOIN "userVideoHistory" ' +
462 'ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :userVideoHistoryId'
463 )
464 replacements.userVideoHistoryId = options.user.id
465
466 Object.assign(attributes, {
467 '"userVideoHistory"."id"': '"userVideoHistory.id"',
468 '"userVideoHistory"."currentTime"': '"userVideoHistory.currentTime"'
469 })
470 }
471
472 if (options.videoPlaylistId) {
473 joins.push(
474 'INNER JOIN "videoPlaylistElement" as "VideoPlaylistElement" ON "videoPlaylistElement"."videoId" = "video"."id" ' +
475 'AND "VideoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
476 )
477 replacements.videoPlaylistId = options.videoPlaylistId
478
479 Object.assign(attributes, {
480 '"VideoPlaylistElement"."createdAt"': '"VideoPlaylistElement.createdAt"',
481 '"VideoPlaylistElement"."updatedAt"': '"VideoPlaylistElement.updatedAt"',
482 '"VideoPlaylistElement"."url"': '"VideoPlaylistElement.url"',
483 '"VideoPlaylistElement"."position"': '"VideoPlaylistElement.position"',
484 '"VideoPlaylistElement"."startTimestamp"': '"VideoPlaylistElement.startTimestamp"',
485 '"VideoPlaylistElement"."stopTimestamp"': '"VideoPlaylistElement.stopTimestamp"',
486 '"VideoPlaylistElement"."videoPlaylistId"': '"VideoPlaylistElement.videoPlaylistId"'
487 })
488 }
489
490 const select = 'SELECT ' + Object.keys(attributes).map(key => {
491 const value = attributes[key]
492 if (value) return `${key} AS ${value}`
493
494 return key
495 }).join(', ')
496
497 return `${select} FROM (${baseQuery}) AS "tmp" ${joins.join(' ')} ${order}`
498}
499
5f3e2425 500export {
6b842050
C
501 buildListQuery,
502 wrapForAPIResults
5f3e2425 503}