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,
31 } from '../../helpers/custom-validators/users'
32 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
33 import { OAuthTokenModel } from '../oauth/oauth-token'
34 import { getSort, throwIfNotValid } from '../utils'
35 import { VideoChannelModel } from '../video/video-channel'
36 import { AccountModel } from './account'
37 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
38 import { values } from 'lodash'
39 import { NSFW_POLICY_TYPES } from '../../initializers'
42 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
48 model: () => AccountModel,
54 [ScopeNames.WITH_VIDEO_CHANNEL]: {
57 model: () => AccountModel,
59 include: [ () => VideoChannelModel ]
68 fields: [ 'username' ],
77 export class UserModel extends Model<UserModel> {
80 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
85 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
91 @Column(DataType.STRING(400))
95 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
96 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
97 nsfwPolicy: NSFWPolicyType
101 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
103 autoPlayVideo: boolean
107 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
113 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
115 blockedReason: string
118 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
123 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
124 @Column(DataType.BIGINT)
133 @HasOne(() => AccountModel, {
134 foreignKey: 'userId',
138 Account: AccountModel
140 @HasMany(() => OAuthTokenModel, {
141 foreignKey: 'userId',
144 OAuthTokens: OAuthTokenModel[]
148 static cryptPasswordIfNeeded (instance: UserModel) {
149 if (instance.changed('password')) {
150 return cryptPassword(instance.password)
152 instance.password = hash
158 static countTotal () {
162 static listForApi (start: number, count: number, sort: string) {
169 'SELECT COALESCE(SUM("size"), 0) FROM ' +
171 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
172 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
173 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
174 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
175 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
180 ] as any // FIXME: typings
188 return UserModel.findAndCountAll(query)
189 .then(({ rows, count }) => {
191 console.log(rows[0]['videoQuotaUsed'])
192 console.log(rows[0].get('videoQuotaUsed'))
200 static listEmailsWithRight (right: UserRight) {
201 const roles = Object.keys(USER_ROLE_LABELS)
202 .map(k => parseInt(k, 10) as UserRole)
203 .filter(role => hasUserRight(role, right))
208 attribute: [ 'email' ],
211 [Sequelize.Op.in]: roles
216 return UserModel.unscoped()
218 .then(u => u.map(u => u.email))
221 static loadById (id: number) {
222 return UserModel.findById(id)
225 static loadByUsername (username: string) {
232 return UserModel.findOne(query)
235 static loadByUsernameAndPopulateChannels (username: string) {
242 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
245 static loadByEmail (email: string) {
252 return UserModel.findOne(query)
255 static loadByUsernameOrEmail (username: string, email?: string) {
256 if (!email) email = username
260 [ Sequelize.Op.or ]: [ { username }, { email } ]
264 return UserModel.findOne(query)
267 static getOriginalVideoFileTotalFromUser (user: UserModel) {
268 // Don't use sequelize because we need to use a sub query
269 const query = 'SELECT SUM("size") AS "total" FROM ' +
270 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
271 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
272 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
273 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
274 'WHERE "account"."userId" = $userId GROUP BY "video"."id") t'
277 bind: { userId: user.id },
278 type: Sequelize.QueryTypes.SELECT
280 return UserModel.sequelize.query(query, options)
281 .then(([ { total } ]) => {
282 if (total === null) return 0
284 return parseInt(total, 10)
288 static async getStats () {
289 const totalUsers = await UserModel.count()
296 hasRight (right: UserRight) {
297 return hasUserRight(this.role, right)
300 isPasswordMatch (password: string) {
301 return comparePassword(password, this.password)
304 toFormattedJSON (): User {
305 const videoQuotaUsed = this.get('videoQuotaUsed')
309 username: this.username,
311 nsfwPolicy: this.nsfwPolicy,
312 autoPlayVideo: this.autoPlayVideo,
314 roleLabel: USER_ROLE_LABELS[ this.role ],
315 videoQuota: this.videoQuota,
316 createdAt: this.createdAt,
317 blocked: this.blocked,
318 blockedReason: this.blockedReason,
319 account: this.Account.toFormattedJSON(),
321 videoQuotaUsed: videoQuotaUsed !== undefined ? parseInt(videoQuotaUsed, 10) : undefined
324 if (Array.isArray(this.Account.VideoChannels) === true) {
325 json.videoChannels = this.Account.VideoChannels
326 .map(c => c.toFormattedJSON())
328 if (v1.createdAt < v2.createdAt) return -1
329 if (v1.createdAt === v2.createdAt) return 0
338 isAbleToUploadVideo (videoFile: { size: number }) {
339 if (this.videoQuota === -1) return Promise.resolve(true)
341 return UserModel.getOriginalVideoFileTotalFromUser(this)
342 .then(totalBytes => {
343 return (videoFile.size + totalBytes) < this.videoQuota