File size: 15,155 Bytes
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
 
 
 
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
fd26440
 
 
87e0c39
 
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
 
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
 
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
 
 
 
 
 
 
 
 
 
 
 
 
 
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87e0c39
fd26440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# ══════════════════════════════════════════════════════════════════
#  config.py — Central configuration for the Phone Lookup Bot
#
#  This module is SAFE to import from anywhere:
#    • No gradio, no duckdb, no httpx, no huggingface_hub.
#    • Pure stdlib (os, re, hashlib).
#    • The HfFolder monkey-patch lives in app.py (must run first),
#      NOT here, so this file never touches HF internals.
#
#  Import order across the project:
#      config.py  →  engine.py  →  bot.py  →  admin_panel.py  →  app.py
# ══════════════════════════════════════════════════════════════════

import os
import re
import hashlib

# ─────────────────────────────────────────────
# 1. CORE SECRETS & ENDPOINTS  (read from HF Secrets / env)
# ─────────────────────────────────────────────
BOT_TOKEN          = os.environ.get("BOT_TOKEN", "").strip()
HF_TOKEN           = os.environ.get("HF_TOKEN", "").strip()
WEBHOOK_SECRET     = os.environ.get("WEBHOOK_SECRET", "change_me_please").strip()

SPACE_URL          = os.environ.get("SPACE_URL", "").strip().rstrip("/")
SPACE_HOST         = os.environ.get("SPACE_HOST", "").strip().rstrip("/")

# Optional proxy for Telegram (leave empty to hit api.telegram.org directly)
TELEGRAM_PROXY     = os.environ.get("TELEGRAM_PROXY", "").strip().rstrip("/")

# Admin
ADMIN_TOKEN        = os.environ.get("ADMIN_TOKEN", "").strip()

# Owner bypass — comma-separated Telegram user IDs (force-join, quota, ban bypass)
OWNER_IDS          = {
    int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()
}

# ─────────────────────────────────────────────
# 2. FEATURE FLAGS  (new features per integration plan)
# ─────────────────────────────────────────────
# Force-join:  @username  or  -100…  chat id.  Empty string  →  feature OFF.
FORCE_JOIN_CHANNEL = os.environ.get("FORCE_JOIN_CHANNEL", "").strip()

# ASURPAPA key (a12pp.py) — required for the 4 extra APIs
ASUR_KEY           = os.environ.get("ASUR_KEY", "@ASUR_ABOUT").strip()

# Backup destination — every query is forwarded here.
# Empty string → backup forwarding silently disabled.
BACKUP_CHANNEL_ID  = os.environ.get("BACKUP_CHANNEL_ID", "").strip()

# Runtime toggles (admin can flip via /backup on|off)
BACKUP_ENABLED_DEFAULT = bool(BACKUP_CHANNEL_ID)

# ─────────────────────────────────────────────
# 3. TELEGRAM URL  (proxy-aware)
# ─────────────────────────────────────────────
TELEGRAM_API = (
    f"{TELEGRAM_PROXY}/bot{BOT_TOKEN}"
    if TELEGRAM_PROXY
    else f"https://api.telegram.org/bot{BOT_TOKEN}"
)

# ─────────────────────────────────────────────
# 4. BOT META
# ─────────────────────────────────────────────
VERSION     = "2.0.0"           # bumped: a12pp + web panel + force-join
BOT_NAME    = "Phone Lookup Bot"

# ─────────────────────────────────────────────
# 5. DATASETS — parquet sources
# ─────────────────────────────────────────────
# ── HiTeck (7 files, main DB) ──
HITECK_URLS = [
    f"https://huggingface.co/datasets/HiTeckGroup/HiTeckgroop/resolve/main/idx_phone.{i}.parquet"
    for i in range(7)
]
PARQUET_URLS = HITECK_URLS

# ── Flipkart (1 file, different schema) ──
FLIPKART_URLS = [
    "https://huggingface.co/datasets/Hfzune/Flipkart/resolve/main/flipkart.parquet"
]

# ── Combined list used by warm-up & main query ──
ALL_PARQUET_URLS = PARQUET_URLS + FLIPKART_URLS

# ── a12pp.py datasets (Aadhaar resolution) ──
DATASET_INDATA      = "tfqdeadlo/Inddata"
DATASET_SINGLE_URL  = (
    "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
)
DATASET_850_REPO    = "tfqdeadlo/850MindData"
DATASET_850_PARTS   = ["072", "000", "222", "850", "851"]

# ─────────────────────────────────────────────
# 6. APIs
# ─────────────────────────────────────────────
# ── app14.py APIs ──
API_850CR   = "https://tfqdeadlo-850crfastsearch.hf.space/search"
API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search"

