]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/user/user.ts
Fix host advanced filter with channels
[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) {
491 Object.assign(where, {
492 blocked: blocked
493 })
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
3fd3ab2d 894 role: this.role,
a1587156 895 roleLabel: USER_ROLE_LABELS[this.role],
43d0ea7f 896
3fd3ab2d 897 videoQuota: this.videoQuota,
bee0abff 898 videoQuotaDaily: this.videoQuotaDaily,
9a82ce24 899
43d0ea7f 900 videoQuotaUsed: videoQuotaUsed !== undefined
9a82ce24 901 ? parseInt(videoQuotaUsed + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
43d0ea7f 902 : undefined,
9a82ce24 903
43d0ea7f 904 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
9a82ce24 905 ? parseInt(videoQuotaUsedDaily + '', 10) + LiveQuotaStore.Instance.getLiveQuotaOf(this.id)
43d0ea7f 906 : undefined,
9a82ce24 907
76314386
RK
908 videosCount: videosCount !== undefined
909 ? parseInt(videosCount + '', 10)
910 : undefined,
4f32032f
C
911 abusesCount: abusesCount
912 ? parseInt(abusesCount, 10)
76314386 913 : undefined,
4f32032f
C
914 abusesAcceptedCount: abusesAcceptedCount
915 ? parseInt(abusesAcceptedCount, 10)
76314386 916 : undefined,
4f32032f
C
917 abusesCreatedCount: abusesCreatedCount !== undefined
918 ? parseInt(abusesCreatedCount + '', 10)
76314386
RK
919 : undefined,
920 videoCommentsCount: videoCommentsCount !== undefined
921 ? parseInt(videoCommentsCount + '', 10)
922 : undefined,
43d0ea7f
C
923
924 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
925 noWelcomeModal: this.noWelcomeModal,
8f581725 926 noAccountSetupWarningModal: this.noAccountSetupWarningModal,
43d0ea7f 927
eacb25c4
C
928 blocked: this.blocked,
929 blockedReason: this.blockedReason,
43d0ea7f 930
c5911fd3 931 account: this.Account.toFormattedJSON(),
43d0ea7f
C
932
933 notificationSettings: this.NotificationSetting
934 ? this.NotificationSetting.toFormattedJSON()
935 : undefined,
936
a76138ff 937 videoChannels: [],
43d0ea7f 938
8bb71f2e
C
939 createdAt: this.createdAt,
940
3cc665f4
C
941 pluginAuth: this.pluginAuth,
942
943 lastLoginDate: this.lastLoginDate
3fd3ab2d
C
944 }
945
1eddc9a7
C
946 if (parameters.withAdminFlags) {
947 Object.assign(json, { adminFlags: this.adminFlags })
948 }
949
3fd3ab2d 950 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 951 json.videoChannels = this.Account.VideoChannels
a1587156
C
952 .map(c => c.toFormattedJSON())
953 .sort((v1, v2) => {
954 if (v1.createdAt < v2.createdAt) return -1
955 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 956
a1587156
C
957 return 1
958 })
ad4a8a1c 959 }
3fd3ab2d
C
960
961 return json
ad4a8a1c
C
962 }
963
ac0868bc 964 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
4e1592da 965 const formatted = this.toFormattedJSON({ withAdminFlags: true })
ac0868bc
C
966
967 const specialPlaylists = this.Account.VideoPlaylists
a1587156 968 .map(p => ({ id: p.id, name: p.name, type: p.type }))
ac0868bc
C
969
970 return Object.assign(formatted, { specialPlaylists })
971 }
b0f9f39e 972}