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

main
Last change on this file since ee25d45 was 221a209, checked in by roboburr <roboburr@â€Ļ>, 3 months ago

Circle: carry over + display tags from the original post

Publisher puts tags as AS Hashtag array in the outbox (href pointing to the
source tag page). Consumer parses + caches them (remote_posts.tags). Feed
cards display them (post-card), and the reader shows tag chips that link to
the /tag page of the source.

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

  • Property mode set to 100644
File size: 7.9 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 // 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 'grid'"); // 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 // Statistieken (premium-module) — kale tellers, cookievrij.
74 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // weergaven per post
75 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
76
77 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
78 // idempotent so it's safe to run on every boot regardless of DB age.
79 db.exec(`
80 CREATE TABLE IF NOT EXISTS playlists (
81 id TEXT PRIMARY KEY,
82 site_id TEXT NOT NULL,
83 title TEXT NOT NULL,
84 artist TEXT,
85 year INTEGER,
86 cover_url TEXT,
87 kind TEXT DEFAULT 'album',
88 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
89 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
90 FOREIGN KEY (site_id) REFERENCES sites(id)
91 );
92 CREATE TABLE IF NOT EXISTS playlist_tracks (
93 playlist_id TEXT NOT NULL,
94 track_id TEXT NOT NULL,
95 position INTEGER NOT NULL DEFAULT 0,
96 PRIMARY KEY (playlist_id, track_id),
97 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
98 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
99 );
100 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
101 ON playlist_tracks(playlist_id, position);
102 `);
103
104 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
105 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
106 db.exec(`
107 CREATE TABLE IF NOT EXISTS app_settings (
108 key TEXT PRIMARY KEY,
109 value TEXT,
110 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
111 );
112 `);
113 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
114
115 // ── Statistieken (premium) — cookievrij ─────────────────────
116 // stat_daily: per dag per site het aantal pageviews (kale teller).
117 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
118 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
119 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
120 db.exec(`
121 CREATE TABLE IF NOT EXISTS stat_daily (
122 site_id TEXT NOT NULL,
123 day TEXT NOT NULL,
124 pageviews INTEGER NOT NULL DEFAULT 0,
125 PRIMARY KEY (site_id, day)
126 );
127 CREATE TABLE IF NOT EXISTS stat_visitor_day (
128 site_id TEXT NOT NULL,
129 day TEXT NOT NULL,
130 visitor_hash TEXT NOT NULL,
131 PRIMARY KEY (site_id, day, visitor_hash)
132 );
133 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
134 `);
135
136 // ── Cirkels (federatie) ─────────────────────────────────────
137 // Decentrale, asymmetrische verbindingen tussen solo-instances.
138 db.exec(`
139 CREATE TABLE IF NOT EXISTS circle_links (
140 id TEXT PRIMARY KEY,
141 local_site_id TEXT NOT NULL,
142 remote_url TEXT NOT NULL,
143 remote_actor_id TEXT,
144 label TEXT,
145 status TEXT DEFAULT 'active',
146 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
147 last_synced DATETIME,
148 last_error TEXT,
149 UNIQUE(local_site_id, remote_url),
150 FOREIGN KEY (local_site_id) REFERENCES sites(id)
151 );
152 CREATE TABLE IF NOT EXISTS remote_actors (
153 id TEXT PRIMARY KEY,
154 url TEXT UNIQUE NOT NULL,
155 name TEXT,
156 summary TEXT,
157 avatar TEXT,
158 public_key TEXT NOT NULL,
159 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
160 );
161 CREATE TABLE IF NOT EXISTS remote_posts (
162 id TEXT PRIMARY KEY,
163 actor_id TEXT NOT NULL,
164 published DATETIME,
165 title TEXT,
166 summary TEXT,
167 url TEXT,
168 media_json TEXT,
169 raw_json TEXT,
170 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
171 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
172 );
173 `);
174
175 // Tags van de originele post — getoond in de cirkel (comma-separated string).
176 ensureColumn('remote_posts', 'tags', 'TEXT');
177}
178
179function ensureColumn(table, column, definition) {
180 try {
181 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
182 console.log(`🔧 Added column ${table}.${column}`);
183 } catch (e) {
184 // "duplicate column name" → already there. Anything else, surface it.
185 if (!/duplicate column/i.test(e.message)) {
186 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
187 }
188 }
189}
190
191export default db;
Note: See TracBrowser for help on using the repository browser.