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

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

Release scheduling + fan-only previews (premium feature #3)

  • DB: posts.publish_at (scheduled go-live) + posts.fan_only.
  • Release scheduling: published + future publish_at -> status 'scheduled' (excluded from public status='published' queries). Scheduler.js publishes them when the time is reached (setInterval 60s + on boot) + adds them to posts_fts. No public queries changed -> low risk.
  • Fan-only: posts.fan_only; the single-post view shows anonymous visitors a clean login gate (pages/fan-gate.ejs, link /auth/login?next=) instead of the content; logged-in fans see everything. Listings show the teaser.
  • create/save: read publish_at + fan_only; FTS excludes 'scheduled'.
  • editor (post-edit): premium-gated fields "Fans only" + "Publish on" (datetime-local) + "scheduled for" notice.
  • server.js: startScheduler() after initializeDatabase.

node --check passed.

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

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