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/types/models'
5 import validator from 'validator'
6 import { exists } from '@server/helpers/custom-validators/misc'
8 export type BuildVideosQueryOptions = {
11 serverAccountId: number
12 followerActorId: number
13 includeLocalVideos: boolean
20 categoryOneOf?: number[]
22 licenceOneOf?: number[]
23 languageOneOf?: string[]
30 videoChannelId?: number
32 videoPlaylistId?: number
36 historyOfUser?: MUserId
38 startDate?: string // ISO 8601
39 endDate?: string // ISO 8601
40 originallyPublishedStartDate?: string
41 originallyPublishedEndDate?: string
43 durationMin?: number // seconds
44 durationMax?: number // seconds
54 function buildListQuery (model: typeof Model, options: BuildVideosQueryOptions) {
55 const and: string[] = []
56 const joins: string[] = []
57 const replacements: any = {}
58 const cte: string[] = []
60 let attributes: string[] = options.attributes || [ '"video"."id"' ]
61 let group = options.group || ''
62 const having = options.having || ''
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"'
70 and.push('"video"."id" NOT IN (SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")')
72 if (options.serverAccountId) {
73 const blockerIds = [ options.serverAccountId ]
74 if (options.user) blockerIds.push(options.user.Account.id)
76 const inClause = createSafeIn(model, blockerIds)
80 ' SELECT 1 FROM "accountBlocklist" ' +
81 ' WHERE "accountBlocklist"."accountId" IN (' + inClause + ') ' +
82 ' AND "accountBlocklist"."targetAccountId" = "account"."id" ' +
85 ' SELECT 1 FROM "serverBlocklist" WHERE "serverBlocklist"."accountId" IN (' + inClause + ') ' +
86 ' AND "serverBlocklist"."targetServerId" = "accountActor"."serverId"' +
91 // Only list public/published videos
92 if (!options.filter || options.filter !== 'all-local') {
94 `("video"."state" = ${VideoState.PUBLISHED} OR ` +
95 `("video"."state" = ${VideoState.TO_TRANSCODE} AND "video"."waitTranscoding" IS false))`
100 `("video"."privacy" = ${VideoPrivacy.PUBLIC} OR "video"."privacy" = ${VideoPrivacy.INTERNAL})`
102 } else { // Or only public videos
104 `"video"."privacy" = ${VideoPrivacy.PUBLIC}`
109 if (options.videoPlaylistId) {
111 'INNER JOIN "videoPlaylistElement" "video"."id" = "videoPlaylistElement"."videoId" ' +
112 'AND "videoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
115 replacements.videoPlaylistId = options.videoPlaylistId
118 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
119 and.push('"video"."remote" IS FALSE')
122 if (options.accountId) {
123 and.push('"account"."id" = :accountId')
124 replacements.accountId = options.accountId
127 if (options.videoChannelId) {
128 and.push('"videoChannel"."id" = :videoChannelId')
129 replacements.videoChannelId = options.videoChannelId
132 if (options.followerActorId) {
136 ' SELECT 1 FROM "videoShare" ' +
137 ' INNER JOIN "actorFollow" "actorFollowShare" ON "actorFollowShare"."targetActorId" = "videoShare"."actorId" ' +
138 ' AND "actorFollowShare"."actorId" = :followerActorId AND "actorFollowShare"."state" = \'accepted\' ' +
139 ' WHERE "videoShare"."videoId" = "video"."id"' +
143 ' SELECT 1 from "actorFollow" ' +
144 ' WHERE "actorFollow"."targetActorId" = "videoChannel"."actorId" AND "actorFollow"."actorId" = :followerActorId ' +
145 ' AND "actorFollow"."state" = \'accepted\'' +
148 if (options.includeLocalVideos) {
149 query += ' OR "video"."remote" IS FALSE'
155 replacements.followerActorId = options.followerActorId
158 if (options.withFiles === true) {
161 ' EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id") ' +
163 ' SELECT 1 FROM "videoStreamingPlaylist" ' +
164 ' INNER JOIN "videoFile" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ' +
165 ' WHERE "videoStreamingPlaylist"."videoId" = "video"."id"' +
171 if (options.tagsOneOf) {
172 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
176 ' SELECT 1 FROM "videoTag" ' +
177 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
178 ' WHERE lower("tag"."name") IN (' + createSafeIn(model, tagsOneOfLower) + ') ' +
179 ' AND "video"."id" = "videoTag"."videoId"' +
184 if (options.tagsAllOf) {
185 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
189 ' SELECT 1 FROM "videoTag" ' +
190 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
191 ' WHERE lower("tag"."name") IN (' + createSafeIn(model, tagsAllOfLower) + ') ' +
192 ' AND "video"."id" = "videoTag"."videoId" ' +
193 ' GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
198 if (options.nsfw === true) {
199 and.push('"video"."nsfw" IS TRUE')
202 if (options.nsfw === false) {
203 and.push('"video"."nsfw" IS FALSE')
206 if (options.categoryOneOf) {
207 and.push('"video"."category" IN (:categoryOneOf)')
208 replacements.categoryOneOf = options.categoryOneOf
211 if (options.licenceOneOf) {
212 and.push('"video"."licence" IN (:licenceOneOf)')
213 replacements.licenceOneOf = options.licenceOneOf
216 if (options.languageOneOf) {
217 const languages = options.languageOneOf.filter(l => l && l !== '_unknown')
218 const languagesQueryParts: string[] = []
220 if (languages.length !== 0) {
221 languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
222 replacements.languageOneOf = languages
224 languagesQueryParts.push(
226 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
227 ' IN (' + createSafeIn(model, languages) + ') AND ' +
228 ' "videoCaption"."videoId" = "video"."id"' +
233 if (options.languageOneOf.includes('_unknown')) {
234 languagesQueryParts.push('"video"."language" IS NULL')
237 if (languagesQueryParts.length !== 0) {
238 and.push('(' + languagesQueryParts.join(' OR ') + ')')
242 // We don't exclude results in this if so if we do a count we don't need to add this complex clauses
243 if (options.trendingDays && options.isCount !== true) {
244 const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * options.trendingDays)
246 joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
247 replacements.viewsGteDate = viewsGteDate
249 attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "videoViewsSum"')
251 group = 'GROUP BY "video"."id"'
254 if (options.historyOfUser) {
255 joins.push('INNER JOIN "userVideoHistory" on "video"."id" = "userVideoHistory"."videoId"')
257 and.push('"userVideoHistory"."userId" = :historyOfUser')
258 replacements.historyOfUser = options.historyOfUser.id
261 if (options.startDate) {
262 and.push('"video"."publishedAt" >= :startDate')
263 replacements.startDate = options.startDate
266 if (options.endDate) {
267 and.push('"video"."publishedAt" <= :endDate')
268 replacements.endDate = options.endDate
271 if (options.originallyPublishedStartDate) {
272 and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
273 replacements.originallyPublishedStartDate = options.originallyPublishedStartDate
276 if (options.originallyPublishedEndDate) {
277 and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
278 replacements.originallyPublishedEndDate = options.originallyPublishedEndDate
281 if (options.durationMin) {
282 and.push('"video"."duration" >= :durationMin')
283 replacements.durationMin = options.durationMin
286 if (options.durationMax) {
287 and.push('"video"."duration" <= :durationMax')
288 replacements.durationMax = options.durationMax
291 if (options.search) {
292 const escapedSearch = model.sequelize.escape(options.search)
293 const escapedLikeSearch = model.sequelize.escape('%' + options.search + '%')
296 '"trigramSearch" AS (' +
297 ' SELECT "video"."id", ' +
298 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
300 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
301 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
305 joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
308 ' "trigramSearch"."id" IS NOT NULL OR ' +
310 ' SELECT 1 FROM "videoTag" ' +
311 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
312 ` WHERE lower("tag"."name") = ${escapedSearch} ` +
313 ' AND "video"."id" = "videoTag"."videoId"' +
316 if (validator.isUUID(options.search)) {
317 base += ` OR "video"."uuid" = ${escapedSearch}`
323 attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
325 attributes.push('0 as similarity')
328 if (options.isCount === true) attributes = [ 'COUNT(*) as "total"' ]
332 if (options.isCount !== true) {
334 if (exists(options.sort)) {
335 if (options.sort === '-originallyPublishedAt' || options.sort === 'originallyPublishedAt') {
336 attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
339 order = buildOrder(options.sort)
340 suffix += `${order} `
343 if (exists(options.count)) {
344 const count = parseInt(options.count + '', 10)
345 suffix += `LIMIT ${count} `
348 if (exists(options.start)) {
349 const start = parseInt(options.start + '', 10)
350 suffix += `OFFSET ${start} `
354 const cteString = cte.length !== 0
355 ? `WITH ${cte.join(', ')} `
358 const query = cteString +
359 'SELECT ' + attributes.join(', ') + ' ' +
360 'FROM "video" ' + joins.join(' ') + ' ' +
361 'WHERE ' + and.join(' AND ') + ' ' +
366 return { query, replacements, order }
369 function buildOrder (value: string) {
370 const { direction, field } = buildDirectionAndField(value)
371 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
373 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
375 if (field.toLowerCase() === 'trending') { // Sort by aggregation
376 return `ORDER BY "videoViewsSum" ${direction}, "video"."views" ${direction}`
379 let firstSort: string
381 if (field.toLowerCase() === 'match') { // Search
382 firstSort = '"similarity"'
383 } else if (field === 'originallyPublishedAt') {
384 firstSort = '"publishedAtForOrder"'
385 } else if (field.includes('.')) {
388 firstSort = `"video"."${field}"`
391 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
394 function wrapForAPIResults (baseQuery: string, replacements: any, options: BuildVideosQueryOptions, order: string) {
397 '"VideoChannel"."id"': '"VideoChannel.id"',
398 '"VideoChannel"."name"': '"VideoChannel.name"',
399 '"VideoChannel"."description"': '"VideoChannel.description"',
400 '"VideoChannel"."actorId"': '"VideoChannel.actorId"',
401 '"VideoChannel->Actor"."id"': '"VideoChannel.Actor.id"',
402 '"VideoChannel->Actor"."preferredUsername"': '"VideoChannel.Actor.preferredUsername"',
403 '"VideoChannel->Actor"."url"': '"VideoChannel.Actor.url"',
404 '"VideoChannel->Actor"."serverId"': '"VideoChannel.Actor.serverId"',
405 '"VideoChannel->Actor"."avatarId"': '"VideoChannel.Actor.avatarId"',
406 '"VideoChannel->Account"."id"': '"VideoChannel.Account.id"',
407 '"VideoChannel->Account"."name"': '"VideoChannel.Account.name"',
408 '"VideoChannel->Account->Actor"."id"': '"VideoChannel.Account.Actor.id"',
409 '"VideoChannel->Account->Actor"."preferredUsername"': '"VideoChannel.Account.Actor.preferredUsername"',
410 '"VideoChannel->Account->Actor"."url"': '"VideoChannel.Account.Actor.url"',
411 '"VideoChannel->Account->Actor"."serverId"': '"VideoChannel.Account.Actor.serverId"',
412 '"VideoChannel->Account->Actor"."avatarId"': '"VideoChannel.Account.Actor.avatarId"',
413 '"VideoChannel->Actor->Server"."id"': '"VideoChannel.Actor.Server.id"',
414 '"VideoChannel->Actor->Server"."host"': '"VideoChannel.Actor.Server.host"',
415 '"VideoChannel->Actor->Avatar"."id"': '"VideoChannel.Actor.Avatar.id"',
416 '"VideoChannel->Actor->Avatar"."filename"': '"VideoChannel.Actor.Avatar.filename"',
417 '"VideoChannel->Actor->Avatar"."fileUrl"': '"VideoChannel.Actor.Avatar.fileUrl"',
418 '"VideoChannel->Actor->Avatar"."onDisk"': '"VideoChannel.Actor.Avatar.onDisk"',
419 '"VideoChannel->Actor->Avatar"."createdAt"': '"VideoChannel.Actor.Avatar.createdAt"',
420 '"VideoChannel->Actor->Avatar"."updatedAt"': '"VideoChannel.Actor.Avatar.updatedAt"',
421 '"VideoChannel->Account->Actor->Server"."id"': '"VideoChannel.Account.Actor.Server.id"',
422 '"VideoChannel->Account->Actor->Server"."host"': '"VideoChannel.Account.Actor.Server.host"',
423 '"VideoChannel->Account->Actor->Avatar"."id"': '"VideoChannel.Account.Actor.Avatar.id"',
424 '"VideoChannel->Account->Actor->Avatar"."filename"': '"VideoChannel.Account.Actor.Avatar.filename"',
425 '"VideoChannel->Account->Actor->Avatar"."fileUrl"': '"VideoChannel.Account.Actor.Avatar.fileUrl"',
426 '"VideoChannel->Account->Actor->Avatar"."onDisk"': '"VideoChannel.Account.Actor.Avatar.onDisk"',
427 '"VideoChannel->Account->Actor->Avatar"."createdAt"': '"VideoChannel.Account.Actor.Avatar.createdAt"',
428 '"VideoChannel->Account->Actor->Avatar"."updatedAt"': '"VideoChannel.Account.Actor.Avatar.updatedAt"',
429 '"Thumbnails"."id"': '"Thumbnails.id"',
430 '"Thumbnails"."type"': '"Thumbnails.type"',
431 '"Thumbnails"."filename"': '"Thumbnails.filename"'
435 'INNER JOIN "video" ON "tmp"."id" = "video"."id"',
437 'INNER JOIN "videoChannel" AS "VideoChannel" ON "video"."channelId" = "VideoChannel"."id"',
438 'INNER JOIN "actor" AS "VideoChannel->Actor" ON "VideoChannel"."actorId" = "VideoChannel->Actor"."id"',
439 'INNER JOIN "account" AS "VideoChannel->Account" ON "VideoChannel"."accountId" = "VideoChannel->Account"."id"',
440 'INNER JOIN "actor" AS "VideoChannel->Account->Actor" ON "VideoChannel->Account"."actorId" = "VideoChannel->Account->Actor"."id"',
442 'LEFT OUTER JOIN "server" AS "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id"',
443 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Actor->Avatar" ON "VideoChannel->Actor"."avatarId" = "VideoChannel->Actor->Avatar"."id"',
445 'LEFT OUTER JOIN "server" AS "VideoChannel->Account->Actor->Server" ' +
446 'ON "VideoChannel->Account->Actor"."serverId" = "VideoChannel->Account->Actor->Server"."id"',
448 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Account->Actor->Avatar" ' +
449 'ON "VideoChannel->Account->Actor"."avatarId" = "VideoChannel->Account->Actor->Avatar"."id"',
451 'LEFT OUTER JOIN "thumbnail" AS "Thumbnails" ON "video"."id" = "Thumbnails"."videoId"'
454 if (options.withFiles) {
455 joins.push('LEFT JOIN "videoFile" AS "VideoFiles" ON "VideoFiles"."videoId" = "video"."id"')
457 joins.push('LEFT JOIN "videoStreamingPlaylist" AS "VideoStreamingPlaylists" ON "VideoStreamingPlaylists"."videoId" = "video"."id"')
459 'LEFT JOIN "videoFile" AS "VideoStreamingPlaylists->VideoFiles" ' +
460 'ON "VideoStreamingPlaylists->VideoFiles"."videoStreamingPlaylistId" = "VideoStreamingPlaylists"."id"'
463 Object.assign(attributes, {
464 '"VideoFiles"."id"': '"VideoFiles.id"',
465 '"VideoFiles"."createdAt"': '"VideoFiles.createdAt"',
466 '"VideoFiles"."updatedAt"': '"VideoFiles.updatedAt"',
467 '"VideoFiles"."resolution"': '"VideoFiles.resolution"',
468 '"VideoFiles"."size"': '"VideoFiles.size"',
469 '"VideoFiles"."extname"': '"VideoFiles.extname"',
470 '"VideoFiles"."infoHash"': '"VideoFiles.infoHash"',
471 '"VideoFiles"."fps"': '"VideoFiles.fps"',
472 '"VideoFiles"."videoId"': '"VideoFiles.videoId"',
474 '"VideoStreamingPlaylists"."id"': '"VideoStreamingPlaylists.id"',
475 '"VideoStreamingPlaylists->VideoFiles"."id"': '"VideoStreamingPlaylists.VideoFiles.id"',
476 '"VideoStreamingPlaylists->VideoFiles"."createdAt"': '"VideoStreamingPlaylists.VideoFiles.createdAt"',
477 '"VideoStreamingPlaylists->VideoFiles"."updatedAt"': '"VideoStreamingPlaylists.VideoFiles.updatedAt"',
478 '"VideoStreamingPlaylists->VideoFiles"."resolution"': '"VideoStreamingPlaylists.VideoFiles.resolution"',
479 '"VideoStreamingPlaylists->VideoFiles"."size"': '"VideoStreamingPlaylists.VideoFiles.size"',
480 '"VideoStreamingPlaylists->VideoFiles"."extname"': '"VideoStreamingPlaylists.VideoFiles.extname"',
481 '"VideoStreamingPlaylists->VideoFiles"."infoHash"': '"VideoStreamingPlaylists.VideoFiles.infoHash"',
482 '"VideoStreamingPlaylists->VideoFiles"."fps"': '"VideoStreamingPlaylists.VideoFiles.fps"',
483 '"VideoStreamingPlaylists->VideoFiles"."videoId"': '"VideoStreamingPlaylists.VideoFiles.videoId"'
489 'LEFT OUTER JOIN "userVideoHistory" ' +
490 'ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :userVideoHistoryId'
492 replacements.userVideoHistoryId = options.user.id
494 Object.assign(attributes, {
495 '"userVideoHistory"."id"': '"userVideoHistory.id"',
496 '"userVideoHistory"."currentTime"': '"userVideoHistory.currentTime"'
500 if (options.videoPlaylistId) {
502 'INNER JOIN "videoPlaylistElement" as "VideoPlaylistElement" ON "videoPlaylistElement"."videoId" = "video"."id" ' +
503 'AND "VideoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
505 replacements.videoPlaylistId = options.videoPlaylistId
507 Object.assign(attributes, {
508 '"VideoPlaylistElement"."createdAt"': '"VideoPlaylistElement.createdAt"',
509 '"VideoPlaylistElement"."updatedAt"': '"VideoPlaylistElement.updatedAt"',
510 '"VideoPlaylistElement"."url"': '"VideoPlaylistElement.url"',
511 '"VideoPlaylistElement"."position"': '"VideoPlaylistElement.position"',
512 '"VideoPlaylistElement"."startTimestamp"': '"VideoPlaylistElement.startTimestamp"',
513 '"VideoPlaylistElement"."stopTimestamp"': '"VideoPlaylistElement.stopTimestamp"',
514 '"VideoPlaylistElement"."videoPlaylistId"': '"VideoPlaylistElement.videoPlaylistId"'
518 const select = 'SELECT ' + Object.keys(attributes).map(key => {
519 const value = attributes[key]
520 if (value) return `${key} AS ${value}`
525 return `${select} FROM (${baseQuery}) AS "tmp" ${joins.join(' ')} ${order}`