aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/runner/runner-registration-token.ts
blob: b2ae6c9eb65c2d751c101ab071b9648e54e5fda7 (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
103
import { FindOptions, literal } from 'sequelize'
import { AllowNull, Column, CreatedAt, HasMany, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { MRunnerRegistrationToken } from '@server/types/models/runners'
import { RunnerRegistrationToken } from '@shared/models'
import { AttributesOnly } from '@shared/typescript-utils'
import { getSort } from '../shared'
import { RunnerModel } from './runner'

/**
 *
 * Tokens used by PeerTube runners to register themselves to the PeerTube instance
 *
 */

@Table({
  tableName: 'runnerRegistrationToken',
  indexes: [
    {
      fields: [ 'registrationToken' ],
      unique: true
    }
  ]
})
export class RunnerRegistrationTokenModel extends Model<Partial<AttributesOnly<RunnerRegistrationTokenModel>>> {

  @AllowNull(false)
  @Column
  registrationToken: string

  @CreatedAt
  createdAt: Date

  @UpdatedAt
  updatedAt: Date

  @HasMany(() => RunnerModel, {
    foreignKey: {
      allowNull: true
    },
    onDelete: 'cascade'
  })
  Runners: RunnerModel[]

  static load (id: number) {
    return RunnerRegistrationTokenModel.findByPk(id)
  }

  static loadByRegistrationToken (registrationToken: string) {
    const query = {
      where: { registrationToken }
    }

    return RunnerRegistrationTokenModel.findOne(query)
  }

  static countTotal () {
    return RunnerRegistrationTokenModel.unscoped().count()
  }

  static listForApi (options: {
    start: number
    count: number
    sort: string
  }) {
    const { start, count, sort } = options

    const query: FindOptions = {
      attributes: {
        include: [
          [
            literal('(SELECT COUNT(*) FROM "runner" WHERE "runner"."runnerRegistrationTokenId" = "RunnerRegistrationTokenModel"."id")'),
            'registeredRunnersCount'
          ]
        ]
      },
      offset: start,
      limit: count,
      order: getSort(sort)
    }

    return Promise.all([
      RunnerRegistrationTokenModel.count(query),
      RunnerRegistrationTokenModel.findAll<MRunnerRegistrationToken>(query)
    ]).then(([ total, data ]) => ({ total, data }))
  }

  // ---------------------------------------------------------------------------

  toFormattedJSON (this: MRunnerRegistrationToken): RunnerRegistrationToken {
    const registeredRunnersCount = this.get('registeredRunnersCount') as number

    return {
      id: this.id,

      registrationToken: this.registrationToken,

      createdAt: this.createdAt,
      updatedAt: this.updatedAt,

      registeredRunnersCount
    }
  }
}