download.js 993 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const storage = require('../storage');
  2. const mozlog = require('../log');
  3. const log = mozlog('send.download');
  4. module.exports = async function(req, res) {
  5. const id = req.params.id;
  6. try {
  7. const meta = req.meta;
  8. const contentLength = await storage.length(id);
  9. const fileStream = await storage.get(id);
  10. let cancelled = false;
  11. req.on('aborted', () => {
  12. cancelled = true;
  13. fileStream.destroy();
  14. });
  15. res.writeHead(200, {
  16. 'Content-Type': 'application/octet-stream',
  17. 'Content-Length': contentLength
  18. });
  19. fileStream.pipe(res).on('finish', async () => {
  20. if (cancelled) {
  21. return;
  22. }
  23. const dl = meta.dl + 1;
  24. const dlimit = meta.dlimit;
  25. try {
  26. if (dl >= dlimit) {
  27. await storage.del(id);
  28. } else {
  29. await storage.incrementField(id, 'dl');
  30. }
  31. } catch (e) {
  32. log.info('StorageError:', id);
  33. }
  34. });
  35. } catch (e) {
  36. res.sendStatus(404);
  37. }
  38. };