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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """bot_state.py — Shared state, locks, TG helpers, activity tracking,
2
+ bans, maintenance, admin auth, quota, flood, dedup, cache GC.
3
+
4
+ This module has NO imports from bot.py.
5
+ The handler file (bot.py) imports from here and re-exports.
6
+ """
7
+ import logging
8
+ import threading
9
+ import time
10
+ from collections import deque, Counter
11
+
12
+ import httpx
13
+
14
+ from config import (
15
+ TELEGRAM_API, OWNER_IDS, FORCE_JOIN_CHANNEL,
16
+ MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL,
17
+ FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC,
18
+ DAILY_QUOTA, DAILY_QUOTA_ADMIN,
19
+ LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX,
20
+ ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL, SEARCH_CACHE_TTL,
21
+ )
22
+ from engine import esc
23
+
24
+ log = logging.getLogger("bot_state")
25
+
26
+ # ══════════════════════════════════════════════════════════════════
27
+ # STATE
28
+ # ══════════════════════════════════════════════════════════════════
29
+ ACTIVITY_LOG = deque(maxlen=ACTIVITY_LOG_MAX)
30
+ ACTIVE_USERS = {}
31
+ UNIQUE_USERS = {}
32
+ PHONE_COUNTS = Counter()
33
+ PEAK_CONCURRENT = 0
34
+ _activity_lock = threading.Lock()
35
+
36
+ _admin_lock = threading.Lock()
37
+ _admin_sessions = {}
38
+ _admin_states = {}
39
+
40
+ BANNED_USERS = set()
41
+ BAN_REASONS = {}
42
+ MAINTENANCE_MODE = False
43
+ MAINTENANCE_REASON = ""
44
+ _state_lock = threading.Lock()
45
+
46
+ USER_HISTORY = {}
47
+ SEARCH_CACHE = {}
48
+ SEARCH_CACHE_LOCK = threading.Lock()
49
+ USER_LAST = {}
50
+ STATS = {"queries": 0, "timeouts": 0, "errors": 0, "backup_sent": 0,
51
+ "started": time.time()}
52
+
53
+ _member_cache = {}
54
+ _member_lock = threading.Lock()
55
+ _pending_query = {}
56
+ _pending_lock = threading.Lock()
57
+ _user_daily = {}
58
+ _quota_lock = threading.Lock()
59
+ _user_msg_times = {}
60
+ _muted_until = {}
61
+ _flood_lock = threading.Lock()
62
+ _seen_updates = {}
63
+ _seen_updates_lock = threading.Lock()
64
+
65
+ # ══════════════════════════════════════════════════════════════════
66
+ # TG HELPERS
67
+ # ══════════════════════════════════════════════════════════════════
68
+ async def tg(method, payload, timeout=30):
69
+ try:
70
+ async with httpx.AsyncClient(timeout=timeout) as cli:
71
+ r = await cli.post(f"{TELEGRAM_API}/{method}", json=payload)
72
+ return r.json()
73
+ except Exception as e:
74
+ log.error(f"tg({method}): {e!r}")
75
+ return {"ok": False, "error": str(e)}
76
+
77
+
78
+ async def send(chat_id, text, **kw):
79
+ kw.setdefault("parse_mode", "HTML")
80
+ kw.setdefault("disable_web_page_preview", True)
81
+ kw = {k: v for k, v in kw.items() if v is not None}
82
+ try:
83
+ res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **kw})
84
+ if res.get("ok"):
85
+ return res["result"]["message_id"]
86
+ log.warning(f"sendMessage failed: {res}")
87
+ except Exception as e:
88
+ log.error(f"send error: {e!r}")
89
+ return None
90
+
91
+
92
+ async def edit(chat_id, message_id, text, **kw):
93
+ kw.setdefault("parse_mode", "HTML")
94
+ kw.setdefault("disable_web_page_preview", True)
95
+ kw = {k: v for k, v in kw.items() if v is not None}
96
+ try:
97
+ res = await tg("editMessageText",
98
+ {"chat_id": chat_id, "message_id": message_id,
99
+ "text": text, **kw})
100
+ if not res.get("ok") and "message is not modified" not in str(res):
101
+ log.warning(f"editMessageText failed: {res}")
102
+ except Exception as e:
103
+ log.error(f"edit error: {e!r}")
104
+
105
+
106
+ async def send_document(chat_id, filename, content, caption=""):
107
+ try:
108
+ files = {"document": (filename, content, "application/octet-stream")}
109
+ data = {"chat_id": str(chat_id)}
110
+ if caption:
111
+ data["caption"] = caption[:1024]
112
+ async with httpx.AsyncClient(timeout=60) as cli:
113
+ r = await cli.post(f"{TELEGRAM_API}/sendDocument",
114
+ data=data, files=files)
115
+ res = r.json()
116
+ if not res.get("ok"):
117
+ log.warning(f"sendDocument failed: {res}")
118
+ return res
119
+ except Exception as e:
120
+ log.error(f"sendDocument error: {e!r}")
121
+ return {"ok": False}
122
+
123
+ # ══════════════════════════════════════════════════════════════════
124
+ # SMALL HELPERS
125
+ # ══════════════════════════════════════════════════════════════════
126
+ def _short_user(user_id, user=None):
127
+ info = UNIQUE_USERS.get(user_id) or {}
128
+ username = (user or {}).get("username") or info.get("username")
129
+ first = (user or {}).get("first_name") or info.get("first_name")
130
+ if username:
131
+ return f"@{username} ({user_id})"
132
+ if first:
133
+ return f"{first} ({user_id})"
134
+ return f"({user_id})"
135
+
136
+
137
+ def _fmt_ts(ts):
138
+ return time.strftime("%H:%M:%S", time.localtime(ts))
139
+
140
+
141
+ def _today_utc():
142
+ return time.strftime("%Y-%m-%d", time.gmtime())
143
+
144
+ # ══════════════════════════════════════════════════════════════════
145
+ # UPDATE DEDUP
146
+ # ══════════════════════════════════════════════════════════════════
147
+ def is_duplicate_update(update_id):
148
+ if not update_id:
149
+ return False
150
+ now = time.time()
151
+ with _seen_updates_lock:
152
+ if len(_seen_updates) > 2000:
153
+ cutoff = now - 600
154
+ for k in [k for k, v in _seen_updates.items() if v < cutoff]:
155
+ del _seen_updates[k]
156
+ if update_id in _seen_updates:
157
+ return True
158
+ _seen_updates[update_id] = now
159
+ return False
160
+
161
+ # ══════════════════════════════════════════════════════════════════
162
+ # FORCE-JOIN
163
+ # ══════════════════════════════════════════════════════════════════
164
+ async def _is_channel_member(user_id):
165
+ if not FORCE_JOIN_CHANNEL:
166
+ return True
167
+ now = time.time()
168
+ with _member_lock:
169
+ c = _member_cache.get(user_id)
170
+ if c and now - c[1] < MEMBERSHIP_CACHE_TTL:
171
+ return c[0]
172
+ is_member = False
173
+ try:
174
+ res = await tg("getChatMember",
175
+ {"chat_id": FORCE_JOIN_CHANNEL, "user_id": user_id},
176
+ timeout=10)
177
+ if res.get("ok"):
178
+ status = (res.get("result") or {}).get("status", "")
179
+ is_member = status in ("member", "administrator", "creator")
180
+ except Exception as e:
181
+ log.warning(f"[membership] {e!r}")
182
+ with _member_lock:
183
+ _member_cache[user_id] = (is_member, now)
184
+ return is_member
185
+
186
+
187
+ def _join_url():
188
+ if not FORCE_JOIN_CHANNEL:
189
+ return ""
190
+ if FORCE_JOIN_CHANNEL.startswith("http"):
191
+ return FORCE_JOIN_CHANNEL
192
+ if FORCE_JOIN_CHANNEL.startswith("@"):
193
+ return f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}"
194
+ return "https://t.me/"
195
+
196
+
197
+ async def check_force_join(chat_id, user, text):
198
+ if not FORCE_JOIN_CHANNEL:
199
+ return True
200
+ uid = user.get("id")
201
+ if not uid:
202
+ return True
203
+ if uid in OWNER_IDS:
204
+ return True
205
+ if _is_admin_session(uid):
206
+ return True
207
+ if text.startswith(("/start", "/help", "/myid", "/whoami",
208
+ "/ping", "/info", "/status")):
209
+ return True
210
+ if await _is_channel_member(uid):
211
+ return True
212
+ with _pending_lock:
213
+ _pending_query[uid] = (text, chat_id, time.time())
214
+ url = _join_url()
215
+ await send(chat_id,
216
+ "🔒 <b>Join required</b>\n\n"
217
+ "To use this bot, please join our channel first.\n\n"
218
+ f"👉 {esc(url)}\n\nAfter joining, tap <b>✅ I Joined</b> below.",
219
+ reply_markup={"inline_keyboard": [
220
+ [{"text": "📢 Join Channel", "url": url}],
221
+ [{"text": "✅ I Joined", "callback_data": "join:check"}],
222
+ ]})
223
+ _log_activity(user, "force_join_block", text[:40], "blocked", "not a member")
224
+ return False
225
+
226
+ # ══════════════════════════════════════════════════════════════════
227
+ # QUOTA
228
+ # ══════════════════════════════════════════════════════════════════
229
+ def _is_unlimited(user_id):
230
+ return user_id in OWNER_IDS or _is_admin_session(user_id)
231
+
232
+
233
+ def check_quota(user_id):
234
+ if _is_unlimited(user_id):
235
+ return True, DAILY_QUOTA_ADMIN
236
+ today = _today_utc()
237
+ with _quota_lock:
238
+ e = _user_daily.get(user_id)
239
+ if not e or e[0] != today:
240
+ _user_daily[user_id] = (today, 0)
241
+ return True, DAILY_QUOTA
242
+ if e[1] >= DAILY_QUOTA:
243
+ return False, 0
244
+ return True, DAILY_QUOTA - e[1]
245
+
246
+
247
+ def incr_quota(user_id):
248
+ if _is_unlimited(user_id):
249
+ return
250
+ today = _today_utc()
251
+ with _quota_lock:
252
+ e = _user_daily.get(user_id)
253
+ if not e or e[0] != today:
254
+ _user_daily[user_id] = (today, 1)
255
+ else:
256
+ _user_daily[user_id] = (today, e[1] + 1)
257
+
258
+ # ══════════════════════���═══════════════════════════════════════════
259
+ # FLOOD
260
+ # ══════════════════════════════════════════════════════════════════
261
+ def check_flood(user_id):
262
+ now = time.time()
263
+ with _flood_lock:
264
+ until = _muted_until.get(user_id, 0)
265
+ if until > now:
266
+ return int(until - now)
267
+ dq = _user_msg_times.setdefault(user_id, deque(maxlen=FLOOD_MAX))
268
+ dq.append(now)
269
+ if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW:
270
+ _muted_until[user_id] = now + FLOOD_MUTE_SEC
271
+ return FLOOD_MUTE_SEC
272
+ return None
273
+
274
+ # ══════════════════════════════════════════════════════════════════
275
+ # ACTIVITY
276
+ # ══════════════════════════════════════════════════════════════════
277
+ def _log_activity(user, action, input_val, reply_type, summary="",
278
+ elapsed_ms=0, source=""):
279
+ if not user or "id" not in user:
280
+ return
281
+ now = time.time()
282
+ user_id = user["id"]
283
+ with _activity_lock:
284
+ info = UNIQUE_USERS.setdefault(user_id, {
285
+ "username": None, "first_name": None, "last_name": None,
286
+ "count": 0, "first_seen": now, "last_seen": now,
287
+ })
288
+ if user.get("username"):
289
+ info["username"] = user["username"]
290
+ if user.get("first_name"):
291
+ info["first_name"] = user["first_name"]
292
+ if user.get("last_name"):
293
+ info["last_name"] = user["last_name"]
294
+ info["count"] += 1
295
+ info["last_seen"] = now
296
+ ACTIVE_USERS[user_id] = now
297
+ if (action == "search" and isinstance(input_val, str)
298
+ and input_val.isdigit() and len(input_val) == 10):
299
+ PHONE_COUNTS[input_val] += 1
300
+ ACTIVITY_LOG.append({
301
+ "ts": now, "user_id": user_id,
302
+ "username": user.get("username"),
303
+ "first_name": user.get("first_name"),
304
+ "action": action, "input": (input_val or "")[:80],
305
+ "reply_type": reply_type, "summary": (summary or "")[:150],
306
+ "elapsed_ms": int(elapsed_ms), "source": source,
307
+ })
308
+
309
+
310
+ def _get_live_users():
311
+ cutoff = time.time() - LIVE_WINDOW
312
+ with _activity_lock:
313
+ live = [(uid, ts) for uid, ts in ACTIVE_USERS.items() if ts >= cutoff]
314
+ live.sort(key=lambda x: -x[1])
315
+ return live
316
+
317
+
318
+ def _get_stats():
319
+ now = time.time()
320
+ today_start = now - (now % 86400)
321
+ with _activity_lock:
322
+ today_users = set()
323
+ today_searches = 0
324
+ total_searches = 0
325
+ for e in ACTIVITY_LOG:
326
+ if e["action"] == "search":
327
+ total_searches += 1
328
+ if e["ts"] >= today_start:
329
+ today_searches += 1
330
+ today_users.add(e["user_id"])
331
+ return {
332
+ "unique_users": len(UNIQUE_USERS),
333
+ "live_users": sum(1 for ts in ACTIVE_USERS.values()
334
+ if ts >= now - LIVE_WINDOW),
335
+ "today_users": len(today_users),
336
+ "today_searches": today_searches,
337
+ "total_searches": total_searches,
338
+ "peak_concurrent": PEAK_CONCURRENT,
339
+ "total_log_entries": len(ACTIVITY_LOG),
340
+ "banned_count": len(BANNED_USERS),
341
+ "maintenance": MAINTENANCE_MODE,
342
+ "cached_searches": len(SEARCH_CACHE),
343
+ "backup_sent": STATS["backup_sent"],
344
+ }
345
+
346
+
347
+ def _add_to_history(user_id, phone, count, elapsed, source):
348
+ if user_id is None:
349
+ return
350
+ with _activity_lock:
351
+ h = USER_HISTORY.setdefault(user_id, deque(maxlen=HISTORY_LEN))
352
+ h.appendleft({"phone": phone, "ts": time.time(), "count": count,
353
+ "elapsed": elapsed, "source": source})
354
+
355
+
356
+ def _avg_latency_today():
357
+ now = time.time()
358
+ today_start = now - (now % 86400)
359
+ with _activity_lock:
360
+ vals = [e["elapsed_ms"] for e in ACTIVITY_LOG
361
+ if e["action"] == "search" and e["ts"] >= today_start
362
+ and e["elapsed_ms"] > 0]
363
+ return (sum(vals) / len(vals)) / 1000.0 if vals else 0.0
364
+
365
+ # ══════════════════════════════════════════════════════════════════
366
+ # BAN / MAINTENANCE
367
+ # ══════════════════════════════════════════════════════════════════
368
+ def _is_banned(user_id):
369
+ with _state_lock:
370
+ return user_id in BANNED_USERS
371
+
372
+
373
+ def _ban_user(user_id, reason=""):
374
+ with _state_lock:
375
+ BANNED_USERS.add(user_id)
376
+ BAN_REASONS[user_id] = reason
377
+
378
+
379
+ def _unban_user(user_id):
380
+ with _state_lock:
381
+ if user_id in BANNED_USERS:
382
+ BANNED_USERS.discard(user_id)
383
+ BAN_REASONS.pop(user_id, None)
384
+ return True
385
+ return False
386
+
387
+
388
+ def _get_maintenance():
389
+ with _state_lock:
390
+ return MAINTENANCE_MODE, MAINTENANCE_REASON
391
+
392
+
393
+ def _set_maintenance(on, reason=""):
394
+ global MAINTENANCE_MODE, MAINTENANCE_REASON
395
+ with _state_lock:
396
+ MAINTENANCE_MODE = on
397
+ MAINTENANCE_REASON = reason if on else ""
398
+
399
+ # ══════════════════════════════════════════════════════════════════
400
+ # ADMIN AUTH
401
+ # ══════════════════════════════════════════════════════════════════
402
+ def _is_admin_session(user_id):
403
+ if user_id is None:
404
+ return False
405
+ with _admin_lock:
406
+ exp = _admin_sessions.get(user_id)
407
+ if exp is None:
408
+ return False
409
+ if time.time() > exp:
410
+ _admin_sessions.pop(user_id, None)
411
+ return False
412
+ return True
413
+
414
+
415
+ def _grant_admin(user_id):
416
+ with _admin_lock:
417
+ _admin_sessions[user_id] = time.time() + ADMIN_SESSION_TTL
418
+
419
+
420
+ def _revoke_admin(user_id):
421
+ with _admin_lock:
422
+ _admin_sessions.pop(user_id, None)
423
+
424
+
425
+ def _admin_state_get(user_id):
426
+ with _admin_lock:
427
+ e = _admin_states.get(user_id)
428
+ if e is None:
429
+ return None
430
+ state, set_at = e
431
+ if time.time() - set_at > ADMIN_PROMPT_TTL:
432
+ _admin_states.pop(user_id, None)
433
+ return None
434
+ return state
435
+
436
+
437
+ def _admin_state_set(user_id, state):
438
+ with _admin_lock:
439
+ _admin_states[user_id] = (state, time.time())
440
+
441
+
442
+ def _admin_state_clear(user_id):
443
+ with _admin_lock:
444
+ _admin_states.pop(user_id, None)
445
+
446
+ # ══════════════════════════════════════════════════════════════════
447
+ # CACHE GC
448
+ # ══════════════════════════════════════════════════════════════════
449
+ def cache_gc():
450
+ global PEAK_CONCURRENT
451
+ while True:
452
+ time.sleep(60)
453
+ now = time.time()
454
+ with SEARCH_CACHE_LOCK:
455
+ dead = [k for k, v in SEARCH_CACHE.items()
456
+ if now - v.get("ts", 0) > SEARCH_CACHE_TTL]
457
+ for k in dead:
458
+ SEARCH_CACHE.pop(k, None)
459
+ with _activity_lock:
460
+ cutoff = now - LIVE_WINDOW
461
+ for uid in list(ACTIVE_USERS.keys()):
462
+ if ACTIVE_USERS[uid] < cutoff:
463
+ del ACTIVE_USERS[uid]
464
+ if len(ACTIVE_USERS) > PEAK_CONCURRENT:
465
+ PEAK_CONCURRENT = len(ACTIVE_USERS)
466
+ with _member_lock:
467
+ for uid, (_, ts) in list(_member_cache.items()):
468
+ if now - ts > MEMBERSHIP_CACHE_TTL * 2:
469
+ _member_cache.pop(uid, None)
470
+ with _pending_lock:
471
+ for uid, (_, _, ts) in list(_pending_query.items()):
472
+ if now - ts > PENDING_QUERY_TTL:
473
+ _pending_query.pop(uid, None)
474
+ with _flood_lock:
475
+ for uid, until in list(_muted_until.items()):
476
+ if until < now - 300:
477
+ _muted_until.pop(uid, None)
478
+ with _seen_updates_lock:
479
+ cutoff = now - 600
480
+ for k in [k for k, v in _seen_updates.items() if v < cutoff]:
481
+ del _seen_updates[k]
482
+ today = _today_utc()
483
+ with _quota_lock:
484
+ for uid, (day, _) in list(_user_daily.items()):
485
+ if day != today:
486
+ _user_daily.pop(uid, None)