| [834bcc3] | 1 | // StatsService — cookie-free statistics (premium module).
|
|---|
| [d549549] | 2 | //
|
|---|
| [834bcc3] | 3 | // Counters: posts.view_count, audio_tracks.play_count, and per day/site the number
|
|---|
| 4 | // of pageviews (stat_daily) + unique visitors (stat_visitor_day).
|
|---|
| [d549549] | 5 | //
|
|---|
| [834bcc3] | 6 | // Unique visitors WITHOUT cookies: a sha256 of IP+UA+daily-salt. The salt rotates
|
|---|
| 7 | // every day and is never stored longer → you cannot track someone across days,
|
|---|
| 8 | // and the raw IP is never persisted. No persistent identifier, no consent
|
|---|
| 9 | // banner required (Plausible/Fathom approach).
|
|---|
| [d549549] | 10 |
|
|---|
| 11 | import crypto from 'node:crypto';
|
|---|
| 12 | import db from '../config/database.js';
|
|---|
| 13 | import { getSetting, setSetting } from './SettingsService.js';
|
|---|
| 14 |
|
|---|
| 15 | function today() {
|
|---|
| 16 | return new Date().toISOString().slice(0, 10); // YYYY-MM-DD (UTC)
|
|---|
| 17 | }
|
|---|
| 18 |
|
|---|
| [834bcc3] | 19 | // Daily rotating salt (cached in process, persisted in app_settings so that
|
|---|
| 20 | // a restart within the same day reuses the same salt).
|
|---|
| [d549549] | 21 | let _salt = null, _saltDay = null;
|
|---|
| 22 | function dailySalt() {
|
|---|
| 23 | const d = today();
|
|---|
| 24 | if (_salt && _saltDay === d) return _salt;
|
|---|
| 25 | let stored = getSetting('stat_salt', null);
|
|---|
| 26 | if (!stored || getSetting('stat_salt_day', null) !== d) {
|
|---|
| 27 | stored = crypto.randomBytes(16).toString('hex');
|
|---|
| 28 | setSetting('stat_salt', stored);
|
|---|
| 29 | setSetting('stat_salt_day', d);
|
|---|
| 30 | }
|
|---|
| 31 | _salt = stored; _saltDay = d;
|
|---|
| 32 | return stored;
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | function visitorHash(req) {
|
|---|
| 36 | const ip = (req && (req.ip || (req.socket && req.socket.remoteAddress))) || '';
|
|---|
| 37 | const ua = (req && req.headers && req.headers['user-agent']) || '';
|
|---|
| 38 | return crypto.createHash('sha256').update(dailySalt() + '|' + ip + '|' + ua).digest('hex').slice(0, 32);
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| [834bcc3] | 41 | // Don't count the owner/admin — otherwise you inflate your own numbers.
|
|---|
| [d549549] | 42 | function isOperator(req) {
|
|---|
| 43 | const u = req && req.session && req.session.user;
|
|---|
| 44 | return !!(u && (u.role === 'god' || u.role === 'admin'));
|
|---|
| 45 | }
|
|---|
| 46 |
|
|---|
| [834bcc3] | 47 | // Skip known bots/crawlers + link-preview fetchers + scripts so they don't inflate
|
|---|
| 48 | // view/visitor-day counts. Empty UA = almost always automated.
|
|---|
| [bb82e7f] | 49 | const BOT_RE = /bot|crawl|spider|slurp|mediapartners|bingpreview|facebookexternalhit|whatsapp|telegram|discord|twitter|linkedin|embedly|pinterest|redditbot|applebot|petalbot|yandex|baidu|duckduckbot|semrush|ahrefs|mj12|dotbot|uptimerobot|pingdom|statuscake|headless|lighthouse|gptbot|claude|ccbot|perplexity|bytespider|amazonbot|googleother|google-read-aloud|python-requests|scrapy|curl|wget|axios|node-fetch|go-http|java\/|okhttp|libwww|httpclient/i;
|
|---|
| 50 | function isBot(req) {
|
|---|
| 51 | const ua = (req && req.headers && req.headers['user-agent']) || '';
|
|---|
| [834bcc3] | 52 | if (!ua) return true; // empty UA = script/bot
|
|---|
| [bb82e7f] | 53 | return BOT_RE.test(ua);
|
|---|
| 54 | }
|
|---|
| 55 |
|
|---|
| [834bcc3] | 56 | // Lazy prepares — tables only exist after initializeDatabase(); this module is
|
|---|
| 57 | // imported before that call.
|
|---|
| [d549549] | 58 | let _s = null;
|
|---|
| 59 | function stmts() {
|
|---|
| 60 | if (_s) return _s;
|
|---|
| 61 | _s = {
|
|---|
| 62 | bumpDaily: db.prepare(`
|
|---|
| 63 | INSERT INTO stat_daily (site_id, day, pageviews) VALUES (?, ?, 1)
|
|---|
| 64 | ON CONFLICT(site_id, day) DO UPDATE SET pageviews = pageviews + 1
|
|---|
| 65 | `),
|
|---|
| 66 | addVisitor: db.prepare('INSERT OR IGNORE INTO stat_visitor_day (site_id, day, visitor_hash) VALUES (?, ?, ?)'),
|
|---|
| 67 | bumpPost: db.prepare('UPDATE posts SET view_count = COALESCE(view_count, 0) + 1 WHERE id = ?'),
|
|---|
| 68 | bumpTrack: db.prepare('UPDATE audio_tracks SET play_count = COALESCE(play_count, 0) + 1 WHERE id = ?'),
|
|---|
| [1794fac] | 69 | bumpReferrer: db.prepare(`
|
|---|
| 70 | INSERT INTO stat_referrer (site_id, host, count) VALUES (?, ?, 1)
|
|---|
| 71 | ON CONFLICT(site_id, host) DO UPDATE SET count = count + 1
|
|---|
| 72 | `),
|
|---|
| [d549549] | 73 | };
|
|---|
| 74 | return _s;
|
|---|
| 75 | }
|
|---|
| 76 |
|
|---|
| [834bcc3] | 77 | // External referrer host from the Referer header (pro stats #5). Empty/own-site/
|
|---|
| 78 | // invalid referrers are skipped → only genuine external sources are counted.
|
|---|
| [1794fac] | 79 | function recordReferrer(siteId, req) {
|
|---|
| 80 | try {
|
|---|
| 81 | const ref = req && req.headers && (req.headers.referer || req.headers.referrer);
|
|---|
| 82 | if (!ref) return;
|
|---|
| 83 | const host = new URL(ref).host.replace(/^www\./, '').toLowerCase();
|
|---|
| 84 | if (!host) return;
|
|---|
| 85 | const own = ((req.headers && req.headers.host) || '').replace(/^www\./, '').toLowerCase();
|
|---|
| [834bcc3] | 86 | if (host === own) return; // internal navigation does not count as a source
|
|---|
| [1794fac] | 87 | stmts().bumpReferrer.run(siteId, host.slice(0, 120));
|
|---|
| [834bcc3] | 88 | } catch { /* not a valid referrer URL → skip */ }
|
|---|
| [1794fac] | 89 | }
|
|---|
| 90 |
|
|---|
| [d549549] | 91 | export function recordPageview(siteId, req) {
|
|---|
| [bb82e7f] | 92 | if (!siteId || isOperator(req) || isBot(req)) return;
|
|---|
| [d549549] | 93 | try {
|
|---|
| 94 | const d = today();
|
|---|
| 95 | stmts().bumpDaily.run(siteId, d);
|
|---|
| 96 | stmts().addVisitor.run(siteId, d, visitorHash(req));
|
|---|
| [1794fac] | 97 | recordReferrer(siteId, req);
|
|---|
| [834bcc3] | 98 | } catch { /* stats must never break a request */ }
|
|---|
| [d549549] | 99 | }
|
|---|
| 100 |
|
|---|
| 101 | export function recordPostView(post, req) {
|
|---|
| [bb82e7f] | 102 | if (!post || !post.id || isOperator(req) || isBot(req)) return;
|
|---|
| [d549549] | 103 | try {
|
|---|
| 104 | stmts().bumpPost.run(post.id);
|
|---|
| 105 | recordPageview(post.site_id, req);
|
|---|
| 106 | } catch {}
|
|---|
| 107 | }
|
|---|
| 108 |
|
|---|
| 109 | export function recordPlay(trackId) {
|
|---|
| 110 | if (!trackId) return;
|
|---|
| 111 | try { stmts().bumpTrack.run(trackId); } catch {}
|
|---|
| 112 | }
|
|---|
| 113 |
|
|---|
| [834bcc3] | 114 | // Instance-wide statistics (solo = the site, hub = all sites combined).
|
|---|
| [d549549] | 115 | export function getStats(days = 14) {
|
|---|
| [1794fac] | 116 | days = [7, 14, 30, 90].includes(Number(days)) ? Number(days) : 14;
|
|---|
| [d549549] | 117 | const pvMap = Object.fromEntries(
|
|---|
| 118 | db.prepare('SELECT day, SUM(pageviews) AS pv FROM stat_daily GROUP BY day').all().map((r) => [r.day, r.pv]),
|
|---|
| 119 | );
|
|---|
| 120 | const visMap = Object.fromEntries(
|
|---|
| 121 | db.prepare('SELECT day, COUNT(*) AS v FROM stat_visitor_day GROUP BY day').all().map((r) => [r.day, r.v]),
|
|---|
| 122 | );
|
|---|
| 123 | const series = [];
|
|---|
| 124 | for (let i = days - 1; i >= 0; i--) {
|
|---|
| 125 | const dt = new Date();
|
|---|
| 126 | dt.setUTCDate(dt.getUTCDate() - i);
|
|---|
| 127 | const d = dt.toISOString().slice(0, 10);
|
|---|
| 128 | series.push({ day: d, pageviews: pvMap[d] || 0, visitors: visMap[d] || 0 });
|
|---|
| 129 | }
|
|---|
| 130 | const totals = {
|
|---|
| [834bcc3] | 131 | pageviews: series.reduce((s, r) => s + r.pageviews, 0), // last N days
|
|---|
| 132 | visitors: series.reduce((s, r) => s + r.visitors, 0), // sum of daily uniques (cookieless has no alternative)
|
|---|
| [d549549] | 133 | plays: db.prepare('SELECT COALESCE(SUM(play_count), 0) AS n FROM audio_tracks').get().n,
|
|---|
| 134 | postViews: db.prepare('SELECT COALESCE(SUM(view_count), 0) AS n FROM posts').get().n,
|
|---|
| 135 | };
|
|---|
| 136 | const topPosts = db.prepare(`
|
|---|
| 137 | SELECT title, slug, COALESCE(view_count, 0) AS views FROM posts
|
|---|
| 138 | WHERE status = 'published' ORDER BY view_count DESC, published_at DESC LIMIT 5
|
|---|
| 139 | `).all();
|
|---|
| 140 | const topTracks = db.prepare(`
|
|---|
| 141 | SELECT title, COALESCE(play_count, 0) AS plays FROM audio_tracks
|
|---|
| 142 | ORDER BY play_count DESC LIMIT 5
|
|---|
| 143 | `).all();
|
|---|
| [834bcc3] | 144 | // Top external sources (pro #5) — aggregated instance-wide per host.
|
|---|
| [1794fac] | 145 | let referrers = [];
|
|---|
| 146 | try {
|
|---|
| 147 | referrers = db.prepare(
|
|---|
| 148 | 'SELECT host, SUM(count) AS n FROM stat_referrer GROUP BY host ORDER BY n DESC LIMIT 10'
|
|---|
| 149 | ).all();
|
|---|
| 150 | } catch { referrers = []; }
|
|---|
| [834bcc3] | 151 | // All-time totals (cookieless unique visitors = sum of daily uniques).
|
|---|
| [1794fac] | 152 | const allTime = {
|
|---|
| 153 | pageviews: db.prepare('SELECT COALESCE(SUM(pageviews),0) AS n FROM stat_daily').get().n,
|
|---|
| 154 | visitorDays: db.prepare('SELECT COUNT(*) AS n FROM stat_visitor_day').get().n,
|
|---|
| 155 | };
|
|---|
| 156 | return { totals, series, topPosts, topTracks, referrers, allTime, days };
|
|---|
| [d549549] | 157 | }
|
|---|