]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user/user.ts
1a7c843907b6838135e483032cecba7ffd66c599
[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 @CreatedAt
407 createdAt: Date
408
409 @UpdatedAt
410 updatedAt: Date
411
412 @HasOne(() => AccountModel, {
413 foreignKey: 'userId',
414 onDelete: 'cascade',
415 hooks: true
416 })
417 Account: AccountModel
418
419 @HasOne(() => UserNotificationSettingModel, {
420 foreignKey: 'userId',
421 onDelete: 'cascade',
422 hooks: true
423 })
424 NotificationSetting: UserNotificationSettingModel
425
426 @HasMany(() => VideoImportModel, {
427 foreignKey: 'userId',
428 onDelete: 'cascade'
429 })
430 VideoImports: VideoImportModel[]
431
432 @HasMany(() => OAuthTokenModel, {
433 foreignKey: 'userId',
434 onDelete: 'cascade'
435 })
436 OAuthTokens: OAuthTokenModel[]
437
438 @BeforeCreate
439 @BeforeUpdate
440 static cryptPasswordIfNeeded (instance: UserModel) {
441 if (instance.changed('password') && instance.password) {
442 return cryptPassword(instance.password)
443 .then(hash => {
444 instance.password = hash
445 return undefined
446 })
447 }
448 }
449
450 @AfterUpdate
451 @AfterDestroy
452 static removeTokenCache (instance: UserModel) {
453 return TokensCache.Instance.clearCacheByUserId(instance.id)
454 }
455
456 static countTotal () {
457 return this.count()
458 }
459
460 static listForAdminApi (parameters: {
461 start: number
462 count: number
463 sort: string
464 search?: string
465 blocked?: boolean
466 }) {
467 const { start, count, sort, search, blocked } = parameters
468 const where: WhereOptions = {}
469
470 if (search) {
471 Object.assign(where, {
472 [Op.or]: [
473 {
474 email: {
475 [Op.iLike]: '%' + search + '%'
476 }
477 },
478 {
479 username: {
480 [Op.iLike]: '%' + search + '%'
481 }
482 }
483 ]
484 })
485 }
486
487 if (blocked !== undefined) {
488 Object.assign(where, { blocked })
489 }
490
491 const query: FindOptions = {
492 offset: start,
493 limit: count,
494 order: getAdminUsersSort(sort),
495 where
496 }
497
498 return Promise.all([
499 UserModel.unscoped().count(query),
500 UserModel.scope([ 'defaultScope', ScopeNames.WITH_QUOTA ]).findAll(query)
501 ]).then(([ total, data ]) => ({ total, data }))
502 }
503
504 static listWithRight (right: UserRight): Promise<MUserDefault[]> {
505 const roles = Object.keys(USER_ROLE_LABELS)
506 .map(k => parseInt(k, 10) as UserRole)
507 .filter(role => hasUserRight(role, right))
508
509 const query = {
510 where: {
511 role: {
512 [Op.in]: roles
513 }
514 }
515 }
516
517 return UserModel.findAll(query)
518 }
519
520 static listUserSubscribersOf (actorId: number): Promise<MUserWithNotificationSetting[]> {
521 const query = {
522 include: [
523 {
524 model: UserNotificationSettingModel.unscoped(),
525 required: true
526 },
527 {
528 attributes: [ 'userId' ],
529 model: AccountModel.unscoped(),
530 required: true,
531 include: [
532 {
533 attributes: [],
534 model: ActorModel.unscoped(),
535 required: true,
536 where: {
537 serverId: null
538 },
539 include: [
540 {
541 attributes: [],
542 as: 'ActorFollowings',
543 model: ActorFollowModel.unscoped(),
544 required: true,
545 where: {
546 targetActorId: actorId
547 }
548 }
549 ]
550 }
551 ]
552 }
553 ]
554 }
555
556 return UserModel.unscoped().findAll(query)
557 }
558
559 static listByUsernames (usernames: string[]): Promise<MUserDefault[]> {
560 const query = {
561 where: {
562 username: usernames
563 }
564 }
565
566 return UserModel.findAll(query)
567 }
568
569 static loadById (id: number): Promise<MUser> {
570 return UserModel.unscoped().findByPk(id)
571 }
572
573 static loadByIdFull (id: number): Promise<MUserDefault> {
574 return UserModel.findByPk(id)
575 }
576
577 static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {
578 const scopes = [
579 ScopeNames.WITH_VIDEOCHANNELS
580 ]
581
582 if (withStats) {
583 scopes.push(ScopeNames.WITH_QUOTA)
584 scopes.push(ScopeNames.WITH_STATS)
585 }
586
587 return UserModel.scope(scopes).findByPk(id)
588 }
589
590 static loadByUsername (username: string): Promise<MUserDefault> {
591 const query = {
592 where: {
593 username
594 }
595 }
596
597 return UserModel.findOne(query)
598 }
599
600 static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {
601 const query = {
602 where: {
603 id
604 }
605 }
606
607 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
608 }
609
610 static loadByEmail (email: string): Promise<MUserDefault> {
611 const query = {
612 where: {
613 email
614 }
615 }
616
617 return UserModel.findOne(query)
618 }
619
620 static loadByUsernameOrEmail (username: string, email?: string): Promise<MUserDefault> {
621 if (!email) email = username
622
623 const query = {
624 where: {
625 [Op.or]: [
626 where(fn('lower', col('username')), fn('lower', username) as any),
627
628 { email }
629 ]
630 }
631 }
632
633 return UserModel.findOne(query)
634 }
635
636 static loadByVideoId (videoId: number): Promise<MUserDefault> {
637 const query = {
638 include: [
639 {
640 required: true,
641 attributes: [ 'id' ],
642 model: AccountModel.unscoped(),
643 include: [
644 {
645 required: true,
646 attributes: [ 'id' ],
647 model: VideoChannelModel.unscoped(),
648 include: [
649 {
650 required: true,
651 attributes: [ 'id' ],
652 model: VideoModel.unscoped(),
653 where: {
654 id: videoId
655 }
656 }
657 ]
658 }
659 ]
660 }
661 ]
662 }
663
664 return UserModel.findOne(query)
665 }
666
667 static loadByVideoImportId (videoImportId: number): Promise<MUserDefault> {
668 const query = {
669 include: [
670 {
671 required: true,
672 attributes: [ 'id' ],
673 model: VideoImportModel.unscoped(),
674 where: {
675 id: videoImportId
676 }
677 }
678 ]
679 }
680
681 return UserModel.findOne(query)
682 }
683
684 static loadByChannelActorId (videoChannelActorId: number): Promise<MUserDefault> {
685 const query = {
686 include: [
687 {
688 required: true,
689 attributes: [ 'id' ],
690 model: AccountModel.unscoped(),
691 include: [
692 {
693 required: true,
694 attributes: [ 'id' ],
695 model: VideoChannelModel.unscoped(),
696 where: {
697 actorId: videoChannelActorId
698 }
699 }
700 ]
701 }
702 ]
703 }
704
705 return UserModel.findOne(query)
706 }
707
708 static loadByAccountActorId (accountActorId: number): Promise<MUserDefault> {
709 const query = {
710 include: [
711 {
712 required: true,
713 attributes: [ 'id' ],
714 model: AccountModel.unscoped(),
715 where: {
716 actorId: accountActorId
717 }
718 }
719 ]
720 }
721
722 return UserModel.findOne(query)
723 }
724
725 static loadByLiveId (liveId: number): Promise<MUser> {
726 const query = {
727 include: [
728 {
729 attributes: [ 'id' ],
730 model: AccountModel.unscoped(),
731 required: true,
732 include: [
733 {
734 attributes: [ 'id' ],
735 model: VideoChannelModel.unscoped(),
736 required: true,
737 include: [
738 {
739 attributes: [ 'id' ],
740 model: VideoModel.unscoped(),
741 required: true,
742 include: [
743 {
744 attributes: [],
745 model: VideoLiveModel.unscoped(),
746 required: true,
747 where: {
748 id: liveId
749 }
750 }
751 ]
752 }
753 ]
754 }
755 ]
756 }
757 ]
758 }
759
760 return UserModel.unscoped().findOne(query)
761 }
762
763 static generateUserQuotaBaseSQL (options: {
764 whereUserId: '$userId' | '"UserModel"."id"'
765 withSelect: boolean
766 daily: boolean
767 }) {
768 const andWhere = options.daily === true
769 ? 'AND "video"."createdAt" > now() - interval \'24 hours\''
770 : ''
771
772 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
773 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
774 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
775
776 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
777 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
778 videoChannelJoin
779
780 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
781 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
782 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
783 videoChannelJoin
784
785 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
786 'FROM (' +
787 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
788 'GROUP BY "t1"."videoId"' +
789 ') t2'
790 }
791
792 static getTotalRawQuery (query: string, userId: number) {
793 const options = {
794 bind: { userId },
795 type: QueryTypes.SELECT as QueryTypes.SELECT
796 }
797
798 return UserModel.sequelize.query<{ total: string }>(query, options)
799 .then(([ { total } ]) => {
800 if (total === null) return 0
801
802 return parseInt(total, 10)
803 })
804 }
805
806 static async getStats () {
807 function getActiveUsers (days: number) {
808 const query = {
809 where: {
810 [Op.and]: [
811 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
812 ]
813 }
814 }
815
816 return UserModel.unscoped().count(query)
817 }
818
819 const totalUsers = await UserModel.unscoped().count()
820 const totalDailyActiveUsers = await getActiveUsers(1)
821 const totalWeeklyActiveUsers = await getActiveUsers(7)
822 const totalMonthlyActiveUsers = await getActiveUsers(30)
823 const totalHalfYearActiveUsers = await getActiveUsers(180)
824
825 return {
826 totalUsers,
827 totalDailyActiveUsers,
828 totalWeeklyActiveUsers,
829 totalMonthlyActiveUsers,
830 totalHalfYearActiveUsers
831 }
832 }
833
834 static autoComplete (search: string) {
835 const query = {
836 where: {
837 username: {
838 [Op.like]: `%${search}%`
839 }
840 },
841 limit: 10
842 }
843
844 return UserModel.findAll(query)
845 .then(u => u.map(u => u.username))
846 }
847
848 hasRight (right: UserRight) {
849 return hasUserRight(this.role, right)
850 }
851
852 hasAdminFlag (flag: UserAdminFlag) {
853 return this.adminFlags & flag
854 }
855
856 isPasswordMatch (password: string) {
857 return comparePassword(password, this.password)
858 }
859
860 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
861 const videoQuotaUsed = this.get('videoQuotaUsed')
862 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
863 const videosCount = this.get('videosCount')
864 const [ abusesCount, abusesAcceptedCount ] = (this.get('abusesCount') as string || ':').split(':')
865 const abusesCreatedCount = this.get('abusesCreatedCount')
866 const videoCommentsCount = this.get('videoCommentsCount')
867
868 const json: User = {
869 id: this.id,
870 username: this.username,
871 email: this.email,
872 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
873
874 pendingEmail: this.pendingEmail,
875 emailVerified: this.emailVerified,
876
877 nsfwPolicy: this.nsfwPolicy,
878
879 // FIXME: deprecated in 4.1
880 webTorrentEnabled: this.p2pEnabled,
881 p2pEnabled: this.p2pEnabled,
882
883 videosHistoryEnabled: this.videosHistoryEnabled,
884 autoPlayVideo: this.autoPlayVideo,
885 autoPlayNextVideo: this.autoPlayNextVideo,
886 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
887 videoLanguages: this.videoLanguages,
888
889 role: this.role,
890 roleLabel: USER_ROLE_LABELS[this.role],
891
892 videoQuota: this.videoQuota,
893 videoQuotaDaily: this.videoQuotaDaily,
894
895 videoQuotaUsed: videoQuotaUsed !== undefined
896 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
897 : undefined,
898
899 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
900 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
901 : undefined,
902
903 videosCount: videosCount !== undefined
904 ? parseInt(videosCount + '', 10)
905 : undefined,
906 abusesCount: abusesCount
907 ? parseInt(abusesCount, 10)
908 : undefined,
909 abusesAcceptedCount: abusesAcceptedCount
910 ? parseInt(abusesAcceptedCount, 10)
911 : undefined,
912 abusesCreatedCount: abusesCreatedCount !== undefined
913 ? parseInt(abusesCreatedCount + '', 10)
914 : undefined,
915 videoCommentsCount: videoCommentsCount !== undefined
916 ? parseInt(videoCommentsCount + '', 10)
917 : undefined,
918
919 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
920 noWelcomeModal: this.noWelcomeModal,
921 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
922
923 blocked: this.blocked,
924 blockedReason: this.blockedReason,
925
926 account: this.Account.toFormattedJSON(),
927
928 notificationSettings: this.NotificationSetting
929 ? this.NotificationSetting.toFormattedJSON()
930 : undefined,
931
932 videoChannels: [],
933
934 createdAt: this.createdAt,
935
936 pluginAuth: this.pluginAuth,
937
938 lastLoginDate: this.lastLoginDate
939 }
940
941 if (parameters.withAdminFlags) {
942 Object.assign(json, { adminFlags: this.adminFlags })
943 }
944
945 if (Array.isArray(this.Account.VideoChannels) === true) {
946 json.videoChannels = this.Account.VideoChannels
947 .map(c => c.toFormattedJSON())
948 .sort((v1, v2) => {
949 if (v1.createdAt < v2.createdAt) return -1
950 if (v1.createdAt === v2.createdAt) return 0
951
952 return 1
953 })
954 }
955
956 return json
957 }
958
959 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
960 const formatted = this.toFormattedJSON({ withAdminFlags: true })
961
962 const specialPlaylists = this.Account.VideoPlaylists
963 .map(p => ({ id: p.id, name: p.name, type: p.type }))
964
965 return Object.assign(formatted, { specialPlaylists })
966 }
967 }