Files
taboada-generador-qr/app.py
T
collina-adminandClaude Opus 4.8 dd8eb0b0f8 App QR de checada Taboada (Python/Tkinter, PyInstaller)
Contrato identico al verificador de Node:
  contador = floor(unix_utc/45)
  codigo   = HMAC-SHA256(SEMILLA, 'q1|'+contador)[0..15] base64url sin padding
  token    = q1.<base36(contador)>.<codigo>
Vector canonico verificado: q1.md56o.Jo2Q_p4tq_sTY9A9YGj-7A

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 18:48:22 -06:00

185 lines
6.5 KiB
Python

"""
App de escritorio (Windows / macOS) que muestra el QR de checada de Taboada.
- QR grande centrado, rota cada 45 s (mismo contrato que el verificador de Node).
- Offline: solo necesita semilla.key junto al ejecutable.
- Esquina: hora UTC + contador, para verificar sincronia contra el servidor de un vistazo.
- Boton "Crear semilla nueva": genera 32 bytes, los guarda y muestra el hex para pegar
en SEMILLA_QR del servidor.
"""
import time
import tkinter as tk
from tkinter import messagebox, scrolledtext
import qrcode
from PIL import Image, ImageTk
import qr_contract as qc
INTERVALO_MS = 200 # cada cuanto revisamos el reloj
FONDO = "#0f172a" # slate-900
FONDO_QR = "#ffffff"
TEXTO = "#e2e8f0" # slate-200
ACENTO = "#38bdf8" # sky-400
class AppQR(tk.Tk):
def __init__(self):
super().__init__()
self.title("Checada Taboada — QR rotativo")
self.configure(bg=FONDO)
self.geometry("720x820")
self.minsize(480, 620)
self.semilla = None
self._contador_dibujado = None
self._qr_tk = None
self._lado_qr_dibujado = 0
self._construir_ui()
self._cargar_semilla_inicial()
self.bind("<Configure>", self._on_resize)
self._tick()
# ------------------------------------------------------------------ UI
def _construir_ui(self):
# Zona del QR (centro, se expande)
self.marco_qr = tk.Frame(self, bg=FONDO)
self.marco_qr.pack(fill="both", expand=True, padx=24, pady=(24, 8))
self.lbl_qr = tk.Label(self.marco_qr, bg=FONDO)
self.lbl_qr.place(relx=0.5, rely=0.5, anchor="center")
# Barra inferior: estado UTC/contador + boton
barra = tk.Frame(self, bg=FONDO)
barra.pack(fill="x", padx=24, pady=(0, 20))
self.lbl_estado = tk.Label(
barra, text="", bg=FONDO, fg=TEXTO,
font=("Menlo", 13), justify="left", anchor="w",
)
self.lbl_estado.pack(side="left")
self.btn_semilla = tk.Button(
barra, text="Crear semilla nueva", command=self._crear_semilla,
bg=ACENTO, fg="#082f49", activebackground="#7dd3fc",
relief="flat", font=("Helvetica", 12, "bold"),
padx=14, pady=8, cursor="hand2",
)
self.btn_semilla.pack(side="right")
def _cargar_semilla_inicial(self):
try:
self.semilla = qc.cargar_semilla()
except FileNotFoundError:
self.semilla = None
self._mostrar_mensaje_qr("No hay semilla.key\n\nPulsa «Crear semilla nueva»\npara generarla.")
except Exception as e:
self.semilla = None
self._mostrar_mensaje_qr("semilla.key invalida:\n%s" % e)
# -------------------------------------------------------------- reloj
def _tick(self):
ahora = time.time()
contador = qc.contador_actual(ahora)
utc = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ahora))
restante = qc.PERIODO - int(ahora % qc.PERIODO)
estado = "UTC %s\nContador %d (rota en %ds)" % (utc, contador, restante)
self.lbl_estado.config(text=estado)
if self.semilla is not None and contador != self._contador_dibujado:
self._dibujar_qr(contador)
self._contador_dibujado = contador
self.after(INTERVALO_MS, self._tick)
# ---------------------------------------------------------------- QR
def _lado_disponible(self) -> int:
self.marco_qr.update_idletasks()
w = self.marco_qr.winfo_width()
h = self.marco_qr.winfo_height()
return max(160, min(w, h) - 20)
def _dibujar_qr(self, contador: int):
url = qc.calcular_url(self.semilla, contador)
lado = self._lado_disponible()
qr = qrcode.QRCode(
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10, border=2,
)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white").convert("RGB")
img = img.resize((lado, lado), Image.NEAREST)
self._qr_tk = ImageTk.PhotoImage(img)
self.lbl_qr.config(image=self._qr_tk, text="")
self._lado_qr_dibujado = lado
def _mostrar_mensaje_qr(self, texto: str):
self.lbl_qr.config(
image="", text=texto, fg=TEXTO, bg=FONDO,
font=("Helvetica", 16), justify="center",
)
self._qr_tk = None
def _on_resize(self, event):
# Redibuja si el tamano cambio de forma apreciable
if self.semilla is None or self._contador_dibujado is None:
return
if abs(self._lado_disponible() - self._lado_qr_dibujado) > 12:
self._dibujar_qr(self._contador_dibujado)
# ------------------------------------------------------------ semilla
def _crear_semilla(self):
if self.semilla is not None:
ok = messagebox.askyesno(
"Crear semilla nueva",
"Ya existe una semilla.\n\n"
"Si creas una nueva, DEBES pegar el hex en SEMILLA_QR del servidor "
"o las checadas dejaran de validar.\n\n¿Continuar?",
)
if not ok:
return
self.semilla = qc.crear_semilla_nueva()
self._contador_dibujado = None # fuerza redibujo
self._mostrar_hex(self.semilla.hex())
def _mostrar_hex(self, hexdata: str):
top = tk.Toplevel(self)
top.title("Semilla nueva — pegar en el servidor")
top.configure(bg=FONDO)
top.geometry("560x260")
top.transient(self)
top.grab_set()
tk.Label(
top, bg=FONDO, fg=TEXTO, justify="left", font=("Helvetica", 12),
text="Guardada en semilla.key.\nPega este hex en la variable SEMILLA_QR del servidor:",
).pack(anchor="w", padx=18, pady=(16, 8))
caja = scrolledtext.ScrolledText(top, height=4, wrap="char",
font=("Menlo", 13), bg="#1e293b", fg=ACENTO)
caja.insert("1.0", hexdata)
caja.configure(state="normal")
caja.pack(fill="x", padx=18)
def copiar():
self.clipboard_clear()
self.clipboard_append(hexdata)
btn.config(text="¡Copiado!")
btn = tk.Button(top, text="Copiar al portapapeles", command=copiar,
bg=ACENTO, fg="#082f49", relief="flat",
font=("Helvetica", 12, "bold"), padx=14, pady=8, cursor="hand2")
btn.pack(pady=16)
if __name__ == "__main__":
AppQR().mainloop()