aboutsummaryrefslogtreecommitdiffstats
path: root/tools/blob-alt-test.js
diff options
context:
space:
mode:
Diffstat (limited to 'tools/blob-alt-test.js')
-rw-r--r--tools/blob-alt-test.js92
1 files changed, 92 insertions, 0 deletions
diff --git a/tools/blob-alt-test.js b/tools/blob-alt-test.js
new file mode 100644
index 0000000..4d958f2
--- /dev/null
+++ b/tools/blob-alt-test.js
@@ -0,0 +1,92 @@
+// A face or banner whose host has lost the file is found on another server
+// that holds the same Blossom blob (same sha256 name): the one the person
+// publishes in their kind 10063 first. The small avatar's thumbnail is made
+// from the copy, the profile page's big face and banner paint from it, and
+// the find is remembered on the device.
+// Run: bun tools/blob-alt-test.js
+import assert from 'node:assert/strict';
+import puppeteer from './puppeteer.js';
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+import { nip19 } from 'nostr-tools';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const sk = generateSecretKey(), PK = getPublicKey(sk), now = Math.floor(Date.now() / 1000);
+const H1 = 'c11a29785c1af623a45ebfdb23860170a9d0c0ead31c1bcb209085cd662f7a17';
+const H2 = '479711427c577f040a5bf8cb05c47f75abfef37580893dd63b66f777c34dc327';
+const png = (color) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', `color=c=${color}:size=320x320`, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout;
+const FACE = png('orange'), COVER = png('teal');
+const html = await buildHtml({ minify: true, pwa: false });
+const hits = { dead: 0, alt: 0 };
+let origin = '';
+const server = Bun.serve({ port: 0, fetch: (req) => {
+ const u = new URL(req.url);
+ if (u.pathname.startsWith('/dead/')) { hits.dead++; return new Response('{"error":"The requested blob was not found."}', { status: 404, headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } }); }
+ if (u.pathname === `/alt/${H1}.png`) { hits.alt++; return new Response(FACE, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); }
+ if (u.pathname === `/alt/${H2}.png`) { hits.alt++; return new Response(COVER, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); }
+ if (u.pathname === '/api/feed') return new Response(snapshot, { headers: { 'content-type': 'application/json' } });
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } });
+} });
+origin = server.url.origin;
+const notes = Array.from({ length: 12 }, (_, i) => finalizeEvent({ kind: 1, created_at: now - 60 - i * 60, tags: [], content: `Post ${i}: the harbour at dusk, boats coming in.` }, sk));
+const profile = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Karnage', picture: `${origin}/dead/${H1}.png`, banner: `${origin}/dead/${H2}.png`, about: 'Saying the quiet part out loud.' }) }, sk);
+const servers = finalizeEvent({ kind: 10063, created_at: now, tags: [['server', `${origin}/alt/`]], content: '' }, sk);
+const snapshot = JSON.stringify({ version: 1, generatedAt: Date.now(), notes, profiles: [profile], popUntil: now - 3600 });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage();
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e)));
+ await page.setViewport({ width: 390, height: 844, isMobile: true, hasTouch: true });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(origin) ? r.continue() : r.abort()); // the public hosts: unreachable here
+ await page.evaluateOnNewDocument(([notes, profile, servers]) => {
+ class FakeSocket extends EventTarget {
+ constructor(url) { super(); this.url = url; this.readyState = 0; this.subs = new Set();
+ setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0); }
+ emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); }
+ message(d) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(d) })); }
+ send(raw) {
+ let m; try { m = JSON.parse(raw); } catch { return; }
+ if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; }
+ if (m[0] !== 'REQ') return;
+ const [, id, f] = m; this.subs.add(id);
+ let evs = [];
+ if (f.kinds?.includes(1) && !f.since) evs = notes.filter((e) => (!f.until || e.created_at <= f.until)
+ && (!f.authors || f.authors.includes(e.pubkey)) && (!f.ids || f.ids.includes(e.id))).slice(0, f.limit || 100);
+ if (f.kinds?.includes(0) && f.authors?.includes(profile.pubkey)) evs = [profile];
+ if (f.kinds?.includes(10063) && f.authors?.includes(servers.pubkey)) evs = [servers];
+ if (f.ids) evs = notes.filter((e) => f.ids.includes(e.id));
+ setTimeout(() => { if (!this.subs.has(id)) return; for (const e of evs) this.message(['EVENT', id, e]); this.message(['EOSE', id]); }, 30);
+ }
+ close() { this.readyState = 3; this.emit('close', new Event('close')); }
+ }
+ Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 });
+ window.WebSocket = FakeSocket;
+ }, [notes, profile, servers]);
+ const bg = (sel) => page.evaluate((s) => document.querySelector(s)?.style.backgroundImage || '', sel);
+ // the feed: the small face's thumbnail is made from the copy
+ await page.goto(origin + '/feed', { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => document.querySelectorAll('.notes-feed > [data-zap-post]').length >= 5, { timeout: 20000 });
+ // the copy is found and the thumbnail made from it (the probe and the
+ // thumbnail's own fetch: two hits); the row keeps the look it was admitted
+ // with, the next paint wears the face
+ for (let i = 0; i < 80 && hits.alt < 2; i++) await sleep(250);
+ assert.ok(hits.dead >= 1 && hits.alt >= 2, `the dead host was asked (${hits.dead}) and the copy fetched for the thumbnail (${hits.alt})`);
+ console.log('✓ the thumbnail is made from the copy on the published server');
+ const remembered = await page.evaluate(() => localStorage.getItem('btc-wallet-blob-alts') || '');
+ assert.ok(remembered.includes(`/alt/${H1}.png`), 'the find is remembered on the device');
+ // the profile page (the screen that showed an empty circle and no cover):
+ // big face and banner from the copies, the post rows' small faces from
+ // the thumbnail
+ await page.goto(origin + '/' + nip19.npubEncode(PK), { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction((h) => (document.querySelector('.profile-banner')?.style.backgroundImage || '').includes('/alt/' + h), { timeout: 20000 }, H2)
+ .catch(async () => { throw new Error('banner not from the copy: ' + await bg('.profile-banner')); });
+ const face = await bg('.profile-avatar');
+ assert.ok(face.includes(`/alt/${H1}.png`), 'the big face paints from the copy: ' + face);
+ console.log('✓ the profile page paints the big face and the banner from the copies');
+ const rowSel = `.note-post[data-zap-post="${notes[0].id}"] .ava-img`;
+ await page.waitForFunction((s, h) => /^url\("data:/.test(document.querySelector(s)?.style.backgroundImage || '') || (document.querySelector(s)?.style.backgroundImage || '').includes('/alt/' + h), { timeout: 20000 }, rowSel, H1)
+ .catch(async () => { throw new Error('post row face: ' + await page.evaluate((id) => [...document.querySelector('.note-post[data-zap-post="' + id + '"]')?.querySelectorAll('[class*=avatar], .ava-img') || []].map((e) => e.outerHTML.slice(0, 220)).join(' || '), notes[0].id)); });
+ assert.deepEqual(errors, []);
+ console.log('✓ the post rows wear the face, and no page errors');
+} finally { await browser.close(); server.stop(true); }