NGU-Web/server/src/analyticsReport.js
Zaldimmar 6289e7203f Links/redirects: /go/ short links with click counts, Plausible and UTM tags (migration 068)
Data > Links/redirects (editors and up) makes short links on our
domain. GET /go/<id> counts the click, reports it to Plausible as a
pageview of /go/<id> (the visitor's browser and address, no key
needed), and redirects (302, no-store) with the link's UTM tags added
to the destination. Unknown ids fall through to the not-found page.
The editor can show a fixed lead-in in the URL ID box (idPrefix).
Vite proxies /go in dev. docs/redirects.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:37:26 -05:00

205 lines
8.4 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
ANALYTICS REPORTS
Plausible's numbers for this site, posted to a Discord channel:
daily yesterday: visitors, pageviews, bounce rate, visit
length, top pages and sources
weekly Mondays: the last 7 days, with the change from the 7
before
Each is switched on in Panel → Site settings → Reports. Both go
out at SEND_HOUR in REPORT_TZ, or as soon after as the server is
up that day; analytics_reports (065) keeps it to one a day.
── Configuration (the ngu-api service environment) ──
PLAUSIBLE_API_KEY a Stats API key (Plausible → Account
settings → API keys)
DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel
settings → Integrations → Webhooks)
PLAUSIBLE_URL default http://127.0.0.1:8000, where the
self-hosted Plausible listens
REPORT_TZ default America/Chicago
Off until the first two are set. The site counted is the hostname
of site.json's url, as in pageMeta.js's analyticsTag.
To send one now (eg. to try the setup), whatever the switches say:
DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly
Setup: docs/analytics-reports.md.
═══════════════════════════════════════════════════════════════ */
import { pathToFileURL } from "node:url";
import { siteFor } from "./pageMeta.js";
export const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null;
const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago";
const SEND_HOUR = 8;
const TICK_MS = 15 * 60 * 1000;
const KINDS = ["daily", "weekly"];
export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL);
/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */
function localNow(now = new Date()) {
const parts = Object.fromEntries(
new Intl.DateTimeFormat("en-US", {
timeZone: REPORT_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hourCycle: "h23",
weekday: "short",
})
.formatToParts(now)
.map((part) => [part.type, part.value]),
);
return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" };
}
/* "2026-10-04" moved by `days`. */
function shift(date, days) {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
/* ── Plausible ─────────────────────────────────────────────── */
async function query(siteId, body) {
const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, {
method: "POST",
headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ site_id: siteId, ...body }),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
return (await res.json()).results ?? [];
}
const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"];
async function totals(siteId, range) {
const [row] = await query(siteId, { metrics: METRICS, date_range: range });
return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0]));
}
async function top(siteId, dimension, range, limit) {
const rows = await query(siteId, {
metrics: ["visitors"],
dimensions: [dimension],
date_range: range,
order_by: [["visitors", "desc"]],
pagination: { limit },
});
return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-";
}
/* ── The message ───────────────────────────────────────────── */
const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
function change(now, before) {
if (!before) return now ? " (new)" : "";
const percent = Math.round(((now - before) / before) * 100);
return ` (${percent >= 0 ? "+" : ""}${percent}%)`;
}
/* The Discord message for `kind` as of `today` (a REPORT_TZ date):
yesterday, or the 7 days ending yesterday. */
export async function buildReport(db, kind, today) {
const siteId = new URL(siteFor(db).url).hostname;
const to = shift(today, -1);
const from = kind === "weekly" ? shift(to, -6) : to;
const range = [from, to];
const limit = kind === "weekly" ? 5 : 3;
const [now, before, pages, sources] = await Promise.all([
totals(siteId, range),
kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null,
top(siteId, "event:page", range, limit),
top(siteId, "visit:source", range, limit),
]);
const vs = (metric) => (before ? change(now[metric], before[metric]) : "");
return {
embeds: [
{
title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`,
fields: [
{ name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true },
{ name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true },
{ name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true },
{ name: "Visit length", value: duration(now.visit_duration), inline: true },
{ name: "Top pages", value: pages },
{ name: "Top sources", value: sources },
],
},
],
};
}
export async function sendReport(db, kind, today = localNow().date) {
const res = await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(await buildReport(db, kind, today)),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
}
/* ── Schedule ──────────────────────────────────────────────── */
export function startAnalyticsReports(db) {
if (!reportsReady()) return;
let running = false;
const tick = async () => {
const { date, hour, monday } = localNow();
if (running || hour < SEND_HOUR) return;
running = true;
try {
const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {};
for (const kind of KINDS) {
if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue;
if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue;
// Marked before sending: a Plausible or Discord failure is
// logged once that day, not every tick.
db.prepare(
`INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?)
ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`,
).run(kind, date);
try {
await sendReport(db, kind, date);
console.log(`analytics ${kind} report sent for ${date}`);
} catch (err) {
console.error(`analytics ${kind} report failed: ${err.message}`);
}
}
} finally {
running = false;
}
};
tick();
setInterval(tick, TICK_MS).unref();
}
/* ── By hand ───────────────────────────────────────────────── */
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const kind = process.argv[2];
if (!KINDS.includes(kind)) {
console.error("usage: node src/analyticsReport.js daily|weekly");
process.exit(1);
}
if (!reportsReady()) {
console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first.");
process.exit(1);
}
const { openDatabase } = await import("./db.js");
const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db");
await sendReport(db, kind);
console.log(`Sent the ${kind} report.`);
}