]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
33f56f64193b5eecfca16b4892edb30d2ca13f2b
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
3 AfterDestroy,
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 isUserVideosHistoryEnabledValid,
36 isUserWebTorrentEnabledValid
37 } from '../../helpers/custom-validators/users'
38 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
39 import { OAuthTokenModel } from '../oauth/oauth-token'
40 import { getSort, throwIfNotValid } from '../utils'
41 import { VideoChannelModel } from '../video/video-channel'
42 import { AccountModel } from './account'
43 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
44 import { values } from 'lodash'
45 import { NSFW_POLICY_TYPES } from '../../initializers'
46 import { clearCacheByUserId } from '../../lib/oauth-model'
47 import { UserNotificationSettingModel } from './user-notification-setting'
48 import { VideoModel } from '../video/video'
49 import { ActorModel } from '../activitypub/actor'
50 import { ActorFollowModel } from '../activitypub/actor-follow'
51 import { VideoImportModel } from '../video/video-import'
52
53 enum ScopeNames {
54 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
55 }
56
57 @DefaultScope({
58 include: [
59 {
60 model: () => AccountModel,
61 required: true
62 },
63 {
64 model: () => UserNotificationSettingModel,
65 required: true
66 }
67 ]
68 })
69 @Scopes({
70 [ScopeNames.WITH_VIDEO_CHANNEL]: {
71 include: [
72 {
73 model: () => AccountModel,
74 required: true,
75 include: [ () => VideoChannelModel ]
76 },
77 {
78 model: () => UserNotificationSettingModel,
79 required: true
80 }
81 ]
82 }
83 })
84 @Table({
85 tableName: 'user',
86 indexes: [
87 {
88 fields: [ 'username' ],
89 unique: true
90 },
91 {
92 fields: [ 'email' ],
93 unique: true
94 }
95 ]
96 })
97 export class UserModel extends Model<UserModel> {
98
99 @AllowNull(false)
100 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
101 @Column
102 password: string
103
104 @AllowNull(false)
105 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
106 @Column
107 username: string
108
109 @AllowNull(false)
110 @IsEmail
111 @Column(DataType.STRING(400))
112 email: string
113
114 @AllowNull(true)
115 @Default(null)
116 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
117 @Column
118 emailVerified: boolean
119
120 @AllowNull(false)
121 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
122 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
123 nsfwPolicy: NSFWPolicyType
124
125 @AllowNull(false)
126 @Default(true)
127 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
128 @Column
129 webTorrentEnabled: boolean
130
131 @AllowNull(false)
132 @Default(true)
133 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
134 @Column
135 videosHistoryEnabled: boolean
136
137 @AllowNull(false)
138 @Default(true)
139 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
140 @Column
141 autoPlayVideo: boolean
142
143 @AllowNull(false)
144 @Default(false)
145 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
146 @Column
147 blocked: boolean
148
149 @AllowNull(true)
150 @Default(null)
151 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
152 @Column
153 blockedReason: string
154
155 @AllowNull(false)
156 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
157 @Column
158 role: number
159
160 @AllowNull(false)
161 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
162 @Column(DataType.BIGINT)
163 videoQuota: number
164
165 @AllowNull(false)
166 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
167 @Column(DataType.BIGINT)
168 videoQuotaDaily: number
169
170 @CreatedAt
171 createdAt: Date
172
173 @UpdatedAt
174 updatedAt: Date
175
176 @HasOne(() => AccountModel, {
177 foreignKey: 'userId',
178 onDelete: 'cascade',
179 hooks: true
180 })
181 Account: AccountModel
182
183 @HasOne(() => UserNotificationSettingModel, {
184 foreignKey: 'userId',
185 onDelete: 'cascade',
186 hooks: true
187 })
188 NotificationSetting: UserNotificationSettingModel
189
190 @HasMany(() => VideoImportModel, {
191 foreignKey: 'userId',
192 onDelete: 'cascade'
193 })
194 VideoImports: VideoImportModel[]
195
196 @HasMany(() => OAuthTokenModel, {
197 foreignKey: 'userId',
198 onDelete: 'cascade'
199 })
200 OAuthTokens: OAuthTokenModel[]
201
202 @BeforeCreate
203 @BeforeUpdate
204 static cryptPasswordIfNeeded (instance: UserModel) {
205 if (instance.changed('password')) {
206 return cryptPassword(instance.password)
207 .then(hash => {
208 instance.password = hash
209 return undefined
210 })
211 }
212 }
213
214 @AfterUpdate
215 @AfterDestroy
216 static removeTokenCache (instance: UserModel) {
217 return clearCacheByUserId(instance.id)
218 }
219
220 static countTotal () {
221 return this.count()
222 }
223
224 static listForApi (start: number, count: number, sort: string, search?: string) {
225 let where = undefined
226 if (search) {
227 where = {
228 [Sequelize.Op.or]: [
229 {
230 email: {
231 [Sequelize.Op.iLike]: '%' + search + '%'
232 }
233 },
234 {
235 username: {
236 [ Sequelize.Op.iLike ]: '%' + search + '%'
237 }
238 }
239 ]
240 }
241 }
242
243 const query = {
244 attributes: {
245 include: [
246 [
247 Sequelize.literal(
248 '(' +
249 'SELECT COALESCE(SUM("size"), 0) ' +
250 'FROM (' +
251 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
252 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
253 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
254 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
255 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
256 ') t' +
257 ')'
258 ),
259 'videoQuotaUsed'
260 ] as any // FIXME: typings
261 ]
262 },
263 offset: start,
264 limit: count,
265 order: getSort(sort),
266 where
267 }
268
269 return UserModel.findAndCountAll(query)
270 .then(({ rows, count }) => {
271 return {
272 data: rows,
273 total: count
274 }
275 })
276 }
277
278 static listWithRight (right: UserRight) {
279 const roles = Object.keys(USER_ROLE_LABELS)
280 .map(k => parseInt(k, 10) as UserRole)
281 .filter(role => hasUserRight(role, right))
282
283 const query = {
284 where: {
285 role: {
286 [Sequelize.Op.in]: roles
287 }
288 }
289 }
290
291 return UserModel.findAll(query)
292 }
293
294 static listUserSubscribersOf (actorId: number) {
295 const query = {
296 include: [
297 {
298 model: UserNotificationSettingModel.unscoped(),
299 required: true
300 },
301 {
302 attributes: [ 'userId' ],
303 model: AccountModel.unscoped(),
304 required: true,
305 include: [
306 {
307 attributes: [ ],
308 model: ActorModel.unscoped(),
309 required: true,
310 where: {
311 serverId: null
312 },
313 include: [
314 {
315 attributes: [ ],
316 as: 'ActorFollowings',
317 model: ActorFollowModel.unscoped(),
318 required: true,
319 where: {
320 targetActorId: actorId
321 }
322 }
323 ]
324 }
325 ]
326 }
327 ]
328 }
329
330 return UserModel.unscoped().findAll(query)
331 }
332
333 static loadById (id: number) {
334 return UserModel.findById(id)
335 }
336
337 static loadByUsername (username: string) {
338 const query = {
339 where: {
340 username
341 }
342 }
343
344 return UserModel.findOne(query)
345 }
346
347 static loadByUsernameAndPopulateChannels (username: string) {
348 const query = {
349 where: {
350 username
351 }
352 }
353
354 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
355 }
356
357 static loadByEmail (email: string) {
358 const query = {
359 where: {
360 email
361 }
362 }
363
364 return UserModel.findOne(query)
365 }
366
367 static loadByUsernameOrEmail (username: string, email?: string) {
368 if (!email) email = username
369
370 const query = {
371 where: {
372 [ Sequelize.Op.or ]: [ { username }, { email } ]
373 }
374 }
375
376 return UserModel.findOne(query)
377 }
378
379 static loadByVideoId (videoId: number) {
380 const query = {
381 include: [
382 {
383 required: true,
384 attributes: [ 'id' ],
385 model: AccountModel.unscoped(),
386 include: [
387 {
388 required: true,
389 attributes: [ 'id' ],
390 model: VideoChannelModel.unscoped(),
391 include: [
392 {
393 required: true,
394 attributes: [ 'id' ],
395 model: VideoModel.unscoped(),
396 where: {
397 id: videoId
398 }
399 }
400 ]
401 }
402 ]
403 }
404 ]
405 }
406
407 return UserModel.findOne(query)
408 }
409
410 static loadByVideoImportId (videoImportId: number) {
411 const query = {
412 include: [
413 {
414 required: true,
415 attributes: [ 'id' ],
416 model: VideoImportModel.unscoped(),
417 where: {
418 id: videoImportId
419 }
420 }
421 ]
422 }
423
424 return UserModel.findOne(query)
425 }
426
427 static getOriginalVideoFileTotalFromUser (user: UserModel) {
428 // Don't use sequelize because we need to use a sub query
429 const query = UserModel.generateUserQuotaBaseSQL()
430
431 return UserModel.getTotalRawQuery(query, user.id)
432 }
433
434 // Returns cumulative size of all video files uploaded in the last 24 hours.
435 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
436 // Don't use sequelize because we need to use a sub query
437 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
438
439 return UserModel.getTotalRawQuery(query, user.id)
440 }
441
442 static async getStats () {
443 const totalUsers = await UserModel.count()
444
445 return {
446 totalUsers
447 }
448 }
449
450 static autoComplete (search: string) {
451 const query = {
452 where: {
453 username: {
454 [ Sequelize.Op.like ]: `%${search}%`
455 }
456 },
457 limit: 10
458 }
459
460 return UserModel.findAll(query)
461 .then(u => u.map(u => u.username))
462 }
463
464 hasRight (right: UserRight) {
465 return hasUserRight(this.role, right)
466 }
467
468 isPasswordMatch (password: string) {
469 return comparePassword(password, this.password)
470 }
471
472 toFormattedJSON (): User {
473 const videoQuotaUsed = this.get('videoQuotaUsed')
474 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
475
476 const json = {
477 id: this.id,
478 username: this.username,
479 email: this.email,
480 emailVerified: this.emailVerified,
481 nsfwPolicy: this.nsfwPolicy,
482 webTorrentEnabled: this.webTorrentEnabled,
483 videosHistoryEnabled: this.videosHistoryEnabled,
484 autoPlayVideo: this.autoPlayVideo,
485 role: this.role,
486 roleLabel: USER_ROLE_LABELS[ this.role ],
487 videoQuota: this.videoQuota,
488 videoQuotaDaily: this.videoQuotaDaily,
489 createdAt: this.createdAt,
490 blocked: this.blocked,
491 blockedReason: this.blockedReason,
492 account: this.Account.toFormattedJSON(),
493 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
494 videoChannels: [],
495 videoQuotaUsed: videoQuotaUsed !== undefined
496 ? parseInt(videoQuotaUsed, 10)
497 : undefined,
498 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
499 ? parseInt(videoQuotaUsedDaily, 10)
500 : undefined
501 }
502
503 if (Array.isArray(this.Account.VideoChannels) === true) {
504 json.videoChannels = this.Account.VideoChannels
505 .map(c => c.toFormattedJSON())
506 .sort((v1, v2) => {
507 if (v1.createdAt < v2.createdAt) return -1
508 if (v1.createdAt === v2.createdAt) return 0
509
510 return 1
511 })
512 }
513
514 return json
515 }
516
517 async isAbleToUploadVideo (videoFile: { size: number }) {
518 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
519
520 const [ totalBytes, totalBytesDaily ] = await Promise.all([
521 UserModel.getOriginalVideoFileTotalFromUser(this),
522 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
523 ])
524
525 const uploadedTotal = videoFile.size + totalBytes
526 const uploadedDaily = videoFile.size + totalBytesDaily
527 if (this.videoQuotaDaily === -1) {
528 return uploadedTotal < this.videoQuota
529 }
530 if (this.videoQuota === -1) {
531 return uploadedDaily < this.videoQuotaDaily
532 }
533
534 return (uploadedTotal < this.videoQuota) &&
535 (uploadedDaily < this.videoQuotaDaily)
536 }
537
538 private static generateUserQuotaBaseSQL (where?: string) {
539 const andWhere = where ? 'AND ' + where : ''
540
541 return 'SELECT SUM("size") AS "total" ' +
542 'FROM (' +
543 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
544 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
545 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
546 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
547 'WHERE "account"."userId" = $userId ' + andWhere +
548 'GROUP BY "video"."id"' +
549 ') t'
550 }
551
552 private static getTotalRawQuery (query: string, userId: number) {
553 const options = {
554 bind: { userId },
555 type: Sequelize.QueryTypes.SELECT
556 }
557
558 return UserModel.sequelize.query(query, options)
559 .then(([ { total } ]) => {
560 if (total === null) return 0
561
562 return parseInt(total, 10)
563 })
564 }
565 }