source: Klonkt/src/config/database.js@ 6c3d805

main
Last change on this file since 6c3d805 was 5a6a457, checked in by Robin Genis <roboburr@…>, 3 months ago

feat(fediverse): federate on save+scheduler, delivery retry-queue, music as listen-link

#1 Posts now federate to followers not only on create, but also when a draft/

scheduled post becomes published (editor save) and when the Scheduler flips a
scheduled post live — previously those silently didn't reach followers.

#2 Delivery retry-queue (ap_delivery): a failed delivery (down server/timeout) is

queued and retried with backoff (1/5/15/60/180/360 min, 6 tries) by a worker,
instead of fire-and-forget. Signing key re-derived from the slug, never stored.

#3 Music posts: audio shortcodes federate as a '🎵 listen on the site' link to the

post (protected player) instead of the raw mp3 — keeps Klonkt's audio friction
intact (no downloadable file handed to Mastodon).

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

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