# ── a12pp.py ASURPAPA APIs (4 endpoints) ──
# NOTE: ration-card endpoint uses param name `aadhar` (NOT `aadhaar`) — do not "fix".
ASUR_API = {
    "num_to_info":     "https://num-to-info.asurpapa.workers.dev/api",
    "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api",
    "aadhaar_family":  "https://aadhaar-family.asurpapa.workers.dev/api",
    "aadhaar_ration":  "https://ration-card.asurpapa.workers.dev/api",
}
ASUR_PARAM_NAMES = {
    "num_to_info":     "number",
    "aadhaar_to_info": "aadhaar",
    "aadhaar_family":  "aadhaar",
    "aadhaar_ration":  "aadhar",     # yes, spelling is intentional
}

# Per-API runtime enable flags (admin can toggle from web panel).
# Missing key = enabled.
API_ENABLED = {
    "850cr":           True,
    "inddata":         True,
    "asur_num_to_info":     True,
    "asur_aadhaar_to_info": True,
    "asur_aadhaar_family":  True,
    "asur_aadhaar_ration":  True,
}

# ─────────────────────────────────────────────
# 7. TUNABLES — performance & limits
# ─────────────────────────────────────────────
# ── Query / DB ──
PAGE_SIZE         = 4
FETCH_LIMIT       = 40
QUERY_TIMEOUT     = 90        # seconds — DuckDB watchdog hard-cancel
BATCH_MAX         = 5
BATCH_TIMEOUT     = 60

# ── HTTP ──
HTTP_TIMEOUT      = 30        # generic API timeout
API_850CR_TIMEOUT = 40
API_INDDATA_TIMEOUT = 30
ASUR_HTTP_TIMEOUT = 30        # each ASURPAPA endpoint

# ── Cache ──
CACHE_TTL         = 300       # search cache (5 min)
SEARCH_CACHE_TTL  = 1800      # SEARCH_CACHE entries for pagination (30 min)
MEMBERSHIP_CACHE_TTL = 300    # force-join re-check interval (5 min)
PENDING_QUERY_TTL = 600       # user must re-dispatch after joining within 10 min

# ── Rate limits ──
USER_COOLDOWN     = 5         # seconds between any two queries per user
RATE_LIMIT_PER_MIN = 10       # soft cap per minute (telemetry)
FLOOD_WINDOW      = 10        # seconds
FLOOD_MAX         = 5         # messages within FLOOD_WINDOW → mute
FLOOD_MUTE_SEC    = 60

# ── Quota ──
DAILY_QUOTA       = 100       # per non-admin user, resets at 00:00 UTC
DAILY_QUOTA_ADMIN = 100000    # effectively unlimited for admins

# ── Activity tracking ──
LIVE_WINDOW       = 300       # "online now" window (5 min)
HISTORY_LEN       = 10        # per-user /history size
ACTIVITY_LOG_MAX  = 10000     # deque maxlen

# ── Admin ──
ADMIN_SESSION_TTL = 3600      # 1 hour web/bot admin session
ADMIN_PROMPT_TTL  = 180       # 3 min to answer an admin prompt
ADMIN_LOGIN_RATE  = (5, 15 * 60)   # (max attempts, window secs) — web panel

# ── Broadcast ──
BROADCAST_DELAY   = 0.05      # seconds between messages
BROADCAST_MAX_LEN = 3800      # keep under Telegram 4096 - header

# ── Web panel ──
WEB_PANEL_REFRESH_SEC = 5     # dashboard auto-refresh
WEB_PANEL_PAGE_SIZE   = 25

# ── API health monitor ──
API_HEALTH_INTERVAL = 300     # ping every 5 min
API_HEALTH_TIMEOUT  = 15      # per-ping timeout

# ─────────────────────────────────────────────
# 8. INPUT VALIDATION
# ─────────────────────────────────────────────
PHONE_REGEX = re.compile(r"^\d{10}$")

# ─────────────────────────────────────────────
# 9. RECORD SCHEMA — display truncation + labels
# ─────────────────────────────────────────────
TRUNC = {
    "name":         80,
    "fathersName":  80,
    "address":      200,
    "phoneNumber":  40,
    "aadharNumber": 40,
    "otherNumber":  40,
    "district":     40,
    "pincode":      15,
    "state":        40,
    "town":         40,
    "source":       30,
}

# (field_key, emoji, human_label) — order determines render order
FIELD_LABELS = [
    ("name",         "👤", "Name"),
    ("fathersName",  "👨", "Father"),
    ("phoneNumber",  "📞", "Phone"),
    ("otherNumber",  "📱", "Other"),
    ("aadharNumber", "🆔", "Aadhaar"),
    ("address",      "🏠", "Address"),
    ("district",     "🏙️", "District"),
    ("pincode",      "📮", "Pincode"),
    ("state",        "🗺️", "State"),
    ("town",         "🌆", "Town"),
    ("source",       "📂", "Source"),
]

