+const lTags = loggerTagsFactory('request')
+
+const httpSignature = require('@peertube/http-signature')
+
+export interface PeerTubeRequestError extends Error {
+ statusCode?: number
+ responseBody?: any
+}
+
+type PeerTubeRequestOptions = {
+ activityPub?: boolean
+ bodyKBLimit?: number // 1MB
+ httpSignature?: {
+ algorithm: string
+ authorizationHeaderName: string
+ keyId: string
+ key: string
+ headers: string[]
+ }
+ jsonResponse?: boolean
+} & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
+
+const peertubeGot = got.extend({
+ ...getAgent(),
+
+ headers: {
+ 'user-agent': getUserAgent()
+ },
+
+ handlers: [
+ (options, next) => {
+ const promiseOrStream = next(options) as CancelableRequest<any>
+ const bodyKBLimit = options.context?.bodyKBLimit as number
+ if (!bodyKBLimit) throw new Error('No KB limit for this request')
+
+ const bodyLimit = bodyKBLimit * 1000
+
+ /* eslint-disable @typescript-eslint/no-floating-promises */
+ promiseOrStream.on('downloadProgress', progress => {
+ if (progress.transferred > bodyLimit && progress.percent !== 1) {
+ const message = `Exceeded the download limit of ${bodyLimit} B`
+ logger.warn(message, lTags())
+
+ // CancelableRequest
+ if (promiseOrStream.cancel) {
+ promiseOrStream.cancel()
+ return
+ }
+
+ // Stream
+ (promiseOrStream as any).destroy()
+ }
+ })
+
+ return promiseOrStream
+ }
+ ],
+
+ hooks: {
+ beforeRequest: [
+ options => {
+ const headers = options.headers || {}
+ headers['host'] = options.url.host
+ },
+
+ options => {
+ const httpSignatureOptions = options.context?.httpSignature
+
+ if (httpSignatureOptions) {
+ const method = options.method ?? 'GET'
+ const path = options.path ?? options.url.pathname
+
+ if (!method || !path) {
+ throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
+ }
+
+ httpSignature.signRequest({
+ getHeader: function (header) {
+ return options.headers[header]
+ },
+
+ setHeader: function (header, value) {
+ options.headers[header] = value
+ },
+
+ method,
+ path
+ }, httpSignatureOptions)
+ }
+ }
+ ]
+ }
+})
+
+function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
+ const gotOptions = buildGotOptions(options)
+
+ return peertubeGot(url, gotOptions)
+ .on('retry', logRetryFactory(url))
+ .catch(err => { throw buildRequestError(err) })
+}
+
+function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
+ const gotOptions = buildGotOptions(options)
+
+ return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
+ .on('retry', logRetryFactory(url))
+ .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, ...lTags() }))
+
+ 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, 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)
+ }