]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/friends.js
Server: fix refreshing token
[github/Chocobozzz/PeerTube.git] / server / lib / friends.js
index a85f4e19acca4f655686704255774af5658a6704..eaea040ca9b0829762e594ad328fbf0d021c3e2c 100644 (file)
@@ -1,35 +1,33 @@
 'use strict'
 
-const async = require('async')
-const config = require('config')
+const each = require('async/each')
+const eachLimit = require('async/eachLimit')
+const eachSeries = require('async/eachSeries')
 const fs = require('fs')
 const mongoose = require('mongoose')
 const request = require('request')
+const waterfall = require('async/waterfall')
 
 const constants = require('../initializers/constants')
 const logger = require('../helpers/logger')
-const peertubeCrypto = require('../helpers/peertube-crypto')
 const requests = require('../helpers/requests')
 
-const http = config.get('webserver.https') ? 'https' : 'http'
-const host = config.get('webserver.host')
-const port = config.get('webserver.port')
 const Pod = mongoose.model('Pod')
 const Request = mongoose.model('Request')
 const Video = mongoose.model('Video')
 
 const friends = {
-  addVideoToFriends: addVideoToFriends,
-  hasFriends: hasFriends,
-  getMyCertificate: getMyCertificate,
-  makeFriends: makeFriends,
-  quitFriends: quitFriends,
-  removeVideoToFriends: removeVideoToFriends,
-  sendOwnedVideosToPod: sendOwnedVideosToPod
+  addVideoToFriends,
+  hasFriends,
+  getMyCertificate,
+  makeFriends,
+  quitFriends,
+  removeVideoToFriends,
+  sendOwnedVideosToPod
 }
 
 function addVideoToFriends (video) {
-  createRequest('add', video)
+  createRequest('add', constants.REQUEST_ENDPOINTS.VIDEOS, video)
 }
 
 function hasFriends (callback) {
@@ -42,10 +40,10 @@ function hasFriends (callback) {
 }
 
 function getMyCertificate (callback) {
-  fs.readFile(peertubeCrypto.getCertDir() + 'peertube.pub', 'utf8', callback)
+  fs.readFile(constants.CONFIG.STORAGE.CERT_DIR + 'peertube.pub', 'utf8', callback)
 }
 
-function makeFriends (callback) {
+function makeFriends (hosts, callback) {
   const podsScore = {}
 
   logger.info('Make friends!')
@@ -55,15 +53,13 @@ function makeFriends (callback) {
       return callback(err)
     }
 
-    const urls = config.get('network.friends')
-
-    async.eachSeries(urls, function (url, callbackEach) {
-      computeForeignPodsList(url, podsScore, callbackEach)
+    eachSeries(hosts, function (host, callbackEach) {
+      computeForeignPodsList(host, podsScore, callbackEach)
     }, function (err) {
       if (err) return callback(err)
 
       logger.debug('Pods scores computed.', { podsScore: podsScore })
-      const podsList = computeWinningPods(urls, podsScore)
+      const podsList = computeWinningPods(hosts, podsScore)
       logger.debug('Pods that we keep.', { podsToKeep: podsList })
 
       makeRequestsToWinningPods(cert, podsList, callback)
@@ -77,7 +73,7 @@ function quitFriends (callback) {
   // Flush pool requests
   Request.flush()
 
-  async.waterfall([
+  waterfall([
     function getPodsList (callbackAsync) {
       return Pod.list(callbackAsync)
     },
@@ -92,7 +88,7 @@ function quitFriends (callback) {
       // Announce we quit them
       // We don't care if the request fails
       // The other pod will exclude us automatically after a while
-      async.eachLimit(pods, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
+      eachLimit(pods, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
         requestParams.toPod = pod
         requests.makeSecureRequest(requestParams, callbackEach)
       }, function (err) {
@@ -101,25 +97,13 @@ function quitFriends (callback) {
           // Don't stop the process
         }
 
-        return callbackAsync()
-      })
-    },
-
-    function removePodsFromDB (callbackAsync) {
-      Pod.removeAll(function (err) {
-        return callbackAsync(err)
+        return callbackAsync(null, pods)
       })
     },
 
-    function listRemoteVideos (callbackAsync) {
-      logger.info('Broke friends, so sad :(')
-
-      Video.listRemotes(callbackAsync)
-    },
-
-    function removeTheRemoteVideos (videosList, callbackAsync) {
-      async.each(videosList, function (video, callbackEach) {
-        video.remove(callbackEach)
+    function removePodsFromDB (pods, callbackAsync) {
+      each(pods, function (pod, callbackEach) {
+        pod.remove(callbackEach)
       }, callbackAsync)
     }
   ], function (err) {
@@ -134,7 +118,7 @@ function quitFriends (callback) {
 }
 
 function removeVideoToFriends (videoParams) {
-  createRequest('remove', videoParams)
+  createRequest('remove', constants.REQUEST_ENDPOINTS.VIDEOS, videoParams)
 }
 
 function sendOwnedVideosToPod (podId) {
@@ -152,7 +136,7 @@ function sendOwnedVideosToPod (podId) {
           return
         }
 
-        createRequest('add', remoteVideo, [ podId ])
+        createRequest('add', constants.REQUEST_ENDPOINTS.VIDEOS, remoteVideo, [ podId ])
       })
     })
   })
@@ -164,45 +148,53 @@ module.exports = friends
 
 // ---------------------------------------------------------------------------
 
-function computeForeignPodsList (url, podsScore, callback) {
-  getForeignPodsList(url, function (err, foreignPodsList) {
+function computeForeignPodsList (host, podsScore, callback) {
+  getForeignPodsList(host, function (err, foreignPodsList) {
     if (err) return callback(err)
 
     if (!foreignPodsList) foreignPodsList = []
 
     // Let's give 1 point to the pod we ask the friends list
-    foreignPodsList.push({ url: url })
+    foreignPodsList.push({ host })
 
     foreignPodsList.forEach(function (foreignPod) {
-      const foreignPodUrl = foreignPod.url
+      const foreignPodHost = foreignPod.host
 
-      if (podsScore[foreignPodUrl]) podsScore[foreignPodUrl]++
-      else podsScore[foreignPodUrl] = 1
+      if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
+      else podsScore[foreignPodHost] = 1
     })
 
     callback()
   })
 }
 
-function computeWinningPods (urls, podsScore) {
+function computeWinningPods (hosts, podsScore) {
   // Build the list of pods to add
   // Only add a pod if it exists in more than a half base pods
   const podsList = []
-  const baseScore = urls.length / 2
-  Object.keys(podsScore).forEach(function (pod) {
-    if (podsScore[pod] > baseScore) podsList.push({ url: pod })
+  const baseScore = hosts.length / 2
+  Object.keys(podsScore).forEach(function (podHost) {
+    // If the pod is not me and with a good score we add it
+    if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
+      podsList.push({ host: podHost })
+    }
   })
 
   return podsList
 }
 
-function getForeignPodsList (url, callback) {
+function getForeignPodsList (host, callback) {
   const path = '/api/' + constants.API_VERSION + '/pods'
 
-  request.get(url + path, function (err, response, body) {
+  request.get(constants.REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
     if (err) return callback(err)
 
-    callback(null, JSON.parse(body))
+    try {
+      const json = JSON.parse(body)
+      return callback(null, json)
+    } catch (err) {
+      return callback(err)
+    }
   })
 }
 
@@ -212,28 +204,28 @@ function makeRequestsToWinningPods (cert, podsList, callback) {
   // Flush pool requests
   Request.forceSend()
 
-  async.eachLimit(podsList, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
+  eachLimit(podsList, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
     const params = {
-      url: pod.url + '/api/' + constants.API_VERSION + '/pods/',
+      url: constants.REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + constants.API_VERSION + '/pods/',
       method: 'POST',
       json: {
-        url: http + '://' + host + ':' + port,
+        host: constants.CONFIG.WEBSERVER.HOST,
         publicKey: cert
       }
     }
 
     requests.makeRetryRequest(params, function (err, res, body) {
       if (err) {
-        logger.error('Error with adding %s pod.', pod.url, { error: err })
+        logger.error('Error with adding %s pod.', pod.host, { error: err })
         // Don't break the process
         return callbackEach()
       }
 
       if (res.statusCode === 200) {
-        const podObj = new Pod({ url: pod.url, publicKey: body.cert })
+        const podObj = new Pod({ host: pod.host, publicKey: body.cert })
         podObj.save(function (err, podCreated) {
           if (err) {
-            logger.error('Cannot add friend %s pod.', pod.url, { error: err })
+            logger.error('Cannot add friend %s pod.', pod.host, { error: err })
             return callbackEach()
           }
 
@@ -243,7 +235,7 @@ function makeRequestsToWinningPods (cert, podsList, callback) {
           return callbackEach()
         })
       } else {
-        logger.error('Status not 200 for %s pod.', pod.url)
+        logger.error('Status not 200 for %s pod.', pod.host)
         return callbackEach()
       }
     })
@@ -257,8 +249,9 @@ function makeRequestsToWinningPods (cert, podsList, callback) {
   })
 }
 
-function createRequest (type, data, to) {
+function createRequest (type, endpoint, data, to) {
   const req = new Request({
+    endpoint,
     request: {
       type: type,
       data: data
@@ -273,3 +266,7 @@ function createRequest (type, data, to) {
     if (err) logger.error('Cannot save the request.', { error: err })
   })
 }
+
+function isMe (host) {
+  return host === constants.CONFIG.WEBSERVER.HOST
+}