Server: add config endpoint
[oweals/peertube.git] / server / helpers / requests.js
1 'use strict'
2
3 const replay = require('request-replay')
4 const request = require('request')
5
6 const constants = require('../initializers/constants')
7 const peertubeCrypto = require('./peertube-crypto')
8
9 const requests = {
10   makeRetryRequest,
11   makeSecureRequest
12 }
13
14 function makeRetryRequest (params, callback) {
15   replay(
16     request(params, callback),
17     {
18       retries: constants.RETRY_REQUESTS,
19       factor: 3,
20       maxTimeout: Infinity,
21       errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
22     }
23   )
24 }
25
26 function makeSecureRequest (params, callback) {
27   const requestParams = {
28     url: constants.REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path
29   }
30
31   if (params.method !== 'POST') {
32     return callback(new Error('Cannot make a secure request with a non POST method.'))
33   }
34
35   requestParams.json = {}
36
37   // Add signature if it is specified in the params
38   if (params.sign === true) {
39     const host = constants.CONFIG.WEBSERVER.HOST
40
41     let dataToSign
42     if (params.data) {
43       dataToSign = dataToSign = params.data
44     } else {
45       // We do not have data to sign so we just take our host
46       // It is not ideal but the connection should be in HTTPS
47       dataToSign = host
48     }
49
50     requestParams.json.signature = {
51       host, // Which host we pretend to be
52       signature: peertubeCrypto.sign(dataToSign)
53     }
54   }
55
56   // If there are data informations
57   if (params.data) {
58     requestParams.json.data = params.data
59   }
60
61   console.log(requestParams.json.data)
62
63   request.post(requestParams, callback)
64 }
65
66 // ---------------------------------------------------------------------------
67
68 module.exports = requests