1 import { createWriteStream, remove } from 'fs-extra'
2 import got, { CancelableRequest, 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 {
21 type PeerTubeRequestOptions = {
23 bodyKBLimit?: number // 1MB
26 authorizationHeaderName: string
31 jsonResponse?: boolean
32 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
34 const peertubeGot = got.extend({
38 'user-agent': getUserAgent()
43 const promiseOrStream = next(options) as CancelableRequest<any>
44 const bodyKBLimit = options.context?.bodyKBLimit as number
45 if (!bodyKBLimit) throw new Error('No KB limit for this request')
47 const bodyLimit = bodyKBLimit * 1000
49 /* eslint-disable @typescript-eslint/no-floating-promises */
50 promiseOrStream.on('downloadProgress', progress => {
51 if (progress.transferred > bodyLimit && progress.percent !== 1) {
52 const message = `Exceeded the download limit of ${bodyLimit} B`
53 logger.warn(message, lTags())
56 if (promiseOrStream.cancel) {
57 promiseOrStream.cancel()
62 (promiseOrStream as any).destroy()
66 return promiseOrStream
73 const headers = options.headers || {}
74 headers['host'] = options.url.host
78 const httpSignatureOptions = options.context?.httpSignature
80 if (httpSignatureOptions) {
81 const method = options.method ?? 'GET'
82 const path = options.path ?? options.url.pathname
84 if (!method || !path) {
85 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
88 httpSignature.signRequest({
89 getHeader: function (header) {
90 return options.headers[header]
93 setHeader: function (header, value) {
94 options.headers[header] = value
99 }, httpSignatureOptions)
106 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
107 const gotOptions = buildGotOptions(options)
109 return peertubeGot(url, gotOptions)
110 .on('retry', logRetryFactory(url))
111 .catch(err => { throw buildRequestError(err) })
114 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
115 const gotOptions = buildGotOptions(options)
117 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
118 .on('retry', logRetryFactory(url))
119 .catch(err => { throw buildRequestError(err) })
122 async function doRequestAndSaveToFile (
125 options: PeerTubeRequestOptions = {}
127 const gotOptions = buildGotOptions(options)
129 const outFile = createWriteStream(destPath)
132 await pipelinePromise(
133 peertubeGot.stream(url, gotOptions),
138 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
140 throw buildRequestError(err)
144 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
145 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
146 await doRequestAndSaveToFile(url, tmpPath)
148 const destPath = join(destDir, destName)
151 await processImage(tmpPath, destPath, size)
153 await remove(tmpPath)
159 function getAgent () {
160 if (!isProxyEnabled()) return {}
162 const proxy = getProxy()
164 logger.info('Using proxy %s.', proxy, lTags())
166 const proxyAgentOptions = {
168 keepAliveMsecs: 1000,
171 scheduling: 'lifo' as 'lifo',
177 http: new HttpProxyAgent(proxyAgentOptions),
178 https: new HttpsProxyAgent(proxyAgentOptions)
183 function getUserAgent () {
184 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
187 function isBinaryResponse (result: Response<any>) {
188 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
191 async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
192 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
194 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
196 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
201 // ---------------------------------------------------------------------------
206 doRequestAndSaveToFile,
209 findLatestRedirection,
213 // ---------------------------------------------------------------------------
215 function buildGotOptions (options: PeerTubeRequestOptions) {
216 const { activityPub, bodyKBLimit = 1000 } = options
218 const context = { bodyKBLimit, httpSignature: options.httpSignature }
220 let headers = options.headers || {}
223 headers = { ...headers, date: new Date().toUTCString() }
226 if (activityPub && !headers.accept) {
227 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
231 method: options.method,
233 timeout: REQUEST_TIMEOUT,
235 searchParams: options.searchParams,
242 function buildRequestError (error: RequestError) {
243 const newError: PeerTubeRequestError = new Error(error.message)
244 newError.name = error.name
245 newError.stack = error.stack
247 if (error.response) {
248 newError.responseBody = error.response.body
249 newError.statusCode = error.response.statusCode
255 function logRetryFactory (url: string) {
256 return (retryCount: number, error: RequestError) => {
257 logger.debug('Retrying request to %s.', url, { retryCount, error, ...lTags() })