Compare commits
77
Commits
01ea45a29a
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
339cf97df1 | ||
|
|
98d8199ffd | ||
|
|
41b4ac1a78 | ||
|
|
3ebbb67817 | ||
|
|
28b255e41b | ||
|
|
a30618e74c | ||
|
|
d945c801f7 | ||
|
|
e1d8283f66 | ||
|
|
450d923e78 | ||
|
|
cc1c46da6b | ||
|
|
74a294a2d1 | ||
|
|
85ff0d6507 | ||
|
|
c924107f1d | ||
|
|
ad6c3c6f57 | ||
|
|
cbc8fe9e98 | ||
|
|
0697c27a01 | ||
|
|
d761d8b510 | ||
|
|
70d09b1008 | ||
|
|
7765f22f61 | ||
|
|
3c1f897f7a | ||
|
|
4e63c73904 | ||
|
|
ef4232d04e | ||
|
|
597c5e5cc2 | ||
|
|
7266fe1b47 | ||
|
|
553af09df4 | ||
|
|
3efb80b802 | ||
|
|
fbc12f84d9 | ||
|
|
983c3ec52e | ||
|
|
98cf8e5f6d | ||
|
|
9308b875b5 | ||
|
|
101703790b | ||
|
|
a28971e36d | ||
|
|
cd693d1a7c | ||
|
|
389572d09e | ||
|
|
080f516f53 | ||
|
|
8a4d088392 | ||
|
|
867f6c46b9 | ||
|
|
4c8db53aac | ||
|
|
7a29a171e1 | ||
|
|
f3c966563e | ||
|
|
741b6ff302 | ||
|
|
d82d30b5eb | ||
|
|
a9a645ce1c | ||
|
|
9fca6d81cc | ||
|
|
4be51e1ae1 | ||
|
|
aac778ceba | ||
|
|
13d42db0a3 | ||
|
|
b4a110abe3 | ||
|
|
b0cec39d6e | ||
|
|
60f5cffe08 | ||
|
|
1992397659 | ||
|
|
c755ed3c5a | ||
|
|
31005975f6 | ||
|
|
b314f01efc | ||
|
|
e677e270fd | ||
|
|
1d6028715b | ||
|
|
c96f9b42c1 | ||
|
|
ca1a73e0bb | ||
|
|
05cfa36e5b | ||
|
|
418e7667e5 | ||
|
|
d7047442b5 | ||
|
|
7cbf62baa7 | ||
|
|
c6934080f1 | ||
|
|
55b5a53642 | ||
|
|
131c902bf3 | ||
|
|
a6b4b44478 | ||
|
|
d507190b11 | ||
|
|
07137d8b15 | ||
|
|
243e64aa98 | ||
|
|
bfc8d30eaa | ||
|
|
38ef607506 | ||
|
|
9880e7c26c | ||
|
|
4650db4b40 | ||
|
|
fca4a1194e | ||
|
|
254a84e822 | ||
|
|
d44931269e | ||
|
|
72273d5b06 |
@@ -7,3 +7,4 @@ __pycache__/
|
||||
.claude/
|
||||
docs/video/
|
||||
tools/bench_out/
|
||||
static/ringlab/tmp/
|
||||
|
||||
+1
-1
@@ -30,4 +30,4 @@ RV_TEST_TLS=1 uv run pytest
|
||||
2. Les deux suites de tests passent (HTTP et TLS).
|
||||
3. Décrivez ce qui change et comment vous l'avez vérifié.
|
||||
|
||||
En contribuant, vous acceptez que votre code soit publié sous licence MIT.
|
||||
En contribuant, vous acceptez que votre code soit publié sous la licence du projet : MIT avec la condition Commons Clause (voir [LICENSE](LICENSE)).
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
"Commons Clause" License Condition v1.0
|
||||
|
||||
The Software is provided to you by the Licensor under the License, as defined
|
||||
below, subject to the following condition.
|
||||
|
||||
Without limiting other conditions in the License, the grant of rights under the
|
||||
License will not include, and the License does not grant to you, the right to
|
||||
Sell the Software.
|
||||
|
||||
For purposes of the foregoing, "Sell" means practicing any or all of the rights
|
||||
granted to you under the License to provide to third parties, for a fee or
|
||||
other consideration (including without limitation fees for hosting or
|
||||
consulting/support services related to the Software), a product or service
|
||||
whose value derives, entirely or substantially, from the functionality of the
|
||||
Software. Any license notice or attribution required by the License must also
|
||||
include this Commons Clause License Condition notice.
|
||||
|
||||
Software: RotatyVote
|
||||
License: MIT
|
||||
Licensor: Showdown76py
|
||||
|
||||
---
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Showdown76py
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# RotatyVote
|
||||
# rotatyvote
|
||||
|
||||
Vote anonyme en présentiel. Un QR code projeté change toutes les 0,5 à 2 s. Pour s'inscrire, le téléphone doit en lire plusieurs à la suite (5 par défaut), ce qui oblige à être devant l'écran.
|
||||
**rotaty**vote est une app web qui permet d'effectuer des votes anonymes, en s'assurant que la personne est présente physiquement. Un code scannable dynamique est projeté au tableau. Pour s'inscrire, le téléphone effectue plusieurs lectures. Le code ne peut pas être partagé en photo ou vidéo.
|
||||
|
||||

