diff options
Diffstat (limited to 'src/features')
| -rw-r--r-- | src/features/messages.js | 124 |
1 files changed, 106 insertions, 18 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); }, |
