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 isUserDisplayNSFWValid,
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'
39 model: () => AccountModel,
48 model: () => AccountModel,
50 include: [ () => VideoChannelModel ]
59 fields: [ 'username' ],
68 export class UserModel extends Model<UserModel> {
71 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
76 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
82 @Column(DataType.STRING(400))
87 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
93 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
95 autoPlayVideo: boolean
98 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
103 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
104 @Column(DataType.BIGINT)
113 @HasOne(() => AccountModel, {
114 foreignKey: 'userId',
118 Account: AccountModel
120 @HasMany(() => OAuthTokenModel, {
121 foreignKey: 'userId',
124 OAuthTokens: OAuthTokenModel[]
128 static cryptPasswordIfNeeded (instance: UserModel) {
129 if (instance.changed('password')) {
130 return cryptPassword(instance.password)
132 instance.password = hash
138 static countTotal () {
142 static listForApi (start: number, count: number, sort: string) {
149 return UserModel.findAndCountAll(query)
150 .then(({ rows, count }) => {
158 static listEmailsWithRight (right: UserRight) {
159 const roles = Object.keys(USER_ROLE_LABELS)
160 .map(k => parseInt(k, 10) as UserRole)
161 .filter(role => hasUserRight(role, right))
166 attribute: [ 'email' ],
169 [Sequelize.Op.in]: roles
174 return UserModel.unscoped()
176 .then(u => u.map(u => u.email))
179 static loadById (id: number) {
180 return UserModel.findById(id)
183 static loadByUsername (username: string) {
190 return UserModel.findOne(query)
193 static loadByUsernameAndPopulateChannels (username: string) {
200 return UserModel.scope('withVideoChannel').findOne(query)
203 static loadByEmail (email: string) {
210 return UserModel.findOne(query)
213 static loadByUsernameOrEmail (username: string, email?: string) {
214 if (!email) email = username
218 [ Sequelize.Op.or ]: [ { username }, { email } ]
222 return UserModel.findOne(query)
225 static getOriginalVideoFileTotalFromUser (user: UserModel) {
226 // Don't use sequelize because we need to use a sub query
227 const query = 'SELECT SUM("size") AS "total" FROM ' +
228 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
229 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
230 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
231 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
232 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
233 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
236 bind: { userId: user.id },
237 type: Sequelize.QueryTypes.SELECT
239 return UserModel.sequelize.query(query, options)
240 .then(([ { total } ]) => {
241 if (total === null) return 0
243 return parseInt(total, 10)
247 static async getStats () {
248 const totalUsers = await UserModel.count()
255 hasRight (right: UserRight) {
256 return hasUserRight(this.role, right)
259 isPasswordMatch (password: string) {
260 return comparePassword(password, this.password)
263 toFormattedJSON (): User {
266 username: this.username,
268 displayNSFW: this.displayNSFW,
269 autoPlayVideo: this.autoPlayVideo,
271 roleLabel: USER_ROLE_LABELS[ this.role ],
272 videoQuota: this.videoQuota,
273 createdAt: this.createdAt,
274 account: this.Account.toFormattedJSON(),
278 if (Array.isArray(this.Account.VideoChannels) === true) {
279 json.videoChannels = this.Account.VideoChannels
280 .map(c => c.toFormattedJSON())
282 if (v1.createdAt < v2.createdAt) return -1
283 if (v1.createdAt === v2.createdAt) return 0
292 isAbleToUploadVideo (videoFile: Express.Multer.File) {
293 if (this.videoQuota === -1) return Promise.resolve(true)
295 return UserModel.getOriginalVideoFileTotalFromUser(this)
296 .then(totalBytes => {
297 return (videoFile.size + totalBytes) < this.videoQuota