]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user/user.ts
Breaking API: Consistency with role id/label
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
1 import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } 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 IsUUID,
18 Model,
19 Scopes,
20 Table,
21 UpdatedAt
22 } from 'sequelize-typescript'
23 import { TokensCache } from '@server/lib/auth/tokens-cache'
24 import { LiveQuotaStore } from '@server/lib/live'
25 import {
26 MMyUserFormattable,
27 MUser,
28 MUserDefault,
29 MUserFormattable,
30 MUserNotifSettingChannelDefault,
31 MUserWithNotificationSetting
32 } from '@server/types/models'
33 import { AttributesOnly } from '@shared/typescript-utils'
34 import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
35 import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models'
36 import { User, UserRole } from '../../../shared/models/users'
37 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
40 import {
41 isUserAdminFlagsValid,
42 isUserAutoPlayNextVideoPlaylistValid,
43 isUserAutoPlayNextVideoValid,
44 isUserAutoPlayVideoValid,
45 isUserBlockedReasonValid,
46 isUserBlockedValid,
47 isUserEmailVerifiedValid,
48 isUserNoModal,
49 isUserNSFWPolicyValid,
50 isUserP2PEnabledValid,
51 isUserPasswordValid,
52 isUserRoleValid,
53 isUserVideoLanguages,
54 isUserVideoQuotaDailyValid,
55 isUserVideoQuotaValid,
56 isUserVideosHistoryEnabledValid
57 } from '../../helpers/custom-validators/users'
58 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
59 import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
60 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
61 import { AccountModel } from '../account/account'
62 import { ActorModel } from '../actor/actor'
63 import { ActorFollowModel } from '../actor/actor-follow'
64 import { ActorImageModel } from '../actor/actor-image'
65 import { OAuthTokenModel } from '../oauth/oauth-token'
66 import { getAdminUsersSort, throwIfNotValid } from '../utils'
67 import { VideoModel } from '../video/video'
68 import { VideoChannelModel } from '../video/video-channel'
69 import { VideoImportModel } from '../video/video-import'
70 import { VideoLiveModel } from '../video/video-live'
71 import { VideoPlaylistModel } from '../video/video-playlist'
72 import { UserNotificationSettingModel } from './user-notification-setting'
73
74 enum ScopeNames {
75 FOR_ME_API = 'FOR_ME_API',
76 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
77 WITH_QUOTA = 'WITH_QUOTA',
78 WITH_STATS = 'WITH_STATS'
79 }
80
81 @DefaultScope(() => ({
82 include: [
83 {
84 model: AccountModel,
85 required: true
86 },
87 {
88 model: UserNotificationSettingModel,
89 required: true
90 }
91 ]
92 }))
93 @Scopes(() => ({
94 [ScopeNames.FOR_ME_API]: {
95 include: [
96 {
97 model: AccountModel,
98 include: [
99 {
100 model: VideoChannelModel.unscoped(),
101 include: [
102 {
103 model: ActorModel,
104 required: true,
105 include: [
106 {
107 model: ActorImageModel,
108 as: 'Banners',
109 required: false
110 }
111 ]
112 }
113 ]
114 },
115 {
116 attributes: [ 'id', 'name', 'type' ],
117 model: VideoPlaylistModel.unscoped(),
118 required: true,
119 where: {
120 type: {
121 [Op.ne]: VideoPlaylistType.REGULAR
122 }
123 }
124 }
125 ]
126 },
127 {
128 model: UserNotificationSettingModel,
129 required: true
130 }
131 ]
132 },
133 [ScopeNames.WITH_VIDEOCHANNELS]: {
134 include: [
135 {
136 model: AccountModel,
137 include: [
138 {
139 model: VideoChannelModel
140 },
141 {
142 attributes: [ 'id', 'name', 'type' ],
143 model: VideoPlaylistModel.unscoped(),
144 required: true,
145 where: {
146 type: {
147 [Op.ne]: VideoPlaylistType.REGULAR
148 }
149 }
150 }
151 ]
152 }
153 ]
154 },
155 [ScopeNames.WITH_QUOTA]: {
156 attributes: {
157 include: [
158 [
159 literal(
160 '(' +
161 UserModel.generateUserQuotaBaseSQL({
162 withSelect: false,
163 whereUserId: '"UserModel"."id"',
164 daily: false
165 }) +
166 ')'
167 ),
168 'videoQuotaUsed'
169 ],
170 [
171 literal(
172 '(' +
173 UserModel.generateUserQuotaBaseSQL({
174 withSelect: false,
175 whereUserId: '"UserModel"."id"',
176 daily: true
177 }) +
178 ')'
179 ),
180 'videoQuotaUsedDaily'
181 ]
182 ]
183 }
184 },
185 [ScopeNames.WITH_STATS]: {
186 attributes: {
187 include: [
188 [
189 literal(
190 '(' +
191 'SELECT COUNT("video"."id") ' +
192 'FROM "video" ' +
193 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
194 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
195 'WHERE "account"."userId" = "UserModel"."id"' +
196 ')'
197 ),
198 'videosCount'
199 ],
200 [
201 literal(
202 '(' +
203 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
204 'FROM (' +
205 'SELECT COUNT("abuse"."id") AS "abuses", ' +
206 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
207 'FROM "abuse" ' +
208 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
209 'WHERE "account"."userId" = "UserModel"."id"' +
210 ') t' +
211 ')'
212 ),
213 'abusesCount'
214 ],
215 [
216 literal(
217 '(' +
218 'SELECT COUNT("abuse"."id") ' +
219 'FROM "abuse" ' +
220 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
221 'WHERE "account"."userId" = "UserModel"."id"' +
222 ')'
223 ),
224 'abusesCreatedCount'
225 ],
226 [
227 literal(
228 '(' +
229 'SELECT COUNT("videoComment"."id") ' +
230 'FROM "videoComment" ' +
231 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
232 'WHERE "account"."userId" = "UserModel"."id"' +
233 ')'
234 ),
235 'videoCommentsCount'
236 ]
237 ]
238 }
239 }
240 }))
241 @Table({
242 tableName: 'user',
243 indexes: [
244 {
245 fields: [ 'username' ],
246 unique: true
247 },
248 {
249 fields: [ 'email' ],
250 unique: true
251 }
252 ]
253 })
254 export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
255
256 @AllowNull(true)
257 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
258 @Column
259 password: string
260
261 @AllowNull(false)
262 @Column
263 username: string
264
265 @AllowNull(false)
266 @IsEmail
267 @Column(DataType.STRING(400))
268 email: string
269
270 @AllowNull(true)
271 @IsEmail
272 @Column(DataType.STRING(400))
273 pendingEmail: string
274
275 @AllowNull(true)
276 @Default(null)
277 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
278 @Column
279 emailVerified: boolean
280
281 @AllowNull(false)
282 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
283 @Column(DataType.ENUM(...Object.values(NSFW_POLICY_TYPES)))
284 nsfwPolicy: NSFWPolicyType
285
286 @AllowNull(false)
287 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
288 @Column
289 p2pEnabled: boolean
290
291 @AllowNull(false)
292 @Default(true)
293 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
294 @Column
295 videosHistoryEnabled: boolean
296
297 @AllowNull(false)
298 @Default(true)
299 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
300 @Column
301 autoPlayVideo: boolean
302
303 @AllowNull(false)
304 @Default(false)
305 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
306 @Column
307 autoPlayNextVideo: boolean
308
309 @AllowNull(false)
310 @Default(true)
311 @Is(
312 'UserAutoPlayNextVideoPlaylist',
313 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
314 )
315 @Column
316 autoPlayNextVideoPlaylist: boolean
317
318 @AllowNull(true)
319 @Default(null)
320 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
321 @Column(DataType.ARRAY(DataType.STRING))
322 videoLanguages: string[]
323
324 @AllowNull(false)
325 @Default(UserAdminFlag.NONE)
326 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
327 @Column
328 adminFlags?: UserAdminFlag
329
330 @AllowNull(false)
331 @Default(false)
332 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
333 @Column
334 blocked: boolean
335
336 @AllowNull(true)
337 @Default(null)
338 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
339 @Column
340 blockedReason: string
341
342 @AllowNull(false)
343 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
344 @Column
345 role: number
346
347 @AllowNull(false)
348 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
349 @Column(DataType.BIGINT)
350 videoQuota: number
351
352 @AllowNull(false)
353 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
354 @Column(DataType.BIGINT)
355 videoQuotaDaily: number
356
357 @AllowNull(false)
358 @Default(DEFAULT_USER_THEME_NAME)
359 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
360 @Column
361 theme: string
362
363 @AllowNull(false)
364 @Default(false)
365 @Is(
366 'UserNoInstanceConfigWarningModal',
367 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
368 )
369 @Column
370 noInstanceConfigWarningModal: boolean
371
372 @AllowNull(false)
373 @Default(false)
374 @Is(
375 'UserNoWelcomeModal',
376 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
377 )
378 @Column
379 noWelcomeModal: boolean
380
381 @AllowNull(false)
382 @Default(false)
383 @Is(
384 'UserNoAccountSetupWarningModal',
385 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
386 )
387 @Column
388 noAccountSetupWarningModal: boolean
389
390 @AllowNull(true)
391 @Default(null)
392 @Column
393 pluginAuth: string
394
395 @AllowNull(false)
396 @Default(DataType.UUIDV4)
397 @IsUUID(4)
398 @Column(DataType.UUID)
399 feedToken: string
400
401 @AllowNull(true)
402 @Default(null)
403 @Column
404 lastLoginDate: Date
405
406 @AllowNull(true)
407 @Default(null)
408 @Column
409 otpSecret: string
410
411 @CreatedAt
412 createdAt: Date
413
414 @UpdatedAt
415 updatedAt: Date
416
417 @HasOne(() => AccountModel, {
418 foreignKey: 'userId',
419 onDelete: 'cascade',
420 hooks: true
421 })
422 Account: AccountModel
423
424 @HasOne(() => UserNotificationSettingModel, {
425 foreignKey: 'userId',
426 onDelete: 'cascade',
427 hooks: true
428 })
429 NotificationSetting: UserNotificationSettingModel
430
431 @HasMany(() => VideoImportModel, {
432 foreignKey: 'userId',
433 onDelete: 'cascade'
434 })
435 VideoImports: VideoImportModel[]
436
437 @HasMany(() => OAuthTokenModel, {
438 foreignKey: 'userId',
439 onDelete: 'cascade'
440 })
441 OAuthTokens: OAuthTokenModel[]
442
443 @BeforeCreate
444 @BeforeUpdate
445 static cryptPasswordIfNeeded (instance: UserModel) {
446 if (instance.changed('password') && instance.password) {
447 return cryptPassword(instance.password)
448 .then(hash => {
449 instance.password = hash
450 return undefined
451 })
452 }
453 }
454
455 @AfterUpdate
456 @AfterDestroy
457 static removeTokenCache (instance: UserModel) {
458 return TokensCache.Instance.clearCacheByUserId(instance.id)
459 }
460
461 static countTotal () {
462 return this.count()
463 }
464
465 static listForAdminApi (parameters: {
466 start: number
467 count: number
468 sort: string
469 search?: string
470 blocked?: boolean
471 }) {
472 const { start, count, sort, search, blocked } = parameters
473 const where: WhereOptions = {}
474
475 if (search) {
476 Object.assign(where, {
477 [Op.or]: [
478 {
479 email: {
480 [Op.iLike]: '%' + search + '%'
481 }
482 },
483 {
484 username: {
485 [Op.iLike]: '%' + search + '%'
486 }
487 }
488 ]
489 })
490 }
491
492 if (blocked !== undefined) {
493 Object.assign(where, { blocked })
494 }
495
496 const query: FindOptions = {
497 offset: start,
498 limit: count,
499 order: getAdminUsersSort(sort),
500 where
501 }
502
503 return Promise.all([
504 UserModel.unscoped().count(query),
505 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
506 ]).then(([ total, data ]) => ({ total, data }))
507 }
508
509 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
510 const roles = Object.keys(USER_ROLE_LABELS)
511 .map(k => parseInt(k, 10) as UserRole)
512 .filter(role => hasUserRight(role, right))
513
514 const query = {
515 where: {
516 role: {
517 [Op.in]: roles
518 }
519 }
520 }
521
522 return UserModel.findAll(query)
523 }
524
525 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
526 const query = {
527 include: [
528 {
529 model: UserNotificationSettingModel.unscoped(),
530 required: true
531 },
532 {
533 attributes: [ 'userId' ],
534 model: AccountModel.unscoped(),
535 required: true,
536 include: [
537 {
538 attributes: [],
539 model: ActorModel.unscoped(),
540 required: true,
541 where: {
542 serverId: null
543 },
544 include: [
545 {
546 attributes: [],
547 as: 'ActorFollowings',
548 model: ActorFollowModel.unscoped(),
549 required: true,
550 where: {
551 targetActorId: actorId
552 }
553 }
554 ]
555 }
556 ]
557 }
558 ]
559 }
560
561 return UserModel.unscoped().findAll(query)
562 }
563
564 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
565 const query = {
566 where: {
567 username: usernames
568 }
569 }
570
571 return UserModel.findAll(query)
572 }
573
574 static loadById (id: number): Promise<MUser> {
575 return UserModel.unscoped().findByPk(id)
576 }
577
578 static loadByIdFull (id: number): Promise<MUserDefault> {
579 return UserModel.findByPk(id)
580 }
581
582 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
583 const scopes = [
584 ScopeNames.WITH_VIDEOCHANNELS
585 ]
586
587 if (withStats) {
588 scopes.push(ScopeNames.WITH_QUOTA)
589 scopes.push(ScopeNames.WITH_STATS)
590 }
591
592 return UserModel.scope(scopes).findByPk(id)
593 }
594
595 static loadByUsername (username: string): Promise<MUserDefault> {
596 const query = {
597 where: {
598 username
599 }
600 }
601
602 return UserModel.findOne(query)
603 }
604
605 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
606 const query = {
607 where: {
608 id
609 }
610 }
611
612 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
613 }
614
615 static loadByEmail (email: string): Promise<MUserDefault> {
616 const query = {
617 where: {
618 email
619 }
620 }
621
622 return UserModel.findOne(query)
623 }
624
625 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
626 if (!email) email = username
627
628 const query = {
629 where: {
630 [Op.or]: [
631 where(fn('lower', col('username')), fn('lower', username) as any),
632
633 { email }
634 ]
635 }
636 }
637
638 return UserModel.findOne(query)
639 }
640
641 static loadByVideoId (videoId: number): Promise<MUserDefault> {
642 const query = {
643 include: [
644 {
645 required: true,
646 attributes: [ 'id' ],
647 model: AccountModel.unscoped(),
648 include: [
649 {
650 required: true,
651 attributes: [ 'id' ],
652 model: VideoChannelModel.unscoped(),
653 include: [
654 {
655 required: true,
656 attributes: [ 'id' ],
657 model: VideoModel.unscoped(),
658 where: {
659 id: videoId
660 }
661 }
662 ]
663 }
664 ]
665 }
666 ]
667 }
668
669 return UserModel.findOne(query)
670 }
671
672 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
673 const query = {
674 include: [
675 {
676 required: true,
677 attributes: [ 'id' ],
678 model: VideoImportModel.unscoped(),
679 where: {
680 id: videoImportId
681 }
682 }
683 ]
684 }
685
686 return UserModel.findOne(query)
687 }
688
689 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
690 const query = {
691 include: [
692 {
693 required: true,
694 attributes: [ 'id' ],
695 model: AccountModel.unscoped(),
696 include: [
697 {
698 required: true,
699 attributes: [ 'id' ],
700 model: VideoChannelModel.unscoped(),
701 where: {
702 actorId: videoChannelActorId
703 }
704 }
705 ]
706 }
707 ]
708 }
709
710 return UserModel.findOne(query)
711 }
712
713 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
714 const query = {
715 include: [
716 {
717 required: true,
718 attributes: [ 'id' ],
719 model: AccountModel.unscoped(),
720 where: {
721 actorId: accountActorId
722 }
723 }
724 ]
725 }
726
727 return UserModel.findOne(query)
728 }
729
730 static loadByLiveId (liveId: number): Promise<MUser> {
731 const query = {
732 include: [
733 {
734 attributes: [ 'id' ],
735 model: AccountModel.unscoped(),
736 required: true,
737 include: [
738 {
739 attributes: [ 'id' ],
740 model: VideoChannelModel.unscoped(),
741 required: true,
742 include: [
743 {
744 attributes: [ 'id' ],
745 model: VideoModel.unscoped(),
746 required: true,
747 include: [
748 {
749 attributes: [],
750 model: VideoLiveModel.unscoped(),
751 required: true,
752 where: {
753 id: liveId
754 }
755 }
756 ]
757 }
758 ]
759 }
760 ]
761 }
762 ]
763 }
764
765 return UserModel.unscoped().findOne(query)
766 }
767
768 static generateUserQuotaBaseSQL (options: {
769 whereUserId: '$userId' | '"UserModel"."id"'
770 withSelect: boolean
771 daily: boolean
772 }) {
773 const andWhere = options.daily === true
774 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
775 : ''
776
777 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
778 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
779 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
780
781 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
782 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
783 videoChannelJoin
784
785 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
786 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
787 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
788 videoChannelJoin
789
790 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
791 'FROM (' +
792 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
793 'GROUP BY "t1"."videoId"' +
794 ') t2'
795 }
796
797 static getTotalRawQuery (query: string, userId: number) {
798 const options = {
799 bind: { userId },
800 type: QueryTypes.SELECT as QueryTypes.SELECT
801 }
802
803 return UserModel.sequelize.query<{ total: string }>(query, options)
804 .then(([ { total } ]) => {
805 if (total === null) return 0
806
807 return parseInt(total, 10)
808 })
809 }
810
811 static async getStats () {
812 function getActiveUsers (days: number) {
813 const query = {
814 where: {
815 [Op.and]: [
816 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
817 ]
818 }
819 }
820
821 return UserModel.unscoped().count(query)
822 }
823
824 const totalUsers = await UserModel.unscoped().count()
825 const totalDailyActiveUsers = await getActiveUsers(1)
826 const totalWeeklyActiveUsers = await getActiveUsers(7)
827 const totalMonthlyActiveUsers = await getActiveUsers(30)
828 const totalHalfYearActiveUsers = await getActiveUsers(180)
829
830 return {
831 totalUsers,
832 totalDailyActiveUsers,
833 totalWeeklyActiveUsers,
834 totalMonthlyActiveUsers,
835 totalHalfYearActiveUsers
836 }
837 }
838
839 static autoComplete (search: string) {
840 const query = {
841 where: {
842 username: {
843 [Op.like]: `%${search}%`
844 }
845 },
846 limit: 10
847 }
848
849 return UserModel.findAll(query)
850 .then(u => u.map(u => u.username))
851 }
852
853 hasRight (right: UserRight) {
854 return hasUserRight(this.role, right)
855 }
856
857 hasAdminFlag (flag: UserAdminFlag) {
858 return this.adminFlags & flag
859 }
860
861 isPasswordMatch (password: string) {
862 return comparePassword(password, this.password)
863 }
864
865 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
866 const videoQuotaUsed = this.get('videoQuotaUsed')
867 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
868 const videosCount = this.get('videosCount')
869 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
870 const abusesCreatedCount = this.get('abusesCreatedCount')
871 const videoCommentsCount = this.get('videoCommentsCount')
872
873 const json: User = {
874 id: this.id,
875 username: this.username,
876 email: this.email,
877 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
878
879 pendingEmail: this.pendingEmail,
880 emailVerified: this.emailVerified,
881
882 nsfwPolicy: this.nsfwPolicy,
883
884 // FIXME: deprecated in 4.1
885 webTorrentEnabled: this.p2pEnabled,
886 p2pEnabled: this.p2pEnabled,
887
888 videosHistoryEnabled: this.videosHistoryEnabled,
889 autoPlayVideo: this.autoPlayVideo,
890 autoPlayNextVideo: this.autoPlayNextVideo,
891 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
892 videoLanguages: this.videoLanguages,
893
894 role: {
895 id: this.role,
896 label: USER_ROLE_LABELS[this.role]
897 },
898
899 videoQuota: this.videoQuota,
900 videoQuotaDaily: this.videoQuotaDaily,
901
902 videoQuotaUsed: videoQuotaUsed !== undefined
903 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
904 : undefined,
905
906 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
907 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
908 : undefined,
909
910 videosCount: videosCount !== undefined
911 ? parseInt(videosCount + '', 10)
912 : undefined,
913 abusesCount: abusesCount
914 ? parseInt(abusesCount, 10)
915 : undefined,
916 abusesAcceptedCount: abusesAcceptedCount
917 ? parseInt(abusesAcceptedCount, 10)
918 : undefined,
919 abusesCreatedCount: abusesCreatedCount !== undefined
920 ? parseInt(abusesCreatedCount + '', 10)
921 : undefined,
922 videoCommentsCount: videoCommentsCount !== undefined
923 ? parseInt(videoCommentsCount + '', 10)
924 : undefined,
925
926 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
927 noWelcomeModal: this.noWelcomeModal,
928 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
929
930 blocked: this.blocked,
931 blockedReason: this.blockedReason,
932
933 account: this.Account.toFormattedJSON(),
934
935 notificationSettings: this.NotificationSetting
936 ? this.NotificationSetting.toFormattedJSON()
937 : undefined,
938
939 videoChannels: [],
940
941 createdAt: this.createdAt,
942
943 pluginAuth: this.pluginAuth,
944
945 lastLoginDate: this.lastLoginDate,
946
947 twoFactorEnabled: !!this.otpSecret
948 }
949
950 if (parameters.withAdminFlags) {
951 Object.assign(json, { adminFlags: this.adminFlags })
952 }
953
954 if (Array.isArray(this.Account.VideoChannels) === true) {
955 json.videoChannels = this.Account.VideoChannels
956 .map(c => c.toFormattedJSON())
957 .sort((v1, v2) => {
958 if (v1.createdAt < v2.createdAt) return -1
959 if (v1.createdAt === v2.createdAt) return 0
960
961 return 1
962 })
963 }
964
965 return json
966 }
967
968 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
969 const formatted = this.toFormattedJSON({ withAdminFlags: true })
970
971 const specialPlaylists = this.Account.VideoPlaylists
972 .map(p => ({ id: p.id, name: p.name, type: p.type }))
973
974 return Object.assign(formatted, { specialPlaylists })
975 }
976 }