v1.13.1-data: links/redirects, captions, partner picks, Plausible reports, migration baseline #28
6 changed files with 254 additions and 1 deletions
|
|
@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
||||||
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service.
|
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service.
|
||||||
- Never run commands against the production server or database unless explicitly asked.
|
- Never run commands against the production server or database unless explicitly asked.
|
||||||
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
|
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
|
||||||
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app.
|
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`).
|
||||||
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
|
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
|
||||||
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
|
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
|
||||||
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.
|
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,8 @@ export const siteSettings = {
|
||||||
text("access_group_viewer"),
|
text("access_group_viewer"),
|
||||||
text("access_group_editor"),
|
text("access_group_editor"),
|
||||||
text("access_group_admin"),
|
text("access_group_admin"),
|
||||||
|
enumeration("report_daily", ["on", "off"]),
|
||||||
|
enumeration("report_weekly", ["on", "off"]),
|
||||||
],
|
],
|
||||||
|
|
||||||
children: [
|
children: [
|
||||||
|
|
|
||||||
203
server/src/analyticsReport.js
Normal file
203
server/src/analyticsReport.js
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
/* ═══════════════════════════════════════════════════════════════
|
||||||
|
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
|
||||||
|
═══════════════════════════════════════════════════════════════ */
|
||||||
|
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
|
import { siteFor } from "./pageMeta.js";
|
||||||
|
|
||||||
|
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.`);
|
||||||
|
}
|
||||||
|
|
@ -45,6 +45,7 @@ import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
|
||||||
import { logSafe, startSessionSweeper } from "./auth.js";
|
import { logSafe, startSessionSweeper } from "./auth.js";
|
||||||
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
||||||
import { startGroupSync } from "./accessGroups.js";
|
import { startGroupSync } from "./accessGroups.js";
|
||||||
|
import { startAnalyticsReports } from "./analyticsReport.js";
|
||||||
import { ENTITIES } from "./admin-schema.js";
|
import { ENTITIES } from "./admin-schema.js";
|
||||||
|
|
||||||
const HOST = process.env.HOST ?? "127.0.0.1";
|
const HOST = process.env.HOST ?? "127.0.0.1";
|
||||||
|
|
@ -241,6 +242,7 @@ app.route("/", pages);
|
||||||
startSessionSweeper(db);
|
startSessionSweeper(db);
|
||||||
startGroupSync(db);
|
startGroupSync(db);
|
||||||
startClipWorker(db);
|
startClipWorker(db);
|
||||||
|
startAnalyticsReports(db);
|
||||||
console.log(`clips ${CLIPS_DIR}`);
|
console.log(`clips ${CLIPS_DIR}`);
|
||||||
|
|
||||||
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
||||||
|
|
|
||||||
19
server/src/migrations/065_analytics_reports.sql
Normal file
19
server/src/migrations/065_analytics_reports.sql
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
-- ═══════════════════════════════════════════════════════════════
|
||||||
|
-- 065 ANALYTICS REPORTS
|
||||||
|
--
|
||||||
|
-- Plausible's numbers posted to Discord (server/src/analyticsReport.js).
|
||||||
|
--
|
||||||
|
-- site_settings.report_daily 'on': yesterday's numbers each morning
|
||||||
|
-- site_settings.report_weekly 'on': last week's each Monday morning
|
||||||
|
-- Blank or 'off': not sent
|
||||||
|
-- analytics_reports the local date each kind was last sent
|
||||||
|
-- for, so a restart doesn't post twice
|
||||||
|
-- ═══════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
ALTER TABLE site_settings ADD COLUMN report_daily TEXT CHECK (report_daily IN ('on', 'off'));
|
||||||
|
ALTER TABLE site_settings ADD COLUMN report_weekly TEXT CHECK (report_weekly IN ('on', 'off'));
|
||||||
|
|
||||||
|
CREATE TABLE analytics_reports (
|
||||||
|
kind TEXT PRIMARY KEY CHECK (kind IN ('daily', 'weekly')),
|
||||||
|
sent_for TEXT NOT NULL
|
||||||
|
) STRICT;
|
||||||
|
|
@ -145,6 +145,33 @@ export const siteSettings = {
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
legend: "Reports",
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
path: "report_daily",
|
||||||
|
label: "Daily analytics report",
|
||||||
|
widget: "select",
|
||||||
|
options: [
|
||||||
|
["on", "On"],
|
||||||
|
["off", "Off"],
|
||||||
|
],
|
||||||
|
blankLabel: "Default: off",
|
||||||
|
help: "Yesterday's visitors, pageviews and top pages from Plausible, posted to Discord each morning. Needs PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL on the server (server/src/analyticsReport.js).",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "report_weekly",
|
||||||
|
label: "Weekly analytics report",
|
||||||
|
widget: "select",
|
||||||
|
options: [
|
||||||
|
["on", "On"],
|
||||||
|
["off", "Off"],
|
||||||
|
],
|
||||||
|
blankLabel: "Default: off",
|
||||||
|
help: "The last 7 days, with the change from the week before, posted to Discord each Monday morning.",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
legend: "Notices",
|
legend: "Notices",
|
||||||
fields: [
|
fields: [
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue