]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/requests.ts
b31074373e2c9c449db2a20c475ff0846a6ee455
[github/Chocobozzz/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 { sign } from './peertube-crypto'
12
13 type MakeRetryRequestParams = {
14 url: string,
15 method: 'GET'|'POST',
16 json: Object
17 }
18 function makeRetryRequest (params: MakeRetryRequestParams) {
19 return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
20 replay(
21 request(params, (err, response, body) => err ? rej(err) : res({ response, body })),
22 {
23 retries: RETRY_REQUESTS,
24 factor: 3,
25 maxTimeout: Infinity,
26 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
27 }
28 )
29 })
30 }
31
32 type MakeSecureRequestParams = {
33 method: 'GET'|'POST'
34 toPod: PodInstance
35 path: string
36 sign: boolean
37 data?: Object
38 }
39 function makeSecureRequest (params: MakeSecureRequestParams) {
40 return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
41 const requestParams = {
42 url: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path,
43 json: {}
44 }
45
46 if (params.method !== 'POST') {
47 return rej(new Error('Cannot make a secure request with a non POST method.'))
48 }
49
50 // Add signature if it is specified in the params
51 if (params.sign === true) {
52 const host = CONFIG.WEBSERVER.HOST
53
54 let dataToSign
55 if (params.data) {
56 dataToSign = params.data
57 } else {
58 // We do not have data to sign so we just take our host
59 // It is not ideal but the connection should be in HTTPS
60 dataToSign = host
61 }
62
63 requestParams.json['signature'] = {
64 host, // Which host we pretend to be
65 signature: sign(dataToSign)
66 }
67 }
68
69 // If there are data informations
70 if (params.data) {
71 requestParams.json['data'] = params.data
72 }
73
74 request.post(requestParams, (err, response, body) => err ? rej(err) : res({ response, body }))
75 })
76 }
77
78 // ---------------------------------------------------------------------------
79
80 export {
81 makeRetryRequest,
82 makeSecureRequest
83 }