2017-08-24 21:54:02 +00:00
|
|
|
const storage = require('../storage');
|
|
|
|
const mozlog = require('../log');
|
|
|
|
const log = mozlog('send.download');
|
2019-02-12 19:50:06 +00:00
|
|
|
const { statDownloadEvent } = require('../amplitude');
|
2017-08-24 21:54:02 +00:00
|
|
|
|
|
|
|
module.exports = async function(req, res) {
|
|
|
|
const id = req.params.id;
|
|
|
|
try {
|
2018-02-06 22:31:18 +00:00
|
|
|
const meta = req.meta;
|
2020-07-13 17:21:28 +00:00
|
|
|
if (meta.dead || meta.flagged) {
|
|
|
|
return res.sendStatus(404);
|
|
|
|
}
|
2018-08-07 22:40:17 +00:00
|
|
|
const fileStream = await storage.get(id);
|
2018-07-12 21:00:22 +00:00
|
|
|
let cancelled = false;
|
|
|
|
|
2020-04-30 00:33:12 +00:00
|
|
|
req.on('aborted', () => {
|
2018-07-12 23:07:18 +00:00
|
|
|
cancelled = true;
|
2018-08-07 22:40:17 +00:00
|
|
|
fileStream.destroy();
|
2018-07-12 23:07:18 +00:00
|
|
|
});
|
2018-07-12 21:00:22 +00:00
|
|
|
|
2018-11-16 21:33:40 +00:00
|
|
|
fileStream.pipe(res).on('finish', async () => {
|
2018-07-12 21:00:22 +00:00
|
|
|
if (cancelled) {
|
2018-06-05 22:26:24 +00:00
|
|
|
return;
|
|
|
|
}
|
2018-07-17 16:48:47 +00:00
|
|
|
|
2018-02-06 22:31:18 +00:00
|
|
|
const dl = meta.dl + 1;
|
|
|
|
const dlimit = meta.dlimit;
|
2019-02-12 19:50:06 +00:00
|
|
|
const ttl = await storage.ttl(id);
|
|
|
|
statDownloadEvent({
|
|
|
|
id,
|
|
|
|
ip: req.ip,
|
|
|
|
owner: meta.owner,
|
|
|
|
download_count: dl,
|
2019-05-03 16:25:12 +00:00
|
|
|
ttl,
|
|
|
|
agent: req.ua.browser.name || req.ua.ua.substring(0, 6)
|
2019-02-12 19:50:06 +00:00
|
|
|
});
|
2017-08-24 21:54:02 +00:00
|
|
|
try {
|
2017-11-30 21:41:09 +00:00
|
|
|
if (dl >= dlimit) {
|
2020-07-13 17:21:28 +00:00
|
|
|
await storage.kill(id);
|
2017-11-30 21:41:09 +00:00
|
|
|
} else {
|
2019-04-19 11:10:49 +00:00
|
|
|
await storage.incrementField(id, 'dl');
|
2017-11-30 21:41:09 +00:00
|
|
|
}
|
2017-08-24 21:54:02 +00:00
|
|
|
} catch (e) {
|
2017-11-30 21:41:09 +00:00
|
|
|
log.info('StorageError:', id);
|
2017-08-24 21:54:02 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
res.sendStatus(404);
|
|
|
|
}
|
|
|
|
};
|