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