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) FROM ' +
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 }) => {
197 console.log(rows[0]['videoQuotaUsed'])
198 console.log(rows[0].get('videoQuotaUsed'))
206 static listEmailsWithRight (right: UserRight) {
207 const roles = Object.keys(USER_ROLE_LABELS)
208 .map(k => parseInt(k, 10) as UserRole)
209 .filter(role => hasUserRight(role, right))
214 attribute: [ 'email' ],
217 [Sequelize.Op.in]: roles
222 return UserModel.unscoped()
224 .then(u => u.map(u => u.email))
227 static loadById (id: number) {
228 return UserModel.findById(id)
231 static loadByUsername (username: string) {
238 return UserModel.findOne(query)
241 static loadByUsernameAndPopulateChannels (username: string) {
248 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
251 static loadByEmail (email: string) {
258 return UserModel.findOne(query)
261 static loadByUsernameOrEmail (username: string, email?: string) {
262 if (!email) email = username
266 [ Sequelize.Op.or ]: [ { username }, { email } ]
270 return UserModel.findOne(query)
273 static getOriginalVideoFileTotalFromUser (user: UserModel) {
274 // Don't use sequelize because we need to use a sub query
275 const query = 'SELECT SUM("size") AS "total" FROM ' +
276 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
277 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
278 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
279 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
280 'WHERE "account"."userId" = $userId ' +
281 'GROUP BY "video"."id") t'
284 bind: { userId: user.id },
285 type: Sequelize.QueryTypes.SELECT
287 return UserModel.sequelize.query(query, options)
288 .then(([ { total } ]) => {
289 if (total === null) return 0
291 return parseInt(total, 10)
295 // Returns comulative size of all video files uploaded in the last 24 hours.
296 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
297 // Don't use sequelize because we need to use a sub query
298 const query = 'SELECT SUM("size") AS "total" FROM ' +
299 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
300 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
301 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
302 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
303 'WHERE "account"."userId" = $userId ' +
304 'AND "video"."createdAt" > now() - interval \'24 hours\'' +
305 'GROUP BY "video"."id") t'
308 bind: { userId: user.id },
309 type: Sequelize.QueryTypes.SELECT
311 return UserModel.sequelize.query(query, options)
312 .then(([ { total } ]) => {
313 if (total === null) return 0
315 return parseInt(total, 10)
319 static async getStats () {
320 const totalUsers = await UserModel.count()
327 hasRight (right: UserRight) {
328 return hasUserRight(this.role, right)
331 isPasswordMatch (password: string) {
332 return comparePassword(password, this.password)
335 toFormattedJSON (): User {
336 const videoQuotaUsed = this.get('videoQuotaUsed')
337 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
341 username: this.username,
343 nsfwPolicy: this.nsfwPolicy,
344 autoPlayVideo: this.autoPlayVideo,
346 roleLabel: USER_ROLE_LABELS[ this.role ],
347 videoQuota: this.videoQuota,
348 videoQuotaDaily: this.videoQuotaDaily,
349 createdAt: this.createdAt,
350 blocked: this.blocked,
351 blockedReason: this.blockedReason,
352 account: this.Account.toFormattedJSON(),
354 videoQuotaUsed: videoQuotaUsed !== undefined
355 ? parseInt(videoQuotaUsed, 10)
357 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
358 ? parseInt(videoQuotaUsedDaily, 10)
362 if (Array.isArray(this.Account.VideoChannels) === true) {
363 json.videoChannels = this.Account.VideoChannels
364 .map(c => c.toFormattedJSON())
366 if (v1.createdAt < v2.createdAt) return -1
367 if (v1.createdAt === v2.createdAt) return 0
376 async isAbleToUploadVideo (videoFile: { size: number }) {
377 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
379 const [ totalBytes, totalBytesDaily ] = await Promise.all([
380 UserModel.getOriginalVideoFileTotalFromUser(this),
381 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
384 const uploadedTotal = videoFile.size + totalBytes
385 const uploadedDaily = videoFile.size + totalBytesDaily
386 if (this.videoQuotaDaily === -1) {
387 return uploadedTotal < this.videoQuota
389 if (this.videoQuota === -1) {
390 return uploadedDaily < this.videoQuotaDaily
393 return (uploadedTotal < this.videoQuota) &&
394 (uploadedDaily < this.videoQuotaDaily)