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,
34 isUserVideoQuotaDailyValid,
35 isUserVideoQuotaValid,
36 isUserVideosHistoryEnabledValid,
37 isUserWebTorrentEnabledValid
38 } from '../../helpers/custom-validators/users'
39 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
40 import { OAuthTokenModel } from '../oauth/oauth-token'
41 import { getSort, throwIfNotValid } from '../utils'
42 import { VideoChannelModel } from '../video/video-channel'
43 import { AccountModel } from './account'
44 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
45 import { values } from 'lodash'
46 import { NSFW_POLICY_TYPES } from '../../initializers/constants'
47 import { clearCacheByUserId } from '../../lib/oauth-model'
48 import { UserNotificationSettingModel } from './user-notification-setting'
49 import { VideoModel } from '../video/video'
50 import { ActorModel } from '../activitypub/actor'
51 import { ActorFollowModel } from '../activitypub/actor-follow'
52 import { VideoImportModel } from '../video/video-import'
53 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
56 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
59 @DefaultScope(() => ({
66 model: UserNotificationSettingModel,
72 [ScopeNames.WITH_VIDEO_CHANNEL]: {
77 include: [ VideoChannelModel ]
80 model: UserNotificationSettingModel,
90 fields: [ 'username' ],
99 export class UserModel extends Model<UserModel> {
102 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
107 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
113 @Column(DataType.STRING(400))
118 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
120 emailVerified: boolean
123 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
124 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
125 nsfwPolicy: NSFWPolicyType
129 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
131 webTorrentEnabled: boolean
135 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
137 videosHistoryEnabled: boolean
141 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
143 autoPlayVideo: boolean
146 @Default(UserAdminFlag.NONE)
147 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
149 adminFlags?: UserAdminFlag
153 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
159 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
161 blockedReason: string
164 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
169 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
170 @Column(DataType.BIGINT)
174 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
175 @Column(DataType.BIGINT)
176 videoQuotaDaily: number
184 @HasOne(() => AccountModel, {
185 foreignKey: 'userId',
189 Account: AccountModel
191 @HasOne(() => UserNotificationSettingModel, {
192 foreignKey: 'userId',
196 NotificationSetting: UserNotificationSettingModel
198 @HasMany(() => VideoImportModel, {
199 foreignKey: 'userId',
202 VideoImports: VideoImportModel[]
204 @HasMany(() => OAuthTokenModel, {
205 foreignKey: 'userId',
208 OAuthTokens: OAuthTokenModel[]
212 static cryptPasswordIfNeeded (instance: UserModel) {
213 if (instance.changed('password')) {
214 return cryptPassword(instance.password)
216 instance.password = hash
224 static removeTokenCache (instance: UserModel) {
225 return clearCacheByUserId(instance.id)
228 static countTotal () {
232 static listForApi (start: number, count: number, sort: string, search?: string) {
233 let where = undefined
239 [Op.iLike]: '%' + search + '%'
244 [ Op.iLike ]: '%' + search + '%'
251 const query: FindOptions = {
257 'SELECT COALESCE(SUM("size"), 0) ' +
259 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
260 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
261 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
262 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
263 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
273 order: getSort(sort),
277 return UserModel.findAndCountAll(query)
278 .then(({ rows, count }) => {
286 static listWithRight (right: UserRight) {
287 const roles = Object.keys(USER_ROLE_LABELS)
288 .map(k => parseInt(k, 10) as UserRole)
289 .filter(role => hasUserRight(role, right))
299 return UserModel.findAll(query)
302 static listUserSubscribersOf (actorId: number) {
306 model: UserNotificationSettingModel.unscoped(),
310 attributes: [ 'userId' ],
311 model: AccountModel.unscoped(),
316 model: ActorModel.unscoped(),
324 as: 'ActorFollowings',
325 model: ActorFollowModel.unscoped(),
328 targetActorId: actorId
338 return UserModel.unscoped().findAll(query)
341 static listByUsernames (usernames: string[]) {
348 return UserModel.findAll(query)
351 static loadById (id: number) {
352 return UserModel.findByPk(id)
355 static loadByUsername (username: string) {
362 return UserModel.findOne(query)
365 static loadByUsernameAndPopulateChannels (username: string) {
372 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
375 static loadByEmail (email: string) {
382 return UserModel.findOne(query)
385 static loadByUsernameOrEmail (username: string, email?: string) {
386 if (!email) email = username
390 [ Op.or ]: [ { username }, { email } ]
394 return UserModel.findOne(query)
397 static loadByVideoId (videoId: number) {
402 attributes: [ 'id' ],
403 model: AccountModel.unscoped(),
407 attributes: [ 'id' ],
408 model: VideoChannelModel.unscoped(),
412 attributes: [ 'id' ],
413 model: VideoModel.unscoped(),
425 return UserModel.findOne(query)
428 static loadByVideoImportId (videoImportId: number) {
433 attributes: [ 'id' ],
434 model: VideoImportModel.unscoped(),
442 return UserModel.findOne(query)
445 static loadByChannelActorId (videoChannelActorId: number) {
450 attributes: [ 'id' ],
451 model: AccountModel.unscoped(),
455 attributes: [ 'id' ],
456 model: VideoChannelModel.unscoped(),
458 actorId: videoChannelActorId
466 return UserModel.findOne(query)
469 static loadByAccountActorId (accountActorId: number) {
474 attributes: [ 'id' ],
475 model: AccountModel.unscoped(),
477 actorId: accountActorId
483 return UserModel.findOne(query)
486 static getOriginalVideoFileTotalFromUser (user: UserModel) {
487 // Don't use sequelize because we need to use a sub query
488 const query = UserModel.generateUserQuotaBaseSQL()
490 return UserModel.getTotalRawQuery(query, user.id)
493 // Returns cumulative size of all video files uploaded in the last 24 hours.
494 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
495 // Don't use sequelize because we need to use a sub query
496 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
498 return UserModel.getTotalRawQuery(query, user.id)
501 static async getStats () {
502 const totalUsers = await UserModel.count()
509 static autoComplete (search: string) {
513 [ Op.like ]: `%${search}%`
519 return UserModel.findAll(query)
520 .then(u => u.map(u => u.username))
523 hasRight (right: UserRight) {
524 return hasUserRight(this.role, right)
527 hasAdminFlag (flag: UserAdminFlag) {
528 return this.adminFlags & flag
531 isPasswordMatch (password: string) {
532 return comparePassword(password, this.password)
535 toFormattedJSON (parameters: { withAdminFlags?: boolean } = {}): User {
536 const videoQuotaUsed = this.get('videoQuotaUsed')
537 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
541 username: this.username,
543 emailVerified: this.emailVerified,
544 nsfwPolicy: this.nsfwPolicy,
545 webTorrentEnabled: this.webTorrentEnabled,
546 videosHistoryEnabled: this.videosHistoryEnabled,
547 autoPlayVideo: this.autoPlayVideo,
549 roleLabel: USER_ROLE_LABELS[ this.role ],
550 videoQuota: this.videoQuota,
551 videoQuotaDaily: this.videoQuotaDaily,
552 createdAt: this.createdAt,
553 blocked: this.blocked,
554 blockedReason: this.blockedReason,
555 account: this.Account.toFormattedJSON(),
556 notificationSettings: this.NotificationSetting ? this.NotificationSetting.toFormattedJSON() : undefined,
558 videoQuotaUsed: videoQuotaUsed !== undefined
559 ? parseInt(videoQuotaUsed + '', 10)
561 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
562 ? parseInt(videoQuotaUsedDaily + '', 10)
566 if (parameters.withAdminFlags) {
567 Object.assign(json, { adminFlags: this.adminFlags })
570 if (Array.isArray(this.Account.VideoChannels) === true) {
571 json.videoChannels = this.Account.VideoChannels
572 .map(c => c.toFormattedJSON())
574 if (v1.createdAt < v2.createdAt) return -1
575 if (v1.createdAt === v2.createdAt) return 0
584 async isAbleToUploadVideo (videoFile: { size: number }) {
585 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
587 const [ totalBytes, totalBytesDaily ] = await Promise.all([
588 UserModel.getOriginalVideoFileTotalFromUser(this),
589 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
592 const uploadedTotal = videoFile.size + totalBytes
593 const uploadedDaily = videoFile.size + totalBytesDaily
595 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
596 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
598 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
601 private static generateUserQuotaBaseSQL (where?: string) {
602 const andWhere = where ? 'AND ' + where : ''
604 return 'SELECT SUM("size") AS "total" ' +
606 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
607 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
608 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
609 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
610 'WHERE "account"."userId" = $userId ' + andWhere +
611 'GROUP BY "video"."id"' +
615 private static getTotalRawQuery (query: string, userId: number) {
618 type: QueryTypes.SELECT as QueryTypes.SELECT
621 return UserModel.sequelize.query<{ total: string }>(query, options)
622 .then(([ { total } ]) => {
623 if (total === null) return 0
625 return parseInt(total, 10)