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 isUserNSFWPolicyValid,
29 } from '../../helpers/custom-validators/users'
30 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
31 import { OAuthTokenModel } from '../oauth/oauth-token'
32 import { getSort, throwIfNotValid } from '../utils'
33 import { VideoChannelModel } from '../video/video-channel'
34 import { AccountModel } from './account'
35 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
36 import { values } from 'lodash'
37 import { NSFW_POLICY_TYPES } from '../../initializers'
42 model: () => AccountModel,
51 model: () => AccountModel,
53 include: [ () => VideoChannelModel ]
62 fields: [ 'username' ],
71 export class UserModel extends Model<UserModel> {
74 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
79 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
85 @Column(DataType.STRING(400))
89 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
90 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
91 nsfwPolicy: NSFWPolicyType
95 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
97 autoPlayVideo: boolean
100 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
105 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
106 @Column(DataType.BIGINT)
115 @HasOne(() => AccountModel, {
116 foreignKey: 'userId',
120 Account: AccountModel
122 @HasMany(() => OAuthTokenModel, {
123 foreignKey: 'userId',
126 OAuthTokens: OAuthTokenModel[]
130 static cryptPasswordIfNeeded (instance: UserModel) {
131 if (instance.changed('password')) {
132 return cryptPassword(instance.password)
134 instance.password = hash
140 static countTotal () {
144 static listForApi (start: number, count: number, sort: string) {
151 return UserModel.findAndCountAll(query)
152 .then(({ rows, count }) => {
160 static listEmailsWithRight (right: UserRight) {
161 const roles = Object.keys(USER_ROLE_LABELS)
162 .map(k => parseInt(k, 10) as UserRole)
163 .filter(role => hasUserRight(role, right))
168 attribute: [ 'email' ],
171 [Sequelize.Op.in]: roles
176 return UserModel.unscoped()
178 .then(u => u.map(u => u.email))
181 static loadById (id: number) {
182 return UserModel.findById(id)
185 static loadByUsername (username: string) {
192 return UserModel.findOne(query)
195 static loadByUsernameAndPopulateChannels (username: string) {
202 return UserModel.scope('withVideoChannel').findOne(query)
205 static loadByEmail (email: string) {
212 return UserModel.findOne(query)
215 static loadByUsernameOrEmail (username: string, email?: string) {
216 if (!email) email = username
220 [ Sequelize.Op.or ]: [ { username }, { email } ]
224 return UserModel.findOne(query)
227 static getOriginalVideoFileTotalFromUser (user: UserModel) {
228 // Don't use sequelize because we need to use a sub query
229 const query = 'SELECT SUM("size") AS "total" FROM ' +
230 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
231 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
232 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
233 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
234 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
235 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
238 bind: { userId: user.id },
239 type: Sequelize.QueryTypes.SELECT
241 return UserModel.sequelize.query(query, options)
242 .then(([ { total } ]) => {
243 if (total === null) return 0
245 return parseInt(total, 10)
249 static async getStats () {
250 const totalUsers = await UserModel.count()
257 hasRight (right: UserRight) {
258 return hasUserRight(this.role, right)
261 isPasswordMatch (password: string) {
262 return comparePassword(password, this.password)
265 toFormattedJSON (): User {
268 username: this.username,
270 nsfwPolicy: this.nsfwPolicy,
271 autoPlayVideo: this.autoPlayVideo,
273 roleLabel: USER_ROLE_LABELS[ this.role ],
274 videoQuota: this.videoQuota,
275 createdAt: this.createdAt,
276 account: this.Account.toFormattedJSON(),
280 if (Array.isArray(this.Account.VideoChannels) === true) {
281 json.videoChannels = this.Account.VideoChannels
282 .map(c => c.toFormattedJSON())
284 if (v1.createdAt < v2.createdAt) return -1
285 if (v1.createdAt === v2.createdAt) return 0
294 isAbleToUploadVideo (videoFile: Express.Multer.File) {
295 if (this.videoQuota === -1) return Promise.resolve(true)
297 return UserModel.getOriginalVideoFileTotalFromUser(this)
298 .then(totalBytes => {
299 return (videoFile.size + totalBytes) < this.videoQuota