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