From 98cf8e5f6de86ab94546c580b4223a36062746f0 Mon Sep 17 00:00:00 2001 From: Showdown76py Date: Mon, 17 Aug 2026 02:15:05 +0100 Subject: [PATCH] Remove dead code, split long functions (tilt search, wipe, sync search, blob mask/ellipse, scan attempt); center split title --- rotatyvote/app.py | 44 ++++---- rotatyvote/ringcode.py | 3 +- static/css/screen.css | 1 + static/js/ringcode.js | 226 +++++++++++++++++++++++------------------ tools/cdp.py | 72 +------------ 5 files changed, 157 insertions(+), 189 deletions(-) diff --git a/rotatyvote/app.py b/rotatyvote/app.py index 7d28cc2..1609c6e 100644 --- a/rotatyvote/app.py +++ b/rotatyvote/app.py @@ -435,7 +435,7 @@ async def admin_get(request: Request): async def admin_patch(request: Request): pid = request.path_params["pid"] - p = require_admin(request, pid) + require_admin(request, pid) d = await body(request) upd = {} if "title" in d: @@ -486,7 +486,7 @@ async def admin_rotate_screen_key(request: Request): async def admin_add_question(request: Request): pid = request.path_params["pid"] - p = require_admin(request, pid) + require_admin(request, pid) d = await body(request) qid = db.add_question(pid, *parse_question(d)) if d.get("open"): @@ -605,6 +605,27 @@ def _finish_enroll(pid, att_id, code=None): return resp, None +def _attempt(request, pid): + """this device's enrollment attempt, from its cookie, or a fresh one (then the cookie must be set)""" + if len(attempts) > 50000: + prune_attempts() + att_id = request.cookies.get(attempt_cookie(pid)) + if att_id and (pid, att_id) in attempts: + return att_id, attempts[(pid, att_id)], None + att_id = new_key() + attempts[(pid, att_id)] = Attempt() + return att_id, attempts[(pid, att_id)], att_id + + +def _expire(a, p, now): + # scans must land in one short window, and a proven presence only waits so long for its paper code + if a.presence_ms: + if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000: + a.slots.clear(); a.first_ms = 0; a.presence_ms = 0 + elif a.first_ms and now - a.first_ms > p["scans_required"] * p["interval_ms"] + config.ATTEMPT_SLACK_MS: + a.slots.clear(); a.first_ms = 0 + + async def voter_scan(request: Request): pid = request.path_params["pid"] p = get_poll(pid) @@ -613,24 +634,11 @@ async def voter_scan(request: Request): return JSONResponse({"status": "enrolled"}) if not p["enrollment_open"]: return JSONResponse({"status": "closed"}) - if len(attempts) > 50000: - prune_attempts() - att_id = request.cookies.get(attempt_cookie(pid)) - fresh_cookie = None - if not att_id or (pid, att_id) not in attempts: - att_id = new_key() - fresh_cookie = att_id - attempts[(pid, att_id)] = Attempt() - a = attempts[(pid, att_id)] + att_id, a, fresh_cookie = _attempt(request, pid) now = now_ms() a.last_ms = now required = p["scans_required"] - window = required * p["interval_ms"] + config.ATTEMPT_SLACK_MS - if a.presence_ms: - if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000: - a.slots.clear(); a.first_ms = 0; a.presence_ms = 0 - elif a.first_ms and now - a.first_ms > window: - a.slots.clear(); a.first_ms = 0 + _expire(a, p, now) status = "progress" slot = resolve_token(p, str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS) @@ -675,7 +683,7 @@ async def voter_rescue(request: Request): async def voter_code(request: Request): pid = request.path_params["pid"] - p = get_poll(pid) + get_poll(pid) d = await body(request) if current_voter(request, pid): return JSONResponse({"status": "enrolled"}) diff --git a/rotatyvote/ringcode.py b/rotatyvote/ringcode.py index 1022666..9029fed 100644 --- a/rotatyvote/ringcode.py +++ b/rotatyvote/ringcode.py @@ -1,4 +1,4 @@ -"""ring code: a static qr in the middle (opens the page, anchors geometry) plus rotating rings of dashes +"""ring code: a dark disc with the logo in the middle (anchors the geometry) plus rotating rings of dashes that carry the time token. layout and bit order must match static/js/ringcode.js exactly. payload = slot mod 2^16 (2 bytes) + first 4 bytes of the token hmac, reed-solomon(12, 6) over gf(256), @@ -8,7 +8,6 @@ import hmac SYNC = "010001100101001000111111" # 24 sectors, min distance 12 to any of its rotations RING_SECTORS = (24, 28, 32, 36) # ring 0 is sync, 1..3 carry 96 data bits NSYM = 6 # rs parity bytes, fixes up to 3 bad bytes -SLOT_BITS = 16 _EXP = [0] * 512 _LOG = [0] * 256 diff --git a/static/css/screen.css b/static/css/screen.css index 74e8b74..c8084e7 100644 --- a/static/css/screen.css +++ b/static/css/screen.css @@ -44,6 +44,7 @@ body.screen { /* the question owns the screen, the ring keeps the room the step list would take */ .s-main.split #qr-steps { display: none; } .s-main.split .entry canvas { width: clamp(90px, min(10vw, 15vh), 220px); } +.s-main.split .s-steps { display: grid; justify-items: center; text-align: center; } .s-main.split .s-steps h2 { font-size: clamp(1.4rem, 2.4vw, 2.6rem); } .s-main.split .s-steps li { font-size: clamp(1rem, 1.5vw, 1.6rem); } diff --git a/static/js/ringcode.js b/static/js/ringcode.js index 22da126..62f6f1d 100644 --- a/static/js/ringcode.js +++ b/static/js/ringcode.js @@ -180,6 +180,34 @@ const EASE = { // deterministic per-dash phase so every dash breathes on its own rhythm const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1; +// the bean keeps its shape, only its inside changes: a soft gradient slides across it from a random end, +// fading the new tone in behind and the old one out ahead. conic so it follows the arc exactly +// arc: center, angular extent cap to cap, and how to stroke the dash +function wipeDash(ctx, { cx, cy, lo, hi, dash }, from, to, fade, k, j) { + const dir = phase(k + 7, j + (fade.seed || 0) * 31) < 0.5 ? 1 : -1; + const delay = phase(k + 3, j + (fade.seed || 0) * 17) * 0.15, x = Math.min(1, Math.max(0, (fade.k - delay) / 0.85)); + const e = (EASE[fade.ease] || EASE.sine)(x); + if (!ctx.createConicGradient) { + ctx.globalAlpha = from + (to - from) * e; + dash(); + return; + } + const soft = (hi - lo) * 0.6, edge = dir > 0 ? lo - soft + (hi - lo + 2 * soft) * e : hi + soft - (hi - lo + 2 * soft) * e; + const start = lo - soft - 0.2, at = (th) => Math.min(1, Math.max(0, (th - start) / (2 * Math.PI))); + const g = ctx.createConicGradient(start, cx, cy); + const [behind, ahead] = dir > 0 ? [to, from] : [from, to]; + for (let i = 0; i <= 6; i++) { + const u = i / 6, w = u * u * (3 - 2 * u); + g.addColorStop(at(edge - soft + 2 * soft * u), `rgba(28,32,54,${behind + (ahead - behind) * w})`); + } + g.addColorStop(0, `rgba(28,32,54,${behind})`); + g.addColorStop(1, `rgba(28,32,54,${ahead})`); + ctx.globalAlpha = 1; + ctx.strokeStyle = g; + dash(); + ctx.strokeStyle = INK; +} + // fade: { from: previous bits, k: 0..1, seed } while the code switches. a changed dash is wiped: // one edge crosses it from a random end, the new tone fills behind it while the old one empties ahead export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) { @@ -189,7 +217,6 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) { ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill(); logo(ctx, cx, cy, CENTER * unit); const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null; - const ease = fade ? fade.k * fade.k * (3 - 2 * fade.k) : 1; ctx.lineCap = "round"; ctx.lineWidth = THICK * unit; ctx.strokeStyle = INK; @@ -208,32 +235,7 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) { dash(); continue; } - // the bean keeps its shape, only its inside changes: a soft gradient slides across it from a random end, - // fading the new tone in behind and the old one out ahead. conic so it follows the arc exactly - const from = alphaOf(prev[k][j]), to = alphaOf(ring[j]); - const lo = a - half - cap, hi = a + half + cap; - const dir = phase(k + 7, j + (fade.seed || 0) * 31) < 0.5 ? 1 : -1; - const delay = phase(k + 3, j + (fade.seed || 0) * 17) * 0.15, x = Math.min(1, Math.max(0, (fade.k - delay) / 0.85)); - const e = (EASE[fade.ease] || EASE.sine)(x); - if (!ctx.createConicGradient) { - ctx.globalAlpha = from + (to - from) * e; - dash(); - continue; - } - const soft = (hi - lo) * 0.6, edge = dir > 0 ? lo - soft + (hi - lo + 2 * soft) * e : hi + soft - (hi - lo + 2 * soft) * e; - const start = lo - soft - 0.2, at = (th) => Math.min(1, Math.max(0, (th - start) / (2 * Math.PI))); - const g = ctx.createConicGradient(start, cx, cy); - const [behind, ahead] = dir > 0 ? [to, from] : [from, to]; - for (let i = 0; i <= 6; i++) { - const u = i / 6, w = u * u * (3 - 2 * u); - g.addColorStop(at(edge - soft + 2 * soft * u), `rgba(28,32,54,${behind + (ahead - behind) * w})`); - } - g.addColorStop(0, `rgba(28,32,54,${behind})`); - g.addColorStop(1, `rgba(28,32,54,${ahead})`); - ctx.globalAlpha = 1; - ctx.strokeStyle = g; - dash(); - ctx.strokeStyle = INK; + wipeDash(ctx, { cx, cy, lo: a - half - cap, hi: a + half + cap, dash }, alphaOf(prev[k][j]), alphaOf(ring[j]), fade, k, j); } }); ctx.globalAlpha = 1; @@ -326,10 +328,9 @@ function solve(A, B) { return B.map((b, i) => b / A[i][i]); } -// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px -function blobs(g, w, h, s, ratio, out) { - // dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6, - // and the disc always has its light surround within reach, whatever the room does around the screen +// dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6, +// and the disc always has its light surround within reach, whatever the room does around the screen +function darkMask(g, w, h, ratio) { const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = ((y / T) | 0) * tw + ((x / T) | 0), v = g[y * w + x]; @@ -347,6 +348,36 @@ function blobs(g, w, h, s, ratio, out) { const thr = m * ratio, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T); for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1; } + return dark; +} + +// ellipse from the moments of a component filled row by row (so the light logo inside doesn't count as +// holes), or null when the shape is not a filled ellipse. rows y0..y1 where stamp[y] === id hold lo..hi +function rowEllipse(lo, hi, stamp, id, y0, y1, count, s) { + let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0; + for (let y = y0; y <= y1; y++) { + if (stamp[y] !== id) continue; + const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2; + const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6; + m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx; + } + const ux = mx / m0, uy = my / m0; + const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy; + const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy)); + const l1 = tr / 2 + dt, l2 = tr / 2 - dt; + if (l2 <= 0) return null; + const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2); + const fill = m0 / (Math.PI * a * b), solidity = count / m0; + if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) return null; + const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy); + const c = Math.cos(phi), sn = Math.sin(phi); + const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER; + return { cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s }; +} + +// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px +function blobs(g, w, h, s, ratio, out) { + const dark = darkMask(g, w, h, ratio); const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1); let id = 0; for (let start = 0; start < w * h; start++) { @@ -365,26 +396,8 @@ function blobs(g, w, h, s, ratio, out) { if (y < h - 1 && dark[i + w]) { dark[i + w] = 0; stack[sp++] = i + w; } } if (count < 30 || y1 - y0 < 5) continue; - // moments of the row-filled shape, so the light logo inside doesn't count as holes - let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0; - for (let y = y0; y <= y1; y++) { - if (stamp[y] !== id) continue; - const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2; - const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6; - m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx; - } - const ux = mx / m0, uy = my / m0; - const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy; - const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy)); - const l1 = tr / 2 + dt, l2 = tr / 2 - dt; - if (l2 <= 0) continue; - const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2); - const fill = m0 / (Math.PI * a * b), solidity = count / m0; - if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) continue; - const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy); - const c = Math.cos(phi), sn = Math.sin(phi); - const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER; - out.push({ cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s }); + const e = rowEllipse(lo, hi, stamp, id, y0, y1, count, s); + if (e) out.push(e); } } @@ -812,6 +825,56 @@ function tokenOf(bits, soft, strict = true) { return { token: tokenFromPayload(fixed.slice(0, fixed.length - NSYM)), fixes: bad }; } +// looks like a code but the geometry is off: a screen seen at 30-45 deg bends the outer rings more than the +// conic fit can follow. search the vanishing line directly, scored on the sync ring and the outer ring. +// tone(u, v) reads brightness at image coordinates +function searchTilt(img, cand, tone, best, opts) { + const D = discConic(img, cand); + if (!D) return null; + const at = (map) => (x, y) => { const [u, v] = map(x, y); return tone(u, v); }; + const n0 = RING_SECTORS[0], s0 = (2 * Math.PI) / n0, nk = RING_SECTORS[3], sk = (2 * Math.PI) / nk; + const quick = (S) => { + let top = null; + for (let dt = -12; dt <= 12; dt += 2) { + const th = best.theta + (dt * Math.PI) / 180, vals = []; + for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0], sectorAngle(th, j, n0), s0)); + if (vals.some(Number.isNaN)) return null; + const sc = Math.max(corr(vals, SYNC_BITS), corrFlat(vals)); + if (!top || sc > top.sc) top = { sc, th }; + } + const outer = []; + for (let j = 0; j < nk; j++) outer.push(sector(S, RADII[3], sectorAngle(top.th, j, nk), sk)); + if (outer.some(Number.isNaN)) return null; + return top.sc + split(outer).quality; + }; + const tryLine = (lx, ly) => { + const map = mapFromLine(D.Q1, [lx, ly, 1], D.mx, D.my, D.sc); + if (!map) return null; + const S = at(map), q = quick(S); + return q == null ? null : { q, S, l: [lx, ly] }; + }; + const tries = []; + for (const m of [0.015, 0.03, 0.045, 0.06, 0.08, 0.1]) for (let i = 0; i < 16; i++) { + const t = tryLine(m * Math.cos((i / 16) * 2 * Math.PI), m * Math.sin((i / 16) * 2 * Math.PI)); + if (t) tries.push(t); + } + tries.sort((p, q) => q.q - p.q); + let out = null; + for (const t of tries.slice(0, 3)) { + // polish around the pick on a finer grid before the full read + let pick = t; + for (const dx of [-0.008, 0, 0.008]) for (const dy of [-0.008, 0, 0.008]) { + if (!dx && !dy) continue; + const c = tryLine(t.l[0] + dx, t.l[1] + dy); + if (c && c.q > pick.q) pick = c; + } + const r = readRings(pick.S, opts); + if (r && r.token) return { ...r, tilt: pick.l }; + if (r && (!out || r.score > out.score)) out = r; + } + return out; +} + // reads one candidate. returns { token, theta, score, scale, soft } or { token: null, ... } or null. // tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames) export function decodeAt(img, cand, opts = {}) { @@ -838,55 +901,16 @@ export function decodeAt(img, cand, opts = {}) { if (r && r.token) return r; if (r && (!best || r.score > best.score)) best = r; } - // looks like a code but the geometry is off: a screen seen at 30-45 deg bends the outer rings more than the - // conic fit can follow. search the vanishing line directly, scored on the sync ring and the outer ring if (opts.tilt !== false && best && best.score > 0.55 && best.theta != null) { - const D = discConic(img, cand); - if (D) { - const at = (map) => (x, y) => { const [u, v] = map(x, y); return bilinear(tone, u - x0, v - y0); }; - const n0 = RING_SECTORS[0], s0 = (2 * Math.PI) / n0, nk = RING_SECTORS[3], sk = (2 * Math.PI) / nk; - const quick = (S) => { - let top = null; - for (let dt = -12; dt <= 12; dt += 2) { - const th = best.theta + (dt * Math.PI) / 180, vals = []; - for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0], sectorAngle(th, j, n0), s0)); - if (vals.some(Number.isNaN)) return null; - const sc = Math.max(corr(vals, SYNC_BITS), corrFlat(vals)); - if (!top || sc > top.sc) top = { sc, th }; - } - const outer = []; - for (let j = 0; j < nk; j++) outer.push(sector(S, RADII[3], sectorAngle(top.th, j, nk), sk)); - if (outer.some(Number.isNaN)) return null; - return top.sc + split(outer).quality; - }; - const tries = []; - for (const m of [0.015, 0.03, 0.045, 0.06, 0.08, 0.1]) for (let i = 0; i < 16; i++) { - const a = (i / 16) * 2 * Math.PI, map = mapFromLine(D.Q1, [m * Math.cos(a), m * Math.sin(a), 1], D.mx, D.my, D.sc); - if (!map) continue; - const S = at(map), q = quick(S); - if (q != null) tries.push({ q, S, l: [m * Math.cos(a), m * Math.sin(a)] }); - } - tries.sort((p, q) => q.q - p.q); - for (const t of tries.slice(0, 3)) { - // polish around the pick on a finer grid before the full read - let pick = t; - for (const dx of [-0.008, 0, 0.008]) for (const dy of [-0.008, 0, 0.008]) { - if (!dx && !dy) continue; - const map = mapFromLine(D.Q1, [t.l[0] + dx, t.l[1] + dy, 1], D.mx, D.my, D.sc); - if (!map) continue; - const S = at(map), q = quick(S); - if (q != null && q > pick.q) pick = { q, S, l: [t.l[0] + dx, t.l[1] + dy] }; - } - const r = readRings(pick.S, { ...opts, span }); - if (r && r.token) return { ...r, tilt: pick.l }; - if (r && r.score > best.score) best = r; - } - } + const r = searchTilt(img, cand, (x, y) => bilinear(tone, x - x0, y - y0), best, { ...opts, span }); + if (r && r.token) return r; + if (r && r.score > best.score) best = r; } return best; } -function readRings(S, opts) { +// rotation and scale of the sync ring: { best } to go on, or { done } when the read stops here +function findSync(S, opts) { const minScore = opts.minScore ?? 0.8; const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0; const syncAt = (theta, scale) => { @@ -900,13 +924,13 @@ function readRings(S, opts) { for (const scale of opts.scales || [0.96, 1.0, 1.04]) { for (let t = 0; t < 72; t++) { const r = syncAt((t / 72) * 2 * Math.PI, scale); - if (!r) return null; + if (!r) return { done: null }; coarse.push(r); } } coarse.sort((p, q) => q.score - p.score); // nothing like the sync pattern at any angle: not a code, skip the fine search - if (coarse[0].score < 0.5) return { token: null, ...coarse[0], vals: undefined }; + if (coarse[0].score < 0.5) return { done: { token: null, ...coarse[0], vals: undefined } }; let best = null; for (const c of coarse.slice(0, 3)) { for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) { @@ -915,7 +939,13 @@ function readRings(S, opts) { } } // weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise - if (!best || best.score < minScore) return best ? { token: null, ...best, vals: undefined } : null; + if (!best || best.score < minScore) return { done: best ? { token: null, ...best, vals: undefined } : null }; + return { best }; +} + +function readRings(S, opts) { + const { best, done } = findSync(S, opts); + if (!best) return done; const dark = [], light = []; best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v)); const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length; diff --git a/tools/cdp.py b/tools/cdp.py index 67bff06..cf3662c 100644 --- a/tools/cdp.py +++ b/tools/cdp.py @@ -1,13 +1,10 @@ -"""tiny chrome devtools protocol client: headless chrome, pages, eval, screencast""" +"""tiny chrome devtools protocol client for the ring bench: headless chrome, pages, eval""" import asyncio -import base64 import itertools import json -import os import shutil import subprocess import tempfile -import time import urllib.request import websockets @@ -96,7 +93,6 @@ class Page: def __init__(self, browser, sid, w, h, dsf): self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf self.load = None - self.frames = None def send(self, method, params=None): return self.b.send(method, params, self.sid) @@ -104,15 +100,6 @@ class Page: def _event(self, method, params): if method == "Page.loadEventFired" and self.load and not self.load.done(): self.load.set_result(True) - elif method == "Page.screencastFrame": - if self.frames is not None: - ts = params["metadata"].get("timestamp", time.time()) - path = os.path.join(self.frame_dir, f"{len(self.frames):06d}.jpg") - with open(path, "wb") as f: - f.write(base64.b64decode(params["data"])) - self.frames.append((ts, path)) - asyncio.get_running_loop().create_task( - self.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]})) async def goto(self, url): self.load = asyncio.get_running_loop().create_future() @@ -124,60 +111,3 @@ class Page: if "exceptionDetails" in r: raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"])) return r.get("result", {}).get("value") - - async def on_new_document(self, source): - await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": source}) - - async def record(self, frame_dir): - os.makedirs(frame_dir, exist_ok=True) - self.frame_dir = frame_dir - self.frames = [] - await self.send("Page.startScreencast", {"format": "jpeg", "quality": 90, - "maxWidth": int(self.w * self.dsf), "maxHeight": int(self.h * self.dsf)}) - - async def stop(self): - if getattr(self, "shooter", None): - self.shooting = False - try: - await asyncio.wait_for(self.shooter, 3) - except Exception: - self.shooter.cancel() - else: - try: - await asyncio.wait_for(self.send("Page.stopScreencast"), 3) - except Exception: - pass - - async def record_shots(self, frame_dir, fps=24): - """screenshot polling: slower than screencast but honours deviceScaleFactor""" - os.makedirs(frame_dir, exist_ok=True) - self.frames, self.shooting = [], True - - async def loop(): - while self.shooting: - t = time.time() - r = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": 90}) - path = os.path.join(frame_dir, f"{len(self.frames):06d}.jpg") - with open(path, "wb") as f: - f.write(base64.b64decode(r["data"])) - self.frames.append((t, path)) - await asyncio.sleep(max(0, 1 / fps - (time.time() - t))) - self.shooter = asyncio.get_running_loop().create_task(loop()) - - async def png(self, path, transparent=False): - if transparent: - await self.send("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}}) - r = await self.send("Page.captureScreenshot", {"format": "png"}) - with open(path, "wb") as f: - f.write(base64.b64decode(r["data"])) - - async def mouse(self, kind, x, y, button="left", clicks=1): - await self.send("Input.dispatchMouseEvent", - {"type": kind, "x": x, "y": y, "button": button, "clickCount": clicks}) - - async def type(self, text, rng, target="document.activeElement"): - # write into the field directly: focus can drift between headless targets while screenshotting - await self.js(f"window.__tt = {target}; __tt.focus()") - for ch in text: - await self.js("__tt.value += " + json.dumps(ch) + "; __tt.dispatchEvent(new Event('input', {bubbles: true}))") - await asyncio.sleep(rng.uniform(0.05, 0.14) + (0.18 if ch == " " and rng.random() < 0.2 else 0))