filelist.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const crypto = require('crypto');
  2. const config = require('../config');
  3. const storage = require('../storage');
  4. const Limiter = require('../limiter');
  5. function id(user, kid) {
  6. const sha = crypto.createHash('sha256');
  7. sha.update(user);
  8. sha.update(kid);
  9. const hash = sha.digest('hex');
  10. return `filelist-${hash}`;
  11. }
  12. module.exports = {
  13. async get(req, res) {
  14. if (!req.user) {
  15. return res.sendStatus(401);
  16. }
  17. const kid = req.params.id;
  18. try {
  19. const fileId = id(req.user, kid);
  20. const contentLength = await storage.length(fileId);
  21. const fileStream = await storage.get(fileId);
  22. res.writeHead(200, {
  23. 'Content-Type': 'application/octet-stream',
  24. 'Content-Length': contentLength
  25. });
  26. fileStream.pipe(res);
  27. } catch (e) {
  28. res.sendStatus(404);
  29. }
  30. },
  31. async post(req, res) {
  32. if (!req.user) {
  33. return res.sendStatus(401);
  34. }
  35. const kid = req.params.id;
  36. try {
  37. const limiter = new Limiter(1024 * 1024 * 10);
  38. const fileStream = req.pipe(limiter);
  39. await storage.set(
  40. id(req.user, kid),
  41. fileStream,
  42. null,
  43. config.max_expire_seconds
  44. );
  45. res.sendStatus(200);
  46. } catch (e) {
  47. if (e.message === 'limit') {
  48. return res.sendStatus(413);
  49. }
  50. res.sendStatus(500);
  51. }
  52. }
  53. };