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
34 if (!bodyKBLimit) throw new Error('No KB limit for this request')
36 /* eslint-disable @typescript-eslint/no-floating-promises */
37 promiseOrStream.on('downloadProgress', progress => {
38 if (progress.transferred * 1000 > bodyKBLimit && progress.percent !== 1) {
39 promiseOrStream.cancel(`Exceeded the download limit of ${bodyKBLimit} bytes`)
43 return promiseOrStream
50 const headers = options.headers || {}
51 headers['host'] = options.url.host
55 const httpSignatureOptions = options.context?.httpSignature
57 if (httpSignatureOptions) {
58 const method = options.method ?? 'GET'
59 const path = options.path ?? options.url.pathname
61 if (!method || !path) {
62 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
65 httpSignature.signRequest({
66 getHeader: function (header) {
67 return options.headers[header]
70 setHeader: function (header, value) {
71 options.headers[header] = value
76 }, httpSignatureOptions)
83 function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
84 const gotOptions = buildGotOptions(options)
86 return peertubeGot(url, gotOptions)
87 .catch(err => { throw buildRequestError(err) })
90 function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
91 const gotOptions = buildGotOptions(options)
93 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
94 .catch(err => { throw buildRequestError(err) })
97 async function doRequestAndSaveToFile (
100 options: PeerTubeRequestOptions = {}
102 const gotOptions = buildGotOptions(options)
104 const outFile = createWriteStream(destPath)
107 await pipelinePromise(
108 peertubeGot.stream(url, gotOptions),
113 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
115 throw buildRequestError(err)
119 async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
120 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
121 await doRequestAndSaveToFile(url, tmpPath)
123 const destPath = join(destDir, destName)
126 await processImage(tmpPath, destPath, size)
128 await remove(tmpPath)
134 function getUserAgent () {
135 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
138 // ---------------------------------------------------------------------------
143 doRequestAndSaveToFile,
147 // ---------------------------------------------------------------------------
149 function buildGotOptions (options: PeerTubeRequestOptions) {
150 const { activityPub, bodyKBLimit = 1000 } = options
152 const context = { bodyKBLimit, httpSignature: options.httpSignature }
154 let headers = options.headers || {}
156 headers = { ...headers, date: new Date().toUTCString() }
159 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
163 method: options.method,
165 searchParams: options.searchParams,
171 function buildRequestError (error: any) {
172 const newError = new Error(error.message)
173 newError.name = error.name
174 newError.stack = error.stack
176 if (error.response?.body) {
177 error.responseBody = error.response.body