aboutsummaryrefslogtreecommitdiffstats
path: root/tools/gif-picker-test.js
blob: 956b4f70d2aa455dccafc99a29ec7c4d3edc730a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// GIF search (gifs.nostr.build): the post composer's GIF button opens a
// picker with the attribution, starter results and a search field; a tap
// puts the original URL in the post, which goes out with a NIP-92 imeta.
// In a DM the picked GIF is sent at once. Uses the live API — localhost is
// admitted as nostr.build's shared development client.
// Run: bun tools/gif-picker-test.js
import puppeteer from './puppeteer.js';
import { cacheKeyFor } from '../src/wallet.js';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { buildHtml } from '../build.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let ok = true;
const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
const PEER = getPublicKey(generateSecretKey());
const html = await buildHtml({ minify: true, pwa: false });
const server = Bun.serve({ port: 5315, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } });
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] });
const page = await browser.newPage();
await page.evaluateOnNewDocument(() => {
  window.__published = [];
  const Real = window.WebSocket;
  window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') { window.__published.push(m[1]); setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['OK', m[1].id, true, '']) })), 0); return; } } catch {} return send(d); }; return ws; };
  window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
});
const gifReqs = [];
page.on('request', (r) => { if (r.url().startsWith('https://gifs.nostr.build/api/')) gifReqs.push(r.url()); });
const errs = [];
page.on('pageerror', (e) => errs.push(String(e)));
const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
const waitFor = async (fn, ms = 15000, arg) => { for (let i = 0; i < ms / 200; i++) { if (await page.evaluate(fn, arg)) return true; await sleep(200); } return false; };
try {
  await page.setViewport({ width: 390, height: 844 });
  await page.goto('http://localhost:5315/', { waitUntil: 'domcontentloaded' });
  await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
  await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
  await click('create a new wallet'); await sleep(600);
  await page.waitForSelector('.words .w .t');
  const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
  await click('skip verification');
  await waitText('receive', 20000);
  const base = cacheKeyFor(mn + '\n');
  await page.evaluate(([k, pk]) => {
    const st = JSON.parse(localStorage.getItem(k + ':messages') || '{}');
    st.dms = { [pk]: [{ id: 'a'.repeat(64), from: pk, text: 'send me a gif', t: Math.floor(Date.now() / 1000) - 60 }] };
    localStorage.setItem(k + ':messages', JSON.stringify(st));
    localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Gifpal', t: Date.now() } }));
  }, [base, PEER]);
  await page.reload({ waitUntil: 'domcontentloaded' });
  await waitText('receive', 20000);

  console.log('\n[in a post]');
  await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click());
  await waitFor(() => !!document.querySelector('.feed-post-fab'), 15000);
  await page.evaluate(() => document.querySelector('.feed-post-fab').click());
  check('the post composer has a GIF button', await waitFor(() => !!document.querySelector('.post-actions .gif-btn'), 8000));
  await page.evaluate(() => document.querySelector('.post-actions .gif-btn').click());
  check('the picker opens with the nostr.build attribution, linked', await waitFor(() => !!document.querySelector('.gif-sheet .gif-head a[href="https://nostr.build"]'), 5000));
  check('...and the first starter\'s GIFs', await waitFor(() => document.querySelectorAll('.gif-grid .gif-tile').length >= 6, 20000), String(await page.evaluate(() => document.querySelectorAll('.gif-tile').length)));
  check('a tile plays the small mp4, not the original', await waitFor(() => [...document.querySelectorAll('.gif-tile video')].some((v) => /mp4/.test(v.currentSrc || v.getAttribute('src') || '') && v.readyState >= 2), 15000));
  await page.focus('.gif-search');
  await page.keyboard.type('cat', { delay: 40 });
  check('typing searches (debounced: one request for "cat")', await waitFor(() => document.querySelector('.gif-grid')?.getAttribute('data-key') === 'gifs:cat', 15000)
    && gifReqs.filter((u) => /[?&]q=c(&|$)|q=ca(&|$)/.test(u)).length === 0, gifReqs.map((u) => new URL(u).searchParams.get('q')).join(','));
  check('no request sends an Authorization header or safe=0', gifReqs.every((u) => !/safe=0/.test(u)));
  const picked = await page.evaluate(() => { const b = document.querySelector('.gif-grid .gif-tile'); const title = b.title; b.click(); return title; });
  await sleep(500);
  const draft = await page.evaluate(() => document.querySelector('.post-input')?.value || '');
  check('the picker closes and the post holds the GIF\'s original URL', !(await page.evaluate(() => !!document.querySelector('.gif-sheet'))) && /https:\/\/gifs\.nostr\.build\/[0-9a-f]{64}\.(gif|webp)/.test(draft), draft);
  await page.evaluate(() => { window.__published = []; [...document.querySelectorAll('.post-actions button')].find((b) => b.textContent.trim() === 'Post').click(); });
  await waitFor(() => window.__published.some((e) => e.kind === 1), 10000);
  const ev = await page.evaluate(() => window.__published.find((e) => e.kind === 1));
  const im = ev && ev.tags.find((x) => x[0] === 'imeta');
  check('the note carries a NIP-92 imeta: url, type, size in pixels, alt', !!im && im.some((x) => /^url https:\/\/gifs\.nostr\.build\//.test(x)) && im.some((x) => /^m image\/(gif|webp)$/.test(x)) && im.some((x) => /^dim \d+x\d+$/.test(x)) && im.some((x) => x.startsWith('alt ')), JSON.stringify(im) + ' ' + picked);

  console.log('\n[in a reply]');
  await sleep(1500);
  await page.evaluate((id) => { const r = document.querySelector('[data-zap-post="' + id + '"]'); [...r.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Reply' || b.title === 'Reply').click(); }, ev.id);
  check('the reply box has a GIF button', await waitFor(() => !!document.querySelector('.thread-reply .gif-btn'), 10000));
  await page.evaluate(() => document.querySelector('.thread-reply .gif-btn').click());
  await waitFor(() => document.querySelectorAll('.gif-grid .gif-tile').length > 0, 20000);
  await page.evaluate(() => document.querySelector('.gif-grid .gif-tile').click());
  await sleep(500);
  const rdraft = await page.evaluate(() => document.querySelector('.thread-reply-input')?.value || '');
  check('the GIF lands in the reply', /https:\/\/gifs\.nostr\.build\//.test(rdraft), rdraft);
  await page.evaluate(() => { window.__published = []; document.querySelector('.thread-reply-send').click(); });
  await waitFor(() => window.__published.some((e) => e.kind === 1), 10000);
  const rev = await page.evaluate(() => window.__published.find((e) => e.kind === 1));
  check('the reply goes out naming the post, with the GIF\'s imeta', !!rev && rev.tags.some((x) => x[0] === 'e' && x[1] === ev.id) && rev.tags.some((x) => x[0] === 'imeta' && x.some((y) => /^dim \d+x\d+$/.test(y))), JSON.stringify(rev && rev.tags));
  await page.evaluate(() => history.back()); await sleep(500);

  console.log('\n[in a DM]');
  await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Messages"]')?.click());
  await waitFor(() => !!document.querySelector('.chat-thread-row .chat-preview'), 10000);
  await page.evaluate(() => document.querySelector('.chat-thread-row .chat-preview').click());
  check('the DM composer has a GIF button', await waitFor(() => !!document.querySelector('.chat-compose .chat-gif'), 8000));
  await page.evaluate(() => { window.__published = []; document.querySelector('.chat-compose .chat-gif').click(); });
  await waitFor(() => document.querySelectorAll('.gif-grid .gif-tile').length > 0, 20000);
  await page.evaluate(() => document.querySelector('.gif-grid .gif-tile').click());
  check('a picked GIF is sent straight away', await waitFor(() => window.__published.some((e) => e.kind === 1059), 10000)
    && await waitFor(() => [...document.querySelectorAll('.chat-row.mine')].some((r) => r.querySelector('img') || /gifs\.nostr\.build/.test(r.textContent)), 8000));
  check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ GIF search in posts and DMs' : '\n❌ failed');
process.exit(ok ? 0 : 1);