8c4c983f7ac0f61ddb4e9ea207f0f049e890e1a6
[oweals/peertube.git] / server / helpers / requests.ts
1 import * as replay from 'request-replay'
2 import * as request from 'request'
3 import * as Promise from 'bluebird'
4
5 import {
6   RETRY_REQUESTS,
7   REMOTE_SCHEME,
8   CONFIG
9 } from '../initializers'
10 import { PodInstance } from '../models'
11 import { PodSignature } from '../../shared'
12 import { signObject } from './peertube-crypto'
13
14 function doRequest (requestOptions: request.CoreOptions & request.UriOptions) {
15   return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
16     request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
17   })
18 }
19
20 type MakeRetryRequestParams = {
21   url: string,
22   method: 'GET' | 'POST',
23   json: Object
24 }
25 function makeRetryRequest (params: MakeRetryRequestParams) {
26   return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
27     replay(
28       request(params, (err, response, body) => err ? rej(err) : res({ response, body })),
29       {
30         retries: RETRY_REQUESTS,
31         factor: 3,
32         maxTimeout: Infinity,
33         errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
34       }
35     )
36   })
37 }
38
39 type MakeSecureRequestParams = {
40   toPod: PodInstance
41   path: string
42   data?: Object
43 }
44 function makeSecureRequest (params: MakeSecureRequestParams) {
45   const requestParams: {
46     method: 'POST',
47     uri: string,
48     json: {
49       signature: PodSignature,
50       data: any
51     }
52   } = {
53     method: 'POST',
54     uri: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path,
55     json: {
56       signature: null,
57       data: null
58     }
59   }
60
61   const host = CONFIG.WEBSERVER.HOST
62
63   let dataToSign
64   if (params.data) {
65     dataToSign = params.data
66   } else {
67     // We do not have data to sign so we just take our host
68     // It is not ideal but the connection should be in HTTPS
69     dataToSign = host
70   }
71
72   sign(dataToSign).then(signature => {
73     requestParams.json.signature = {
74       host, // Which host we pretend to be
75       signature
76     }
77
78     // If there are data information
79     if (params.data) {
80       requestParams.json.data = params.data
81     }
82
83     return doRequest(requestParams)
84   })
85 }
86
87 // ---------------------------------------------------------------------------
88
89 export {
90   doRequest,
91   makeRetryRequest,
92   makeSecureRequest
93 }