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
29 jsonResponse?: boolean
30 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
32 const peertubeGot = got.extend({
36 'user-agent': getUserAgent()
41 const promiseOrStream = next(options) as CancelableRequest<any>
42 const bodyKBLimit = options.context?.bodyKBLimit as number
43 if (!bodyKBLimit) throw new Error('No KB limit for this request')
45 const bodyLimit = bodyKBLimit * 1000
47 /* eslint-disable @typescript-eslint/no-floating-promises */
48 promiseOrStream.on('downloadProgress', progress => {
49 if (progress.transferred > bodyLimit && progress.percent !== 1) {
50 const message = `Exceeded the download limit of ${bodyLimit} B`
54 if (promiseOrStream.cancel) {
55 promiseOrStream.cancel()
60 (promiseOrStream as any).destroy()
64 return promiseOrStream
71 const headers = options.headers || {}
72 headers['host'] = options.url.host
76 const httpSignatureOptions = options.context?.httpSignature
78 if (httpSignatureOptions) {
79 const method = options.method ?? 'GET'
80 const path = options.path ?? options.url.pathname
82 if (!method || !path) {
83 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
86 httpSignature.signRequest({
87 getHeader: function (header) {
88 return options.headers[header]
91 setHeader: function (header, value) {
92 options.headers[header] = value
97 }, httpSignatureOptions)
101 (options: GotOptions) => {
102 options.timeout = REQUEST_TIMEOUT
108 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
109 const gotOptions = buildGotOptions(options)
111 return peertubeGot(url, gotOptions)
112 .catch(err => { throw buildRequestError(err) })
115 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
116 const gotOptions = buildGotOptions(options)
118 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
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 }))
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)
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 // ---------------------------------------------------------------------------
192 doRequestAndSaveToFile,
196 // ---------------------------------------------------------------------------
198 function buildGotOptions (options: PeerTubeRequestOptions) {
199 const { activityPub, bodyKBLimit = 1000 } = options
201 const context = { bodyKBLimit, httpSignature: options.httpSignature }
203 let headers = options.headers || {}
206 headers = { ...headers, date: new Date().toUTCString() }
209 if (activityPub && !headers.accept) {
210 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
214 method: options.method,
217 searchParams: options.searchParams,
223 function buildRequestError (error: RequestError) {
224 const newError: PeerTubeRequestError = new Error(error.message)
225 newError.name = error.name
226 newError.stack = error.stack
228 if (error.response) {
229 newError.responseBody = error.response.body
230 newError.statusCode = error.response.statusCode