source: Klonkt/src/config/database.js@ 628056f

main
Last change on this file since 628056f was 9a34d31, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

fix(notifications): table renamed to user_notifications (collision with stale table)

Older DBs still have an unused 'notifications' table (different schema, no
read column) -> CREATE TABLE IF NOT EXISTS became a no-op and the index on
read crashed the boot (demo + demohub in crash loop). Table + queries now
use user_notifications.

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

  • Property mode set to 100644
File size: 12.8 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 // Persoonlijke interface-taal (nl|en|de). Null = volg de standaard (site/env/browser).
46 ensureColumn('users', 'lang', 'TEXT');
47 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
48 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'moderate'");
49 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
50 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
51 // Cirkels: mag deze site in cirkels van anderen verschijnen (surfacing opt-out).
52 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
53
54 // EÊn EXPLICIETE primaire/hoofd-site (= de bedrijfs-/labelsite in hub-modus,
55 // de enige site in solo) i.p.v. de fragiele "oudste = hoofd"-conventie die op
56 // 4 plekken gedupliceerd stond. Backfill: markeer de oudste als er nog geen
57 // primaire site is, zodat bestaand gedrag exact behouden blijft.
58 ensureColumn('sites', 'is_primary', 'INTEGER DEFAULT 0');
59 try {
60 const hasPrimary = db.prepare('SELECT 1 FROM sites WHERE is_primary = 1 LIMIT 1').get();
61 if (!hasPrimary) {
62 const oldest = db.prepare('SELECT id FROM sites ORDER BY created_at ASC LIMIT 1').get();
63 if (oldest) db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(oldest.id);
64 }
65 } catch (e) { /* sites-tabel nog leeg/afwezig bij verse init — ensurePrimarySite regelt 't */ }
66
67 // v9 audit additions —————————————————————————————————————————
68 // SEO/social columns the v9 template uses (most live in 001-init.sql already
69 // for fresh DBs but ensureColumn is idempotent for existing DBs).
70 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
71 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
72 ensureColumn('sites', 'publisher_name', 'TEXT');
73 ensureColumn('sites', 'publisher_url', 'TEXT');
74 ensureColumn('sites', 'publisher_logo', 'TEXT');
75 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
76 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
77 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
78 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
79 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
80 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
81 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
82 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
83
84 // Per-post noindex + type
85 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
86 ensureColumn('posts', 'publish_at', 'DATETIME'); // release-planning (premium #3): geplande go-live
87 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
88 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
89
90 // Statistieken (premium-module) — kale tellers, cookievrij.
91 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // weergaven per post
92 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
93 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-voor-email (premium #2)
94 ensureColumn('audio_tracks', 'credit', 'TEXT'); // eigenaar/credit (copyright-houder)
95 ensureColumn('audio_tracks', 'license', 'TEXT'); // licentie (bv. "CC BY 4.0", "Alle rechten voorbehouden")
96 ensureColumn('audio_tracks', 'link_spotify', 'TEXT'); // "open in"-links per track
97 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
98 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
99
100 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
101 // idempotent so it's safe to run on every boot regardless of DB age.
102 db.exec(`
103 CREATE TABLE IF NOT EXISTS playlists (
104 id TEXT PRIMARY KEY,
105 site_id TEXT NOT NULL,
106 title TEXT NOT NULL,
107 artist TEXT,
108 year INTEGER,
109 cover_url TEXT,
110 kind TEXT DEFAULT 'album',
111 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
112 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
113 FOREIGN KEY (site_id) REFERENCES sites(id)
114 );
115 CREATE TABLE IF NOT EXISTS playlist_tracks (
116 playlist_id TEXT NOT NULL,
117 track_id TEXT NOT NULL,
118 position INTEGER NOT NULL DEFAULT 0,
119 PRIMARY KEY (playlist_id, track_id),
120 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
121 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
122 );
123 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
124 ON playlist_tracks(playlist_id, position);
125 `);
126
127 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
128 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
129 db.exec(`
130 CREATE TABLE IF NOT EXISTS app_settings (
131 key TEXT PRIMARY KEY,
132 value TEXT,
133 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
134 );
135 `);
136 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
137
138 // ── Statistieken (premium) — cookievrij ─────────────────────
139 // stat_daily: per dag per site het aantal pageviews (kale teller).
140 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
141 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
142 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
143 db.exec(`
144 CREATE TABLE IF NOT EXISTS stat_daily (
145 site_id TEXT NOT NULL,
146 day TEXT NOT NULL,
147 pageviews INTEGER NOT NULL DEFAULT 0,
148 PRIMARY KEY (site_id, day)
149 );
150 CREATE TABLE IF NOT EXISTS stat_visitor_day (
151 site_id TEXT NOT NULL,
152 day TEXT NOT NULL,
153 visitor_hash TEXT NOT NULL,
154 PRIMARY KEY (site_id, day, visitor_hash)
155 );
156 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
157 CREATE TABLE IF NOT EXISTS stat_referrer (
158 site_id TEXT NOT NULL,
159 host TEXT NOT NULL,
160 count INTEGER NOT NULL DEFAULT 0,
161 PRIMARY KEY (site_id, host)
162 );
163 `);
164
165 // ── Cirkels (federatie) ─────────────────────────────────────
166 // Decentrale, asymmetrische verbindingen tussen solo-instances.
167 db.exec(`
168 CREATE TABLE IF NOT EXISTS circle_links (
169 id TEXT PRIMARY KEY,
170 local_site_id TEXT NOT NULL,
171 remote_url TEXT NOT NULL,
172 remote_actor_id TEXT,
173 label TEXT,
174 status TEXT DEFAULT 'active',
175 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
176 last_synced DATETIME,
177 last_error TEXT,
178 UNIQUE(local_site_id, remote_url),
179 FOREIGN KEY (local_site_id) REFERENCES sites(id)
180 );
181 CREATE TABLE IF NOT EXISTS remote_actors (
182 id TEXT PRIMARY KEY,
183 url TEXT UNIQUE NOT NULL,
184 name TEXT,
185 summary TEXT,
186 avatar TEXT,
187 public_key TEXT NOT NULL,
188 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
189 );
190 CREATE TABLE IF NOT EXISTS remote_posts (
191 id TEXT PRIMARY KEY,
192 actor_id TEXT NOT NULL,
193 published DATETIME,
194 title TEXT,
195 summary TEXT,
196 url TEXT,
197 media_json TEXT,
198 raw_json TEXT,
199 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
200 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
201 );
202 `);
203
204 // Tags van de originele post — getoond in de cirkel (comma-separated string).
205 ensureColumn('remote_posts', 'tags', 'TEXT');
206
207 // Nieuwsbrief / mailinglijst (premium). Abonnees per site; double opt-in als SMTP
208 // er is (status 'pending' tot bevestigd), anders single opt-in ('confirmed').
209 // 'unsub' = uitgeschreven. token = confirm/unsubscribe-sleutel (in de e-maillinks).
210 db.exec(`
211 CREATE TABLE IF NOT EXISTS subscribers (
212 id TEXT PRIMARY KEY,
213 site_id TEXT NOT NULL,
214 email TEXT NOT NULL,
215 status TEXT NOT NULL DEFAULT 'pending',
216 source TEXT DEFAULT 'widget',
217 token TEXT NOT NULL,
218 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
219 confirmed_at DATETIME,
220 UNIQUE(site_id, email)
221 );
222 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
223 `);
224
225 // Verstuurde nieuwsbrieven (historie + aantallen).
226 db.exec(`
227 CREATE TABLE IF NOT EXISTS newsletters (
228 id TEXT PRIMARY KEY,
229 site_id TEXT NOT NULL,
230 subject TEXT NOT NULL,
231 body TEXT NOT NULL,
232 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
233 recipient_count INTEGER DEFAULT 0
234 );
235 `);
236
237 // Show-agenda (premium #8): tourdata/optredens per site.
238 db.exec(`
239 CREATE TABLE IF NOT EXISTS shows (
240 id TEXT PRIMARY KEY,
241 site_id TEXT NOT NULL,
242 date TEXT NOT NULL,
243 time TEXT,
244 city TEXT NOT NULL,
245 venue TEXT,
246 country TEXT,
247 ticket_url TEXT,
248 notes TEXT,
249 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
250 );
251 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
252 `);
253
254 // Meldingen: iemand reageert op je reactie / post, of liket je post. Snapshots
255 // van naam/titel zodat de lijst goedkoop te tonen is zonder joins.
256 // NB: bewust 'user_notifications' — sommige oudere DBs hebben nog een stale,
257 // ongebruikte 'notifications'-tabel met een ander schema (geen read-kolom).
258 db.exec(`
259 CREATE TABLE IF NOT EXISTS user_notifications (
260 id TEXT PRIMARY KEY,
261 user_id TEXT NOT NULL,
262 type TEXT NOT NULL,
263 actor_id TEXT,
264 actor_name TEXT,
265 post_slug TEXT,
266 post_title TEXT,
267 url TEXT,
268 read INTEGER DEFAULT 0,
269 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
270 );
271 CREATE INDEX IF NOT EXISTS idx_unotif_user ON user_notifications(user_id, read, created_at);
272 `);
273
274 // Link-in-bio klikstatistiek (premium #6). Per (site, url) een teller; de
275 // link-in-bio-pagina linkt via /links/go/:i dat de klik telt en doorstuurt.
276 db.exec(`
277 CREATE TABLE IF NOT EXISTS link_clicks (
278 site_id TEXT NOT NULL,
279 url TEXT NOT NULL,
280 clicks INTEGER DEFAULT 0,
281 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
282 PRIMARY KEY (site_id, url)
283 );
284 `);
285
286 // Likes / favorieten: een ingelogde gebruiker kan een post liken. De set van
287 // posts die een gebruiker likte = z'n favorieten (/favorieten-pagina). EÊn rij
288 // per (post, user); uniek zodat liken idempotent is.
289 db.exec(`
290 CREATE TABLE IF NOT EXISTS post_likes (
291 post_id TEXT NOT NULL,
292 user_id TEXT NOT NULL,
293 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
294 PRIMARY KEY (post_id, user_id)
295 );
296 CREATE INDEX IF NOT EXISTS idx_post_likes_user ON post_likes(user_id, created_at);
297 CREATE INDEX IF NOT EXISTS idx_post_likes_post ON post_likes(post_id);
298 `);
299}
300
301function ensureColumn(table, column, definition) {
302 try {
303 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
304 console.log(`🔧 Added column ${table}.${column}`);
305 } catch (e) {
306 // "duplicate column name" → already there. Anything else, surface it.
307 if (!/duplicate column/i.test(e.message)) {
308 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
309 }
310 }
311}
312
313export default db;
Note: See TracBrowser for help on using the repository browser.