drop.chapril.org-firefoxsend/server/routes/download.js
2020-07-24 08:32:43 -07:00

51 lines
1.2 KiB
JavaScript

const storage = require('../storage');
const mozlog = require('../log');
const log = mozlog('send.download');
const { statDownloadEvent } = require('../amplitude');
module.exports = async function(req, res) {
const id = req.params.id;
try {
const meta = req.meta;
if (meta.dead || meta.flagged) {
return res.sendStatus(404);
}
const fileStream = await storage.get(id);
let cancelled = false;
req.on('aborted', () => {
cancelled = true;
fileStream.destroy();
});
fileStream.pipe(res).on('finish', async () => {
if (cancelled) {
return;
}
const dl = meta.dl + 1;
const dlimit = meta.dlimit;
const ttl = await storage.ttl(id);
statDownloadEvent({
id,
ip: req.ip,
owner: meta.owner,
download_count: dl,
ttl,
agent: req.ua.browser.name || req.ua.ua.substring(0, 6)
});
try {
if (dl >= dlimit) {
await storage.kill(id);
} else {
await storage.incrementField(id, 'dl');
}
} catch (e) {
log.info('StorageError:', id);
}
});
} catch (e) {
res.sendStatus(404);
}
};