1 import { createWriteStream, remove } from 'fs-extra'
2 import got, { CancelableRequest, Options as GotOptions } from 'got'
3 import { join } from 'path'
4 import { CONFIG } from '../initializers/config'
5 import { ACTIVITY_PUB, PEERTUBE_VERSION, WEBSERVER } from '../initializers/constants'
6 import { pipelinePromise } from './core-utils'
7 import { processImage } from './image-utils'
8 import { logger } from './logger'
10 const httpSignature = require('http-signature')
12 type PeerTubeRequestOptions = {
14 bodyKBLimit?: number // 1MB
17 authorizationHeaderName: string
22 jsonResponse?: boolean
23 } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
25 const peertubeGot = got.extend({
27 'user-agent': getUserAgent()
32 const promiseOrStream = next(options) as CancelableRequest<any>
33 const bodyKBLimit = options.context?.bodyKBLimit as number
34 if (!bodyKBLimit) throw new Error('No KB limit for this request')
36 const bodyLimit = bodyKBLimit * 1000
38 /* eslint-disable @typescript-eslint/no-floating-promises */
39 promiseOrStream.on('downloadProgress', progress => {
40 if (progress.transferred > bodyLimit && progress.percent !== 1) {
41 const message = `Exceeded the download limit of ${bodyLimit} B`
45 if (promiseOrStream.cancel) {
46 promiseOrStream.cancel()
51 (promiseOrStream as any).destroy()
55 return promiseOrStream
62 const headers = options.headers || {}
63 headers['host'] = options.url.host
67 const httpSignatureOptions = options.context?.httpSignature
69 if (httpSignatureOptions) {
70 const method = options.method ?? 'GET'
71 const path = options.path ?? options.url.pathname
73 if (!method || !path) {
74 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
77 httpSignature.signRequest({
78 getHeader: function (header) {
79 return options.headers[header]
82 setHeader: function (header, value) {
83 options.headers[header] = value
88 }, httpSignatureOptions)
95 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
96 const gotOptions = buildGotOptions(options)
98 return peertubeGot(url, gotOptions)
99 .catch(err => { throw buildRequestError(err) })
102 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
103 const gotOptions = buildGotOptions(options)
105 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
106 .catch(err => { throw buildRequestError(err) })
109 async function doRequestAndSaveToFile (
112 options: PeerTubeRequestOptions = {}
114 const gotOptions = buildGotOptions(options)
116 const outFile = createWriteStream(destPath)
119 await pipelinePromise(
120 peertubeGot.stream(url, gotOptions),
125 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
127 throw buildRequestError(err)
131 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
132 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
133 await doRequestAndSaveToFile(url, tmpPath)
135 const destPath = join(destDir, destName)
138 await processImage(tmpPath, destPath, size)
140 await remove(tmpPath)
146 function getUserAgent () {
147 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
150 // ---------------------------------------------------------------------------
155 doRequestAndSaveToFile,
159 // ---------------------------------------------------------------------------
161 function buildGotOptions (options: PeerTubeRequestOptions) {
162 const { activityPub, bodyKBLimit = 1000 } = options
164 const context = { bodyKBLimit, httpSignature: options.httpSignature }
166 let headers = options.headers || {}
168 headers = { ...headers, date: new Date().toUTCString() }
171 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
175 method: options.method,
177 searchParams: options.searchParams,
183 function buildRequestError (error: any) {
184 const newError = new Error(error.message)
185 newError.name = error.name
186 newError.stack = error.stack
188 if (error.response?.body) {
189 error.responseBody = error.response.body