almeira-web/scripts/deploy_auto_register_and_bold_apk.py

185 lines
7.8 KiB
Python

import paramiko
import os
import urllib.request
import json
import ssl
import sys
import io
import time
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
HOST = "161.97.93.156"
USER = "carlos"
PASSWORD = "Innova1978+*?"
REMOTE_BASE = "/home/carlos/apps/dripzone-app"
LOCAL_APP = r"c:\Users\Carlos\dev\almeira-web\dripzone-app"
LOCAL_APK = os.path.join(LOCAL_APP, "public", "DripZone.apk")
REMOTE_APK = f"{REMOTE_BASE}/public/DripZone.apk"
EVOLUTION_API_URL = "https://evolution.almeira.com.co"
EVOLUTION_API_KEY = "EE49029EEB85-4568-8F81-C9FDFC6E2943"
INSTANCE_NAME = "AutomataAlmeira"
TARGET_PHONE = "573167455877"
APK_URL = "https://drip-zone.online/DripZone.apk"
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
SYNC_FILES = [
"src/lib/whatsapp-order-parser.ts",
"src/lib/evolution-api.ts",
"src/app/api/orders/route.ts",
"src/lib/bold-service.ts",
"src/app/admin/pedidos/page.tsx",
"src/types/index.ts",
"src/lib/data-service.ts",
"src/lib/server-appwrite.ts",
]
def main():
print("[1/5] Verificando APK local...", flush=True)
if not os.path.exists(LOCAL_APK):
print(f" [ERROR] El archivo {LOCAL_APK} no existe.")
sys.exit(1)
size_mb = os.path.getsize(LOCAL_APK) / (1024 * 1024)
print(f" -> APK local verificado: {LOCAL_APK} ({size_mb:.2f} MB)", flush=True)
print("[2/5] Conectando por SSH al VPS...", flush=True)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connected = False
for attempt in range(1, 5):
try:
print(f" Intento de conexión SSH {attempt}/4 a {HOST}...", flush=True)
ssh.connect(
hostname=HOST,
username=USER,
password=PASSWORD,
timeout=60,
banner_timeout=60,
auth_timeout=60
)
connected = True
break
except Exception as e:
print(f" [Aviso]: Intento {attempt} falló: {e}. Reintentando en 4s...", flush=True)
time.sleep(4)
if not connected:
print("[ERROR] No se pudo conectar al VPS tras 4 intentos.")
sys.exit(1)
print("[3/5] Subiendo APK y código fuente al VPS vía SFTP...", flush=True)
sftp = ssh.open_sftp()
def ensure_remote_dir(remote_dir):
parts = remote_dir.strip("/").split("/")
current = ""
for p in parts:
current += "/" + p
try:
sftp.mkdir(current)
except:
pass
ensure_remote_dir(f"{REMOTE_BASE}/public")
print(f" -> Subiendo APK ({size_mb:.2f} MB)...", flush=True)
sftp.put(LOCAL_APK, REMOTE_APK)
for rel_path in SYNC_FILES:
loc = os.path.join(LOCAL_APP, rel_path.replace("/", os.sep))
if os.path.exists(loc):
rem = f"{REMOTE_BASE}/{rel_path}"
rem_dir = os.path.dirname(rem)
ensure_remote_dir(rem_dir)
sftp.put(loc, rem)
print(f" -> Sincronizado: {rel_path}", flush=True)
sftp.close()
print(" [OK] Archivos subidos por SFTP con éxito.", flush=True)
print("[4/5] Actualizando contenedor DripZone...", flush=True)
stdin, stdout, stderr = ssh.exec_command("docker ps --format '{{.Names}}'")
containers = [c.strip() for c in stdout.read().decode('utf-8').splitlines() if c.strip()]
drip_containers = [c for c in containers if 'drip' in c.lower() or 'bfmno' in c.lower()]
print(" Contenedores detectados:", drip_containers, flush=True)
for c in drip_containers:
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/public/DripZone.apk 2>/dev/null || true")
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/public/dripzone.apk 2>/dev/null || true")
ssh.exec_command(f"docker cp {REMOTE_APK} {c}:/app/DripZone.apk 2>/dev/null || true")
for rel_path in SYNC_FILES:
loc = f"{REMOTE_BASE}/{rel_path}"
cmd = f"docker cp {loc} {c}:/app/{rel_path} 2>/dev/null || true"
ssh.exec_command(cmd)
print(f" -> Actualizado contenedor: {c}", flush=True)
ssh.close()
time.sleep(2)
try:
req = urllib.request.Request(APK_URL, method='HEAD')
with urllib.request.urlopen(req, context=ctx, timeout=15) as res:
live_size_mb = int(res.headers.get('Content-Length', 0)) / (1024 * 1024)
print(f" [OK] APK online verificado en {APK_URL} (HTTP {res.status}, {live_size_mb:.2f} MB)", flush=True)
except Exception as e:
print(f" [WARN] Verificación HEAD APK: {e}", flush=True)
print("[5/5] Enviando reporte y APK al WhatsApp de Carlos (+57 316 745 5877)...", flush=True)
message_text = (
"🚀 *DripZone - Auto-Registro de Clientes & Pasarela Bold Activados*\n\n"
"¡Hola Carlos! Se ha implementado y desplegado el flujo completo que solicitaste:\n\n"
"👤 *1. Auto-Registro Automático de Clientes en la App:*\n"
"• Cuando un cliente hace un pedido por WhatsApp o desde el Catálogo de WhatsApp y aún no está registrado, el sistema crea de forma automática su cuenta en la App (`usr-wa-...`), vinculando su número celular, nombre y ciudad.\n"
"• Si el cliente ya existe, se actualiza su conteo de órdenes y última actividad.\n\n"
"📦 *2. Registro del Pedido Vinculado al Cliente:*\n"
"• El pedido se registra en Appwrite y en la App enlazado al `userId` del cliente con todos los ítems desglosados (valor unitario, talla, subtotal, envío y saldo contraentrega).\n\n"
"💳 *3. Enlace de Pago en Línea con Bold en la Notificación:*\n"
"• Al enviarle la confirmación del pedido al cliente desde la línea oficial DripZone (+57 310 639 0296), se le incluye el enlace directo de pago de la separación ($10.000 COP) generado en Bold.\n"
"• El cliente puede pagar de inmediato por *PSE, Nequi, Botón Bancolombia, Tarjetas de Crédito / Débito o QR Bre-B*.\n\n"
f"🔗 *Descarga Directa del APK Android:* {APK_URL}\n\n"
"Adjunto el archivo APK actualizado y listo para instalar."
)
# 1. Enviar mensaje de texto a Carlos
req_text = urllib.request.Request(
f"{EVOLUTION_API_URL}/message/sendText/{INSTANCE_NAME}",
data=json.dumps({"number": TARGET_PHONE, "text": message_text, "delay": 500}).encode("utf-8"),
headers={"apikey": EVOLUTION_API_KEY, "Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req_text, context=ctx, timeout=30) as resp:
print(" [OK] Mensaje de texto enviado a WhatsApp (Status:", resp.status, ")", flush=True)
except Exception as e:
print(" [Error texto WhatsApp]:", e, flush=True)
# 2. Enviar documento APK a Carlos
req_media = urllib.request.Request(
f"{EVOLUTION_API_URL}/message/sendMedia/{INSTANCE_NAME}",
data=json.dumps({
"number": TARGET_PHONE,
"mediatype": "document",
"mimetype": "application/vnd.android.package-archive",
"fileName": "DripZone_AutoRegistro_Bold.apk",
"caption": "📲 *DripZone APK Actualizado - Auto-Registro de Clientes & Pasarela Bold*",
"media": APK_URL
}).encode("utf-8"),
headers={"apikey": EVOLUTION_API_KEY, "Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req_media, context=ctx, timeout=120) as resp:
print(" [OK] Documento APK enviado a WhatsApp (Status:", resp.status, ")", flush=True)
except Exception as e:
print(" [Error envío documento APK directo]:", e, flush=True)
print("\n✅ [DESPLIEGUE, SINCRONIZACIÓN Y ENVÍO A WHATSAPP COMPLETADOS]", flush=True)
if __name__ == "__main__":
main()