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