]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/helpers/requests.ts
Support proxies for PeerTube (#4346)
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
index 36e69458e533064a584e93a061d6361b57dc4db6..e09e230863d25f6eef7da65803916a1a86f9a2c6 100644 (file)
@@ -1,19 +1,21 @@
 import { createWriteStream, remove } from 'fs-extra'
 import got, { CancelableRequest, Options as GotOptions, RequestError } from 'got'
+import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
 import { join } from 'path'
 import { CONFIG } from '../initializers/config'
 import { ACTIVITY_PUB, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants'
 import { pipelinePromise } from './core-utils'
 import { processImage } from './image-utils'
 import { logger } from './logger'
+import { getProxy, isProxyEnabled } from './proxy'
+
+const httpSignature = require('http-signature')
 
 export interface PeerTubeRequestError extends Error {
   statusCode?: number
   responseBody?: any
 }
 
-const httpSignature = require('http-signature')
-
 type PeerTubeRequestOptions = {
   activityPub?: boolean
   bodyKBLimit?: number // 1MB
@@ -29,6 +31,8 @@ type PeerTubeRequestOptions = {
 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
 
 const peertubeGot = got.extend({
+  ...getAgent(),
+
   headers: {
     'user-agent': getUserAgent()
   },
@@ -153,6 +157,30 @@ async function downloadImage (url: string, destDir: string, destName: string, si
   }
 }
 
+function getAgent () {
+  if (!isProxyEnabled()) return {}
+
+  const proxy = getProxy()
+
+  logger.info('Using proxy %s.', proxy)
+
+  const proxyAgentOptions = {
+    keepAlive: true,
+    keepAliveMsecs: 1000,
+    maxSockets: 256,
+    maxFreeSockets: 256,
+    scheduling: 'lifo' as 'lifo',
+    proxy
+  }
+
+  return {
+    agent: {
+      http: new HttpProxyAgent(proxyAgentOptions),
+      https: new HttpsProxyAgent(proxyAgentOptions)
+    }
+  }
+}
+
 function getUserAgent () {
   return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
 }