| 1 | /**
|
|---|
| 2 | * Export van een draagbaar inhoudsarchief (shaer-1a6).
|
|---|
| 3 | *
|
|---|
| 4 | * Bouwt precies wat docs/EXPORT-FORMAT.md beschrijft. Lees dat eerst; hier staat
|
|---|
| 5 | * alleen wat de code doet, niet waarom het formaat zo is.
|
|---|
| 6 | *
|
|---|
| 7 | * Twee dingen zijn geen implementatiedetail maar eis:
|
|---|
| 8 | *
|
|---|
| 9 | * REPRODUCEERBAAR Twee exports van ongewijzigde inhoud horen byte-voor-byte
|
|---|
| 10 | * gelijk te zijn, anders is een diff of een checksum nutteloos.
|
|---|
| 11 | * Vandaar gesorteerde sleutels, vaste volgorde, geen tijdstip
|
|---|
| 12 | * in de postbestanden en een vaste mtime in de zip.
|
|---|
| 13 | * GEEN CREDENTIALS Dit is niet de storage-zip uit shaer-190t. Hier komt geen
|
|---|
| 14 | * sleutel, sessie, hash of DM van een ander in.
|
|---|
| 15 | */
|
|---|
| 16 |
|
|---|
| 17 | import fs from 'fs';
|
|---|
| 18 | import path from 'path';
|
|---|
| 19 | import crypto from 'crypto';
|
|---|
| 20 | import db from '../config/database.js';
|
|---|
| 21 | import { MEDIA_ROOT } from '../config/paths.js';
|
|---|
| 22 |
|
|---|
| 23 | export const FORMAT_VERSION = 1;
|
|---|
| 24 |
|
|---|
| 25 | /** JSON met gesorteerde sleutels: zonder vaste volgorde is byte-gelijkheid toeval. */
|
|---|
| 26 | export function stableJson(value) {
|
|---|
| 27 | const sorteer = (v) => {
|
|---|
| 28 | if (Array.isArray(v)) return v.map(sorteer);
|
|---|
| 29 | if (v && typeof v === 'object') {
|
|---|
| 30 | const uit = {};
|
|---|
| 31 | for (const k of Object.keys(v).sort()) if (v[k] !== undefined) uit[k] = sorteer(v[k]);
|
|---|
| 32 | return uit;
|
|---|
| 33 | }
|
|---|
| 34 | return v;
|
|---|
| 35 | };
|
|---|
| 36 | return `${JSON.stringify(sorteer(value), null, 2)}\n`;
|
|---|
| 37 | }
|
|---|
| 38 |
|
|---|
| 39 | const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
|---|
| 40 | /**
|
|---|
| 41 | * Naar ISO 8601 in UTC.
|
|---|
| 42 | *
|
|---|
| 43 | * SQLite schrijft CURRENT_TIMESTAMP als "2026-07-01 12:56:10" -- in UTC, maar
|
|---|
| 44 | * ZONDER zone erbij. Date.parse leest die vorm als LOKALE tijd, en dan schuift
|
|---|
| 45 | * elk tijdstempel in het archief mee met de tijdzone van de machine die de export
|
|---|
| 46 | * draait. Op een server in Amsterdam is dat twee uur, en dat merk je pas als je
|
|---|
| 47 | * ergens anders importeert.
|
|---|
| 48 | *
|
|---|
| 49 | * Gevonden doordat Bart vroeg of dit wel naar UTC normaliseert. De testmachine
|
|---|
| 50 | * draait op UTC, dus geen enkele test kon het zien.
|
|---|
| 51 | */
|
|---|
| 52 | const toISO = (d) => {
|
|---|
| 53 | if (!d) return null;
|
|---|
| 54 | const s = String(d).trim();
|
|---|
| 55 | const zonderZone = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(s);
|
|---|
| 56 | const t = Date.parse(zonderZone ? `${s.replace(' ', 'T')}Z` : s);
|
|---|
| 57 | return isNaN(t) ? null : new Date(t).toISOString();
|
|---|
| 58 | };
|
|---|
| 59 |
|
|---|
| 60 | const MIME_BY_EXT = {
|
|---|
| 61 | jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif',
|
|---|
| 62 | webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml',
|
|---|
| 63 | mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime',
|
|---|
| 64 | mp3: 'audio/mpeg', m4a: 'audio/mp4', ogg: 'audio/ogg', wav: 'audio/wav', flac: 'audio/flac',
|
|---|
| 65 | };
|
|---|
| 66 | const extOf = (u) => ((String(u).split('?')[0].match(/\.(\w+)$/) || [])[1] || '').toLowerCase();
|
|---|
| 67 | const mimeOf = (u) => MIME_BY_EXT[extOf(u)] || 'application/octet-stream';
|
|---|
| 68 | const as2TypeOf = (mime) => (mime.startsWith('video/') ? 'Video' : mime.startsWith('audio/') ? 'Audio' : 'Image');
|
|---|
| 69 |
|
|---|
| 70 | /**
|
|---|
| 71 | * Van een media-URL naar een bestand op schijf.
|
|---|
| 72 | *
|
|---|
| 73 | * /media is een kale express.static op MEDIA_ROOT, dus het URL-pad IS het pad
|
|---|
| 74 | * onder die map. Een absolute URL naar onze eigen origin telt net zo goed als
|
|---|
| 75 | * een pad -- de content slaat allebei op.
|
|---|
| 76 | *
|
|---|
| 77 | * De ../-controle is geen formaliteit: een verzonnen pad in oude inhoud zou
|
|---|
| 78 | * anders een willekeurig bestand van de schijf het archief in trekken.
|
|---|
| 79 | */
|
|---|
| 80 | function localMediaPath(url, origin) {
|
|---|
| 81 | let p = String(url || '');
|
|---|
| 82 | if (!p) return null;
|
|---|
| 83 | if (/^https?:/i.test(p)) {
|
|---|
| 84 | try {
|
|---|
| 85 | const u = new URL(p);
|
|---|
| 86 | if (`${u.protocol}//${u.host}` !== origin) return null; // andermans host: nooit van onze schijf
|
|---|
| 87 | p = u.pathname;
|
|---|
| 88 | } catch { return null; }
|
|---|
| 89 | }
|
|---|
| 90 | if (!p.startsWith('/media/')) return null;
|
|---|
| 91 | const abs = path.resolve(MEDIA_ROOT, decodeURIComponent(p.slice('/media/'.length)));
|
|---|
| 92 | const root = path.resolve(MEDIA_ROOT);
|
|---|
| 93 | if (abs !== root && !abs.startsWith(`${root}${path.sep}`)) return null;
|
|---|
| 94 | return abs;
|
|---|
| 95 | }
|
|---|
| 96 |
|
|---|
| 97 | /** Alle media waar een post naar wijst, in vaste volgorde en zonder dubbelen. */
|
|---|
| 98 | function mediaRefsOf(post, origin) {
|
|---|
| 99 | const uit = [];
|
|---|
| 100 | const zie = new Set();
|
|---|
| 101 | const voegToe = (url, name, rol, extra = {}) => {
|
|---|
| 102 | const u = String(url || '').trim();
|
|---|
| 103 | if (!u || zie.has(u)) return;
|
|---|
| 104 | zie.add(u);
|
|---|
| 105 | uit.push({ url: u, name: name || null, rol, ...extra });
|
|---|
| 106 | };
|
|---|
| 107 | // De ROL is niet decoratief. Zonder rol staat er in het archief wel een
|
|---|
| 108 | // bestand, maar niet dat het de cover was of bij de speler hoorde -- en dan
|
|---|
| 109 | // komt de post na een herstel zonder cover en zonder speler terug. Gevonden
|
|---|
| 110 | // door bij de oefenherstel ALLE kolommen te vergelijken in plaats van een
|
|---|
| 111 | // handjevol.
|
|---|
| 112 | voegToe(post.cover_image_url, post.cover_alt, 'cover');
|
|---|
| 113 | voegToe(post.cover_video_url, post.cover_alt, 'coverVideo');
|
|---|
| 114 | for (const m of String(post.content || '').matchAll(/<img[^>]+src=["']([^"']+)["'][^>]*>/gi)) voegToe(m[1], null, 'inline');
|
|---|
| 115 | try {
|
|---|
| 116 | for (const a of JSON.parse(post.c2s_attachments || '[]')) {
|
|---|
| 117 | voegToe(a && a.url, a && a.name, 'c2s');
|
|---|
| 118 | // Een audio-bijlage draagt een poster (de omslag die de speler toont). Die
|
|---|
| 119 | // staat in een eigen veld en zou anders stil wegvallen -- op beta viel dat
|
|---|
| 120 | // pas op bij de export van echte data.
|
|---|
| 121 | voegToe(a && a.poster, a && a.name ? `${a.name} (poster)` : null, 'poster', { posterFor: a && a.url });
|
|---|
| 122 | }
|
|---|
| 123 | } catch { /* kapotte kolom blokkeert de export niet */ }
|
|---|
| 124 | // Gehoste audio: [[track:id]] verwijst naar een audio_tracks-rij met een media-rij eronder.
|
|---|
| 125 | for (const m of String(post.content || '').matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)) {
|
|---|
| 126 | try {
|
|---|
| 127 | const t = db.prepare('SELECT t.title, m.storage_path FROM audio_tracks t LEFT JOIN media m ON m.id = t.media_id WHERE t.id = ?').get(m[1]);
|
|---|
| 128 | if (t && t.storage_path) voegToe(`/media/${path.relative(path.resolve(MEDIA_ROOT), path.resolve(t.storage_path))}`, t.title, 'track');
|
|---|
| 129 | } catch { /* geen audio-tabellen: niets te doen */ }
|
|---|
| 130 | }
|
|---|
| 131 | return uit;
|
|---|
| 132 | }
|
|---|
| 133 |
|
|---|
| 134 | /**
|
|---|
| 135 | * De audio-metadata die alleen in de database staat en nergens anders uit te
|
|---|
| 136 | * halen is: titel, artiest, credit, licentie, externe links.
|
|---|
| 137 | *
|
|---|
| 138 | * `shaer:media` koppelt de track aan zijn bestand in het archief. Zonder die
|
|---|
| 139 | * verwijzing weet een importer wel dát er een track was en hoe hij heette, maar
|
|---|
| 140 | * niet wélk van de bijlagen erbij hoort -- en dan valt [[track:]] bij een
|
|---|
| 141 | * herstel op niets terug.
|
|---|
| 142 | */
|
|---|
| 143 | function audioOf(post, attachments) {
|
|---|
| 144 | const uit = [];
|
|---|
| 145 | for (const m of String(post.content || '').matchAll(/\[\[track:([A-Za-z0-9_-]+)\]\]/g)) {
|
|---|
| 146 | try {
|
|---|
| 147 | const t = db.prepare('SELECT t.*, md.storage_path FROM audio_tracks t LEFT JOIN media md ON md.id = t.media_id WHERE t.id = ?').get(m[1]);
|
|---|
| 148 | if (!t) continue;
|
|---|
| 149 | let bestand;
|
|---|
| 150 | if (t.storage_path) {
|
|---|
| 151 | const rel = `/media/${path.relative(path.resolve(MEDIA_ROOT), path.resolve(t.storage_path))}`;
|
|---|
| 152 | const bij = attachments.find((a) => String(a['shaer:originalUrl'] || '').endsWith(rel));
|
|---|
| 153 | bestand = bij ? bij.url : undefined;
|
|---|
| 154 | }
|
|---|
| 155 | uit.push({
|
|---|
| 156 | 'shaer:ref': `[[track:${t.id}]]`,
|
|---|
| 157 | 'shaer:media': bestand,
|
|---|
| 158 | name: t.title, artist: t.artist || undefined, album: t.album || undefined,
|
|---|
| 159 | duration: t.duration || undefined, credit: t.credit || undefined, license: t.license || undefined,
|
|---|
| 160 | url: [t.link_spotify, t.link_youtube, t.link_soundcloud].filter(Boolean),
|
|---|
| 161 | });
|
|---|
| 162 | } catch { /* idem */ }
|
|---|
| 163 | }
|
|---|
| 164 | return uit.length ? uit : undefined;
|
|---|
| 165 | }
|
|---|
| 166 |
|
|---|
| 167 | /** Eén post als AS2-object volgens het formaat. Bijlagen komen van de beller. */
|
|---|
| 168 | function postObject(post, site, origin, attachments) {
|
|---|
| 169 | const heeftTitel = !!(post.title && String(post.title).trim());
|
|---|
| 170 | const published = toISO(post.published_at || post.created_at) || toISO(post.created_at);
|
|---|
| 171 | const updated = toISO(post.updated_at);
|
|---|
| 172 | const poll = (() => {
|
|---|
| 173 | try {
|
|---|
| 174 | const d = JSON.parse(post.poll_json || 'null');
|
|---|
| 175 | if (!d || !Array.isArray(d.options) || d.options.length < 2) return null;
|
|---|
| 176 | const opties = d.options.map((o) => ({ type: 'Note', name: String(o && o.name != null ? o.name : o) }));
|
|---|
| 177 | return { multiple: !!d.multiple, opties, endTime: d.endTime || null, closed: !!d.closed };
|
|---|
| 178 | } catch { return null; }
|
|---|
| 179 | })();
|
|---|
| 180 | const tags = [];
|
|---|
| 181 | try {
|
|---|
| 182 | for (const t of String(post.tags || '').split(',').map((x) => x.trim()).filter(Boolean)) {
|
|---|
| 183 | tags.push({ type: 'Hashtag', name: t.startsWith('#') ? t : `#${t}`, href: `${origin}/tag/${encodeURIComponent(t.replace(/^#/, ''))}` });
|
|---|
| 184 | }
|
|---|
| 185 | } catch { /* tags zijn optioneel */ }
|
|---|
| 186 |
|
|---|
| 187 | return {
|
|---|
| 188 | '@context': ['https://www.w3.org/ns/activitystreams', { shaer: 'https://klonkt.com/ns#', toot: 'http://joinmastodon.org/ns#', Hashtag: 'as:Hashtag', sensitive: 'as:sensitive' }],
|
|---|
| 189 | id: `${origin}/ap/notes/${encodeURIComponent(post.id)}`,
|
|---|
| 190 | type: poll ? 'Question' : (heeftTitel ? 'Article' : 'Note'),
|
|---|
| 191 | attributedTo: `${origin}/ap/users/${encodeURIComponent(site.slug)}`,
|
|---|
| 192 | name: heeftTitel ? post.title : undefined,
|
|---|
| 193 | content: post.content || '',
|
|---|
| 194 | contentMap: post.language ? { [post.language]: post.content || '' } : undefined,
|
|---|
| 195 | summary: post.content_warning || undefined,
|
|---|
| 196 | sensitive: post.nsfw ? true : undefined,
|
|---|
| 197 | published,
|
|---|
| 198 | updated: (updated && updated !== published) ? updated : undefined,
|
|---|
| 199 | url: `${origin}/${encodeURIComponent(post.slug)}`,
|
|---|
| 200 | attachment: attachments.length ? attachments : undefined,
|
|---|
| 201 | tag: tags.length ? tags : undefined,
|
|---|
| 202 | ...(poll ? (poll.multiple ? { anyOf: poll.opties } : { oneOf: poll.opties }) : {}),
|
|---|
| 203 | endTime: poll ? (poll.endTime || undefined) : undefined,
|
|---|
| 204 | // AS2 kent `closed` op een Question. Zonder dit staat een poll die vroegtijdig
|
|---|
| 205 | // is gesloten na een herstel weer open -- gevonden op echte beta-data.
|
|---|
| 206 | closed: (poll && poll.closed) ? true : undefined,
|
|---|
| 207 | quoteUrl: post.quote_uri || undefined,
|
|---|
| 208 | 'shaer:quoteActor': post.quote_actor || undefined,
|
|---|
| 209 | 'shaer:slug': post.slug,
|
|---|
| 210 | 'shaer:status': post.status || 'draft',
|
|---|
| 211 | 'shaer:excerpt': post.excerpt || undefined,
|
|---|
| 212 | 'shaer:type': post.type || undefined,
|
|---|
| 213 | 'shaer:pinned': post.pinned ? true : undefined,
|
|---|
| 214 | 'shaer:noindex': post.noindex ? true : undefined,
|
|---|
| 215 | 'shaer:fanOnly': post.fan_only ? true : undefined,
|
|---|
| 216 | 'shaer:paid': post.paid ? true : undefined,
|
|---|
| 217 | 'shaer:paidMinCents': post.paid ? (post.paid_min_cents || undefined) : undefined,
|
|---|
| 218 | 'shaer:apVisibility': post.ap_visibility || undefined,
|
|---|
| 219 | 'shaer:publishAt': toISO(post.publish_at) || undefined,
|
|---|
| 220 | 'shaer:coverAlt': post.cover_alt || undefined,
|
|---|
| 221 | 'shaer:viewCount': post.view_count || undefined,
|
|---|
| 222 | 'shaer:audio': audioOf(post, attachments),
|
|---|
| 223 | };
|
|---|
| 224 | }
|
|---|
| 225 |
|
|---|
| 226 | /** De leesbare kopie. Afgeleid, eenrichtingsverkeer -- de importer kijkt hier nooit naar. */
|
|---|
| 227 | function readableMarkdown(post, obj) {
|
|---|
| 228 | const fm = [
|
|---|
| 229 | '---',
|
|---|
| 230 | `title: ${JSON.stringify(post.title || post.slug)}`,
|
|---|
| 231 | `slug: ${JSON.stringify(post.slug)}`,
|
|---|
| 232 | `date: ${obj.published || ''}`,
|
|---|
| 233 | `status: ${post.status || 'draft'}`,
|
|---|
| 234 | post.content_warning ? `content_warning: ${JSON.stringify(post.content_warning)}` : null,
|
|---|
| 235 | '---',
|
|---|
| 236 | ].filter((l) => l !== null).join('\n');
|
|---|
| 237 | return `${fm}\n${post.content || ''}\n`;
|
|---|
| 238 | }
|
|---|
| 239 |
|
|---|
| 240 | /**
|
|---|
| 241 | * Bouw het archief als een lijst bestanden: pad -> inhoud (Buffer).
|
|---|
| 242 | *
|
|---|
| 243 | * Bewust geen schrijven naar schijf hier: dat maakt de vorm testbaar zonder
|
|---|
| 244 | * tijdelijke mappen, en de beller bepaalt of het een map of een zip wordt.
|
|---|
| 245 | */
|
|---|
| 246 | export function buildArchive(slug, opts = {}) {
|
|---|
| 247 | const origin = (opts.origin || process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 248 | const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
|
|---|
| 249 | if (!site) {
|
|---|
| 250 | // De naam van de INSTANCE (de map, de unit) en de slug van de SITE in zijn
|
|---|
| 251 | // database zijn twee dingen. Ze vallen vaak samen en soms niet, en dan zat je
|
|---|
| 252 | // met een foutmelding die je liet raden. Zeg dus wat er wel in staat.
|
|---|
| 253 | let bestaand = [];
|
|---|
| 254 | try { bestaand = db.prepare('SELECT slug FROM sites ORDER BY rowid').all().map((r) => r.slug); } catch { /* geen sites-tabel */ }
|
|---|
| 255 | const wat = slug ? `onbekende site: ${slug}` : 'geen site opgegeven';
|
|---|
| 256 | throw new Error(bestaand.length
|
|---|
| 257 | ? `${wat}. In deze database staat: ${bestaand.join(', ')}`
|
|---|
| 258 | : `${wat}. In deze database staat geen enkele site -- wijst DATABASE_PATH naar de juiste?`);
|
|---|
| 259 | }
|
|---|
| 260 |
|
|---|
| 261 | const bestanden = new Map(); // pad -> Buffer
|
|---|
| 262 | const tellingen = { posts: 0, replies: 0, media: 0, mediaMissing: 0 };
|
|---|
| 263 | const ontbrekend = []; // voor de rapportage van de beller
|
|---|
| 264 |
|
|---|
| 265 | // Vaste volgorde: eerst op publicatiedatum, dan op id. Zonder tweede sleutel
|
|---|
| 266 | // is de volgorde van twee posts op dezelfde seconde niet bepaald.
|
|---|
| 267 | const posts = db.prepare(`SELECT * FROM posts WHERE site_id = ?
|
|---|
| 268 | ORDER BY COALESCE(published_at, created_at) ASC, id ASC`).all(site.id);
|
|---|
| 269 |
|
|---|
| 270 | for (const post of posts) {
|
|---|
| 271 | const attachments = [];
|
|---|
| 272 | for (const ref of mediaRefsOf(post, origin)) {
|
|---|
| 273 | const schijf = localMediaPath(ref.url, origin);
|
|---|
| 274 | const mime = mimeOf(ref.url);
|
|---|
| 275 | let bytes = null;
|
|---|
| 276 | if (schijf) { try { bytes = fs.readFileSync(schijf); } catch { bytes = null; } }
|
|---|
| 277 | if (bytes) {
|
|---|
| 278 | const hash = sha256(bytes);
|
|---|
| 279 | const naam = `media/${hash}${extOf(ref.url) ? `.${extOf(ref.url)}` : ''}`;
|
|---|
| 280 | if (!bestanden.has(naam)) { bestanden.set(naam, bytes); tellingen.media += 1; }
|
|---|
| 281 | attachments.push({
|
|---|
| 282 | type: as2TypeOf(mime), mediaType: mime, name: ref.name || undefined,
|
|---|
| 283 | url: naam, 'shaer:availability': 'included',
|
|---|
| 284 | 'shaer:originalUrl': /^https?:/i.test(ref.url) ? ref.url : `${origin}${ref.url}`,
|
|---|
| 285 | 'shaer:sha256': hash,
|
|---|
| 286 | 'shaer:role': ref.rol,
|
|---|
| 287 | 'shaer:posterFor': ref.posterFor || undefined,
|
|---|
| 288 | });
|
|---|
| 289 | } else {
|
|---|
| 290 | // De derde staat uit het formaat: we weten DAT het bestond en waar het
|
|---|
| 291 | // stond, maar we hebben de bytes niet. Stil weglaten zou een leugen zijn.
|
|---|
| 292 | tellingen.mediaMissing += 1;
|
|---|
| 293 | const orig = /^https?:/i.test(ref.url) ? ref.url : `${origin}${ref.url}`;
|
|---|
| 294 | ontbrekend.push({ post: post.slug, url: orig });
|
|---|
| 295 | attachments.push({
|
|---|
| 296 | type: as2TypeOf(mime), mediaType: mime, name: ref.name || undefined,
|
|---|
| 297 | url: orig, 'shaer:availability': 'missing', 'shaer:originalUrl': orig,
|
|---|
| 298 | 'shaer:role': ref.rol,
|
|---|
| 299 | 'shaer:posterFor': ref.posterFor || undefined,
|
|---|
| 300 | });
|
|---|
| 301 | }
|
|---|
| 302 | }
|
|---|
| 303 |
|
|---|
| 304 | const obj = postObject(post, site, origin, attachments);
|
|---|
| 305 | bestanden.set(`posts/${post.id}.json`, Buffer.from(stableJson(obj), 'utf8'));
|
|---|
| 306 | bestanden.set(`readable/${post.slug}.md`, Buffer.from(readableMarkdown(post, obj), 'utf8'));
|
|---|
| 307 | tellingen.posts += 1;
|
|---|
| 308 |
|
|---|
| 309 | // Antwoorden van anderen: alleen-lezen archief, nooit opnieuw bezorgd.
|
|---|
| 310 | let replies = [];
|
|---|
| 311 | try {
|
|---|
| 312 | replies = db.prepare(`SELECT * FROM ap_interactions WHERE post_id = ? AND kind = 'reply'
|
|---|
| 313 | ORDER BY COALESCE(published, created_at) ASC, id ASC`).all(post.id);
|
|---|
| 314 | } catch { /* tabel kan ontbreken op een heel oude database */ }
|
|---|
| 315 | if (replies.length) {
|
|---|
| 316 | const coll = {
|
|---|
| 317 | '@context': ['https://www.w3.org/ns/activitystreams', { shaer: 'https://klonkt.com/ns#' }],
|
|---|
| 318 | type: 'OrderedCollection',
|
|---|
| 319 | 'shaer:archive': true,
|
|---|
| 320 | 'shaer:inReplyTo': obj.id,
|
|---|
| 321 | totalItems: replies.length,
|
|---|
| 322 | orderedItems: replies.map((r) => ({
|
|---|
| 323 | id: r.object_uri || undefined,
|
|---|
| 324 | type: 'Note',
|
|---|
| 325 | attributedTo: r.actor_uri || undefined,
|
|---|
| 326 | inReplyTo: r.parent_uri || obj.id,
|
|---|
| 327 | content: r.content || '',
|
|---|
| 328 | published: toISO(r.published || r.created_at) || undefined,
|
|---|
| 329 | 'shaer:actorName': r.actor_name || undefined,
|
|---|
| 330 | 'shaer:actorHandle': r.actor_handle || undefined,
|
|---|
| 331 | })),
|
|---|
| 332 | };
|
|---|
| 333 | bestanden.set(`replies/${post.id}.json`, Buffer.from(stableJson(coll), 'utf8'));
|
|---|
| 334 | tellingen.replies += replies.length;
|
|---|
| 335 | }
|
|---|
| 336 | }
|
|---|
| 337 |
|
|---|
| 338 | const files = {};
|
|---|
| 339 | for (const pad of [...bestanden.keys()].sort()) files[pad] = sha256(bestanden.get(pad));
|
|---|
| 340 | const manifest = {
|
|---|
| 341 | formatVersion: FORMAT_VERSION,
|
|---|
| 342 | generator: `klonkt/${opts.version || 'dev'}`,
|
|---|
| 343 | exportedAt: opts.exportedAt || new Date().toISOString(),
|
|---|
| 344 | origin,
|
|---|
| 345 | actor: `${origin}/ap/users/${encodeURIComponent(site.slug)}`,
|
|---|
| 346 | site: { slug: site.slug, title: site.title || site.slug },
|
|---|
| 347 | counts: tellingen,
|
|---|
| 348 | files,
|
|---|
| 349 | };
|
|---|
| 350 | bestanden.set('manifest.json', Buffer.from(stableJson(manifest), 'utf8'));
|
|---|
| 351 |
|
|---|
| 352 | return { files: bestanden, manifest, counts: tellingen, missing: ontbrekend };
|
|---|
| 353 | }
|
|---|
| 354 |
|
|---|
| 355 | // ── Zip, store-only en deterministisch ────────────────────────────
|
|---|
| 356 | // Geen nieuwe afhankelijkheid, en zonder compressie is byte-gelijkheid geen
|
|---|
| 357 | // kwestie van vertrouwen in de instellingen van een bibliotheek. De mtime is
|
|---|
| 358 | // vast (1980-01-01, de nul van het zip-formaat) om dezelfde reden.
|
|---|
| 359 |
|
|---|
| 360 | const _crcTabel = (() => {
|
|---|
| 361 | const t = new Int32Array(256);
|
|---|
| 362 | for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c; }
|
|---|
| 363 | return t;
|
|---|
| 364 | })();
|
|---|
| 365 | function crc32(buf) {
|
|---|
| 366 | let c = 0 ^ -1;
|
|---|
| 367 | for (let i = 0; i < buf.length; i++) c = (c >>> 8) ^ _crcTabel[(c ^ buf[i]) & 0xFF];
|
|---|
| 368 | return (c ^ -1) >>> 0;
|
|---|
| 369 | }
|
|---|
| 370 |
|
|---|
| 371 | export function zipArchive(files) {
|
|---|
| 372 | const paden = [...files.keys()].sort();
|
|---|
| 373 | const lokaal = [];
|
|---|
| 374 | const centraal = [];
|
|---|
| 375 | let offset = 0;
|
|---|
| 376 | for (const pad of paden) {
|
|---|
| 377 | const naam = Buffer.from(pad, 'utf8');
|
|---|
| 378 | const data = files.get(pad);
|
|---|
| 379 | const crc = crc32(data);
|
|---|
| 380 | const lh = Buffer.alloc(30);
|
|---|
| 381 | lh.writeUInt32LE(0x04034b50, 0); lh.writeUInt16LE(20, 4); lh.writeUInt16LE(0x0800, 6);
|
|---|
| 382 | lh.writeUInt16LE(0, 8); // store, geen compressie
|
|---|
| 383 | lh.writeUInt16LE(0, 10); lh.writeUInt16LE(33, 12); // vaste tijd: 1980-01-01
|
|---|
| 384 | lh.writeUInt32LE(crc, 14); lh.writeUInt32LE(data.length, 18); lh.writeUInt32LE(data.length, 22);
|
|---|
| 385 | lh.writeUInt16LE(naam.length, 26); lh.writeUInt16LE(0, 28);
|
|---|
| 386 | lokaal.push(lh, naam, data);
|
|---|
| 387 |
|
|---|
| 388 | const ch = Buffer.alloc(46);
|
|---|
| 389 | ch.writeUInt32LE(0x02014b50, 0); ch.writeUInt16LE(20, 4); ch.writeUInt16LE(20, 6);
|
|---|
| 390 | ch.writeUInt16LE(0x0800, 8); ch.writeUInt16LE(0, 10);
|
|---|
| 391 | ch.writeUInt16LE(0, 12); ch.writeUInt16LE(33, 14);
|
|---|
| 392 | ch.writeUInt32LE(crc, 16); ch.writeUInt32LE(data.length, 20); ch.writeUInt32LE(data.length, 24);
|
|---|
| 393 | ch.writeUInt16LE(naam.length, 28); ch.writeUInt16LE(0, 30); ch.writeUInt16LE(0, 32);
|
|---|
| 394 | ch.writeUInt16LE(0, 34); ch.writeUInt16LE(0, 36); ch.writeUInt32LE(0, 38);
|
|---|
| 395 | ch.writeUInt32LE(offset, 42);
|
|---|
| 396 | centraal.push(ch, naam);
|
|---|
| 397 | offset += 30 + naam.length + data.length;
|
|---|
| 398 | }
|
|---|
| 399 | const cd = Buffer.concat(centraal);
|
|---|
| 400 | const eocd = Buffer.alloc(22);
|
|---|
| 401 | eocd.writeUInt32LE(0x06054b50, 0);
|
|---|
| 402 | eocd.writeUInt16LE(paden.length, 8); eocd.writeUInt16LE(paden.length, 10);
|
|---|
| 403 | eocd.writeUInt32LE(cd.length, 12); eocd.writeUInt32LE(offset, 16);
|
|---|
| 404 | return Buffer.concat([...lokaal, cd, eocd]);
|
|---|
| 405 | }
|
|---|
| 406 |
|
|---|
| 407 | /** Schrijf het archief als losse bestanden naar een map. */
|
|---|
| 408 | export function writeArchiveDir(files, dir) {
|
|---|
| 409 | for (const pad of [...files.keys()].sort()) {
|
|---|
| 410 | const doel = path.join(dir, pad);
|
|---|
| 411 | fs.mkdirSync(path.dirname(doel), { recursive: true });
|
|---|
| 412 | fs.writeFileSync(doel, files.get(pad));
|
|---|
| 413 | }
|
|---|
| 414 | }
|
|---|