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