-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathupload.js
38 lines (31 loc) · 1.51 KB
/
upload.js
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
const Uploader = require('../Uploader')
const logger = require('../logger')
async function startDownUpload({ req, res, getSize, download }) {
logger.debug('Starting download stream.', null, req.id)
const { stream, size: maybeSize } = await download()
let size
// if the provider already knows the size, we can use that
if (typeof maybeSize === 'number' && !Number.isNaN(maybeSize) && maybeSize > 0) {
size = maybeSize
}
// if not we need to get the size
if (size == null) {
size = await getSize()
}
const { clientSocketConnectTimeout } = req.companion.options
logger.debug('Instantiating uploader.', null, req.id)
const uploader = new Uploader(Uploader.reqToOptions(req, size))
// "Forking" off the upload operation to background, so we can return the http request:
; (async () => {
// wait till the client has connected to the socket, before starting
// the download, so that the client can receive all download/upload progress.
logger.debug('Waiting for socket connection before beginning remote download/upload.', null, req.id)
await uploader.awaitReady(clientSocketConnectTimeout)
logger.debug('Socket connection received. Starting remote download/upload.', null, req.id)
await uploader.tryUploadStream(stream, req)
})().catch((err) => logger.error(err))
// Respond the request
// NOTE: the Uploader will continue running after the http request is responded
res.status(200).json({ token: uploader.token })
}
module.exports = { startDownUpload }