diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/features/messages.js | 124 | ||||
| -rw-r--r-- | src/image-thumbnails.js | 29 | ||||
| -rw-r--r-- | src/nostr-login.js | 21 | ||||
| -rw-r--r-- | src/nostr.js | 25 | ||||
| -rw-r--r-- | src/style.css | 7 |
5 files changed, 184 insertions, 22 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 245e1ce..57f0e23 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -15,7 +15,7 @@ import { mediaServers } from '../media-servers.js'; // listens for both identities and decrypts with whichever keys are present. import { - subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay, wakeRelays, + subscribeOn, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, queryDepthOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay, wakeRelays, npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44, PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread, verifyEventsAsync, setSyncConfig, DEFAULT_SYNC_RELAYS, } from '../nostr.js'; @@ -36,7 +36,7 @@ import { loadMediaIndex, saveMediaIndex, wipeMediaIndex } from '../media-cache.j import { mergeFeedWindow } from '../feed-window.js'; import { createThreadStore } from '../thread-cache.js'; import { createThreadPrefetch } from '../thread-prefetch.js'; -import { makeImageThumbnails } from '../image-thumbnails.js'; +import { makeImageThumbnails, loopGif } from '../image-thumbnails.js'; import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js'; import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js'; import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache, searchRecipients, searchable, setLocalPeople } from '../recipient-search.js'; @@ -5361,7 +5361,8 @@ export function messagesFeature(ctx) { const batch = [...incoming.values()]; incoming.clear(); chain = chain.then(async () => { const byId = new Map(c.notes.map((e) => [e.id, e])); - const fresh = batch.filter((e) => !byId.has(e.id)); + // older than the page already settled: kept back until paging gets there + const fresh = batch.filter((e) => !byId.has(e.id) && !holdBack(c, e)); if (!fresh.length) return; for (const e of fresh) byId.set(e.id, e); const merged = newestArticles([...byId.values()]).sort((a, b) => b.created_at - a.created_at); @@ -5384,16 +5385,19 @@ export function messagesFeature(ctx) { }; const asked = new Set([...NOTE_RELAYS, ...PROFILE_ARCHIVE_RELAYS]); (async () => { - await Promise.all([ - queryStreamOn([...asked], filter, take, 4500), + const depths = await Promise.all([ + queryDepthOn([...asked], filter, take, 4500), // the author's own relays, as soon as their list is known relaysOf(pk).then((own) => { const more = (own || []).filter((r) => !asked.has(r)); - return more.length ? queryStreamOn(more, filter, take, 4500) : null; - }).catch(() => {}), + return more.length ? queryDepthOn(more, filter, take, 4500) : []; + }).catch(() => []), + primalNotes(pk, filter.limit, 0, take), ]); clearTimeout(timer); await flush(); + await chain; + settlePage(c, depths.flat(), filter.limit); if (any) persistPage('notes', pk, c.notes.slice(0, 20).map(slimNote)); // cache stays bounded })().catch(() => {}).finally(() => { c.status = 'ready'; @@ -5512,22 +5516,75 @@ export function messagesFeature(ctx) { whenHide = setTimeout(() => whenEl && whenEl.classList.remove('on'), 250); }); } + // How far back a page of someone's posts can be trusted. Relays each hold + // their own part of an author's history, so the oldest post of a merged + // answer says little: ours held 6 of Ben Arc's posts reaching back to + // April while his own relay's newest 30 ended in late September, and + // "older than the oldest" then asked for posts before April — five months + // never shown, his Napstr launch among them (Adam, 2026-11-20). A source + // that sent a full page has more below its oldest post; the page is + // complete down to the NEWEST such floor. Posts below it wait in c.held + // and join the page that reaches them. No source full: nothing is left. + const fullPage = (n, limit) => n >= Math.ceil(limit / 2); + const holdBack = (c, e) => { + if (!c.floor || e.created_at >= c.floor) return false; + (c.held ||= new Map()).set(e.id, e); + return true; + }; + function settlePage(c, depths, limit) { + const floors = depths.filter((d) => d && fullPage(d.n, limit) && Number.isFinite(d.min)).map((d) => d.min); + const floor = floors.length ? Math.max(...floors) : 0; + // a refresh of a page already scrolled deeper never raises the floor + c.floor = c.floor && floor ? Math.min(c.floor, floor) : (c.floor && !floor ? c.floor : floor); + const all = new Map([...(c.held || new Map()), ...c.notes.map((e) => [e.id, e])]); + c.held = new Map(); + const shown = []; + for (const e of all.values()) (c.floor && e.created_at < c.floor ? c.held.set(e.id, e) : shown.push(e)); + c.notes = newestArticles(shown).sort((a, b) => b.created_at - a.created_at); + if (!floors.length && !c.floor) c.end = true; + else if (floors.length) c.end = false; + return floors.length > 0; + } + // Primal's cache keeps what relays have pruned (of the nine posts around + // the Napstr launch, the relays we ask held none). It answers posts and + // replies as separate feeds; each is a source with its own depth. The + // events are the signed originals, checked like a relay's. + async function primalNotes(pk, limit, until, take) { + const ask = async (notes) => { + const args = { pubkey: pk, notes, limit }; + if (until) args.until = until; + const evs = await primalCache('feed', args, 5000).catch(() => []); + const good = await verifiedPrimal((evs || []).filter((e) => e.pubkey === pk), PROFILE_KINDS); + for (const e of good) take(e); + return { url: 'primal:' + notes, n: good.length, min: good.length ? Math.min(...good.map((e) => e.created_at)) : Infinity }; + }; + return Promise.all([ask('authored'), ask('replies')]); + } async function loadOlderNotes(pk) { const c = notesCache.get(pk); if (!c || c.status !== 'ready' || c.loadingMore || c.end) return; const oldest = c.notes[c.notes.length - 1]; - if (!oldest) { c.end = true; return; } + if (!oldest && !c.floor) { c.end = true; return; } c.loadingMore = true; render(); try { - const evs = await queryOn(await notesRelays(pk), - { kinds: PROFILE_KINDS, authors: [pk], limit: 30, until: oldest.created_at - 1 }, 4500); + const limit = 30; + const until = (c.floor || oldest.created_at) - 1; + const got = new Map(); + const take = (e) => { if (e && e.pubkey === pk && e.created_at <= until) got.set(e.id, e); }; + const depths = await Promise.all([ + queryDepthOn(await notesRelays(pk), { kinds: PROFILE_KINDS, authors: [pk], limit, until }, take, 4500), + primalNotes(pk, limit, until, take), + ]); + const before = c.notes.length; const seen = new Set(c.notes.map((e) => e.id)); - const older = (evs || []) - .filter((e) => !seen.has(e.id) && seen.add(e.id)) - .sort((a, b) => b.created_at - a.created_at); - if (older.length) { await notesReady(older); c.notes = newestArticles([...c.notes, ...older]); } - else c.end = true; // the relays have nothing older + for (const e of got.values()) if (!seen.has(e.id)) (c.held ||= new Map()).set(e.id, e); + // this page reaches down to the new floor (or to the bottom: no source had more) + c.floor = 0; + const more = settlePage(c, depths.flat(), limit); + if (!more) { c.floor = 0; c.end = true; } + const added = c.notes.slice(before); + if (added.length) await notesReady(added.slice(0, FEED_PAGE)); } catch {} finally { c.loadingMore = false; if (ui.profilePk === pk) render(); @@ -6988,6 +7045,8 @@ export function messagesFeature(ctx) { if (!r) return null; const dims = JSON.parse(r.headers.get('x-dims') || 'null'); if (!dims || !dims.width) return null; + // a GIF kept before GIFs were looped: made again, to loop + if (r.headers.get('x-original') === '1' && r.headers.get('x-gif') !== '1' && /\.gif(\?|$)/i.test(url)) return null; const src = r.headers.get('x-original') === '1' ? null : URL.createObjectURL(await r.blob()); return { ...dims, thumb: src }; } catch { return null; } @@ -7003,17 +7062,22 @@ export function messagesFeature(ctx) { if (e && e.corsRefused) { noteNoCors(url); corsRefused.add(url); } // refused, as corsFetch confirmed return null; } + const gif = /gif/i.test(blob.type); + // a GIF that would play once and stop is painted from a copy that loops + let looped = null; + // (up to 4 MB: the copy is kept on disk beside the column copies) + if (gif && blob.size < 4e6) { try { const fixed = loopGif(await blob.arrayBuffer()); if (fixed) looped = new Blob([fixed], { type: 'image/gif' }); } catch {} } const result = await makeImageThumbnails(blob, { width: MEDIA_THUMB_W, tileSize: tileThumbs.has(url) ? 0 : TILE_PX, }); if (!result) return null; - const dims = { width: result.width, height: result.height }, out = result.media; + const dims = { width: result.width, height: result.height }, out = result.media || looped; // Both sizes share one decode in the worker; only cache writes and object // URLs come back to the page. The lightbox still uses the original. if (result.tile) await saveTileThumb(url, result.tile).catch(() => {}); try { const store = await thumbStore(); - await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1' } })); + await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1', ...(gif ? { 'x-gif': '1' } : {}) } })); const keys = await store.keys(); for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k); } catch {} @@ -10046,8 +10110,32 @@ export function messagesFeature(ctx) { if (!liveShown) { stopLivePlayer(); return; } mountLivePlayer(); const box = document.querySelector('.live-chat'); + fitLiveChat(box); if (box && box._stick !== false) box.scrollTop = box.scrollHeight; } + // On a phone the chat is as tall as the room left under the stream, so the + // message box (and the newest line above it) sits on screen, over the nav: + // at a fixed 60vh the card ran off the bottom, and a swipe inside the chat + // never moved the page to bring it up (Adam, 2026-11-20). A long + // description leaves little room: the chat keeps a floor and the page + // scrolls. On a variable of the document: a render takes inline styles back. + function fitLiveChat(box) { + const root = document.documentElement; + const card = box && box.closest('.live-chat-card'); + if (!card || !matchMedia('(max-width: 520px)').matches) { root.style.removeProperty('--live-chat-max'); return; } + const nav = document.querySelector('.app-bottom-nav'); + const b = box.getBoundingClientRect(); + const under = card.getBoundingClientRect().bottom - b.bottom; // the message box and the card's foot + const room = window.innerHeight - (nav ? nav.getBoundingClientRect().height : 0) - (b.top + window.scrollY) - under; + const px = Math.max(170, Math.floor(room)) + 'px'; + if (root.style.getPropertyValue('--live-chat-max') !== px) root.style.setProperty('--live-chat-max', px); + } + if (typeof window !== 'undefined') window.addEventListener('resize', () => { + const box = ui.liveStream && document.querySelector('.live-chat'); + if (!box) return; + fitLiveChat(box); + if (box._stick !== false) box.scrollTop = box.scrollHeight; + }); async function sendLiveChat(w, text, reply) { const id = await requireIdentity(); @@ -10959,7 +11047,7 @@ export function messagesFeature(ctx) { return h('img', { src: mediaSrc(url, known), 'data-pic': url, class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '', // a few-ms decode of the copy paints with the page; an original never holds the page for its decode - decoding: known && known.thumb ? 'sync' : 'async', + decoding: known && known.thumb && !/\.gif(\?|$)/i.test(url) ? 'sync' : 'async', // (a looped GIF's copy is the whole animation) width: size?.width, height: size?.height, style: size ? 'height:auto;aspect-ratio:' + size.width + '/' + size.height + ';--ar:' + (size.width / size.height).toFixed(4) : undefined, onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); }, diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js index 2686dac..80e6915 100644 --- a/src/image-thumbnails.js +++ b/src/image-thumbnails.js @@ -96,3 +96,32 @@ export function makeImageThumbnails(blob, { width = 0, tileSize = 0 } = {}) { || typeof createImageBitmap === 'undefined' || queue.length >= MAX_QUEUE) return Promise.resolve(null); return new Promise((resolve) => { queue.push({ input: { blob, width, tileSize }, resolve }); drain(); }); } + +// A GIF with no loop instruction (the NETSCAPE2.0 application extension) +// plays once and stops on its last frame: every browser reads it that way. +// Plenty of GIFs are made without one (a gifs.nostr.build reply GIF froze +// after a second, Adam, 2026-11-19), and people expect a GIF to loop. The +// extension, "loop forever", goes right after the global colour table. +// Returns the patched bytes, or null when the file loops already or isn't +// a GIF. +export function loopGif(bytes) { + const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); + if (b.length < 13 || b[0] !== 0x47 || b[1] !== 0x49 || b[2] !== 0x46) return null; // "GIF" + const tag = [0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30]; // NETSCAPE2.0 + const anim = [0x41, 0x4e, 0x49, 0x4d, 0x45, 0x58, 0x54, 0x53, 0x31, 0x2e, 0x30]; // ANIMEXTS1.0 + outer: for (let i = 13; i < b.length - 11; i++) { + if (b[i] !== 0x4e && b[i] !== 0x41) continue; + const t = b[i] === 0x4e ? tag : anim; + for (let j = 1; j < 11; j++) if (b[i + j] !== t[j]) continue outer; + return null; + } + const packed = b[10]; + const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0); + if (at > b.length) return null; + const ext = new Uint8Array([0x21, 0xff, 0x0b, ...tag, 0x03, 0x01, 0x00, 0x00, 0x00]); + const out = new Uint8Array(b.length + ext.length); + out.set(b.subarray(0, at), 0); + out.set(ext, at); + out.set(b.subarray(at), at + ext.length); + return out; +} diff --git a/src/nostr-login.js b/src/nostr-login.js index 562a5d4..e5490ec 100644 --- a/src/nostr-login.js +++ b/src/nostr-login.js @@ -36,7 +36,7 @@ import { hex, bech32 } from '@scure/base'; import { sha256 } from '@noble/hashes/sha256'; import { entropyToMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; -import { getPublicKey, finalizeEvent, nip44 } from './nostr.js'; +import { getPublicKey, finalizeEvent, nip44, liveRelayList } from './nostr.js'; import { SimplePool } from 'nostr-tools/pool'; import { generateSecretKey } from 'nostr-tools/pure'; import { decode as nip19decode } from 'nostr-tools/nip19'; @@ -208,7 +208,24 @@ export function nostrConnectPending(timeoutMs = 180_000) { } catch {} return null; } -export async function nostrConnect({ relays = ['wss://relay.coinos.io', 'wss://nos.lol'], timeoutMs = 180_000, resume = null } = {}) { +// The relays a nostrconnect:// link names: the signer app publishes its +// approval there and we wait there, so a dead one is a login that spins +// until it times out. A PAFF account's Amber sign-in sat on "waiting for +// signer" while nos.lol (the link's second relay) refused connections, and +// relay.nsec.app was down the same night (Adam, 2026-11-19). So the link +// leads with relay.coinos.io and relay.primal.net (up, and both keep NIP-46 +// traffic), leaves out any relay this device has recently found dead, and +// names three: one relay's outage no longer strands the handshake. +const CONNECT_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://offchain.pub']; +export function connectRelays(candidates = CONNECT_RELAYS, n = 3) { + let live = candidates; + try { live = liveRelayList(candidates); } catch {} + const picked = live.slice(0, n); + // our own relay always: its ops are ours to fix, and the poller reads it + if (!picked.includes(candidates[0])) picked.unshift(candidates[0]); + return picked.slice(0, n); +} +export async function nostrConnect({ relays = connectRelays(), timeoutMs = 180_000, resume = null } = {}) { const { BunkerSigner, createNostrConnectURI } = await loadNip46(); const local = resume ? hex.decode(resume.local) : generateSecretKey(); const secret = resume ? resume.secret : hex.encode(crypto.getRandomValues(new Uint8Array(16))); diff --git a/src/nostr.js b/src/nostr.js index 4b7f5c3..d2c9e44 100644 --- a/src/nostr.js +++ b/src/nostr.js @@ -602,6 +602,31 @@ export async function queryStreamOn(relays, filter, onEvent, maxWait = 1500) { }); } catch {} finally { await Promise.all(pending); } } +// queryStreamOn that also says how deep each relay's answer went: resolves +// with [{ url, n, min }] — how many events that relay sent for the filter and +// the oldest created_at among them. A caller paging backwards needs it: +// relays hold different parts of an author's history, and the oldest event +// of the merged answer may be one relay's stray copy from months earlier. +export async function queryDepthOn(relays, filter, onEvent, maxWait = 1500) { + probeRelays(relays); + const pending = [], stats = [], seen = new Set(); + try { + const live = readRelays(relays); + await Promise.all(live.map((url) => { + const s = { url, n: 0, min: Infinity }; + stats.push(s); + return askRelay(url, [filter], maxWait, (event) => { + if (!event) return; + s.n++; + if (event.created_at < s.min) s.min = event.created_at; + if (seen.has(event.id)) return; + seen.add(event.id); + pending.push(verifyOneAsync(event).then((ok) => ok && onEvent(event)).catch(() => {})); + }); + })); + } catch {} finally { await Promise.all(pending); } + return stats; +} export async function publishOn(relays, evt, { onauth = null, onrefused = null } = {}) { try { const live = liveRelays(relays); diff --git a/src/style.css b/src/style.css index a9ceadb..311cfbb 100644 --- a/src/style.css +++ b/src/style.css @@ -975,7 +975,10 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } .live-rec-link { background: var(--paper); color: var(--ink); text-decoration: none; } .live-say { padding: 6px 12px; border-radius: 8px; color: #fff; background: rgba(0, 0, 0, .65); font-size: 14px; text-align: center; } /* the top padding is headroom for a hat on the first line's face: a scroller clips what rises out of it */ -.live-chat { display: flex; flex-direction: column; gap: 8px; max-height: 46vh; min-height: 120px; overflow-y: auto; overscroll-behavior: contain; padding-top: 12px; } +/* no overscroll-behavior here: at the end of the chat the swipe carries on to + the page, or the last lines and the message box stay under the screen edge + with no way to reach them (Adam, 2026-11-20) */ +.live-chat { display: flex; flex-direction: column; gap: 8px; max-height: 46vh; min-height: 120px; overflow-y: auto; padding-top: 12px; } .live-line { display: flex; gap: 8px; align-items: flex-start; min-width: 0; } .live-line-body { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; line-height: 1.35; } .live-zap .live-line-body b { color: var(--accent); } @@ -991,7 +994,7 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; } .live-page > .live-chat-card { margin-top: 0; padding-top: 6px; border-top: none; } .live-page > .card > :not(.live-player, .live-chat) { margin-left: 14px; margin-right: 14px; } .live-page .live-player { border-radius: 0; } - .live-page .live-chat { padding: 10px 14px 0; max-height: 60vh; } + .live-page .live-chat { padding: 10px 14px 0; max-height: var(--live-chat-max, 60vh); } .live-page .live-title { font-size: 17px; } .live-chat .chat-row { gap: 10px; } .live-chat .chat-bubble { display: block; background: transparent; border: 0; border-radius: 0; padding: 0; font-size: 15px; } |
