1 import { createWriteStream, remove } from 'fs-extra'
2 import got, { CancelableRequest, NormalizedOptions, Options as GotOptions, RequestError, Response } from 'got'
3 import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
4 import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUTS, WEBSERVER } from '../initializers/constants'
5 import { pipelinePromise } from './core-utils'
6 import { logger, loggerTagsFactory } from './logger'
7 import { getProxy, isProxyEnabled } from './proxy'
9 const lTags = loggerTagsFactory('request')
11 const httpSignature = require('@peertube/http-signature')
13 export interface PeerTubeRequestError extends Error {
19 type PeerTubeRequestOptions = {
22 bodyKBLimit?: number // 1MB
25 authorizationHeaderName: string
30 jsonResponse?: boolean
31 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
33 const peertubeGot = got.extend({
37 'user-agent': getUserAgent()
42 const promiseOrStream = next(options) as CancelableRequest<any>
43 const bodyKBLimit = options.context?.bodyKBLimit as number
44 if (!bodyKBLimit) throw new Error('No KB limit for this request')
46 const bodyLimit = bodyKBLimit * 1000
48 /* eslint-disable @typescript-eslint/no-floating-promises */
49 promiseOrStream.on('downloadProgress', progress => {
50 if (progress.transferred > bodyLimit && progress.percent !== 1) {
51 const message = `Exceeded the download limit of ${bodyLimit} B`
52 logger.warn(message, lTags())
55 if (promiseOrStream.cancel) {
56 promiseOrStream.cancel()
61 (promiseOrStream as any).destroy()
65 return promiseOrStream
72 const headers = options.headers || {}
73 headers['host'] = options.url.host
77 const httpSignatureOptions = options.context?.httpSignature
79 if (httpSignatureOptions) {
80 const method = options.method ?? 'GET'
81 const path = options.path ?? options.url.pathname
83 if (!method || !path) {
84 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
87 httpSignature.signRequest({
88 getHeader: function (header) {
89 return options.headers[header]
92 setHeader: function (header, value) {
93 options.headers[header] = value
98 }, httpSignatureOptions)
104 (_options: NormalizedOptions, error: RequestError, retryCount: number) => {
105 logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() })
111 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
112 const gotOptions = buildGotOptions(options)
114 return peertubeGot(url, gotOptions)
115 .catch(err => { throw buildRequestError(err) })
118 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
119 const gotOptions = buildGotOptions(options)
121 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
122 .catch(err => { throw buildRequestError(err) })
125 async function doRequestAndSaveToFile (
128 options: PeerTubeRequestOptions = {}
130 const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE })
132 const outFile = createWriteStream(destPath)
135 await pipelinePromise(
136 peertubeGot.stream(url, gotOptions),
141 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
143 throw buildRequestError(err)
147 function getAgent () {
148 if (!isProxyEnabled()) return {}
150 const proxy = getProxy()
152 logger.info('Using proxy %s.', proxy, lTags())
154 const proxyAgentOptions = {
156 keepAliveMsecs: 1000,
159 scheduling: 'lifo' as 'lifo',
165 http: new HttpProxyAgent(proxyAgentOptions),
166 https: new HttpsProxyAgent(proxyAgentOptions)
171 function getUserAgent () {
172 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
175 function isBinaryResponse (result: Response<any>) {
176 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
179 async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
180 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
182 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
184 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
189 // ---------------------------------------------------------------------------
194 doRequestAndSaveToFile,
197 findLatestRedirection,
201 // ---------------------------------------------------------------------------
203 function buildGotOptions (options: PeerTubeRequestOptions) {
204 const { activityPub, bodyKBLimit = 1000 } = options
206 const context = { bodyKBLimit, httpSignature: options.httpSignature }
208 let headers = options.headers || {}
211 headers = { ...headers, date: new Date().toUTCString() }
214 if (activityPub && !headers.accept) {
215 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
219 method: options.method,
221 timeout: options.timeout ?? REQUEST_TIMEOUTS.DEFAULT,
223 searchParams: options.searchParams,
230 function buildRequestError (error: RequestError) {
231 const newError: PeerTubeRequestError = new Error(error.message)
232 newError.name = error.name
233 newError.stack = error.stack
235 if (error.response) {
236 newError.responseBody = error.response.body
237 newError.responseHeaders = error.response.headers
238 newError.statusCode = error.response.statusCode