1 import * as Sequelize from 'sequelize'
3 AllowNull, BeforeCreate, BeforeUpdate, Column, CreatedAt, DataType, Default, DefaultScope, HasMany, HasOne, Is, IsEmail, Model,
4 Scopes, Table, UpdatedAt
5 } from 'sequelize-typescript'
6 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
7 import { User, UserRole } from '../../../shared/models/users'
9 isUserAutoPlayVideoValid, isUserDisplayNSFWValid, isUserPasswordValid, isUserRoleValid, isUserUsernameValid,
11 } from '../../helpers/custom-validators/users'
12 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
13 import { OAuthTokenModel } from '../oauth/oauth-token'
14 import { getSort, throwIfNotValid } from '../utils'
15 import { VideoChannelModel } from '../video/video-channel'
16 import { VideoCommentModel } from '../video/video-comment'
17 import { AccountModel } from './account'
22 model: () => AccountModel,
31 model: () => AccountModel,
33 include: [ () => VideoChannelModel ]
42 fields: [ 'username' ],
51 export class UserModel extends Model<UserModel> {
54 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
59 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
65 @Column(DataType.STRING(400))
70 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
76 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
78 autoPlayVideo: boolean
81 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
86 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
87 @Column(DataType.BIGINT)
96 @HasOne(() => AccountModel, {
101 Account: AccountModel
103 @HasMany(() => OAuthTokenModel, {
104 foreignKey: 'userId',
107 OAuthTokens: OAuthTokenModel[]
111 static cryptPasswordIfNeeded (instance: UserModel) {
112 if (instance.changed('password')) {
113 return cryptPassword(instance.password)
115 instance.password = hash
121 static countTotal () {
125 static listForApi (start: number, count: number, sort: string) {
132 return UserModel.findAndCountAll(query)
133 .then(({ rows, count }) => {
141 static listEmailsWithRight (right: UserRight) {
142 const roles = Object.keys(USER_ROLE_LABELS)
143 .map(k => parseInt(k, 10) as UserRole)
144 .filter(role => hasUserRight(role, right))
149 attribute: [ 'email' ],
152 [Sequelize.Op.in]: roles
157 return UserModel.unscoped()
159 .then(u => u.map(u => u.email))
162 static loadById (id: number) {
163 return UserModel.findById(id)
166 static loadByUsername (username: string) {
173 return UserModel.findOne(query)
176 static loadByUsernameAndPopulateChannels (username: string) {
183 return UserModel.scope('withVideoChannel').findOne(query)
186 static loadByEmail (email: string) {
193 return UserModel.findOne(query)
196 static loadByUsernameOrEmail (username: string, email?: string) {
197 if (!email) email = username
201 [ Sequelize.Op.or ]: [ { username }, { email } ]
205 return UserModel.findOne(query)
208 static getOriginalVideoFileTotalFromUser (user: UserModel) {
209 // Don't use sequelize because we need to use a sub query
210 const query = 'SELECT SUM("size") AS "total" FROM ' +
211 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
212 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
213 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
214 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
215 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
216 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
219 bind: { userId: user.id },
220 type: Sequelize.QueryTypes.SELECT
222 return UserModel.sequelize.query(query, options)
223 .then(([ { total } ]) => {
224 if (total === null) return 0
226 return parseInt(total, 10)
230 static async getStats () {
231 const totalUsers = await UserModel.count()
238 hasRight (right: UserRight) {
239 return hasUserRight(this.role, right)
242 isPasswordMatch (password: string) {
243 return comparePassword(password, this.password)
246 toFormattedJSON (): User {
249 username: this.username,
251 displayNSFW: this.displayNSFW,
252 autoPlayVideo: this.autoPlayVideo,
254 roleLabel: USER_ROLE_LABELS[ this.role ],
255 videoQuota: this.videoQuota,
256 createdAt: this.createdAt,
257 account: this.Account.toFormattedJSON(),
261 if (Array.isArray(this.Account.VideoChannels) === true) {
262 json.videoChannels = this.Account.VideoChannels
263 .map(c => c.toFormattedJSON())
265 if (v1.createdAt < v2.createdAt) return -1
266 if (v1.createdAt === v2.createdAt) return 0
275 isAbleToUploadVideo (videoFile: Express.Multer.File) {
276 if (this.videoQuota === -1) return Promise.resolve(true)
278 return UserModel.getOriginalVideoFileTotalFromUser(this)
279 .then(totalBytes => {
280 return (videoFile.size + totalBytes) < this.videoQuota