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 { join } from 'path'
5 import { CONFIG } from '../initializers/config'
6 import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUTS, WEBSERVER } from '../initializers/constants'
7 import { pipelinePromise } from './core-utils'
8 import { processImage } from './image-utils'
9 import { logger, loggerTagsFactory } from './logger'
10 import { getProxy, isProxyEnabled } from './proxy'
12 const lTags = loggerTagsFactory('request')
14 const httpSignature = require('@peertube/http-signature')
16 export interface PeerTubeRequestError extends Error {
22 type PeerTubeRequestOptions = {
25 bodyKBLimit?: number // 1MB
28 authorizationHeaderName: string
33 jsonResponse?: boolean
34 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
36 const peertubeGot = got.extend({
40 'user-agent': getUserAgent()
45 const promiseOrStream = next(options) as CancelableRequest<any>
46 const bodyKBLimit = options.context?.bodyKBLimit as number
47 if (!bodyKBLimit) throw new Error('No KB limit for this request')
49 const bodyLimit = bodyKBLimit * 1000
51 /* eslint-disable @typescript-eslint/no-floating-promises */
52 promiseOrStream.on('downloadProgress', progress => {
53 if (progress.transferred > bodyLimit && progress.percent !== 1) {
54 const message = `Exceeded the download limit of ${bodyLimit} B`
55 logger.warn(message, lTags())
58 if (promiseOrStream.cancel) {
59 promiseOrStream.cancel()
64 (promiseOrStream as any).destroy()
68 return promiseOrStream
75 const headers = options.headers || {}
76 headers['host'] = options.url.host
80 const httpSignatureOptions = options.context?.httpSignature
82 if (httpSignatureOptions) {
83 const method = options.method ?? 'GET'
84 const path = options.path ?? options.url.pathname
86 if (!method || !path) {
87 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
90 httpSignature.signRequest({
91 getHeader: function (header) {
92 return options.headers[header]
95 setHeader: function (header, value) {
96 options.headers[header] = value
101 }, httpSignatureOptions)
107 (_options: NormalizedOptions, error: RequestError, retryCount: number) => {
108 logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() })
114 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
115 const gotOptions = buildGotOptions(options)
117 return peertubeGot(url, gotOptions)
118 .catch(err => { throw buildRequestError(err) })
121 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
122 const gotOptions = buildGotOptions(options)
124 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
125 .catch(err => { throw buildRequestError(err) })
128 async function doRequestAndSaveToFile (
131 options: PeerTubeRequestOptions = {}
133 const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE })
135 const outFile = createWriteStream(destPath)
138 await pipelinePromise(
139 peertubeGot.stream(url, gotOptions),
144 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
146 throw buildRequestError(err)
150 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
151 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
152 await doRequestAndSaveToFile(url, tmpPath)
154 const destPath = join(destDir, destName)
157 await processImage(tmpPath, destPath, size)
159 await remove(tmpPath)
165 function getAgent () {
166 if (!isProxyEnabled()) return {}
168 const proxy = getProxy()
170 logger.info('Using proxy %s.', proxy, lTags())
172 const proxyAgentOptions = {
174 keepAliveMsecs: 1000,
177 scheduling: 'lifo' as 'lifo',
183 http: new HttpProxyAgent(proxyAgentOptions),
184 https: new HttpsProxyAgent(proxyAgentOptions)
189 function getUserAgent () {
190 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
193 function isBinaryResponse (result: Response<any>) {
194 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
197 async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
198 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
200 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
202 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
207 // ---------------------------------------------------------------------------
212 doRequestAndSaveToFile,
215 findLatestRedirection,
219 // ---------------------------------------------------------------------------
221 function buildGotOptions (options: PeerTubeRequestOptions) {
222 const { activityPub, bodyKBLimit = 1000 } = options
224 const context = { bodyKBLimit, httpSignature: options.httpSignature }
226 let headers = options.headers || {}
229 headers = { ...headers, date: new Date().toUTCString() }
232 if (activityPub && !headers.accept) {
233 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
237 method: options.method,
239 timeout: options.timeout ?? REQUEST_TIMEOUTS.DEFAULT,
241 searchParams: options.searchParams,
248 function buildRequestError (error: RequestError) {
249 const newError: PeerTubeRequestError = new Error(error.message)
250 newError.name = error.name
251 newError.stack = error.stack
253 if (error.response) {
254 newError.responseBody = error.response.body
255 newError.responseHeaders = error.response.headers
256 newError.statusCode = error.response.statusCode