askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
toolbar: Back and Forward are greyed out when there's nowhere to go
cc08c7a
1 week, 2 days ago
History
cards-service.ts · 9.9 KB · 204 lines
| 1 | /** |
| 2 | * Card view, main-process side: read a tab's posts with its site's view rule, scrolling it at a reading pace to gather |
| 3 | * more, and show them in a tab of the browser's own (dbb-cards://<id>/). "More posts" reads more from the same tab. |
| 4 | * |
| 5 | * What it never does: click, like, follow, post or type on the site. It only scrolls the tab it was asked to read, |
| 6 | * reads in an isolated world the page's scripts can't reach, and sends nothing anywhere (the cards load the post's |
| 7 | * images from the site's own image host, as the site itself does). |
| 8 | */ |
| 9 | |
| 10 | import { randomBytes } from "node:crypto"; |
| 11 | import { webContents, type WebContents } from "electron"; |
| 12 | import { buildCardsHtml, mergePosts, readerSource, validatePosts, validateViewRule, type Post, type ViewRule } from "./cards.js"; |
| 13 | |
| 14 | export const CARDS_SCHEME = "dbb-cards"; |
| 15 | const ID_RE = /^[0-9a-f]{18}$/; |
| 16 | export const cardsUrl = (id: string, path = "") => `${CARDS_SCHEME}://${id}/${path}`; |
| 17 | |
| 18 | export function parseCardsUrl(url: string): { id: string; path: string } | null { |
| 19 | try { |
| 20 | const u = new URL(url); |
| 21 | return u.protocol === `${CARDS_SCHEME}:` && ID_RE.test(u.hostname) ? { id: u.hostname, path: u.pathname.replace(/^\/+/, "") } : null; |
| 22 | } catch { |
| 23 | return null; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | const WORLD = 1011; |
| 28 | /** A screen at a time, with a pause like a person reading, so the site loads the next posts. */ |
| 29 | const STEP_MS = 700; |
| 30 | /** How far each step scrolls, in screens. Sites keep a few screens of posts rendered around the view, so nothing is skipped. */ |
| 31 | const STEP_SCREENS = 1.5; |
| 32 | |
| 33 | export interface CardsDeps { |
| 34 | askChrome(op: string, args: Record<string, unknown>): Promise<unknown>; |
| 35 | emit(payload: Record<string, unknown>): void; |
| 36 | isOurTab(wc: WebContents | undefined): wc is WebContents; |
| 37 | } |
| 38 | |
| 39 | interface View { |
| 40 | rule: ViewRule; |
| 41 | srcWcId: number; |
| 42 | source: string; |
| 43 | title: string; |
| 44 | posts: Map<string, Post>; |
| 45 | html: string; |
| 46 | at: number; |
| 47 | busy: boolean; |
| 48 | batches: Array<{ from: number; at: Date }>; |
| 49 | /** Said at the top of the cards when the last More posts found nothing new. */ |
| 50 | note: string; |
| 51 | } |
| 52 | |
| 53 | /** What one read found: new posts, screens scrolled, distinct posts seen on the page, and an error if reading failed. */ |
| 54 | interface Read { |
| 55 | added: number; |
| 56 | screens: number; |
| 57 | seen: number; |
| 58 | error: string; |
| 59 | } |
| 60 | |
| 61 | export interface CardsResult { |
| 62 | ok: boolean; |
| 63 | reason?: "no-tab" | "no-rule" | "busy" | "none-found" | "error"; |
| 64 | message?: string; |
| 65 | tab?: { id: number; wcId: number }; |
| 66 | posts?: number; |
| 67 | promoted?: number; |
| 68 | } |
| 69 | |
| 70 | export function createCards(deps: CardsDeps, opts: { stepMs?: number; max?: number } = {}) { |
| 71 | const views = new Map<string, View>(); |
| 72 | const stepMs = opts.stepMs ?? STEP_MS; |
| 73 | const maxViews = opts.max ?? 20; |
| 74 | |
| 75 | async function read(wc: WebContents, rule: ViewRule): Promise<{ posts: Post[]; title: string; url: string }> { |
| 76 | const raw = (await wc.executeJavaScriptInIsolatedWorld(WORLD, [{ code: readerSource(rule) }])) as { title?: unknown; url?: unknown } | null; |
| 77 | return { posts: validatePosts(raw, rule), title: typeof raw?.title === "string" ? raw.title.slice(0, 200) : "", url: typeof raw?.url === "string" ? raw.url : wc.getURL() }; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Reads, scrolls a screen, waits, reads again, until `want` new posts or `rounds` screens. It gives up early only at |
| 82 | * the end: 3 reads in a row with nothing new while scrolling no longer moves the page (the site has nothing more). |
| 83 | */ |
| 84 | async function gather(wc: WebContents, v: View, want: number, rounds: number): Promise<Read> { |
| 85 | const out: Read = { added: 0, screens: 0, seen: 0, error: "" }; |
| 86 | const seen = new Set<string>(); |
| 87 | let stuck = 0; |
| 88 | let moved = true; |
| 89 | for (let i = 0; i < rounds && !wc.isDestroyed(); i++) { |
| 90 | let r: Awaited<ReturnType<typeof read>>; |
| 91 | try { |
| 92 | r = await read(wc, v.rule); |
| 93 | } catch (e) { |
| 94 | out.error = (e as Error).message; |
| 95 | break; |
| 96 | } |
| 97 | if (!v.title && r.title) v.title = r.title; |
| 98 | for (const p of r.posts) seen.add(p.link); |
| 99 | const n = mergePosts(v.posts, r.posts); |
| 100 | out.added += n; |
| 101 | stuck = n || moved ? 0 : stuck + 1; |
| 102 | // At the bottom, a site fetches its next page; that can take a few seconds, so wait there before giving up. |
| 103 | if (out.added >= want || stuck >= 4) break; |
| 104 | deps.emit({ kind: "cards-progress", wcId: wc.id, posts: v.posts.size }); |
| 105 | const y = (await wc.executeJavaScriptInIsolatedWorld(WORLD, [{ code: `(() => { const y = scrollY; window.scrollBy(0, Math.round(innerHeight * ${STEP_SCREENS})); return [y, scrollY]; })()` }]).catch(() => null)) as [number, number] | null; |
| 106 | moved = !!y && y[1] !== y[0]; |
| 107 | if (moved) out.screens++; |
| 108 | await new Promise((res) => setTimeout(res, moved ? stepMs : stepMs * 2)); |
| 109 | } |
| 110 | out.seen = seen.size; |
| 111 | return out; |
| 112 | } |
| 113 | |
| 114 | function render(id: string, v: View): string { |
| 115 | const src = webContents.fromId(v.srcWcId); |
| 116 | const alive = !!src && !src.isDestroyed(); |
| 117 | v.html = buildCardsHtml({ rule: v.rule, source: v.source, title: v.title, posts: [...v.posts.values()], moreUrl: alive ? cardsUrl(id, "more") : "", collectedAt: new Date(), batches: v.batches, note: v.note }); |
| 118 | return v.html; |
| 119 | } |
| 120 | |
| 121 | /** `rule`: the view rule to read with (from an installed view-rule plugin; checked again here). */ |
| 122 | async function open(o: { wcId: number; want?: number; rounds?: number; rule: unknown }): Promise<CardsResult> { |
| 123 | const wc = webContents.fromId(o.wcId); |
| 124 | if (!deps.isOurTab(wc)) return { ok: false, reason: "no-tab", message: "No such tab." }; |
| 125 | const checked = validateViewRule(o.rule); |
| 126 | if (!checked.ok) return { ok: false, reason: "no-rule", message: `That view rule was refused: ${checked.error}` }; |
| 127 | const rule = checked.rule; |
| 128 | const v: View = { rule, srcWcId: wc.id, source: wc.getURL(), title: "", posts: new Map(), html: "", at: Date.now(), busy: true, batches: [], note: "" }; |
| 129 | try { |
| 130 | deps.emit({ kind: "cards-progress", wcId: wc.id, posts: 0, start: true }); |
| 131 | await gather(wc, v, o.want ?? 80, o.rounds ?? 24); |
| 132 | } catch (e) { |
| 133 | return { ok: false, reason: "error", message: `Couldn't read this page: ${(e as Error).message}` }; |
| 134 | } finally { |
| 135 | v.busy = false; |
| 136 | deps.emit({ kind: "cards-progress", wcId: wc.id, done: true, posts: v.posts.size }); |
| 137 | } |
| 138 | if (!v.posts.size) return { ok: false, reason: "none-found", message: "No posts were found on this page." }; |
| 139 | const id = randomBytes(9).toString("hex"); |
| 140 | views.set(id, v); |
| 141 | while (views.size > maxViews) views.delete(views.keys().next().value as string); |
| 142 | render(id, v); |
| 143 | let tab: { id: number; wcId: number }; |
| 144 | try { |
| 145 | tab = (await deps.askChrome("tab.new", { url: cardsUrl(id), activate: true, wait: true })) as { id: number; wcId: number }; |
| 146 | } catch (e) { |
| 147 | return { ok: false, reason: "error", message: `Couldn't open the card tab: ${(e as Error).message}` }; |
| 148 | } |
| 149 | const all = [...v.posts.values()]; |
| 150 | return { ok: true, tab, posts: all.filter((p) => !p.promoted).length, promoted: all.filter((p) => p.promoted).length }; |
| 151 | } |
| 152 | |
| 153 | /** What dbb-cards://<id>/<path> serves. "more" reads more posts first, then sends the tab to the first new one. */ |
| 154 | async function serve(url: string): Promise<{ status: number; html: string }> { |
| 155 | const p = parseCardsUrl(url); |
| 156 | const v = p ? views.get(p.id) : undefined; |
| 157 | if (!p || !v) return { status: 410, html: EXPIRED_CARDS_HTML }; |
| 158 | if (p.path === "more") { |
| 159 | const src = webContents.fromId(v.srcWcId); |
| 160 | if (src && !src.isDestroyed() && !v.busy) { |
| 161 | v.busy = true; |
| 162 | const before = v.posts.size; |
| 163 | // A tab in the background isn't rendered, so the site wouldn't load more as it scrolls: show it while it is |
| 164 | // read (a few seconds), then go back to the cards. |
| 165 | await deps.askChrome("tab.peek", { wcId: src.id, on: true }).catch(() => {}); |
| 166 | let r: Read = { added: 0, screens: 0, seen: 0, error: "" }; |
| 167 | try { |
| 168 | // A tab that sat in the background takes a moment to draw again before it can load more. |
| 169 | await new Promise((res) => setTimeout(res, 1200)); |
| 170 | r = await gather(src, v, 60, 18); |
| 171 | } catch (e) { |
| 172 | r.error = (e as Error).message; |
| 173 | } finally { |
| 174 | v.busy = false; |
| 175 | await deps.askChrome("tab.peek", { wcId: src.id, on: false }).catch(() => {}); |
| 176 | } |
| 177 | if (v.posts.size > before) v.batches.push({ from: before, at: new Date() }); |
| 178 | // Never silent: when nothing new came, say what the read saw. |
| 179 | v.note = r.added |
| 180 | ? "" |
| 181 | : r.error |
| 182 | ? `More posts couldn't read the page: ${r.error.slice(0, 120)}.` |
| 183 | : r.seen === 0 |
| 184 | ? `More posts found no posts on the page at all (scrolled ${r.screens} screen${r.screens === 1 ? "" : "s"}). The page may have changed, or the tab is on another page.` |
| 185 | : `More posts scrolled ${r.screens} screen${r.screens === 1 ? "" : "s"} and read ${r.seen} posts, all already here: the site didn't load newer ones in time. Try again in a moment.`; |
| 186 | deps.emit({ kind: "cards-progress", wcId: src.id, done: true, posts: v.posts.size, added: r.added, note: v.note }); |
| 187 | render(p.id, v); |
| 188 | return { status: 200, html: `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${cardsUrl(p.id)}#new">` }; |
| 189 | } |
| 190 | render(p.id, v); |
| 191 | return { status: 200, html: `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${cardsUrl(p.id)}">` }; |
| 192 | } |
| 193 | return { status: 200, html: v.html || render(p.id, v) }; |
| 194 | } |
| 195 | |
| 196 | return { open, serve }; |
| 197 | } |
| 198 | |
| 199 | export const EXPIRED_CARDS_HTML = `<!doctype html><html><head><meta charset="utf-8"><title>Card view expired</title> |
| 200 | <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"> |
| 201 | <style>body{font:16px/1.6 -apple-system,system-ui,sans-serif;max-width:560px;margin:90px auto;padding:0 22px;color:#555}h1{font-size:21px}</style></head> |
| 202 | <body><h1>This card view has expired</h1><p>Card views are kept in memory for this session only. Open the site again and choose View ▸ Card View.</p></body></html>`; |
| 203 | |
| 204 | export type CardsService = ReturnType<typeof createCards>; |