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