source: Klonkt/src/config/database.js@ c9c6a2d

main
Last change on this file since c9c6a2d was c9c6a2d, checked in by roboburr <roboburr@…>, 3 months ago

feat(meldingen): notifications — reply on comment, comment on post, like on post

For every logged-in user (Google visitors/fans and admin). Bell icon in the
header with unread counter + notifications page /notifications (via user menu
desktop + profile sheet mobile; badge also on the mobile Profile tab). Opening =
read. Triggers in comments (reply→comment author, top-level→post author) and
like (→post author); notify() skips notifying yourself. Table notifications
+ NotificationService. NL/EN/DE.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 12.6 KB
RevLine 
[7bc636b]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');
[c80e78b]41 // Google OAuth: koppel een Google-account aan een user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
[640b39c]43 // Read-only/kijk-account: kan alles bekijken maar geen wijzigingen doen.
44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
[5e61b17]45 // Persoonlijke interface-taal (nl|en|de). Null = volg de standaard (site/env/browser).
46 ensureColumn('users', 'lang', 'TEXT');
[7bc636b]47 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
[8ea3d0d]48 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'moderate'");
[7bc636b]49 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
50 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
[0091cb7]51 // Cirkels: mag deze site in cirkels van anderen verschijnen (surfacing opt-out).
52 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
[7bc636b]53
[7881080]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
[7bc636b]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}]
[8ea3d0d]79 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
[7bc636b]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');
[b9dc94c]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)
[7bc636b]88 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
89
[d549549]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
[91094a4]93 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-voor-email (premium #2)
[0d7acdf]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")
[183875b]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');
[d549549]99
[7bc636b]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 `);
[6351545]126
127 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
[52215bc]128 // (solo = één site, hub = bedrijfssite + /user/). Default = solo.
[6351545]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();
[b300682]137
[d549549]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);
[1794fac]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 );
[d549549]163 `);
164
[b300682]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 `);
[221a209]203
204 // Tags van de originele post — getoond in de cirkel (comma-separated string).
205 ensureColumn('remote_posts', 'tags', 'TEXT');
[2e247e4]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 `);
[37edecd]236
[8d32dcf]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
[c9c6a2d]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 db.exec(`
257 CREATE TABLE IF NOT EXISTS notifications (
258 id TEXT PRIMARY KEY,
259 user_id TEXT NOT NULL,
260 type TEXT NOT NULL,
261 actor_id TEXT,
262 actor_name TEXT,
263 post_slug TEXT,
264 post_title TEXT,
265 url TEXT,
266 read INTEGER DEFAULT 0,
267 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
268 );
269 CREATE INDEX IF NOT EXISTS idx_notif_user ON notifications(user_id, read, created_at);
270 `);
271
[37edecd]272 // Link-in-bio klikstatistiek (premium #6). Per (site, url) een teller; de
273 // link-in-bio-pagina linkt via /links/go/:i dat de klik telt en doorstuurt.
274 db.exec(`
275 CREATE TABLE IF NOT EXISTS link_clicks (
276 site_id TEXT NOT NULL,
277 url TEXT NOT NULL,
278 clicks INTEGER DEFAULT 0,
279 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
280 PRIMARY KEY (site_id, url)
281 );
282 `);
[535f955]283
284 // Likes / favorieten: een ingelogde gebruiker kan een post liken. De set van
285 // posts die een gebruiker likte = z'n favorieten (/favorieten-pagina). Eén rij
286 // per (post, user); uniek zodat liken idempotent is.
287 db.exec(`
288 CREATE TABLE IF NOT EXISTS post_likes (
289 post_id TEXT NOT NULL,
290 user_id TEXT NOT NULL,
291 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
292 PRIMARY KEY (post_id, user_id)
293 );
294 CREATE INDEX IF NOT EXISTS idx_post_likes_user ON post_likes(user_id, created_at);
295 CREATE INDEX IF NOT EXISTS idx_post_likes_post ON post_likes(post_id);
296 `);
[7bc636b]297}
298
299function ensureColumn(table, column, definition) {
300 try {
301 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
302 console.log(`🔧 Added column ${table}.${column}`);
303 } catch (e) {
304 // "duplicate column name" → already there. Anything else, surface it.
305 if (!/duplicate column/i.test(e.message)) {
306 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
307 }
308 }
309}
310
311export default db;
Note: See TracBrowser for help on using the repository browser.