Split types and typings
[oweals/peertube.git] / server / models / account / account-video-rate.ts
1 import { values } from 'lodash'
2 import { FindOptions, Op, Transaction } from 'sequelize'
3 import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
4 import { VideoRateType } from '../../../shared/models/videos'
5 import { CONSTRAINTS_FIELDS, VIDEO_RATE_TYPES } from '../../initializers/constants'
6 import { VideoModel } from '../video/video'
7 import { AccountModel } from './account'
8 import { ActorModel } from '../activitypub/actor'
9 import { buildLocalAccountIdsIn, getSort, throwIfNotValid } from '../utils'
10 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
11 import { AccountVideoRate } from '../../../shared'
12 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from '../video/video-channel'
13 import * as Bluebird from 'bluebird'
14 import {
15   MAccountVideoRate,
16   MAccountVideoRateAccountUrl,
17   MAccountVideoRateAccountVideo,
18   MAccountVideoRateFormattable
19 } from '@server/types/models/video/video-rate'
20
21 /*
22   Account rates per video.
23 */
24 @Table({
25   tableName: 'accountVideoRate',
26   indexes: [
27     {
28       fields: [ 'videoId', 'accountId' ],
29       unique: true
30     },
31     {
32       fields: [ 'videoId' ]
33     },
34     {
35       fields: [ 'accountId' ]
36     },
37     {
38       fields: [ 'videoId', 'type' ]
39     },
40     {
41       fields: [ 'url' ],
42       unique: true
43     }
44   ]
45 })
46 export class AccountVideoRateModel extends Model<AccountVideoRateModel> {
47
48   @AllowNull(false)
49   @Column(DataType.ENUM(...values(VIDEO_RATE_TYPES)))
50   type: VideoRateType
51
52   @AllowNull(false)
53   @Is('AccountVideoRateUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
54   @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_RATES.URL.max))
55   url: string
56
57   @CreatedAt
58   createdAt: Date
59
60   @UpdatedAt
61   updatedAt: Date
62
63   @ForeignKey(() => VideoModel)
64   @Column
65   videoId: number
66
67   @BelongsTo(() => VideoModel, {
68     foreignKey: {
69       allowNull: false
70     },
71     onDelete: 'CASCADE'
72   })
73   Video: VideoModel
74
75   @ForeignKey(() => AccountModel)
76   @Column
77   accountId: number
78
79   @BelongsTo(() => AccountModel, {
80     foreignKey: {
81       allowNull: false
82     },
83     onDelete: 'CASCADE'
84   })
85   Account: AccountModel
86
87   static load (accountId: number, videoId: number, transaction?: Transaction): Bluebird<MAccountVideoRate> {
88     const options: FindOptions = {
89       where: {
90         accountId,
91         videoId
92       }
93     }
94     if (transaction) options.transaction = transaction
95
96     return AccountVideoRateModel.findOne(options)
97   }
98
99   static loadByAccountAndVideoOrUrl (accountId: number, videoId: number, url: string, t?: Transaction): Bluebird<MAccountVideoRate> {
100     const options: FindOptions = {
101       where: {
102         [Op.or]: [
103           {
104             accountId,
105             videoId
106           },
107           {
108             url
109           }
110         ]
111       }
112     }
113     if (t) options.transaction = t
114
115     return AccountVideoRateModel.findOne(options)
116   }
117
118   static listByAccountForApi (options: {
119     start: number
120     count: number
121     sort: string
122     type?: string
123     accountId: number
124   }) {
125     const query: FindOptions = {
126       offset: options.start,
127       limit: options.count,
128       order: getSort(options.sort),
129       where: {
130         accountId: options.accountId
131       },
132       include: [
133         {
134           model: VideoModel,
135           required: true,
136           include: [
137             {
138               model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, { withAccount: true } as SummaryOptions ] }),
139               required: true
140             }
141           ]
142         }
143       ]
144     }
145     if (options.type) query.where['type'] = options.type
146
147     return AccountVideoRateModel.findAndCountAll(query)
148   }
149
150   static loadLocalAndPopulateVideo (
151     rateType: VideoRateType,
152     accountName: string,
153     videoId: number | string,
154     t?: Transaction
155   ): Bluebird<MAccountVideoRateAccountVideo> {
156     const options: FindOptions = {
157       where: {
158         videoId,
159         type: rateType
160       },
161       include: [
162         {
163           model: AccountModel.unscoped(),
164           required: true,
165           include: [
166             {
167               attributes: [ 'id', 'url', 'followersUrl', 'preferredUsername' ],
168               model: ActorModel.unscoped(),
169               required: true,
170               where: {
171                 preferredUsername: accountName
172               }
173             }
174           ]
175         },
176         {
177           model: VideoModel.unscoped(),
178           required: true
179         }
180       ]
181     }
182     if (t) options.transaction = t
183
184     return AccountVideoRateModel.findOne(options)
185   }
186
187   static loadByUrl (url: string, transaction: Transaction) {
188     const options: FindOptions = {
189       where: {
190         url
191       }
192     }
193     if (transaction) options.transaction = transaction
194
195     return AccountVideoRateModel.findOne(options)
196   }
197
198   static listAndCountAccountUrlsByVideoId (rateType: VideoRateType, videoId: number, start: number, count: number, t?: Transaction) {
199     const query = {
200       offset: start,
201       limit: count,
202       where: {
203         videoId,
204         type: rateType
205       },
206       transaction: t,
207       include: [
208         {
209           attributes: [ 'actorId' ],
210           model: AccountModel.unscoped(),
211           required: true,
212           include: [
213             {
214               attributes: [ 'url' ],
215               model: ActorModel.unscoped(),
216               required: true
217             }
218           ]
219         }
220       ]
221     }
222
223     return AccountVideoRateModel.findAndCountAll<MAccountVideoRateAccountUrl>(query)
224   }
225
226   static cleanOldRatesOf (videoId: number, type: VideoRateType, beforeUpdatedAt: Date) {
227     return AccountVideoRateModel.sequelize.transaction(async t => {
228       const query = {
229         where: {
230           updatedAt: {
231             [Op.lt]: beforeUpdatedAt
232           },
233           videoId,
234           type,
235           accountId: {
236             [Op.notIn]: buildLocalAccountIdsIn()
237           }
238         },
239         transaction: t
240       }
241
242       const deleted = await AccountVideoRateModel.destroy(query)
243
244       const options = {
245         transaction: t,
246         where: {
247           id: videoId
248         }
249       }
250
251       if (type === 'like') await VideoModel.increment({ likes: -deleted }, options)
252       else if (type === 'dislike') await VideoModel.increment({ dislikes: -deleted }, options)
253     })
254   }
255
256   toFormattedJSON (this: MAccountVideoRateFormattable): AccountVideoRate {
257     return {
258       video: this.Video.toFormattedJSON(),
259       rating: this.type
260     }
261   }
262 }