ramirez/src/modules/webserver.js

80 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-08-12 17:08:37 -04:00
const http = require("http");
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.statusCode = 404;
2020-08-12 17:08:37 -04:00
res.end("Page Not Found");
}
2020-05-24 18:54:26 -04:00
async function serveLogs(req, res, pathParts, query) {
const threadId = pathParts[pathParts.length - 1];
if (threadId.match(/^[0-9a-f\-]+$/) === null) return notfound(res);
const thread = await threads.findById(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(query.simple),
verbose: Boolean(query.verbose),
});
const contentType = formatLogResult.extra && formatLogResult.extra.contentType || "text/plain; charset=UTF-8";
2020-05-24 18:54:26 -04:00
res.setHeader("Content-Type", contentType);
res.end(formatLogResult.content);
}
2020-05-24 18:54:26 -04:00
function serveAttachments(req, res, pathParts) {
const desiredFilename = pathParts[pathParts.length - 1];
const id = pathParts[pathParts.length - 2];
if (id.match(/^[0-9]+$/) === null) return notfound(res);
if (desiredFilename.match(/^[0-9a-z._-]+$/i) === null) return notfound(res);
2019-03-06 16:31:24 -05:00
const attachmentPath = attachments.getLocalAttachmentPath(id);
fs.access(attachmentPath, (err) => {
if (err) return notfound(res);
2020-08-12 17:08:37 -04:00
const filenameParts = desiredFilename.split(".");
const ext = (filenameParts.length > 1 ? filenameParts[filenameParts.length - 1] : "bin");
2018-08-07 18:10:38 -04:00
const fileMime = mime.getType(ext);
2020-08-12 17:08:37 -04:00
res.setHeader("Content-Type", fileMime);
const read = fs.createReadStream(attachmentPath);
read.pipe(res);
})
}
module.exports = () => {
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(`http://${req.url}`);
2020-08-12 17:08:37 -04:00
const pathParts = parsedUrl.pathname.split("/").filter(v => v !== "");
2020-05-24 18:54:26 -04:00
const query = qs.parse(parsedUrl.query);
2020-08-12 17:08:37 -04:00
if (parsedUrl.pathname.startsWith("/logs/")) {
2020-05-24 18:54:26 -04:00
serveLogs(req, res, pathParts, query);
2020-08-12 17:08:37 -04:00
} else if (parsedUrl.pathname.startsWith("/attachments/")) {
2020-05-24 18:54:26 -04:00
serveAttachments(req, res, pathParts, query);
} else {
notfound(res);
}
});
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);
};