source: Klonkt/src/config/database.js@ 64b90c0

main
Last change on this file since 64b90c0 was 0091cb7, checked in by roboburr <roboburr@…>, 3 months ago

Circles v1 — steps 4+5: Admin UI + /cirkel feed

  • Mode 'Circles' in Admin > Settings (radio + section).
  • Admin > Circle (admin-circle): add sources/list/status, per source Refresh (syncOne) + Delete (cleans up orphaned cache), and a visibility toggle (sites.allow_circle, opt-out for surfacing).
  • /cirkel feed: cached remote_posts as static cards (source/avatar, title, summary, cover, link to source). Only when tenancy=circle.
  • allow_circle column (ensureColumn) + CircleFederation respects it.
  • Output escaped everywhere + URL-scheme guards (http/https) against XSS import.

v1 functionally complete (publish + pull + UI + feed). Remaining: hardening/review.

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

  • Property mode set to 100644
File size: 6.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 'trust'");
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 // v9 audit additions —————————————————————————————————————————
53 // SEO/social columns the v9 template uses (most live in 001-init.sql already
54 // for fresh DBs but ensureColumn is idempotent for existing DBs).
55 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
56 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
57 ensureColumn('sites', 'publisher_name', 'TEXT');
58 ensureColumn('sites', 'publisher_url', 'TEXT');
59 ensureColumn('sites', 'publisher_logo', 'TEXT');
60 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
61 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
62 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
63 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
64 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'timeline'"); // timeline | grid
65 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
66 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
67 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
68
69 // Per-post noindex + type
70 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
71 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
72
73 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
74 // idempotent so it's safe to run on every boot regardless of DB age.
75 db.exec(`
76 CREATE TABLE IF NOT EXISTS playlists (
77 id TEXT PRIMARY KEY,
78 site_id TEXT NOT NULL,
79 title TEXT NOT NULL,
80 artist TEXT,
81 year INTEGER,
82 cover_url TEXT,
83 kind TEXT DEFAULT 'album',
84 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
85 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
86 FOREIGN KEY (site_id) REFERENCES sites(id)
87 );
88 CREATE TABLE IF NOT EXISTS playlist_tracks (
89 playlist_id TEXT NOT NULL,
90 track_id TEXT NOT NULL,
91 position INTEGER NOT NULL DEFAULT 0,
92 PRIMARY KEY (playlist_id, track_id),
93 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
94 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
95 );
96 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
97 ON playlist_tracks(playlist_id, position);
98 `);
99
100 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
101 // (solo = één site, hub = bedrijfssite + /user/). Default = solo.
102 db.exec(`
103 CREATE TABLE IF NOT EXISTS app_settings (
104 key TEXT PRIMARY KEY,
105 value TEXT,
106 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
107 );
108 `);
109 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
110
111 // ── Cirkels (federatie) ─────────────────────────────────────
112 // Decentrale, asymmetrische verbindingen tussen solo-instances.
113 db.exec(`
114 CREATE TABLE IF NOT EXISTS circle_links (
115 id TEXT PRIMARY KEY,
116 local_site_id TEXT NOT NULL,
117 remote_url TEXT NOT NULL,
118 remote_actor_id TEXT,
119 label TEXT,
120 status TEXT DEFAULT 'active',
121 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
122 last_synced DATETIME,
123 last_error TEXT,
124 UNIQUE(local_site_id, remote_url),
125 FOREIGN KEY (local_site_id) REFERENCES sites(id)
126 );
127 CREATE TABLE IF NOT EXISTS remote_actors (
128 id TEXT PRIMARY KEY,
129 url TEXT UNIQUE NOT NULL,
130 name TEXT,
131 summary TEXT,
132 avatar TEXT,
133 public_key TEXT NOT NULL,
134 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
135 );
136 CREATE TABLE IF NOT EXISTS remote_posts (
137 id TEXT PRIMARY KEY,
138 actor_id TEXT NOT NULL,
139 published DATETIME,
140 title TEXT,
141 summary TEXT,
142 url TEXT,
143 media_json TEXT,
144 raw_json TEXT,
145 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
146 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
147 );
148 `);
149}
150
151function ensureColumn(table, column, definition) {
152 try {
153 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
154 console.log(`🔧 Added column ${table}.${column}`);
155 } catch (e) {
156 // "duplicate column name" → already there. Anything else, surface it.
157 if (!/duplicate column/i.test(e.message)) {
158 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
159 }
160 }
161}
162
163export default db;
Note: See TracBrowser for help on using the repository browser.