1 import { createWriteStream, remove } from 'fs-extra'
2 import got, { CancelableRequest, Options as GotOptions, RequestError } from 'got'
3 import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
4 import { join } from 'path'
5 import { CONFIG } from '../initializers/config'
6 import { ACTIVITY_PUB, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants'
7 import { pipelinePromise } from './core-utils'
8 import { processImage } from './image-utils'
9 import { logger } from './logger'
10 import { getProxy, isProxyEnabled } from './proxy'
12 const httpSignature = require('http-signature')
14 export interface PeerTubeRequestError extends Error {
19 type PeerTubeRequestOptions = {
21 bodyKBLimit?: number // 1MB
24 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`
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)
102 (options: GotOptions) => {
103 options.timeout = REQUEST_TIMEOUT
109 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
110 const gotOptions = buildGotOptions(options)
112 return peertubeGot(url, gotOptions)
113 .catch(err => { throw buildRequestError(err) })
116 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
117 const gotOptions = buildGotOptions(options)
119 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
120 .catch(err => { throw buildRequestError(err) })
123 async function doRequestAndSaveToFile (
126 options: PeerTubeRequestOptions = {}
128 const gotOptions = buildGotOptions(options)
130 const outFile = createWriteStream(destPath)
133 await pipelinePromise(
134 peertubeGot.stream(url, gotOptions),
139 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
141 throw buildRequestError(err)
145 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
146 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
147 await doRequestAndSaveToFile(url, tmpPath)
149 const destPath = join(destDir, destName)
152 await processImage(tmpPath, destPath, size)
154 await remove(tmpPath)
160 function getAgent () {
161 if (!isProxyEnabled()) return {}
163 const proxy = getProxy()
165 logger.info('Using proxy %s.', proxy)
167 const proxyAgentOptions = {
169 keepAliveMsecs: 1000,
172 scheduling: 'lifo' as 'lifo',
178 http: new HttpProxyAgent(proxyAgentOptions),
179 https: new HttpsProxyAgent(proxyAgentOptions)
184 function getUserAgent () {
185 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
188 // ---------------------------------------------------------------------------
193 doRequestAndSaveToFile,
197 // ---------------------------------------------------------------------------
199 function buildGotOptions (options: PeerTubeRequestOptions) {
200 const { activityPub, bodyKBLimit = 1000 } = options
202 const context = { bodyKBLimit, httpSignature: options.httpSignature }
204 let headers = options.headers || {}
207 headers = { ...headers, date: new Date().toUTCString() }
210 if (activityPub && !headers.accept) {
211 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
215 method: options.method,
218 searchParams: options.searchParams,
219 timeout: options.timeout ?? REQUEST_TIMEOUT,
225 function buildRequestError (error: RequestError) {
226 const newError: PeerTubeRequestError = new Error(error.message)
227 newError.name = error.name
228 newError.stack = error.stack
230 if (error.response) {
231 newError.responseBody = error.response.body
232 newError.statusCode = error.response.statusCode