Camera app scan: the big qr rotates every 3 s and one scan with the phone's camera app enrolls or validates a vote (10 s), for browsers with the camera blocked; qr stays big beside the ring during a vote, step by step help on the phone
This commit is contained in:
+143
-29
@@ -5,9 +5,15 @@ 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));
|
||||
const PENDING_KEY = `rv_pending_${pid}`;
|
||||
|
||||
// the camera app redirect leaves a one-time claim (or why there is none) in the hash. off the url bar at once
|
||||
const hash = new URLSearchParams(location.hash.slice(1));
|
||||
const claim = hash.get("c"), camExpired = hash.get("cam") === "expired";
|
||||
if (location.hash) history.replaceState(null, "", location.pathname);
|
||||
// a camera app scan covers votes for a few seconds (server PASS_HOLD_MS, minus the round trip)
|
||||
let passUntil = 0;
|
||||
let presenceFor = null;
|
||||
|
||||
let scanner = null;
|
||||
let required = 5;
|
||||
@@ -50,6 +56,22 @@ function scanMsg(text, kind = "") {
|
||||
m.className = `scan-msg ${kind || "muted"}`;
|
||||
}
|
||||
|
||||
// the camera app way: a quiet line under a working scanner, step by step without one.
|
||||
// people are already on the page, so it has to say why they leave it and what happens after
|
||||
function camAlt(el, solo, vote = false) {
|
||||
el.classList.toggle("solo", solo);
|
||||
if (!solo) {
|
||||
el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Scannez le grand QR de l'écran avec l'appareil photo."));
|
||||
return;
|
||||
}
|
||||
// the vote dialog has the heading in its own title
|
||||
el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Inscrivez-vous avec l'appareil photo"),
|
||||
h("ol", {},
|
||||
h("li", {}, "Quittez cette page et ouvrez l'appareil photo du téléphone."),
|
||||
h("li", {}, "Scannez le grand QR de l'écran."),
|
||||
h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez le lien qui s'affiche. Vous êtes inscrit·e.")));
|
||||
}
|
||||
|
||||
async function startScanner() {
|
||||
if (scanner) return;
|
||||
if (!window.isSecureContext) {
|
||||
@@ -61,6 +83,8 @@ async function startScanner() {
|
||||
try {
|
||||
await scanner.start();
|
||||
$("#start-cam").hidden = true;
|
||||
$("#dots").hidden = false;
|
||||
camAlt($("#enroll-alt"), false);
|
||||
scanMsg("");
|
||||
navigator.wakeLock?.request("screen").catch(() => {});
|
||||
} catch (e) {
|
||||
@@ -68,31 +92,30 @@ async function startScanner() {
|
||||
scanner.destroy();
|
||||
scanner = null;
|
||||
$("#cam-box").hidden = true;
|
||||
// the camera app is the way now: the ring and a big retry button would only compete with it
|
||||
$("#dots").hidden = true;
|
||||
$("#start-cam").hidden = false;
|
||||
$("#start-cam").className = "link";
|
||||
$("#start-cam").textContent = "Réessayer la caméra";
|
||||
scanMsg(camError(e), "bad");
|
||||
camAlt($("#enroll-alt"), true);
|
||||
}
|
||||
}
|
||||
|
||||
// what blocked the camera, and where to unblock it on this phone. the browser only tells the kind of failure
|
||||
// what blocked the camera. no settings walkthrough: the camera app path below works without them
|
||||
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.";
|
||||
return "Ce navigateur n'a pas accès à la caméra.";
|
||||
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é.";
|
||||
return "Caméra occupée ou bloquée par le téléphone.";
|
||||
case "NotFoundError":
|
||||
case "OverconstrainedError":
|
||||
return "Aucune caméra trouvée sur cet appareil.";
|
||||
return "Aucune caméra trouvée.";
|
||||
default:
|
||||
return "Caméra indisponible. Autorisez-la puis réessayez.";
|
||||
return "Caméra indisponible.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,12 +262,13 @@ function rankCameras(cams) {
|
||||
}
|
||||
|
||||
// token of a code shown for this poll, null for anything else
|
||||
// the classic qr is the camera app code: /V/<poll>/<code>, upper case
|
||||
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;
|
||||
const [v, id, tok] = u.pathname.split("/").filter(Boolean);
|
||||
if (v?.toLowerCase() !== "v" || id?.toLowerCase() !== pid || !tok) return null;
|
||||
return tok;
|
||||
}
|
||||
|
||||
function stopScanner() {
|
||||
@@ -258,7 +282,50 @@ function stopScanner() {
|
||||
function onScan(token) {
|
||||
if (landing || sent.has(token)) return;
|
||||
sent.add(token);
|
||||
submitToken(token);
|
||||
if (codeStyle === "qr") redeem({ token }).then(afterPass);
|
||||
else submitToken(token);
|
||||
}
|
||||
|
||||
async function redeem(body) {
|
||||
try { return await api("POST", `${apiBase}/pass`, body); }
|
||||
catch { return { status: "network" }; }
|
||||
}
|
||||
|
||||
function pendingVote() {
|
||||
let p;
|
||||
try { p = JSON.parse(lsGet(PENDING_KEY)); } catch { return null; }
|
||||
return p && Date.now() - p.at < 5 * 60e3 ? p : null;
|
||||
}
|
||||
|
||||
// what one camera app scan gave: enrolled, votes covered for a moment, or why not
|
||||
async function afterPass(r) {
|
||||
switch (r.status) {
|
||||
case "enrolled":
|
||||
passUntil = Date.now() + 8000;
|
||||
enrolled();
|
||||
break;
|
||||
case "pass": {
|
||||
passUntil = Date.now() + (r.hold_ms || 10000) - 1500;
|
||||
// the choice made before going to the camera app goes through on its own
|
||||
const p = pendingVote();
|
||||
const q = p && lastState?.questions.find((x) => x.id === p.qid && x.state === "open" && !x.voted);
|
||||
if (q) castVote(q, p.choices);
|
||||
break;
|
||||
}
|
||||
case "need_code":
|
||||
stopScanner();
|
||||
show("#v-code");
|
||||
break;
|
||||
case "closed":
|
||||
if (!lastState) block("Inscriptions closes. Inscrit·e dans un autre navigateur ? Revenez-y pour voter.");
|
||||
break;
|
||||
case "full":
|
||||
block("Nombre maximal d'inscriptions atteint.");
|
||||
break;
|
||||
case "expired":
|
||||
toast("QR expiré, scannez-le à nouveau.", "bad");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function submitToken(token) {
|
||||
@@ -384,6 +451,8 @@ function sel(qid) {
|
||||
|
||||
function renderVote(st) {
|
||||
lastState = st;
|
||||
// voted from the tab the camera app opened: nothing left to scan here
|
||||
if (presenceFor && st.questions.some((q) => q.id === presenceFor && q.voted)) $("#presence").close();
|
||||
if (st.code_style) codeStyle = st.code_style;
|
||||
const box = $("#questions");
|
||||
box.replaceChildren();
|
||||
@@ -450,17 +519,33 @@ async function confirmVote(q) {
|
||||
dlg.showModal();
|
||||
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
|
||||
if (dlg.returnValue !== "ok") return;
|
||||
castVote(q, s.blank ? [] : choices);
|
||||
}
|
||||
|
||||
async function castVote(q, choices, retried = false) {
|
||||
let presence;
|
||||
if (lastState.vote_scans > 0) {
|
||||
presence = await collectPresence(lastState.vote_scans);
|
||||
if (!presence) return;
|
||||
if (lastState.vote_scans > 0 && Date.now() > passUntil) {
|
||||
// kept for the tab the camera app opens, which sends it on its own
|
||||
lsSet(PENDING_KEY, JSON.stringify({ qid: q.id, choices, at: Date.now() }));
|
||||
presence = await collectPresence(lastState.vote_scans, q.id);
|
||||
// cancelled (or voted from the other tab): a later scan must not cast a choice left behind
|
||||
if (!presence) {
|
||||
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices, presence });
|
||||
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices, presence });
|
||||
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
|
||||
selections.delete(q.id);
|
||||
celebrate("Vote enregistré");
|
||||
navigator.vibrate?.(60);
|
||||
} catch (e) {
|
||||
// the camera app scan ran out on the server side: scan again
|
||||
if (e.code === "presence_required" && !presence && !retried) {
|
||||
passUntil = 0;
|
||||
return castVote(q, choices, true);
|
||||
}
|
||||
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");
|
||||
@@ -469,16 +554,29 @@ async function confirmVote(q) {
|
||||
|
||||
// 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) {
|
||||
function collectPresence(n, qid) {
|
||||
const dlg = $("#presence");
|
||||
const got = [];
|
||||
// the classic qr is the camera app code: one read is enough, the server then covers the vote
|
||||
if (codeStyle === "qr") n = 1;
|
||||
const paint = () => paintRing($("#p-ring"), got.length, n, 120);
|
||||
paint();
|
||||
$("#p-title").textContent = codeStyle === "ring" ? "Visez le cercle" : "Scannez le QR";
|
||||
$("#p-scan").hidden = false;
|
||||
$("#p-msg").textContent = "";
|
||||
camAlt($("#p-alt"), false);
|
||||
presenceFor = qid;
|
||||
dlg.showModal();
|
||||
const seenAt = new Map();
|
||||
const sc = makeScanner($("#p-video"), (t) => {
|
||||
const seenAt = new Map(), tried = new Set();
|
||||
const sc = makeScanner($("#p-video"), async (t) => {
|
||||
if (got.length >= n || got.includes(t)) return;
|
||||
if (codeStyle === "qr") {
|
||||
if (tried.has(t)) return;
|
||||
tried.add(t);
|
||||
const r = await redeem({ token: t });
|
||||
if (r.status === "pass" && !got.length) { got.push(t); paint(); setTimeout(() => finish([]), FILL_MS); }
|
||||
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();
|
||||
@@ -493,14 +591,20 @@ function collectPresence(n) {
|
||||
function finish(value) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
presenceFor = null;
|
||||
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.`; });
|
||||
// no camera here: the camera app opens a new tab that sends the kept choice
|
||||
sc.start().catch((e) => {
|
||||
$("#p-title").textContent = "Validez avec l'appareil photo";
|
||||
$("#p-msg").textContent = camError(e);
|
||||
$("#p-scan").hidden = true;
|
||||
camAlt($("#p-alt"), true, true);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -553,14 +657,24 @@ async function boot() {
|
||||
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";
|
||||
// the classic qr is read once (camera app code), the ring several times
|
||||
required = codeStyle === "qr" ? 1 : me.scans_required;
|
||||
if (me.need_code) { show("#v-code"); return; }
|
||||
startEnroll(me.count);
|
||||
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
|
||||
}
|
||||
|
||||
boot();
|
||||
async function start() {
|
||||
// the claim goes first: it may enroll this phone before the page asks who it is
|
||||
const r = claim ? await redeem({ claim }) : null;
|
||||
if (r?.status === "enrolled") { lsSet(DONE_KEY, "1"); celebrate("Inscription validée"); passUntil = Date.now() + 8000; }
|
||||
await boot();
|
||||
if (r && r.status !== "enrolled") afterPass(r);
|
||||
else if (camExpired) afterPass({ status: "expired" });
|
||||
}
|
||||
|
||||
camAlt($("#enroll-alt"), false);
|
||||
start();
|
||||
// a socket can look open after sleep while being dead, so refetch on wake
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible" && lastState) boot();
|
||||
|
||||
Reference in New Issue
Block a user