aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/socket.js
blob: a30d4376ffc9d3cbaf093a3389c12db4d901fa7f (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
import { get } from 'svelte/store';
import { rate, user, token, invoices, preferredCurrency, newPayment } from '$lib/store';
import { success } from '$lib/utils';

let interval, socket;

export const auth = () => {
	let t = get(token);
	if (t) send('login', t);
};

export const send = (type, data) => {
	socket?.readyState === 1 && socket.send(JSON.stringify({ type, data }));
};

export const messages = (data) => ({
	rate() {
		rate.set(data);
	},

	payment() {
		if (data.invoice) invoices.set({ ...get(invoices), [data.invoice.uuid]: data.invoice });
		newPayment.set(true);
		if (data.amount > 0) {
			success(`Received ${data.amount} sats!`);
		} else {
			success(`Sent ${-data.amount} sats!`);
		}
	},

	connected: auth,

	login() {
		user.set(data);
		preferredCurrency.set('USD');
	}
});

const initialReconnectDelay = 1000;
const maxReconnectDelay = 16000;

let currentReconnectDelay = initialReconnectDelay;

export function connect() {
	clearInterval(interval);

	if (socket) return auth();

	socket = new WebSocket('ws://localhost:3119/ws');
	socket.addEventListener('open', onWebsocketOpen);
	socket.addEventListener('close', onWebsocketClose);
	socket.addEventListener('message', onWebsocketMessage);

	interval = setInterval(() => send('heartbeat'), 5000);
}

export function close() {
	if (socket) socket.close();
}

function onWebsocketMessage(msg) {
	let { type, data } = JSON.parse(msg.data);
	messages(data)[type] && messages(data)[type]();
}

function onWebsocketOpen() {
	currentReconnectDelay = initialReconnectDelay;
}

function onWebsocketClose() {
	socket = null;
	setTimeout(() => {
		reconnectToWebsocket();
	}, currentReconnectDelay + Math.floor(Math.random() * 3000));
}

function reconnectToWebsocket() {
	if (currentReconnectDelay < maxReconnectDelay) {
		currentReconnectDelay *= 2;
	}
	connect();
}
ass="k">try { const m = JSON.parse(data); 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(data); }; return ws; }; window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); }, STRANGER); 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 = 8000) => { for (let i = 0; i < ms / 200; i++) { if (await page.evaluate(fn)) return true; await sleep(200); } return false; }; const list = () => page.evaluate(() => [...document.querySelectorAll('.mention-ac .chat-name')].map((n) => n.textContent)); const value = () => page.evaluate(() => document.querySelector('.post-input').value); try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.href, { 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); await sleep(3000); // a new wallet's starter follows land first; ours go over them const base = cacheKeyFor(mn + '\n'); await page.evaluate(([k, pk]) => { localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Globetrotter', t: Date.now() } })); localStorage.setItem('btc-wallet-feed:' + k, 'following'); }, [base, FRIEND]); await page.reload({ waitUntil: 'domcontentloaded' }); await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); await sleep(1500); const opened = await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((n) => (n.getAttribute('aria-label') || n.textContent).trim().toLowerCase() === 'new post'); if (b) { b.click(); return true; } return false; }); check('the composer opens', opened && !!(await page.waitForSelector('.post-input', { timeout: 5000 }).catch(() => null))); await page.click('.post-input'); console.log('\n[someone you follow]'); await page.keyboard.type('hello @glo'); check('"@glo" lists the person you follow', await waitFor(() => [...document.querySelectorAll('.mention-ac .chat-name')].some((n) => n.textContent === 'Globetrotter')), JSON.stringify(await list())); await page.keyboard.press('Enter'); await sleep(300); check('Enter puts nostr:npub… in its place, list gone', (await value()) === 'hello nostr:' + npubEncode(FRIEND) + ' ' && !(await list()).length, JSON.stringify(await value())); console.log('\n[someone found by the search]'); await page.keyboard.type('and @sato'); check('"@sato" lists the search\'s hit', await waitFor(() => [...document.querySelectorAll('.mention-ac .chat-name')].some((n) => n.textContent === 'Satoshi Stranger')), JSON.stringify(await list())); await page.evaluate(() => [...document.querySelectorAll('.mention-ac .item')].find((n) => /Satoshi Stranger/.test(n.textContent)).click()); await sleep(300); check('a tap puts them in too', (await value()).includes('and nostr:' + npubEncode(STRANGER) + ' '), JSON.stringify(await value())); await page.keyboard.type('@nobody'); await sleep(300); await page.keyboard.press('Escape'); await sleep(200); check('Escape closes the list', !(await list()).length); await page.keyboard.press('Backspace'); // on a line of its own (Chrome wraps lines in <div>s after an Enter) await page.keyboard.type(' '); await page.keyboard.press('Enter'); await page.keyboard.type('cc @glo'); await waitFor(() => [...document.querySelectorAll('.mention-ac .chat-name')].some((n) => n.textContent === 'Globetrotter')); await page.keyboard.press('Enter'); await sleep(300); check('...and on a second line, in place', /\ncc nostr:npub1[a-z0-9]+ $/.test(await value()) && !(await value()).includes('@glo'), JSON.stringify((await value()).slice(-90))); console.log('\n[posting]'); await page.evaluate(() => { window.__published = []; [...document.querySelectorAll('.post-actions button')].find((b) => /^post$/i.test(b.textContent.trim())).click(); }); await waitFor(() => window.__published.some((e) => e.kind === 1), 8000); const ev = (await page.evaluate(() => window.__published)).find((e) => e.kind === 1); check('the post carries both p tags', !!ev && [FRIEND, STRANGER].every((pk) => ev.tags.some((x) => x[0] === 'p' && x[1] === pk)), JSON.stringify(ev && ev.tags)); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ @mentions suggest people and tag them' : '\n❌ failed'); process.exit(ok ? 0 : 1);