source: Klonkt/src/config/database.js@ 37edecd

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

Link-in-bio + click stats (premium feature #6)

Linktree-style page from the existing sites.profile_links (JSON [{platform,url}])
+ PLATFORMS icons. Clicks counted per url.

  • DB: link_clicks (site_id, url, clicks), PK (site_id,url).
  • routes/linkbio.js (premium-gated): GET /links (page with profile_links as buttons), GET /links/go/:i (counts click per url + 302 redirect). Open-redirect safe: only redirects to a url in the site's own profile_links; http(s)/mailto only.
  • view pages/linkbio.ejs (photo/name/bio + brand-coloured buttons with SVG icons).
  • admin-stats: link-clicks section (top 50, per url) for the current site.
  • admin dashboard: 🔗 Link-in-bio link (premium, non-hub).

node --check passed.

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

  • Property mode set to 100644
File size: 10.1 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 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-voor-email (premium #2)
90
91 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
92 // idempotent so it's safe to run on every boot regardless of DB age.
93 db.exec(`
94 CREATE TABLE IF NOT EXISTS playlists (
95 id TEXT PRIMARY KEY,
96 site_id TEXT NOT NULL,
97 title TEXT NOT NULL,
98 artist TEXT,
99 year INTEGER,
100 cover_url TEXT,
101 kind TEXT DEFAULT 'album',
102 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
103 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
104 FOREIGN KEY (site_id) REFERENCES sites(id)
105 );
106 CREATE TABLE IF NOT EXISTS playlist_tracks (
107 playlist_id TEXT NOT NULL,
108 track_id TEXT NOT NULL,
109 position INTEGER NOT NULL DEFAULT 0,
110 PRIMARY KEY (playlist_id, track_id),
111 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
112 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
113 );
114 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
115 ON playlist_tracks(playlist_id, position);
116 `);
117
118 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
119 // (solo = ÊÊn site, hub = bedrijfssite + /user/). Default = solo.
120 db.exec(`
121 CREATE TABLE IF NOT EXISTS app_settings (
122 key TEXT PRIMARY KEY,
123 value TEXT,
124 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
125 );
126 `);
127 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
128
129 // ── Statistieken (premium) — cookievrij ─────────────────────
130 // stat_daily: per dag per site het aantal pageviews (kale teller).
131 // stat_visitor_day: per dag per site een rij per UNIEKE bezoeker-hash
132 // (sha256 van IP+UA+dag-salt; de salt roteert dagelijks en wordt nooit
133 // bewaard → geen persistente identifier, geen cookie, geen toestemming nodig).
134 db.exec(`
135 CREATE TABLE IF NOT EXISTS stat_daily (
136 site_id TEXT NOT NULL,
137 day TEXT NOT NULL,
138 pageviews INTEGER NOT NULL DEFAULT 0,
139 PRIMARY KEY (site_id, day)
140 );
141 CREATE TABLE IF NOT EXISTS stat_visitor_day (
142 site_id TEXT NOT NULL,
143 day TEXT NOT NULL,
144 visitor_hash TEXT NOT NULL,
145 PRIMARY KEY (site_id, day, visitor_hash)
146 );
147 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
148 `);
149
150 // ── Cirkels (federatie) ─────────────────────────────────────
151 // Decentrale, asymmetrische verbindingen tussen solo-instances.
152 db.exec(`
153 CREATE TABLE IF NOT EXISTS circle_links (
154 id TEXT PRIMARY KEY,
155 local_site_id TEXT NOT NULL,
156 remote_url TEXT NOT NULL,
157 remote_actor_id TEXT,
158 label TEXT,
159 status TEXT DEFAULT 'active',
160 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
161 last_synced DATETIME,
162 last_error TEXT,
163 UNIQUE(local_site_id, remote_url),
164 FOREIGN KEY (local_site_id) REFERENCES sites(id)
165 );
166 CREATE TABLE IF NOT EXISTS remote_actors (
167 id TEXT PRIMARY KEY,
168 url TEXT UNIQUE NOT NULL,
169 name TEXT,
170 summary TEXT,
171 avatar TEXT,
172 public_key TEXT NOT NULL,
173 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
174 );
175 CREATE TABLE IF NOT EXISTS remote_posts (
176 id TEXT PRIMARY KEY,
177 actor_id TEXT NOT NULL,
178 published DATETIME,
179 title TEXT,
180 summary TEXT,
181 url TEXT,
182 media_json TEXT,
183 raw_json TEXT,
184 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
185 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
186 );
187 `);
188
189 // Tags van de originele post — getoond in de cirkel (comma-separated string).
190 ensureColumn('remote_posts', 'tags', 'TEXT');
191
192 // Nieuwsbrief / mailinglijst (premium). Abonnees per site; double opt-in als SMTP
193 // er is (status 'pending' tot bevestigd), anders single opt-in ('confirmed').
194 // 'unsub' = uitgeschreven. token = confirm/unsubscribe-sleutel (in de e-maillinks).
195 db.exec(`
196 CREATE TABLE IF NOT EXISTS subscribers (
197 id TEXT PRIMARY KEY,
198 site_id TEXT NOT NULL,
199 email TEXT NOT NULL,
200 status TEXT NOT NULL DEFAULT 'pending',
201 source TEXT DEFAULT 'widget',
202 token TEXT NOT NULL,
203 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
204 confirmed_at DATETIME,
205 UNIQUE(site_id, email)
206 );
207 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
208 `);
209
210 // Verstuurde nieuwsbrieven (historie + aantallen).
211 db.exec(`
212 CREATE TABLE IF NOT EXISTS newsletters (
213 id TEXT PRIMARY KEY,
214 site_id TEXT NOT NULL,
215 subject TEXT NOT NULL,
216 body TEXT NOT NULL,
217 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
218 recipient_count INTEGER DEFAULT 0
219 );
220 `);
221
222 // Link-in-bio klikstatistiek (premium #6). Per (site, url) een teller; de
223 // link-in-bio-pagina linkt via /links/go/:i dat de klik telt en doorstuurt.
224 db.exec(`
225 CREATE TABLE IF NOT EXISTS link_clicks (
226 site_id TEXT NOT NULL,
227 url TEXT NOT NULL,
228 clicks INTEGER DEFAULT 0,
229 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
230 PRIMARY KEY (site_id, url)
231 );
232 `);
233}
234
235function ensureColumn(table, column, definition) {
236 try {
237 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
238 console.log(`🔧 Added column ${table}.${column}`);
239 } catch (e) {
240 // "duplicate column name" → already there. Anything else, surface it.
241 if (!/duplicate column/i.test(e.message)) {
242 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
243 }
244 }
245}
246
247export default db;
Note: See TracBrowser for help on using the repository browser.