|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Visit Notifier — Polls Cloudflare for new page visits and plays an audio notification. |
| 4 | + * |
| 5 | + * Usage: |
| 6 | + * node scripts/visit-notifier.mjs |
| 7 | + * |
| 8 | + * Environment variables (or .env in project root): |
| 9 | + * SITE_URL — Your deployed site URL (default: https://masterselects.pages.dev) |
| 10 | + * VISITOR_NOTIFY_SECRET — The secret matching your Cloudflare env |
| 11 | + * POLL_INTERVAL_MS — Polling interval in ms (default: 5000) |
| 12 | + * BEEP_FREQUENCY — Beep frequency in Hz (default: 800) |
| 13 | + * BEEP_DURATION — Beep duration in ms (default: 400) |
| 14 | + */ |
| 15 | + |
| 16 | +import { execSync } from 'node:child_process'; |
| 17 | +import { readFileSync } from 'node:fs'; |
| 18 | +import { resolve, dirname } from 'node:path'; |
| 19 | +import { fileURLToPath } from 'node:url'; |
| 20 | + |
| 21 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 22 | +const ROOT = resolve(__dirname, '..'); |
| 23 | + |
| 24 | +// ── Load .env if present ────────────────────────────────────────── |
| 25 | +function loadEnv() { |
| 26 | + try { |
| 27 | + const envPath = resolve(ROOT, '.dev.vars'); |
| 28 | + const content = readFileSync(envPath, 'utf-8'); |
| 29 | + for (const line of content.split('\n')) { |
| 30 | + const trimmed = line.trim(); |
| 31 | + if (!trimmed || trimmed.startsWith('#')) continue; |
| 32 | + const eqIdx = trimmed.indexOf('='); |
| 33 | + if (eqIdx === -1) continue; |
| 34 | + const key = trimmed.slice(0, eqIdx).trim(); |
| 35 | + let value = trimmed.slice(eqIdx + 1).trim(); |
| 36 | + // Strip quotes |
| 37 | + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { |
| 38 | + value = value.slice(1, -1); |
| 39 | + } |
| 40 | + if (!process.env[key]) process.env[key] = value; |
| 41 | + } |
| 42 | + } catch { |
| 43 | + // .dev.vars not found — rely on process.env |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +loadEnv(); |
| 48 | + |
| 49 | +// ── Config ──────────────────────────────────────────────────────── |
| 50 | +const SITE_URL = (process.env.SITE_URL || 'https://masterselects.pages.dev').replace(/\/$/, ''); |
| 51 | +const SECRET = process.env.VISITOR_NOTIFY_SECRET; |
| 52 | +const POLL_MS = parseInt(process.env.POLL_INTERVAL_MS || '5000', 10); |
| 53 | +const BEEP_FREQ = parseInt(process.env.BEEP_FREQUENCY || '800', 10); |
| 54 | +const BEEP_DUR = parseInt(process.env.BEEP_DURATION || '400', 10); |
| 55 | + |
| 56 | +if (!SECRET) { |
| 57 | + console.error('ERROR: VISITOR_NOTIFY_SECRET is not set.'); |
| 58 | + console.error('Set it in .dev.vars or as an environment variable.'); |
| 59 | + process.exit(1); |
| 60 | +} |
| 61 | + |
| 62 | +// ── Audio notification ──────────────────────────────────────────── |
| 63 | +function playBeep() { |
| 64 | + try { |
| 65 | + if (process.platform === 'win32') { |
| 66 | + execSync( |
| 67 | + `powershell -NoProfile -Command "[console]::beep(${BEEP_FREQ},${BEEP_DUR})"`, |
| 68 | + { stdio: 'ignore' }, |
| 69 | + ); |
| 70 | + } else if (process.platform === 'darwin') { |
| 71 | + execSync('afplay /System/Library/Sounds/Glass.aiff', { stdio: 'ignore' }); |
| 72 | + } else { |
| 73 | + // Linux: try paplay, then beep, then printf BEL |
| 74 | + try { |
| 75 | + execSync('paplay /usr/share/sounds/freedesktop/stereo/message-new-instant.oga', { stdio: 'ignore' }); |
| 76 | + } catch { |
| 77 | + try { |
| 78 | + execSync(`beep -f ${BEEP_FREQ} -l ${BEEP_DUR}`, { stdio: 'ignore' }); |
| 79 | + } catch { |
| 80 | + process.stdout.write('\x07'); // terminal bell |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + } catch { |
| 85 | + process.stdout.write('\x07'); // fallback: terminal bell |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +// ── State ───────────────────────────────────────────────────────── |
| 90 | +let lastSeenTs = Date.now(); |
| 91 | +let totalVisits = 0; |
| 92 | + |
| 93 | +// ── Formatting ──────────────────────────────────────────────────── |
| 94 | +function formatVisit(v) { |
| 95 | + const time = new Date(v.ts).toLocaleTimeString('de-DE'); |
| 96 | + const location = [v.city, v.country].filter(Boolean).join(', ') || 'unknown'; |
| 97 | + return ` ${time} ${v.path.padEnd(30)} ${location}`; |
| 98 | +} |
| 99 | + |
| 100 | +// ── Polling ─────────────────────────────────────────────────────── |
| 101 | +async function poll() { |
| 102 | + try { |
| 103 | + const url = `${SITE_URL}/api/visits?secret=${encodeURIComponent(SECRET)}&since=${lastSeenTs}&limit=50`; |
| 104 | + const res = await fetch(url, { |
| 105 | + headers: { 'User-Agent': 'MasterSelects-VisitNotifier/1.0' }, |
| 106 | + }); |
| 107 | + |
| 108 | + if (!res.ok) { |
| 109 | + const text = await res.text(); |
| 110 | + console.error(`[${new Date().toLocaleTimeString()}] API error ${res.status}: ${text.slice(0, 200)}`); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + const data = await res.json(); |
| 115 | + |
| 116 | + if (data.visits && data.visits.length > 0) { |
| 117 | + // Sort oldest first for display |
| 118 | + const sorted = [...data.visits].sort((a, b) => a.ts - b.ts); |
| 119 | + |
| 120 | + for (const visit of sorted) { |
| 121 | + totalVisits++; |
| 122 | + console.log(`\n>>> NEW VISITOR (#${totalVisits}) <<<`); |
| 123 | + console.log(formatVisit(visit)); |
| 124 | + playBeep(); |
| 125 | + } |
| 126 | + |
| 127 | + // Update watermark to newest visit |
| 128 | + const newest = Math.max(...data.visits.map((v) => v.ts)); |
| 129 | + lastSeenTs = newest; |
| 130 | + } |
| 131 | + } catch (err) { |
| 132 | + console.error(`[${new Date().toLocaleTimeString()}] Poll error: ${err.message}`); |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// ── Main ────────────────────────────────────────────────────────── |
| 137 | +console.log('==========================================='); |
| 138 | +console.log(' MasterSelects Visit Notifier'); |
| 139 | +console.log('==========================================='); |
| 140 | +console.log(`Site: ${SITE_URL}`); |
| 141 | +console.log(`Polling: every ${POLL_MS / 1000}s`); |
| 142 | +console.log(`Audio: ${BEEP_FREQ}Hz, ${BEEP_DUR}ms`); |
| 143 | +console.log('-------------------------------------------'); |
| 144 | +console.log('Waiting for visitors...\n'); |
| 145 | + |
| 146 | +// Initial beep to confirm audio works |
| 147 | +playBeep(); |
| 148 | + |
| 149 | +// Poll loop |
| 150 | +setInterval(poll, POLL_MS); |
| 151 | +// Also poll immediately |
| 152 | +poll(); |
0 commit comments