]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/models/user/user.ts
Fix host advanced filter with channels
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
... / ...
CommitLineData
1import { values } from 'lodash'
2import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
3import {
4 AfterDestroy,
5 AfterUpdate,
6 AllowNull,
7 BeforeCreate,
8 BeforeUpdate,
9 Column,
10 CreatedAt,
11 DataType,
12 Default,
13 DefaultScope,
14 HasMany,
15 HasOne,
16 Is,
17 IsEmail,
18 IsUUID,
19 Model,
20 Scopes,
21 Table,
22 UpdatedAt
23} from 'sequelize-typescript'
24import { TokensCache } from '@server/lib/auth/tokens-cache'
25import { LiveQuotaStore } from '@server/lib/live'
26import {
27 MMyUserFormattable,
28 MUser,
29 MUserDefault,
30 MUserFormattable,
31 MUserNotifSettingChannelDefault,
32 MUserWithNotificationSetting
33} from '@server/types/models'
34import { AttributesOnly } from '@shared/typescript-utils'
35import { hasUserRight, USER_ROLE_LABELS } from '../../../shared/core-utils/users'
36import { AbuseState, MyUser, UserRight, VideoPlaylistType } from '../../../shared/models'
37import { User, UserRole } from '../../../shared/models/users'
38import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
39import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
40import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
41import {
42 isUserAdminFlagsValid,
43 isUserAutoPlayNextVideoPlaylistValid,
44 isUserAutoPlayNextVideoValid,
45 isUserAutoPlayVideoValid,
46 isUserBlockedReasonValid,
47 isUserBlockedValid,
48 isUserEmailVerifiedValid,
49 isUserNoModal,
50 isUserNSFWPolicyValid,
51 isUserP2PEnabledValid,
52 isUserPasswordValid,
53 isUserRoleValid,
54 isUserUsernameValid,
55 isUserVideoLanguages,
56 isUserVideoQuotaDailyValid,
57 isUserVideoQuotaValid,
58 isUserVideosHistoryEnabledValid
59} from '../../helpers/custom-validators/users'
60import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
61import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
62import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
63import { AccountModel } from '../account/account'
64import { ActorModel } from '../actor/actor'
65import { ActorFollowModel } from '../actor/actor-follow'
66import { ActorImageModel } from '../actor/actor-image'
67import { OAuthTokenModel } from '../oauth/oauth-token'
68import { getAdminUsersSort, throwIfNotValid } from '../utils'
69import { VideoModel } from '../video/video'
70import { VideoChannelModel } from '../video/video-channel'
71import { VideoImportModel } from '../video/video-import'
72import { VideoLiveModel } from '../video/video-live'
73import { VideoPlaylistModel } from '../video/video-playlist'
74import { UserNotificationSettingModel } from './user-notification-setting'
75
76enum ScopeNames {
77 FOR_ME_API = 'FOR_ME_API',
78 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
79 WITH_QUOTA = 'WITH_QUOTA',
80 WITH_STATS = 'WITH_STATS'
81}
82
83@DefaultScope(() => ({
84 include: [
85 {
86 model: AccountModel,
87 required: true
88 },
89 {
90 model: UserNotificationSettingModel,
91 required: true
92 }
93 ]
94}))
95@Scopes(() => ({
96 [ScopeNames.FOR_ME_API]: {
97 include: [
98 {
99 model: AccountModel,
100 include: [
101 {
102 model: VideoChannelModel.unscoped(),
103 include: [
104 {
105 model: ActorModel,
106 required: true,
107 include: [
108 {
109 model: ActorImageModel,
110 as: 'Banners',
111 required: false
112 }
113 ]
114 }
115 ]
116 },
117 {
118 attributes: [ 'id', 'name', 'type' ],
119 model: VideoPlaylistModel.unscoped(),
120 required: true,
121 where: {
122 type: {
123 [Op.ne]: VideoPlaylistType.REGULAR
124 }
125 }
126 }
127 ]
128 },
129 {
130 model: UserNotificationSettingModel,
131 required: true
132 }
133 ]
134 },
135 [ScopeNames.WITH_VIDEOCHANNELS]: {
136 include: [
137 {
138 model: AccountModel,
139 include: [
140 {
141 model: VideoChannelModel
142 },
143 {
144 attributes: [ 'id', 'name', 'type' ],
145 model: VideoPlaylistModel.unscoped(),
146 required: true,
147 where: {
148 type: {
149 [Op.ne]: VideoPlaylistType.REGULAR
150 }
151 }
152 }
153 ]
154 }
155 ]
156 },
157 [ScopeNames.WITH_QUOTA]: {
158 attributes: {
159 include: [
160 [
161 literal(
162 '(' +
163 UserModel.generateUserQuotaBaseSQL({
164 withSelect: false,
165 whereUserId: '"UserModel"."id"',
166 daily: false
167 }) +
168 ')'
169 ),
170 'videoQuotaUsed'
171 ],
172 [
173 literal(
174 '(' +
175 UserModel.generateUserQuotaBaseSQL({
176 withSelect: false,
177 whereUserId: '"UserModel"."id"',
178 daily: true
179 }) +
180 ')'
181 ),
182 'videoQuotaUsedDaily'
183 ]
184 ]
185 }
186 },
187 [ScopeNames.WITH_STATS]: {
188 attributes: {
189 include: [
190 [
191 literal(
192 '(' +
193 'SELECT COUNT("video"."id") ' +
194 'FROM "video" ' +
195 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
196 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
197 'WHERE "account"."userId" = "UserModel"."id"' +
198 ')'
199 ),
200 'videosCount'
201 ],
202 [
203 literal(
204 '(' +
205 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
206 'FROM (' +
207 'SELECT COUNT("abuse"."id") AS "abuses", ' +
208 `COUNT("abuse"."id") FILTER (WHERE "abuse"."state" = ${AbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
209 'FROM "abuse" ' +
210 'INNER JOIN "account" ON "account"."id" = "abuse"."flaggedAccountId" ' +
211 'WHERE "account"."userId" = "UserModel"."id"' +
212 ') t' +
213 ')'
214 ),
215 'abusesCount'
216 ],
217 [
218 literal(
219 '(' +
220 'SELECT COUNT("abuse"."id") ' +
221 'FROM "abuse" ' +
222 'INNER JOIN "account" ON "account"."id" = "abuse"."reporterAccountId" ' +
223 'WHERE "account"."userId" = "UserModel"."id"' +
224 ')'
225 ),
226 'abusesCreatedCount'
227 ],
228 [
229 literal(
230 '(' +
231 'SELECT COUNT("videoComment"."id") ' +
232 'FROM "videoComment" ' +
233 'INNER JOIN "account" ON "account"."id" = "videoComment"."accountId" ' +
234 'WHERE "account"."userId" = "UserModel"."id"' +
235 ')'
236 ),
237 'videoCommentsCount'
238 ]
239 ]
240 }
241 }
242}))
243@Table({
244 tableName: 'user',
245 indexes: [
246 {
247 fields: [ 'username' ],
248 unique: true
249 },
250 {
251 fields: [ 'email' ],
252 unique: true
253 }
254 ]
255})
256export class UserModel extends Model<Partial<AttributesOnly<UserModel>>> {
257
258 @AllowNull(true)
259 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password', true))
260 @Column
261 password: string
262
263 @AllowNull(false)
264 @Is('UserUsername', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
265 @Column
266 username: string
267
268 @AllowNull(false)
269 @IsEmail
270 @Column(DataType.STRING(400))
271 email: string
272
273 @AllowNull(true)
274 @IsEmail
275 @Column(DataType.STRING(400))
276 pendingEmail: string
277
278 @AllowNull(true)
279 @Default(null)
280 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
281 @Column
282 emailVerified: boolean
283
284 @AllowNull(false)
285 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
286 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
287 nsfwPolicy: NSFWPolicyType
288
289 @AllowNull(false)
290 @Is('p2pEnabled', value => throwIfNotValid(value, isUserP2PEnabledValid, 'P2P enabled'))
291 @Column
292 p2pEnabled: boolean
293
294 @AllowNull(false)
295 @Default(true)
296 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
297 @Column
298 videosHistoryEnabled: boolean
299
300 @AllowNull(false)
301 @Default(true)
302 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
303 @Column
304 autoPlayVideo: boolean
305
306 @AllowNull(false)
307 @Default(false)
308 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
309 @Column
310 autoPlayNextVideo: boolean
311
312 @AllowNull(false)
313 @Default(true)
314 @Is(
315 'UserAutoPlayNextVideoPlaylist',
316 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
317 )
318 @Column
319 autoPlayNextVideoPlaylist: boolean
320
321 @AllowNull(true)
322 @Default(null)
323 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
324 @Column(DataType.ARRAY(DataType.STRING))
325 videoLanguages: string[]
326
327 @AllowNull(false)
328 @Default(UserAdminFlag.NONE)
329 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
330 @Column
331 adminFlags?: UserAdminFlag
332
333 @AllowNull(false)
334 @Default(false)
335 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
336 @Column
337 blocked: boolean
338
339 @AllowNull(true)
340 @Default(null)
341 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
342 @Column
343 blockedReason: string
344
345 @AllowNull(false)
346 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
347 @Column
348 role: number
349
350 @AllowNull(false)
351 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
352 @Column(DataType.BIGINT)
353 videoQuota: number
354
355 @AllowNull(false)
356 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
357 @Column(DataType.BIGINT)
358 videoQuotaDaily: number
359
360 @AllowNull(false)
361 @Default(DEFAULT_USER_THEME_NAME)
362 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
363 @Column
364 theme: string
365
366 @AllowNull(false)
367 @Default(false)
368 @Is(
369 'UserNoInstanceConfigWarningModal',
370 value => throwIfNotValid(value, isUserNoModal, 'no instance config warning modal')
371 )
372 @Column
373 noInstanceConfigWarningModal: boolean
374
375 @AllowNull(false)
376 @Default(false)
377 @Is(
378 'UserNoWelcomeModal',
379 value => throwIfNotValid(value, isUserNoModal, 'no welcome modal')
380 )
381 @Column
382 noWelcomeModal: boolean
383
384 @AllowNull(false)
385 @Default(false)
386 @Is(
387 'UserNoAccountSetupWarningModal',
388 value => throwIfNotValid(value, isUserNoModal, 'no account setup warning modal')
389 )
390 @Column
391 noAccountSetupWarningModal: boolean
392
393 @AllowNull(true)
394 @Default(null)
395 @Column
396 pluginAuth: string
397
398 @AllowNull(false)
399 @Default(DataType.UUIDV4)
400 @IsUUID(4)
401 @Column(DataType.UUID)
402 feedToken: string
403
404 @AllowNull(true)
405 @Default(null)
406 @Column
407 lastLoginDate: Date
408
409 @CreatedAt
410 createdAt: Date
411
412 @UpdatedAt
413 updatedAt: Date
414
415 @HasOne(() => AccountModel, {
416 foreignKey: 'userId',
417 onDelete: 'cascade',
418 hooks: true
419 })
420 Account: AccountModel
421
422 @HasOne(() => UserNotificationSettingModel, {
423 foreignKey: 'userId',
424 onDelete: 'cascade',
425 hooks: true
426 })
427 NotificationSetting: UserNotificationSettingModel
428
429 @HasMany(() => VideoImportModel, {
430 foreignKey: 'userId',
431 onDelete: 'cascade'
432 })
433 VideoImports: VideoImportModel[]
434
435 @HasMany(() => OAuthTokenModel, {
436 foreignKey: 'userId',
437 onDelete: 'cascade'
438 })
439 OAuthTokens: OAuthTokenModel[]
440
441 @BeforeCreate
442 @BeforeUpdate
443 static cryptPasswordIfNeeded (instance: UserModel) {
444 if (instance.changed('password') && instance.password) {
445 return cryptPassword(instance.password)
446 .then(hash => {
447 instance.password = hash
448 return undefined
449 })
450 }
451 }
452
453 @AfterUpdate
454 @AfterDestroy
455 static removeTokenCache (instance: UserModel) {
456 return TokensCache.Instance.clearCacheByUserId(instance.id)
457 }
458
459 static countTotal () {
460 return this.count()
461 }
462
463 static listForAdminApi (parameters: {
464 start: number
465 count: number
466 sort: string
467 search?: string
468 blocked?: boolean
469 }) {
470 const { start, count, sort, search, blocked } = parameters
471 const where: WhereOptions = {}
472
473 if (search) {
474 Object.assign(where, {
475 [Op.or]: [
476 {
477 email: {
478 [Op.iLike]: '%' + search + '%'
479 }
480 },
481 {
482 username: {
483 [Op.iLike]: '%' + search + '%'
484 }
485 }
486 ]
487 })
488 }
489
490 if (blocked !== undefined) {
491 Object.assign(where, {
492 blocked: blocked
493 })
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: this.role,
895 roleLabel: USER_ROLE_LABELS[this.role],
896
897 videoQuota: this.videoQuota,
898 videoQuotaDaily: this.videoQuotaDaily,
899
900 videoQuotaUsed: videoQuotaUsed !== undefined
901 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
902 : undefined,
903
904 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
905 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
906 : undefined,
907
908 videosCount: videosCount !== undefined
909 ? parseInt(videosCount + '', 10)
910 : undefined,
911 abusesCount: abusesCount
912 ? parseInt(abusesCount, 10)
913 : undefined,
914 abusesAcceptedCount: abusesAcceptedCount
915 ? parseInt(abusesAcceptedCount, 10)
916 : undefined,
917 abusesCreatedCount: abusesCreatedCount !== undefined
918 ? parseInt(abusesCreatedCount + '', 10)
919 : undefined,
920 videoCommentsCount: videoCommentsCount !== undefined
921 ? parseInt(videoCommentsCount + '', 10)
922 : undefined,
923
924 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
925 noWelcomeModal: this.noWelcomeModal,
926 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
927
928 blocked: this.blocked,
929 blockedReason: this.blockedReason,
930
931 account: this.Account.toFormattedJSON(),
932
933 notificationSettings: this.NotificationSetting
934 ? this.NotificationSetting.toFormattedJSON()
935 : undefined,
936
937 videoChannels: [],
938
939 createdAt: this.createdAt,
940
941 pluginAuth: this.pluginAuth,
942
943 lastLoginDate: this.lastLoginDate
944 }
945
946 if (parameters.withAdminFlags) {
947 Object.assign(json, { adminFlags: this.adminFlags })
948 }
949
950 if (Array.isArray(this.Account.VideoChannels) === true) {
951 json.videoChannels = this.Account.VideoChannels
952 .map(c => c.toFormattedJSON())
953 .sort((v1, v2) => {
954 if (v1.createdAt < v2.createdAt) return -1
955 if (v1.createdAt === v2.createdAt) return 0
956
957 return 1
958 })
959 }
960
961 return json
962 }
963
964 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
965 const formatted = this.toFormattedJSON({ withAdminFlags: true })
966
967 const specialPlaylists = this.Account.VideoPlaylists
968 .map(p => ({ id: p.id, name: p.name, type: p.type }))
969
970 return Object.assign(formatted, { specialPlaylists })
971 }
972}