1 import * as Sequelize from 'sequelize'
3 import { getSort, addMethodsToModel } from '../utils'
9 isUserDisplayNSFWValid,
10 isUserVideoQuotaValid,
12 } from '../../helpers'
13 import { UserRight, USER_ROLE_LABELS, hasUserRight } from '../../../shared'
20 } from './user-interface'
22 let User: Sequelize.Model<UserInstance, UserAttributes>
23 let isPasswordMatch: UserMethods.IsPasswordMatch
24 let hasRight: UserMethods.HasRight
25 let toFormattedJSON: UserMethods.ToFormattedJSON
26 let countTotal: UserMethods.CountTotal
27 let getByUsername: UserMethods.GetByUsername
28 let listForApi: UserMethods.ListForApi
29 let loadById: UserMethods.LoadById
30 let loadByUsername: UserMethods.LoadByUsername
31 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
32 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
33 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
35 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
36 User = sequelize.define<UserInstance, UserAttributes>('User',
39 type: DataTypes.STRING,
42 passwordValid: value => {
43 const res = isUserPasswordValid(value)
44 if (res === false) throw new Error('Password not valid.')
49 type: DataTypes.STRING,
52 usernameValid: value => {
53 const res = isUserUsernameValid(value)
54 if (res === false) throw new Error('Username not valid.')
59 type: DataTypes.STRING(400),
66 type: DataTypes.BOOLEAN,
71 const res = isUserDisplayNSFWValid(value)
72 if (res === false) throw new Error('Display NSFW is not valid.')
77 type: DataTypes.INTEGER,
81 const res = isUserRoleValid(value)
82 if (res === false) throw new Error('Role is not valid.')
87 type: DataTypes.BIGINT,
90 videoQuotaValid: value => {
91 const res = isUserVideoQuotaValid(value)
92 if (res === false) throw new Error('Video quota is not valid.')
100 fields: [ 'username' ],
109 beforeCreate: beforeCreateOrUpdate,
110 beforeUpdate: beforeCreateOrUpdate
115 const classMethods = [
123 loadByUsernameAndPopulateChannels,
124 loadByUsernameOrEmail
126 const instanceMethods = [
132 addMethodsToModel(User, classMethods, instanceMethods)
137 function beforeCreateOrUpdate (user: UserInstance) {
138 if (user.changed('password')) {
139 return cryptPassword(user.password)
147 // ------------------------------ METHODS ------------------------------
149 hasRight = function (this: UserInstance, right: UserRight) {
150 return hasUserRight(this.role, right)
153 isPasswordMatch = function (this: UserInstance, password: string) {
154 return comparePassword(password, this.password)
157 toFormattedJSON = function (this: UserInstance) {
160 username: this.username,
162 displayNSFW: this.displayNSFW,
164 roleLabel: USER_ROLE_LABELS[this.role],
165 videoQuota: this.videoQuota,
166 createdAt: this.createdAt,
169 uuid: this.Account.uuid
173 if (Array.isArray(this.Account.VideoChannels) === true) {
174 const videoChannels = this.Account.VideoChannels
175 .map(c => c.toFormattedJSON())
177 if (v1.createdAt < v2.createdAt) return -1
178 if (v1.createdAt === v2.createdAt) return 0
183 json['videoChannels'] = videoChannels
189 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
190 if (this.videoQuota === -1) return Promise.resolve(true)
192 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
193 return (videoFile.size + totalBytes) < this.videoQuota
197 // ------------------------------ STATICS ------------------------------
199 function associate (models) {
200 User.hasOne(models.Account, {
201 foreignKey: 'userId',
205 User.hasMany(models.OAuthToken, {
206 foreignKey: 'userId',
211 countTotal = function () {
215 getByUsername = function (username: string) {
220 include: [ { model: User['sequelize'].models.Account, required: true } ]
223 return User.findOne(query)
226 listForApi = function (start: number, count: number, sort: string) {
230 order: [ getSort(sort) ],
231 include: [ { model: User['sequelize'].models.Account, required: true } ]
234 return User.findAndCountAll(query).then(({ rows, count }) => {
242 loadById = function (id: number) {
244 include: [ { model: User['sequelize'].models.Account, required: true } ]
247 return User.findById(id, options)
250 loadByUsername = function (username: string) {
255 include: [ { model: User['sequelize'].models.Account, required: true } ]
258 return User.findOne(query)
261 loadByUsernameAndPopulateChannels = function (username: string) {
268 model: User['sequelize'].models.Account,
270 include: [ User['sequelize'].models.VideoChannel ]
275 return User.findOne(query)
278 loadByUsernameOrEmail = function (username: string, email: string) {
280 include: [ { model: User['sequelize'].models.Account, required: true } ],
282 [Sequelize.Op.or]: [ { username }, { email } ]
286 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
287 return (User as any).findOne(query)
290 // ---------------------------------------------------------------------------
292 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
293 // Don't use sequelize because we need to use a sub query
294 const query = 'SELECT SUM("size") AS "total" FROM ' +
295 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
296 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
297 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
298 'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
299 'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
300 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
303 bind: { userId: user.id },
304 type: Sequelize.QueryTypes.SELECT
306 return User['sequelize'].query(query, options).then(([ { total } ]) => {
307 if (total === null) return 0
309 return parseInt(total, 10)