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,
34 isUserVideoQuotaValid,
35 isUserWebTorrentEnabledValid
36 } from '../../helpers/custom-validators/users'
37 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
38 import { OAuthTokenModel } from '../oauth/oauth-token'
39 import { getSort, throwIfNotValid } from '../utils'
40 import { VideoChannelModel } from '../video/video-channel'
41 import { AccountModel } from './account'
42 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
43 import { values } from 'lodash'
44 import { NSFW_POLICY_TYPES } from '../../initializers'
45 import { clearCacheByUserId } from '../../lib/oauth-model'
48 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
54 model: () => AccountModel,
60 [ScopeNames.WITH_VIDEO_CHANNEL]: {
63 model: () => AccountModel,
65 include: [ () => VideoChannelModel ]
74 fields: [ 'username' ],
83 export class UserModel extends Model<UserModel> {
86 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
91 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
97 @Column(DataType.STRING(400))
102 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
104 emailVerified: boolean
107 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
108 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
109 nsfwPolicy: NSFWPolicyType
112 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
114 webTorrentEnabled: boolean
118 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
120 autoPlayVideo: boolean
124 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
130 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
132 blockedReason: string
135 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
140 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
141 @Column(DataType.BIGINT)
145 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
146 @Column(DataType.BIGINT)
147 videoQuotaDaily: number
155 @HasOne(() => AccountModel, {
156 foreignKey: 'userId',
160 Account: AccountModel
162 @HasMany(() => OAuthTokenModel, {
163 foreignKey: 'userId',
166 OAuthTokens: OAuthTokenModel[]
170 static cryptPasswordIfNeeded (instance: UserModel) {
171 if (instance.changed('password')) {
172 return cryptPassword(instance.password)
174 instance.password = hash
182 static removeTokenCache (instance: UserModel) {
183 return clearCacheByUserId(instance.id)
186 static countTotal () {
190 static listForApi (start: number, count: number, sort: string, search?: string) {
191 let where = undefined
197 [Sequelize.Op.iLike]: '%' + search + '%'
202 [ Sequelize.Op.iLike ]: '%' + search + '%'
215 'SELECT COALESCE(SUM("size"), 0) ' +
217 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
218 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
219 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
220 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
221 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
226 ] as any // FIXME: typings
231 order: getSort(sort),
235 return UserModel.findAndCountAll(query)
236 .then(({ rows, count }) => {
244 static listEmailsWithRight (right: UserRight) {
245 const roles = Object.keys(USER_ROLE_LABELS)
246 .map(k => parseInt(k, 10) as UserRole)
247 .filter(role => hasUserRight(role, right))
250 attribute: [ 'email' ],
253 [Sequelize.Op.in]: roles
258 return UserModel.unscoped()
260 .then(u => u.map(u => u.email))
263 static loadById (id: number) {
264 return UserModel.findById(id)
267 static loadByUsername (username: string) {
274 return UserModel.findOne(query)
277 static loadByUsernameAndPopulateChannels (username: string) {
284 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
287 static loadByEmail (email: string) {
294 return UserModel.findOne(query)
297 static loadByUsernameOrEmail (username: string, email?: string) {
298 if (!email) email = username
302 [ Sequelize.Op.or ]: [ { username }, { email } ]
306 return UserModel.findOne(query)
309 static getOriginalVideoFileTotalFromUser (user: UserModel) {
310 // Don't use sequelize because we need to use a sub query
311 const query = UserModel.generateUserQuotaBaseSQL()
313 return UserModel.getTotalRawQuery(query, user.id)
316 // Returns cumulative size of all video files uploaded in the last 24 hours.
317 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
318 // Don't use sequelize because we need to use a sub query
319 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
321 return UserModel.getTotalRawQuery(query, user.id)
324 static async getStats () {
325 const totalUsers = await UserModel.count()
332 static autoComplete (search: string) {
336 [ Sequelize.Op.like ]: `%${search}%`
342 return UserModel.findAll(query)
343 .then(u => u.map(u => u.username))
346 hasRight (right: UserRight) {
347 return hasUserRight(this.role, right)
350 isPasswordMatch (password: string) {
351 return comparePassword(password, this.password)
354 toFormattedJSON (): User {
355 const videoQuotaUsed = this.get('videoQuotaUsed')
356 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
360 username: this.username,
362 emailVerified: this.emailVerified,
363 nsfwPolicy: this.nsfwPolicy,
364 webTorrentEnabled: this.webTorrentEnabled,
365 autoPlayVideo: this.autoPlayVideo,
367 roleLabel: USER_ROLE_LABELS[ this.role ],
368 videoQuota: this.videoQuota,
369 videoQuotaDaily: this.videoQuotaDaily,
370 createdAt: this.createdAt,
371 blocked: this.blocked,
372 blockedReason: this.blockedReason,
373 account: this.Account.toFormattedJSON(),
375 videoQuotaUsed: videoQuotaUsed !== undefined
376 ? parseInt(videoQuotaUsed, 10)
378 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
379 ? parseInt(videoQuotaUsedDaily, 10)
383 if (Array.isArray(this.Account.VideoChannels) === true) {
384 json.videoChannels = this.Account.VideoChannels
385 .map(c => c.toFormattedJSON())
387 if (v1.createdAt < v2.createdAt) return -1
388 if (v1.createdAt === v2.createdAt) return 0
397 async isAbleToUploadVideo (videoFile: { size: number }) {
398 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
400 const [ totalBytes, totalBytesDaily ] = await Promise.all([
401 UserModel.getOriginalVideoFileTotalFromUser(this),
402 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
405 const uploadedTotal = videoFile.size + totalBytes
406 const uploadedDaily = videoFile.size + totalBytesDaily
407 if (this.videoQuotaDaily === -1) {
408 return uploadedTotal < this.videoQuota
410 if (this.videoQuota === -1) {
411 return uploadedDaily < this.videoQuotaDaily
414 return (uploadedTotal < this.videoQuota) &&
415 (uploadedDaily < this.videoQuotaDaily)
418 private static generateUserQuotaBaseSQL (where?: string) {
419 const andWhere = where ? 'AND ' + where : ''
421 return 'SELECT SUM("size") AS "total" ' +
423 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
424 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
425 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
426 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
427 'WHERE "account"."userId" = $userId ' + andWhere +
428 'GROUP BY "video"."id"' +
432 private static getTotalRawQuery (query: string, userId: number) {
435 type: Sequelize.QueryTypes.SELECT
438 return UserModel.sequelize.query(query, options)
439 .then(([ { total } ]) => {
440 if (total === null) return 0
442 return parseInt(total, 10)