2017-08-24 23:54:02 +02:00
|
|
|
const storage = require('../storage');
|
|
|
|
const mozlog = require('../log');
|
|
|
|
const log = mozlog('send.download');
|
2019-02-12 20:50:06 +01:00
|
|
|
const { statDownloadEvent } = require('../amplitude');
|
2017-08-24 23:54:02 +02:00
|
|
|
|
|
|
|
module.exports = async function(req, res) {
|
|
|
|
const id = req.params.id;
|
|
|
|
try {
|
2018-02-06 23:31:18 +01:00
|
|
|
const meta = req.meta;
|
2018-08-08 00:40:17 +02:00
|
|
|
const fileStream = await storage.get(id);
|
2018-07-12 23:00:22 +02:00
|
|
|
let cancelled = false;
|
|
|
|
|
2018-07-13 01:07:18 +02:00
|
|
|
req.on('close', () => {
|
|
|
|
cancelled = true;
|
2018-08-08 00:40:17 +02:00
|
|
|
fileStream.destroy();
|
2018-07-13 01:07:18 +02:00
|
|
|
});
|
2018-07-12 23:00:22 +02:00
|
|
|
|
2018-11-16 22:33:40 +01:00
|
|
|
fileStream.pipe(res).on('finish', async () => {
|
2018-07-12 23:00:22 +02:00
|
|
|
if (cancelled) {
|
2018-06-06 00:26:24 +02:00
|
|
|
return;
|
|
|
|
}
|
2018-07-17 18:48:47 +02:00
|
|
|
|
2018-02-06 23:31:18 +01:00
|
|
|
const dl = meta.dl + 1;
|
|
|
|
const dlimit = meta.dlimit;
|
2019-02-12 20:50:06 +01:00
|
|
|
const ttl = await storage.ttl(id);
|
|
|
|
statDownloadEvent({
|
|
|
|
id,
|
|
|
|
ip: req.ip,
|
|
|
|
owner: meta.owner,
|
|
|
|
download_count: dl,
|
|
|
|
ttl
|
|
|
|
});
|
2017-08-24 23:54:02 +02:00
|
|
|
try {
|
2017-11-30 22:41:09 +01:00
|
|
|
if (dl >= dlimit) {
|
2018-02-06 23:31:18 +01:00
|
|
|
await storage.del(id);
|
2017-11-30 22:41:09 +01:00
|
|
|
} else {
|
|
|
|
await storage.setField(id, 'dl', dl);
|
|
|
|
}
|
2017-08-24 23:54:02 +02:00
|
|
|
} catch (e) {
|
2017-11-30 22:41:09 +01:00
|
|
|
log.info('StorageError:', id);
|
2017-08-24 23:54:02 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
res.sendStatus(404);
|
|
|
|
}
|
|
|
|
};
|