1 import * as Sequelize from 'sequelize'
2 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
6 isUserDisplayNSFWValid,
11 } from '../../helpers'
12 import { addMethodsToModel, getSort } from '../utils'
13 import { UserAttributes, UserInstance, UserMethods } from './user-interface'
15 let User: Sequelize.Model<UserInstance, UserAttributes>
16 let isPasswordMatch: UserMethods.IsPasswordMatch
17 let hasRight: UserMethods.HasRight
18 let toFormattedJSON: UserMethods.ToFormattedJSON
19 let countTotal: UserMethods.CountTotal
20 let getByUsername: UserMethods.GetByUsername
21 let listForApi: UserMethods.ListForApi
22 let loadById: UserMethods.LoadById
23 let loadByUsername: UserMethods.LoadByUsername
24 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
25 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
26 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
28 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
29 User = sequelize.define<UserInstance, UserAttributes>('User',
32 type: DataTypes.STRING,
35 passwordValid: value => {
36 const res = isUserPasswordValid(value)
37 if (res === false) throw new Error('Password not valid.')
42 type: DataTypes.STRING,
45 usernameValid: value => {
46 const res = isUserUsernameValid(value)
47 if (res === false) throw new Error('Username not valid.')
52 type: DataTypes.STRING(400),
59 type: DataTypes.BOOLEAN,
64 const res = isUserDisplayNSFWValid(value)
65 if (res === false) throw new Error('Display NSFW is not valid.')
70 type: DataTypes.INTEGER,
74 const res = isUserRoleValid(value)
75 if (res === false) throw new Error('Role is not valid.')
80 type: DataTypes.BIGINT,
83 videoQuotaValid: value => {
84 const res = isUserVideoQuotaValid(value)
85 if (res === false) throw new Error('Video quota is not valid.')
93 fields: [ 'username' ],
102 beforeCreate: beforeCreateOrUpdate,
103 beforeUpdate: beforeCreateOrUpdate
108 const classMethods = [
116 loadByUsernameAndPopulateChannels,
117 loadByUsernameOrEmail
119 const instanceMethods = [
125 addMethodsToModel(User, classMethods, instanceMethods)
130 function beforeCreateOrUpdate (user: UserInstance) {
131 if (user.changed('password')) {
132 return cryptPassword(user.password)
140 // ------------------------------ METHODS ------------------------------
142 hasRight = function (this: UserInstance, right: UserRight) {
143 return hasUserRight(this.role, right)
146 isPasswordMatch = function (this: UserInstance, password: string) {
147 return comparePassword(password, this.password)
150 toFormattedJSON = function (this: UserInstance) {
153 username: this.username,
155 displayNSFW: this.displayNSFW,
157 roleLabel: USER_ROLE_LABELS[this.role],
158 videoQuota: this.videoQuota,
159 createdAt: this.createdAt,
160 account: this.Account.toFormattedJSON()
163 if (Array.isArray(this.Account.VideoChannels) === true) {
164 const videoChannels = this.Account.VideoChannels
165 .map(c => c.toFormattedJSON())
167 if (v1.createdAt < v2.createdAt) return -1
168 if (v1.createdAt === v2.createdAt) return 0
173 json['videoChannels'] = videoChannels
179 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
180 if (this.videoQuota === -1) return Promise.resolve(true)
182 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
183 return (videoFile.size + totalBytes) < this.videoQuota
187 // ------------------------------ STATICS ------------------------------
189 function associate (models) {
190 User.hasOne(models.Account, {
191 foreignKey: 'userId',
195 User.hasMany(models.OAuthToken, {
196 foreignKey: 'userId',
201 countTotal = function () {
205 getByUsername = function (username: string) {
210 include: [ { model: User['sequelize'].models.Account, required: true } ]
213 return User.findOne(query)
216 listForApi = function (start: number, count: number, sort: string) {
220 order: [ getSort(sort) ],
221 include: [ { model: User['sequelize'].models.Account, required: true } ]
224 return User.findAndCountAll(query).then(({ rows, count }) => {
232 loadById = function (id: number) {
234 include: [ { model: User['sequelize'].models.Account, required: true } ]
237 return User.findById(id, options)
240 loadByUsername = function (username: string) {
245 include: [ { model: User['sequelize'].models.Account, required: true } ]
248 return User.findOne(query)
251 loadByUsernameAndPopulateChannels = function (username: string) {
258 model: User['sequelize'].models.Account,
260 include: [ User['sequelize'].models.VideoChannel ]
265 return User.findOne(query)
268 loadByUsernameOrEmail = function (username: string, email: string) {
270 include: [ { model: User['sequelize'].models.Account, required: true } ],
272 [Sequelize.Op.or]: [ { username }, { email } ]
276 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
277 return (User as any).findOne(query)
280 // ---------------------------------------------------------------------------
282 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
283 // Don't use sequelize because we need to use a sub query
284 const query = 'SELECT SUM("size") AS "total" FROM ' +
285 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
286 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
287 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
288 'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
289 'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
290 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
293 bind: { userId: user.id },
294 type: Sequelize.QueryTypes.SELECT
296 return User['sequelize'].query(query, options).then(([ { total } ]) => {
297 if (total === null) return 0
299 return parseInt(total, 10)