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( """
mining_started=true