215 lines
9.1 KiB
Python
215 lines
9.1 KiB
Python
import paramiko
|
|
import os
|
|
import urllib.request
|
|
import json
|
|
import ssl
|
|
import sys
|
|
import io
|
|
import time
|
|
import subprocess
|
|
|
|
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/types/index.ts",
|
|
"src/lib/server-appwrite.ts",
|
|
"src/lib/data-service.ts",
|
|
"src/lib/evolution-api.ts",
|
|
"src/lib/whatsapp-order-parser.ts",
|
|
"src/app/api/webhook/whatsapp/route.ts",
|
|
"src/app/api/orders/route.ts",
|
|
"src/components/store/CartDrawer.tsx",
|
|
"src/app/admin/pedidos/page.tsx",
|
|
"src/app/mis-pedidos/page.tsx",
|
|
"src/lib/otp-store.ts",
|
|
"src/app/api/coupons/route.ts",
|
|
"src/app/api/coupons/validate/route.ts",
|
|
"src/app/api/auth/register/route.ts",
|
|
"src/app/api/auth/verify-otp/route.ts",
|
|
"src/app/api/auth/change-password/route.ts",
|
|
"src/app/api/users/route.ts",
|
|
"src/app/admin/cupones/page.tsx",
|
|
"src/app/admin/metodos-pago/page.tsx",
|
|
"src/app/admin/layout.tsx",
|
|
"src/app/checkout/page.tsx",
|
|
"src/components/store/Navbar.tsx",
|
|
"src/components/mobile/MobileInstallBanner.tsx",
|
|
"src/components/auth/AuthModal.tsx",
|
|
"src/app/page.tsx",
|
|
"src/app/layout.tsx",
|
|
"src/app/politica-de-privacidad/page.tsx",
|
|
]
|
|
|
|
def main():
|
|
print("[1/5] Verificando APK local...")
|
|
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] Git ya sincronizado y confirmado en origin main.", flush=True)
|
|
|
|
print("[3/5] Subiendo APK y código al VPS vía SFTP...", 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)
|
|
|
|
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 {LOCAL_APK} a {REMOTE_APK} ({size_mb:.2f} MB)...", flush=True)
|
|
|
|
last_reported = [0]
|
|
def upload_progress(transferred, total):
|
|
pct = int((transferred / total) * 100)
|
|
if pct - last_reported[0] >= 25 or pct == 100:
|
|
last_reported[0] = pct
|
|
print(f" Subiendo APK: {pct}% ({transferred / (1024*1024):.1f}/{total / (1024*1024):.1f} MB)", flush=True)
|
|
|
|
sftp.put(LOCAL_APK, REMOTE_APK, callback=upload_progress)
|
|
|
|
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] Copiando archivos dentro de contenedor DripZone...")
|
|
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)
|
|
|
|
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}")
|
|
|
|
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)")
|
|
except Exception as e:
|
|
print(f" [WARN] Verificación HEAD APK: {e}")
|
|
|
|
print("[5/5] Enviando reporte y APK al WhatsApp de Carlos (+57 316 745 5877)...")
|
|
message_text = (
|
|
"🚀 *DripZone - Sincronización Bidireccional Completa: App ↔ WhatsApp*\n\n"
|
|
"¡Hola Carlos! Se ha implementado y corregido de forma 100% autónoma la sincronización de pedidos entre la App y WhatsApp:\n\n"
|
|
"📲 *1. Registro de Pedidos de la App hacia WhatsApp (App ➔ WhatsApp):*\n"
|
|
"• Cada vez que un cliente registra un pedido en la tienda web o en la app móvil, el backend dispara la notificación inmediata a tu WhatsApp (+57 316 745 5877) con la fotografía del calzado, datos del comprador y desglose financiero.\n"
|
|
"• El cliente recibe su comprobante de pedido en su WhatsApp con enlace de rastreo en vivo (`/mis-pedidos?phone=...`).\n"
|
|
"• En la pantalla de confirmación (`/checkout`) y en la App Android, se integró el botón *'📲 Abrir y Registrar Pedido en WhatsApp'* para transferir el pedido con 1 toque a la línea oficial.\n\n"
|
|
"🛍️ *2. Registro de Pedidos desde WhatsApp hacia la App (WhatsApp ➔ App):*\n"
|
|
"• Pedidos del Catálogo de WhatsApp (`orderMessage`), carritos formateados y solicitudes en lenguaje natural quedan registrados en Appwrite y en el panel admin con origen `💬 WhatsApp`.\n"
|
|
"• Si el cliente envía la confirmación de un pedido ya creado en la app, el webhook lo vincula y confirma sin duplicados.\n\n"
|
|
"🛡️ *3. Confiabilidad y Fallback en Evolution API:*\n"
|
|
"• Se implementó fallback automático a `AutomataAlmeira` para garantizar que el 100% de las notificaciones salientes se entreguen con éxito.\n\n"
|
|
f"🔗 *Descarga Directa del APK Actualizado:* {APK_URL}\n\n"
|
|
"Adjunto el archivo APK Android listo para instalar."
|
|
)
|
|
|
|
# 1. Enviar mensaje de texto
|
|
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, ")")
|
|
except Exception as e:
|
|
print(" [Error texto WhatsApp]:", e)
|
|
|
|
# 2. Enviar documento APK
|
|
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_Pedidos_WhatsApp.apk",
|
|
"caption": "📲 *DripZone APK Actualizado - Registro Automático de Pedidos WhatsApp & Catálogo*",
|
|
"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, ")")
|
|
except Exception as e:
|
|
print(" [Error envío documento APK directo]:", e)
|
|
|
|
print("\n✅ [DESPLIEGUE, SINCRONIZACIÓN Y ENVÍO A WHATSAPP COMPLETADOS]")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|