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