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