Hfzune commited on
Commit
0c2b831
·
verified ·
1 Parent(s): f583194

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +724 -0
app.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import huggingface_hub
2
+ if not hasattr(huggingface_hub, "HfFolder"):
3
+ class _HfFolder:
4
+ @staticmethod
5
+ def get_token():
6
+ try: return huggingface_hub.get_token()
7
+ except: return None
8
+ @staticmethod
9
+ def save_token(t):
10
+ try: huggingface_hub.login(t)
11
+ except: pass
12
+ @staticmethod
13
+ def delete_token():
14
+ try: huggingface_hub.logout()
15
+ except: pass
16
+ huggingface_hub.HfFolder = _HfFolder
17
+
18
+ import os, sys, re, io, csv, json, time, html, uuid, asyncio, hashlib, hmac, threading, traceback, logging, urllib.parse
19
+ from datetime import datetime, timezone
20
+ from collections import deque, Counter
21
+ from typing import Optional
22
+ import duckdb, httpx, gradio as gr
23
+ from fastapi import Request
24
+ from fastapi.responses import JSONResponse, HTMLResponse, Response
25
+ from starlette.routing import Route as StarletteRoute
26
+
27
+ try:
28
+ import spaces
29
+ _HAS_SPACES = True
30
+ except:
31
+ _HAS_SPACES = False
32
+ class spaces:
33
+ @staticmethod
34
+ def GPU(*a, **kw):
35
+ def deco(f): return f
36
+ return deco
37
+
38
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(message)s", datefmt="%H:%M:%S")
39
+ log = logging.getLogger("app")
40
+
41
+ # ══ CONFIG ══
42
+ BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip()
43
+ HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
44
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me").strip()
45
+ SPACE_URL = os.environ.get("SPACE_URL", "").strip().rstrip("/")
46
+ SPACE_HOST = os.environ.get("SPACE_HOST", "").strip().rstrip("/")
47
+ ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "").strip()
48
+ OWNER_IDS = {int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()}
49
+ FORCE_JOIN_CHANNEL = os.environ.get("FORCE_JOIN_CHANNEL", "").strip()
50
+ ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT").strip()
51
+ BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "").strip()
52
+ BACKUP_ENABLED = bool(BACKUP_CHANNEL_ID)
53
+ TELEGRAM_API = f"https://api.telegram.org/bot{BOT_TOKEN}"
54
+ VERSION = "4.0.0"
55
+ BOT_NAME = "Phone Lookup Bot"
56
+
57
+ HITECK_URLS = [f"https://huggingface.co/datasets/HiTeckGroup/HiTeckgroop/resolve/main/idx_phone.{i}.parquet" for i in range(7)]
58
+ FLIPKART_URLS = ["https://huggingface.co/datasets/Hfzune/Flipkart/resolve/main/flipkart.parquet"]
59
+ ALL_PARQUET_URLS = HITECK_URLS + FLIPKART_URLS
60
+
61
+ API_850CR = "https://tfqdeadlo-850crfastsearch.hf.space/search"
62
+ API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search"
63
+ ASUR_API = {
64
+ "num_to_info": "https://num-to-info.asurpapa.workers.dev/api",
65
+ "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api",
66
+ "aadhaar_family": "https://aadhaar-family.asurpapa.workers.dev/api",
67
+ "aadhaar_ration": "https://ration-card.asurpapa.workers.dev/api",
68
+ }
69
+ ASUR_PARAM_NAMES = {"num_to_info": "number", "aadhaar_to_info": "aadhaar", "aadhaar_family": "aadhaar", "aadhaar_ration": "aadhar"}
70
+
71
+ PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT = 4, 40, 90
72
+ BATCH_MAX, BATCH_TIMEOUT, HTTP_TIMEOUT = 5, 60, 30
73
+ CACHE_TTL, SEARCH_CACHE_TTL, MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL = 300, 1800, 300, 600
74
+ USER_COOLDOWN, FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC = 5, 10, 5, 60
75
+ DAILY_QUOTA, DAILY_QUOTA_ADMIN = 100, 100000
76
+ LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX = 300, 10, 10000
77
+ ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL = 3600, 180
78
+ BROADCAST_DELAY, BROADCAST_MAX_LEN = 0.05, 3800
79
+ PHONE_REGEX = re.compile(r"^\d{10}$")
80
+ SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32]
81
+
82
+ TRUNC = {"name": 80, "fathersName": 80, "address": 200, "phoneNumber": 40, "aadharNumber": 40, "otherNumber": 40, "district": 40, "pincode": 15, "state": 40, "town": 40, "source": 30}
83
+ FIELD_LABELS = [("name", "👤", "Name"), ("fathersName", "👨", "Father"), ("phoneNumber", "📞", "Phone"), ("otherNumber", "📱", "Other"), ("aadharNumber", "🆔", "Aadhaar"), ("address", "🏠", "Address"), ("district", "🏙️", "District"), ("pincode", "📮", "Pincode"), ("state", "🗺️", "State"), ("town", "🌆", "Town"), ("source", "📂", "Source")]
84
+ SOURCE_LABEL = {"hiteck": "HiTeck", "flipkart": "Flipkart", "850cr": "850CR Fast", "inddata": "IndData 1.4B", "asur_num": "ASUR NumInfo", "asur_aadhaar": "ASUR AadhaarLink"}
85
+
86
+ # ══ ENGINE ══
87
+ def esc(x): return html.escape(str(x), quote=False) if x is not None else ""
88
+ def _tv(v, n):
89
+ if v is None: return ""
90
+ s = str(v).strip()
91
+ if s.lower() in ("", "null", "none", "nan", "n/a", "na"): return ""
92
+ return s if len(s) <= n else s[:n-1] + "…"
93
+
94
+ _con, _con_lock, _query_lock = None, threading.Lock(), threading.Lock()
95
+ con_ready, warmed, _warm_started = threading.Event(), threading.Event(), False
96
+
97
+ def get_con():
98
+ global _con
99
+ with _con_lock:
100
+ if _con: return _con
101
+ c = duckdb.connect(":memory:")
102
+ c.execute("INSTALL httpfs; LOAD httpfs;")
103
+ if HF_TOKEN:
104
+ try: c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');")
105
+ except: pass
106
+ c.execute("SET enable_object_cache=true; SET preserve_insertion_order=false; SET threads=6; SET memory_limit='12GB';")
107
+ _con = c; con_ready.set(); return _con
108
+
109
+ def run_search_safe(phone, limit=FETCH_LIMIT, timeout_secs=QUERY_TIMEOUT):
110
+ con = get_con()
111
+ with _query_lock:
112
+ stop = threading.Event()
113
+ def watchdog():
114
+ if not stop.wait(timeout_secs):
115
+ try: con.interrupt()
116
+ except: pass
117
+ threading.Thread(target=watchdog, daemon=True).start()
118
+ results = []
119
+ try:
120
+ urls = ", ".join(f"'{u}'" for u in HITECK_URLS)
121
+ 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 {limit}"
122
+ cur = con.execute(sql, [phone])
123
+ cols = [d[0] for d in cur.description]
124
+ for r in cur.fetchall():
125
+ rec = dict(zip(cols, r))
126
+ if not rec.get("source"): rec["source"] = SOURCE_LABEL["hiteck"]
127
+ results.append(rec)
128
+ fk_urls = ", ".join(f"'{u}'" for u in FLIPKART_URLS)
129
+ fk_sql = f"SELECT CustomerName AS name, NULL AS fathersName, CustomerPhone AS phoneNumber, NULL AS aadharNumber, NULL AS otherNumber, CustomerAddress AS address, CustomerCity AS district, CustomerPincode AS pincode, CustomerState AS state, CustomerCity AS town, '{SOURCE_LABEL['flipkart']}' AS source FROM read_parquet([{fk_urls}], union_by_name=true) WHERE RIGHT(REPLACE(REPLACE(REPLACE(CAST(CustomerPhone AS VARCHAR),' ', ''), '-', ''), '+', ''), 10) = ? LIMIT {limit}"
130
+ cur = con.execute(fk_sql, [phone])
131
+ cols = [d[0] for d in cur.description]
132
+ for r in cur.fetchall():
133
+ rec = dict(zip(cols, r))
134
+ for k in ("name", "address", "district", "state", "town"):
135
+ if isinstance(rec.get(k), str) and "%" in rec[k]:
136
+ try: rec[k] = urllib.parse.unquote(rec[k])
137
+ except: pass
138
+ results.append(rec)
139
+ return results
140
+ finally: stop.set()
141
+
142
+ def warm_phone_cache():
143
+ global _warm_started
144
+ if warmed.is_set(): return
145
+ _warm_started = True
146
+ try:
147
+ con = get_con()
148
+ for url in ALL_PARQUET_URLS:
149
+ try: con.execute(f"SELECT * FROM read_parquet('{url}') LIMIT 1").fetchall()
150
+ except: pass
151
+ warmed.set()
152
+ except: _warm_started = False
153
+
154
+ def _is_valid_api_response(name, resp):
155
+ if not isinstance(resp, dict) or resp.get("error"): return False
156
+ if name == "850cr": return resp.get("success") is True and len(resp.get("results", [])) > 0
157
+ if name == "inddata": return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
158
+ if name == "num_to_info": return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
159
+ if name == "aadhaar_to_info": return resp.get("status") == "success" and len(resp.get("data", [])) > 0
160
+ if name == "aadhaar_family": return resp.get("status") is True and len(resp.get("members", [])) > 0
161
+ if name == "aadhaar_ration": return resp.get("status") is True and any(resp.get(k) for k in ("head_family", "ration_number", "scheme", "address", "fps_id"))
162
+ return False
163
+
164
+ def _record_has_content(rec): return any(str(rec.get(k, "")).strip().lower() not in ("", "null", "none") for k in ["name", "fathersName", "phoneNumber", "aadharNumber", "address"])
165
+ def _drop_empty_records(records): return [r for r in records if _record_has_content(r)]
166
+
167
+ async def _q_cr850_raw(client, number):
168
+ try: return (await client.get(f"{API_850CR}/{number}", timeout=40)).json()
169
+ except: return None
170
+ async def _q_inddata_raw(client, number):
171
+ try: return (await client.get(API_INDDATA, params={"mobile": number}, timeout=30)).json()
172
+ except: return None
173
+
174
+ async def search_fast_apis_filtered(phone):
175
+ t0 = time.time()
176
+ raw_850cr, raw_inddata = None, None
177
+ async with httpx.AsyncClient(timeout=60) as cli:
178
+ r850, rind = await asyncio.gather(_q_cr850_raw(cli, phone), _q_inddata_raw(cli, phone), return_exceptions=True)
179
+ if isinstance(r850, dict): raw_850cr = r850
180
+ if isinstance(rind, dict): raw_inddata = rind
181
+ records, status, aadhaar = [], {}, None
182
+
183
+ if _is_valid_api_response("850cr", raw_850cr):
184
+ for item in raw_850cr["results"]:
185
+ addr = item.get("address") or {}
186
+ full = addr.get("full_address", "").lstrip(", ").strip() if isinstance(addr, dict) else ""
187
+ records.append({"name": item.get("name"), "fathersName": item.get("father_name"), "phoneNumber": phone, "otherNumber": item.get("alternate_number"), "address": full, "state": item.get("state"), "source": SOURCE_LABEL["850cr"]})
188
+ status["850cr"] = "ok"
189
+ else: status["850cr"] = "empty" if raw_850cr is None else "error"
190
+
191
+ if _is_valid_api_response("inddata", raw_inddata):
192
+ d = raw_inddata["data"]
193
+ # EXTRACT AADHAAR FROM INDDATA API
194
+ aadhaar = str(d.get("id") or d.get("aadhar") or d.get("aadhaar") or "").strip()
195
+ if len(aadhaar) != 12: aadhaar = None
196
+
197
+ records.append({"name": d.get("name"), "fathersName": d.get("fname"), "phoneNumber": phone, "aadharNumber": aadhaar, "otherNumber": d.get("alt"), "address": d.get("address"), "town": d.get("circle"), "source": SOURCE_LABEL["inddata"]})
198
+ status["inddata"] = "ok"
199
+ else: status["inddata"] = "empty" if raw_inddata is None else "error"
200
+
201
+ return {"records": _drop_empty_records(records), "source_status": status, "raw": {"850cr": raw_850cr, "inddata": raw_inddata}, "aadhaar": aadhaar, "elapsed": time.time() - t0}
202
+
203
+ async def fetch_asurpapa_all(mobile, aadhaar):
204
+ results = {}
205
+ async with httpx.AsyncClient(timeout=30) as cli:
206
+ try: results["num_to_info"] = (await cli.get(ASUR_API["num_to_info"], params={"key": ASUR_KEY, "number": mobile})).json()
207
+ except Exception as e: results["num_to_info"] = {"error": str(e)}
208
+ if not aadhaar:
209
+ for k in ("aadhaar_to_info", "aadhaar_family", "aadhaar_ration"): results[k] = {"error": "skipped"}
210
+ return results
211
+ async def _call(name):
212
+ try: return name, (await cli.get(ASUR_API[name], params={"key": ASUR_KEY, ASUR_PARAM_NAMES[name]: aadhaar})).json()
213
+ except Exception as e: return name, {"error": str(e)}
214
+ gathered = await asyncio.gather(_call("aadhaar_to_info"), _call("aadhaar_family"), _call("aadhaar_ration"))
215
+ for name, res in gathered: results[name] = res
216
+ return results
217
+
218
+ def _format_asur_extras(aadhaar, api_results):
219
+ lines = []
220
+ if aadhaar: lines.append(f"🆔 <b>Aadhaar:</b> <code>XXXX-XXXX-{esc(aadhaar[-4:])}</code>")
221
+ nti = api_results.get("num_to_info")
222
+ if _is_valid_api_response("num_to_info", nti):
223
+ d = nti["data"]; ex = []
224
+ if d.get("email"): ex.append(f"📧 {esc(d['email'])}")
225
+ if d.get("alt"): ex.append(f"📱 Alt: {esc(d['alt'])}")
226
+ if d.get("circle"): ex.append(f"🌐 {esc(d['circle'])}")
227
+ if ex: lines.append(" · ".join(ex))
228
+ fam = api_results.get("aadhaar_family")
229
+ if _is_valid_api_response("aadhaar_family", fam):
230
+ members = fam.get("members", [])
231
+ lines.append(f"👨‍👩‍👧 <b>Family ({len(members)}):</b>")
232
+ for m in members[:5]: lines.append(f" • {esc(m.get('name'))} ({esc(m.get('relation'))})")
233
+ if len(members) > 5: lines.append(f" <i>… and {len(members)-5} more</i>")
234
+ rat = api_results.get("aadhaar_ration")
235
+ if _is_valid_api_response("aadhaar_ration", rat):
236
+ bits = []
237
+ if rat.get("head_family"): bits.append(f"👤 {esc(rat['head_family'])}")
238
+ if rat.get("ration_number"): bits.append(f"🔢 <code>{esc(rat['ration_number'])}</code>")
239
+ if rat.get("scheme"): bits.append(f"📋 {esc(rat['scheme'])}")
240
+ if bits: lines.append("🍚 <b>Ration:</b> " + " · ".join(bits))
241
+ return ("🪪 <b>ASURPAPA Details</b>\n" + "\n".join(lines)) if lines else ""
242
+
243
+ async def asur_lookup_filtered(phone, aadhaar):
244
+ t0 = time.time()
245
+ api_results = await fetch_asurpapa_all(phone, aadhaar)
246
+ records, status = [], {}
247
+ if _is_valid_api_response("num_to_info", api_results.get("num_to_info")):
248
+ d = api_results["num_to_info"]["data"]
249
+ records.append({"name": d.get("name"), "fathersName": d.get("fname"), "phoneNumber": phone, "otherNumber": d.get("alt"), "address": d.get("address"), "town": d.get("circle"), "source": SOURCE_LABEL["asur_num"]})
250
+ if _is_valid_api_response("aadhaar_to_info", api_results.get("aadhaar_to_info")):
251
+ for item in api_results["aadhaar_to_info"]["data"]:
252
+ records.append({"name": item.get("name"), "phoneNumber": item.get("phoneNumber"), "source": SOURCE_LABEL["asur_aadhaar"]})
253
+ return {"records": _drop_empty_records(records), "extras": _format_asur_extras(aadhaar, api_results), "api_results": api_results, "elapsed": time.time() - t0}
254
+
255
+ def _norm(s): return re.sub(r"\s+", " ", str(s).strip().lower()) if s else ""
256
+ def dedup_records(records):
257
+ seen, result = {}, []
258
+ for rec in records:
259
+ if not isinstance(rec, dict): continue
260
+ n, f, a = _norm(rec.get("name")), _norm(rec.get("fathersName")), _norm(rec.get("address"))
261
+ an = re.sub(r"[^a-z0-9]+", " ", a).strip()
262
+ key = ("na", n, an) if n and an else ("nf", n, f) if n and f else ("a", an) if an else None
263
+ if not key: result.append(rec); continue
264
+ if key not in seen: seen[key] = len(result); result.append(rec)
265
+ else:
266
+ idx = seen[key]
267
+ if sum(1 for v in rec.values() if v) > sum(1 for v in result[idx].values() if v): result[idx] = rec
268
+ return result
269
+
270
+ def format_result(idx, row):
271
+ lines = [f"<b>━━━ #{idx} ━━━</b>"]
272
+ for key, emoji, label in FIELD_LABELS:
273
+ v = _tv(row.get(key), TRUNC.get(key, 60))
274
+ if v: lines.append(f"{emoji} <b>{label}:</b> <code>{esc(v)}</code>")
275
+ return "\n".join(lines)
276
+
277
+ def render_page(results, page, total_pages, phone, elapsed, note="", extras=""):
278
+ start = page * PAGE_SIZE
279
+ chunk = results[start:start + PAGE_SIZE]
280
+ head = f"📱 <b>Phone:</b> <code>{esc(phone)}</code>\n📄 <b>Page {page+1}/{total_pages}</b> · {len(results)} result(s) · ⏱️ {elapsed:.1f}s"
281
+ if note: head += f"\n⚠️ <i>{esc(note)}</i>"
282
+ parts = [head]
283
+ if extras and page == 0: parts.append(extras)
284
+ parts.append("\n\n".join(format_result(start + i + 1, r) for i, r in enumerate(chunk)) if chunk else "<i>No records to display.</i>")
285
+ return "\n\n".join(parts)
286
+
287
+ def normalize_phone(text):
288
+ digits = "".join(c for c in text.strip() if c.isdigit())
289
+ if len(digits) == 11 and digits.startswith("0"): digits = digits[1:]
290
+ if len(digits) == 12 and digits.startswith("91"): digits = digits[2:]
291
+ elif len(digits) == 11 and digits.startswith("91"): digits = digits[1:]
292
+ return (digits, None) if len(digits) == 10 and PHONE_REGEX.match(digits) else (None, f"invalid")
293
+
294
+ # ══ BOT STATE ══
295
+ ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, PHONE_COUNTS, PEAK_CONCURRENT = deque(maxlen=ACTIVITY_LOG_MAX), {}, {}, Counter(), 0
296
+ _activity_lock, _admin_lock, _state_lock = threading.Lock(), threading.Lock(), threading.Lock()
297
+ _admin_sessions, _admin_states = {}, {}
298
+ BANNED_USERS, BAN_REASONS, MAINTENANCE_MODE, MAINTENANCE_REASON = set(), {}, False, ""
299
+ USER_HISTORY, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_LAST = {}, {}, threading.Lock(), {}
300
+ STATS = {"queries": 0, "timeouts": 0, "errors": 0, "backup_sent": 0, "started": time.time()}
301
+ _member_cache, _member_lock, _pending_query, _pending_lock = {}, threading.Lock(), {}, threading.Lock()
302
+ _user_daily, _quota_lock, _user_msg_times, _muted_until, _flood_lock = {}, threading.Lock(), {}, {}, threading.Lock()
303
+ _seen_updates, _seen_updates_lock = {}, threading.Lock()
304
+
305
+ # ══ TELEGRAM HELPERS ══
306
+ async def tg(method, payload, timeout=30):
307
+ try:
308
+ async with httpx.AsyncClient(timeout=timeout) as cli:
309
+ return (await cli.post(f"{TELEGRAM_API}/{method}", json=payload)).json()
310
+ except Exception as e: return {"ok": False, "error": str(e)}
311
+ async def send(chat_id, text, **kw):
312
+ kw.setdefault("parse_mode", "HTML"); kw.setdefault("disable_web_page_preview", True)
313
+ res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **{k: v for k, v in kw.items() if v is not None}})
314
+ return res["result"]["message_id"] if res.get("ok") else None
315
+ async def edit(chat_id, msg_id, text, **kw):
316
+ kw.setdefault("parse_mode", "HTML"); kw.setdefault("disable_web_page_preview", True)
317
+ await tg("editMessageText", {"chat_id": chat_id, "message_id": msg_id, "text": text, **{k: v for k, v in kw.items() if v is not None}})
318
+ async def send_document(chat_id, filename, content, caption=""):
319
+ try:
320
+ async with httpx.AsyncClient(timeout=60) as cli:
321
+ return (await cli.post(f"{TELEGRAM_API}/sendDocument", data={"chat_id": str(chat_id), "caption": caption[:1024]}, files={"document": (filename, content, "application/octet-stream")})).json()
322
+ except: return {"ok": False}
323
+
324
+ # ══ BOT LOGIC ══
325
+ def _short_user(uid, user=None):
326
+ u = (user or {}).get("username") or UNIQUE_USERS.get(uid, {}).get("username")
327
+ f = (user or {}).get("first_name") or UNIQUE_USERS.get(uid, {}).get("first_name")
328
+ return f"@{u}" if u else f if f else f"({uid})"
329
+ def _fmt_ts(ts): return time.strftime("%H:%M:%S", time.localtime(ts))
330
+ def _today_utc(): return time.strftime("%Y-%m-%d", time.gmtime())
331
+
332
+ def is_duplicate_update(update_id):
333
+ if not update_id: return False
334
+ with _seen_updates_lock:
335
+ if len(_seen_updates) > 2000:
336
+ for k in [k for k, v in _seen_updates.items() if v < time.time() - 600]: del _seen_updates[k]
337
+ if update_id in _seen_updates: return True
338
+ _seen_updates[update_id] = time.time(); return False
339
+
340
+ async def _is_channel_member(uid):
341
+ if not FORCE_JOIN_CHANNEL: return True
342
+ with _member_lock:
343
+ c = _member_cache.get(uid)
344
+ if c and time.time() - c[1] < MEMBERSHIP_CACHE_TTL: return c[0]
345
+ is_m = False
346
+ res = await tg("getChatMember", {"chat_id": FORCE_JOIN_CHANNEL, "user_id": uid})
347
+ if res.get("ok"): is_m = res.get("result", {}).get("status") in ("member", "administrator", "creator")
348
+ with _member_lock: _member_cache[uid] = (is_m, time.time())
349
+ return is_m
350
+
351
+ async def check_force_join(chat_id, user, text):
352
+ uid = user.get("id")
353
+ if not FORCE_JOIN_CHANNEL or uid in OWNER_IDS or _is_admin_session(uid) or text.startswith(("/start", "/help", "/myid", "/whoami", "/ping", "/info", "/status")): return True
354
+ if await _is_channel_member(uid): return True
355
+ with _pending_lock: _pending_query[uid] = (text, chat_id, time.time())
356
+ url = FORCE_JOIN_CHANNEL if FORCE_JOIN_CHANNEL.startswith("http") else f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}" if FORCE_JOIN_CHANNEL.startswith("@") else "https://t.me/"
357
+ await send(chat_id, f"🔒 <b>Join required</b>\n\n👉 {esc(url)}\n\nTap <b>✅ I Joined</b> below.", reply_markup={"inline_keyboard": [[{"text": "📢 Join", "url": url}], [{"text": "✅ I Joined", "callback_data": "join:check"}]]})
358
+ return False
359
+
360
+ def _is_unlimited(uid): return uid in OWNER_IDS or _is_admin_session(uid)
361
+ def check_quota(uid):
362
+ if _is_unlimited(uid): return True, DAILY_QUOTA_ADMIN
363
+ today = _today_utc()
364
+ with _quota_lock:
365
+ e = _user_daily.get(uid)
366
+ if not e or e[0] != today: _user_daily[uid] = (today, 0); return True, DAILY_QUOTA
367
+ return (False, 0) if e[1] >= DAILY_QUOTA else (True, DAILY_QUOTA - e[1])
368
+ def incr_quota(uid):
369
+ if _is_unlimited(uid): return
370
+ today = _today_utc()
371
+ with _quota_lock:
372
+ e = _user_daily.get(uid); _user_daily[uid] = (today, 1) if not e or e[0] != today else (today, e[1] + 1)
373
+
374
+ def check_flood(uid):
375
+ now = time.time()
376
+ with _flood_lock:
377
+ if _muted_until.get(uid, 0) > now: return int(_muted_until[uid] - now)
378
+ dq = _user_msg_times.setdefault(uid, deque(maxlen=FLOOD_MAX)); dq.append(now)
379
+ if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW: _muted_until[uid] = now + FLOOD_MUTE_SEC; return FLOOD_MUTE_SEC
380
+ return None
381
+
382
+ def _log_activity(user, action, inp, reply, summary="", ms=0, src=""):
383
+ if not user or "id" not in user: return
384
+ with _activity_lock:
385
+ info = UNIQUE_USERS.setdefault(user["id"], {"username": None, "first_name": None, "count": 0, "first_seen": time.time(), "last_seen": time.time()})
386
+ info.update({"username": user.get("username"), "first_name": user.get("first_name"), "last_seen": time.time()})
387
+ info["count"] += 1; ACTIVE_USERS[user["id"]] = time.time()
388
+ if action == "search" and isinstance(inp, str) and len(inp) == 10: PHONE_COUNTS[inp] += 1
389
+ ACTIVITY_LOG.append({"ts": time.time(), "user_id": user["id"], "username": user.get("username"), "first_name": user.get("first_name"), "action": action, "input": inp[:80], "reply_type": reply, "summary": summary[:150], "elapsed_ms": int(ms), "source": src})
390
+
391
+ def _get_stats():
392
+ with _activity_lock:
393
+ return {"unique_users": len(UNIQUE_USERS), "live_users": sum(1 for ts in ACTIVE_USERS.values() if ts >= time.time() - LIVE_WINDOW), "today_users": len(set(e["user_id"] for e in ACTIVITY_LOG if e["action"] == "search" and e["ts"] >= time.time() - (time.time() % 86400))), "today_searches": sum(1 for e in ACTIVITY_LOG if e["action"] == "search" and e["ts"] >= time.time() - (time.time() % 86400)), "total_searches": sum(1 for e in ACTIVITY_LOG if e["action"] == "search"), "peak_concurrent": PEAK_CONCURRENT, "total_log_entries": len(ACTIVITY_LOG), "banned_count": len(BANNED_USERS), "maintenance": MAINTENANCE_MODE, "cached_searches": len(SEARCH_CACHE), "backup_sent": STATS["backup_sent"]}
394
+
395
+ def _is_banned(uid): return uid in BANNED_USERS
396
+ def _ban_user(uid, reason=""): BANNED_USERS.add(uid); BAN_REASONS[uid] = reason
397
+ def _unban_user(uid): BANNED_USERS.discard(uid); BAN_REASONS.pop(uid, None)
398
+ def _get_maintenance(): return MAINTENANCE_MODE, MAINTENANCE_REASON
399
+ def _set_maintenance(on, reason=""): globals().update({"MAINTENANCE_MODE": on, "MAINTENANCE_REASON": reason if on else ""})
400
+
401
+ def _is_admin_session(uid): return _admin_sessions.get(uid, 0) > time.time()
402
+ def _grant_admin(uid): _admin_sessions[uid] = time.time() + ADMIN_SESSION_TTL
403
+ def _revoke_admin(uid): _admin_sessions.pop(uid, None)
404
+ def _admin_state_get(uid):
405
+ e = _admin_states.get(uid)
406
+ if e and time.time() - e[1] < ADMIN_PROMPT_TTL: return e[0]
407
+ _admin_states.pop(uid, None); return None
408
+ def _admin_state_set(uid, state): _admin_states[uid] = (state, time.time())
409
+ def _admin_state_clear(uid): _admin_states.pop(uid, None)
410
+
411
+ def _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, count):
412
+ return {"meta": {"ts_utc": datetime.now(timezone.utc).isoformat(), "bot_version": VERSION, "telegram_user_id": user.get("id"), "username": user.get("username")}, "input": {"mobile": phone}, "status": status, "elapsed_s": round(elapsed, 2), "aadhaar": fast_data.get("aadhaar"), "api_responses_raw": {**(fast_data.get("raw") or {}), **(asur_data.get("api_results") or {})}, "api_status": fast_data.get("source_status"), "db_results": db_results or [], "records_shown": count}
413
+ async def forward_to_backup(user, phone, status, elapsed, fast_data, asur_data, db_results, count):
414
+ if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED: return
415
+ try:
416
+ payload = _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, count)
417
+ await send(BACKUP_CHANNEL_ID, f"📥 <b>Lookup</b> {phone}\n👤 {user.get('id')} (@{user.get('username')})\n📊 {status} · {count} records · {elapsed:.1f}s")
418
+ await send_document(BACKUP_CHANNEL_ID, f"lookup_{phone}.json", json.dumps(payload, indent=2).encode(), caption=f"Mobile {phone}")
419
+ STATS["backup_sent"] += 1
420
+ except: pass
421
+
422
+ def page_keyboard(sid, page, total, exp=True):
423
+ nav = []
424
+ if page > 0: nav.append({"text": "◀ Prev", "callback_data": f"p:{sid}:{page-1}"})
425
+ nav.append({"text": f"{page+1} / {total}", "callback_data": "noop"})
426
+ if page < total - 1: nav.append({"text": "Next ▶", "callback_data": f"p:{sid}:{page+1}"})
427
+ rows = [nav, [{"text": "📋 Copy", "callback_data": f"c:{sid}:{page}"}] + ([{"text": "📥 Export", "callback_data": f"e:{sid}"}] if exp else [])]
428
+ return {"inline_keyboard": rows}
429
+
430
+ async def _db_search_async(phone, loop):
431
+ if not con_ready.is_set(): return []
432
+ try: return await asyncio.wait_for(loop.run_in_executor(None, run_search_safe, phone), timeout=QUERY_TIMEOUT + 10)
433
+ except: STATS["timeouts"] += 1; return []
434
+
435
+ async def _show_progressive(cid, mid, phone, results, elapsed, note="", extras="", asur_snap=None):
436
+ sid = uuid.uuid4().hex[:10]; tp = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
437
+ SEARCH_CACHE[sid] = {"ts": time.time(), "results": results, "query": phone, "elapsed": elapsed, "source_note": note, "extras_block": extras, "asur_data": asur_snap or {}}
438
+ await edit(cid, mid, render_page(results, 0, tp, phone, elapsed, note, extras), reply_markup=page_keyboard(sid, 0, tp))
439
+ return sid
440
+
441
+ async def _do_progressive_search(phone, cid, mid, user):
442
+ t0 = time.time(); loop = asyncio.get_running_loop()
443
+ db_task = asyncio.create_task(_db_search_async(phone, loop))
444
+ fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
445
+
446
+ fast_data = await fast_task
447
+ fast_records = dedup_records(fast_data["records"])
448
+ aadhaar = fast_data.get("aadhaar")
449
+ search_id, extras = None, ""
450
+ if fast_records: search_id = await _show_progressive(cid, mid, phone, fast_records, fast_data["elapsed"], "⚡ Fast results…")
451
+
452
+ asur_task = asyncio.create_task(asur_lookup_filtered(phone, aadhaar))
453
+ asur_data = await asur_task
454
+ asur_records = dedup_records(asur_data["records"])
455
+ extras = asur_data["extras"]
456
+
457
+ if asur_records or extras:
458
+ comb = dedup_records(fast_records + asur_records)
459
+ snap = {"api_results": asur_data["api_results"]}
460
+ if search_id: SEARCH_CACHE[search_id].update({"results": comb, "extras_block": extras, "asur_data": snap, "elapsed": time.time()-t0, "source_note": "🪪 ASUR added…"}); await edit(cid, mid, render_page(comb, 0, max(1, (len(comb)+PAGE_SIZE-1)//PAGE_SIZE), phone, time.time()-t0, "🪪 ASUR added…", extras), reply_markup=page_keyboard(search_id, 0, max(1, (len(comb)+PAGE_SIZE-1)//PAGE_SIZE)))
461
+ else: search_id = await _show_progressive(cid, mid, phone, comb, time.time()-t0, "🪪 ASUR added…", extras, snap)
462
+
463
+ db_results = await db_task
464
+ comb = dedup_records(fast_records + asur_records + db_results)
465
+ elapsed = time.time() - t0
466
+ tp = max(1, (len(comb) + PAGE_SIZE - 1) // PAGE_SIZE)
467
+
468
+ if not comb and not extras:
469
+ await edit(cid, mid, f"❌ <b>No record found</b>\n📱 {esc(phone)}")
470
+ asyncio.create_task(forward_to_backup(user, phone, "empty", elapsed, fast_data, asur_data, db_results, 0)); return
471
+
472
+ note = f"➕ {len(comb)-len(dedup_records(fast_records+asur_records))} more from DB"
473
+ if search_id:
474
+ SEARCH_CACHE[search_id].update({"results": comb, "elapsed": elapsed, "source_note": note, "ts": time.time()})
475
+ await edit(cid, mid, render_page(comb, 0, tp, phone, elapsed, note, extras), reply_markup=page_keyboard(search_id, 0, tp))
476
+ else: search_id = await _show_progressive(cid, mid, phone, comb, elapsed, note, extras, {"api_results": asur_data["api_results"]})
477
+
478
+ STATS["queries"] += 1
479
+ asyncio.create_task(forward_to_backup(user, phone, "success", elapsed, fast_data, asur_data, db_results, len(comb)))
480
+
481
+ async def _handle_batch(chat_id, user, phones):
482
+ await send(chat_id, f"🔍 Batch {len(phones)} nums…")
483
+ res = await asyncio.gather(*[search_fast_apis_filtered(p) for p in phones], return_exceptions=True)
484
+ lines = [f"📊 <b>Batch Results</b>"] + [f"✅ {p} — {len(r['records'])} recs" if isinstance(r, dict) else f"❌ {p}" for p, r in zip(phones, res)]
485
+ await send(chat_id, "\n".join(lines))
486
+
487
+ async def _run_broadcast(cid, msg):
488
+ with _activity_lock: recips = list(UNIQUE_USERS.keys())
489
+ sent = 0
490
+ for uid in recips:
491
+ if _is_banned(uid): continue
492
+ if (await tg("sendMessage", {"chat_id": uid, "text": f"📢 {msg}", "parse_mode": "HTML"})).get("ok"): sent += 1
493
+ await asyncio.sleep(BROADCAST_DELAY)
494
+ await send(cid, f"✅ Sent: {sent}/{len(recips)}")
495
+
496
+ async def _send_log_export(cid):
497
+ buf = io.StringIO(); w = csv.writer(buf)
498
+ w.writerow(["ts", "uid", "user", "action", "input", "reply", "ms", "src"])
499
+ with _activity_lock:
500
+ for e in ACTIVITY_LOG: w.writerow([time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])), e["user_id"], e.get("username") or "", e["action"], e.get("input"), e.get("reply_type"), e.get("elapsed_ms", 0), e.get("source", "")])
501
+ await send_document(cid, f"logs.csv", buf.getvalue().encode(), f"{len(ACTIVITY_LOG)} entries")
502
+
503
+ # ══ HANDLERS ══
504
+ async def handle_message(msg):
505
+ try:
506
+ cid, user, uid, text = msg["chat"]["id"], msg.get("from") or {}, (msg.get("from") or {}).get("id"), (msg.get("text") or "").strip()
507
+ if not text or uid is None: return
508
+ if _is_banned(uid): await send(cid, "🚫 Banned."); return
509
+
510
+ state = _admin_state_get(uid)
511
+ if state == "await_admin_token" and not _is_admin_session(uid):
512
+ _admin_state_clear(uid)
513
+ if text == ADMIN_TOKEN: _grant_admin(uid); await send(cid, "✅ Admin granted", reply_markup=admin_menu_kb()); await send(cid, render_admin_menu())
514
+ else: await send(cid, "❌ Invalid token.")
515
+ return
516
+ if state and _is_admin_session(uid):
517
+ _admin_state_clear(uid)
518
+ if state == "await_ban_id": parts=text.split(None,1); _ban_user(int(parts[0]), parts[1] if len(parts)>1 else ""); await send(cid, "🚫 Banned.")
519
+ elif state == "await_unban_id": _unban_user(int(text.strip())); await send(cid, "✅ Unbanned.")
520
+ elif state == "await_broadcast": asyncio.create_task(_run_broadcast(cid, text)); await send(cid, "Broadcasting…")
521
+ return
522
+
523
+ m_on, m_r = _get_maintenance()
524
+ if m_on and not _is_admin_session(uid) and not text.startswith(("/start","/help","/status","/info","/myid")):
525
+ await send(cid, f"🛠️ Maintenance: {esc(m_r)}"); return
526
+
527
+ if not await check_force_join(cid, user, text): return
528
+
529
+ if text == "/admin":
530
+ if _is_admin_session(uid): await send(cid, render_admin_menu(), reply_markup=admin_menu_kb())
531
+ else: _admin_state_set(uid, "await_admin_token"); await send(cid, "🔐 Token:")
532
+ return
533
+ if text == "/logout": _revoke_admin(uid); await send(cid, "Logged out."); return
534
+
535
+ if text.startswith("/") and _is_admin_session(uid):
536
+ await _handle_admin_command(cid, user, text, uid); return
537
+
538
+ if text == "/status":
539
+ s = _get_stats()
540
+ await send(cid, f"📊 Users: {s['unique_users']} · Searches: {s['total_searches']}\nAPI: 850CR + IndData + ASUR\nDB: {con_ready.is_set()}")
541
+ return
542
+ if text == "/info": await send(cid, f"ℹ️ Bot v{VERSION}. Send mobile number to search."); return
543
+ if text == "/history":
544
+ h = USER_HISTORY.get(uid, [])
545
+ if not h: await send(cid, "No history.")
546
+ else: await send(cid, "🕘 Recent:", reply_markup={"inline_keyboard": [[{"text": x["phone"], "callback_data": f"h:{x['phone']}"}] for x in h]})
547
+ return
548
+ if text == "/myid": await send(cid, f"🆔 {uid}"); return
549
+ if text in ("/start", "/help"):
550
+ await send(cid, WELCOME_TEMPLATE.format(v=VERSION))
551
+ if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start()
552
+ return
553
+
554
+ if "," in text:
555
+ parts = [p.strip() for p in text.split(",") if p.strip()]
556
+ phones = [normalize_phone(p)[0] for p in parts]
557
+ if all(phones): await _handle_batch(cid, user, phones); return
558
+ await send(cid, "❌ Batch format: 9876543210,9876543211"); return
559
+
560
+ phone, err = normalize_phone(text)
561
+ if not phone: await send(cid, "❌ Send a 10-digit number."); return
562
+
563
+ mute = check_flood(uid)
564
+ if mute: await send(cid, f"⏳ Wait {mute}s."); return
565
+
566
+ now = time.time()
567
+ if now - USER_LAST.get(uid, 0) < USER_COOLDOWN: await send(cid, f"⏳ Wait {int(USER_COOLDOWN-(now-USER_LAST.get(uid,0)))}s."); return
568
+ USER_LAST[uid] = now
569
+
570
+ ok, rem = check_quota(uid)
571
+ if not ok: await send(cid, f"❌ Quota {DAILY_QUOTA} reached."); return
572
+ incr_quota(uid)
573
+
574
+ if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start()
575
+
576
+ mid = await send(cid, f"🔍 Searching <code>{phone}</code>…")
577
+ if mid: await _do_progressive_search(phone, cid, mid, user)
578
+ except Exception as e: log.error(f"handle_message: {e!r}")
579
+
580
+ async def handle_callback(cb):
581
+ try:
582
+ data, cb_id, msg, user = cb.get("data", ""), cb["id"], cb.get("message") or {}, cb.get("from") or {}
583
+ cid, mid, uid = msg.get("chat", {}).get("id"), msg.get("message_id"), user.get("id")
584
+ if not cid or not mid: return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
585
+
586
+ if data == "join:check":
587
+ with _member_lock: _member_cache.pop(uid, None)
588
+ if not await _is_channel_member(uid): return await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Not joined", "show_alert": True})
589
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "✅ Verified!"})
590
+ try: await tg("deleteMessage", {"chat_id": cid, "message_id": mid})
591
+ except: pass
592
+ with _pending_lock: pending = _pending_query.pop(uid, None)
593
+ if pending and time.time() - pending[2] < PENDING_QUERY_TTL: await handle_message({"chat": {"id": cid}, "from": user, "text": pending[0]})
594
+ else: await send(cid, "✅ Thanks! Send a number.")
595
+ return
596
+
597
+ if data.startswith("adm:") and _is_admin_session(uid):
598
+ action = data.split(":")[1]
599
+ if action == "menu": await edit(cid, mid, render_admin_menu(), reply_markup=admin_menu_kb())
600
+ elif action == "live": await edit(cid, mid, render_live(), reply_markup=admin_menu_kb())
601
+ elif action == "stats": await edit(cid, mid, render_stats(), reply_markup=admin_menu_kb())
602
+ elif action == "log": await edit(cid, mid, *render_log(list(reversed(ACTIVITY_LOG)), int(data.split(":")[2]) if len(data.split(":"))>2 else 0))
603
+ elif action == "ban": _admin_state_set(uid, "await_ban_id"); await edit(cid, mid, "Send ID to ban:")
604
+ elif action == "unban": _admin_state_set(uid, "await_unban_id"); await edit(cid, mid, "Send ID to unban:")
605
+ elif action == "broadcast": _admin_state_set(uid, "await_broadcast"); await edit(cid, mid, "Send message:")
606
+ elif action == "export": await _send_log_export(cid)
607
+ return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
608
+
609
+ if data.startswith("h:"):
610
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Searching…"})
611
+ return await handle_message({"chat": {"id": cid}, "from": user, "text": data.split(":")[1]})
612
+
613
+ if data.startswith("e:") and (sid := data.split(":")[1]) in SEARCH_CACHE:
614
+ ent = SEARCH_CACHE[sid]
615
+ await send_document(cid, f"results_{ent['query']}.json", json.dumps(ent, indent=2, default=str).encode(), f"{len(ent['results'])} recs")
616
+ return await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Sent"})
617
+
618
+ if data.startswith("p:") and (parts := data.split(":"))[1] in SEARCH_CACHE:
619
+ ent = SEARCH_CACHE[parts[1]]; pg = int(parts[2]); tp = max(1, (len(ent["results"])+PAGE_SIZE-1)//PAGE_SIZE)
620
+ await edit(cid, mid, render_page(ent["results"], pg, tp, ent["query"], ent["elapsed"], ent.get("source_note",""), ent.get("extras_block","")), reply_markup=page_keyboard(parts[1], pg, tp))
621
+ return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
622
+
623
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
624
+ except: pass
625
+
626
+ # ══ ADMIN ══
627
+ def admin_menu_kb(): return {"inline_keyboard": [[{"text": "📊 Stats", "callback_data": "adm:stats"}, {"text": "📜 Logs", "callback_data": "adm:log:0"}], [{"text": "🚫 Ban", "callback_data": "adm:ban"}, {"text": "✅ Unban", "callback_data": "adm:unban"}], [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"}, {"text": "📥 Export", "callback_data": "adm:export"}], [{"text": "🔄 Menu", "callback_data": "adm:menu"}]]}
628
+ def render_admin_menu(): return f"🛡️ Admin v{VERSION}\nUsers: {len(UNIQUE_USERS)}\nBanned: {len(BANNED_USERS)}"
629
+ def render_stats(): return f"📈 Stats\nUsers: {len(UNIQUE_USERS)}\nSearches: {STATS['queries']}"
630
+ def render_log(entries, page=0, size=8):
631
+ tp = max(1, (len(entries)+size-1)//size); page = max(0, min(page, tp-1))
632
+ return "\n".join([f"{_fmt_ts(e['ts'])} {e['action']} {e.get('input','')}" for e in entries[page*size:(page+1)*size]]), {"inline_keyboard": [[{"text": "◀", "callback_data": f"adm:log:{page-1}"}, {"text": f"{page+1}/{tp}", "callback_data": "noop"}, {"text": "▶", "callback_data": f"adm:log:{page+1}"}]]}
633
+
634
+ async def _handle_admin_command(cid, user, text, uid):
635
+ cmd, args = text.split()[0].lower(), text.split()[1:]
636
+ if cmd == "/stats": await send(cid, render_stats())
637
+ elif cmd == "/ban" and args: _ban_user(int(args[0]), " ".join(args[1:])); await send(cid, "Banned.")
638
+ elif cmd == "/unban" and args: _unban_user(int(args[0])); await send(cid, "Unbanned.")
639
+ elif cmd == "/broadcast" and args: asyncio.create_task(_run_broadcast(cid, " ".join(args))); await send(cid, "Broadcasting…")
640
+ elif cmd == "/export": await _send_log_export(cid)
641
+ elif cmd == "/maintenance" and args: _set_maintenance(args[0]=="on", " ".join(args[1:])); await send(cid, f"Maintenance {args[0]}")
642
+ else: await send(cid, render_admin_menu(), reply_markup=admin_menu_kb())
643
+
644
+ # ══ WEB ENDPOINTS ══
645
+ async def admin_index(req: Request):
646
+ for p in ("admin.html", "/app/admin.html"):
647
+ if os.path.exists(p): return Response(open(p, "rb").read(), media_type="text/html")
648
+ return HTMLResponse("<h1>admin.html not found</h1>", status_code=404)
649
+ async def admin_login(req: Request):
650
+ if (await req.json()).get("token") == ADMIN_TOKEN:
651
+ resp = JSONResponse({"ok": True})
652
+ resp.set_cookie("admin_session", "1", max_age=3600, httponly=True, path="/admin")
653
+ return resp
654
+ return JSONResponse({"error": "invalid"}, status_code=401)
655
+ async def api_stats(req): return JSONResponse(_get_stats())
656
+ async def api_logs(req): return JSONResponse({"entries": list(reversed(list(ACTIVITY_LOG)))[:100]})
657
+ async def api_ban(req): d=await req.json(); _ban_user(d["user_id"], d.get("reason","")); return JSONResponse({"ok":True})
658
+ async def api_unban(req): _unban_user((await req.json())["user_id"]); return JSONResponse({"ok":True})
659
+
660
+ async def webhook_handler(request: Request):
661
+ if SECRET_TOKEN and request.headers.get("x-telegram-bot-api-secret-token") != SECRET_TOKEN: return JSONResponse({"ok": False}, status_code=403)
662
+ try: update = await request.json()
663
+ except: return JSONResponse({"ok": True})
664
+ if "message" in update and not is_duplicate_update(update.get("update_id")): asyncio.create_task(handle_message(update["message"]))
665
+ elif "callback_query" in update: asyncio.create_task(handle_callback(update["callback_query"]))
666
+ return JSONResponse({"ok": True})
667
+
668
+ async def health_handler(req):
669
+ return JSONResponse({"status": "ok", "version": VERSION, "con_ready": con_ready.is_set(), "warmed": warmed.is_set()})
670
+
671
+ # ══ BOOT ══
672
+ def _boot():
673
+ demo = gr.Blocks(title="Bot")
674
+ with demo:
675
+ gr.Markdown(f"# {BOT_NAME} v{VERSION}")
676
+ gr.JSON(label="Status", value={"ready": con_ready.is_set()})
677
+ if _HAS_SPACES:
678
+ @spaces.GPU(duration=10)
679
+ def dummy(): return "ok"
680
+ gr.Button("init", visible=False).click(fn=dummy, inputs=None, outputs=None)
681
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False, prevent_thread_lock=True)
682
+
683
+ app = demo.app
684
+ app.router.routes.insert(0, StarletteRoute("/webhook", webhook_handler, methods=["POST"]))
685
+ app.router.routes.insert(0, StarletteRoute("/health", health_handler, methods=["GET"]))
686
+
687
+ if ADMIN_TOKEN:
688
+ app.router.routes.insert(0, StarletteRoute("/admin", admin_index, methods=["GET"]))
689
+ app.router.routes.insert(0, StarletteRoute("/admin/login", admin_login, methods=["POST"]))
690
+ app.router.routes.insert(0, StarletteRoute("/admin/api/stats", api_stats, methods=["GET"]))
691
+ app.router.routes.insert(0, StarletteRoute("/admin/api/logs", api_logs, methods=["GET"]))
692
+ app.router.routes.insert(0, StarletteRoute("/admin/api/ban", api_ban, methods=["POST"]))
693
+ app.router.routes.insert(0, StarletteRoute("/admin/api/unban", api_unban, methods=["POST"]))
694
+
695
+ app.build_middleware_stack()
696
+
697
+ threading.Thread(target=warm_phone_cache, daemon=True).start()
698
+ threading.Thread(target=cache_gc, daemon=True).start()
699
+ threading.Thread(target=_set_webhook, daemon=True).start()
700
+
701
+ log.info("✅ Bot Ready")
702
+ return demo
703
+
704
+ def cache_gc():
705
+ while True:
706
+ time.sleep(60); now = time.time()
707
+ for k in [k for k, v in SEARCH_CACHE.items() if now - v.get("ts", 0) > SEARCH_CACHE_TTL]: SEARCH_CACHE.pop(k, None)
708
+ for k in [k for k, v in _seen_updates.items() if v < now - 600]: _seen_updates.pop(k, None)
709
+
710
+ def _set_webhook():
711
+ if not BOT_TOKEN or not (SPACE_URL or SPACE_HOST): return
712
+ url = f"{(SPACE_URL or 'https://'+SPACE_HOST).rstrip('/')}/webhook"
713
+ with httpx.Client() as cli:
714
+ r = cli.post(f"{TELEGRAM_API}/setWebhook", json={"url": url, "secret_token": SECRET_TOKEN, "allowed_updates": ["message", "callback_query"], "drop_pending_updates": True})
715
+ log.info(f"Webhook: {r.json()}")
716
+
717
+ WELCOME_TEMPLATE = "👋 <b>Phone Lookup Bot</b> v{v}\n\nSend me any <b>10-digit mobile number</b>."
718
+
719
+ if __name__ == "__main__":
720
+ try:
721
+ demo = _boot()
722
+ demo.block_thread()
723
+ except Exception as e:
724
+ log.critical(f"Boot failed: {e}")