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