1 import { values } from 'lodash'
2 import * as Sequelize from 'sequelize'
3 import * as Promise from 'bluebird'
5 import { getSort } from '../utils'
6 import { USER_ROLES } from '../../initializers'
12 isUserDisplayNSFWValid,
14 } from '../../helpers'
16 import { addMethodsToModel } from '../utils'
22 } from './user-interface'
24 let User: Sequelize.Model<UserInstance, UserAttributes>
25 let isPasswordMatch: UserMethods.IsPasswordMatch
26 let toFormattedJSON: UserMethods.ToFormattedJSON
27 let isAdmin: UserMethods.IsAdmin
28 let countTotal: UserMethods.CountTotal
29 let getByUsername: UserMethods.GetByUsername
30 let list: UserMethods.List
31 let listForApi: UserMethods.ListForApi
32 let loadById: UserMethods.LoadById
33 let loadByUsername: UserMethods.LoadByUsername
34 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
35 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
37 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
38 User = sequelize.define<UserInstance, UserAttributes>('User',
41 type: DataTypes.STRING,
44 passwordValid: value => {
45 const res = isUserPasswordValid(value)
46 if (res === false) throw new Error('Password not valid.')
51 type: DataTypes.STRING,
54 usernameValid: value => {
55 const res = isUserUsernameValid(value)
56 if (res === false) throw new Error('Username not valid.')
61 type: DataTypes.STRING(400),
68 type: DataTypes.BOOLEAN,
73 const res = isUserDisplayNSFWValid(value)
74 if (res === false) throw new Error('Display NSFW is not valid.')
79 type: DataTypes.ENUM(values(USER_ROLES)),
83 type: DataTypes.BIGINT,
86 videoQuotaValid: value => {
87 const res = isUserVideoQuotaValid(value)
88 if (res === false) throw new Error('Video quota is not valid.')
96 fields: [ 'username' ],
105 beforeCreate: beforeCreateOrUpdate,
106 beforeUpdate: beforeCreateOrUpdate
111 const classMethods = [
120 loadByUsernameOrEmail
122 const instanceMethods = [
128 addMethodsToModel(User, classMethods, instanceMethods)
133 function beforeCreateOrUpdate (user: UserInstance) {
134 return cryptPassword(user.password).then(hash => {
140 // ------------------------------ METHODS ------------------------------
142 isPasswordMatch = function (this: UserInstance, password: string) {
143 return comparePassword(password, this.password)
146 toFormattedJSON = function (this: UserInstance) {
149 username: this.username,
151 displayNSFW: this.displayNSFW,
153 videoQuota: this.videoQuota,
154 createdAt: this.createdAt
158 isAdmin = function (this: UserInstance) {
159 return this.role === USER_ROLES.ADMIN
162 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
163 if (this.videoQuota === -1) return Promise.resolve(true)
165 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
166 return (videoFile.size + totalBytes) < this.videoQuota
170 // ------------------------------ STATICS ------------------------------
172 function associate (models) {
173 User.hasOne(models.Author, {
174 foreignKey: 'userId',
178 User.hasMany(models.OAuthToken, {
179 foreignKey: 'userId',
184 countTotal = function () {
188 getByUsername = function (username: string) {
195 return User.findOne(query)
199 return User.findAll()
202 listForApi = function (start: number, count: number, sort: string) {
206 order: [ getSort(sort) ]
209 return User.findAndCountAll(query).then(({ rows, count }) => {
217 loadById = function (id: number) {
218 return User.findById(id)
221 loadByUsername = function (username: string) {
228 return User.findOne(query)
231 loadByUsernameOrEmail = function (username: string, email: string) {
234 $or: [ { username }, { email } ]
238 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
239 return (User as any).findOne(query)
242 // ---------------------------------------------------------------------------
244 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
245 // Don't use sequelize because we need to use a subquery
246 const query = 'SELECT SUM("size") AS "total" FROM ' +
247 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
248 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
249 'INNER JOIN "Authors" ON "Videos"."authorId" = "Authors"."id" ' +
250 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
251 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
254 bind: { userId: user.id },
255 type: Sequelize.QueryTypes.SELECT
257 return User['sequelize'].query(query, options).then(([ { total } ]) => {
258 if (total === null) return 0
260 return parseInt(total, 10)