From 9d34f3570e5dcb60686832952d7830f8873b05da Mon Sep 17 00:00:00 2001 From: ChrisChrome Date: Sun, 15 Dec 2024 16:20:16 -0700 Subject: [PATCH] Add basic, anonymous analytics --- index.js | 38 ++++++++++++++++++++++++++ migrations/004_gen_analytics_table.sql | 4 +++ 2 files changed, 42 insertions(+) create mode 100644 migrations/004_gen_analytics_table.sql diff --git a/index.js b/index.js index 7148e84..dde74df 100644 --- a/index.js +++ b/index.js @@ -84,6 +84,30 @@ app.set('views', __dirname + '/views'); // Static files app.use(express.static('public')); +const addAnalytic = (tag) => { + db.get("SELECT * FROM analytics WHERE tag = ?", [tag], (err, row) => { + if (err) { + console.error('Error checking analytics:', err); + } + if (!row) { + db.run("INSERT INTO analytics (tag, count) VALUES (?, 1)", [tag], (err) => { + if (err) console.error('Error creating analytics:', err); + }); + } else { + db.run("UPDATE analytics SET count = count + 1 WHERE tag = ?", [tag], (err) => { + if (err) console.error('Error updating analytics:', err); + }); + } + }); +} + +app.use((req,res,next) => { + if (req.path.startsWith("/api/v1")) { + addAnalytic("apiCalls"); + }; + next(); +}) + // Admin routes // admin/logout @@ -513,6 +537,17 @@ app.get("/discord", (req, res) => { }); }); +app.get("/analytics", (req, res) => { + db.all("SELECT * FROM analytics", (err, rows) => { + if (err) { + console.error('Error getting analytics:', err); + res.status(500).send('Internal server error'); + return; + } + res.json(rows); + }); +}); + // Query to get a route app.get('/api/v1/route/:apiKey/:ani/:number', (req, res) => { const apiKey = req.params.apiKey; @@ -533,6 +568,8 @@ app.get('/api/v1/route/:apiKey/:ani/:number', (req, res) => { // Check if the ANI is within the block range // If it is, return `local` console.log(`New Call: ${ani} -> ${number}`); + // incriment estCallsMade analytics + addAnalytic("estCallsMade"); if (ani >= row.block_start && ani <= row.block_start + row.block_length) { res.status(200).send('local'); } else { @@ -564,6 +601,7 @@ app.get('/api/v1', (req, res) => { // Backwards compatibility with TandmX cause // Check if the ANI is within the block range // If it is, return `local` console.log(`New Call: ${ani} -> ${number}`); + addAnalytic("estCallsMade"); if (ani >= row.block_start && ani <= row.block_start + row.block_length) { res.status(200).send('local'); } else { diff --git a/migrations/004_gen_analytics_table.sql b/migrations/004_gen_analytics_table.sql new file mode 100644 index 0000000..2fdc65c --- /dev/null +++ b/migrations/004_gen_analytics_table.sql @@ -0,0 +1,4 @@ +CREATE TABLE IF NOT EXISTS analytics ( + tag TEXT NOT NULL PRIMARY KEY, + count INTEGER NOT NULL DEFAULT 0 +); \ No newline at end of file