Improve playback speed style
[oweals/peertube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
3   AllowNull,
4   BeforeCreate,
5   BeforeUpdate,
6   Column,
7   CreatedAt,
8   DataType,
9   Default,
10   DefaultScope,
11   HasMany,
12   HasOne,
13   Is,
14   IsEmail,
15   Model,
16   Scopes,
17   Table,
18   UpdatedAt
19 } from 'sequelize-typescript'
20 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
21 import { User, UserRole } from '../../../shared/models/users'
22 import {
23   isUserAutoPlayVideoValid,
24   isUserDisplayNSFWValid,
25   isUserPasswordValid,
26   isUserRoleValid,
27   isUserUsernameValid,
28   isUserVideoQuotaValid
29 } from '../../helpers/custom-validators/users'
30 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
31 import { OAuthTokenModel } from '../oauth/oauth-token'
32 import { getSort, throwIfNotValid } from '../utils'
33 import { VideoChannelModel } from '../video/video-channel'
34 import { AccountModel } from './account'
35
36 @DefaultScope({
37   include: [
38     {
39       model: () => AccountModel,
40       required: true
41     }
42   ]
43 })
44 @Scopes({
45   withVideoChannel: {
46     include: [
47       {
48         model: () => AccountModel,
49         required: true,
50         include: [ () => VideoChannelModel ]
51       }
52     ]
53   }
54 })
55 @Table({
56   tableName: 'user',
57   indexes: [
58     {
59       fields: [ 'username' ],
60       unique: true
61     },
62     {
63       fields: [ 'email' ],
64       unique: true
65     }
66   ]
67 })
68 export class UserModel extends Model<UserModel> {
69
70   @AllowNull(false)
71   @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
72   @Column
73   password: string
74
75   @AllowNull(false)
76   @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
77   @Column
78   username: string
79
80   @AllowNull(false)
81   @IsEmail
82   @Column(DataType.STRING(400))
83   email: string
84
85   @AllowNull(false)
86   @Default(false)
87   @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
88   @Column
89   displayNSFW: boolean
90
91   @AllowNull(false)
92   @Default(true)
93   @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
94   @Column
95   autoPlayVideo: boolean
96
97   @AllowNull(false)
98   @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
99   @Column
100   role: number
101
102   @AllowNull(false)
103   @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
104   @Column(DataType.BIGINT)
105   videoQuota: number
106
107   @CreatedAt
108   createdAt: Date
109
110   @UpdatedAt
111   updatedAt: Date
112
113   @HasOne(() => AccountModel, {
114     foreignKey: 'userId',
115     onDelete: 'cascade',
116     hooks: true
117   })
118   Account: AccountModel
119
120   @HasMany(() => OAuthTokenModel, {
121     foreignKey: 'userId',
122     onDelete: 'cascade'
123   })
124   OAuthTokens: OAuthTokenModel[]
125
126   @BeforeCreate
127   @BeforeUpdate
128   static cryptPasswordIfNeeded (instance: UserModel) {
129     if (instance.changed('password')) {
130       return cryptPassword(instance.password)
131         .then(hash => {
132           instance.password = hash
133           return undefined
134         })
135     }
136   }
137
138   static countTotal () {
139     return this.count()
140   }
141
142   static listForApi (start: number, count: number, sort: string) {
143     const query = {
144       offset: start,
145       limit: count,
146       order: getSort(sort)
147     }
148
149     return UserModel.findAndCountAll(query)
150       .then(({ rows, count }) => {
151         return {
152           data: rows,
153           total: count
154         }
155       })
156   }
157
158   static listEmailsWithRight (right: UserRight) {
159     const roles = Object.keys(USER_ROLE_LABELS)
160       .map(k => parseInt(k, 10) as UserRole)
161       .filter(role => hasUserRight(role, right))
162
163     console.log(roles)
164
165     const query = {
166       attribute: [ 'email' ],
167       where: {
168         role: {
169           [Sequelize.Op.in]: roles
170         }
171       }
172     }
173
174     return UserModel.unscoped()
175       .findAll(query)
176       .then(u => u.map(u => u.email))
177   }
178
179   static loadById (id: number) {
180     return UserModel.findById(id)
181   }
182
183   static loadByUsername (username: string) {
184     const query = {
185       where: {
186         username
187       }
188     }
189
190     return UserModel.findOne(query)
191   }
192
193   static loadByUsernameAndPopulateChannels (username: string) {
194     const query = {
195       where: {
196         username
197       }
198     }
199
200     return UserModel.scope('withVideoChannel').findOne(query)
201   }
202
203   static loadByEmail (email: string) {
204     const query = {
205       where: {
206         email
207       }
208     }
209
210     return UserModel.findOne(query)
211   }
212
213   static loadByUsernameOrEmail (username: string, email?: string) {
214     if (!email) email = username
215
216     const query = {
217       where: {
218         [ Sequelize.Op.or ]: [ { username }, { email } ]
219       }
220     }
221
222     return UserModel.findOne(query)
223   }
224
225   static getOriginalVideoFileTotalFromUser (user: UserModel) {
226     // Don't use sequelize because we need to use a sub query
227     const query = 'SELECT SUM("size") AS "total" FROM ' +
228       '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
229       'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
230       'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
231       'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
232       'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
233       'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
234
235     const options = {
236       bind: { userId: user.id },
237       type: Sequelize.QueryTypes.SELECT
238     }
239     return UserModel.sequelize.query(query, options)
240       .then(([ { total } ]) => {
241         if (total === null) return 0
242
243         return parseInt(total, 10)
244       })
245   }
246
247   static async getStats () {
248     const totalUsers = await UserModel.count()
249
250     return {
251       totalUsers
252     }
253   }
254
255   hasRight (right: UserRight) {
256     return hasUserRight(this.role, right)
257   }
258
259   isPasswordMatch (password: string) {
260     return comparePassword(password, this.password)
261   }
262
263   toFormattedJSON (): User {
264     const json = {
265       id: this.id,
266       username: this.username,
267       email: this.email,
268       displayNSFW: this.displayNSFW,
269       autoPlayVideo: this.autoPlayVideo,
270       role: this.role,
271       roleLabel: USER_ROLE_LABELS[ this.role ],
272       videoQuota: this.videoQuota,
273       createdAt: this.createdAt,
274       account: this.Account.toFormattedJSON(),
275       videoChannels: []
276     }
277
278     if (Array.isArray(this.Account.VideoChannels) === true) {
279       json.videoChannels = this.Account.VideoChannels
280         .map(c => c.toFormattedJSON())
281         .sort((v1, v2) => {
282           if (v1.createdAt < v2.createdAt) return -1
283           if (v1.createdAt === v2.createdAt) return 0
284
285           return 1
286         })
287     }
288
289     return json
290   }
291
292   isAbleToUploadVideo (videoFile: Express.Multer.File) {
293     if (this.videoQuota === -1) return Promise.resolve(true)
294
295     return UserModel.getOriginalVideoFileTotalFromUser(this)
296       .then(totalBytes => {
297         return (videoFile.size + totalBytes) < this.videoQuota
298       })
299   }
300 }