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,
162 uuid: this.Account.uuid
166 if (Array.isArray(this.Account.VideoChannels) === true) {
167 const videoChannels = this.Account.VideoChannels
168 .map(c => c.toFormattedJSON())
170 if (v1.createdAt < v2.createdAt) return -1
171 if (v1.createdAt === v2.createdAt) return 0
176 json['videoChannels'] = videoChannels
182 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
183 if (this.videoQuota === -1) return Promise.resolve(true)
185 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
186 return (videoFile.size + totalBytes) < this.videoQuota
190 // ------------------------------ STATICS ------------------------------
192 function associate (models) {
193 User.hasOne(models.Account, {
194 foreignKey: 'userId',
198 User.hasMany(models.OAuthToken, {
199 foreignKey: 'userId',
204 countTotal = function () {
208 getByUsername = function (username: string) {
213 include: [ { model: User['sequelize'].models.Account, required: true } ]
216 return User.findOne(query)
219 listForApi = function (start: number, count: number, sort: string) {
223 order: [ getSort(sort) ],
224 include: [ { model: User['sequelize'].models.Account, required: true } ]
227 return User.findAndCountAll(query).then(({ rows, count }) => {
235 loadById = function (id: number) {
237 include: [ { model: User['sequelize'].models.Account, required: true } ]
240 return User.findById(id, options)
243 loadByUsername = function (username: string) {
248 include: [ { model: User['sequelize'].models.Account, required: true } ]
251 return User.findOne(query)
254 loadByUsernameAndPopulateChannels = function (username: string) {
261 model: User['sequelize'].models.Account,
263 include: [ User['sequelize'].models.VideoChannel ]
268 return User.findOne(query)
271 loadByUsernameOrEmail = function (username: string, email: string) {
273 include: [ { model: User['sequelize'].models.Account, required: true } ],
275 [Sequelize.Op.or]: [ { username }, { email } ]
279 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
280 return (User as any).findOne(query)
283 // ---------------------------------------------------------------------------
285 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
286 // Don't use sequelize because we need to use a sub query
287 const query = 'SELECT SUM("size") AS "total" FROM ' +
288 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
289 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
290 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
291 'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
292 'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
293 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
296 bind: { userId: user.id },
297 type: Sequelize.QueryTypes.SELECT
299 return User['sequelize'].query(query, options).then(([ { total } ]) => {
300 if (total === null) return 0
302 return parseInt(total, 10)