1 import { FindOptions, literal, Op, QueryTypes } from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isUserAdminFlagsValid,
26 isUserAutoPlayVideoValid,
27 isUserBlockedReasonValid,
29 isUserEmailVerifiedValid,
30 isUserNSFWPolicyValid,
35 isUserVideoQuotaDailyValid,
36 isUserVideoQuotaValid,
37 isUserVideosHistoryEnabledValid,
38 isUserWebTorrentEnabledValid
39 } from '../../helpers/custom-validators/users'
40 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
41 import { OAuthTokenModel } from '../oauth/oauth-token'
42 import { getSort, throwIfNotValid } from '../utils'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { AccountModel } from './account'
45 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
46 import { values } from 'lodash'
47 import { NSFW_POLICY_TYPES } from '../../initializers/constants'
48 import { clearCacheByUserId } from '../../lib/oauth-model'
49 import { UserNotificationSettingModel } from './user-notification-setting'
50 import { VideoModel } from '../video/video'
51 import { ActorModel } from '../activitypub/actor'
52 import { ActorFollowModel } from '../activitypub/actor-follow'
53 import { VideoImportModel } from '../video/video-import'
54 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
57 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
60 @DefaultScope(() => ({
67 model: UserNotificationSettingModel,
73 [ScopeNames.WITH_VIDEO_CHANNEL]: {
78 include: [ VideoChannelModel ]
81 model: UserNotificationSettingModel,
91 fields: [ 'username' ],
100 export class UserModel extends Model<UserModel> {
103 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
108 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
114 @Column(DataType.STRING(400))
119 @Column(DataType.STRING(400))
124 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
126 emailVerified: boolean
129 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
130 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
131 nsfwPolicy: NSFWPolicyType
135 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
137 webTorrentEnabled: boolean
141 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
143 videosHistoryEnabled: boolean
147 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
149 autoPlayVideo: boolean
153 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
154 @Column(DataType.ARRAY(DataType.STRING))
155 videoLanguages: string[]
158 @Default(UserAdminFlag.NONE)
159 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
161 adminFlags?: UserAdminFlag
165 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
171 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
173 blockedReason: string
176 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
181 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
182 @Column(DataType.BIGINT)
186 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
187 @Column(DataType.BIGINT)
188 videoQuotaDaily: number
196 @HasOne(() => AccountModel, {
197 foreignKey: 'userId',
201 Account: AccountModel
203 @HasOne(() => UserNotificationSettingModel, {
204 foreignKey: 'userId',
208 NotificationSetting: UserNotificationSettingModel
210 @HasMany(() => VideoImportModel, {
211 foreignKey: 'userId',
214 VideoImports: VideoImportModel[]
216 @HasMany(() => OAuthTokenModel, {
217 foreignKey: 'userId',
220 OAuthTokens: OAuthTokenModel[]
224 static cryptPasswordIfNeeded (instance: UserModel) {
225 if (instance.changed('password')) {
226 return cryptPassword(instance.password)
228 instance.password = hash
236 static removeTokenCache (instance: UserModel) {
237 return clearCacheByUserId(instance.id)
240 static countTotal () {
244 static listForApi (start: number, count: number, sort: string, search?: string) {
245 let where = undefined
251 [Op.iLike]: '%' + search + '%'
256 [ Op.iLike ]: '%' + search + '%'
263 const query: FindOptions = {
269 'SELECT COALESCE(SUM("size"), 0) ' +
271 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
272 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
273 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
274 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
275 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
285 order: getSort(sort),
289 return UserModel.findAndCountAll(query)
290 .then(({ rows, count }) => {
298 static listWithRight (right: UserRight) {
299 const roles = Object.keys(USER_ROLE_LABELS)
300 .map(k => parseInt(k, 10) as UserRole)
301 .filter(role => hasUserRight(role, right))
311 return UserModel.findAll(query)
314 static listUserSubscribersOf (actorId: number) {
318 model: UserNotificationSettingModel.unscoped(),
322 attributes: [ 'userId' ],
323 model: AccountModel.unscoped(),
328 model: ActorModel.unscoped(),
336 as: 'ActorFollowings',
337 model: ActorFollowModel.unscoped(),
340 targetActorId: actorId
350 return UserModel.unscoped().findAll(query)
353 static listByUsernames (usernames: string[]) {
360 return UserModel.findAll(query)
363 static loadById (id: number) {
364 return UserModel.findByPk(id)
367 static loadByUsername (username: string) {
370 username: { [ Op.iLike ]: username }
374 return UserModel.findOne(query)
377 static loadByUsernameAndPopulateChannels (username: string) {
380 username: { [ Op.iLike ]: username }
384 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
387 static loadByEmail (email: string) {
394 return UserModel.findOne(query)
397 static loadByUsernameOrEmail (username: string, email?: string) {
398 if (!email) email = username
402 [ Op.or ]: [ { username: { [ Op.iLike ]: username } }, { email } ]
406 return UserModel.findOne(query)
409 static loadByVideoId (videoId: number) {
414 attributes: [ 'id' ],
415 model: AccountModel.unscoped(),
419 attributes: [ 'id' ],
420 model: VideoChannelModel.unscoped(),
424 attributes: [ 'id' ],
425 model: VideoModel.unscoped(),
437 return UserModel.findOne(query)
440 static loadByVideoImportId (videoImportId: number) {
445 attributes: [ 'id' ],
446 model: VideoImportModel.unscoped(),
454 return UserModel.findOne(query)
457 static loadByChannelActorId (videoChannelActorId: number) {
462 attributes: [ 'id' ],
463 model: AccountModel.unscoped(),
467 attributes: [ 'id' ],
468 model: VideoChannelModel.unscoped(),
470 actorId: videoChannelActorId
478 return UserModel.findOne(query)
481 static loadByAccountActorId (accountActorId: number) {
486 attributes: [ 'id' ],
487 model: AccountModel.unscoped(),
489 actorId: accountActorId
495 return UserModel.findOne(query)
498 static getOriginalVideoFileTotalFromUser (user: UserModel) {
499 // Don't use sequelize because we need to use a sub query
500 const query = UserModel.generateUserQuotaBaseSQL()
502 return UserModel.getTotalRawQuery(query, user.id)
505 // Returns cumulative size of all video files uploaded in the last 24 hours.
506 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
507 // Don't use sequelize because we need to use a sub query
508 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
510 return UserModel.getTotalRawQuery(query, user.id)
513 static async getStats () {
514 const totalUsers = await UserModel.count()
521 static autoComplete (search: string) {
525 [ Op.like ]: `%${search}%`
531 return UserModel.findAll(query)
532 .then(u => u.map(u => u.username))
535 hasRight (right: UserRight) {
536 return hasUserRight(this.role, right)
539 hasAdminFlag (flag: UserAdminFlag) {
540 return this.adminFlags & flag
543 isPasswordMatch (password: string) {
544 return comparePassword(password, this.password)
547 toFormattedJSON (parameters: { withAdminFlags?: boolean } = {}): User {
548 const videoQuotaUsed = this.get('videoQuotaUsed')
549 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
553 username: this.username,
555 pendingEmail: this.pendingEmail,
556 emailVerified: this.emailVerified,
557 nsfwPolicy: this.nsfwPolicy,
558 webTorrentEnabled: this.webTorrentEnabled,
559 videosHistoryEnabled: this.videosHistoryEnabled,
560 autoPlayVideo: this.autoPlayVideo,
561 videoLanguages: this.videoLanguages,
563 roleLabel: USER_ROLE_LABELS[ this.role ],
564 videoQuota: this.videoQuota,
565 videoQuotaDaily: this.videoQuotaDaily,
566 createdAt: this.createdAt,
567 blocked: this.blocked,
568 blockedReason: this.blockedReason,
569 account: this.Account.toFormattedJSON(),
570 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
572 videoQuotaUsed: videoQuotaUsed !== undefined
573 ? parseInt(videoQuotaUsed + '', 10)
575 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
576 ? parseInt(videoQuotaUsedDaily + '', 10)
580 if (parameters.withAdminFlags) {
581 Object.assign(json, { adminFlags: this.adminFlags })
584 if (Array.isArray(this.Account.VideoChannels) === true) {
585 json.videoChannels = this.Account.VideoChannels
586 .map(c => c.toFormattedJSON())
588 if (v1.createdAt < v2.createdAt) return -1
589 if (v1.createdAt === v2.createdAt) return 0
598 async isAbleToUploadVideo (videoFile: { size: number }) {
599 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
601 const [ totalBytes, totalBytesDaily ] = await Promise.all([
602 UserModel.getOriginalVideoFileTotalFromUser(this),
603 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
606 const uploadedTotal = videoFile.size + totalBytes
607 const uploadedDaily = videoFile.size + totalBytesDaily
609 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
610 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
612 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
615 private static generateUserQuotaBaseSQL (where?: string) {
616 const andWhere = where ? 'AND ' + where : ''
618 return 'SELECT SUM("size") AS "total" ' +
620 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
621 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
622 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
623 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
624 'WHERE "account"."userId" = $userId ' + andWhere +
625 'GROUP BY "video"."id"' +
629 private static getTotalRawQuery (query: string, userId: number) {
632 type: QueryTypes.SELECT as QueryTypes.SELECT
635 return UserModel.sequelize.query<{ total: string }>(query, options)
636 .then(([ { total } ]) => {
637 if (total === null) return 0
639 return parseInt(total, 10)