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