]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - src/pods.js
Logging refractoring
[github/Chocobozzz/PeerTube.git] / src / pods.js
index 9d6539685fab1dd03ca9c499060beac5f1c9a06f..a0dbb6b68c2efeff289b3f0f9aed2a7959005114 100644 (file)
@@ -1,16 +1,18 @@
 ;(function () {
   'use strict'
 
-  var fs = require('fs')
-  var config = require('config')
   var async = require('async')
+  var config = require('config')
+  var fs = require('fs')
   var request = require('request')
 
   var logger = require('./logger')
-  var utils = require('./utils')
   var PodsDB = require('./database').PodsDB
+  var poolRequests = require('./poolRequests')
+  var utils = require('./utils')
 
   var pods = {}
+
   var http = config.get('webserver.https') ? 'https' : 'http'
   var host = config.get('webserver.host')
   var port = config.get('webserver.port')
@@ -18,7 +20,7 @@
   // ----------- Private functions -----------
 
   function getForeignPodsList (url, callback) {
-    var path = '/api/pods'
+    var path = '/api/' + global.API_VERSION + '/pods'
 
     request.get(url + path, function (err, response, body) {
       if (err) throw err
@@ -27,6 +29,7 @@
   }
 
   // ----------- Public functions -----------
+
   pods.list = function (callback) {
     PodsDB.find(function (err, pods_list) {
       if (err) {
@@ -44,7 +47,8 @@
 
     var params = {
       url: data.url,
-      publicKey: data.publicKey
+      publicKey: data.publicKey,
+      score: global.FRIEND_BASE_SCORE
     }
 
     PodsDB.create(params, function (err, pod) {
@@ -53,7 +57,7 @@
         return callback(err)
       }
 
-      fs.readFile(utils.certDir + 'petube.pub', 'utf8', function (err, cert) {
+      fs.readFile(utils.certDir + 'peertube.pub', 'utf8', function (err, cert) {
         if (err) {
           logger.error('Cannot read cert file.', { error: err })
           return callback(err)
     })
   }
 
-  // { path, data }
-  pods.makeSecureRequest = function (data, callback) {
-    PodsDB.find({}, { url: 1, publicKey: 1 }).exec(function (err, urls) {
-      if (err) {
-        logger.error('Cannot get the list of the pods.', { error: err })
-        return callback(err)
-      }
-
-      logger.debug('Make multiple requests.')
-      utils.makeMultipleRetryRequest(
-        { encrypt: true, sign: true, method: data.method, path: data.path, data: data.data },
-
-        urls,
-
-        function (err, response, body, url) {
-          if (err || response.statusCode !== 200) {
-            logger.error('Error sending secure request to %s/%s pod.', url, data.path, { error: err })
-          }
-        },
-
-        function (err) {
-          if (err) {
-            logger.error('There was some errors when sending the video meta data.', { error: err })
-            return callback(err)
-          }
+  pods.addVideoToFriends = function (video) {
+    // To avoid duplicates
+    var id = video.name + video.magnetUri
+    poolRequests.addToPoolRequests(id, 'add', video)
+  }
 
-          logger.debug('Finished')
-          callback(null)
-        }
-      )
-    })
+  pods.removeVideoToFriends = function (video) {
+    // To avoid duplicates
+    var id = video.name + video.magnetUri
+    poolRequests.addToPoolRequests(id, 'remove', video)
   }
 
   pods.makeFriends = function (callback) {
-    logger.debug('Read public key...')
-    fs.readFile(utils.certDir + 'petube.pub', 'utf8', function (err, cert) {
+    var pods_score = {}
+
+    logger.info('Make friends!')
+    fs.readFile(utils.certDir + 'peertube.pub', 'utf8', function (err, cert) {
       if (err) {
         logger.error('Cannot read public cert.', { error: err })
         return callback(err)
       }
 
       var urls = config.get('network.friends')
-      var pods_score = {}
 
-      async.each(urls, function (url, callback) {
-        // Always add a trust pod
-        pods_score[url] = Infinity
+      async.each(urls, computeForeignPodsList, function () {
+        logger.debug('Pods scores computed.', { pods_score: pods_score })
+        var pods_list = computeWinningPods(urls, pods_score)
+        logger.debug('Pods that we keep computed.', { pods_to_keep: pods_list })
 
-        getForeignPodsList(url, function (foreign_pods_list) {
-          if (foreign_pods_list.length === 0) return callback()
+        makeRequestsToWinningPods(cert, pods_list)
+      })
+    })
 
-          async.each(foreign_pods_list, function (foreign_pod, callback) {
-            var foreign_url = foreign_pod.url
-            if (pods_score[foreign_url]) pods_score[foreign_url]++
-            else pods_score[foreign_url] = 1
-            callback()
-          }, callback)
-        })
-      }, function () {
-        logger.debug('Pods score', { pods_score: pods_score })
-
-        // Build the list of pods to add
-        // Only add a pod if it exists in more than a half base pods
-        var pods_list = []
-        var base_score = urls.length / 2
-        Object.keys(pods_score).forEach(function (pod) {
-          if (pods_score[pod] > base_score) pods_list.push({ url: pod })
+    // -----------------------------------------------------------------------
+
+    function computeForeignPodsList (url, callback) {
+      // Let's give 1 point to the pod we ask the friends list
+      pods_score[url] = 1
+
+      getForeignPodsList(url, function (foreign_pods_list) {
+        if (foreign_pods_list.length === 0) return callback()
+
+        async.each(foreign_pods_list, function (foreign_pod, callback_each) {
+          var foreign_url = foreign_pod.url
+
+          if (pods_score[foreign_url]) pods_score[foreign_url]++
+          else pods_score[foreign_url] = 1
+
+          callback_each()
+        }, function () {
+          callback()
         })
+      })
+    }
 
-        logger.debug('Pods that we keep', { pods: pods_list })
+    function computeWinningPods (urls, pods_score) {
+      // Build the list of pods to add
+      // Only add a pod if it exists in more than a half base pods
+      var pods_list = []
+      var base_score = urls.length / 2
+      Object.keys(pods_score).forEach(function (pod) {
+        if (pods_score[pod] > base_score) pods_list.push({ url: pod })
+      })
 
-        var data = {
-          url: http + '://' + host + ':' + port,
-          publicKey: cert
-        }
+      return pods_list
+    }
 
-        logger.debug('Make requests...')
-
-        utils.makeMultipleRetryRequest(
-          { method: 'POST', path: '/api/pods/', data: data },
-
-          pods_list,
-
-          function eachRequest (err, response, body, url) {
-            if (!err && response.statusCode === 200) {
-              pods.add({ url: url, publicKey: body.cert }, function (err) {
-                if (err) {
-                  logger.error('Error with adding %s pod.', url, { error: err })
-                }
-              })
-            } else {
-              logger.error('Error with adding %s pod.', url)
-            }
-          },
-
-          function endRequests (err) {
-            if (err) {
-              logger.error('There was some errors when we wanted to make friends.', { error: err })
-              return callback(err)
-            }
-
-            logger.debug('Finished')
-            callback(null)
+    function makeRequestsToWinningPods (cert, pods_list) {
+      var data = {
+        url: http + '://' + host + ':' + port,
+        publicKey: cert
+      }
+
+      utils.makeMultipleRetryRequest(
+        { method: 'POST', path: '/api/' + global.API_VERSION + '/pods/', data: data },
+
+        pods_list,
+
+        function eachRequest (err, response, body, url, pod, callback_each_request) {
+          // We add the pod if it responded correctly with its public certificate
+          if (!err && response.statusCode === 200) {
+            pods.add({ url: pod.url, publicKey: body.cert, score: global.FRIEND_BASE_SCORE }, function (err) {
+              if (err) {
+                logger.error('Error with adding %s pod.', pod.url, { error: err })
+              }
+
+              return callback_each_request()
+            })
+          } else {
+            logger.error('Error with adding %s pod.', pod.url, { error: err || new Error('Status not 200') })
+            return callback_each_request()
           }
-        )
-      })
-    })
+        },
+
+        function endRequests (err) {
+          if (err) {
+            logger.error('There was some errors when we wanted to make friends.', { error: err })
+            return callback(err)
+          }
+
+          logger.debug('makeRequestsToWinningPods finished.')
+          return callback(null)
+        }
+      )
+    }
   }
 
   module.exports = pods