- generador/: ficha.py (validación cliente.yml), registro.py (registry.json + puertos), plantillas.py (.env/compose/README/scripts), nucleo.py (estampar/validar_paquete/desplegar), evolution.py (API client), CLI python -m generador (estampar|validar|whatsapp|desplegar|listar|eliminar) - src/api/webhook_evolution.py: adaptador webhook nativo Evolution → WebhookMessage (réplicas sin n8n); registrado en main.py - fichas/ejemplo-demo.yml: ficha demo con credenciales falsas - Solo-generar es default; --desplegar explícito. El generador solo LEE el molde (git archive de HEAD) y ESCRIBE en replicas/ (gitignored) - 31 tests nuevos (Evolution mockeado con httpx.MockTransport): 158 verdes Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
250 lines
9.0 KiB
Python
250 lines
9.0 KiB
Python
"""CLI del generador de réplicas.
|
|
|
|
python -m generador estampar fichas/cliente.yml # solo-generar (default)
|
|
python -m generador estampar fichas/cliente.yml --desplegar
|
|
python -m generador validar <slug>
|
|
python -m generador whatsapp <slug> # aprovisiona Evolution + QR + espera
|
|
python -m generador desplegar <slug> # levanta un paquete ya estampado
|
|
python -m generador listar
|
|
python -m generador eliminar <slug> [--borrar-carpeta] [--borrar-instancia]
|
|
"""
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import shutil
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from generador.nucleo import (
|
|
DIR_REPLICAS,
|
|
ErrorEstampado,
|
|
Registro,
|
|
desplegar_paquete,
|
|
estampar,
|
|
validar_paquete,
|
|
_leer_env,
|
|
)
|
|
from generador.registro import ErrorRegistro
|
|
|
|
|
|
def _imprimir_checks(checks) -> None:
|
|
for c in checks:
|
|
icono = "✅" if c.ok else "❌"
|
|
detalle = f" ({c.detalle})" if c.detalle and not c.ok else ""
|
|
print(f" {icono} {c.nombre}{detalle}")
|
|
|
|
|
|
def cmd_estampar(args) -> int:
|
|
desplegar = args.desplegar and not args.solo_generar
|
|
try:
|
|
r = estampar(
|
|
args.ficha,
|
|
permitir_sucio=args.permitir_sucio,
|
|
desplegar=desplegar,
|
|
)
|
|
except (ErrorEstampado, ErrorRegistro) as e:
|
|
if args.json:
|
|
print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False))
|
|
else:
|
|
print(f"❌ {e}", file=sys.stderr)
|
|
return 1
|
|
if args.json:
|
|
print(json.dumps({
|
|
"ok": r.ok, "slug": r.slug, "carpeta": r.carpeta,
|
|
"puerto": r.puerto, "estado": r.estado,
|
|
"checks": [{"nombre": c.nombre, "ok": c.ok, "detalle": c.detalle} for c in r.checks],
|
|
}, ensure_ascii=False))
|
|
return 0 if r.ok else 1
|
|
print(f"{'✅' if r.ok else '❌'} Réplica '{r.slug}' → {r.estado}")
|
|
print(f" carpeta: {r.carpeta}")
|
|
print(f" puerto: {r.puerto}")
|
|
print(f" molde: commit {r.commit_molde[:9]}")
|
|
_imprimir_checks(r.checks)
|
|
if r.ok and not desplegar:
|
|
print("\nSiguientes pasos:")
|
|
print(f" cd {r.carpeta} && docker compose up -d --build")
|
|
print(" python3 conectar_whatsapp.py # vincular WhatsApp (QR)")
|
|
return 0 if r.ok else 1
|
|
|
|
|
|
def cmd_validar(args) -> int:
|
|
paquete = _resolver_paquete(args.slug)
|
|
if paquete is None:
|
|
return 1
|
|
checks = validar_paquete(paquete, Registro(DIR_REPLICAS / "registry.json"))
|
|
_imprimir_checks(checks)
|
|
ok = all(c.ok for c in checks)
|
|
print("✅ paquete válido" if ok else "❌ paquete con problemas")
|
|
return 0 if ok else 1
|
|
|
|
|
|
def cmd_whatsapp(args) -> int:
|
|
from generador.evolution import ClienteEvolution, ErrorEvolution, aprovisionar
|
|
|
|
paquete = _resolver_paquete(args.slug)
|
|
if paquete is None:
|
|
return 1
|
|
env = _leer_env(paquete / ".env")
|
|
cliente = ClienteEvolution(env["EVOLUTION_API_URL"], env["EVOLUTION_API_KEY"])
|
|
try:
|
|
estado = aprovisionar(cliente, args.slug, env["BASE_URL"])
|
|
if estado == "open":
|
|
print("✅ WhatsApp ya vinculado. Nada más que hacer.")
|
|
return 0
|
|
qr = cliente.obtener_qr(args.slug)
|
|
b64 = (qr.get("base64") or "").split(",")[-1]
|
|
if b64:
|
|
ruta_qr = paquete / "qr-whatsapp.png"
|
|
ruta_qr.write_bytes(base64.b64decode(b64))
|
|
print(f"QR guardado en {ruta_qr} — escanéalo desde el teléfono del cliente:")
|
|
print(" WhatsApp → Ajustes → Dispositivos vinculados → Vincular dispositivo")
|
|
elif qr.get("pairingCode"):
|
|
print(f"Código de vinculación: {qr['pairingCode']}")
|
|
print("Esperando escaneo (Ctrl-C para salir)…")
|
|
transcurrido = 0
|
|
while True:
|
|
time.sleep(5)
|
|
if cliente.estado_conexion(args.slug) == "open":
|
|
print("✅ WhatsApp vinculado. La réplica ya recibe mensajes.")
|
|
return 0
|
|
transcurrido += 5
|
|
if transcurrido >= 50:
|
|
print("Renovando QR…")
|
|
qr = cliente.obtener_qr(args.slug)
|
|
b64 = (qr.get("base64") or "").split(",")[-1]
|
|
if b64:
|
|
(paquete / "qr-whatsapp.png").write_bytes(base64.b64decode(b64))
|
|
transcurrido = 0
|
|
except ErrorEvolution as e:
|
|
print(f"❌ {e}", file=sys.stderr)
|
|
return 1
|
|
except KeyboardInterrupt:
|
|
print("\nInterrumpido. Reanuda con: python -m generador whatsapp", args.slug)
|
|
return 130
|
|
|
|
|
|
def cmd_desplegar(args) -> int:
|
|
paquete = _resolver_paquete(args.slug)
|
|
if paquete is None:
|
|
return 1
|
|
registro = Registro(DIR_REPLICAS / "registry.json")
|
|
entrada = registro.listar().get(args.slug)
|
|
if not entrada:
|
|
print(f"❌ '{args.slug}' no está en el registro", file=sys.stderr)
|
|
return 1
|
|
try:
|
|
desplegar_paquete(paquete, entrada["puerto"])
|
|
registro.actualizar(args.slug, estado="desplegada")
|
|
except ErrorEstampado as e:
|
|
print(f"❌ {e}", file=sys.stderr)
|
|
return 1
|
|
print(f"✅ Réplica '{args.slug}' desplegada — salud OK en puerto {entrada['puerto']}")
|
|
return 0
|
|
|
|
|
|
def cmd_listar(args) -> int:
|
|
registro = Registro(DIR_REPLICAS / "registry.json")
|
|
replicas = registro.listar()
|
|
if not replicas:
|
|
print("(sin réplicas en el registro)")
|
|
return 0
|
|
if args.json:
|
|
print(json.dumps(replicas, ensure_ascii=False, indent=2))
|
|
return 0
|
|
ancho = max(len(s) for s in replicas)
|
|
for slug, r in sorted(replicas.items()):
|
|
print(
|
|
f" {slug:<{ancho}} puerto={r.get('puerto')} "
|
|
f"estado={r.get('estado'):<11} destino={r.get('destino','?')} "
|
|
f"cliente={r.get('cliente','?')}"
|
|
)
|
|
return 0
|
|
|
|
|
|
def cmd_eliminar(args) -> int:
|
|
registro = Registro(DIR_REPLICAS / "registry.json")
|
|
try:
|
|
entrada = registro.eliminar(args.slug)
|
|
except ErrorRegistro as e:
|
|
print(f"❌ {e}", file=sys.stderr)
|
|
return 1
|
|
print(f"✅ '{args.slug}' eliminado del registro (era puerto {entrada.get('puerto')})")
|
|
carpeta = DIR_REPLICAS / args.slug
|
|
if args.borrar_carpeta and carpeta.exists():
|
|
shutil.rmtree(carpeta)
|
|
print(f" carpeta borrada: {carpeta}")
|
|
elif carpeta.exists():
|
|
print(f" la carpeta sigue en {carpeta} (usa --borrar-carpeta para quitarla)")
|
|
if args.borrar_instancia:
|
|
from generador.evolution import ClienteEvolution, ErrorEvolution
|
|
|
|
env_ruta = carpeta / ".env"
|
|
if not env_ruta.exists():
|
|
print(" ⚠️ sin .env para saber a qué Evolution borrar la instancia")
|
|
else:
|
|
env = _leer_env(env_ruta)
|
|
try:
|
|
ClienteEvolution(
|
|
env["EVOLUTION_API_URL"], env["EVOLUTION_API_KEY"]
|
|
).eliminar_instancia(args.slug)
|
|
print(f" instancia Evolution '{args.slug}' eliminada")
|
|
except ErrorEvolution as e:
|
|
print(f" ⚠️ no se pudo borrar la instancia Evolution: {e}")
|
|
return 0
|
|
|
|
|
|
def _resolver_paquete(slug: str) -> Path | None:
|
|
paquete = DIR_REPLICAS / slug
|
|
if not paquete.is_dir():
|
|
print(f"❌ No existe el paquete {paquete}", file=sys.stderr)
|
|
return None
|
|
return paquete
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(prog="generador", description=__doc__)
|
|
sub = parser.add_subparsers(dest="comando", required=True)
|
|
|
|
p = sub.add_parser("estampar", help="genera el paquete de una réplica desde su ficha")
|
|
p.add_argument("ficha", help="ruta al cliente.yml")
|
|
p.add_argument("--desplegar", action="store_true",
|
|
help="además de generar, levanta la réplica en este host")
|
|
p.add_argument("--solo-generar", action="store_true",
|
|
help="(default) genera el paquete y para; anula --desplegar")
|
|
p.add_argument("--permitir-sucio", action="store_true",
|
|
help="permite molde con cambios sin commit (solo desarrollo)")
|
|
p.add_argument("--json", action="store_true", help="salida JSON (para el panel)")
|
|
p.set_defaults(fn=cmd_estampar)
|
|
|
|
p = sub.add_parser("validar", help="re-valida un paquete ya estampado")
|
|
p.add_argument("slug")
|
|
p.set_defaults(fn=cmd_validar)
|
|
|
|
p = sub.add_parser("whatsapp", help="aprovisiona Evolution y muestra el QR")
|
|
p.add_argument("slug")
|
|
p.set_defaults(fn=cmd_whatsapp)
|
|
|
|
p = sub.add_parser("desplegar", help="levanta un paquete ya estampado en este host")
|
|
p.add_argument("slug")
|
|
p.set_defaults(fn=cmd_desplegar)
|
|
|
|
p = sub.add_parser("listar", help="réplicas del registro")
|
|
p.add_argument("--json", action="store_true")
|
|
p.set_defaults(fn=cmd_listar)
|
|
|
|
p = sub.add_parser("eliminar", help="quita una réplica del registro")
|
|
p.add_argument("slug")
|
|
p.add_argument("--borrar-carpeta", action="store_true")
|
|
p.add_argument("--borrar-instancia", action="store_true",
|
|
help="borra también la instancia en Evolution")
|
|
p.set_defaults(fn=cmd_eliminar)
|
|
|
|
args = parser.parse_args(argv)
|
|
return args.fn(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|