]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/requests.ts
Prepare 3.4 changelog
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
CommitLineData
bfe2ef6b 1import { createWriteStream, remove } from 'fs-extra'
b5c36108 2import got, { CancelableRequest, Options as GotOptions, RequestError } from 'got'
8729a870 3import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
db4b15f2
C
4import { join } from 'path'
5import { CONFIG } from '../initializers/config'
7500d6c9 6import { ACTIVITY_PUB, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants'
db4b15f2 7import { pipelinePromise } from './core-utils'
58d515e3 8import { processImage } from './image-utils'
bfe2ef6b 9import { logger } from './logger'
8729a870 10import { getProxy, isProxyEnabled } from './proxy'
11
12const httpSignature = require('http-signature')
da854ddd 13
b5c36108
C
14export interface PeerTubeRequestError extends Error {
15 statusCode?: number
16 responseBody?: any
17}
18
db4b15f2
C
19type PeerTubeRequestOptions = {
20 activityPub?: boolean
21 bodyKBLimit?: number // 1MB
22 httpSignature?: {
23 algorithm: string
24 authorizationHeaderName: string
25 keyId: string
26 key: string
27 headers: string[]
28 }
29 jsonResponse?: boolean
30} & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
31
32const peertubeGot = got.extend({
8729a870 33 ...getAgent(),
34
db4b15f2
C
35 headers: {
36 'user-agent': getUserAgent()
37 },
38
39 handlers: [
40 (options, next) => {
41 const promiseOrStream = next(options) as CancelableRequest<any>
b329abc2 42 const bodyKBLimit = options.context?.bodyKBLimit as number
db4b15f2
C
43 if (!bodyKBLimit) throw new Error('No KB limit for this request')
44
b329abc2
C
45 const bodyLimit = bodyKBLimit * 1000
46
db4b15f2
C
47 /* eslint-disable @typescript-eslint/no-floating-promises */
48 promiseOrStream.on('downloadProgress', progress => {
b329abc2
C
49 if (progress.transferred > bodyLimit && progress.percent !== 1) {
50 const message = `Exceeded the download limit of ${bodyLimit} B`
51 logger.warn(message)
52
53 // CancelableRequest
54 if (promiseOrStream.cancel) {
55 promiseOrStream.cancel()
56 return
57 }
58
59 // Stream
60 (promiseOrStream as any).destroy()
db4b15f2
C
61 }
62 })
e0ce715a 63
db4b15f2
C
64 return promiseOrStream
65 }
66 ],
67
68 hooks: {
69 beforeRequest: [
70 options => {
71 const headers = options.headers || {}
72 headers['host'] = options.url.host
73 },
74
75 options => {
76 const httpSignatureOptions = options.context?.httpSignature
77
78 if (httpSignatureOptions) {
79 const method = options.method ?? 'GET'
80 const path = options.path ?? options.url.pathname
81
82 if (!method || !path) {
83 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
84 }
85
86 httpSignature.signRequest({
87 getHeader: function (header) {
88 return options.headers[header]
89 },
90
91 setHeader: function (header, value) {
92 options.headers[header] = value
93 },
94
95 method,
96 path
97 }, httpSignatureOptions)
98 }
7500d6c9
C
99 },
100
101 (options: GotOptions) => {
102 options.timeout = REQUEST_TIMEOUT
db4b15f2
C
103 }
104 ]
da854ddd 105 }
db4b15f2 106})
e4f97bab 107
db4b15f2
C
108function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
109 const gotOptions = buildGotOptions(options)
110
111 return peertubeGot(url, gotOptions)
112 .catch(err => { throw buildRequestError(err) })
113}
114
115function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
116 const gotOptions = buildGotOptions(options)
117
118 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
119 .catch(err => { throw buildRequestError(err) })
e4f97bab 120}
dac0a531 121
db4b15f2
C
122async function doRequestAndSaveToFile (
123 url: string,
bfe2ef6b 124 destPath: string,
db4b15f2 125 options: PeerTubeRequestOptions = {}
bfe2ef6b 126) {
db4b15f2 127 const gotOptions = buildGotOptions(options)
02988fdc 128
db4b15f2 129 const outFile = createWriteStream(destPath)
bfe2ef6b 130
db4b15f2
C
131 try {
132 await pipelinePromise(
133 peertubeGot.stream(url, gotOptions),
134 outFile
135 )
136 } catch (err) {
137 remove(destPath)
138 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err }))
bfe2ef6b 139
db4b15f2
C
140 throw buildRequestError(err)
141 }
0d0e8dd0
C
142}
143
6040f87d
C
144async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) {
145 const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName)
db4b15f2 146 await doRequestAndSaveToFile(url, tmpPath)
58d515e3 147
6040f87d 148 const destPath = join(destDir, destName)
4ee7a4c9
C
149
150 try {
2fb5b3a5 151 await processImage(tmpPath, destPath, size)
4ee7a4c9
C
152 } catch (err) {
153 await remove(tmpPath)
154
155 throw err
156 }
58d515e3
C
157}
158
8729a870 159function getAgent () {
160 if (!isProxyEnabled()) return {}
161
162 const proxy = getProxy()
163
164 logger.info('Using proxy %s.', proxy)
165
166 const proxyAgentOptions = {
167 keepAlive: true,
168 keepAliveMsecs: 1000,
169 maxSockets: 256,
170 maxFreeSockets: 256,
171 scheduling: 'lifo' as 'lifo',
172 proxy
173 }
174
175 return {
176 agent: {
177 http: new HttpProxyAgent(proxyAgentOptions),
178 https: new HttpsProxyAgent(proxyAgentOptions)
179 }
180 }
181}
182
e0ce715a 183function getUserAgent () {
66170ca8 184 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
e0ce715a
C
185}
186
9f10b292 187// ---------------------------------------------------------------------------
dac0a531 188
65fcc311 189export {
e4f97bab 190 doRequest,
db4b15f2 191 doJSONRequest,
58d515e3
C
192 doRequestAndSaveToFile,
193 downloadImage
65fcc311 194}
bfe2ef6b
C
195
196// ---------------------------------------------------------------------------
197
db4b15f2
C
198function buildGotOptions (options: PeerTubeRequestOptions) {
199 const { activityPub, bodyKBLimit = 1000 } = options
bfe2ef6b 200
db4b15f2 201 const context = { bodyKBLimit, httpSignature: options.httpSignature }
bfe2ef6b 202
db4b15f2
C
203 let headers = options.headers || {}
204
e7053b1d
C
205 if (!headers.date) {
206 headers = { ...headers, date: new Date().toUTCString() }
207 }
db4b15f2 208
e7053b1d 209 if (activityPub && !headers.accept) {
db4b15f2 210 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
bfe2ef6b 211 }
db4b15f2
C
212
213 return {
214 method: options.method,
bbb3be68 215 dnsCache: true,
db4b15f2
C
216 json: options.json,
217 searchParams: options.searchParams,
218 headers,
219 context
220 }
221}
222
b5c36108
C
223function buildRequestError (error: RequestError) {
224 const newError: PeerTubeRequestError = new Error(error.message)
db4b15f2
C
225 newError.name = error.name
226 newError.stack = error.stack
227
b5c36108
C
228 if (error.response) {
229 newError.responseBody = error.response.body
230 newError.statusCode = error.response.statusCode
db4b15f2
C
231 }
232
b5c36108 233 return newError
bfe2ef6b 234}