]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/requests.ts
Update translations
[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 }
99 }
100 ]
da854ddd 101 }
db4b15f2 102})
e4f97bab 103
db4b15f2
C
104function doRequest (url: string, options: PeerTubeRequestOptions = {}) {
105 const gotOptions = buildGotOptions(options)
106
107 return peertubeGot(url, gotOptions)
108 .catch(err => { throw buildRequestError(err) })
109}
110
111function 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
118async 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
140async 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 155function 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 179function getUserAgent () {
66170ca8 180 return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})`
e0ce715a
C
181}
182
9f10b292 183// ---------------------------------------------------------------------------
dac0a531 184
65fcc311 185export {
e4f97bab 186 doRequest,
db4b15f2 187 doJSONRequest,
58d515e3 188 doRequestAndSaveToFile,
b3fc41a1
C
189 downloadImage,
190 peertubeGot
65fcc311 191}
bfe2ef6b
C
192
193// ---------------------------------------------------------------------------
194
db4b15f2
C
195function buildGotOptions (options: PeerTubeRequestOptions) {
196 const { activityPub, bodyKBLimit = 1000 } = options
bfe2ef6b 197
db4b15f2 198 const context = { bodyKBLimit, httpSignature: options.httpSignature }
bfe2ef6b 199
db4b15f2
C
200 let headers = options.headers || {}
201
e7053b1d
C
202 if (!headers.date) {
203 headers = { ...headers, date: new Date().toUTCString() }
204 }
db4b15f2 205
e7053b1d 206 if (activityPub && !headers.accept) {
db4b15f2 207 headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER }
bfe2ef6b 208 }
db4b15f2
C
209
210 return {
211 method: options.method,
bbb3be68 212 dnsCache: true,
e81f6ccf 213 timeout: REQUEST_TIMEOUT,
db4b15f2
C
214 json: options.json,
215 searchParams: options.searchParams,
216 headers,
217 context
218 }
219}
220
b5c36108
C
221function buildRequestError (error: RequestError) {
222 const newError: PeerTubeRequestError = new Error(error.message)
db4b15f2
C
223 newError.name = error.name
224 newError.stack = error.stack
225
b5c36108
C
226 if (error.response) {
227 newError.responseBody = error.response.body
228 newError.statusCode = error.response.statusCode
db4b15f2
C
229 }
230
b5c36108 231 return newError
bfe2ef6b 232}