# ═══════════════════════════════════════════════════════════════════════════ # core.py — File 2 of 4 # ───────────────────────────────────────────────────────────────────────── # DuckDB engine · HTTP clients · formatters · activity · admin auth · logging # ═══════════════════════════════════════════════════════════════════════════ import config # triggers HfFolder shim + loads env import os import io import csv import json import gzip import time import hmac import asyncio import threading from datetime import datetime, timezone, timedelta from collections import deque import httpx import duckdb from config import ( # env TELEGRAM_TOKEN, API_KEY, WEBHOOK_BASE_URL, TG_API, TG_API_PROXY, ADMIN_SECRET, VIEWER_SECRET, LOG_CHAT_ID, HF_TOKEN, MAX_INMEM_LOG, LOG_FILE_PATH, LOG_ROTATE_MB, LOG_KEEP_ROTATED, LOG_RETENTION_DAYS, ADMIN_SESSION_TTL_MIN, ADMIN_MAX_FAILS, USER_COOLDOWN, DOSSIER_COOLDOWN, QUERY_TIMEOUT, PAGE_SIZE, FETCH_LIMIT, BATCH_TIMEOUT, HISTORY_LEN, LIVE_WINDOW, CACHE_TTL, BROADCAST_DELAY, VERSION, STARTED_AT, # data PHONE_REGEX, AADHAAR_REGEX, TRUNC, APIS, PARQUET_URLS, API_850CR, API_INDDATA, FIELD_LABELS, # state USERS, USER_STATE, ADMIN_SESSIONS, ADMIN_FAILS, ADMIN_AWAITING, LOG_DEQUE, ADMIN_AUDIT, ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, PHONE_COUNTS, BANNED_USERS, BAN_REASONS, USER_HISTORY, SEARCH_CACHE, USER_LAST, DOSSIER_LAST, STATS, # locks _activity_lock, _admin_lock, _state_lock, # helpers log, now_iso, record_id, escape_html, chunk_text, fmt_ts, short_user, touch_user, filter_searches, ) # module-local mutable globals (returned via globals so imports stay read-only) _dossier_state = {"peak": 0} # exposed as PEAK_CONCURRENT via get_stats() # ═══════════════════════════════════════════════════════════════════════════ # DUCKDB ENGINE # ═══════════════════════════════════════════════════════════════════════════ _con = None _con_lock = threading.Lock() _con_ready = threading.Event() _query_lock = threading.Lock() _warmed = threading.Event() _warm_thread_started = False def get_con(): """Lazy-init DuckDB. Safe to call from any thread.""" global _con with _con_lock: if _con is not None: return _con log.info("🔧 Initializing DuckDB…") c = duckdb.connect(":memory:") c.execute("INSTALL httpfs; LOAD httpfs;") if HF_TOKEN: c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');") c.execute("SET enable_object_cache=true;") c.execute("SET preserve_insertion_order=false;") c.execute("SET threads=6;") c.execute("SET memory_limit='12GB';") urls = ", ".join(f"'{u}'" for u in PARQUET_URLS) try: c.execute( f"SELECT COUNT(*) FROM read_parquet([{urls}], union_by_name=true) WHERE 1=0" ) log.info("✅ DuckDB connection ready") except Exception as e: log.warning(f"⚠️ DuckDB metadata warning: {e}") _con = c _con_ready.set() return _con def warm_phone_cache(): """Warm each parquet file. Runs once; safe to call repeatedly.""" global _warm_thread_started if _warmed.is_set(): return _warm_thread_started = True log.info(f"🔥 Warm-up starting ({len(PARQUET_URLS)} HiTeck files)…") t0 = time.time() loaded = skipped = 0 try: con = get_con() for url in PARQUET_URLS: name = url.rsplit("/", 1)[-1] try: con.execute(f"SELECT * FROM read_parquet('{url}') LIMIT 1").fetchall() loaded += 1 log.info(f" ✅ warmed: {name}") except Exception as e: skipped += 1 log.warning(f" ⏭️ skipped {name}: {str(e)[:120]}") _warmed.set() log.info(f"✅ Warm-up complete in {time.time() - t0:.1f}s " f"({loaded} loaded, {skipped} skipped)") if loaded == 0: log.error("⚠️ NO files warmed — will fall back to APIs only") except Exception as e: log.error(f"⚠️ Warm-up fatal: {e}") _warm_thread_started = False def run_search_safe(phone: str, limit: int = FETCH_LIMIT, timeout_secs: int = QUERY_TIMEOUT) -> list: """ Blocking DuckDB query with interrupt watchdog. Runs via executor. Raises duckdb.InterruptException on timeout (converted by caller). """ con = get_con() with _query_lock: stopped = threading.Event() def watchdog(): if not stopped.wait(timeout_secs): log.warning(f"⏱️ Query timeout {timeout_secs}s — interrupting DuckDB") try: con.interrupt() except Exception as e: log.warning(f"⚠️ interrupt failed: {e}") wd = threading.Thread(target=watchdog, daemon=True) wd.start() try: urls = ", ".join(f"'{u}'" for u in PARQUET_URLS) sql = f""" SELECT name, fathersName, phoneNumber, aadharNumber, otherNumber, address, district, pincode, state, town, source FROM read_parquet([{urls}], union_by_name=true) WHERE CAST(phoneNumber AS VARCHAR) = ? LIMIT {int(limit)} """ cur = con.execute(sql, [phone]) cols = [d[0] for d in cur.description] return [dict(zip(cols, r)) for r in cur.fetchall()] finally: stopped.set() # ═══════════════════════════════════════════════════════════════════════════ # HTTP CLIENTS (asurpapa + 2 DuckDB fallbacks) # ═══════════════════════════════════════════════════════════════════════════ def _is_ok(body) -> bool: """Handles both `status:'success'` (str) and `status:true` (bool) shapes.""" s = body.get("status") if isinstance(body, dict) else None return s in ("success", True) async def call_upstream(api_key: str, number: str) -> dict: """Query one asurpapa API.""" cfg = APIS[api_key] params = {"key": API_KEY, cfg["param"]: number} redacted = f"{cfg['url']}?key=***&{cfg['param']}={number}" t0 = time.time() try: async with httpx.AsyncClient(timeout=25.0) as client: r = await client.get(cfg["url"], params=params) elapsed = int((time.time() - t0) * 1000) try: body = r.json() except Exception: body = {"_raw": r.text[:4000]} return { "http_code": r.status_code, "body": body, "elapsed_ms": elapsed, "req_params": {cfg["param"]: number}, "req_url_redacted": redacted, "error": None, } except Exception as e: return { "http_code": 0, "body": {"error": str(e)}, "elapsed_ms": int((time.time() - t0) * 1000), "req_params": {cfg["param"]: number}, "req_url_redacted": redacted, "error": str(e), } async def _q_cr850(client: httpx.AsyncClient, number: str) -> list: try: r = await client.get(f"{API_850CR}/{number}", timeout=40.0) if r.status_code != 200: return [] data = r.json() if not data.get("success") or not data.get("results"): return [] out = [] for item in data["results"]: addr = item.get("address") or {} full = addr.get("full_address", "") if isinstance(addr, dict) else "" if full: full = full.lstrip(", ").strip() out.append({ "name": item.get("name"), "fathersName": item.get("father_name"), "phoneNumber": number, "aadharNumber": None, "otherNumber": item.get("alternate_number"), "address": full, "district": None, "pincode": None, "state": item.get("state"), "town": None, "source": "850CR Fast", }) return out except Exception as e: log.warning(f"850CR API failed: {e}") return [] async def _q_inddata(client: httpx.AsyncClient, number: str) -> list: try: r = await client.get(API_INDDATA, params={"mobile": number}, timeout=30.0) if r.status_code != 200: return [] data = r.json() rows = data.get("data") if isinstance(data, dict) else None if not isinstance(rows, list): return [] return [{ "name": item.get("name"), "fathersName": item.get("fname"), "phoneNumber": number, "aadharNumber": None, "otherNumber": None, "address": item.get("address"), "district": None, "pincode": None, "state": None, "town": None, "source": "IndData 1.4B", } for item in rows] except Exception as e: log.warning(f"IndData API failed: {e}") return [] async def search_apis(number: str) -> list: """Parallel fallback when DuckDB is not warmed.""" log.info(f"🔄 API fallback for {number}") async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client: results = await asyncio.gather( _q_cr850(client, number), _q_inddata(client, number), return_exceptions=True, ) merged = [] for res in results: if isinstance(res, list): merged.extend(res) return merged # ═══════════════════════════════════════════════════════════════════════════ # DEDUP + NORMALIZE # ═══════════════════════════════════════════════════════════════════════════ def _norm(s) -> str: if not s: return "" return " ".join(str(s).strip().lower().split()) def _dedup_key(rec: dict): name = _norm(rec.get("name")) father = _norm(rec.get("fathersName")) addr = _norm(rec.get("address")) addr_n = "".join(ch if ch.isalnum() else " " for ch in addr).strip() if name and addr_n: return ("na", name, addr_n) if name and father: return ("nf", name, father) if addr_n: return ("a", addr_n) return None def dedup_records(records: list) -> list: """Prefer the record with more non-empty fields per dedup key.""" seen = {} result = [] for rec in records: key = _dedup_key(rec) if key is None: result.append(rec) continue idx = seen.get(key) if idx is None: seen[key] = len(result) result.append(rec) else: ef = sum(1 for v in result[idx].values() if v) nf = sum(1 for v in rec.values() if v) if nf > ef: result[idx] = rec return result def normalize_phone(text: str): """Accepts 9876543210, +91 98765 43210, 09876543210, 919876543210, dashes, etc.""" raw = (text or "").strip() digits = "".join(ch for ch in raw if ch.isdigit()) if not digits: return None, "not a valid number" if len(digits) == 11 and digits.startswith("0"): digits = digits[1:] if len(digits) == 12 and digits.startswith("91"): digits = digits[2:] elif len(digits) == 11 and digits.startswith("91"): digits = digits[1:] if len(digits) == 10: if PHONE_REGEX.match(digits): return digits, None return None, "not a valid 10-digit number" return None, f"expected 10 digits, got {len(digits)}" # ═══════════════════════════════════════════════════════════════════════════ # UNIFIED SEARCH ENTRY # ═══════════════════════════════════════════════════════════════════════════ async def do_search(phone: str) -> tuple: """Returns (deduped_rows, elapsed_secs, source_label).""" loop = asyncio.get_running_loop() t0 = time.time() if not _warmed.is_set(): results = await search_apis(phone) source = "api_fallback" else: results = await asyncio.wait_for( loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT), timeout=QUERY_TIMEOUT + 10, ) source = "duckdb" return dedup_records(results), time.time() - t0, source async def lookup_aadhaar_for_phone(phone: str) -> tuple: """Returns (aadhaar_list, matching_rows). Used by /360.""" loop = asyncio.get_running_loop() rows = await asyncio.wait_for( loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT), timeout=QUERY_TIMEOUT + 10, ) rows = dedup_records(rows) aadhaars = [] for r in rows: a = str(r.get("aadharNumber") or "").strip() if a and a.isdigit() and len(a) == 12 and a not in aadhaars: aadhaars.append(a) return aadhaars, rows # ═══════════════════════════════════════════════════════════════════════════ # TELEGRAM HTTP HELPERS # ═══════════════════════════════════════════════════════════════════════════ async def tg_call(method: str, payload: dict, timeout: float = 20.0) -> dict: try: async with httpx.AsyncClient(timeout=timeout) as client: r = await client.post(f"{TG_API_PROXY}/{method}", json=payload) return r.json() except Exception as e: log.warning(f"❌ tg_call({method}): {e}") return {"ok": False, "error": str(e)} async def tg_send_message(chat_id, text: str, parse_mode: str = "HTML", reply_markup: dict = None): for chunk in chunk_text(text, 3800): payload = { "chat_id": chat_id, "text": chunk, "parse_mode": parse_mode, "disable_web_page_preview": True, } if reply_markup: payload["reply_markup"] = reply_markup await tg_call("sendMessage", payload) async def tg_send_document(chat_id, file_path: str, filename: str, caption: str = ""): try: async with httpx.AsyncClient(timeout=180.0) as client: with open(file_path, "rb") as f: files = {"document": (filename, f, "application/gzip")} data = {"chat_id": str(chat_id)} if caption: data["caption"] = caption[:1024] r = await client.post(f"{TG_API_PROXY}/sendDocument", data=data, files=files) try: return r.json() except Exception: return {"ok": False, "status": r.status_code} except Exception as e: log.warning(f"❌ sendDocument: {e}") return {"ok": False, "error": str(e)} async def tg_send_bytes(chat_id, filename: str, content: bytes, caption: str = ""): try: async with httpx.AsyncClient(timeout=120.0) as client: files = {"document": (filename, content, "application/octet-stream")} data = {"chat_id": str(chat_id)} if caption: data["caption"] = caption[:1024] r = await client.post(f"{TG_API_PROXY}/sendDocument", data=data, files=files) return r.json() except Exception as e: log.warning(f"❌ sendBytes: {e}") return {"ok": False, "error": str(e)} async def tg_answer_callback(cb_id: str, text: str = "", alert: bool = False): await tg_call("answerCallbackQuery", { "callback_query_id": cb_id, "text": text, "show_alert": alert, }) # ═══════════════════════════════════════════════════════════════════════════ # FORMATTERS — asurpapa (4) # ═══════════════════════════════════════════════════════════════════════════ def _tv(v, n: int) -> str: """Truncate a value to n chars; empty for null-ish.""" if v is None: return "" s = str(v).strip() if s.lower() in ("", "null", "none", "nan"): return "" return s if len(s) <= n else s[: n - 1] + "…" def fmt_mobile(body: dict) -> str: if not _is_ok(body): return "❌ No data found." d = body.get("data") or {} return "\n".join([ f"📱 {escape_html(d.get('name') or 'N/A')}", f"Mobile: {escape_html(d.get('mobile') or '')}", f"Father: {escape_html(d.get('fname') or 'N/A')}", f"Circle: {escape_html(d.get('circle') or 'N/A')}", f"Email: {escape_html(d.get('email') or 'N/A')}", f"Address: {escape_html(d.get('address') or 'N/A')}", ]) def fmt_aadhaar_info(body: dict) -> str: if not _is_ok(body): return "❌ No data found." rows = body.get("data") or [] total = int(body.get("count") or len(rows)) if not rows: return "❌ No records." out = [f"📋 Found {total} record(s). Showing first {min(5, len(rows))}:\n"] for i, p in enumerate(rows[:5], 1): out.append( f"{i}. {escape_html(p.get('name') or 'N/A')}\n" f" Father: {escape_html(p.get('fathersName') or 'N/A')}\n" f" Phone: {escape_html(p.get('phoneNumber') or '')}\n" f" Aadhaar: {escape_html(p.get('aadharNumber') or '')}\n" f" Address: {escape_html(p.get('address') or 'N/A')}\n" ) if total > 5: out.append(f"\n…and {total - 5} more. Full data attached below.") return "\n".join(out) def fmt_aadhaar_family(body: dict) -> str: if not _is_ok(body): return "❌ No data found." members = body.get("members") or [] total = body.get("total_records") or len(members) out = [f"👨‍👩‍👧 Family Members ({total})\n"] for m in members: out.append( f"• {escape_html(m.get('name') or 'N/A')} " f"({escape_html(m.get('relation') or '')})\n" f" UID: {escape_html(m.get('masked_uid') or '')} " f"Member: {escape_html(m.get('member_id') or '')}" ) return "\n".join(out) def fmt_aadhaar_ration(body: dict) -> str: if not _is_ok(body): return "❌ No data found." return "\n".join([ "🍚 Ration Card", f"Head: {escape_html(body.get('head_family') or 'N/A')}", f"Ration No: {escape_html(body.get('ration_number') or '')}", f"Application: {escape_html(body.get('application_no') or 'N/A')}", f"Scheme: {escape_html(body.get('scheme') or 'N/A')}", f"District: {escape_html(body.get('district') or 'N/A')}, " f"{escape_html(body.get('state') or '')}", f"FPS: {escape_html(body.get('fps_id') or '')}", f"Address: {escape_html(body.get('address') or 'N/A')}", ]) FORMATTERS = { "mobile": fmt_mobile, "aadhaar_info": fmt_aadhaar_info, "aadhaar_family": fmt_aadhaar_family, "aadhaar_ration": fmt_aadhaar_ration, } # ═══════════════════════════════════════════════════════════════════════════ # FORMATTERS — DuckDB paginated results # ═══════════════════════════════════════════════════════════════════════════ def format_result(idx: int, row: dict) -> str: lines = [f"━━━ #{idx} ━━━"] for key, emoji, label in FIELD_LABELS: v = _tv(row.get(key), TRUNC.get(key, 60)) if v: lines.append(f"{emoji} {label}: {escape_html(v)}") return "\n".join(lines) def plain_record(idx: int, row: dict) -> str: lines = [f"#{idx}"] for key, _e, label in FIELD_LABELS: v = _tv(row.get(key), TRUNC.get(key, 60)) if v: lines.append(f"{label}: {v}") return "\n".join(lines) def render_page(results: list, page: int, total_pages: int, phone: str, elapsed: float, source_note: str = "") -> str: start = page * PAGE_SIZE chunk = results[start:start + PAGE_SIZE] head = ( f"📱 Phone: {escape_html(phone)}\n" f"📄 Page {page + 1}/{total_pages} · " f"{len(results)} result(s) · ⏱️ {elapsed:.1f}s" ) if source_note: head += f"\n⚠️ {source_note}" body = "\n\n".join(format_result(start + i + 1, r) for i, r in enumerate(chunk)) return f"{head}\n\n{body}" def page_keyboard(search_id: str, page: int, total_pages: int, has_export: bool = True) -> dict: nav = [] if page > 0: nav.append({"text": "◀ Prev", "callback_data": f"p:{search_id}:{page - 1}"}) nav.append({"text": f"{page + 1} / {total_pages}", "callback_data": "noop"}) if page < total_pages - 1: nav.append({"text": "Next ▶", "callback_data": f"p:{search_id}:{page + 1}"}) extras = [{"text": "📋 Copy page", "callback_data": f"c:{search_id}:{page}"}] if has_export: extras.append({"text": "📥 Export", "callback_data": f"e:{search_id}"}) return {"inline_keyboard": [nav, extras]} # ═══════════════════════════════════════════════════════════════════════════ # FORMATTERS — /360 dossier # ═══════════════════════════════════════════════════════════════════════════ def _divider(label: str = "", total: int = 36) -> str: if not label: return "━" * total pad = max(0, total - len(label) - 4) left = pad // 2 right = pad - left return "━" * left + f" {label} " + "━" * right def _fmt_360_header(phone: str, aadhaar: str) -> str: a_short = f"{aadhaar[:4]}…{aadhaar[-4:]}" if len(aadhaar) >= 8 else aadhaar return "\n".join([ "🎯 360° DOSSIER", f"📱 Mobile: {phone}", f"🆔 Aadhaar: {a_short}", "━━━━━━━━━━━━━━━━━━━━━━━━━━" ]) def _fmt_360_mobile(rows: list) -> str: out = [_divider("📱 Mobile Records")] if not rows: out.append("⚠️ No mobile records found") return "\n".join(out) for i, r in enumerate(rows[:5], 1): out.append(f"{i}. {escape_html(r.get('name') or 'N/A')}") if r.get("fathersName"): out.append(f" 👨 {escape_html(str(r['fathersName'])[:80])}") if r.get("address"): out.append(f" 🏠 {escape_html(str(r['address'])[:100])}") if r.get("source"): out.append(f" 📂 {escape_html(r['source'])}") if len(rows) > 5: out.append(f" …+{len(rows) - 5} more") return "\n".join(out) def _fmt_360_aadhaar_info(body: dict, aadhaar: str) -> str: out = [_divider("🆔 Aadhaar Info")] if not body or not _is_ok(body): out.append("⚠️ Unavailable") return "\n".join(out) rows = body.get("data") or [] total = int(body.get("count") or len(rows)) if not rows: out.append("⚠️ No records") return "\n".join(out) out.append(f"Found {total} · showing {min(5, len(rows))}:") for i, p in enumerate(rows[:5], 1): out.append(f"{i}. {escape_html(p.get('name') or 'N/A')}") if p.get("fathersName"): out.append(f" 👨 {escape_html(str(p['fathersName'])[:80])}") if p.get("phoneNumber"): out.append(f" 📞 {escape_html(str(p['phoneNumber']))}") if p.get("address"): out.append(f" 🏠 {escape_html(str(p['address'])[:100])}") if total > 5: out.append(f"…+{total - 5} more (full in JSON)") return "\n".join(out) def _fmt_360_family(body: dict) -> str: out = [_divider("👨‍👩‍👧 Family Members")] if not body or not _is_ok(body): out.append("⚠️ Unavailable") return "\n".join(out) members = body.get("members") or [] total = body.get("total_records") or len(members) if not members: out.append("⚠️ No family records") return "\n".join(out) out.append(f"Total: {total}") for m in members: rel = m.get("relation") or "" uid = m.get("masked_uid") or "" out.append(f"• {escape_html(m.get('name') or 'N/A')} " f"({escape_html(rel)}) — {escape_html(uid)}") return "\n".join(out) def _fmt_360_ration(body: dict) -> str: out = [_divider("🍚 Ration Card")] if not body or not _is_ok(body): out.append("⚠️ Unavailable") return "\n".join(out) out.append(f"👤 Head: {escape_html(body.get('head_family') or 'N/A')}") out.append(f"🔢 Ration: {escape_html(body.get('ration_number') or 'N/A')}") out.append(f"📋 Scheme: {escape_html(body.get('scheme') or 'N/A')}") district = escape_html(body.get("district") or "") state = escape_html(body.get("state") or "") if district or state: out.append(f"🗺️ {district}, {state}") out.append(f"🏪 FPS: {escape_html(body.get('fps_id') or 'N/A')}") if body.get("address"): out.append(f"🏠 {escape_html(str(body['address'])[:120])}") return "\n".join(out) def render_dossier(phone: str, aadhaar_used: str, mobile_rows: list, info_body: dict, family_body: dict, ration_body: dict, elapsed: float) -> tuple: """ Build the cool /360 dossier. Returns (formatted_text, raw_json_dict). """ sections = { "mobile": bool(mobile_rows), "aadhaar_info": bool(info_body and _is_ok(info_body)), "family": bool(family_body and _is_ok(family_body)), "ration": bool(ration_body and _is_ok(ration_body)), } ok_count = sum(1 for v in sections.values() if v) blocks = [ _fmt_360_header(phone, aadhaar_used), "", _fmt_360_mobile(mobile_rows), "", _fmt_360_aadhaar_info(info_body, aadhaar_used), "", _fmt_360_family(family_body), "", _fmt_360_ration(ration_body), "", _divider(), f"⏱️ {elapsed:.1f}s · {ok_count}/4 sections", "📎 Full dossier attached as JSON", ] text = "\n".join(blocks) raw = { "phone": phone, "aadhaar_used": aadhaar_used, "elapsed_secs": round(elapsed, 2), "sections_ok": sections, "mobile_rows": mobile_rows, "aadhaar_info": info_body, "family": family_body, "ration": ration_body, "generated_at": now_iso(), "version": VERSION, } return text, raw # ═══════════════════════════════════════════════════════════════════════════ # ACTIVITY TRACKING # ═══════════════════════════════════════════════════════════════════════════ def log_activity(user: dict, action: str, input_val: str, reply_type: str, summary: str = "", elapsed_ms: int = 0, source: str = ""): if not user or "id" not in user: return now = time.time() uid = user["id"] with _activity_lock: info = UNIQUE_USERS.setdefault(uid, { "username": None, "first_name": None, "last_name": None, "count": 0, "first_seen": now, "last_seen": now, }) for k in ("username", "first_name", "last_name"): if user.get(k): info[k] = user[k] info["count"] += 1 info["last_seen"] = now ACTIVE_USERS[uid] = now if (action == "search" and isinstance(input_val, str) and input_val.isdigit() and len(input_val) == 10): PHONE_COUNTS[input_val] += 1 ACTIVITY_LOG.append({ "ts": now, "user_id": uid, "username": user.get("username"), "first_name": user.get("first_name"), "action": action, "input": (input_val or "")[:80], "reply_type": reply_type, "summary": (summary or "")[:150], "elapsed_ms": int(elapsed_ms), "source": source, }) # track peak live_now = sum(1 for t in ACTIVE_USERS.values() if t >= now - LIVE_WINDOW) if live_now > _dossier_state["peak"]: _dossier_state["peak"] = live_now def get_live_users() -> list: cutoff = time.time() - LIVE_WINDOW with _activity_lock: live = [(uid, ts) for uid, ts in ACTIVE_USERS.items() if ts >= cutoff] live.sort(key=lambda x: -x[1]) return live def get_stats() -> dict: now = time.time() today_start = now - (now % 86400) with _activity_lock: today_users = set() today_searches = total_searches = 0 for e in ACTIVITY_LOG: if e["action"] == "search": total_searches += 1 if e["ts"] >= today_start: today_searches += 1 today_users.add(e["user_id"]) return { "unique_users": len(UNIQUE_USERS), "live_users": sum(1 for ts in ACTIVE_USERS.values() if ts >= now - LIVE_WINDOW), "today_users": len(today_users), "today_searches": today_searches, "total_searches": total_searches, "peak_concurrent": _dossier_state["peak"], "total_log_entries": len(ACTIVITY_LOG), "banned_count": len(BANNED_USERS), "maintenance": MAINTENANCE_MODE, "dossiers": STATS.get("dossiers", 0), } def add_to_history(user_id: int, phone: str, count: int, elapsed: float, source: str): if user_id is None: return with _activity_lock: h = USER_HISTORY.setdefault(user_id, deque(maxlen=HISTORY_LEN)) h.appendleft({"phone": phone, "ts": time.time(), "count": count, "elapsed": elapsed, "source": source}) # ═══════════════════════════════════════════════════════════════════════════ # BAN / MAINTENANCE # ═══════════════════════════════════════════════════════════════════════════ def is_banned(user_id: int) -> bool: with _state_lock: return user_id in BANNED_USERS def ban_user(user_id: int, reason: str = ""): with _state_lock: BANNED_USERS.add(user_id) BAN_REASONS[user_id] = reason def unban_user(user_id: int) -> bool: with _state_lock: if user_id in BANNED_USERS: BANNED_USERS.discard(user_id) BAN_REASONS.pop(user_id, None) return True return False def get_maintenance() -> tuple: with _state_lock: return config.MAINTENANCE_MODE, config.MAINTENANCE_REASON def set_maintenance(on: bool, reason: str = ""): # global MAINTENANCE_MODE, MAINTENANCE_REASON with _state_lock: config.MAINTENANCE_MODE = on config.MAINTENANCE_REASON = reason if on else "" # ═══════════════════════════════════════════════════════════════════════════ # ADMIN AUTH STATE # ═══════════════════════════════════════════════════════════════════════════ def is_admin_session(user_id: int) -> bool: if user_id is None: return False with _admin_lock: exp = ADMIN_SESSIONS.get(user_id) if exp is None: return False if time.time() > exp: ADMIN_SESSIONS.pop(user_id, None) return False return True def grant_admin(user_id: int): with _admin_lock: ADMIN_SESSIONS[user_id] = time.time() + ADMIN_SESSION_TTL_MIN * 60 def revoke_admin(user_id: int): with _admin_lock: ADMIN_SESSIONS.pop(user_id, None) _admin_states = {} def admin_state_get(user_id: int): with _admin_lock: entry = _admin_states.get(user_id) if entry is None: return None state, set_at = entry if time.time() - set_at > 180: # 3-min prompt TTL _admin_states.pop(user_id, None) return None return state def admin_state_set(user_id: int, state: str): with _admin_lock: _admin_states[user_id] = (state, time.time()) def admin_state_clear(user_id: int): with _admin_lock: _admin_states.pop(user_id, None) def admin_audit(uid: int, action: str, detail: str = ""): ADMIN_AUDIT.appendleft({ "ts": now_iso(), "user_id": uid, "action": action, "detail": detail[:200], }) # ═══════════════════════════════════════════════════════════════════════════ # LOG WRITE LAYER (3-tier: deque + JSONL + channel mirror) # ═══════════════════════════════════════════════════════════════════════════ def _rotate_if_needed(): try: if not os.path.exists(LOG_FILE_PATH): return if os.path.getsize(LOG_FILE_PATH) < LOG_ROTATE_MB * 1024 * 1024: return for i in range(LOG_KEEP_ROTATED, 0, -1): src = f"{LOG_FILE_PATH}.{i}" dst = f"{LOG_FILE_PATH}.{i + 1}" if os.path.exists(src): if i == LOG_KEEP_ROTATED: try: os.remove(src) except Exception: pass else: os.rename(src, dst) os.rename(LOG_FILE_PATH, f"{LOG_FILE_PATH}.1") log.info(f"📦 Rotated {LOG_FILE_PATH}") except Exception as e: log.warning(f"rotation failed: {e}") def write_log_record(rec: dict): """Append to deque + JSONL file (rotation-aware). Caller fires mirror_log.""" LOG_DEQUE.append(rec) try: _rotate_if_needed() with open(LOG_FILE_PATH, "a", encoding="utf-8") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n") except Exception as e: log.warning(f"log write failed: {e}") async def mirror_log(rec: dict): """Mirror a compact summary line to LOG_CHAT_ID (survives restarts).""" if not LOG_CHAT_ID: return try: aadhaar = rec.get("aadhaar_used", "") aadhaar_part = ( f" aadhaar={escape_html(aadhaar[:4])}…{escape_html(aadhaar[-4:])}" if aadhaar else "" ) sections = rec.get("sections_present") or [] sections_part = ( f" [{sum(1 for x in sections if x)}/{len(sections)} sections]" if sections else "" ) line = ( f"{rec['ts_utc']} " f"{escape_html(rec['type'])} " f"u={rec['user_id']} " f"q={escape_html(rec['query'])}" f"{aadhaar_part} " f"{rec['status']} {rec['elapsed_ms']}ms" f"{sections_part}" ) await tg_send_message(int(LOG_CHAT_ID), line) except Exception as e: log.warning(f"mirror failed: {e}") async def retention_loop(): """Daily-ish trim of memory + old rotated files.""" while True: try: cutoff = datetime.now(timezone.utc) - timedelta(days=LOG_RETENTION_DAYS) kept = deque( (r for r in LOG_DEQUE if datetime.fromisoformat(r["ts_utc"]) >= cutoff), maxlen=MAX_INMEM_LOG, ) LOG_DEQUE.clear() LOG_DEQUE.extend(kept) for i in range(1, LOG_KEEP_ROTATED + 1): p = f"{LOG_FILE_PATH}.{i}" if os.path.exists(p): mtime = datetime.fromtimestamp(os.path.getmtime(p), tz=timezone.utc) if mtime < cutoff: try: os.remove(p) except Exception: pass except Exception as e: log.warning(f"retention error: {e}") await asyncio.sleep(3600 * 6) # ═══════════════════════════════════════════════════════════════════════════ # EXPORTS (module __all__ for clarity) # ═══════════════════════════════════════════════════════════════════════════ __all__ = [ # DuckDB "get_con", "warm_phone_cache", "run_search_safe", "_con_ready", "_warmed", # HTTP "call_upstream", "search_apis", "do_search", "lookup_aadhaar_for_phone", # helpers "_is_ok", "dedup_records", "normalize_phone", # Telegram "tg_call", "tg_send_message", "tg_send_document", "tg_send_bytes", "tg_answer_callback", # formatters "FORMATTERS", "format_result", "plain_record", "render_page", "page_keyboard", "render_dossier", # activity "log_activity", "get_live_users", "get_stats", "add_to_history", # moderation "is_banned", "ban_user", "unban_user", "get_maintenance", "set_maintenance", # admin "is_admin_session", "grant_admin", "revoke_admin", "admin_state_get", "admin_state_set", "admin_state_clear", "admin_audit", # logging "write_log_record", "mirror_log", "retention_loop", ] log.info(f"core loaded: VERSION={VERSION}")