|
||||
|
||||
@@ -15,7 +15,7 @@ Ouvrez `http://localhost:8000`, créez un scrutin, ouvrez le lien projecteur sur
|
||||
|
||||
### HTTPS obligatoire
|
||||
|
||||
Les téléphones n'ouvrent la caméra qu'en HTTPS. Trois options :
|
||||
Les téléphones n'ouvrent la caméra qu'en HTTPS. Il y a donc 3 options possibles :
|
||||
|
||||
| Option | Variables |
|
||||
|---|---|
|
||||
@@ -23,7 +23,7 @@ Les téléphones n'ouvrent la caméra qu'en HTTPS. Trois options :
|
||||
| Reverse proxy (Caddy, nginx) | `BEHIND_PROXY=1` |
|
||||
| Tunnel (Cloudflare Tunnel, etc.) | `BEHIND_PROXY=1` |
|
||||
|
||||
Dans tous les cas, définissez `PUBLIC_URL=https://vote.example.org` : c'est l'adresse encodée dans les QR codes.
|
||||
Dans tous les cas, définissez `PUBLIC_URL=https://vote.example.org` (pour l'affichage sur le site)
|
||||
|
||||
Caddy :
|
||||
|
||||
@@ -55,40 +55,44 @@ location / {
|
||||
| `PUBLIC_URL` | origine du projecteur | URL encodée dans les QR |
|
||||
| `PORT` / `HOST` | `8000` / `0.0.0.0` | écoute |
|
||||
| `DB_PATH` | `rotatyvote.db` | base SQLite |
|
||||
| `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin |
|
||||
| `CREATE_PASSWORD` | vide | mot de passe pour créer un scrutin, optionnel |
|
||||
| `TOKEN_GRACE_MS` | `2500` | tolérance réseau sur un code |
|
||||
| `MAX_TRIALS` | `50` | essais `/essai` ouverts en même temps |
|
||||
|
||||
## Déroulé
|
||||
|
||||
1. Créer le scrutin, garder le lien admin (clé dans l'URL, non récupérable).
|
||||
2. Ouvrir les inscriptions. Le projecteur affiche le QR rotatif et le nombre d'inscriptions.
|
||||
1. Créer le scrutin, garder le lien admin (clé dans l'URL).
|
||||
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 instantanément.
|
||||
5. Clore, publier les résultats à l'écran, exporter en JSON.
|
||||
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. 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.
|
||||
|
||||
## Code circulaire
|
||||
|
||||
Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le logo au centre, entouré de 4 anneaux de segments qui tournent. Le QR classique reste disponible par scrutin (Inscriptions > Code projeté).
|
||||
Par défaut, le projecteur affiche un code circulaire dyanmique. Le QR classique reste disponible par scrutin (Inscriptions > Code projeté). Cette option peut être avantagueuse si vous avez des soucis de lecture de code au tableau à cause de la distance, des reflets, de l'angle de vue, etc.
|
||||
|
||||
- L'anneau intérieur porte un motif fixe qui donne l'orientation. Les 3 autres portent le jeton : 16 bits de créneau et 32 bits de signature HMAC, protégés par un code Reed-Solomon (12, 6) qui corrige 3 octets illisibles.
|
||||
Spécifications techniques de notre code circulaire dynamique :
|
||||
- L'anneau intérieur porte un motif fixe qui donne l'orientation. Les 3 autres portent "un jeton" : 16 bits de créneau et 32 bits de signature HMAC, protégés par un code Reed-Solomon (12, 6) qui corrige 3 octets illisibles.
|
||||
- Le téléphone repère le disque central, corrige la perspective à partir des anneaux (deux cercles concentriques suffisent à retrouver l'horizon), lit les segments puis corrige les erreurs.
|
||||
- La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée. Un segment qui change de couleur passe en fondu.
|
||||
- Les anneaux ne s'ouvrent pas avec l'appareil photo natif : un petit QR fixe, dans un coin de l'écran, mène à la page de vote.
|
||||
- Signature de 32 bits : un jeton ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire.
|
||||
- De loin : le téléphone cherche le disque sur une copie réduite de l'image, puis lit un recadrage à la résolution du capteur. Le disque est repéré par rapport au blanc qui l'entoure, pas par un seuil global, ce qui tient avec un projecteur délavé dans une salle sombre. Repère pratique : rester à moins de 10 fois le diamètre du code (un code de 1 m se lit jusqu'à 10 m environ).
|
||||
- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code, code lointain sur projecteur délavé, séquences de 6 s). `CPU=6` simule un téléphone lent, `V1=1` rejoue l'ancien décodeur comme référence, `SUITE=far,seq` limite les séries.
|
||||
- La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée.
|
||||
- Il reste tout de même un petit QR fixe, dans le coin de l'écran, pour ouvrir la page de vote.
|
||||
- Signature de 32 bits sur le jeton. Il ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire.
|
||||
- De loin : le téléphone cherche le disque sur une copie réduite de l'image, puis lit un recadrage à la résolution du capteur. Le disque est repéré par rapport au blanc qui l'entoure, pas par un seuil global. Repère pratique : rester à moins de 10 fois le diamètre du code (un code de 1 m se lit jusqu'à 10 m environ).
|
||||
|
||||
## Sécurité : ce qui est garanti, ce qui ne l'est pas
|
||||
## Sécurité - garanties de sécurité de rotatyvote
|
||||
|
||||
**Présence à l'inscription.** Chaque code est un HMAC du créneau horaire, valable environ 3 s. Il faut N codes distincts en une fenêtre courte : une photo ou une capture partagée ne suffit pas.
|
||||
**Présence à l'inscription.** Chaque code est un HMAC du créneau horaire, valable environ 3 s. Il faut N codes distincts en une fenêtre courte : une photo ou une vidéo ne suffit pas.
|
||||
|
||||
**Présence au vote (activée par défaut).** Pour valider un bulletin, le téléphone doit lire 3 codes frais sur le projecteur, qui garde le QR affiché pendant chaque vote. Un téléphone inscrit puis emporté hors de la salle ne peut donc plus voter. Les personnes inscrites avec un code papier ou un code de secours en sont dispensées. Désactivable (Inscriptions > Sécurité) pour une salle sans vidéoprojecteur.
|
||||
**Présence au vote (activée par défaut).** Pour valider un bulletin, le téléphone doit lire le code sur le projecteur, pour vérifier la présence dans la salle. Un téléphone inscrit puis emporté hors de la salle ne peut donc plus voter. (Désactivable (Inscriptions > Sécurité) pour une salle sans vidéoprojecteur.)
|
||||
|
||||
**Anonymat.** Deux tables séparées : `participation` (qui a voté à quelle question) et `ballots` (quel choix), écrites dans la même transaction. Aucune colonne ne relie un bulletin à la personne qui a voté, aucun horodatage, identifiants aléatoires, journal SQLite non-WAL, `secure_delete`, aucun log de connexion. Les codes de présence sont vérifiés puis oubliés. Les résultats restent cachés pendant le vote, admin compris. Un vote est définitif.
|
||||
**Anonymat.** Deux tables séparées : `participation` (qui a voté à quelle question) et `ballots` (quel choix), écrites dans la même transaction. Aucune colonne ne relie un bulletin à la personne qui a voté, aucun horodatage, identifiants aléatoires, journal SQLite non-WAL, `secure_delete`, aucun log de connexion. Les codes de présence sont vérifiés puis oubliés. Les résultats restent cachés pendant le vote y compris pour les administrateurs. Par conscéquent, un vote est définitif.
|
||||
|
||||
**Un vote par inscription et par question.** Imposé par la base (clé primaire), y compris en requêtes simultanées.
|
||||
|
||||
**Une personne, un vote : garanti seulement avec le code papier.** Le même QR vaut pour toute la salle, et aucun site web ne peut identifier un téléphone de façon fiable : en navigation privée ou par script, une personne présente peut créer plusieurs inscriptions. Avec « Code papier obligatoire », chaque inscription consomme un code à usage unique remis à l'émargement (testé en accès simultanés : un code, une inscription). Le code n'est jamais relié au bulletin.
|
||||
**Une personne, un vote (garanti seulement avec le code papier).** Le même QR vaut pour toute la salle. Bien que des protections sont mises en place, aucun site web ne peut identifier un téléphone de façon fiable. En navigation privée ou par script, une personne présente peut créer plusieurs inscriptions. Avec « Code papier obligatoire », chaque inscription consomme un code à usage unique remis à l'émargement (testé en accès simultanés : un code, une inscription). Le code n'est jamais relié au bulletin.
|
||||
Il est conseillé de compter le nombre de personnes présentes, et de vérifier que le compte est bon, ou d'imposer un plafond.
|
||||
|
||||
**Caméra cassée.** Les codes de secours permettent de s'inscrire sans scanner. À remettre après vérification sur place : ils dispensent aussi du scan au vote.
|
||||
|
||||
@@ -99,12 +103,12 @@ Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le
|
||||
| Photo ou capture du QR envoyée à quelqu'un | Aucun : le code expire en ~3 s et il en faut plusieurs | Intégrée |
|
||||
| Lien projecteur divulgué | Le QR peut être affiché ailleurs | Clé masquée de l'URL, révocable (Partage > Nouveau lien) |
|
||||
| Téléphone inscrit confié à une personne absente | Vote à distance | Scan au moment du vote |
|
||||
| Retransmission vidéo en direct de l'écran, ou relais des codes par script | Une personne absente peut s'inscrire et voter en direct | Code papier obligatoire (sans code, pas d'inscription) ; à défaut, compteur affiché et fermeture rapide des inscriptions |
|
||||
| Retransmission vidéo en direct de l'écran, ou relais des codes par script sophistiqué | Une personne absente peut s'inscrire et voter en direct | Code papier obligatoire (sans code, pas d'inscription). A défaut, compteur affiché et fermeture rapide des inscriptions |
|
||||
| Code papier ou de secours confié à une personne absente | Elle vote à la place de la personne présente, sans voix supplémentaire | Équivaut à une procuration ; remettre les codes en main propre |
|
||||
|
||||
**Hors périmètre.** Une personne malveillante qui administre le serveur (elle pourrait modifier le code). Pour cette menace, il faut un système de vote vérifiable de bout en bout.
|
||||
**Hors périmètre.** Une personne malveillante qui administre le serveur (elle pourrait modifier le code). L'infrastructure de rotatyvote ne permet pas de mettre en place des vérifications pour ce risque.
|
||||
|
||||
## Tests
|
||||
## Tests (pour les constributeurs)
|
||||
|
||||
```bash
|
||||
uv run pytest
|
||||
@@ -128,6 +132,18 @@ Les tests lancent un vrai serveur et lisent les codes sur le WebSocket du projec
|
||||
- schéma anonyme ;
|
||||
- scan de présence au vote, codes de secours, code papier en accès simultanés.
|
||||
|
||||
## Écriture du source code
|
||||
|
||||
L'intelligence artificielle générative a partiellement contribué à l'écriture de ce code. Modèle : Claude Opus 5.5.
|
||||
|
||||
## Licence
|
||||
|
||||
MIT, voir [LICENSE](LICENSE). Contributions : [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
MIT avec la condition Commons Clause, voir [LICENSE](LICENSE).
|
||||
|
||||
- Tout le monde peut utiliser RotatyVote gratuitement, entreprises comprises, y compris pour ses propres votes.
|
||||
- Vous pouvez modifier le code et le partager gratuitement, sous la même licence.
|
||||
- Vous ne pouvez pas le vendre, ni vendre un logiciel ou un service (hébergement, support, intégration) dont la valeur repose entièrement ou en grande partie sur lui.
|
||||
|
||||
Ce n'est donc pas une licence open source au sens de l'OSI, mais le code reste public. Les versions publiées avant ce changement restent sous MIT seule.
|
||||
|
||||
Contributions : [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
name = "rotatyvote"
|
||||
version = "0.1.0"
|
||||
requires-python = ">=3.11"
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = [
|
||||
"segno>=1.6.6",
|
||||
"starlette>=1.10.0",
|
||||
|
||||
+284
-63
@@ -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"]), "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)
|
||||
@@ -415,6 +479,18 @@ async def create_poll(request: Request):
|
||||
return JSONResponse({"id": pid, "admin_key": admin_key, "screen_key": screen_key})
|
||||
|
||||
|
||||
async def create_trial(request: Request):
|
||||
# no password even when creation is locked: a trial only enrolls, nobody gets its admin key
|
||||
db.purge_trials(config.TRIAL_TTL_MS)
|
||||
if db.trial_count() >= config.MAX_TRIALS:
|
||||
return err("too_many_trials", 429)
|
||||
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, entry_big=1)
|
||||
return JSONResponse({"id": pid, "screen_key": screen_key})
|
||||
|
||||
|
||||
async def admin_get(request: Request):
|
||||
pid = request.path_params["pid"]
|
||||
require_admin(request, pid)
|
||||
@@ -423,7 +499,7 @@ async def admin_get(request: Request):
|
||||
|
||||
async def admin_patch(request: Request):
|
||||
pid = request.path_params["pid"]
|
||||
p = require_admin(request, pid)
|
||||
require_admin(request, pid)
|
||||
d = await body(request)
|
||||
upd = {}
|
||||
if "title" in d:
|
||||
@@ -447,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:
|
||||
@@ -458,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})
|
||||
|
||||
@@ -472,9 +555,30 @@ 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"]
|
||||
p = require_admin(request, pid)
|
||||
require_admin(request, pid)
|
||||
d = await body(request)
|
||||
qid = db.add_question(pid, *parse_question(d))
|
||||
if d.get("open"):
|
||||
@@ -502,12 +606,47 @@ async def admin_question_action(request: Request):
|
||||
if st != "open":
|
||||
return err("not_open")
|
||||
db.set_question(qid, state="closed")
|
||||
elif action == "reopen":
|
||||
# a late vote can still come in, but never once the room has seen the tally
|
||||
if st != "closed":
|
||||
return err("not_closed")
|
||||
if q["shown"]:
|
||||
return err("already_shown")
|
||||
db.set_question(qid, state="open")
|
||||
db.update_poll(pid, focus_qid=qid)
|
||||
elif action in ("publish", "unpublish"):
|
||||
if st != "closed":
|
||||
return err("not_closed")
|
||||
db.set_question(qid, results_public=int(action == "publish"))
|
||||
if action == "publish":
|
||||
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":
|
||||
@@ -559,23 +698,53 @@ 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="/")
|
||||
hub.refresh(pid)
|
||||
# a trial has no admin: the first enrolled phone opens the sample question so the vote can be tried too
|
||||
p = db.poll(pid)
|
||||
if p["trial"] and not p["focus_qid"]:
|
||||
q = next((q for q in db.questions(pid) if q["state"] == "draft"), None)
|
||||
if q:
|
||||
db.set_question(q["id"], state="open")
|
||||
db.update_poll(pid, focus_qid=q["id"])
|
||||
hub.refresh(pid, voters=True)
|
||||
return resp, None
|
||||
|
||||
|
||||
def _attempt(request, pid):
|
||||
"""this device's enrollment attempt, from its cookie, or a fresh one (then the cookie must be set)"""
|
||||
if len(attempts) > 50000:
|
||||
prune_attempts()
|
||||
att_id = request.cookies.get(attempt_cookie(pid))
|
||||
if att_id and (pid, att_id) in attempts:
|
||||
return att_id, attempts[(pid, att_id)], None
|
||||
att_id = new_key()
|
||||
attempts[(pid, att_id)] = Attempt()
|
||||
return att_id, attempts[(pid, att_id)], att_id
|
||||
|
||||
|
||||
def _expire(a, p, now):
|
||||
# scans must land in one short window, and a proven presence only waits so long for its paper code
|
||||
if a.presence_ms:
|
||||
if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
|
||||
a.slots.clear(); a.first_ms = 0; a.presence_ms = 0
|
||||
elif a.first_ms and now - a.first_ms > p["scans_required"] * p["interval_ms"] + config.ATTEMPT_SLACK_MS:
|
||||
a.slots.clear(); a.first_ms = 0
|
||||
|
||||
|
||||
async def voter_scan(request: Request):
|
||||
pid = request.path_params["pid"]
|
||||
p = get_poll(pid)
|
||||
@@ -584,24 +753,11 @@ async def voter_scan(request: Request):
|
||||
return JSONResponse({"status": "enrolled"})
|
||||
if not p["enrollment_open"]:
|
||||
return JSONResponse({"status": "closed"})
|
||||
if len(attempts) > 50000:
|
||||
prune_attempts()
|
||||
att_id = request.cookies.get(attempt_cookie(pid))
|
||||
fresh_cookie = None
|
||||
if not att_id or (pid, att_id) not in attempts:
|
||||
att_id = new_key()
|
||||
fresh_cookie = att_id
|
||||
attempts[(pid, att_id)] = Attempt()
|
||||
a = attempts[(pid, att_id)]
|
||||
att_id, a, fresh_cookie = _attempt(request, pid)
|
||||
now = now_ms()
|
||||
a.last_ms = now
|
||||
required = p["scans_required"]
|
||||
window = required * p["interval_ms"] + config.ATTEMPT_SLACK_MS
|
||||
if a.presence_ms:
|
||||
if now - a.presence_ms > config.CODE_ENTRY_TTL_S * 1000:
|
||||
a.slots.clear(); a.first_ms = 0; a.presence_ms = 0
|
||||
elif a.first_ms and now - a.first_ms > window:
|
||||
a.slots.clear(); a.first_ms = 0
|
||||
_expire(a, p, now)
|
||||
|
||||
status = "progress"
|
||||
slot = resolve_token(p, str(d.get("token", ""))[:64], config.TOKEN_GRACE_MS)
|
||||
@@ -628,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"]
|
||||
@@ -646,7 +853,7 @@ async def voter_rescue(request: Request):
|
||||
|
||||
async def voter_code(request: Request):
|
||||
pid = request.path_params["pid"]
|
||||
p = get_poll(pid)
|
||||
get_poll(pid)
|
||||
d = await body(request)
|
||||
if current_voter(request, pid):
|
||||
return JSONResponse({"status": "enrolled"})
|
||||
@@ -689,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:
|
||||
@@ -738,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)
|
||||
@@ -790,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:
|
||||
@@ -809,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/"):
|
||||
@@ -845,22 +1057,31 @@ 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"]),
|
||||
Route("/api/trial", create_trial, methods=["POST"]),
|
||||
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),
|
||||
|
||||
@@ -25,10 +25,24 @@ 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
|
||||
|
||||
# throwaway polls from /essai: deleted after this, and only so many alive at once
|
||||
TRIAL_TTL_MS = 2 * 3600 * 1000
|
||||
MAX_TRIALS = int(os.environ.get("MAX_TRIALS", "50"))
|
||||
|
||||
MIN_INTERVAL_MS = 300
|
||||
MAX_INTERVAL_MS = 5000
|
||||
MIN_SCANS = 2
|
||||
|
||||
+38
-6
@@ -87,6 +87,14 @@ class DB:
|
||||
("voters", "via_code", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("access_codes", "rescue", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("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:
|
||||
@@ -110,25 +118,41 @@ class DB:
|
||||
|
||||
|
||||
def create_poll(self, title, interval_ms, scans_required, require_code, expected, max_voters, vote_scans=0,
|
||||
code_style="qr"):
|
||||
code_style="qr", trial=False):
|
||||
pid = new_id()
|
||||
while self.one("SELECT 1 FROM polls WHERE id=?", pid):
|
||||
pid = new_id()
|
||||
admin_key, screen_key = new_key(), new_key()
|
||||
self.c.execute(
|
||||
"INSERT INTO polls(id,title,admin_hash,screen_hash,secret,interval_ms,scans_required,"
|
||||
"require_code,expected,max_voters,vote_scans,code_style,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
"require_code,expected,max_voters,vote_scans,code_style,trial,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(pid, title, sha(admin_key), sha(screen_key), secrets.token_bytes(32), interval_ms,
|
||||
scans_required, int(require_code), expected, max_voters, vote_scans, code_style, now_ms()),
|
||||
scans_required, int(require_code), expected, max_voters, vote_scans, code_style, int(trial), now_ms()),
|
||||
)
|
||||
return pid, admin_key, screen_key
|
||||
|
||||
def purge_trials(self, max_age_ms):
|
||||
old = [r["id"] for r in self.all("SELECT id FROM polls WHERE trial=1 AND created_at<?", now_ms() - max_age_ms)]
|
||||
with self.tx() as c:
|
||||
for pid in old:
|
||||
qids = "SELECT id FROM questions WHERE poll_id=?"
|
||||
c.execute(f"DELETE FROM ballots WHERE question_id IN ({qids})", (pid,))
|
||||
c.execute(f"DELETE FROM participation WHERE question_id IN ({qids})", (pid,))
|
||||
for table, col in (("questions", "poll_id"), ("voters", "poll_id"), ("access_codes", "poll_id"),
|
||||
("polls", "id")):
|
||||
c.execute(f"DELETE FROM {table} WHERE {col}=?", (pid,))
|
||||
return old
|
||||
|
||||
def trial_count(self):
|
||||
return self.one("SELECT COUNT(*) n FROM polls WHERE trial=1")["n"]
|
||||
|
||||
def poll(self, pid):
|
||||
return self.one("SELECT * FROM polls WHERE id=?", pid)
|
||||
|
||||
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
|
||||
@@ -206,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"}
|
||||
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))
|
||||
@@ -250,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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""ring code: a static qr in the middle (opens the page, anchors geometry) plus rotating rings of dashes
|
||||
"""ring code: a dark disc with the logo in the middle (anchors the geometry) plus rotating rings of dashes
|
||||
that carry the time token. layout and bit order must match static/js/ringcode.js exactly.
|
||||
|
||||
payload = slot mod 2^16 (2 bytes) + first 4 bytes of the token hmac, reed-solomon(12, 6) over gf(256),
|
||||
@@ -8,7 +8,6 @@ import hmac
|
||||
SYNC = "010001100101001000111111" # 24 sectors, min distance 12 to any of its rotations
|
||||
RING_SECTORS = (24, 28, 32, 36) # ring 0 is sync, 1..3 carry 96 data bits
|
||||
NSYM = 6 # rs parity bytes, fixes up to 3 bad bytes
|
||||
SLOT_BITS = 16
|
||||
|
||||
_EXP = [0] * 512
|
||||
_LOG = [0] * 256
|
||||
|
||||
+16
-15
@@ -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
|
||||
|
||||
+59
-3
@@ -44,14 +44,26 @@
|
||||
<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>
|
||||
<select id="s-interval">
|
||||
<option value="500">0,5 s</option>
|
||||
<option value="700">0,7 s</option>
|
||||
<option value="800">0,8 s</option>
|
||||
<option value="1000">1 s</option>
|
||||
<option value="1500">1,5 s</option>
|
||||
<option value="2000">2 s</option>
|
||||
@@ -110,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>
|
||||
@@ -124,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
@@ -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); }
|
||||
|
||||
+35
-3
@@ -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,11 +129,21 @@ 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 { fill: none; stroke: var(--line); stroke-linecap: round; transition: stroke .3s; }
|
||||
.ring .seg.on { stroke: var(--ink); }
|
||||
.ring .seg.last { stroke: var(--mark); }
|
||||
.ring .seg, .ring .fill { fill: none; stroke-linecap: round; }
|
||||
.ring .seg { stroke: var(--line); }
|
||||
/* 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); opacity: 0;
|
||||
transition: stroke-dashoffset .5s cubic-bezier(.3, .7, .2, 1), opacity .12s, stroke .22s;
|
||||
}
|
||||
.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); }
|
||||
|
||||
.codes-print { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; margin-top: 12px; }
|
||||
@@ -154,3 +169,20 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; }
|
||||
.card { padding: 0; }
|
||||
.code-cell { break-inside: avoid; }
|
||||
}
|
||||
.center { text-align: center; }
|
||||
|
||||
/* created poll: the two windows it opens */
|
||||
.duo { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 2px 0 6px; }
|
||||
.duo.stack { grid-template-columns: 1fr; margin-top: 12px; }
|
||||
.duo .pane { display: grid; gap: 10px; background: var(--bg); border-radius: var(--r-field); padding: 14px; }
|
||||
.duo .pane-head { display: flex; align-items: center; gap: 12px; }
|
||||
.duo .pane .linkbox input { background: var(--surface); }
|
||||
.duo p { margin: 0; display: grid; gap: 1px; min-width: 0; }
|
||||
.duo b { font: 700 .92rem var(--round); }
|
||||
.duo span { font-size: .78rem; color: var(--ink-3); }
|
||||
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; }
|
||||
|
||||
+124
-12
@@ -8,19 +8,51 @@ body.screen {
|
||||
.s-tools { display: flex; gap: 10px; align-items: center; }
|
||||
:fullscreen .s-tools button { display: none; }
|
||||
|
||||
.s-main { min-height: 0; display: grid; padding: 1vh 4vw; }
|
||||
/* definite tracks: percentage heights below resolve the same in every engine */
|
||||
.s-main { min-height: 0; display: grid; grid-template-rows: minmax(0, 1fr); padding: 1vh 4vw; }
|
||||
|
||||
.s-enroll { display: grid; grid-template-columns: auto 1fr; gap: 5vw; align-items: center; min-height: 0; }
|
||||
.s-enroll { display: grid; grid-template-columns: auto 1fr; grid-template-rows: minmax(0, 1fr); gap: 5vw; align-items: center; min-height: 0; height: 100%; }
|
||||
.qr-wrap {
|
||||
height: 100%; max-height: 74vh; aspect-ratio: 1; display: grid; grid-template-rows: 1fr auto;
|
||||
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(70px, 7vw, 130px); height: auto; aspect-ratio: 1; image-rendering: pixelated; }
|
||||
.entry div { display: grid; gap: .3vh; font-size: clamp(.8rem, 1.1vw, 1.2rem); color: var(--ink-2); }
|
||||
/* 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; }
|
||||
#qr { width: 100%; height: 100%; min-height: 0; image-rendering: pixelated; image-rendering: crisp-edges; object-fit: contain; }
|
||||
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; }
|
||||
.tick { height: 6px; background: var(--bg); border-radius: 99px; overflow: hidden; margin: 0 1vh; }
|
||||
#tick-bar { height: 100%; width: 0; background: var(--mark); border-radius: 99px; }
|
||||
.s-steps h2 { font-size: clamp(2rem, 4.6vw, 5rem); letter-spacing: -.03em; margin-bottom: .5em; }
|
||||
@@ -35,14 +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 .qr-wrap { max-height: 52vh; }
|
||||
.s-main.split .s-steps h2 { font-size: clamp(1.4rem, 2.4vw, 2.6rem); }
|
||||
/* 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 #qr-steps { display: none; }
|
||||
.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; }
|
||||
@@ -68,5 +110,75 @@ 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 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; }
|
||||
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 { display: grid; grid-template-columns: auto; justify-items: center; row-gap: 1vh; text-align: center; max-width: 42vw; }
|
||||
}
|
||||
.qr-wrap.ring .tick { display: none; }
|
||||
|
||||
/* light motion: blocks rise in, fade out, the question lands piece by piece, result bars grow */
|
||||
@keyframes s-in { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
|
||||
@keyframes s-out { to { opacity: 0; transform: translateY(-8px); } }
|
||||
@keyframes s-grow { from { transform: scaleX(0); } }
|
||||
@keyframes s-bump { 40% { transform: scale(1.18); } }
|
||||
.s-main:not(.split) > section { grid-area: 1 / 1; }
|
||||
.s-main > section:not([hidden]), .entry:not([hidden]) { animation: s-in .5s cubic-bezier(.2, .7, .2, 1) both; }
|
||||
.s-main > section.leaving, .entry.leaving { animation: s-out .22s ease both; }
|
||||
#focus.enter .q-text { animation: s-in .5s cubic-bezier(.2, .7, .2, 1) both; }
|
||||
#focus.enter .opts li, #focus.enter .bar-row { animation: s-in .45s cubic-bezier(.2, .7, .2, 1) both; }
|
||||
#focus.enter :is(.opts li, .bar-row):nth-child(1) { animation-delay: .08s; }
|
||||
#focus.enter :is(.opts li, .bar-row):nth-child(2) { animation-delay: .14s; }
|
||||
#focus.enter :is(.opts li, .bar-row):nth-child(3) { animation-delay: .2s; }
|
||||
#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-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; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.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; }
|
||||
|
||||
@@ -50,3 +50,49 @@ dialog[open] { animation: rise .2s ease-out; }
|
||||
#confirm-choices { list-style: none; padding: 0; margin: 0 0 8px; }
|
||||
#confirm-choices li { font: 700 1.2rem var(--round); background: var(--mark); border-radius: 12px; padding: 10px 14px; margin: 6px 0; }
|
||||
dialog .actions button { flex: 1; }
|
||||
|
||||
/* confirmation after enrolling or voting: the projector's mark, its check drawing in */
|
||||
.celebrate {
|
||||
position: fixed; inset: 0; z-index: 50; display: grid; place-content: center; justify-items: center; gap: 18px;
|
||||
background: color-mix(in srgb, var(--bg) 92%, transparent); color: var(--ink);
|
||||
animation: cel-in .3s ease both;
|
||||
}
|
||||
.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, .celebrate small, .celebrate.verifying svg { animation: none; }
|
||||
.celebrate .tick { animation: none; stroke-dashoffset: 0; }
|
||||
}
|
||||
|
||||
/* next camera: some phones hand over the selfie lens or the ultra wide */
|
||||
.cam-switch {
|
||||
position: absolute; right: 10px; bottom: 10px; width: 44px; height: 44px; padding: 0; border-radius: 50%;
|
||||
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, .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; }
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>RotatyVote · Essai</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/essai.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap narrow">
|
||||
<div class="topbar"><a class="brand" href="/"><img src="/static/img/mark.svg" alt=""><span>rotaty<b>vote</b></span></a></div>
|
||||
|
||||
<section class="card">
|
||||
<h1>Tester l'écran</h1>
|
||||
<p>Ouvrez cette page sur l'ordinateur relié au projecteur, puis visez l'écran avec votre téléphone depuis le fond de la salle.</p>
|
||||
<div class="actions"><button id="go" class="primary block" type="button">Lancer l'essai</button></div>
|
||||
<p class="hint">Scrutin jetable, effacé au bout de 2 h.</p>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
+55
-24
@@ -16,24 +16,7 @@
|
||||
<h1>Nouveau scrutin</h1>
|
||||
<form id="form">
|
||||
<label for="title">Titre</label>
|
||||
<input id="title" type="text" required maxlength="200" placeholder="Assemblée générale 2026">
|
||||
|
||||
<div class="row">
|
||||
<div>
|
||||
<label for="interval">Rotation du code</label>
|
||||
<select id="interval">
|
||||
<option value="500" selected>0,5 s</option>
|
||||
<option value="1000">1 s</option>
|
||||
<option value="1500">1,5 s</option>
|
||||
<option value="2000">2 s</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="scans">Codes à scanner</label>
|
||||
<input id="scans" type="number" min="2" max="20" value="5">
|
||||
</div>
|
||||
</div>
|
||||
<p class="hint" id="duration-hint"></p>
|
||||
<input id="title" type="text" required maxlength="200" placeholder="Conseil d'administration">
|
||||
|
||||
<div class="row">
|
||||
<div>
|
||||
@@ -53,6 +36,37 @@
|
||||
<input id="codes" type="number" min="1" max="5000" value="50">
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<select id="interval">
|
||||
<option value="500">0,5 s</option>
|
||||
<option value="700">0,7 s</option>
|
||||
<option value="800" selected>0,8 s</option>
|
||||
<option value="1000">1 s</option>
|
||||
<option value="1500">1,5 s</option>
|
||||
<option value="2000">2 s</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="scans">Codes à scanner</label>
|
||||
<input id="scans" type="number" min="2" max="20" value="5">
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div id="pw-box" hidden>
|
||||
<label for="pw">Mot de passe de création</label>
|
||||
<input id="pw" type="password" autocomplete="current-password">
|
||||
@@ -61,16 +75,33 @@
|
||||
<div class="actions"><button class="primary block" type="submit">Créer le scrutin</button></div>
|
||||
</form>
|
||||
</section>
|
||||
<p class="hint center" id="try-link"><a href="/essai">Tester l'écran et les téléphones</a></p>
|
||||
|
||||
<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>
|
||||
<label>Lien d'administration</label>
|
||||
<div class="linkbox"><input id="admin-link" type="text" readonly><button id="copy-admin" class="small" type="button">Copier</button></div>
|
||||
<label>Lien du projecteur</label>
|
||||
<div class="linkbox"><input id="screen-link" type="text" readonly><button id="copy-screen" class="small" type="button">Copier</button></div>
|
||||
<p class="hint">Pour l'ordinateur du vidéoprojecteur. Ne pas diffuser.</p>
|
||||
<div class="actions"><a id="go-admin" class="btn primary block" href="#">Ouvrir l'administration</a></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>
|
||||
<div class="linkbox"><input id="admin-link" type="text" readonly aria-label="Lien d'administration"><button id="copy-admin" class="small" type="button">Copier</button></div>
|
||||
<a id="go-admin" class="btn primary block" href="#" target="_blank" rel="noopener">Ouvrir l'administration</a>
|
||||
</div>
|
||||
<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>Projecteur</b><span>Affiché à la salle, à ouvrir sur l'écran projeté</span></p></div>
|
||||
<div class="linkbox"><input id="screen-link" type="text" readonly aria-label="Lien du projecteur"><button id="copy-screen" class="small" type="button">Copier</button></div>
|
||||
<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>
|
||||
|
||||
+162
-6
@@ -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 = [
|
||||
@@ -21,6 +23,7 @@ function errMsg(e) {
|
||||
not_draft: "La question n'est plus en brouillon",
|
||||
not_open: "La question n'est pas ouverte",
|
||||
not_closed: "La question n'est pas close",
|
||||
already_shown: "Résultats déjà publiés, le vote ne peut plus être rouvert",
|
||||
};
|
||||
return m[e.code] || e.message;
|
||||
}
|
||||
@@ -62,6 +65,7 @@ function render() {
|
||||
|
||||
renderSettings(p);
|
||||
renderQuestions();
|
||||
renderShare(p);
|
||||
}
|
||||
|
||||
function renderSettings(p) {
|
||||
@@ -77,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);
|
||||
@@ -91,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));
|
||||
}
|
||||
|
||||
@@ -113,32 +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" : ""}) ? Définitif.`));
|
||||
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"));
|
||||
: 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");
|
||||
@@ -205,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) => {
|
||||
@@ -265,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) {
|
||||
@@ -287,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)}`;
|
||||
|
||||
+71
-23
@@ -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") {
|
||||
@@ -149,6 +161,10 @@ const SVGNS = "http://www.w3.org/2000/svg";
|
||||
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) {
|
||||
@@ -174,20 +190,52 @@ export function ring(n, total, size = 160, label = `${n}/${total}`) {
|
||||
const r = 40, sw = 10, c = 2 * Math.PI * r;
|
||||
// round caps overhang sw/2 on each side, so shorten each dash by sw
|
||||
const slot = c / total, gap = total > 1 ? 5 : 0, seg = slot - gap - sw;
|
||||
const at = (len) => { const a = -Math.PI / 2 + len / r; return `${50 + r * Math.cos(a)} ${50 + r * Math.sin(a)}`; };
|
||||
const fills = [];
|
||||
for (let i = 0; i < total; i++) {
|
||||
const el = document.createElementNS(SVGNS, "circle");
|
||||
el.setAttribute("cx", 50); el.setAttribute("cy", 50); el.setAttribute("r", r);
|
||||
el.setAttribute("stroke-width", sw);
|
||||
el.setAttribute("stroke-dasharray", `${seg} ${c - seg}`);
|
||||
// start at 12 o'clock
|
||||
el.setAttribute("stroke-dashoffset", String(c / 4 - i * slot - (gap + sw) / 2));
|
||||
el.setAttribute("class", "seg" + (i < n ? " on" : "") + (i === n - 1 && n < total ? " last" : ""));
|
||||
svg.append(el);
|
||||
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. 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.style.strokeDasharray = `${seg} ${seg + sw * 2}`;
|
||||
el.style.strokeDashoffset = String(seg);
|
||||
fills.push(el);
|
||||
}
|
||||
svg.append(el);
|
||||
}
|
||||
}
|
||||
const t = document.createElementNS(SVGNS, "text");
|
||||
t.setAttribute("x", 50); t.setAttribute("y", 50);
|
||||
t.setAttribute("text-anchor", "middle"); t.setAttribute("dominant-baseline", "central");
|
||||
t.textContent = label;
|
||||
svg.append(t);
|
||||
// updates in place so the css transitions run
|
||||
svg.set = (k, text = `${k}/${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;
|
||||
};
|
||||
svg.total = total;
|
||||
svg.set(n, label);
|
||||
return svg;
|
||||
}
|
||||
|
||||
// keeps the same svg between counts so each new segment fills instead of popping in
|
||||
export function paintRing(box, n, total, size) {
|
||||
let svg = box.querySelector("svg.ring");
|
||||
if (!svg || svg.total !== total) {
|
||||
svg = ring(0, total, size);
|
||||
box.replaceChildren(svg);
|
||||
// one frame at the old count, so the first fill animates too
|
||||
svg.getBoundingClientRect();
|
||||
}
|
||||
svg.set(n);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { $, api, toast } from "./common.js";
|
||||
|
||||
$("#go").addEventListener("click", async (e) => {
|
||||
e.target.disabled = true;
|
||||
try {
|
||||
const r = await api("POST", "/api/trial");
|
||||
location.href = `/screen/${r.id}#${r.screen_key}`;
|
||||
} catch (err) {
|
||||
toast(err.code === "too_many_trials" ? "Trop d'essais en cours, réessayez plus tard" : `Erreur : ${err.message}`, "bad");
|
||||
e.target.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
+14
-8
@@ -3,15 +3,9 @@ import { $, api, toast } from "./common.js";
|
||||
const cfg = await api("GET", "/api/config").catch(() => ({}));
|
||||
$("#pw-box").hidden = !cfg.create_password;
|
||||
|
||||
function hint() {
|
||||
const s = (+$("#interval").value * +$("#scans").value) / 1000;
|
||||
$("#duration-hint").textContent = `≈ ${s.toLocaleString("fr-FR")} s de scan`;
|
||||
}
|
||||
$("#interval").addEventListener("change", hint);
|
||||
$("#scans").addEventListener("input", hint);
|
||||
hint();
|
||||
|
||||
$("#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();
|
||||
@@ -22,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,
|
||||
@@ -34,7 +30,10 @@ $("#form").addEventListener("submit", async (e) => {
|
||||
$("#admin-link").value = admin;
|
||||
$("#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;
|
||||
} catch (err) {
|
||||
toast(err.code === "bad_password" ? "Mot de passe incorrect" : `Erreur : ${err.message}`, "bad");
|
||||
@@ -49,3 +48,10 @@ for (const [btn, input] of [["#copy-admin", "#admin-link"], ["#copy-screen", "#s
|
||||
catch { $(input).select(); }
|
||||
});
|
||||
}
|
||||
|
||||
// a real window, not a tab: it can be dragged onto the projected display and put full screen there
|
||||
$("#go-screen").addEventListener("click", (e) => {
|
||||
const w = window.open($("#go-screen").href, "_blank", "popup,width=1280,height=720");
|
||||
// blocked popup: the plain link still opens a tab
|
||||
if (w) { w.opener = null; e.preventDefault(); }
|
||||
});
|
||||
|
||||
@@ -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(); });
|
||||
+197
-47
@@ -154,21 +154,62 @@ const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
|
||||
const INK = "#1c2036";
|
||||
|
||||
function logo(ctx, cx, cy, r) {
|
||||
// the rotaty mark in light tones on the dark disc
|
||||
const n = 6, rr = r * 0.52, step = (2 * Math.PI) / n;
|
||||
// same geometry as static/img/mark.svg: r 11, stroke 5, 6 dashes of 4.52 every 11.52, first one yellow
|
||||
const u = (r * 0.62) / 13.5, rr = 11 * u, step = (2 * Math.PI) / 6, dash = 4.52 / 11, start = 3.5 / 11;
|
||||
ctx.lineCap = "round";
|
||||
ctx.lineWidth = r * 0.17;
|
||||
for (let j = 0; j < n; j++) {
|
||||
const a = -Math.PI / 2 + j * step;
|
||||
ctx.lineWidth = 5 * u;
|
||||
for (let j = 0; j < 6; j++) {
|
||||
const a = -Math.PI / 2 + start + j * step;
|
||||
ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff";
|
||||
ctx.beginPath(); ctx.arc(cx, cy, rr, a + step * 0.2, a + step * 0.8); ctx.stroke();
|
||||
ctx.beginPath(); ctx.arc(cx, cy, rr, a, a + dash); ctx.stroke();
|
||||
}
|
||||
// check mark inside, same one the phone shows once its scans count
|
||||
ctx.strokeStyle = "#ffffff";
|
||||
ctx.lineWidth = 2.4 * u;
|
||||
ctx.lineJoin = "round";
|
||||
ctx.beginPath(); ctx.moveTo(cx - 3.2 * u, cy + 0.15 * u); ctx.lineTo(cx - 0.9 * u, cy + 2.45 * u); ctx.lineTo(cx + 3.35 * u, cy - 2.3 * u); ctx.stroke();
|
||||
}
|
||||
|
||||
const EASE = {
|
||||
sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x),
|
||||
cubic: (x) => (x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2),
|
||||
quart: (x) => (x < 0.5 ? 8 * x ** 4 : 1 - (-2 * x + 2) ** 4 / 2),
|
||||
linear: (x) => x,
|
||||
};
|
||||
|
||||
// deterministic per-dash phase so every dash breathes on its own rhythm
|
||||
const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1;
|
||||
|
||||
// fade: { from: previous bits, k: 0..1 } while the code switches, so changed dashes cross-fade
|
||||
// the bean keeps its shape, only its inside changes: a soft gradient slides across it from a random end,
|
||||
// fading the new tone in behind and the old one out ahead. conic so it follows the arc exactly
|
||||
// arc: center, angular extent cap to cap, and how to stroke the dash
|
||||
function wipeDash(ctx, { cx, cy, lo, hi, dash }, from, to, fade, k, j) {
|
||||
const dir = phase(k + 7, j + (fade.seed || 0) * 31) < 0.5 ? 1 : -1;
|
||||
const delay = phase(k + 3, j + (fade.seed || 0) * 17) * 0.15, x = Math.min(1, Math.max(0, (fade.k - delay) / 0.85));
|
||||
const e = (EASE[fade.ease] || EASE.sine)(x);
|
||||
if (!ctx.createConicGradient) {
|
||||
ctx.globalAlpha = from + (to - from) * e;
|
||||
dash();
|
||||
return;
|
||||
}
|
||||
const soft = (hi - lo) * 0.6, edge = dir > 0 ? lo - soft + (hi - lo + 2 * soft) * e : hi + soft - (hi - lo + 2 * soft) * e;
|
||||
const start = lo - soft - 0.2, at = (th) => Math.min(1, Math.max(0, (th - start) / (2 * Math.PI)));
|
||||
const g = ctx.createConicGradient(start, cx, cy);
|
||||
const [behind, ahead] = dir > 0 ? [to, from] : [from, to];
|
||||
for (let i = 0; i <= 6; i++) {
|
||||
const u = i / 6, w = u * u * (3 - 2 * u);
|
||||
g.addColorStop(at(edge - soft + 2 * soft * u), `rgba(28,32,54,${behind + (ahead - behind) * w})`);
|
||||
}
|
||||
g.addColorStop(0, `rgba(28,32,54,${behind})`);
|
||||
g.addColorStop(1, `rgba(28,32,54,${ahead})`);
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.strokeStyle = g;
|
||||
dash();
|
||||
ctx.strokeStyle = INK;
|
||||
}
|
||||
|
||||
// fade: { from: previous bits, k: 0..1, seed } while the code switches. a changed dash is wiped:
|
||||
// one edge crosses it from a random end, the new tone fills behind it while the old one empties ahead
|
||||
export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
|
||||
ctx.fillStyle = "#eef0f6";
|
||||
ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill();
|
||||
@@ -176,9 +217,9 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
|
||||
ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill();
|
||||
logo(ctx, cx, cy, CENTER * unit);
|
||||
const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null;
|
||||
const ease = fade ? fade.k * fade.k * (3 - 2 * fade.k) : 1;
|
||||
ctx.lineCap = "round";
|
||||
ctx.lineWidth = THICK * unit;
|
||||
ctx.strokeStyle = INK;
|
||||
ringsOf(bits).forEach((ring, k) => {
|
||||
const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n;
|
||||
const cap = (THICK * unit) / 2 / r;
|
||||
@@ -186,12 +227,15 @@ export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
|
||||
const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7);
|
||||
const len = LEN[0] + (LEN[1] - LEN[0]) * w;
|
||||
const alphaOf = (bit) => { const [a0, a1] = bit === "1" ? ALPHA_DARK : ALPHA_LIGHT; return a0 + (a1 - a0) * w2; };
|
||||
const now = alphaOf(ring[j]), before = prev ? alphaOf(prev[k][j]) : now;
|
||||
const half = Math.max(0.01, (step * len) / 2 - cap);
|
||||
const a = sectorAngle(theta, j, n) - Math.PI / 2;
|
||||
ctx.globalAlpha = before + (now - before) * ease;
|
||||
ctx.strokeStyle = INK;
|
||||
ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
|
||||
const dash = () => { ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke(); };
|
||||
if (!prev || prev[k][j] === ring[j]) {
|
||||
ctx.globalAlpha = alphaOf(ring[j]);
|
||||
dash();
|
||||
continue;
|
||||
}
|
||||
wipeDash(ctx, { cx, cy, lo: a - half - cap, hi: a + half + cap, dash }, alphaOf(prev[k][j]), alphaOf(ring[j]), fade, k, j);
|
||||
}
|
||||
});
|
||||
ctx.globalAlpha = 1;
|
||||
@@ -236,6 +280,23 @@ function corr(vals, bits) {
|
||||
return dv && db ? num / Math.sqrt(dv * db) : 0;
|
||||
}
|
||||
|
||||
// same as corr after removing the first angular harmonic from both sides: a reflection or a lamp lights one side
|
||||
// of the ring brighter, and that slow swell alone pulls a clean sync ring under the threshold
|
||||
const flatten = (v) => {
|
||||
const n = v.length;
|
||||
let a = 0, b = 0, c = 0;
|
||||
for (let j = 0; j < n; j++) { const t = (2 * Math.PI * j) / n; a += v[j]; b += v[j] * Math.cos(t); c += v[j] * Math.sin(t); }
|
||||
a /= n; b *= 2 / n; c *= 2 / n;
|
||||
return v.map((x, j) => { const t = (2 * Math.PI * j) / n; return x - a - b * Math.cos(t) - c * Math.sin(t); });
|
||||
};
|
||||
const SYNC_FLAT = flatten(SYNC_BITS);
|
||||
function corrFlat(vals) {
|
||||
const f = flatten(vals);
|
||||
let num = 0, dv = 0, db = 0;
|
||||
for (let i = 0; i < f.length; i++) { num += f[i] * -SYNC_FLAT[i]; dv += f[i] * f[i]; db += SYNC_FLAT[i] * SYNC_FLAT[i]; }
|
||||
return dv && db ? num / Math.sqrt(dv * db) : 0;
|
||||
}
|
||||
|
||||
// otsu split of one ring: threshold + how well it separates (between-class / total variance)
|
||||
function split(vals) {
|
||||
const s = [...vals].sort((a, b) => a - b), n = s.length;
|
||||
@@ -267,10 +328,9 @@ function solve(A, B) {
|
||||
return B.map((b, i) => b / A[i][i]);
|
||||
}
|
||||
|
||||
// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px
|
||||
function blobs(g, w, h, s, ratio, out) {
|
||||
// dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6,
|
||||
// and the disc always has its light surround within reach, whatever the room does around the screen
|
||||
// dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6,
|
||||
// and the disc always has its light surround within reach, whatever the room does around the screen
|
||||
function darkMask(g, w, h, ratio) {
|
||||
const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th);
|
||||
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
||||
const i = ((y / T) | 0) * tw + ((x / T) | 0), v = g[y * w + x];
|
||||
@@ -288,6 +348,36 @@ function blobs(g, w, h, s, ratio, out) {
|
||||
const thr = m * ratio, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T);
|
||||
for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1;
|
||||
}
|
||||
return dark;
|
||||
}
|
||||
|
||||
// ellipse from the moments of a component filled row by row (so the light logo inside doesn't count as
|
||||
// holes), or null when the shape is not a filled ellipse. rows y0..y1 where stamp[y] === id hold lo..hi
|
||||
function rowEllipse(lo, hi, stamp, id, y0, y1, count, s) {
|
||||
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
if (stamp[y] !== id) continue;
|
||||
const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2;
|
||||
const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6;
|
||||
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
|
||||
}
|
||||
const ux = mx / m0, uy = my / m0;
|
||||
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
|
||||
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
|
||||
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
|
||||
if (l2 <= 0) return null;
|
||||
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
|
||||
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
|
||||
if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) return null;
|
||||
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
|
||||
const c = Math.cos(phi), sn = Math.sin(phi);
|
||||
const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER;
|
||||
return { cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s };
|
||||
}
|
||||
|
||||
// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px
|
||||
function blobs(g, w, h, s, ratio, out) {
|
||||
const dark = darkMask(g, w, h, ratio);
|
||||
const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1);
|
||||
let id = 0;
|
||||
for (let start = 0; start < w * h; start++) {
|
||||
@@ -306,26 +396,8 @@ function blobs(g, w, h, s, ratio, out) {
|
||||
if (y < h - 1 && dark[i + w]) { dark[i + w] = 0; stack[sp++] = i + w; }
|
||||
}
|
||||
if (count < 30 || y1 - y0 < 5) continue;
|
||||
// moments of the row-filled shape, so the light logo inside doesn't count as holes
|
||||
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
if (stamp[y] !== id) continue;
|
||||
const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2;
|
||||
const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6;
|
||||
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
|
||||
}
|
||||
const ux = mx / m0, uy = my / m0;
|
||||
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
|
||||
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
|
||||
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
|
||||
if (l2 <= 0) continue;
|
||||
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
|
||||
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
|
||||
if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) continue;
|
||||
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
|
||||
const c = Math.cos(phi), sn = Math.sin(phi);
|
||||
const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER;
|
||||
out.push({ cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s });
|
||||
const e = rowEllipse(lo, hi, stamp, id, y0, y1, count, s);
|
||||
if (e) out.push(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,6 +717,14 @@ function projective(img, cand) {
|
||||
if (!l || Math.abs(l[2]) < 1e-9) return null;
|
||||
l = l.map((v) => v / l[2]);
|
||||
lastProjective.l = l; lastProjective.stage = 'line';
|
||||
const map = mapFromLine(Q1, l, mx, my, sc);
|
||||
lastProjective.stage = map ? 'ok' : 'ellipse';
|
||||
lastProjective.map = map;
|
||||
return map;
|
||||
}
|
||||
|
||||
// code space -> image from the disc conic Q1 and a vanishing line l (normalized coordinates), or null
|
||||
function mapFromLine(Q1, l, mx, my, sc) {
|
||||
// rectify: P maps the vanishing line to infinity
|
||||
const P = [[1, 0, 0], [0, 1, 0], l];
|
||||
const Pi = inv3(P);
|
||||
@@ -659,20 +739,28 @@ function projective(img, cand) {
|
||||
// (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER
|
||||
let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk;
|
||||
if (a < 0) { a = -a; b = -b; c = -c; }
|
||||
lastProjective.ellipse = [a, b, c]; lastProjective.stage = 'ellipse';
|
||||
if (!(a > 0 && a * c - b * b > 0)) return null;
|
||||
lastProjective.stage = 'ok';
|
||||
const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q);
|
||||
// affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER
|
||||
const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]];
|
||||
const map = (x, y) => {
|
||||
return (x, y) => {
|
||||
const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y;
|
||||
const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2];
|
||||
// points beyond the vanishing line fold back: report them off image
|
||||
if (w <= 0) return [NaN, NaN];
|
||||
const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w;
|
||||
return [X * sc + mx, Y * sc + my];
|
||||
};
|
||||
lastProjective.map = map;
|
||||
return map;
|
||||
}
|
||||
|
||||
// disc conic in normalized coordinates, for the tilt search
|
||||
function discConic(img, cand) {
|
||||
const disc = discEdge(img, cand, 160);
|
||||
if (disc.length < 40) return null;
|
||||
const mx = disc.reduce((s, p) => s + p[0], 0) / disc.length, my = disc.reduce((s, p) => s + p[1], 0) / disc.length;
|
||||
const sc = Math.sqrt(disc.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / disc.length) || 1;
|
||||
const Q1 = fitConic(disc.map((p) => [(p[0] - mx) / sc, (p[1] - my) / sc]));
|
||||
return Q1 && { Q1, mx, my, sc };
|
||||
}
|
||||
|
||||
// unsharp mask on a small crop: undoes part of the camera blur and flattens slow brightness changes
|
||||
@@ -737,6 +825,56 @@ function tokenOf(bits, soft, strict = true) {
|
||||
return { token: tokenFromPayload(fixed.slice(0, fixed.length - NSYM)), fixes: bad };
|
||||
}
|
||||
|
||||
// looks like a code but the geometry is off: a screen seen at 30-45 deg bends the outer rings more than the
|
||||
// conic fit can follow. search the vanishing line directly, scored on the sync ring and the outer ring.
|
||||
// tone(u, v) reads brightness at image coordinates
|
||||
function searchTilt(img, cand, tone, best, opts) {
|
||||
const D = discConic(img, cand);
|
||||
if (!D) return null;
|
||||
const at = (map) => (x, y) => { const [u, v] = map(x, y); return tone(u, v); };
|
||||
const n0 = RING_SECTORS[0], s0 = (2 * Math.PI) / n0, nk = RING_SECTORS[3], sk = (2 * Math.PI) / nk;
|
||||
const quick = (S) => {
|
||||
let top = null;
|
||||
for (let dt = -12; dt <= 12; dt += 2) {
|
||||
const th = best.theta + (dt * Math.PI) / 180, vals = [];
|
||||
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0], sectorAngle(th, j, n0), s0));
|
||||
if (vals.some(Number.isNaN)) return null;
|
||||
const sc = Math.max(corr(vals, SYNC_BITS), corrFlat(vals));
|
||||
if (!top || sc > top.sc) top = { sc, th };
|
||||
}
|
||||
const outer = [];
|
||||
for (let j = 0; j < nk; j++) outer.push(sector(S, RADII[3], sectorAngle(top.th, j, nk), sk));
|
||||
if (outer.some(Number.isNaN)) return null;
|
||||
return top.sc + split(outer).quality;
|
||||
};
|
||||
const tryLine = (lx, ly) => {
|
||||
const map = mapFromLine(D.Q1, [lx, ly, 1], D.mx, D.my, D.sc);
|
||||
if (!map) return null;
|
||||
const S = at(map), q = quick(S);
|
||||
return q == null ? null : { q, S, l: [lx, ly] };
|
||||
};
|
||||
const tries = [];
|
||||
for (const m of [0.015, 0.03, 0.045, 0.06, 0.08, 0.1]) for (let i = 0; i < 16; i++) {
|
||||
const t = tryLine(m * Math.cos((i / 16) * 2 * Math.PI), m * Math.sin((i / 16) * 2 * Math.PI));
|
||||
if (t) tries.push(t);
|
||||
}
|
||||
tries.sort((p, q) => q.q - p.q);
|
||||
let out = null;
|
||||
for (const t of tries.slice(0, 3)) {
|
||||
// polish around the pick on a finer grid before the full read
|
||||
let pick = t;
|
||||
for (const dx of [-0.008, 0, 0.008]) for (const dy of [-0.008, 0, 0.008]) {
|
||||
if (!dx && !dy) continue;
|
||||
const c = tryLine(t.l[0] + dx, t.l[1] + dy);
|
||||
if (c && c.q > pick.q) pick = c;
|
||||
}
|
||||
const r = readRings(pick.S, opts);
|
||||
if (r && r.token) return { ...r, tilt: pick.l };
|
||||
if (r && (!out || r.score > out.score)) out = r;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// reads one candidate. returns { token, theta, score, scale, soft } or { token: null, ... } or null.
|
||||
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
|
||||
export function decodeAt(img, cand, opts = {}) {
|
||||
@@ -763,16 +901,22 @@ export function decodeAt(img, cand, opts = {}) {
|
||||
if (r && r.token) return r;
|
||||
if (r && (!best || r.score > best.score)) best = r;
|
||||
}
|
||||
if (opts.tilt !== false && best && best.score > 0.55 && best.theta != null) {
|
||||
const r = searchTilt(img, cand, (x, y) => bilinear(tone, x - x0, y - y0), best, { ...opts, span });
|
||||
if (r && r.token) return r;
|
||||
if (r && r.score > best.score) best = r;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readRings(S, opts) {
|
||||
// rotation and scale of the sync ring: { best } to go on, or { done } when the read stops here
|
||||
function findSync(S, opts) {
|
||||
const minScore = opts.minScore ?? 0.8;
|
||||
const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
|
||||
const syncAt = (theta, scale) => {
|
||||
const vals = [];
|
||||
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0));
|
||||
return vals.some(Number.isNaN) ? null : { score: corr(vals, SYNC_BITS), theta, scale, vals };
|
||||
return vals.some(Number.isNaN) ? null : { score: Math.max(corr(vals, SYNC_BITS), corrFlat(vals)), theta, scale, vals };
|
||||
};
|
||||
// coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits.
|
||||
// ~5x fewer samples than a dense search, which matters on low-end phones
|
||||
@@ -780,13 +924,13 @@ function readRings(S, opts) {
|
||||
for (const scale of opts.scales || [0.96, 1.0, 1.04]) {
|
||||
for (let t = 0; t < 72; t++) {
|
||||
const r = syncAt((t / 72) * 2 * Math.PI, scale);
|
||||
if (!r) return null;
|
||||
if (!r) return { done: null };
|
||||
coarse.push(r);
|
||||
}
|
||||
}
|
||||
coarse.sort((p, q) => q.score - p.score);
|
||||
// nothing like the sync pattern at any angle: not a code, skip the fine search
|
||||
if (coarse[0].score < 0.5) return { token: null, ...coarse[0], vals: undefined };
|
||||
if (coarse[0].score < 0.5) return { done: { token: null, ...coarse[0], vals: undefined } };
|
||||
let best = null;
|
||||
for (const c of coarse.slice(0, 3)) {
|
||||
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
|
||||
@@ -795,7 +939,13 @@ function readRings(S, opts) {
|
||||
}
|
||||
}
|
||||
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
|
||||
if (!best || best.score < minScore) return best ? { token: null, ...best, vals: undefined } : null;
|
||||
if (!best || best.score < minScore) return { done: best ? { token: null, ...best, vals: undefined } : null };
|
||||
return { best };
|
||||
}
|
||||
|
||||
function readRings(S, opts) {
|
||||
const { best, done } = findSync(S, opts);
|
||||
if (!best) return done;
|
||||
const dark = [], light = [];
|
||||
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
|
||||
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
|
||||
@@ -877,4 +1027,4 @@ export function makeReader(opts = {}) {
|
||||
}
|
||||
|
||||
// internals for the lab bench
|
||||
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf };
|
||||
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf, discConic, mapFromLine, refine };
|
||||
|
||||
+31
-17
@@ -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 };
|
||||
}
|
||||
}
|
||||
|
||||
+147
-29
@@ -1,62 +1,156 @@
|
||||
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;
|
||||
let entry = null;
|
||||
let prevBits = null, switchedAt = 0;
|
||||
let focusView = "";
|
||||
|
||||
// shows at once (css plays the entrance), hides after a short exit so blocks don't just vanish
|
||||
function reveal(el, on) {
|
||||
if (on) {
|
||||
clearTimeout(el._leave);
|
||||
el.classList.remove("leaving");
|
||||
el.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (el.hidden || el.classList.contains("leaving")) return;
|
||||
el.classList.add("leaving");
|
||||
el._leave = setTimeout(() => { el.hidden = true; el.classList.remove("leaving"); }, 220);
|
||||
}
|
||||
|
||||
// restarts a css animation class on an element that stays in the dom
|
||||
function replay(el, cls) {
|
||||
el.classList.remove(cls);
|
||||
void el.offsetWidth;
|
||||
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;
|
||||
$("#enroll").hidden = !qrOn;
|
||||
$("#focus").hidden = !focus;
|
||||
$("#idle").hidden = qrOn || !!focus;
|
||||
$(".s-main").classList.toggle("split", qrOn && !!focus);
|
||||
const ring = st.code_style === "ring";
|
||||
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : ring ? "Visez le cercle pour voter" : "Scannez pour voter";
|
||||
// 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);
|
||||
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";
|
||||
$("#entry").hidden = !(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() {
|
||||
$("#s-title").textContent = st.title;
|
||||
$("#idle-title").textContent = st.title;
|
||||
document.title = st.title;
|
||||
$("#voters").textContent = st.voters;
|
||||
if ($("#voters").textContent !== String(st.voters)) {
|
||||
$("#voters").textContent = st.voters;
|
||||
replay($("#voters"), "bump");
|
||||
}
|
||||
$("#voters-label").textContent =
|
||||
`inscription${st.voters > 1 ? "s" : ""}` + (st.expected ? ` sur ${st.expected}` : "");
|
||||
$("#secs").textContent = Math.ceil((st.scans_required * st.interval_ms) / 1000);
|
||||
|
||||
const f = st.focus;
|
||||
const box = $("#focus");
|
||||
box.replaceChildren();
|
||||
if (f) {
|
||||
box.append(h("div", { class: "q-text" }, f.text));
|
||||
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), ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`,
|
||||
h("div", { class: "progress" }, fill(pct(f.participants, st.voters), ""))),
|
||||
);
|
||||
} else if (f.results) {
|
||||
box.append(resultsView(f));
|
||||
} else {
|
||||
box.append(h("p", { class: "status" }, `Vote clos, ${f.participants} vote${f.participants > 1 ? "s" : ""}`));
|
||||
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
|
||||
paintTurnout(box.querySelector(".turnout"), f);
|
||||
} else if (view !== focusView) {
|
||||
focusView = view;
|
||||
if (f) {
|
||||
// the old question fades with the section when there is no new one
|
||||
box.replaceChildren(h("div", { class: "q-text" }, f.text));
|
||||
if (f.state === "open") {
|
||||
box.append(
|
||||
h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))),
|
||||
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));
|
||||
} else {
|
||||
box.append(h("p", { class: "status" }, `Vote clos, ${f.participants} vote${f.participants > 1 ? "s" : ""}`));
|
||||
}
|
||||
replay(box, "enter");
|
||||
}
|
||||
}
|
||||
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");
|
||||
@@ -78,10 +172,10 @@ function ringLoop(t) {
|
||||
if (c.width !== size) { c.width = c.height = size; }
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.clearRect(0, 0, size, size);
|
||||
const fadeMs = Math.min(220, qr.interval_ms * 0.25);
|
||||
const fadeMs = Math.min(700, qr.interval_ms * 0.7);
|
||||
const k = prevBits ? Math.min(1, (t - switchedAt) / fadeMs) : 1;
|
||||
drawRing(ctx, size / 2, size / 2, (size / 2) / DISC * 0.98, (t / 1000) * (2 * Math.PI / 45), qr.bits, t / 1000,
|
||||
prevBits ? { from: prevBits, k } : null);
|
||||
prevBits ? { from: prevBits, k, seed: qr.slot } : null);
|
||||
requestAnimationFrame(ringLoop);
|
||||
}
|
||||
|
||||
@@ -98,7 +192,7 @@ function animateTick() {
|
||||
}
|
||||
|
||||
let skew = 0;
|
||||
window.addEventListener("resize", paintQR);
|
||||
window.addEventListener("resize", () => { paintQR(); layout(); });
|
||||
|
||||
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
|
||||
|
||||
@@ -146,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); });
|
||||
}
|
||||
|
||||
+335
-38
@@ -1,13 +1,22 @@
|
||||
import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
|
||||
import { $, h, api, pollId, liveSocket, resultsView, toast, paintRing, icon } from "./common.js";
|
||||
import { makeRingScanner } from "./ringscan.js";
|
||||
|
||||
const pid = pollId();
|
||||
const DONE_KEY = `rv_done_${pid}`;
|
||||
const apiBase = `/api/v/${pid}`;
|
||||
|
||||
// token from the QR that opened this page, then drop it from the url bar so it isn't shared
|
||||
const firstToken = decodeURIComponent(location.hash.slice(1));
|
||||
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;
|
||||
@@ -34,9 +43,13 @@ function lsGet(k) { try { return localStorage.getItem(k); } catch { return null;
|
||||
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }
|
||||
|
||||
|
||||
// the segment fill in app.css takes .5 s, plus a beat to see the ring complete
|
||||
const FILL_MS = 650;
|
||||
let landing = false;
|
||||
|
||||
function renderDots(n) {
|
||||
const box = $("#dots");
|
||||
box.replaceChildren(ring(n, required, 150));
|
||||
paintRing(box, n, required, 150);
|
||||
box.setAttribute("aria-label", `${n} codes lus sur ${required}`);
|
||||
}
|
||||
|
||||
@@ -46,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) {
|
||||
@@ -57,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) {
|
||||
@@ -64,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.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,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;
|
||||
@@ -82,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);
|
||||
@@ -99,17 +157,76 @@ function makeScanner(video, onToken, onOther) {
|
||||
// ~15 fps cap, saves battery on fast phones
|
||||
setTimeout(loop, Math.max(0, 66 - (performance.now() - t0)));
|
||||
}
|
||||
const swap = h("button", { class: "cam-switch", type: "button", "aria-label": "Changer de caméra", hidden: true }, icon("swap", 20));
|
||||
// sensor zoom, by hand only: an automatic one made the preview jump and shook too much on cheap phones.
|
||||
// the far ring gets its pixels from the full sensor resolution instead (openCamera, ringscan)
|
||||
const zoom = h("button", { class: "cam-zoom", type: "button", "aria-label": "Zoom", hidden: true }, "1×");
|
||||
video.parentElement.append(swap, zoom);
|
||||
let zs = null;
|
||||
function setZoom(z) {
|
||||
const track = stream?.getVideoTracks()[0];
|
||||
if (!track || !zs) return;
|
||||
zs.now = z;
|
||||
zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`;
|
||||
track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; });
|
||||
}
|
||||
// a slow phone reads few frames and misses codes: past ~300 ms a frame, drop the stream to 720p once
|
||||
let slow = 0, frames = 0, dropped = false;
|
||||
function pace(ms) {
|
||||
slow = frames++ ? slow * 0.8 + ms * 0.2 : ms;
|
||||
if (dropped || frames < 6 || slow < 300 || video.videoWidth * video.videoHeight <= 1280 * 720) return;
|
||||
dropped = true;
|
||||
stream?.getVideoTracks()[0]?.applyConstraints({ width: { ideal: 1280 }, height: { ideal: 720 } }).catch(() => {});
|
||||
}
|
||||
function steer(d) {
|
||||
// people keep their seat between votes: a zoom that read the ring is where the next scan starts
|
||||
if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now));
|
||||
}
|
||||
async function attach(s) {
|
||||
stream = s;
|
||||
const track = s.getVideoTracks()[0];
|
||||
// not every browser knows focusMode, those ignore it
|
||||
track?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
|
||||
const cap = track?.getCapabilities?.().zoom;
|
||||
zs = cap && cap.max >= 1.5 ? { base: Math.max(1, cap.min), max: Math.min(cap.max, 3), now: Math.max(1, cap.min) } : null;
|
||||
zoom.hidden = !zs;
|
||||
zoom.textContent = "1×";
|
||||
video.srcObject = s;
|
||||
await video.play();
|
||||
const saved = +lsGet(ZOOM_KEY);
|
||||
if (zs && saved > zs.base) setZoom(Math.min(zs.max, saved));
|
||||
}
|
||||
zoom.onclick = () => {
|
||||
if (!zs) return;
|
||||
const steps = [zs.base, 2, 3].filter((z) => z >= zs.base && z <= zs.max);
|
||||
setZoom(steps.find((z) => z > zs.now + 0.05) ?? zs.base);
|
||||
};
|
||||
swap.onclick = async () => {
|
||||
const cams = rankCameras(await videoInputs());
|
||||
if (cams.length < 2) return;
|
||||
const cur = stream?.getVideoTracks()[0]?.getSettings().deviceId;
|
||||
const next = cams[(cams.findIndex((d) => d.deviceId === cur) + 1) % cams.length];
|
||||
stream?.getTracks().forEach((t) => t.stop());
|
||||
try { await attach(await openCamera(next.deviceId)); lsSet(CAM_KEY, next.deviceId); }
|
||||
catch { await attach(await openCamera(null)); }
|
||||
};
|
||||
return {
|
||||
async start() {
|
||||
// rings from the back of a room are a few dozen pixels wide at 720p, ask for the full sensor
|
||||
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: w }, height: { ideal: h } },
|
||||
});
|
||||
// not every browser knows focusMode, those ignore it
|
||||
stream.getVideoTracks()[0]?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
|
||||
video.srcObject = stream;
|
||||
await video.play();
|
||||
const saved = lsGet(CAM_KEY);
|
||||
let s = null;
|
||||
if (saved) s = await openCamera(saved).catch(() => null);
|
||||
s ||= await openCamera(null);
|
||||
// some browsers ignore facingMode or hand over the ultra wide: switch to the main back lens when labels say so
|
||||
const track = s.getVideoTracks()[0], cams = await videoInputs();
|
||||
if (!saved && cams.length > 1 && (track.getSettings().facingMode === "user" || !isMainBack(track.label))) {
|
||||
const best = rankCameras(cams)[0];
|
||||
if (best && best.deviceId !== track.getSettings().deviceId) {
|
||||
s.getTracks().forEach((t) => t.stop());
|
||||
s = await openCamera(best.deviceId).catch(() => null) || await openCamera(null);
|
||||
}
|
||||
}
|
||||
swap.hidden = cams.length < 2;
|
||||
await attach(s);
|
||||
running = true;
|
||||
loop();
|
||||
},
|
||||
@@ -118,17 +235,46 @@ function makeScanner(video, onToken, onOther) {
|
||||
stream?.getTracks().forEach((t) => t.stop());
|
||||
video.srcObject = null;
|
||||
},
|
||||
destroy() {},
|
||||
destroy() { swap.remove(); zoom.remove(); },
|
||||
};
|
||||
}
|
||||
|
||||
const CAM_KEY = "rv_cam";
|
||||
const ZOOM_KEY = `rv_zoom_${pid}`;
|
||||
const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i;
|
||||
|
||||
function openCamera(deviceId) {
|
||||
// rings from the back of a room are a few dozen pixels wide at 720p. 4k was tried: a mid-range android took
|
||||
// it and fell to one frame every 2 s, so 1080p, and 720p on phones too slow for that (pace)
|
||||
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
|
||||
const base = { width: { ideal: w }, height: { ideal: h } };
|
||||
return navigator.mediaDevices.getUserMedia({
|
||||
audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } },
|
||||
});
|
||||
}
|
||||
|
||||
async function videoInputs() {
|
||||
try { return (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput"); }
|
||||
catch { return []; }
|
||||
}
|
||||
|
||||
// without a label we can't tell, so trust what facingMode gave
|
||||
const isMainBack = (label) => !label || (!FRONT.test(label) && !ODD.test(label));
|
||||
|
||||
// main back lens first, other back lenses next, front last. android lists its main back camera first
|
||||
function rankCameras(cams) {
|
||||
const score = (d) => (FRONT.test(d.label) ? -4 : 0) + (ODD.test(d.label) ? -2 : 0) + (BACK.test(d.label) ? 1 : 0);
|
||||
return cams.map((d, i) => ({ d, i, s: score(d) })).sort((a, b) => b.s - a.s || a.i - b.i).map((x) => x.d);
|
||||
}
|
||||
|
||||
// token of a code shown for this poll, null for anything else
|
||||
// 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() {
|
||||
@@ -140,9 +286,55 @@ function stopScanner() {
|
||||
}
|
||||
|
||||
function onScan(token) {
|
||||
if (sent.has(token)) return;
|
||||
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) {
|
||||
@@ -169,7 +361,11 @@ function handleScan(r) {
|
||||
$("#code").focus();
|
||||
break;
|
||||
case "enrolled":
|
||||
enrolled();
|
||||
// the 5th code answers "enrolled" straight away: fill the last segment and let it land first
|
||||
if (landing) break;
|
||||
landing = true;
|
||||
renderDots(required);
|
||||
setTimeout(() => { landing = false; enrolled(); }, FILL_MS);
|
||||
break;
|
||||
case "closed":
|
||||
block("Inscriptions closes.");
|
||||
@@ -180,13 +376,45 @@ function handleScan(r) {
|
||||
}
|
||||
}
|
||||
|
||||
function enrolled() {
|
||||
function enrolled(viaCam = false) {
|
||||
stopScanner();
|
||||
lsSet(DONE_KEY, "1");
|
||||
navigator.vibrate?.([40, 60, 40]);
|
||||
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 mark(withTick) {
|
||||
const svg = document.createElementNS(MARK_NS, "svg");
|
||||
svg.setAttribute("viewBox", "0 0 32 32");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const g = document.createElementNS(MARK_NS, "g");
|
||||
g.setAttribute("transform", "rotate(-90 16 16)");
|
||||
for (const [stroke, dash] of [["currentColor", "4.52 7"], ["#ffcc00", "4.52 64.6"]]) {
|
||||
const c = document.createElementNS(MARK_NS, "circle");
|
||||
for (const [k, v] of Object.entries({ cx: 16, cy: 16, r: 11, fill: "none", stroke, "stroke-width": 5,
|
||||
"stroke-linecap": "round", "stroke-dasharray": dash, "stroke-dashoffset": -3.5 })) c.setAttribute(k, v);
|
||||
g.append(c);
|
||||
}
|
||||
const tick = document.createElementNS(MARK_NS, "path");
|
||||
for (const [k, v] of Object.entries({ d: "M12.8 16.15l2.3 2.3 4.25-4.75", fill: "none", stroke: "currentColor", "stroke-width": 2.4,
|
||||
"stroke-linecap": "round", "stroke-linejoin": "round", pathLength: 1, class: "tick" })) tick.setAttribute(k, v);
|
||||
svg.append(g);
|
||||
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);
|
||||
// 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);
|
||||
|
||||
$("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); });
|
||||
@@ -239,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();
|
||||
@@ -305,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);
|
||||
toast("Vote enregistré", "ok");
|
||||
// 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");
|
||||
@@ -324,32 +571,62 @@ 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 = [];
|
||||
const paint = () => $("#p-ring").replaceChildren(ring(got.length, n, 120));
|
||||
// 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) => {
|
||||
if (got.includes(t)) return;
|
||||
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) finish(got);
|
||||
if (got.length >= n) setTimeout(() => finish(got), FILL_MS);
|
||||
});
|
||||
let done, finished = false;
|
||||
const result = new Promise((res) => { done = res; });
|
||||
function finish(value) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -366,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(); }
|
||||
@@ -390,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");
|
||||
@@ -402,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();
|
||||
|
||||
@@ -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>
|
||||
@@ -165,14 +165,14 @@ window.runSeq = async (cfg) => {
|
||||
for (const name of cfg.pipes) res[name] = { got: [], false: 0, frames: 0, ms: 0, first5: null };
|
||||
for (const key of Object.keys(scanners)) delete scanners[key];
|
||||
let px = 0, py = 0;
|
||||
const fadeMs = Math.min(220, s.interval * 0.25), t00 = s.t0 || 0;
|
||||
const fadeMs = Math.min(700, s.interval * (s.fadeK || 0.7)), t00 = s.t0 || 0;
|
||||
for (let i = 0; i < s.fps * s.secs; i++) {
|
||||
const ms = t00 + (i * 1000) / s.fps + rnd() * 20, slot = Math.floor(ms / s.interval), idx = slot - Math.floor(t00 / s.interval);
|
||||
const cur = s.tokens[idx], prev = idx > 0 ? s.tokens[idx - 1] : null, since = ms - slot * s.interval;
|
||||
// hand shake: drifting offset plus a random smear for this exposure
|
||||
px = px * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3; py = py * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3;
|
||||
const t = { ...s, bits: cur.bits, token: cur.token, theta: (ms / 1000) * (2 * Math.PI / 45), anim: ms / 1000,
|
||||
fade: prev && since < fadeMs ? { from: prev.bits, k: since / fadeMs } : null,
|
||||
fade: prev && since < fadeMs ? { from: prev.bits, k: since / fadeMs, seed: slot } : null,
|
||||
dx: (s.dx || 0) + px * (s.W / 1280), dy: (s.dy || 0) + py * (s.W / 1280),
|
||||
motion: [(rnd() - 0.5) * 2 * s.shake, (rnd() - 0.5) * 2 * s.shake], now: ms };
|
||||
const f = frame(room, t, rnd);
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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
@@ -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;
|
||||
});
|
||||
|
||||
@@ -12,8 +12,10 @@ for (const ms of [1000, 500]) {
|
||||
}
|
||||
|
||||
let slot = 0, bits = "", prevBits = "", switchedAt = 0, idx = 0;
|
||||
// changed dashes cross-fade over a short time, a few frames are then unreadable, which is fine
|
||||
const FADE = Math.min(220, MS * 0.25);
|
||||
// changed dashes wipe over a short time, a few frames are then unreadable, which is fine
|
||||
// ?fade=0.5 tries a longer wipe, as a share of the interval
|
||||
const FADE = params.get("fade") ? MS * +params.get("fade") : Math.min(700, MS * 0.7);
|
||||
const EASE = params.get("ease") || "sine";
|
||||
function tick() {
|
||||
prevBits = bits || null;
|
||||
switchedAt = performance.now();
|
||||
@@ -34,7 +36,7 @@ function frame(t) {
|
||||
if (MODE === "ring") {
|
||||
// one full turn every 45 s
|
||||
const k = prevBits ? Math.min(1, (t - switchedAt) / FADE) : 1;
|
||||
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, t / 1000, prevBits ? { from: prevBits, k } : null);
|
||||
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, t / 1000, prevBits ? { from: prevBits, k, seed: slot, ease: EASE } : null);
|
||||
} else {
|
||||
const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8));
|
||||
const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2;
|
||||
|
||||
@@ -76,6 +76,7 @@ function page(pw, ph, d, t, rnd) {
|
||||
}
|
||||
|
||||
// one sensor frame. t: W H frac tilt axis dist wash cast oblur pblur motion noise band gain dx dy theta bits anim fade
|
||||
// glare: [dx, dy, radius, strength 0..1, tint] around the code centre, in code diameters
|
||||
// returns { canvas, truth } where truth maps code space to pixel index coordinates of the frame
|
||||
export function frame(room, t, rnd) {
|
||||
const { W, H } = t, ss = 2;
|
||||
@@ -117,6 +118,16 @@ export function frame(room, t, rnd) {
|
||||
sctx.imageSmoothingQuality = "high";
|
||||
sctx.drawImage(B, x0, y0, x1 - x0, y1 - y0);
|
||||
}
|
||||
if (t.glare) {
|
||||
// reflection of a window or lamp on the screen: a tinted bright veil over part of the code
|
||||
const [gx, gy, gr, gs, tint] = t.glare, [ccx, ccy] = applyH(fwd, P.cx, P.cy);
|
||||
const x = ccx + gx * d, y = ccy + gy * d, g = sctx.createRadialGradient(x, y, 0, x, y, gr * d);
|
||||
const [tr, tg, tb] = tint || [255, 235, 245];
|
||||
g.addColorStop(0, `rgba(${tr},${tg},${tb},${gs})`); g.addColorStop(0.5, `rgba(${tr},${tg},${tb},${gs * 0.6})`); g.addColorStop(1, `rgba(${tr},${tg},${tb},0)`);
|
||||
sctx.globalCompositeOperation = "screen";
|
||||
sctx.fillStyle = g; sctx.fillRect(0, 0, W, H);
|
||||
sctx.globalCompositeOperation = "source-over";
|
||||
}
|
||||
const out = document.createElement("canvas"); out.width = W; out.height = H;
|
||||
const octx = out.getContext("2d", { willReadFrequently: true });
|
||||
// optical blur is angular (scales with sensor resolution), pixel softness is not
|
||||
|
||||
+15
-5
@@ -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> s</span></li>
|
||||
<li id="step2"><span>Visez le cercle <b id="secs">5</b> 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
@@ -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>
|
||||
|
||||
+217
-32
@@ -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,17 +169,28 @@ 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"
|
||||
|
||||
# closed too early: reopening keeps the ballots and the voted flags
|
||||
assert admin(server, p, "POST", f"/questions/{qid}/reopen").status_code == 200
|
||||
r = await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [1]})
|
||||
assert r.status_code == 409 and r.json()["error"] == "already_voted"
|
||||
assert admin(server, p, "POST", f"/questions/{qid}/close").status_code == 200
|
||||
|
||||
# voters only see results once published
|
||||
me = (await a.get(f"/api/v/{p['id']}/me")).json()
|
||||
assert me["questions"] == []
|
||||
admin(server, p, "POST", f"/questions/{qid}/publish")
|
||||
me = (await a.get(f"/api/v/{p['id']}/me")).json()
|
||||
assert me["questions"][0]["results"]["counts"] == [1, 0]
|
||||
# once the room has seen the tally there is no going back, even after hiding it
|
||||
admin(server, p, "POST", f"/questions/{qid}/unpublish")
|
||||
r = admin(server, p, "POST", f"/questions/{qid}/reopen")
|
||||
assert r.status_code == 400 and r.json()["error"] == "already_shown"
|
||||
await a.aclose()
|
||||
await b.aclose()
|
||||
|
||||
@@ -190,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():
|
||||
@@ -200,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())
|
||||
@@ -444,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",
|
||||
@@ -508,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())
|
||||
@@ -616,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})
|
||||
@@ -631,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"]
|
||||
@@ -667,3 +660,195 @@ def test_entry_redirect(server):
|
||||
p = create(server)
|
||||
r = httpx.get(f"{server['base']}/V/{p['id'].upper()}", follow_redirects=False, verify=server["verify"])
|
||||
assert r.status_code == 301 and r.headers["location"] == f"/v/{p['id']}"
|
||||
|
||||
|
||||
def test_trial_enrolls_then_expires(server):
|
||||
r = httpx.post(server["base"] + "/api/trial", verify=server["verify"])
|
||||
assert r.status_code == 200
|
||||
p = r.json()
|
||||
assert "admin_key" not in p
|
||||
|
||||
async def run():
|
||||
async with projector(server, p) as next_token:
|
||||
c = await enroll(server, p, next_token)
|
||||
# nobody can push a question on a trial, the first phone in opens the sample one
|
||||
me = (await c.get(f"/api/v/{p['id']}/me")).json()
|
||||
q = next(q for q in me["questions"] if q["state"] == "open")
|
||||
assert me["vote_scans"] == 3
|
||||
fresh = [await next_token() for _ in range(3)]
|
||||
r = await c.post(f"/api/v/{p['id']}/vote", json={"question_id": q["id"], "choices": [0], "presence": fresh})
|
||||
assert r.status_code == 200, r.text
|
||||
await c.aclose()
|
||||
|
||||
asyncio.run(run())
|
||||
# age it past the ttl, the next trial sweeps it away with everything it held
|
||||
con = sqlite3.connect(server["db"])
|
||||
con.execute("UPDATE polls SET created_at=created_at-? WHERE id=?", (3 * 3600 * 1000, p["id"]))
|
||||
con.commit()
|
||||
assert httpx.post(server["base"] + "/api/trial", verify=server["verify"]).status_code == 200
|
||||
assert con.execute("SELECT COUNT(*) FROM polls WHERE id=?", (p["id"],)).fetchone()[0] == 0
|
||||
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())
|
||||
|
||||
+1
-71
@@ -1,13 +1,10 @@
|
||||
"""tiny chrome devtools protocol client: headless chrome, pages, eval, screencast"""
|
||||
"""tiny chrome devtools protocol client for the ring bench: headless chrome, pages, eval"""
|
||||
import asyncio
|
||||
import base64
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import websockets
|
||||
@@ -96,7 +93,6 @@ class Page:
|
||||
def __init__(self, browser, sid, w, h, dsf):
|
||||
self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf
|
||||
self.load = None
|
||||
self.frames = None
|
||||
|
||||
def send(self, method, params=None):
|
||||
return self.b.send(method, params, self.sid)
|
||||
@@ -104,15 +100,6 @@ class Page:
|
||||
def _event(self, method, params):
|
||||
if method == "Page.loadEventFired" and self.load and not self.load.done():
|
||||
self.load.set_result(True)
|
||||
elif method == "Page.screencastFrame":
|
||||
if self.frames is not None:
|
||||
ts = params["metadata"].get("timestamp", time.time())
|
||||
path = os.path.join(self.frame_dir, f"{len(self.frames):06d}.jpg")
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(params["data"]))
|
||||
self.frames.append((ts, path))
|
||||
asyncio.get_running_loop().create_task(
|
||||
self.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]}))
|
||||
|
||||
async def goto(self, url):
|
||||
self.load = asyncio.get_running_loop().create_future()
|
||||
@@ -124,60 +111,3 @@ class Page:
|
||||
if "exceptionDetails" in r:
|
||||
raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"]))
|
||||
return r.get("result", {}).get("value")
|
||||
|
||||
async def on_new_document(self, source):
|
||||
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": source})
|
||||
|
||||
async def record(self, frame_dir):
|
||||
os.makedirs(frame_dir, exist_ok=True)
|
||||
self.frame_dir = frame_dir
|
||||
self.frames = []
|
||||
await self.send("Page.startScreencast", {"format": "jpeg", "quality": 90,
|
||||
"maxWidth": int(self.w * self.dsf), "maxHeight": int(self.h * self.dsf)})
|
||||
|
||||
async def stop(self):
|
||||
if getattr(self, "shooter", None):
|
||||
self.shooting = False
|
||||
try:
|
||||
await asyncio.wait_for(self.shooter, 3)
|
||||
except Exception:
|
||||
self.shooter.cancel()
|
||||
else:
|
||||
try:
|
||||
await asyncio.wait_for(self.send("Page.stopScreencast"), 3)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def record_shots(self, frame_dir, fps=24):
|
||||
"""screenshot polling: slower than screencast but honours deviceScaleFactor"""
|
||||
os.makedirs(frame_dir, exist_ok=True)
|
||||
self.frames, self.shooting = [], True
|
||||
|
||||
async def loop():
|
||||
while self.shooting:
|
||||
t = time.time()
|
||||
r = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": 90})
|
||||
path = os.path.join(frame_dir, f"{len(self.frames):06d}.jpg")
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(r["data"]))
|
||||
self.frames.append((t, path))
|
||||
await asyncio.sleep(max(0, 1 / fps - (time.time() - t)))
|
||||
self.shooter = asyncio.get_running_loop().create_task(loop())
|
||||
|
||||
async def png(self, path, transparent=False):
|
||||
if transparent:
|
||||
await self.send("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}})
|
||||
r = await self.send("Page.captureScreenshot", {"format": "png"})
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(r["data"]))
|
||||
|
||||
async def mouse(self, kind, x, y, button="left", clicks=1):
|
||||
await self.send("Input.dispatchMouseEvent",
|
||||
{"type": kind, "x": x, "y": y, "button": button, "clickCount": clicks})
|
||||
|
||||
async def type(self, text, rng, target="document.activeElement"):
|
||||
# write into the field directly: focus can drift between headless targets while screenshotting
|
||||
await self.js(f"window.__tt = {target}; __tt.focus()")
|
||||
for ch in text:
|
||||
await self.js("__tt.value += " + json.dumps(ch) + "; __tt.dispatchEvent(new Event('input', {bubbles: true}))")
|
||||
await asyncio.sleep(rng.uniform(0.05, 0.14) + (0.18 if ch == " " and rng.random() < 0.2 else 0))
|
||||
|
||||
+51
-8
@@ -1,7 +1,7 @@
|
||||
"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome,
|
||||
runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]
|
||||
env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300
|
||||
CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)"""
|
||||
env: SUITE=legacy,far,glare,seq,neg (default all but glare) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300
|
||||
IV=700 FADE_K=0.3 (sequence code interval and wipe share) CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)"""
|
||||
import asyncio
|
||||
import base64
|
||||
import collections
|
||||
@@ -22,7 +22,7 @@ sys.path.insert(0, str(ROOT / "tools"))
|
||||
from cdp import Browser # noqa: E402
|
||||
from rotatyvote import ringcode # noqa: E402
|
||||
|
||||
PORT = 8200
|
||||
PORT = int(os.environ.get("BENCH_PORT", "8200"))
|
||||
V1 = bool(os.environ.get("V1"))
|
||||
rng = random.Random(11)
|
||||
|
||||
@@ -55,7 +55,7 @@ def code(r):
|
||||
|
||||
|
||||
# washed projector: (black level, white level) of the screen as the camera sees it
|
||||
WASH = {0.45: (80, 195), 0.3: (105, 181)}
|
||||
WASH = {1.0: (0, 255), 0.45: (80, 195), 0.3: (105, 181)}
|
||||
SENSORS = {1280: (1280, 720), 1920: (1920, 1080)}
|
||||
|
||||
|
||||
@@ -84,6 +84,44 @@ def far_trials(n):
|
||||
return out
|
||||
|
||||
|
||||
def glare_trials(n):
|
||||
"""a reflection on the screen lights part of the code, often with a laptop lid or screen seen at an angle"""
|
||||
r = random.Random(53)
|
||||
out = []
|
||||
for d, tilt, strength, contrast in itertools.product([150, 250, 350], [0, 30, 45], [0.35, 0.6], [1.0, 0.45]):
|
||||
for _ in range(n):
|
||||
t = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
|
||||
a, k = r.uniform(0, 6.283), r.uniform(0.1, 0.6)
|
||||
tint = r.choice([(255, 235, 245), (255, 250, 230), (230, 240, 255)])
|
||||
t.update(code(r), tilt=tilt, glare=[k * math.cos(a), k * math.sin(a), r.uniform(0.5, 1.1), strength, tint],
|
||||
glareS=strength, jpeg=r.choice([0, 0.6]))
|
||||
out.append(t)
|
||||
return out
|
||||
|
||||
|
||||
async def run_glare(p, n, pipes):
|
||||
diag = os.environ.get("DIAG")
|
||||
res = await chunks(p, "runFar", "trials", glare_trials(n), {"pipes": pipes, "keep": 3, "diag": diag}, 10)
|
||||
print(f"\n== reflection on the screen, single frames ({len(res)} frames), 1920 sensor ==")
|
||||
table(res, ("d", "tilt", "glareS", "contrast"), pipes)
|
||||
for pn in pipes:
|
||||
wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"])
|
||||
print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, false tokens {wrong}")
|
||||
if diag:
|
||||
# where failing frames break when the true geometry is substituted stage by stage
|
||||
for key in ("tilt", "glareS"):
|
||||
for v in sorted({r[key] for r in res}):
|
||||
sub = [r for r in res if r[key] == v and not r[pipes[0]]["ok"]]
|
||||
st = collections.Counter(r["diag"]["stage"] for r in sub)
|
||||
print(f" {key} {v}: {len(sub)} failures by stage {dict(st)} oracle sync {sum((r['diag']['oracleScore'] or 0) for r in sub) / max(1, len(sub)):.2f}"
|
||||
f" byte errs with true geometry {sum(r['diag']['byteErr'] for r in sub) / max(1, len(sub)):.1f}")
|
||||
out = ROOT / "tools" / "bench_out"
|
||||
out.mkdir(exist_ok=True)
|
||||
for i, r in enumerate(res[:3]):
|
||||
if r.get("png"):
|
||||
(out / f"glare_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
|
||||
|
||||
|
||||
def neg_trials(n):
|
||||
"""nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around"""
|
||||
r = random.Random(31)
|
||||
@@ -98,11 +136,14 @@ 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)
|
||||
s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=500, shake=r.uniform(0.3, 1.2),
|
||||
tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * 500 + r.uniform(0, 400))
|
||||
iv = int(os.environ.get("IV", "500"))
|
||||
s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=iv, shake=r.uniform(0.3, 1.2),
|
||||
fadeK=float(os.environ.get("FADE_K", "0.25")),
|
||||
tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * iv + r.uniform(0, iv * 0.8))
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
@@ -225,7 +266,7 @@ async def main():
|
||||
break
|
||||
except httpx.HTTPError:
|
||||
await asyncio.sleep(0.1)
|
||||
b = Browser(9336)
|
||||
b = Browser(int(os.environ.get("CDP_PORT", "9336")))
|
||||
await b.start()
|
||||
p = await b.page(960, 720)
|
||||
throttle = float(os.environ.get("CPU", "1"))
|
||||
@@ -241,6 +282,8 @@ async def main():
|
||||
await run_legacy(p, n)
|
||||
if "far" in suites:
|
||||
await run_far(p, n, pipes, os.environ.get("DIAG"))
|
||||
if "glare" in suites:
|
||||
await run_glare(p, n, pipes)
|
||||
if "seq" in suites:
|
||||
await run_seq(p, max(1, n // 2), pipes)
|
||||
if "neg" in suites:
|
||||
|
||||
Reference in New Issue
Block a user