send/server/routes/download.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

const storage = require('../storage');
const mozlog = require('../log');
const log = mozlog('send.download');
module.exports = async function(req, res) {
const id = req.params.id;
try {
2018-02-06 22:31:18 +00:00
const meta = req.meta;
const contentLength = await storage.length(id);
res.writeHead(200, {
'Content-Disposition': 'attachment',
'Content-Type': 'application/octet-stream',
'Content-Length': contentLength,
2018-02-06 22:31:18 +00:00
'WWW-Authenticate': `send-v1 ${req.nonce}`
});
const file_stream = storage.get(id);
let cancelled = false;
2018-07-12 23:07:18 +00:00
req.on('close', () => {
cancelled = true;
file_stream.destroy();
});
2018-07-12 23:07:18 +00:00
file_stream.on('close', async () => {
if (cancelled) {
2018-06-05 22:26:24 +00:00
return;
}
2018-02-06 22:31:18 +00:00
const dl = meta.dl + 1;
const dlimit = meta.dlimit;
try {
2017-11-30 21:41:09 +00:00
if (dl >= dlimit) {
2018-02-06 22:31:18 +00:00
await storage.del(id);
2017-11-30 21:41:09 +00:00
} else {
await storage.setField(id, 'dl', dl);
}
} catch (e) {
2017-11-30 21:41:09 +00:00
log.info('StorageError:', id);
}
});
file_stream.pipe(res);
} catch (e) {
res.sendStatus(404);
}
};