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 isUserVideosHistoryEnabledValid
37 } from '../../helpers/custom-validators/users'
38 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
39 import { OAuthTokenModel } from '../oauth/oauth-token'
40 import { getSort, throwIfNotValid } from '../utils'
41 import { VideoChannelModel } from '../video/video-channel'
42 import { AccountModel } from './account'
43 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
44 import { values } from 'lodash'
45 import { NSFW_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
114 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
116 webTorrentEnabled: boolean
120 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
122 videosHistoryEnabled: boolean
126 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
128 autoPlayVideo: boolean
132 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
138 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
140 blockedReason: string
143 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
148 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
149 @Column(DataType.BIGINT)
153 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
154 @Column(DataType.BIGINT)
155 videoQuotaDaily: number
163 @HasOne(() => AccountModel, {
164 foreignKey: 'userId',
168 Account: AccountModel
170 @HasMany(() => OAuthTokenModel, {
171 foreignKey: 'userId',
174 OAuthTokens: OAuthTokenModel[]
178 static cryptPasswordIfNeeded (instance: UserModel) {
179 if (instance.changed('password')) {
180 return cryptPassword(instance.password)
182 instance.password = hash
190 static removeTokenCache (instance: UserModel) {
191 return clearCacheByUserId(instance.id)
194 static countTotal () {
198 static listForApi (start: number, count: number, sort: string, search?: string) {
199 let where = undefined
205 [Sequelize.Op.iLike]: '%' + search + '%'
210 [ Sequelize.Op.iLike ]: '%' + search + '%'
223 'SELECT COALESCE(SUM("size"), 0) ' +
225 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
226 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
227 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
228 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
229 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
234 ] as any // FIXME: typings
239 order: getSort(sort),
243 return UserModel.findAndCountAll(query)
244 .then(({ rows, count }) => {
252 static listEmailsWithRight (right: UserRight) {
253 const roles = Object.keys(USER_ROLE_LABELS)
254 .map(k => parseInt(k, 10) as UserRole)
255 .filter(role => hasUserRight(role, right))
258 attribute: [ 'email' ],
261 [Sequelize.Op.in]: roles
266 return UserModel.unscoped()
268 .then(u => u.map(u => u.email))
271 static loadById (id: number) {
272 return UserModel.findById(id)
275 static loadByUsername (username: string) {
282 return UserModel.findOne(query)
285 static loadByUsernameAndPopulateChannels (username: string) {
292 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
295 static loadByEmail (email: string) {
302 return UserModel.findOne(query)
305 static loadByUsernameOrEmail (username: string, email?: string) {
306 if (!email) email = username
310 [ Sequelize.Op.or ]: [ { username }, { email } ]
314 return UserModel.findOne(query)
317 static getOriginalVideoFileTotalFromUser (user: UserModel) {
318 // Don't use sequelize because we need to use a sub query
319 const query = UserModel.generateUserQuotaBaseSQL()
321 return UserModel.getTotalRawQuery(query, user.id)
324 // Returns cumulative size of all video files uploaded in the last 24 hours.
325 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
326 // Don't use sequelize because we need to use a sub query
327 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
329 return UserModel.getTotalRawQuery(query, user.id)
332 static async getStats () {
333 const totalUsers = await UserModel.count()
340 static autoComplete (search: string) {
344 [ Sequelize.Op.like ]: `%${search}%`
350 return UserModel.findAll(query)
351 .then(u => u.map(u => u.username))
354 hasRight (right: UserRight) {
355 return hasUserRight(this.role, right)
358 isPasswordMatch (password: string) {
359 return comparePassword(password, this.password)
362 toFormattedJSON (): User {
363 const videoQuotaUsed = this.get('videoQuotaUsed')
364 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
368 username: this.username,
370 emailVerified: this.emailVerified,
371 nsfwPolicy: this.nsfwPolicy,
372 webTorrentEnabled: this.webTorrentEnabled,
373 autoPlayVideo: this.autoPlayVideo,
375 roleLabel: USER_ROLE_LABELS[ this.role ],
376 videoQuota: this.videoQuota,
377 videoQuotaDaily: this.videoQuotaDaily,
378 createdAt: this.createdAt,
379 blocked: this.blocked,
380 blockedReason: this.blockedReason,
381 account: this.Account.toFormattedJSON(),
383 videoQuotaUsed: videoQuotaUsed !== undefined
384 ? parseInt(videoQuotaUsed, 10)
386 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
387 ? parseInt(videoQuotaUsedDaily, 10)
391 if (Array.isArray(this.Account.VideoChannels) === true) {
392 json.videoChannels = this.Account.VideoChannels
393 .map(c => c.toFormattedJSON())
395 if (v1.createdAt < v2.createdAt) return -1
396 if (v1.createdAt === v2.createdAt) return 0
405 async isAbleToUploadVideo (videoFile: { size: number }) {
406 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
408 const [ totalBytes, totalBytesDaily ] = await Promise.all([
409 UserModel.getOriginalVideoFileTotalFromUser(this),
410 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
413 const uploadedTotal = videoFile.size + totalBytes
414 const uploadedDaily = videoFile.size + totalBytesDaily
415 if (this.videoQuotaDaily === -1) {
416 return uploadedTotal < this.videoQuota
418 if (this.videoQuota === -1) {
419 return uploadedDaily < this.videoQuotaDaily
422 return (uploadedTotal < this.videoQuota) &&
423 (uploadedDaily < this.videoQuotaDaily)
426 private static generateUserQuotaBaseSQL (where?: string) {
427 const andWhere = where ? 'AND ' + where : ''
429 return 'SELECT SUM("size") AS "total" ' +
431 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
432 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
433 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
434 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
435 'WHERE "account"."userId" = $userId ' + andWhere +
436 'GROUP BY "video"."id"' +
440 private static getTotalRawQuery (query: string, userId: number) {
443 type: Sequelize.QueryTypes.SELECT
446 return UserModel.sequelize.query(query, options)
447 .then(([ { total } ]) => {
448 if (total === null) return 0
450 return parseInt(total, 10)