download.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const storage = require('../storage');
  2. const mozlog = require('../log');
  3. const log = mozlog('send.download');
  4. const { statDownloadEvent } = require('../amplitude');
  5. module.exports = async function(req, res) {
  6. const id = req.params.id;
  7. try {
  8. const meta = req.meta;
  9. const fileStream = await storage.get(id);
  10. let cancelled = false;
  11. req.on('aborted', () => {
  12. cancelled = true;
  13. fileStream.destroy();
  14. });
  15. fileStream.pipe(res).on('finish', async () => {
  16. if (cancelled) {
  17. return;
  18. }
  19. const dl = meta.dl + 1;
  20. const dlimit = meta.dlimit;
  21. const ttl = await storage.ttl(id);
  22. statDownloadEvent({
  23. id,
  24. ip: req.ip,
  25. owner: meta.owner,
  26. download_count: dl,
  27. ttl,
  28. agent: req.ua.browser.name || req.ua.ua.substring(0, 6)
  29. });
  30. try {
  31. if (dl >= dlimit) {
  32. await storage.del(id);
  33. } else {
  34. await storage.incrementField(id, 'dl');
  35. }
  36. } catch (e) {
  37. log.info('StorageError:', id);
  38. }
  39. });
  40. } catch (e) {
  41. res.sendStatus(404);
  42. }
  43. };