1 import * as Sequelize from 'sequelize'
2 import * as Promise from 'bluebird'
4 import { getSort } from '../utils'
10 isUserDisplayNSFWValid,
11 isUserVideoQuotaValid,
13 } from '../../helpers'
14 import { UserRight, USER_ROLE_LABELS, hasUserRight } from '../../../shared'
16 import { addMethodsToModel } from '../utils'
22 } from './user-interface'
24 let User: Sequelize.Model<UserInstance, UserAttributes>
25 let isPasswordMatch: UserMethods.IsPasswordMatch
26 let hasRight: UserMethods.HasRight
27 let toFormattedJSON: UserMethods.ToFormattedJSON
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.INTEGER,
83 const res = isUserRoleValid(value)
84 if (res === false) throw new Error('Role is not valid.')
89 type: DataTypes.BIGINT,
92 videoQuotaValid: value => {
93 const res = isUserVideoQuotaValid(value)
94 if (res === false) throw new Error('Video quota is not valid.')
102 fields: [ 'username' ],
111 beforeCreate: beforeCreateOrUpdate,
112 beforeUpdate: beforeCreateOrUpdate
117 const classMethods = [
125 loadByUsernameAndPopulateChannels,
126 loadByUsernameOrEmail
128 const instanceMethods = [
134 addMethodsToModel(User, classMethods, instanceMethods)
139 function beforeCreateOrUpdate (user: UserInstance) {
140 return cryptPassword(user.password).then(hash => {
146 // ------------------------------ METHODS ------------------------------
148 hasRight = function (this: UserInstance, right: UserRight) {
149 return hasUserRight(this.role, right)
152 isPasswordMatch = function (this: UserInstance, password: string) {
153 return comparePassword(password, this.password)
156 toFormattedJSON = function (this: UserInstance) {
159 username: this.username,
161 displayNSFW: this.displayNSFW,
163 roleLabel: USER_ROLE_LABELS[this.role],
164 videoQuota: this.videoQuota,
165 createdAt: this.createdAt,
168 uuid: this.Author.uuid
172 if (Array.isArray(this.Author.VideoChannels) === true) {
173 const videoChannels = this.Author.VideoChannels
174 .map(c => c.toFormattedJSON())
176 if (v1.createdAt < v2.createdAt) return -1
177 if (v1.createdAt === v2.createdAt) return 0
182 json['videoChannels'] = videoChannels
188 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
189 if (this.videoQuota === -1) return Promise.resolve(true)
191 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
192 return (videoFile.size + totalBytes) < this.videoQuota
196 // ------------------------------ STATICS ------------------------------
198 function associate (models) {
199 User.hasOne(models.Author, {
200 foreignKey: 'userId',
204 User.hasMany(models.OAuthToken, {
205 foreignKey: 'userId',
210 countTotal = function () {
214 getByUsername = function (username: string) {
219 include: [ { model: User['sequelize'].models.Author, required: true } ]
222 return User.findOne(query)
225 listForApi = function (start: number, count: number, sort: string) {
229 order: [ getSort(sort) ],
230 include: [ { model: User['sequelize'].models.Author, required: true } ]
233 return User.findAndCountAll(query).then(({ rows, count }) => {
241 loadById = function (id: number) {
243 include: [ { model: User['sequelize'].models.Author, required: true } ]
246 return User.findById(id, options)
249 loadByUsername = function (username: string) {
254 include: [ { model: User['sequelize'].models.Author, required: true } ]
257 return User.findOne(query)
260 loadByUsernameAndPopulateChannels = function (username: string) {
267 model: User['sequelize'].models.Author,
269 include: [ User['sequelize'].models.VideoChannel ]
274 return User.findOne(query)
277 loadByUsernameOrEmail = function (username: string, email: string) {
279 include: [ { model: User['sequelize'].models.Author, required: true } ],
281 [Sequelize.Op.or]: [ { username }, { email } ]
285 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
286 return (User as any).findOne(query)
289 // ---------------------------------------------------------------------------
291 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
292 // Don't use sequelize because we need to use a sub query
293 const query = 'SELECT SUM("size") AS "total" FROM ' +
294 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
295 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
296 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
297 'INNER JOIN "Authors" ON "VideoChannels"."authorId" = "Authors"."id" ' +
298 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
299 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
302 bind: { userId: user.id },
303 type: Sequelize.QueryTypes.SELECT
305 return User['sequelize'].query(query, options).then(([ { total } ]) => {
306 if (total === null) return 0
308 return parseInt(total, 10)