1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-10 23:53:31 -05:00
shimapan/app/routes/upload.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-10-09 22:01:02 -04:00
var express = require('express');
var router = express.Router();
2017-10-14 15:13:50 -04:00
var User = require('../models/User.js');
2017-10-09 22:01:02 -04:00
var Upload = require('../models/Upload.js');
2017-10-22 12:19:51 -04:00
var Key = require('../models/Key.js');
2017-10-11 10:15:19 -04:00
var multer = require('multer');
2017-10-09 22:01:02 -04:00
var dest = multer({dest: 'uploads/'});
2018-07-26 13:17:37 -04:00
const requireAuth = require('../util/requireAuth').requireAuth;
const wrap = require('../util/wrap.js').wrap;
const generatedIdExists = async id =>
await Upload.countDocuments({id: id}) === 1;
2017-10-22 12:19:51 -04:00
2018-07-26 13:17:37 -04:00
const generateId = async () => {
const charset = "abcdefghijklmnopqrstuvwxyz";
const len = 6;
const id = [...Array(len)]
.map(() => charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
return await generatedIdExists(id)
? generateId()
: id;
2017-10-22 12:19:51 -04:00
};
2017-10-14 15:13:50 -04:00
2018-07-26 13:17:37 -04:00
const updateStats = async req =>
Promise.all([
User.updateOne({username: req.authUser}, {$inc: {uploadCount: 1, uploadSize: req.file.size}}),
req.authKey
? Key.updateOne({key: req.authKey}, {$inc: {uploadCount: 1, uploadSize: req.file.size}})
: Promise.resolve()
]);
router.post('/', requireAuth('file.upload'), dest.single('file'), wrap(async (req, res, next) => {
2017-10-22 12:19:51 -04:00
if (!req.file)
2018-07-26 13:17:37 -04:00
return res.status(400).json({message: 'No file specified.'});
// Max file size is 128 MiB
if (req.file.size > 1024 * 1024 * 128)
return res.status(413).json({message: 'File too large.'});
const upload = {
name: req.file.originalname,
id: await generateId(),
uploader: req.authUser,
uploaderKey: req.authKey,
date: Date.now(),
mime: req.file.mimetype,
file: req.file
};
await Promise.all([
Upload.create(upload),
updateStats(req)
]);
res.status(200).json({
id: upload.id,
url: 'https://shimapan.rocks/v/' + upload.id
2017-10-09 22:01:02 -04:00
});
2018-07-26 13:17:37 -04:00
}));
2017-10-09 22:01:02 -04:00
module.exports = router;