1 import { Sequelize } from 'sequelize'
2 import validator from 'validator'
3 import { exists } from '@server/helpers/custom-validators/misc'
4 import { WEBSERVER } from '@server/initializers/constants'
5 import { buildDirectionAndField, createSafeIn } from '@server/models/utils'
6 import { MUserAccountId, MUserId } from '@server/types/models'
7 import { VideoFilter, VideoPrivacy, VideoState } from '@shared/models'
8 import { AbstractVideosQueryBuilder } from './shared/abstract-videos-query-builder'
12 * Build videos list SQL query to fetch rows
16 export type BuildVideosListQueryOptions = {
19 serverAccountId: number
20 followerActorId: number
21 includeLocalVideos: boolean
32 categoryOneOf?: number[]
33 licenceOneOf?: number[]
34 languageOneOf?: string[]
43 videoChannelId?: number
45 videoPlaylistId?: number
47 trendingAlgorithm?: string // best, hot, or any other algorithm implemented
51 historyOfUser?: MUserId
53 startDate?: string // ISO 8601
54 endDate?: string // ISO 8601
55 originallyPublishedStartDate?: string
56 originallyPublishedEndDate?: string
58 durationMin?: number // seconds
59 durationMax?: number // seconds
69 export class VideosIdListQueryBuilder extends AbstractVideosQueryBuilder {
70 protected replacements: any = {}
72 private attributes: string[]
73 private joins: string[] = []
75 private readonly and: string[] = []
77 private readonly cte: string[] = []
86 constructor (protected readonly sequelize: Sequelize) {
90 queryVideoIds (options: BuildVideosListQueryOptions) {
91 this.buildIdsListQuery(options)
93 return this.runQuery()
96 countVideoIds (countOptions: BuildVideosListQueryOptions): Promise<number> {
97 this.buildIdsListQuery(countOptions)
99 return this.runQuery().then(rows => rows.length !== 0 ? rows[0].total : 0)
102 getIdsListQueryAndSort (options: BuildVideosListQueryOptions) {
103 this.buildIdsListQuery(options)
104 return { query: this.query, sort: this.sort, replacements: this.replacements }
107 private buildIdsListQuery (options: BuildVideosListQueryOptions) {
108 this.attributes = options.attributes || [ '"video"."id"' ]
110 if (options.group) this.group = options.group
111 if (options.having) this.having = options.having
113 this.joins = this.joins.concat([
114 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId"',
115 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId"',
116 'INNER JOIN "actor" "accountActor" ON "account"."actorId" = "accountActor"."id"'
119 this.whereNotBlacklisted()
121 if (options.serverAccountId) {
122 this.whereNotBlocked(options.serverAccountId, options.user)
125 // Only list public/published videos
126 if (!options.filter || (options.filter !== 'all-local' && options.filter !== 'all')) {
127 this.whereStateAndPrivacyAvailable(options.user)
130 if (options.videoPlaylistId) {
131 this.joinPlaylist(options.videoPlaylistId)
134 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
135 this.whereOnlyLocal()
139 this.whereHost(options.host)
142 if (options.accountId) {
143 this.whereAccountId(options.accountId)
146 if (options.videoChannelId) {
147 this.whereChannelId(options.videoChannelId)
150 if (options.followerActorId) {
151 this.whereFollowerActorId(options.followerActorId, options.includeLocalVideos)
154 if (options.withFiles === true) {
155 this.whereFileExists()
158 if (options.tagsOneOf) {
159 this.whereTagsOneOf(options.tagsOneOf)
162 if (options.tagsAllOf) {
163 this.whereTagsAllOf(options.tagsAllOf)
167 this.whereUUIDs(options.uuids)
170 if (options.nsfw === true) {
172 } else if (options.nsfw === false) {
176 if (options.isLive === true) {
178 } else if (options.isLive === false) {
182 if (options.categoryOneOf) {
183 this.whereCategoryOneOf(options.categoryOneOf)
186 if (options.licenceOneOf) {
187 this.whereLicenceOneOf(options.licenceOneOf)
190 if (options.languageOneOf) {
191 this.whereLanguageOneOf(options.languageOneOf)
194 // We don't exclude results in this so if we do a count we don't need to add this complex clause
195 if (options.isCount !== true) {
196 if (options.trendingDays) {
197 this.groupForTrending(options.trendingDays)
198 } else if ([ 'best', 'hot' ].includes(options.trendingAlgorithm)) {
199 this.groupForHotOrBest(options.trendingAlgorithm, options.user)
203 if (options.historyOfUser) {
204 this.joinHistory(options.historyOfUser.id)
207 if (options.startDate) {
208 this.whereStartDate(options.startDate)
211 if (options.endDate) {
212 this.whereEndDate(options.endDate)
215 if (options.originallyPublishedStartDate) {
216 this.whereOriginallyPublishedStartDate(options.originallyPublishedStartDate)
219 if (options.originallyPublishedEndDate) {
220 this.whereOriginallyPublishedEndDate(options.originallyPublishedEndDate)
223 if (options.durationMin) {
224 this.whereDurationMin(options.durationMin)
227 if (options.durationMax) {
228 this.whereDurationMax(options.durationMax)
231 this.whereSearch(options.search)
233 if (options.isCount === true) {
234 this.setCountAttribute()
236 if (exists(options.sort)) {
237 this.setSort(options.sort)
240 if (exists(options.count)) {
241 this.setLimit(options.count)
244 if (exists(options.start)) {
245 this.setOffset(options.start)
249 const cteString = this.cte.length !== 0
250 ? `WITH ${this.cte.join(', ')} `
253 this.query = cteString +
254 'SELECT ' + this.attributes.join(', ') + ' ' +
255 'FROM "video" ' + this.joins.join(' ') + ' ' +
256 'WHERE ' + this.and.join(' AND ') + ' ' +
264 private setCountAttribute () {
265 this.attributes = [ 'COUNT(*) as "total"' ]
268 private joinHistory (userId: number) {
269 this.joins.push('INNER JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId"')
271 this.and.push('"userVideoHistory"."userId" = :historyOfUser')
273 this.replacements.historyOfUser = userId
276 private joinPlaylist (playlistId: number) {
278 'INNER JOIN "videoPlaylistElement" "video"."id" = "videoPlaylistElement"."videoId" ' +
279 'AND "videoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
282 this.replacements.videoPlaylistId = playlistId
285 private whereStateAndPrivacyAvailable (user?: MUserAccountId) {
287 `("video"."state" = ${VideoState.PUBLISHED} OR ` +
288 `("video"."state" = ${VideoState.TO_TRANSCODE} AND "video"."waitTranscoding" IS false))`
293 `("video"."privacy" = ${VideoPrivacy.PUBLIC} OR "video"."privacy" = ${VideoPrivacy.INTERNAL})`
295 } else { // Or only public videos
297 `"video"."privacy" = ${VideoPrivacy.PUBLIC}`
302 private whereOnlyLocal () {
303 this.and.push('"video"."remote" IS FALSE')
306 private whereHost (host: string) {
308 if (host === WEBSERVER.HOST) {
309 this.and.push('"accountActor"."serverId" IS NULL')
313 this.joins.push('INNER JOIN "server" ON "server"."id" = "accountActor"."serverId"')
315 this.and.push('"server"."host" = :host')
316 this.replacements.host = host
319 private whereAccountId (accountId: number) {
320 this.and.push('"account"."id" = :accountId')
321 this.replacements.accountId = accountId
324 private whereChannelId (channelId: number) {
325 this.and.push('"videoChannel"."id" = :videoChannelId')
326 this.replacements.videoChannelId = channelId
329 private whereFollowerActorId (followerActorId: number, includeLocalVideos: boolean) {
332 ' EXISTS (' + // Videos shared by actors we follow
333 ' SELECT 1 FROM "videoShare" ' +
334 ' INNER JOIN "actorFollow" "actorFollowShare" ON "actorFollowShare"."targetActorId" = "videoShare"."actorId" ' +
335 ' AND "actorFollowShare"."actorId" = :followerActorId AND "actorFollowShare"."state" = \'accepted\' ' +
336 ' WHERE "videoShare"."videoId" = "video"."id"' +
339 ' EXISTS (' + // Videos published by accounts we follow
340 ' SELECT 1 from "actorFollow" ' +
341 ' WHERE "actorFollow"."targetActorId" = "account"."actorId" AND "actorFollow"."actorId" = :followerActorId ' +
342 ' AND "actorFollow"."state" = \'accepted\'' +
345 if (includeLocalVideos) {
346 query += ' OR "video"."remote" IS FALSE'
352 this.replacements.followerActorId = followerActorId
355 private whereFileExists () {
358 ' EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id") ' +
360 ' SELECT 1 FROM "videoStreamingPlaylist" ' +
361 ' INNER JOIN "videoFile" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ' +
362 ' WHERE "videoStreamingPlaylist"."videoId" = "video"."id"' +
368 private whereTagsOneOf (tagsOneOf: string[]) {
369 const tagsOneOfLower = tagsOneOf.map(t => t.toLowerCase())
373 ' SELECT 1 FROM "videoTag" ' +
374 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
375 ' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsOneOfLower) + ') ' +
376 ' AND "video"."id" = "videoTag"."videoId"' +
381 private whereTagsAllOf (tagsAllOf: string[]) {
382 const tagsAllOfLower = tagsAllOf.map(t => t.toLowerCase())
386 ' SELECT 1 FROM "videoTag" ' +
387 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
388 ' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsAllOfLower) + ') ' +
389 ' AND "video"."id" = "videoTag"."videoId" ' +
390 ' GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
395 private whereUUIDs (uuids: string[]) {
396 this.and.push('"video"."uuid" IN (' + createSafeIn(this.sequelize, uuids) + ')')
399 private whereCategoryOneOf (categoryOneOf: number[]) {
400 this.and.push('"video"."category" IN (:categoryOneOf)')
401 this.replacements.categoryOneOf = categoryOneOf
404 private whereLicenceOneOf (licenceOneOf: number[]) {
405 this.and.push('"video"."licence" IN (:licenceOneOf)')
406 this.replacements.licenceOneOf = licenceOneOf
409 private whereLanguageOneOf (languageOneOf: string[]) {
410 const languages = languageOneOf.filter(l => l && l !== '_unknown')
411 const languagesQueryParts: string[] = []
413 if (languages.length !== 0) {
414 languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
415 this.replacements.languageOneOf = languages
417 languagesQueryParts.push(
419 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
420 ' IN (' + createSafeIn(this.sequelize, languages) + ') AND ' +
421 ' "videoCaption"."videoId" = "video"."id"' +
426 if (languageOneOf.includes('_unknown')) {
427 languagesQueryParts.push('"video"."language" IS NULL')
430 if (languagesQueryParts.length !== 0) {
431 this.and.push('(' + languagesQueryParts.join(' OR ') + ')')
435 private whereNSFW () {
436 this.and.push('"video"."nsfw" IS TRUE')
439 private whereSFW () {
440 this.and.push('"video"."nsfw" IS FALSE')
443 private whereLive () {
444 this.and.push('"video"."isLive" IS TRUE')
447 private whereVOD () {
448 this.and.push('"video"."isLive" IS FALSE')
451 private whereNotBlocked (serverAccountId: number, user?: MUserAccountId) {
452 const blockerIds = [ serverAccountId ]
453 if (user) blockerIds.push(user.Account.id)
455 const inClause = createSafeIn(this.sequelize, blockerIds)
459 ' SELECT 1 FROM "accountBlocklist" ' +
460 ' WHERE "accountBlocklist"."accountId" IN (' + inClause + ') ' +
461 ' AND "accountBlocklist"."targetAccountId" = "account"."id" ' +
464 ' SELECT 1 FROM "serverBlocklist" WHERE "serverBlocklist"."accountId" IN (' + inClause + ') ' +
465 ' AND "serverBlocklist"."targetServerId" = "accountActor"."serverId"' +
470 private whereSearch (search?: string) {
472 this.attributes.push('0 as similarity')
476 const escapedSearch = this.sequelize.escape(search)
477 const escapedLikeSearch = this.sequelize.escape('%' + search + '%')
480 '"trigramSearch" AS (' +
481 ' SELECT "video"."id", ' +
482 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
484 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
485 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
489 this.joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
492 ' "trigramSearch"."id" IS NOT NULL OR ' +
494 ' SELECT 1 FROM "videoTag" ' +
495 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
496 ` WHERE lower("tag"."name") = ${escapedSearch} ` +
497 ' AND "video"."id" = "videoTag"."videoId"' +
500 if (validator.isUUID(search)) {
501 base += ` OR "video"."uuid" = ${escapedSearch}`
507 this.attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
510 private whereNotBlacklisted () {
511 this.and.push('"video"."id" NOT IN (SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")')
514 private whereStartDate (startDate: string) {
515 this.and.push('"video"."publishedAt" >= :startDate')
516 this.replacements.startDate = startDate
519 private whereEndDate (endDate: string) {
520 this.and.push('"video"."publishedAt" <= :endDate')
521 this.replacements.endDate = endDate
524 private whereOriginallyPublishedStartDate (startDate: string) {
525 this.and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
526 this.replacements.originallyPublishedStartDate = startDate
529 private whereOriginallyPublishedEndDate (endDate: string) {
530 this.and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
531 this.replacements.originallyPublishedEndDate = endDate
534 private whereDurationMin (durationMin: number) {
535 this.and.push('"video"."duration" >= :durationMin')
536 this.replacements.durationMin = durationMin
539 private whereDurationMax (durationMax: number) {
540 this.and.push('"video"."duration" <= :durationMax')
541 this.replacements.durationMax = durationMax
544 private groupForTrending (trendingDays: number) {
545 const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
547 this.joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
548 this.replacements.viewsGteDate = viewsGteDate
550 this.attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "score"')
552 this.group = 'GROUP BY "video"."id"'
555 private groupForHotOrBest (trendingAlgorithm: string, user?: MUserAccountId) {
557 * "Hotness" is a measure based on absolute view/comment/like/dislike numbers,
558 * with fixed weights only applied to their log values.
560 * This algorithm gives little chance for an old video to have a good score,
561 * for which recent spikes in interactions could be a sign of "hotness" and
562 * justify a better score. However there are multiple ways to achieve that
563 * goal, which is left for later. Yes, this is a TODO :)
566 * - weights and base score are in number of half-days.
567 * - all comments are counted, regardless of being written by the video author or not
568 * see https://github.com/reddit-archive/reddit/blob/master/r2/r2/lib/db/_sorts.pyx#L47-L58
569 * - we have less interactions than on reddit, so multiply weights by an arbitrary factor
574 view: Math.floor((1 / 3) * 50),
575 comment: 2 * 50, // a comment takes more time than a like to do, but can be done multiple times
579 this.joins.push('LEFT JOIN "videoComment" ON "video"."id" = "videoComment"."videoId"')
582 `LOG(GREATEST(1, "video"."likes" - 1)) * ${weights.like} ` + // likes (+)
583 `+ LOG(GREATEST(1, "video"."dislikes" - 1)) * ${weights.dislike} ` + // dislikes (-)
584 `+ LOG("video"."views" + 1) * ${weights.view} ` + // views (+)
585 `+ LOG(GREATEST(1, COUNT(DISTINCT "videoComment"."id"))) * ${weights.comment} ` + // comments (+)
586 '+ (SELECT (EXTRACT(epoch FROM "video"."publishedAt") - 1446156582) / 47000) ' // base score (in number of half-days)
588 if (trendingAlgorithm === 'best' && user) {
590 'LEFT JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :bestUser'
592 this.replacements.bestUser = user.id
594 attribute += `+ POWER(COUNT(DISTINCT "userVideoHistory"."id"), 2.0) * ${weights.history} `
597 attribute += 'AS "score"'
598 this.attributes.push(attribute)
600 this.group = 'GROUP BY "video"."id"'
603 private setSort (sort: string) {
604 if (sort === '-originallyPublishedAt' || sort === 'originallyPublishedAt') {
605 this.attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
608 this.sort = this.buildOrder(sort)
611 private buildOrder (value: string) {
612 const { direction, field } = buildDirectionAndField(value)
613 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
615 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
617 if ([ 'trending', 'hot', 'best' ].includes(field.toLowerCase())) { // Sort by aggregation
618 return `ORDER BY "score" ${direction}, "video"."views" ${direction}`
621 let firstSort: string
623 if (field.toLowerCase() === 'match') { // Search
624 firstSort = '"similarity"'
625 } else if (field === 'originallyPublishedAt') {
626 firstSort = '"publishedAtForOrder"'
627 } else if (field.includes('.')) {
630 firstSort = `"video"."${field}"`
633 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
636 private setLimit (countArg: number) {
637 const count = parseInt(countArg + '', 10)
638 this.limit = `LIMIT ${count}`
641 private setOffset (startArg: number) {
642 const start = parseInt(startArg + '', 10)
643 this.offset = `OFFSET ${start}`