1 import * as Sequelize from 'sequelize'
19 } from 'sequelize-typescript'
20 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
21 import { User, UserRole } from '../../../shared/models/users'
23 isUserAutoPlayVideoValid,
24 isUserBlockedReasonValid,
26 isUserEmailVerifiedValid,
27 isUserNSFWPolicyValid,
31 isUserVideoQuotaDailyValid,
33 } from '../../helpers/custom-validators/users'
34 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
35 import { OAuthTokenModel } from '../oauth/oauth-token'
36 import { getSort, throwIfNotValid } from '../utils'
37 import { VideoChannelModel } from '../video/video-channel'
38 import { AccountModel } from './account'
39 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
40 import { values } from 'lodash'
41 import { NSFW_POLICY_TYPES } from '../../initializers'
44 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
50 model: () => AccountModel,
56 [ScopeNames.WITH_VIDEO_CHANNEL]: {
59 model: () => AccountModel,
61 include: [ () => VideoChannelModel ]
70 fields: [ 'username' ],
79 export class UserModel extends Model<UserModel> {
82 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
87 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
93 @Column(DataType.STRING(400))
98 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
100 emailVerified: boolean
103 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
104 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
105 nsfwPolicy: NSFWPolicyType
109 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
111 autoPlayVideo: boolean
115 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
121 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
123 blockedReason: string
126 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
131 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
132 @Column(DataType.BIGINT)
136 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
137 @Column(DataType.BIGINT)
138 videoQuotaDaily: number
146 @HasOne(() => AccountModel, {
147 foreignKey: 'userId',
151 Account: AccountModel
153 @HasMany(() => OAuthTokenModel, {
154 foreignKey: 'userId',
157 OAuthTokens: OAuthTokenModel[]
161 static cryptPasswordIfNeeded (instance: UserModel) {
162 if (instance.changed('password')) {
163 return cryptPassword(instance.password)
165 instance.password = hash
171 static countTotal () {
175 static listForApi (start: number, count: number, sort: string) {
182 'SELECT COALESCE(SUM("size"), 0) ' +
184 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
185 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
186 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
187 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
188 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
193 ] as any // FIXME: typings
201 return UserModel.findAndCountAll(query)
202 .then(({ rows, count }) => {
210 static listEmailsWithRight (right: UserRight) {
211 const roles = Object.keys(USER_ROLE_LABELS)
212 .map(k => parseInt(k, 10) as UserRole)
213 .filter(role => hasUserRight(role, right))
216 attribute: [ 'email' ],
219 [Sequelize.Op.in]: roles
224 return UserModel.unscoped()
226 .then(u => u.map(u => u.email))
229 static loadById (id: number) {
230 return UserModel.findById(id)
233 static loadByUsername (username: string) {
240 return UserModel.findOne(query)
243 static loadByUsernameAndPopulateChannels (username: string) {
250 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
253 static loadByEmail (email: string) {
260 return UserModel.findOne(query)
263 static loadByUsernameOrEmail (username: string, email?: string) {
264 if (!email) email = username
268 [ Sequelize.Op.or ]: [ { username }, { email } ]
272 return UserModel.findOne(query)
275 static getOriginalVideoFileTotalFromUser (user: UserModel) {
276 // Don't use sequelize because we need to use a sub query
277 const query = UserModel.generateUserQuotaBaseSQL()
279 return UserModel.getTotalRawQuery(query, user.id)
282 // Returns cumulative size of all video files uploaded in the last 24 hours.
283 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
284 // Don't use sequelize because we need to use a sub query
285 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
287 return UserModel.getTotalRawQuery(query, user.id)
290 static async getStats () {
291 const totalUsers = await UserModel.count()
298 static autoComplete (search: string) {
302 [ Sequelize.Op.like ]: `%${search}%`
308 return UserModel.findAll(query)
309 .then(u => u.map(u => u.username))
312 hasRight (right: UserRight) {
313 return hasUserRight(this.role, right)
316 isPasswordMatch (password: string) {
317 return comparePassword(password, this.password)
320 toFormattedJSON (): User {
321 const videoQuotaUsed = this.get('videoQuotaUsed')
322 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
326 username: this.username,
328 emailVerified: this.emailVerified,
329 nsfwPolicy: this.nsfwPolicy,
330 autoPlayVideo: this.autoPlayVideo,
332 roleLabel: USER_ROLE_LABELS[ this.role ],
333 videoQuota: this.videoQuota,
334 videoQuotaDaily: this.videoQuotaDaily,
335 createdAt: this.createdAt,
336 blocked: this.blocked,
337 blockedReason: this.blockedReason,
338 account: this.Account.toFormattedJSON(),
340 videoQuotaUsed: videoQuotaUsed !== undefined
341 ? parseInt(videoQuotaUsed, 10)
343 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
344 ? parseInt(videoQuotaUsedDaily, 10)
348 if (Array.isArray(this.Account.VideoChannels) === true) {
349 json.videoChannels = this.Account.VideoChannels
350 .map(c => c.toFormattedJSON())
352 if (v1.createdAt < v2.createdAt) return -1
353 if (v1.createdAt === v2.createdAt) return 0
362 async isAbleToUploadVideo (videoFile: { size: number }) {
363 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
365 const [ totalBytes, totalBytesDaily ] = await Promise.all([
366 UserModel.getOriginalVideoFileTotalFromUser(this),
367 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
370 const uploadedTotal = videoFile.size + totalBytes
371 const uploadedDaily = videoFile.size + totalBytesDaily
372 if (this.videoQuotaDaily === -1) {
373 return uploadedTotal < this.videoQuota
375 if (this.videoQuota === -1) {
376 return uploadedDaily < this.videoQuotaDaily
379 return (uploadedTotal < this.videoQuota) &&
380 (uploadedDaily < this.videoQuotaDaily)
383 private static generateUserQuotaBaseSQL (where?: string) {
384 const andWhere = where ? 'AND ' + where : ''
386 return 'SELECT SUM("size") AS "total" ' +
388 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
389 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
390 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
391 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
392 'WHERE "account"."userId" = $userId ' + andWhere +
393 'GROUP BY "video"."id"' +
397 private static getTotalRawQuery (query: string, userId: number) {
400 type: Sequelize.QueryTypes.SELECT
403 return UserModel.sequelize.query(query, options)
404 .then(([ { total } ]) => {
405 if (total === null) return 0
407 return parseInt(total, 10)