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