ioslauncher / app.py
Minacrypto's picture
Update app.py
58a857c verified
Raw History Blame Contribute Delete
18.3 kB
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(
"""
<style>
.main {
padding: 0 0.4rem;
}
.block-container {
max-width: 1700px;
padding-top: 1rem;
padding-bottom: 2rem;
}
.header {
text-align: center;
margin-bottom: 20px;
}
.header-title {
font-size: 2rem;
font-weight: 800;
}
.header-subtitle {
color: #999;
font-size: 0.88rem;
}
.platform-card {
min-height: 155px;
border-radius: 18px;
padding: 16px;
margin-bottom: 12px;
background: rgba(255,255,255,0.045);
border: 1px solid rgba(255,255,255,0.12);
box-shadow:
0 4px 18px rgba(0,0,0,0.12);
}
.platform-name {
font-size: 1.05rem;
font-weight: 800;
margin-bottom: 12px;
}
.platform-status {
font-size: 1rem;
font-weight: 900;
margin-bottom: 10px;
}
.green {
color: #39d353;
}
.red {
color: #ff4d4f;
}
.yellow {
color: #ffc107;
}
.gray {
color: #aaa;
}
.platform-detail {
color: #999;
font-size: 0.78rem;
min-height: 32px;
}
.platform-time {
color: #777;
font-size: 0.70rem;
margin-top: 8px;
}
.summary {
border-radius: 18px;
padding: 18px;
text-align: center;
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.10);
}
.summary-number {
font-size: 1.8rem;
font-weight: 900;
}
.summary-label {
color: #999;
font-size: 0.8rem;
}
.security-box {
border-radius: 15px;
padding: 14px;
margin-top: 15px;
background: rgba(255,193,7,0.06);
border: 1px solid rgba(255,193,7,0.20);
}
</style>
""",
unsafe_allow_html=True,
)
# ============================================================
# CABECERA
# ============================================================
st.markdown(
"""
<div class="header">
<div class="header-title">
⛏️ Cloud Mining Monitor
</div>
<div class="header-subtitle">
Estado real confirmado por el script externo
</div>
</div>
""",
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"""
<div class="summary">
<div class="summary-number green">
🟢 {mining}/{total}
</div>
<div class="summary-label">
MINANDO
</div>
</div>
""",
unsafe_allow_html=True,
)
with c2:
st.markdown(
f"""
<div class="summary">
<div class="summary-number red">
🔴 {not_started}
</div>
<div class="summary-label">
NO INICIÓ
</div>
</div>
""",
unsafe_allow_html=True,
)
with c3:
st.markdown(
f"""
<div class="summary">
<div class="summary-number yellow">
🟡 {waiting}
</div>
<div class="summary-label">
ESPERANDO
</div>
</div>
""",
unsafe_allow_html=True,
)
with c4:
st.markdown(
f"""
<div class="summary">
<div class="summary-number red">
🔴 {errors}
</div>
<div class="summary-label">
ERROR
</div>
</div>
""",
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"""
<div class="platform-card">
<div class="platform-name">
{info["icon"]}
{info["name"]}
</div>
<div class="platform-status {css}">
{icon} {label}
</div>
<div class="platform-detail">
{detail}
</div>
<div class="platform-time">
Última comprobación:
{formatted_time}
</div>
</div>
""",
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(
"""
<div class="security-box">
<b>⚠️ Cómo se determina MINANDO</b>
<br><br>
Este panel no considera un HTTP 200/201 como prueba
suficiente de minería.
<br><br>
El estado 🟢 MINANDO solamente aparece cuando el script
externo confirma explícitamente:
<br><br>
<code>mining_started=true</code>
<br><br>
Esto evita mostrar falsos positivos cuando una API acepta
una petición pero el nodo todavía no está minando.
<br><br>
Los JWT configurados como Secrets permanecen en el
entorno del servidor y no se muestran en el panel.
</div>
""",
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."
)