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