-function doRequestAndSaveToFile (requestOptions: request.CoreOptions & request.UriOptions, destPath: string) {
- return new Promise<request.RequestResponse>((res, rej) => {
- request(requestOptions)
- .on('response', response => res(response as request.RequestResponse))
- .on('error', err => rej(err))
- .pipe(createWriteStream(destPath))
- })
+async function doRequestAndSaveToFile (
+ url: string,
+ destPath: string,
+ options: PeerTubeRequestOptions = {}
+) {
+ const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE })
+
+ const outFile = createWriteStream(destPath)
+
+ try {
+ await pipelinePromise(
+ peertubeGot.stream(url, gotOptions),
+ outFile
+ )
+ } catch (err) {
+ remove(destPath)
+ .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
+
+ throw buildRequestError(err)
+ }
+}
+
+function getAgent () {
+ if (!isProxyEnabled()) return {}
+
+ const proxy = getProxy()
+
+ logger.info('Using proxy %s.', proxy, lTags())
+
+ 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})`
+}
+
+function isBinaryResponse (result: Response<any>) {
+ return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
+}
+
+async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
+ if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
+
+ const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
+
+ if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
+
+ return url