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 { VideoInclude, VideoPrivacy, VideoState } from '@shared/models'
8 import { AbstractRunQuery } from './shared/abstract-run-query'
12 * Build videos list SQL query to fetch rows
16 export type DisplayOnlyForFollowerOptions = {
18 orLocalVideos: boolean
21 export type BuildVideosListQueryOptions = {
24 serverAccountIdForBlock: number
26 displayOnlyForFollower: DisplayOnlyForFollowerOptions
36 include?: VideoInclude
38 categoryOneOf?: number[]
39 licenceOneOf?: number[]
40 languageOneOf?: string[]
48 hasWebtorrentFiles?: boolean
51 videoChannelId?: number
53 videoPlaylistId?: number
55 trendingAlgorithm?: string // best, hot, or any other algorithm implemented
59 historyOfUser?: MUserId
61 startDate?: string // ISO 8601
62 endDate?: string // ISO 8601
63 originallyPublishedStartDate?: string
64 originallyPublishedEndDate?: string
66 durationMin?: number // seconds
67 durationMax?: number // seconds
77 export class VideosIdListQueryBuilder extends AbstractRunQuery {
78 protected replacements: any = {}
80 private attributes: string[]
81 private joins: string[] = []
83 private readonly and: string[] = []
85 private readonly cte: string[] = []
94 constructor (protected readonly sequelize: Sequelize) {
98 queryVideoIds (options: BuildVideosListQueryOptions) {
99 this.buildIdsListQuery(options)
101 return this.runQuery()
104 countVideoIds (countOptions: BuildVideosListQueryOptions): Promise<number> {
105 this.buildIdsListQuery(countOptions)
107 return this.runQuery().then(rows => rows.length !== 0 ? rows[0].total : 0)
110 getQuery (options: BuildVideosListQueryOptions) {
111 this.buildIdsListQuery(options)
113 return { query: this.query, sort: this.sort, replacements: this.replacements }
116 private buildIdsListQuery (options: BuildVideosListQueryOptions) {
117 this.attributes = options.attributes || [ '"video"."id"' ]
119 if (options.group) this.group = options.group
120 if (options.having) this.having = options.having
122 this.joins = this.joins.concat([
123 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId"',
124 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId"',
125 'INNER JOIN "actor" "accountActor" ON "account"."actorId" = "accountActor"."id"'
128 if (!(options.include & VideoInclude.BLACKLISTED)) {
129 this.whereNotBlacklisted()
132 if (options.serverAccountIdForBlock && !(options.include & VideoInclude.BLOCKED_OWNER)) {
133 this.whereNotBlocked(options.serverAccountIdForBlock, options.user)
136 // Only list published videos
137 if (!(options.include & VideoInclude.NOT_PUBLISHED_STATE)) {
138 this.whereStateAvailable()
141 // Only list videos with the appropriate priavcy
142 if (!(options.include & VideoInclude.HIDDEN_PRIVACY)) {
143 this.wherePrivacyAvailable(options.user)
146 if (options.videoPlaylistId) {
147 this.joinPlaylist(options.videoPlaylistId)
150 if (exists(options.isLocal)) {
151 this.whereLocal(options.isLocal)
155 this.whereHost(options.host)
158 if (options.accountId) {
159 this.whereAccountId(options.accountId)
162 if (options.videoChannelId) {
163 this.whereChannelId(options.videoChannelId)
166 if (options.displayOnlyForFollower) {
167 this.whereFollowerActorId(options.displayOnlyForFollower)
170 if (options.hasFiles === true) {
171 this.whereFileExists()
174 if (exists(options.hasWebtorrentFiles)) {
175 this.whereWebTorrentFileExists(options.hasWebtorrentFiles)
178 if (exists(options.hasHLSFiles)) {
179 this.whereHLSFileExists(options.hasHLSFiles)
182 if (options.tagsOneOf) {
183 this.whereTagsOneOf(options.tagsOneOf)
186 if (options.tagsAllOf) {
187 this.whereTagsAllOf(options.tagsAllOf)
191 this.whereUUIDs(options.uuids)
194 if (options.nsfw === true) {
196 } else if (options.nsfw === false) {
200 if (options.isLive === true) {
202 } else if (options.isLive === false) {
206 if (options.categoryOneOf) {
207 this.whereCategoryOneOf(options.categoryOneOf)
210 if (options.licenceOneOf) {
211 this.whereLicenceOneOf(options.licenceOneOf)
214 if (options.languageOneOf) {
215 this.whereLanguageOneOf(options.languageOneOf)
218 // We don't exclude results in this so if we do a count we don't need to add this complex clause
219 if (options.isCount !== true) {
220 if (options.trendingDays) {
221 this.groupForTrending(options.trendingDays)
222 } else if ([ 'best', 'hot' ].includes(options.trendingAlgorithm)) {
223 this.groupForHotOrBest(options.trendingAlgorithm, options.user)
227 if (options.historyOfUser) {
228 this.joinHistory(options.historyOfUser.id)
231 if (options.startDate) {
232 this.whereStartDate(options.startDate)
235 if (options.endDate) {
236 this.whereEndDate(options.endDate)
239 if (options.originallyPublishedStartDate) {
240 this.whereOriginallyPublishedStartDate(options.originallyPublishedStartDate)
243 if (options.originallyPublishedEndDate) {
244 this.whereOriginallyPublishedEndDate(options.originallyPublishedEndDate)
247 if (options.durationMin) {
248 this.whereDurationMin(options.durationMin)
251 if (options.durationMax) {
252 this.whereDurationMax(options.durationMax)
255 this.whereSearch(options.search)
257 if (options.isCount === true) {
258 this.setCountAttribute()
260 if (exists(options.sort)) {
261 this.setSort(options.sort)
264 if (exists(options.count)) {
265 this.setLimit(options.count)
268 if (exists(options.start)) {
269 this.setOffset(options.start)
273 const cteString = this.cte.length !== 0
274 ? `WITH ${this.cte.join(', ')} `
277 this.query = cteString +
278 'SELECT ' + this.attributes.join(', ') + ' ' +
279 'FROM "video" ' + this.joins.join(' ') + ' ' +
280 'WHERE ' + this.and.join(' AND ') + ' ' +
288 private setCountAttribute () {
289 this.attributes = [ 'COUNT(*) as "total"' ]
292 private joinHistory (userId: number) {
293 this.joins.push('INNER JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId"')
295 this.and.push('"userVideoHistory"."userId" = :historyOfUser')
297 this.replacements.historyOfUser = userId
300 private joinPlaylist (playlistId: number) {
302 'INNER JOIN "videoPlaylistElement" "video"."id" = "videoPlaylistElement"."videoId" ' +
303 'AND "videoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
306 this.replacements.videoPlaylistId = playlistId
309 private whereStateAvailable () {
311 `("video"."state" = ${VideoState.PUBLISHED} OR ` +
312 `("video"."state" = ${VideoState.TO_TRANSCODE} AND "video"."waitTranscoding" IS false))`
316 private wherePrivacyAvailable (user?: MUserAccountId) {
319 `("video"."privacy" = ${VideoPrivacy.PUBLIC} OR "video"."privacy" = ${VideoPrivacy.INTERNAL})`
321 } else { // Or only public videos
323 `"video"."privacy" = ${VideoPrivacy.PUBLIC}`
328 private whereLocal (isLocal: boolean) {
329 const isRemote = isLocal ? 'FALSE' : 'TRUE'
331 this.and.push('"video"."remote" IS ' + isRemote)
334 private whereHost (host: string) {
336 if (host === WEBSERVER.HOST) {
337 this.and.push('"accountActor"."serverId" IS NULL')
341 this.joins.push('INNER JOIN "server" ON "server"."id" = "accountActor"."serverId"')
343 this.and.push('"server"."host" = :host')
344 this.replacements.host = host
347 private whereAccountId (accountId: number) {
348 this.and.push('"account"."id" = :accountId')
349 this.replacements.accountId = accountId
352 private whereChannelId (channelId: number) {
353 this.and.push('"videoChannel"."id" = :videoChannelId')
354 this.replacements.videoChannelId = channelId
357 private whereFollowerActorId (options: { actorId: number, orLocalVideos: boolean }) {
360 ' EXISTS (' + // Videos shared by actors we follow
361 ' SELECT 1 FROM "videoShare" ' +
362 ' INNER JOIN "actorFollow" "actorFollowShare" ON "actorFollowShare"."targetActorId" = "videoShare"."actorId" ' +
363 ' AND "actorFollowShare"."actorId" = :followerActorId AND "actorFollowShare"."state" = \'accepted\' ' +
364 ' WHERE "videoShare"."videoId" = "video"."id"' +
367 ' EXISTS (' + // Videos published by accounts we follow
368 ' SELECT 1 from "actorFollow" ' +
369 ' WHERE "actorFollow"."targetActorId" = "account"."actorId" AND "actorFollow"."actorId" = :followerActorId ' +
370 ' AND "actorFollow"."state" = \'accepted\'' +
373 if (options.orLocalVideos) {
374 query += ' OR "video"."remote" IS FALSE'
380 this.replacements.followerActorId = options.actorId
383 private whereFileExists () {
384 this.and.push(`(${this.buildWebTorrentFileExistsQuery(true)} OR ${this.buildHLSFileExistsQuery(true)})`)
387 private whereWebTorrentFileExists (exists: boolean) {
388 this.and.push(this.buildWebTorrentFileExistsQuery(exists))
391 private whereHLSFileExists (exists: boolean) {
392 this.and.push(this.buildHLSFileExistsQuery(exists))
395 private buildWebTorrentFileExistsQuery (exists: boolean) {
396 const prefix = exists ? '' : 'NOT '
398 return prefix + 'EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id")'
401 private buildHLSFileExistsQuery (exists: boolean) {
402 const prefix = exists ? '' : 'NOT '
404 return prefix + 'EXISTS (' +
405 ' SELECT 1 FROM "videoStreamingPlaylist" ' +
406 ' INNER JOIN "videoFile" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ' +
407 ' WHERE "videoStreamingPlaylist"."videoId" = "video"."id"' +
411 private whereTagsOneOf (tagsOneOf: string[]) {
412 const tagsOneOfLower = tagsOneOf.map(t => t.toLowerCase())
416 ' SELECT 1 FROM "videoTag" ' +
417 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
418 ' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsOneOfLower) + ') ' +
419 ' AND "video"."id" = "videoTag"."videoId"' +
424 private whereTagsAllOf (tagsAllOf: string[]) {
425 const tagsAllOfLower = tagsAllOf.map(t => t.toLowerCase())
429 ' SELECT 1 FROM "videoTag" ' +
430 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
431 ' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsAllOfLower) + ') ' +
432 ' AND "video"."id" = "videoTag"."videoId" ' +
433 ' GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
438 private whereUUIDs (uuids: string[]) {
439 this.and.push('"video"."uuid" IN (' + createSafeIn(this.sequelize, uuids) + ')')
442 private whereCategoryOneOf (categoryOneOf: number[]) {
443 this.and.push('"video"."category" IN (:categoryOneOf)')
444 this.replacements.categoryOneOf = categoryOneOf
447 private whereLicenceOneOf (licenceOneOf: number[]) {
448 this.and.push('"video"."licence" IN (:licenceOneOf)')
449 this.replacements.licenceOneOf = licenceOneOf
452 private whereLanguageOneOf (languageOneOf: string[]) {
453 const languages = languageOneOf.filter(l => l && l !== '_unknown')
454 const languagesQueryParts: string[] = []
456 if (languages.length !== 0) {
457 languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
458 this.replacements.languageOneOf = languages
460 languagesQueryParts.push(
462 ' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
463 ' IN (' + createSafeIn(this.sequelize, languages) + ') AND ' +
464 ' "videoCaption"."videoId" = "video"."id"' +
469 if (languageOneOf.includes('_unknown')) {
470 languagesQueryParts.push('"video"."language" IS NULL')
473 if (languagesQueryParts.length !== 0) {
474 this.and.push('(' + languagesQueryParts.join(' OR ') + ')')
478 private whereNSFW () {
479 this.and.push('"video"."nsfw" IS TRUE')
482 private whereSFW () {
483 this.and.push('"video"."nsfw" IS FALSE')
486 private whereLive () {
487 this.and.push('"video"."isLive" IS TRUE')
490 private whereVOD () {
491 this.and.push('"video"."isLive" IS FALSE')
494 private whereNotBlocked (serverAccountId: number, user?: MUserAccountId) {
495 const blockerIds = [ serverAccountId ]
496 if (user) blockerIds.push(user.Account.id)
498 const inClause = createSafeIn(this.sequelize, blockerIds)
502 ' SELECT 1 FROM "accountBlocklist" ' +
503 ' WHERE "accountBlocklist"."accountId" IN (' + inClause + ') ' +
504 ' AND "accountBlocklist"."targetAccountId" = "account"."id" ' +
507 ' SELECT 1 FROM "serverBlocklist" WHERE "serverBlocklist"."accountId" IN (' + inClause + ') ' +
508 ' AND "serverBlocklist"."targetServerId" = "accountActor"."serverId"' +
513 private whereSearch (search?: string) {
515 this.attributes.push('0 as similarity')
519 const escapedSearch = this.sequelize.escape(search)
520 const escapedLikeSearch = this.sequelize.escape('%' + search + '%')
523 '"trigramSearch" AS (' +
524 ' SELECT "video"."id", ' +
525 ` similarity(lower(immutable_unaccent("video"."name")), lower(immutable_unaccent(${escapedSearch}))) as similarity ` +
527 ' WHERE lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
528 ' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
532 this.joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
535 ' "trigramSearch"."id" IS NOT NULL OR ' +
537 ' SELECT 1 FROM "videoTag" ' +
538 ' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
539 ` WHERE lower("tag"."name") = ${escapedSearch} ` +
540 ' AND "video"."id" = "videoTag"."videoId"' +
543 if (validator.isUUID(search)) {
544 base += ` OR "video"."uuid" = ${escapedSearch}`
550 this.attributes.push(`COALESCE("trigramSearch"."similarity", 0) as similarity`)
553 private whereNotBlacklisted () {
554 this.and.push('"video"."id" NOT IN (SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")')
557 private whereStartDate (startDate: string) {
558 this.and.push('"video"."publishedAt" >= :startDate')
559 this.replacements.startDate = startDate
562 private whereEndDate (endDate: string) {
563 this.and.push('"video"."publishedAt" <= :endDate')
564 this.replacements.endDate = endDate
567 private whereOriginallyPublishedStartDate (startDate: string) {
568 this.and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
569 this.replacements.originallyPublishedStartDate = startDate
572 private whereOriginallyPublishedEndDate (endDate: string) {
573 this.and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
574 this.replacements.originallyPublishedEndDate = endDate
577 private whereDurationMin (durationMin: number) {
578 this.and.push('"video"."duration" >= :durationMin')
579 this.replacements.durationMin = durationMin
582 private whereDurationMax (durationMax: number) {
583 this.and.push('"video"."duration" <= :durationMax')
584 this.replacements.durationMax = durationMax
587 private groupForTrending (trendingDays: number) {
588 const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
590 this.joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
591 this.replacements.viewsGteDate = viewsGteDate
593 this.attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "score"')
595 this.group = 'GROUP BY "video"."id"'
598 private groupForHotOrBest (trendingAlgorithm: string, user?: MUserAccountId) {
600 * "Hotness" is a measure based on absolute view/comment/like/dislike numbers,
601 * with fixed weights only applied to their log values.
603 * This algorithm gives little chance for an old video to have a good score,
604 * for which recent spikes in interactions could be a sign of "hotness" and
605 * justify a better score. However there are multiple ways to achieve that
606 * goal, which is left for later. Yes, this is a TODO :)
609 * - weights and base score are in number of half-days.
610 * - all comments are counted, regardless of being written by the video author or not
611 * see https://github.com/reddit-archive/reddit/blob/master/r2/r2/lib/db/_sorts.pyx#L47-L58
612 * - we have less interactions than on reddit, so multiply weights by an arbitrary factor
617 view: Math.floor((1 / 3) * 50),
618 comment: 2 * 50, // a comment takes more time than a like to do, but can be done multiple times
622 this.joins.push('LEFT JOIN "videoComment" ON "video"."id" = "videoComment"."videoId"')
625 `LOG(GREATEST(1, "video"."likes" - 1)) * ${weights.like} ` + // likes (+)
626 `+ LOG(GREATEST(1, "video"."dislikes" - 1)) * ${weights.dislike} ` + // dislikes (-)
627 `+ LOG("video"."views" + 1) * ${weights.view} ` + // views (+)
628 `+ LOG(GREATEST(1, COUNT(DISTINCT "videoComment"."id"))) * ${weights.comment} ` + // comments (+)
629 '+ (SELECT (EXTRACT(epoch FROM "video"."publishedAt") - 1446156582) / 47000) ' // base score (in number of half-days)
631 if (trendingAlgorithm === 'best' && user) {
633 'LEFT JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :bestUser'
635 this.replacements.bestUser = user.id
637 attribute += `+ POWER(COUNT(DISTINCT "userVideoHistory"."id"), 2.0) * ${weights.history} `
640 attribute += 'AS "score"'
641 this.attributes.push(attribute)
643 this.group = 'GROUP BY "video"."id"'
646 private setSort (sort: string) {
647 if (sort === '-originallyPublishedAt' || sort === 'originallyPublishedAt') {
648 this.attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
651 this.sort = this.buildOrder(sort)
654 private buildOrder (value: string) {
655 const { direction, field } = buildDirectionAndField(value)
656 if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
658 if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
660 if ([ 'trending', 'hot', 'best' ].includes(field.toLowerCase())) { // Sort by aggregation
661 return `ORDER BY "score" ${direction}, "video"."views" ${direction}`
664 let firstSort: string
666 if (field.toLowerCase() === 'match') { // Search
667 firstSort = '"similarity"'
668 } else if (field === 'originallyPublishedAt') {
669 firstSort = '"publishedAtForOrder"'
670 } else if (field.includes('.')) {
673 firstSort = `"video"."${field}"`
676 return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
679 private setLimit (countArg: number) {
680 const count = parseInt(countArg + '', 10)
681 this.limit = `LIMIT ${count}`
684 private setOffset (startArg: number) {
685 const start = parseInt(startArg + '', 10)
686 this.offset = `OFFSET ${start}`