A simple file sharing site with an easy to use API and online panel.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.5KB

  1. const express = require('express');
  2. const router = express.Router();
  3. const config = require('config');
  4. const fs = require('fs');
  5. const ModelPath = '../../models/';
  6. const Upload = require(ModelPath + 'Upload.js');
  7. const View = require(ModelPath + 'View.js');
  8. const insertView = async (req, upload) =>
  9. Promise.all([
  10. View.create({
  11. uid: upload.uid,
  12. uploader: upload.uploader,
  13. remoteAddress: req.ip,
  14. userAgent: req.headers['user-agent']
  15. }),
  16. Upload.updateOne({uid: upload.uid}, {$inc: {views: 1}})
  17. ]);
  18. router.get('/:uid', async (req, res) => {
  19. const upload = await Upload.findOne({uid: req.params.uid});
  20. if (!upload)
  21. return res.status(404).json({message: 'File not found.'});
  22. // Increment the file's view counter and insert a a view record
  23. await insertView(req, upload);
  24. // Whether the file should be an attachment or displayed inline on the page
  25. const mimetype = upload.file.mime.split('/');
  26. const inlineMimeTypes = config.get('View.inlineMimeTypes').map(type => type.split('/'));
  27. let inline = inlineMimeTypes.some(type =>
  28. (mimetype[0] === type[0] || type[0] === '*') &&
  29. (mimetype[1] === type[1] || type[1] === '*'));
  30. res.status(200);
  31. res.set({
  32. 'Content-Disposition': inline ? 'inline' : 'attachment; filename="' + upload.file.originalName + '"',
  33. 'Content-Type': upload.file.mime
  34. });
  35. fs.createReadStream(upload.file.path)
  36. .pipe(res);
  37. });
  38. module.exports = router;