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