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