Files
rotatyvote/static/js/vote.js
T

569 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { $, h, api, pollId, liveSocket, resultsView, toast, paintRing, icon } from "./common.js";
import { makeRingScanner } from "./ringscan.js";
const pid = pollId();
const DONE_KEY = `rv_done_${pid}`;
const apiBase = `/api/v/${pid}`;
// token from the QR that opened this page, then drop it from the url bar so it isn't shared
const firstToken = decodeURIComponent(location.hash.slice(1));
if (location.hash) history.replaceState(null, "", location.pathname);
let scanner = null;
let required = 5;
let socket = null;
const sent = new Set();
const selections = new Map();
let queue = Promise.resolve();
let lastState = null;
let codeStyle = "qr"; // what the projector shows: rotating qr or ring code
let qrEngine = null;
let lastJson = "";
function show(id) {
for (const s of ["#v-loading", "#v-enroll", "#v-code", "#v-rescue", "#v-blocked", "#v-vote"]) $(s).hidden = s !== id;
}
function block(msg) {
stopScanner();
$("#blocked-msg").textContent = msg;
show("#v-blocked");
}
function lsGet(k) { try { return localStorage.getItem(k); } catch { return null; } }
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }
// the segment fill in app.css takes .5 s, plus a beat to see the ring complete
const FILL_MS = 650;
let landing = false;
function renderDots(n) {
const box = $("#dots");
paintRing(box, n, required, 150);
box.setAttribute("aria-label", `${n} codes lus sur ${required}`);
}
function scanMsg(text, kind = "") {
const m = $("#scan-msg");
m.textContent = text;
m.className = `scan-msg ${kind || "muted"}`;
}
async function startScanner() {
if (scanner) return;
if (!window.isSecureContext) {
scanMsg("Caméra impossible sans HTTPS.", "bad");
return;
}
$("#cam-box").hidden = false;
scanner = makeScanner($("#video"), onScan, () => scanMsg("QR d'un autre scrutin.", "bad"));
try {
await scanner.start();
$("#start-cam").hidden = true;
scanMsg("");
navigator.wakeLock?.request("screen").catch(() => {});
} catch (e) {
console.warn(e);
scanner.destroy();
scanner = null;
$("#cam-box").hidden = true;
$("#start-cam").hidden = false;
scanMsg("Autorisez la caméra puis réessayez.", "bad");
}
}
// own camera loop: decodes the ring code, or the classic qr through qr-scanner's engine.
// calls onToken(token) for every code of this poll it reads
function makeScanner(video, onToken, onOther) {
let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
const rings = makeRingScanner();
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
try {
if (codeStyle === "ring") {
// reads a crop at sensor resolution: a far code keeps all its pixels
const d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token);
steer(d, performance.now());
} else {
// 960 px is plenty for a qr and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
qrEngine ||= await window.QrScanner.createQrEngine();
const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null);
if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); }
}
} catch (e) { console.warn(e); }
}
// ~15 fps cap, saves battery on fast phones
setTimeout(loop, Math.max(0, 66 - (performance.now() - t0)));
}
const swap = h("button", { class: "cam-switch", type: "button", "aria-label": "Changer de caméra", hidden: true }, icon("swap", 20));
// sensor zoom: a far ring gets real pixels instead of an upscaled crop. it steers itself (zoomPlan) until
// the button is touched, then it's the person's call
const zoom = h("button", { class: "cam-zoom", type: "button", "aria-label": "Zoom", hidden: true }, "1×");
video.parentElement.append(swap, zoom);
let zs = null;
function setZoom(z) {
const track = stream?.getVideoTracks()[0];
if (!track || !zs) return;
zs.now = z;
zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`;
track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; });
}
function steer(d, now) {
if (!zs) return;
// people keep their seat between votes: the zoom that read the ring is where the next scan starts
if (d.token) lsSet(ZOOM_KEY, String(zs.now));
if (!zs.auto) return;
const z = zoomPlan(zs, d, now);
if (z != null) setZoom(z);
}
async function attach(s) {
stream = s;
const track = s.getVideoTracks()[0];
// not every browser knows focusMode, those ignore it
track?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
const cap = track?.getCapabilities?.().zoom;
zs = cap && cap.max >= 1.5 ? newZoomState(Math.max(1, cap.min), Math.min(cap.max, 4)) : null;
zoom.hidden = !zs;
zoom.textContent = "1×";
video.srcObject = s;
await video.play();
const saved = +lsGet(ZOOM_KEY);
if (zs && saved > zs.base) setZoom(Math.min(zs.max, saved));
}
zoom.onclick = () => {
if (!zs) return;
zs.auto = false;
const steps = [zs.base, 2, 3].filter((z) => z >= zs.base && z <= zs.max);
setZoom(steps.find((z) => z > zs.now + 0.05) ?? zs.base);
};
swap.onclick = async () => {
const cams = rankCameras(await videoInputs());
if (cams.length < 2) return;
const cur = stream?.getVideoTracks()[0]?.getSettings().deviceId;
const next = cams[(cams.findIndex((d) => d.deviceId === cur) + 1) % cams.length];
stream?.getTracks().forEach((t) => t.stop());
try { await attach(await openCamera(next.deviceId)); lsSet(CAM_KEY, next.deviceId); }
catch { await attach(await openCamera(null)); }
};
return {
async start() {
const saved = lsGet(CAM_KEY);
let s = null;
if (saved) s = await openCamera(saved).catch(() => null);
s ||= await openCamera(null);
// some browsers ignore facingMode or hand over the ultra wide: switch to the main back lens when labels say so
const track = s.getVideoTracks()[0], cams = await videoInputs();
if (!saved && cams.length > 1 && (track.getSettings().facingMode === "user" || !isMainBack(track.label))) {
const best = rankCameras(cams)[0];
if (best && best.deviceId !== track.getSettings().deviceId) {
s.getTracks().forEach((t) => t.stop());
s = await openCamera(best.deviceId).catch(() => null) || await openCamera(null);
}
}
swap.hidden = cams.length < 2;
await attach(s);
running = true;
loop();
},
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() { swap.remove(); zoom.remove(); },
};
}
// auto zoom. a code that is seen (sync ring found) but not read, small and near the middle gets zoomed toward
// ~40 % of the frame, never so far that it would leave the frame. a code filling the frame zooms back out,
// and losing it for a while goes back to the widest view
function newZoomState(base, max) {
const t = performance.now();
return { base, max, now: base, auto: true, lastRead: 0, lastSeen: t, lastMove: t };
}
function zoomPlan(zs, d, now) {
if (d.token) zs.lastRead = now;
// a zoom too many costs nothing, so a weak sync ring is enough to steer on
const w = d.where, seen = !!w && (d.score ?? 0) >= 0.4;
if (seen) zs.lastSeen = now;
if (now - zs.lastMove < 600) return null;
let z = null;
if (seen && !d.token && now - zs.lastRead > 900 && w.d < 0.24 && zs.now < zs.max) {
const off = Math.max(Math.abs(w.x - 0.5), Math.abs(w.y - 0.5));
const fit = (zs.now * 0.45) / (off + w.d / 2);
z = Math.min(zs.max, fit, zs.now * Math.min(2, 0.4 / w.d));
if (z < zs.now + 0.15) z = null;
} else if (seen && w.d > 0.8 && zs.now > zs.base) {
z = Math.max(zs.base, zs.now * 0.6);
} else if (!seen && now - zs.lastSeen > 1800 && zs.now > zs.base) {
z = zs.base;
zs.lastSeen = now;
} else if (!seen && zs.now === zs.base && now - zs.lastSeen > 800 && now - zs.lastMove > 800) {
// from the back rows the ring is too small to be found at all: look closer where the person aims, the
// middle, and fall back to wide again (branch above) when nothing shows up there either
z = Math.min(zs.max, zs.base * 2);
zs.lastSeen = now;
}
if (z != null) zs.lastMove = now;
return z;
}
const CAM_KEY = "rv_cam";
const ZOOM_KEY = `rv_zoom_${pid}`;
const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i;
function openCamera(deviceId) {
// rings from the back of a room are a few dozen pixels wide at 720p, ask for the full sensor
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
const base = { width: { ideal: w }, height: { ideal: h } };
return navigator.mediaDevices.getUserMedia({
audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } },
});
}
async function videoInputs() {
try { return (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput"); }
catch { return []; }
}
// without a label we can't tell, so trust what facingMode gave
const isMainBack = (label) => !label || (!FRONT.test(label) && !ODD.test(label));
// main back lens first, other back lenses next, front last. android lists its main back camera first
function rankCameras(cams) {
const score = (d) => (FRONT.test(d.label) ? -4 : 0) + (ODD.test(d.label) ? -2 : 0) + (BACK.test(d.label) ? 1 : 0);
return cams.map((d, i) => ({ d, i, s: score(d) })).sort((a, b) => b.s - a.s || a.i - b.i).map((x) => x.d);
}
// token of a code shown for this poll, null for anything else
function tokenOf(data) {
let u;
try { u = new URL(data); } catch { return null; }
const parts = u.pathname.split("/").filter(Boolean);
if (parts[0] !== "v" || parts[1] !== pid) return null;
return decodeURIComponent(u.hash.slice(1)) || null;
}
function stopScanner() {
if (!scanner) return;
scanner.stop();
scanner.destroy();
scanner = null;
$("#cam-box").hidden = true;
}
function onScan(token) {
if (landing || sent.has(token)) return;
sent.add(token);
submitToken(token);
}
function submitToken(token) {
// serialized so progress never goes backwards on out of order responses
queue = queue.then(async () => {
let r;
try { r = await api("POST", `${apiBase}/scan`, { token }); }
catch { scanMsg("Réseau instable…", "bad"); return; }
handleScan(r);
});
}
function handleScan(r) {
if (r.required) required = r.required;
switch (r.status) {
case "progress":
renderDots(r.count);
scanMsg(r.accepted || r.valid ? "" : "Code expiré, continuez…");
navigator.vibrate?.(15);
break;
case "need_code":
stopScanner();
show("#v-code");
$("#code").focus();
break;
case "enrolled":
// the 5th code answers "enrolled" straight away: fill the last segment and let it land first
if (landing) break;
landing = true;
renderDots(required);
setTimeout(() => { landing = false; enrolled(); }, FILL_MS);
break;
case "closed":
block("Inscriptions closes.");
break;
case "full":
block("Nombre maximal d'inscriptions atteint.");
break;
}
}
function enrolled() {
stopScanner();
lsSet(DONE_KEY, "1");
navigator.vibrate?.([40, 60, 40]);
celebrate("Inscription validée");
boot();
}
// the projector's center mark with its check, drawn in, held a moment, then gone
const MARK_NS = "http://www.w3.org/2000/svg";
function celebrate(text) {
const svg = document.createElementNS(MARK_NS, "svg");
svg.setAttribute("viewBox", "0 0 32 32");
svg.setAttribute("aria-hidden", "true");
const g = document.createElementNS(MARK_NS, "g");
g.setAttribute("transform", "rotate(-90 16 16)");
for (const [stroke, dash] of [["currentColor", "4.52 7"], ["#ffcc00", "4.52 64.6"]]) {
const c = document.createElementNS(MARK_NS, "circle");
for (const [k, v] of Object.entries({ cx: 16, cy: 16, r: 11, fill: "none", stroke, "stroke-width": 5,
"stroke-linecap": "round", "stroke-dasharray": dash, "stroke-dashoffset": -3.5 })) c.setAttribute(k, v);
g.append(c);
}
const tick = document.createElementNS(MARK_NS, "path");
for (const [k, v] of Object.entries({ d: "M12.8 16.15l2.3 2.3 4.25-4.75", fill: "none", stroke: "currentColor", "stroke-width": 2.4,
"stroke-linecap": "round", "stroke-linejoin": "round", pathLength: 1, class: "tick" })) tick.setAttribute(k, v);
svg.append(g, tick);
const el = h("div", { class: "celebrate", role: "status" }, svg, h("p", {}, text));
document.body.append(el);
setTimeout(() => el.classList.add("out"), 1300);
setTimeout(() => el.remove(), 1700);
}
$("#start-cam").addEventListener("click", startScanner);
$("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); });
$("#rescue-back").addEventListener("click", () => startEnroll(0));
$("#rescue-form").addEventListener("submit", async (e) => {
e.preventDefault();
const msg = $("#rescue-msg");
try {
const r = await api("POST", `${apiBase}/rescue`, { code: $("#rescue-code").value });
if (r.status === "enrolled") return enrolled();
msg.className = "scan-msg bad";
msg.textContent = { bad_code: "Code invalide ou déjà utilisé.", closed: "Inscriptions closes.", full: "Nombre maximal d'inscriptions atteint." }[r.status] || r.status;
} catch (err) {
msg.className = "scan-msg bad";
msg.textContent = `Erreur : ${err.message}`;
}
});
$("#code-form").addEventListener("submit", async (e) => {
e.preventDefault();
const msg = $("#code-msg");
try {
const r = await api("POST", `${apiBase}/code`, { code: $("#code").value });
if (r.status === "enrolled") return enrolled();
if (r.status === "bad_code") {
msg.className = "scan-msg bad";
msg.textContent = `Code invalide (${r.tries_left} essai(s) restant(s))`;
} else if (r.status === "rescan") {
sent.clear();
toast("Délai dépassé, rescannez.", "bad");
startEnroll(0);
} else handleScan(r);
} catch (err) {
msg.className = "scan-msg bad";
msg.textContent = `Erreur : ${err.message}`;
}
});
function startEnroll(count) {
show("#v-enroll");
renderDots(count);
startScanner();
}
function sel(qid) {
if (!selections.has(qid)) selections.set(qid, { set: new Set(), blank: false });
return selections.get(qid);
}
function renderVote(st) {
lastState = st;
if (st.code_style) codeStyle = st.code_style;
const box = $("#questions");
box.replaceChildren();
let pending = 0;
const todo = (q) => q.state === "open" && !q.voted;
for (const q of [...st.questions.filter(todo), ...st.questions.filter((q) => !todo(q))]) {
if (todo(q)) pending++;
box.append(questionCard(q));
}
$("#waiting").hidden = pending > 0;
}
function questionCard(q) {
const card = h("article", { class: `vq ${q.state === "open" && !q.voted ? "open" : ""}` });
card.append(h("div", { class: "q-text" }, q.text));
if (q.state === "closed") {
card.append(h("span", { class: "badge public" }, "Résultats"), resultsView(q));
return card;
}
if (q.voted) {
card.append(h("p", { class: "voted" }, h("span", { class: "voted-mark" }, icon("check", 16)), "Vote enregistré"));
return card;
}
const s = sel(q.id);
const multi = q.kind === "multi";
const group = h("div", { role: multi ? "group" : "radiogroup", "aria-label": q.text });
q.options.forEach((label, i) => {
group.append(h("button", {
type: "button", class: `choice ${multi ? "multi" : ""}`, role: multi ? "checkbox" : "radio",
"aria-checked": String(s.set.has(i)),
onclick: () => {
s.blank = false;
if (multi) {
if (s.set.has(i)) s.set.delete(i);
else if (s.set.size < q.max_choices) s.set.add(i);
else toast(`${q.max_choices} choix maximum`, "bad");
} else {
s.set = new Set([i]);
}
renderVote(lastState);
},
}, h("span", { class: "mark" }), label));
});
if (q.allow_blank) {
group.append(h("button", {
type: "button", class: "choice blank", role: multi ? "checkbox" : "radio", "aria-checked": String(s.blank),
onclick: () => { s.blank = !s.blank; s.set.clear(); renderVote(lastState); },
}, h("span", { class: "mark" }), "Vote blanc"));
}
card.append(group);
if (multi) card.append(h("p", { class: "hint" }, `${q.max_choices} choix max`));
const ready = s.blank || s.set.size > 0;
card.append(h("button", { class: "go block", type: "button", disabled: !ready, onclick: () => confirmVote(q) }, "Voter"));
return card;
}
async function confirmVote(q) {
const s = sel(q.id);
const choices = [...s.set].sort((a, b) => a - b);
$("#confirm-q").textContent = q.text;
$("#confirm-choices").replaceChildren(...(s.blank ? [h("li", {}, "Vote blanc")] : choices.map((i) => h("li", {}, q.options[i]))));
const dlg = $("#confirm");
dlg.returnValue = "";
dlg.showModal();
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
if (dlg.returnValue !== "ok") return;
let presence;
if (lastState.vote_scans > 0) {
presence = await collectPresence(lastState.vote_scans);
if (!presence) return;
}
try {
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices, presence });
selections.delete(q.id);
celebrate("Vote enregistré");
navigator.vibrate?.(60);
} catch (e) {
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit.",
presence_required: "Scan expiré, revotez en visant l'écran." };
toast(m[e.code] || `Erreur : ${e.message}`, "bad");
}
}
// proof of presence at vote time: read n distinct codes off the projector, resolve with them
// (or null if cancelled). the server checks freshness
function collectPresence(n) {
const dlg = $("#presence");
const got = [];
const paint = () => paintRing($("#p-ring"), got.length, n, 120);
paint();
$("#p-msg").textContent = "";
dlg.showModal();
const sc = makeScanner($("#p-video"), (t) => {
if (got.length >= n || got.includes(t)) return;
got.push(t);
paint();
navigator.vibrate?.(15);
if (got.length >= n) setTimeout(() => finish(got), FILL_MS);
});
let done, finished = false;
const result = new Promise((res) => { done = res; });
function finish(value) {
if (finished) return;
finished = true;
sc.stop();
sc.destroy();
if (dlg.open) dlg.close();
done(value);
}
dlg.addEventListener("close", () => finish(null), { once: true });
sc.start().catch(() => { $("#p-msg").textContent = "Autorisez la caméra puis réessayez."; });
return result;
}
$("#p-cancel").addEventListener("click", () => $("#presence").close());
function connect() {
if (socket) return;
socket = liveSocket(`/ws/${pid}/voter`, {
onMessage(msg) {
if (msg.type === "state") {
// identical state -> keep the dom, a rebuild under the finger eats the tap
const j = JSON.stringify(msg);
if (j === lastJson) return;
lastJson = j;
show("#v-vote");
$("#title").textContent = msg.title;
renderVote(msg);
}
else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); }
},
onStatus(s) {
const c = $("#conn");
c.hidden = s === "online";
c.className = "conn offline";
c.textContent = "Reconnexion…";
},
});
}
async function boot() {
let me;
try { me = await api("GET", `${apiBase}/me`); }
catch (e) {
show("#v-blocked");
$("#blocked-msg").textContent = e.status === 404 ? "Scrutin introuvable." : "Serveur injoignable.";
return;
}
$("#title").textContent = me.title;
document.title = me.title;
if (me.enrolled) {
lsSet(DONE_KEY, "1");
show("#v-vote");
lastJson = JSON.stringify(me);
renderVote(me);
connect();
return;
}
if (lsGet(DONE_KEY)) {
return block("Appareil déjà inscrit à ce scrutin (accès perdu). Adressez-vous à l'équipe organisatrice.");
}
if (!me.enrollment_open) return block("Inscriptions closes.");
required = me.scans_required;
codeStyle = me.code_style || "qr";
if (me.need_code) { show("#v-code"); return; }
startEnroll(me.count);
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
}
boot();
// a socket can look open after sleep while being dead, so refetch on wake
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && lastState) boot();
});