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