aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/video/video-job-info.ts
blob: 7da5128d7598a338262bf3b8b5a09082270240c2 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { Op, QueryTypes, Transaction } from 'sequelize'
import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, IsInt, Model, Table, Unique, UpdatedAt } from 'sequelize-typescript'
import { AttributesOnly } from '@shared/core-utils'
import { VideoModel } from './video'

export type VideoJobInfoColumnType = 'pendingMove' | 'pendingTranscode'

@Table({
  tableName: 'videoJobInfo',
  indexes: [
    {
      fields: [ 'videoId' ],
      where: {
        videoId: {
          [Op.ne]: null
        }
      }
    }
  ]
})

export class VideoJobInfoModel extends Model<Partial<AttributesOnly<VideoJobInfoModel>>> {
  @CreatedAt
  createdAt: Date

  @UpdatedAt
  updatedAt: Date

  @AllowNull(false)
  @Default(0)
  @IsInt
  @Column
  pendingMove: number

  @AllowNull(false)
  @Default(0)
  @IsInt
  @Column
  pendingTranscode: number

  @ForeignKey(() => VideoModel)
  @Unique
  @Column
  videoId: number

  @BelongsTo(() => VideoModel, {
    foreignKey: {
      allowNull: false
    },
    onDelete: 'cascade'
  })
  Video: VideoModel

  static load (videoId: number, transaction?: Transaction) {
    const where = {
      videoId
    }

    return VideoJobInfoModel.findOne({ where, transaction })
  }

  static async increaseOrCreate (videoUUID: string, column: VideoJobInfoColumnType): Promise<number> {
    const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } }

    const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(`
    INSERT INTO "videoJobInfo" ("videoId", "${column}", "createdAt", "updatedAt")
    SELECT
      "video"."id" AS "videoId", 1, NOW(), NOW()
    FROM
      "video"
    WHERE
      "video"."uuid" = $videoUUID
    ON CONFLICT ("videoId") DO UPDATE
    SET
      "${column}" = "videoJobInfo"."${column}" + 1,
      "updatedAt" = NOW()
    RETURNING
      "${column}"
    `, options)

    return pendingMove
  }

  static async decrease (videoUUID: string, column: VideoJobInfoColumnType): Promise<number> {
    const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } }

    const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(`
    UPDATE
      "videoJobInfo"
    SET
      "${column}" = "videoJobInfo"."${column}" - 1,
      "updatedAt" = NOW()
    FROM "video"
    WHERE
      "video"."id" = "videoJobInfo"."videoId" AND "video"."uuid" = $videoUUID
    RETURNING
      "${column}";
    `, options)

    return pendingMove
  }
}