]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/pod/pod.ts
Add follow tabs
[github/Chocobozzz/PeerTube.git] / server / models / pod / pod.ts
index df64127213da6ccb095690f842ba19c20fb1f197..6d270ad7fdc7dfeb3eeb949f44d3edb7120aad37 100644 (file)
@@ -4,7 +4,7 @@ import * as Sequelize from 'sequelize'
 import { FRIEND_SCORE, PODS_SCORE } from '../../initializers'
 import { logger, isHostValid } from '../../helpers'
 
-import { addMethodsToModel } from '../utils'
+import { addMethodsToModel, getSort } from '../utils'
 import {
   PodInstance,
   PodAttributes,
@@ -17,6 +17,7 @@ let toFormattedJSON: PodMethods.ToFormattedJSON
 let countAll: PodMethods.CountAll
 let incrementScores: PodMethods.IncrementScores
 let list: PodMethods.List
+let listForApi: PodMethods.ListForApi
 let listAllIds: PodMethods.ListAllIds
 let listRandomPodIdsWithRequest: PodMethods.ListRandomPodIdsWithRequest
 let listBadPods: PodMethods.ListBadPods
@@ -38,10 +39,6 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
           }
         }
       },
-      publicKey: {
-        type: DataTypes.STRING(5000),
-        allowNull: false
-      },
       score: {
         type: DataTypes.INTEGER,
         defaultValue: FRIEND_SCORE.BASE,
@@ -50,13 +47,6 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
           isInt: true,
           max: FRIEND_SCORE.MAX
         }
-      },
-      email: {
-        type: DataTypes.STRING(400),
-        allowNull: false,
-        validate: {
-          isEmail: true
-        }
       }
     },
     {
@@ -73,11 +63,10 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
   )
 
   const classMethods = [
-    associate,
-
     countAll,
     incrementScores,
     list,
+    listForApi,
     listAllIds,
     listRandomPodIdsWithRequest,
     listBadPods,
@@ -98,7 +87,6 @@ toFormattedJSON = function (this: PodInstance) {
   const json = {
     id: this.id,
     host: this.host,
-    email: this.email,
     score: this.score as number,
     createdAt: this.createdAt
   }
@@ -108,14 +96,6 @@ toFormattedJSON = function (this: PodInstance) {
 
 // ------------------------------ Statics ------------------------------
 
-function associate (models) {
-  Pod.belongsToMany(models.Request, {
-    foreignKey: 'podId',
-    through: models.RequestToPod,
-    onDelete: 'cascade'
-  })
-}
-
 countAll = function () {
   return Pod.count()
 }
@@ -128,7 +108,7 @@ incrementScores = function (ids: number[], value: number) {
   const options = {
     where: {
       id: {
-        $in: ids
+        [Sequelize.Op.in]: ids
       }
     },
     // In this case score is a literal and not an integer so we do not validate it
@@ -142,6 +122,21 @@ list = function () {
   return Pod.findAll()
 }
 
+listForApi = function (start: number, count: number, sort: string) {
+  const query = {
+    offset: start,
+    limit: count,
+    order: [ getSort(sort) ]
+  }
+
+  return Pod.findAndCountAll(query).then(({ rows, count }) => {
+    return {
+      data: rows,
+      total: count
+    }
+  })
+}
+
 listAllIds = function (transaction: Sequelize.Transaction) {
   const query = {
     attributes: [ 'id' ],
@@ -161,6 +156,7 @@ listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, ta
     let start = Math.floor(Math.random() * count) - limit
     if (start < 0) start = 0
 
+    const subQuery = `(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`
     const query = {
       attributes: [ 'id' ],
       order: [
@@ -170,7 +166,7 @@ listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, ta
       limit: limit,
       where: {
         id: {
-          $in: Sequelize.literal(`(SELECT DISTINCT "${tableWithPods}"."podId" FROM "${tableWithPods}" ${tableWithPodsJoins})`)
+          [Sequelize.Op.in]: Sequelize.literal(subQuery)
         }
       }
     }
@@ -184,7 +180,9 @@ listRandomPodIdsWithRequest = function (limit: number, tableWithPods: string, ta
 listBadPods = function () {
   const query = {
     where: {
-      score: { $lte: 0 }
+      score: {
+        [Sequelize.Op.lte]: 0
+      }
     }
   }
 
@@ -219,7 +217,7 @@ updatePodsScore = function (goodPods: number[], badPods: number[]) {
   }
 
   if (badPods.length !== 0) {
-    incrementScores(badPods, PODS_SCORE.MALUS)
+    incrementScores(badPods, PODS_SCORE.PENALTY)
       .then(() => removeBadPods())
       .catch(err => {
         if (err) logger.error('Cannot decrement scores of bad pods.', err)
@@ -230,20 +228,21 @@ updatePodsScore = function (goodPods: number[], badPods: number[]) {
 // ---------------------------------------------------------------------------
 
 // Remove pods with a score of 0 (too many requests where they were unreachable)
-function removeBadPods () {
-  return listBadPods()
-    .then(pods => {
-      const podsRemovePromises = pods.map(pod => pod.destroy())
-      return Promise.all(podsRemovePromises).then(() => pods.length)
-    })
-    .then(numberOfPodsRemoved => {
-      if (numberOfPodsRemoved) {
-        logger.info('Removed %d pods.', numberOfPodsRemoved)
-      } else {
-        logger.info('No need to remove bad pods.')
-      }
-    })
-    .catch(err => {
-      logger.error('Cannot remove bad pods.', err)
-    })
+async function removeBadPods () {
+  try {
+    const pods = await listBadPods()
+
+    const podsRemovePromises = pods.map(pod => pod.destroy())
+    await Promise.all(podsRemovePromises)
+
+    const numberOfPodsRemoved = pods.length
+
+    if (numberOfPodsRemoved) {
+      logger.info('Removed %d pods.', numberOfPodsRemoved)
+    } else {
+      logger.info('No need to remove bad pods.')
+    }
+  } catch (err) {
+    logger.error('Cannot remove bad pods.', err)
+  }
 }