aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/peertube-runner/shared/http.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/peertube-runner/shared/http.ts')
-rw-r--r--packages/peertube-runner/shared/http.ts66
1 files changed, 66 insertions, 0 deletions
diff --git a/packages/peertube-runner/shared/http.ts b/packages/peertube-runner/shared/http.ts
new file mode 100644
index 000000000..d3fff70d1
--- /dev/null
+++ b/packages/peertube-runner/shared/http.ts
@@ -0,0 +1,66 @@
1import { createWriteStream, remove } from 'fs-extra'
2import { request as requestHTTP } from 'http'
3import { request as requestHTTPS, RequestOptions } from 'https'
4import { logger } from './logger'
5
6export function downloadFile (options: {
7 url: string
8 destination: string
9 runnerToken: string
10 jobToken: string
11}) {
12 const { url, destination, runnerToken, jobToken } = options
13
14 logger.debug(`Downloading file ${url}`)
15
16 return new Promise<void>((res, rej) => {
17 const parsed = new URL(url)
18
19 const body = JSON.stringify({
20 runnerToken,
21 jobToken
22 })
23
24 const getOptions: RequestOptions = {
25 method: 'POST',
26 hostname: parsed.hostname,
27 port: parsed.port,
28 path: parsed.pathname,
29 headers: {
30 'Content-Type': 'application/json',
31 'Content-Length': Buffer.byteLength(body, 'utf-8')
32 }
33 }
34
35 const request = getRequest(url)(getOptions, response => {
36 const code = response.statusCode ?? 0
37
38 if (code >= 400) {
39 return rej(new Error(response.statusMessage))
40 }
41
42 const file = createWriteStream(destination)
43 file.on('finish', () => res())
44
45 response.pipe(file)
46 })
47
48 request.on('error', err => {
49 remove(destination)
50 .catch(err => console.error(err))
51
52 return rej(err)
53 })
54
55 request.write(body)
56 request.end()
57 })
58}
59
60// ---------------------------------------------------------------------------
61
62function getRequest (url: string) {
63 if (url.startsWith('https://')) return requestHTTPS
64
65 return requestHTTP
66}