1 import * as Sequelize from 'sequelize'
21 } from 'sequelize-typescript'
22 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
25 isUserAutoPlayVideoValid,
26 isUserBlockedReasonValid,
28 isUserEmailVerifiedValid,
29 isUserNSFWPolicyValid,
33 isUserVideoQuotaDailyValid,
35 } from '../../helpers/custom-validators/users'
36 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
37 import { OAuthTokenModel } from '../oauth/oauth-token'
38 import { getSort, throwIfNotValid } from '../utils'
39 import { VideoChannelModel } from '../video/video-channel'
40 import { AccountModel } from './account'
41 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
42 import { values } from 'lodash'
43 import { NSFW_POLICY_TYPES } from '../../initializers'
44 import { clearCacheByUserId } from '../../lib/oauth-model'
47 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
53 model: () => AccountModel,
59 [ScopeNames.WITH_VIDEO_CHANNEL]: {
62 model: () => AccountModel,
64 include: [ () => VideoChannelModel ]
73 fields: [ 'username' ],
82 export class UserModel extends Model<UserModel> {
85 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
90 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
96 @Column(DataType.STRING(400))
101 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
103 emailVerified: boolean
106 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
107 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
108 nsfwPolicy: NSFWPolicyType
112 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
114 autoPlayVideo: boolean
118 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
124 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
126 blockedReason: string
129 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
134 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
135 @Column(DataType.BIGINT)
139 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
140 @Column(DataType.BIGINT)
141 videoQuotaDaily: number
149 @HasOne(() => AccountModel, {
150 foreignKey: 'userId',
154 Account: AccountModel
156 @HasMany(() => OAuthTokenModel, {
157 foreignKey: 'userId',
160 OAuthTokens: OAuthTokenModel[]
164 static cryptPasswordIfNeeded (instance: UserModel) {
165 if (instance.changed('password')) {
166 return cryptPassword(instance.password)
168 instance.password = hash
176 static removeTokenCache (instance: UserModel) {
177 return clearCacheByUserId(instance.id)
180 static countTotal () {
184 static listForApi (start: number, count: number, sort: string, search?: string) {
185 let where = undefined
191 [Sequelize.Op.iLike]: '%' + search + '%'
196 [ Sequelize.Op.iLike ]: '%' + search + '%'
209 'SELECT COALESCE(SUM("size"), 0) ' +
211 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
212 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
213 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
214 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
215 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
220 ] as any // FIXME: typings
225 order: getSort(sort),
229 return UserModel.findAndCountAll(query)
230 .then(({ rows, count }) => {
238 static listEmailsWithRight (right: UserRight) {
239 const roles = Object.keys(USER_ROLE_LABELS)
240 .map(k => parseInt(k, 10) as UserRole)
241 .filter(role => hasUserRight(role, right))
244 attribute: [ 'email' ],
247 [Sequelize.Op.in]: roles
252 return UserModel.unscoped()
254 .then(u => u.map(u => u.email))
257 static loadById (id: number) {
258 return UserModel.findById(id)
261 static loadByUsername (username: string) {
268 return UserModel.findOne(query)
271 static loadByUsernameAndPopulateChannels (username: string) {
278 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
281 static loadByEmail (email: string) {
288 return UserModel.findOne(query)
291 static loadByUsernameOrEmail (username: string, email?: string) {
292 if (!email) email = username
296 [ Sequelize.Op.or ]: [ { username }, { email } ]
300 return UserModel.findOne(query)
303 static getOriginalVideoFileTotalFromUser (user: UserModel) {
304 // Don't use sequelize because we need to use a sub query
305 const query = UserModel.generateUserQuotaBaseSQL()
307 return UserModel.getTotalRawQuery(query, user.id)
310 // Returns cumulative size of all video files uploaded in the last 24 hours.
311 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
312 // Don't use sequelize because we need to use a sub query
313 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
315 return UserModel.getTotalRawQuery(query, user.id)
318 static async getStats () {
319 const totalUsers = await UserModel.count()
326 static autoComplete (search: string) {
330 [ Sequelize.Op.like ]: `%${search}%`
336 return UserModel.findAll(query)
337 .then(u => u.map(u => u.username))
340 hasRight (right: UserRight) {
341 return hasUserRight(this.role, right)
344 isPasswordMatch (password: string) {
345 return comparePassword(password, this.password)
348 toFormattedJSON (): User {
349 const videoQuotaUsed = this.get('videoQuotaUsed')
350 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
354 username: this.username,
356 emailVerified: this.emailVerified,
357 nsfwPolicy: this.nsfwPolicy,
358 autoPlayVideo: this.autoPlayVideo,
360 roleLabel: USER_ROLE_LABELS[ this.role ],
361 videoQuota: this.videoQuota,
362 videoQuotaDaily: this.videoQuotaDaily,
363 createdAt: this.createdAt,
364 blocked: this.blocked,
365 blockedReason: this.blockedReason,
366 account: this.Account.toFormattedJSON(),
368 videoQuotaUsed: videoQuotaUsed !== undefined
369 ? parseInt(videoQuotaUsed, 10)
371 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
372 ? parseInt(videoQuotaUsedDaily, 10)
376 if (Array.isArray(this.Account.VideoChannels) === true) {
377 json.videoChannels = this.Account.VideoChannels
378 .map(c => c.toFormattedJSON())
380 if (v1.createdAt < v2.createdAt) return -1
381 if (v1.createdAt === v2.createdAt) return 0
390 async isAbleToUploadVideo (videoFile: { size: number }) {
391 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
393 const [ totalBytes, totalBytesDaily ] = await Promise.all([
394 UserModel.getOriginalVideoFileTotalFromUser(this),
395 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
398 const uploadedTotal = videoFile.size + totalBytes
399 const uploadedDaily = videoFile.size + totalBytesDaily
400 if (this.videoQuotaDaily === -1) {
401 return uploadedTotal < this.videoQuota
403 if (this.videoQuota === -1) {
404 return uploadedDaily < this.videoQuotaDaily
407 return (uploadedTotal < this.videoQuota) &&
408 (uploadedDaily < this.videoQuotaDaily)
411 private static generateUserQuotaBaseSQL (where?: string) {
412 const andWhere = where ? 'AND ' + where : ''
414 return 'SELECT SUM("size") AS "total" ' +
416 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
417 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
418 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
419 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
420 'WHERE "account"."userId" = $userId ' + andWhere +
421 'GROUP BY "video"."id"' +
425 private static getTotalRawQuery (query: string, userId: number) {
428 type: Sequelize.QueryTypes.SELECT
431 return UserModel.sequelize.query(query, options)
432 .then(([ { total } ]) => {
433 if (total === null) return 0
435 return parseInt(total, 10)