source: Klonkt/src/config/database.js@ 837fc9c

main
Last change on this file since 837fc9c was 837fc9c, checked in by Robin Genis <roboburr@…>, 2 months ago

feat(posts): NSFW / sensitive content

Mark a post NSFW (checkbox in the editor, available to all). On-site the cover blurs in
feed/grid and the whole post blurs behind a 'Gevoelige inhoud' banner until clicked. In the
fediverse the Note gets sensitive:true + a content-warning summary (Mastodon CW). i18n NL/EN/DE.

  • Property mode set to 100644
File size: 18.7 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: link a Google account to a user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
43 // Read-only/viewer account: can view everything but make no changes.
44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
45 // Personal interface language (nl|en|de). Null = follow the default (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 // Circles: whether this site may appear in other sites' circles (surfacing opt-out).
50 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
51
52 // One EXPLICIT primary/main site (= the company/label site in hub mode,
53 // the only site in solo) instead of the fragile "oldest = main" convention
54 // that was duplicated in 4 places. Backfill: mark the oldest if no primary
55 // site exists yet, so existing behaviour is preserved exactly.
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 table still empty/absent on fresh init — ensurePrimarySite handles it */ }
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', 'publish_at', 'DATETIME'); // release planning (premium #3): scheduled go-live
85 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
86 ensureColumn('posts', 'nsfw', 'INTEGER DEFAULT 0'); // sensitive content → blur + click-to-reveal; fediverse sensitive
87 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
88
89 // Statistics (premium module) — bare counters, cookie-free.
90 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
91 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
92 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-for-email (premium #2)
93 ensureColumn('audio_tracks', 'credit', 'TEXT'); // owner/credit (copyright holder)
94 ensureColumn('audio_tracks', 'license', 'TEXT'); // license (e.g. "CC BY 4.0", "All rights reserved")
95 ensureColumn('audio_tracks', 'link_spotify', 'TEXT'); // "open in" links per track
96 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
97 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
98
99 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
100 // idempotent so it's safe to run on every boot regardless of DB age.
101 db.exec(`
102 CREATE TABLE IF NOT EXISTS playlists (
103 id TEXT PRIMARY KEY,
104 site_id TEXT NOT NULL,
105 title TEXT NOT NULL,
106 artist TEXT,
107 year INTEGER,
108 cover_url TEXT,
109 kind TEXT DEFAULT 'album',
110 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
111 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
112 FOREIGN KEY (site_id) REFERENCES sites(id)
113 );
114 CREATE TABLE IF NOT EXISTS playlist_tracks (
115 playlist_id TEXT NOT NULL,
116 track_id TEXT NOT NULL,
117 position INTEGER NOT NULL DEFAULT 0,
118 PRIMARY KEY (playlist_id, track_id),
119 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
120 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
121 );
122 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
123 ON playlist_tracks(playlist_id, position);
124 `);
125
126 // Global app settings (key/value singleton). Includes the tenancy mode
127 // (solo = one site, hub = company site + /user/). Default = solo.
128 db.exec(`
129 CREATE TABLE IF NOT EXISTS app_settings (
130 key TEXT PRIMARY KEY,
131 value TEXT,
132 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
133 );
134 `);
135 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
136
137 // ── Statistics (premium) — cookie-free ──────────────────────
138 // stat_daily: pageview count per day per site (bare counter).
139 // stat_visitor_day: one row per UNIQUE visitor hash per day per site
140 // (sha256 of IP+UA+day-salt; the salt rotates daily and is never stored
141 // → no persistent identifier, no cookie, no consent required).
142 db.exec(`
143 CREATE TABLE IF NOT EXISTS stat_daily (
144 site_id TEXT NOT NULL,
145 day TEXT NOT NULL,
146 pageviews INTEGER NOT NULL DEFAULT 0,
147 PRIMARY KEY (site_id, day)
148 );
149 CREATE TABLE IF NOT EXISTS stat_visitor_day (
150 site_id TEXT NOT NULL,
151 day TEXT NOT NULL,
152 visitor_hash TEXT NOT NULL,
153 PRIMARY KEY (site_id, day, visitor_hash)
154 );
155 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
156 CREATE TABLE IF NOT EXISTS stat_referrer (
157 site_id TEXT NOT NULL,
158 host TEXT NOT NULL,
159 count INTEGER NOT NULL DEFAULT 0,
160 PRIMARY KEY (site_id, host)
161 );
162 `);
163
164 // ── Circles (federation) ────────────────────────────────────
165 // Decentralised, asymmetric connections between solo instances.
166 db.exec(`
167 CREATE TABLE IF NOT EXISTS circle_links (
168 id TEXT PRIMARY KEY,
169 local_site_id TEXT NOT NULL,
170 remote_url TEXT NOT NULL,
171 remote_actor_id TEXT,
172 label TEXT,
173 status TEXT DEFAULT 'active',
174 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
175 last_synced DATETIME,
176 last_error TEXT,
177 UNIQUE(local_site_id, remote_url),
178 FOREIGN KEY (local_site_id) REFERENCES sites(id)
179 );
180 CREATE TABLE IF NOT EXISTS remote_actors (
181 id TEXT PRIMARY KEY,
182 url TEXT UNIQUE NOT NULL,
183 name TEXT,
184 summary TEXT,
185 avatar TEXT,
186 public_key TEXT NOT NULL,
187 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
188 );
189 CREATE TABLE IF NOT EXISTS remote_posts (
190 id TEXT PRIMARY KEY,
191 actor_id TEXT NOT NULL,
192 published DATETIME,
193 title TEXT,
194 summary TEXT,
195 url TEXT,
196 media_json TEXT,
197 raw_json TEXT,
198 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
199 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
200 );
201 `);
202
203 // Tags from the original post — shown in the circle feed (comma-separated string).
204 ensureColumn('remote_posts', 'tags', 'TEXT');
205
206 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
207 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
208 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
209 db.exec(`
210 CREATE TABLE IF NOT EXISTS subscribers (
211 id TEXT PRIMARY KEY,
212 site_id TEXT NOT NULL,
213 email TEXT NOT NULL,
214 status TEXT NOT NULL DEFAULT 'pending',
215 source TEXT DEFAULT 'widget',
216 token TEXT NOT NULL,
217 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
218 confirmed_at DATETIME,
219 UNIQUE(site_id, email)
220 );
221 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
222 `);
223
224 // Sent newsletters (history + counts).
225 db.exec(`
226 CREATE TABLE IF NOT EXISTS newsletters (
227 id TEXT PRIMARY KEY,
228 site_id TEXT NOT NULL,
229 subject TEXT NOT NULL,
230 body TEXT NOT NULL,
231 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
232 recipient_count INTEGER DEFAULT 0
233 );
234 `);
235
236 // Show agenda (premium #8): tour dates / gigs per site.
237 db.exec(`
238 CREATE TABLE IF NOT EXISTS shows (
239 id TEXT PRIMARY KEY,
240 site_id TEXT NOT NULL,
241 date TEXT NOT NULL,
242 time TEXT,
243 city TEXT NOT NULL,
244 venue TEXT,
245 country TEXT,
246 ticket_url TEXT,
247 notes TEXT,
248 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
249 );
250 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
251 `);
252
253 // Notifications: someone replies to your comment / post, or likes your post. Snapshots
254 // of name/title so the list can be shown cheaply without joins.
255 // NB: deliberately named 'user_notifications' — some older DBs still have a stale,
256 // unused 'notifications' table with a different schema (no read column).
257 db.exec(`
258 CREATE TABLE IF NOT EXISTS user_notifications (
259 id TEXT PRIMARY KEY,
260 user_id TEXT NOT NULL,
261 type TEXT NOT NULL,
262 actor_id TEXT,
263 actor_name TEXT,
264 post_slug TEXT,
265 post_title TEXT,
266 url TEXT,
267 read INTEGER DEFAULT 0,
268 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
269 );
270 `);
271 // Older DBs may have a user_notifications table predating these columns — add
272 // them before the index (which references `read`), else boot crashes.
273 ensureColumn('user_notifications', 'type', 'TEXT');
274 ensureColumn('user_notifications', 'actor_id', 'TEXT');
275 ensureColumn('user_notifications', 'actor_name', 'TEXT');
276 ensureColumn('user_notifications', 'post_slug', 'TEXT');
277 ensureColumn('user_notifications', 'post_title', 'TEXT');
278 ensureColumn('user_notifications', 'url', 'TEXT');
279 ensureColumn('user_notifications', 'read', 'INTEGER DEFAULT 0');
280 db.exec('CREATE INDEX IF NOT EXISTS idx_unotif_user ON user_notifications(user_id, read, created_at);');
281
282 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
283 // link-in-bio page links via /links/go/:i which counts the click and redirects.
284 db.exec(`
285 CREATE TABLE IF NOT EXISTS link_clicks (
286 site_id TEXT NOT NULL,
287 url TEXT NOT NULL,
288 clicks INTEGER DEFAULT 0,
289 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
290 PRIMARY KEY (site_id, url)
291 );
292 `);
293
294 // Likes / favourites: a logged-in user can like a post. The set of
295 // posts a user liked = their favourites (/favorieten page). One row
296 // per (post, user); unique so that liking is idempotent.
297 db.exec(`
298 CREATE TABLE IF NOT EXISTS post_likes (
299 post_id TEXT NOT NULL,
300 user_id TEXT NOT NULL,
301 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
302 PRIMARY KEY (post_id, user_id)
303 );
304 CREATE INDEX IF NOT EXISTS idx_post_likes_user ON post_likes(user_id, created_at);
305 CREATE INDEX IF NOT EXISTS idx_post_likes_post ON post_likes(post_id);
306 `);
307
308 // ── ActivityPub (fediverse bridge) ──────────────────────────
309 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
310 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
311 db.exec(`
312 CREATE TABLE IF NOT EXISTS ap_keys (
313 slug TEXT PRIMARY KEY,
314 public_pem TEXT NOT NULL,
315 private_pem TEXT NOT NULL,
316 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
317 );
318 CREATE TABLE IF NOT EXISTS ap_followers (
319 id INTEGER PRIMARY KEY AUTOINCREMENT,
320 slug TEXT NOT NULL,
321 actor_uri TEXT NOT NULL,
322 inbox TEXT,
323 shared_inbox TEXT,
324 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
325 UNIQUE(slug, actor_uri)
326 );
327 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
328 CREATE TABLE IF NOT EXISTS ap_interactions (
329 id INTEGER PRIMARY KEY AUTOINCREMENT,
330 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
331 post_id TEXT NOT NULL,
332 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
333 actor_uri TEXT NOT NULL,
334 actor_name TEXT,
335 actor_handle TEXT,
336 actor_url TEXT,
337 actor_icon TEXT,
338 content TEXT, -- sanitized HTML (reply)
339 published TEXT,
340 parent_uri TEXT, -- the note this reply replies to (for nesting)
341 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
342 UNIQUE(kind, post_id, actor_uri, object_uri)
343 );
344 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
345 CREATE TABLE IF NOT EXISTS ap_outbox (
346 id TEXT PRIMARY KEY, -- note path segment (uuid) → /ap/notes/<id>
347 site_slug TEXT NOT NULL,
348 post_id TEXT NOT NULL,
349 post_slug TEXT,
350 in_reply_to TEXT, -- remote status uri we reply to
351 to_actor TEXT, -- remote actor uri (mentioned)
352 to_handle TEXT,
353 content TEXT NOT NULL, -- sanitized HTML of our reply
354 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
355 );
356 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
357 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
358 CREATE TABLE IF NOT EXISTS ap_my_reactions (
359 site_slug TEXT NOT NULL,
360 target_uri TEXT NOT NULL,
361 kind TEXT NOT NULL, -- 'like' | 'boost'
362 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
363 UNIQUE(site_slug, target_uri, kind)
364 );
365 `);
366 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
367 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (🔁) → can undo
368 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (⭐) → can undo
369
370 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
371 db.exec(`
372 CREATE TABLE IF NOT EXISTS ap_following (
373 id INTEGER PRIMARY KEY AUTOINCREMENT,
374 slug TEXT NOT NULL, -- our site that follows
375 actor_uri TEXT NOT NULL, -- the followed account's actor id
376 handle TEXT, name TEXT, icon TEXT, url TEXT,
377 inbox TEXT, -- their inbox (for Create delivery / Undo)
378 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
379 status TEXT DEFAULT 'pending', -- pending | accepted
380 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
381 UNIQUE(slug, actor_uri)
382 );
383 CREATE TABLE IF NOT EXISTS ap_timeline (
384 id TEXT NOT NULL, -- the remote note's AP id
385 slug TEXT NOT NULL, -- whose home timeline (our site)
386 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
387 content TEXT, url TEXT, published TEXT, media_json TEXT,
388 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
389 UNIQUE(slug, id)
390 );
391 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
392 CREATE TABLE IF NOT EXISTS ap_blocks (
393 id INTEGER PRIMARY KEY AUTOINCREMENT,
394 slug TEXT NOT NULL, -- our site that set the block
395 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
396 kind TEXT NOT NULL, -- 'actor' | 'domain'
397 label TEXT, -- display (@handle or domain)
398 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
399 UNIQUE(slug, target)
400 );
401 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
402 CREATE TABLE IF NOT EXISTS ap_delivery (
403 id INTEGER PRIMARY KEY AUTOINCREMENT,
404 slug TEXT NOT NULL, -- our site/actor that signs the delivery
405 inbox TEXT NOT NULL, -- recipient inbox URL
406 body TEXT NOT NULL, -- the activity JSON to POST
407 attempts INTEGER NOT NULL DEFAULT 0,
408 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
409 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
410 );
411 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
412 `);
413 // "Feature" a followed account: its posts show in the local Cirkel.
414 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
415 // A timeline post you boosted (🔁) — also shown in the Cirkel (mixed by date).
416 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
417 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (⭐) → toggle
418}
419
420function ensureColumn(table, column, definition) {
421 try {
422 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
423 console.log(`🔧 Added column ${table}.${column}`);
424 } catch (e) {
425 // "duplicate column name" → already there. Anything else, surface it.
426 if (!/duplicate column/i.test(e.message)) {
427 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
428 }
429 }
430}
431
432export default db;
Note: See TracBrowser for help on using the repository browser.