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 listForApi: UserMethods.ListForApi
31 let loadById: UserMethods.LoadById
32 let loadByUsername: UserMethods.LoadByUsername
33 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
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 = [
119 loadByUsernameAndPopulateChannels,
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,
157 uuid: this.Author.uuid
161 if (Array.isArray(this.Author.VideoChannels) === true) {
162 const videoChannels = this.Author.VideoChannels
163 .map(c => c.toFormattedJSON())
165 if (v1.createdAt < v2.createdAt) return -1
166 if (v1.createdAt === v2.createdAt) return 0
171 json['videoChannels'] = videoChannels
177 isAdmin = function (this: UserInstance) {
178 return this.role === USER_ROLES.ADMIN
181 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
182 if (this.videoQuota === -1) return Promise.resolve(true)
184 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
185 return (videoFile.size + totalBytes) < this.videoQuota
189 // ------------------------------ STATICS ------------------------------
191 function associate (models) {
192 User.hasOne(models.Author, {
193 foreignKey: 'userId',
197 User.hasMany(models.OAuthToken, {
198 foreignKey: 'userId',
203 countTotal = function () {
207 getByUsername = function (username: string) {
212 include: [ { model: User['sequelize'].models.Author, required: true } ]
215 return User.findOne(query)
218 listForApi = function (start: number, count: number, sort: string) {
222 order: [ getSort(sort) ],
223 include: [ { model: User['sequelize'].models.Author, required: true } ]
226 return User.findAndCountAll(query).then(({ rows, count }) => {
234 loadById = function (id: number) {
236 include: [ { model: User['sequelize'].models.Author, required: true } ]
239 return User.findById(id, options)
242 loadByUsername = function (username: string) {
247 include: [ { model: User['sequelize'].models.Author, required: true } ]
250 return User.findOne(query)
253 loadByUsernameAndPopulateChannels = function (username: string) {
260 model: User['sequelize'].models.Author,
262 include: [ User['sequelize'].models.VideoChannel ]
267 return User.findOne(query)
270 loadByUsernameOrEmail = function (username: string, email: string) {
272 include: [ { model: User['sequelize'].models.Author, required: true } ],
274 [Sequelize.Op.or]: [ { username }, { email } ]
278 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
279 return (User as any).findOne(query)
282 // ---------------------------------------------------------------------------
284 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
285 // Don't use sequelize because we need to use a sub query
286 const query = 'SELECT SUM("size") AS "total" FROM ' +
287 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
288 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
289 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
290 'INNER JOIN "Authors" ON "VideoChannels"."authorId" = "Authors"."id" ' +
291 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
292 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
295 bind: { userId: user.id },
296 type: Sequelize.QueryTypes.SELECT
298 return User['sequelize'].query(query, options).then(([ { total } ]) => {
299 if (total === null) return 0
301 return parseInt(total, 10)