]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/user/user.ts
Upgrade express validator to v4
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
index 6b2410259cdcfd0bac3cf74c5341b3b78f5989ef..79a595528db53babdd2371a7d880ff803b2196ff 100644 (file)
@@ -1,5 +1,6 @@
 import { values } from 'lodash'
 import * as Sequelize from 'sequelize'
+import * as Promise from 'bluebird'
 
 import { getSort } from '../utils'
 import { USER_ROLES } from '../../initializers'
@@ -8,12 +9,12 @@ import {
   comparePassword,
   isUserPasswordValid,
   isUserUsernameValid,
-  isUserDisplayNSFWValid
+  isUserDisplayNSFWValid,
+  isUserVideoQuotaValid
 } from '../../helpers'
 
 import { addMethodsToModel } from '../utils'
 import {
-  UserClass,
   UserInstance,
   UserAttributes,
 
@@ -22,7 +23,7 @@ import {
 
 let User: Sequelize.Model<UserInstance, UserAttributes>
 let isPasswordMatch: UserMethods.IsPasswordMatch
-let toFormatedJSON: UserMethods.ToFormatedJSON
+let toFormattedJSON: UserMethods.ToFormattedJSON
 let isAdmin: UserMethods.IsAdmin
 let countTotal: UserMethods.CountTotal
 let getByUsername: UserMethods.GetByUsername
@@ -31,6 +32,7 @@ let listForApi: UserMethods.ListForApi
 let loadById: UserMethods.LoadById
 let loadByUsername: UserMethods.LoadByUsername
 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
+let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
 
 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
   User = sequelize.define<UserInstance, UserAttributes>('User',
@@ -39,7 +41,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         type: DataTypes.STRING,
         allowNull: false,
         validate: {
-          passwordValid: function (value) {
+          passwordValid: value => {
             const res = isUserPasswordValid(value)
             if (res === false) throw new Error('Password not valid.')
           }
@@ -49,7 +51,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         type: DataTypes.STRING,
         allowNull: false,
         validate: {
-          usernameValid: function (value) {
+          usernameValid: value => {
             const res = isUserUsernameValid(value)
             if (res === false) throw new Error('Username not valid.')
           }
@@ -67,7 +69,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         allowNull: false,
         defaultValue: false,
         validate: {
-          nsfwValid: function (value) {
+          nsfwValid: value => {
             const res = isUserDisplayNSFWValid(value)
             if (res === false) throw new Error('Display NSFW is not valid.')
           }
@@ -76,6 +78,16 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
       role: {
         type: DataTypes.ENUM(values(USER_ROLES)),
         allowNull: false
+      },
+      videoQuota: {
+        type: DataTypes.BIGINT,
+        allowNull: false,
+        validate: {
+          videoQuotaValid: value => {
+            const res = isUserVideoQuotaValid(value)
+            if (res === false) throw new Error('Video quota is not valid.')
+          }
+        }
       }
     },
     {
@@ -109,8 +121,9 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
   ]
   const instanceMethods = [
     isPasswordMatch,
-    toFormatedJSON,
-    isAdmin
+    toFormattedJSON,
+    isAdmin,
+    isAbleToUploadVideo
   ]
   addMethodsToModel(User, classMethods, instanceMethods)
 
@@ -118,30 +131,26 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
 }
 
 function beforeCreateOrUpdate (user: UserInstance) {
-  return new Promise(function (resolve, reject) {
-    cryptPassword(user.password, function (err, hash) {
-      if (err) return reject(err)
-
-      user.password = hash
-
-      return resolve()
-    })
+  return cryptPassword(user.password).then(hash => {
+    user.password = hash
+    return undefined
   })
 }
 
 // ------------------------------ METHODS ------------------------------
 
-isPasswordMatch = function (this: UserInstance, password: string, callback: UserMethods.IsPasswordMatchCallback) {
-  return comparePassword(password, this.password, callback)
+isPasswordMatch = function (this: UserInstance, password: string) {
+  return comparePassword(password, this.password)
 }
 
-toFormatedJSON = function (this: UserInstance) {
+toFormattedJSON = function (this: UserInstance) {
   return {
     id: this.id,
     username: this.username,
     email: this.email,
     displayNSFW: this.displayNSFW,
     role: this.role,
+    videoQuota: this.videoQuota,
     createdAt: this.createdAt
   }
 }
@@ -150,6 +159,14 @@ isAdmin = function (this: UserInstance) {
   return this.role === USER_ROLES.ADMIN
 }
 
+isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
+  if (this.videoQuota === -1) return Promise.resolve(true)
+
+  return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
+    return (videoFile.size + totalBytes) < this.videoQuota
+  })
+}
+
 // ------------------------------ STATICS ------------------------------
 
 function associate (models) {
@@ -164,8 +181,8 @@ function associate (models) {
   })
 }
 
-countTotal = function (callback: UserMethods.CountTotalCallback) {
-  return this.count().asCallback(callback)
+countTotal = function () {
+  return this.count()
 }
 
 getByUsername = function (username: string) {
@@ -178,44 +195,80 @@ getByUsername = function (username: string) {
   return User.findOne(query)
 }
 
-list = function (callback: UserMethods.ListCallback) {
-  return User.find().asCallback(callback)
+list = function () {
+  return User.findAll()
 }
 
-listForApi = function (start: number, count: number, sort: string, callback: UserMethods.ListForApiCallback) {
+listForApi = function (start: number, count: number, sort: string) {
   const query = {
     offset: start,
     limit: count,
     order: [ getSort(sort) ]
   }
 
-  return User.findAndCountAll(query).asCallback(function (err, result) {
-    if (err) return callback(err)
-
-    return callback(null, result.rows, result.count)
+  return User.findAndCountAll(query).then(({ rows, count }) => {
+    return {
+      data: rows,
+      total: count
+    }
   })
 }
 
-loadById = function (id: number, callback: UserMethods.LoadByIdCallback) {
-  return User.findById(id).asCallback(callback)
+loadById = function (id: number) {
+  return User.findById(id)
 }
 
-loadByUsername = function (username: string, callback: UserMethods.LoadByUsernameCallback) {
+loadByUsername = function (username: string) {
   const query = {
     where: {
-      username: username
+      username
     }
   }
 
-  return User.findOne(query).asCallback(callback)
+  return User.findOne(query)
 }
 
-loadByUsernameOrEmail = function (username: string, email: string, callback: UserMethods.LoadByUsernameOrEmailCallback) {
+loadByUsernameOrEmail = function (username: string, email: string) {
   const query = {
     where: {
       $or: [ { username }, { email } ]
     }
   }
 
-  return User.findOne(query).asCallback(callback)
+  // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
+  return (User as any).findOne(query)
+}
+
+// ---------------------------------------------------------------------------
+
+function getOriginalVideoFileTotalFromUser (user: UserInstance) {
+  // attributes = [] because we don't want other fields than the sum
+  const query = {
+    where: {
+      resolution: 0 // Original, TODO: improve readability
+    },
+    include: [
+      {
+        attributes: [],
+        model: User['sequelize'].models.Video,
+        include: [
+          {
+            attributes: [],
+            model: User['sequelize'].models.Author,
+            include: [
+              {
+                attributes: [],
+                model: User['sequelize'].models.User,
+                where: {
+                  id: user.id
+                }
+              }
+            ]
+          }
+        ]
+      }
+    ]
+  }
+
+  return User['sequelize'].models.VideoFile.sum('size', query)
 }