ramirez/src/modules/webserver.js

70 lines
2.0 KiB
JavaScript
Raw Normal View History

const express = require("express");
const helmet = require("helmet");
2020-08-12 17:08:37 -04:00
const mime = require("mime");
const url = require("url");
const fs = require("fs");
const qs = require("querystring");
const moment = require("moment");
const config = require("../cfg");
const threads = require("../data/threads");
const attachments = require("../data/attachments");
const { formatters } = require("../formatters");
function notfound(res) {
res.status(404).send("Page Not Found");
}
/**
* @param {express.Request} req
* @param {express.Response} res
*/
async function serveLogs(req, res) {
const thread = await threads.findById(req.params.threadId);
if (! thread) return notfound(res);
2020-05-24 18:54:26 -04:00
let threadMessages = await thread.getThreadMessages();
const formatLogResult = await formatters.formatLog(thread, threadMessages, {
simple: Boolean(req.query.simple),
verbose: Boolean(req.query.verbose),
});
const contentType = formatLogResult.extra && formatLogResult.extra.contentType || "text/plain; charset=UTF-8";
2020-05-24 18:54:26 -04:00
res.set("Content-Type", contentType);
res.send(formatLogResult.content);
}
function serveAttachments(req, res) {
if (req.params.attachmentId.match(/^[0-9]+$/) === null) return notfound(res);
if (req.params.filename.match(/^[0-9a-z._-]+$/i) === null) return notfound(res);
const attachmentPath = attachments.getLocalAttachmentPath(req.params.attachmentId);
fs.access(attachmentPath, (err) => {
if (err) return notfound(res);
const filenameParts = req.params.filename.split(".");
2020-08-12 17:08:37 -04:00
const ext = (filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : "bin");
2018-08-07 18:10:38 -04:00
const fileMime = mime.getType(ext);
res.set("Content-Type", fileMime);
const read = fs.createReadStream(attachmentPath);
read.pipe(res);
})
}
module.exports = () => {
const server = express();
server.use(helmet());
server.get("/logs/:threadId", serveLogs);
server.get("/logs/:attachmentId/:filename", serveAttachments);
2020-08-12 17:08:37 -04:00
server.on("error", err => {
console.log("[WARN] Web server error:", err.message);
2018-08-07 17:54:01 -04:00
});
server.listen(config.port);
};