"""SQLite database layer — schema, migrations, CRUD, monitoring.""" import os import json import sqlite3 from datetime import datetime from .config import settings as s from .hub_sync import mark_dirty DB_DIR = s.DB_DIR DB_PATH = s.DB_PATH SCHEMA_VERSION = 14 def get_conn(): os.makedirs(DB_DIR, exist_ok=True) conn = sqlite3.connect(DB_PATH, timeout=30) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") conn.execute("PRAGMA busy_timeout = 30000") return conn def _get_schema_version(conn): try: row = conn.execute("PRAGMA user_version").fetchone() return row[0] if row else 0 except Exception: return 0 def init_db(): conn = get_conn() version = _get_schema_version(conn) # ─── Fresh install: create all tables ─── if version == 0: conn.executescript(""" CREATE TABLE IF NOT EXISTS devices ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, device_type TEXT NOT NULL, description TEXT DEFAULT '', sort_order INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS os_versions ( id INTEGER PRIMARY KEY AUTOINCREMENT, device_id INTEGER NOT NULL REFERENCES devices(id) ON DELETE CASCADE, os_type TEXT NOT NULL, version_name TEXT NOT NULL, description TEXT DEFAULT '', sort_order INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS downloads ( id INTEGER PRIMARY KEY AUTOINCREMENT, os_version_id INTEGER NOT NULL REFERENCES os_versions(id) ON DELETE CASCADE, file_type TEXT NOT NULL, title TEXT NOT NULL, description TEXT DEFAULT '', mega_link TEXT NOT NULL, file_size TEXT DEFAULT '', sort_order INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS admins ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS announcements ( id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT DEFAULT '公告', title TEXT NOT NULL, content TEXT NOT NULL, active INTEGER DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS visit_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, ip TEXT DEFAULT '', user_agent TEXT DEFAULT '', path TEXT DEFAULT '', device_name TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS download_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, download_id INTEGER, title TEXT DEFAULT '', file_type TEXT DEFAULT '', device_name TEXT DEFAULT '', os_name TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS mega_cache ( id INTEGER PRIMARY KEY AUTOINCREMENT, file_name TEXT NOT NULL UNIQUE, file_size INTEGER DEFAULT 0, mega_link TEXT, file_id TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") # ─── Migrations ─── if version == 5: # v5 → v6: add file_id column to mega_cache try: conn.execute("ALTER TABLE mega_cache ADD COLUMN file_id TEXT DEFAULT ''") except Exception: pass # column may already exist conn.execute("PRAGMA user_version = 6") if version <= 6: # v6 → v7: add problem_reports table conn.executescript(""" CREATE TABLE IF NOT EXISTS problem_reports ( id INTEGER PRIMARY KEY AUTOINCREMENT, sn TEXT NOT NULL, os_type TEXT DEFAULT '', problem_type TEXT NOT NULL, description TEXT DEFAULT '', os_version TEXT DEFAULT '', matched_filenames TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, status TEXT DEFAULT 'pending', resolved_at TIMESTAMP, resolution_note TEXT DEFAULT '' ); """) conn.execute("PRAGMA user_version = 7") if version <= 7: # v7 → v8: add sn_file_maps table conn.executescript(""" CREATE TABLE IF NOT EXISTS sn_file_maps ( id INTEGER PRIMARY KEY AUTOINCREMENT, sn TEXT NOT NULL UNIQUE, files TEXT NOT NULL DEFAULT '[]', note TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) conn.execute("PRAGMA user_version = 8") if version <= 8: # v8 → v9: add os_file_maps table conn.executescript(""" CREATE TABLE IF NOT EXISTS os_file_maps ( id INTEGER PRIMARY KEY AUTOINCREMENT, os_version TEXT NOT NULL UNIQUE, files TEXT NOT NULL DEFAULT '[]', note TEXT DEFAULT '', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) conn.execute("PRAGMA user_version = 9") if version <= 9: # v9 → v10: add app_settings table conn.executescript(""" CREATE TABLE IF NOT EXISTS app_settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); INSERT OR IGNORE INTO app_settings (key, value) VALUES ('map_display_mode', 'all'); """) conn.execute("PRAGMA user_version = 10") if version <= 10: # v10 → v11: add mes_cache table (public MES query result cache) conn.executescript(""" CREATE TABLE IF NOT EXISTS mes_cache ( sn TEXT PRIMARY KEY, raw_json TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) conn.execute("PRAGMA user_version = 11") if version <= 11: # v11 -> v12: add mes_query_logs table (MES query monitoring) conn.executescript(""" CREATE TABLE IF NOT EXISTS mes_query_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, sn TEXT NOT NULL, cached INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL DEFAULT 'ok', duration_ms INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) conn.execute("PRAGMA user_version = 12") if version <= 12: # v12 -> v13: record which MES field a report refers to cols = {r["name"] for r in conn.execute("PRAGMA table_info(problem_reports)")} if "field_name" not in cols: conn.execute( "ALTER TABLE problem_reports ADD COLUMN field_name TEXT DEFAULT ''" ) conn.execute("PRAGMA user_version = 13") if version <= 13: # v13 -> v14: access profiles — one row per access code, each carrying its # own visible-field set so a code decides what the browser is allowed to see. from .fields import ALL_FIELDS, DEFAULT_USER_FIELDS conn.executescript(""" CREATE TABLE IF NOT EXISTS access_profiles ( id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT NOT NULL UNIQUE, name TEXT NOT NULL DEFAULT '', is_admin INTEGER NOT NULL DEFAULT 0, visible_fields TEXT NOT NULL DEFAULT '[]', enabled INTEGER NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); """) legacy = conn.execute( "SELECT value FROM app_settings WHERE key = 'mes_access_code'" ).fetchone() legacy_code = (legacy["value"] if legacy else "") or s.MES_ACCESS_CODE if legacy_code: conn.execute( "INSERT OR IGNORE INTO access_profiles " "(code, name, is_admin, visible_fields) VALUES (?, ?, 0, ?)", (legacy_code, "用户", json.dumps(DEFAULT_USER_FIELDS)), ) conn.execute( "INSERT OR IGNORE INTO access_profiles " "(code, name, is_admin, visible_fields) VALUES (?, ?, 1, ?)", ("bevis", "管理员", json.dumps(ALL_FIELDS)), ) conn.execute("PRAGMA user_version = 14") conn.commit() conn.close() # ─── Device CRUD ─── def list_devices(device_type=None): conn = get_conn() if device_type: rows = conn.execute( "SELECT * FROM devices WHERE device_type=? ORDER BY sort_order, name", (device_type,), ).fetchall() else: rows = conn.execute( "SELECT * FROM devices ORDER BY sort_order, name" ).fetchall() conn.close() return [dict(r) for r in rows] def get_device(device_id): conn = get_conn() row = conn.execute( "SELECT * FROM devices WHERE id=?", (device_id,) ).fetchone() conn.close() return dict(row) if row else None def create_device(name, device_type, description="", sort_order=0): conn = get_conn() try: cur = conn.execute( "INSERT INTO devices (name, device_type, description, sort_order) VALUES (?,?,?,?)", (name, device_type, description, sort_order), ) conn.commit() mark_dirty() return cur.lastrowid except sqlite3.IntegrityError: return None finally: conn.close() def update_device(device_id, name=None, device_type=None, description=None, sort_order=None): conn = get_conn() fields, vals = [], [] if name is not None: fields.append("name=?") vals.append(name) if device_type is not None: fields.append("device_type=?") vals.append(device_type) if description is not None: fields.append("description=?") vals.append(description) if sort_order is not None: fields.append("sort_order=?") vals.append(sort_order) if not fields: conn.close() return False vals.append(device_id) try: conn.execute( f"UPDATE devices SET {', '.join(fields)} WHERE id=?", vals ) conn.commit() mark_dirty() return True except sqlite3.IntegrityError: return False finally: conn.close() def delete_device(device_id): conn = get_conn() conn.execute("DELETE FROM devices WHERE id=?", (device_id,)) conn.commit() mark_dirty() conn.close() # ─── OS Version CRUD ─── def list_os_versions(device_id): conn = get_conn() rows = conn.execute( "SELECT * FROM os_versions WHERE device_id=? ORDER BY sort_order, version_name", (device_id,), ).fetchall() conn.close() return [dict(r) for r in rows] def get_os_version(os_id): conn = get_conn() row = conn.execute( "SELECT * FROM os_versions WHERE id=?", (os_id,) ).fetchone() conn.close() return dict(row) if row else None def create_os_version(device_id, os_type, version_name, description="", sort_order=0): conn = get_conn() cur = conn.execute( "INSERT INTO os_versions (device_id, os_type, version_name, description, sort_order) VALUES (?,?,?,?,?)", (device_id, os_type, version_name, description, sort_order), ) conn.commit() mark_dirty() conn.close() return cur.lastrowid def update_os_version(os_id, os_type=None, version_name=None, description=None, sort_order=None): conn = get_conn() fields, vals = [], [] if os_type is not None: fields.append("os_type=?") vals.append(os_type) if version_name is not None: fields.append("version_name=?") vals.append(version_name) if description is not None: fields.append("description=?") vals.append(description) if sort_order is not None: fields.append("sort_order=?") vals.append(sort_order) if not fields: conn.close() return False vals.append(os_id) conn.execute(f"UPDATE os_versions SET {', '.join(fields)} WHERE id=?", vals) conn.commit() mark_dirty() conn.close() return True def delete_os_version(os_id): conn = get_conn() conn.execute("DELETE FROM os_versions WHERE id=?", (os_id,)) conn.commit() mark_dirty() conn.close() # ─── Download CRUD ─── def list_downloads(os_version_id): conn = get_conn() rows = conn.execute( "SELECT * FROM downloads WHERE os_version_id=? ORDER BY sort_order, title", (os_version_id,), ).fetchall() conn.close() return [dict(r) for r in rows] def get_download(download_id): conn = get_conn() row = conn.execute( "SELECT * FROM downloads WHERE id=?", (download_id,) ).fetchone() conn.close() return dict(row) if row else None def create_download(os_version_id, file_type, title, mega_link, description="", file_size="", sort_order=0): conn = get_conn() cur = conn.execute( "INSERT INTO downloads (os_version_id, file_type, title, description, mega_link, file_size, sort_order) VALUES (?,?,?,?,?,?,?)", (os_version_id, file_type, title, description, mega_link, file_size, sort_order), ) conn.commit() mark_dirty() conn.close() return cur.lastrowid def update_download(download_id, file_type=None, title=None, description=None, mega_link=None, file_size=None, sort_order=None): conn = get_conn() fields, vals = [], [] if file_type is not None: fields.append("file_type=?") vals.append(file_type) if title is not None: fields.append("title=?") vals.append(title) if description is not None: fields.append("description=?") vals.append(description) if mega_link is not None: fields.append("mega_link=?") vals.append(mega_link) if file_size is not None: fields.append("file_size=?") vals.append(file_size) if sort_order is not None: fields.append("sort_order=?") vals.append(sort_order) if not fields: conn.close() return False vals.append(download_id) conn.execute(f"UPDATE downloads SET {', '.join(fields)} WHERE id=?", vals) conn.commit() mark_dirty() conn.close() return True def delete_download(download_id): conn = get_conn() conn.execute("DELETE FROM downloads WHERE id=?", (download_id,)) conn.commit() mark_dirty() conn.close() # ─── Admin CRUD ─── def get_admin(username): conn = get_conn() row = conn.execute( "SELECT * FROM admins WHERE username=?", (username,) ).fetchone() conn.close() return dict(row) if row else None def create_admin(username, password_hash): conn = get_conn() try: conn.execute( "INSERT INTO admins (username, password_hash) VALUES (?,?)", (username, password_hash), ) conn.commit() return True except sqlite3.IntegrityError: return False finally: conn.close() def update_admin_password(username, password_hash): conn = get_conn() try: cur = conn.execute( "UPDATE admins SET password_hash=? WHERE username=?", (password_hash, username), ) conn.commit() updated = cur.rowcount > 0 finally: conn.close() if updated: mark_dirty() return updated # ─── Device tree (public) ─── def get_device_tree(): conn = get_conn() devices = conn.execute( "SELECT * FROM devices ORDER BY sort_order, name" ).fetchall() tree = [] for d in devices: d = dict(d) os_list = conn.execute( "SELECT * FROM os_versions WHERE device_id=? ORDER BY sort_order, version_name", (d["id"],), ).fetchall() d["os_versions"] = [] for osv in os_list: osv = dict(osv) dl_list = conn.execute( "SELECT * FROM downloads WHERE os_version_id=? ORDER BY sort_order, title", (osv["id"],), ).fetchall() osv["downloads"] = [dict(dl) for dl in dl_list] d["os_versions"].append(osv) tree.append(d) conn.close() return tree # ─── Announcements ─── def list_announcements(): conn = get_conn() rows = conn.execute( "SELECT * FROM announcements ORDER BY created_at DESC" ).fetchall() conn.close() return [dict(r) for r in rows] def list_active_announcements(): conn = get_conn() rows = conn.execute( "SELECT * FROM announcements WHERE active=1 ORDER BY created_at DESC" ).fetchall() conn.close() return [dict(r) for r in rows] def save_announcement(id=None, kind="公告", title="", content="", active=True): conn = get_conn() now = datetime.now().isoformat() if id: conn.execute( "UPDATE announcements SET kind=?, title=?, content=?, active=?, updated_at=? WHERE id=?", (kind, title, content, 1 if active else 0, now, id), ) else: conn.execute( "INSERT INTO announcements (kind, title, content, active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)", (kind, title, content, 1 if active else 0, now, now), ) id = conn.execute("SELECT last_insert_rowid()").fetchone()[0] conn.commit() mark_dirty() row = conn.execute( "SELECT * FROM announcements WHERE id=?", (id,) ).fetchone() conn.close() return dict(row) def delete_announcement(id: int): conn = get_conn() conn.execute("DELETE FROM announcements WHERE id=?", (id,)) conn.commit() mark_dirty() conn.close() def toggle_announcement(id: int): conn = get_conn() conn.execute( "UPDATE announcements SET active = CASE WHEN active=1 THEN 0 ELSE 1 END, updated_at=? WHERE id=?", (datetime.now().isoformat(), id), ) conn.commit() mark_dirty() conn.close() # ─── Visit / download logging ─── def log_visit(ip="", user_agent="", path="", device_name=""): conn = get_conn() conn.execute( "INSERT INTO visit_logs (ip, user_agent, path, device_name) VALUES (?, ?, ?, ?)", (ip, user_agent, path, device_name), ) conn.commit() conn.close() def log_download_click(download_id, title="", file_type="", device_name="", os_name=""): conn = get_conn() conn.execute( "INSERT INTO download_logs (download_id, title, file_type, device_name, os_name) VALUES (?, ?, ?, ?, ?)", (download_id, title, file_type, device_name, os_name), ) conn.commit() conn.close() # ─── Monitoring ─── def get_monitoring_stats(): conn = get_conn() total_visits = conn.execute( "SELECT COUNT(*) FROM visit_logs" ).fetchone()[0] total_downloads = conn.execute( "SELECT COUNT(*) FROM download_logs" ).fetchone()[0] today_visits = conn.execute( "SELECT COUNT(*) FROM visit_logs WHERE date(created_at)=date('now')" ).fetchone()[0] today_downloads = conn.execute( "SELECT COUNT(*) FROM download_logs WHERE date(created_at)=date('now')" ).fetchone()[0] top_devices = conn.execute( "SELECT device_name, COUNT(*) as cnt FROM visit_logs WHERE device_name != '' GROUP BY device_name ORDER BY cnt DESC LIMIT 10" ).fetchall() recent_visits = conn.execute( "SELECT * FROM visit_logs ORDER BY created_at DESC LIMIT 50" ).fetchall() recent_downloads = conn.execute( "SELECT * FROM download_logs ORDER BY created_at DESC LIMIT 50" ).fetchall() daily_visits = conn.execute( "SELECT date(created_at) as day, COUNT(*) as cnt FROM visit_logs WHERE created_at >= datetime('now', '-30 days') GROUP BY date(created_at) ORDER BY day" ).fetchall() conn.close() return { "total_visits": total_visits, "total_downloads": total_downloads, "today_visits": today_visits, "today_downloads": today_downloads, "top_devices": [dict(r) for r in top_devices], "recent_visits": [dict(r) for r in recent_visits], "recent_downloads": [dict(r) for r in recent_downloads], "daily_visits": [dict(r) for r in daily_visits], } # ─── MEGA Cache ─── def refresh_mega_cache(files: list[dict]): """Full replace of mega_cache (old approach, kept for compatibility).""" conn = get_conn() conn.execute("DELETE FROM mega_cache") conn.executemany( "INSERT INTO mega_cache (file_name, file_size, mega_link, file_id) VALUES (?, ?, ?, ?)", [(f["file_name"], f.get("file_size", 0), f.get("mega_link"), f.get("file_id", "")) for f in files], ) conn.commit() conn.close() def append_mega_cache(files: list[dict]): """Incremental insert (old approach, kept for compatibility).""" conn = get_conn() conn.executemany( "INSERT OR IGNORE INTO mega_cache (file_name, file_size, mega_link, file_id) VALUES (?, ?, ?, ?)", [(f["file_name"], f.get("file_size", 0), f.get("mega_link"), f.get("file_id", "")) for f in files], ) conn.commit() conn.close() def upsert_mega_cache(files: list[dict]): """Bulk upsert file_name + file_size + file_id, preserving existing mega_link. Uses ON CONFLICT to update file_id/file_size without touching mega_link. """ conn = get_conn() conn.executemany( "INSERT INTO mega_cache (file_name, file_size, file_id) VALUES (?, ?, ?) " "ON CONFLICT(file_name) DO UPDATE SET file_id=excluded.file_id, file_size=excluded.file_size", [(f["file_name"], f.get("file_size", 0), f.get("file_id", "")) for f in files], ) conn.commit() mark_dirty() conn.close() def upsert_mega_cache_links(files: list[dict]): """Bulk upsert external share-link files, overwriting mega_link. Used for files that live outside the MEGA account tree (see mega_links.json); their link is already known, so it must be written rather than preserved. """ conn = get_conn() conn.executemany( "INSERT INTO mega_cache (file_name, file_size, file_id, mega_link) VALUES (?, ?, ?, ?) " "ON CONFLICT(file_name) DO UPDATE SET file_id=excluded.file_id, " "file_size=excluded.file_size, mega_link=excluded.mega_link", [ (f["file_name"], f.get("file_size", 0), f.get("file_id", ""), f["mega_link"]) for f in files ], ) conn.commit() mark_dirty() conn.close() def update_mega_links(links: dict[str, str]): """Batch update mega_link WHERE file_name matches. links: {file_name: mega_link_url} """ conn = get_conn() conn.executemany( "UPDATE mega_cache SET mega_link=? WHERE file_name=?", [(link, name) for name, link in links.items()], ) conn.commit() mark_dirty() conn.close() def get_exported_names() -> set[str]: conn = get_conn() rows = conn.execute("SELECT file_name FROM mega_cache").fetchall() conn.close() return {r["file_name"] for r in rows} def get_exported_names_with_links() -> set[str]: conn = get_conn() rows = conn.execute( "SELECT file_name FROM mega_cache WHERE mega_link IS NOT NULL AND mega_link != ''" ).fetchall() conn.close() return {r["file_name"] for r in rows} def clear_mega_cache(): conn = get_conn() conn.execute("DELETE FROM mega_cache") conn.commit() mark_dirty() conn.close() def search_mega_cache(keyword: str, max_results: int = 10) -> list[dict]: conn = get_conn() rows = conn.execute( "SELECT file_name as name, file_size as size, mega_link as link, id " "FROM mega_cache WHERE file_name LIKE ? ORDER BY file_name LIMIT ?", (f"%{keyword}%", max_results), ).fetchall() conn.close() return [dict(r) for r in rows] def get_mega_cache_count() -> int: conn = get_conn() cnt = conn.execute("SELECT COUNT(*) FROM mega_cache").fetchone()[0] conn.close() return cnt def get_mega_cache_mtime() -> float | None: conn = get_conn() row = conn.execute( "SELECT MAX(created_at) FROM mega_cache" ).fetchone() conn.close() if row and row[0]: return datetime.fromisoformat(row[0]).timestamp() return None def get_mega_cache_stats() -> dict: conn = get_conn() total = conn.execute("SELECT COUNT(*) FROM mega_cache").fetchone()[0] with_links = conn.execute( "SELECT COUNT(*) FROM mega_cache WHERE mega_link IS NOT NULL AND mega_link != ''" ).fetchone()[0] total_size = conn.execute( "SELECT COALESCE(SUM(file_size), 0) FROM mega_cache" ).fetchone()[0] row = conn.execute("SELECT MAX(created_at) FROM mega_cache").fetchone() mtime = row[0] if row and row[0] else None ext_rows = conn.execute( "SELECT SUBSTR(file_name, -4) as ext, COUNT(*) as cnt FROM mega_cache " "GROUP BY ext ORDER BY cnt DESC LIMIT 10" ).fetchall() recent = conn.execute( "SELECT file_name, file_size, created_at FROM mega_cache ORDER BY id DESC LIMIT 5" ).fetchall() conn.close() return { "total": total, "with_links": with_links, "without_links": total - with_links, "total_size": total_size, "last_update": mtime, "extensions": [dict(r) for r in ext_rows], "recent": [dict(r) for r in recent], } # ─── Problem Reports ─── def create_report(sn: str, problem_type: str, os_type: str = "", os_version: str = "", matched_filenames: str = "", description: str = "", field_name: str = "") -> int: conn = get_conn() cur = conn.execute( "INSERT INTO problem_reports (sn, problem_type, os_type, os_version, matched_filenames, description, field_name) " "VALUES (?, ?, ?, ?, ?, ?, ?)", (sn, problem_type, os_type, os_version, matched_filenames, description, field_name), ) report_id = cur.lastrowid conn.commit() mark_dirty() conn.close() return report_id def get_reports(status: str | None = None, limit: int = 50) -> list[dict]: conn = get_conn() if status: rows = conn.execute( "SELECT * FROM problem_reports WHERE status = ? ORDER BY created_at DESC LIMIT ?", (status, limit), ).fetchall() else: rows = conn.execute( "SELECT * FROM problem_reports ORDER BY created_at DESC LIMIT ?", (limit,), ).fetchall() conn.close() return [dict(r) for r in rows] def update_report(report_id: int, status: str, resolution_note: str = "") -> bool: conn = get_conn() cur = conn.execute( "UPDATE problem_reports SET status = ?, resolved_at = CURRENT_TIMESTAMP, resolution_note = ? WHERE id = ?", (status, resolution_note, report_id), ) conn.commit() mark_dirty() affected = cur.rowcount > 0 conn.close() return affected def delete_report(report_id: int) -> bool: conn = get_conn() cur = conn.execute("DELETE FROM problem_reports WHERE id = ?", (report_id,)) conn.commit() mark_dirty() affected = cur.rowcount > 0 conn.close() return affected # ─── SN File Maps ─── def list_sn_file_maps(limit: int = 100) -> list[dict]: conn = get_conn() rows = conn.execute( "SELECT * FROM sn_file_maps ORDER BY updated_at DESC LIMIT ?", (limit,), ).fetchall() conn.close() return [dict(r) for r in rows] def get_sn_file_map(sn: str) -> dict | None: conn = get_conn() row = conn.execute( "SELECT * FROM sn_file_maps WHERE sn = ?", (sn,) ).fetchone() conn.close() return dict(row) if row else None def upsert_sn_file_map(sn: str, files: list[str], note: str = "") -> int: import json conn = get_conn() existing = conn.execute( "SELECT id FROM sn_file_maps WHERE sn = ?", (sn,) ).fetchone() now = datetime.now().isoformat() if existing: conn.execute( "UPDATE sn_file_maps SET files = ?, note = ?, updated_at = ? WHERE id = ?", (json.dumps(files), note, now, existing["id"]), ) map_id = existing["id"] else: cur = conn.execute( "INSERT INTO sn_file_maps (sn, files, note, updated_at) VALUES (?, ?, ?, ?)", (sn, json.dumps(files), note, now), ) map_id = cur.lastrowid conn.commit() mark_dirty() conn.close() return map_id def delete_sn_file_map(map_id: int) -> bool: conn = get_conn() cur = conn.execute("DELETE FROM sn_file_maps WHERE id = ?", (map_id,)) conn.commit() mark_dirty() affected = cur.rowcount > 0 conn.close() return affected # ─── OS File Maps ─── def list_os_file_maps(limit: int = 100) -> list[dict]: conn = get_conn() rows = conn.execute( "SELECT * FROM os_file_maps ORDER BY updated_at DESC LIMIT ?", (limit,), ).fetchall() conn.close() return [dict(r) for r in rows] def get_os_file_map(os_version: str) -> dict | None: conn = get_conn() row = conn.execute( "SELECT * FROM os_file_maps WHERE os_version = ?", (os_version,) ).fetchone() conn.close() return dict(row) if row else None def upsert_os_file_map(os_version: str, files: list[str], note: str = "") -> int: import json conn = get_conn() existing = conn.execute( "SELECT id FROM os_file_maps WHERE os_version = ?", (os_version,) ).fetchone() now = datetime.now().isoformat() if existing: conn.execute( "UPDATE os_file_maps SET files = ?, note = ?, updated_at = ? WHERE id = ?", (json.dumps(files), note, now, existing["id"]), ) map_id = existing["id"] else: cur = conn.execute( "INSERT INTO os_file_maps (os_version, files, note, updated_at) VALUES (?, ?, ?, ?)", (os_version, json.dumps(files), note, now), ) map_id = cur.lastrowid conn.commit() mark_dirty() conn.close() return map_id def delete_os_file_map(map_id: int) -> bool: conn = get_conn() cur = conn.execute("DELETE FROM os_file_maps WHERE id = ?", (map_id,)) conn.commit() mark_dirty() affected = cur.rowcount > 0 conn.close() return affected # ─── App Settings ─── def get_setting(key: str, default: str = "") -> str: conn = get_conn() row = conn.execute( "SELECT value FROM app_settings WHERE key = ?", (key,) ).fetchone() conn.close() return row["value"] if row else default def set_setting(key: str, value: str): conn = get_conn() conn.execute( "INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) " "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP", (key, value), ) conn.commit() mark_dirty() conn.close() # ─── MES Query Cache ─── def get_mes_cache(sn: str) -> dict | None: conn = get_conn() row = conn.execute( "SELECT sn, raw_json, created_at FROM mes_cache WHERE sn = ?", (sn,) ).fetchone() conn.close() return dict(row) if row else None def upsert_mes_cache(sn: str, raw_json: str): conn = get_conn() conn.execute( "INSERT OR REPLACE INTO mes_cache (sn, raw_json, created_at) " "VALUES (?, ?, CURRENT_TIMESTAMP)", (sn, raw_json), ) conn.commit() mark_dirty() conn.close() # ─── Access Profiles ─── # One row per access code. `visible_fields` is the authoritative list of MES keys # the code may see; the API strips everything else before responding. def _profile_row(row) -> dict | None: if not row: return None d = dict(row) try: d["visible_fields"] = json.loads(d.get("visible_fields") or "[]") except (json.JSONDecodeError, TypeError): d["visible_fields"] = [] d["is_admin"] = bool(d["is_admin"]) d["enabled"] = bool(d["enabled"]) return d def list_access_profiles() -> list[dict]: conn = get_conn() rows = conn.execute( "SELECT * FROM access_profiles ORDER BY is_admin DESC, id" ).fetchall() conn.close() return [_profile_row(r) for r in rows] def get_access_profile(profile_id: int) -> dict | None: conn = get_conn() row = conn.execute( "SELECT * FROM access_profiles WHERE id = ?", (profile_id,) ).fetchone() conn.close() return _profile_row(row) def get_profile_by_code(code: str) -> dict | None: if not code: return None conn = get_conn() row = conn.execute( "SELECT * FROM access_profiles WHERE code = ?", (code,) ).fetchone() conn.close() return _profile_row(row) def create_access_profile( code: str, name: str = "", is_admin: bool = False, visible_fields: list[str] | None = None, enabled: bool = True, ) -> int: conn = get_conn() cur = conn.execute( "INSERT INTO access_profiles (code, name, is_admin, visible_fields, enabled) " "VALUES (?, ?, ?, ?, ?)", (code, name, 1 if is_admin else 0, json.dumps(visible_fields or []), 1 if enabled else 0), ) conn.commit() mark_dirty() pid = cur.lastrowid conn.close() return pid def update_access_profile(profile_id: int, **kwargs) -> bool: allowed = {"code", "name", "is_admin", "visible_fields", "enabled"} sets, params = [], [] for key, value in kwargs.items(): if key not in allowed: continue if key == "visible_fields": value = json.dumps(value or []) elif key in ("is_admin", "enabled"): value = 1 if value else 0 sets.append(f"{key} = ?") params.append(value) if not sets: return False params.append(profile_id) conn = get_conn() cur = conn.execute( f"UPDATE access_profiles SET {', '.join(sets)}, updated_at = CURRENT_TIMESTAMP " "WHERE id = ?", params, ) conn.commit() mark_dirty() ok = cur.rowcount > 0 conn.close() return ok def delete_access_profile(profile_id: int) -> bool: conn = get_conn() cur = conn.execute("DELETE FROM access_profiles WHERE id = ?", (profile_id,)) conn.commit() mark_dirty() ok = cur.rowcount > 0 conn.close() return ok def access_profiles_fingerprint() -> str: """Hash of every profile's code + field set + enabled flag. Embedded in access tokens: any edit revokes all outstanding tokens at once. """ import hashlib parts = [ f"{p['id']}:{p['code']}:{int(p['enabled'])}:{','.join(sorted(p['visible_fields']))}" for p in list_access_profiles() ] return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16] # ─── Legacy single access code (kept for the /access-code admin endpoint) ─── def _primary_user_profile() -> dict | None: conn = get_conn() row = conn.execute( "SELECT * FROM access_profiles WHERE is_admin = 0 ORDER BY id LIMIT 1" ).fetchone() conn.close() return _profile_row(row) def get_mes_access_code() -> str: profile = _primary_user_profile() if profile: return profile["code"] return get_setting("mes_access_code", "") or s.MES_ACCESS_CODE def set_mes_access_code(code: str): profile = _primary_user_profile() if profile: update_access_profile(profile["id"], code=code) else: create_access_profile(code, "用户", False, []) set_setting("mes_access_code", code) # ─── MES Query Logs (monitoring) ─── def log_mes_query(sn: str, cached: bool = False, status: str = "ok", duration_ms: int = 0): conn = get_conn() conn.execute( "INSERT INTO mes_query_logs (sn, cached, status, duration_ms) VALUES (?, ?, ?, ?)", (sn, 1 if cached else 0, status, duration_ms), ) conn.commit() conn.close() def get_mes_monitoring_stats() -> dict: conn = get_conn() total = conn.execute("SELECT COUNT(*) FROM mes_query_logs").fetchone()[0] today = conn.execute( "SELECT COUNT(*) FROM mes_query_logs WHERE date(created_at)=date('now')" ).fetchone()[0] success = conn.execute( "SELECT COUNT(*) FROM mes_query_logs WHERE status='ok'" ).fetchone()[0] errors = conn.execute( "SELECT COUNT(*) FROM mes_query_logs WHERE status='error'" ).fetchone()[0] cache_hits = conn.execute( "SELECT COUNT(*) FROM mes_query_logs WHERE cached=1" ).fetchone()[0] unique_sn = conn.execute( "SELECT COUNT(DISTINCT sn) FROM mes_query_logs" ).fetchone()[0] avg_ms = conn.execute( "SELECT COALESCE(AVG(duration_ms), 0) FROM mes_query_logs WHERE status='ok'" ).fetchone()[0] recent = conn.execute( "SELECT * FROM mes_query_logs ORDER BY created_at DESC LIMIT 50" ).fetchall() daily = conn.execute( "SELECT date(created_at) as day, COUNT(*) as cnt FROM mes_query_logs " "WHERE created_at >= datetime('now', '-30 days') GROUP BY date(created_at) ORDER BY day" ).fetchall() top_sn = conn.execute( "SELECT sn, COUNT(*) as cnt FROM mes_query_logs GROUP BY sn ORDER BY cnt DESC LIMIT 10" ).fetchall() total_reports = conn.execute("SELECT COUNT(*) FROM problem_reports").fetchone()[0] pending_reports = conn.execute( "SELECT COUNT(*) FROM problem_reports WHERE status='pending'" ).fetchone()[0] os_maps = conn.execute("SELECT COUNT(*) FROM os_file_maps").fetchone()[0] sn_maps = conn.execute("SELECT COUNT(*) FROM sn_file_maps").fetchone()[0] conn.close() return { "total_queries": total, "today_queries": today, "success_queries": success, "error_queries": errors, "cache_hits": cache_hits, "unique_sn": unique_sn, "avg_duration_ms": int(avg_ms or 0), "recent_queries": [dict(r) for r in recent], "daily_queries": [dict(r) for r in daily], "top_sn": [dict(r) for r in top_sn], "total_reports": total_reports, "pending_reports": pending_reports, "os_map_count": os_maps, "sn_map_count": sn_maps, } def lookup_os_file_map(os_version: str) -> dict | None: """Return {os_version, files, note} for an exact OS version, or None.""" import json row = get_os_file_map(os_version) if not row: return None files = row.get("files") if isinstance(files, str): try: files = json.loads(files) except (ValueError, TypeError): files = [] return { "os_version": row.get("os_version", ""), "files": files or [], "note": row.get("note", ""), }