diff options
| -rw-r--r-- | src/features/messages.js | 117 | ||||
| -rw-r--r-- | src/features/nwc.js | 24 | ||||
| -rw-r--r-- | src/image-thumbnails.js | 19 | ||||
| -rw-r--r-- | src/style.css | 11 | ||||
| -rw-r--r-- | tools/feed-media-views-test.js | 5 | ||||
| -rw-r--r-- | tools/image-thumbnails-test.js | 19 | ||||
| -rw-r--r-- | tools/media-grid-dups-test.js | 52 | ||||
| -rw-r--r-- | tools/push-resubscribe-test.js | 103 | ||||
| -rw-r--r-- | tools/video-tile-poster-test.js | 36 |
9 files changed, 338 insertions, 48 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 4900c40..71d3370 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -6768,6 +6768,7 @@ export function messagesFeature(ctx) { const videoProbes = new Map(); let videoProbing = 0; const videoProbeQueue = []; + const clipGone = (url) => { const d = videoInfo.get(url); return !!d && typeof d.goneAt === 'number' && Date.now() - d.goneAt < 86_400_000; }; const probeFailedLately = (d) => !!d && typeof d.failedAt === 'number' && Date.now() - d.failedAt < 3_600_000; function probeVideo(url, layout = false) { const have = videoInfo.get(url); @@ -6801,7 +6802,7 @@ export function messagesFeature(ctx) { // player's plain load answers this request without them, and it fails. // Any clip that had played in the feed was "unmeasurable" that way. const r = await fetch(url, { headers: { Range: 'bytes=0-' + (VIDEO_PROBE_BYTES - 1) }, cache: 'no-store', signal: ctrl.signal }); - if (!r.ok) throw new Error('HTTP ' + r.status); + if (!r.ok) throw Object.assign(new Error('HTTP ' + r.status), { status: r.status }); const ranges = r.status === 206; const total = ranges ? +(/\/(\d+)\s*$/.exec(r.headers.get('content-range') || '') || [])[1] : +r.headers.get('content-length'); // never more than the first bytes, even from a server that ignored the range @@ -6818,7 +6819,7 @@ export function messagesFeature(ctx) { let o = 0; for (const p of parts) { if (o >= buf.length) break; buf.set(p.subarray(0, buf.length - o), o); o += p.length; } const head = readMp4Head(buf); - const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) }; + const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, goneAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) }; if (total > 0) d.size = total; else { // a server that hides Content-Range from scripts (Primal's) still @@ -6832,8 +6833,13 @@ export function messagesFeature(ctx) { if (head.w && !(videoInfo.get(url) || {}).w) { d.w = head.w; d.h = head.h; } if (head.w) rememberVideo(url, head.w, head.h); noteVideoInfo(url, d); - } catch { - noteVideoInfo(url, { failedAt: Date.now() }); // a host that won't say (no CORS, down, slow): asked again in an hour + } catch (e) { + // a host that won't say (no CORS, down, slow): asked again in an hour. + // One that says the file is gone (deleted: a 404 or 410) is believed + // for a day, and the grid leaves the clip out (clipGone). + const gone = e && (e.status === 404 || e.status === 410); + noteVideoInfo(url, { failedAt: Date.now(), ...(gone ? { goneAt: Date.now() } : {}) }); + if (gone && mediaMode === 'videos') scheduleRepaint(); } finally { clearTimeout(timer); } return videoInfo.get(url); } @@ -13717,12 +13723,17 @@ export function messagesFeature(ctx) { // <img> of the original (or the 1100px column copy) to fetch and decode, // and the browser's lazy margin is a screen or two. These are local and a // few KB, so every tile loads at once and decodes in no time. - const TILE_CACHE = 'coinos-tile-thumbs-v1', TILE_PX = 360, TILE_MAX = 1200; + const TILE_CACHE = 'coinos-tile-thumbs-v2', TILE_PX = 360, TILE_MAX = 1200; const tileThumbs = new Map(); // url -> object URL const tileKey = (url) => 'https://tile-thumb.invalid/?u=' + encodeURIComponent(url); const tileQueue = [], tileTried = new Set(), tileLooked = new Set(); let tileBusy = 0, tileRepaint = null; - const tileStore = () => caches.open(TILE_CACHE); + let tileOldGone = false; + const tileStore = () => { + // the square tiles of before (v1) go: the grid's rows want each shape + if (!tileOldGone) { tileOldGone = true; caches.delete('coinos-tile-thumbs-v1').catch(() => {}); } + return caches.open(TILE_CACHE); + }; async function warmTileThumbs(urls) { if (typeof caches === 'undefined') return; let found = 0; @@ -13742,7 +13753,7 @@ export function messagesFeature(ctx) { const kept = mediaReady.get(url)?.thumb; if (!kept && (noCorsHost(url) || corsRefused.has(url))) { // the host keeps its bytes: the server cuts the tile - const tile = await serverPicBlob(url, 'tile'); + const tile = await serverPicBlob(url, 'row'); if (tile) await saveTileThumb(url, tile); return; } @@ -13752,7 +13763,7 @@ export function messagesFeature(ctx) { if (!res.ok) return; blob = await res.blob(); } catch (e) { - if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'tile'); if (tile) await saveTileThumb(url, tile); } + if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'row'); if (tile) await saveTileThumb(url, tile); } return; } if (/gif/i.test(blob.type)) return; // animated: the tile shows the original @@ -13907,16 +13918,51 @@ export function messagesFeature(ctx) { // videos by default on a phone that's in vertical orientation and only // horizontal videos if the phone is in landscape but have some kind of // control to toggle the ability to see all videos".) - const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', or unset: the screen's way round - const clipsAll = () => { try { return localStorage.getItem(CLIPS_FIT_KEY) === 'all'; } catch { return false; } }; - const setClipsAll = (all) => { try { if (all) localStorage.setItem(CLIPS_FIT_KEY, 'all'); else localStorage.removeItem(CLIPS_FIT_KEY); } catch {} }; + // On a desktop-sized window every shape is the default (Adam, 2026-10-22: + // the justified rows hold both); a phone keeps to its way round. + const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', 'fit' (the screen's way round), or unset: the device's default + const bigWindow = () => { try { return matchMedia('(min-width: 1000px) and (min-height: 600px)').matches; } catch { return false; } }; + const clipsAll = () => { try { const v = localStorage.getItem(CLIPS_FIT_KEY); return v === 'all' || (v !== 'fit' && bigWindow()); } catch { return bigWindow(); } }; + const setClipsAll = (all) => { try { if (all === bigWindow()) localStorage.removeItem(CLIPS_FIT_KEY); else localStorage.setItem(CLIPS_FIT_KEY, all ? 'all' : 'fit'); } catch {} }; const screenTall = () => window.innerHeight >= window.innerWidth; - const clipShape = (url) => { + const clipSize = (url) => { const d = videoInfo.get(url) || {}; const k = d.w && d.h ? d : videoDims.get(url) || mediaReady.get(url); const w = k && (k.w || k.width), hh = k && (k.h || k.height); - return w && hh ? (hh > w ? 'tall' : hh < w ? 'wide' : 'square') : null; + return w && hh ? { w, h: hh } : null; }; + // (no size yet: the still's proportions, which a grid of every shape has + // loaded without measuring anything — so going back to one shape finds + // the clips' shapes known) + const clipShape = (url) => { + const z = clipSize(url), r = z ? z.w / z.h : posterAr.get(url); + return r ? (r < 0.99 ? 'tall' : r > 1.01 ? 'wide' : 'square') : null; + }; + // width over height, kept between a phone's upright 9:16 and a cinema 2:1 + // (a stray 32:9 or 1:4 would make a tile a sliver); unknown: a square + // (until the clip's size is known, the still's own proportions: the + // server's and a frame grab keep the clip's shape) + const posterAr = new Map(); + const clampAr = (r) => Math.min(2, Math.max(0.5, r)); + const clipRatio = (url) => { const z = clipSize(url); return z ? clampAr(z.w / z.h) : posterAr.get(url) || 1; }; + // a grid item's: the file's measured size, the post's word for it (NIP-92 + // dim), or its still once that has loaded + function itemRatio(it) { + if (clipSize(it.url)) return clipRatio(it.url); + for (const tag of it.ev.tags || []) { + if (tag[0] !== 'imeta' || !tag.includes('url ' + it.url)) continue; + const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(imetaFields(tag).dim || ''); + if (m && +m[1] && +m[2]) return clampAr(+m[1] / +m[2]); + } + return posterAr.get(it.url) || 1; + } + function arFromStill(img, url) { + if (clipSize(url) || !img.naturalWidth || !img.naturalHeight) return; + const r = clampAr(img.naturalWidth / img.naturalHeight); + posterAr.set(url, r); + const tile = img.closest('.media-grid.justified .media-tile'); + if (tile) tile.style.setProperty('--ar', r.toFixed(3)); + } // true/false, or null while the clip's shape isn't known const clipFits = (url) => { if (clipsAll()) return true; const sh = clipShape(url); return sh === null ? null : sh === 'square' || sh === (screenTall() ? 'tall' : 'wide'); }; const clipsLabel = () => t(clipsAll() ? 'clipsAll' : screenTall() ? 'clipsTall' : 'clipsWide'); @@ -13952,7 +13998,10 @@ export function messagesFeature(ctx) { // or the same words from the same person posted again with another upload. const sameFile = (url) => { const m = /\/([0-9a-f]{64})(?:\.\w+)?(?:[?#]|$)/i.exec(url); return m ? m[1].toLowerCase() : url.replace(/[?#].*$/, ''); }; const saidAgain = (ev) => { const w = String(ev.content || '').replace(/https?:\/\/\S+/g, '').replace(/\s+/g, ' ').trim(); return w.length >= 8 ? ev.pubkey + '|' + w : null; }; - function mediaItems(c, kind) { + // (anyShape: the pager's list — every clip, the ones the wrong way round + // for the screen held out of sight by pagerFit, so "All shapes" there has + // them to show) + function mediaItems(c, kind, anyShape = false) { const out = [], seen = new Set(), said = new Map(); const r = mediaIndex(c.id); indexMedia(r, c.notes); @@ -13965,7 +14014,8 @@ export function messagesFeature(ctx) { const again = saidAgain(ev); if (again && said.has(again) && said.get(again) !== ev.id) continue; if (kind === 'videos') learnVideoMeta(ev); - const urls = kind === 'videos' ? clipUrlsOf(ev).filter(fitClip) + // (a clip whose host says it's deleted has nothing to show: a blank tile) + const urls = kind === 'videos' ? clipUrlsOf(ev).filter((u) => !clipGone(u) && (anyShape || fitClip(u))) : noteMediaUrls(ev.content).filter((u) => !u.startsWith('https://i.ytimg.com/')); // (the words are taken by a post that shows: one whose clip doesn't fit // the screen leaves them to the next) @@ -14195,7 +14245,15 @@ export function messagesFeature(ctx) { if (missing.length) warmTileThumbs(missing).then(() => queueTileThumbs(missing.filter((u) => !tileThumbs.has(u)))); } if (mediaMode === 'videos') for (const it of items.slice(0, 24)) preconnect(playSrc(it.url)); - return h('div', { class: 'media-grid', 'data-key': 'media-grid:' + mediaMode }, + // The tiles take the clips' shape (Adam, 2026-10-22): wide clips only (a + // wide screen) go one to a row, their posters whole, not slivers cut to + // portrait tiles; every shape ("All shapes") is laid out in justified + // rows, each tile its clip's own proportions and each row as tall as it + // takes to fill the width; tall ones only (a phone held upright) keep + // the tall tiles three across. + // Pictures go in justified rows too, in their own shapes. + const shape = mediaMode === 'images' ? ' justified' : mediaMode !== 'videos' ? '' : clipsAll() ? ' justified' : screenTall() ? '' : ' wide'; + return h('div', { class: 'media-grid' + shape, 'data-key': 'media-grid:' + mediaMode }, ...items.map((it) => { const k = mediaKey(it); // a video tile shows a still at once: kept, given, or the server's @@ -14208,12 +14266,14 @@ export function messagesFeature(ctx) { const fromServer = mediaMode === 'videos' && poster && poster === serverThumb(it.url); return h('button', { class: 'media-tile' + (mediaMode === 'videos' ? ' video' : ''), type: 'button', 'data-key': 'tile:' + k, + style: shape === ' justified' ? '--ar:' + itemRatio(it).toFixed(3) : undefined, 'aria-label': displayName(it.ev.pubkey), onClick: () => openMediaPager(mediaMode, k), onPointerDown: mediaMode === 'videos' ? () => earlyPlayer(it.url) : undefined, }, mediaMode === 'images' || poster ? h('img', { src: poster || tileThumbs.get(it.url) || mediaSrc(it.url), alt: '', draggable: 'false', loading: poster || tileThumbs.has(it.url) ? 'eager' : 'lazy', decoding: 'async', + onLoad: (e) => arFromStill(e.currentTarget, it.url), onError: (e) => { if (fromServer) { serverThumbFailed.add(it.url); render(); return; } // the frame grab's turn const b = e.target.closest('.media-tile'); if (b) b.classList.add('broken'); @@ -14249,7 +14309,9 @@ export function messagesFeature(ctx) { if (await grabFrame(url)) { if (!v.isConnected) return; const img = document.createElement('img'); - img.alt = ''; img.draggable = false; img.src = videoThumbs.get(url); + img.alt = ''; img.draggable = false; + img.addEventListener('load', () => arFromStill(img, url), { once: true }); + img.src = videoThumbs.get(url); v.replaceWith(img); if (heavy && d.size) img.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); return; @@ -14271,6 +14333,18 @@ export function messagesFeature(ctx) { // (a plain load: shown, not kept — a player's pixels can only be // read from a CORS load, and those fail on a cached plain copy) v.muted = true; + // a clip the player can't load either is gone as far as the grid + // goes: a deleted file whose 404 came without CORS headers + // (Primal's blossom) only looked like a quiet host to the probe, + // and its tile sat blank. Left out for a day, like a 404 the + // probe could read. + v.addEventListener('error', () => { + if (!v.isConnected || !v.getAttribute('src')) return; // let go of by the eight-second cap + noteVideoInfo(url, { goneAt: Date.now() }); + const b = v.closest('.media-tile'); + if (b) b.classList.add('broken'); + scheduleRepaint(); + }, { once: true }); v.src = v.getAttribute('data-src'); if (heavy && d.size) v.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); return; @@ -15587,7 +15661,7 @@ export function messagesFeature(ctx) { const c = feedNow(); pager.groups ||= new Map(); const src = pagerSource(); - for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind))) { + for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind, true))) { const k = mediaKey(it); if (pager.keys.has(k)) continue; pager.keys.add(k); @@ -15683,8 +15757,13 @@ export function messagesFeature(ctx) { function pagerFit() { if (!pager) return; const cur = pager.cur || pager.anchor, cg = cur && cur.closest('.mp-group'); + // the grid's pager goes by the grid's rule: a clip of a shape not yet + // known stays out until it's measured (fitClip measures it); a page's + // pager shows one until it's known not to fit + const strict = pager.kind === 'videos' && !pagerSource(); + const ok = (u) => (strict ? fitClip(u) : clipFits(u) !== false); for (const g of pagerGroups(true)) { - const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || clipFits(m.getAttribute('data-full') || m.getAttribute('data-src')) !== false; }); + const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || ok(m.getAttribute('data-full') || m.getAttribute('data-src')); }); pagerToggleGroup(g, 'mp-off', !fits); } } diff --git a/src/features/nwc.js b/src/features/nwc.js index ec79081..9c71a7f 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -822,6 +822,25 @@ export function nwcFeature(ctx) { // wrong keys — background wake-ups silently die the first time a // connection is recreated. Debounced; the server replaces by endpoint. let regTimer = null; + // The browser's subscription, made again when it's gone: iOS drops it after + // three pushes that showed no notification (and a key rotation strands an + // old one), and nothing else re-arms a wallet whose `background` is still on. + async function currentSub() { + const reg = await navigator.serviceWorker.ready; + const { publicKey } = await (await fetch(`${NOTIFIER}/vapid`)).json(); + const want = b64ToBytes(publicKey); + let sub = await reg.pushManager.getSubscription(); + if (sub) { + let have = []; + try { have = new Uint8Array(sub.options.applicationServerKey || []); } catch {} + if (have.length === want.length && have.every((b, i) => b === want[i])) return sub.toJSON(); + try { await sub.unsubscribe(); } catch {} + } + if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return null; + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: want }); + dlog('nwc: push subscription was gone, made a new one'); + return sub.toJSON(); + } function refreshRegistration() { if (!load().background) return; if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return; @@ -831,8 +850,7 @@ export function nwcFeature(ctx) { const pks = watchPks(); if (!pks.length) return; const up2 = upEndpoint(); - const sub = up2 ? { endpoint: up2, unifiedpush: true } - : await (await navigator.serviceWorker.ready).pushManager.getSubscription().then((x) => x && x.toJSON()); + const sub = up2 ? { endpoint: up2, unifiedpush: true } : await currentSub(); if (!sub) return; await fetch(`${NOTIFIER}/register`, { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -949,7 +967,7 @@ export function nwcFeature(ctx) { if (typeof window !== 'undefined') { window.addEventListener('online', () => listen()); document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && conns().length) listen(); + if (document.visibilityState === 'visible' && conns().length) { listen(); refreshRegistration(); } }); } } diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js index ffac4b9..2686dac 100644 --- a/src/image-thumbnails.js +++ b/src/image-thumbnails.js @@ -14,16 +14,21 @@ function thumbnailWorker() { const result = { width: bitmap.width, height: bitmap.height, media: null, tile: null }; // GIFs must keep animating; a canvas copy would freeze their first frame. if (!/gif/i.test(blob.type)) { + // The grid's tile: the picture in its own shape (justified rows), + // tileSize tall, its middle cut to between 1:2 and 2:1 — the most a + // tile stretches either way. if (tileSize) { - const side = Math.min(bitmap.width, bitmap.height), px = Math.min(tileSize, side); - let square; + const W = bitmap.width, H = bitmap.height; + const cw = Math.min(W, H * 2), ch = Math.min(H, W * 2); + const th = Math.min(tileSize, ch), tw = Math.max(1, Math.round(th * cw / ch)); + let cut; try { - square = await createImageBitmap(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side, - { resizeWidth: px, resizeHeight: px, resizeQuality: 'high' }); - const canvas = new OffscreenCanvas(px, px); - canvas.getContext('2d').drawImage(square, 0, 0); + cut = await createImageBitmap(bitmap, (W - cw) / 2, (H - ch) / 2, cw, ch, + { resizeWidth: tw, resizeHeight: th, resizeQuality: 'high' }); + const canvas = new OffscreenCanvas(tw, th); + canvas.getContext('2d').drawImage(cut, 0, 0); result.tile = await encode(canvas, 0.8); - } catch {} finally { square?.close(); } + } catch {} finally { cut?.close(); } } if (width && bitmap.width > width * 1.25) { try { diff --git a/src/style.css b/src/style.css index 4fbe96b..61d6f01 100644 --- a/src/style.css +++ b/src/style.css @@ -1538,6 +1538,17 @@ body::after { background: var(--surface2); overflow: hidden; cursor: pointer; } .media-tile.video { aspect-ratio: 9 / 16; } +/* only wide clips in it: one to a row, the poster whole */ +.media-grid.wide { grid-template-columns: 1fr; gap: 6px; } +.media-grid.wide .media-tile.video { aspect-ratio: 16 / 9; } +/* every shape in it: justified rows. A tile starts at its proportions at + the row height and grows in proportion to them, so a row's tiles share one + height and fill the width; the filler takes the last row's slack instead + of stretching its few tiles. */ +.media-grid.justified { display: flex; flex-wrap: wrap; --row-h: 140px; } +.media-grid.justified .media-tile { aspect-ratio: var(--ar); flex: var(--ar) 1 calc(var(--ar) * var(--row-h)); min-width: 0; } +.media-grid.justified::after { content: ''; flex: 1000 1 0; } +@media (max-width: 600px) { .media-grid.justified { --row-h: 100px; } } .media-tile img, .media-tile video { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; } .media-tile.broken { display: none; } .media-tile-play { diff --git a/tools/feed-media-views-test.js b/tools/feed-media-views-test.js index 87bf3cf..1eac95c 100644 --- a/tools/feed-media-views-test.js +++ b/tools/feed-media-views-test.js @@ -95,7 +95,8 @@ const pagerState = () => page.evaluate(() => { const p = document.querySelector('.media-pager'); if (!p) return null; const sc = p.querySelector('.mp-scroll'); - const slides = [...sc.querySelectorAll('.mp-slide')]; // (not the loading screen at the end) + // (not the loading screen at the end, nor a clip held out for its shape) + const slides = [...sc.querySelectorAll('.mp-slide')].filter((x) => !x.closest('.mp-off')); const i = slides.findIndex((x) => { const r = x.getBoundingClientRect(); return Math.abs(r.top) < 4 && Math.abs(r.left) < 4; }); // the slide on screen const vids = slides.map((s) => s.querySelector('video')); return { n: slides.length, i, src: (slides[i]?.querySelector('.mp-media')?.getAttribute('data-src') || '').split('/').pop(), @@ -201,7 +202,7 @@ try { const vi = await info(); check('a probe reads the size, ranges, layout and picture size from 64 KB', vi['a.mp4']?.probed && vi['a.mp4'].ranges && vi['a.mp4'].faststart && vi['a.mp4'].size > 1000 && vi['a.mp4'].w === 360 && vi['a.mp4'].h === 640, JSON.stringify(vi['a.mp4'])); - check('the landscape clip is left out of Videos', !(await page.evaluate(() => [...document.querySelectorAll('.media-pager video')].some((v) => /slow/.test(v.getAttribute('data-src')))))); + check('the landscape clip is left out of Videos', !(await page.evaluate(() => [...document.querySelectorAll('.media-pager video')].some((v) => /slow/.test(v.getAttribute('data-src')) && !v.closest('.mp-off'))))); check('an index-last file from a server without ranges is seen for what it is', vi['slow.mp4']?.probed && vi['slow.mp4'].faststart === false && vi['slow.mp4'].ranges === false, JSON.stringify(vi['slow.mp4'])); check('the 50 MB clip is known as such before any of it plays', vi['c.mp4']?.size === 50000000, JSON.stringify(vi['c.mp4'])); await page.keyboard.press('ArrowDown'); await sleep(1200); diff --git a/tools/image-thumbnails-test.js b/tools/image-thumbnails-test.js index ede7e11..6ece275 100644 --- a/tools/image-thumbnails-test.js +++ b/tools/image-thumbnails-test.js @@ -1,4 +1,4 @@ -// Real minified blob worker: both thumbnail sizes, animated originals, +// Real minified blob worker: both thumbnail sizes (the tile in the picture's own shape), animated originals, // bounded concurrency and graceful fallback, with no page-thread encoding. import assert from 'node:assert/strict'; import puppeteer from './puppeteer.js'; @@ -30,25 +30,30 @@ try { thumbnails(new Blob(['broken'],{type:'image/jpeg'}),{width:1100}), thumbnails(blob,{width:1100}), ]); const media = await decode(big.media), tile = await decode(big.tile); - const square = new OffscreenCanvas(360,360);square.getContext('2d').drawImage(tile,0,0); - const pixel=[...square.getContext('2d').getImageData(0,180,1,1).data]; + const whole = new OffscreenCanvas(tile.width,tile.height);whole.getContext('2d').drawImage(tile,0,0); + const pixel=[...whole.getContext('2d').getImageData(tile.width>>1,180,1,1).data], edge=[...whole.getContext('2d').getImageData(2,180,1,1).data]; + // a panorama past 2:1 keeps its middle, 2:1 + const pano=new OffscreenCanvas(4000,1000);pano.getContext('2d').fillStyle='green';pano.getContext('2d').fillRect(0,0,4000,1000); + const panoTile=await decode((await thumbnails(await encode.call(pano,{type:'image/png'}),{tileSize:360})).tile); const smallCanvas=new OffscreenCanvas(32,20);smallCanvas.getContext('2d'); const smallBlob=await encode.call(smallCanvas,{type:'image/png'}); const small=await thumbnails(smallBlob,{width:1100,tileSize:360}); const smallTile=await decode(small.tile); const gif=new Blob([Uint8Array.from(atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),c=>c.charCodeAt(0))],{type:'image/gif'}); const animated=await thumbnails(gif,{width:1100,tileSize:360}); - const out={mainCalls,maxPending,big:[big.width,big.height],media:[media.width,media.height],tile:[tile.width,tile.height],pixel, + const out={mainCalls,maxPending,big:[big.width,big.height],media:[media.width,media.height],tile:[tile.width,tile.height],pixel,edge,pano:[panoTile.width,panoTile.height], tileOnly:!tiles.media&&!!tiles.tile,bad,recovered:!!recovered.media,smallOriginal:small.media===null,smallTile:[smallTile.width,smallTile.height], animated: animated && [animated.width,animated.height,animated.media,animated.tile]}; media.close();tile.close();smallTile.close();return out; }); console.log(result); assert.equal(result.mainCalls,0);assert.equal(result.maxPending,1); - assert.deepEqual(result.big,[3000,2000]);assert.deepEqual(result.media,[1100,733]);assert.deepEqual(result.tile,[360,360]); - assert(result.pixel[2]>200&&result.pixel[0]<30,'tile crops the center'); + assert.deepEqual(result.big,[3000,2000]);assert.deepEqual(result.media,[1100,733]);assert.deepEqual(result.tile,[540,360]); + // the grid's justified rows: a tile in the picture's own shape, 360 tall, uncut up to 2:1 + assert(result.pixel[2]>200&&result.pixel[0]<30&&result.edge[0]>200,'tile keeps the whole picture'); + assert.deepEqual(result.pano,[720,360]); assert(result.tileOnly&&result.recovered&&result.smallOriginal);assert.equal(result.bad,null); - assert.deepEqual(result.smallTile,[20,20]);assert.deepEqual(result.animated,[1,1,null,null]); + assert.deepEqual(result.smallTile,[32,20]);assert.deepEqual(result.animated,[1,1,null,null]); const fallback=await browser.newPage();await fallback.goto(server.url.href);await fallback.waitForFunction(()=>window.thumbnails); assert.equal(await fallback.evaluate(async()=>{window.Worker=class {constructor(){throw Error('blocked');}};return thumbnails(new Blob(['x']),{width:1100});}),null); console.log('✓ thumbnails stay off the page thread; sizes, crop, originals, queue, bad-image recovery and worker fallback pass'); diff --git a/tools/media-grid-dups-test.js b/tools/media-grid-dups-test.js index 360ae0c..205a4a5 100644 --- a/tools/media-grid-dups-test.js +++ b/tools/media-grid-dups-test.js @@ -17,19 +17,24 @@ const clip = (name, size) => { if (!existsSync(f)) Bun.spawnSync(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size + ':rate=10', '-t', '30', '-c:v', 'libvpx', '-b:v', '100k', f]); return f; }; -const CLIPS = { wide: clip('wide', '320x180'), again: clip('wide', '320x180'), other: clip('wide', '320x180'), last: clip('last', '240x240') }; +const CLIPS = { wide: clip('wide', '320x180'), again: clip('wide', '320x180'), other: clip('wide', '320x180'), tall: clip('tall', '180x320'), last: clip('last', '240x240') }; +const pic = (size) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout; +const picWide = pic('640x360'), picTall = pic('360x640'); const SK = generateSecretKey(), AUTHOR = getPublicKey(SK); const now = Math.floor(Date.now() / 1000); const html = await buildHtml({ minify: true, pwa: false }); const server = Bun.serve({ port: 0, fetch: (req) => { const path = new URL(req.url).pathname; - const m = /^\/(wide|again|other|last)\.webm$/.exec(path); + const m = /^\/(wide|again|other|tall|last)\.webm$/.exec(path); if (m) { const f = Bun.file(CLIPS[m[1]]), range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.get('range') || ''); if (!range) return new Response(f, { headers: { 'content-type': 'video/webm', 'accept-ranges': 'bytes' } }); const a = +range[1], b = range[2] ? Math.min(+range[2], f.size - 1) : f.size - 1; return new Response(f.slice(a, b + 1), { status: 206, headers: { 'content-type': 'video/webm', 'accept-ranges': 'bytes', 'content-range': 'bytes ' + a + '-' + b + '/' + f.size, 'content-length': String(b - a + 1) } }); } + const pm = /^\/pic-(wide|tall)\.png$/.exec(path); + if (pm) return new Response(pm[1] === 'wide' ? picWide : picTall, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); + if (path === '/dead.webm') return new Response('gone', { status: 404 }); if (path === '/still.png') return new Response(png, { headers: { 'content-type': 'image/png' } }); if (path.startsWith('/punks') || path === '/verify-worker.js') return new Response(Bun.file('dist' + path)); return new Response(html, { headers: { 'content-type': 'text/html' } }); @@ -45,6 +50,13 @@ const seeded = [ post('Transylvania lightning conference 2026 ' + U('again'), U('again'), 200), post('Transylvania lightning conference 2026 ' + U('other'), U('other'), 300), post('the last clip ' + U('last'), U('last'), 400), + // pictures, one wide and one tall, the post saying nothing of their size + finalizeEvent({ kind: 1, created_at: now - 120, tags: [], content: 'a wide view ' + server.url.origin + '/pic-wide.png' }, SK), + finalizeEvent({ kind: 1, created_at: now - 130, tags: [], content: 'a tall view ' + server.url.origin + '/pic-tall.png' }, SK), + // a tall one: out of a wide screen's grid until "All shapes" + finalizeEvent({ kind: 1, created_at: now - 450, tags: [['imeta', 'url ' + U('tall'), 'm video/webm', 'dim 180x320']], content: 'standing up ' + U('tall') }, SK), + // a clip its host has since deleted (it says so: 404) — no blank tile for it + finalizeEvent({ kind: 1, created_at: now - 500, tags: [['imeta', 'url ' + U('dead'), 'm video/webm', 'dim 320x180']], content: 'deleted since ' + U('dead') }, SK), ]; const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] }); @@ -80,16 +92,48 @@ try { await page.reload({ waitUntil: 'domcontentloaded' }); await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); - check('the clips are in the feed', await waitFor(() => document.querySelectorAll('.notes-feed video.note-video').length >= 6, null, 20000)); + check('the clips are in the feed', await waitFor(() => document.querySelectorAll('.notes-feed video.note-video').length >= 8, null, 20000)); + await page.evaluate(() => document.querySelector('.media-mode[data-mode="videos"]').click()); + // a desktop-sized window starts on every shape (justified rows, the tall clip in) + check('a desktop starts on every shape', await waitFor(() => !!document.querySelector('.media-grid.justified') && [...document.querySelectorAll('.media-grid .media-tile')].some((t) => t.getAttribute('data-key').endsWith('/tall.webm')), null, 15000)); + // the rest starts from the screen's way round: wide only + await page.evaluate(() => { localStorage.setItem('coinos-clips-fit', 'fit'); document.querySelector('.media-mode[data-mode="images"]').click(); }); + await sleep(300); await page.evaluate(() => document.querySelector('.media-mode[data-mode="videos"]').click()); await waitFor(() => document.querySelectorAll('.media-grid .media-tile').length >= 3, null, 15000); + await waitFor(() => document.querySelectorAll('.media-grid .media-tile').length === 3, null, 8000); await sleep(1500); const tiles = await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile').length); - check('one tile per clip: the reposted file once, the re-uploaded post once, the other one', tiles === 3, tiles + ' tiles'); + check('a wide screen lays the clips out one to a row, wide', await page.evaluate(() => { const g = document.querySelector('.media-grid'), t = g.querySelector('.media-tile').getBoundingClientRect(); return g.classList.contains('wide') && Math.abs(t.width / t.height - 16 / 9) < 0.05 && t.width > g.getBoundingClientRect().width * 0.95; })); + check('one tile per clip: the reposted file once, the re-uploaded post once, the other one, none for the deleted one', tiles === 3, tiles + ' tiles'); await page.evaluate(() => document.querySelector('.media-grid .media-tile').click()); check('the pager opens', await waitFor(() => !!document.querySelector('.mp-slide.mp-cur video.mp-media'), null, 6000)); check('the clip is drawn no bigger than 1.5× its pixels', await waitFor(() => { const v = document.querySelector('.mp-slide.mp-cur video.mp-media'); return v && v.videoWidth && v.getBoundingClientRect().width <= v.videoWidth * 1.5 + 1 && v.style.maxWidth; }, null, 8000), JSON.stringify(await page.evaluate(() => { const v = document.querySelector('.mp-slide.mp-cur video.mp-media'); return v && { vw: v.videoWidth, w: v.getBoundingClientRect().width, max: v.style.maxWidth }; }))); + // "All shapes", from the pager's top bar: the tall clip is there to flick to + const tallShown = () => page.evaluate(() => { const s = [...document.querySelectorAll('.mp-slide')].find((x) => x.getAttribute('data-k').endsWith('/tall.webm')); return !!s && !s.closest('.mp-group').classList.contains('mp-off'); }); + check('in the pager, the tall clip is held out on a wide screen', !(await tallShown())); + await page.evaluate(() => document.querySelector('.mp-fit').click()); + check('…and "All shapes" brings it in', await waitFor(() => { const s = [...document.querySelectorAll('.mp-slide')].find((x) => x.getAttribute('data-k').endsWith('/tall.webm')); return !!s && !s.closest('.mp-group').classList.contains('mp-off'); }, null, 3000)); + await page.keyboard.press('Escape'); + check('…which, being the desktop\'s default, is kept as no setting at all', await page.evaluate(() => localStorage.getItem('coinos-clips-fit') === null)); + check('the grid has it too', await waitFor(() => [...document.querySelectorAll('.media-grid .media-tile')].some((t) => t.getAttribute('data-key').endsWith('/tall.webm')), null, 5000)); + const rows = () => page.evaluate(() => { + const g = document.querySelector('.media-grid'), gw = g.getBoundingClientRect().width; + const ts = [...g.querySelectorAll('.media-tile')].map((t) => ({ k: t.getAttribute('data-key').split('/').pop(), r: t.getBoundingClientRect() })); + const by = new Map(); for (const t of ts) { const y = Math.round(t.r.top); (by.get(y) || by.set(y, []).get(y)).push(t); } + return { justified: g.classList.contains('justified'), gw, rows: [...by.values()].map((row) => ({ ks: row.map((t) => t.k), hs: row.map((t) => Math.round(t.r.height)), ars: row.map((t) => +(t.r.width / t.r.height).toFixed(2)), w: Math.round(row.reduce((a, t) => a + t.r.width, 0) + 3 * (row.length - 1)) })) }; + }); + await waitFor(() => { const t = [...document.querySelectorAll('.media-grid .media-tile')].find((x) => x.getAttribute('data-key').endsWith('/tall.webm')); return t && t.getBoundingClientRect().width < t.getBoundingClientRect().height; }, null, 5000); + const R = await rows(); + const tallT = R.rows.flatMap((r) => r.ks.map((k, i) => ({ k, ar: r.ars[i] }))).find((x) => x.k === 'tall.webm'); + check('…in justified rows: every tile its clip\'s shape (the tall one tall, the wide ones wide)', R.justified && tallT && Math.abs(tallT.ar - 0.5625) < 0.03 && R.rows.flatMap((r) => r.ks.map((k, i) => ({ k, ar: r.ars[i] }))).filter((x) => x.k !== 'tall.webm' && x.k !== 'last.webm').every((x) => Math.abs(x.ar - 16 / 9) < 0.03), JSON.stringify(R)); + check('…one height across each row', R.rows.every((r) => Math.max(...r.hs) - Math.min(...r.hs) <= 1), JSON.stringify(R.rows.map((r) => r.hs))); + // the Images grid: justified rows too, each picture in its own shape + await page.evaluate(() => document.querySelector('.media-mode[data-mode="images"]').click()); + const picAr = (name) => page.evaluate((n) => { const t = [...document.querySelectorAll('.media-grid .media-tile')].find((x) => x.getAttribute('data-key').endsWith(n)); if (!t) return null; const r = t.getBoundingClientRect(); return +(r.width / r.height).toFixed(2); }, name); + check('the Images grid lays pictures out in justified rows, each its own shape', await waitFor(() => { const g = document.querySelector('.media-grid.justified'); if (!g) return false; const ar = (n) => { const t = [...g.querySelectorAll('.media-tile')].find((x) => x.getAttribute('data-key').endsWith(n)); if (!t) return 0; const r = t.getBoundingClientRect(); return r.width / r.height; }; return Math.abs(ar('pic-wide.png') - 16 / 9) < 0.05 && Math.abs(ar('pic-tall.png') - 9 / 16) < 0.05; }, null, 10000), + JSON.stringify({ wide: await picAr('pic-wide.png'), tall: await picAr('pic-tall.png') })); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); diff --git a/tools/push-resubscribe-test.js b/tools/push-resubscribe-test.js new file mode 100644 index 0000000..19998b2 --- /dev/null +++ b/tools/push-resubscribe-test.js @@ -0,0 +1,103 @@ +// iOS drops a web push subscription after three pushes that showed no +// notification, and nothing used to make a new one: the wallet's background +// switch stayed on, getSubscription() came back empty, and the notifier kept +// a dead endpoint, so NWC requests stopped waking the closed app until the +// user toggled it off and on (reported by PullCap). Opening the app, or +// coming back to it, must subscribe again and tell the notifier. +// +// Run: bun tools/push-resubscribe-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { cacheKeyFor } from '../src/wallet.js'; +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 html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5263, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const KEY = 'BP' + 'A'.repeat(85); // any 65-byte key, base64url +await page.evaluateOnNewDocument((KEY) => { + const bytes = () => Uint8Array.from(atob(KEY.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)); + window.__subs = 0; window.__regs = []; + let sub = null; // iOS has already dropped it + const make = () => ({ + endpoint: 'https://web.push.apple.com/sub' + window.__subs, + options: { applicationServerKey: bytes().buffer }, + toJSON() { return { endpoint: this.endpoint, keys: { p256dh: 'x', auth: 'y' } }; }, + unsubscribe: () => { sub = null; return Promise.resolve(true); }, + }); + window.__drop = () => { sub = null; }; + const reg = { + pushManager: { + getSubscription: () => Promise.resolve(sub), + subscribe: () => { window.__subs++; sub = make(); return Promise.resolve(sub); }, + }, + showNotification: () => Promise.resolve(), + }; + Object.defineProperty(navigator.serviceWorker, 'ready', { get: () => Promise.resolve(reg) }); + Notification.requestPermission = () => Promise.resolve('granted'); + Object.defineProperty(Notification, 'permission', { get: () => 'granted' }); + const f = window.fetch; + window.fetch = async (u, o) => { + const url = String(u); + if (url.startsWith('https://nwcpush.coinos.io/vapid')) return new Response(JSON.stringify({ publicKey: KEY })); + if (url.startsWith('https://nwcpush.coinos.io/register')) { + const b = JSON.parse(o.body); + if (b.servicePubkeys) window.__regs.push(b.subscription.endpoint); + return new Response('{"ok":true}'); + } + return f(u, o); + }; +}, KEY); +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; }; +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5263/', { 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(500); + await click('to import'); await sleep(400); + await page.waitForSelector('textarea'); + const mn = generateMnemonic(wordlist); + await page.type('textarea', mn); + await click('open wallet'); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + + // a wallet answering in the background, whose subscription iOS took away + await page.evaluate((k) => localStorage.setItem(k + ':nwc', JSON.stringify({ + conns: [{ id: 'x', name: 'test', servicePk: 'a'.repeat(64), sk: 'b'.repeat(64), maxSat: 1000, budget: {} }], + background: true, + })), base); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await sleep(3000); + let s = await page.evaluate(() => ({ subs: window.__subs, regs: window.__regs })); + check('opening the app subscribes again', s.subs >= 1, `${s.subs} subscribe()`); + check('...and registers the new endpoint for the connection', s.regs.includes('https://web.push.apple.com/sub' + s.subs), s.regs.join(' ')); + + // dropped again while the app sat in the background; it resumes, no reload + await page.evaluate(() => { window.__drop(); window.__regs.length = 0; }); + await page.evaluate(() => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' }); + document.dispatchEvent(new Event('visibilitychange')); + }); + await sleep(3000); + const before = s.subs; + s = await page.evaluate(() => ({ subs: window.__subs, regs: window.__regs })); + check('coming back to the app subscribes again', s.subs > before, `${s.subs} subscribe()`); + check('...and registers it', s.regs.includes('https://web.push.apple.com/sub' + s.subs), s.regs.join(' ')); + + // a live subscription is left alone + await page.evaluate(() => { window.__regs.length = 0; document.dispatchEvent(new Event('visibilitychange')); }); + await sleep(3000); + const again = await page.evaluate(() => ({ subs: window.__subs, regs: window.__regs })); + check('a subscription still there is reused', again.subs === s.subs && again.regs.length >= 1); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ a dropped push subscription comes back' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/video-tile-poster-test.js b/tools/video-tile-poster-test.js index 3b5fe93..1f2cb47 100644 --- a/tools/video-tile-poster-test.js +++ b/tools/video-tile-poster-test.js @@ -1,7 +1,8 @@ // Videos grid: a tile shows the server's still (vmedia thumb.jpg, cached at // the CDN) at once, instead of waiting on the browser's own probe and frame // grab — and never touches the clip itself for it. A clip the server has no -// picture for falls back to the frame grab. +// picture for falls back to the frame grab, and one the browser can't load +// either (deleted, its 404 without CORS headers) leaves the grid. // Run: bun tools/video-tile-poster-test.js import puppeteer from './puppeteer.js'; import { cacheKeyFor } from '../src/wallet.js'; @@ -13,12 +14,15 @@ const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' const JPG = '/tmp/coinos-video-tile-poster.jpg'; Bun.spawnSync(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'color=c=orange:s=270x480', '-frames:v', '1', JPG]); const JPEG = Buffer.from(await Bun.file(JPG).arrayBuffer()); +const MP4 = '/tmp/coinos-video-tile-poster.mp4'; +Bun.spawnSync(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'color=c=blue:s=360x640:d=1', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', MP4]); +const CLIPBYTES = Buffer.from(await Bun.file(MP4).arrayBuffer()); const AUTHOR = (() => { const sk = generateSecretKey(); return { sk, pk: getPublicKey(sk) }; })(); const now = Math.floor(Date.now() / 1000); const CLIP = (n) => 'https://media.test/' + n + '.mp4'; const post = (n, ago) => finalizeEvent({ kind: 1, created_at: now - ago, content: 'clip ' + n + ' ' + CLIP(n), tags: [['imeta', 'url ' + CLIP(n), 'm video/mp4', 'size 900000', 'dim 360x640']] }, AUTHOR.sk); -const POSTS = [post('a', 100), post('b', 200), post('nopic', 300)]; +const POSTS = [post('a', 100), post('b', 200), post('nopic', 300), post('dead', 400)]; const html = await buildHtml({ minify: true, pwa: false }); const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); @@ -31,10 +35,16 @@ page.on('request', (r) => { if (u.pathname.startsWith('/vmedia/thumb.jpg')) { const src = u.searchParams.get('u'); asked.push(['thumb', src]); - if (src === CLIP('nopic')) return r.respond({ status: 404, body: 'No picture' }); + if (src === CLIP('nopic') || src === CLIP('dead')) return r.respond({ status: 404, body: 'No picture' }); return r.respond({ status: 200, contentType: 'image/jpeg', body: JPEG, headers: { 'access-control-allow-origin': '*' } }); } - if (u.host === 'media.test') { asked.push(['clip', r.url()]); return r.abort(); } + if (u.host === 'media.test') { + asked.push(['clip', r.url()]); + // deleted, and the host's 404 says nothing to scripts (Primal's blossom) + if (u.pathname === '/dead.mp4') return r.respond({ status: 404, body: 'not found' }); + if (u.pathname === '/nopic.mp4') return r.respond({ status: 200, contentType: 'video/mp4', body: CLIPBYTES, headers: { 'access-control-allow-origin': '*' } }); + return r.abort(); + } r.continue(); }); await page.evaluateOnNewDocument(() => { @@ -79,17 +89,31 @@ try { await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); - check('the Videos grid has the three clips', await waitFor(() => document.querySelectorAll('.media-grid .media-tile.video').length === 3, 15000), + check('the Videos grid has the clips', await waitFor(() => document.querySelectorAll('.media-grid .media-tile.video').length >= 3, 15000), String(await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile.video').length))); check('two tiles show the server\'s still, loaded', await waitFor(() => [...document.querySelectorAll('.media-tile.video img')] .filter((i) => i.src.includes('/vmedia/thumb.jpg') && i.naturalWidth > 0).length === 2, 8000), JSON.stringify(await page.evaluate(() => [...document.querySelectorAll('.media-tile.video')].map((t) => (t.querySelector('img')?.src || t.querySelector('video') ? 'video' : t.innerHTML).slice(-40))))); check('the clip without one falls back to the frame grab', await waitFor(() => [...document.querySelectorAll('.media-tile.video')] .some((t) => !t.querySelector('img') && (t.querySelector('video') || t.querySelector('.media-tile-cost'))), 8000)); + check('the deleted clip leaves the grid instead of sitting there blank', await waitFor(() => { + const tiles = [...document.querySelectorAll('.media-grid .media-tile.video')].filter((t) => getComputedStyle(t).display !== 'none'); + return tiles.length === 3 && !document.querySelector('.media-grid video[src*="dead"]'); + }, 10000), String(await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile.video').length))); await sleep(1500); - const clipHits = asked.filter(([k, u]) => k === 'clip' && !u.includes('nopic')); + const clipHits = asked.filter(([k, u]) => k === 'clip' && !u.includes('nopic') && !u.includes('dead')); check('the pictured clips themselves were never fetched for a still', clipHits.length === 0, clipHits.map((x) => x[1]).join(', ')); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); + // remembered: the next visit leaves it out from the start + await sleep(2000); + asked.length = 0; + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); + await waitFor(() => document.querySelectorAll('.media-grid .media-tile.video').length >= 3, 15000); + await sleep(3000); + check('...and stays out after a reload', await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile.video').length) === 3 + && !asked.some(([k, u]) => k === 'clip' && u.includes('dead')), String(await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile.video').length))); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ video tiles show the server\'s still at once' : '\n❌ failed'); process.exit(ok ? 0 : 1); |
