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