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