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