]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
a1587156 1import { FindOptions, literal, Op, QueryTypes, where, fn, col, WhereOptions } from 'sequelize'
3fd3ab2d 2import {
d175a6f7 3 AfterDestroy,
f201a749 4 AfterUpdate,
a73c582e
C
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
3fd3ab2d 21} from 'sequelize-typescript'
ac0868bc 22import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared'
ba75d268 23import { User, UserRole } from '../../../shared/models/users'
65fcc311 24import {
43d0ea7f 25 isNoInstanceConfigWarningModal,
ac0868bc 26 isNoWelcomeModal,
1eddc9a7 27 isUserAdminFlagsValid,
bee29df8 28 isUserAutoPlayNextVideoPlaylistValid,
ac0868bc
C
29 isUserAutoPlayNextVideoValid,
30 isUserAutoPlayVideoValid,
eacb25c4 31 isUserBlockedReasonValid,
e6921918 32 isUserBlockedValid,
d9eaee39 33 isUserEmailVerifiedValid,
5cf84858 34 isUserNSFWPolicyValid,
a73c582e
C
35 isUserPasswordValid,
36 isUserRoleValid,
37 isUserUsernameValid,
3caf77d3 38 isUserVideoLanguages,
5cf84858 39 isUserVideoQuotaDailyValid,
64cc5e85 40 isUserVideoQuotaValid,
cef534ed 41 isUserVideosHistoryEnabledValid,
ac0868bc 42 isUserWebTorrentEnabledValid
3fd3ab2d 43} from '../../helpers/custom-validators/users'
da854ddd 44import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
45import { OAuthTokenModel } from '../oauth/oauth-token'
46import { getSort, throwIfNotValid } from '../utils'
47import { VideoChannelModel } from '../video/video-channel'
29128b2f 48import { VideoPlaylistModel } from '../video/video-playlist'
3fd3ab2d 49import { AccountModel } from './account'
0883b324
C
50import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
51import { values } from 'lodash'
ffb321be 52import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
f201a749 53import { clearCacheByUserId } from '../../lib/oauth-model'
cef534ed
C
54import { UserNotificationSettingModel } from './user-notification-setting'
55import { VideoModel } from '../video/video'
56import { ActorModel } from '../activitypub/actor'
57import { ActorFollowModel } from '../activitypub/actor-follow'
dc133480 58import { VideoImportModel } from '../video/video-import'
1eddc9a7 59import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
503c6f44 60import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
7cd4d2ba 61import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
453e83ea 62import * as Bluebird from 'bluebird'
1ca9f7c3 63import {
ac0868bc 64 MMyUserFormattable,
1ca9f7c3
C
65 MUserDefault,
66 MUserFormattable,
67 MUserId,
68 MUserNotifSettingChannelDefault,
ac0868bc
C
69 MUserWithNotificationSetting,
70 MVideoFullLight
1ca9f7c3 71} from '@server/typings/models'
3fd3ab2d 72
9c2e0dbf 73enum ScopeNames {
ac0868bc 74 FOR_ME_API = 'FOR_ME_API'
9c2e0dbf
C
75}
76
3acc5084 77@DefaultScope(() => ({
d48ff09d
C
78 include: [
79 {
3acc5084 80 model: AccountModel,
d48ff09d 81 required: true
cef534ed
C
82 },
83 {
3acc5084 84 model: UserNotificationSettingModel,
cef534ed 85 required: true
d48ff09d
C
86 }
87 ]
3acc5084
C
88}))
89@Scopes(() => ({
ac0868bc 90 [ScopeNames.FOR_ME_API]: {
d48ff09d
C
91 include: [
92 {
3acc5084 93 model: AccountModel,
ac0868bc
C
94 include: [
95 {
96 model: VideoChannelModel
97 },
98 {
99 attributes: [ 'id', 'name', 'type' ],
100 model: VideoPlaylistModel.unscoped(),
101 required: true,
102 where: {
103 type: {
a1587156 104 [Op.ne]: VideoPlaylistType.REGULAR
ac0868bc
C
105 }
106 }
107 }
108 ]
cef534ed
C
109 },
110 {
3acc5084 111 model: UserNotificationSettingModel,
cef534ed 112 required: true
d48ff09d 113 }
3acc5084 114 ]
d48ff09d 115 }
3acc5084 116}))
3fd3ab2d
C
117@Table({
118 tableName: 'user',
119 indexes: [
feb4bdfd 120 {
3fd3ab2d
C
121 fields: [ 'username' ],
122 unique: true
feb4bdfd
C
123 },
124 {
3fd3ab2d
C
125 fields: [ 'email' ],
126 unique: true
feb4bdfd 127 }
e02643f3 128 ]
3fd3ab2d
C
129})
130export class UserModel extends Model<UserModel> {
131
132 @AllowNull(false)
133 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
134 @Column
135 password: string
136
137 @AllowNull(false)
138 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
139 @Column
140 username: string
141
142 @AllowNull(false)
143 @IsEmail
144 @Column(DataType.STRING(400))
145 email: string
146
d1ab89de
C
147 @AllowNull(true)
148 @IsEmail
149 @Column(DataType.STRING(400))
150 pendingEmail: string
151
d9eaee39
JM
152 @AllowNull(true)
153 @Default(null)
1735c825 154 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
d9eaee39
JM
155 @Column
156 emailVerified: boolean
157
3fd3ab2d 158 @AllowNull(false)
0883b324 159 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
1735c825 160 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
0883b324 161 nsfwPolicy: NSFWPolicyType
3fd3ab2d 162
64cc5e85 163 @AllowNull(false)
0229b014 164 @Default(true)
ed638e53
RK
165 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
166 @Column
167 webTorrentEnabled: boolean
64cc5e85 168
8b9a525a
C
169 @AllowNull(false)
170 @Default(true)
171 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
172 @Column
173 videosHistoryEnabled: boolean
174
7efe153b
AL
175 @AllowNull(false)
176 @Default(true)
177 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
178 @Column
179 autoPlayVideo: boolean
180
6aa54148
L
181 @AllowNull(false)
182 @Default(false)
183 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
184 @Column
185 autoPlayNextVideo: boolean
186
bee29df8
RK
187 @AllowNull(false)
188 @Default(true)
a1587156
C
189 @Is(
190 'UserAutoPlayNextVideoPlaylist',
191 value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean')
192 )
bee29df8
RK
193 @Column
194 autoPlayNextVideoPlaylist: boolean
195
3caf77d3
C
196 @AllowNull(true)
197 @Default(null)
198 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
199 @Column(DataType.ARRAY(DataType.STRING))
200 videoLanguages: string[]
201
1eddc9a7
C
202 @AllowNull(false)
203 @Default(UserAdminFlag.NONE)
204 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
205 @Column
206 adminFlags?: UserAdminFlag
207
e6921918
C
208 @AllowNull(false)
209 @Default(false)
210 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
211 @Column
212 blocked: boolean
213
eacb25c4
C
214 @AllowNull(true)
215 @Default(null)
1735c825 216 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
eacb25c4
C
217 @Column
218 blockedReason: string
219
3fd3ab2d
C
220 @AllowNull(false)
221 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
222 @Column
223 role: number
224
225 @AllowNull(false)
226 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
227 @Column(DataType.BIGINT)
228 videoQuota: number
229
bee0abff
FA
230 @AllowNull(false)
231 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
232 @Column(DataType.BIGINT)
233 videoQuotaDaily: number
234
7cd4d2ba 235 @AllowNull(false)
ffb321be 236 @Default(DEFAULT_THEME_NAME)
503c6f44 237 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
7cd4d2ba
C
238 @Column
239 theme: string
240
43d0ea7f
C
241 @AllowNull(false)
242 @Default(false)
243 @Is(
244 'UserNoInstanceConfigWarningModal',
245 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
246 )
247 @Column
248 noInstanceConfigWarningModal: boolean
249
250 @AllowNull(false)
251 @Default(false)
252 @Is(
253 'UserNoInstanceConfigWarningModal',
254 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
255 )
256 @Column
257 noWelcomeModal: boolean
258
3fd3ab2d
C
259 @CreatedAt
260 createdAt: Date
261
262 @UpdatedAt
263 updatedAt: Date
264
265 @HasOne(() => AccountModel, {
266 foreignKey: 'userId',
f05a1c30
C
267 onDelete: 'cascade',
268 hooks: true
3fd3ab2d
C
269 })
270 Account: AccountModel
69b0a27c 271
cef534ed
C
272 @HasOne(() => UserNotificationSettingModel, {
273 foreignKey: 'userId',
274 onDelete: 'cascade',
275 hooks: true
276 })
277 NotificationSetting: UserNotificationSettingModel
278
dc133480
C
279 @HasMany(() => VideoImportModel, {
280 foreignKey: 'userId',
281 onDelete: 'cascade'
282 })
283 VideoImports: VideoImportModel[]
284
3fd3ab2d
C
285 @HasMany(() => OAuthTokenModel, {
286 foreignKey: 'userId',
287 onDelete: 'cascade'
288 })
289 OAuthTokens: OAuthTokenModel[]
290
291 @BeforeCreate
292 @BeforeUpdate
293 static cryptPasswordIfNeeded (instance: UserModel) {
294 if (instance.changed('password')) {
295 return cryptPassword(instance.password)
296 .then(hash => {
297 instance.password = hash
298 return undefined
299 })
300 }
59557c46 301 }
26d7d31b 302
f201a749 303 @AfterUpdate
d175a6f7 304 @AfterDestroy
f201a749
C
305 static removeTokenCache (instance: UserModel) {
306 return clearCacheByUserId(instance.id)
307 }
308
3fd3ab2d
C
309 static countTotal () {
310 return this.count()
311 }
954605a8 312
24b9417c 313 static listForApi (start: number, count: number, sort: string, search?: string) {
a1587156
C
314 let where: WhereOptions
315
24b9417c
C
316 if (search) {
317 where = {
3acc5084 318 [Op.or]: [
24b9417c
C
319 {
320 email: {
3acc5084 321 [Op.iLike]: '%' + search + '%'
24b9417c
C
322 }
323 },
324 {
325 username: {
a1587156 326 [Op.iLike]: '%' + search + '%'
24b9417c
C
327 }
328 }
329 ]
330 }
331 }
332
3acc5084 333 const query: FindOptions = {
a76138ff
C
334 attributes: {
335 include: [
336 [
3acc5084 337 literal(
a76138ff 338 '(' +
a1587156
C
339 'SELECT COALESCE(SUM("size"), 0) ' +
340 'FROM (' +
341 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
342 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
343 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
344 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
345 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
346 ') t' +
a76138ff
C
347 ')'
348 ),
349 'videoQuotaUsed'
3acc5084 350 ]
a76138ff
C
351 ]
352 },
3fd3ab2d
C
353 offset: start,
354 limit: count,
24b9417c
C
355 order: getSort(sort),
356 where
3fd3ab2d 357 }
72c7248b 358
3fd3ab2d 359 return UserModel.findAndCountAll(query)
a1587156
C
360 .then(({ rows, count }) => {
361 return {
362 data: rows,
363 total: count
364 }
365 })
72c7248b
C
366 }
367
453e83ea 368 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
ba75d268 369 const roles = Object.keys(USER_ROLE_LABELS)
a1587156
C
370 .map(k => parseInt(k, 10) as UserRole)
371 .filter(role => hasUserRight(role, right))
ba75d268 372
ba75d268 373 const query = {
ba75d268
C
374 where: {
375 role: {
3acc5084 376 [Op.in]: roles
ba75d268
C
377 }
378 }
379 }
380
cef534ed
C
381 return UserModel.findAll(query)
382 }
383
453e83ea 384 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
cef534ed
C
385 const query = {
386 include: [
387 {
388 model: UserNotificationSettingModel.unscoped(),
389 required: true
390 },
391 {
392 attributes: [ 'userId' ],
393 model: AccountModel.unscoped(),
394 required: true,
395 include: [
396 {
a1587156 397 attributes: [],
cef534ed
C
398 model: ActorModel.unscoped(),
399 required: true,
400 where: {
401 serverId: null
402 },
403 include: [
404 {
a1587156 405 attributes: [],
cef534ed
C
406 as: 'ActorFollowings',
407 model: ActorFollowModel.unscoped(),
408 required: true,
409 where: {
410 targetActorId: actorId
411 }
412 }
413 ]
414 }
415 ]
416 }
417 ]
418 }
419
420 return UserModel.unscoped().findAll(query)
ba75d268
C
421 }
422
453e83ea 423 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
f7cc67b4
C
424 const query = {
425 where: {
426 username: usernames
427 }
428 }
429
430 return UserModel.findAll(query)
431 }
432
453e83ea 433 static loadById (id: number): Bluebird<MUserDefault> {
9b39106d 434 return UserModel.findByPk(id)
3fd3ab2d 435 }
feb4bdfd 436
453e83ea 437 static loadByUsername (username: string): Bluebird<MUserDefault> {
3fd3ab2d
C
438 const query = {
439 where: {
a1587156 440 username: { [Op.iLike]: username }
d48ff09d 441 }
3fd3ab2d 442 }
089ff2f2 443
3fd3ab2d 444 return UserModel.findOne(query)
feb4bdfd
C
445 }
446
ac0868bc 447 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
3fd3ab2d
C
448 const query = {
449 where: {
a1587156 450 username: { [Op.iLike]: username }
d48ff09d 451 }
3fd3ab2d 452 }
9bd26629 453
ac0868bc 454 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
feb4bdfd
C
455 }
456
453e83ea 457 static loadByEmail (email: string): Bluebird<MUserDefault> {
ecb4e35f
C
458 const query = {
459 where: {
460 email
461 }
462 }
463
464 return UserModel.findOne(query)
465 }
466
453e83ea 467 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
ba12e8b3
C
468 if (!email) email = username
469
3fd3ab2d 470 const query = {
3fd3ab2d 471 where: {
a1587156 472 [Op.or]: [
c4a1811e
C
473 where(fn('lower', col('username')), fn('lower', username)),
474
475 { email }
476 ]
3fd3ab2d 477 }
6fcd19ba 478 }
69b0a27c 479
d48ff09d 480 return UserModel.findOne(query)
72c7248b
C
481 }
482
453e83ea 483 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
cef534ed
C
484 const query = {
485 include: [
486 {
487 required: true,
488 attributes: [ 'id' ],
489 model: AccountModel.unscoped(),
490 include: [
491 {
492 required: true,
493 attributes: [ 'id' ],
494 model: VideoChannelModel.unscoped(),
495 include: [
496 {
497 required: true,
498 attributes: [ 'id' ],
499 model: VideoModel.unscoped(),
500 where: {
501 id: videoId
502 }
503 }
504 ]
505 }
506 ]
507 }
508 ]
509 }
510
511 return UserModel.findOne(query)
512 }
513
453e83ea 514 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
dc133480
C
515 const query = {
516 include: [
517 {
518 required: true,
519 attributes: [ 'id' ],
520 model: VideoImportModel.unscoped(),
521 where: {
522 id: videoImportId
523 }
524 }
525 ]
526 }
527
528 return UserModel.findOne(query)
529 }
530
453e83ea 531 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
f7cc67b4
C
532 const query = {
533 include: [
534 {
535 required: true,
536 attributes: [ 'id' ],
537 model: AccountModel.unscoped(),
538 include: [
539 {
540 required: true,
541 attributes: [ 'id' ],
542 model: VideoChannelModel.unscoped(),
543 where: {
544 actorId: videoChannelActorId
545 }
546 }
547 ]
548 }
549 ]
550 }
551
552 return UserModel.findOne(query)
553 }
554
453e83ea 555 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
f7cc67b4
C
556 const query = {
557 include: [
558 {
559 required: true,
560 attributes: [ 'id' ],
561 model: AccountModel.unscoped(),
562 where: {
563 actorId: accountActorId
564 }
565 }
566 ]
567 }
568
569 return UserModel.findOne(query)
570 }
571
453e83ea 572 static getOriginalVideoFileTotalFromUser (user: MUserId) {
3fd3ab2d 573 // Don't use sequelize because we need to use a sub query
8b604880 574 const query = UserModel.generateUserQuotaBaseSQL()
bee0abff 575
8b604880 576 return UserModel.getTotalRawQuery(query, user.id)
bee0abff
FA
577 }
578
8b604880 579 // Returns cumulative size of all video files uploaded in the last 24 hours.
453e83ea 580 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
bee0abff 581 // Don't use sequelize because we need to use a sub query
8b604880 582 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
68a3b9f2 583
8b604880 584 return UserModel.getTotalRawQuery(query, user.id)
72c7248b
C
585 }
586
09cababd
C
587 static async getStats () {
588 const totalUsers = await UserModel.count()
589
590 return {
591 totalUsers
592 }
593 }
594
5cf84858
C
595 static autoComplete (search: string) {
596 const query = {
597 where: {
598 username: {
a1587156 599 [Op.like]: `%${search}%`
5cf84858
C
600 }
601 },
602 limit: 10
603 }
604
605 return UserModel.findAll(query)
606 .then(u => u.map(u => u.username))
607 }
608
22a73cb8 609 canGetVideo (video: MVideoFullLight) {
2a5518a6 610 const videoUserId = video.VideoChannel.Account.userId
22a73cb8 611
2a5518a6
C
612 if (video.isBlacklisted()) {
613 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
22a73cb8
C
614 }
615
2a5518a6
C
616 if (video.privacy === VideoPrivacy.PRIVATE) {
617 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
22a73cb8
C
618 }
619
2a5518a6
C
620 if (video.privacy === VideoPrivacy.INTERNAL) return true
621
22a73cb8
C
622 return false
623 }
624
3fd3ab2d
C
625 hasRight (right: UserRight) {
626 return hasUserRight(this.role, right)
627 }
72c7248b 628
1eddc9a7
C
629 hasAdminFlag (flag: UserAdminFlag) {
630 return this.adminFlags & flag
631 }
632
3fd3ab2d
C
633 isPasswordMatch (password: string) {
634 return comparePassword(password, this.password)
feb4bdfd
C
635 }
636
ac0868bc 637 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
a76138ff 638 const videoQuotaUsed = this.get('videoQuotaUsed')
bee0abff 639 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
a76138ff 640
ac0868bc 641 const json: User = {
3fd3ab2d
C
642 id: this.id,
643 username: this.username,
644 email: this.email,
43d0ea7f
C
645 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
646
d1ab89de 647 pendingEmail: this.pendingEmail,
d9eaee39 648 emailVerified: this.emailVerified,
43d0ea7f 649
0883b324 650 nsfwPolicy: this.nsfwPolicy,
ed638e53 651 webTorrentEnabled: this.webTorrentEnabled,
276d9652 652 videosHistoryEnabled: this.videosHistoryEnabled,
7efe153b 653 autoPlayVideo: this.autoPlayVideo,
6aa54148 654 autoPlayNextVideo: this.autoPlayNextVideo,
bee29df8 655 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
3caf77d3 656 videoLanguages: this.videoLanguages,
43d0ea7f 657
3fd3ab2d 658 role: this.role,
a1587156 659 roleLabel: USER_ROLE_LABELS[this.role],
43d0ea7f 660
3fd3ab2d 661 videoQuota: this.videoQuota,
bee0abff 662 videoQuotaDaily: this.videoQuotaDaily,
43d0ea7f
C
663 videoQuotaUsed: videoQuotaUsed !== undefined
664 ? parseInt(videoQuotaUsed + '', 10)
665 : undefined,
666 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
667 ? parseInt(videoQuotaUsedDaily + '', 10)
668 : undefined,
669
670 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
671 noWelcomeModal: this.noWelcomeModal,
672
eacb25c4
C
673 blocked: this.blocked,
674 blockedReason: this.blockedReason,
43d0ea7f 675
c5911fd3 676 account: this.Account.toFormattedJSON(),
43d0ea7f
C
677
678 notificationSettings: this.NotificationSetting
679 ? this.NotificationSetting.toFormattedJSON()
680 : undefined,
681
a76138ff 682 videoChannels: [],
43d0ea7f
C
683
684 createdAt: this.createdAt
3fd3ab2d
C
685 }
686
1eddc9a7
C
687 if (parameters.withAdminFlags) {
688 Object.assign(json, { adminFlags: this.adminFlags })
689 }
690
3fd3ab2d 691 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 692 json.videoChannels = this.Account.VideoChannels
a1587156
C
693 .map(c => c.toFormattedJSON())
694 .sort((v1, v2) => {
695 if (v1.createdAt < v2.createdAt) return -1
696 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 697
a1587156
C
698 return 1
699 })
ad4a8a1c 700 }
3fd3ab2d
C
701
702 return json
ad4a8a1c
C
703 }
704
ac0868bc
C
705 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
706 const formatted = this.toFormattedJSON()
707
708 const specialPlaylists = this.Account.VideoPlaylists
a1587156 709 .map(p => ({ id: p.id, name: p.name, type: p.type }))
ac0868bc
C
710
711 return Object.assign(formatted, { specialPlaylists })
712 }
713
bee0abff
FA
714 async isAbleToUploadVideo (videoFile: { size: number }) {
715 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
b0f9f39e 716
bee0abff
FA
717 const [ totalBytes, totalBytesDaily ] = await Promise.all([
718 UserModel.getOriginalVideoFileTotalFromUser(this),
719 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
720 ])
721
722 const uploadedTotal = videoFile.size + totalBytes
723 const uploadedDaily = videoFile.size + totalBytesDaily
bee0abff 724
3acc5084
C
725 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
726 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
727
728 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
b0f9f39e 729 }
8b604880
C
730
731 private static generateUserQuotaBaseSQL (where?: string) {
732 const andWhere = where ? 'AND ' + where : ''
733
734 return 'SELECT SUM("size") AS "total" ' +
735 'FROM (' +
a1587156
C
736 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
737 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
738 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
739 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
740 'WHERE "account"."userId" = $userId ' + andWhere +
741 'GROUP BY "video"."id"' +
8b604880
C
742 ') t'
743 }
744
745 private static getTotalRawQuery (query: string, userId: number) {
746 const options = {
747 bind: { userId },
3acc5084 748 type: QueryTypes.SELECT as QueryTypes.SELECT
8b604880
C
749 }
750
3acc5084 751 return UserModel.sequelize.query<{ total: string }>(query, options)
8b604880
C
752 .then(([ { total } ]) => {
753 if (total === null) return 0
754
3acc5084 755 return parseInt(total, 10)
8b604880
C
756 })
757 }
b0f9f39e 758}