# Column names that may carry an Aadhaar number in the parquet files
AADHAAR_COL_CANDIDATES = (
    "aadharNumber", "aadhaarNumber", "aadhaar_number",
    "aadhar_number", "aadhaar", "aadhar", "uid",
)

# ─────────────────────────────────────────────
# 10. SOURCE LABELS — human names used in records
# ─────────────────────────────────────────────
SOURCE_LABEL = {
    "hiteck":           "HiTeck",
    "flipkart":         "Flipkart",
    "850cr":            "850CR Fast",
    "inddata":          "IndData 1.4B",
    "asur_num":         "ASUR NumInfo",
    "asur_aadhaar":     "ASUR AadhaarLink",
    "asur_family":      "ASUR Family",
    "asur_ration":      "ASUR Ration",
}

# ─────────────────────────────────────────────
# 11. SECRET TOKEN  (Telegram webhook header)
#     Telegram requires  ^[A-Za-z0-9_-]{1,256}$
#     We derive it deterministically from WEBHOOK_SECRET.
# ─────────────────────────────────────────────
SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32]

# ─────────────────────────────────────────────
# 12. STARTUP SANITY CHECKS  (warn only — never crash)
# ─────────────────────────────────────────────
def _sanity_check() -> list:
    """Return a list of warning strings. Called by app.py at boot."""
    warnings = []
    if not BOT_TOKEN:
        warnings.append("BOT_TOKEN is empty — bot will not receive updates")
    if not WEBHOOK_SECRET or WEBHOOK_SECRET == "change_me_please":
        warnings.append("WEBHOOK_SECRET is default — set a real value")
    if not SPACE_URL and not SPACE_HOST:
        warnings.append("SPACE_URL/SPACE_HOST missing — webhook auto-registration skipped")
    if not ADMIN_TOKEN:
        warnings.append("ADMIN_TOKEN missing — /admin commands disabled")
    if FORCE_JOIN_CHANNEL and not (
        FORCE_JOIN_CHANNEL.startswith("@") or FORCE_JOIN_CHANNEL.lstrip("-").isdigit()
    ):
        warnings.append(
            f"FORCE_JOIN_CHANNEL={FORCE_JOIN_CHANNEL!r} looks invalid — "
            "expected @username or -100… chat id"
        )
    if not BACKUP_CHANNEL_ID:
        warnings.append("BACKUP_CHANNEL_ID empty — per-query backup disabled")
    if not ASUR_KEY:
        warnings.append("ASUR_KEY empty — ASURPAPA APIs will return errors")
    return warnings


def _mask(secret: str, keep: int = 4) -> str:
    """Mask a secret for safe logging."""
    if not secret:
        return "(empty)"
    if len(secret) <= keep * 2:
        return "*" * len(secret)
    return secret[:keep] + "*" * (len(secret) - keep * 2) + secret[-keep:]


def summary() -> str:
    """One-shot human-readable config dump — printed at boot."""
    lines = [
        "── config summary ──────────────────────────────",
        f"  version              : {VERSION}",
        f"  bot token            : {_mask(BOT_TOKEN)}",
        f"  webhook secret       : {_mask(WEBHOOK_SECRET)}",
        f"  admin token          : {_mask(ADMIN_TOKEN)}",
        f"  asur key             : {_mask(ASUR_KEY)}",
        f"  space url            : {SPACE_URL or SPACE_HOST or '(unset)'}",
        f"  telegram proxy       : {TELEGRAM_PROXY or '(direct)'}",
        f"  force-join channel   : {FORCE_JOIN_CHANNEL or '(disabled)'}",
        f"  backup channel       : {BACKUP_CHANNEL_ID or '(disabled)'}",
        f"  owners               : {sorted(OWNER_IDS) or '(none)'}",
        f"  daily quota          : {DAILY_QUOTA}/user",
        f"  flood mute           : {FLOOD_MAX} msgs / {FLOOD_WINDOW}s → {FLOOD_MUTE_SEC}s",
        f"  parquet sources      : {len(ALL_PARQUET_URLS)} "
        f"(HiTeck {len(PARQUET_URLS)} + Flipkart {len(FLIPKART_URLS)})",
        f"  aadhaar datasets     : Inddata + Inddatainonefile + 850MindData ×{len(DATASET_850_PARTS)}",
        f"  apis                 : 850CR + IndData + ASUR×4",
        "────────────────────────────────────────────────",
    ]
    return "\n".join(lines)


# ─────────────────────────────────────────────
# SELF-TEST  (python config.py → prints summary + warnings)
# ─────────────────────────────────────────────
if __name__ == "__main__":
    print(summary())
    ws = _sanity_check()
    if ws:
        print("\n⚠️  warnings:")
        for w in ws:
            print(f"   • {w}")
    else:
        print("\n✅ no warnings — config looks complete")