import sqlite3 import time from config import DB_PATH def init_db(db_path=DB_PATH): conn = sqlite3.connect(db_path) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS speed_tests ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp REAL NOT NULL, failed BOOLEAN NOT NULL, isp TEXT, ip TEXT, location_code TEXT, location_city TEXT, location_region TEXT, latency REAL, jitter REAL, down_100kB REAL, down_1MB REAL, down_10MB REAL, down_25MB REAL, down_90th REAL, up_100kB REAL, up_1MB REAL, up_10MB REAL, up_90th REAL ) ''') conn.commit() conn.close() def init_ping_db(db_path=DB_PATH): conn = sqlite3.connect(db_path) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS ping_checks ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp REAL NOT NULL, target_ip TEXT NOT NULL, success BOOLEAN NOT NULL, latency_ms REAL ) ''') conn.commit() try: conn.execute("ALTER TABLE ping_checks ADD COLUMN is_gateway INTEGER DEFAULT 0") conn.commit() except sqlite3.OperationalError: pass # column already exists conn.close() def insert_ping_result(target_ip: str, success: bool, latency_ms: float | None, is_gateway: bool = False, db_path=DB_PATH): conn = sqlite3.connect(db_path) c = conn.cursor() c.execute( "INSERT INTO ping_checks (timestamp, target_ip, success, latency_ms, is_gateway) VALUES (?, ?, ?, ?, ?)", (time.time(), target_ip, success, latency_ms, int(is_gateway)) ) conn.commit() conn.close() def insert_result(data: dict|None, db_path=DB_PATH): conn = sqlite3.connect(db_path) c = conn.cursor() if data is None: c.execute("INSERT INTO speed_tests (timestamp, failed) VALUES (?, ?)", (time.time(), True)) conn.commit() conn.close() return # Convert bytes per second to Megabits per second (Mbps) def to_mbps(bytes_per_sec): return (bytes_per_sec * 8) / 1000000 if bytes_per_sec else None # Ookla provides a UTC ISO timestamp, but we'll stick to local Unix time for consistency with your old data current_time = time.time() c.execute(''' INSERT INTO speed_tests ( timestamp, failed, isp, ip, location_code, location_city, location_region, latency, jitter, down_90th, up_90th ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', ( current_time, False, data.get("isp"), data.get("interface", {}).get("externalIp"), data.get("server", {}).get("name"), # Ookla Server Name data.get("server", {}).get("location"), # Ookla Server City data.get("server", {}).get("country"), # Ookla Server Country data.get("ping", {}).get("latency"), data.get("ping", {}).get("jitter"), to_mbps(data.get("download", {}).get("bandwidth")), to_mbps(data.get("upload", {}).get("bandwidth")) )) conn.commit() conn.close()