source: Klonkt/src/config/database.js@ 0688b5f

main
Last change on this file since 0688b5f was 0688b5f, checked in by roboburr <roboburr@…>, 2 months ago

feat(fediverse): post language → AS2 contentMap

A post can now carry a language; it federates as an AS2 contentMap (a BCP-47-keyed
copy of the content, alongside plain content) so Mastodon's timeline language filter
and translate button work. Editor gets a language picker (defaults to the author's
UI language).

  • src/config/database.js — posts.language column.
  • src/services/ActivityPubService.js — buildNote emits contentMap { <lang>: content } when the post has a valid BCP-47 language.
  • src/routes/posts.js — capture/validate/store language on create/save (default = the author's current language) and pass it to the federation hooks.
  • src/services/Scheduler.js — carry language when a scheduled post goes live.
  • src/views/pages/post-edit.ejs — language <select> (18 common languages).
  • src/services/i18n.js — pedit.f_language + pedit.language_hint (nl/en/de).
  • test/activitypub-as2.test.js — allow contentMap/nameMap/summaryMap; don't treat a language-map's keys as vocab terms; kitchen-sink post now sets a language.
  • test/post-language.test.js — contentMap shape, no-language, invalid-code = ignored.
  • CHANGELOG(.nl/.de).md — "Set a post's language" under Unreleased.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 17.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// With WAL + several concurrent writers (request handlers, the delivery worker, the
20// background thread-crawler) a short write-lock should retry rather than throw SQLITE_BUSY.
21db.pragma('busy_timeout = 5000'); // wait up to 5s for a lock instead of failing immediately
22db.pragma('synchronous = NORMAL'); // safe with WAL (no torn writes); fewer fsyncs = faster writes
23
24export function initializeDatabase() {
25 const tableExists = db.prepare(`
26 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
27 `).get();
28
29 if (!tableExists) {
30 console.log('🔧 Initializing database schema...');
31 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
32 const schema = fs.readFileSync(schemaPath, 'utf-8');
33 db.exec(schema);
34 console.log('✅ Database initialized with v9-soul schema');
35 }
36
37 // Additive column migrations — safe to run every boot.
38 // SQLite throws if the column already exists; we swallow that.
39 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
40 ensureColumn('sites', 'profile_photo', 'TEXT');
41 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
42 ensureColumn('audio_tracks', 'album', 'TEXT');
43 ensureColumn('users', 'reset_token', 'TEXT');
44 ensureColumn('users', 'reset_token_expires', 'DATETIME');
45 // Google OAuth: link a Google account to a user (login via Google).
46 ensureColumn('users', 'google_sub', 'TEXT');
47 // Read-only/viewer account: can view everything but make no changes.
48 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
49 // Personal interface language (nl|en|de). Null = follow the default (site/env/browser).
50 ensureColumn('users', 'lang', 'TEXT');
51 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
52 // Circles: whether this site may appear in other sites' circles (surfacing opt-out).
53 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
54
55 // One EXPLICIT primary/main site (= the company/label site in hub mode,
56 // the only site in solo) instead of the fragile "oldest = main" convention
57 // that was duplicated in 4 places. Backfill: mark the oldest if no primary
58 // site exists yet, so existing behaviour is preserved exactly.
59 ensureColumn('sites', 'is_primary', 'INTEGER DEFAULT 0');
60 try {
61 const hasPrimary = db.prepare('SELECT 1 FROM sites WHERE is_primary = 1 LIMIT 1').get();
62 if (!hasPrimary) {
63 const oldest = db.prepare('SELECT id FROM sites ORDER BY created_at ASC LIMIT 1').get();
64 if (oldest) db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(oldest.id);
65 }
66 } catch (e) { /* sites table still empty/absent on fresh init — ensurePrimarySite handles it */ }
67
68 // v9 audit additions —————————————————————————————————————————
69 // SEO/social columns the v9 template uses (most live in 001-init.sql already
70 // for fresh DBs but ensureColumn is idempotent for existing DBs).
71 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
72 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
73 ensureColumn('sites', 'publisher_name', 'TEXT');
74 ensureColumn('sites', 'publisher_url', 'TEXT');
75 ensureColumn('sites', 'publisher_logo', 'TEXT');
76 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
77 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
78 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
79 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
80 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
81 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
82 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
83 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
84
85 // Per-post noindex + type
86 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
87 ensureColumn('posts', 'publish_at', 'DATETIME'); // release planning (premium #3): scheduled go-live
88 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
89 ensureColumn('posts', 'nsfw', 'INTEGER DEFAULT 0'); // sensitive content → blur + click-to-reveal; fediverse sensitive
90 ensureColumn('posts', 'cover_video_url', 'TEXT'); // muted loop MP4 for an animated cover (Safari-smooth)
91 ensureColumn('posts', 'cover_alt', 'TEXT'); // alt text / description for the cover (a11y → AS2 attachment `name`)
92 ensureColumn('posts', 'language', 'TEXT'); // BCP-47 content language → federates as AS2 contentMap (Mastodon language filter/translate)
93 ensureColumn('posts', 'content_warning', 'TEXT'); // custom CW label (empty = default "Gevoelige inhoud")
94 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
95 ensureColumn('posts', 'poll_json', 'TEXT'); // a poll WE host → federates as AS2 Question: {multiple,options[{name}],endTime,closed}
96
97 // Statistics (premium module) — bare counters, cookie-free.
98 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
99 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
100 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-for-email (premium #2)
101 ensureColumn('audio_tracks', 'credit', 'TEXT'); // owner/credit (copyright holder)
102 ensureColumn('audio_tracks', 'license', 'TEXT'); // license (e.g. "CC BY 4.0", "All rights reserved")
103 ensureColumn('audio_tracks', 'link_spotify', 'TEXT'); // "open in" links per track
104 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
105 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
106 // Per-track: federate the actual audio file as an AS2 Audio attachment so it plays inline
107 // in EVERY fediverse client (incl. the Mastodon apps). Default 0 = gated (web player only,
108 // file not exposed). Opt-in 1 = the file is served ungated + shared on the fediverse.
109 ensureColumn('audio_tracks', 'fedi_open', 'INTEGER DEFAULT 0');
110
111 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
112 // idempotent so it's safe to run on every boot regardless of DB age.
113 db.exec(`
114 CREATE TABLE IF NOT EXISTS playlists (
115 id TEXT PRIMARY KEY,
116 site_id TEXT NOT NULL,
117 title TEXT NOT NULL,
118 artist TEXT,
119 year INTEGER,
120 cover_url TEXT,
121 kind TEXT DEFAULT 'album',
122 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
123 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
124 FOREIGN KEY (site_id) REFERENCES sites(id)
125 );
126 CREATE TABLE IF NOT EXISTS playlist_tracks (
127 playlist_id TEXT NOT NULL,
128 track_id TEXT NOT NULL,
129 position INTEGER NOT NULL DEFAULT 0,
130 PRIMARY KEY (playlist_id, track_id),
131 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
132 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
133 );
134 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
135 ON playlist_tracks(playlist_id, position);
136 `);
137
138 // Global app settings (key/value singleton). Includes the tenancy mode
139 // (solo = one site, hub = company site + /user/). Default = solo.
140 db.exec(`
141 CREATE TABLE IF NOT EXISTS app_settings (
142 key TEXT PRIMARY KEY,
143 value TEXT,
144 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
145 );
146 `);
147 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
148
149 // ── Statistics (premium) — cookie-free ──────────────────────
150 // stat_daily: pageview count per day per site (bare counter).
151 // stat_visitor_day: one row per UNIQUE visitor hash per day per site
152 // (sha256 of IP+UA+day-salt; the salt rotates daily and is never stored
153 // → no persistent identifier, no cookie, no consent required).
154 db.exec(`
155 CREATE TABLE IF NOT EXISTS stat_daily (
156 site_id TEXT NOT NULL,
157 day TEXT NOT NULL,
158 pageviews INTEGER NOT NULL DEFAULT 0,
159 PRIMARY KEY (site_id, day)
160 );
161 CREATE TABLE IF NOT EXISTS stat_visitor_day (
162 site_id TEXT NOT NULL,
163 day TEXT NOT NULL,
164 visitor_hash TEXT NOT NULL,
165 PRIMARY KEY (site_id, day, visitor_hash)
166 );
167 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
168 CREATE TABLE IF NOT EXISTS stat_referrer (
169 site_id TEXT NOT NULL,
170 host TEXT NOT NULL,
171 count INTEGER NOT NULL DEFAULT 0,
172 PRIMARY KEY (site_id, host)
173 );
174 `);
175
176 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
177 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
178 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
179 db.exec(`
180 CREATE TABLE IF NOT EXISTS subscribers (
181 id TEXT PRIMARY KEY,
182 site_id TEXT NOT NULL,
183 email TEXT NOT NULL,
184 status TEXT NOT NULL DEFAULT 'pending',
185 source TEXT DEFAULT 'widget',
186 token TEXT NOT NULL,
187 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
188 confirmed_at DATETIME,
189 UNIQUE(site_id, email)
190 );
191 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
192 `);
193
194 // Sent newsletters (history + counts).
195 db.exec(`
196 CREATE TABLE IF NOT EXISTS newsletters (
197 id TEXT PRIMARY KEY,
198 site_id TEXT NOT NULL,
199 subject TEXT NOT NULL,
200 body TEXT NOT NULL,
201 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
202 recipient_count INTEGER DEFAULT 0
203 );
204 `);
205
206 // Show agenda (premium #8): tour dates / gigs per site.
207 db.exec(`
208 CREATE TABLE IF NOT EXISTS shows (
209 id TEXT PRIMARY KEY,
210 site_id TEXT NOT NULL,
211 date TEXT NOT NULL,
212 time TEXT,
213 city TEXT NOT NULL,
214 venue TEXT,
215 country TEXT,
216 ticket_url TEXT,
217 notes TEXT,
218 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
219 );
220 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
221 `);
222
223 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
224 // link-in-bio page links via /links/go/:i which counts the click and redirects.
225 db.exec(`
226 CREATE TABLE IF NOT EXISTS link_clicks (
227 site_id TEXT NOT NULL,
228 url TEXT NOT NULL,
229 clicks INTEGER DEFAULT 0,
230 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
231 PRIMARY KEY (site_id, url)
232 );
233 `);
234
235
236 // ── ActivityPub (fediverse bridge) ──────────────────────────
237 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
238 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
239 db.exec(`
240 CREATE TABLE IF NOT EXISTS ap_keys (
241 slug TEXT PRIMARY KEY,
242 public_pem TEXT NOT NULL,
243 private_pem TEXT NOT NULL,
244 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
245 );
246 CREATE TABLE IF NOT EXISTS ap_followers (
247 id INTEGER PRIMARY KEY AUTOINCREMENT,
248 slug TEXT NOT NULL,
249 actor_uri TEXT NOT NULL,
250 inbox TEXT,
251 shared_inbox TEXT,
252 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
253 UNIQUE(slug, actor_uri)
254 );
255 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
256 CREATE TABLE IF NOT EXISTS ap_interactions (
257 id INTEGER PRIMARY KEY AUTOINCREMENT,
258 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
259 post_id TEXT NOT NULL,
260 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
261 actor_uri TEXT NOT NULL,
262 actor_name TEXT,
263 actor_handle TEXT,
264 actor_url TEXT,
265 actor_icon TEXT,
266 content TEXT, -- sanitized HTML (reply)
267 published TEXT,
268 parent_uri TEXT, -- the note this reply replies to (for nesting)
269 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
270 UNIQUE(kind, post_id, actor_uri, object_uri)
271 );
272 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
273 CREATE TABLE IF NOT EXISTS ap_outbox (
274 id TEXT PRIMARY KEY, -- note path segment (uuid) → /ap/notes/<id>
275 site_slug TEXT NOT NULL,
276 post_id TEXT NOT NULL,
277 post_slug TEXT,
278 in_reply_to TEXT, -- remote status uri we reply to
279 to_actor TEXT, -- remote actor uri (mentioned)
280 to_handle TEXT,
281 content TEXT NOT NULL, -- sanitized HTML of our reply
282 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
283 );
284 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
285 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
286 CREATE TABLE IF NOT EXISTS ap_my_reactions (
287 site_slug TEXT NOT NULL,
288 target_uri TEXT NOT NULL,
289 kind TEXT NOT NULL, -- 'like' | 'boost'
290 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
291 UNIQUE(site_slug, target_uri, kind)
292 );
293 `);
294 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
295 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (🔁) → can undo
296 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (⭐) → can undo
297
298 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
299 db.exec(`
300 CREATE TABLE IF NOT EXISTS ap_following (
301 id INTEGER PRIMARY KEY AUTOINCREMENT,
302 slug TEXT NOT NULL, -- our site that follows
303 actor_uri TEXT NOT NULL, -- the followed account's actor id
304 handle TEXT, name TEXT, icon TEXT, url TEXT,
305 inbox TEXT, -- their inbox (for Create delivery / Undo)
306 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
307 status TEXT DEFAULT 'pending', -- pending | accepted
308 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
309 UNIQUE(slug, actor_uri)
310 );
311 CREATE TABLE IF NOT EXISTS ap_timeline (
312 id TEXT NOT NULL, -- the remote note's AP id
313 slug TEXT NOT NULL, -- whose home timeline (our site)
314 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
315 content TEXT, url TEXT, published TEXT, media_json TEXT,
316 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
317 UNIQUE(slug, id)
318 );
319 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
320 CREATE TABLE IF NOT EXISTS ap_blocks (
321 id INTEGER PRIMARY KEY AUTOINCREMENT,
322 slug TEXT NOT NULL, -- our site that set the block
323 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
324 kind TEXT NOT NULL, -- 'actor' | 'domain'
325 label TEXT, -- display (@handle or domain)
326 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
327 UNIQUE(slug, target)
328 );
329 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
330 CREATE TABLE IF NOT EXISTS ap_delivery (
331 id INTEGER PRIMARY KEY AUTOINCREMENT,
332 slug TEXT NOT NULL, -- our site/actor that signs the delivery
333 inbox TEXT NOT NULL, -- recipient inbox URL
334 body TEXT NOT NULL, -- the activity JSON to POST
335 attempts INTEGER NOT NULL DEFAULT 0,
336 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
337 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
338 );
339 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
340 CREATE TABLE IF NOT EXISTS poll_votes (
341 id INTEGER PRIMARY KEY AUTOINCREMENT,
342 post_id INTEGER NOT NULL, -- our local poll post (posts.id)
343 actor_uri TEXT NOT NULL, -- the remote voter's AP actor URI
344 choice TEXT NOT NULL, -- the chosen option's name (matches poll_json options[].name)
345 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
346 UNIQUE(post_id, actor_uri, choice)
347 );
348 CREATE INDEX IF NOT EXISTS idx_poll_votes_post ON poll_votes(post_id);
349 `);
350 // "Feature" a followed account: its posts show in the local Cirkel.
351 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
352 // A timeline post you boosted (🔁) — also shown in the Cirkel (mixed by date).
353 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
354 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (⭐) → toggle
355 ensureColumn('ap_timeline', 'nsfw', 'INTEGER DEFAULT 0'); // remote sensitive post → blur in the Cirkel
356 ensureColumn('ap_timeline', 'cw', 'TEXT'); // remote content-warning text
357 ensureColumn('ap_timeline', 'reblog_name', 'TEXT'); // a followed account boosted this → "X boosted"
358 ensureColumn('ap_timeline', 'reblog_handle', 'TEXT'); // the booster's @handle
359 ensureColumn('ap_timeline', 'reblog_icon', 'TEXT'); // the booster's avatar
360 ensureColumn('ap_timeline', 'poll_json', 'TEXT'); // a Question (poll): {multiple,options[{name,count}],endTime,closed,voters,voted}
361}
362
363function ensureColumn(table, column, definition) {
364 try {
365 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
366 console.log(`🔧 Added column ${table}.${column}`);
367 } catch (e) {
368 // "duplicate column name" → already there. Anything else, surface it.
369 if (!/duplicate column/i.test(e.message)) {
370 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
371 }
372 }
373}
374
375export default db;
Note: See TracBrowser for help on using the repository browser.