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 isUserWebTorrentPolicyValid
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 { WebTorrentPolicyType } from '../../../shared/models/users/user-webtorrent-policy.type'
44 import { values } from 'lodash'
45 import { NSFW_POLICY_TYPES, WEBTORRENT_POLICY_TYPES } from '../../initializers'
46 import { clearCacheByUserId } from '../../lib/oauth-model'
49 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
55 model: () => AccountModel,
61 [ScopeNames.WITH_VIDEO_CHANNEL]: {
64 model: () => AccountModel,
66 include: [ () => VideoChannelModel ]
75 fields: [ 'username' ],
84 export class UserModel extends Model<UserModel> {
87 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
92 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
98 @Column(DataType.STRING(400))
103 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
105 emailVerified: boolean
108 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
109 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
110 nsfwPolicy: NSFWPolicyType
113 @Is('UserWebTorrentPolicy', value => throwIfNotValid(value, isUserWebTorrentPolicyValid, 'WebTorrent policy'))
114 @Column(DataType.ENUM(values(WEBTORRENT_POLICY_TYPES)))
115 webTorrentPolicy: WebTorrentPolicyType
119 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
121 autoPlayVideo: boolean
125 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
131 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
133 blockedReason: string
136 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
141 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
142 @Column(DataType.BIGINT)
146 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
147 @Column(DataType.BIGINT)
148 videoQuotaDaily: number
156 @HasOne(() => AccountModel, {
157 foreignKey: 'userId',
161 Account: AccountModel
163 @HasMany(() => OAuthTokenModel, {
164 foreignKey: 'userId',
167 OAuthTokens: OAuthTokenModel[]
171 static cryptPasswordIfNeeded (instance: UserModel) {
172 if (instance.changed('password')) {
173 return cryptPassword(instance.password)
175 instance.password = hash
183 static removeTokenCache (instance: UserModel) {
184 return clearCacheByUserId(instance.id)
187 static countTotal () {
191 static listForApi (start: number, count: number, sort: string, search?: string) {
192 let where = undefined
198 [Sequelize.Op.iLike]: '%' + search + '%'
203 [ Sequelize.Op.iLike ]: '%' + search + '%'
216 'SELECT COALESCE(SUM("size"), 0) ' +
218 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
219 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
220 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
221 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
222 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
227 ] as any // FIXME: typings
232 order: getSort(sort),
236 return UserModel.findAndCountAll(query)
237 .then(({ rows, count }) => {
245 static listEmailsWithRight (right: UserRight) {
246 const roles = Object.keys(USER_ROLE_LABELS)
247 .map(k => parseInt(k, 10) as UserRole)
248 .filter(role => hasUserRight(role, right))
251 attribute: [ 'email' ],
254 [Sequelize.Op.in]: roles
259 return UserModel.unscoped()
261 .then(u => u.map(u => u.email))
264 static loadById (id: number) {
265 return UserModel.findById(id)
268 static loadByUsername (username: string) {
275 return UserModel.findOne(query)
278 static loadByUsernameAndPopulateChannels (username: string) {
285 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
288 static loadByEmail (email: string) {
295 return UserModel.findOne(query)
298 static loadByUsernameOrEmail (username: string, email?: string) {
299 if (!email) email = username
303 [ Sequelize.Op.or ]: [ { username }, { email } ]
307 return UserModel.findOne(query)
310 static getOriginalVideoFileTotalFromUser (user: UserModel) {
311 // Don't use sequelize because we need to use a sub query
312 const query = UserModel.generateUserQuotaBaseSQL()
314 return UserModel.getTotalRawQuery(query, user.id)
317 // Returns cumulative size of all video files uploaded in the last 24 hours.
318 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
319 // Don't use sequelize because we need to use a sub query
320 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
322 return UserModel.getTotalRawQuery(query, user.id)
325 static async getStats () {
326 const totalUsers = await UserModel.count()
333 static autoComplete (search: string) {
337 [ Sequelize.Op.like ]: `%${search}%`
343 return UserModel.findAll(query)
344 .then(u => u.map(u => u.username))
347 hasRight (right: UserRight) {
348 return hasUserRight(this.role, right)
351 isPasswordMatch (password: string) {
352 return comparePassword(password, this.password)
355 toFormattedJSON (): User {
356 const videoQuotaUsed = this.get('videoQuotaUsed')
357 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
361 username: this.username,
363 emailVerified: this.emailVerified,
364 nsfwPolicy: this.nsfwPolicy,
365 webTorrentPolicy: this.webTorrentPolicy,
366 autoPlayVideo: this.autoPlayVideo,
368 roleLabel: USER_ROLE_LABELS[ this.role ],
369 videoQuota: this.videoQuota,
370 videoQuotaDaily: this.videoQuotaDaily,
371 createdAt: this.createdAt,
372 blocked: this.blocked,
373 blockedReason: this.blockedReason,
374 account: this.Account.toFormattedJSON(),
376 videoQuotaUsed: videoQuotaUsed !== undefined
377 ? parseInt(videoQuotaUsed, 10)
379 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
380 ? parseInt(videoQuotaUsedDaily, 10)
384 if (Array.isArray(this.Account.VideoChannels) === true) {
385 json.videoChannels = this.Account.VideoChannels
386 .map(c => c.toFormattedJSON())
388 if (v1.createdAt < v2.createdAt) return -1
389 if (v1.createdAt === v2.createdAt) return 0
398 async isAbleToUploadVideo (videoFile: { size: number }) {
399 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
401 const [ totalBytes, totalBytesDaily ] = await Promise.all([
402 UserModel.getOriginalVideoFileTotalFromUser(this),
403 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
406 const uploadedTotal = videoFile.size + totalBytes
407 const uploadedDaily = videoFile.size + totalBytesDaily
408 if (this.videoQuotaDaily === -1) {
409 return uploadedTotal < this.videoQuota
411 if (this.videoQuota === -1) {
412 return uploadedDaily < this.videoQuotaDaily
415 return (uploadedTotal < this.videoQuota) &&
416 (uploadedDaily < this.videoQuotaDaily)
419 private static generateUserQuotaBaseSQL (where?: string) {
420 const andWhere = where ? 'AND ' + where : ''
422 return 'SELECT SUM("size") AS "total" ' +
424 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
425 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
426 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
427 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
428 'WHERE "account"."userId" = $userId ' + andWhere +
429 'GROUP BY "video"."id"' +
433 private static getTotalRawQuery (query: string, userId: number) {
436 type: Sequelize.QueryTypes.SELECT
439 return UserModel.sequelize.query(query, options)
440 .then(([ { total } ]) => {
441 if (total === null) return 0
443 return parseInt(total, 10)