2018-08-01 20:09:51 +03:00
|
|
|
import http, { ServerResponse } from "http";
|
|
|
|
import { GlobalPlugin } from "knub";
|
2018-08-18 19:51:28 +03:00
|
|
|
import { GuildArchives } from "../data/GuildArchives";
|
2018-08-05 00:45:35 +03:00
|
|
|
import { sleep } from "../utils";
|
2018-08-01 20:09:51 +03:00
|
|
|
|
|
|
|
const DEFAULT_PORT = 9920;
|
2018-08-18 19:51:28 +03:00
|
|
|
const archivesRegex = /^\/(spam-logs|archives)\/([a-z0-9\-]+)\/?$/i;
|
2018-08-01 20:09:51 +03:00
|
|
|
|
|
|
|
function notFound(res: ServerResponse) {
|
|
|
|
res.statusCode = 404;
|
|
|
|
res.end("Not Found");
|
|
|
|
}
|
|
|
|
|
|
|
|
export class LogServerPlugin extends GlobalPlugin {
|
2018-08-18 19:51:28 +03:00
|
|
|
protected archives: GuildArchives;
|
2018-08-01 20:09:51 +03:00
|
|
|
protected server: http.Server;
|
|
|
|
|
2018-08-05 00:45:35 +03:00
|
|
|
async onLoad() {
|
2018-08-18 19:51:28 +03:00
|
|
|
this.archives = new GuildArchives(null);
|
2018-08-01 20:09:51 +03:00
|
|
|
|
|
|
|
this.server = http.createServer(async (req, res) => {
|
2018-08-18 19:51:28 +03:00
|
|
|
const pathMatch = req.url.match(archivesRegex);
|
|
|
|
if (!pathMatch) return notFound(res);
|
2018-08-01 20:09:51 +03:00
|
|
|
|
2018-08-18 19:51:28 +03:00
|
|
|
const logId = pathMatch[2];
|
|
|
|
|
|
|
|
if (pathMatch[1] === "spam-logs") {
|
|
|
|
res.statusCode = 301;
|
|
|
|
res.setHeader("Location", `/archives/${logId}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (pathMatch) {
|
|
|
|
const log = await this.archives.find(logId);
|
2018-08-01 20:09:51 +03:00
|
|
|
if (!log) return notFound(res);
|
|
|
|
|
|
|
|
res.setHeader("Content-Type", "text/plain; charset=UTF-8");
|
|
|
|
res.end(log.body);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-08-05 00:45:35 +03:00
|
|
|
let retried = false;
|
|
|
|
|
|
|
|
this.server.on("error", async (err: any) => {
|
|
|
|
if (err.code === "EADDRINUSE" && !retried) {
|
|
|
|
console.log("Got EADDRINUSE, retrying in 2 sec...");
|
|
|
|
retried = true;
|
|
|
|
await sleep(2000);
|
|
|
|
this.server.listen(this.configValue("port", DEFAULT_PORT));
|
|
|
|
} else {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-08-01 20:09:51 +03:00
|
|
|
this.server.listen(this.configValue("port", DEFAULT_PORT));
|
|
|
|
}
|
|
|
|
|
|
|
|
async onUnload() {
|
|
|
|
return new Promise(resolve => {
|
|
|
|
this.server.close(() => resolve());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|