1 import * as Sequelize from 'sequelize'
2 import * as Promise from 'bluebird'
4 import { getSort, addMethodsToModel } from '../utils'
10 isUserDisplayNSFWValid,
11 isUserVideoQuotaValid,
13 } from '../../helpers'
14 import { UserRight, USER_ROLE_LABELS, hasUserRight } from '../../../shared'
21 } from './user-interface'
23 let User: Sequelize.Model<UserInstance, UserAttributes>
24 let isPasswordMatch: UserMethods.IsPasswordMatch
25 let hasRight: UserMethods.HasRight
26 let toFormattedJSON: UserMethods.ToFormattedJSON
27 let countTotal: UserMethods.CountTotal
28 let getByUsername: UserMethods.GetByUsername
29 let listForApi: UserMethods.ListForApi
30 let loadById: UserMethods.LoadById
31 let loadByUsername: UserMethods.LoadByUsername
32 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
33 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
34 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
36 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
37 User = sequelize.define<UserInstance, UserAttributes>('User',
40 type: DataTypes.STRING,
43 passwordValid: value => {
44 const res = isUserPasswordValid(value)
45 if (res === false) throw new Error('Password not valid.')
50 type: DataTypes.STRING,
53 usernameValid: value => {
54 const res = isUserUsernameValid(value)
55 if (res === false) throw new Error('Username not valid.')
60 type: DataTypes.STRING(400),
67 type: DataTypes.BOOLEAN,
72 const res = isUserDisplayNSFWValid(value)
73 if (res === false) throw new Error('Display NSFW is not valid.')
78 type: DataTypes.INTEGER,
82 const res = isUserRoleValid(value)
83 if (res === false) throw new Error('Role is not valid.')
88 type: DataTypes.BIGINT,
91 videoQuotaValid: value => {
92 const res = isUserVideoQuotaValid(value)
93 if (res === false) throw new Error('Video quota is not valid.')
101 fields: [ 'username' ],
110 beforeCreate: beforeCreateOrUpdate,
111 beforeUpdate: beforeCreateOrUpdate
116 const classMethods = [
124 loadByUsernameAndPopulateChannels,
125 loadByUsernameOrEmail
127 const instanceMethods = [
133 addMethodsToModel(User, classMethods, instanceMethods)
138 function beforeCreateOrUpdate (user: UserInstance) {
139 return cryptPassword(user.password).then(hash => {
145 // ------------------------------ METHODS ------------------------------
147 hasRight = function (this: UserInstance, right: UserRight) {
148 return hasUserRight(this.role, right)
151 isPasswordMatch = function (this: UserInstance, password: string) {
152 return comparePassword(password, this.password)
155 toFormattedJSON = function (this: UserInstance) {
158 username: this.username,
160 displayNSFW: this.displayNSFW,
162 roleLabel: USER_ROLE_LABELS[this.role],
163 videoQuota: this.videoQuota,
164 createdAt: this.createdAt,
167 uuid: this.Author.uuid
171 if (Array.isArray(this.Author.VideoChannels) === true) {
172 const videoChannels = this.Author.VideoChannels
173 .map(c => c.toFormattedJSON())
175 if (v1.createdAt < v2.createdAt) return -1
176 if (v1.createdAt === v2.createdAt) return 0
181 json['videoChannels'] = videoChannels
187 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
188 if (this.videoQuota === -1) return Promise.resolve(true)
190 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
191 return (videoFile.size + totalBytes) < this.videoQuota
195 // ------------------------------ STATICS ------------------------------
197 function associate (models) {
198 User.hasOne(models.Author, {
199 foreignKey: 'userId',
203 User.hasMany(models.OAuthToken, {
204 foreignKey: 'userId',
209 countTotal = function () {
213 getByUsername = function (username: string) {
218 include: [ { model: User['sequelize'].models.Author, required: true } ]
221 return User.findOne(query)
224 listForApi = function (start: number, count: number, sort: string) {
228 order: [ getSort(sort) ],
229 include: [ { model: User['sequelize'].models.Author, required: true } ]
232 return User.findAndCountAll(query).then(({ rows, count }) => {
240 loadById = function (id: number) {
242 include: [ { model: User['sequelize'].models.Author, required: true } ]
245 return User.findById(id, options)
248 loadByUsername = function (username: string) {
253 include: [ { model: User['sequelize'].models.Author, required: true } ]
256 return User.findOne(query)
259 loadByUsernameAndPopulateChannels = function (username: string) {
266 model: User['sequelize'].models.Author,
268 include: [ User['sequelize'].models.VideoChannel ]
273 return User.findOne(query)
276 loadByUsernameOrEmail = function (username: string, email: string) {
278 include: [ { model: User['sequelize'].models.Author, required: true } ],
280 [Sequelize.Op.or]: [ { username }, { email } ]
284 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
285 return (User as any).findOne(query)
288 // ---------------------------------------------------------------------------
290 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
291 // Don't use sequelize because we need to use a sub query
292 const query = 'SELECT SUM("size") AS "total" FROM ' +
293 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
294 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
295 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
296 'INNER JOIN "Authors" ON "VideoChannels"."authorId" = "Authors"."id" ' +
297 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
298 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
301 bind: { userId: user.id },
302 type: Sequelize.QueryTypes.SELECT
304 return User['sequelize'].query(query, options).then(([ { total } ]) => {
305 if (total === null) return 0
307 return parseInt(total, 10)