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