From fb633ba64f3827df0b970663e21921cd0fef52ec Mon Sep 17 00:00:00 2001 From: Flummi Date: Thu, 25 Apr 2019 18:00:47 +0000 Subject: [PATCH] router, api and stuff --- src/inc/cfg.mjs | 58 ---------------------------- src/inc/router.mjs | 22 +++++++++++ src/inc/routes/api.mjs | 79 ++++++++++++++++++++++++++++++++++++++ src/inc/routes/inc/api.mjs | 16 ++++++++ src/inc/routes/index.mjs | 5 +++ src/inc/trigger/debug.mjs | 11 +++--- src/index.mjs | 7 ++-- src/websrv.mjs | 14 +++++++ 8 files changed, 145 insertions(+), 67 deletions(-) delete mode 100644 src/inc/cfg.mjs create mode 100644 src/inc/router.mjs create mode 100644 src/inc/routes/api.mjs create mode 100644 src/inc/routes/inc/api.mjs create mode 100644 src/inc/routes/index.mjs create mode 100644 src/websrv.mjs diff --git a/src/inc/cfg.mjs b/src/inc/cfg.mjs deleted file mode 100644 index 322342e..0000000 --- a/src/inc/cfg.mjs +++ /dev/null @@ -1,58 +0,0 @@ -import sql from "./sql"; - -let cfg = { - client: {}, - main: {}, - websrv: {}, - trigger: {} -}; -let admins = []; - -const read = () => new Promise((resolve, reject) => { - sql.query("select * from cfg").then(rows => { - for (let row in rows) { - cfg[rows[row].class][rows[row].key] = { - val: ((type, value) => { - switch (type) { - case "string": - return value; - case "int": - return parseInt(value); - case "bool": - return value === "true"; - case "json": - return JSON.parse(value); - } - })(rows[row].type, rows[row].value), - hidden: rows[row].hidden === 1, - type: rows[row].type - } - } - loadAdmins().then(() => resolve()); - }) - .catch(err => { - reject("no cfg"); - }) -}); - -export const loadAdmins = () => new Promise((resolve, reject) => { - admins = []; - sql.query(`select * from admins`) - .then(rows => { - rows.forEach(row => { - admins.push({ - id: row.id, - prefix: row.prefix, - account: row.account, - network: row.network, - level: row.level - }); - }); - resolve(); - }) - .catch(err => { - reject("keine Admins vorhanden"); - }); -}); - -export { cfg, read, admins }; diff --git a/src/inc/router.mjs b/src/inc/router.mjs new file mode 100644 index 0000000..4f2c899 --- /dev/null +++ b/src/inc/router.mjs @@ -0,0 +1,22 @@ +class Router { + constructor() { + this.routes = new Map(); + }; + route(method, args) { + this.routes.set(args[0], { method: method, f: args[1] }); + console.info("route set", method, args[0]); + }; + get() { + this.route("GET", arguments); + }; + post() { + this.route("POST", arguments); + }; +}; +const router = new Router(); +export default router; +export const routes = router.routes; + +Map.prototype.getRegex = function(path, method, tmp) { + return (!(tmp = [...this.entries()].filter(r => r[0].exec(path) && r[1].method.includes(method))[0])) ? false : tmp[1].f; +}; diff --git a/src/inc/routes/api.mjs b/src/inc/routes/api.mjs new file mode 100644 index 0000000..9db2859 --- /dev/null +++ b/src/inc/routes/api.mjs @@ -0,0 +1,79 @@ +import router from "../router"; +import sql from "../sql"; +import cfg from "../../../config.json"; + +import { mimes, queries } from "./inc/api"; + +router.get(/^\/api$/, (req, res) => { + res.end("api lol"); +}); + +router.get(/^\/api\/random(\/user\/.+|\/image|\/video|\/audio|\/)?$/, async (req, res) => { + const db = await sql; + let q = queries.random.main; + let args = []; + + res.writeHead(200, { 'Content-Type': 'text/html' }); + + if(req.url.split[2] === "user") { + q += queries.random.where("username like ?"); + args.push(req.url.split[3] || "flummi"); + } + else + q += queries.random.where(mimes[req.url.split[2]] ? mimes[req.url.split[2]].map(mime => `mime = "${mime}"`).join(" or ") : null); + + db.query(q, args) + .then(rows => { + res.end(JSON.stringify(rows.length > 0 ? rows[0] : []), 'utf-8'); + }).catch(err => res.end(JSON.stringify( err ), 'utf-8')); +}); + +router.get(/^\/api\/p(\/[0-9]+|\/)?(\/[0-9]+)?\/?$/, async (req, res) => { + const db = await sql; + const id = parseInt(req.url.split[2]) || 99999999; + const eps = Math.min(parseInt(req.url.split[3]) || 100, 200); + db.query("select * from f0ck.items where id < ? order by id desc limit ?", [id, eps]) + .then(rows => { + let items = { + "items": [], + "last": id + }; + rows.forEach((e,i,a) => { + items.items.push({ + "id": e.id, + "mime": e.mime + }); + items.last = e.id; + }); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(JSON.stringify(items), 'utf-8'); + }).catch(err => res.end(JSON.stringify( err ), 'utf-8')); +}); + +router.get(/^\/api\/item\/[0-9]+$/, async (req, res) => { + const db = await sql; + db.query(queries.item, Array(3).fill(req.url.split[2])) + .then(rows => { + const data = rows[0].length > 0 ? { + ...rows[0][0], ...{ + thumb: `${cfg.main.url}/t/${rows[0][0].id}.png`, + next: rows[1].length ? rows[1][0].id : null, + prev: rows[2].length ? rows[2][0].id : null, + } + } : { + error: true + }; + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(JSON.stringify(data), 'utf-8'); + }).catch(err => res.end(JSON.stringify( err ), 'utf-8')); +}); + +router.get(/^\/api\/user\/.*(\/[0-9]+)?$/, async (req, res) => { + const db = await sql; + const user = req.url.split[2]; + const eps = Math.min(req.url.split[3] || 50, 50); + db.query(queries.user, [ user, eps ]) + .then(rows => { + res.end(JSON.stringify(rows.length > 0 ? rows : []), 'utf-8'); + }).catch(err => res.end(JSON.stringify( err ), 'utf-8')); +}); diff --git a/src/inc/routes/inc/api.mjs b/src/inc/routes/inc/api.mjs new file mode 100644 index 0000000..5374000 --- /dev/null +++ b/src/inc/routes/inc/api.mjs @@ -0,0 +1,16 @@ +export const mimes = { + image: [ "image/png", "image/gif", "image/jpeg" ], + video: [ "video/webm", "video/mp4", "video/quicktime" ], + audio: [ "audio/mpeg", "audio/flac", "audio/x-flac", "audio/ogg" ] +}; + +export const queries = { + random: { + main: "select id, mime, size, username, userchannel, usernetwork, stamp, dest, src from f0ck.items ", + where: where => `${where?`where ${where}`:""} order by rand() limit 1` + }, + item: "select id, mime, size, src, stamp, userchannel, username, usernetwork from f0ck.items where id = ? limit 1;" + + "select id from f0ck.items where id = (select min(id) from f0ck.items where id > ?);" + + "select id from f0ck.items where id = (select max(id) from f0ck.items where id < ?)", + user: "select id, mime, size, src, stamp, userchannel, username, usernetwork from f0ck.items where username = ? limit ?" +}; diff --git a/src/inc/routes/index.mjs b/src/inc/routes/index.mjs new file mode 100644 index 0000000..bb2f52b --- /dev/null +++ b/src/inc/routes/index.mjs @@ -0,0 +1,5 @@ +import router from "../router"; + +router.get(/^\/$/, (req, res) => { + res.end("index lol"); +}); diff --git a/src/inc/trigger/debug.mjs b/src/inc/trigger/debug.mjs index ea9e5dc..d2df426 100644 --- a/src/inc/trigger/debug.mjs +++ b/src/inc/trigger/debug.mjs @@ -1,4 +1,4 @@ -import { admins, getLevel } from "../admin"; +import { admins } from "../admin"; import vm from "vm"; const maxoutput = 1000; @@ -19,15 +19,14 @@ export default bot => bot._trigger.set("sandbox_debug", new bot.trigger({ context.admins = admins; context.e = e; context.bot = bot; - context.level = getLevel; let output = vm.runInContext(args, vm.createContext(context)); if (typeof output !== undefined && output) { output = JSON.stringify(output); - if (output.length > maxoutput) - return e.reply(`holy fuck, Ausgabe wäre viel zu lang! (${output.length} Zeichen :DDDDDD)`); - else - return e.reply(output); + return r.reply(output.length > maxoutput ? `holy fuck, Ausgabe wäre viel zu lang! (${output.length} Zeichen :DDDDDD)` : output); } + else + e.reply("false lol"); + } catch (err) { e.reply(err.message); diff --git a/src/index.mjs b/src/index.mjs index 0871b03..5aebdc3 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -1,13 +1,14 @@ import cfg from "../config.json"; -import sql from "./inc/sql"; import { cuffeo } from "cuffeo"; import triggers from "./inc/trigger"; import events from "./inc/events"; +import "./websrv"; + (async () => { // Chatbots - const self = { + /*const self = { _trigger: new Map(), trigger: function trigger(args) { this.call = args.call; @@ -21,7 +22,7 @@ import events from "./inc/events"; bot: new cuffeo(cfg.clients) }; triggers.forEach(mod => mod(self)); - events.forEach(event => event(self)); + events.forEach(event => event(self));*/ // })(); diff --git a/src/websrv.mjs b/src/websrv.mjs new file mode 100644 index 0000000..b0e63bf --- /dev/null +++ b/src/websrv.mjs @@ -0,0 +1,14 @@ +import http from "http"; +import url from "url"; + +import "./inc/routes/index"; +import "./inc/routes/api"; + +import { routes } from "./inc/router"; + +http.createServer((req, res, r, uri = url.parse(req.url)) => { + req.url = uri; + req.url.split = uri.pathname.split("/"); + req.url.split.shift(); + (!(r = routes.getRegex(req.url.pathname, req.method)) ? res.end(`404 - ${req.url.pathname}`) : r(req, res)) +}).listen(1499);