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 isUserNSFWPolicyValid,
30 isUserVideoQuotaValid,
31 isUserVideoQuotaDailyValid
32 } from '../../helpers/custom-validators/users'
33 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
34 import { OAuthTokenModel } from '../oauth/oauth-token'
35 import { getSort, throwIfNotValid } from '../utils'
36 import { VideoChannelModel } from '../video/video-channel'
37 import { AccountModel } from './account'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { values } from 'lodash'
40 import { NSFW_POLICY_TYPES } from '../../initializers'
43 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
49 model: () => AccountModel,
55 [ScopeNames.WITH_VIDEO_CHANNEL]: {
58 model: () => AccountModel,
60 include: [ () => VideoChannelModel ]
69 fields: [ 'username' ],
78 export class UserModel extends Model<UserModel> {
81 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
86 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
92 @Column(DataType.STRING(400))
96 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
97 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
98 nsfwPolicy: NSFWPolicyType
102 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
104 autoPlayVideo: boolean
108 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
114 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
116 blockedReason: string
119 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
124 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
125 @Column(DataType.BIGINT)
129 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
130 @Column(DataType.BIGINT)
131 videoQuotaDaily: number
139 @HasOne(() => AccountModel, {
140 foreignKey: 'userId',
144 Account: AccountModel
146 @HasMany(() => OAuthTokenModel, {
147 foreignKey: 'userId',
150 OAuthTokens: OAuthTokenModel[]
154 static cryptPasswordIfNeeded (instance: UserModel) {
155 if (instance.changed('password')) {
156 return cryptPassword(instance.password)
158 instance.password = hash
164 static countTotal () {
168 static listForApi (start: number, count: number, sort: string) {
175 'SELECT COALESCE(SUM("size"), 0) ' +
177 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
178 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
179 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
180 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
181 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
186 ] as any // FIXME: typings
194 return UserModel.findAndCountAll(query)
195 .then(({ rows, count }) => {
203 static listEmailsWithRight (right: UserRight) {
204 const roles = Object.keys(USER_ROLE_LABELS)
205 .map(k => parseInt(k, 10) as UserRole)
206 .filter(role => hasUserRight(role, right))
209 attribute: [ 'email' ],
212 [Sequelize.Op.in]: roles
217 return UserModel.unscoped()
219 .then(u => u.map(u => u.email))
222 static loadById (id: number) {
223 return UserModel.findById(id)
226 static loadByUsername (username: string) {
233 return UserModel.findOne(query)
236 static loadByUsernameAndPopulateChannels (username: string) {
243 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
246 static loadByEmail (email: string) {
253 return UserModel.findOne(query)
256 static loadByUsernameOrEmail (username: string, email?: string) {
257 if (!email) email = username
261 [ Sequelize.Op.or ]: [ { username }, { email } ]
265 return UserModel.findOne(query)
268 static getOriginalVideoFileTotalFromUser (user: UserModel) {
269 // Don't use sequelize because we need to use a sub query
270 const query = UserModel.generateUserQuotaBaseSQL()
272 return UserModel.getTotalRawQuery(query, user.id)
275 // Returns cumulative size of all video files uploaded in the last 24 hours.
276 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
277 // Don't use sequelize because we need to use a sub query
278 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
280 return UserModel.getTotalRawQuery(query, user.id)
283 static async getStats () {
284 const totalUsers = await UserModel.count()
291 hasRight (right: UserRight) {
292 return hasUserRight(this.role, right)
295 isPasswordMatch (password: string) {
296 return comparePassword(password, this.password)
299 toFormattedJSON (): User {
300 const videoQuotaUsed = this.get('videoQuotaUsed')
301 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
305 username: this.username,
307 nsfwPolicy: this.nsfwPolicy,
308 autoPlayVideo: this.autoPlayVideo,
310 roleLabel: USER_ROLE_LABELS[ this.role ],
311 videoQuota: this.videoQuota,
312 videoQuotaDaily: this.videoQuotaDaily,
313 createdAt: this.createdAt,
314 blocked: this.blocked,
315 blockedReason: this.blockedReason,
316 account: this.Account.toFormattedJSON(),
318 videoQuotaUsed: videoQuotaUsed !== undefined
319 ? parseInt(videoQuotaUsed, 10)
321 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
322 ? parseInt(videoQuotaUsedDaily, 10)
326 if (Array.isArray(this.Account.VideoChannels) === true) {
327 json.videoChannels = this.Account.VideoChannels
328 .map(c => c.toFormattedJSON())
330 if (v1.createdAt < v2.createdAt) return -1
331 if (v1.createdAt === v2.createdAt) return 0
340 async isAbleToUploadVideo (videoFile: { size: number }) {
341 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
343 const [ totalBytes, totalBytesDaily ] = await Promise.all([
344 UserModel.getOriginalVideoFileTotalFromUser(this),
345 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
348 const uploadedTotal = videoFile.size + totalBytes
349 const uploadedDaily = videoFile.size + totalBytesDaily
350 if (this.videoQuotaDaily === -1) {
351 return uploadedTotal < this.videoQuota
353 if (this.videoQuota === -1) {
354 return uploadedDaily < this.videoQuotaDaily
357 return (uploadedTotal < this.videoQuota) &&
358 (uploadedDaily < this.videoQuotaDaily)
361 private static generateUserQuotaBaseSQL (where?: string) {
362 const andWhere = where ? 'AND ' + where : ''
364 return 'SELECT SUM("size") AS "total" ' +
366 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
367 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
368 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
369 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
370 'WHERE "account"."userId" = $userId ' + andWhere +
371 'GROUP BY "video"."id"' +
375 private static getTotalRawQuery (query: string, userId: number) {
378 type: Sequelize.QueryTypes.SELECT
381 return UserModel.sequelize.query(query, options)
382 .then(([ { total } ]) => {
383 if (total === null) return 0
385 return parseInt(total, 10)