]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
Skip videos count on client if we don't use it
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import { FindOptions, literal, Op, QueryTypes } from 'sequelize'
2 import {
3 AfterDestroy,
4 AfterUpdate,
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
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
24 import {
25 isNoInstanceConfigWarningModal,
26 isNoWelcomeModal,
27 isUserAdminFlagsValid,
28 isUserAutoPlayNextVideoPlaylistValid,
29 isUserAutoPlayNextVideoValid,
30 isUserAutoPlayVideoValid,
31 isUserBlockedReasonValid,
32 isUserBlockedValid,
33 isUserEmailVerifiedValid,
34 isUserNSFWPolicyValid,
35 isUserPasswordValid,
36 isUserRoleValid,
37 isUserUsernameValid,
38 isUserVideoLanguages,
39 isUserVideoQuotaDailyValid,
40 isUserVideoQuotaValid,
41 isUserVideosHistoryEnabledValid,
42 isUserWebTorrentEnabledValid
43 } from '../../helpers/custom-validators/users'
44 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
45 import { OAuthTokenModel } from '../oauth/oauth-token'
46 import { getSort, throwIfNotValid } from '../utils'
47 import { VideoChannelModel } from '../video/video-channel'
48 import { VideoPlaylistModel } from '../video/video-playlist'
49 import { AccountModel } from './account'
50 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
51 import { values } from 'lodash'
52 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
53 import { clearCacheByUserId } from '../../lib/oauth-model'
54 import { UserNotificationSettingModel } from './user-notification-setting'
55 import { VideoModel } from '../video/video'
56 import { ActorModel } from '../activitypub/actor'
57 import { ActorFollowModel } from '../activitypub/actor-follow'
58 import { VideoImportModel } from '../video/video-import'
59 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
60 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
61 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
62 import * as Bluebird from 'bluebird'
63 import {
64 MMyUserFormattable,
65 MUserDefault,
66 MUserFormattable,
67 MUserId,
68 MUserNotifSettingChannelDefault,
69 MUserWithNotificationSetting,
70 MVideoFullLight
71 } from '@server/typings/models'
72
73 enum ScopeNames {
74 FOR_ME_API = 'FOR_ME_API'
75 }
76
77 @DefaultScope(() => ({
78 include: [
79 {
80 model: AccountModel,
81 required: true
82 },
83 {
84 model: UserNotificationSettingModel,
85 required: true
86 }
87 ]
88 }))
89 @Scopes(() => ({
90 [ScopeNames.FOR_ME_API]: {
91 include: [
92 {
93 model: AccountModel,
94 include: [
95 {
96 model: VideoChannelModel
97 },
98 {
99 attributes: [ 'id', 'name', 'type' ],
100 model: VideoPlaylistModel.unscoped(),
101 required: true,
102 where: {
103 type: {
104 [ Op.ne ]: VideoPlaylistType.REGULAR
105 }
106 }
107 }
108 ]
109 },
110 {
111 model: UserNotificationSettingModel,
112 required: true
113 }
114 ]
115 }
116 }))
117 @Table({
118 tableName: 'user',
119 indexes: [
120 {
121 fields: [ 'username' ],
122 unique: true
123 },
124 {
125 fields: [ 'email' ],
126 unique: true
127 }
128 ]
129 })
130 export class UserModel extends Model<UserModel> {
131
132 @AllowNull(false)
133 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
134 @Column
135 password: string
136
137 @AllowNull(false)
138 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
139 @Column
140 username: string
141
142 @AllowNull(false)
143 @IsEmail
144 @Column(DataType.STRING(400))
145 email: string
146
147 @AllowNull(true)
148 @IsEmail
149 @Column(DataType.STRING(400))
150 pendingEmail: string
151
152 @AllowNull(true)
153 @Default(null)
154 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
155 @Column
156 emailVerified: boolean
157
158 @AllowNull(false)
159 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
160 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
161 nsfwPolicy: NSFWPolicyType
162
163 @AllowNull(false)
164 @Default(true)
165 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
166 @Column
167 webTorrentEnabled: boolean
168
169 @AllowNull(false)
170 @Default(true)
171 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
172 @Column
173 videosHistoryEnabled: boolean
174
175 @AllowNull(false)
176 @Default(true)
177 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
178 @Column
179 autoPlayVideo: boolean
180
181 @AllowNull(false)
182 @Default(false)
183 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
184 @Column
185 autoPlayNextVideo: boolean
186
187 @AllowNull(false)
188 @Default(true)
189 @Is('UserAutoPlayNextVideoPlaylist', value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean'))
190 @Column
191 autoPlayNextVideoPlaylist: boolean
192
193 @AllowNull(true)
194 @Default(null)
195 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
196 @Column(DataType.ARRAY(DataType.STRING))
197 videoLanguages: string[]
198
199 @AllowNull(false)
200 @Default(UserAdminFlag.NONE)
201 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
202 @Column
203 adminFlags?: UserAdminFlag
204
205 @AllowNull(false)
206 @Default(false)
207 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
208 @Column
209 blocked: boolean
210
211 @AllowNull(true)
212 @Default(null)
213 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
214 @Column
215 blockedReason: string
216
217 @AllowNull(false)
218 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
219 @Column
220 role: number
221
222 @AllowNull(false)
223 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
224 @Column(DataType.BIGINT)
225 videoQuota: number
226
227 @AllowNull(false)
228 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
229 @Column(DataType.BIGINT)
230 videoQuotaDaily: number
231
232 @AllowNull(false)
233 @Default(DEFAULT_THEME_NAME)
234 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
235 @Column
236 theme: string
237
238 @AllowNull(false)
239 @Default(false)
240 @Is(
241 'UserNoInstanceConfigWarningModal',
242 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
243 )
244 @Column
245 noInstanceConfigWarningModal: boolean
246
247 @AllowNull(false)
248 @Default(false)
249 @Is(
250 'UserNoInstanceConfigWarningModal',
251 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
252 )
253 @Column
254 noWelcomeModal: boolean
255
256 @CreatedAt
257 createdAt: Date
258
259 @UpdatedAt
260 updatedAt: Date
261
262 @HasOne(() => AccountModel, {
263 foreignKey: 'userId',
264 onDelete: 'cascade',
265 hooks: true
266 })
267 Account: AccountModel
268
269 @HasOne(() => UserNotificationSettingModel, {
270 foreignKey: 'userId',
271 onDelete: 'cascade',
272 hooks: true
273 })
274 NotificationSetting: UserNotificationSettingModel
275
276 @HasMany(() => VideoImportModel, {
277 foreignKey: 'userId',
278 onDelete: 'cascade'
279 })
280 VideoImports: VideoImportModel[]
281
282 @HasMany(() => OAuthTokenModel, {
283 foreignKey: 'userId',
284 onDelete: 'cascade'
285 })
286 OAuthTokens: OAuthTokenModel[]
287
288 @BeforeCreate
289 @BeforeUpdate
290 static cryptPasswordIfNeeded (instance: UserModel) {
291 if (instance.changed('password')) {
292 return cryptPassword(instance.password)
293 .then(hash => {
294 instance.password = hash
295 return undefined
296 })
297 }
298 }
299
300 @AfterUpdate
301 @AfterDestroy
302 static removeTokenCache (instance: UserModel) {
303 return clearCacheByUserId(instance.id)
304 }
305
306 static countTotal () {
307 return this.count()
308 }
309
310 static listForApi (start: number, count: number, sort: string, search?: string) {
311 let where = undefined
312 if (search) {
313 where = {
314 [Op.or]: [
315 {
316 email: {
317 [Op.iLike]: '%' + search + '%'
318 }
319 },
320 {
321 username: {
322 [ Op.iLike ]: '%' + search + '%'
323 }
324 }
325 ]
326 }
327 }
328
329 const query: FindOptions = {
330 attributes: {
331 include: [
332 [
333 literal(
334 '(' +
335 'SELECT COALESCE(SUM("size"), 0) ' +
336 'FROM (' +
337 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
338 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
339 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
340 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
341 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
342 ') t' +
343 ')'
344 ),
345 'videoQuotaUsed'
346 ]
347 ]
348 },
349 offset: start,
350 limit: count,
351 order: getSort(sort),
352 where
353 }
354
355 return UserModel.findAndCountAll(query)
356 .then(({ rows, count }) => {
357 return {
358 data: rows,
359 total: count
360 }
361 })
362 }
363
364 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
365 const roles = Object.keys(USER_ROLE_LABELS)
366 .map(k => parseInt(k, 10) as UserRole)
367 .filter(role => hasUserRight(role, right))
368
369 const query = {
370 where: {
371 role: {
372 [Op.in]: roles
373 }
374 }
375 }
376
377 return UserModel.findAll(query)
378 }
379
380 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
381 const query = {
382 include: [
383 {
384 model: UserNotificationSettingModel.unscoped(),
385 required: true
386 },
387 {
388 attributes: [ 'userId' ],
389 model: AccountModel.unscoped(),
390 required: true,
391 include: [
392 {
393 attributes: [ ],
394 model: ActorModel.unscoped(),
395 required: true,
396 where: {
397 serverId: null
398 },
399 include: [
400 {
401 attributes: [ ],
402 as: 'ActorFollowings',
403 model: ActorFollowModel.unscoped(),
404 required: true,
405 where: {
406 targetActorId: actorId
407 }
408 }
409 ]
410 }
411 ]
412 }
413 ]
414 }
415
416 return UserModel.unscoped().findAll(query)
417 }
418
419 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
420 const query = {
421 where: {
422 username: usernames
423 }
424 }
425
426 return UserModel.findAll(query)
427 }
428
429 static loadById (id: number): Bluebird<MUserDefault> {
430 return UserModel.findByPk(id)
431 }
432
433 static loadByUsername (username: string): Bluebird<MUserDefault> {
434 const query = {
435 where: {
436 username: { [ Op.iLike ]: username }
437 }
438 }
439
440 return UserModel.findOne(query)
441 }
442
443 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
444 const query = {
445 where: {
446 username: { [ Op.iLike ]: username }
447 }
448 }
449
450 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
451 }
452
453 static loadByEmail (email: string): Bluebird<MUserDefault> {
454 const query = {
455 where: {
456 email
457 }
458 }
459
460 return UserModel.findOne(query)
461 }
462
463 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
464 if (!email) email = username
465
466 const query = {
467 where: {
468 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
469 }
470 }
471
472 return UserModel.findOne(query)
473 }
474
475 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
476 const query = {
477 include: [
478 {
479 required: true,
480 attributes: [ 'id' ],
481 model: AccountModel.unscoped(),
482 include: [
483 {
484 required: true,
485 attributes: [ 'id' ],
486 model: VideoChannelModel.unscoped(),
487 include: [
488 {
489 required: true,
490 attributes: [ 'id' ],
491 model: VideoModel.unscoped(),
492 where: {
493 id: videoId
494 }
495 }
496 ]
497 }
498 ]
499 }
500 ]
501 }
502
503 return UserModel.findOne(query)
504 }
505
506 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
507 const query = {
508 include: [
509 {
510 required: true,
511 attributes: [ 'id' ],
512 model: VideoImportModel.unscoped(),
513 where: {
514 id: videoImportId
515 }
516 }
517 ]
518 }
519
520 return UserModel.findOne(query)
521 }
522
523 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
524 const query = {
525 include: [
526 {
527 required: true,
528 attributes: [ 'id' ],
529 model: AccountModel.unscoped(),
530 include: [
531 {
532 required: true,
533 attributes: [ 'id' ],
534 model: VideoChannelModel.unscoped(),
535 where: {
536 actorId: videoChannelActorId
537 }
538 }
539 ]
540 }
541 ]
542 }
543
544 return UserModel.findOne(query)
545 }
546
547 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
548 const query = {
549 include: [
550 {
551 required: true,
552 attributes: [ 'id' ],
553 model: AccountModel.unscoped(),
554 where: {
555 actorId: accountActorId
556 }
557 }
558 ]
559 }
560
561 return UserModel.findOne(query)
562 }
563
564 static getOriginalVideoFileTotalFromUser (user: MUserId) {
565 // Don't use sequelize because we need to use a sub query
566 const query = UserModel.generateUserQuotaBaseSQL()
567
568 return UserModel.getTotalRawQuery(query, user.id)
569 }
570
571 // Returns cumulative size of all video files uploaded in the last 24 hours.
572 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
573 // Don't use sequelize because we need to use a sub query
574 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
575
576 return UserModel.getTotalRawQuery(query, user.id)
577 }
578
579 static async getStats () {
580 const totalUsers = await UserModel.count()
581
582 return {
583 totalUsers
584 }
585 }
586
587 static autoComplete (search: string) {
588 const query = {
589 where: {
590 username: {
591 [ Op.like ]: `%${search}%`
592 }
593 },
594 limit: 10
595 }
596
597 return UserModel.findAll(query)
598 .then(u => u.map(u => u.username))
599 }
600
601 canGetVideo (video: MVideoFullLight) {
602 const videoUserId = video.VideoChannel.Account.userId
603
604 if (video.isBlacklisted()) {
605 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
606 }
607
608 if (video.privacy === VideoPrivacy.PRIVATE) {
609 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
610 }
611
612 if (video.privacy === VideoPrivacy.INTERNAL) return true
613
614 return false
615 }
616
617 hasRight (right: UserRight) {
618 return hasUserRight(this.role, right)
619 }
620
621 hasAdminFlag (flag: UserAdminFlag) {
622 return this.adminFlags & flag
623 }
624
625 isPasswordMatch (password: string) {
626 return comparePassword(password, this.password)
627 }
628
629 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
630 const videoQuotaUsed = this.get('videoQuotaUsed')
631 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
632
633 const json: User = {
634 id: this.id,
635 username: this.username,
636 email: this.email,
637 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
638
639 pendingEmail: this.pendingEmail,
640 emailVerified: this.emailVerified,
641
642 nsfwPolicy: this.nsfwPolicy,
643 webTorrentEnabled: this.webTorrentEnabled,
644 videosHistoryEnabled: this.videosHistoryEnabled,
645 autoPlayVideo: this.autoPlayVideo,
646 autoPlayNextVideo: this.autoPlayNextVideo,
647 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
648 videoLanguages: this.videoLanguages,
649
650 role: this.role,
651 roleLabel: USER_ROLE_LABELS[ this.role ],
652
653 videoQuota: this.videoQuota,
654 videoQuotaDaily: this.videoQuotaDaily,
655 videoQuotaUsed: videoQuotaUsed !== undefined
656 ? parseInt(videoQuotaUsed + '', 10)
657 : undefined,
658 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
659 ? parseInt(videoQuotaUsedDaily + '', 10)
660 : undefined,
661
662 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
663 noWelcomeModal: this.noWelcomeModal,
664
665 blocked: this.blocked,
666 blockedReason: this.blockedReason,
667
668 account: this.Account.toFormattedJSON(),
669
670 notificationSettings: this.NotificationSetting
671 ? this.NotificationSetting.toFormattedJSON()
672 : undefined,
673
674 videoChannels: [],
675
676 createdAt: this.createdAt
677 }
678
679 if (parameters.withAdminFlags) {
680 Object.assign(json, { adminFlags: this.adminFlags })
681 }
682
683 if (Array.isArray(this.Account.VideoChannels) === true) {
684 json.videoChannels = this.Account.VideoChannels
685 .map(c => c.toFormattedJSON())
686 .sort((v1, v2) => {
687 if (v1.createdAt < v2.createdAt) return -1
688 if (v1.createdAt === v2.createdAt) return 0
689
690 return 1
691 })
692 }
693
694 return json
695 }
696
697 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
698 const formatted = this.toFormattedJSON()
699
700 const specialPlaylists = this.Account.VideoPlaylists
701 .map(p => ({ id: p.id, name: p.name, type: p.type }))
702
703 return Object.assign(formatted, { specialPlaylists })
704 }
705
706 async isAbleToUploadVideo (videoFile: { size: number }) {
707 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
708
709 const [ totalBytes, totalBytesDaily ] = await Promise.all([
710 UserModel.getOriginalVideoFileTotalFromUser(this),
711 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
712 ])
713
714 const uploadedTotal = videoFile.size + totalBytes
715 const uploadedDaily = videoFile.size + totalBytesDaily
716
717 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
718 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
719
720 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
721 }
722
723 private static generateUserQuotaBaseSQL (where?: string) {
724 const andWhere = where ? 'AND ' + where : ''
725
726 return 'SELECT SUM("size") AS "total" ' +
727 'FROM (' +
728 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
729 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
730 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
731 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
732 'WHERE "account"."userId" = $userId ' + andWhere +
733 'GROUP BY "video"."id"' +
734 ') t'
735 }
736
737 private static getTotalRawQuery (query: string, userId: number) {
738 const options = {
739 bind: { userId },
740 type: QueryTypes.SELECT as QueryTypes.SELECT
741 }
742
743 return UserModel.sequelize.query<{ total: string }>(query, options)
744 .then(([ { total } ]) => {
745 if (total === null) return 0
746
747 return parseInt(total, 10)
748 })
749 }
750 }