]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/requests.ts
Don't display log tag filter for audit logs
[github/Chocobozzz/PeerTube.git] / server / helpers / requests.ts
CommitLineData
bfe2ef6b 1import { createWriteStream, remove } from 'fs-extra'
62549e6c 2import got, { CancelableRequest, Options as GotOptions, RequestError, Response } from 'got'
8729a870 3import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent'
db4b15f2
C
4import { join } from 'path'
5import { CONFIG } from '../initializers/config'
62549e6c 6import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUT, WEBSERVER } from '../initializers/constants'
db4b15f2 7import { pipelinePromise } from './core-utils'
58d515e3 8import { processImage } from './image-utils'
ac036180 9import { logger, loggerTagsFactory } from './logger'
8729a870 10import { getProxy, isProxyEnabled } from './proxy'
11
ac036180
C
12const lTags = loggerTagsFactory('request')
13
5842a854 14const httpSignature = require('@peertube/http-signature')
da854ddd 15
b5c36108
C
16export interface PeerTubeRequestError extends Error {
17 statusCode?: number
18 responseBody?: any
19}
20
db4b15f2
C
21type PeerTubeRequestOptions = {
22 activityPub?: boolean
23 bodyKBLimit?: number // 1MB
24 httpSignature?: {
25 algorithm: string
26 authorizationHeaderName: string
27 keyId: string
28 key: string
29 headers: string[]
30 }
31 jsonResponse?: boolean
32} & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
33
34const peertubeGot = got.extend({
8729a870 35 ...getAgent(),
36
db4b15f2
C
37 headers: {
38 'user-agent': getUserAgent()
39 },
40
41 handlers: [
42 (options, next) => {
43 const promiseOrStream = next(options) as CancelableRequest<any>
b329abc2 44 const bodyKBLimit = options.context?.bodyKBLimit as number
db4b15f2
C
45 if (!bodyKBLimit) throw new Error('No KB limit for this request')
46
b329abc2
C
47 const bodyLimit = bodyKBLimit * 1000
48
db4b15f2
C
49 /* eslint-disable @typescript-eslint/no-floating-promises */
50 promiseOrStream.on('downloadProgress', progress => {
b329abc2
C
51 if (progress.transferred > bodyLimit && progress.percent !== 1) {
52 const message = `Exceeded the download limit of ${bodyLimit} B`
ac036180 53 logger.warn(message, lTags())
b329abc2
C
54
55 // CancelableRequest
56 if (promiseOrStream.cancel) {
57 promiseOrStream.cancel()
58 return
59 }
60
61 // Stream
62 (promiseOrStream as any).destroy()
db4b15f2
C
63 }
64 })
e0ce715a 65
db4b15f2
C
66 return promiseOrStream
67 }
68 ],
69
70 hooks: {
71 beforeRequest: [
72 options => {
73 const headers = options.headers || {}
74 headers['host'] = options.url.host
75 },
76
77 options => {
78 const httpSignatureOptions = options.context?.httpSignature
79
80 if (httpSignatureOptions) {
81 const method = options.method ?? 'GET'
82 const path = options.path ?? options.url.pathname
83
84 if (!method || !path) {
85 throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
86 }
87
88 httpSignature.signRequest({
89 getHeader: function (header) {
90 return options.headers[header]
91 },
92
93 setHeader: function (header, value) {
94 options.headers[header] = value
95 },
96
97 method,
98 path
99 }, httpSignatureOptions)
100 }
101 }
102 ]
da854ddd 103 }
db4b15f2 104})
e4f97bab 105
db4b15f2
C
106function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
107 const gotOptions = buildGotOptions(options)
108
109 return peertubeGot(url, gotOptions)
ac036180 110 .on('retry', logRetryFactory(url))
db4b15f2
C
111 .catch(err => { throw buildRequestError(err) })
112}
113
114function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) {
115 const gotOptions = buildGotOptions(options)
116
117 return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' })
ac036180 118 .on('retry', logRetryFactory(url))
db4b15f2 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)
ac036180 138 .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() }))
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
ac036180 164 logger.info('Using proxy %s.', proxy, lTags())
8729a870 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
62549e6c
C
187function isBinaryResponse (result: Response<any>) {
188 return BINARY_CONTENT_TYPES.has(result.headers['content-type'])
189}
190
dedcd583
C
191async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) {
192 if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)
193
194 const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) })
195
196 if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1)
197
198 return url
199}
200
9f10b292 201// ---------------------------------------------------------------------------
dac0a531 202
65fcc311 203export {
e4f97bab 204 doRequest,
db4b15f2 205 doJSONRequest,
58d515e3 206 doRequestAndSaveToFile,
62549e6c 207 isBinaryResponse,
b3fc41a1 208 downloadImage,
dedcd583 209 findLatestRedirection,
b3fc41a1 210 peertubeGot
65fcc311 211}
bfe2ef6b
C
212
213// ---------------------------------------------------------------------------
214
db4b15f2
C
215function buildGotOptions (options: PeerTubeRequestOptions) {
216 const { activityPub, bodyKBLimit = 1000 } = options
bfe2ef6b 217
db4b15f2 218 const context = { bodyKBLimit, httpSignature: options.httpSignature }
bfe2ef6b 219
db4b15f2
C
220 let headers = options.headers || {}
221
e7053b1d
C
222 if (!headers.date) {
223 headers = { ...headers, date: new Date().toUTCString() }
224 }
db4b15f2 225
e7053b1d 226 if (activityPub && !headers.accept) {
db4b15f2 227 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
bfe2ef6b 228 }
db4b15f2
C
229
230 return {
231 method: options.method,
bbb3be68 232 dnsCache: true,
e81f6ccf 233 timeout: REQUEST_TIMEOUT,
db4b15f2
C
234 json: options.json,
235 searchParams: options.searchParams,
ac036180 236 retry: 2,
db4b15f2
C
237 headers,
238 context
239 }
240}
241
b5c36108
C
242function buildRequestError (error: RequestError) {
243 const newError: PeerTubeRequestError = new Error(error.message)
db4b15f2
C
244 newError.name = error.name
245 newError.stack = error.stack
246
b5c36108
C
247 if (error.response) {
248 newError.responseBody = error.response.body
249 newError.statusCode = error.response.statusCode
db4b15f2
C
250 }
251
b5c36108 252 return newError
bfe2ef6b 253}
ac036180
C
254
255function logRetryFactory (url: string) {
256 return (retryCount: number, error: RequestError) => {
257 logger.debug('Retrying request to %s.', url, { retryCount, error, ...lTags() })
258 }
259}