Split types and typings
[oweals/peertube.git] / server / models / video / schedule-video-update.ts
1 import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Model, Table, UpdatedAt } from 'sequelize-typescript'
2 import { ScopeNames as VideoScopeNames, VideoModel } from './video'
3 import { VideoPrivacy } from '../../../shared/models/videos'
4 import { Op, Transaction } from 'sequelize'
5 import { MScheduleVideoUpdateFormattable, MScheduleVideoUpdateVideoAll } from '@server/types/models'
6
7 @Table({
8   tableName: 'scheduleVideoUpdate',
9   indexes: [
10     {
11       fields: [ 'videoId' ],
12       unique: true
13     },
14     {
15       fields: [ 'updateAt' ]
16     }
17   ]
18 })
19 export class ScheduleVideoUpdateModel extends Model<ScheduleVideoUpdateModel> {
20
21   @AllowNull(false)
22   @Default(null)
23   @Column
24   updateAt: Date
25
26   @AllowNull(true)
27   @Default(null)
28   @Column
29   privacy: VideoPrivacy.PUBLIC | VideoPrivacy.UNLISTED | VideoPrivacy.INTERNAL
30
31   @CreatedAt
32   createdAt: Date
33
34   @UpdatedAt
35   updatedAt: Date
36
37   @ForeignKey(() => VideoModel)
38   @Column
39   videoId: number
40
41   @BelongsTo(() => VideoModel, {
42     foreignKey: {
43       allowNull: false
44     },
45     onDelete: 'cascade'
46   })
47   Video: VideoModel
48
49   static areVideosToUpdate () {
50     const query = {
51       logging: false,
52       attributes: [ 'id' ],
53       where: {
54         updateAt: {
55           [Op.lte]: new Date()
56         }
57       }
58     }
59
60     return ScheduleVideoUpdateModel.findOne(query)
61       .then(res => !!res)
62   }
63
64   static listVideosToUpdate (t: Transaction) {
65     const query = {
66       where: {
67         updateAt: {
68           [Op.lte]: new Date()
69         }
70       },
71       include: [
72         {
73           model: VideoModel.scope(
74             [
75               VideoScopeNames.WITH_WEBTORRENT_FILES,
76               VideoScopeNames.WITH_STREAMING_PLAYLISTS,
77               VideoScopeNames.WITH_ACCOUNT_DETAILS,
78               VideoScopeNames.WITH_BLACKLISTED,
79               VideoScopeNames.WITH_THUMBNAILS,
80               VideoScopeNames.WITH_TAGS
81             ]
82           )
83         }
84       ],
85       transaction: t
86     }
87
88     return ScheduleVideoUpdateModel.findAll<MScheduleVideoUpdateVideoAll>(query)
89   }
90
91   static deleteByVideoId (videoId: number, t: Transaction) {
92     const query = {
93       where: {
94         videoId
95       },
96       transaction: t
97     }
98
99     return ScheduleVideoUpdateModel.destroy(query)
100   }
101
102   toFormattedJSON (this: MScheduleVideoUpdateFormattable) {
103     return {
104       updateAt: this.updateAt,
105       privacy: this.privacy || undefined
106     }
107   }
108 }