Hfzune commited on
Commit
c2cb427
·
verified ·
1 Parent(s): fba1d6c

Create app.py

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