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