Hfzune commited on
Commit
bf73b60
Β·
verified Β·
1 Parent(s): dfabb56

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +852 -0
app.py ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────────
2
+ # 0. HfFolder shim (must be first executable code)
3
+ # ─────────────────────────────────────────────────────────────
4
+ import huggingface_hub
5
+ if not hasattr(huggingface_hub, "HfFolder"):
6
+ class _HfFolder:
7
+ @staticmethod
8
+ def get_token(): return huggingface_hub.get_token()
9
+ @staticmethod
10
+ def save_token(token): huggingface_hub.login(token)
11
+ @staticmethod
12
+ def delete_token(): huggingface_hub.logout()
13
+ huggingface_hub.HfFolder = _HfFolder
14
+
15
+ # ─────────────────────────────────────────────────────────────
16
+ # 1. Imports
17
+ # ─────────────────────────────────────────────────────────────
18
+ import os
19
+ import re
20
+ import time
21
+ import html
22
+ import json
23
+ import asyncio
24
+ import logging
25
+ import threading
26
+ from typing import Optional
27
+
28
+ import httpx
29
+ from fastapi import Request
30
+ from fastapi.responses import JSONResponse
31
+ from starlette.routing import Route as StarletteRoute
32
+ import gradio as gr
33
+ import spaces
34
+
35
+ # ─────────────────────────────────────────────────────────────
36
+ # 2. Config
37
+ # ─────────────────────────────────────────────────────────────
38
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
39
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "1221")
40
+ SPACE_URL = os.environ["SPACE_URL"].rstrip("/")
41
+ TELEGRAM_PROXY = os.environ.get("TELEGRAM_PROXY", "").rstrip("/")
42
+
43
+ ADMIN_IDS = [int(x) for x in os.environ.get("ADMIN_IDS", "").split(",") if x.strip().isdigit()]
44
+ AUTH_ENABLED = len(ADMIN_IDS) > 0
45
+
46
+ TG_API = (TELEGRAM_PROXY + "/bot" + BOT_TOKEN) if TELEGRAM_PROXY \
47
+ else f"https://api.telegram.org/bot{BOT_TOKEN}"
48
+
49
+ RATE_LIMIT_SEC = 5
50
+ PAGE_SIZE = 4
51
+ QUERY_TIMEOUT = 90 # outer cap for whole search
52
+ HTTP_TIMEOUT = httpx.Timeout(60.0, connect=15.0)
53
+ CACHE_TTL = 300 # 5 minutes
54
+ ADMIN_STATE_TTL = 180 # admin input states expire after 3 min
55
+ TELEGRAM_MAX_MSG = 4000 # 4096 limit, leave headroom
56
+
57
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
58
+ log = logging.getLogger("bot")
59
+
60
+ # ─────────────────────────────────────────────────────────────
61
+ # 3. HTTP clients (one AsyncClient per running event loop)
62
+ # ─────────────────────────────────────────────────────────────
63
+ _api_clients: dict[int, httpx.AsyncClient] = {}
64
+ _clients_lock = threading.Lock()
65
+
66
+
67
+ async def _get_api_client() -> httpx.AsyncClient:
68
+ loop = asyncio.get_running_loop()
69
+ key = id(loop)
70
+ client = _api_clients.get(key)
71
+ if client is None or client.is_closed:
72
+ client = httpx.AsyncClient(timeout=HTTP_TIMEOUT, follow_redirects=True)
73
+ with _clients_lock:
74
+ _api_clients[key] = client
75
+ return client
76
+
77
+
78
+ # ─────────────────────────────────────────────────────────────
79
+ # 4. Result cache (per phone number, 5-min TTL)
80
+ # ─────────────────────────────────────────────────────────────
81
+ _cache: dict[str, tuple[float, list]] = {}
82
+ _cache_lock = threading.Lock()
83
+
84
+
85
+ def _cache_get(number: str) -> Optional[list]:
86
+ with _cache_lock:
87
+ entry = _cache.get(number)
88
+ if entry is None:
89
+ return None
90
+ ts, data = entry
91
+ if time.time() - ts > CACHE_TTL:
92
+ _cache.pop(number, None)
93
+ return None
94
+ return data
95
+
96
+
97
+ def _cache_set(number: str, data: list):
98
+ with _cache_lock:
99
+ _cache[number] = (time.time(), data)
100
+ # opportunistic cleanup
101
+ if len(_cache) > 500:
102
+ now = time.time()
103
+ for k in list(_cache.keys()):
104
+ if now - _cache[k][0] > CACHE_TTL:
105
+ _cache.pop(k, None)
106
+
107
+
108
+ # ─────────────────────────────────────────────────────────────
109
+ # 5. External data sources
110
+ # ─────────────────────────────────────────────────────────────
111
+ def _clean(v):
112
+ if v is None:
113
+ return None
114
+ s = str(v).strip()
115
+ if s in ("", "null", "N/A", "None", "-"):
116
+ return None
117
+ return s
118
+
119
+
120
+ async def _q_cr850(client, number):
121
+ url = f"https://sauravsingh2111-850crfastsearch.hf.space/search/{number}"
122
+ try:
123
+ r = await client.get(url, timeout=40.0)
124
+ if r.status_code != 200:
125
+ return []
126
+ data = r.json()
127
+ if not data.get("success") or not data.get("results"):
128
+ return []
129
+ out = []
130
+ for item in data["results"]:
131
+ addr = item.get("address") or {}
132
+ full = None
133
+ if isinstance(addr, dict):
134
+ full = addr.get("full_address")
135
+ if full:
136
+ full = full.lstrip(", ").strip()
137
+ out.append({
138
+ "source": "850CR Fast",
139
+ "fields": {
140
+ "Name": _clean(item.get("name")),
141
+ "Father": _clean(item.get("father_name")),
142
+ "Address": _clean(full),
143
+ "Alternate": _clean(item.get("alternate_number")),
144
+ "Circle": _clean(item.get("circle")),
145
+ "Operator": _clean(item.get("operator")),
146
+ "State": _clean(item.get("state")),
147
+ "Email": _clean(item.get("email")),
148
+ },
149
+ })
150
+ return out
151
+ except Exception as e:
152
+ log.warning("cr850 failed: %s", e)
153
+ return []
154
+
155
+
156
+ async def _q_inddata(client, number):
157
+ url = "https://tfqdeadlo-inddataapi.hf.space/search"
158
+ try:
159
+ r = await client.get(url, params={"mobile": number}, timeout=30.0)
160
+ if r.status_code != 200:
161
+ return []
162
+ data = r.json()
163
+ rows = data.get("data") if isinstance(data, dict) else None
164
+ if not isinstance(rows, list):
165
+ return []
166
+ out = []
167
+ for item in rows:
168
+ out.append({
169
+ "source": "IndData 1.4B",
170
+ "fields": {
171
+ "Mobile": _clean(item.get("mobile")),
172
+ "Name": _clean(item.get("name")),
173
+ "Father": _clean(item.get("fname")),
174
+ "Address": _clean(item.get("address")),
175
+ "Email": _clean(item.get("email")),
176
+ "ID": _clean(item.get("id")),
177
+ },
178
+ })
179
+ return out
180
+ except Exception as e:
181
+ log.warning("inddata failed: %s", e)
182
+ return []
183
+
184
+
185
+ async def _q_hiteck_main(client, number):
186
+ url = "https://hiteckgroup-hiteckgroup.hf.space/search"
187
+ try:
188
+ r = await client.get(url, params={"mobile": number}, timeout=30.0)
189
+ if r.status_code != 200:
190
+ return []
191
+ data = r.json()
192
+ rows = data.get("data") if isinstance(data, dict) else None
193
+ if not isinstance(rows, list):
194
+ return []
195
+ out = []
196
+ for item in rows:
197
+ addr = item.get("address")
198
+ if addr:
199
+ addr = addr.replace("!", ", ")
200
+ out.append({
201
+ "source": "HiTeck 1.78B",
202
+ "fields": {
203
+ "Mobile": _clean(item.get("mobile")),
204
+ "Name": _clean(item.get("name")),
205
+ "Father": _clean(item.get("fname")),
206
+ "Address": _clean(addr),
207
+ "Alternate": _clean(item.get("alt")),
208
+ "Circle": _clean(item.get("circle")),
209
+ "Email": _clean(item.get("email")),
210
+ },
211
+ })
212
+ return out
213
+ except Exception as e:
214
+ log.warning("hiteck_main failed: %s", e)
215
+ return []
216
+
217
+
218
+ async def _q_hiteck_big(client, number):
219
+ url = "https://hiteckgroup-hiteckgroupp.hf.space/search"
220
+ try:
221
+ r = await client.get(url, params={"q": number}, timeout=35.0)
222
+ if r.status_code != 200:
223
+ return []
224
+ data = r.json()
225
+ rows = data.get("results") if isinstance(data, dict) else None
226
+ if not isinstance(rows, list):
227
+ return []
228
+ out = []
229
+ for item in rows:
230
+ out.append({
231
+ "source": "HiTeck 5B",
232
+ "fields": {
233
+ "Name": _clean(item.get("name")),
234
+ "Father": _clean(item.get("fathersName")),
235
+ "Phone": _clean(item.get("phoneNumber")),
236
+ "Aadhaar": _clean(item.get("aadharNumber")),
237
+ "Other": _clean(item.get("otherNumber")),
238
+ "Address": _clean(item.get("address")),
239
+ "District": _clean(item.get("district")),
240
+ "State": _clean(item.get("state")),
241
+ "Town": _clean(item.get("town")),
242
+ "Pincode": _clean(item.get("pincode")),
243
+ "Source": _clean(item.get("source")),
244
+ },
245
+ })
246
+ return out
247
+ except Exception as e:
248
+ log.warning("hiteck_big failed: %s", e)
249
+ return []
250
+
251
+
252
+ # ─────────────────────────────────────────────────────────────
253
+ # 5b. Per-API safety wrapper
254
+ # ─────────────────────────────────────────────────────────────
255
+ async def _safe(fn, client, number, timeout: float, label: str) -> list[dict]:
256
+ t0 = time.time()
257
+ try:
258
+ res = await asyncio.wait_for(fn(client, number), timeout=timeout)
259
+ log.info("%s β†’ %d records in %.2fs", label, len(res), time.time() - t0)
260
+ return res
261
+ except asyncio.TimeoutError:
262
+ log.warning("%s β†’ TIMEOUT after %.1fs", label, timeout)
263
+ return []
264
+ except Exception as e:
265
+ log.warning("%s β†’ ERROR after %.2fs: %s", label, time.time() - t0, e)
266
+ return []
267
+
268
+
269
+ # ─────────────────────────────────────────────────────────────
270
+ # 5c. De-duplication
271
+ # ─────────────────────────────────────────────────────────────
272
+ def _norm(s) -> str:
273
+ if not s:
274
+ return ""
275
+ return re.sub(r"\s+", " ", str(s).strip().lower())
276
+
277
+
278
+ def _dedup_key(rec: dict):
279
+ """Use name+father+address when available β€” safer than name+father alone."""
280
+ f = rec.get("fields", {})
281
+ name = _norm(f.get("Name"))
282
+ father = _norm(f.get("Father"))
283
+ addr = _norm(f.get("Address"))
284
+ addr_n = re.sub(r"[^a-z0-9]+", " ", addr).strip()
285
+
286
+ if name and addr_n:
287
+ return ("na", name, addr_n)
288
+ if name and father:
289
+ return ("nf", name, father)
290
+ if addr_n:
291
+ return ("a", addr_n)
292
+ return None
293
+
294
+
295
+ def _dedup(records: list[dict]) -> list[dict]:
296
+ seen: dict = {}
297
+ result: list[dict] = []
298
+ for rec in records:
299
+ key = _dedup_key(rec)
300
+ if key is None:
301
+ result.append(rec)
302
+ continue
303
+ idx = seen.get(key)
304
+ if idx is None:
305
+ seen[key] = len(result)
306
+ result.append(rec)
307
+ else:
308
+ existing = result[idx]
309
+ if len(rec.get("fields", {})) > len(existing.get("fields", {})):
310
+ result[idx] = rec
311
+ return result
312
+
313
+
314
+ # ─────────────────────────────────────────────────────────────
315
+ # 5d. Search (cached)
316
+ # ─────────────────────────────────────────────────────────────
317
+ async def search_phone(number: str) -> list[dict]:
318
+ cached = _cache_get(number)
319
+ if cached is not None:
320
+ log.info("Cache HIT for %s (%d records)", number, len(cached))
321
+ return cached
322
+
323
+ client = await _get_api_client()
324
+ t0 = time.time()
325
+
326
+ chunks = await asyncio.gather(
327
+ _safe(_q_cr850, client, number, 40, "850CR"),
328
+ _safe(_q_inddata, client, number, 30, "IndData"),
329
+ _safe(_q_hiteck_main, client, number, 30, "HiTeck1.78B"),
330
+ _safe(_q_hiteck_big, client, number, 35, "HiTeck5B"),
331
+ )
332
+
333
+ merged: list[dict] = []
334
+ for chunk in chunks:
335
+ merged.extend(chunk)
336
+
337
+ before = len(merged)
338
+ deduped = _dedup(merged)
339
+ log.info("Search %s: %d raw β†’ %d unique in %.2fs",
340
+ number, before, len(deduped), time.time() - t0)
341
+
342
+ _cache_set(number, deduped)
343
+ return deduped
344
+
345
+
346
+ # ─────────────────────────────────────────────────────────────
347
+ # 6. Telegram API helpers
348
+ # ─────────────────────────────────────────────────────────────
349
+ async def tg(method: str, **payload):
350
+ client = await _get_api_client()
351
+ url = f"{TG_API}/{method}"
352
+ r = await client.post(url, json=payload)
353
+ if r.status_code >= 400:
354
+ log.warning("Telegram %s failed: %s %s", method, r.status_code, r.text[:200])
355
+ try:
356
+ return r.json()
357
+ except Exception:
358
+ return {}
359
+
360
+
361
+ async def send(chat_id: int, text: str, **kw):
362
+ """Send a message, splitting if it exceeds Telegram's limit."""
363
+ kw.setdefault("parse_mode", "HTML")
364
+ kw.setdefault("disable_web_page_preview", True)
365
+ try:
366
+ if len(text) <= TELEGRAM_MAX_MSG:
367
+ return await tg("sendMessage", chat_id=chat_id, text=text, **kw)
368
+ # Split on double-newline boundaries
369
+ chunks = _split_message(text, TELEGRAM_MAX_MSG)
370
+ result = None
371
+ for i, chunk in enumerate(chunks):
372
+ # Only include reply_markup on the LAST chunk
373
+ kw_chunk = dict(kw)
374
+ if i < len(chunks) - 1:
375
+ kw_chunk.pop("reply_markup", None)
376
+ result = await tg("sendMessage", chat_id=chat_id, text=chunk, **kw_chunk)
377
+ return result
378
+ except Exception:
379
+ log.exception("send failed")
380
+ return {}
381
+
382
+
383
+ async def edit(chat_id: int, message_id: int, text: str, **kw):
384
+ kw.setdefault("parse_mode", "HTML")
385
+ kw.setdefault("disable_web_page_preview", True)
386
+ # Telegram's editMessageText also has a 4096 limit; if too long, we fall back to send.
387
+ if len(text) > TELEGRAM_MAX_MSG:
388
+ try:
389
+ await tg("deleteMessage", chat_id=chat_id, message_id=message_id)
390
+ except Exception:
391
+ pass
392
+ return await send(chat_id, text, **kw)
393
+ try:
394
+ return await tg("editMessageText", chat_id=chat_id, message_id=message_id, text=text, **kw)
395
+ except Exception:
396
+ log.exception("edit failed")
397
+ return {}
398
+
399
+
400
+ async def answer_callback(callback_id: str, **kw):
401
+ try:
402
+ return await tg("answerCallbackQuery", callback_query_id=callback_id, **kw)
403
+ except Exception:
404
+ log.exception("answer_callback failed")
405
+ return {}
406
+
407
+
408
+ def _split_message(text: str, limit: int) -> list[str]:
409
+ """Split by double-newline boundaries; fall back to hard cut if needed."""
410
+ parts = text.split("\n\n")
411
+ chunks: list[str] = []
412
+ cur = ""
413
+ for p in parts:
414
+ candidate = (cur + "\n\n" + p) if cur else p
415
+ if len(candidate) <= limit:
416
+ cur = candidate
417
+ else:
418
+ if cur:
419
+ chunks.append(cur)
420
+ # if a single part is too big, hard-split it
421
+ while len(p) > limit:
422
+ chunks.append(p[:limit])
423
+ p = p[limit:]
424
+ cur = p
425
+ if cur:
426
+ chunks.append(cur)
427
+ return chunks
428
+
429
+
430
+ # ─────────────────────────────────────────────────────────────
431
+ # 7. Formatting
432
+ # ─────────────────────────────────────────────────────────────
433
+ def _esc(v) -> str:
434
+ if v is None:
435
+ return ""
436
+ return html.escape(str(v))
437
+
438
+
439
+ def render_record(rec: dict) -> str:
440
+ src = _esc(rec.get("source", "Unknown"))
441
+ fields = rec.get("fields", {})
442
+ lines = [f"πŸ—‚ <b>{src}</b>"]
443
+ for k, v in fields.items():
444
+ if v is None or v == "":
445
+ continue
446
+ # Truncate very long fields to keep messages sane
447
+ val = str(v)
448
+ if len(val) > 300:
449
+ val = val[:297] + "..."
450
+ lines.append(f"β€’ <b>{_esc(k)}:</b> {_esc(val)}")
451
+ if len(lines) == 1:
452
+ lines.append("β€’ <i>no data</i>")
453
+ return "\n".join(lines)
454
+
455
+
456
+ def render_page(number: str, records: list[dict], page: int) -> str:
457
+ total = len(records)
458
+ start = page * PAGE_SIZE
459
+ chunk = records[start:start + PAGE_SIZE]
460
+ if not chunk:
461
+ return "No more results."
462
+ pages = (total - 1) // PAGE_SIZE + 1
463
+ header = (
464
+ f"πŸ”Ž <b>Results for</b> <code>{_esc(number)}</code> β€” "
465
+ f"page {page + 1}/{pages} ({total} record{'s' if total != 1 else ''})\n\n"
466
+ )
467
+ body = "\n\n━━━━━━━━━━━━━━━━━━\n\n".join(render_record(r) for r in chunk)
468
+ return header + body
469
+
470
+
471
+ def pagination_kb(number: str, page: int, total: int):
472
+ nav = []
473
+ if page > 0:
474
+ nav.append({"text": "β—€ Prev", "callback_data": f"pg|{number}|{page - 1}"})
475
+ if (page + 1) * PAGE_SIZE < total:
476
+ nav.append({"text": "Next β–Ά", "callback_data": f"pg|{number}|{page + 1}"})
477
+ return {"inline_keyboard": [nav]} if nav else None
478
+
479
+
480
+ # ─────────────────────────────────────────────────────────────
481
+ # 8. Per-user state
482
+ # ─────────────────────────────────────────────────────────────
483
+ _last_search: dict[int, float] = {}
484
+ _search_lock = threading.Lock()
485
+
486
+ _admin_states: dict[int, tuple[str, float]] = {} # user_id -> (state, set_at)
487
+ _authorized_users: set[int] = set()
488
+ _custom_apis: list[str] = []
489
+ _admin_lock = threading.Lock()
490
+
491
+
492
+ def _admin_state_get(user_id: int) -> Optional[str]:
493
+ with _admin_lock:
494
+ entry = _admin_states.get(user_id)
495
+ if entry is None:
496
+ return None
497
+ state, set_at = entry
498
+ if time.time() - set_at > ADMIN_STATE_TTL:
499
+ _admin_states.pop(user_id, None)
500
+ return None
501
+ return state
502
+
503
+
504
+ def _admin_state_set(user_id: int, state: str):
505
+ with _admin_lock:
506
+ _admin_states[user_id] = (state, time.time())
507
+
508
+
509
+ def _admin_state_clear(user_id: int):
510
+ with _admin_lock:
511
+ _admin_states.pop(user_id, None)
512
+
513
+
514
+ # ─────────────────────────────────────────────────────────────
515
+ # 9. Admin helpers
516
+ # ─────────────────────────────────────────────────────────────
517
+ def _is_admin(user_id: int) -> bool:
518
+ return user_id in ADMIN_IDS
519
+
520
+
521
+ def _is_authorized(user_id: int) -> bool:
522
+ if not AUTH_ENABLED:
523
+ return True
524
+ with _admin_lock:
525
+ return user_id in _authorized_users or _is_admin(user_id)
526
+
527
+
528
+ def _admin_menu_kb():
529
+ return {
530
+ "inline_keyboard": [
531
+ [{"text": "βž• Add User", "callback_data": "admin|add_user"}],
532
+ [{"text": "βž– Remove User", "callback_data": "admin|remove_user"}],
533
+ [{"text": "πŸ“‹ List Users", "callback_data": "admin|list_users"}],
534
+ [{"text": "πŸ”Œ Add API", "callback_data": "admin|add_api"}],
535
+ [{"text": "πŸ—‘ Clear APIs", "callback_data": "admin|clear_apis"}],
536
+ [{"text": "πŸ“‹ List APIs", "callback_data": "admin|list_apis"}],
537
+ ]
538
+ }
539
+
540
+
541
+ # ─────────────────────────────────────────────────────────────
542
+ # 10. Message handlers
543
+ # ─────────────────────────────────────────────────────────────
544
+ async def handle_message(update: dict):
545
+ msg = update.get("message") or update.get("edited_message")
546
+ if not msg:
547
+ return
548
+
549
+ chat_id = msg["chat"]["id"]
550
+ sender = msg.get("from") or {}
551
+ user_id = sender.get("id")
552
+ if user_id is None:
553
+ # Channel post or other anonymous source β€” ignore
554
+ return
555
+
556
+ # Non-text messages β€” polite nudge, no crash
557
+ if "text" not in msg:
558
+ await send(chat_id, "❗ Please send a <b>text message</b> with a 10‑digit number.")
559
+ return
560
+
561
+ text = (msg.get("text") or "").strip()
562
+ log.info("MSG from %s: %r", user_id, text[:100])
563
+
564
+ # ── Admin input capture (with expiry) ──
565
+ state = _admin_state_get(user_id)
566
+ if state and _is_admin(user_id):
567
+ if state == "await_user_id":
568
+ if text.isdigit():
569
+ with _admin_lock:
570
+ _authorized_users.add(int(text))
571
+ _admin_state_clear(user_id)
572
+ await send(chat_id, f"βœ… User <code>{text}</code> authorized.")
573
+ else:
574
+ await send(chat_id, "❗ Send a numeric Telegram user ID (or /cancel).")
575
+ return
576
+ if state == "await_api_url":
577
+ if text.startswith("http"):
578
+ with _admin_lock:
579
+ _custom_apis.append(text.rstrip("/"))
580
+ _admin_state_clear(user_id)
581
+ await send(chat_id, f"βœ… API added: <code>{_esc(text)}</code>")
582
+ else:
583
+ await send(chat_id, "❗ Send a valid http(s) URL (or /cancel).")
584
+ return
585
+
586
+ # ── Commands ──
587
+ if text.startswith("/"):
588
+ cmd = text.split()[0].lower()
589
+
590
+ if cmd == "/start":
591
+ await send(
592
+ chat_id,
593
+ "πŸ‘‹ <b>Welcome!</b>\n\n"
594
+ "Send me a <b>10‑digit mobile number</b> and I'll search across multiple databases.\n\n"
595
+ "Commands:\n"
596
+ "/start β€” this message\n"
597
+ "/status β€” bot health\n"
598
+ "/myid β€” show your Telegram user ID\n"
599
+ "/cancel β€” cancel current input",
600
+ )
601
+ return
602
+
603
+ if cmd == "/myid":
604
+ await send(chat_id, f"πŸ†” Your Telegram user ID: <code>{user_id}</code>")
605
+ return
606
+
607
+ if cmd == "/cancel":
608
+ _admin_state_clear(user_id)
609
+ await send(chat_id, "βœ… Cancelled.")
610
+ return
611
+
612
+ if cmd == "/status":
613
+ with _cache_lock:
614
+ cache_size = len(_cache)
615
+ await send(
616
+ chat_id,
617
+ "βœ… <b>Bot alive</b>\n"
618
+ f"πŸ—‚ Sources: 4 (dedup ON)\n"
619
+ f"πŸ’Ύ Cache entries: {cache_size}\n"
620
+ f"⏱ Rate limit: {RATE_LIMIT_SEC}s\n"
621
+ f"πŸ“„ Page size: {PAGE_SIZE}",
622
+ )
623
+ return
624
+
625
+ if cmd == "/nemesis":
626
+ if not _is_admin(user_id):
627
+ await send(chat_id, "β›” Unauthorized.")
628
+ return
629
+ await send(chat_id, "πŸ›‘ <b>Admin Panel</b>\nChoose an action:", reply_markup=_admin_menu_kb())
630
+ return
631
+
632
+ return
633
+
634
+ # ── Auth gate ──
635
+ if not _is_authorized(user_id):
636
+ await send(chat_id, "β›” You are not authorized to use this bot.")
637
+ return
638
+
639
+ # ── Validate number ──
640
+ if not (text.isdigit() and len(text) == 10):
641
+ await send(chat_id, "❗ Please send a <b>10‑digit mobile number</b> only.")
642
+ return
643
+
644
+ # ── Rate limit ──
645
+ now = time.time()
646
+ with _search_lock:
647
+ last = _last_search.get(user_id, 0)
648
+ if now - last < RATE_LIMIT_SEC:
649
+ wait = int(RATE_LIMIT_SEC - (now - last)) + 1
650
+ await send(chat_id, f"⏳ Please wait <b>{wait}s</b> before searching again.")
651
+ return
652
+ _last_search[user_id] = now
653
+ # opportunistic cleanup of stale rate-limit entries
654
+ if len(_last_search) > 1000:
655
+ cutoff = now - 3600
656
+ for k in list(_last_search.keys()):
657
+ if _last_search[k] < cutoff:
658
+ _last_search.pop(k, None)
659
+
660
+ await send(chat_id, f"πŸ” <b>Searching</b> <code>{_esc(text)}</code> across 4 databases …")
661
+
662
+ try:
663
+ records = await asyncio.wait_for(search_phone(text), timeout=QUERY_TIMEOUT)
664
+ except asyncio.TimeoutError:
665
+ await send(chat_id, "⏰ Search timed out. Try again in a moment.")
666
+ return
667
+ except Exception:
668
+ log.exception("search_phone unexpected error")
669
+ await send(chat_id, "⚠️ Unexpected error during search.")
670
+ return
671
+
672
+ if not records:
673
+ await send(chat_id, f"❌ No records found for <code>{_esc(text)}</code>.")
674
+ return
675
+
676
+ kb = pagination_kb(text, 0, len(records))
677
+ await send(chat_id, render_page(text, records, 0), reply_markup=kb)
678
+
679
+
680
+ async def handle_callback(update: dict):
681
+ cb = update.get("callback_query")
682
+ if not cb:
683
+ return
684
+ data = cb.get("data") or ""
685
+ chat_id = cb["message"]["chat"]["id"]
686
+ user_id = (cb.get("from") or {}).get("id")
687
+ message_id = cb["message"]["message_id"]
688
+
689
+ await answer_callback(cb["id"])
690
+
691
+ if user_id is None:
692
+ return
693
+
694
+ if data.startswith("admin|"):
695
+ if not _is_admin(user_id):
696
+ await edit(chat_id, message_id, "β›” Unauthorized.")
697
+ return
698
+ action = data.split("|", 1)[1]
699
+
700
+ if action == "add_user":
701
+ _admin_state_set(user_id, "await_user_id")
702
+ await edit(chat_id, message_id, "Send the Telegram user ID to authorize (or /cancel):")
703
+ return
704
+
705
+ if action == "remove_user":
706
+ with _admin_lock:
707
+ users = sorted(_authorized_users)
708
+ if not users:
709
+ await edit(chat_id, message_id, "No authorized users.", reply_markup=_admin_menu_kb())
710
+ else:
711
+ txt = "Authorized users:\n" + "\n".join(f"<code>{u}</code>" for u in users)
712
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
713
+ return
714
+
715
+ if action == "list_users":
716
+ with _admin_lock:
717
+ users = sorted(_authorized_users)
718
+ txt = "Authorized users:\n" + ("\n".join(f"<code>{u}</code>" for u in users) if users else "β€”")
719
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
720
+ return
721
+
722
+ if action == "add_api":
723
+ _admin_state_set(user_id, "await_api_url")
724
+ await edit(chat_id, message_id, "Send the API base URL to add (or /cancel):")
725
+ return
726
+
727
+ if action == "clear_apis":
728
+ with _admin_lock:
729
+ _custom_apis.clear()
730
+ await edit(chat_id, message_id, "βœ… All custom APIs cleared.", reply_markup=_admin_menu_kb())
731
+ return
732
+
733
+ if action == "list_apis":
734
+ with _admin_lock:
735
+ apis = list(_custom_apis)
736
+ txt = "Custom APIs:\n" + ("\n".join(f"<code>{_esc(a)}</code>" for a in apis) if apis else "β€”")
737
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
738
+ return
739
+
740
+ return
741
+
742
+ # ── Pagination ──
743
+ if not data.startswith("pg|"):
744
+ return
745
+
746
+ try:
747
+ _, number, page_s = data.split("|", 2)
748
+ page = int(page_s)
749
+ except Exception:
750
+ return
751
+
752
+ try:
753
+ records = await asyncio.wait_for(search_phone(number), timeout=QUERY_TIMEOUT)
754
+ except Exception:
755
+ log.exception("callback search failed")
756
+ await edit(chat_id, message_id, "⚠️ Could not load that page. Try again.")
757
+ return
758
+
759
+ if not records:
760
+ await edit(chat_id, message_id, "❌ No records found.")
761
+ return
762
+
763
+ kb = pagination_kb(number, page, len(records))
764
+ await edit(chat_id, message_id, render_page(number, records, page), reply_markup=kb)
765
+
766
+
767
+ # ─────────────────────────────────────────────────────────────
768
+ # 11. FastAPI routes
769
+ # ──────────��──────────────────────────────────────────────────
770
+ async def webhook_handler(request: Request):
771
+ # Always return 200 to Telegram β€” bad secret means we just ignore the payload.
772
+ if request.headers.get("x-telegram-bot-api-secret-token") != WEBHOOK_SECRET:
773
+ log.warning("Bad webhook secret β€” ignoring")
774
+ return JSONResponse({"ok": True})
775
+
776
+ try:
777
+ update = await request.json()
778
+ except Exception:
779
+ return JSONResponse({"ok": True})
780
+
781
+ try:
782
+ if "message" in update or "edited_message" in update:
783
+ await handle_message(update)
784
+ elif "callback_query" in update:
785
+ await handle_callback(update)
786
+ except Exception:
787
+ log.exception("Handler error")
788
+
789
+ return JSONResponse({"ok": True})
790
+
791
+
792
+ async def health_handler(request: Request):
793
+ with _cache_lock:
794
+ cache_size = len(_cache)
795
+ return JSONResponse({
796
+ "status": "ok",
797
+ "time": time.time(),
798
+ "cache_entries": cache_size,
799
+ })
800
+
801
+
802
+ # ─────────────────────────────────────────────────────────────
803
+ # 12. Gradio UI (ZeroGPU registration)
804
+ # ─────────────────────────────────────────────────────────────
805
+ @spaces.GPU(duration=10)
806
+ def _zerogpu_register():
807
+ return "gpu-ready"
808
+
809
+
810
+ with gr.Blocks(title="Phone Lookup Bot") as demo:
811
+ gr.Markdown("## Phone Lookup Bot\nTelegram webhook endpoint is live.")
812
+ _btn = gr.Button("init-gpu", visible=False)
813
+ _btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
814
+
815
+
816
+ # ─────────────────────────────────────────────────────────────
817
+ # 13. Launch + inject routes
818
+ # ─────────────────────────────────────────────────────────────
819
+ demo.launch(
820
+ server_name="0.0.0.0",
821
+ server_port=7860,
822
+ share=False,
823
+ ssr_mode=False,
824
+ prevent_thread_lock=True,
825
+ )
826
+
827
+ live_app = demo.app
828
+ live_app.router.routes.insert(0, StarletteRoute("/webhook", webhook_handler, methods=["POST"]))
829
+ live_app.router.routes.insert(0, StarletteRoute("/health", health_handler, methods=["GET"]))
830
+ live_app.build_middleware_stack()
831
+
832
+
833
+ # ─────────────────────────────────────────────────────────────
834
+ # 14. setWebhook (sync β€” own thread)
835
+ # ─────────────────────────────────────────────────────────────
836
+ def _set_webhook_sync():
837
+ time.sleep(3)
838
+ try:
839
+ with httpx.Client(timeout=15.0) as c:
840
+ r = c.post(f"{TG_API}/setWebhook", json={
841
+ "url": f"{SPACE_URL}/webhook",
842
+ "secret_token": WEBHOOK_SECRET,
843
+ "allowed_updates": ["message", "edited_message", "callback_query"],
844
+ })
845
+ log.info("setWebhook β†’ %s", r.text)
846
+ except Exception:
847
+ log.exception("setWebhook failed")
848
+
849
+
850
+ threading.Thread(target=_set_webhook_sync, daemon=True).start()
851
+
852
+ demo.block_thread()