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

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

feat(nsfw): custom content-warning text + blur in the Cirkel

  • Per-post content-warning text (like Mastodon): editor field; used as the on-site veil/banner label and the fediverse Note summary (falls back to 'Gevoelige inhoud').
  • Cirkel feed now blurs remote sensitive posts: ap_timeline gets nsfw+cw (captured from the incoming Note's sensitive/summary), getCirkelPosts returns them, circle.js maps them so post-card/tile show the veil.
  • Property mode set to 100644
File size: 19.0 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', 'content_warning', 'TEXT'); // custom CW label (empty = default "Gevoelige inhoud")
88 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
89
90 // Statistics (premium module) — bare counters, cookie-free.
91 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
92 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
93 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-for-email (premium #2)
94 ensureColumn('audio_tracks', 'credit', 'TEXT'); // owner/credit (copyright holder)
95 ensureColumn('audio_tracks', 'license', 'TEXT'); // license (e.g. "CC BY 4.0", "All rights reserved")
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 // Global app settings (key/value singleton). Includes the tenancy mode
128 // (solo = one site, hub = company site + /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 // ── Statistics (premium) — cookie-free ──────────────────────
139 // stat_daily: pageview count per day per site (bare counter).
140 // stat_visitor_day: one row per UNIQUE visitor hash per day per site
141 // (sha256 of IP+UA+day-salt; the salt rotates daily and is never stored
142 // → no persistent identifier, no cookie, no consent required).
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 // ── Circles (federation) ────────────────────────────────────
166 // Decentralised, asymmetric connections between 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 from the original post — shown in the circle feed (comma-separated string).
205 ensureColumn('remote_posts', 'tags', 'TEXT');
206
207 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
208 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
209 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
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 // Sent newsletters (history + counts).
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): tour dates / gigs 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 // Notifications: someone replies to your comment / post, or likes your post. Snapshots
255 // of name/title so the list can be shown cheaply without joins.
256 // NB: deliberately named 'user_notifications' — some older DBs still have a stale,
257 // unused 'notifications' table with a different schema (no read column).
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 `);
272 // Older DBs may have a user_notifications table predating these columns — add
273 // them before the index (which references `read`), else boot crashes.
274 ensureColumn('user_notifications', 'type', 'TEXT');
275 ensureColumn('user_notifications', 'actor_id', 'TEXT');
276 ensureColumn('user_notifications', 'actor_name', 'TEXT');
277 ensureColumn('user_notifications', 'post_slug', 'TEXT');
278 ensureColumn('user_notifications', 'post_title', 'TEXT');
279 ensureColumn('user_notifications', 'url', 'TEXT');
280 ensureColumn('user_notifications', 'read', 'INTEGER DEFAULT 0');
281 db.exec('CREATE INDEX IF NOT EXISTS idx_unotif_user ON user_notifications(user_id, read, created_at);');
282
283 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
284 // link-in-bio page links via /links/go/:i which counts the click and redirects.
285 db.exec(`
286 CREATE TABLE IF NOT EXISTS link_clicks (
287 site_id TEXT NOT NULL,
288 url TEXT NOT NULL,
289 clicks INTEGER DEFAULT 0,
290 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
291 PRIMARY KEY (site_id, url)
292 );
293 `);
294
295 // Likes / favourites: a logged-in user can like a post. The set of
296 // posts a user liked = their favourites (/favorieten page). One row
297 // per (post, user); unique so that liking is idempotent.
298 db.exec(`
299 CREATE TABLE IF NOT EXISTS post_likes (
300 post_id TEXT NOT NULL,
301 user_id TEXT NOT NULL,
302 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
303 PRIMARY KEY (post_id, user_id)
304 );
305 CREATE INDEX IF NOT EXISTS idx_post_likes_user ON post_likes(user_id, created_at);
306 CREATE INDEX IF NOT EXISTS idx_post_likes_post ON post_likes(post_id);
307 `);
308
309 // ── ActivityPub (fediverse bridge) ──────────────────────────
310 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
311 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
312 db.exec(`
313 CREATE TABLE IF NOT EXISTS ap_keys (
314 slug TEXT PRIMARY KEY,
315 public_pem TEXT NOT NULL,
316 private_pem TEXT NOT NULL,
317 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
318 );
319 CREATE TABLE IF NOT EXISTS ap_followers (
320 id INTEGER PRIMARY KEY AUTOINCREMENT,
321 slug TEXT NOT NULL,
322 actor_uri TEXT NOT NULL,
323 inbox TEXT,
324 shared_inbox TEXT,
325 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
326 UNIQUE(slug, actor_uri)
327 );
328 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
329 CREATE TABLE IF NOT EXISTS ap_interactions (
330 id INTEGER PRIMARY KEY AUTOINCREMENT,
331 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
332 post_id TEXT NOT NULL,
333 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
334 actor_uri TEXT NOT NULL,
335 actor_name TEXT,
336 actor_handle TEXT,
337 actor_url TEXT,
338 actor_icon TEXT,
339 content TEXT, -- sanitized HTML (reply)
340 published TEXT,
341 parent_uri TEXT, -- the note this reply replies to (for nesting)
342 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
343 UNIQUE(kind, post_id, actor_uri, object_uri)
344 );
345 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
346 CREATE TABLE IF NOT EXISTS ap_outbox (
347 id TEXT PRIMARY KEY, -- note path segment (uuid) → /ap/notes/<id>
348 site_slug TEXT NOT NULL,
349 post_id TEXT NOT NULL,
350 post_slug TEXT,
351 in_reply_to TEXT, -- remote status uri we reply to
352 to_actor TEXT, -- remote actor uri (mentioned)
353 to_handle TEXT,
354 content TEXT NOT NULL, -- sanitized HTML of our reply
355 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
356 );
357 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
358 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
359 CREATE TABLE IF NOT EXISTS ap_my_reactions (
360 site_slug TEXT NOT NULL,
361 target_uri TEXT NOT NULL,
362 kind TEXT NOT NULL, -- 'like' | 'boost'
363 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
364 UNIQUE(site_slug, target_uri, kind)
365 );
366 `);
367 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
368 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (🔁) → can undo
369 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (⭐) → can undo
370
371 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
372 db.exec(`
373 CREATE TABLE IF NOT EXISTS ap_following (
374 id INTEGER PRIMARY KEY AUTOINCREMENT,
375 slug TEXT NOT NULL, -- our site that follows
376 actor_uri TEXT NOT NULL, -- the followed account's actor id
377 handle TEXT, name TEXT, icon TEXT, url TEXT,
378 inbox TEXT, -- their inbox (for Create delivery / Undo)
379 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
380 status TEXT DEFAULT 'pending', -- pending | accepted
381 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
382 UNIQUE(slug, actor_uri)
383 );
384 CREATE TABLE IF NOT EXISTS ap_timeline (
385 id TEXT NOT NULL, -- the remote note's AP id
386 slug TEXT NOT NULL, -- whose home timeline (our site)
387 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
388 content TEXT, url TEXT, published TEXT, media_json TEXT,
389 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
390 UNIQUE(slug, id)
391 );
392 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
393 CREATE TABLE IF NOT EXISTS ap_blocks (
394 id INTEGER PRIMARY KEY AUTOINCREMENT,
395 slug TEXT NOT NULL, -- our site that set the block
396 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
397 kind TEXT NOT NULL, -- 'actor' | 'domain'
398 label TEXT, -- display (@handle or domain)
399 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
400 UNIQUE(slug, target)
401 );
402 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
403 CREATE TABLE IF NOT EXISTS ap_delivery (
404 id INTEGER PRIMARY KEY AUTOINCREMENT,
405 slug TEXT NOT NULL, -- our site/actor that signs the delivery
406 inbox TEXT NOT NULL, -- recipient inbox URL
407 body TEXT NOT NULL, -- the activity JSON to POST
408 attempts INTEGER NOT NULL DEFAULT 0,
409 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
410 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
411 );
412 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
413 `);
414 // "Feature" a followed account: its posts show in the local Cirkel.
415 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
416 // A timeline post you boosted (🔁) — also shown in the Cirkel (mixed by date).
417 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
418 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (⭐) → toggle
419 ensureColumn('ap_timeline', 'nsfw', 'INTEGER DEFAULT 0'); // remote sensitive post → blur in the Cirkel
420 ensureColumn('ap_timeline', 'cw', 'TEXT'); // remote content-warning text
421}
422
423function ensureColumn(table, column, definition) {
424 try {
425 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
426 console.log(`🔧 Added column ${table}.${column}`);
427 } catch (e) {
428 // "duplicate column name" → already there. Anything else, surface it.
429 if (!/duplicate column/i.test(e.message)) {
430 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
431 }
432 }
433}
434
435export default db;
Note: See TracBrowser for help on using the repository browser.