2017-10-09 22:01:02 -04:00
|
|
|
var express = require('express');
|
|
|
|
var router = express.Router();
|
|
|
|
|
2017-10-11 10:15:19 -04:00
|
|
|
var mongoose = require('mongoose');
|
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-11 10:15:19 -04:00
|
|
|
|
|
|
|
var multer = require('multer');
|
2017-10-09 22:01:02 -04:00
|
|
|
var dest = multer({dest: 'uploads/'});
|
|
|
|
|
|
|
|
function fileNameExists(name) {
|
2017-10-14 15:13:50 -04:00
|
|
|
Upload.count({name: name}, function (err, count) {
|
2017-10-09 22:01:02 -04:00
|
|
|
return count !== 0;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-10-14 15:13:50 -04:00
|
|
|
function updateStats(user, size) {
|
|
|
|
User.updateOne({username: user}, { $inc: { uploadCount: 1, uploadSize: size } }, function(err, res) {
|
|
|
|
if (err) {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-10-09 22:01:02 -04:00
|
|
|
function genFileName() {
|
|
|
|
var charset = "abcdefghijklmnopqrstuvwxyz";
|
|
|
|
do {
|
|
|
|
var chars = [];
|
|
|
|
for (var i = 0; i < 6; i++)
|
|
|
|
chars.push(charset.charAt(Math.floor(Math.random() * charset.length)));
|
|
|
|
} while (fileNameExists(chars.join('')));
|
|
|
|
return chars.join('');
|
|
|
|
}
|
|
|
|
|
2017-10-14 15:13:50 -04:00
|
|
|
router.post('/', dest.single('file'), function (req, res) {
|
2017-10-13 16:16:48 -04:00
|
|
|
if (req.payload.scope.indexOf('file.upload') === -1) {
|
2017-10-13 18:07:52 -04:00
|
|
|
res.status(403).json({'message': 'Permission error.'});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Size must be below 128 Megabytes (1024*1024*128 Bytes)
|
|
|
|
if (req.file.size >= 134217728) {
|
|
|
|
res.status(413).json({'message': 'File too large.'});
|
2017-10-13 16:16:48 -04:00
|
|
|
return;
|
|
|
|
}
|
2017-10-11 10:15:19 -04:00
|
|
|
|
2017-10-14 15:13:50 -04:00
|
|
|
updateStats(req.payload.username, req.file.size);
|
|
|
|
|
2017-10-09 22:01:02 -04:00
|
|
|
var entry = {
|
|
|
|
name: genFileName(),
|
2017-10-14 15:13:50 -04:00
|
|
|
uploader: req.payload.username,
|
2017-10-09 22:01:02 -04:00
|
|
|
created: Date.now(),
|
|
|
|
file: req.file
|
|
|
|
};
|
|
|
|
|
2017-10-14 15:13:50 -04:00
|
|
|
Upload.create(entry, function (err, next) {
|
2017-10-09 22:01:02 -04:00
|
|
|
if (err) {
|
|
|
|
next(err);
|
|
|
|
} else {
|
2017-10-14 15:13:50 -04:00
|
|
|
res.send({
|
|
|
|
name: entry.name,
|
|
|
|
url: 'https://shimapan.rocks/v/' + entry.name
|
|
|
|
});
|
2017-10-09 22:01:02 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = router;
|