2018-07-26 21:53:15 -04:00
|
|
|
const express = require('express');
|
|
|
|
const router = express.Router();
|
|
|
|
const config = require('config');
|
2018-08-01 20:25:00 -04:00
|
|
|
const fs = require('fs');
|
2018-07-26 21:53:15 -04:00
|
|
|
|
2018-08-01 11:54:35 -04:00
|
|
|
const ModelPath = '../../models/';
|
2018-07-26 21:53:15 -04:00
|
|
|
const Upload = require(ModelPath + 'Upload.js');
|
2018-09-15 18:25:48 -04:00
|
|
|
const View = require(ModelPath + 'View.js');
|
2018-07-26 21:53:15 -04:00
|
|
|
|
2018-09-15 18:25:48 -04:00
|
|
|
const insertView = async (req, upload) =>
|
|
|
|
Promise.all([
|
|
|
|
View.create({
|
|
|
|
uid: upload.uid,
|
|
|
|
uploader: upload.uploader,
|
|
|
|
remoteAddress: req.ip,
|
|
|
|
userAgent: req.headers['user-agent']
|
|
|
|
}),
|
|
|
|
Upload.updateOne({uid: upload.uid}, {$inc: {views: 1}})
|
|
|
|
]);
|
2018-07-26 21:53:15 -04:00
|
|
|
|
2019-01-02 14:25:51 -05:00
|
|
|
router.get('/:uid', async (req, res) => {
|
2018-09-15 16:20:14 -04:00
|
|
|
const upload = await Upload.findOne({uid: req.params.uid});
|
2018-07-26 21:53:15 -04:00
|
|
|
if (!upload)
|
|
|
|
return res.status(404).json({message: 'File not found.'});
|
|
|
|
|
2018-09-15 18:25:48 -04:00
|
|
|
// Increment the file's view counter and insert a a view record
|
|
|
|
await insertView(req, upload);
|
2018-07-26 21:53:15 -04:00
|
|
|
|
|
|
|
// Whether the file should be an attachment or displayed inline on the page
|
2018-08-01 20:25:00 -04:00
|
|
|
const mimetype = upload.file.mime.split('/');
|
2018-07-26 21:53:15 -04:00
|
|
|
const inlineMimeTypes = config.get('View.inlineMimeTypes').map(type => type.split('/'));
|
2018-08-01 20:25:00 -04:00
|
|
|
let inline = inlineMimeTypes.some(type =>
|
|
|
|
(mimetype[0] === type[0] || type[0] === '*') &&
|
|
|
|
(mimetype[1] === type[1] || type[1] === '*'));
|
2018-07-26 21:53:15 -04:00
|
|
|
|
2018-08-01 20:25:00 -04:00
|
|
|
res.status(200);
|
2018-07-26 21:53:15 -04:00
|
|
|
res.set({
|
2018-08-01 20:25:00 -04:00
|
|
|
'Content-Disposition': inline ? 'inline' : 'attachment; filename="' + upload.file.originalName + '"',
|
|
|
|
'Content-Type': upload.file.mime
|
2017-10-09 22:01:02 -04:00
|
|
|
});
|
2018-07-26 21:53:15 -04:00
|
|
|
|
|
|
|
fs.createReadStream(upload.file.path)
|
|
|
|
.pipe(res);
|
2019-01-02 14:25:51 -05:00
|
|
|
});
|
2017-10-09 22:01:02 -04:00
|
|
|
|
|
|
|
module.exports = router;
|