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