aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/peertube-runner/shared/http.ts
blob: df64dc168c4e33fe94476e65152a9c6190f44474 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { createWriteStream, remove } from 'fs-extra'
import { request as requestHTTP } from 'http'
import { request as requestHTTPS, RequestOptions } from 'https'
import { logger } from './logger'

export function downloadFile (options: {
  url: string
  destination: string
  runnerToken: string
  jobToken: string
}) {
  const { url, destination, runnerToken, jobToken } = options

  logger.debug(`Downloading file ${url}`)

  return new Promise<void>((res, rej) => {
    const parsed = new URL(url)

    const body = JSON.stringify({
      runnerToken,
      jobToken
    })

    const getOptions: RequestOptions = {
      method: 'POST',
      hostname: parsed.hostname,
      port: parsed.port,
      path: parsed.pathname,
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(body, 'utf-8')
      }
    }

    const request = getRequest(url)(getOptions, response => {
      const code = response.statusCode ?? 0

      if (code >= 400) {
        return rej(new Error(response.statusMessage))
      }

      const file = createWriteStream(destination)
      file.on('finish', () => res())

      response.pipe(file)
    })

    request.on('error', err => {
      remove(destination)
        .catch(err => logger.error(err))

      return rej(err)
    })

    request.write(body)
    request.end()
  })
}

// ---------------------------------------------------------------------------

function getRequest (url: string) {
  if (url.startsWith('https://')) return requestHTTPS

  return requestHTTP
}