source: Klonkt/src/config/database.js@ 255e3d3

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

Hub #3: explicit is_primary flag + shared getPrimarySite() (DRY)

The "oldest site = primary site" assumption was duplicated independently in
resolveSite, hub.js, account.js and admin.js (fragile: if the oldest happened
to be an artist site, the hub home would be wrong). Now:

  • sites.is_primary column + backfill (marks the oldest if none is primary yet; ensurePrimarySite sets it on fresh installs) → existing behaviour exactly preserved.
  • one getPrimarySite() helper (is_primary, fallback oldest) replaces the 4 copies.
  • god can CHOOSE the primary/main site: ★ button + "primary" badge on /admin/sites (exactly one primary via a transaction).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 8.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: 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 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
46 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'moderate'");
47 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
48 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
49 // Cirkels: mag deze site in cirkels van anderen verschijnen (surfacing opt-out).
50 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
51
52 // Eén EXPLICIETE primaire/hoofd-site (= de bedrijfs-/labelsite in hub-modus,
53 // de enige site in solo) i.p.v. de fragiele "oudste = hoofd"-conventie die op
54 // 4 plekken gedupliceerd stond. Backfill: markeer de oudste als er nog geen
55 // primaire site is, zodat bestaand gedrag exact behouden blijft.
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-tabel nog leeg/afwezig bij verse init — ensurePrimarySite regelt 't */ }
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', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
85
86 // Statistieken (premium-module) — kale tellers, cookievrij.
87 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // weergaven per post
88 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
89
90 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
91 // idempotent so it's safe to run on every boot regardless of DB age.
92 db.exec(`
93 CREATE TABLE IF NOT EXISTS playlists (
94 id TEXT PRIMARY KEY,
95 site_id TEXT NOT NULL,
96 title TEXT NOT NULL,
97 artist TEXT,
98 year INTEGER,
99 cover_url TEXT,
100 kind TEXT DEFAULT 'album',
101 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
102 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
103 FOREIGN KEY (site_id) REFERENCES sites(id)
104 );
105 CREATE TABLE IF NOT EXISTS playlist_tracks (
106 playlist_id TEXT NOT NULL,
107 track_id TEXT NOT NULL,
108 position INTEGER NOT NULL DEFAULT 0,
109 PRIMARY KEY (playlist_id, track_id),
110 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
111 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
112 );
113 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
114 ON playlist_tracks(playlist_id, position);
115 `);
116
117 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
118 // (solo = één site, hub = bedrijfssite + /user/). Default = solo.
119 db.exec(`
120 CREATE TABLE IF NOT EXISTS app_settings (
121 key TEXT PRIMARY KEY,
122 value TEXT,
123 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
124 );
125 `);
126 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
127
128 // ── Statistieken (premium) — cookievrij ─────────────────────
129 // stat_daily: per dag per site het aantal pageviews (kale teller).
130 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
131 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
132 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
133 db.exec(`
134 CREATE TABLE IF NOT EXISTS stat_daily (
135 site_id TEXT NOT NULL,
136 day TEXT NOT NULL,
137 pageviews INTEGER NOT NULL DEFAULT 0,
138 PRIMARY KEY (site_id, day)
139 );
140 CREATE TABLE IF NOT EXISTS stat_visitor_day (
141 site_id TEXT NOT NULL,
142 day TEXT NOT NULL,
143 visitor_hash TEXT NOT NULL,
144 PRIMARY KEY (site_id, day, visitor_hash)
145 );
146 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
147 `);
148
149 // ── Cirkels (federatie) ─────────────────────────────────────
150 // Decentrale, asymmetrische verbindingen tussen solo-instances.
151 db.exec(`
152 CREATE TABLE IF NOT EXISTS circle_links (
153 id TEXT PRIMARY KEY,
154 local_site_id TEXT NOT NULL,
155 remote_url TEXT NOT NULL,
156 remote_actor_id TEXT,
157 label TEXT,
158 status TEXT DEFAULT 'active',
159 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
160 last_synced DATETIME,
161 last_error TEXT,
162 UNIQUE(local_site_id, remote_url),
163 FOREIGN KEY (local_site_id) REFERENCES sites(id)
164 );
165 CREATE TABLE IF NOT EXISTS remote_actors (
166 id TEXT PRIMARY KEY,
167 url TEXT UNIQUE NOT NULL,
168 name TEXT,
169 summary TEXT,
170 avatar TEXT,
171 public_key TEXT NOT NULL,
172 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
173 );
174 CREATE TABLE IF NOT EXISTS remote_posts (
175 id TEXT PRIMARY KEY,
176 actor_id TEXT NOT NULL,
177 published DATETIME,
178 title TEXT,
179 summary TEXT,
180 url TEXT,
181 media_json TEXT,
182 raw_json TEXT,
183 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
184 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
185 );
186 `);
187
188 // Tags van de originele post — getoond in de cirkel (comma-separated string).
189 ensureColumn('remote_posts', 'tags', 'TEXT');
190}
191
192function ensureColumn(table, column, definition) {
193 try {
194 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
195 console.log(`🔧 Added column ${table}.${column}`);
196 } catch (e) {
197 // "duplicate column name" → already there. Anything else, surface it.
198 if (!/duplicate column/i.test(e.message)) {
199 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
200 }
201 }
202}
203
204export default db;
Note: See TracBrowser for help on using the repository browser.