import os import streamlit as st import sqlite3 import html from datetime import datetime, timezone from pathlib import Path # ============================================================ # CONFIGURACIÓN # ============================================================ st.set_page_config( page_title="Cloud Mining Monitor", page_icon="⛏️", layout="wide", initial_sidebar_state="collapsed", ) # ============================================================ # SECRETS DE HUGGING FACE # ============================================================ # # Añadir en: # # Hugging Face Space # → Settings # → Variables and secrets # → Secrets # # Nombres EXACTOS: # # NETWORK3_TOKEN # OPTIMAI_TOKEN # OXIN_TOKEN # # IMPORTANTE: # Estos valores NO se muestran en la interfaz. # ============================================================ NETWORK3_TOKEN = os.getenv("NETWORK3_TOKEN") OPTIMAI_TOKEN = os.getenv("OPTIMAI_TOKEN") OXIN_TOKEN = os.getenv("OXIN_TOKEN") # Los tokens se cargan desde Secrets pero NO se imprimen, # guardan en SQLite ni se envían al cliente. # # En este diseño el script de Carnets continúa siendo quien # realiza las peticiones a las APIs externas. # ============================================================ # BASE DE DATOS PERSISTENTE # ============================================================ DATA_DIR = Path("data") DATA_DIR.mkdir(parents=True, exist_ok=True) DB_PATH = DATA_DIR / "mining_monitor.db" # ============================================================ # PLATAFORMAS # ============================================================ PLATFORMS = { "network3": { "name": "Network3", "icon": "🌐", "url": "https://network3.tcc-coin.com", }, "optimai": { "name": "OptimAI", "icon": "⚡", "url": "https://node.optimai.network", }, "oxin": { "name": "Oxinchain", "icon": "⛏️", "url": "https://mine.oxinchain.io", }, } # ============================================================ # BASE DE DATOS # ============================================================ def get_connection(): conn = sqlite3.connect( str(DB_PATH), timeout=10, check_same_thread=False, ) conn.row_factory = sqlite3.Row return conn def init_database(): conn = get_connection() conn.execute( """ CREATE TABLE IF NOT EXISTS platform_status ( platform_id TEXT PRIMARY KEY, active INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL DEFAULT 'NO COMPROBADO', detail TEXT DEFAULT '', http_status TEXT DEFAULT '', evidence TEXT DEFAULT '', response TEXT DEFAULT '', updated_at TEXT DEFAULT NULL ) """ ) conn.execute( """ CREATE TABLE IF NOT EXISTS check_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, platform_id TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL, detail TEXT DEFAULT '', http_status TEXT DEFAULT '', evidence TEXT DEFAULT '', response TEXT DEFAULT '', created_at TEXT NOT NULL ) """ ) for platform_id in PLATFORMS: conn.execute( """ INSERT OR IGNORE INTO platform_status ( platform_id, active, status, detail ) VALUES ( ?, 0, 'NO COMPROBADO', 'Esperando primera ejecución del script' ) """, (platform_id,), ) conn.commit() conn.close() init_database() # ============================================================ # CARGAR ESTADO # ============================================================ def load_status(): conn = get_connection() rows = conn.execute( """ SELECT * FROM platform_status """ ).fetchall() conn.close() result = {} for row in rows: result[row["platform_id"]] = dict(row) return result # ============================================================ # GUARDAR RESULTADO # ============================================================ def save_result( platform_id, active, status, detail="", http_status="", evidence="", response="", ): if platform_id not in PLATFORMS: return now = datetime.now(timezone.utc).isoformat() # Seguridad contra falsos positivos. if status == "MINANDO" and not active: status = "NO INICIÓ" conn = get_connection() conn.execute( """ INSERT INTO platform_status ( platform_id, active, status, detail, http_status, evidence, response, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(platform_id) DO UPDATE SET active = excluded.active, status = excluded.status, detail = excluded.detail, http_status = excluded.http_status, evidence = excluded.evidence, response = excluded.response, updated_at = excluded.updated_at """, ( platform_id, 1 if active else 0, status, detail[:1000], str(http_status)[:50], evidence[:1000], response[:4000], now, ), ) conn.execute( """ INSERT INTO check_history ( platform_id, active, status, detail, http_status, evidence, response, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, ( platform_id, 1 if active else 0, status, detail[:1000], str(http_status)[:50], evidence[:1000], response[:4000], now, ), ) conn.commit() conn.close() # ============================================================ # RECEPCIÓN DEL SCRIPT DE CARNETS # ============================================================ query_params = st.query_params if "app" in query_params: app_id = str( query_params.get( "app", "" ) ).lower().strip() if app_id in PLATFORMS: # ---------------------------------------------------- # DATOS ENVIADOS POR CARNETS # ---------------------------------------------------- mining_started_raw = str( query_params.get( "mining_started", "" ) ).lower().strip() status_raw = str( query_params.get( "status", "" ) ).upper().strip() detail = str( query_params.get( "detail", "" ) ) http_status = str( query_params.get( "http_status", "" ) ) evidence = str( query_params.get( "evidence", "" ) ) response = str( query_params.get( "response", "" ) ) # ---------------------------------------------------- # REGLA DE ESTADO # ---------------------------------------------------- if mining_started_raw == "true": active = True final_status = "MINANDO" if not evidence: evidence = ( "El script confirmó explícitamente " "mining_started=true" ) elif mining_started_raw == "false": active = False final_status = "NO INICIÓ" elif status_raw == "ERROR": active = False final_status = "ERROR" else: active = False final_status = "SIN EVIDENCIA" if not detail: detail = ( "El script no proporcionó " "mining_started=true/false." ) save_result( platform_id=app_id, active=active, status=final_status, detail=detail, http_status=http_status, evidence=evidence, response=response, ) # ============================================================ # CARGAR ESTADO ACTUAL # ============================================================ statuses = load_status() # ============================================================ # CSS # ============================================================ st.markdown( """ """, unsafe_allow_html=True, ) # ============================================================ # CABECERA # ============================================================ st.markdown( """
⛏️ Cloud Mining Monitor
Estado real confirmado por el script externo
""", unsafe_allow_html=True, ) # ============================================================ # CÁLCULOS # ============================================================ total = len(PLATFORMS) mining = sum( 1 for item in statuses.values() if item["active"] == 1 ) errors = sum( 1 for item in statuses.values() if item["status"] == "ERROR" ) waiting = sum( 1 for item in statuses.values() if item["status"] in ( "NO COMPROBADO", "SIN EVIDENCIA", ) ) not_started = ( total - mining - errors - waiting ) # ============================================================ # RESUMEN # ============================================================ c1, c2, c3, c4 = st.columns(4) with c1: st.markdown( f"""
🟢 {mining}/{total}
MINANDO
""", unsafe_allow_html=True, ) with c2: st.markdown( f"""
🔴 {not_started}
NO INICIÓ
""", unsafe_allow_html=True, ) with c3: st.markdown( f"""
🟡 {waiting}
ESPERANDO
""", unsafe_allow_html=True, ) with c4: st.markdown( f"""
🔴 {errors}
ERROR
""", unsafe_allow_html=True, ) # ============================================================ # CUADRÍCULA # ============================================================ st.markdown("### 📱 Plataformas") platform_items = list( PLATFORMS.items() ) COLUMNS = 4 for start in range( 0, len(platform_items), COLUMNS, ): row = platform_items[ start:start + COLUMNS ] columns = st.columns( COLUMNS, gap="small", ) for column, ( platform_id, info, ) in zip( columns, row, ): item = statuses[ platform_id ] active = ( item["active"] == 1 ) status = item["status"] detail = html.escape( item["detail"] or "" ) updated_at = item[ "updated_at" ] if updated_at: try: dt = datetime.fromisoformat( updated_at ) formatted_time = ( dt.astimezone().strftime( "%d/%m/%Y %H:%M:%S" ) ) except Exception: formatted_time = ( updated_at ) else: formatted_time = "Nunca" # ---------------------------------------------------- # ESTADO VISUAL # ---------------------------------------------------- if active: icon = "🟢" label = "MINANDO" css = "green" elif status == "NO INICIÓ": icon = "🔴" label = "NO INICIÓ" css = "red" elif status == "ERROR": icon = "🔴" label = "ERROR" css = "red" elif status == "SIN EVIDENCIA": icon = "🟡" label = "SIN EVIDENCIA" css = "yellow" else: icon = "🟡" label = "ESPERANDO" css = "yellow" with column: st.markdown( f"""
{info["icon"]} {info["name"]}
{icon} {label}
{detail}
Última comprobación: {formatted_time}
""", unsafe_allow_html=True, ) # ============================================================ # DETALLE # ============================================================ st.markdown("---") st.markdown( "### 🔎 Evidencia de las comprobaciones" ) for platform_id, info in PLATFORMS.items(): item = statuses[ platform_id ] with st.expander( f'{info["icon"]} {info["name"]}' ): st.write( f'**Estado:** ' f'{item["status"]}' ) st.write( f'**HTTP:** ' f'{item["http_status"] or "N/D"}' ) st.write( f'**Evidencia:** ' f'{item["evidence"] or "N/D"}' ) st.write( f'**Detalle:** ' f'{item["detail"] or "N/D"}' ) if item["response"]: st.code( item["response"], language="json", ) # ============================================================ # AVISO DE SEGURIDAD # ============================================================ st.markdown( """
⚠️ Cómo se determina MINANDO

Este panel no considera un HTTP 200/201 como prueba suficiente de minería.

El estado 🟢 MINANDO solamente aparece cuando el script externo confirma explícitamente:

mining_started=true

Esto evita mostrar falsos positivos cuando una API acepta una petición pero el nodo todavía no está minando.

Los JWT configurados como Secrets permanecen en el entorno del servidor y no se muestran en el panel.
""", unsafe_allow_html=True, ) # ============================================================ # INFORMACIÓN DE ALMACENAMIENTO # ============================================================ st.markdown("---") st.caption( f"💾 Base de datos: {DB_PATH}" ) st.caption( "Los resultados se almacenan en SQLite y no dependen de " "st.session_state." )