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_TIMEOUT, 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 = {
24 bodyKBLimit?: number // 1MB
27 authorizationHeaderName: string
32 jsonResponse?: boolean
33 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
35 const peertubeGot = got.extend({
39 'user-agent': getUserAgent()
44 const promiseOrStream = next(options) as CancelableRequest<any>
45 const bodyKBLimit = options.context?.bodyKBLimit as number
46 if (!bodyKBLimit) throw new Error('No KB limit for this request')
48 const bodyLimit = bodyKBLimit * 1000
50 /* eslint-disable @typescript-eslint/no-floating-promises */
51 promiseOrStream.on('downloadProgress', progress => {
52 if (progress.transferred > bodyLimit && progress.percent !== 1) {
53 const message = `Exceeded the download limit of ${bodyLimit} B`
54 logger.warn(message, lTags())
57 if (promiseOrStream.cancel) {
58 promiseOrStream.cancel()
63 (promiseOrStream as any).destroy()
67 return promiseOrStream
74 const headers = options.headers || {}
75 headers['host'] = options.url.host
79 const httpSignatureOptions = options.context?.httpSignature
81 if (httpSignatureOptions) {
82 const method = options.method ?? 'GET'
83 const path = options.path ?? options.url.pathname
85 if (!method || !path) {
86 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
89 httpSignature.signRequest({
90 getHeader: function (header) {
91 return options.headers[header]
94 setHeader: function (header, value) {
95 options.headers[header] = value
100 }, httpSignatureOptions)
106 (_options: NormalizedOptions, error: RequestError, retryCount: number) => {
107 logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() })
113 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
114 const gotOptions = buildGotOptions(options)
116 return peertubeGot(url, gotOptions)
117 .catch(err => { throw buildRequestError(err) })
120 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
121 const gotOptions = buildGotOptions(options)
123 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
124 .catch(err => { throw buildRequestError(err) })
127 async function doRequestAndSaveToFile (
130 options: PeerTubeRequestOptions = {}
132 const gotOptions = buildGotOptions(options)
134 const outFile = createWriteStream(destPath)
137 await pipelinePromise(
138 peertubeGot.stream(url, gotOptions),
143 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
145 throw buildRequestError(err)
149 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
150 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
151 await doRequestAndSaveToFile(url, tmpPath)
153 const destPath = join(destDir, destName)
156 await processImage(tmpPath, destPath, size)
158 await remove(tmpPath)
164 function getAgent () {
165 if (!isProxyEnabled()) return {}
167 const proxy = getProxy()
169 logger.info('Using proxy %s.', proxy, lTags())
171 const proxyAgentOptions = {
173 keepAliveMsecs: 1000,
176 scheduling: 'lifo' as 'lifo',
182 http: new HttpProxyAgent(proxyAgentOptions),
183 https: new HttpsProxyAgent(proxyAgentOptions)
188 function getUserAgent () {
189 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
192 function isBinaryResponse (result: Response<any>) {
193 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
196 async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
197 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
199 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
201 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
206 // ---------------------------------------------------------------------------
211 doRequestAndSaveToFile,
214 findLatestRedirection,
218 // ---------------------------------------------------------------------------
220 function buildGotOptions (options: PeerTubeRequestOptions) {
221 const { activityPub, bodyKBLimit = 1000 } = options
223 const context = { bodyKBLimit, httpSignature: options.httpSignature }
225 let headers = options.headers || {}
228 headers = { ...headers, date: new Date().toUTCString() }
231 if (activityPub && !headers.accept) {
232 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
236 method: options.method,
238 timeout: REQUEST_TIMEOUT,
240 searchParams: options.searchParams,
247 function buildRequestError (error: RequestError) {
248 const newError: PeerTubeRequestError = new Error(error.message)
249 newError.name = error.name
250 newError.stack = error.stack
252 if (error.response) {
253 newError.responseBody = error.response.body
254 newError.responseHeaders = error.response.headers
255 newError.statusCode = error.response.statusCode