-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))
- })
+function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
+ const gotOptions = buildGotOptions(options)
+
+ return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
+ .catch(err => { throw buildRequestError(err) })
+}
+
+async function doRequestAndSaveToFile (
+ url: string,
+ destPath: string,
+ options: PeerTubeRequestOptions = {}
+) {
+ const gotOptions = buildGotOptions(options)
+
+ 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 }))
+
+ throw buildRequestError(err)
+ }
+}
+
+async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
+ const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
+ await doRequestAndSaveToFile(url, tmpPath)
+
+ const destPath = join(destDir, destName)
+
+ try {
+ await processImage(tmpPath, destPath, size)
+ } catch (err) {
+ await remove(tmpPath)
+
+ throw err
+ }
+}
+
+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})`