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

main
Last change on this file since d5e78f7 was 8f2f97c, checked in by Robin Genis <roboburr@â€Ļ>, 3 months ago

Prutter (DM feature) fully removed

Reason: redundant feature + unnecessary attack surface (real-time WebSocket +
storing private messages = privacy/abuse risk). Removed: routes/prutter.js,
PrutterService, the WebSocket server in server.js, both DM views, all nav links
(topnav/bottom-tab), the DM button on profiles, the per-site enable_prutter
toggle and column. Existing (empty) DM tables in old DBs remain untouched but
are no longer referenced anywhere. No WebSocket left in the app.

Co-Authored-By: Claude <noreply@â€Ļ>

  • Property mode set to 100644
File size: 12.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: 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 // Persoonlijke interface-taal (nl|en|de). Null = volg de standaard (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 // 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', 'publish_at', 'DATETIME'); // release-planning (premium #3): geplande 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 // Statistieken (premium-module) — kale tellers, cookievrij.
89 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // weergaven per post
90 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
91 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-voor-email (premium #2)
92 ensureColumn('audio_tracks', 'credit', 'TEXT'); // eigenaar/credit (copyright-houder)
93 ensureColumn('audio_tracks', 'license', 'TEXT'); // licentie (bv. "CC BY 4.0", "Alle rechten voorbehouden")
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 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
126 // (solo = ÊÊn site, hub = bedrijfssite + /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 // ── Statistieken (premium) — cookievrij ─────────────────────
137 // stat_daily: per dag per site het aantal pageviews (kale teller).
138 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
139 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
140 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
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 // ── Cirkels (federatie) ─────────────────────────────────────
164 // Decentrale, asymmetrische verbindingen tussen 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 van de originele post — getoond in de cirkel (comma-separated string).
203 ensureColumn('remote_posts', 'tags', 'TEXT');
204
205 // Nieuwsbrief / mailinglijst (premium). Abonnees per site; double opt-in als SMTP
206 // er is (status 'pending' tot bevestigd), anders single opt-in ('confirmed').
207 // 'unsub' = uitgeschreven. token = confirm/unsubscribe-sleutel (in de e-maillinks).
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 // Verstuurde nieuwsbrieven (historie + aantallen).
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): tourdata/optredens 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 // Meldingen: iemand reageert op je reactie / post, of liket je post. Snapshots
253 // van naam/titel zodat de lijst goedkoop te tonen is zonder joins.
254 // NB: bewust 'user_notifications' — sommige oudere DBs hebben nog een stale,
255 // ongebruikte 'notifications'-tabel met een ander schema (geen read-kolom).
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 CREATE INDEX IF NOT EXISTS idx_unotif_user ON user_notifications(user_id, read, created_at);
270 `);
271
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 `);
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 `);
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.