from __future__ import annotations import re import sqlite3 from pathlib import Path MAIN_CONFIRMED = "confirmed" MAIN_PRESENT = "present" NO_MAIN = "none" # no canonical and no confirmed primary binding UNAVAILABLE = "unavailable" # DB/table/query failed; state is unknown MAX_UID = (1 << 63) - 1 _ACCOUNT_NAME = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z") def _account_uid(name: str) -> int | None: """Exact account identity, mirrored from bot/account_limits.py.""" if not isinstance(name, str): return None match = _ACCOUNT_NAME.fullmatch(name) if match is None: return None try: uid = int(match[1]) except ValueError: return None return uid if uid <= MAX_UID else None def _main_name(name: str, uid: int) -> str | None: name = str(name or "") if not name or name.startswith(("pm", "sol")): return None if name.startswith("tg"): if _account_uid(name) != uid: return None return "tg%d" % uid return name def _normalise_key(value) -> str: if isinstance(value, bytes): value = value.decode("utf-8", "ignore") text = str(value or "").strip() return text[3:] if text.startswith("sk-") else text def _keys_match(stored, live) -> bool: stored = _normalise_key(stored) live = _normalise_key(live) return bool(stored and live and stored == live) def _readonly(path) -> sqlite3.Connection | None: """Open an existing SQLite file read-only; never create a missing file.""" try: resolved = Path(path).resolve(strict=True) except (OSError, RuntimeError): return None if not resolved.is_file(): return None con = sqlite3.connect(resolved.as_uri() + "?mode=ro", uri=True, timeout=0.35) con.row_factory = sqlite3.Row con.execute("PRAGMA query_only=ON") con.execute("PRAGMA busy_timeout=350") return con def _chunks(values, size: int = 400): values = list(values) for start in range(0, len(values), size): yield values[start:start + size] def main_key_states(bot_db, gw_db, uids) -> dict[int, str]: try: wanted = sorted({int(uid) for uid in uids if 0 < int(uid) <= MAX_UID}) except (TypeError, ValueError): return {} if not wanted: return {} result = {uid: UNAVAILABLE for uid in wanted} bot_con = None gw_con = None try: bot_con = _readonly(bot_db) gw_con = _readonly(gw_db) if bot_con is None or gw_con is None: return result bindings: dict[int, tuple] = {} for chunk in _chunks(wanted): marks = ",".join("?" for _ in chunk) rows = bot_con.execute( "SELECT tg_id,token_name,api_key FROM users WHERE tg_id IN (%s)" % marks, chunk, ) for row in rows: bindings[int(row["tg_id"])] = (row["token_name"], row["api_key"]) names = set() for uid in wanted: names.add("tg%d" % uid) binding = bindings.get(uid) bound_name = _main_name(binding[0], uid) if binding else None if bound_name: names.add(bound_name) live: dict[str, list] = {} for chunk in _chunks(sorted(names)): marks = ",".join("?" for _ in chunk) rows = gw_con.execute( "SELECT name,key FROM tokens WHERE deleted_at IS NULL " "AND status IN (1,2) AND name IN (%s)" % marks, chunk, ) for row in rows: live.setdefault(str(row["name"]), []).append(row["key"]) for uid in wanted: canonical = "tg%d" % uid binding = bindings.get(uid) bound_name = _main_name(binding[0], uid) if binding else None if bound_name: rows = live.get(bound_name, []) if len(rows) == 1 and _keys_match(binding[1], rows[0]): result[uid] = MAIN_CONFIRMED continue result[uid] = MAIN_PRESENT if canonical in live else NO_MAIN return result except (sqlite3.Error, OSError, ValueError): return {uid: UNAVAILABLE for uid in wanted} finally: if bot_con is not None: bot_con.close() if gw_con is not None: gw_con.close()