Files
rotatyvote/static/js/vote.js
T

568 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(camError(e), "bad");
}
}
// what blocked the camera, and where to unblock it on this phone. the browser only tells the kind of failure
function camError(e) {
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const android = /Android/.test(navigator.userAgent);
switch (e && e.name) {
case "NotAllowedError":
case "SecurityError":
return ios
? "Accès à la caméra refusé. Touchez « aA » dans la barre d'adresse, puis Réglages du site web, Caméra, Autoriser. Si rien ne change, ouvrez Réglages, puis Safari, puis Caméra."
: android
? "Accès à la caméra refusé. Touchez le cadenas à gauche de l'adresse, puis Autorisations, Caméra. Vérifiez aussi l'accès à la caméra dans les réglages de confidentialité du téléphone."
: "Accès à la caméra refusé. Autorisez-la dans les réglages du navigateur pour ce site, puis réessayez.";
case "NotReadableError":
case "AbortError":
return "La caméra est bloquée par le téléphone. Fermez les autres applis qui l'utilisent, ou réactivez l'accès à la caméra dans les réglages de confidentialité.";
case "NotFoundError":
case "OverconstrainedError":
return "Aucune caméra trouvée sur cet appareil.";
default:
return "Caméra indisponible. Autorisez-la puis réessayez.";
}
}
// 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");
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 ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token);
steer(d);
pace(performance.now() - ts);
} 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, by hand only: an automatic one made the preview jump and shook too much on cheap phones.
// the far ring gets its pixels from the full sensor resolution instead (openCamera, ringscan)
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; });
}
// a slow phone reads few frames and misses codes: past ~300 ms a frame, drop the stream to 720p once
let slow = 0, frames = 0, dropped = false;
function pace(ms) {
slow = frames++ ? slow * 0.8 + ms * 0.2 : ms;
if (dropped || frames < 6 || slow < 300 || video.videoWidth * video.videoHeight <= 1280 * 720) return;
dropped = true;
stream?.getVideoTracks()[0]?.applyConstraints({ width: { ideal: 1280 }, height: { ideal: 720 } }).catch(() => {});
}
function steer(d) {
// people keep their seat between votes: a zoom that read the ring is where the next scan starts
if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now));
}
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 ? { base: Math.max(1, cap.min), max: Math.min(cap.max, 3), now: Math.max(1, cap.min) } : 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;
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(); },
};
}
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. 4k was tried: a mid-range android took
// it and fell to one frame every 2 s, so 1080p, and 720p on phones too slow for that (pace)
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 seenAt = new Map();
const sc = makeScanner($("#p-video"), (t) => {
if (got.length >= n || got.includes(t)) return;
// the server takes codes spread over ~8 s + n intervals: on a slow phone the oldest ones lapse, drop them
const now = performance.now();
while (got.length && now - seenAt.get(got[0]) > 9000) got.shift();
got.push(t);
seenAt.set(t, now);
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 });
// no camera at vote time: the desk can still count this vote by hand (votes en plus)
sc.start().catch((e) => { $("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`; });
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();
});