Hfzune commited on
Commit
3569dee
·
verified ·
1 Parent(s): fb26119

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +968 -393
app.py CHANGED
@@ -1,455 +1,1030 @@
1
- """
2
- Telegram Info Bot — FastAPI + Telegram Webhook + Admin Panel
3
- Runs on Hugging Face Spaces (Gradio SDK, port 7860). No GPU needed.
4
- """
5
 
6
  import os
 
7
  import re
8
  import json
9
- import hmac
10
  import time
11
  import gzip
12
- import shutil
 
13
  import asyncio
14
- import uuid
15
- import csv
16
- import io
17
- from datetime import datetime, timezone
18
  from collections import deque
19
- from html import escape
20
- from pathlib import Path
21
 
22
  import httpx
23
- from fastapi import FastAPI, Request, HTTPException, Depends, Response
24
- from fastapi.responses import HTMLResponse
25
- from fastapi.security import HTTPBasic, HTTPBasicCredentials
26
  import gradio as gr
27
 
28
-
29
- # ============================================================
30
  # CONFIG
31
- # ============================================================
32
- BOT_TOKEN = os.getenv("BOT_TOKEN", "").strip()
33
- API_KEY = os.getenv("API_KEY", "").strip()
34
- WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET", "").strip()
35
- WEBHOOK_PATH = os.getenv("WEBHOOK_PATH", "").strip()
36
- PUBLIC_URL = os.getenv("PUBLIC_URL", "").strip().rstrip("/")
37
-
38
- PANEL_USER = os.getenv("PANEL_USER", "admin").strip()
39
- PANEL_PASS = os.getenv("PANEL_PASS", "").strip()
40
- PANEL_TOKEN = os.getenv("PANEL_TOKEN", "").strip()
41
- PANEL_ALLOWED = [x.strip() for x in os.getenv("PANEL_ALLOWED_IPS", "").split(",") if x.strip()]
42
-
43
- ADMIN_SECRET = os.getenv("ADMIN_SECRET", "").strip()
44
- VIEWER_SECRET = os.getenv("VIEWER_SECRET", "").strip()
45
- ADMIN_SESSION_TTL = int(os.getenv("ADMIN_SESSION_TTL_MIN", "30")) * 60
46
- ADMIN_MAX_FAILS = int(os.getenv("ADMIN_MAX_FAILS", "3"))
47
-
48
- LOG_CHAT_ID = os.getenv("LOG_CHAT_ID", "").strip()
49
- MAX_INMEM_LOG = int(os.getenv("MAX_INMEM_LOG", "2000"))
50
- LOG_FILE = Path(os.getenv("LOG_FILE_PATH", "/tmp/bot_logs.jsonl"))
51
- LOG_ROTATE_B = int(os.getenv("LOG_ROTATE_MB", "40")) * 1024 * 1024
52
- LOG_KEEP_ROT = int(os.getenv("LOG_KEEP_ROTATED", "3"))
53
-
54
- BASE_MOBILE = os.getenv("BASE_MOBILE", "https://num-to-info.asurpapa.workers.dev/api")
55
- BASE_AADHAAR = os.getenv("BASE_AADHAAR", "https://aadhaar.asurpapa.workers.dev/api")
56
- BASE_FAMILY = os.getenv("BASE_FAMILY", "https://aadhaar-family.asurpapa.workers.dev/api")
57
- BASE_RATION = os.getenv("BASE_RATION", "https://ration-card.asurpapa.workers.dev/api")
58
-
59
- TG_API = f"https://api.telegram.org/bot{BOT_TOKEN}"
60
- PORT = int(os.getenv("PORT", "7860"))
61
- START = time.time()
62
-
63
-
64
- # ============================================================
65
- # STATE
66
- # ============================================================
67
- USERS = {} # user_id -> meta
68
- STATE = {} # user_id -> awaiting action
69
- ADMIN_SESS = {} # user_id -> expiry ts
70
- ADMIN_FAILS = {} # user_id -> [ts,...]
71
- LOG_DEQUE = deque(maxlen=MAX_INMEM_LOG)
72
- USERS_FILE = Path("/tmp/bot_users.json")
73
-
74
- if USERS_FILE.exists():
75
- try:
76
- USERS.update(json.loads(USERS_FILE.read_text(encoding="utf-8")))
77
- except Exception:
78
- pass
79
-
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- # ============================================================
82
- # LOG PERSISTENCE
83
- # ============================================================
84
- def _rotate_logs():
85
- if not LOG_FILE.exists():
86
- return
87
- if LOG_FILE.stat().st_size < LOG_ROTATE_B:
88
- return
89
- stem, ext = LOG_FILE.stem, LOG_FILE.suffix
90
- oldest = LOG_FILE.with_name(f"{stem}.{LOG_KEEP_ROT}{ext}")
91
- if oldest.exists():
92
- try:
93
- oldest.unlink()
94
- except Exception:
95
- pass
96
- for i in range(LOG_KEEP_ROT - 1, 0, -1):
97
- src = LOG_FILE.with_name(f"{stem}.{i}{ext}")
98
- dst = LOG_FILE.with_name(f"{stem}.{i+1}{ext}")
99
- if src.exists():
100
- try:
101
- if dst.exists():
102
- dst.unlink()
103
- src.rename(dst)
104
- except Exception:
105
- pass
106
- target = LOG_FILE.with_name(f"{stem}.1{ext}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  try:
108
- target.write_bytes(LOG_FILE.read_bytes())
109
- LOG_FILE.write_text("", encoding="utf-8")
 
 
 
 
 
110
  except Exception:
111
- pass
112
 
 
 
 
 
 
 
 
 
113
 
114
- def _persist_users():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  try:
116
- USERS_FILE.write_text(json.dumps(USERS), encoding="utf-8")
117
- except Exception:
118
- pass
119
-
120
-
121
- def log_entry(entry: dict):
122
- entry.setdefault("_id", uuid.uuid4().hex[:12])
123
- entry.setdefault("ts", time.time())
124
- entry.setdefault("ts_iso", datetime.now(timezone.utc).isoformat())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- LOG_DEQUE.append(entry)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- # full record -> file
 
 
 
129
  try:
130
- LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
131
- _rotate_logs()
132
- with LOG_FILE.open("a", encoding="utf-8") as f:
133
- f.write(json.dumps(entry, ensure_ascii=False) + "\n")
 
 
 
 
 
 
 
 
 
 
134
  except Exception as e:
135
- print(f"[log write err] {e}")
136
-
137
- # mirror -> private channel (survives restarts)
138
- if LOG_CHAT_ID:
139
- try:
140
- loop = asyncio.get_running_loop()
141
- loop.create_task(_mirror_to_channel(entry))
142
- except RuntimeError:
143
- pass
144
-
145
 
146
- async def _mirror_to_channel(entry: dict):
 
147
  try:
148
- body = json.dumps(entry, ensure_ascii=False, indent=2)
149
- if len(body) > 3500:
150
- body = body[:3500] + "\n...(truncated)"
151
- text = f"📝 <b>{escape(entry.get('type','?'))}</b> — user <code>{entry.get('user_id')}</code>\n<pre>{escape(body)}</pre>"
152
- async with httpx.AsyncClient(timeout=10) as c:
153
- await c.post(f"{TG_API}/sendMessage", json={
154
- "chat_id": LOG_CHAT_ID,
155
- "text": text[:4000],
156
- "parse_mode": "HTML",
157
- })
158
- except Exception:
159
- pass
160
-
161
 
162
- # ============================================================
163
- # TELEGRAM HELPERS
164
- # ============================================================
165
- async def tg_send(chat_id, text, reply_markup=None, parse_mode="HTML"):
166
  try:
167
- payload = {"chat_id": chat_id, "text": text[:4000]}
168
- if parse_mode:
169
- payload["parse_mode"] = parse_mode
170
- if reply_markup:
171
- payload["reply_markup"] = reply_markup
172
- async with httpx.AsyncClient(timeout=15) as c:
173
- r = await c.post(f"{TG_API}/sendMessage", json=payload)
174
- return r.json()
175
  except Exception as e:
176
- print(f"[tg_send] {e}")
177
- return None
178
 
 
 
 
 
179
 
180
- async def tg_edit(chat_id, msg_id, text, reply_markup=None):
181
- try:
182
- payload = {"chat_id": chat_id, "message_id": msg_id,
183
- "text": text[:4000], "parse_mode": "HTML"}
 
 
 
 
 
 
 
 
 
 
 
184
  if reply_markup:
185
  payload["reply_markup"] = reply_markup
186
- async with httpx.AsyncClient(timeout=15) as c:
187
- return (await c.post(f"{TG_API}/editMessageText", json=payload)).json()
188
- except Exception:
189
- return None
 
 
 
 
 
 
 
 
 
 
 
190
 
 
 
191
 
192
- async def tg_answer_cb(cb_id, text=None):
193
- try:
194
- payload = {"callback_query_id": cb_id}
195
- if text:
196
- payload["text"] = text[:200]
197
- async with httpx.AsyncClient(timeout=10) as c:
198
- await c.post(f"{TG_API}/answerCallbackQuery", json=payload)
199
- except Exception:
200
- pass
201
-
 
202
 
203
- async def tg_send_document(chat_id, filepath: Path, caption=""):
204
- try:
205
- async with httpx.AsyncClient(timeout=180) as c:
206
- with filepath.open("rb") as f:
207
- files = {"document": (filepath.name, f, "application/octet-stream")}
208
- data = {"chat_id": str(chat_id), "caption": caption[:1000]}
209
- return (await c.post(f"{TG_API}/sendDocument", data=data, files=files)).json()
210
- except Exception as e:
211
- print(f"[tg_send_doc] {e}")
212
- return None
213
 
 
 
 
 
214
 
215
- # ============================================================
216
- # UPSTREAM
217
- # ============================================================
218
- async def fetch(url, params):
219
- params = {**params, "key": API_KEY}
220
- t0 = time.time()
221
  try:
222
- async with httpx.AsyncClient(timeout=15) as c:
223
- r = await c.get(url, params=params)
224
- elapsed = int((time.time() - t0) * 1000)
225
- try:
226
- body = r.json()
227
- except Exception:
228
- body = {"status": "error", "message": f"Non-JSON: {r.text[:200]}"}
229
- return body, r.status_code, elapsed, params
230
  except Exception as e:
231
- return {"status": "error", "message": str(e)}, 0, int((time.time() - t0) * 1000), params
232
-
233
-
234
- # ============================================================
235
- # FORMATTERS
236
- # ============================================================
237
- def _v(x):
238
- if x is None or x == "" or x == "null" or x == "None":
239
- return "—"
240
- return escape(str(x))
241
-
242
-
243
- def fmt_mobile(data):
244
- if not isinstance(data, dict) or data.get("status") != "success":
245
- msg = data.get("message") if isinstance(data, dict) else "Unknown error"
246
- return f"❌ <b>Failed:</b> {_v(msg)}"
247
- d = data.get("data") or {}
248
- return (
249
- "📱 <b>Mobile Info</b>\n━━━━━━━━━━━━━━━\n"
250
- f"<b>Mobile:</b> {_v(d.get('mobile'))}\n"
251
- f"<b>Name:</b> {_v(d.get('name'))}\n"
252
- f"<b>Father:</b> {_v(d.get('fname'))}\n"
253
- f"<b>Address:</b> {_v(d.get('address'))}\n"
254
- f"<b>Alt:</b> {_v(d.get('alt'))}\n"
255
- f"<b>Circle:</b> {_v(d.get('circle'))}\n"
256
- f"<b>Email:</b> {_v(d.get('email'))}"
257
- )
258
-
259
-
260
- def fmt_aadhaar(data):
261
- if not isinstance(data, dict) or data.get("status") != "success":
262
- msg = data.get("message") if isinstance(data, dict) else "Unknown error"
263
- return f"❌ <b>Failed:</b> {_v(msg)}"
264
- records = data.get("data") or []
265
- if not records:
266
- return "⚠️ No records found."
267
- out = [f"🆔 <b>Aadhaar Lookup</b> — {data.get('count', len(records))} record(s)"]
268
- for i, r in enumerate(records, 1):
269
- out.append(
270
- f"\n<b>#{i} {_v(r.get('name'))}</b>\n"
271
- f"👨 Father: {_v(r.get('fathersName'))}\n"
272
- f"📞 Phone: {_v(r.get('phoneNumber'))}\n"
273
- f"📞 Alt: {_v(r.get('otherNumber'))}\n"
274
- f"🏠 Address: {_v(r.get('address'))}"
275
- )
276
- return "\n".join(out)
277
-
278
-
279
- def fmt_family(data):
280
- if not isinstance(data, dict) or not data.get("status"):
281
- msg = data.get("message") if isinstance(data, dict) else "Unknown error"
282
- return f"❌ <b>Failed:</b> {_v(msg)}"
283
- members = data.get("members") or []
284
- out = [f"👨‍👩‍👧 <b>Family Info</b> — {data.get('total_records', len(members))} member(s)"]
285
- for m in members:
286
- out.append(
287
- f"\n<b>{_v(m.get('name'))}</b> ({_v(m.get('relation'))})\n"
288
- f"🆔 UID: {_v(m.get('masked_uid'))}\n"
289
- f"🔢 Member ID: {_v(m.get('member_id'))}"
290
- )
291
- return "\n".join(out)
292
-
293
-
294
- def fmt_ration(data):
295
- if not isinstance(data, dict) or not data.get("status"):
296
- msg = data.get("message") if isinstance(data, dict) else "Unknown error"
297
- return f"❌ <b>Failed:</b> {_v(msg)}"
298
- return (
299
- "🍚 <b>Ration Card Info</b>\n━━━━━━━━━━━━━━━\n"
300
- f"<b>Aadhaar:</b> {_v(data.get('aadhar'))}\n"
301
- f"<b>Head of Family:</b> {_v(data.get('head_family'))}\n"
302
- f"<b>Ration No:</b> {_v(data.get('ration_number'))}\n"
303
- f"<b>Application:</b> {_v(data.get('application_no'))}\n"
304
- f"<b>Scheme:</b> {_v(data.get('scheme'))}\n"
305
- f"<b>Address:</b> {_v(data.get('address'))}\n"
306
- f"<b>District:</b> {_v(data.get('district'))}\n"
307
- f"<b>State:</b> {_v(data.get('state'))}\n"
308
- f"<b>FPS ID:</b> {_v(data.get('fps_id'))}"
309
- )
310
-
311
-
312
- # ============================================================
313
- # ADMIN HELPERS
314
- # ============================================================
315
- def is_admin(uid):
316
- exp = ADMIN_SESS.get(uid, 0)
317
- if exp < time.time():
318
- ADMIN_SESS.pop(uid, None)
319
- return False
320
- return True
321
-
322
-
323
- def check_admin_code(code):
324
- if not code:
325
- return None
326
- if ADMIN_SECRET and hmac.compare_digest(code, ADMIN_SECRET):
327
- return "admin"
328
- if VIEWER_SECRET and hmac.compare_digest(code, VIEWER_SECRET):
329
- return "viewer"
330
- return None
331
-
332
-
333
- # ============================================================
334
- # KEYBOARDS
335
- # ============================================================
336
- KEYBOARD = {"inline_keyboard": [
337
- [{"text": "📱 Mobile Info", "callback_data": "mobile"}],
338
- [{"text": "🆔 Aadhaar Info", "callback_data": "aadhaar"}],
339
- [{"text": "👨‍👩‍👧 Aadhaar Family", "callback_data": "family"}],
340
- [{"text": "🍚 Ration Card", "callback_data": "ration"}],
341
- ]}
342
- BACK_BTN = {"inline_keyboard": [[{"text": "« Back to Menu", "callback_data": "menu"}]]}
343
- PROMPTS = {
344
- "mobile": "📱 Send a <b>10-digit mobile number</b>",
345
- "aadhaar": "🆔 Send a <b>12-digit Aadhaar number</b>",
346
- "family": "👨‍👩‍👧 Send a <b>12-digit Aadhaar number</b>",
347
- "ration": "🍚 Send a <b>12-digit Aadhaar number</b>",
348
- }
349
 
 
350
 
351
- # ============================================================
352
- # BOT HANDLERS
353
- # ============================================================
354
- async def handle_start(user_id, chat_id):
355
- await tg_send(
 
 
 
 
 
 
 
 
356
  chat_id,
357
- "👋 <b>Welcome!</b>\n\nChoose a lookup type below.\n\n"
358
- "<i>By using this bot you confirm you have lawful basis for querying.</i>",
359
- reply_markup=KEYBOARD,
360
  )
361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
363
- async def handle_menu_cb(user_id, chat_id, msg_id):
364
- STATE.pop(user_id, None)
365
- await tg_edit(chat_id, msg_id, "Choose a lookup type:", reply_markup=KEYBOARD)
366
-
367
-
368
- async def handle_type_cb(user_id, chat_id, msg_id, action):
369
- STATE[user_id] = action
370
- await tg_edit(chat_id, msg_id, PROMPTS[action], reply_markup=BACK_BTN)
 
 
371
 
 
 
 
 
 
 
372
 
373
- async def handle_admin_start(user_id, chat_id):
374
- STATE[user_id] = "await_admin_code"
375
- await tg_send(chat_id, "🔐 Enter admin secret code:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
- async def handle_admin_code(user_id, chat_id, code):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  now = time.time()
380
- fails = [t for t in ADMIN_FAILS.get(user_id, []) if now - t < 600]
381
- ADMIN_FAILS[user_id] = fails
382
-
383
  if len(fails) >= ADMIN_MAX_FAILS:
384
- STATE.pop(user_id, None)
385
- await tg_send(chat_id, "⛔ Too many failed attempts. Try again in 10 minutes.")
386
  return
387
 
388
- role = check_admin_code(code)
389
- STATE.pop(user_id, None)
390
-
391
- if role:
392
- ADMIN_SESS[user_id] = now + ADMIN_SESSION_TTL
393
- ADMIN_FAILS[user_id] = []
394
- await tg_send(
395
- chat_id,
396
- f"✅ Authenticated as <b>{role}</b> (valid {ADMIN_SESSION_TTL//60} min).\n\n"
397
- "Commands:\n/logs — latest log file\n/logs N — last N records\n"
398
- "/logs YYYY-MM-DD YYYY-MM-DD — date range\n/logstats — stats\n"
399
- "/export users|searches — CSV export\n/logout — end session",
400
- )
401
- if LOG_CHAT_ID:
402
- await tg_send(LOG_CHAT_ID, f"🔓 Admin auth: {user_id} as {role}")
403
  else:
404
  fails.append(now)
405
- ADMIN_FAILS[user_id] = fails
406
- await tg_send(chat_id, "❌ Invalid code.")
407
- if LOG_CHAT_ID:
408
- await tg_send(LOG_CHAT_ID, f"⚠️ Failed admin attempt by {user_id}")
409
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
- async def handle_logout(user_id, chat_id):
412
- ADMIN_SESS.pop(user_id, None)
413
- await tg_send(chat_id, "👋 Logged out.")
414
 
 
 
 
 
 
 
415
 
416
- async def handle_logstats(user_id, chat_id):
417
- if not is_admin(user_id):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  return
419
- size = LOG_FILE.stat().st_size if LOG_FILE.exists() else 0
420
- await tg_send(
421
- chat_id,
422
- f"📊 <b>Log Stats</b>\n"
423
- f"In-memory: {len(LOG_DEQUE)}/{MAX_INMEM_LOG}\n"
424
- f"File: {size/1024:.1f} KB\n"
425
- f"Users: {len(USERS)}\n"
426
- f"Uptime: {(time.time()-START)/3600:.2f} h",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  )
428
-
429
-
430
- async def handle_logs(user_id, chat_id, text):
431
- if not is_admin(user_id):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  return
433
- parts = text.split()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  try:
435
- if len(parts) == 1:
436
- if not LOG_FILE.exists() or LOG_FILE.stat().st_size == 0:
437
- await tg_send(chat_id, "⚠️ No logs yet.")
438
- return
439
- gz = Path("/tmp/logs_export.jsonl.gz")
440
- with LOG_FILE.open("rb") as fin, gzip.open(gz, "wb") as fout:
441
- shutil.copyfileobj(fin, fout)
442
- if gz.stat().st_size > 45 * 1024 * 1024:
443
- # fall back to in-memory
444
- gz2 = Path("/tmp/logs_inmem.jsonl.gz")
445
- with gzip.open(gz2, "wt", encoding="utf-8") as f:
446
- for r in LOG_DEQUE:
447
- f.write(json.dumps(r, ensure_ascii=False) + "\n")
448
- await tg_send_document(chat_id, gz2, caption=f"Last {len(LOG_DEQUE)} records (file too large)")
449
- try: gz.unlink()
450
- except: pass
451
- try: gz2.unlink()
452
- except: pass
453
- else:
454
- await tg_send_document(chat_id, gz, caption=f"Logs ({LOG_FILE.stat().st_size/1024:.1f} KB)")
455
- try: g
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — Telegram bot + admin panel + logging
2
+ # HF Spaces: Gradio SDK (CPU, zero GPU). FastAPI owns the server;
3
+ # Gradio is mounted at /gradio. Run with `python app.py`.
 
4
 
5
  import os
6
+ import io
7
  import re
8
  import json
 
9
  import time
10
  import gzip
11
+ import hmac
12
+ import base64
13
  import asyncio
14
+ import hashlib
15
+ import logging
16
+ from datetime import datetime, timezone, timedelta
 
17
  from collections import deque
18
+ from typing import Optional
 
19
 
20
  import httpx
21
+ from fastapi import FastAPI, Request, Response, HTTPException
22
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, PlainTextResponse
23
+ from starlette.middleware.base import BaseHTTPMiddleware
24
  import gradio as gr
25
 
26
+ # ────────────────────────────────────────────────────────────────────
 
27
  # CONFIG
28
+ # ────────────────────────────────────────────────────────────────────
29
+ def _env(k, default=""):
30
+ return os.environ.get(k, default).strip()
31
+
32
+ TELEGRAM_TOKEN = _env("TELEGRAM_TOKEN") or _env("BOT_TOKEN")
33
+ API_KEY = _env("API_KEY", "@ASUR_ABOUT")
34
+ SPACE_HOST = _env("SPACE_HOST")
35
+ WEBHOOK_BASE_URL = _env("WEBHOOK_BASE_URL") or (f"https://{SPACE_HOST}" if SPACE_HOST else "")
36
+
37
+ ADMIN_SECRET = _env("ADMIN_SECRET", "change-me-" + os.urandom(8).hex())
38
+ VIEWER_SECRET = _env("VIEWER_SECRET")
39
+ LOG_CHAT_ID = _env("LOG_CHAT_ID") # str; "-100123..." if set
40
+ MAX_INMEM_LOG = int(_env("MAX_INMEM_LOG", "5000"))
41
+ LOG_FILE_PATH = _env("LOG_FILE_PATH", "/tmp/bot_logs.jsonl")
42
+ LOG_ROTATE_MB = int(_env("LOG_ROTATE_MB", "40"))
43
+ LOG_KEEP_ROTATED = int(_env("LOG_KEEP_ROTATED", "3"))
44
+ PANEL_ALLOWED_IPS = [x.strip() for x in _env("PANEL_ALLOWED_IPS").split(",") if x.strip()]
45
+ PANEL_SESSION_TTL_MIN = int(_env("PANEL_SESSION_TTL_MIN", "60"))
46
+ ADMIN_SESSION_TTL_MIN = int(_env("ADMIN_SESSION_TTL_MIN", "30"))
47
+ ADMIN_MAX_FAILS = int(_env("ADMIN_MAX_FAILS", "3"))
48
+ LOG_RETENTION_DAYS = int(_env("LOG_RETENTION_DAYS", "30"))
49
+
50
+ # Derived: single secret for panel (username ignored, password = ADMIN_SECRET)
51
+ PANEL_TOKEN = ADMIN_SECRET
52
+ SESSION_KEY = hashlib.sha256((ADMIN_SECRET + os.urandom(8).hex()).encode()).hexdigest()
53
+
54
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
55
+ log = logging.getLogger("bot")
56
+
57
+ STARTED_AT = datetime.now(timezone.utc)
58
+
59
+ # ────────────────────────────────────────────────────────────────────
60
+ # UPSTREAM APIs
61
+ # ────────────────────────────────────────────────────────────────────
62
+ APIS = {
63
+ "mobile": {
64
+ "url": "https://num-to-info.asurpapa.workers.dev/api",
65
+ "param": "number",
66
+ "pattern": re.compile(r"^[6-9]\d{9}$"),
67
+ "hint": "Send a 10-digit Indian mobile number.",
68
+ },
69
+ "aadhaar_info": {
70
+ "url": "https://aadhaar.asurpapa.workers.dev/api",
71
+ "param": "aadhaar",
72
+ "pattern": re.compile(r"^\d{12}$"),
73
+ "hint": "Send a 12-digit Aadhaar number.",
74
+ },
75
+ "aadhaar_family": {
76
+ "url": "https://aadhaar-family.asurpapa.workers.dev/api",
77
+ "param": "aadhaar",
78
+ "pattern": re.compile(r"^\d{12}$"),
79
+ "hint": "Send a 12-digit Aadhaar number.",
80
+ },
81
+ "aadhaar_ration": {
82
+ "url": "https://ration-card.asurpapa.workers.dev/api",
83
+ "param": "aadhar", # single-a — upstream typo, must match
84
+ "pattern": re.compile(r"^\d{12}$"),
85
+ "hint": "Send a 12-digit Aadhaar number.",
86
+ },
87
+ }
88
 
89
+ def _is_ok(body: dict) -> bool:
90
+ s = body.get("status") if isinstance(body, dict) else None
91
+ return s in ("success", True)
92
+
93
+ # ────────────────────────────────────────────────────────────────────
94
+ # IN-MEMORY STATE
95
+ # ────────────────────────────────────────────────────────────────────
96
+ USERS: dict[int, dict] = {}
97
+ USER_STATE: dict[int, dict] = {} # uid -> {"awaiting": api_key}
98
+ ADMIN_SESSIONS: dict[int, float] = {} # uid -> expiry_ts
99
+ ADMIN_FAILS: dict[int, list] = {} # uid -> [ts, ts, ...]
100
+ ADMIN_AWAITING: set[int] = set()
101
+ LOG_DEQUE: deque = deque(maxlen=MAX_INMEM_LOG)
102
+ ADMIN_AUDIT: deque = deque(maxlen=1000)
103
+
104
+ # ────────────────────────────────────────────────────────────────────
105
+ # HELPERS
106
+ # ────────────────────────────────────────────────────────────────────
107
+ def now_iso():
108
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
109
+
110
+ def record_id(ts_iso: str, uid: int, query: str) -> str:
111
+ h = hashlib.sha1(f"{ts_iso}|{uid}|{query}".encode()).hexdigest()
112
+ return h[:16]
113
+
114
+ def touch_user(uid: int, from_obj: dict):
115
+ u = USERS.setdefault(uid, {
116
+ "user_id": uid,
117
+ "username": from_obj.get("username") or "",
118
+ "first_name": from_obj.get("first_name") or "",
119
+ "first_seen": now_iso(),
120
+ "last_seen": now_iso(),
121
+ "total_searches": 0,
122
+ "last_query_type": "",
123
+ "blocked": False,
124
+ })
125
+ u["last_seen"] = now_iso()
126
+ if from_obj.get("username"):
127
+ u["username"] = from_obj["username"]
128
+ if from_obj.get("first_name"):
129
+ u["first_name"] = from_obj["first_name"]
130
+ return u
131
+
132
+ def make_session_cookie() -> str:
133
+ exp = int(time.time()) + PANEL_SESSION_TTL_MIN * 60
134
+ msg = f"panel:{exp}"
135
+ sig = hmac.new(SESSION_KEY.encode(), msg.encode(), hashlib.sha256).hexdigest()[:24]
136
+ return f"{exp}.{sig}"
137
+
138
+ def check_session_cookie(val: str) -> bool:
139
  try:
140
+ exp_s, sig = val.split(".")
141
+ exp = int(exp_s)
142
+ if exp < time.time():
143
+ return False
144
+ msg = f"panel:{exp}"
145
+ expected = hmac.new(SESSION_KEY.encode(), msg.encode(), hashlib.sha256).hexdigest()[:24]
146
+ return hmac.compare_digest(sig, expected)
147
  except Exception:
148
+ return False
149
 
150
+ def is_admin(uid: int) -> bool:
151
+ exp = ADMIN_SESSIONS.get(uid)
152
+ if not exp:
153
+ return False
154
+ if exp < time.time():
155
+ ADMIN_SESSIONS.pop(uid, None)
156
+ return False
157
+ return True
158
 
159
+ def admin_audit(uid: int, action: str, detail: str = ""):
160
+ ADMIN_AUDIT.appendleft({
161
+ "ts": now_iso(), "user_id": uid, "action": action, "detail": detail,
162
+ })
163
+
164
+ def escape_html(s) -> str:
165
+ if s is None:
166
+ return ""
167
+ s = str(s)
168
+ return (s.replace("&", "&amp;").replace("<", "&lt;")
169
+ .replace(">", "&gt;").replace('"', "&quot;"))
170
+
171
+ def chunk_text(text: str, limit: int = 3800) -> list[str]:
172
+ if len(text) <= limit:
173
+ return [text]
174
+ chunks, buf = [], ""
175
+ for line in text.split("\n"):
176
+ if len(buf) + len(line) + 1 > limit and buf:
177
+ chunks.append(buf); buf = line
178
+ else:
179
+ buf = (buf + "\n" + line) if buf else line
180
+ if buf:
181
+ chunks.append(buf)
182
+ return chunks or [text[:limit]]
183
+
184
+ # ────────────────────────────────────────────────────────────────────
185
+ # UPSTREAM CLIENT
186
+ # ────────────────────────────────────────────────────────────────────
187
+ async def call_upstream(api_key: str, number: str):
188
+ cfg = APIS[api_key]
189
+ params = {"key": API_KEY, cfg["param"]: number}
190
+ redacted_url = f"{cfg['url']}?key=***&{cfg['param']}={number}"
191
+ t0 = time.time()
192
  try:
193
+ async with httpx.AsyncClient(timeout=25.0) as client:
194
+ r = await client.get(cfg["url"], params=params)
195
+ elapsed = int((time.time() - t0) * 1000)
196
+ try:
197
+ body = r.json()
198
+ except Exception:
199
+ body = {"_raw": r.text[:4000]}
200
+ return {
201
+ "http_code": r.status_code,
202
+ "body": body,
203
+ "elapsed_ms": elapsed,
204
+ "req_params": {cfg["param"]: number},
205
+ "req_url_redacted": redacted_url,
206
+ "error": None,
207
+ }
208
+ except Exception as e:
209
+ return {
210
+ "http_code": 0,
211
+ "body": {"error": str(e)},
212
+ "elapsed_ms": int((time.time() - t0) * 1000),
213
+ "req_params": {cfg["param"]: number},
214
+ "req_url_redacted": redacted_url,
215
+ "error": str(e),
216
+ }
217
+
218
+ # ────────────────────────────────────────────────────────────────────
219
+ # FORMATTERS (all HTML — must be escaped)
220
+ # ────────────────────────────────────────────────────────────────────
221
+ def fmt_mobile(body: dict) -> str:
222
+ if not _is_ok(body):
223
+ return "❌ <b>No data found.</b>"
224
+ d = body.get("data") or {}
225
+ lines = [
226
+ f"📱 <b>{escape_html(d.get('name') or 'N/A')}</b>",
227
+ f"<b>Mobile:</b> <code>{escape_html(d.get('mobile') or '')}</code>",
228
+ f"<b>Father:</b> {escape_html(d.get('fname') or 'N/A')}",
229
+ f"<b>Circle:</b> {escape_html(d.get('circle') or 'N/A')}",
230
+ f"<b>Email:</b> {escape_html(d.get('email') or 'N/A')}",
231
+ f"<b>Address:</b> {escape_html(d.get('address') or 'N/A')}",
232
+ ]
233
+ return "\n".join(lines)
234
+
235
+ def fmt_aadhaar_info(body: dict) -> tuple[str, list]:
236
+ if not _is_ok(body):
237
+ return "❌ <b>No data found.</b>", []
238
+ rows = body.get("data") or []
239
+ total = int(body.get("count") or len(rows))
240
+ if not rows:
241
+ return "❌ <b>No records.</b>", []
242
+ preview = rows[:5]
243
+ out = [f"📋 <b>Found {total} record(s).</b> Showing first {len(preview)}:\n"]
244
+ for i, p in enumerate(preview, 1):
245
+ out.append(
246
+ f"{i}. <b>{escape_html(p.get('name') or 'N/A')}</b>\n"
247
+ f" Father: {escape_html(p.get('fathersName') or 'N/A')}\n"
248
+ f" Phone: <code>{escape_html(p.get('phoneNumber') or '')}</code>\n"
249
+ f" Aadhaar: <code>{escape_html(p.get('aadharNumber') or '')}</code>\n"
250
+ f" Address: {escape_html(p.get('address') or 'N/A')}\n"
251
+ )
252
+ if total > len(preview):
253
+ out.append(f"\n…and <b>{total - len(preview)}</b> more. Full data attached below.")
254
+ return "\n".join(out), rows
255
+
256
+ def fmt_aadhaar_family(body: dict) -> str:
257
+ if not _is_ok(body):
258
+ return "❌ <b>No data found.</b>"
259
+ members = body.get("members") or []
260
+ total = body.get("total_records") or len(members)
261
+ aadhar = body.get("aadhar") or ""
262
+ out = [f"👨‍👩‍👧 <b>Family Members ({total})</b>\n"]
263
+ for m in members:
264
+ out.append(
265
+ f"• <b>{escape_html(m.get('name') or 'N/A')}</b> "
266
+ f"<i>({escape_html(m.get('relation') or '')})</i>\n"
267
+ f" UID: <code>{escape_html(m.get('masked_uid') or '')}</code> "
268
+ f"Member: <code>{escape_html(m.get('member_id') or '')}</code>"
269
+ )
270
+ return "\n".join(out)
271
 
272
+ def fmt_aadhaar_ration(body: dict) -> str:
273
+ if not _is_ok(body):
274
+ return "❌ <b>No data found.</b>"
275
+ return "\n".join([
276
+ f"🍚 <b>Ration Card</b>",
277
+ f"<b>Head:</b> {escape_html(body.get('head_family') or 'N/A')}",
278
+ f"<b>Ration No:</b> <code>{escape_html(body.get('ration_number') or '')}</code>",
279
+ f"<b>Application:</b> {escape_html(body.get('application_no') or 'N/A')}",
280
+ f"<b>Scheme:</b> {escape_html(body.get('scheme') or 'N/A')}",
281
+ f"<b>District:</b> {escape_html(body.get('district') or 'N/A')}, {escape_html(body.get('state') or '')}",
282
+ f"<b>FPS:</b> <code>{escape_html(body.get('fps_id') or '')}</code>",
283
+ f"<b>Address:</b> {escape_html(body.get('address') or 'N/A')}",
284
+ ])
285
+
286
+ FORMATTERS = {
287
+ "mobile": lambda b: fmt_mobile(b),
288
+ "aadhaar_info": lambda b: fmt_aadhaar_info(b)[0],
289
+ "aadhaar_family": lambda b: fmt_aadhaar_family(b),
290
+ "aadhaar_ration": lambda b: fmt_aadhaar_ration(b),
291
+ }
292
 
293
+ # ────────────────────────────────────────────────────────────────────
294
+ # LOGGING
295
+ # ────────────────────────────────────────────────────────────────────
296
+ def _rotate_if_needed():
297
  try:
298
+ if not os.path.exists(LOG_FILE_PATH):
299
+ return
300
+ if os.path.getsize(LOG_FILE_PATH) < LOG_ROTATE_MB * 1024 * 1024:
301
+ return
302
+ # shift: .3 -> delete, .2 -> .3, .1 -> .2, current -> .1
303
+ for i in range(LOG_KEEP_ROTATED, 0, -1):
304
+ src = f"{LOG_FILE_PATH}.{i}"
305
+ dst = f"{LOG_FILE_PATH}.{i+1}"
306
+ if os.path.exists(src):
307
+ if i == LOG_KEEP_ROTATED:
308
+ os.remove(src)
309
+ else:
310
+ os.rename(src, dst)
311
+ os.rename(LOG_FILE_PATH, f"{LOG_FILE_PATH}.1")
312
  except Exception as e:
313
+ log.warning(f"rotation failed: {e}")
 
 
 
 
 
 
 
 
 
314
 
315
+ def write_log_record(rec: dict):
316
+ LOG_DEQUE.append(rec)
317
  try:
318
+ _rotate_if_needed()
319
+ with open(LOG_FILE_PATH, "a", encoding="utf-8") as f:
320
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
321
+ except Exception as e:
322
+ log.warning(f"log write failed: {e}")
 
 
 
 
 
 
 
 
323
 
324
+ async def mirror_log(rec: dict):
325
+ if not LOG_CHAT_ID:
326
+ return
 
327
  try:
328
+ line = (
329
+ f"<code>{rec['ts_utc']}</code> "
330
+ f"<b>{rec['type']}</b> "
331
+ f"u=<code>{rec['user_id']}</code> "
332
+ f"q=<code>{escape_html(rec['query'])}</code> "
333
+ f"{rec['status']} {rec['elapsed_ms']}ms"
334
+ )
335
+ await tg_send_message(int(LOG_CHAT_ID), line, parse_mode="HTML")
336
  except Exception as e:
337
+ log.warning(f"mirror failed: {e}")
 
338
 
339
+ # ────────────────────────────────────────────────────────────────────
340
+ # TELEGRAM API
341
+ # ────────────────────────────────────────────────────────────────────
342
+ TG_API = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}"
343
 
344
+ async def tg_call(method: str, payload: dict, timeout: float = 20.0):
345
+ async with httpx.AsyncClient(timeout=timeout) as client:
346
+ r = await client.post(f"{TG_API}/{method}", json=payload)
347
+ try:
348
+ return r.json()
349
+ except Exception:
350
+ return {"ok": False, "status": r.status_code}
351
+
352
+ async def tg_send_message(chat_id: int, text: str, parse_mode: str = "HTML",
353
+ reply_markup: Optional[dict] = None) -> list:
354
+ """Split long text and send each chunk. Returns last result(s)."""
355
+ results = []
356
+ for chunk in chunk_text(text, 3800):
357
+ payload = {"chat_id": chat_id, "text": chunk, "parse_mode": parse_mode,
358
+ "disable_web_page_preview": True}
359
  if reply_markup:
360
  payload["reply_markup"] = reply_markup
361
+ results.append(await tg_call("sendMessage", payload))
362
+ return results
363
+
364
+ async def tg_send_document(chat_id: int, file_path: str, filename: str, caption: str = ""):
365
+ async with httpx.AsyncClient(timeout=180.0) as client:
366
+ with open(file_path, "rb") as f:
367
+ files = {"document": (filename, f, "application/gzip")}
368
+ data = {"chat_id": str(chat_id)}
369
+ if caption:
370
+ data["caption"] = caption[:1024]
371
+ r = await client.post(f"{TG_API}/sendDocument", data=data, files=files)
372
+ try:
373
+ return r.json()
374
+ except Exception:
375
+ return {"ok": False, "status": r.status_code}
376
 
377
+ async def tg_answer_callback(cb_id: str, text: str = ""):
378
+ await tg_call("answerCallbackQuery", {"callback_query_id": cb_id, "text": text})
379
 
380
+ # ────────────────────────────────────────────────────────────────────
381
+ # BOT HANDLERS
382
+ # ────────────────────────────────────────────────────────────────────
383
+ SERVICES_MENU = {
384
+ "inline_keyboard": [
385
+ [{"text": "📱 Mobile → Info", "callback_data": "svc:mobile"}],
386
+ [{"text": "🆔 Aadhaar → Info", "callback_data": "svc:aadhaar_info"}],
387
+ [{"text": "👨‍👩‍👧 Aadhaar → Family", "callback_data": "svc:aadhaar_family"}],
388
+ [{"text": "🍚 Aadhaar → Ration", "callback_data": "svc:aadhaar_ration"}],
389
+ ]
390
+ }
391
 
392
+ async def do_query(uid: int, chat_id: int, api_key: str, number: str):
393
+ cfg = APIS[api_key]
394
+ if not cfg["pattern"].match(number):
395
+ await tg_send_message(chat_id, f"❌ {cfg['hint']}")
396
+ return
 
 
 
 
 
397
 
398
+ up = await call_upstream(api_key, number)
399
+ body = up["body"]
400
+ ok = _is_ok(body) and up["http_code"] == 200
401
+ status = "success" if ok else "fail"
402
 
 
 
 
 
 
 
403
  try:
404
+ bot_reply = FORMATTERS[api_key](body)
 
 
 
 
 
 
 
405
  except Exception as e:
406
+ bot_reply = f"❌ Format error: {escape_html(str(e))}"
407
+
408
+ ts_iso = now_iso()
409
+ rec = {
410
+ "id": record_id(ts_iso, uid, number),
411
+ "ts_utc": ts_iso,
412
+ "ts_local": datetime.now().astimezone().isoformat(timespec="seconds"),
413
+ "user_id": uid,
414
+ "username": USERS.get(uid, {}).get("username", ""),
415
+ "type": api_key,
416
+ "query": number,
417
+ "req_url_redacted": up["req_url_redacted"],
418
+ "req_params": up["req_params"],
419
+ "http_code": up["http_code"],
420
+ "status": status,
421
+ "resp_body": body,
422
+ "elapsed_ms": up["elapsed_ms"],
423
+ "bot_reply_html": bot_reply,
424
+ }
425
+ write_log_record(rec)
426
+ asyncio.create_task(mirror_log(rec))
427
+
428
+ # update user stats
429
+ u = USERS.get(uid)
430
+ if u:
431
+ u["total_searches"] += 1
432
+ u["last_query_type"] = api_key
433
+
434
+ # send reply
435
+ if not ok:
436
+ err = body.get("error") if isinstance(body, dict) else "unknown"
437
+ await tg_send_message(chat_id, f"❌ Query failed.\n<code>{escape_html(err or 'no data')}</code>")
438
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
 
440
+ await tg_send_message(chat_id, bot_reply)
441
 
442
+ # For aadhaar_info: attach full JSON as file if truncated
443
+ if api_key == "aadhaar_info" and len(body.get("data") or []) > 5:
444
+ try:
445
+ full_path = "/tmp/_aadhaar_full.json"
446
+ with open(full_path, "w", encoding="utf-8") as f:
447
+ json.dump(body, f, indent=2, ensure_ascii=False)
448
+ await tg_send_document(chat_id, full_path, "aadhaar_full.json",
449
+ caption=f"Full records for {number}")
450
+ except Exception as e:
451
+ log.warning(f"attach failed: {e}")
452
+
453
+ async def handle_start(uid: int, chat_id: int):
454
+ await tg_send_message(
455
  chat_id,
456
+ "👋 <b>Welcome!</b>\n\nChoose a service and I'll ask for the number:",
457
+ reply_markup=SERVICES_MENU,
 
458
  )
459
 
460
+ async def handle_command(uid: int, chat_id: int, cmd: str, text: str, msg: dict):
461
+ if cmd == "start":
462
+ await handle_start(uid, chat_id)
463
+ return
464
+ if cmd == "help":
465
+ await tg_send_message(chat_id,
466
+ "Send /start to choose a service.\n"
467
+ "Admin: /admin")
468
+ return
469
+ if cmd == "cancel":
470
+ USER_STATE.pop(uid, None)
471
+ ADMIN_AWAITING.discard(uid)
472
+ await tg_send_message(chat_id, "Cancelled.")
473
+ return
474
 
475
+ # Admin commands
476
+ if cmd == "admin":
477
+ ADMIN_AWAITING.add(uid)
478
+ await tg_send_message(chat_id, "🔐 Enter admin secret code:")
479
+ return
480
+ if cmd == "logout":
481
+ ADMIN_SESSIONS.pop(uid, None)
482
+ await tg_send_message(chat_id, "✅ Logged out.")
483
+ admin_audit(uid, "logout")
484
+ return
485
 
486
+ if cmd in ("logs", "logstats", "export", "clear_cache", "help_admin"):
487
+ if not is_admin(uid):
488
+ await tg_send_message(chat_id, "❌ Not authenticated. Use /admin first.")
489
+ return
490
+ await handle_admin_command(uid, chat_id, cmd, text)
491
+ return
492
 
493
+ await tg_send_message(chat_id, "Unknown command. Send /start.")
494
+
495
+ async def handle_admin_command(uid: int, chat_id: int, cmd: str, text: str):
496
+ admin_audit(uid, cmd, text)
497
+ if cmd == "help_admin":
498
+ await tg_send_message(chat_id,
499
+ "<b>Admin commands:</b>\n"
500
+ "/logs — full log (gzipped .jsonl)\n"
501
+ "/logs N — last N records (max 100)\n"
502
+ "/logs YYYY-MM-DD YYYY-MM-DD — date range\n"
503
+ "/logstats — counts + memory\n"
504
+ "/export users — users CSV\n"
505
+ "/export searches — searches CSV\n"
506
+ "/clear_cache — flush in-memory cache\n"
507
+ "/logout — end session")
508
+ return
509
+ if cmd == "logstats":
510
+ total_searches = sum(u["total_searches"] for u in USERS.values())
511
+ try:
512
+ size = os.path.getsize(LOG_FILE_PATH) if os.path.exists(LOG_FILE_PATH) else 0
513
+ except Exception:
514
+ size = 0
515
+ rotated = sum(1 for i in range(1, LOG_KEEP_ROTATED + 1)
516
+ if os.path.exists(f"{LOG_FILE_PATH}.{i}"))
517
+ await tg_send_message(chat_id,
518
+ f"📊 <b>Log Stats</b>\n"
519
+ f"Memory: {len(LOG_DEQUE)}/{MAX_INMEM_LOG} records\n"
520
+ f"File: {size/1e6:.2f} MB\n"
521
+ f"Rotated: {rotated} files\n"
522
+ f"Retention: {LOG_RETENTION_DAYS} days\n"
523
+ f"Users: {len(USERS)}\n"
524
+ f"Total searches: {total_searches}")
525
+ return
526
+ if cmd == "clear_cache":
527
+ n = len(LOG_DEQUE); LOG_DEQUE.clear()
528
+ await tg_send_message(chat_id, f"🧹 Cache cleared ({n} records from memory). File untouched.")
529
+ return
530
+ if cmd == "export":
531
+ parts = text.split()
532
+ what = parts[1].lower() if len(parts) > 1 else ""
533
+ if what == "users":
534
+ path = "/tmp/users_export.csv"
535
+ with open(path, "w", newline="", encoding="utf-8") as f:
536
+ w = csv.DictWriter(f, fieldnames=["user_id","username","first_name","first_seen","last_seen","total_searches","blocked"])
537
+ w.writeheader()
538
+ for u in USERS.values(): w.writerow(u)
539
+ await tg_send_document(chat_id, path, "users.csv", caption=f"{len(USERS)} users")
540
+ elif what == "searches":
541
+ path = "/tmp/searches_export.csv"
542
+ with open(path, "w", newline="", encoding="utf-8") as f:
543
+ cols = ["id","ts_utc","user_id","username","type","query","http_code","status","elapsed_ms","req_url_redacted"]
544
+ w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
545
+ w.writeheader()
546
+ for r in LOG_DEQUE: w.writerow(r)
547
+ await tg_send_document(chat_id, path, "searches.csv", caption=f"{len(LOG_DEQUE)} records")
548
+ else:
549
+ await tg_send_message(chat_id, "Usage: /export users | /export searches")
550
+ return
551
+ if cmd == "logs":
552
+ await handle_logs(chat_id, text)
553
+ return
554
 
555
+ async def handle_logs(chat_id: int, text: str):
556
+ parts = text.split()
557
+ args = parts[1:] if len(parts) > 1 else []
558
+
559
+ # Determine record set
560
+ records = None # None => use full file
561
+ if len(args) == 1 and args[0].isdigit():
562
+ n = min(int(args[0]), 100)
563
+ records = list(LOG_DEQUE)[-n:]
564
+ if not records:
565
+ await tg_send_message(chat_id, "No records in memory.")
566
+ return
567
+ elif len(args) == 2:
568
+ try:
569
+ from_dt = datetime.strptime(args[0], "%Y-%m-%d").replace(tzinfo=timezone.utc)
570
+ to_dt = datetime.strptime(args[1], "%Y-%m-%d").replace(tzinfo=timezone.utc) + timedelta(days=1)
571
+ except Exception:
572
+ await tg_send_message(chat_id, "❌ Date format: /logs YYYY-MM-DD YYYY-MM-DD")
573
+ return
574
+ records = []
575
+ for r in list(LOG_DEQUE):
576
+ try:
577
+ ts = datetime.fromisoformat(r["ts_utc"])
578
+ if from_dt <= ts < to_dt: records.append(r)
579
+ except Exception:
580
+ pass
581
+ if not records:
582
+ await tg_send_message(chat_id, "No records in range.")
583
+ return
584
+
585
+ # Write raw jsonl
586
+ if records is not None:
587
+ raw_path = "/tmp/_logs_selected.jsonl"
588
+ with open(raw_path, "w", encoding="utf-8") as f:
589
+ for r in records:
590
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
591
+ src = raw_path
592
+ base_name = "logs_selected"
593
+ else:
594
+ if not os.path.exists(LOG_FILE_PATH):
595
+ await tg_send_message(chat_id, "Log file not found.")
596
+ return
597
+ src = LOG_FILE_PATH
598
+ base_name = "bot_logs"
599
+
600
+ # Gzip
601
+ gz_path = f"/tmp/{base_name}.jsonl.gz"
602
+ with open(src, "rb") as fi, gzip.open(gz_path, "wb") as fo:
603
+ fo.write(fi.read())
604
+
605
+ size = os.path.getsize(gz_path)
606
+ max_send = 45 * 1024 * 1024
607
+
608
+ if size <= max_send:
609
+ await tg_send_document(chat_id, gz_path, f"{base_name}.jsonl.gz",
610
+ caption=f"{size/1024:.1f} KB")
611
+ return
612
 
613
+ # Split raw file into 40MB chunks, gzip each
614
+ with open(src, "rb") as f:
615
+ raw = f.read()
616
+ limit = 40 * 1024 * 1024
617
+ chunks, cur, cur_size = [], [], 0
618
+ for line in raw.split(b"\n"):
619
+ add = len(line) + 1
620
+ if cur_size + add > limit and cur:
621
+ chunks.append(b"\n".join(cur)); cur, cur_size = [line], add
622
+ else:
623
+ cur.append(line); cur_size += add
624
+ if cur:
625
+ chunks.append(b"\n".join(cur))
626
+
627
+ await tg_send_message(chat_id, f"📦 File is {size/1e6:.1f} MB — splitting into {len(chunks)} parts.")
628
+ for i, chunk in enumerate(chunks, 1):
629
+ part_raw = f"/tmp/_part_{i}.jsonl"
630
+ part_gz = f"/tmp/_part_{i}.jsonl.gz"
631
+ with open(part_raw, "wb") as f: f.write(chunk)
632
+ with gzip.open(part_gz, "wb") as fo:
633
+ with open(part_raw, "rb") as fi: fo.write(fi.read())
634
+ await tg_send_document(chat_id, part_gz, f"{base_name}_part{i}.jsonl.gz",
635
+ caption=f"Part {i}/{len(chunks)}")
636
+ await asyncio.sleep(1.0)
637
+
638
+ async def handle_admin_secret(uid: int, chat_id: int, code: str):
639
+ ADMIN_AWAITING.discard(uid)
640
  now = time.time()
641
+ fails = [t for t in ADMIN_FAILS.get(uid, []) if now - t < 600]
 
 
642
  if len(fails) >= ADMIN_MAX_FAILS:
643
+ await tg_send_message(chat_id, "❌ Too many attempts. Try again in 10 minutes.")
 
644
  return
645
 
646
+ ok_full = hmac.compare_digest(code, ADMIN_SECRET)
647
+ ok_view = bool(VIEWER_SECRET) and hmac.compare_digest(code, VIEWER_SECRET)
648
+
649
+ if ok_full or ok_view:
650
+ ADMIN_SESSIONS[uid] = now + ADMIN_SESSION_TTL_MIN * 60
651
+ ADMIN_FAILS.pop(uid, None)
652
+ admin_audit(uid, "admin_login", "full" if ok_full else "viewer")
653
+ await tg_send_message(chat_id,
654
+ f"✅ Authenticated ({'full' if ok_full else 'viewer'}). Valid {ADMIN_SESSION_TTL_MIN} min.\n"
655
+ "Commands: /logs, /logstats, /export, /clear_cache, /logout, /help_admin")
 
 
 
 
 
656
  else:
657
  fails.append(now)
658
+ ADMIN_FAILS[uid] = fails
659
+ remaining = ADMIN_MAX_FAILS - len(fails)
660
+ if len(fails) >= ADMIN_MAX_FAILS:
661
+ await tg_send_message(chat_id, "❌ Invalid. Locked for 10 minutes.")
662
+ if LOG_CHAT_ID:
663
+ asyncio.create_task(tg_send_message(int(LOG_CHAT_ID),
664
+ f"⚠️ Admin fails x{len(fails)} from uid <code>{uid}</code>"))
665
+ else:
666
+ await tg_send_message(chat_id, f"❌ Invalid. {remaining} attempt(s) left.")
667
+
668
+ async def handle_message(msg: dict):
669
+ uid = msg["from"]["id"]
670
+ chat_id = msg["chat"]["id"]
671
+ text = (msg.get("text") or "").strip()
672
+
673
+ touch_user(uid, msg.get("from", {}))
674
+
675
+ if text.startswith("/"):
676
+ cmd = text.split()[0][1:].split("@")[0]
677
+ await handle_command(uid, chat_id, cmd, text, msg)
678
+ return
679
 
680
+ if uid in ADMIN_AWAITING:
681
+ await handle_admin_secret(uid, chat_id, text)
682
+ return
683
 
684
+ st = USER_STATE.get(uid)
685
+ if st and st.get("awaiting"):
686
+ api_key = st["awaiting"]
687
+ USER_STATE.pop(uid, None)
688
+ await do_query(uid, chat_id, api_key, text)
689
+ return
690
 
691
+ await tg_send_message(chat_id,
692
+ "Send /start to choose a service.",
693
+ reply_markup=SERVICES_MENU)
694
+
695
+ async def handle_callback(cb: dict):
696
+ uid = cb["from"]["id"]
697
+ data = cb.get("data", "")
698
+ cb_id = cb["id"]
699
+ chat_id = cb["message"]["chat"]["id"]
700
+
701
+ touch_user(uid, cb.get("from", {}))
702
+
703
+ if data.startswith("svc:"):
704
+ api_key = data.split(":", 1)[1]
705
+ if api_key not in APIS:
706
+ await tg_answer_callback(cb_id, "Unknown service")
707
+ return
708
+ USER_STATE[uid] = {"awaiting": api_key}
709
+ await tg_answer_callback(cb_id, "OK")
710
+ await tg_send_message(chat_id, f"📥 {APIS[api_key]['hint']}")
711
  return
712
+ await tg_answer_callback(cb_id)
713
+
714
+ # ────────────────────────────────────────────────────────────────────
715
+ # FASTAPI + GRADIO
716
+ # ────────────────────────────────────────────────────────────────────
717
+ fastapi_app = FastAPI(title="Log Bot", docs_url=None, redoc_url=None)
718
+
719
+ class PanelAuthMiddleware(BaseHTTPMiddleware):
720
+ async def dispatch(self, request: Request, call_next):
721
+ path = request.url.path
722
+ public = (
723
+ path == "/" or path == "/health" or path == "/telegram"
724
+ or path == "/robots.txt" or path.startswith("/gradio")
725
+ )
726
+ if public:
727
+ return await call_next(request)
728
+
729
+ if path == "/panel" or path.startswith("/api/"):
730
+ # IP allowlist
731
+ if PANEL_ALLOWED_IPS:
732
+ ip = (request.headers.get("x-forwarded-for", "").split(",")[0].strip()
733
+ or (request.client.host if request.client else ""))
734
+ if ip not in PANEL_ALLOWED_IPS:
735
+ return PlainTextResponse("Forbidden", status_code=403)
736
+
737
+ # Token in query
738
+ token = request.query_params.get("token", "")
739
+ if token and hmac.compare_digest(token, PANEL_TOKEN):
740
+ return await call_next(request)
741
+
742
+ # Session cookie
743
+ cookie = request.cookies.get("panel_session", "")
744
+ if cookie and check_session_cookie(cookie):
745
+ return await call_next(request)
746
+
747
+ # Basic auth -> set cookie
748
+ auth = request.headers.get("authorization", "")
749
+ if auth.startswith("Basic "):
750
+ try:
751
+ decoded = base64.b64decode(auth[6:]).decode()
752
+ _, pw = decoded.split(":", 1)
753
+ if hmac.compare_digest(pw, PANEL_TOKEN):
754
+ resp = await call_next(request)
755
+ resp.set_cookie("panel_session", make_session_cookie(),
756
+ max_age=PANEL_SESSION_TTL_MIN * 60,
757
+ httponly=True, samesite="lax")
758
+ return resp
759
+ except Exception:
760
+ pass
761
+ return Response("Unauthorized", status_code=401,
762
+ headers={"WWW-Authenticate": 'Basic realm="panel"'})
763
+
764
+ return await call_next(request)
765
+
766
+ fastapi_app.add_middleware(PanelAuthMiddleware)
767
+
768
+ # ── Webhook ──
769
+ @fastapi_app.post("/telegram")
770
+ async def telegram_webhook(request: Request):
771
+ try:
772
+ data = await request.json()
773
+ except Exception:
774
+ return {"ok": False}
775
+ try:
776
+ if "message" in data:
777
+ await handle_message(data["message"])
778
+ elif "callback_query" in data:
779
+ await handle_callback(data["callback_query"])
780
+ except Exception as e:
781
+ log.exception(f"webhook error: {e}")
782
+ return {"ok": True}
783
+
784
+ @fastapi_app.get("/health")
785
+ async def health():
786
+ return {
787
+ "ok": True,
788
+ "started_at": STARTED_AT.isoformat(),
789
+ "inmem": len(LOG_DEQUE),
790
+ }
791
+
792
+ @fastapi_app.get("/robots.txt", response_class=PlainTextResponse)
793
+ async def robots():
794
+ return "User-agent: *\nDisallow: /\n"
795
+
796
+ @fastapi_app.get("/", response_class=HTMLResponse)
797
+ async def root():
798
+ return f"""<!doctype html><html><head><title>Log Bot</title></head>
799
+ <body style="font-family:system-ui;background:#111;color:#eee;padding:2rem;">
800
+ <h1>🤖 Log Bot</h1>
801
+ <p>Running. Started {STARTED_AT.isoformat()}</p>
802
+ <p>Admin panel: <a style="color:#6cf" href="/panel">/panel</a></p>
803
+ <p>Health: <a style="color:#6cf" href="/health">/health</a></p>
804
+ </body></html>"""
805
+
806
+ # ── Panel routes ──
807
+ PANEL_HTML_PATH = "panel.html"
808
+
809
+ @fastapi_app.get("/panel", response_class=HTMLResponse)
810
+ async def panel(request: Request):
811
+ try:
812
+ with open(PANEL_HTML_PATH, "r", encoding="utf-8") as f:
813
+ html = f.read()
814
+ except Exception:
815
+ return HTMLResponse("<h1>panel.html missing</h1>", status_code=500)
816
+ resp = HTMLResponse(html, headers={"X-Robots-Tag": "noindex, nofollow"})
817
+ return resp
818
+
819
+ @fastapi_app.get("/api/stats")
820
+ async def api_stats():
821
+ now = datetime.now(timezone.utc)
822
+ today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
823
+ day_ago = now - timedelta(hours=24)
824
+ total = sum(u["total_searches"] for u in USERS.values())
825
+ today = 0; last24 = 0; errors = 0
826
+ for r in LOG_DEQUE:
827
+ try:
828
+ ts = datetime.fromisoformat(r["ts_utc"])
829
+ except Exception:
830
+ continue
831
+ if ts >= today_start: today += 1
832
+ if ts >= day_ago: last24 += 1
833
+ if r.get("status") != "success": errors += 1
834
+ try:
835
+ size = os.path.getsize(LOG_FILE_PATH) if os.path.exists(LOG_FILE_PATH) else 0
836
+ except Exception:
837
+ size = 0
838
+ return {
839
+ "total_users": len(USERS),
840
+ "total_searches": total,
841
+ "today": today,
842
+ "last_24h": last24,
843
+ "errors": errors,
844
+ "inmem_count": len(LOG_DEQUE),
845
+ "max_inmem": MAX_INMEM_LOG,
846
+ "log_file_mb": round(size / 1e6, 3),
847
+ "since": STARTED_AT.isoformat(),
848
+ }
849
+
850
+ def _filter_searches(q_type, q_status, q_user, q_from, q_to):
851
+ out = []
852
+ for r in LOG_DEQUE:
853
+ if q_type and r.get("type") != q_type: continue
854
+ if q_status and r.get("status") != q_status: continue
855
+ if q_user:
856
+ try:
857
+ if int(r.get("user_id")) != int(q_user): continue
858
+ except Exception:
859
+ continue
860
+ if q_from or q_to:
861
+ try:
862
+ ts = datetime.fromisoformat(r["ts_utc"])
863
+ except Exception:
864
+ continue
865
+ if q_from:
866
+ try:
867
+ f = datetime.strptime(q_from, "%Y-%m-%d").replace(tzinfo=timezone.utc)
868
+ if ts < f: continue
869
+ except Exception: pass
870
+ if q_to:
871
+ try:
872
+ t = datetime.strptime(q_to, "%Y-%m-%d").replace(tzinfo=timezone.utc) + timedelta(days=1)
873
+ if ts >= t: continue
874
+ except Exception: pass
875
+ out.append(r)
876
+ return out
877
+
878
+ @fastapi_app.get("/api/searches")
879
+ async def api_searches(request: Request):
880
+ q = request.query_params
881
+ page = max(1, int(q.get("page", "1")))
882
+ per_page = min(200, max(10, int(q.get("per_page", "50"))))
883
+ rows = _filter_searches(
884
+ q.get("type", ""), q.get("status", ""), q.get("user", ""),
885
+ q.get("from", ""), q.get("to", ""),
886
  )
887
+ total = len(rows)
888
+ start = (page - 1) * per_page
889
+ page_rows = rows[start:start + per_page]
890
+ # don't send resp_body in list view — too big
891
+ slim = [{k: r.get(k) for k in
892
+ ("id","ts_utc","ts_local","user_id","username","type","query",
893
+ "status","http_code","elapsed_ms")} for r in page_rows]
894
+ return {"total": total, "page": page, "per_page": per_page, "rows": slim}
895
+
896
+ @fastapi_app.get("/api/search/{rid}")
897
+ async def api_search_one(rid: str):
898
+ for r in LOG_DEQUE:
899
+ if r.get("id") == rid:
900
+ return r
901
+ raise HTTPException(404, "not found")
902
+
903
+ @fastapi_app.get("/api/users")
904
+ async def api_users(request: Request):
905
+ page = max(1, int(request.query_params.get("page", "1")))
906
+ per_page = min(200, max(10, int(request.query_params.get("per_page", "50"))))
907
+ rows = sorted(USERS.values(), key=lambda u: u["last_seen"], reverse=True)
908
+ total = len(rows)
909
+ start = (page - 1) * per_page
910
+ return {"total": total, "page": page, "per_page": per_page,
911
+ "rows": rows[start:start + per_page]}
912
+
913
+ @fastapi_app.get("/api/audit")
914
+ async def api_audit():
915
+ return {"rows": list(ADMIN_AUDIT)[:500]}
916
+
917
+ # ── Downloads ──
918
+ @fastapi_app.get("/api/logs/download")
919
+ async def api_logs_download(request: Request):
920
+ fmt = request.query_params.get("format", "jsonl").lower()
921
+ limit = request.query_params.get("limit", "")
922
+ rows = list(LOG_DEQUE)
923
+ if limit.isdigit():
924
+ rows = rows[-int(limit):]
925
+ admin_audit(0, "panel_download", f"logs {fmt} n={len(rows)}")
926
+
927
+ if fmt == "csv":
928
+ buf = io.StringIO()
929
+ cols = ["id","ts_utc","user_id","username","type","query","http_code","status","elapsed_ms","req_url_redacted"]
930
+ w = csv.DictWriter(buf, fieldnames=cols, extrasaction="ignore")
931
+ w.writeheader()
932
+ for r in rows: w.writerow(r)
933
+ data = buf.getvalue().encode()
934
+ return StreamingResponse(io.BytesIO(data), media_type="text/csv",
935
+ headers={"Content-Disposition": 'attachment; filename="searches.csv"'})
936
+
937
+ # jsonl (gzipped)
938
+ raw = ("\n".join(json.dumps(r, ensure_ascii=False) for r in rows)).encode()
939
+ gz = gzip.compress(raw)
940
+ return StreamingResponse(io.BytesIO(gz), media_type="application/gzip",
941
+ headers={"Content-Disposition": 'attachment; filename="searches.jsonl.gz"'})
942
+
943
+ @fastapi_app.get("/api/users/download")
944
+ async def api_users_download():
945
+ buf = io.StringIO()
946
+ cols = ["user_id","username","first_name","first_seen","last_seen","total_searches","blocked"]
947
+ w = csv.DictWriter(buf, fieldnames=cols, extrasaction="ignore")
948
+ w.writeheader()
949
+ for u in USERS.values(): w.writerow(u)
950
+ admin_audit(0, "panel_download", "users csv")
951
+ data = buf.getvalue().encode()
952
+ return StreamingResponse(io.BytesIO(data), media_type="text/csv",
953
+ headers={"Content-Disposition": 'attachment; filename="users.csv"'})
954
+
955
+ # ────────────────────────────────────────────────────────────────────
956
+ # LIFESPAN
957
+ # ───────────────────────────────────────────────────────────────────��
958
+ async def _set_webhook():
959
+ if not WEBHOOK_BASE_URL or not TELEGRAM_TOKEN:
960
+ log.warning("no WEBHOOK_BASE_URL or TOKEN — skipping setWebhook")
961
  return
962
+ url = WEBHOOK_BASE_URL.rstrip("/") + "/telegram"
963
+ await tg_call("setWebhook", {"url": url, "drop_pending_updates": False})
964
+ log.info(f"webhook set to {url}")
965
+
966
+ async def _retention_task():
967
+ while True:
968
+ try:
969
+ cutoff = datetime.now(timezone.utc) - timedelta(days=LOG_RETENTION_DAYS)
970
+ # trim in-memory
971
+ kept = deque((r for r in LOG_DEQUE
972
+ if datetime.fromisoformat(r["ts_utc"]) >= cutoff),
973
+ maxlen=MAX_INMEM_LOG)
974
+ LOG_DEQUE.clear(); LOG_DEQUE.extend(kept)
975
+ # delete old rotated files
976
+ for i in range(1, LOG_KEEP_ROTATED + 1):
977
+ p = f"{LOG_FILE_PATH}.{i}"
978
+ if os.path.exists(p):
979
+ mtime = datetime.fromtimestamp(os.path.getmtime(p), tz=timezone.utc)
980
+ if mtime < cutoff:
981
+ try: os.remove(p)
982
+ except Exception: pass
983
+ except Exception as e:
984
+ log.warning(f"retention error: {e}")
985
+ await asyncio.sleep(3600 * 6)
986
+
987
+ @fastapi_app.on_event("startup")
988
+ async def _startup():
989
+ os.makedirs(os.path.dirname(LOG_FILE_PATH) or ".", exist_ok=True)
990
  try:
991
+ with open(LOG_FILE_PATH, "a"): pass
992
+ except Exception as e:
993
+ log.warning(f"cannot write {LOG_FILE_PATH}: {e}")
994
+ log.info(f"started; ADMIN_SECRET set={bool(ADMIN_SECRET)}; LOG_CHAT_ID={bool(LOG_CHAT_ID)}")
995
+ asyncio.create_task(_set_webhook())
996
+ asyncio.create_task(_retention_task())
997
+ if LOG_CHAT_ID:
998
+ asyncio.create_task(tg_send_message(int(LOG_CHAT_ID),
999
+ f"✅ Bot started at {STARTED_AT.isoformat()}"))
1000
+
1001
+ @fastapi_app.on_event("shutdown")
1002
+ async def _shutdown():
1003
+ if LOG_CHAT_ID:
1004
+ try:
1005
+ await tg_send_message(int(LOG_CHAT_ID), f"🛑 Bot shutting down at {now_iso()}")
1006
+ except Exception:
1007
+ pass
1008
+
1009
+ # ────────────────────────────────────────────────────────────────────
1010
+ # GRADIO (minimal — just a status page at /gradio)
1011
+ # ────────────────────────────────────────────────────────────────────
1012
+ def build_gradio():
1013
+ with gr.Blocks(title="Log Bot") as demo:
1014
+ gr.Markdown(
1015
+ "# 🤖 Log Bot\n\n"
1016
+ "Running on HF Spaces.\n\n"
1017
+ "- Telegram webhook: `/telegram`\n"
1018
+ "- Admin panel: [`/panel`](/panel)\n"
1019
+ "- Health: [`/health`](/health)"
1020
+ )
1021
+ with gr.Row():
1022
+ gr.Textbox(label="Status", value="running", interactive=False)
1023
+ return demo
1024
+
1025
+ demo = build_gradio()
1026
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/gradio")
1027
+
1028
+ if __name__ == "__main__":
1029
+ import uvicorn
1030
+ uvicorn.run(app, host="0.0.0.0", port=7860)