2020-08-31 22:15:34 +00:00
|
|
|
require("dotenv").config();
|
|
|
|
const magick = require("../utils/image.js");
|
2020-09-01 22:10:19 +00:00
|
|
|
const { version } = require("../package.json");
|
2020-08-31 22:15:34 +00:00
|
|
|
const express = require("express");
|
|
|
|
const multer = require("multer");
|
|
|
|
const path = require("path");
|
|
|
|
const storage = multer.diskStorage({
|
|
|
|
destination: function(req, file, cb) {
|
|
|
|
cb(null, "/tmp/");
|
|
|
|
},
|
|
|
|
filename: function(req, file, cb) {
|
2020-09-02 02:52:12 +00:00
|
|
|
cb(null, Date.now() + path.extname(file.originalname));
|
2020-08-31 22:15:34 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
const upload = multer({ storage: storage });
|
|
|
|
const app = express();
|
2020-09-03 03:52:01 +00:00
|
|
|
const port = 3000;
|
2020-08-31 22:15:34 +00:00
|
|
|
|
|
|
|
const formats = ["image/jpeg", "image/png", "image/webp", "image/gif"];
|
|
|
|
|
2020-10-06 19:48:22 +00:00
|
|
|
function isValidJSON(json) {
|
|
|
|
try {
|
|
|
|
JSON.parse(json);
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-08-31 22:15:34 +00:00
|
|
|
app.get("/", (req, res) => {
|
2020-09-03 03:52:01 +00:00
|
|
|
res.send(`esmBot v${version}`);
|
2020-08-31 22:15:34 +00:00
|
|
|
});
|
|
|
|
|
2020-10-06 19:48:22 +00:00
|
|
|
app.post("/run", upload.single("image"), async (req, res, next) => {
|
2020-09-19 00:54:52 +00:00
|
|
|
const type = req.file ? (req.file.mimetype === "video/mp4" ? "image/gif" : req.file.mimetype) : "image/png";
|
2020-08-31 22:15:34 +00:00
|
|
|
if (!formats.includes(type)) {
|
|
|
|
return res.sendStatus(400);
|
|
|
|
}
|
2020-10-06 19:48:22 +00:00
|
|
|
if (!isValidJSON(req.body.data)) return res.sendStatus(400);
|
|
|
|
|
|
|
|
const object = JSON.parse(req.body.data);
|
|
|
|
if (!magick.check(object.cmd)) return res.sendStatus(400);
|
|
|
|
|
|
|
|
object.path = req.file ? req.file.path : null;
|
|
|
|
object.type = type.split("/")[1];
|
2020-08-31 22:15:34 +00:00
|
|
|
|
|
|
|
try {
|
2020-10-06 19:48:22 +00:00
|
|
|
const data = await magick.run(object, true);
|
|
|
|
res.contentType(type);
|
2020-09-02 02:52:12 +00:00
|
|
|
res.send(data);
|
2020-08-31 22:15:34 +00:00
|
|
|
} catch (e) {
|
|
|
|
next(e);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
app.listen(port, () => {
|
|
|
|
console.log(`Started image API on port ${port}.`);
|
|
|
|
});
|