]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
Correctly delete directories on import
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
3 AfterDelete,
4 AfterUpdate,
5 AllowNull,
6 BeforeCreate,
7 BeforeUpdate,
8 Column,
9 CreatedAt,
10 DataType,
11 Default,
12 DefaultScope,
13 HasMany,
14 HasOne,
15 Is,
16 IsEmail,
17 Model,
18 Scopes,
19 Table,
20 UpdatedAt
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
24 import {
25 isUserAutoPlayVideoValid,
26 isUserBlockedReasonValid,
27 isUserBlockedValid,
28 isUserEmailVerifiedValid,
29 isUserNSFWPolicyValid,
30 isUserPasswordValid,
31 isUserRoleValid,
32 isUserUsernameValid,
33 isUserVideoQuotaDailyValid,
34 isUserVideoQuotaValid
35 } from '../../helpers/custom-validators/users'
36 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
37 import { OAuthTokenModel } from '../oauth/oauth-token'
38 import { getSort, throwIfNotValid } from '../utils'
39 import { VideoChannelModel } from '../video/video-channel'
40 import { AccountModel } from './account'
41 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
42 import { values } from 'lodash'
43 import { NSFW_POLICY_TYPES } from '../../initializers'
44 import { clearCacheByUserId } from '../../lib/oauth-model'
45
46 enum ScopeNames {
47 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
48 }
49
50 @DefaultScope({
51 include: [
52 {
53 model: () => AccountModel,
54 required: true
55 }
56 ]
57 })
58 @Scopes({
59 [ScopeNames.WITH_VIDEO_CHANNEL]: {
60 include: [
61 {
62 model: () => AccountModel,
63 required: true,
64 include: [ () => VideoChannelModel ]
65 }
66 ]
67 }
68 })
69 @Table({
70 tableName: 'user',
71 indexes: [
72 {
73 fields: [ 'username' ],
74 unique: true
75 },
76 {
77 fields: [ 'email' ],
78 unique: true
79 }
80 ]
81 })
82 export class UserModel extends Model<UserModel> {
83
84 @AllowNull(false)
85 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
86 @Column
87 password: string
88
89 @AllowNull(false)
90 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
91 @Column
92 username: string
93
94 @AllowNull(false)
95 @IsEmail
96 @Column(DataType.STRING(400))
97 email: string
98
99 @AllowNull(true)
100 @Default(null)
101 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
102 @Column
103 emailVerified: boolean
104
105 @AllowNull(false)
106 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
107 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
108 nsfwPolicy: NSFWPolicyType
109
110 @AllowNull(false)
111 @Default(true)
112 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
113 @Column
114 autoPlayVideo: boolean
115
116 @AllowNull(false)
117 @Default(false)
118 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
119 @Column
120 blocked: boolean
121
122 @AllowNull(true)
123 @Default(null)
124 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
125 @Column
126 blockedReason: string
127
128 @AllowNull(false)
129 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
130 @Column
131 role: number
132
133 @AllowNull(false)
134 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
135 @Column(DataType.BIGINT)
136 videoQuota: number
137
138 @AllowNull(false)
139 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
140 @Column(DataType.BIGINT)
141 videoQuotaDaily: number
142
143 @CreatedAt
144 createdAt: Date
145
146 @UpdatedAt
147 updatedAt: Date
148
149 @HasOne(() => AccountModel, {
150 foreignKey: 'userId',
151 onDelete: 'cascade',
152 hooks: true
153 })
154 Account: AccountModel
155
156 @HasMany(() => OAuthTokenModel, {
157 foreignKey: 'userId',
158 onDelete: 'cascade'
159 })
160 OAuthTokens: OAuthTokenModel[]
161
162 @BeforeCreate
163 @BeforeUpdate
164 static cryptPasswordIfNeeded (instance: UserModel) {
165 if (instance.changed('password')) {
166 return cryptPassword(instance.password)
167 .then(hash => {
168 instance.password = hash
169 return undefined
170 })
171 }
172 }
173
174 @AfterUpdate
175 @AfterDelete
176 static removeTokenCache (instance: UserModel) {
177 return clearCacheByUserId(instance.id)
178 }
179
180 static countTotal () {
181 return this.count()
182 }
183
184 static listForApi (start: number, count: number, sort: string) {
185 const query = {
186 attributes: {
187 include: [
188 [
189 Sequelize.literal(
190 '(' +
191 'SELECT COALESCE(SUM("size"), 0) ' +
192 'FROM (' +
193 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
194 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
195 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
196 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
197 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
198 ') t' +
199 ')'
200 ),
201 'videoQuotaUsed'
202 ] as any // FIXME: typings
203 ]
204 },
205 offset: start,
206 limit: count,
207 order: getSort(sort)
208 }
209
210 return UserModel.findAndCountAll(query)
211 .then(({ rows, count }) => {
212 return {
213 data: rows,
214 total: count
215 }
216 })
217 }
218
219 static listEmailsWithRight (right: UserRight) {
220 const roles = Object.keys(USER_ROLE_LABELS)
221 .map(k => parseInt(k, 10) as UserRole)
222 .filter(role => hasUserRight(role, right))
223
224 const query = {
225 attribute: [ 'email' ],
226 where: {
227 role: {
228 [Sequelize.Op.in]: roles
229 }
230 }
231 }
232
233 return UserModel.unscoped()
234 .findAll(query)
235 .then(u => u.map(u => u.email))
236 }
237
238 static loadById (id: number) {
239 return UserModel.findById(id)
240 }
241
242 static loadByUsername (username: string) {
243 const query = {
244 where: {
245 username
246 }
247 }
248
249 return UserModel.findOne(query)
250 }
251
252 static loadByUsernameAndPopulateChannels (username: string) {
253 const query = {
254 where: {
255 username
256 }
257 }
258
259 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
260 }
261
262 static loadByEmail (email: string) {
263 const query = {
264 where: {
265 email
266 }
267 }
268
269 return UserModel.findOne(query)
270 }
271
272 static loadByUsernameOrEmail (username: string, email?: string) {
273 if (!email) email = username
274
275 const query = {
276 where: {
277 [ Sequelize.Op.or ]: [ { username }, { email } ]
278 }
279 }
280
281 return UserModel.findOne(query)
282 }
283
284 static getOriginalVideoFileTotalFromUser (user: UserModel) {
285 // Don't use sequelize because we need to use a sub query
286 const query = UserModel.generateUserQuotaBaseSQL()
287
288 return UserModel.getTotalRawQuery(query, user.id)
289 }
290
291 // Returns cumulative size of all video files uploaded in the last 24 hours.
292 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
293 // Don't use sequelize because we need to use a sub query
294 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
295
296 return UserModel.getTotalRawQuery(query, user.id)
297 }
298
299 static async getStats () {
300 const totalUsers = await UserModel.count()
301
302 return {
303 totalUsers
304 }
305 }
306
307 static autoComplete (search: string) {
308 const query = {
309 where: {
310 username: {
311 [ Sequelize.Op.like ]: `%${search}%`
312 }
313 },
314 limit: 10
315 }
316
317 return UserModel.findAll(query)
318 .then(u => u.map(u => u.username))
319 }
320
321 hasRight (right: UserRight) {
322 return hasUserRight(this.role, right)
323 }
324
325 isPasswordMatch (password: string) {
326 return comparePassword(password, this.password)
327 }
328
329 toFormattedJSON (): User {
330 const videoQuotaUsed = this.get('videoQuotaUsed')
331 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
332
333 const json = {
334 id: this.id,
335 username: this.username,
336 email: this.email,
337 emailVerified: this.emailVerified,
338 nsfwPolicy: this.nsfwPolicy,
339 autoPlayVideo: this.autoPlayVideo,
340 role: this.role,
341 roleLabel: USER_ROLE_LABELS[ this.role ],
342 videoQuota: this.videoQuota,
343 videoQuotaDaily: this.videoQuotaDaily,
344 createdAt: this.createdAt,
345 blocked: this.blocked,
346 blockedReason: this.blockedReason,
347 account: this.Account.toFormattedJSON(),
348 videoChannels: [],
349 videoQuotaUsed: videoQuotaUsed !== undefined
350 ? parseInt(videoQuotaUsed, 10)
351 : undefined,
352 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
353 ? parseInt(videoQuotaUsedDaily, 10)
354 : undefined
355 }
356
357 if (Array.isArray(this.Account.VideoChannels) === true) {
358 json.videoChannels = this.Account.VideoChannels
359 .map(c => c.toFormattedJSON())
360 .sort((v1, v2) => {
361 if (v1.createdAt < v2.createdAt) return -1
362 if (v1.createdAt === v2.createdAt) return 0
363
364 return 1
365 })
366 }
367
368 return json
369 }
370
371 async isAbleToUploadVideo (videoFile: { size: number }) {
372 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
373
374 const [ totalBytes, totalBytesDaily ] = await Promise.all([
375 UserModel.getOriginalVideoFileTotalFromUser(this),
376 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
377 ])
378
379 const uploadedTotal = videoFile.size + totalBytes
380 const uploadedDaily = videoFile.size + totalBytesDaily
381 if (this.videoQuotaDaily === -1) {
382 return uploadedTotal < this.videoQuota
383 }
384 if (this.videoQuota === -1) {
385 return uploadedDaily < this.videoQuotaDaily
386 }
387
388 return (uploadedTotal < this.videoQuota) &&
389 (uploadedDaily < this.videoQuotaDaily)
390 }
391
392 private static generateUserQuotaBaseSQL (where?: string) {
393 const andWhere = where ? 'AND ' + where : ''
394
395 return 'SELECT SUM("size") AS "total" ' +
396 'FROM (' +
397 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
398 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
399 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
400 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
401 'WHERE "account"."userId" = $userId ' + andWhere +
402 'GROUP BY "video"."id"' +
403 ') t'
404 }
405
406 private static getTotalRawQuery (query: string, userId: number) {
407 const options = {
408 bind: { userId },
409 type: Sequelize.QueryTypes.SELECT
410 }
411
412 return UserModel.sequelize.query(query, options)
413 .then(([ { total } ]) => {
414 if (total === null) return 0
415
416 return parseInt(total, 10)
417 })
418 }
419 }