]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/requests.ts
Add video privacy setting
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
CommitLineData
4d4e5cd4
C
1import * as replay from 'request-replay'
2import * as request from 'request'
6fcd19ba 3import * as Promise from 'bluebird'
dac0a531 4
65fcc311
C
5import {
6 RETRY_REQUESTS,
7 REMOTE_SCHEME,
8 CONFIG
9} from '../initializers'
69818c93 10import { PodInstance } from '../models'
4771e000 11import { PodSignature } from '../../shared'
65fcc311 12import { sign } from './peertube-crypto'
dac0a531 13
69818c93
C
14type MakeRetryRequestParams = {
15 url: string,
16 method: 'GET'|'POST',
17 json: Object
18}
6fcd19ba
C
19function 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 })
528a9efa 31}
dac0a531 32
69818c93
C
33type MakeSecureRequestParams = {
34 method: 'GET'|'POST'
35 toPod: PodInstance
36 path: string
69818c93
C
37 data?: Object
38}
6fcd19ba
C
39function makeSecureRequest (params: MakeSecureRequestParams) {
40 return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
4771e000
C
41 const requestParams: {
42 url: string,
43 json: {
44 signature: PodSignature,
45 data: any
46 }
47 } = {
6fcd19ba 48 url: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path,
4771e000
C
49 json: {
50 signature: null,
51 data: null
52 }
6fcd19ba 53 }
dac0a531 54
6fcd19ba
C
55 if (params.method !== 'POST') {
56 return rej(new Error('Cannot make a secure request with a non POST method.'))
57 }
bdfbd4f1 58
709756b8 59 const host = CONFIG.WEBSERVER.HOST
bdfbd4f1 60
709756b8
C
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 }
bdfbd4f1 69
709756b8 70 sign(dataToSign).then(signature => {
4771e000 71 requestParams.json.signature = {
6fcd19ba 72 host, // Which host we pretend to be
709756b8 73 signature
6fcd19ba 74 }
bdfbd4f1 75
f5028693 76 // If there are data information
709756b8 77 if (params.data) {
4771e000 78 requestParams.json.data = params.data
709756b8 79 }
bdfbd4f1 80
709756b8
C
81 request.post(requestParams, (err, response, body) => err ? rej(err) : res({ response, body }))
82 })
6fcd19ba 83 })
9f10b292 84}
dac0a531 85
9f10b292 86// ---------------------------------------------------------------------------
dac0a531 87
65fcc311
C
88export {
89 makeRetryRequest,
90 makeSecureRequest
91}