import http from "http"; import url from "url"; import { promises as fs } from "fs"; import querystring from "querystring"; import cfg from "../config.json"; import sql from "./inc/sql.mjs"; import lib from "./inc/lib.mjs"; import router from "./inc/router.mjs"; (async () => { await Promise.all((await fs.readdir("./src/inc/routes")) .filter(r => r.endsWith(".mjs")) .map(r => import(`./inc/routes/${r}`))); http.createServer(async (req, res, r) => { const t_start = process.hrtime(); req.url = url.parse(req.url.replace(/(?!^.)(\/+)?$/, '')); req.url.split = req.url.pathname.split("/").slice(1); req.url.qs = querystring.parse(req.url.query); req.post = await new Promise((resolve, _, data = "") => req .on("data", d => void (data += d)) .on("end", () => void resolve(Object.fromEntries(Object.entries(querystring.parse(data)).map(([k, v]) => { try { return [k, decodeURIComponent(v)]; } catch(err) { return [k, v]; } }))))); res.reply = ({ code = 200, type = "text/html", body }) => res.writeHead(code, { "Content-Type": `${type}; charset=utf-8` }).end(body); res.redirect = target => res.writeHead(301, { "Cache-Control": "no-cache, public", "Location": target }).end(); req.cookies = {}; if(req.headers.cookie) { req.headers.cookie.split("; ").forEach(c => { const parts = c.split('='); req.cookies[parts.shift().trim()] = decodeURI(parts.join('=')); }); } req.session = false; if(req.cookies.session) { const user = await sql("user_sessions") .select("user.id", "user.login", "user.user", "user.level", "user_sessions.id as sess_id") .where("user_sessions.session", lib.md5(req.cookies.session)) .leftJoin("user", "user.id", "user_sessions.user_id") .limit(1); if(user.length > 0) { req.session = user[0]; await sql("user_sessions").update("last_used", (Date.now() / 1e3)).where("id", user[0].sess_id); } else { // delete session return res.writeHead(301, { "Cache-Control": "no-cache, public", "Set-Cookie": "session=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT", "Location": req.url.path }).end(); } } !(r = router.routes.getRoute(req.url.pathname, req.method)) ? res.writeHead(404).end(`404 - ${req.method} ${req.url.pathname}`) : await r(req, res); console.log([ `[${(new Date()).toLocaleTimeString()}]`, `${(process.hrtime(t_start)[1] / 1e6).toFixed(2)}ms`, `${req.method} ${res.statusCode}`, req.url.pathname].map(e=>e.toString().padEnd(15)).join("")); }).listen(cfg.websrv.port, () => setTimeout(() => { console.log(`f0ck is listening on port ${cfg.websrv.port}.`); }, 500)); })();