2017-08-24 23:54:02 +02:00
|
|
|
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 23:31:18 +01:00
|
|
|
const meta = req.meta;
|
2017-08-24 23:54:02 +02:00
|
|
|
const contentLength = await storage.length(id);
|
|
|
|
res.writeHead(200, {
|
2017-08-31 18:43:36 +02:00
|
|
|
'Content-Disposition': 'attachment',
|
2017-08-24 23:54:02 +02:00
|
|
|
'Content-Type': 'application/octet-stream',
|
|
|
|
'Content-Length': contentLength,
|
2018-02-06 23:31:18 +01:00
|
|
|
'WWW-Authenticate': `send-v1 ${req.nonce}`
|
2017-08-24 23:54:02 +02:00
|
|
|
});
|
|
|
|
const file_stream = storage.get(id);
|
2018-06-06 00:26:24 +02:00
|
|
|
let sentBytes = 0;
|
|
|
|
file_stream.on('data', c => (sentBytes += c.length));
|
2017-08-24 23:54:02 +02:00
|
|
|
file_stream.on('end', async () => {
|
2018-06-06 00:26:24 +02:00
|
|
|
if (sentBytes < contentLength) {
|
|
|
|
return;
|
|
|
|
}
|
2018-02-06 23:31:18 +01:00
|
|
|
const dl = meta.dl + 1;
|
|
|
|
const dlimit = meta.dlimit;
|
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
|
|
|
}
|
|
|
|
});
|
|
|
|
file_stream.pipe(res);
|
|
|
|
} catch (e) {
|
|
|
|
res.sendStatus(404);
|
|
|
|
}
|
|
|
|
};
|