]>
Commit | Line | Data |
---|---|---|
bfe2ef6b | 1 | import { createWriteStream, remove } from 'fs-extra' |
62549e6c | 2 | import got, { CancelableRequest, Options as GotOptions, RequestError, Response } from 'got' |
8729a870 | 3 | import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' |
db4b15f2 C |
4 | import { join } from 'path' |
5 | import { CONFIG } from '../initializers/config' | |
62549e6c | 6 | import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants' |
db4b15f2 | 7 | import { pipelinePromise } from './core-utils' |
58d515e3 | 8 | import { processImage } from './image-utils' |
bfe2ef6b | 9 | import { logger } from './logger' |
8729a870 | 10 | import { getProxy, isProxyEnabled } from './proxy' |
11 | ||
5842a854 | 12 | const httpSignature = require('@peertube/http-signature') |
da854ddd | 13 | |
b5c36108 C |
14 | export interface PeerTubeRequestError extends Error { |
15 | statusCode?: number | |
16 | responseBody?: any | |
17 | } | |
18 | ||
db4b15f2 C |
19 | type 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 | ||
32 | const 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 | } | |
99 | } | |
100 | ] | |
da854ddd | 101 | } |
db4b15f2 | 102 | }) |
e4f97bab | 103 | |
db4b15f2 C |
104 | function doRequest (url: string, options: PeerTubeRequestOptions = {}) { |
105 | const gotOptions = buildGotOptions(options) | |
106 | ||
107 | return peertubeGot(url, gotOptions) | |
108 | .catch(err => { throw buildRequestError(err) }) | |
109 | } | |
110 | ||
111 | function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) { | |
112 | const gotOptions = buildGotOptions(options) | |
113 | ||
114 | return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' }) | |
115 | .catch(err => { throw buildRequestError(err) }) | |
e4f97bab | 116 | } |
dac0a531 | 117 | |
db4b15f2 C |
118 | async function doRequestAndSaveToFile ( |
119 | url: string, | |
bfe2ef6b | 120 | destPath: string, |
db4b15f2 | 121 | options: PeerTubeRequestOptions = {} |
bfe2ef6b | 122 | ) { |
db4b15f2 | 123 | const gotOptions = buildGotOptions(options) |
02988fdc | 124 | |
db4b15f2 | 125 | const outFile = createWriteStream(destPath) |
bfe2ef6b | 126 | |
db4b15f2 C |
127 | try { |
128 | await pipelinePromise( | |
129 | peertubeGot.stream(url, gotOptions), | |
130 | outFile | |
131 | ) | |
132 | } catch (err) { | |
133 | remove(destPath) | |
134 | .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err })) | |
bfe2ef6b | 135 | |
db4b15f2 C |
136 | throw buildRequestError(err) |
137 | } | |
0d0e8dd0 C |
138 | } |
139 | ||
6040f87d C |
140 | async function downloadImage (url: string, destDir: string, destName: string, size: { width: number, height: number }) { |
141 | const tmpPath = join(CONFIG.STORAGE.TMP_DIR, 'pending-' + destName) | |
db4b15f2 | 142 | await doRequestAndSaveToFile(url, tmpPath) |
58d515e3 | 143 | |
6040f87d | 144 | const destPath = join(destDir, destName) |
4ee7a4c9 C |
145 | |
146 | try { | |
2fb5b3a5 | 147 | await processImage(tmpPath, destPath, size) |
4ee7a4c9 C |
148 | } catch (err) { |
149 | await remove(tmpPath) | |
150 | ||
151 | throw err | |
152 | } | |
58d515e3 C |
153 | } |
154 | ||
8729a870 | 155 | function getAgent () { |
156 | if (!isProxyEnabled()) return {} | |
157 | ||
158 | const proxy = getProxy() | |
159 | ||
160 | logger.info('Using proxy %s.', proxy) | |
161 | ||
162 | const proxyAgentOptions = { | |
163 | keepAlive: true, | |
164 | keepAliveMsecs: 1000, | |
165 | maxSockets: 256, | |
166 | maxFreeSockets: 256, | |
167 | scheduling: 'lifo' as 'lifo', | |
168 | proxy | |
169 | } | |
170 | ||
171 | return { | |
172 | agent: { | |
173 | http: new HttpProxyAgent(proxyAgentOptions), | |
174 | https: new HttpsProxyAgent(proxyAgentOptions) | |
175 | } | |
176 | } | |
177 | } | |
178 | ||
e0ce715a | 179 | function getUserAgent () { |
66170ca8 | 180 | return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})` |
e0ce715a C |
181 | } |
182 | ||
62549e6c C |
183 | function isBinaryResponse (result: Response<any>) { |
184 | return BINARY_CONTENT_TYPES.has(result.headers['content-type']) | |
185 | } | |
186 | ||
dedcd583 C |
187 | async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) { |
188 | if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url) | |
189 | ||
190 | const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) }) | |
191 | ||
192 | if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1) | |
193 | ||
194 | return url | |
195 | } | |
196 | ||
9f10b292 | 197 | // --------------------------------------------------------------------------- |
dac0a531 | 198 | |
65fcc311 | 199 | export { |
e4f97bab | 200 | doRequest, |
db4b15f2 | 201 | doJSONRequest, |
58d515e3 | 202 | doRequestAndSaveToFile, |
62549e6c | 203 | isBinaryResponse, |
b3fc41a1 | 204 | downloadImage, |
dedcd583 | 205 | findLatestRedirection, |
b3fc41a1 | 206 | peertubeGot |
65fcc311 | 207 | } |
bfe2ef6b C |
208 | |
209 | // --------------------------------------------------------------------------- | |
210 | ||
db4b15f2 C |
211 | function buildGotOptions (options: PeerTubeRequestOptions) { |
212 | const { activityPub, bodyKBLimit = 1000 } = options | |
bfe2ef6b | 213 | |
db4b15f2 | 214 | const context = { bodyKBLimit, httpSignature: options.httpSignature } |
bfe2ef6b | 215 | |
db4b15f2 C |
216 | let headers = options.headers || {} |
217 | ||
e7053b1d C |
218 | if (!headers.date) { |
219 | headers = { ...headers, date: new Date().toUTCString() } | |
220 | } | |
db4b15f2 | 221 | |
e7053b1d | 222 | if (activityPub && !headers.accept) { |
db4b15f2 | 223 | headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER } |
bfe2ef6b | 224 | } |
db4b15f2 C |
225 | |
226 | return { | |
227 | method: options.method, | |
bbb3be68 | 228 | dnsCache: true, |
e81f6ccf | 229 | timeout: REQUEST_TIMEOUT, |
db4b15f2 C |
230 | json: options.json, |
231 | searchParams: options.searchParams, | |
232 | headers, | |
233 | context | |
234 | } | |
235 | } | |
236 | ||
b5c36108 C |
237 | function buildRequestError (error: RequestError) { |
238 | const newError: PeerTubeRequestError = new Error(error.message) | |
db4b15f2 C |
239 | newError.name = error.name |
240 | newError.stack = error.stack | |
241 | ||
b5c36108 C |
242 | if (error.response) { |
243 | newError.responseBody = error.response.body | |
244 | newError.statusCode = error.response.statusCode | |
db4b15f2 C |
245 | } |
246 | ||
b5c36108 | 247 | return newError |
bfe2ef6b | 248 | } |