You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
2.5 KiB
93 lines
2.5 KiB
1 year ago
|
import { Application, Router } from "@oak/mod.ts";
|
||
|
import initDB, { db, IP } from "./database.ts";
|
||
|
import { deviousLick, hash } from "./utils.ts";
|
||
|
import config, { Site } from "./config.ts";
|
||
|
|
||
|
interface Value {
|
||
|
site: string;
|
||
|
id: string;
|
||
|
ip: string;
|
||
|
path: string;
|
||
|
}
|
||
|
|
||
|
export default async function init() {
|
||
|
await initDB();
|
||
|
|
||
|
const router = new Router();
|
||
|
|
||
|
router.post("/add", async (ctx) => {
|
||
|
const value: Value = await ctx.request.body({ type: "json" }).value;
|
||
|
const hashedIP = await hash(value.ip);
|
||
|
const site: Site = (config.sites as Record<string, Site>)[value.site];
|
||
|
|
||
|
if (!site) {
|
||
|
ctx.response.status = 406;
|
||
|
ctx.response.body = "Unknown site!";
|
||
|
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
let ipDB: IP;
|
||
|
|
||
|
await db.use(config.db.namespace, value.site);
|
||
|
|
||
|
try {
|
||
|
ipDB = (await db.select("ip:" + hashedIP))[0] as IP;
|
||
|
} catch {
|
||
|
const geolocation = await deviousLick(value.ip);
|
||
|
|
||
|
await db.create("ip:" + hashedIP, {
|
||
|
location: geolocation,
|
||
|
history: [],
|
||
|
});
|
||
|
|
||
|
ipDB = (await db.select("ip:" + hashedIP))[0] as IP;
|
||
|
}
|
||
|
|
||
|
ipDB.history.push({
|
||
|
timestamp: new Date(),
|
||
|
path: value.path,
|
||
|
});
|
||
|
|
||
|
console.log(`${hashedIP} ${value.path}`);
|
||
|
|
||
|
// deno-lint-ignore no-explicit-any
|
||
|
await db.update(`ip:${hashedIP}`, ipDB as Record<string, any>);
|
||
|
|
||
|
ctx.response.status = 200;
|
||
|
ctx.response.body = "Successfully added request to history!";
|
||
|
});
|
||
|
|
||
|
router.get("/sites", (ctx) => {
|
||
|
ctx.response.status = 200;
|
||
|
ctx.response.type = "application/json";
|
||
|
ctx.response.body = JSON.stringify(config.sites);
|
||
|
});
|
||
|
|
||
|
router.get("/site/:site", (ctx) => {
|
||
|
const siteName: string = ctx.params.site;
|
||
|
const site = (config.sites as Record<string, Site>)[siteName];
|
||
|
|
||
|
ctx.response.status = 200;
|
||
|
ctx.response.type = "application/json";
|
||
|
ctx.response.body = JSON.stringify(site);
|
||
|
});
|
||
|
|
||
|
router.get("/site/:site/analytics", async (ctx) => {
|
||
|
const siteName: string = ctx.params.site;
|
||
|
|
||
|
await db.use(config.db.namespace, siteName);
|
||
|
|
||
|
const database = await db.select("ip");
|
||
|
|
||
|
ctx.response.status = 200;
|
||
|
ctx.response.type = "application/json";
|
||
|
ctx.response.body = JSON.stringify(database);
|
||
|
});
|
||
|
|
||
|
const app = new Application();
|
||
|
app.use(router.routes());
|
||
|
|
||
|
return app;
|
||
|
}
|