source: Klonkt/src/config/database.js@ 1794fac

main
Last change on this file since 1794fac was 1794fac, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

Pro stats (premium feature #5): referrers + period selector + all-time

Extension of the cookie-free StatsService.

  • DB: stat_referrer (site_id, host, count).
  • StatsService: recordPageview now also counts the external referrer host (Referer header; empty/own-site/invalid skipped, www- normalised). getStats(days) clamps to 7/14/30/90 + returns top-10 referrers (instance-wide) + all-time (pageviews, visitor days).
  • admin-stats route: ?days=7|14|30|90.
  • admin-stats view: period buttons, dynamic labels, Sources section, all-time row.

node --check passed.

Co-Authored-By: Claude <noreply@â€Ļ>

  • Property mode set to 100644
File size: 10.3 KB
Line 
1import Database from 'better-sqlite3';
2import path from 'path';
3import { fileURLToPath } from 'url';
4import fs from 'fs';
5
6const __dirname = path.dirname(fileURLToPath(import.meta.url));
7const dbPath = process.env.DATABASE_PATH || path.join(__dirname, '../../storage/database.sqlite');
8
9// Ensure storage directory exists
10const storageDir = path.dirname(dbPath);
11if (!fs.existsSync(storageDir)) {
12 fs.mkdirSync(storageDir, { recursive: true });
13}
14
15// Initialize database
16const db = new Database(dbPath);
17db.pragma('journal_mode = WAL');
18db.pragma('foreign_keys = ON');
19
20export function initializeDatabase() {
21 const tableExists = db.prepare(`
22 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
23 `).get();
24
25 if (!tableExists) {
26 console.log('🔧 Initializing database schema...');
27 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
28 const schema = fs.readFileSync(schemaPath, 'utf-8');
29 db.exec(schema);
30 console.log('✅ Database initialized with v9-soul schema');
31 }
32
33 // Additive column migrations — safe to run every boot.
34 // SQLite throws if the column already exists; we swallow that.
35 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
36 ensureColumn('sites', 'profile_photo', 'TEXT');
37 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
38 ensureColumn('audio_tracks', 'album', 'TEXT');
39 ensureColumn('users', 'reset_token', 'TEXT');
40 ensureColumn('users', 'reset_token_expires', 'DATETIME');
41 // Google OAuth: koppel een Google-account aan een user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
43 // Read-only/kijk-account: kan alles bekijken maar geen wijzigingen doen.
44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
45 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
46 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'moderate'");
47 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
48 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
49 // Cirkels: mag deze site in cirkels van anderen verschijnen (surfacing opt-out).
50 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
51
52 // EÊn EXPLICIETE primaire/hoofd-site (= de bedrijfs-/labelsite in hub-modus,
53 // de enige site in solo) i.p.v. de fragiele "oudste = hoofd"-conventie die op
54 // 4 plekken gedupliceerd stond. Backfill: markeer de oudste als er nog geen
55 // primaire site is, zodat bestaand gedrag exact behouden blijft.
56 ensureColumn('sites', 'is_primary', 'INTEGER DEFAULT 0');
57 try {
58 const hasPrimary = db.prepare('SELECT 1 FROM sites WHERE is_primary = 1 LIMIT 1').get();
59 if (!hasPrimary) {
60 const oldest = db.prepare('SELECT id FROM sites ORDER BY created_at ASC LIMIT 1').get();
61 if (oldest) db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(oldest.id);
62 }
63 } catch (e) { /* sites-tabel nog leeg/afwezig bij verse init — ensurePrimarySite regelt 't */ }
64
65 // v9 audit additions —————————————————————————————————————————
66 // SEO/social columns the v9 template uses (most live in 001-init.sql already
67 // for fresh DBs but ensureColumn is idempotent for existing DBs).
68 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
69 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
70 ensureColumn('sites', 'publisher_name', 'TEXT');
71 ensureColumn('sites', 'publisher_url', 'TEXT');
72 ensureColumn('sites', 'publisher_logo', 'TEXT');
73 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
74 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
75 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
76 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
77 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
78 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
79 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
80 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
81
82 // Per-post noindex + type
83 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
84 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
85
86 // Statistieken (premium-module) — kale tellers, cookievrij.
87 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // weergaven per post
88 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
89 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-voor-email (premium #2)
90
91 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
92 // idempotent so it's safe to run on every boot regardless of DB age.
93 db.exec(`
94 CREATE TABLE IF NOT EXISTS playlists (
95 id TEXT PRIMARY KEY,
96 site_id TEXT NOT NULL,
97 title TEXT NOT NULL,
98 artist TEXT,
99 year INTEGER,
100 cover_url TEXT,
101 kind TEXT DEFAULT 'album',
102 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
103 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
104 FOREIGN KEY (site_id) REFERENCES sites(id)
105 );
106 CREATE TABLE IF NOT EXISTS playlist_tracks (
107 playlist_id TEXT NOT NULL,
108 track_id TEXT NOT NULL,
109 position INTEGER NOT NULL DEFAULT 0,
110 PRIMARY KEY (playlist_id, track_id),
111 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
112 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
113 );
114 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
115 ON playlist_tracks(playlist_id, position);
116 `);
117
118 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
119 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
120 db.exec(`
121 CREATE TABLE IF NOT EXISTS app_settings (
122 key TEXT PRIMARY KEY,
123 value TEXT,
124 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
125 );
126 `);
127 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
128
129 // ── Statistieken (premium) — cookievrij ─────────────────────
130 // stat_daily: per dag per site het aantal pageviews (kale teller).
131 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
132 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
133 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
134 db.exec(`
135 CREATE TABLE IF NOT EXISTS stat_daily (
136 site_id TEXT NOT NULL,
137 day TEXT NOT NULL,
138 pageviews INTEGER NOT NULL DEFAULT 0,
139 PRIMARY KEY (site_id, day)
140 );
141 CREATE TABLE IF NOT EXISTS stat_visitor_day (
142 site_id TEXT NOT NULL,
143 day TEXT NOT NULL,
144 visitor_hash TEXT NOT NULL,
145 PRIMARY KEY (site_id, day, visitor_hash)
146 );
147 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
148 CREATE TABLE IF NOT EXISTS stat_referrer (
149 site_id TEXT NOT NULL,
150 host TEXT NOT NULL,
151 count INTEGER NOT NULL DEFAULT 0,
152 PRIMARY KEY (site_id, host)
153 );
154 `);
155
156 // ── Cirkels (federatie) ─────────────────────────────────────
157 // Decentrale, asymmetrische verbindingen tussen solo-instances.
158 db.exec(`
159 CREATE TABLE IF NOT EXISTS circle_links (
160 id TEXT PRIMARY KEY,
161 local_site_id TEXT NOT NULL,
162 remote_url TEXT NOT NULL,
163 remote_actor_id TEXT,
164 label TEXT,
165 status TEXT DEFAULT 'active',
166 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
167 last_synced DATETIME,
168 last_error TEXT,
169 UNIQUE(local_site_id, remote_url),
170 FOREIGN KEY (local_site_id) REFERENCES sites(id)
171 );
172 CREATE TABLE IF NOT EXISTS remote_actors (
173 id TEXT PRIMARY KEY,
174 url TEXT UNIQUE NOT NULL,
175 name TEXT,
176 summary TEXT,
177 avatar TEXT,
178 public_key TEXT NOT NULL,
179 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
180 );
181 CREATE TABLE IF NOT EXISTS remote_posts (
182 id TEXT PRIMARY KEY,
183 actor_id TEXT NOT NULL,
184 published DATETIME,
185 title TEXT,
186 summary TEXT,
187 url TEXT,
188 media_json TEXT,
189 raw_json TEXT,
190 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
191 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
192 );
193 `);
194
195 // Tags van de originele post — getoond in de cirkel (comma-separated string).
196 ensureColumn('remote_posts', 'tags', 'TEXT');
197
198 // Nieuwsbrief / mailinglijst (premium). Abonnees per site; double opt-in als SMTP
199 // er is (status 'pending' tot bevestigd), anders single opt-in ('confirmed').
200 // 'unsub' = uitgeschreven. token = confirm/unsubscribe-sleutel (in de e-maillinks).
201 db.exec(`
202 CREATE TABLE IF NOT EXISTS subscribers (
203 id TEXT PRIMARY KEY,
204 site_id TEXT NOT NULL,
205 email TEXT NOT NULL,
206 status TEXT NOT NULL DEFAULT 'pending',
207 source TEXT DEFAULT 'widget',
208 token TEXT NOT NULL,
209 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
210 confirmed_at DATETIME,
211 UNIQUE(site_id, email)
212 );
213 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
214 `);
215
216 // Verstuurde nieuwsbrieven (historie + aantallen).
217 db.exec(`
218 CREATE TABLE IF NOT EXISTS newsletters (
219 id TEXT PRIMARY KEY,
220 site_id TEXT NOT NULL,
221 subject TEXT NOT NULL,
222 body TEXT NOT NULL,
223 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
224 recipient_count INTEGER DEFAULT 0
225 );
226 `);
227
228 // Link-in-bio klikstatistiek (premium #6). Per (site, url) een teller; de
229 // link-in-bio-pagina linkt via /links/go/:i dat de klik telt en doorstuurt.
230 db.exec(`
231 CREATE TABLE IF NOT EXISTS link_clicks (
232 site_id TEXT NOT NULL,
233 url TEXT NOT NULL,
234 clicks INTEGER DEFAULT 0,
235 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
236 PRIMARY KEY (site_id, url)
237 );
238 `);
239}
240
241function ensureColumn(table, column, definition) {
242 try {
243 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
244 console.log(`🔧 Added column ${table}.${column}`);
245 } catch (e) {
246 // "duplicate column name" → already there. Anything else, surface it.
247 if (!/duplicate column/i.test(e.message)) {
248 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
249 }
250 }
251}
252
253export default db;
Note: See TracBrowser for help on using the repository browser.