]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Don't expose constants directly in initializers/
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
e02643f3 1import * as Sequelize from 'sequelize'
3fd3ab2d 2import {
d175a6f7 3 AfterDestroy,
f201a749 4 AfterUpdate,
a73c582e
C
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
3fd3ab2d 21} from 'sequelize-typescript'
e34c85e5 22import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
ba75d268 23import { User, UserRole } from '../../../shared/models/users'
65fcc311 24import {
a73c582e 25 isUserAutoPlayVideoValid,
eacb25c4 26 isUserBlockedReasonValid,
e6921918 27 isUserBlockedValid,
d9eaee39 28 isUserEmailVerifiedValid,
5cf84858 29 isUserNSFWPolicyValid,
a73c582e
C
30 isUserPasswordValid,
31 isUserRoleValid,
32 isUserUsernameValid,
5cf84858 33 isUserVideoQuotaDailyValid,
64cc5e85 34 isUserVideoQuotaValid,
cef534ed
C
35 isUserVideosHistoryEnabledValid,
36 isUserWebTorrentEnabledValid
3fd3ab2d 37} from '../../helpers/custom-validators/users'
da854ddd 38import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
39import { OAuthTokenModel } from '../oauth/oauth-token'
40import { getSort, throwIfNotValid } from '../utils'
41import { VideoChannelModel } from '../video/video-channel'
42import { AccountModel } from './account'
0883b324
C
43import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
44import { values } from 'lodash'
74dc3bca 45import { NSFW_POLICY_TYPES } from '../../initializers/constants'
f201a749 46import { clearCacheByUserId } from '../../lib/oauth-model'
cef534ed
C
47import { UserNotificationSettingModel } from './user-notification-setting'
48import { VideoModel } from '../video/video'
49import { ActorModel } from '../activitypub/actor'
50import { ActorFollowModel } from '../activitypub/actor-follow'
dc133480 51import { VideoImportModel } from '../video/video-import'
3fd3ab2d 52
9c2e0dbf
C
53enum ScopeNames {
54 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
55}
56
d48ff09d
C
57@DefaultScope({
58 include: [
59 {
60 model: () => AccountModel,
61 required: true
cef534ed
C
62 },
63 {
64 model: () => UserNotificationSettingModel,
65 required: true
d48ff09d
C
66 }
67 ]
68})
69@Scopes({
9c2e0dbf 70 [ScopeNames.WITH_VIDEO_CHANNEL]: {
d48ff09d
C
71 include: [
72 {
73 model: () => AccountModel,
74 required: true,
75 include: [ () => VideoChannelModel ]
cef534ed
C
76 },
77 {
78 model: () => UserNotificationSettingModel,
79 required: true
d48ff09d
C
80 }
81 ]
82 }
83})
3fd3ab2d
C
84@Table({
85 tableName: 'user',
86 indexes: [
feb4bdfd 87 {
3fd3ab2d
C
88 fields: [ 'username' ],
89 unique: true
feb4bdfd
C
90 },
91 {
3fd3ab2d
C
92 fields: [ 'email' ],
93 unique: true
feb4bdfd 94 }
e02643f3 95 ]
3fd3ab2d
C
96})
97export 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
d9eaee39
JM
114 @AllowNull(true)
115 @Default(null)
116 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
117 @Column
118 emailVerified: boolean
119
3fd3ab2d 120 @AllowNull(false)
0883b324
C
121 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
122 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
123 nsfwPolicy: NSFWPolicyType
3fd3ab2d 124
64cc5e85 125 @AllowNull(false)
0229b014 126 @Default(true)
ed638e53
RK
127 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
128 @Column
129 webTorrentEnabled: boolean
64cc5e85 130
8b9a525a
C
131 @AllowNull(false)
132 @Default(true)
133 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
134 @Column
135 videosHistoryEnabled: boolean
136
7efe153b
AL
137 @AllowNull(false)
138 @Default(true)
139 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
140 @Column
141 autoPlayVideo: boolean
142
e6921918
C
143 @AllowNull(false)
144 @Default(false)
145 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
146 @Column
147 blocked: boolean
148
eacb25c4
C
149 @AllowNull(true)
150 @Default(null)
151 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
152 @Column
153 blockedReason: string
154
3fd3ab2d
C
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
bee0abff
FA
165 @AllowNull(false)
166 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
167 @Column(DataType.BIGINT)
168 videoQuotaDaily: number
169
3fd3ab2d
C
170 @CreatedAt
171 createdAt: Date
172
173 @UpdatedAt
174 updatedAt: Date
175
176 @HasOne(() => AccountModel, {
177 foreignKey: 'userId',
f05a1c30
C
178 onDelete: 'cascade',
179 hooks: true
3fd3ab2d
C
180 })
181 Account: AccountModel
69b0a27c 182
cef534ed
C
183 @HasOne(() => UserNotificationSettingModel, {
184 foreignKey: 'userId',
185 onDelete: 'cascade',
186 hooks: true
187 })
188 NotificationSetting: UserNotificationSettingModel
189
dc133480
C
190 @HasMany(() => VideoImportModel, {
191 foreignKey: 'userId',
192 onDelete: 'cascade'
193 })
194 VideoImports: VideoImportModel[]
195
3fd3ab2d
C
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 }
59557c46 212 }
26d7d31b 213
f201a749 214 @AfterUpdate
d175a6f7 215 @AfterDestroy
f201a749
C
216 static removeTokenCache (instance: UserModel) {
217 return clearCacheByUserId(instance.id)
218 }
219
3fd3ab2d
C
220 static countTotal () {
221 return this.count()
222 }
954605a8 223
24b9417c
C
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
3fd3ab2d 243 const query = {
a76138ff
C
244 attributes: {
245 include: [
246 [
247 Sequelize.literal(
248 '(' +
8b604880
C
249 'SELECT COALESCE(SUM("size"), 0) ' +
250 'FROM (' +
a76138ff
C
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 },
3fd3ab2d
C
263 offset: start,
264 limit: count,
24b9417c
C
265 order: getSort(sort),
266 where
3fd3ab2d 267 }
72c7248b 268
3fd3ab2d
C
269 return UserModel.findAndCountAll(query)
270 .then(({ rows, count }) => {
271 return {
272 data: rows,
273 total: count
274 }
72c7248b 275 })
72c7248b
C
276 }
277
cef534ed 278 static listWithRight (right: UserRight) {
ba75d268
C
279 const roles = Object.keys(USER_ROLE_LABELS)
280 .map(k => parseInt(k, 10) as UserRole)
281 .filter(role => hasUserRight(role, right))
282
ba75d268 283 const query = {
ba75d268
C
284 where: {
285 role: {
286 [Sequelize.Op.in]: roles
287 }
288 }
289 }
290
cef534ed
C
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)
ba75d268
C
331 }
332
f7cc67b4
C
333 static listByUsernames (usernames: string[]) {
334 const query = {
335 where: {
336 username: usernames
337 }
338 }
339
340 return UserModel.findAll(query)
341 }
342
3fd3ab2d 343 static loadById (id: number) {
9b39106d 344 return UserModel.findByPk(id)
3fd3ab2d 345 }
feb4bdfd 346
3fd3ab2d
C
347 static loadByUsername (username: string) {
348 const query = {
349 where: {
350 username
d48ff09d 351 }
3fd3ab2d 352 }
089ff2f2 353
3fd3ab2d 354 return UserModel.findOne(query)
feb4bdfd
C
355 }
356
3fd3ab2d
C
357 static loadByUsernameAndPopulateChannels (username: string) {
358 const query = {
359 where: {
360 username
d48ff09d 361 }
3fd3ab2d 362 }
9bd26629 363
9c2e0dbf 364 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
feb4bdfd
C
365 }
366
ecb4e35f
C
367 static loadByEmail (email: string) {
368 const query = {
369 where: {
370 email
371 }
372 }
373
374 return UserModel.findOne(query)
375 }
376
ba12e8b3
C
377 static loadByUsernameOrEmail (username: string, email?: string) {
378 if (!email) email = username
379
3fd3ab2d 380 const query = {
3fd3ab2d
C
381 where: {
382 [ Sequelize.Op.or ]: [ { username }, { email } ]
383 }
6fcd19ba 384 }
69b0a27c 385
d48ff09d 386 return UserModel.findOne(query)
72c7248b
C
387 }
388
cef534ed
C
389 static loadByVideoId (videoId: number) {
390 const query = {
391 include: [
392 {
393 required: true,
394 attributes: [ 'id' ],
395 model: AccountModel.unscoped(),
396 include: [
397 {
398 required: true,
399 attributes: [ 'id' ],
400 model: VideoChannelModel.unscoped(),
401 include: [
402 {
403 required: true,
404 attributes: [ 'id' ],
405 model: VideoModel.unscoped(),
406 where: {
407 id: videoId
408 }
409 }
410 ]
411 }
412 ]
413 }
414 ]
415 }
416
417 return UserModel.findOne(query)
418 }
419
dc133480
C
420 static loadByVideoImportId (videoImportId: number) {
421 const query = {
422 include: [
423 {
424 required: true,
425 attributes: [ 'id' ],
426 model: VideoImportModel.unscoped(),
427 where: {
428 id: videoImportId
429 }
430 }
431 ]
432 }
433
434 return UserModel.findOne(query)
435 }
436
f7cc67b4
C
437 static loadByChannelActorId (videoChannelActorId: number) {
438 const query = {
439 include: [
440 {
441 required: true,
442 attributes: [ 'id' ],
443 model: AccountModel.unscoped(),
444 include: [
445 {
446 required: true,
447 attributes: [ 'id' ],
448 model: VideoChannelModel.unscoped(),
449 where: {
450 actorId: videoChannelActorId
451 }
452 }
453 ]
454 }
455 ]
456 }
457
458 return UserModel.findOne(query)
459 }
460
461 static loadByAccountActorId (accountActorId: number) {
462 const query = {
463 include: [
464 {
465 required: true,
466 attributes: [ 'id' ],
467 model: AccountModel.unscoped(),
468 where: {
469 actorId: accountActorId
470 }
471 }
472 ]
473 }
474
475 return UserModel.findOne(query)
476 }
477
ce5496d6 478 static getOriginalVideoFileTotalFromUser (user: UserModel) {
3fd3ab2d 479 // Don't use sequelize because we need to use a sub query
8b604880 480 const query = UserModel.generateUserQuotaBaseSQL()
bee0abff 481
8b604880 482 return UserModel.getTotalRawQuery(query, user.id)
bee0abff
FA
483 }
484
8b604880 485 // Returns cumulative size of all video files uploaded in the last 24 hours.
bee0abff
FA
486 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
487 // Don't use sequelize because we need to use a sub query
8b604880 488 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
68a3b9f2 489
8b604880 490 return UserModel.getTotalRawQuery(query, user.id)
72c7248b
C
491 }
492
09cababd
C
493 static async getStats () {
494 const totalUsers = await UserModel.count()
495
496 return {
497 totalUsers
498 }
499 }
500
5cf84858
C
501 static autoComplete (search: string) {
502 const query = {
503 where: {
504 username: {
505 [ Sequelize.Op.like ]: `%${search}%`
506 }
507 },
508 limit: 10
509 }
510
511 return UserModel.findAll(query)
512 .then(u => u.map(u => u.username))
513 }
514
3fd3ab2d
C
515 hasRight (right: UserRight) {
516 return hasUserRight(this.role, right)
517 }
72c7248b 518
3fd3ab2d
C
519 isPasswordMatch (password: string) {
520 return comparePassword(password, this.password)
feb4bdfd
C
521 }
522
c5911fd3 523 toFormattedJSON (): User {
a76138ff 524 const videoQuotaUsed = this.get('videoQuotaUsed')
bee0abff 525 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
a76138ff 526
3fd3ab2d
C
527 const json = {
528 id: this.id,
529 username: this.username,
530 email: this.email,
d9eaee39 531 emailVerified: this.emailVerified,
0883b324 532 nsfwPolicy: this.nsfwPolicy,
ed638e53 533 webTorrentEnabled: this.webTorrentEnabled,
276d9652 534 videosHistoryEnabled: this.videosHistoryEnabled,
7efe153b 535 autoPlayVideo: this.autoPlayVideo,
3fd3ab2d
C
536 role: this.role,
537 roleLabel: USER_ROLE_LABELS[ this.role ],
538 videoQuota: this.videoQuota,
bee0abff 539 videoQuotaDaily: this.videoQuotaDaily,
3fd3ab2d 540 createdAt: this.createdAt,
eacb25c4
C
541 blocked: this.blocked,
542 blockedReason: this.blockedReason,
c5911fd3 543 account: this.Account.toFormattedJSON(),
cef534ed 544 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
a76138ff 545 videoChannels: [],
bee0abff
FA
546 videoQuotaUsed: videoQuotaUsed !== undefined
547 ? parseInt(videoQuotaUsed, 10)
548 : undefined,
549 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
550 ? parseInt(videoQuotaUsedDaily, 10)
551 : undefined
3fd3ab2d
C
552 }
553
554 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 555 json.videoChannels = this.Account.VideoChannels
3fd3ab2d
C
556 .map(c => c.toFormattedJSON())
557 .sort((v1, v2) => {
558 if (v1.createdAt < v2.createdAt) return -1
559 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 560
3fd3ab2d
C
561 return 1
562 })
ad4a8a1c 563 }
3fd3ab2d
C
564
565 return json
ad4a8a1c
C
566 }
567
bee0abff
FA
568 async isAbleToUploadVideo (videoFile: { size: number }) {
569 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
b0f9f39e 570
bee0abff
FA
571 const [ totalBytes, totalBytesDaily ] = await Promise.all([
572 UserModel.getOriginalVideoFileTotalFromUser(this),
573 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
574 ])
575
576 const uploadedTotal = videoFile.size + totalBytes
577 const uploadedDaily = videoFile.size + totalBytesDaily
578 if (this.videoQuotaDaily === -1) {
579 return uploadedTotal < this.videoQuota
580 }
581 if (this.videoQuota === -1) {
582 return uploadedDaily < this.videoQuotaDaily
583 }
584
585 return (uploadedTotal < this.videoQuota) &&
586 (uploadedDaily < this.videoQuotaDaily)
b0f9f39e 587 }
8b604880
C
588
589 private static generateUserQuotaBaseSQL (where?: string) {
590 const andWhere = where ? 'AND ' + where : ''
591
592 return 'SELECT SUM("size") AS "total" ' +
593 'FROM (' +
594 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
595 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
596 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
597 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
598 'WHERE "account"."userId" = $userId ' + andWhere +
599 'GROUP BY "video"."id"' +
600 ') t'
601 }
602
603 private static getTotalRawQuery (query: string, userId: number) {
604 const options = {
605 bind: { userId },
606 type: Sequelize.QueryTypes.SELECT
607 }
608
609 return UserModel.sequelize.query(query, options)
610 .then(([ { total } ]) => {
611 if (total === null) return 0
612
613 return parseInt(total, 10)
614 })
615 }
b0f9f39e 616}