Compare commits

...
26 Commits
Author SHA1 Message Date
showdown 339cf97df1 Export: icon button at the right of each closed question opens the export dialog on it; templates reordered liste, barres, compact, procès-verbal, markdown, csv 2026-11-19 01:24:02 +01:00
showdown 98d8199ffd Results share link: read-only /r page with a revocable key, the admin ticks which closed questions it shows (sharing locks reopen like publish), refreshes every 15 s 2026-11-19 01:11:05 +01:00
showdown 41b4ac1a78 Results export as plain text: procès-verbal, compact, liste, barres, markdown and csv templates with a preview, copy and download, from the share tab or a closed question; tally maths shared with the results bars 2026-11-19 01:01:54 +01:00
showdown 3ebbb67817 Vote page: 1 s Vérification spinner while a camera app scan is checked; no comma in the via-qr note 2026-11-18 01:30:38 +01:00
showdown 28b255e41b Camera app scan: the first scan only opens the page, joining takes the ring or a second scan read within 4 s of the qr leaving the screen (votes keep 12 s); organizers can turn it off; open vote options and turnout bar stay above the big qr; native scan noted under the check 2026-11-18 01:12:35 +01:00
showdown a30618e74c 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 2026-11-18 00:54:12 +01:00
showdown d945c801f7 Duplicated screen: projection folds beside the open drawer, entry qr against the ring; entry qr at error level q; split ring column can shrink 2026-11-17 20:48:44 +01:00
showdown e1d8283f66 Links page: drop the admin pane duplicated into the duplicated-screen section 2026-11-17 20:44:03 +01:00
showdown 450d923e78 Duplicated screen mode: /present shows the projector view with the admin in a drawer (Gérer); both modes offered on the links page and the share tab 2026-11-17 20:41:02 +01:00
showdown cc1c46da6b Giant entry qr by default for new polls and trials; it slides and grows between the corner and the big spot 2026-11-17 17:36:35 +01:00
showdown 74a294a2d1 Vote page: camera error says what blocked it (denied, busy or blocked by the phone, none) and where to unblock it on iPhone or Android 2026-11-17 17:15:12 +01:00
showdown 85ff0d6507 Hand-added votes: pad per-answer counts to the option count; test covers it 2026-11-17 14:46:46 +01:00
showdown c924107f1d Hand-added votes per question (paper, show of hands): counted in the turnout and shown hatched orange at the end of each result bar, kept apart from phone ballots 2026-11-17 14:42:54 +01:00
showdown ad6c3c6f57 Big entry qr shows the closed question and its ballot count above it 2026-11-17 14:20:54 +01:00
showdown cbc8fe9e98 Big entry qr comes back while a closed vote waits for its results; progress ring fill uses real dash lengths (pathLength broke on some android webviews) 2026-11-17 14:17:37 +01:00
showdown 0697c27a01 Vote presence: codes may span the enrollment slack as long as one is fresh (slow phones hit 'scan expiré' with 5 scans); phone drops codes too old to count 2026-11-17 14:14:56 +01:00
showdown d761d8b510 Big entry qr beside the ring as an admin option (corner again once a question is up); admin lists questions newest first, open vote on top 2026-11-17 14:12:26 +01:00
showdown 70d09b1008 Scanner: gpu canvases (cpu ones copied whole frames in software), back to 1080p with a 720p fallback on slow phones; lab frame save works on android 2026-11-17 14:06:03 +01:00
showdown 7765f22f61 Ring lab phone page: stream size and fps, decode time, save a raw video frame; bench FPS option 2026-11-17 13:56:42 +01:00
showdown 3c1f897f7a Vote page: no visible auto zoom (preview jumped, 4x shook on cheap phones); up to 4k stream and a centre search at twice the detail instead 2026-11-17 13:52:22 +01:00
showdown 4e63c73904 Vote page: remember the zoom that read the ring for the next scans, quicker zoom search 2026-11-17 13:43:30 +01:00
showdown ef4232d04e Vote page: auto zoom looks closer at the middle when no ring shows up at all (back rows) 2026-11-17 13:40:28 +01:00
showdown 597c5e5cc2 Vote page: camera zooms itself onto a small ring it sees but can't read, until the zoom button is touched 2026-11-17 13:33:18 +01:00
showdown 7266fe1b47 Projector: bigger entry qr tucked into the bottom right corner, a bit smaller while a question is up 2026-11-17 13:13:30 +01:00
showdown 553af09df4 Projector: entry qr docks bottom right outside the layout so the ring keeps its size; projected code choice on the create page 2026-11-17 12:18:49 +01:00
showdown 3efb80b802 Vote screen: ring keeps the wider column and title shares a line with the entry qr; camera zoom button where the phone supports it 2026-11-17 12:08:25 +01:00
27 changed files with 1502 additions and 230 deletions
+1 -1
View File
@@ -65,7 +65,7 @@ location / {
2. Ouvrir les inscriptions. Le projecteur affiche le code dyanmique et le nombre d'inscriptions.
3. Fermer les inscriptions quand tout le monde est inscrit.
4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent en temps réel.
5. Clore, publier les résultats à l'écran. Vous pouvez à la fin, exporter les résultats en JSON.
5. Clore, publier les résultats à l'écran. Les votes comptés à la main (bulletins papier, main levée) s'ajoutent avec « Votes en plus » : ils restent séparés des votes par téléphone et s'affichent en orange hachuré. Vous pouvez à la fin, exporter les résultats en JSON.
Avant votre vote, `/essai` lance un scrutin jetable sur l'écran à tester. On vise l'écran avec son téléphone depuis le fond de la salle. Dès la première inscription, une question d'essai s'ouvre pour essayer aussi le vote et ses 3 secondes de confirmation. Personne ne reçoit le lien d'administration, et l'essai est effacé au bout de 2 h, même sans mot de passe de création.
+227 -45
View File
@@ -1,5 +1,6 @@
import asyncio
import contextlib
import hmac
import json
import logging
from dataclasses import dataclass, field
@@ -18,7 +19,7 @@ from starlette.websockets import WebSocket, WebSocketDisconnect
from . import config, ringcode
from .db import DB, open_db
from .tokens import check_key, current_slot, make_token, new_key, now_ms, sha, verify_token
from .tokens import check_key, current_slot, make_pass, new_key, now_ms, sha, verify_pass
log = logging.getLogger("rotatyvote")
STATIC = Path(__file__).resolve().parent.parent / "static"
@@ -50,11 +51,52 @@ def clear_attempts(pid):
del attempts[k]
# camera app scans, in memory like attempts: (pid, voter id) -> pass end, claim nonce -> (pid, minted at)
passes: dict[tuple[str, str], int] = {}
claims: dict[str, tuple[str, int, int]] = {} # nonce -> (pid, minted at, ms the code was off screen)
def grant_pass(pid, vid):
now = now_ms()
if len(passes) > 20000:
for k in [k for k, t in passes.items() if t < now]:
del passes[k]
passes[(pid, vid)] = now + config.PASS_HOLD_MS
def has_pass(pid, vid):
return passes.get((pid, vid), 0) >= now_ms()
def mint_claim(pid, late):
now = now_ms()
if len(claims) > 20000:
for k in [k for k, (_, t, _) in claims.items() if now - t > config.PASS_CLAIM_TTL_MS]:
del claims[k]
nonce = new_key()
claims[nonce] = (pid, now, late)
return nonce
def pass_on(p):
# the classic qr is the camera app code itself, it can't be turned off there
return bool(p["camera_pass"]) or p["code_style"] == "qr"
def pass_late(p, tok):
"""ms since the camera app code left the screen (<= 0 still shown), None if forged or past PASS_GRACE_MS"""
slot = verify_pass(p["secret"], p["id"], tok[:40], config.PASS_ROTATE_MS, config.PASS_GRACE_MS)
return None if slot is None else now_ms() - (slot + 1) * config.PASS_ROTATE_MS
def q_public(q, with_results: bool):
d = {
"id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]),
"max_choices": q["max_choices"], "allow_blank": bool(q["allow_blank"]), "state": q["state"],
"results_public": bool(q["results_public"]), "shown": bool(q["shown"]), "participants": db.participants(q["id"]),
"results_public": bool(q["results_public"]), "shown": bool(q["shown"]), "shared": bool(q["shared"]),
"participants": db.participants(q["id"]),
# how many were added by hand, never how they split while the vote is open
"extra_ballots": db.extra(q)["ballots"],
}
# nobody, admin included, sees tallies while a question is open
if with_results and q["state"] == "closed":
@@ -71,11 +113,12 @@ def admin_state(pid):
"scans_required": p["scans_required"], "enrollment_open": bool(p["enrollment_open"]),
"max_voters": p["max_voters"], "expected": p["expected"],
"require_code": bool(p["require_code"]), "focus_qid": p["focus_qid"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"],
"vote_scans": p["vote_scans"], "code_style": p["code_style"], "entry_big": bool(p["entry_big"]),
"camera_pass": bool(p["camera_pass"]), "share_key": p["share_key"],
},
"voters": db.voter_count(pid),
"codes": codes_summary(pid),
"questions": [q_public(q, True) for q in db.questions(pid)],
"questions": [{**q_public(q, True), "extra": db.extra(q)} for q in db.questions(pid)],
"screens": len(hub.screens.get(pid, ())),
"public_url": config.PUBLIC_URL,
}
@@ -117,6 +160,7 @@ def screen_state(pid):
"voters": db.voter_count(pid), "expected": p["expected"], "max_voters": p["max_voters"],
"scans_required": p["scans_required"], "interval_ms": p["interval_ms"], "focus": focus,
"presence": presence_check(p), "vote_scans": p["vote_scans"], "code_style": p["code_style"],
"entry_big": bool(p["entry_big"]), "camera_pass": pass_on(p),
}
@@ -131,7 +175,7 @@ def voter_state(pid, voter):
qs.append(d)
scans = 0 if voter["via_code"] else p["vote_scans"]
return {"type": "state", "title": p["title"], "enrolled": True, "questions": qs, "vote_scans": scans,
"code_style": p["code_style"]}
"code_style": p["code_style"], "camera_pass": pass_on(p)}
def qr_modules(url: str, error="m"):
@@ -139,22 +183,32 @@ def qr_modules(url: str, error="m"):
return ["".join("1" if b else "0" for b in row) for row in qr.matrix]
def entry_qr(base: str, pid: str):
"""static qr shown in a corner of the ring-code projector: opens the voting page from the camera app.
upper case keeps it in qr alphanumeric mode, a smaller symbol (/V/ redirects to /v/)"""
url = f"{base}/V/{pid}".upper()
return {"type": "entry", "modules": qr_modules(url, error="l"), "url": f"{base}/v/{pid}"}
def pass_slot():
return now_ms() // config.PASS_ROTATE_MS
def entry_qr(base: str, p, slot: int):
"""qr for the phone's camera app: opens the voting page and proves presence (/V/pid/code redirects).
upper case keeps it in qr alphanumeric mode, a smaller symbol"""
pid, rot = p["id"], config.PASS_ROTATE_MS
if not pass_on(p):
# camera app scans turned off: a plain link to the page, it never changes
return {"type": "entry", "modules": qr_modules(f"{base}/V/{pid}".upper(), error="q"), "url": f"{base}/v/{pid}"}
url = f"{base}/V/{pid}/{make_pass(p['secret'], pid, slot)}".upper()
# level q survives a glare patch or a smudge on a quarter of the symbol. 33 modules w/ the code
return {"type": "entry", "modules": qr_modules(url, error="q"), "url": f"{base}/v/{pid}",
"token": make_pass(p["secret"], pid, slot), "slot": slot, "interval_ms": rot, "valid_until": (slot + 1) * rot}
def resolve_token(p, tok: str, grace_ms: int):
"""full slot for a fresh, authentic token in either format (qr 'slot.mac' or ring 'r<s16>.<mac>'), else None"""
if tok.startswith("r"):
iv, now = p["interval_ms"], now_ms()
slot = ringcode.resolve(p["secret"], p["id"], iv, tok, current_slot(iv, now), (iv + grace_ms) // iv + 1)
if slot is None or not 0 <= now - slot * iv <= iv + grace_ms:
return None
return slot
return verify_token(p["secret"], p["id"], p["interval_ms"], tok, grace_ms)
"""full slot for a fresh, authentic ring token 'r<s16>.<mac>', else None"""
if not tok.startswith("r"):
return None
iv, now = p["interval_ms"], now_ms()
slot = ringcode.resolve(p["secret"], p["id"], iv, tok, current_slot(iv, now), (iv + grace_ms) // iv + 1)
if slot is None or not 0 <= now - slot * iv <= iv + grace_ms:
return None
return slot
class Hub:
@@ -215,6 +269,13 @@ class Hub:
return
await self.send_all(conns, voter_state(pid, v))
async def send_entry(self, p, screens, slot, kind="entry"):
by_origin: dict[str, list[WebSocket]] = {}
for ws, origin in list(screens.items()):
by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
for base, conns in by_origin.items():
await self.send_all(conns, {**entry_qr(base, p, slot), "type": kind})
def ensure_ticker(self, pid):
t = self.tickers.get(pid)
if t and not t.done():
@@ -224,31 +285,31 @@ class Hub:
self.tickers[pid] = asyncio.get_running_loop().create_task(self._tick(pid))
async def _tick(self, pid):
last_pass = -1
try:
while True:
p = db.poll(pid)
screens = self.screens.get(pid)
if not p or not needs_qr(p) or not screens:
return
ps = pass_slot()
if p["code_style"] == "qr":
# the classic qr is the camera app code itself, in the middle of the screen
if ps != last_pass:
last_pass = ps
await self.send_entry(p, screens, ps, "qr")
await asyncio.sleep(max(0.01, ((ps + 1) * config.PASS_ROTATE_MS - now_ms()) / 1000))
continue
if ps != last_pass and pass_on(p):
last_pass = ps
await self.send_entry(p, screens, ps)
iv = p["interval_ms"]
slot = current_slot(iv)
if p["code_style"] == "ring":
# the screen draws the rings itself, it only needs the bits for this slot
await self.send_all(screens, {
"type": "ring", "bits": ringcode.render_bits(p["secret"], pid, iv, slot),
"token": ringcode.token(p["secret"], pid, iv, slot), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv})
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
continue
token = make_token(p["secret"], pid, iv, slot)
by_origin: dict[str, list[WebSocket]] = {}
for ws, origin in list(screens.items()):
by_origin.setdefault(config.PUBLIC_URL or origin, []).append(ws)
for base, conns in by_origin.items():
url = f"{base}/v/{pid}#{token}"
msg = {"type": "qr", "url": url, "token": token, "modules": qr_modules(url), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv}
await self.send_all(conns, msg)
# the screen draws the rings itself, it only needs the bits for this slot
await self.send_all(screens, {
"type": "ring", "bits": ringcode.render_bits(p["secret"], pid, iv, slot),
"token": ringcode.token(p["secret"], pid, iv, slot), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv})
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
except asyncio.CancelledError:
pass
@@ -407,6 +468,9 @@ async def create_poll(request: Request):
questions = [parse_question(q) for q in (d.get("questions") or [])]
pid, admin_key, screen_key = db.create_poll(title, interval, scans, bool(d.get("require_code")),
expected, max_voters, vote_scans, code_style)
# the giant entry qr beside the ring is the default: people open the page from the back rows
db.update_poll(pid, entry_big=int(d.get("entry_big", True) is not False),
camera_pass=int(d.get("camera_pass", True) is not False))
for q in questions:
db.add_question(pid, *q)
codes = int(d.get("codes") or 0)
@@ -423,7 +487,7 @@ async def create_trial(request: Request):
pid, _, screen_key = db.create_poll("Essai", 800, 5, False, None, 200, config.DEFAULT_VOTE_SCANS, "ring",
trial=True)
db.add_question(pid, "Le vote d'essai fonctionne ?", "single", ["Oui", "Non"], 1, False)
db.update_poll(pid, enrollment_open=1)
db.update_poll(pid, enrollment_open=1, entry_big=1)
return JSONResponse({"id": pid, "screen_key": screen_key})
@@ -459,6 +523,10 @@ async def admin_patch(request: Request):
if d["code_style"] not in ("ring", "qr"):
return err("bad_code_style")
upd["code_style"] = d["code_style"]
if "entry_big" in d:
upd["entry_big"] = int(bool(d["entry_big"]))
if "camera_pass" in d:
upd["camera_pass"] = int(bool(d["camera_pass"]))
if "vote_scans" in d:
upd["vote_scans"] = clamp_int(d["vote_scans"], 0, config.MAX_VOTE_SCANS, "vote_scans")
if "focus_qid" in d:
@@ -470,6 +538,9 @@ async def admin_patch(request: Request):
if any(k in upd for k in ("interval_ms", "scans_required", "require_code")) or upd.get("enrollment_open") == 0:
# rules changed mid-way: half-done attempts start over
clear_attempts(pid)
if ("camera_pass" in upd or "code_style" in upd) and hub.screens.get(pid):
# switched off: the rotating qr on screen must turn back into the plain link now, not at the next tick
await hub.send_entry(db.poll(pid), hub.screens[pid], pass_slot())
hub.refresh(pid, voters=True)
return JSONResponse({"ok": True})
@@ -484,6 +555,27 @@ async def admin_rotate_screen_key(request: Request):
return JSONResponse({"screen_key": key})
async def admin_share_key(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
# POST makes a new link (the old one dies), DELETE turns the link off
key = new_key() if request.method == "POST" else None
db.update_poll(pid, share_key=key)
hub.refresh(pid)
return JSONResponse({"share_key": key})
async def shared_results(request: Request):
pid = request.path_params["pid"]
p = get_poll(pid)
auth = request.headers.get("authorization", "")
key = auth[7:] if auth.lower().startswith("bearer ") else ""
if not p["share_key"] or not hmac.compare_digest(key.encode(), p["share_key"].encode()):
return err("bad_share_key", 403)
qs = [q_public(q, True) for q in db.questions(pid) if q["state"] == "closed" and q["shared"]]
return JSONResponse({"title": p["title"], "questions": qs})
async def admin_add_question(request: Request):
pid = request.path_params["pid"]
require_admin(request, pid)
@@ -530,6 +622,31 @@ async def admin_question_action(request: Request):
db.set_question(qid, shown=1)
if action == "publish":
db.update_poll(pid, focus_qid=qid)
elif action in ("share", "unshare"):
if st != "closed":
return err("not_closed")
db.set_question(qid, shared=int(action == "share"))
# people outside the room have seen the tally, same lock as publish
if action == "share":
db.set_question(qid, shown=1)
elif action == "extra":
if st == "draft":
return err("not_open")
d = await body(request)
n = len(json.loads(q["options"]))
counts = d.get("counts")
if not isinstance(counts, list) or len(counts) != n:
return err("bad_extra")
counts = [clamp_int(c, 0, 100000, "counts") for c in counts]
blank = clamp_int(d.get("blank", 0), 0, 100000, "blank") if q["allow_blank"] else 0
# single choice: one ballot per answer. multi: the count of ballots is given (at least the biggest answer)
if q["kind"] == "multi":
ballots = clamp_int(d.get("ballots", max(counts, default=0) + blank), 0, 100000, "ballots")
if ballots < max(counts, default=0) + blank or ballots > sum(counts) + blank:
return err("bad_extra")
else:
ballots = sum(counts) + blank
db.set_question(qid, extra=json.dumps({"counts": counts, "blank": blank, "ballots": ballots}))
elif action == "focus":
db.update_poll(pid, focus_qid=qid)
elif action == "delete":
@@ -581,16 +698,18 @@ async def voter_me(request: Request):
"type": "state", "title": p["title"], "enrolled": False,
"enrollment_open": bool(p["enrollment_open"]), "scans_required": p["scans_required"],
"require_code": bool(p["require_code"]), "need_code": presence and bool(p["require_code"]),
"code_style": p["code_style"],
"code_style": p["code_style"], "camera_pass": pass_on(p),
"count": len(a.slots) if a else 0,
})
def _finish_enroll(pid, att_id, code=None):
def _finish_enroll(pid, att_id, code=None, with_pass=False):
cred, e = db.enroll(pid, code)
if e:
return None, e
attempts.pop((pid, att_id), None)
if with_pass:
grant_pass(pid, db.voter_by_cred(pid, cred)["id"])
resp = JSONResponse({"status": "enrolled"})
set_cookie(resp, voter_cookie(pid), cred, 7 * 24 * 3600)
resp.delete_cookie(attempt_cookie(pid), path="/")
@@ -665,6 +784,57 @@ async def voter_scan(request: Request):
return resp
async def camera_pass(request: Request):
"""the entry qr read by the camera app lands here. strict cookies may not come along on a navigation
from another app, so check the code now and hand the page a one-time claim it redeems with its cookies"""
pid = request.path_params["pid"].lower()
p = db.poll(pid)
if p and not pass_on(p):
return RedirectResponse(f"/v/{pid}", status_code=303)
late = pass_late(p, request.path_params["tok"]) if p else None
# 303 + the no-store every response gets: the camera app never reuses an old redirect
return RedirectResponse(f"/v/{pid}#" + (f"c={mint_claim(pid, late)}" if late is not None else "cam=expired"),
status_code=303)
async def voter_pass(request: Request):
"""one camera app scan = presence: enrolls this phone, or covers its votes for PASS_HOLD_MS.
takes the claim from camera_pass, or the code itself when the page's own camera read the qr"""
pid = request.path_params["pid"]
p = get_poll(pid)
d = await body(request)
if not pass_on(p):
return JSONResponse({"status": "off"})
now = now_ms()
if d.get("claim"):
c = claims.pop(str(d["claim"])[:64], None)
late = c[2] if c and c[0] == pid and now - c[1] <= config.PASS_CLAIM_TTL_MS else None
else:
late = pass_late(p, str(d.get("token", "")))
if late is None:
return JSONResponse({"status": "expired"})
v = current_voter(request, pid)
if v:
grant_pass(pid, v["id"])
return JSONResponse({"status": "pass", "hold_ms": config.PASS_HOLD_MS})
if not p["enrollment_open"]:
return JSONResponse({"status": "closed"})
# joining is where a forwarded link hurts most: the code must be read almost live
if late > config.PASS_ENROLL_GRACE_MS:
return JSONResponse({"status": "late"})
att_id, a, fresh_cookie = _attempt(request, pid)
a.last_ms = a.presence_ms = now
if p["require_code"]:
resp = JSONResponse({"status": "need_code"})
else:
resp, e = _finish_enroll(pid, att_id, with_pass=True)
if not resp:
return JSONResponse({"status": e})
if fresh_cookie and p["require_code"]:
set_cookie(resp, attempt_cookie(pid), fresh_cookie, 900)
return resp
async def voter_rescue(request: Request):
"""enrollment with a one-time rescue code, for phones whose camera can't scan"""
pid = request.path_params["pid"]
@@ -726,17 +896,21 @@ async def voter_vote(request: Request):
if len(choices) > q["max_choices"]:
return err("too_many_choices")
p = db.poll(pid)
need = 0 if v["via_code"] else p["vote_scans"]
need = 0 if v["via_code"] or has_pass(pid, v["id"]) else p["vote_scans"]
if need:
# proof of presence at vote time: fresh distinct codes read off the projector.
# checked then dropped, nothing about them is stored next to the ballot
tokens = d.get("presence")
if not isinstance(tokens, list):
return err("presence_required")
window = config.TOKEN_GRACE_MS + need * p["interval_ms"]
slots = {resolve_token(p, str(t)[:64], window) for t in tokens[:20]}
# a slow phone can take well over need * interval to see enough distinct codes, so the codes may span
# the same slack as an enrollment, as long as one of them is fresh: the phone sees the screen right now
tokens = [str(t)[:64] for t in tokens[:20]]
window = config.ATTEMPT_SLACK_MS + need * p["interval_ms"]
slots = {resolve_token(p, t, window) for t in tokens}
slots.discard(None)
if len(slots) < need:
fresh = any(resolve_token(p, t, config.TOKEN_GRACE_MS) is not None for t in tokens)
if len(slots) < need or not fresh:
return err("presence_required")
e = db.cast(pid, qid, v["id"], choices)
if e:
@@ -775,7 +949,7 @@ async def ws_screen(ws: WebSocket):
scheme = "https" if ws.url.scheme == "wss" or config.BEHIND_PROXY else "http"
origin = f"{scheme}://{public_host(ws)}"
hub.screens.setdefault(pid, {})[ws] = origin
await hub.send(ws, entry_qr(config.PUBLIC_URL or origin, pid))
await hub.send(ws, entry_qr(config.PUBLIC_URL or origin, p, pass_slot()))
await hub.send(ws, screen_state(pid))
hub.ensure_ticker(pid)
hub.refresh(pid)
@@ -827,7 +1001,8 @@ async def ws_voter(ws: WebSocket):
CSP = ("default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self'; "
"img-src 'self' data: blob:; media-src 'self' blob: mediastream:; connect-src 'self' ws: wss:; "
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'")
# same origin only: the duplicated-screen page shows the admin page in a side panel
"frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'")
class SecurityHeaders:
@@ -846,7 +1021,7 @@ class SecurityHeaders:
(b"content-security-policy", CSP.encode()),
(b"referrer-policy", b"no-referrer"),
(b"x-content-type-options", b"nosniff"),
(b"x-frame-options", b"DENY"),
(b"x-frame-options", b"SAMEORIGIN"),
(b"permissions-policy", b"camera=(self), microphone=(), geolocation=()"),
]
if not path.startswith("/static/vendor/"):
@@ -882,8 +1057,12 @@ routes = [
Route("/", page("index.html")),
Route("/admin/{pid}", page("admin.html")),
Route("/screen/{pid}", page("screen.html")),
# duplicated screen: the projector view with the admin in a drawer, opened with the admin key
Route("/present/{pid}", page("screen.html")),
Route("/essai", page("essai.html")),
Route("/v/{pid}", page("vote.html")),
Route("/r/{pid}", page("results.html")),
Route("/V/{pid}/{tok}", camera_pass),
Route("/V/{pid}", lambda r: RedirectResponse(f"/v/{r.path_params['pid'].lower()}", status_code=301)),
Route("/api/config", public_config, methods=["GET"]),
Route("/api/polls", create_poll, methods=["POST"]),
@@ -891,15 +1070,18 @@ routes = [
Route("/api/polls/{pid}", admin_get, methods=["GET"]),
Route("/api/polls/{pid}", admin_patch, methods=["PATCH"]),
Route("/api/polls/{pid}/screen-key", admin_rotate_screen_key, methods=["POST"]),
Route("/api/polls/{pid}/share-key", admin_share_key, methods=["POST", "DELETE"]),
Route("/api/polls/{pid}/questions", admin_add_question, methods=["POST"]),
Route("/api/polls/{pid}/questions/{qid:int}/{action}", admin_question_action, methods=["POST"]),
Route("/api/polls/{pid}/codes", admin_codes, methods=["GET", "POST"]),
Route("/api/polls/{pid}/export", admin_export, methods=["GET"]),
Route("/api/r/{pid}", shared_results, methods=["GET"]),
Route("/api/v/{pid}/me", voter_me, methods=["GET"]),
Route("/api/v/{pid}/scan", voter_scan, methods=["POST"]),
Route("/api/v/{pid}/code", voter_code, methods=["POST"]),
Route("/api/v/{pid}/vote", voter_vote, methods=["POST"]),
Route("/api/v/{pid}/rescue", voter_rescue, methods=["POST"]),
Route("/api/v/{pid}/pass", voter_pass, methods=["POST"]),
WebSocketRoute("/ws/{pid}/screen", ws_screen),
WebSocketRoute("/ws/{pid}/admin", ws_admin),
WebSocketRoute("/ws/{pid}/voter", ws_voter),
+10
View File
@@ -25,6 +25,16 @@ CODE_ENTRY_TTL_S = 180
# keepalive for websockets, proxies drop idle ones (cloudflare ~100s)
HEARTBEAT_S = float(os.environ.get("HEARTBEAT_S", "25"))
# entry qr read by the phone's own camera app: one scan proves presence (browsers with the camera blocked).
# a new code every 3 s. once off the screen it still validates a vote for 12 s, an enrollment for 4 s only,
# and a scan covers votes for 10 s
PASS_ROTATE_MS = 3000
PASS_GRACE_MS = 12000
PASS_ENROLL_GRACE_MS = 4000
PASS_HOLD_MS = int(os.environ.get("PASS_HOLD_MS", "10000"))
# the redirect hands the page a one-time claim: slow page loads on a crowded network don't eat the window
PASS_CLAIM_TTL_MS = 20000
# codes needed to confirm each vote, 0 turns the check off
DEFAULT_VOTE_SCANS = 3
MAX_VOTE_SCANS = 5
+18 -3
View File
@@ -89,6 +89,12 @@ class DB:
("polls", "code_style", "TEXT NOT NULL DEFAULT 'qr'"),
("polls", "trial", "INTEGER NOT NULL DEFAULT 0"),
("questions", "shown", "INTEGER NOT NULL DEFAULT 0"),
("polls", "entry_big", "INTEGER NOT NULL DEFAULT 0"),
("questions", "extra", "TEXT"),
("polls", "camera_pass", "INTEGER NOT NULL DEFAULT 1"),
# read-only results link. kept in clear so the admin can copy it again, it only shows tallies
("polls", "share_key", "TEXT"),
("questions", "shared", "INTEGER NOT NULL DEFAULT 0"),
):
cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")}
if col not in cols:
@@ -145,7 +151,8 @@ class DB:
def update_poll(self, pid, **fields):
allowed = {"title", "interval_ms", "scans_required", "enrollment_open", "max_voters",
"expected", "require_code", "focus_qid", "vote_scans", "code_style"}
"expected", "require_code", "focus_qid", "vote_scans", "code_style", "entry_big", "camera_pass",
"share_key"}
fields = {k: v for k, v in fields.items() if k in allowed}
if not fields:
return
@@ -223,7 +230,7 @@ class DB:
return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid)
def set_question(self, qid, **fields):
allowed = {"state", "results_public", "shown"}
allowed = {"state", "results_public", "shown", "extra", "shared"}
fields = {k: v for k, v in fields.items() if k in allowed}
sets = ",".join(f"{k}=?" for k in fields)
self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid))
@@ -267,7 +274,15 @@ class DB:
for i in ch:
if 0 <= i < len(counts):
counts[i] += 1
return {"counts": counts, "blank": blank, "ballots": total}
return {"counts": counts, "blank": blank, "ballots": total, "extra": self.extra(q)}
def extra(self, q):
"""votes added by hand (paper, show of hands), kept apart from the phone ballots"""
n = len(json.loads(q["options"]))
e = json.loads(q["extra"]) if q["extra"] else {}
counts = (list(e.get("counts") or []) + [0] * n)[:n]
blank = e.get("blank", 0)
return {"counts": counts, "blank": blank, "ballots": e.get("ballots", sum(counts) + blank)}
def ballots(self, qid):
# pk is random so this order is meaningless, which is the point
+16 -15
View File
@@ -29,30 +29,31 @@ def check_key(given: str | None, stored_hash: str) -> bool:
return hmac.compare_digest(sha(given), stored_hash)
def _mac(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
msg = f"{poll_id}:{interval_ms}:{slot}".encode()
# 72 bits is plenty for a code that lives ~3s, keeps the QR small
return base64.urlsafe_b64encode(hmac.new(secret, msg, hashlib.sha256).digest()[:9]).decode()
def current_slot(interval_ms: int, at_ms: int | None = None) -> int:
return (at_ms if at_ms is not None else now_ms()) // interval_ms
def make_token(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
return f"{slot}.{_mac(secret, poll_id, interval_ms, slot)}"
def _pass_mac(secret: bytes, poll_id: str, slot: int) -> str:
# 50 bits in qr alphanumeric charset (base32 upper), the code lives ~15 s and is checked online only
d = hmac.new(secret, f"pass:{poll_id}:{slot}".encode(), hashlib.sha256).digest()
return base64.b32encode(d[:7]).decode()[:10]
def verify_token(secret: bytes, poll_id: str, interval_ms: int, token: str, grace_ms: int) -> int | None:
"""returns the slot if the token is authentic and fresh, else None"""
def make_pass(secret: bytes, poll_id: str, slot: int) -> str:
return f"{slot}-{_pass_mac(secret, poll_id, slot)}"
def verify_pass(secret: bytes, poll_id: str, token: str, rotate_ms: int, grace_ms: int) -> int | None:
"""camera app code from the entry qr: slot if authentic and shown less than rotate + grace ago"""
try:
slot_s, mac = token.split(".", 1)
slot_s, mac = token.upper().split("-", 1)
slot = int(slot_s)
# compare_digest raises on non ascii str
if not hmac.compare_digest(mac.encode(), _pass_mac(secret, poll_id, slot).encode()):
return None
except (ValueError, AttributeError):
return None
if not hmac.compare_digest(mac, _mac(secret, poll_id, interval_ms, slot)):
return None
age = now_ms() - slot * interval_ms
if age < 0 or age > interval_ms + grace_ms:
age = now_ms() - slot * rotate_ms
if age < 0 or age > rotate_ms + grace_ms:
return None
return slot
+57 -3
View File
@@ -44,9 +44,19 @@
<div class="card">
<label for="s-code-style">Code projeté</label>
<select id="s-code-style">
<option value="ring">Code circulaire</option>
<option value="ring">Cercle animé</option>
<option value="qr">QR classique</option>
</select>
<label for="s-camera">Scan avec l'appareil photo</label>
<select id="s-camera">
<option value="1">Autorisé</option>
<option value="0">Désactivé</option>
</select>
<label for="s-entry-big">QR d'entrée</label>
<select id="s-entry-big">
<option value="0">Dans le coin</option>
<option value="1">Grand, à côté du cercle</option>
</select>
<div class="row">
<div>
<label for="s-interval">Rotation du code</label>
@@ -112,12 +122,27 @@
<button id="screen-rotate" class="small" type="button">Nouveau lien</button>
</div>
<div class="share-row">
<div><b>Résultats</b><span class="muted">Bulletins anonymes et décomptes</span></div>
<button id="export" class="small" type="button">Exporter</button>
<div><b>Écran dupliqué</b><span class="muted">Projection et gestion sur le même écran</span></div>
<a id="open-present" class="btn small" href="#" target="_blank" rel="noopener">Ouvrir</a>
</div>
<div class="share-row">
<div><b>Résultats</b><span class="muted">Exporter en texte ou JSON (anonyme)</span></div>
<div class="code-actions">
<button id="export-text" class="small" type="button">Texte</button>
<button id="export" class="small" type="button">JSON</button>
</div>
</div>
</div>
<div class="card share-list" id="share-card">
<div class="share-row">
<div><b>Lien des résultats</b><span class="muted" id="share-summary"></span></div>
<div class="code-actions" id="share-actions"></div>
</div>
<div id="share-qs"></div>
</div>
</section>
<section id="codes-sheet" class="card" hidden>
<div class="no-print actions"><button id="codes-close" class="small" type="button">Fermer</button><button id="codes-do-print" class="small primary" type="button">Imprimer</button></div>
<h2 id="codes-title"></h2>
@@ -126,6 +151,35 @@
</div>
</main>
<dialog id="extra-dlg">
<form method="dialog" id="extra-form">
<h2>Votes en plus</h2>
<p class="muted" id="extra-q"></p>
<div id="extra-fields"></div>
<p class="hint">Bulletins papier, vote à main levée… Ils s'ajoutent aux votes par téléphone et s'affichent en orange hachuré.</p>
<div class="actions">
<button value="cancel" type="submit">Annuler</button>
<span class="spacer"></span>
<button value="ok" class="primary" type="submit">Enregistrer</button>
</div>
</form>
</dialog>
<dialog id="export-dlg">
<form method="dialog">
<h2>Exporter les résultats</h2>
<select id="ex-scope" aria-label="Questions"></select>
<div class="templates" id="ex-formats" role="radiogroup" aria-label="Modèle"></div>
<pre id="ex-preview" tabindex="0"></pre>
<div class="actions">
<button value="cancel" type="submit">Fermer</button>
<span class="spacer"></span>
<button id="ex-download" type="button">Télécharger</button>
<button id="ex-copy" class="primary" type="button">Copier</button>
</div>
</form>
</dialog>
<dialog id="composer">
<form method="dialog" id="q-form">
<h2>Nouvelle question</h2>
+27 -6
View File
@@ -54,15 +54,36 @@
.share-row > div:first-child { display: grid; }
.share-row .muted { font-size: .85rem; }
#composer { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); }
#composer::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); }
#composer[open] { animation: rise .2s ease-out; }
#composer h2 { font-size: 1.3rem; }
#composer, #extra-dlg, #export-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); }
#composer::backdrop, #extra-dlg::backdrop, #export-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); }
#composer[open], #extra-dlg[open], #export-dlg[open] { animation: rise .2s ease-out; }
#composer h2, #extra-dlg h2, #export-dlg h2 { font-size: 1.3rem; }
.spacer { flex: 1; }
@media (max-width: 560px) {
.summary-row > * { flex: 1 1 auto; }
#composer .actions button { flex: 1 1 100%; }
#composer .spacer { display: none; }
#composer .actions button, #extra-dlg .actions button, #export-dlg .actions button { flex: 1 1 100%; }
#composer .spacer, #extra-dlg .spacer, #export-dlg .spacer { display: none; }
}
#q-opts { min-height: 132px; }
.extra-row { margin: 8px 0; display: grid; grid-template-columns: 1fr 110px; gap: 12px; align-items: center; font-weight: 600; }
.extra-row input { text-align: right; }
#export-dlg { width: min(94vw, 720px); }
#ex-scope { margin-bottom: 12px; }
#ex-scope[hidden] { display: none; }
#ex-formats button[aria-checked="true"] { background: var(--mark); border-color: var(--mark); color: var(--ink); }
#ex-preview {
margin: 12px 0 0; padding: 14px 16px; max-height: 50vh; overflow: auto; background: var(--bg); border-radius: var(--r-field);
font: .82rem/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; white-space: pre; tab-size: 4;
}
#ex-preview.empty { white-space: normal; color: var(--ink-3); font-family: var(--sans); text-align: center; padding: 32px 16px; }
#share-qs { border-top: 1.5px solid var(--bg); padding: 6px 0 10px; }
#share-qs:empty { display: none; }
.share-q { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; font-weight: 500; cursor: pointer; }
.share-q input { margin-top: 3px; flex: none; }
.share-none { margin: 8px 0; font-size: .85rem; }
.q .copy-btn { margin-left: auto; padding: 7px 9px; border-radius: 10px; border: 1.5px solid var(--line); color: var(--ink-2); }
+13 -3
View File
@@ -116,6 +116,11 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.bar-label { overflow-wrap: anywhere; }
.bar-track { height: 12px; background: var(--bg); border-radius: 99px; overflow: hidden; }
.bar-fill { height: 100%; background: var(--ink-3); border-radius: 99px; transition: width .6s cubic-bezier(.2, .8, .2, 1); }
/* one bar = phone ballots then hand-added votes, hatched orange */
.bar-stack { height: 100%; display: flex; border-radius: 99px; overflow: hidden; transition: width .6s cubic-bezier(.2, .8, .2, 1); }
.bar-stack > div { flex: 1 1 0; border-radius: 0; height: 100%; }
.bar-extra, .progress > .p-extra { background: repeating-linear-gradient(-45deg, #f08a24 0 5px, #f9c58f 5px 10px); }
.extra-note { color: #b85e0b; font-weight: 600; }
.bar-row.lead .bar-fill { background: var(--mark); }
.bar-row.lead .bar-label { font-weight: 700; }
.bar-num { font: 700 1rem var(--round); min-width: 80px; text-align: right; }
@@ -124,16 +129,19 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
.progress { height: 8px; background: var(--bg); border-radius: 99px; overflow: hidden; margin-top: 6px; }
.progress > div { height: 100%; background: var(--ink); border-radius: 99px; transition: width .3s; }
.progress { display: flex; }
.progress > .p-extra { border-radius: 0 99px 99px 0; }
.progress > div:not(:last-child) { border-radius: 99px 0 0 99px; }
.ring { display: block; overflow: visible; }
.ring .seg, .ring .fill { fill: none; stroke-linecap: round; }
.ring .seg { stroke: var(--line); }
/* empty fill sits one length ahead and hidden, so the round cap dot doesn't show */
/* empty fill sits one length ahead (offset set in js) and hidden, so the round cap dot doesn't show */
.ring .fill {
stroke: var(--ink); stroke-dasharray: 1 1; stroke-dashoffset: 1; opacity: 0;
stroke: var(--ink); opacity: 0;
transition: stroke-dashoffset .5s cubic-bezier(.3, .7, .2, 1), opacity .12s, stroke .22s;
}
.ring .fill.on { stroke-dashoffset: 0; opacity: 1; }
.ring .fill.on { opacity: 1; }
.ring .fill.last { stroke: var(--mark); }
@media (prefers-reduced-motion: reduce) { .ring .fill { transition: opacity .2s, stroke .2s; } }
.ring text { font: 700 20px var(--round); fill: var(--ink); }
@@ -176,3 +184,5 @@ details.advanced { margin-top: 14px; }
details.advanced summary { font-size: .82rem; color: var(--ink-3); cursor: pointer; width: fit-content; padding: 4px 0; }
details.advanced summary:hover { color: var(--ink-2); }
details.advanced[open] summary { color: var(--ink-2); }
.mode-title { font-size: 1.05rem; margin: 22px 0 2px; }
.mode-title + .hint { margin: 0 0 8px; }
+88 -23
View File
@@ -17,10 +17,39 @@ body.screen {
background: #fff; border-radius: 28px; padding: 2vh; gap: 1.4vh;
}
.qr-wrap.ring { background: transparent; padding: 0; }
.entry { display: flex; align-items: center; gap: 1.2vw; margin-top: 3vh; background: var(--surface); border-radius: 18px; padding: 1.2vh 1.2vw; width: fit-content; }
.entry canvas { width: clamp(140px, min(21vw, 34vh), 420px); height: auto; aspect-ratio: 1; image-rendering: pixelated; flex: none; }
.entry div { display: grid; gap: .3vh; font-size: clamp(.8rem, 1.1vw, 1.2rem); color: var(--ink-2); min-width: 0; overflow-wrap: break-word; }
/* the entry qr docks in the bottom right corner, outside the layout: the ring never shrinks for it.
the column under it keeps that much room free (body.has-entry) */
body.screen { --dock-qr: clamp(150px, min(34vh, 24vw), 480px); --dock-h: calc(var(--dock-qr) + 2.4vh + 2.9rem); }
/* with a question on screen the qr leaves the question some height */
body.split-on { --dock-qr: clamp(130px, min(26vh, 19vw), 380px); }
.entry {
position: fixed; right: 1.2vw; bottom: 1.5vh; z-index: 5; display: grid; justify-items: center; gap: .8vh;
background: var(--surface); border-radius: 18px; padding: 1.2vh; text-align: center; max-width: 40vw;
}
.entry canvas { width: var(--dock-qr); height: auto; aspect-ratio: 1; image-rendering: pixelated; }
.entry div { display: grid; gap: .2vh; font-size: clamp(.7rem, .95vw, 1rem); color: var(--ink-2); overflow-wrap: break-word; }
.entry b { color: var(--ink); font-weight: 700; }
body.has-entry .s-main:not(.split) .s-steps, body.has-entry .s-main.split #focus { padding-bottom: var(--dock-h); }
/* big mode: the entry qr takes the right column beside the ring, the steps give it the room.
translate, not transform: the entrance animation owns transform */
body.entry-big { --dock-qr: clamp(180px, min(58vh, 34vw), 640px); }
body.entry-big .entry { top: 50%; bottom: auto; right: max(4vw, calc((50vw - var(--dock-qr)) / 2 - 2vw)); translate: 0 -46%; padding: 2vh; gap: 1.2vh; }
body.entry-big .entry div { font-size: clamp(.9rem, 1.4vw, 1.6rem); }
body.entry-big .s-main:not(.split) .s-steps { visibility: hidden; }
body.entry-q-on { --dock-qr: clamp(160px, min(52vh, 32vw), 580px); }
/* width 0 + min-width 100%: a long question wraps to the qr's width instead of widening the block */
.entry-q { display: grid; gap: .6vh; padding-bottom: 1vh; margin-bottom: .4vh; border-bottom: 2px solid var(--bg); width: 0; min-width: 100%; }
.entry-q > b { font: 700 clamp(1rem, 1.7vw, 2rem) var(--round); color: var(--ink); line-height: 1.15; }
.entry-q > span { font: 600 clamp(.85rem, 1.2vw, 1.4rem) var(--round); color: var(--ink-2); }
/* open vote above the big qr: its options and the turnout bar, smaller than in the question block */
body.entry-q-on.entry-opts-on { --dock-qr: clamp(150px, min(48vh, 30vw), 540px); }
.entry-opts { list-style: none; padding: 0; margin: .2vh 0 0; display: flex; flex-wrap: wrap; justify-content: center; gap: .6vh .5vw; }
.entry-opts li { font: 600 clamp(.8rem, 1.15vw, 1.35rem) var(--round); background: var(--bg); border-radius: 12px; padding: .6vh .8vw; }
/* .entry div is a grid: the count reads on one line, the bar stays a flex row */
.entry-q .turnout { display: block; font: 600 clamp(.8rem, 1.1vw, 1.3rem) var(--round); color: var(--ink-2); }
.entry-q .turnout .progress { display: flex; }
.entry-q .turnout b { color: var(--ink); font-size: 1.35em; }
.entry-q .turnout .progress { height: 10px; margin-top: .8vh; }
/* the ring loop resizes the canvas bitmap every frame: its intrinsic size must not feed the layout,
or safari widens the column, which grows the bitmap, which widens the column... */
#qr { width: 100%; height: 100%; min-width: 0; min-height: 0; contain: size; image-rendering: pixelated; image-rendering: crisp-edges; object-fit: contain; }
@@ -38,20 +67,24 @@ body.screen {
font-weight: 700; font-size: .8em;
}
/* enrollment + a question at the same time: qr shrinks to the side */
.s-main.split { grid-template-columns: minmax(0, 1fr) minmax(0, 1.3fr); gap: 5vw; }
.s-main.split .s-enroll { grid-template-columns: 1fr; justify-items: center; gap: 3vh; }
.s-main.split .s-enroll { grid-template-rows: minmax(0, 1fr) auto; gap: 2vh; height: 100%; }
/* a question on screen while the ring is up (vote with presence scans, late enrollment). the back rows read
the ring, so it keeps the wider column and as much height as possible */
.s-main.split { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 4vw; }
.s-main.split .s-enroll { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 3vh; }
.s-main.split .s-enroll { grid-template-rows: minmax(0, 1fr) auto; gap: 1.5vh; height: 100%; }
.s-main.split .qr-wrap { height: 100%; width: auto; max-width: 100%; max-height: none; }
.s-main.split .entry { margin-top: 1.5vh; }
/* 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 { text-align: center; }
.s-main.split .s-steps h2 { font-size: clamp(1.2rem, 2.1vw, 2.4rem); margin: 0; }
/* the question side scales with height too, so it still fits above the docked qr on short screens */
.s-main.split .s-focus .q-text { font-size: clamp(1.3rem, min(3.2vw, 6.5vh), 3.6rem); margin-bottom: 2.5vh; }
.s-main.split .s-focus .opts { gap: 1vh; margin-bottom: 2.5vh; }
.s-main.split .s-focus .opts li { font-size: clamp(.95rem, min(1.8vw, 3.6vh), 2rem); padding: 1.1vh 1.5vw; }
.s-main.split .s-focus .turnout { font-size: clamp(.9rem, min(1.5vw, 3vh), 1.7rem); }
.s-main.split .s-focus .results .bar-row { font-size: clamp(.95rem, min(1.8vw, 3.6vh), 2rem); margin: 1.2vh 0; }
.s-main.split .s-steps li { font-size: clamp(1rem, 1.5vw, 1.6rem); }
.s-focus { align-self: center; max-width: 1400px; width: 100%; margin: 0 auto; }
.s-focus { align-self: center; align-self: safe center; max-width: 1400px; width: 100%; margin: 0 auto; }
.s-focus .q-text { font-size: clamp(1.8rem, 3.8vw, 4rem); letter-spacing: -.025em; line-height: 1.1; margin-bottom: 4vh; }
.s-focus .opts { list-style: none; padding: 0; margin: 0 0 4vh; display: grid; gap: 1.4vh; }
.s-focus .opts li { font: 600 clamp(1.1rem, 2.2vw, 2.3rem) var(--round); background: var(--surface); border-radius: 20px; padding: 1.6vh 2vw; }
@@ -77,19 +110,20 @@ body.screen {
@media (max-aspect-ratio: 1/1) {
.s-enroll, .s-main.split { grid-template-columns: 1fr; }
.qr-wrap { max-height: 50vh; justify-self: center; }
/* upright screen: the ring takes what the text leaves, the entry qr sits next to the steps */
/* upright screen: the ring takes what the text leaves, the docked entry qr sits right of the steps */
body.screen { --dock-qr: clamp(120px, min(21vh, 34vw), 340px); }
.s-main:not(.split) .s-enroll { grid-template-rows: minmax(0, 1fr) auto; gap: 3vh; height: 100%; }
.s-main:not(.split) .qr-wrap { height: 100%; width: auto; max-width: 100%; max-height: none; }
.s-steps { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 4vw; align-items: center; }
.s-steps > * { grid-column: 1; }
.s-steps .entry { grid-column: 2; grid-row: 1 / span 3; flex-direction: column; gap: .8vh; margin: 0; padding: 1.2vh; text-align: center; }
.s-steps .entry div { font-size: clamp(.7rem, 2.2vw, 1.1rem); overflow-wrap: normal; white-space: nowrap; }
.s-steps .entry canvas { width: clamp(110px, min(30vw, 17vh), 300px); }
/* upright + question: ring and entry share one row above the question */
body.has-entry .s-main:not(.split) .s-steps { padding-bottom: 0; padding-right: calc(var(--dock-qr) + 6vw); }
/* no room beside the ring on an upright screen: the big qr stays a (bigger) corner one */
body.entry-big { --dock-qr: clamp(140px, min(26vh, 40vw), 400px); }
body.entry-big .entry { top: auto; bottom: 1.5vh; right: 1.2vw; translate: none; }
body.entry-big .s-main:not(.split) .s-steps { visibility: visible; }
.entry-q { display: none; }
/* upright + question: ring and title share one row above the question */
.s-main.split .s-enroll { grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: none; height: auto; align-items: center; justify-items: stretch; }
.s-main.split .qr-wrap { height: auto; width: 100%; max-height: 38vh; justify-self: center; }
.s-main.split .s-steps { grid-template-columns: auto; justify-items: center; row-gap: 1vh; }
.s-main.split .s-steps .entry { grid-column: 1; grid-row: auto; }
.s-main.split .s-steps { display: grid; grid-template-columns: auto; justify-items: center; row-gap: 1vh; text-align: center; max-width: 42vw; }
}
.qr-wrap.ring .tick { display: none; }
@@ -109,7 +143,7 @@ body.screen {
#focus.enter :is(.opts li, .bar-row):nth-child(4) { animation-delay: .26s; }
#focus.enter :is(.opts li, .bar-row):nth-child(n+5) { animation-delay: .32s; }
#focus.enter .turnout, #focus.enter .results-foot, #focus.enter .status { animation: s-in .45s .3s cubic-bezier(.2, .7, .2, 1) both; }
#focus.enter .bar-fill { transform-origin: left; animation: s-grow .9s .25s cubic-bezier(.2, .7, .2, 1) both; }
#focus.enter .bar-stack { transform-origin: left; animation: s-grow .9s .25s cubic-bezier(.2, .7, .2, 1) both; }
.turnout .progress > div { transition: width .5s cubic-bezier(.2, .7, .2, 1); }
#voters { display: inline-block; }
#voters.bump { animation: s-bump .35s ease; }
@@ -117,3 +151,34 @@ body.screen {
.s-main > section, .entry, #focus.enter *, #voters.bump { animation: none !important; }
.turnout .progress > div { transition: none; }
}
/* duplicated screen: the admin slides in over the projection, the room sees it while it's open */
.ctl {
position: fixed; top: 0; right: 0; bottom: 0; z-index: 30; width: min(480px, 94vw); display: grid; grid-template-rows: auto 1fr;
background: var(--bg); box-shadow: -12px 0 40px rgba(28, 32, 54, .18); translate: 105% 0; transition: translate .35s cubic-bezier(.2, .7, .2, 1);
}
.ctl.open { translate: 0 0; }
.ctl-head { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; font: 700 1rem var(--round); }
.ctl iframe { width: 100%; height: 100%; border: 0; background: var(--bg); }
/* the manage button stays reachable in full screen, faint until hovered */
:fullscreen .s-tools .ctl-btn { display: inline-flex; opacity: .3; }
:fullscreen .s-tools .ctl-btn:hover, :fullscreen .s-tools .ctl-btn:focus-visible { opacity: 1; }
@media (prefers-reduced-motion: reduce) { .ctl { transition: none; } }
/* drawer open: the projection keeps the space on its left. --room is that width */
body.screen { --ctl-w: min(480px, 94vw); }
body.ctl-open { --room: calc(100vw - var(--ctl-w)); }
body.ctl-open :is(.s-head, .s-main, .s-foot) { margin-right: var(--ctl-w); }
body.ctl-open .entry { right: calc(var(--ctl-w) + 1.2vw); }
/* big qr: ring and qr share the room, the qr right against the ring */
body.ctl-open.entry-big { --dock-qr: clamp(140px, min(46vh, calc(var(--room) * .34)), 520px); }
body.ctl-open.entry-big .s-main:not(.split) .qr-wrap { max-height: min(74vh, calc(var(--room) * .48)); }
body.ctl-open.entry-big .s-main:not(.split) .s-enroll { gap: 2vw; }
body.ctl-open.entry-big .entry { right: auto; left: calc(4vw + min(74vh, var(--room) * .48) + 2vw); }
body.ctl-open.split-on { --dock-qr: clamp(100px, min(22vh, calc(var(--room) * .2)), 260px); }
body.ctl-open .s-main.split .s-focus .q-text { font-size: clamp(1.1rem, min(calc(var(--room) * .04), 6vh), 3rem); }
body.ctl-open .s-main.split .s-focus .opts li { font-size: clamp(.9rem, min(calc(var(--room) * .024), 3.4vh), 1.8rem); }
/* narrow room: the ring follows its column's width, not the row's height */
body.ctl-open .s-main.split .qr-wrap { width: 100%; height: auto; max-height: 100%; align-self: center; }
/* grid items won't shrink below their content by default: let the ring's column be as narrow as the room */
.s-main > section { min-width: 0; }
+21 -2
View File
@@ -60,13 +60,17 @@ dialog .actions button { flex: 1; }
.celebrate svg { width: 132px; height: 132px; animation: cel-pop .5s cubic-bezier(.2, .9, .3, 1.25) both; }
.celebrate .tick { stroke-dasharray: 1; stroke-dashoffset: 1; animation: cel-tick .45s .25s cubic-bezier(.3, .7, .2, 1) forwards; }
.celebrate p { margin: 0; font: 700 1.3rem var(--round); animation: cel-in .4s .35s ease both; }
.celebrate small { margin-top: -10px; font: 600 .95rem var(--round); color: var(--ink-2); animation: cel-in .4s .45s ease both; }
.celebrate.out { animation: cel-out .4s ease forwards; }
@keyframes cel-in { from { opacity: 0; } }
@keyframes cel-out { to { opacity: 0; } }
@keyframes cel-pop { from { transform: scale(.6) rotate(-40deg); opacity: 0; } }
@keyframes cel-tick { to { stroke-dashoffset: 0; } }
.celebrate.verifying svg { animation: cel-spin 1s linear infinite; }
.celebrate.verifying p { animation-delay: 0s; }
@keyframes cel-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.celebrate, .celebrate svg, .celebrate p { animation: none; }
.celebrate, .celebrate svg, .celebrate p, .celebrate small, .celebrate.verifying svg { animation: none; }
.celebrate .tick { animation: none; stroke-dashoffset: 0; }
}
@@ -76,4 +80,19 @@ dialog .actions button { flex: 1; }
display: grid; place-items: center; border: 0; color: #fff; background: rgba(20, 22, 36, .55);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
}
.cam-switch:hover { border: 0; background: rgba(20, 22, 36, .75); }
.cam-switch:hover, .cam-zoom:hover { border: 0; background: rgba(20, 22, 36, .75); }
.cam-zoom {
position: absolute; left: 10px; bottom: 10px; min-width: 44px; height: 44px; padding: 0 12px; border-radius: 22px;
border: 0; color: #fff; background: rgba(20, 22, 36, .55); font: 700 .95rem var(--round);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
}
/* the phone's own camera app reads the projector qr when the browser can't use the camera */
.cam-alt { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 0 0 12px; font-size: .9rem; color: var(--ink-2); text-align: left; }
.cam-alt .icon { flex: none; }
.cam-alt.solo { flex-direction: column; gap: 12px; margin: 4px 0 18px; color: var(--ink); }
.cam-alt.solo .icon { width: 64px; height: 64px; padding: 14px; border-radius: 50%; background: var(--mark); stroke-width: 1.8; }
.cam-alt.solo b { font: 700 1.25rem/1.25 var(--round); text-align: center; }
.cam-alt.solo ol { list-style: none; counter-reset: st; padding: 0; margin: 0; display: grid; gap: 10px; font: 600 1rem/1.35 var(--round); }
.cam-alt.solo li { counter-increment: st; display: grid; grid-template-columns: 28px 1fr; gap: 10px; align-items: start; }
.cam-alt.solo li::before { content: counter(st); display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--ink); color: var(--surface); font-weight: 700; font-size: .9rem; }
+20
View File
@@ -38,6 +38,16 @@
<details class="advanced">
<summary>Réglages du code</summary>
<label for="code-style">Code projeté</label>
<select id="code-style">
<option value="ring" selected>Cercle animé</option>
<option value="qr">QR classique</option>
</select>
<label for="camera">Scan avec l'appareil photo</label>
<select id="camera">
<option value="1" selected>Autorisé</option>
<option value="0">Désactivé</option>
</select>
<div class="row">
<div>
<label for="interval">Rotation du code</label>
@@ -70,6 +80,8 @@
<section id="done" class="card" hidden>
<h1>Scrutin créé</h1>
<div class="notice warn">Conservez le lien d'administration : il ne pourra pas être récupéré.</div>
<h2 class="mode-title">Écran splitté</h2>
<p class="hint">L'administration sur votre écran, le projecteur sur l'écran étendu.</p>
<div class="duo stack">
<div class="pane">
<div class="pane-head"><svg class="icon" viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H4z"/><path d="M2 19.5h20"/><path d="M8 9h8"/><path d="M8 12.5h5"/></svg><p><b>Administration</b><span>Sur votre écran</span></p></div>
@@ -82,6 +94,14 @@
<a id="go-screen" class="btn block" href="#" target="_blank" rel="noopener">Ouvrir le projecteur</a>
</div>
</div>
<h2 class="mode-title">Écran dupliqué</h2>
<p class="hint">Un seul écran, recopié sur le projecteur. Le bouton « Gérer » ouvre l'administration par-dessus.</p>
<div class="duo stack">
<div class="pane">
<div class="pane-head"><svg class="icon" viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 4h20"/><path d="M4 4v10h16V4"/><path d="M12 14v3"/><path d="M8.5 21l3.5-4 3.5 4"/></svg><p><b>Écran unique</b><span>Projection et gestion au même endroit</span></p></div>
<a id="go-present" class="btn block" href="#" target="_blank" rel="noopener">Ouvrir l'écran dupliqué</a>
</div>
</div>
</section>
</main>
</body>
+159 -5
View File
@@ -1,9 +1,11 @@
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js";
import { FORMATS, exportText } from "./export.js";
const pid = pollId();
const key = takeKey(`rv_admin_${pid}`);
const base = `/api/polls/${pid}`;
const TAB_KEY = "rv_admin_tab";
const FMT_KEY = "rv_export_fmt";
let state = null;
const TEMPLATES = [
@@ -63,6 +65,7 @@ function render() {
renderSettings(p);
renderQuestions();
renderShare(p);
}
function renderSettings(p) {
@@ -78,6 +81,11 @@ function renderSettings(p) {
if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? "";
if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans);
if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style;
if (active !== $("#s-entry-big")) $("#s-entry-big").value = p.entry_big ? "1" : "0";
$("#s-entry-big").disabled = p.code_style !== "ring";
if (active !== $("#s-camera")) $("#s-camera").value = p.camera_pass ? "1" : "0";
// the classic qr is the camera app code itself
$("#s-camera").disabled = p.code_style !== "ring";
$("#s-code").checked = p.require_code;
$("#access-row").hidden = !p.require_code && !state.codes.access.total;
const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none);
@@ -92,8 +100,8 @@ function renderQuestions() {
box.append(h("p", { class: "empty" }, "Aucune question pour l'instant."));
return;
}
const order = { open: 0, draft: 1, closed: 2 };
const qs = [...state.questions].sort((a, b) => order[a.state] - order[b.state] || a.id - b.id);
// the open vote first, then newest first: a question just created or just closed stays at the top
const qs = [...state.questions].sort((a, b) => (b.state === "open") - (a.state === "open") || b.id - a.id);
for (const q of qs) box.append(questionCard(q));
}
@@ -114,33 +122,69 @@ function questionCard(q) {
actions.push(act("Lancer le vote", "open", "small go"));
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
} else if (q.state === "open") {
actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants} vote${q.participants > 1 ? "s" : ""}) ?`));
actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants + q.extra_ballots} vote${q.participants + q.extra_ballots > 1 ? "s" : ""}) ?`));
} else {
actions.push(q.results_public
? act("Masquer les résultats", "unpublish")
: act("Publier les résultats", "publish", "small primary", "Publier les résultats ? Le vote ne pourra plus être rouvert."));
if (!q.shown) actions.push(act("Rouvrir le vote", "reopen"));
}
if (q.state !== "draft") actions.push(h("button", { class: "small", type: "button", onclick: () => editExtra(q) }, "Votes en plus"));
if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus"));
if (q.state === "closed") {
actions.push(h("button", {
class: "small copy-btn", type: "button", title: "Exporter les résultats", "aria-label": "Exporter les résultats",
onclick: () => openExport(q.id),
}, icon("copy", 16)));
}
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Publiés"));
if (q.shared && state.poll.share_key) badges.push(h("span", { class: "badge public" }, "Partagés"));
if (focused) badges.push(h("span", { class: "focus-mark" }, icon("screen", 14), "À l'écran"));
if (q.kind === "multi") badges.push(h("span", { class: "badge" }, `${q.max_choices} choix max`));
return h("article", { class: `q ${q.state}` },
h("div", { class: "q-head" }, h("div", {}, badges),
q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`) : null),
q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`,
q.extra_ballots ? h("span", { class: "extra-note" }, ` + ${q.extra_ballots}`) : null) : null),
h("div", { class: "q-text" }, q.text),
q.state === "closed"
? resultsView(q)
: h("div", { class: "chips" }, q.options.map((o) => h("span", { class: "chip" }, o)),
q.allow_blank ? h("span", { class: "chip ghost" }, "Blanc") : null),
q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters), "")) : null,
q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters + q.extra_ballots), ""),
q.extra_ballots ? fill(pct(q.extra_ballots, voters + q.extra_ballots), "p-extra") : null) : null,
h("div", { class: "actions" }, actions),
);
}
// votes added by hand, in a dialog: the question list re-renders on every incoming vote
async function editExtra(q) {
const dlg = $("#extra-dlg"), e = q.extra, inputs = [];
const field = (label, value) => {
const inp = h("input", { type: "number", min: 0, max: 100000, value: String(value), inputmode: "numeric" });
inputs.push(inp);
return h("label", { class: "extra-row" }, h("span", {}, label), inp);
};
$("#extra-q").textContent = q.text;
$("#extra-fields").replaceChildren(...[
...q.options.map((o, i) => field(o, e.counts[i] || 0)),
q.allow_blank ? field("Blanc", e.blank) : null,
q.kind === "multi" ? field("Bulletins (choix multiple)", e.ballots) : null,
].filter(Boolean));
dlg.returnValue = "";
dlg.showModal();
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
if (dlg.returnValue !== "ok") return;
const vals = inputs.map((i) => Math.max(0, Math.floor(+i.value || 0)));
const n = q.options.length;
const payload = { counts: vals.slice(0, n), blank: q.allow_blank ? vals[n] : 0 };
if (q.kind === "multi") payload.ballots = vals[vals.length - 1];
try { await call("POST", `/questions/${q.id}/extra`, payload); toast("Votes ajoutés", "ok"); }
catch (err) { toast(err.code === "bad_extra" ? "Nombre de bulletins incohérent" : errMsg(err), "bad"); }
}
// composer
const composer = $("#composer");
@@ -207,6 +251,8 @@ const SETTINGS = {
"#s-code": (el) => ({ require_code: el.checked }),
"#s-vote-scans": (el) => ({ vote_scans: +el.value }),
"#s-code-style": (el) => ({ code_style: el.value }),
"#s-entry-big": (el) => ({ entry_big: el.value === "1" }),
"#s-camera": (el) => ({ camera_pass: el.value === "1" }),
};
for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => {
@@ -267,6 +313,111 @@ $("#export").addEventListener("click", async () => {
} catch (e) { toast(errMsg(e), "bad"); }
});
// read-only results link, the admin ticks which closed questions it shows
const shareUrl = (k) => `${location.origin}/r/${pid}#${k}`;
function renderShare(p) {
const btn = (label, onclick, cls = "small") => h("button", { class: cls, type: "button", onclick }, label);
const rotate = async (msg) => {
if (msg && !confirm(msg)) return;
try { const r = await call("POST", "/share-key"); await copy(shareUrl(r.share_key), "Lien des résultats"); }
catch (e) { toast(errMsg(e), "bad"); }
};
const off = async () => {
if (!confirm("Désactiver le lien des résultats ?")) return;
try { await call("DELETE", "/share-key"); } catch (e) { toast(errMsg(e), "bad"); }
};
const closed = state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id);
const n = closed.filter((q) => q.shared).length;
$("#share-summary").textContent = p.share_key ? `${n} question${n > 1 ? "s" : ""} visible${n > 1 ? "s" : ""}` : "Lecture seule";
$("#share-actions").replaceChildren(...(p.share_key
? [btn("Copier", () => copy(shareUrl(p.share_key), "Lien des résultats")),
btn("Nouveau lien", () => rotate("Créer un nouveau lien ? L'ancien cessera de fonctionner.")),
btn("Désactiver", off, "small danger")]
: [btn("Créer", () => rotate())]));
if (!p.share_key) return $("#share-qs").replaceChildren();
$("#share-qs").replaceChildren(...(closed.length
? closed.map((q) => h("label", { class: "share-q" },
h("input", {
type: "checkbox", checked: q.shared,
onchange: async (e) => {
const on = e.target.checked;
if (on && !q.shown && !confirm("Partager ces résultats ? Le vote ne pourra plus être rouvert.")) {
e.target.checked = false;
return;
}
try { await call("POST", `/questions/${q.id}/${on ? "share" : "unshare"}`); }
catch (err) { e.target.checked = !on; toast(errMsg(err), "bad"); }
},
}), h("span", {}, q.text)))
: [h("p", { class: "muted share-none" }, "Aucune question close.")]));
}
// text export, built in the browser from the closed tallies the socket already sends
const exDlg = $("#export-dlg");
let fmt = FORMATS[0];
try { fmt = FORMATS.find((f) => f.id === localStorage.getItem(FMT_KEY)) || fmt; } catch { /* private mode */ }
let exText = "";
for (const f of FORMATS) {
$("#ex-formats").append(h("button", {
class: "small", type: "button", role: "radio", dataset: { fmt: f.id },
onclick: () => {
fmt = f;
try { localStorage.setItem(FMT_KEY, f.id); } catch { /* private mode */ }
renderExport();
},
}, f.label));
}
function closedQuestions() {
return state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id);
}
function renderExport() {
for (const b of $("#ex-formats").children) b.setAttribute("aria-checked", String(b.dataset.fmt === fmt.id));
const scope = $("#ex-scope").value;
const qs = closedQuestions().filter((q) => scope === "all" || String(q.id) === scope);
const now = new Date().toLocaleString("fr-FR", { dateStyle: "long", timeStyle: "short" });
exText = qs.length ? exportText(fmt, state.poll, state.voters, qs, now) : "";
const pre = $("#ex-preview");
pre.classList.toggle("empty", !exText);
pre.textContent = exText || "Aucune question close.";
$("#ex-copy").disabled = $("#ex-download").disabled = !exText;
}
function openExport(qid = "all") {
const qs = closedQuestions();
const sel = $("#ex-scope");
sel.replaceChildren(h("option", { value: "all" }, "Toutes les questions closes"),
...qs.map((q) => h("option", { value: String(q.id) }, q.text)));
sel.value = String(qid);
sel.hidden = qs.length < 2;
renderExport();
exDlg.showModal();
}
$("#ex-scope").addEventListener("change", renderExport);
$("#export-text").addEventListener("click", () => openExport());
$("#ex-copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(exText); toast("Copié"); }
catch {
// prompt() would flatten the lines, select the preview so cmd+c works
getSelection().selectAllChildren($("#ex-preview"));
toast("Texte sélectionné");
}
});
$("#ex-download").addEventListener("click", () => {
// bom so excel reads the accents in the csv
const body = fmt.ext === "csv" ? "\ufeff" + exText : exText;
const blob = new Blob([body], { type: `${fmt.mime};charset=utf-8` });
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.${fmt.ext}` });
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
});
liveSocket(`/ws/${pid}/admin`, {
auth: key,
onMessage(msg) {
@@ -289,3 +440,6 @@ liveSocket(`/ws/${pid}/admin`, {
c.textContent = "Reconnexion…";
},
});
// duplicated screen: the projector view with this admin in a drawer, same admin key
$("#open-present").href = `/present/${pid}#${encodeURIComponent(key)}`;
+37 -16
View File
@@ -1,3 +1,6 @@
import { tally, pct } from "./export.js";
export { pct };
export const $ = (sel, root = document) => root.querySelector(sel);
// tiny element builder, children are always text nodes or elements so no html injection
@@ -103,9 +106,6 @@ export function drawQR(canvas, modules, px) {
}
}
export function pct(n, d) {
return d ? Math.round((n / d) * 1000) / 10 : 0;
}
// CSSOM write, a style="" attribute would be blocked by the CSP
export function fill(percent, cls = "bar-fill") {
@@ -115,25 +115,37 @@ export function fill(percent, cls = "bar-fill") {
}
export function resultsView(q) {
const r = q.results;
if (!r) return null;
const base = r.ballots - r.blank;
const max = Math.max(1, ...r.counts);
const rows = q.options.map((label, i) =>
h("div", { class: "bar-row" + (r.counts[i] === max && r.counts[i] > 0 ? " lead" : "") },
if (!q.results) return null;
// votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots
const { phone, extra, tot, ballots, blank, base, exBallots } = tally(q);
const max = Math.max(1, ...tot);
const rows = q.options.map((label, i) => {
const stack = h("div", { class: "bar-stack" },
seg("bar-fill", phone[i]), extra[i] ? seg("bar-extra", extra[i]) : null);
stack.style.width = `${pct(tot[i], max)}%`;
return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") },
h("div", { class: "bar-label" }, label),
h("div", { class: "bar-track" }, fill(pct(r.counts[i], max))),
h("div", { class: "bar-num" }, r.counts[i], h("small", {}, ` ${pct(r.counts[i], base).toLocaleString("fr-FR")} %`)),
));
h("div", { class: "bar-track" }, stack),
h("div", { class: "bar-num" }, tot[i], h("small", {}, ` ${pct(tot[i], base).toLocaleString("fr-FR")} %`)),
);
});
return h("div", { class: "results" },
rows,
h("p", { class: "results-foot" },
`${r.ballots} bulletin${r.ballots > 1 ? "s" : ""}`,
q.allow_blank ? `, dont ${r.blank} blanc${r.blank > 1 ? "s" : ""}` : "",
`${ballots} bulletin${ballots > 1 ? "s" : ""}`,
q.allow_blank ? `, dont ${blank} blanc${blank > 1 ? "s" : ""}` : "",
exBallots ? h("span", { class: "extra-note" }, `, dont ${exBallots} ajouté${exBallots > 1 ? "s" : ""} à la main`) : "",
),
);
}
// a flex share of a bar (CSSOM write, the CSP blocks style="")
function seg(cls, n) {
const el = h("div", { class: cls });
el.style.flexGrow = String(n);
return el;
}
export const STATE_LABEL = { draft: "Brouillon", open: "Vote ouvert", closed: "Clos" };
export function toast(msg, kind = "info") {
@@ -150,6 +162,9 @@ const ICONS = {
screen: ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"],
check: ["M5 12.5l4.5 4.5L19 7.5"],
swap: ["M4 9h13l-3.5-3.5", "M20 15H7l3.5 3.5"],
camera: ["M3 8.5A2.5 2.5 0 0 1 5.5 6h2L9 4h6l1.5 2h2A2.5 2.5 0 0 1 21 8.5v9a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z",
"M12 9.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7"],
copy: ["M9 9h10v10H9z", "M5 15V5h10"],
};
export function icon(name, size = 16) {
@@ -180,13 +195,18 @@ export function ring(n, total, size = 160, label = `${n}/${total}`) {
for (let i = 0; i < total; i++) {
const s0 = i * slot + (gap + sw) / 2;
const d = `M ${at(s0)} A ${r} ${r} 0 ${seg / r > Math.PI ? 1 : 0} 1 ${at(s0 + seg)}`;
// track underneath, fill on top sweeps clockwise through pathLength 1
// track underneath, fill on top sweeps clockwise. dash lengths in real units: some android webviews
// mishandle pathLength and draw the fill whole or not at all
for (const cls of ["seg", "fill"]) {
const el = document.createElementNS(SVGNS, "path");
el.setAttribute("d", d);
el.setAttribute("stroke-width", sw);
el.setAttribute("class", cls);
if (cls === "fill") { el.setAttribute("pathLength", 1); fills.push(el); }
if (cls === "fill") {
el.style.strokeDasharray = `${seg} ${seg + sw * 2}`;
el.style.strokeDashoffset = String(seg);
fills.push(el);
}
svg.append(el);
}
}
@@ -199,6 +219,7 @@ export function ring(n, total, size = 160, label = `${n}/${total}`) {
fills.forEach((el, i) => {
el.classList.toggle("on", i < k);
el.classList.toggle("last", i === k - 1 && k < total);
el.style.strokeDashoffset = String(i < k ? 0 : seg);
});
t.textContent = text;
};
+148
View File
@@ -0,0 +1,148 @@
// plain text results export, pure functions (no dom) so node can run them too
export function tally(q) {
const r = q.results;
const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 };
const extra = r.counts.map((_, i) => ex.counts[i] || 0);
const tot = r.counts.map((c, i) => c + extra[i]);
const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank;
return { phone: r.counts, extra, tot, ballots, blank, base: ballots - blank, exBallots: ex.ballots, exBlank: ex.blank };
}
export function pct(n, d) {
return d ? Math.round((n / d) * 1000) / 10 : 0;
}
// fr-FR toLocaleString puts a narrow nbsp in thousands, which breaks column alignment
const num = (n) => String(n).replace(".", ",");
const pctTxt = (n, d) => `${num(pct(n, d))} %`;
const plural = (n, word) => `${n} ${word}${n > 1 ? "s" : ""}`;
function foot(q, t) {
let s = plural(t.ballots, "bulletin");
if (q.allow_blank) s += `, dont ${plural(t.blank, "blanc")}`;
if (t.exBallots) s += `, dont ${t.exBallots} ajouté${t.exBallots > 1 ? "s" : ""} à la main`;
return s;
}
const nb = (qs, k) => (qs.length > 1 ? `${k + 1}. ` : "");
const kindNote = (q) => (q.kind === "multi" ? `Choix multiple, ${q.max_choices} max` : "");
function header(poll, voters, now) {
return [poll.title, `Résultats du ${now} · ${plural(voters, "inscription")}`];
}
// visible length, emoji and accents count as one column
const width = (s) => [...s].length;
const padEnd = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
const padStart = (s, n) => " ".repeat(Math.max(0, n - width(s))) + s;
function rows(q, t) {
const out = q.options.map((label, i) => ({ label, n: t.tot[i], p: pctTxt(t.tot[i], t.base) }));
if (q.allow_blank) out.push({ label: "Blanc", n: t.blank, p: "" });
return out;
}
function minutes(poll, voters, qs, now) {
const out = [...header(poll, voters, now)];
qs.forEach((q, k) => {
const t = tally(q), rs = rows(q, t);
const lw = Math.max(...rs.map((r) => width(r.label)));
const nw = Math.max(...rs.map((r) => String(r.n).length));
out.push("", `${nb(qs, k)}${q.text}`);
if (kindNote(q)) out.push(` ${kindNote(q)}`);
for (const r of rs) out.push(` ${padEnd(r.label, lw)} ${padStart(String(r.n), nw)} ${padStart(r.p, 7)}`.trimEnd());
out.push(` ${foot(q, t)}`);
});
return out.join("\n");
}
// no column alignment, survives a paste in an email or a chat
function compact(poll, voters, qs) {
const out = [poll.title];
for (const q of qs) {
const t = tally(q);
const parts = rows(q, t).map((r) => (r.p ? `${r.label} ${r.n} (${r.p})` : `${r.label} ${r.n}`));
out.push("", q.text + (kindNote(q) ? ` (${kindNote(q).toLowerCase()})` : ""),
`${parts.join(" · ")} · ${plural(t.ballots, "bulletin")}`);
}
return out.join("\n");
}
// the long npppav label would eat the whole line
const SHORT = { "ne prend pas part au vote": "NPPPAV" };
function list(poll, voters, qs) {
const out = [poll.title];
for (const q of qs) {
const t = tally(q);
const parts = rows(q, t).map((r) => `${SHORT[r.label.toLowerCase()] || r.label} (${r.n})`);
out.push("", `${q.text} [${plural(t.ballots, "bulletin")}]`, parts.join(" / "));
}
return out.join("\n");
}
function bars(poll, voters, qs) {
const out = [poll.title];
const W = 20;
for (const q of qs) {
const t = tally(q), rs = rows(q, t);
const lw = Math.max(...rs.map((r) => width(r.label)));
out.push("", q.text);
for (const r of rs) {
const full = Math.round((t.base ? r.n / t.base : 0) * W);
const bar = r.p ? "█".repeat(Math.min(W, full)) + "░".repeat(Math.max(0, W - full)) : " ".repeat(W);
out.push(`${padEnd(r.label, lw)} ${bar} ${r.n}${r.p ? ` · ${r.p}` : ""}`);
}
out.push(foot(q, t));
}
return out.join("\n");
}
const mdCell = (s) => String(s).replace(/\|/g, "\\|");
function markdown(poll, voters, qs, now) {
const [title, sub] = header(poll, voters, now);
const out = [`# ${mdCell(title)}`, "", sub];
qs.forEach((q, k) => {
const t = tally(q);
out.push("", `## ${nb(qs, k)}${q.text}`, "");
if (kindNote(q)) out.push(`*${kindNote(q)}*`, "");
out.push("| Réponse | Voix | % |", "| --- | ---: | ---: |");
for (const r of rows(q, t)) out.push(`| ${mdCell(r.label)} | ${r.n} | ${r.p} |`);
out.push("", `${foot(q, t)}.`);
});
return out.join("\n");
}
// semicolons, the decimal comma makes plain commas ambiguous in french spreadsheets
const csvCell = (v) => {
const s = String(v);
return /[;"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
function csv(poll, voters, qs) {
const out = [["n", "question", "réponse", "voix", "dont ajoutées", "% exprimés"]];
qs.forEach((q, k) => {
const t = tally(q);
q.options.forEach((o, i) => out.push([k + 1, q.text, o, t.tot[i], t.extra[i], num(pct(t.tot[i], t.base))]));
if (q.allow_blank) out.push([k + 1, q.text, "Blanc", t.blank, t.exBlank, ""]);
out.push([k + 1, q.text, "Bulletins", t.ballots, t.exBallots, ""]);
});
return out.map((r) => r.map(csvCell).join(";")).join("\n");
}
export const FORMATS = [
{ id: "list", label: "Liste", ext: "txt", mime: "text/plain", build: list },
{ id: "bars", label: "Barres", ext: "txt", mime: "text/plain", build: bars },
{ id: "compact", label: "Compact", ext: "txt", mime: "text/plain", build: compact },
{ id: "pv", label: "Procès-verbal", ext: "txt", mime: "text/plain", build: minutes },
{ id: "md", label: "Markdown", ext: "md", mime: "text/markdown", build: markdown },
{ id: "csv", label: "CSV", ext: "csv", mime: "text/csv", build: csv },
];
// closed questions only (nobody sees open tallies), in the order they were asked
export function exportText(fmt, poll, voters, questions, now) {
const qs = questions.filter((q) => q.state === "closed" && q.results).sort((a, b) => a.id - b.id);
return fmt.build(poll, voters, qs, now);
}
+5
View File
@@ -4,6 +4,8 @@ const cfg = await api("GET", "/api/config").catch(() => ({}));
$("#pw-box").hidden = !cfg.create_password;
$("#codes-on").addEventListener("change", (e) => { $("#codes-box").hidden = !e.target.checked; });
// the classic qr is the camera app code itself
$("#code-style").addEventListener("change", (e) => { $("#camera").disabled = e.target.value !== "ring"; });
$("#form").addEventListener("submit", async (e) => {
e.preventDefault();
@@ -14,6 +16,8 @@ $("#form").addEventListener("submit", async (e) => {
title: $("#title").value,
interval_ms: +$("#interval").value,
scans_required: +$("#scans").value,
code_style: $("#code-style").value,
camera_pass: $("#camera").value === "1",
expected: $("#expected").value ? +$("#expected").value : null,
max_voters: $("#maxv").value ? +$("#maxv").value : null,
require_code: $("#codes-on").checked,
@@ -27,6 +31,7 @@ $("#form").addEventListener("submit", async (e) => {
$("#screen-link").value = screen;
$("#go-admin").href = admin;
$("#go-screen").href = screen;
$("#go-present").href = `${location.origin}/present/${res.id}#${res.admin_key}`;
$("#create").hidden = true;
$("#try-link").hidden = true;
$("#done").hidden = false;
+27
View File
@@ -0,0 +1,27 @@
import { $, h, api, pollId, hashKey, resultsView } from "./common.js";
const pid = pollId();
// the key stays in the address bar so the link can be passed on as is
const key = hashKey();
async function load() {
let data;
try { data = await api("GET", `/api/r/${pid}`, undefined, key); }
catch {
$("#denied").hidden = false;
$("#list").replaceChildren();
return;
}
$("#denied").hidden = true;
$("#title").textContent = data.title;
document.title = `Résultats · ${data.title}`;
const qs = data.questions.sort((a, b) => a.id - b.id);
$("#list").replaceChildren(...(qs.length
? qs.map((q) => h("article", { class: "q" }, h("div", { class: "q-text" }, q.text), resultsView(q)))
: [h("p", { class: "muted" }, "Aucun résultat pour l'instant.")]));
}
load();
// questions get added as the meeting goes on
setInterval(() => { if (!document.hidden) load(); }, 15000);
document.addEventListener("visibilitychange", () => { if (!document.hidden) load(); });
+31 -17
View File
@@ -6,8 +6,11 @@ const WIDE = 960, CROP = 360;
export function makeRingScanner(opts = {}) {
const reader = makeReader(opts);
const wide = document.createElement("canvas"), wctx = wide.getContext("2d", { willReadFrequently: true });
const crop = document.createElement("canvas"), cctx = crop.getContext("2d", { willReadFrequently: true });
// no willReadFrequently: it moves the canvas to the cpu, and drawing a video frame into it then copies and
// scales the whole frame in software (2 s per frame for a 4k stream on a mid-range android). on the gpu the
// scaling is free and only these small canvases are read back
const wide = document.createElement("canvas"), wctx = wide.getContext("2d");
const crop = document.createElement("canvas"), cctx = crop.getContext("2d");
let track = null;
// source px of the square around a code of the given unit
@@ -23,9 +26,12 @@ export function makeRingScanner(opts = {}) {
const seed = { cx: (t.cx - x0) * k - 0.5, cy: (t.cy - y0) * k - 0.5, r: t.unit * CENTER * k, A: t.A && t.A.map((v) => v * k) };
const d = reader.read(grayOf(cctx.getImageData(0, 0, crop.width, crop.height)), now, seed);
if (!d.cand) return null;
// where the code sits in the frame and how big, as fractions: lets the camera zoom in on a small one
const ux = x0 + (d.cand.cx + 0.5) / k, uy = y0 + (d.cand.cy + 0.5) / k, unit = d.cand.r / CENTER / k;
d.where = { x: ux / sw, y: uy / sh, d: (2 * DISC * unit) / Math.min(sw, sh) };
// only a blob with a sync ring keeps the crop alive, anything else goes back to the whole frame
if (!d.token && !d.soft) { track = null; return d; }
track = { cx: x0 + (d.cand.cx + 0.5) / k, cy: y0 + (d.cand.cy + 0.5) / k, unit: d.cand.r / CENTER / k, A: d.cand.A.map((v) => v / k), at: now };
track = { cx: ux, cy: uy, unit, A: d.cand.A.map((v) => v / k), at: now };
return d;
}
@@ -37,20 +43,28 @@ export function makeRingScanner(opts = {}) {
if (d) return d;
}
track = null;
// phones held upright hand over a 1080x1920 stream
const k = Math.min(1, WIDE / Math.max(sw, sh));
wide.width = Math.round(sw * k); wide.height = Math.round(sh * k);
// plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 5 });
let last = null;
for (const c of cands) {
const d = readAt(src, sw, sh, { cx: (c.cx + 0.5) / k, cy: (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
const r = search(src, sw, sh, now, 0, 0, sw, sh);
if (r.token || r.found) return r;
// nothing in the whole view: the back rows see a ring too small to find on the reduced copy. look at the
// middle, where people aim, at twice the detail. same as zooming in, without moving the preview
return search(src, sw, sh, now, sw / 4, sh / 4, sw / 2, sh / 2);
},
};
// finds discs in the region x0 y0 w h of the frame (on a copy of at most WIDE px), reads them at full resolution
function search(src, sw, sh, now, x0, y0, w, h) {
const k = Math.min(1, WIDE / Math.max(w, h));
wide.width = Math.round(w * k); wide.height = Math.round(h * k);
// plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, x0, y0, w, h, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 5 });
let last = null;
for (const c of cands) {
const d = readAt(src, sw, sh, { cx: x0 + (c.cx + 0.5) / k, cy: y0 + (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
}
}
+98 -16
View File
@@ -1,8 +1,10 @@
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js";
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, pct } from "./common.js";
import { render as drawRing, DISC } from "./ringcode.js";
const pid = pollId();
const key = takeKey(`rv_screen_${pid}`);
// /present/: duplicated screen, the laptop shows what the projector shows. admin key, admin in a drawer
const present = location.pathname.startsWith("/present/");
const key = takeKey(present ? `rv_present_${pid}` : `rv_screen_${pid}`);
let st = null;
let qr = null; // current code message, qr or ring
let raf = 0;
@@ -30,23 +32,70 @@ function replay(el, cls) {
el.classList.add(cls);
}
// the entry qr jumps between the corner and the big spot: slide and grow it from where it was (flip)
function flip(el, before) {
if (!before || el.hidden || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const after = el.getBoundingClientRect();
if (!after.width || !after.height) return;
const dx = before.left - after.left, dy = before.top - after.top, sx = before.width / after.width, sy = before.height / after.height;
if (Math.abs(dx) < 2 && Math.abs(dy) < 2 && Math.abs(sx - 1) < 0.02 && Math.abs(sy - 1) < 0.02) return;
el.animate([
{ transformOrigin: "0 0", transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` },
{ transformOrigin: "0 0", transform: "none" },
], { duration: 600, easing: "cubic-bezier(.2, .7, .2, 1)" });
}
function layout() {
if (!st) return;
const entryEl = $("#entry");
const before = !entryEl.hidden && !entryEl.classList.contains("leaving") ? entryEl.getBoundingClientRect() : null;
// qr stays up while enrolling, and during a vote that needs a presence scan
const qrOn = st.enrollment_open || st.presence;
const focus = st.focus;
const ring = st.code_style === "ring";
// the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does
const cam = st.camera_pass !== false;
const entryOn = !!(ring && entry && (st.enrollment_open || (cam && st.presence)));
// with the big qr on, a vote waiting for scans (or closed with nothing to show) moves above it
const f = st.focus, idleVote = f && f.state === "closed" && !f.results;
// an upright screen has no room for the question above the qr (.entry-q hidden): it keeps its own block
const openVote = cam && f && f.state === "open" && st.presence && !matchMedia("(max-aspect-ratio: 1/1)").matches;
const big = entryOn && st.entry_big && (!f || idleVote || openVote);
const focus = big ? null : f;
reveal($("#enroll"), qrOn);
reveal($("#focus"), !!focus);
reveal($("#idle"), !qrOn && !focus);
$(".s-main").classList.toggle("split", qrOn && !!focus);
const ring = st.code_style === "ring";
document.body.classList.toggle("split-on", qrOn && !!focus);
// a vote waiting for presence scans takes the title, even while late arrivals can still enroll
$("#qr-title").textContent = st.presence || !st.enrollment_open ? (ring ? "Visez le cercle pour voter" : "Scannez pour voter") : "Inscription";
$("#qr-steps").hidden = !st.enrollment_open;
// rings can't be opened by the camera app, so a small fixed qr leads to the page
$("#step1").textContent = ring ? "Ouvrez la page de vote" : "Scannez ce code";
reveal($("#entry"), !!(ring && st.enrollment_open && entry));
$("#step1").textContent = ring ? (cam ? "Scannez le QR avec l'appareil photo" : "Ouvrez la page de vote") : "Scannez avec l'appareil photo";
$("#step2").hidden = !ring;
reveal($("#entry"), entryOn);
document.body.classList.toggle("has-entry", entryOn);
document.body.classList.toggle("entry-big", big);
const showQ = big && !!f;
document.body.classList.toggle("entry-q-on", showQ);
$("#entry-q").hidden = !showQ;
// an open vote keeps its options and turnout bar on screen, just above the qr
const opts = showQ && !!openVote;
document.body.classList.toggle("entry-opts-on", opts);
$("#entry-q-opts").hidden = !opts;
$("#entry-q-turnout").hidden = !opts;
$("#entry-q-count").hidden = opts;
if (showQ) {
$("#entry-q-text").textContent = f.text;
if (opts) {
const ul = $("#entry-q-opts"), key = JSON.stringify(f.options);
if (ul.dataset.key !== key) { ul.dataset.key = key; ul.replaceChildren(...f.options.map((o) => h("li", {}, o))); }
paintTurnout($("#entry-q-turnout"), f);
} else {
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
}
}
$("#entry-hint").textContent = cam ? "Scannez avec l'appareil photo" : big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?";
$(".qr-wrap").classList.toggle("ring", ring);
flip(entryEl, before);
}
function render() {
@@ -63,13 +112,10 @@ function render() {
const f = st.focus;
const box = $("#focus");
const view = f ? `${f.id}|${f.state}|${f.results ? 1 : 0}|${f.text}` : "";
const view = f ? `${f.id}|${f.state}|${f.results ? JSON.stringify(f.results) : 0}|${f.text}` : "";
if (f && view === focusView && f.state === "open") {
// same question still open: only the turnout moves, in place so the bar slides
const t = box.querySelector(".turnout");
t.querySelector("b").textContent = f.participants;
t.querySelector(".t-of").textContent = ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`;
t.querySelector(".progress > div").style.width = `${pct(f.participants, st.voters)}%`;
paintTurnout(box.querySelector(".turnout"), f);
} else if (view !== focusView) {
focusView = view;
if (f) {
@@ -78,9 +124,9 @@ function render() {
if (f.state === "open") {
box.append(
h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))),
h("div", { class: "turnout" },
h("b", {}, f.participants), h("span", { class: "t-of" }, ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`),
h("div", { class: "progress" }, fill(pct(f.participants, st.voters), ""))),
paintTurnout(h("div", { class: "turnout" },
h("b", {}), h("span", { class: "t-of" }),
h("div", { class: "progress" }, h("div", {}), h("div", { class: "p-extra" }))), f),
);
} else if (f.results) {
box.append(resultsView(f));
@@ -93,6 +139,18 @@ function render() {
layout();
}
// "9 votes sur 10, dont 3 ajoutés": hand-added votes count in, and show hatched at the end of the bar
function paintTurnout(t, f) {
const extra = f.extra_ballots || 0, all = f.participants + extra, of = st.voters + extra;
t.querySelector("b").textContent = all;
t.querySelector(".t-of").textContent = ` vote${all > 1 ? "s" : ""} sur ${of}` +
(extra ? `, dont ${extra} ajouté${extra > 1 ? "s" : ""}` : "");
const [phone, added] = t.querySelectorAll(".progress > div");
phone.style.width = `${pct(f.participants, of)}%`;
added.style.width = `${pct(extra, of)}%`;
return t;
}
function paintQR() {
if (!qr || qr.type !== "qr") return;
const c = $("#qr");
@@ -134,7 +192,7 @@ function animateTick() {
}
let skew = 0;
window.addEventListener("resize", paintQR);
window.addEventListener("resize", () => { paintQR(); layout(); });
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
@@ -182,3 +240,27 @@ liveSocket(`/ws/${pid}/screen`, {
if (s !== "online") { qr = null; const cv = $("#qr"); cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); }
},
});
if (present) {
const btn = h("button", { class: "small ctl-btn", type: "button", "aria-expanded": "false" }, "Gérer");
const close = h("button", { class: "small", type: "button" }, "Fermer");
const drawer = h("aside", { class: "ctl", "aria-label": "Gestion du scrutin" },
h("div", { class: "ctl-head" }, h("b", {}, "Gestion"), close));
document.body.append(drawer);
$(".s-tools").prepend(btn);
const toggle = (open) => {
// the admin page loads on first open only, and keeps its state when the drawer closes
if (open && !drawer.querySelector("iframe")) {
drawer.append(h("iframe", { src: `/admin/${pid}#${encodeURIComponent(key)}`, title: "Administration" }));
}
// the projection folds into the room the drawer leaves, the entry qr slides along
const entryEl = $("#entry"), before = entryEl.hidden ? null : entryEl.getBoundingClientRect();
drawer.classList.toggle("open", open);
document.body.classList.toggle("ctl-open", open);
btn.setAttribute("aria-expanded", String(open));
flip(entryEl, before);
};
btn.addEventListener("click", () => toggle(!drawer.classList.contains("open")));
close.addEventListener("click", () => toggle(false));
document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggle(false); });
}
+245 -31
View File
@@ -5,9 +5,18 @@ 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}`;
const ARRIVED_KEY = `rv_arrived_${pid}`;
const VIA_QR = "Avec la caméra native via le QR";
// 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 camPass = true; // organizers can turn the camera app way off
let scanner = null;
let required = 5;
@@ -50,6 +59,25 @@ 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.hidden = !camPass;
el.classList.toggle("solo", solo);
if (!solo) {
el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Rouvrez votre scanneur de code QR et scannez le grand QR."));
return;
}
// "re-open": the same scanner that brought them here, not something new to find
// the vote dialog has the heading in its own title
el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Confirmez avec votre scanneur de code QR"),
h("ol", {},
h("li", {}, "Rouvrez votre scanneur de code QR, celui qui vous a amené·e ici."),
h("li", {}, "Scannez le grand QR de l'écran."),
// joining only takes a code that left the screen less than 4 s ago
h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez tout de suite le lien qui s'affiche. Vous êtes inscrit·e.")));
}
async function startScanner() {
if (scanner) return;
if (!window.isSecureContext) {
@@ -61,6 +89,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,8 +98,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;
scanMsg("Autorisez la caméra puis réessayez.", "bad");
$("#start-cam").className = "link";
$("#start-cam").textContent = "Réessayer la caméra";
scanMsg(camError(e), "bad");
camAlt($("#enroll-alt"), true);
}
}
// what blocked the camera. no settings walkthrough: the camera app path below works without them
function camError(e) {
switch (e && e.name) {
case "NotAllowedError":
case "SecurityError":
return "Ce navigateur n'a pas accès à la caméra.";
case "NotReadableError":
case "AbortError":
return "Caméra occupée ou bloquée par le téléphone.";
case "NotFoundError":
case "OverconstrainedError":
return "Aucune caméra trouvée.";
default:
return "Caméra indisponible.";
}
}
@@ -77,7 +129,7 @@ async function startScanner() {
// 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 canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
const rings = makeRingScanner();
async function loop() {
if (!running) return;
@@ -86,8 +138,10 @@ function makeScanner(video, onToken, onOther) {
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);
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);
@@ -104,14 +158,49 @@ function makeScanner(video, onToken, onOther) {
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));
video.parentElement.append(swap);
// 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
s.getVideoTracks()[0]?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
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;
@@ -146,15 +235,17 @@ function makeScanner(video, onToken, onOther) {
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() { swap.remove(); },
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, ask for the full sensor
// 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({
@@ -177,12 +268,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() {
@@ -196,7 +288,53 @@ 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(true);
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;
case "late":
toast("Lien ouvert trop tard. Rescannez et touchez le lien tout de suite.", "bad");
break;
}
}
function submitToken(token) {
@@ -238,17 +376,17 @@ function handleScan(r) {
}
}
function enrolled() {
function enrolled(viaCam = false) {
stopScanner();
lsSet(DONE_KEY, "1");
navigator.vibrate?.([40, 60, 40]);
celebrate("Inscription validée");
celebrate("Inscription validée", viaCam ? VIA_QR : "");
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) {
function mark(withTick) {
const svg = document.createElementNS(MARK_NS, "svg");
svg.setAttribute("viewBox", "0 0 32 32");
svg.setAttribute("aria-hidden", "true");
@@ -263,11 +401,18 @@ function celebrate(text) {
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));
svg.append(g);
if (withTick) svg.append(tick);
return svg;
}
function celebrate(text, sub = "") {
const el = h("div", { class: "celebrate", role: "status" }, mark(true), h("p", {}, text), sub ? h("small", {}, sub) : "");
document.body.append(el);
setTimeout(() => el.classList.add("out"), 1300);
setTimeout(() => el.remove(), 1700);
// a second line takes longer to read
const hold = sub ? 2000 : 1300;
setTimeout(() => el.classList.add("out"), hold);
setTimeout(() => el.remove(), hold + 400);
}
$("#start-cam").addEventListener("click", startScanner);
@@ -322,6 +467,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();
@@ -388,17 +535,34 @@ 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
if (camPass) 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é");
// no codes sent while some were due: the camera app scan covered it
celebrate("Vote enregistré", !presence && lastState.vote_scans > 0 ? VIA_QR : "");
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");
@@ -407,16 +571,34 @@ 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 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();
got.push(t);
seenAt.set(t, now);
paint();
navigator.vibrate?.(15);
if (got.length >= n) setTimeout(() => finish(got), FILL_MS);
@@ -426,13 +608,25 @@ 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 });
sc.start().catch(() => { $("#p-msg").textContent = "Autorisez la caméra puis réessayez."; });
// no camera here: the camera app opens a new tab that sends the kept choice
sc.start().catch((e) => {
$("#p-scan").hidden = true;
if (!camPass) {
// no camera and no camera app way: the desk can still count this vote by hand (votes en plus)
$("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`;
return;
}
$("#p-title").textContent = "Validez avec votre scanneur de code QR";
$("#p-msg").textContent = camError(e);
camAlt($("#p-alt"), true, true);
});
return result;
}
@@ -449,6 +643,7 @@ function connect() {
lastJson = j;
show("#v-vote");
$("#title").textContent = msg.title;
camPass = msg.camera_pass !== false;
renderVote(msg);
}
else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); }
@@ -473,6 +668,8 @@ async function boot() {
}
$("#title").textContent = me.title;
document.title = me.title;
camPass = me.camera_pass !== false;
camAlt($("#enroll-alt"), $("#enroll-alt").classList.contains("solo"));
if (me.enrolled) {
lsSet(DONE_KEY, "1");
show("#v-vote");
@@ -485,14 +682,31 @@ 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() {
await boot();
// the scan that brings someone here only opens the page: joining takes the ring, or a second scan
const arrived = +lsGet(ARRIVED_KEY) > Date.now() - 3 * 3600e3;
if (claim && (lastState || arrived)) {
// the check takes a few ms: held a second so people see their scan was taken and checked
const wait = h("div", { class: "celebrate verifying", role: "status" }, mark(false), h("p", {}, "Vérification"));
document.body.append(wait);
const [r] = await Promise.all([redeem({ claim }), new Promise((res) => setTimeout(res, 1000))]);
wait.remove();
afterPass(r);
}
else if (camExpired) afterPass({ status: "expired" });
if (!lastState) lsSet(ARRIVED_KEY, String(Date.now()));
}
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();
+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RotatyVote · Résultats</title>
<link rel="icon" href="/static/img/mark.svg" type="image/svg+xml">
<link rel="stylesheet" href="/static/css/app.css">
<script type="module" src="/static/js/results.js"></script>
</head>
<body>
<main class="wrap narrow results-page">
<div class="topbar">
<span class="brand"><img src="/static/img/mark.svg" alt=""><span>rotaty<b>vote</b></span></span>
</div>
<h1 id="title">Résultats</h1>
<p id="denied" class="notice bad" hidden>Lien invalide ou désactivé.</p>
<div id="list"></div>
</main>
</body>
</html>
+1
View File
@@ -12,3 +12,4 @@ html, body { margin: 0; height: 100%; background: #f5f6fa; color: #1c2036; font:
button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; }
button.ghost { background: #fff; }
.hist { font-size: 14px; color: #4a4f66; }
#shot { width: 100%; border-radius: 12px; margin-top: 12px; }
+4
View File
@@ -13,8 +13,12 @@
<div>Images lues<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></div>
<div>Flux caméra<b id="res">-</b></div>
<div>Temps de calcul<b id="ms">-</b></div>
</div>
<button id="go">Démarrer la caméra</button>
<button id="snap" class="ghost">Enregistrer l'image vidéo</button>
<button id="again" class="ghost">Nouvel essai</button>
<p class="hist" id="hist"></p>
<img id="shot" alt="Image vidéo enregistrée" hidden>
</main></body></html>
+27 -3
View File
@@ -3,9 +3,9 @@ import { makeRingScanner } from "/static/js/ringscan.js";
const rings = makeRingScanner();
const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
let tokens = new Set(), mode = "aucun";
let tokens = new Set(), mode = "aucun", msAvg = 0;
const history = [];
function reset() {
@@ -15,9 +15,12 @@ function reset() {
async function start() {
engine = await QrScanner.createQrEngine();
// same request as the vote page, so what this page measures is what voters get
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
});
const set = stream.getVideoTracks()[0].getSettings();
$("res").textContent = `${set.width}×${set.height} ${set.frameRate ? Math.round(set.frameRate) + " i/s" : ""}`;
video.srcObject = stream;
await video.play();
running = true;
@@ -34,7 +37,9 @@ async function loop() {
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++;
const d = rings.scan(video, video.videoWidth, video.videoHeight);
const ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight);
msAvg = msAvg ? msAvg * 0.9 + (performance.now() - ts) * 0.1 : performance.now() - ts;
$("ms").textContent = `${Math.round(msAvg)} ms`;
if (d.cand) qr++;
if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); }
else if (mode !== "anneaux") {
@@ -63,3 +68,22 @@ async function loop() {
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
$("again").addEventListener("click", reset);
// one raw frame of the stream as the decoder sees it, to send back when a phone can't read the ring.
// built and clicked in the same tap: android drops a download started after an async step (toBlob)
$("snap").addEventListener("click", () => {
if (!video.videoWidth) return;
const c = document.createElement("canvas");
c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext("2d").drawImage(video, 0, 0);
const url = c.toDataURL("image/jpeg", 0.95);
const a = document.createElement("a");
a.href = url;
a.download = `rotatyvote-frame-${video.videoWidth}x${video.videoHeight}-${Date.now()}.jpg`;
document.body.append(a);
a.click();
a.remove();
// fallback: long press the picture to save it
$("shot").src = url;
$("shot").hidden = false;
});
+15 -5
View File
@@ -33,12 +33,8 @@
<h2 id="qr-title">Inscription</h2>
<ol id="qr-steps">
<li><span id="step1">Scannez ce code</span></li>
<li><span>Visez l'écran <b id="secs">5</b>&nbsp;s</span></li>
<li id="step2"><span>Visez le cercle <b id="secs">5</b>&nbsp;s</span></li>
</ol>
<div id="entry" class="entry" hidden>
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
<div><b>Pas encore sur la page ?</b><span id="entry-url"></span></div>
</div>
<p id="url-warn" class="notice warn" hidden></p>
</div>
</section>
@@ -51,6 +47,20 @@
</section>
</main>
<aside id="entry" class="entry" hidden>
<div id="entry-q" class="entry-q" hidden>
<b id="entry-q-text"></b>
<ul id="entry-q-opts" class="entry-opts" hidden></ul>
<span id="entry-q-count"></span>
<div id="entry-q-turnout" class="turnout" hidden>
<b></b><span class="t-of"></span>
<div class="progress"><div></div><div class="p-extra"></div></div>
</div>
</div>
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
<div><b id="entry-hint">Scannez avec l'appareil photo</b><span id="entry-url"></span></div>
</aside>
<footer class="s-foot">
<div class="s-count"><b id="voters">0</b> <span id="voters-label">inscriptions</span></div>
</footer>
+7 -3
View File
@@ -28,6 +28,7 @@
<video id="video" playsinline muted></video>
</div>
<p id="scan-msg" class="scan-msg muted"></p>
<div id="enroll-alt" class="cam-alt"></div>
<button id="start-cam" class="primary block" type="button">Activer la caméra</button>
<button id="no-cam" class="link" type="button">Caméra indisponible ?</button>
</div>
@@ -84,10 +85,13 @@
</dialog>
<dialog id="presence">
<h2 tabindex="-1" autofocus>Visez l'écran</h2>
<div id="p-ring" class="dots"></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
<h2 id="p-title" tabindex="-1" autofocus>Visez le cercle</h2>
<div id="p-scan">
<div id="p-ring" class="dots"></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
</div>
<p id="p-msg" class="scan-msg bad"></p>
<div id="p-alt" class="cam-alt"></div>
<div class="actions"><button id="p-cancel" type="button">Annuler</button></div>
</dialog>
</body>
+177 -32
View File
@@ -35,7 +35,8 @@ def server(tmp_path_factory):
port = free_port()
tmp = tmp_path_factory.mktemp("db")
db = tmp / "test.db"
env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1"}
env = {**os.environ, "PORT": str(port), "HOST": "127.0.0.1", "DB_PATH": str(db), "PUBLIC_URL": "", "HEARTBEAT_S": "1",
"PASS_HOLD_MS": "1500"}
scheme, wscheme, ws_kw = "http", "ws", {}
if TLS:
cert, key = tmp / "cert.pem", tmp / "key.pem"
@@ -168,7 +169,8 @@ def test_full_flow_and_anonymity(server):
assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200
q = admin(server, p, "GET", "").json()["questions"][0]
assert q["results"] == {"counts": [1, 0], "blank": 1, "ballots": 2}
assert q["results"] == {"counts": [1, 0], "blank": 1, "ballots": 2,
"extra": {"counts": [0, 0], "blank": 0, "ballots": 0}}
r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})
assert r.status_code == 409 and r.json()["error"] == "not_open"
@@ -200,8 +202,8 @@ def test_full_flow_and_anonymity(server):
assert con.execute("SELECT COUNT(*) FROM participation").fetchone()[0] >= 2
def test_stale_duplicate_and_forged_tokens(server):
p = create(server, scans_required=3, code_style="qr")
def test_duplicate_token_counts_once(server):
p = create(server, scans_required=3)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
@@ -210,25 +212,8 @@ def test_stale_duplicate_and_forged_tokens(server):
tok = await next_token()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and r["accepted"]
# same code twice does not count twice
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and not r["accepted"]
# forged mac
slot = tok.split(".")[0]
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"{int(slot) + 1}.AAAAAAAAAAAA"})).json()
assert not r["valid"] and r["count"] == 1
# replaying an old photo of the screen
old = await next_token()
await asyncio.sleep(3.2)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": old})).json()
assert not r["valid"]
# a token from another poll is useless here
other = create(server)
admin(server, other, "PATCH", "", json={"enrollment_open": True})
async with projector(server, other) as other_next:
ot = await other_next()
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": ot})).json()
assert not r["valid"]
await c.aclose()
asyncio.run(run())
@@ -454,8 +439,7 @@ def test_behind_proxy(proxied):
entry = m
if m["type"] == "qr":
break
assert m["url"].startswith(f"https://vote.example.org/v/{p['id']}#")
assert entry["url"] == f"https://vote.example.org/v/{p['id']}"
assert m["url"] == entry["url"] == f"https://vote.example.org/v/{p['id']}"
await ws.close()
# browser origin is the public host, not the rewritten Host: must pass the origin check
v = await websockets.connect(f"{proxied['ws']}/ws/{p['id']}/voter", origin="https://vote.example.org",
@@ -518,9 +502,10 @@ def test_vote_needs_fresh_presence_scans(server):
await asyncio.sleep(3.5) # photo of the screen taken earlier
r = await a.post(url, json={"question_id": qid, "choices": [0], "presence": old})
assert r.json()["error"] == "presence_required"
fresh = [await next_token() for _ in range(3)]
r = await a.post(url, json={"question_id": qid, "choices": [1], "presence": fresh})
assert r.status_code == 200
# slow phone: two codes read a while ago and one just now, all distinct, counts
mixed = old[1:] + [await next_token()]
r = await a.post(url, json={"question_id": qid, "choices": [1], "presence": mixed})
assert r.status_code == 200, r.text
await a.aclose()
asyncio.run(run())
@@ -626,7 +611,7 @@ def test_heartbeat_survives_dead_client(server):
asyncio.run(run())
def test_ring_tokens_stale_forged_and_cross_format(server):
def test_ring_tokens_stale_and_forged(server):
from rotatyvote import tokens as tk
p = create(server, scans_required=3, code_style="ring")
admin(server, p, "PATCH", "", json={"enrollment_open": True})
@@ -641,12 +626,10 @@ def test_ring_tokens_stale_forged_and_cross_format(server):
assert tok.startswith("r")
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tok})).json()
assert r["count"] == 1 and r["accepted"]
# the same slot in the classic format is the same code: counted once
s16 = int(tok[1:].split(".")[0])
now = tk.current_slot(iv)
full = next(s for s in range(now, now - 10, -1) if s & 0xFFFF == s16)
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tk.make_token(secret, p["id"], iv, full)})).json()
assert r["valid"] and not r["accepted"] and r["count"] == 1
# a camera app code is not a ring code
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": tk.make_pass(secret, p["id"], 1)})).json()
assert not r["valid"]
# forged mac, malformed
r = (await c.post(f"/api/v/{p['id']}/scan", json={"token": f"r{s16}.00000000"})).json()
assert not r["valid"]
@@ -707,3 +690,165 @@ def test_trial_enrolls_then_expires(server):
assert con.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (p["id"],)).fetchone()[0] == 0
con.close()
assert httpx.get(f"{server['base']}/screen/{p['id']}", verify=server["verify"]).status_code == 404
def test_hand_added_votes(server):
p = create(server, vote_scans=0)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
async with projector(server, p) as next_token:
a = await enroll(server, p, next_token)
qid = admin(server, p, "POST", "/questions", json={"text": "Q", "options": ["A", "B"], "open": True}).json()["id"]
assert (await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})).status_code == 200
# paper ballots counted at the desk
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [2, 5], "blank": 1}).status_code == 200
q = admin(server, p, "GET", "").json()["questions"][0]
assert q["extra_ballots"] == 8 and q["extra"] == {"counts": [2, 5], "blank": 1, "ballots": 8}
assert "results" not in q # still open: no tally, hand-added or not
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [1]}).status_code == 400
assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [-1, 0]}).status_code == 400
admin(server, p, "POST", f"/questions/{qid}/close")
r = admin(server, p, "GET", "").json()["questions"][0]["results"]
# phone ballots and hand-added ones stay apart
assert r["counts"] == [1, 0] and r["ballots"] == 1 and r["extra"]["counts"] == [2, 5]
await a.aclose()
asyncio.run(run())
def test_duplicated_screen_page(server):
p = create(server)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
r = httpx.get(f"{server['base']}/present/{p['id']}", verify=server["verify"])
assert r.status_code == 200
# the admin page may only be framed by the site itself (duplicated screen drawer)
assert r.headers["x-frame-options"] == "SAMEORIGIN" and "frame-ancestors 'self'" in r.headers["content-security-policy"]
assert httpx.get(f"{server['base']}/present/nopenope", verify=server["verify"]).status_code == 404
async def run():
# the duplicated screen talks to the projector socket with the admin key
async with projector(server, p, key=p["admin_key"]) as next_token:
assert (await next_token()) is not None
asyncio.run(run())
async def camera_code(server, p, kind="entry"):
"""the code the camera app would read off the projector right now"""
ws = await websockets.connect(f"{server['ws']}/ws/{p['id']}/screen", **server["ws_kw"])
await ws.send(json.dumps({"key": p["screen_key"]}))
while True:
m = json.loads(await asyncio.wait_for(ws.recv(), 5))
if m["type"] == kind:
await ws.close()
return m
def test_camera_app_scan_enrolls_and_covers_votes(server):
from rotatyvote import tokens as tk
p = create(server, scans_required=5, vote_scans=3)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
e = await camera_code(server, p)
assert len(e["modules"]) == 33
a = device(server)
r = await a.get(f"/V/{p['id'].upper()}/{e['token'].upper()}", follow_redirects=False)
assert r.status_code == 303 and "no-store" in r.headers["cache-control"]
loc = r.headers["location"]
assert loc.startswith(f"/v/{p['id']}#c=")
claim = loc.split("#c=")[1]
# one scan is enough to enroll, the claim is single use
assert (await a.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "enrolled"
b = device(server)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"claim": claim})).json()["status"] == "expired"
url = f"/api/v/{p['id']}/vote"
q1 = admin(server, p, "POST", "/questions", json={"text": "Q1", "options": ["A", "B"], "open": True}).json()["id"]
# the scan that enrolled also covers a vote right after
assert (await a.post(url, json={"question_id": q1, "choices": [0]})).status_code == 200
await asyncio.sleep(1.6)
admin(server, p, "POST", f"/questions/{q1}/close")
q2 = admin(server, p, "POST", "/questions", json={"text": "Q2", "options": ["A", "B"], "open": True}).json()["id"]
r = await a.post(url, json={"question_id": q2, "choices": [1]})
assert r.json()["error"] == "presence_required"
# rescan with the camera app (or the page's camera on the classic qr): the code itself
e = await camera_code(server, p)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "pass"
assert (await a.post(url, json={"question_id": q2, "choices": [1]})).status_code == 200
# forged, malformed, other poll, stale
bad = await a.get(f"/V/{p['id']}/{e['slot']}-AAAAAAAAAA", follow_redirects=False)
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
bad = await a.get(f"/V/{p['id']}/%C3%A9-%C3%A9", follow_redirects=False)
assert bad.headers["location"] == f"/v/{p['id']}#cam=expired"
other = create(server)
admin(server, other, "PATCH", "", json={"enrollment_open": True})
oe = await camera_code(server, other)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": oe["token"]})).json()["status"] == "expired"
con = sqlite3.connect(server["db"])
secret = con.execute("SELECT secret FROM polls WHERE id=?", (p["id"],)).fetchone()[0]
con.close()
stale = tk.make_pass(secret, p["id"], e["slot"] - 6)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": stale})).json()["status"] == "expired"
# gone from the screen 6 s ago: too late to join (4 s), still fine for a vote (12 s)
recent = tk.make_pass(secret, p["id"], tk.current_slot(3000) - 3)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "late"
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": recent})).json()["status"] == "pass"
# late arrival after enrollment closed: nothing to do here
admin(server, p, "PATCH", "", json={"enrollment_open": False})
e = await camera_code(server, p)
assert (await b.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "closed"
for x in (a, b):
await x.aclose()
asyncio.run(run())
def test_camera_app_scan_then_paper_code(server):
p = create(server, require_code=True, codes=2)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
code = admin(server, p, "GET", "/codes").json()["codes"][0]["code"]
async def run():
e = await camera_code(server, p)
a = device(server)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "need_code"
assert (await a.get(f"/api/v/{p['id']}/me")).json()["need_code"]
assert (await a.post(f"/api/v/{p['id']}/code", json={"code": code})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
def test_classic_qr_is_the_camera_code(server):
p = create(server, code_style="qr", vote_scans=2)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
async def run():
m = await camera_code(server, p, "qr")
assert m["interval_ms"] == 3000 and len(m["modules"]) == 33
a = device(server)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": m["token"]})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
def test_camera_app_scan_can_be_turned_off(server):
p = create(server, camera_pass=False)
admin(server, p, "PATCH", "", json={"enrollment_open": True})
assert admin(server, p, "GET", "").json()["poll"]["camera_pass"] is False
async def run():
e = await camera_code(server, p)
assert "token" not in e and len(e["modules"]) == 29
a = device(server)
r = await a.get(f"/V/{p['id']}/1-AAAAAAAAAA", follow_redirects=False)
assert r.headers["location"] == f"/v/{p['id']}"
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": "1-AAAAAAAAAA"})).json()["status"] == "off"
admin(server, p, "PATCH", "", json={"camera_pass": True})
e = await camera_code(server, p)
assert (await a.post(f"/api/v/{p['id']}/pass", json={"token": e["token"]})).json()["status"] == "enrolled"
await a.aclose()
asyncio.run(run())
+2 -1
View File
@@ -136,7 +136,8 @@ def neg_trials(n):
def seqs(n):
r = random.Random(47)
out = []
for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], [15, 7]):
fpss = [int(x) for x in os.environ.get("FPS", "15,7").split(",")]
for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], fpss):
for _ in range(n):
s = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
iv = int(os.environ.get("IV", "500"))