File size: 41,045 Bytes
38f7b1e 06ba0f0 38f7b1e e0a2e1a 38f7b1e e16e5ad 38f7b1e e0a2e1a 38f7b1e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | # ═══════════════════════════════════════════════════════════════════════════
# 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 "❌ <b>No data found.</b>"
d = body.get("data") or {}
return "\n".join([
f"📱 <b>{escape_html(d.get('name') or 'N/A')}</b>",
f"<b>Mobile:</b> <code>{escape_html(d.get('mobile') or '')}</code>",
f"<b>Father:</b> {escape_html(d.get('fname') or 'N/A')}",
f"<b>Circle:</b> {escape_html(d.get('circle') or 'N/A')}",
f"<b>Email:</b> {escape_html(d.get('email') or 'N/A')}",
f"<b>Address:</b> {escape_html(d.get('address') or 'N/A')}",
])
def fmt_aadhaar_info(body: dict) -> str:
if not _is_ok(body):
return "❌ <b>No data found.</b>"
rows = body.get("data") or []
total = int(body.get("count") or len(rows))
if not rows:
return "❌ <b>No records.</b>"
out = [f"📋 <b>Found {total} record(s).</b> Showing first {min(5, len(rows))}:\n"]
for i, p in enumerate(rows[:5], 1):
out.append(
f"{i}. <b>{escape_html(p.get('name') or 'N/A')}</b>\n"
f" Father: {escape_html(p.get('fathersName') or 'N/A')}\n"
f" Phone: <code>{escape_html(p.get('phoneNumber') or '')}</code>\n"
f" Aadhaar: <code>{escape_html(p.get('aadharNumber') or '')}</code>\n"
f" Address: {escape_html(p.get('address') or 'N/A')}\n"
)
if total > 5:
out.append(f"\n…and <b>{total - 5}</b> more. Full data attached below.")
return "\n".join(out)
def fmt_aadhaar_family(body: dict) -> str:
if not _is_ok(body):
return "❌ <b>No data found.</b>"
members = body.get("members") or []
total = body.get("total_records") or len(members)
out = [f"👨👩👧 <b>Family Members ({total})</b>\n"]
for m in members:
out.append(
f"• <b>{escape_html(m.get('name') or 'N/A')}</b> "
f"<i>({escape_html(m.get('relation') or '')})</i>\n"
f" UID: <code>{escape_html(m.get('masked_uid') or '')}</code> "
f"Member: <code>{escape_html(m.get('member_id') or '')}</code>"
)
return "\n".join(out)
def fmt_aadhaar_ration(body: dict) -> str:
if not _is_ok(body):
return "❌ <b>No data found.</b>"
return "\n".join([
"🍚 <b>Ration Card</b>",
f"<b>Head:</b> {escape_html(body.get('head_family') or 'N/A')}",
f"<b>Ration No:</b> <code>{escape_html(body.get('ration_number') or '')}</code>",
f"<b>Application:</b> {escape_html(body.get('application_no') or 'N/A')}",
f"<b>Scheme:</b> {escape_html(body.get('scheme') or 'N/A')}",
f"<b>District:</b> {escape_html(body.get('district') or 'N/A')}, "
f"{escape_html(body.get('state') or '')}",
f"<b>FPS:</b> <code>{escape_html(body.get('fps_id') or '')}</code>",
f"<b>Address:</b> {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"<b>━━━ #{idx} ━━━</b>"]
for key, emoji, label in FIELD_LABELS:
v = _tv(row.get(key), TRUNC.get(key, 60))
if v:
lines.append(f"{emoji} <b>{label}:</b> <code>{escape_html(v)}</code>")
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"📱 <b>Phone:</b> <code>{escape_html(phone)}</code>\n"
f"📄 <b>Page {page + 1}/{total_pages}</b> · "
f"{len(results)} result(s) · ⏱️ {elapsed:.1f}s"
)
if source_note:
head += f"\n⚠️ <i>{source_note}</i>"
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([
"<b>🎯 360° DOSSIER</b>",
f"📱 <b>Mobile:</b> <code>{phone}</code>",
f"🆔 <b>Aadhaar:</b> <code>{a_short}</code>",
"━━━━━━━━━━━━━━━━━━━━━━━━━━"
])
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}. <b>{escape_html(r.get('name') or 'N/A')}</b>")
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}. <b>{escape_html(p.get('name') or 'N/A')}</b>")
if p.get("fathersName"):
out.append(f" 👨 {escape_html(str(p['fathersName'])[:80])}")
if p.get("phoneNumber"):
out.append(f" 📞 <code>{escape_html(str(p['phoneNumber']))}</code>")
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"• <b>{escape_html(m.get('name') or 'N/A')}</b> "
f"({escape_html(rel)}) — <code>{escape_html(uid)}</code>")
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: <b>{escape_html(body.get('head_family') or 'N/A')}</b>")
out.append(f"🔢 Ration: <code>{escape_html(body.get('ration_number') or 'N/A')}</code>")
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: <code>{escape_html(body.get('fps_id') or 'N/A')}</code>")
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=<code>{escape_html(aadhaar[:4])}…{escape_html(aadhaar[-4:])}</code>"
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"<code>{rec['ts_utc']}</code> "
f"<b>{escape_html(rec['type'])}</b> "
f"u=<code>{rec['user_id']}</code> "
f"q=<code>{escape_html(rec['query'])}</code>"
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}") |