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