Files
rotatyvote/static/js/vote.js
T

411 lines
13 KiB
JavaScript

import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
import { decodeFrame, grayOf } from "./ringcode.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 */ } }
function renderDots(n) {
const box = $("#dots");
box.replaceChildren(ring(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 });
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
// 960 px is plenty 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);
try {
if (codeStyle === "ring") {
const d = decodeFrame(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)));
if (d.token) onToken(d.token);
} else {
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)));
}
return {
async start() {
stream = await navigator.mediaDevices.getUserMedia({
audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: 1280 }, height: { ideal: 720 } },
});
video.srcObject = stream;
await video.play();
running = true;
loop();
},
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() {},
};
}
// 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 (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":
enrolled();
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]);
boot();
}
$("#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);
toast("Vote enregistré", "ok");
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 = () => $("#p-ring").replaceChildren(ring(got.length, n, 120));
paint();
$("#p-msg").textContent = "";
dlg.showModal();
const sc = makeScanner($("#p-video"), (t) => {
if (got.includes(t)) return;
got.push(t);
paint();
navigator.vibrate?.(15);
if (got.length >= n) finish(got);
});
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();
});