source: Klonkt/src/config/database.js@ 5f483e3

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

chore: code cleanup — remove dead files, deps, DB tables, Google-login remnants

  • Deleted dead files: routes/notifications.js + services/NotificationService.js + views/pages/notifications.ejs (old bell, unmounted; live fedi notifications live in posts.js); deploy/verify.ps1 (stale smoke test).
  • package.json — drop unused ws dependency (no WebSocket since Prutter was removed).
  • .env.example — drop GOOGLE_* vars (Google login removed).
  • config/database.js — remove CREATE statements for dead tables (circle_links/remote_actors/ remote_posts from old Circles v1; user_notifications; post_likes). No DROP — existing rows stay.
  • services/i18n.js — remove dead keys: hub, prutter, and the whole Google-login set (+ the agoog.* wizard + glog.* notices, ~280 lines). Kept aseo.verify_google. solo_desc/login_google_only de-Googled.
  • views/pages/auth-login.ejs — drop the dead Google error block + button CSS; the password login form is unchanged.
  • deploy/post-receive — fix stale pm2 reload prutcms -> klonkt.
  • Property mode set to 100644
File size: 15.8 KB
RevLine 
[7bc636b]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');
[834bcc3]41 // Google OAuth: link a Google account to a user (login via Google).
[c80e78b]42 ensureColumn('users', 'google_sub', 'TEXT');
[834bcc3]43 // Read-only/viewer account: can view everything but make no changes.
[640b39c]44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
[834bcc3]45 // Personal interface language (nl|en|de). Null = follow the default (site/env/browser).
[5e61b17]46 ensureColumn('users', 'lang', 'TEXT');
[7bc636b]47 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
[8ea3d0d]48 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'moderate'");
[834bcc3]49 // Circles: whether this site may appear in other sites' circles (surfacing opt-out).
[0091cb7]50 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
[7bc636b]51
[834bcc3]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.
[7881080]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 }
[834bcc3]63 } catch (e) { /* sites table still empty/absent on fresh init — ensurePrimarySite handles it */ }
[7881080]64
[7bc636b]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}]
[8ea3d0d]77 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
[7bc636b]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');
[834bcc3]84 ensureColumn('posts', 'publish_at', 'DATETIME'); // release planning (premium #3): scheduled go-live
[b9dc94c]85 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
[837fc9c]86 ensureColumn('posts', 'nsfw', 'INTEGER DEFAULT 0'); // sensitive content → blur + click-to-reveal; fediverse sensitive
[b7d4458]87 ensureColumn('posts', 'content_warning', 'TEXT'); // custom CW label (empty = default "Gevoelige inhoud")
[7bc636b]88 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
89
[834bcc3]90 // Statistics (premium module) — bare counters, cookie-free.
91 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
[d549549]92 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
[834bcc3]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
[183875b]97 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
98 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
[d549549]99
[7bc636b]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 `);
[6351545]126
[834bcc3]127 // Global app settings (key/value singleton). Includes the tenancy mode
128 // (solo = one site, hub = company site + /user/). Default = solo.
[6351545]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();
[b300682]137
[834bcc3]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).
[d549549]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);
[1794fac]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 );
[d549549]163 `);
164
[834bcc3]165 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
166 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
167 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
[2e247e4]168 db.exec(`
169 CREATE TABLE IF NOT EXISTS subscribers (
170 id TEXT PRIMARY KEY,
171 site_id TEXT NOT NULL,
172 email TEXT NOT NULL,
173 status TEXT NOT NULL DEFAULT 'pending',
174 source TEXT DEFAULT 'widget',
175 token TEXT NOT NULL,
176 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
177 confirmed_at DATETIME,
178 UNIQUE(site_id, email)
179 );
180 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
181 `);
182
[834bcc3]183 // Sent newsletters (history + counts).
[2e247e4]184 db.exec(`
185 CREATE TABLE IF NOT EXISTS newsletters (
186 id TEXT PRIMARY KEY,
187 site_id TEXT NOT NULL,
188 subject TEXT NOT NULL,
189 body TEXT NOT NULL,
190 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
191 recipient_count INTEGER DEFAULT 0
192 );
193 `);
[37edecd]194
[834bcc3]195 // Show agenda (premium #8): tour dates / gigs per site.
[8d32dcf]196 db.exec(`
197 CREATE TABLE IF NOT EXISTS shows (
198 id TEXT PRIMARY KEY,
199 site_id TEXT NOT NULL,
200 date TEXT NOT NULL,
201 time TEXT,
202 city TEXT NOT NULL,
203 venue TEXT,
204 country TEXT,
205 ticket_url TEXT,
206 notes TEXT,
207 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
208 );
209 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
210 `);
211
[834bcc3]212 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
213 // link-in-bio page links via /links/go/:i which counts the click and redirects.
[37edecd]214 db.exec(`
215 CREATE TABLE IF NOT EXISTS link_clicks (
216 site_id TEXT NOT NULL,
217 url TEXT NOT NULL,
218 clicks INTEGER DEFAULT 0,
219 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
220 PRIMARY KEY (site_id, url)
221 );
222 `);
[535f955]223
[6bd25d1]224
225 // ── ActivityPub (fediverse bridge) ──────────────────────────
226 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
227 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
228 db.exec(`
229 CREATE TABLE IF NOT EXISTS ap_keys (
230 slug TEXT PRIMARY KEY,
231 public_pem TEXT NOT NULL,
232 private_pem TEXT NOT NULL,
233 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
234 );
235 CREATE TABLE IF NOT EXISTS ap_followers (
236 id INTEGER PRIMARY KEY AUTOINCREMENT,
237 slug TEXT NOT NULL,
238 actor_uri TEXT NOT NULL,
239 inbox TEXT,
240 shared_inbox TEXT,
241 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
242 UNIQUE(slug, actor_uri)
243 );
244 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
[c16e0a5]245 CREATE TABLE IF NOT EXISTS ap_interactions (
246 id INTEGER PRIMARY KEY AUTOINCREMENT,
247 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
248 post_id TEXT NOT NULL,
249 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
250 actor_uri TEXT NOT NULL,
251 actor_name TEXT,
252 actor_handle TEXT,
253 actor_url TEXT,
254 actor_icon TEXT,
255 content TEXT, -- sanitized HTML (reply)
256 published TEXT,
[7d932ce]257 parent_uri TEXT, -- the note this reply replies to (for nesting)
[c16e0a5]258 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
259 UNIQUE(kind, post_id, actor_uri, object_uri)
260 );
261 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
[55bc7f9]262 CREATE TABLE IF NOT EXISTS ap_outbox (
263 id TEXT PRIMARY KEY, -- note path segment (uuid) → /ap/notes/<id>
264 site_slug TEXT NOT NULL,
265 post_id TEXT NOT NULL,
266 post_slug TEXT,
267 in_reply_to TEXT, -- remote status uri we reply to
268 to_actor TEXT, -- remote actor uri (mentioned)
269 to_handle TEXT,
270 content TEXT NOT NULL, -- sanitized HTML of our reply
271 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
272 );
273 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
[3d37c67]274 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
275 CREATE TABLE IF NOT EXISTS ap_my_reactions (
276 site_slug TEXT NOT NULL,
277 target_uri TEXT NOT NULL,
278 kind TEXT NOT NULL, -- 'like' | 'boost'
279 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
280 UNIQUE(site_slug, target_uri, kind)
281 );
[6bd25d1]282 `);
[7d932ce]283 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
[c745659]284 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (🔁) → can undo
[3289a64]285 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (⭐) → can undo
[914eb9f]286
287 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
288 db.exec(`
289 CREATE TABLE IF NOT EXISTS ap_following (
290 id INTEGER PRIMARY KEY AUTOINCREMENT,
291 slug TEXT NOT NULL, -- our site that follows
292 actor_uri TEXT NOT NULL, -- the followed account's actor id
293 handle TEXT, name TEXT, icon TEXT, url TEXT,
294 inbox TEXT, -- their inbox (for Create delivery / Undo)
295 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
296 status TEXT DEFAULT 'pending', -- pending | accepted
297 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
298 UNIQUE(slug, actor_uri)
299 );
300 CREATE TABLE IF NOT EXISTS ap_timeline (
301 id TEXT NOT NULL, -- the remote note's AP id
302 slug TEXT NOT NULL, -- whose home timeline (our site)
303 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
304 content TEXT, url TEXT, published TEXT, media_json TEXT,
305 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
306 UNIQUE(slug, id)
307 );
308 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
[f5c3870]309 CREATE TABLE IF NOT EXISTS ap_blocks (
310 id INTEGER PRIMARY KEY AUTOINCREMENT,
311 slug TEXT NOT NULL, -- our site that set the block
312 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
313 kind TEXT NOT NULL, -- 'actor' | 'domain'
314 label TEXT, -- display (@handle or domain)
315 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
316 UNIQUE(slug, target)
317 );
318 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
[5a6a457]319 CREATE TABLE IF NOT EXISTS ap_delivery (
320 id INTEGER PRIMARY KEY AUTOINCREMENT,
321 slug TEXT NOT NULL, -- our site/actor that signs the delivery
322 inbox TEXT NOT NULL, -- recipient inbox URL
323 body TEXT NOT NULL, -- the activity JSON to POST
324 attempts INTEGER NOT NULL DEFAULT 0,
325 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
326 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
327 );
328 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
[914eb9f]329 `);
[5045c30]330 // "Feature" a followed account: its posts show in the local Cirkel.
[f278df9]331 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
[5045c30]332 // A timeline post you boosted (🔁) — also shown in the Cirkel (mixed by date).
333 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
[9d34855]334 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (⭐) → toggle
[b7d4458]335 ensureColumn('ap_timeline', 'nsfw', 'INTEGER DEFAULT 0'); // remote sensitive post → blur in the Cirkel
336 ensureColumn('ap_timeline', 'cw', 'TEXT'); // remote content-warning text
[7bc636b]337}
338
339function ensureColumn(table, column, definition) {
340 try {
341 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
342 console.log(`🔧 Added column ${table}.${column}`);
343 } catch (e) {
344 // "duplicate column name" → already there. Anything else, surface it.
345 if (!/duplicate column/i.test(e.message)) {
346 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
347 }
348 }
349}
350
351export default db;
Note: See TracBrowser for help on using the repository browser.