]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
add blocked filter in users list to filter banned users
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
5600def4 1import { col, FindOptions, fn, literal, Op, QueryTypes, where, WhereOptions } from 'sequelize'
3fd3ab2d 2import {
d175a6f7 3 AfterDestroy,
f201a749 4 AfterUpdate,
a73c582e
C
5 AllowNull,
6 BeforeCreate,
7 BeforeUpdate,
8 Column,
9 CreatedAt,
10 DataType,
11 Default,
12 DefaultScope,
13 HasMany,
14 HasOne,
15 Is,
16 IsEmail,
17 Model,
18 Scopes,
19 Table,
20 UpdatedAt
3fd3ab2d 21} from 'sequelize-typescript'
5600def4 22import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoAbuseState, VideoPlaylistType, VideoPrivacy } from '../../../shared'
ba75d268 23import { User, UserRole } from '../../../shared/models/users'
65fcc311 24import {
43d0ea7f 25 isNoInstanceConfigWarningModal,
ac0868bc 26 isNoWelcomeModal,
1eddc9a7 27 isUserAdminFlagsValid,
bee29df8 28 isUserAutoPlayNextVideoPlaylistValid,
ac0868bc
C
29 isUserAutoPlayNextVideoValid,
30 isUserAutoPlayVideoValid,
eacb25c4 31 isUserBlockedReasonValid,
e6921918 32 isUserBlockedValid,
d9eaee39 33 isUserEmailVerifiedValid,
5cf84858 34 isUserNSFWPolicyValid,
a73c582e
C
35 isUserPasswordValid,
36 isUserRoleValid,
37 isUserUsernameValid,
3caf77d3 38 isUserVideoLanguages,
5cf84858 39 isUserVideoQuotaDailyValid,
64cc5e85 40 isUserVideoQuotaValid,
cef534ed 41 isUserVideosHistoryEnabledValid,
ac0868bc 42 isUserWebTorrentEnabledValid
3fd3ab2d 43} from '../../helpers/custom-validators/users'
da854ddd 44import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
45import { OAuthTokenModel } from '../oauth/oauth-token'
46import { getSort, throwIfNotValid } from '../utils'
47import { VideoChannelModel } from '../video/video-channel'
29128b2f 48import { VideoPlaylistModel } from '../video/video-playlist'
3fd3ab2d 49import { AccountModel } from './account'
0883b324
C
50import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
51import { values } from 'lodash'
3f87a46f 52import { DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
f201a749 53import { clearCacheByUserId } from '../../lib/oauth-model'
cef534ed
C
54import { UserNotificationSettingModel } from './user-notification-setting'
55import { VideoModel } from '../video/video'
56import { ActorModel } from '../activitypub/actor'
57import { ActorFollowModel } from '../activitypub/actor-follow'
dc133480 58import { VideoImportModel } from '../video/video-import'
1eddc9a7 59import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
503c6f44 60import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
7cd4d2ba 61import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
453e83ea 62import * as Bluebird from 'bluebird'
1ca9f7c3 63import {
ac0868bc 64 MMyUserFormattable,
1ca9f7c3
C
65 MUserDefault,
66 MUserFormattable,
67 MUserId,
68 MUserNotifSettingChannelDefault,
ac0868bc
C
69 MUserWithNotificationSetting,
70 MVideoFullLight
26d6bf65 71} from '@server/types/models'
3fd3ab2d 72
9c2e0dbf 73enum ScopeNames {
76314386
RK
74 FOR_ME_API = 'FOR_ME_API',
75 WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',
76 WITH_STATS = 'WITH_STATS'
9c2e0dbf
C
77}
78
3acc5084 79@DefaultScope(() => ({
d48ff09d
C
80 include: [
81 {
3acc5084 82 model: AccountModel,
d48ff09d 83 required: true
cef534ed
C
84 },
85 {
3acc5084 86 model: UserNotificationSettingModel,
cef534ed 87 required: true
d48ff09d
C
88 }
89 ]
3acc5084
C
90}))
91@Scopes(() => ({
ac0868bc 92 [ScopeNames.FOR_ME_API]: {
d48ff09d
C
93 include: [
94 {
3acc5084 95 model: AccountModel,
ac0868bc
C
96 include: [
97 {
98 model: VideoChannelModel
99 },
100 {
101 attributes: [ 'id', 'name', 'type' ],
102 model: VideoPlaylistModel.unscoped(),
103 required: true,
104 where: {
105 type: {
a1587156 106 [Op.ne]: VideoPlaylistType.REGULAR
ac0868bc
C
107 }
108 }
109 }
110 ]
cef534ed
C
111 },
112 {
3acc5084 113 model: UserNotificationSettingModel,
cef534ed 114 required: true
d48ff09d 115 }
3acc5084 116 ]
76314386
RK
117 },
118 [ScopeNames.WITH_VIDEOCHANNELS]: {
119 include: [
120 {
121 model: AccountModel,
122 include: [
123 {
124 model: VideoChannelModel
125 },
126 {
127 attributes: [ 'id', 'name', 'type' ],
128 model: VideoPlaylistModel.unscoped(),
129 required: true,
130 where: {
131 type: {
132 [Op.ne]: VideoPlaylistType.REGULAR
133 }
134 }
135 }
136 ]
137 }
138 ]
139 },
140 [ScopeNames.WITH_STATS]: {
141 attributes: {
142 include: [
5600def4
C
143 [
144 literal(
145 '(' +
146 UserModel.generateUserQuotaBaseSQL({
147 withSelect: false,
148 whereUserId: '"UserModel"."id"'
149 }) +
150 ')'
151 ),
152 'videoQuotaUsed'
153 ],
76314386
RK
154 [
155 literal(
156 '(' +
157 'SELECT COUNT("video"."id") ' +
158 'FROM "video" ' +
159 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
160 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
161 'WHERE "account"."userId" = "UserModel"."id"' +
162 ')'
163 ),
164 'videosCount'
165 ],
166 [
167 literal(
168 '(' +
169 `SELECT concat_ws(':', "abuses", "acceptedAbuses") ` +
170 'FROM (' +
171 'SELECT COUNT("videoAbuse"."id") AS "abuses", ' +
172 `COUNT("videoAbuse"."id") FILTER (WHERE "videoAbuse"."state" = ${VideoAbuseState.ACCEPTED}) AS "acceptedAbuses" ` +
173 'FROM "videoAbuse" ' +
174 'INNER JOIN "video" ON "videoAbuse"."videoId" = "video"."id" ' +
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 ') t' +
179 ')'
180 ),
181 'videoAbusesCount'
182 ],
183 [
184 literal(
185 '(' +
186 'SELECT COUNT("videoAbuse"."id") ' +
187 'FROM "videoAbuse" ' +
188 'INNER JOIN "account" ON "account"."id" = "videoAbuse"."reporterAccountId" ' +
189 'WHERE "account"."userId" = "UserModel"."id"' +
190 ')'
191 ),
192 'videoAbusesCreatedCount'
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
C
221})
222export class UserModel extends Model<UserModel> {
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
3cc665f4
C
356 @AllowNull(true)
357 @Default(null)
358 @Column
359 lastLoginDate: Date
360
3fd3ab2d
C
361 @CreatedAt
362 createdAt: Date
363
364 @UpdatedAt
365 updatedAt: Date
366
367 @HasOne(() => AccountModel, {
368 foreignKey: 'userId',
f05a1c30
C
369 onDelete: 'cascade',
370 hooks: true
3fd3ab2d
C
371 })
372 Account: AccountModel
69b0a27c 373
cef534ed
C
374 @HasOne(() => UserNotificationSettingModel, {
375 foreignKey: 'userId',
376 onDelete: 'cascade',
377 hooks: true
378 })
379 NotificationSetting: UserNotificationSettingModel
380
dc133480
C
381 @HasMany(() => VideoImportModel, {
382 foreignKey: 'userId',
383 onDelete: 'cascade'
384 })
385 VideoImports: VideoImportModel[]
386
3fd3ab2d
C
387 @HasMany(() => OAuthTokenModel, {
388 foreignKey: 'userId',
389 onDelete: 'cascade'
390 })
391 OAuthTokens: OAuthTokenModel[]
392
393 @BeforeCreate
394 @BeforeUpdate
395 static cryptPasswordIfNeeded (instance: UserModel) {
e1c55031 396 if (instance.changed('password') && instance.password) {
3fd3ab2d
C
397 return cryptPassword(instance.password)
398 .then(hash => {
399 instance.password = hash
400 return undefined
401 })
402 }
59557c46 403 }
26d7d31b 404
f201a749 405 @AfterUpdate
d175a6f7 406 @AfterDestroy
f201a749
C
407 static removeTokenCache (instance: UserModel) {
408 return clearCacheByUserId(instance.id)
409 }
410
3fd3ab2d
C
411 static countTotal () {
412 return this.count()
413 }
954605a8 414
8491293b
RK
415 static listForApi (parameters: {
416 start: number
417 count: number
418 sort: string
419 search?: string
420 blocked?: boolean
421 }) {
422 const { start, count, sort, search, blocked } = parameters
423 const where: WhereOptions = {}
a1587156 424
24b9417c 425 if (search) {
8491293b 426 Object.assign(where, {
3acc5084 427 [Op.or]: [
24b9417c
C
428 {
429 email: {
3acc5084 430 [Op.iLike]: '%' + search + '%'
24b9417c
C
431 }
432 },
433 {
434 username: {
a1587156 435 [Op.iLike]: '%' + search + '%'
24b9417c
C
436 }
437 }
438 ]
8491293b
RK
439 })
440 }
441
442 if (blocked !== undefined) {
443 Object.assign(where, {
444 blocked: blocked
445 })
24b9417c
C
446 }
447
3acc5084 448 const query: FindOptions = {
a76138ff 449 attributes: {
5600def4
C
450 include: [
451 [
452 literal(
453 '(' +
454 UserModel.generateUserQuotaBaseSQL({
455 withSelect: false,
456 whereUserId: '"UserModel"."id"'
457 }) +
458 ')'
459 ),
460 'videoQuotaUsed'
461 ] as any // FIXME: typings
462 ]
a76138ff 463 },
3fd3ab2d
C
464 offset: start,
465 limit: count,
24b9417c
C
466 order: getSort(sort),
467 where
3fd3ab2d 468 }
72c7248b 469
3fd3ab2d 470 return UserModel.findAndCountAll(query)
a1587156
C
471 .then(({ rows, count }) => {
472 return {
473 data: rows,
474 total: count
475 }
476 })
72c7248b
C
477 }
478
453e83ea 479 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
ba75d268 480 const roles = Object.keys(USER_ROLE_LABELS)
a1587156
C
481 .map(k => parseInt(k, 10) as UserRole)
482 .filter(role => hasUserRight(role, right))
ba75d268 483
ba75d268 484 const query = {
ba75d268
C
485 where: {
486 role: {
3acc5084 487 [Op.in]: roles
ba75d268
C
488 }
489 }
490 }
491
cef534ed
C
492 return UserModel.findAll(query)
493 }
494
453e83ea 495 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
cef534ed
C
496 const query = {
497 include: [
498 {
499 model: UserNotificationSettingModel.unscoped(),
500 required: true
501 },
502 {
503 attributes: [ 'userId' ],
504 model: AccountModel.unscoped(),
505 required: true,
506 include: [
507 {
a1587156 508 attributes: [],
cef534ed
C
509 model: ActorModel.unscoped(),
510 required: true,
511 where: {
512 serverId: null
513 },
514 include: [
515 {
a1587156 516 attributes: [],
cef534ed
C
517 as: 'ActorFollowings',
518 model: ActorFollowModel.unscoped(),
519 required: true,
520 where: {
521 targetActorId: actorId
522 }
523 }
524 ]
525 }
526 ]
527 }
528 ]
529 }
530
531 return UserModel.unscoped().findAll(query)
ba75d268
C
532 }
533
453e83ea 534 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
f7cc67b4
C
535 const query = {
536 where: {
537 username: usernames
538 }
539 }
540
541 return UserModel.findAll(query)
542 }
543
76314386
RK
544 static loadById (id: number, withStats = false): Bluebird<MUserDefault> {
545 const scopes = [
546 ScopeNames.WITH_VIDEOCHANNELS
547 ]
548
549 if (withStats) scopes.push(ScopeNames.WITH_STATS)
550
551 return UserModel.scope(scopes).findByPk(id)
3fd3ab2d 552 }
feb4bdfd 553
453e83ea 554 static loadByUsername (username: string): Bluebird<MUserDefault> {
3fd3ab2d
C
555 const query = {
556 where: {
a1587156 557 username: { [Op.iLike]: username }
d48ff09d 558 }
3fd3ab2d 559 }
089ff2f2 560
3fd3ab2d 561 return UserModel.findOne(query)
feb4bdfd
C
562 }
563
ac0868bc 564 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
3fd3ab2d
C
565 const query = {
566 where: {
a1587156 567 username: { [Op.iLike]: username }
d48ff09d 568 }
3fd3ab2d 569 }
9bd26629 570
ac0868bc 571 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
feb4bdfd
C
572 }
573
453e83ea 574 static loadByEmail (email: string): Bluebird<MUserDefault> {
ecb4e35f
C
575 const query = {
576 where: {
577 email
578 }
579 }
580
581 return UserModel.findOne(query)
582 }
583
453e83ea 584 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
ba12e8b3
C
585 if (!email) email = username
586
3fd3ab2d 587 const query = {
3fd3ab2d 588 where: {
a1587156 589 [Op.or]: [
c4a1811e
C
590 where(fn('lower', col('username')), fn('lower', username)),
591
592 { email }
593 ]
3fd3ab2d 594 }
6fcd19ba 595 }
69b0a27c 596
d48ff09d 597 return UserModel.findOne(query)
72c7248b
C
598 }
599
453e83ea 600 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
cef534ed
C
601 const query = {
602 include: [
603 {
604 required: true,
605 attributes: [ 'id' ],
606 model: AccountModel.unscoped(),
607 include: [
608 {
609 required: true,
610 attributes: [ 'id' ],
611 model: VideoChannelModel.unscoped(),
612 include: [
613 {
614 required: true,
615 attributes: [ 'id' ],
616 model: VideoModel.unscoped(),
617 where: {
618 id: videoId
619 }
620 }
621 ]
622 }
623 ]
624 }
625 ]
626 }
627
628 return UserModel.findOne(query)
629 }
630
453e83ea 631 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
dc133480
C
632 const query = {
633 include: [
634 {
635 required: true,
636 attributes: [ 'id' ],
637 model: VideoImportModel.unscoped(),
638 where: {
639 id: videoImportId
640 }
641 }
642 ]
643 }
644
645 return UserModel.findOne(query)
646 }
647
453e83ea 648 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
f7cc67b4
C
649 const query = {
650 include: [
651 {
652 required: true,
653 attributes: [ 'id' ],
654 model: AccountModel.unscoped(),
655 include: [
656 {
657 required: true,
658 attributes: [ 'id' ],
659 model: VideoChannelModel.unscoped(),
660 where: {
661 actorId: videoChannelActorId
662 }
663 }
664 ]
665 }
666 ]
667 }
668
669 return UserModel.findOne(query)
670 }
671
453e83ea 672 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
f7cc67b4
C
673 const query = {
674 include: [
675 {
676 required: true,
677 attributes: [ 'id' ],
678 model: AccountModel.unscoped(),
679 where: {
680 actorId: accountActorId
681 }
682 }
683 ]
684 }
685
686 return UserModel.findOne(query)
687 }
688
453e83ea 689 static getOriginalVideoFileTotalFromUser (user: MUserId) {
3fd3ab2d 690 // Don't use sequelize because we need to use a sub query
5600def4
C
691 const query = UserModel.generateUserQuotaBaseSQL({
692 withSelect: true,
693 whereUserId: '$userId'
694 })
bee0abff 695
8b604880 696 return UserModel.getTotalRawQuery(query, user.id)
bee0abff
FA
697 }
698
8b604880 699 // Returns cumulative size of all video files uploaded in the last 24 hours.
453e83ea 700 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
bee0abff 701 // Don't use sequelize because we need to use a sub query
5600def4
C
702 const query = UserModel.generateUserQuotaBaseSQL({
703 withSelect: true,
704 whereUserId: '$userId',
705 where: '"video"."createdAt" > now() - interval \'24 hours\''
706 })
68a3b9f2 707
8b604880 708 return UserModel.getTotalRawQuery(query, user.id)
72c7248b
C
709 }
710
09cababd 711 static async getStats () {
3cc665f4
C
712 function getActiveUsers (days: number) {
713 const query = {
714 where: {
715 [Op.and]: [
716 literal(`"lastLoginDate" > NOW() - INTERVAL '${days}d'`)
717 ]
718 }
719 }
720
721 return UserModel.count(query)
722 }
723
09cababd 724 const totalUsers = await UserModel.count()
3cc665f4
C
725 const totalDailyActiveUsers = await getActiveUsers(1)
726 const totalWeeklyActiveUsers = await getActiveUsers(7)
727 const totalMonthlyActiveUsers = await getActiveUsers(30)
09cababd
C
728
729 return {
3cc665f4
C
730 totalUsers,
731 totalDailyActiveUsers,
732 totalWeeklyActiveUsers,
733 totalMonthlyActiveUsers
09cababd
C
734 }
735 }
736
5cf84858
C
737 static autoComplete (search: string) {
738 const query = {
739 where: {
740 username: {
a1587156 741 [Op.like]: `%${search}%`
5cf84858
C
742 }
743 },
744 limit: 10
745 }
746
747 return UserModel.findAll(query)
748 .then(u => u.map(u => u.username))
749 }
750
22a73cb8 751 canGetVideo (video: MVideoFullLight) {
2a5518a6 752 const videoUserId = video.VideoChannel.Account.userId
22a73cb8 753
2a5518a6
C
754 if (video.isBlacklisted()) {
755 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
22a73cb8
C
756 }
757
2a5518a6
C
758 if (video.privacy === VideoPrivacy.PRIVATE) {
759 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
22a73cb8
C
760 }
761
2a5518a6
C
762 if (video.privacy === VideoPrivacy.INTERNAL) return true
763
22a73cb8
C
764 return false
765 }
766
3fd3ab2d
C
767 hasRight (right: UserRight) {
768 return hasUserRight(this.role, right)
769 }
72c7248b 770
1eddc9a7
C
771 hasAdminFlag (flag: UserAdminFlag) {
772 return this.adminFlags & flag
773 }
774
3fd3ab2d
C
775 isPasswordMatch (password: string) {
776 return comparePassword(password, this.password)
feb4bdfd
C
777 }
778
ac0868bc 779 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
a76138ff 780 const videoQuotaUsed = this.get('videoQuotaUsed')
bee0abff 781 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
76314386
RK
782 const videosCount = this.get('videosCount')
783 const [ videoAbusesCount, videoAbusesAcceptedCount ] = (this.get('videoAbusesCount') as string || ':').split(':')
784 const videoAbusesCreatedCount = this.get('videoAbusesCreatedCount')
785 const videoCommentsCount = this.get('videoCommentsCount')
a76138ff 786
ac0868bc 787 const json: User = {
3fd3ab2d
C
788 id: this.id,
789 username: this.username,
790 email: this.email,
43d0ea7f
C
791 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
792
d1ab89de 793 pendingEmail: this.pendingEmail,
d9eaee39 794 emailVerified: this.emailVerified,
43d0ea7f 795
0883b324 796 nsfwPolicy: this.nsfwPolicy,
ed638e53 797 webTorrentEnabled: this.webTorrentEnabled,
276d9652 798 videosHistoryEnabled: this.videosHistoryEnabled,
7efe153b 799 autoPlayVideo: this.autoPlayVideo,
6aa54148 800 autoPlayNextVideo: this.autoPlayNextVideo,
bee29df8 801 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
3caf77d3 802 videoLanguages: this.videoLanguages,
43d0ea7f 803
3fd3ab2d 804 role: this.role,
a1587156 805 roleLabel: USER_ROLE_LABELS[this.role],
43d0ea7f 806
3fd3ab2d 807 videoQuota: this.videoQuota,
bee0abff 808 videoQuotaDaily: this.videoQuotaDaily,
43d0ea7f
C
809 videoQuotaUsed: videoQuotaUsed !== undefined
810 ? parseInt(videoQuotaUsed + '', 10)
811 : undefined,
812 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
813 ? parseInt(videoQuotaUsedDaily + '', 10)
814 : undefined,
76314386
RK
815 videosCount: videosCount !== undefined
816 ? parseInt(videosCount + '', 10)
817 : undefined,
818 videoAbusesCount: videoAbusesCount
819 ? parseInt(videoAbusesCount, 10)
820 : undefined,
821 videoAbusesAcceptedCount: videoAbusesAcceptedCount
822 ? parseInt(videoAbusesAcceptedCount, 10)
823 : undefined,
824 videoAbusesCreatedCount: videoAbusesCreatedCount !== undefined
825 ? parseInt(videoAbusesCreatedCount + '', 10)
826 : undefined,
827 videoCommentsCount: videoCommentsCount !== undefined
828 ? parseInt(videoCommentsCount + '', 10)
829 : undefined,
43d0ea7f
C
830
831 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
832 noWelcomeModal: this.noWelcomeModal,
833
eacb25c4
C
834 blocked: this.blocked,
835 blockedReason: this.blockedReason,
43d0ea7f 836
c5911fd3 837 account: this.Account.toFormattedJSON(),
43d0ea7f
C
838
839 notificationSettings: this.NotificationSetting
840 ? this.NotificationSetting.toFormattedJSON()
841 : undefined,
842
a76138ff 843 videoChannels: [],
43d0ea7f 844
8bb71f2e
C
845 createdAt: this.createdAt,
846
3cc665f4
C
847 pluginAuth: this.pluginAuth,
848
849 lastLoginDate: this.lastLoginDate
3fd3ab2d
C
850 }
851
1eddc9a7
C
852 if (parameters.withAdminFlags) {
853 Object.assign(json, { adminFlags: this.adminFlags })
854 }
855
3fd3ab2d 856 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 857 json.videoChannels = this.Account.VideoChannels
a1587156
C
858 .map(c => c.toFormattedJSON())
859 .sort((v1, v2) => {
860 if (v1.createdAt < v2.createdAt) return -1
861 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 862
a1587156
C
863 return 1
864 })
ad4a8a1c 865 }
3fd3ab2d
C
866
867 return json
ad4a8a1c
C
868 }
869
ac0868bc
C
870 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
871 const formatted = this.toFormattedJSON()
872
873 const specialPlaylists = this.Account.VideoPlaylists
a1587156 874 .map(p => ({ id: p.id, name: p.name, type: p.type }))
ac0868bc
C
875
876 return Object.assign(formatted, { specialPlaylists })
877 }
878
bee0abff
FA
879 async isAbleToUploadVideo (videoFile: { size: number }) {
880 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
b0f9f39e 881
bee0abff
FA
882 const [ totalBytes, totalBytesDaily ] = await Promise.all([
883 UserModel.getOriginalVideoFileTotalFromUser(this),
884 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
885 ])
886
887 const uploadedTotal = videoFile.size + totalBytes
888 const uploadedDaily = videoFile.size + totalBytesDaily
bee0abff 889
3acc5084
C
890 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
891 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
892
893 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
b0f9f39e 894 }
8b604880 895
5600def4
C
896 private static generateUserQuotaBaseSQL (options: {
897 whereUserId: '$userId' | '"UserModel"."id"'
898 withSelect: boolean
899 where?: string
900 }) {
901 const andWhere = options.where
902 ? 'AND ' + options.where
903 : ''
8b604880 904
5600def4 905 const videoChannelJoin = 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
a1587156 906 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
5600def4
C
907 `WHERE "account"."userId" = ${options.whereUserId} ${andWhere}`
908
909 const webtorrentFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
910 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
911 videoChannelJoin
912
913 const hlsFiles = 'SELECT "videoFile"."size" AS "size", "video"."id" AS "videoId" FROM "videoFile" ' +
914 'INNER JOIN "videoStreamingPlaylist" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id ' +
915 'INNER JOIN "video" ON "videoStreamingPlaylist"."videoId" = "video"."id" ' +
916 videoChannelJoin
917
918 return 'SELECT COALESCE(SUM("size"), 0) AS "total" ' +
919 'FROM (' +
920 `SELECT MAX("t1"."size") AS "size" FROM (${webtorrentFiles} UNION ${hlsFiles}) t1 ` +
921 'GROUP BY "t1"."videoId"' +
922 ') t2'
8b604880
C
923 }
924
925 private static getTotalRawQuery (query: string, userId: number) {
926 const options = {
927 bind: { userId },
3acc5084 928 type: QueryTypes.SELECT as QueryTypes.SELECT
8b604880
C
929 }
930
3acc5084 931 return UserModel.sequelize.query<{ total: string }>(query, options)
8b604880
C
932 .then(([ { total } ]) => {
933 if (total === null) return 0
934
3acc5084 935 return parseInt(total, 10)
8b604880
C
936 })
937 }
b0f9f39e 938}