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'
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 WHERE "videoShare"."videoId" = "video"."id"' +
142 ' SELECT 1 from "actorFollow" ' +
143 ' WHERE "actorFollow"."targetActorId" = "videoChannel"."actorId" AND "actorFollow"."actorId" = :followerActorId' +
146 if (options.includeLocalVideos) {
147 query += ' OR "video"."remote" IS FALSE'
153 replacements.followerActorId = options.followerActorId
156 if (options.withFiles === true) {
157 and.push('EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id")')
160 if (options.tagsOneOf) {
161 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
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"' +
173 if (options.tagsAllOf) {
174 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
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 +
187 if (options.nsfw === true) {
188 and.push('"video"."nsfw" IS TRUE')
191 if (options.nsfw === false) {
192 and.push('"video"."nsfw" IS FALSE')
195 if (options.categoryOneOf) {
196 and.push('"video"."category" IN (:categoryOneOf)')
197 replacements.categoryOneOf = options.categoryOneOf
200 if (options.licenceOneOf) {
201 and.push('"video"."licence" IN (:licenceOneOf)')
202 replacements.licenceOneOf = options.licenceOneOf
205 if (options.languageOneOf) {
206 const languages = options.languageOneOf.filter(l => l && l !== '_unknown')
207 const languagesQueryParts: string[] = []
209 if (languages.length !== 0) {
210 languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
211 replacements.languageOneOf = languages
213 languagesQueryParts.push(
215 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
216 ' IN (' + createSafeIn(model, languages) + ') AND ' +
217 ' "videoCaption"."videoId" = "video"."id"' +
222 if (options.languageOneOf.includes('_unknown')) {
223 languagesQueryParts.push('"video"."language" IS NULL')
226 if (languagesQueryParts.length !== 0) {
227 and.push('(' + languagesQueryParts.join(' OR ') + ')')
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)
235 joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
236 replacements.viewsGteDate = viewsGteDate
238 attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "videoViewsSum"')
240 group = 'GROUP BY "video"."id"'
243 if (options.historyOfUser) {
244 joins.push('INNER JOIN "userVideoHistory" on "video"."id" = "userVideoHistory"."videoId"')
246 and.push('"userVideoHistory"."userId" = :historyOfUser')
247 replacements.historyOfUser = options.historyOfUser.id
250 if (options.startDate) {
251 and.push('"video"."publishedAt" >= :startDate')
252 replacements.startDate = options.startDate
255 if (options.endDate) {
256 and.push('"video"."publishedAt" <= :endDate')
257 replacements.endDate = options.endDate
260 if (options.originallyPublishedStartDate) {
261 and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
262 replacements.originallyPublishedStartDate = options.originallyPublishedStartDate
265 if (options.originallyPublishedEndDate) {
266 and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
267 replacements.originallyPublishedEndDate = options.originallyPublishedEndDate
270 if (options.durationMin) {
271 and.push('"video"."duration" >= :durationMin')
272 replacements.durationMin = options.durationMin
275 if (options.durationMax) {
276 and.push('"video"."duration" <= :durationMax')
277 replacements.durationMax = options.durationMax
280 if (options.search) {
281 const escapedSearch = model.sequelize.escape(options.search)
282 const escapedLikeSearch = model.sequelize.escape('%' + options.search + '%')
285 '"trigramSearch" AS (' +
286 ' SELECT "video"."id", ' +
287 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
289 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
290 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
294 joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
297 ' "trigramSearch"."id" IS NOT NULL OR ' +
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"' +
305 if (validator.isUUID(options.search)) {
306 base += ` OR "video"."uuid" = ${escapedSearch}`
312 attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
314 attributes.push('0 as similarity')
317 if (options.isCount === true) attributes = [ 'COUNT(*) as "total"' ]
321 if (options.isCount !== true) {
323 if (exists(options.sort)) {
324 if (options.sort === '-originallyPublishedAt' || options.sort === 'originallyPublishedAt') {
325 attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
328 order = buildOrder(model, options.sort)
329 suffix += `${order} `
332 if (exists(options.count)) {
333 const count = parseInt(options.count + '', 10)
334 suffix += `LIMIT ${count} `
337 if (exists(options.start)) {
338 const start = parseInt(options.start + '', 10)
339 suffix += `OFFSET ${start} `
343 const cteString = cte.length !== 0
344 ? `WITH ${cte.join(', ')} `
347 const query = cteString +
348 'SELECT ' + attributes.join(', ') + ' ' +
349 'FROM "video" ' + joins.join(' ') + ' ' +
350 'WHERE ' + and.join(' AND ') + ' ' +
355 return { query, replacements, order }
358 function buildOrder (model: typeof Model, value: string) {
359 const { direction, field } = buildDirectionAndField(value)
360 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
362 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
364 if (field.toLowerCase() === 'trending') { // Sort by aggregation
365 return `ORDER BY "videoViewsSum" ${direction}, "video"."views" ${direction}`
368 let firstSort: string
370 if (field.toLowerCase() === 'match') { // Search
371 firstSort = '"similarity"'
372 } else if (field === 'originallyPublishedAt') {
373 firstSort = '"publishedAtForOrder"'
374 } else if (field.includes('.')) {
377 firstSort = `"video"."${field}"`
380 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
383 function wrapForAPIResults (baseQuery: string, replacements: any, options: BuildVideosQueryOptions, order: string) {
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"'
424 'INNER JOIN "video" ON "tmp"."id" = "video"."id"',
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"',
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"',
434 'LEFT OUTER JOIN "server" AS "VideoChannel->Account->Actor->Server" ' +
435 'ON "VideoChannel->Account->Actor"."serverId" = "VideoChannel->Account->Actor->Server"."id"',
437 'LEFT OUTER JOIN "avatar" AS "VideoChannel->Account->Actor->Avatar" ' +
438 'ON "VideoChannel->Account->Actor"."avatarId" = "VideoChannel->Account->Actor->Avatar"."id"',
440 'LEFT OUTER JOIN "thumbnail" AS "Thumbnails" ON "video"."id" = "Thumbnails"."videoId"'
443 if (options.withFiles) {
444 joins.push('INNER JOIN "videoFile" AS "VideoFiles" ON "VideoFiles"."videoId" = "video"."id"')
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"'
461 'LEFT OUTER JOIN "userVideoHistory" ' +
462 'ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :userVideoHistoryId'
464 replacements.userVideoHistoryId = options.user.id
466 Object.assign(attributes, {
467 '"userVideoHistory"."id"': '"userVideoHistory.id"',
468 '"userVideoHistory"."currentTime"': '"userVideoHistory.currentTime"'
472 if (options.videoPlaylistId) {
474 'INNER JOIN "videoPlaylistElement" as "VideoPlaylistElement" ON "videoPlaylistElement"."videoId" = "video"."id" ' +
475 'AND "VideoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
477 replacements.videoPlaylistId = options.videoPlaylistId
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"'
490 const select = 'SELECT ' + Object.keys(attributes).map(key => {
491 const value = attributes[key]
492 if (value) return `${key} AS ${value}`
497 return `${select} FROM (${baseQuery}) AS "tmp" ${joins.join(' ')} ${order}`