diff options
Diffstat (limited to 'tools/youtube-tap-test.js')
| -rw-r--r-- | tools/youtube-tap-test.js | 110 |
1 files changed, 110 insertions, 0 deletions
diff --git a/tools/youtube-tap-test.js b/tools/youtube-tap-test.js new file mode 100644 index 0000000..271277f --- /dev/null +++ b/tools/youtube-tap-test.js @@ -0,0 +1,110 @@ +// A YouTube clip in a post takes one tap, like any clip: on the picture — +// the still, or the player already going (autoplayed, muted) — it plays with +// sound, full screen. The player's own taps never reach the page, so a layer +// over the picture takes them; YouTube's control bar along the bottom is +// left to YouTube, and full screen the layer steps aside. +// Run: bun tools/youtube-tap-test.js +import puppeteer from './puppeteer.js'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; +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 png = Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=480x360', '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout; + +const SK = generateSecretKey(), AUTHOR = getPublicKey(SK); +const now = Math.floor(Date.now() / 1000); +const POSTS = [ + finalizeEvent({ kind: 1, created_at: now - 100, tags: [], content: 'watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ' }, SK), + ...Array.from({ length: 4 }, (_, i) => finalizeEvent({ kind: 1, created_at: now - 200 - i * 60, tags: [], content: 'filler ' + i + ' ' + 'lorem ipsum dolor sit amet. '.repeat(5) }, SK)), +]; +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: (req) => { + const path = new URL(req.url).pathname; + if (path.startsWith('/punks') || path === '/verify-worker.js') return new Response(Bun.file('dist' + path)); + return new Response(html, { headers: { 'content-type': 'text/html' } }); +} }); +// YouTube, stood in for: the player page notes every command it is sent +const PLAYER = '<!doctype html><html><body style="margin:0;background:#222;height:100vh"><script>window.__cmds=[];addEventListener("message",(e)=>{try{const m=JSON.parse(e.data);if(m.event==="command")window.__cmds.push(m.func)}catch{}});</script></body></html>'; + +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] }); +async function run(saveData) { + console.log('\n[' + (saveData ? 'Data Saver: the still first' : 'autoplay: the player already going, muted') + ']'); + const ctx = await browser.createBrowserContext(); + const page = await ctx.newPage(); + await page.setRequestInterception(true); + page.on('request', (r) => { + const u = r.url(); + if (u.startsWith('https://www.youtube-nocookie.com/embed/')) return r.respond({ status: 200, contentType: 'text/html', body: PLAYER }); + if (u.startsWith('https://i.ytimg.com/')) return r.respond({ status: 200, contentType: 'image/png', body: png }); + return r.continue(); + }); + await page.evaluateOnNewDocument((sd) => { + if (sd) Object.defineProperty(navigator, 'connection', { configurable: true, get: () => ({ saveData: true, effectiveType: '4g', addEventListener() {}, removeEventListener() {} }) }); + const Real = window.WebSocket; + window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') return; } catch {} return send(d); }; return ws; }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); + }, saveData); + const errs = []; + page.on('pageerror', (e) => errs.push(String(e))); + const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); + const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; + const waitFor = async (fn, arg, ms = 10000) => { for (let i = 0; i < ms / 100; i++) { if (await page.evaluate(fn, arg)) return true; await sleep(100); } return false; }; + const box = () => page.evaluate(() => { const b = document.querySelector('.notes-feed .yt-embed').getBoundingClientRect(); return { x: b.x, y: b.y, w: b.width, h: b.height }; }); + const st = () => page.evaluate(() => { const b = document.querySelector('.yt-embed'); const f = b && b.querySelector('iframe'); const sh = b && b.querySelector('.yt-shield'); return { fs: !!b && document.fullscreenElement === b, iframe: !!f, muted: !!f && /mute=1/.test(f.src), shield: !!sh && getComputedStyle(sh).display !== 'none', thread: !!document.querySelector('.thread-card') }; }); + const cmds = async () => { const f = page.frames().find((x) => x.url().startsWith('https://www.youtube-nocookie.com/')); return f ? f.evaluate(() => window.__cmds.slice()) : null; }; + try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); + await click('create a new wallet'); await sleep(600); + await page.waitForSelector('.words .w .t'); + const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await click('skip verification'); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + await page.evaluate(([k, pk, ns]) => { + localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(k + ':feedNotes', JSON.stringify(ns)); + localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Tuber', t: Date.now() } })); + localStorage.setItem('btc-wallet-feed:' + k, 'following'); + }, [base, AUTHOR, POSTS]); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); + await page.waitForSelector('.notes-feed .yt-embed', { timeout: 20000 }); + await page.evaluate(() => document.querySelector('.notes-feed .yt-embed').scrollIntoView({ block: 'center' })); + await sleep(1500); + let s = await st(); + if (!saveData) { + check('in view, the player loads by itself, muted', s.iframe && s.muted, JSON.stringify(s)); + check('…with a layer over its picture', s.shield); + await waitFor(() => !!document.querySelector('.yt-embed iframe'), null, 3000); + await sleep(500); + // YouTube's control bar along the bottom is YouTube's + let b = await box(); + await page.mouse.click(b.x + b.w * 0.3, b.y + b.h - 20); await sleep(500); + check('a tap on YouTube\'s control bar stays YouTube\'s', !(await st()).fs && !(await st()).thread, JSON.stringify(await st())); + } else { + check('with Data Saver, the still and a play button', !s.iframe && await page.evaluate(() => !!document.querySelector('.yt-embed .yt-play')), JSON.stringify(s)); + } + const b = await box(); + await page.mouse.click(b.x + b.w * 0.3, b.y + b.h * 0.35); + check('one tap on the picture: full screen', await waitFor(() => document.fullscreenElement === document.querySelector('.yt-embed'), null, 3000), JSON.stringify(await st())); + s = await st(); + check('…the player there', s.iframe); + check('…with sound', saveData ? !s.muted : (await waitFor(() => true, null, 300)) && (await cmds())?.includes('unMute'), saveData ? JSON.stringify(s) : JSON.stringify(await cmds())); + if (!saveData) check('…playing', (await cmds())?.includes('playVideo')); + check('…not the thread', !s.thread); + check('full screen, the layer steps aside (YouTube\'s controls are all there)', !s.shield, JSON.stringify(s)); + await page.evaluate(() => document.exitFullscreen()); await sleep(500); + s = await st(); + check('out of full screen, the layer is back', s.shield && !s.fs, JSON.stringify(s)); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); + } finally { await ctx.close(); } +} +try { await run(false); await run(true); } finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ a YouTube clip: one tap, full screen, with sound' : '\n❌ failed'); +process.exit(ok ? 0 : 1); |
