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,
27 isUserEmailVerifiedValid,
31 isUserVideoQuotaValid,
32 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'
42 import { VideoFileModel } from '../video/video-file'
45 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
51 model: () => AccountModel,
57 [ScopeNames.WITH_VIDEO_CHANNEL]: {
60 model: () => AccountModel,
62 include: [ () => VideoChannelModel ]
71 fields: [ 'username' ],
80 export class UserModel extends Model<UserModel> {
83 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
88 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
94 @Column(DataType.STRING(400))
99 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
101 emailVerified: boolean
104 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
105 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
106 nsfwPolicy: NSFWPolicyType
110 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
112 autoPlayVideo: boolean
116 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
122 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
124 blockedReason: string
127 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
132 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
133 @Column(DataType.BIGINT)
137 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
138 @Column(DataType.BIGINT)
139 videoQuotaDaily: number
147 @HasOne(() => AccountModel, {
148 foreignKey: 'userId',
152 Account: AccountModel
154 @HasMany(() => OAuthTokenModel, {
155 foreignKey: 'userId',
158 OAuthTokens: OAuthTokenModel[]
162 static cryptPasswordIfNeeded (instance: UserModel) {
163 if (instance.changed('password')) {
164 return cryptPassword(instance.password)
166 instance.password = hash
172 static countTotal () {
176 static listForApi (start: number, count: number, sort: string) {
183 'SELECT COALESCE(SUM("size"), 0) ' +
185 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
186 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
187 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
188 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
189 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
194 ] as any // FIXME: typings
202 return UserModel.findAndCountAll(query)
203 .then(({ rows, count }) => {
211 static listEmailsWithRight (right: UserRight) {
212 const roles = Object.keys(USER_ROLE_LABELS)
213 .map(k => parseInt(k, 10) as UserRole)
214 .filter(role => hasUserRight(role, right))
217 attribute: [ 'email' ],
220 [Sequelize.Op.in]: roles
225 return UserModel.unscoped()
227 .then(u => u.map(u => u.email))
230 static loadById (id: number) {
231 return UserModel.findById(id)
234 static loadByUsername (username: string) {
241 return UserModel.findOne(query)
244 static loadByUsernameAndPopulateChannels (username: string) {
251 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
254 static loadByEmail (email: string) {
261 return UserModel.findOne(query)
264 static loadByUsernameOrEmail (username: string, email?: string) {
265 if (!email) email = username
269 [ Sequelize.Op.or ]: [ { username }, { email } ]
273 return UserModel.findOne(query)
276 static getOriginalVideoFileTotalFromUser (user: UserModel) {
277 // Don't use sequelize because we need to use a sub query
278 const query = UserModel.generateUserQuotaBaseSQL()
280 return UserModel.getTotalRawQuery(query, user.id)
283 // Returns cumulative size of all video files uploaded in the last 24 hours.
284 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
285 // Don't use sequelize because we need to use a sub query
286 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
288 return UserModel.getTotalRawQuery(query, user.id)
291 static async getStats () {
292 const totalUsers = await UserModel.count()
299 hasRight (right: UserRight) {
300 return hasUserRight(this.role, right)
303 isPasswordMatch (password: string) {
304 return comparePassword(password, this.password)
307 toFormattedJSON (): User {
308 const videoQuotaUsed = this.get('videoQuotaUsed')
309 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
313 username: this.username,
315 emailVerified: this.emailVerified,
316 nsfwPolicy: this.nsfwPolicy,
317 autoPlayVideo: this.autoPlayVideo,
319 roleLabel: USER_ROLE_LABELS[ this.role ],
320 videoQuota: this.videoQuota,
321 videoQuotaDaily: this.videoQuotaDaily,
322 createdAt: this.createdAt,
323 blocked: this.blocked,
324 blockedReason: this.blockedReason,
325 account: this.Account.toFormattedJSON(),
327 videoQuotaUsed: videoQuotaUsed !== undefined
328 ? parseInt(videoQuotaUsed, 10)
330 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
331 ? parseInt(videoQuotaUsedDaily, 10)
335 if (Array.isArray(this.Account.VideoChannels) === true) {
336 json.videoChannels = this.Account.VideoChannels
337 .map(c => c.toFormattedJSON())
339 if (v1.createdAt < v2.createdAt) return -1
340 if (v1.createdAt === v2.createdAt) return 0
349 async isAbleToUploadVideo (videoFile: { size: number }) {
350 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
352 const [ totalBytes, totalBytesDaily ] = await Promise.all([
353 UserModel.getOriginalVideoFileTotalFromUser(this),
354 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
357 const uploadedTotal = videoFile.size + totalBytes
358 const uploadedDaily = videoFile.size + totalBytesDaily
359 if (this.videoQuotaDaily === -1) {
360 return uploadedTotal < this.videoQuota
362 if (this.videoQuota === -1) {
363 return uploadedDaily < this.videoQuotaDaily
366 return (uploadedTotal < this.videoQuota) &&
367 (uploadedDaily < this.videoQuotaDaily)
370 private static generateUserQuotaBaseSQL (where?: string) {
371 const andWhere = where ? 'AND ' + where : ''
373 return 'SELECT SUM("size") AS "total" ' +
375 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
376 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
377 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
378 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
379 'WHERE "account"."userId" = $userId ' + andWhere +
380 'GROUP BY "video"."id"' +
384 private static getTotalRawQuery (query: string, userId: number) {
387 type: Sequelize.QueryTypes.SELECT
390 return UserModel.sequelize.query(query, options)
391 .then(([ { total } ]) => {
392 if (total === null) return 0
394 return parseInt(total, 10)
398 static autocomplete (search: string) {
399 return UserModel.findAll({
402 [Sequelize.Op.like]: `%${search}%`
406 .then(u => u.map(u => u.username))