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 { comparePassword, cryptPassword } from '../../helpers'
9 isUserAutoPlayVideoValid, isUserDisplayNSFWValid, isUserPasswordValid, isUserRoleValid, isUserUsernameValid,
11 } from '../../helpers/custom-validators/users'
12 import { OAuthTokenModel } from '../oauth/oauth-token'
13 import { getSort, throwIfNotValid } from '../utils'
14 import { VideoChannelModel } from '../video/video-channel'
15 import { AccountModel } from './account'
20 model: () => AccountModel,
29 model: () => AccountModel,
31 include: [ () => VideoChannelModel ]
40 fields: [ 'username' ],
49 export class UserModel extends Model<UserModel> {
52 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
57 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
63 @Column(DataType.STRING(400))
68 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
74 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
76 autoPlayVideo: boolean
79 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
84 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
85 @Column(DataType.BIGINT)
94 @HasOne(() => AccountModel, {
100 @HasMany(() => OAuthTokenModel, {
101 foreignKey: 'userId',
104 OAuthTokens: OAuthTokenModel[]
108 static cryptPasswordIfNeeded (instance: UserModel) {
109 if (instance.changed('password')) {
110 return cryptPassword(instance.password)
112 instance.password = hash
118 static countTotal () {
122 static getByUsername (username: string) {
127 include: [ { model: AccountModel, required: true } ]
130 return UserModel.findOne(query)
133 static listForApi (start: number, count: number, sort: string) {
137 order: [ getSort(sort) ]
140 return UserModel.findAndCountAll(query)
141 .then(({ rows, count }) => {
149 static loadById (id: number) {
150 return UserModel.findById(id)
153 static loadByUsername (username: string) {
160 return UserModel.findOne(query)
163 static loadByUsernameAndPopulateChannels (username: string) {
170 return UserModel.scope('withVideoChannel').findOne(query)
173 static loadByUsernameOrEmail (username: string, email: string) {
176 [ Sequelize.Op.or ]: [ { username }, { email } ]
180 return UserModel.findOne(query)
183 private static getOriginalVideoFileTotalFromUser (user: UserModel) {
184 // Don't use sequelize because we need to use a sub query
185 const query = 'SELECT SUM("size") AS "total" FROM ' +
186 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
187 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
188 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
189 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
190 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
191 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
194 bind: { userId: user.id },
195 type: Sequelize.QueryTypes.SELECT
197 return UserModel.sequelize.query(query, options)
198 .then(([ { total } ]) => {
199 if (total === null) return 0
201 return parseInt(total, 10)
205 hasRight (right: UserRight) {
206 return hasUserRight(this.role, right)
209 isPasswordMatch (password: string) {
210 return comparePassword(password, this.password)
216 username: this.username,
218 displayNSFW: this.displayNSFW,
219 autoPlayVideo: this.autoPlayVideo,
221 roleLabel: USER_ROLE_LABELS[ this.role ],
222 videoQuota: this.videoQuota,
223 createdAt: this.createdAt,
224 account: this.Account.toFormattedJSON()
227 if (Array.isArray(this.Account.VideoChannels) === true) {
228 json['videoChannels'] = this.Account.VideoChannels
229 .map(c => c.toFormattedJSON())
231 if (v1.createdAt < v2.createdAt) return -1
232 if (v1.createdAt === v2.createdAt) return 0
241 isAbleToUploadVideo (videoFile: Express.Multer.File) {
242 if (this.videoQuota === -1) return Promise.resolve(true)
244 return UserModel.getOriginalVideoFileTotalFromUser(this)
245 .then(totalBytes => {
246 return (videoFile.size + totalBytes) < this.videoQuota