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 { AccountModel } from './account'
21 model: () => AccountModel,
30 model: () => AccountModel,
32 include: [ () => VideoChannelModel ]
41 fields: [ 'username' ],
50 export class UserModel extends Model<UserModel> {
53 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
58 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
64 @Column(DataType.STRING(400))
69 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
75 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
77 autoPlayVideo: boolean
80 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
85 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
86 @Column(DataType.BIGINT)
95 @HasOne(() => AccountModel, {
100 Account: AccountModel
102 @HasMany(() => OAuthTokenModel, {
103 foreignKey: 'userId',
106 OAuthTokens: OAuthTokenModel[]
110 static cryptPasswordIfNeeded (instance: UserModel) {
111 if (instance.changed('password')) {
112 return cryptPassword(instance.password)
114 instance.password = hash
120 static countTotal () {
124 static listForApi (start: number, count: number, sort: string) {
131 return UserModel.findAndCountAll(query)
132 .then(({ rows, count }) => {
140 static listEmailsWithRight (right: UserRight) {
141 const roles = Object.keys(USER_ROLE_LABELS)
142 .map(k => parseInt(k, 10) as UserRole)
143 .filter(role => hasUserRight(role, right))
148 attribute: [ 'email' ],
151 [Sequelize.Op.in]: roles
156 return UserModel.unscoped()
158 .then(u => u.map(u => u.email))
161 static loadById (id: number) {
162 return UserModel.findById(id)
165 static loadByUsername (username: string) {
172 return UserModel.findOne(query)
175 static loadByUsernameAndPopulateChannels (username: string) {
182 return UserModel.scope('withVideoChannel').findOne(query)
185 static loadByEmail (email: string) {
192 return UserModel.findOne(query)
195 static loadByUsernameOrEmail (username: string, email?: string) {
196 if (!email) email = username
200 [ Sequelize.Op.or ]: [ { username }, { email } ]
204 return UserModel.findOne(query)
207 static getOriginalVideoFileTotalFromUser (user: UserModel) {
208 // Don't use sequelize because we need to use a sub query
209 const query = 'SELECT SUM("size") AS "total" FROM ' +
210 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
211 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
212 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
213 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
214 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
215 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
218 bind: { userId: user.id },
219 type: Sequelize.QueryTypes.SELECT
221 return UserModel.sequelize.query(query, options)
222 .then(([ { total } ]) => {
223 if (total === null) return 0
225 return parseInt(total, 10)
229 hasRight (right: UserRight) {
230 return hasUserRight(this.role, right)
233 isPasswordMatch (password: string) {
234 return comparePassword(password, this.password)
237 toFormattedJSON (): User {
240 username: this.username,
242 displayNSFW: this.displayNSFW,
243 autoPlayVideo: this.autoPlayVideo,
245 roleLabel: USER_ROLE_LABELS[ this.role ],
246 videoQuota: this.videoQuota,
247 createdAt: this.createdAt,
248 account: this.Account.toFormattedJSON(),
252 if (Array.isArray(this.Account.VideoChannels) === true) {
253 json.videoChannels = this.Account.VideoChannels
254 .map(c => c.toFormattedJSON())
256 if (v1.createdAt < v2.createdAt) return -1
257 if (v1.createdAt === v2.createdAt) return 0
266 isAbleToUploadVideo (videoFile: Express.Multer.File) {
267 if (this.videoQuota === -1) return Promise.resolve(true)
269 return UserModel.getOriginalVideoFileTotalFromUser(this)
270 .then(totalBytes => {
271 return (videoFile.size + totalBytes) < this.videoQuota