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')); });