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