aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/video/sql/video-model-get-query-builder.ts
blob: 0a3723e632aa4a68eb7f134803e3244634c761c3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { Sequelize, Transaction } from 'sequelize'
import validator from 'validator'
import { AbstractVideosModelQueryBuilder } from './shared/abstract-videos-model-query-builder'

export type BuildVideoGetQueryOptions = {
  id: number | string
  transaction?: Transaction
  userId?: number
  forGetAPI?: boolean
}

export class VideosModelGetQueryBuilder extends AbstractVideosModelQueryBuilder {
  protected attributes: { [key: string]: string }
  protected joins: string[] = []
  protected where: string

  constructor (protected readonly sequelize: Sequelize) {
    super('get')
  }

  queryVideos (options: BuildVideoGetQueryOptions) {
    this.buildGetQuery(options)

    return this.runQuery(options.transaction, true).then(rows => {
      const videos = this.videoModelBuilder.buildVideosFromRows(rows)

      if (videos.length > 1) {
        throw new Error('Video results is more than ')
      }

      if (videos.length === 0) return null
      return videos[0]
    })
  }

  private buildGetQuery (options: BuildVideoGetQueryOptions) {
    this.attributes = {
      '"video".*': ''
    }

    this.includeChannels()
    this.includeAccounts()

    this.includeTags()

    this.includeThumbnails()

    this.includeFiles()

    this.includeBlacklisted()

    this.includeScheduleUpdate()

    this.includeLive()

    if (options.userId) {
      this.includeUserHistory(options.userId)
    }

    if (options.forGetAPI === true) {
      this.includeTrackers()
      this.includeRedundancies()
    }

    this.whereId(options.id)

    const select = this.buildSelect()
    const order = this.buildOrder()

    this.query = `${select} FROM "video" ${this.joins.join(' ')} ${this.where} ${order}`
  }

  private whereId (id: string | number) {
    if (validator.isInt('' + id)) {
      this.where = 'WHERE "video".id = :videoId'
    } else {
      this.where = 'WHERE uuid = :videoId'
    }

    this.replacements.videoId = id
  }

  private buildOrder () {
    return 'ORDER BY "Tags"."name" ASC'
  }
}