Karan Adhikari commited on
Commit
532c525
·
unverified ·
1 Parent(s): 498fa78

Migrate scan/rescan/dbcheck from bot commands to WebUI Tools page

Browse files

- Add resumable scan engine (Backend/helper/scan_manager.py) with DB-persisted
per-channel cursors; interrupted scans resume until a Rescan is requested
- Add DbCheckManager for integrity checking + dead-link purge with live stats
- Add Tools page (/admin/tools) with channel selector, live progress bars,
DB check info, and dead-link purge
- Add Tools API routes and nav links
- Restore scan state on startup in __main__.py
- Respect Telegram limits (batching, delays, FloodWait back-off) to avoid bans
- Remove scan/rescan/scanstatus/cancelscan/dbcheck/search bot commands
(delete scanner.py, trim utilities.py to /stats, update bot command menu)

Backend/__main__.py CHANGED
@@ -12,6 +12,7 @@ from Backend.helper.pyro import restart_notification, setup_bot_commands
12
  from Backend.pyrofork.bot import Userbot, StreamBot
13
  from Backend.pyrofork.clients import initialize_clients
14
  from Backend.helper import subscription_task_manager
 
15
  from Backend.helper.link_checker import DeadLinkChecker
16
  from Backend.fastapi.main import app
17
  from Backend.helper.auto_catalog import (
@@ -31,6 +32,13 @@ async def start_services():
31
 
32
  await SettingsManager.initialize(db)
33
  await asleep(0.5)
 
 
 
 
 
 
 
34
 
35
  try:
36
  await db.reload_extra_databases(SettingsManager.current().extra_databases)
 
12
  from Backend.pyrofork.bot import Userbot, StreamBot
13
  from Backend.pyrofork.clients import initialize_clients
14
  from Backend.helper import subscription_task_manager
15
+ from Backend.helper.scan_manager import scan_manager, dbcheck_manager
16
  from Backend.helper.link_checker import DeadLinkChecker
17
  from Backend.fastapi.main import app
18
  from Backend.helper.auto_catalog import (
 
32
 
33
  await SettingsManager.initialize(db)
34
  await asleep(0.5)
35
+
36
+ try:
37
+ await scan_manager.load(db)
38
+ dbcheck_manager.bind_db(db)
39
+ except Exception as e:
40
+ LOGGER.error(f"Failed to restore scan manager state on startup: {e}")
41
+ await asleep(0.3)
42
 
43
  try:
44
  await db.reload_extra_databases(SettingsManager.current().extra_databases)
Backend/fastapi/main.py CHANGED
@@ -12,7 +12,7 @@ from Backend.fastapi.routes.template_routes import (
12
  login_page, login_post, logout, set_theme, dashboard_page,
13
  media_management_page, edit_media_page, public_status_page, stremio_guide_page,
14
  admin_dashboard_page, admin_subscriptions_page, admin_access_page,
15
- custom_catalogs_page, settings_page
16
  )
17
  from Backend.fastapi.routes.api_routes import (
18
  list_media_api, delete_media_api, update_media_api,
@@ -32,7 +32,9 @@ from Backend.fastapi.routes.api_routes import (
32
  add_custom_catalog_item_api, remove_custom_catalog_item_api,
33
  auto_sync_custom_catalogs_api, auto_catalog_sync_status_api,
34
  get_auto_catalog_settings_api, update_auto_catalog_settings_api,
35
- get_settings_api, update_settings_api
 
 
36
  )
37
 
38
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
@@ -387,6 +389,43 @@ async def get_settings(_: bool = Depends(require_auth)):
387
  async def update_settings(payload: dict, _: bool = Depends(require_auth)):
388
  return await update_settings_api(payload)
389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  @app.exception_handler(401)
391
  async def auth_exception_handler(request: Request, exc):
392
  return RedirectResponse(url="/login", status_code=302)
 
12
  login_page, login_post, logout, set_theme, dashboard_page,
13
  media_management_page, edit_media_page, public_status_page, stremio_guide_page,
14
  admin_dashboard_page, admin_subscriptions_page, admin_access_page,
15
+ custom_catalogs_page, settings_page, tools_page
16
  )
17
  from Backend.fastapi.routes.api_routes import (
18
  list_media_api, delete_media_api, update_media_api,
 
32
  add_custom_catalog_item_api, remove_custom_catalog_item_api,
33
  auto_sync_custom_catalogs_api, auto_catalog_sync_status_api,
34
  get_auto_catalog_settings_api, update_auto_catalog_settings_api,
35
+ get_settings_api, update_settings_api,
36
+ get_tools_channels_api, start_scan_api, cancel_scan_api, scan_status_api,
37
+ start_dbcheck_api, cancel_dbcheck_api, dbcheck_status_api, purge_dead_links_api
38
  )
39
 
40
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
 
389
  async def update_settings(payload: dict, _: bool = Depends(require_auth)):
390
  return await update_settings_api(payload)
391
 
392
+ # --- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands) ---
393
+ @app.get("/admin/tools", response_class=HTMLResponse)
394
+ async def admin_tools(request: Request, _: bool = Depends(require_auth)):
395
+ return await tools_page(request, _)
396
+
397
+ @app.get("/api/admin/tools/channels")
398
+ async def tools_channels(_: bool = Depends(require_auth)):
399
+ return await get_tools_channels_api()
400
+
401
+ @app.post("/api/admin/tools/scan/start")
402
+ async def tools_scan_start(payload: dict, _: bool = Depends(require_auth)):
403
+ return await start_scan_api(payload)
404
+
405
+ @app.post("/api/admin/tools/scan/cancel")
406
+ async def tools_scan_cancel(_: bool = Depends(require_auth)):
407
+ return await cancel_scan_api()
408
+
409
+ @app.get("/api/admin/tools/scan/status")
410
+ async def tools_scan_status(_: bool = Depends(require_auth)):
411
+ return await scan_status_api()
412
+
413
+ @app.post("/api/admin/tools/dbcheck/start")
414
+ async def tools_dbcheck_start(_: bool = Depends(require_auth)):
415
+ return await start_dbcheck_api()
416
+
417
+ @app.post("/api/admin/tools/dbcheck/cancel")
418
+ async def tools_dbcheck_cancel(_: bool = Depends(require_auth)):
419
+ return await cancel_dbcheck_api()
420
+
421
+ @app.get("/api/admin/tools/dbcheck/status")
422
+ async def tools_dbcheck_status(_: bool = Depends(require_auth)):
423
+ return await dbcheck_status_api()
424
+
425
+ @app.post("/api/admin/tools/dead-links/purge")
426
+ async def tools_purge_dead_links(payload: dict | None = None, _: bool = Depends(require_auth)):
427
+ return await purge_dead_links_api(payload)
428
+
429
  @app.exception_handler(401)
430
  async def auth_exception_handler(request: Request, exc):
431
  return RedirectResponse(url="/login", status_code=302)
Backend/fastapi/routes/api_routes.py CHANGED
@@ -1065,3 +1065,119 @@ async def update_settings_api(payload: dict) -> dict:
1065
  raise HTTPException(status_code=400, detail=str(exc))
1066
  except Exception as exc:
1067
  raise HTTPException(status_code=500, detail=str(exc))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1065
  raise HTTPException(status_code=400, detail=str(exc))
1066
  except Exception as exc:
1067
  raise HTTPException(status_code=500, detail=str(exc))
1068
+
1069
+
1070
+
1071
+ # ─────────────────────────────────────────────────────────────────────────────
1072
+ # Tools — WebUI replacement for /scan, /rescan, /scanstatus, /cancelscan,
1073
+ # /dbcheck. All driven from the Tools page; no bot commands remain.
1074
+ # ─────────────────────────────────────────────────────────────────────────────
1075
+
1076
+ def _scan_client():
1077
+ """Pick a Telegram client capable of fetching channel messages.
1078
+
1079
+ Prefer the primary StreamBot (it must be an admin in the AUTH channels to
1080
+ index them); fall back to any connected client."""
1081
+ if StreamBot is not None:
1082
+ return StreamBot
1083
+ if multi_clients:
1084
+ return multi_clients.get(0) or next(iter(multi_clients.values()))
1085
+ return None
1086
+
1087
+
1088
+ async def get_tools_channels_api() -> dict:
1089
+ """Return the configured AUTH channels with friendly names for the picker."""
1090
+ channels = list(SettingsManager.current().auth_channels)
1091
+ client = _scan_client()
1092
+ result = []
1093
+ for ch in channels:
1094
+ name = str(ch)
1095
+ try:
1096
+ if client is not None:
1097
+ chat = await client.get_chat(int(ch) if str(ch).lstrip("-").isdigit() else ch)
1098
+ name = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(ch)
1099
+ except Exception as e:
1100
+ LOGGER.warning(f"[Tools] Could not resolve channel {ch}: {e}")
1101
+ result.append({"id": str(ch), "name": name})
1102
+ return {"status": "success", "data": result}
1103
+
1104
+
1105
+ async def start_scan_api(payload: dict) -> dict:
1106
+ from Backend.helper.scan_manager import scan_manager
1107
+ client = _scan_client()
1108
+ if client is None:
1109
+ raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")
1110
+
1111
+ mode = str(payload.get("mode", "scan")).lower()
1112
+ if mode not in ("scan", "rescan"):
1113
+ raise HTTPException(status_code=400, detail="mode must be 'scan' or 'rescan'.")
1114
+ channels = payload.get("channels") or []
1115
+ if not isinstance(channels, list):
1116
+ raise HTTPException(status_code=400, detail="'channels' must be a list.")
1117
+
1118
+ result = await scan_manager.start(client, channels, mode=mode)
1119
+ if not result.get("ok"):
1120
+ raise HTTPException(status_code=409, detail=result.get("message", "Could not start scan."))
1121
+ return {"status": "success", **result}
1122
+
1123
+
1124
+ async def cancel_scan_api() -> dict:
1125
+ from Backend.helper.scan_manager import scan_manager
1126
+ result = await scan_manager.cancel()
1127
+ return {"status": "success" if result.get("ok") else "error", **result}
1128
+
1129
+
1130
+ async def scan_status_api() -> dict:
1131
+ from Backend.helper.scan_manager import scan_manager
1132
+ return {"status": "success", "data": scan_manager.get_status()}
1133
+
1134
+
1135
+ async def start_dbcheck_api() -> dict:
1136
+ from Backend.helper.scan_manager import dbcheck_manager
1137
+ client = _scan_client()
1138
+ if client is None:
1139
+ raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")
1140
+ result = await dbcheck_manager.start(client)
1141
+ if not result.get("ok"):
1142
+ raise HTTPException(status_code=409, detail=result.get("message", "Could not start DB check."))
1143
+ return {"status": "success", **result}
1144
+
1145
+
1146
+ async def cancel_dbcheck_api() -> dict:
1147
+ from Backend.helper.scan_manager import dbcheck_manager
1148
+ result = await dbcheck_manager.cancel()
1149
+ return {"status": "success" if result.get("ok") else "error", **result}
1150
+
1151
+
1152
+ async def dbcheck_status_api() -> dict:
1153
+ from Backend.helper.scan_manager import dbcheck_manager
1154
+ return {"status": "success", "data": dbcheck_manager.get_status()}
1155
+
1156
+
1157
+ async def purge_dead_links_api(payload: dict | None = None) -> dict:
1158
+ """Purge dead links.
1159
+
1160
+ - With no body (or {"source": "dbcheck"}): purge the dead entries found by
1161
+ the most recent DB check.
1162
+ - {"source": "flagged"}: purge every entry flagged is_dead in the DB
1163
+ (these come from the background Dead-Link Checker).
1164
+ - {"stream_ids": [...]}: purge a specific set.
1165
+ """
1166
+ from Backend.helper.scan_manager import dbcheck_manager
1167
+ payload = payload or {}
1168
+ source = str(payload.get("source", "dbcheck")).lower()
1169
+ stream_ids = payload.get("stream_ids")
1170
+
1171
+ if stream_ids is not None:
1172
+ result = await dbcheck_manager.purge(stream_ids)
1173
+ elif source == "flagged":
1174
+ try:
1175
+ flagged = await db.get_all_dead_links()
1176
+ ids = list({d.get("quality_id") for d in flagged if d.get("quality_id")})
1177
+ except Exception as e:
1178
+ raise HTTPException(status_code=500, detail=f"Could not load flagged dead links: {e}")
1179
+ result = await dbcheck_manager.purge(ids)
1180
+ else:
1181
+ result = await dbcheck_manager.purge()
1182
+
1183
+ return {"status": "success" if result.get("ok") else "error", **result}
Backend/fastapi/routes/template_routes.py CHANGED
@@ -290,6 +290,23 @@ async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)
290
 
291
 
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
294
  theme_name = request.session.get("theme", "dark_professional")
295
  theme = get_theme(theme_name)
 
290
 
291
 
292
 
293
+ async def tools_page(request: Request, _: bool = Depends(require_auth)):
294
+ theme_name = request.session.get("theme", "dark_professional")
295
+ theme = get_theme(theme_name)
296
+ current_user = get_current_user(request)
297
+
298
+ return templates.TemplateResponse(
299
+ "tools.html",
300
+ {
301
+ "request": request,
302
+ "theme": theme,
303
+ "themes": get_all_themes(),
304
+ "current_theme": theme_name,
305
+ "current_user": current_user,
306
+ },
307
+ )
308
+
309
+
310
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
311
  theme_name = request.session.get("theme", "dark_professional")
312
  theme = get_theme(theme_name)
Backend/fastapi/templates/base.html CHANGED
@@ -168,6 +168,7 @@ tailwind.config = {
168
  <a href="/admin/dashboard" class="nav-link">Admin</a>
169
  <a href="/admin/subscriptions" class="nav-link">Subs</a>
170
  <a href="/admin/access" class="nav-link">Access</a>
 
171
  <a href="/admin/settings" class="nav-link">Settings</a>
172
  </div>
173
  {% endif %}
@@ -228,6 +229,7 @@ tailwind.config = {
228
  <a href="/admin/dashboard" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-chart-line"></i> Admin</a>
229
  <a href="/admin/subscriptions" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-credit-card"></i> Subs</a>
230
  <a href="/admin/access" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-shield"></i> Access</a>
 
231
  <!-- ↓ NEW -->
232
  <a href="/admin/settings" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-gear"></i> Settings</a>
233
  </div>
 
168
  <a href="/admin/dashboard" class="nav-link">Admin</a>
169
  <a href="/admin/subscriptions" class="nav-link">Subs</a>
170
  <a href="/admin/access" class="nav-link">Access</a>
171
+ <a href="/admin/tools" class="nav-link">Tools</a>
172
  <a href="/admin/settings" class="nav-link">Settings</a>
173
  </div>
174
  {% endif %}
 
229
  <a href="/admin/dashboard" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-chart-line"></i> Admin</a>
230
  <a href="/admin/subscriptions" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-credit-card"></i> Subs</a>
231
  <a href="/admin/access" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-shield"></i> Access</a>
232
+ <a href="/admin/tools" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-screwdriver-wrench"></i> Tools</a>
233
  <!-- ↓ NEW -->
234
  <a href="/admin/settings" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-gear"></i> Settings</a>
235
  </div>
Backend/fastapi/templates/tools.html ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Tools — TG Stremio{% endblock %}
3
+
4
+ {% block content %}
5
+
6
+ <style>
7
+ .tool-card {
8
+ background: color-mix(in srgb, var(--card) 45%, transparent);
9
+ backdrop-filter: blur(20px);
10
+ border: 1px solid var(--border);
11
+ border-radius: 1.5rem;
12
+ padding: 1.5rem 1.75rem;
13
+ box-shadow: 0 8px 32px rgba(0,0,0,0.15);
14
+ }
15
+ .tool-card h2 {
16
+ font-size: 1rem; font-weight: 800;
17
+ letter-spacing: 0.05em; text-transform: uppercase;
18
+ color: var(--primary); margin-bottom: 1.25rem;
19
+ display: flex; align-items: center; gap: 0.5rem;
20
+ }
21
+ .s-label {
22
+ display: block; font-size: 0.78rem; font-weight: 700;
23
+ color: var(--text-sec); text-transform: uppercase;
24
+ letter-spacing: 0.04em; margin-bottom: 0.5rem;
25
+ }
26
+ .btn {
27
+ display: inline-flex; align-items: center; gap: 0.5rem;
28
+ padding: 0.6rem 1.25rem; border-radius: 9999px;
29
+ font-size: 0.85rem; font-weight: 700; cursor: pointer;
30
+ border: 1px solid transparent; transition: all 0.15s; white-space: nowrap;
31
+ }
32
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
33
+ .btn-primary { background: var(--primary); color: #fff; box-shadow: 0 0 18px color-mix(in srgb,var(--primary) 40%,transparent); }
34
+ .btn-danger { background: rgba(239,68,68,0.12); border-color: rgba(239,68,68,0.3); color: #ef4444; }
35
+ .btn-danger:hover:not(:disabled) { background: rgba(239,68,68,0.25); }
36
+ .btn-ghost { background: color-mix(in srgb,var(--text-sec) 12%,transparent); color: var(--text); }
37
+ .btn-warning { background: rgba(245,158,11,0.14); border-color: rgba(245,158,11,0.35); color: #f59e0b; }
38
+ .btn-warning:hover:not(:disabled) { background: rgba(245,158,11,0.28); }
39
+
40
+ /* channel chips */
41
+ .chip-list { display: flex; flex-direction: column; gap: 0.5rem; max-height: 240px; overflow-y: auto; }
42
+ .chip {
43
+ display: flex; align-items: center; gap: 0.75rem;
44
+ padding: 0.7rem 1rem; border-radius: 0.9rem;
45
+ border: 1px solid var(--border);
46
+ background: color-mix(in srgb, var(--bg) 60%, transparent);
47
+ cursor: pointer; transition: border-color 0.15s, background 0.15s;
48
+ }
49
+ .chip:hover { border-color: var(--primary); }
50
+ .chip.selected { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 12%, transparent); }
51
+ .chip input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); }
52
+ .chip .c-name { font-weight: 700; font-size: 0.9rem; }
53
+ .chip .c-id { font-size: 0.72rem; color: var(--text-sec); }
54
+
55
+ /* progress */
56
+ .progress-track {
57
+ width: 100%; height: 0.65rem; border-radius: 9999px;
58
+ background: color-mix(in srgb, var(--text-sec) 18%, transparent);
59
+ overflow: hidden;
60
+ }
61
+ .progress-fill {
62
+ height: 100%; border-radius: 9999px; background: var(--primary);
63
+ width: 0%; transition: width 0.4s ease;
64
+ }
65
+ .progress-fill.indeterminate {
66
+ width: 35% !important;
67
+ animation: indet 1.2s ease-in-out infinite;
68
+ }
69
+ @keyframes indet { 0% { margin-left: -35%; } 100% { margin-left: 100%; } }
70
+
71
+ .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px,1fr)); gap: 0.75rem; }
72
+ .stat-box {
73
+ background: color-mix(in srgb, var(--bg) 55%, transparent);
74
+ border: 1px solid var(--border); border-radius: 0.9rem;
75
+ padding: 0.75rem 0.9rem;
76
+ }
77
+ .stat-box .v { font-size: 1.3rem; font-weight: 800; }
78
+ .stat-box .l { font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-sec); }
79
+
80
+ .status-pill {
81
+ display: inline-flex; align-items: center; gap: 0.4rem;
82
+ padding: 0.25rem 0.8rem; border-radius: 9999px;
83
+ font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em;
84
+ }
85
+ .status-idle { background: color-mix(in srgb,var(--text-sec) 15%,transparent); color: var(--text-sec); }
86
+ .status-running { background: rgba(34,197,94,0.15); color: #22c55e; }
87
+ .status-paused { background: rgba(245,158,11,0.15); color: #f59e0b; }
88
+ .status-cancelled { background: rgba(245,158,11,0.15); color: #f59e0b; }
89
+ .status-completed { background: rgba(34,197,94,0.15); color: #22c55e; }
90
+ .status-error { background: rgba(239,68,68,0.15); color: #ef4444; }
91
+
92
+ .dead-row {
93
+ display: flex; align-items: center; justify-content: space-between; gap: 0.75rem;
94
+ padding: 0.6rem 0.9rem; border-radius: 0.75rem;
95
+ border: 1px solid var(--border);
96
+ background: color-mix(in srgb, var(--bg) 55%, transparent);
97
+ }
98
+ .dead-list { display: flex; flex-direction: column; gap: 0.4rem; max-height: 320px; overflow-y: auto; }
99
+ .divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }
100
+ .hint { font-size: 0.78rem; color: var(--text-sec); }
101
+ </style>
102
+
103
+ <!-- Page header -->
104
+ <div class="flex items-center justify-between mb-8 flex-wrap gap-3">
105
+ <div>
106
+ <h1 class="text-3xl font-extrabold">Tools</h1>
107
+ <p class="mt-1 text-sm" style="color:var(--text-sec)">
108
+ Scan your channels, verify the database, and clean up dead links — all from here.
109
+ </p>
110
+ </div>
111
+ </div>
112
+
113
+ <div class="space-y-6">
114
+
115
+ <!-- ══ Channel Scanner ══════════��═══════════════════════════════════ -->
116
+ <div class="tool-card">
117
+ <div class="flex items-center justify-between flex-wrap gap-2">
118
+ <h2 style="margin-bottom:0"><i class="fa-solid fa-satellite-dish"></i> Channel Scanner</h2>
119
+ <span id="scan-status-pill" class="status-pill status-idle">Idle</span>
120
+ </div>
121
+
122
+ <p class="hint mt-3 mb-4">
123
+ Index existing files from your AUTH channels into the database. A scan
124
+ <strong>resumes from where it left off</strong> if the server restarts or you
125
+ stop it — it only restarts from scratch when you choose <strong>Rescan</strong>.
126
+ The bot must be an admin in each channel.
127
+ </p>
128
+
129
+ <label class="s-label">Select channels</label>
130
+ <div class="chip-list" id="channel-list">
131
+ <div class="hint" id="channels-loading"><i class="fa-solid fa-spinner fa-spin"></i> Loading channels…</div>
132
+ </div>
133
+
134
+ <div class="flex items-center gap-2 mt-3">
135
+ <button class="btn btn-ghost" type="button" onclick="selectAllChannels(true)"><i class="fa-solid fa-check-double"></i> Select all</button>
136
+ <button class="btn btn-ghost" type="button" onclick="selectAllChannels(false)"><i class="fa-solid fa-xmark"></i> Clear</button>
137
+ </div>
138
+
139
+ <hr class="divider">
140
+
141
+ <!-- live progress -->
142
+ <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
143
+ <div class="text-sm font-bold" id="scan-current">No scan running</div>
144
+ <div class="text-sm" style="color:var(--text-sec)">
145
+ <i class="fa-regular fa-clock"></i> <span id="scan-elapsed">0s</span>
146
+ </div>
147
+ </div>
148
+ <div class="progress-track mb-4">
149
+ <div class="progress-fill" id="scan-bar"></div>
150
+ </div>
151
+
152
+ <div class="stat-grid mb-4">
153
+ <div class="stat-box"><div class="v" id="sc-processed">0</div><div class="l">Processed</div></div>
154
+ <div class="stat-box"><div class="v" style="color:#22c55e" id="sc-indexed">0</div><div class="l">Indexed</div></div>
155
+ <div class="stat-box"><div class="v" id="sc-dup">0</div><div class="l">Skipped (dup)</div></div>
156
+ <div class="stat-box"><div class="v" id="sc-meta">0</div><div class="l">Skipped (meta)</div></div>
157
+ <div class="stat-box"><div class="v" id="sc-nonvid">0</div><div class="l">Non-video</div></div>
158
+ <div class="stat-box"><div class="v" style="color:#ef4444" id="sc-errors">0</div><div class="l">Errors</div></div>
159
+ </div>
160
+
161
+ <div class="flex items-center gap-2 flex-wrap">
162
+ <button class="btn btn-primary" id="scan-start-btn" onclick="startScan('scan')">
163
+ <i class="fa-solid fa-play"></i> <span id="scan-start-label">Start Scan</span>
164
+ </button>
165
+ <button class="btn btn-warning" id="rescan-btn" onclick="confirmRescan()">
166
+ <i class="fa-solid fa-arrows-rotate"></i> Rescan (wipe & re-index)
167
+ </button>
168
+ <button class="btn btn-danger" id="scan-cancel-btn" onclick="cancelScan()" disabled>
169
+ <i class="fa-solid fa-stop"></i> Stop
170
+ </button>
171
+ </div>
172
+ <p class="hint mt-3" id="scan-error" style="color:#ef4444;display:none"></p>
173
+ </div>
174
+
175
+ <!-- ══ Database Check ════════════════════════════════════════════════ -->
176
+ <div class="tool-card">
177
+ <div class="flex items-center justify-between flex-wrap gap-2">
178
+ <h2 style="margin-bottom:0"><i class="fa-solid fa-stethoscope"></i> Database Check &amp; Dead Links</h2>
179
+ <span id="dbc-status-pill" class="status-pill status-idle">Idle</span>
180
+ </div>
181
+
182
+ <p class="hint mt-3 mb-4">
183
+ Verify that every indexed file still exists on Telegram. Dead entries
184
+ found here can be purged below. Runs are throttled to respect Telegram limits.
185
+ </p>
186
+
187
+ <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
188
+ <div class="text-sm font-bold" id="dbc-current">No check running</div>
189
+ <div class="text-sm" style="color:var(--text-sec)">
190
+ <i class="fa-solid fa-gauge-high"></i> <span id="dbc-speed">0</span>/s ·
191
+ <i class="fa-regular fa-clock"></i> <span id="dbc-elapsed">0s</span>
192
+ </div>
193
+ </div>
194
+ <div class="progress-track mb-4">
195
+ <div class="progress-fill" id="dbc-bar"></div>
196
+ </div>
197
+
198
+ <div class="stat-grid mb-4">
199
+ <div class="stat-box"><div class="v" id="dbc-checked">0</div><div class="l">Checked</div></div>
200
+ <div class="stat-box"><div class="v" style="color:#22c55e" id="dbc-alive">0</div><div class="l">Alive</div></div>
201
+ <div class="stat-box"><div class="v" style="color:#ef4444" id="dbc-dead">0</div><div class="l">Dead</div></div>
202
+ <div class="stat-box"><div class="v" id="dbc-errors">0</div><div class="l">Errors</div></div>
203
+ <div class="stat-box"><div class="v" id="dbc-purged">0</div><div class="l">Purged</div></div>
204
+ </div>
205
+
206
+ <div class="flex items-center gap-2 flex-wrap">
207
+ <button class="btn btn-primary" id="dbc-start-btn" onclick="startDbCheck()">
208
+ <i class="fa-solid fa-play"></i> Run DB Check
209
+ </button>
210
+ <button class="btn btn-danger" id="dbc-cancel-btn" onclick="cancelDbCheck()" disabled>
211
+ <i class="fa-solid fa-stop"></i> Stop
212
+ </button>
213
+ </div>
214
+
215
+ <hr class="divider">
216
+
217
+ <!-- Dead links -->
218
+ <div class="flex items-center justify-between mb-3 flex-wrap gap-2">
219
+ <label class="s-label" style="margin-bottom:0">Dead links found</label>
220
+ <div class="flex items-center gap-2">
221
+ <button class="btn btn-ghost" type="button" onclick="loadFlaggedDeadLinks()">
222
+ <i class="fa-solid fa-rotate"></i> Load flagged
223
+ </button>
224
+ <button class="btn btn-danger" id="purge-btn" onclick="purgeDeadLinks()" disabled>
225
+ <i class="fa-solid fa-trash"></i> <span id="purge-label">Purge dead links</span>
226
+ </button>
227
+ </div>
228
+ </div>
229
+ <p class="hint mb-3">
230
+ "Load flagged" shows dead links detected automatically by the background checker.
231
+ Running a DB Check above also fills this list. Purging removes those entries from the database.
232
+ </p>
233
+ <div class="dead-list" id="dead-list">
234
+ <div class="hint">No dead links to show yet. Run a DB Check or load flagged links.</div>
235
+ </div>
236
+ </div>
237
+
238
+ </div>
239
+
240
+ <script>
241
+ /* ─────────────── State ─────────────── */
242
+ let scanTimer = null;
243
+ let dbcTimer = null;
244
+ let deadSource = "dbcheck"; // where the current dead list came from
245
+ let purgeIds = []; // explicit ids to purge when source = flagged
246
+
247
+ /* ─────────────── Channels ─────────────── */
248
+ async function loadChannels() {
249
+ const list = document.getElementById('channel-list');
250
+ try {
251
+ const res = await fetch('/api/admin/tools/channels');
252
+ const data = await res.json();
253
+ const channels = (data && data.data) || [];
254
+ if (!channels.length) {
255
+ list.innerHTML = `<div class="hint">No AUTH channels configured. Add them in <a href="/admin/settings" style="color:var(--primary)">Settings</a>.</div>`;
256
+ return;
257
+ }
258
+ list.innerHTML = channels.map(c => `
259
+ <label class="chip" data-id="${escapeHtmlAttr(c.id)}">
260
+ <input type="checkbox" value="${escapeHtmlAttr(c.id)}" onchange="onChipChange(this)">
261
+ <span class="min-w-0">
262
+ <span class="c-name block">${escapeHtml(c.name)}</span>
263
+ <span class="c-id">${escapeHtml(c.id)}</span>
264
+ </span>
265
+ </label>
266
+ `).join('');
267
+ } catch (e) {
268
+ list.innerHTML = `<div class="hint" style="color:#ef4444">Failed to load channels.</div>`;
269
+ }
270
+ }
271
+
272
+ function onChipChange(input) {
273
+ input.closest('.chip').classList.toggle('selected', input.checked);
274
+ }
275
+ function selectAllChannels(state) {
276
+ document.querySelectorAll('#channel-list input[type=checkbox]').forEach(cb => {
277
+ cb.checked = state;
278
+ onChipChange(cb);
279
+ });
280
+ }
281
+ function getSelectedChannels() {
282
+ return [...document.querySelectorAll('#channel-list input[type=checkbox]:checked')].map(cb => cb.value);
283
+ }
284
+
285
+ /* ─────────────── Scan control ─────────────── */
286
+ async function startScan(mode) {
287
+ const channels = getSelectedChannels();
288
+ if (mode === 'scan' && !channels.length) {
289
+ // allow plain resume with no selection only if resumable
290
+ showToast('Select at least one channel to scan.', 'error', 'No channels');
291
+ return;
292
+ }
293
+ try {
294
+ const res = await fetch('/api/admin/tools/scan/start', {
295
+ method: 'POST',
296
+ headers: { 'Content-Type': 'application/json' },
297
+ body: JSON.stringify({ mode, channels })
298
+ });
299
+ const data = await res.json();
300
+ if (res.ok) {
301
+ showToast(data.message || 'Scan started.', 'success', 'Scanner');
302
+ startScanPolling();
303
+ } else {
304
+ showToast(data.detail || 'Could not start scan.', 'error', 'Error');
305
+ }
306
+ } catch (e) {
307
+ showToast('Network error.', 'error', 'Error');
308
+ }
309
+ }
310
+
311
+ function confirmRescan() {
312
+ const channels = getSelectedChannels();
313
+ if (!channels.length) {
314
+ showToast('Select the channels you want to rescan.', 'error', 'No channels');
315
+ return;
316
+ }
317
+ if (!confirm(`Rescan will DELETE all existing DB entries for ${channels.length} selected channel(s) and re-index from scratch.\n\nProceed?`)) return;
318
+ startScan('rescan');
319
+ }
320
+
321
+ async function cancelScan() {
322
+ try {
323
+ const res = await fetch('/api/admin/tools/scan/cancel', { method: 'POST' });
324
+ const data = await res.json();
325
+ showToast(data.message || 'Stop requested.', data.ok ? 'info' : 'error', 'Scanner');
326
+ } catch (e) {
327
+ showToast('Network error.', 'error', 'Error');
328
+ }
329
+ }
330
+
331
+ function startScanPolling() {
332
+ if (scanTimer) clearInterval(scanTimer);
333
+ pollScan();
334
+ scanTimer = setInterval(pollScan, 1500);
335
+ }
336
+
337
+ async function pollScan() {
338
+ try {
339
+ const res = await fetch('/api/admin/tools/scan/status');
340
+ const data = await res.json();
341
+ renderScan(data.data || {});
342
+ } catch (e) { /* ignore transient errors */ }
343
+ }
344
+
345
+ function renderScan(s) {
346
+ const pill = document.getElementById('scan-status-pill');
347
+ const status = s.status || 'idle';
348
+ pill.className = 'status-pill status-' + status;
349
+ pill.textContent = status.charAt(0).toUpperCase() + status.slice(1);
350
+
351
+ const c = s.counters || {};
352
+ setText('sc-processed', c.processed || 0);
353
+ setText('sc-indexed', c.indexed || 0);
354
+ setText('sc-dup', c.skipped_dup || 0);
355
+ setText('sc-meta', c.skipped_meta || 0);
356
+ setText('sc-nonvid', c.skipped_nonvid || 0);
357
+ setText('sc-errors', c.errors || 0);
358
+ setText('scan-elapsed', s.elapsed || '0s');
359
+
360
+ const bar = document.getElementById('scan-bar');
361
+ const startBtn = document.getElementById('scan-start-btn');
362
+ const cancelBtn = document.getElementById('scan-cancel-btn');
363
+ const rescanBtn = document.getElementById('rescan-btn');
364
+ const startLabel = document.getElementById('scan-start-label');
365
+ const errEl = document.getElementById('scan-error');
366
+
367
+ if (s.is_running) {
368
+ const name = s.current_channel_name || s.current_channel || '';
369
+ document.getElementById('scan-current').textContent =
370
+ `Scanning ${name}` + (s.current_id ? ` · up to msg #${s.current_id}` : '');
371
+ bar.classList.add('indeterminate');
372
+ startBtn.disabled = true; rescanBtn.disabled = true; cancelBtn.disabled = false;
373
+ errEl.style.display = 'none';
374
+ } else {
375
+ bar.classList.remove('indeterminate');
376
+ startBtn.disabled = false; rescanBtn.disabled = false; cancelBtn.disabled = true;
377
+
378
+ if (s.resumable) {
379
+ startLabel.textContent = 'Resume Scan';
380
+ bar.style.width = '60%';
381
+ document.getElementById('scan-current').textContent =
382
+ `Paused — ${ (s.pending||[]).length } channel(s) remaining. Resume to continue.`;
383
+ } else {
384
+ startLabel.textContent = 'Start Scan';
385
+ bar.style.width = (status === 'completed') ? '100%' : '0%';
386
+ document.getElementById('scan-current').textContent =
387
+ status === 'completed' ? 'Scan complete.' :
388
+ status === 'error' ? 'Scan failed.' : 'No scan running';
389
+ }
390
+
391
+ if (s.error) { errEl.style.display = ''; errEl.textContent = s.error; }
392
+ else errEl.style.display = 'none';
393
+
394
+ if (scanTimer && ['completed','cancelled','error','paused','idle'].includes(status)) {
395
+ clearInterval(scanTimer); scanTimer = null;
396
+ }
397
+ }
398
+ }
399
+
400
+ /* ─────────────── DB Check control ─────────────── */
401
+ async function startDbCheck() {
402
+ try {
403
+ const res = await fetch('/api/admin/tools/dbcheck/start', { method: 'POST' });
404
+ const data = await res.json();
405
+ if (res.ok) {
406
+ showToast('DB check started.', 'success', 'DB Check');
407
+ startDbcPolling();
408
+ } else {
409
+ showToast(data.detail || 'Could not start.', 'error', 'Error');
410
+ }
411
+ } catch (e) { showToast('Network error.', 'error', 'Error'); }
412
+ }
413
+
414
+ async function cancelDbCheck() {
415
+ try {
416
+ const res = await fetch('/api/admin/tools/dbcheck/cancel', { method: 'POST' });
417
+ const data = await res.json();
418
+ showToast(data.message || 'Stop requested.', data.ok ? 'info' : 'error', 'DB Check');
419
+ } catch (e) { showToast('Network error.', 'error', 'Error'); }
420
+ }
421
+
422
+ function startDbcPolling() {
423
+ if (dbcTimer) clearInterval(dbcTimer);
424
+ pollDbc();
425
+ dbcTimer = setInterval(pollDbc, 1500);
426
+ }
427
+
428
+ async function pollDbc() {
429
+ try {
430
+ const res = await fetch('/api/admin/tools/dbcheck/status');
431
+ const data = await res.json();
432
+ renderDbc(data.data || {});
433
+ } catch (e) { /* ignore */ }
434
+ }
435
+
436
+ function renderDbc(s) {
437
+ const pill = document.getElementById('dbc-status-pill');
438
+ const status = s.status || 'idle';
439
+ pill.className = 'status-pill status-' + status;
440
+ pill.textContent = status.charAt(0).toUpperCase() + status.slice(1);
441
+
442
+ setText('dbc-checked', s.checked || 0);
443
+ setText('dbc-alive', s.alive || 0);
444
+ setText('dbc-dead', s.dead || 0);
445
+ setText('dbc-errors', s.errors || 0);
446
+ setText('dbc-purged', s.purged || 0);
447
+ setText('dbc-speed', s.speed || 0);
448
+ setText('dbc-elapsed', s.elapsed || '0s');
449
+
450
+ const bar = document.getElementById('dbc-bar');
451
+ const startBtn = document.getElementById('dbc-start-btn');
452
+ const cancelBtn = document.getElementById('dbc-cancel-btn');
453
+
454
+ if (s.is_running) {
455
+ document.getElementById('dbc-current').textContent = `Checking… ${s.checked || 0} verified`;
456
+ bar.classList.add('indeterminate');
457
+ startBtn.disabled = true; cancelBtn.disabled = false;
458
+ } else {
459
+ bar.classList.remove('indeterminate');
460
+ bar.style.width = (status === 'completed' || status === 'cancelled') ? '100%' : '0%';
461
+ startBtn.disabled = false; cancelBtn.disabled = true;
462
+ document.getElementById('dbc-current').textContent =
463
+ status === 'completed' ? `Done — ${s.dead || 0} dead found.` :
464
+ status === 'cancelled' ? 'Stopped.' :
465
+ status === 'error' ? 'Check failed.' : 'No check running';
466
+
467
+ if (dbcTimer && ['completed','cancelled','error','idle'].includes(status)) {
468
+ clearInterval(dbcTimer); dbcTimer = null;
469
+ }
470
+ }
471
+
472
+ // refresh dead list from this run's findings
473
+ if ((s.dead_entries || []).length || status === 'completed') {
474
+ deadSource = 'dbcheck';
475
+ purgeIds = [];
476
+ renderDeadList(s.dead_entries || []);
477
+ }
478
+ }
479
+
480
+ /* ─────────────── Dead links ─────────────── */
481
+ function renderDeadList(entries) {
482
+ const list = document.getElementById('dead-list');
483
+ const purgeBtn = document.getElementById('purge-btn');
484
+ const purgeLabel = document.getElementById('purge-label');
485
+
486
+ if (!entries.length) {
487
+ list.innerHTML = `<div class="hint">No dead links to show.</div>`;
488
+ purgeBtn.disabled = true;
489
+ purgeLabel.textContent = 'Purge dead links';
490
+ return;
491
+ }
492
+ list.innerHTML = entries.map(e => `
493
+ <div class="dead-row">
494
+ <span class="min-w-0 truncate">
495
+ <i class="fa-solid fa-link-slash" style="color:#ef4444"></i>
496
+ ${escapeHtml(e.title || 'Unknown')}
497
+ ${e.quality ? `<span class="c-id">· ${escapeHtml(e.quality)}</span>` : ''}
498
+ </span>
499
+ </div>
500
+ `).join('');
501
+ purgeBtn.disabled = false;
502
+ purgeLabel.textContent = `Purge ${entries.length} dead link${entries.length === 1 ? '' : 's'}`;
503
+ }
504
+
505
+ async function loadFlaggedDeadLinks() {
506
+ try {
507
+ const res = await fetch('/api/admin/dead-links');
508
+ const data = await res.json();
509
+ const links = (data && data.data) || [];
510
+ deadSource = 'flagged';
511
+ purgeIds = links.map(l => l.quality_id).filter(Boolean);
512
+ renderDeadList(links.map(l => ({ title: l.title, quality: l.quality })));
513
+ showToast(`${links.length} flagged dead link(s) loaded.`, 'info', 'Dead Links');
514
+ } catch (e) { showToast('Failed to load flagged links.', 'error', 'Error'); }
515
+ }
516
+
517
+ async function purgeDeadLinks() {
518
+ if (!confirm('Permanently remove these dead links from the database?')) return;
519
+ const btn = document.getElementById('purge-btn');
520
+ btn.disabled = true;
521
+ const body = (deadSource === 'flagged')
522
+ ? { source: 'flagged' }
523
+ : { source: 'dbcheck' };
524
+ try {
525
+ const res = await fetch('/api/admin/tools/dead-links/purge', {
526
+ method: 'POST',
527
+ headers: { 'Content-Type': 'application/json' },
528
+ body: JSON.stringify(body)
529
+ });
530
+ const data = await res.json();
531
+ if (res.ok && data.ok) {
532
+ showToast(data.message || 'Purged.', 'success', 'Dead Links');
533
+ renderDeadList([]);
534
+ pollDbc();
535
+ } else {
536
+ showToast(data.message || data.detail || 'Nothing to purge.', 'error', 'Dead Links');
537
+ btn.disabled = false;
538
+ }
539
+ } catch (e) {
540
+ showToast('Network error.', 'error', 'Error');
541
+ btn.disabled = false;
542
+ }
543
+ }
544
+
545
+ /* ─────────────── Utils ─────────────── */
546
+ function setText(id, val) { const el = document.getElementById(id); if (el) el.textContent = val; }
547
+ function escapeHtml(str) {
548
+ return String(str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;')
549
+ .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
550
+ }
551
+ function escapeHtmlAttr(str) {
552
+ return String(str || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;');
553
+ }
554
+
555
+ /* ─────────────── Init ─────────────── */
556
+ loadChannels();
557
+ pollScan().then(() => {
558
+ const pill = document.getElementById('scan-status-pill');
559
+ if (pill.classList.contains('status-running')) startScanPolling();
560
+ });
561
+ pollDbc().then(() => {
562
+ const pill = document.getElementById('dbc-status-pill');
563
+ if (pill.classList.contains('status-running')) startDbcPolling();
564
+ });
565
+ </script>
566
+
567
+ {% endblock %}
Backend/helper/pyro.py CHANGED
@@ -13,13 +13,6 @@ from pyrogram.types import BotCommand
13
  from pyrogram import enums
14
 
15
 
16
-
17
-
18
- # ---------------------------------------------------------------------------
19
- # Pre-compiled patterns used in clean_filename
20
- # ---------------------------------------------------------------------------
21
-
22
- # Broad emoji / unicode-symbol regex (covers all major Unicode emoji blocks)
23
  _EMOJI_PATTERN = re.compile(
24
  "["
25
  "\U0001F600-\U0001F64F" # emoticons
@@ -36,7 +29,6 @@ _EMOJI_PATTERN = re.compile(
36
  re.UNICODE,
37
  )
38
 
39
- # Decorative / non-filename characters that are not emojis but still break PTN
40
  _DECORATION_PATTERN = re.compile(
41
  r"[•·‣⁃◦⦿⦾❖✦✧✪✫✬✭✮★☆♦♣♠♥►◄→←↑↓»«|¦‖⟨⟩⌨⌚⌛⏰⏱⏲⏳✔✖✗✘✅❌❎⚠⛔🚫]+",
42
  re.UNICODE,
@@ -47,7 +39,6 @@ _CHANNEL_TAG_PATTERN = re.compile(
47
  r"_@[A-Za-z]+_|@[A-Za-z]+_|[\[\]\s@]*@[^.\s\[\]]+[\]\[\s@]*"
48
  )
49
 
50
- # Common audio/source tags that are *not* relevant to the title
51
  _CODEC_TAG_PATTERN = re.compile(
52
  r"(?<=\W)(org|AMZN|DDP|DD|NF|AAC|TVDL|5\.1|2\.1|2\.0|7\.0|7\.1|5\.0|~|\b\w+kbps\b)(?=\W)",
53
  re.IGNORECASE,
@@ -105,17 +96,6 @@ def get_readable_file_size(size_in_bytes):
105
 
106
 
107
  def clean_filename(filename: str) -> str:
108
- """
109
- Sanitise a raw Telegram caption / file name so PTN can parse it correctly.
110
-
111
- Processing order:
112
- 1. Strip emoji sequences (they silently confuse PTN)
113
- 2. Strip decorative unicode punctuation (•, ★, »…)
114
- 3. Replace non-ASCII characters that survived with spaces
115
- 4. Remove Telegram channel / username tags
116
- 5. Remove common audio/source codec tags
117
- 6. Collapse whitespace
118
- """
119
  if not filename:
120
  return "unknown_file"
121
 
@@ -221,10 +201,7 @@ async def restart_notification():
221
  commands = [
222
  BotCommand("start", "🚀 Start the bot"),
223
  BotCommand("set", "🎬 Manually add IMDb metadata"),
224
- BotCommand("scan", "🔍 Scan channel content"),
225
- BotCommand("search", "🔎 Search DB by title"),
226
  BotCommand("stats", "📊 DB and system stats"),
227
- BotCommand("dbcheck", "🩺 Check DB integrity"),
228
  BotCommand("log", "📄 Send the log file"),
229
  BotCommand("restart", "♻️ Restart the bot"),
230
  ]
 
13
  from pyrogram import enums
14
 
15
 
 
 
 
 
 
 
 
16
  _EMOJI_PATTERN = re.compile(
17
  "["
18
  "\U0001F600-\U0001F64F" # emoticons
 
29
  re.UNICODE,
30
  )
31
 
 
32
  _DECORATION_PATTERN = re.compile(
33
  r"[•·‣⁃◦⦿⦾❖✦✧✪✫✬✭✮★☆♦♣♠♥►◄→←↑↓»«|¦‖⟨⟩⌨⌚⌛⏰⏱⏲⏳✔✖✗✘✅❌❎⚠⛔🚫]+",
34
  re.UNICODE,
 
39
  r"_@[A-Za-z]+_|@[A-Za-z]+_|[\[\]\s@]*@[^.\s\[\]]+[\]\[\s@]*"
40
  )
41
 
 
42
  _CODEC_TAG_PATTERN = re.compile(
43
  r"(?<=\W)(org|AMZN|DDP|DD|NF|AAC|TVDL|5\.1|2\.1|2\.0|7\.0|7\.1|5\.0|~|\b\w+kbps\b)(?=\W)",
44
  re.IGNORECASE,
 
96
 
97
 
98
  def clean_filename(filename: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
99
  if not filename:
100
  return "unknown_file"
101
 
 
201
  commands = [
202
  BotCommand("start", "🚀 Start the bot"),
203
  BotCommand("set", "🎬 Manually add IMDb metadata"),
 
 
204
  BotCommand("stats", "📊 DB and system stats"),
 
205
  BotCommand("log", "📄 Send the log file"),
206
  BotCommand("restart", "♻️ Restart the bot"),
207
  ]
Backend/helper/scan_manager.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import time
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from pyrogram.errors import FloodWait, ChannelPrivate, ChatAdminRequired
8
+
9
+ from Backend.logger import LOGGER
10
+ from Backend.helper.encrypt import encode_string, decode_string
11
+ from Backend.helper.metadata import metadata
12
+ from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
13
+
14
+
15
+ # ─────────────────────────────────────────────────────────────────────────────
16
+ # Tunables — kept conservative so we never trip Telegram's flood limits.
17
+ # ─────────────────────────────────────────────────────────────────────────────
18
+ SCAN_BATCH_SIZE = 200 # get_messages accepts up to 200 ids per call
19
+ SCAN_MAX_EMPTY_BATCHES = 10 # stop after this many consecutive empty batches
20
+ SCAN_MAX_ID_CAP = 1_000_000 # hard ceiling to avoid runaway loops
21
+ SCAN_BATCH_DELAY = 0.5 # seconds to sleep between batches
22
+ SCAN_PERSIST_EVERY = 1 # persist state every N batches
23
+
24
+ DBCHECK_CONCURRENCY = 5 # concurrent get_messages during integrity check
25
+ DBCHECK_BATCH_DELAY = 0.3 # seconds between concurrent groups
26
+ DBCHECK_PAGE_SIZE = 100 # mongo pagination size
27
+
28
+ _STATE_COLLECTION = "scan_state"
29
+ _SCAN_DOC_ID = "scan"
30
+
31
+
32
+ def _now() -> float:
33
+ return time.time()
34
+
35
+
36
+ def _fmt_elapsed(seconds: float) -> str:
37
+ s = int(seconds)
38
+ m, s = divmod(s, 60)
39
+ h, m = divmod(m, 60)
40
+ if h:
41
+ return f"{h}h {m}m {s}s"
42
+ if m:
43
+ return f"{m}m {s}s"
44
+ return f"{s}s"
45
+
46
+
47
+ # ═════════════════════════════════════════════════════════════════════════════
48
+ # ScanManager — resumable channel indexer
49
+ # ═════════════════════════════════════════════════════════════════════════════
50
+ class ScanManager:
51
+ def __init__(self) -> None:
52
+ self._db = None
53
+ self._task: Optional[asyncio.Task] = None
54
+ self._cancel = False
55
+ self._lock = asyncio.Lock()
56
+ self.state: Dict[str, Any] = self._blank_state()
57
+
58
+ # ── State helpers ────────────────────────────────────────────────────────
59
+ @staticmethod
60
+ def _blank_state() -> Dict[str, Any]:
61
+ return {
62
+ "status": "idle", # idle|running|paused|completed|cancelled|error
63
+ "mode": "scan", # scan|rescan
64
+ "selected_channels": [], # channels chosen for the active run
65
+ "pending": [], # channels still to finish this run
66
+ "current_channel": None,
67
+ "current_channel_name": "",
68
+ "current_id": 0, # last message id reached in current channel
69
+ "cursors": {}, # {channel_id: next_message_id} — persistent
70
+ "counters": {
71
+ "total_found": 0,
72
+ "processed": 0,
73
+ "indexed": 0,
74
+ "skipped_dup": 0,
75
+ "skipped_meta": 0,
76
+ "skipped_nonvid": 0,
77
+ "errors": 0,
78
+ },
79
+ "started_at": 0.0,
80
+ "updated_at": 0.0,
81
+ "finished_at": 0.0,
82
+ "error": None,
83
+ }
84
+
85
+ @staticmethod
86
+ def _blank_counters() -> Dict[str, int]:
87
+ return {
88
+ "total_found": 0,
89
+ "processed": 0,
90
+ "indexed": 0,
91
+ "skipped_dup": 0,
92
+ "skipped_meta": 0,
93
+ "skipped_nonvid": 0,
94
+ "errors": 0,
95
+ }
96
+
97
+ def bind_db(self, db) -> None:
98
+ self._db = db
99
+
100
+ async def load(self, db) -> None:
101
+ """Load persisted state on boot. A scan that was 'running' when the
102
+ process died is flipped to 'paused' so the user can resume it."""
103
+ self._db = db
104
+ try:
105
+ doc = await db.dbs["tracking"][_STATE_COLLECTION].find_one({"_id": _SCAN_DOC_ID})
106
+ except Exception as e:
107
+ LOGGER.error(f"[ScanManager] load failed: {e}")
108
+ doc = None
109
+
110
+ if doc:
111
+ doc.pop("_id", None)
112
+ merged = self._blank_state()
113
+ merged.update(doc)
114
+ # Normalise cursor keys to str (mongo keys are strings anyway)
115
+ merged["cursors"] = {str(k): int(v) for k, v in (merged.get("cursors") or {}).items()}
116
+ if merged["status"] == "running":
117
+ merged["status"] = "paused"
118
+ self.state = merged
119
+ if self.state["status"] == "paused":
120
+ LOGGER.info("[ScanManager] Found an interrupted scan — marked as paused (resumable).")
121
+ await self._persist()
122
+ else:
123
+ self.state = self._blank_state()
124
+
125
+ async def _persist(self) -> None:
126
+ if self._db is None:
127
+ return
128
+ self.state["updated_at"] = _now()
129
+ try:
130
+ doc = dict(self.state)
131
+ doc["_id"] = _SCAN_DOC_ID
132
+ await self._db.dbs["tracking"][_STATE_COLLECTION].update_one(
133
+ {"_id": _SCAN_DOC_ID}, {"$set": doc}, upsert=True
134
+ )
135
+ except Exception as e:
136
+ LOGGER.error(f"[ScanManager] persist failed: {e}")
137
+
138
+ # ── Public status (serialisable for the API) ─────────────────────────────
139
+ def get_status(self) -> Dict[str, Any]:
140
+ s = self.state
141
+ elapsed = 0.0
142
+ if s["started_at"]:
143
+ end = s["finished_at"] or _now()
144
+ elapsed = max(0.0, end - s["started_at"])
145
+ return {
146
+ "status": s["status"],
147
+ "mode": s["mode"],
148
+ "is_running": s["status"] == "running",
149
+ "resumable": s["status"] in ("paused", "cancelled") and bool(s["pending"]),
150
+ "selected_channels": list(s["selected_channels"]),
151
+ "pending": list(s["pending"]),
152
+ "current_channel": s["current_channel"],
153
+ "current_channel_name": s["current_channel_name"],
154
+ "current_id": s["current_id"],
155
+ "counters": dict(s["counters"]),
156
+ "elapsed": _fmt_elapsed(elapsed),
157
+ "elapsed_seconds": int(elapsed),
158
+ "error": s["error"],
159
+ }
160
+
161
+ # ── Duplicate detection ──────────────────────────────────────────────────
162
+ async def _stream_id_exists(self, channel: int, msg_id: int) -> bool:
163
+ db = self._db
164
+ try:
165
+ stream_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
166
+ except Exception:
167
+ return False
168
+ for i in range(1, db.current_db_index + 1):
169
+ storage = db.dbs.get(f"storage_{i}")
170
+ if storage is None:
171
+ continue
172
+ if await storage["movie"].find_one({"telegram.id": stream_hash}):
173
+ return True
174
+ if await storage["tv"].find_one({"seasons.episodes.telegram.id": stream_hash}):
175
+ return True
176
+ return False
177
+
178
+ # ── Control: start / resume / cancel ─────────────────────────────────────
179
+ async def start(self, client, channels: List[str], mode: str = "scan") -> Dict[str, Any]:
180
+ """Start (or resume) a scan.
181
+
182
+ mode == "rescan" → purge selected channels, reset their cursors, fresh scan.
183
+ mode == "scan" → resume any pending work, scanning each channel from its
184
+ saved cursor (so previously-indexed messages are skipped
185
+ and we continue exactly where we left off).
186
+ """
187
+ async with self._lock:
188
+ if self.state["status"] == "running":
189
+ return {"ok": False, "message": "A scan is already running."}
190
+
191
+ channels = [str(c).strip() for c in (channels or []) if str(c).strip()]
192
+
193
+ if mode == "scan" and not channels and self.state["pending"]:
194
+ # Plain resume of an interrupted run
195
+ channels = list(self.state["pending"])
196
+
197
+ if not channels:
198
+ return {"ok": False, "message": "No channels selected."}
199
+
200
+ if mode == "rescan":
201
+ # Purge + reset cursors for the selected channels
202
+ for ch in channels:
203
+ try:
204
+ ch_int = int(str(ch).replace("-100", ""))
205
+ except ValueError:
206
+ continue
207
+ try:
208
+ await self._purge_channel_entries(ch_int)
209
+ except Exception as e:
210
+ LOGGER.error(f"[ScanManager] purge failed for {ch}: {e}")
211
+ self.state["cursors"].pop(str(ch), None)
212
+ self.state["selected_channels"] = list(channels)
213
+ self.state["pending"] = list(channels)
214
+ self.state["counters"] = self._blank_counters()
215
+ else:
216
+ # Resume / fresh incremental scan
217
+ resuming = self.state["status"] in ("paused", "cancelled") and self.state["pending"]
218
+ if resuming:
219
+ # Merge any newly-selected channels into the pending queue
220
+ merged_pending = list(self.state["pending"])
221
+ for ch in channels:
222
+ if ch not in merged_pending:
223
+ merged_pending.append(ch)
224
+ self.state["pending"] = merged_pending
225
+ self.state["selected_channels"] = list(
226
+ dict.fromkeys(self.state["selected_channels"] + channels)
227
+ )
228
+ else:
229
+ self.state["selected_channels"] = list(channels)
230
+ self.state["pending"] = list(channels)
231
+ self.state["counters"] = self._blank_counters()
232
+
233
+ self.state["mode"] = mode
234
+ self.state["status"] = "running"
235
+ self.state["error"] = None
236
+ self.state["finished_at"] = 0.0
237
+ self.state["started_at"] = _now()
238
+ self._cancel = False
239
+ await self._persist()
240
+
241
+ self._task = asyncio.create_task(self._run(client))
242
+ return {"ok": True, "message": f"{'Rescan' if mode == 'rescan' else 'Scan'} started.",
243
+ "status": self.get_status()}
244
+
245
+ async def cancel(self) -> Dict[str, Any]:
246
+ if self.state["status"] != "running":
247
+ return {"ok": False, "message": "No scan is currently running."}
248
+ self._cancel = True
249
+ return {"ok": True, "message": "Stop requested — the scan will pause after the current batch."}
250
+
251
+ # ── Worker ────────────────────────────────────────────────────────────────
252
+ async def _run(self, client) -> None:
253
+ try:
254
+ while self.state["pending"] and not self._cancel:
255
+ ch = self.state["pending"][0]
256
+ try:
257
+ ch_id = int(ch)
258
+ except ValueError:
259
+ LOGGER.warning(f"[ScanManager] invalid channel id: {ch}")
260
+ self.state["pending"].pop(0)
261
+ await self._persist()
262
+ continue
263
+
264
+ completed = await self._scan_channel(client, ch_id, ch)
265
+ if self._cancel:
266
+ break
267
+ if completed:
268
+ # channel done for this run — drop it from pending
269
+ if self.state["pending"] and self.state["pending"][0] == ch:
270
+ self.state["pending"].pop(0)
271
+ await self._persist()
272
+
273
+ if self._cancel:
274
+ self.state["status"] = "cancelled"
275
+ LOGGER.info("[ScanManager] Scan cancelled by user (resumable).")
276
+ else:
277
+ self.state["status"] = "completed"
278
+ self.state["current_channel"] = None
279
+ self.state["current_channel_name"] = ""
280
+ LOGGER.info("[ScanManager] Scan completed.")
281
+ self.state["finished_at"] = _now()
282
+ await self._persist()
283
+
284
+ except (ChannelPrivate, ChatAdminRequired) as e:
285
+ self.state["status"] = "error"
286
+ self.state["error"] = f"Access denied to channel — make sure the bot is an admin. ({e})"
287
+ self.state["finished_at"] = _now()
288
+ LOGGER.error(f"[ScanManager] {self.state['error']}")
289
+ await self._persist()
290
+ except asyncio.CancelledError:
291
+ # Process is shutting down — leave status running so load() flips to paused
292
+ await self._persist()
293
+ raise
294
+ except Exception as e:
295
+ self.state["status"] = "error"
296
+ self.state["error"] = str(e)
297
+ self.state["finished_at"] = _now()
298
+ LOGGER.error(f"[ScanManager] Unexpected error: {e}")
299
+ await self._persist()
300
+
301
+ async def _scan_channel(self, client, chat_id: int, ch_key: str) -> bool:
302
+ """Scan one channel from its saved cursor. Returns True if it ran to the
303
+ natural end (so it can be removed from the pending queue), False if it
304
+ was interrupted (cancel / shutdown)."""
305
+ db = self._db
306
+ s = self.state
307
+
308
+ try:
309
+ chat = await client.get_chat(chat_id)
310
+ s["current_channel_name"] = getattr(chat, "title", str(chat_id))
311
+ except (ChannelPrivate, ChatAdminRequired):
312
+ raise
313
+ except Exception as e:
314
+ s["current_channel_name"] = str(chat_id)
315
+ LOGGER.warning(f"[ScanManager] Could not resolve channel name for {chat_id}: {e}")
316
+
317
+ s["current_channel"] = ch_key
318
+ current = int(s["cursors"].get(str(ch_key), 1) or 1)
319
+ LOGGER.info(f"[ScanManager] Scanning {s['current_channel_name']} ({chat_id}) from id {current}")
320
+
321
+ empty_streak = 0
322
+ batch_count = 0
323
+
324
+ while empty_streak < SCAN_MAX_EMPTY_BATCHES and current < SCAN_MAX_ID_CAP:
325
+ if self._cancel:
326
+ return False
327
+
328
+ batch_ids = list(range(current, min(current + SCAN_BATCH_SIZE, SCAN_MAX_ID_CAP)))
329
+ try:
330
+ messages = await client.get_messages(chat_id, batch_ids)
331
+ except FloodWait as e:
332
+ LOGGER.info(f"[ScanManager] FloodWait {e.value}s — sleeping…")
333
+ await asyncio.sleep(e.value)
334
+ try:
335
+ messages = await client.get_messages(chat_id, batch_ids)
336
+ except Exception as ex:
337
+ LOGGER.error(f"[ScanManager] Retry failed at {current}: {ex}")
338
+ s["counters"]["errors"] += 1
339
+ current += SCAN_BATCH_SIZE
340
+ empty_streak += 1
341
+ s["cursors"][str(ch_key)] = current
342
+ s["current_id"] = current
343
+ continue
344
+ except Exception as e:
345
+ LOGGER.error(f"[ScanManager] Batch fetch error at {current}: {e}")
346
+ s["counters"]["errors"] += 1
347
+ current += SCAN_BATCH_SIZE
348
+ empty_streak += 1
349
+ s["cursors"][str(ch_key)] = current
350
+ s["current_id"] = current
351
+ continue
352
+
353
+ if not isinstance(messages, list):
354
+ messages = [messages]
355
+
356
+ batch_had_content = False
357
+ for message in messages:
358
+ if self._cancel:
359
+ s["cursors"][str(ch_key)] = current
360
+ s["current_id"] = current
361
+ await self._persist()
362
+ return False
363
+ if message is None or message.empty:
364
+ continue
365
+
366
+ batch_had_content = True
367
+ s["counters"]["total_found"] += 1
368
+ await self._process_message(message, chat_id)
369
+ s["counters"]["processed"] += 1
370
+
371
+ empty_streak = 0 if batch_had_content else empty_streak + 1
372
+ current += SCAN_BATCH_SIZE
373
+ s["cursors"][str(ch_key)] = current
374
+ s["current_id"] = current
375
+
376
+ batch_count += 1
377
+ if batch_count % SCAN_PERSIST_EVERY == 0:
378
+ await self._persist()
379
+
380
+ await asyncio.sleep(SCAN_BATCH_DELAY)
381
+
382
+ await self._persist()
383
+ LOGGER.info(f"[ScanManager] Finished {s['current_channel_name']} at id {current}")
384
+ return True
385
+
386
+ async def _process_message(self, message, chat_id: int) -> None:
387
+ s = self.state
388
+ db = self._db
389
+
390
+ is_video = bool(message.video)
391
+ is_video_doc = False
392
+ if message.document and not is_video:
393
+ mime = getattr(message.document, "mime_type", "") or ""
394
+ is_video_doc = mime.startswith("video/")
395
+
396
+ if not (is_video or is_video_doc):
397
+ s["counters"]["skipped_nonvid"] += 1
398
+ return
399
+
400
+ file = message.video or message.document
401
+ title = message.caption or file.file_name
402
+ msg_id = message.id
403
+ size = get_readable_file_size(file.file_size)
404
+ channel_int = int(str(chat_id).replace("-100", ""))
405
+
406
+ try:
407
+ if await self._stream_id_exists(channel_int, msg_id):
408
+ s["counters"]["skipped_dup"] += 1
409
+ return
410
+ except Exception as e:
411
+ LOGGER.warning(f"[ScanManager] Dup-check error msg {msg_id}: {e}")
412
+
413
+ try:
414
+ metadata_info = await metadata(clean_filename(title), channel_int, msg_id)
415
+ except Exception as e:
416
+ LOGGER.warning(f"[ScanManager] Metadata exception for msg {msg_id}: {e}")
417
+ metadata_info = None
418
+
419
+ if metadata_info is None:
420
+ s["counters"]["skipped_meta"] += 1
421
+ return
422
+
423
+ title_clean = remove_urls(title)
424
+ if not title_clean.endswith(('.mkv', '.mp4')):
425
+ title_clean += '.mkv'
426
+
427
+ try:
428
+ updated_id = await db.insert_media(
429
+ metadata_info,
430
+ channel=channel_int,
431
+ msg_id=msg_id,
432
+ size=size,
433
+ name=title_clean,
434
+ )
435
+ if updated_id:
436
+ s["counters"]["indexed"] += 1
437
+ else:
438
+ s["counters"]["skipped_meta"] += 1
439
+ except Exception as e:
440
+ LOGGER.error(f"[ScanManager] DB insert error msg {msg_id}: {e}")
441
+ s["counters"]["errors"] += 1
442
+
443
+ # ── Purge (rescan helper) ────────────────────────────────────────────────
444
+ async def _purge_channel_entries(self, channel_int: int) -> int:
445
+ db = self._db
446
+ purged = 0
447
+ for i in range(1, db.current_db_index + 1):
448
+ storage = db.dbs.get(f"storage_{i}")
449
+ if storage is None:
450
+ continue
451
+
452
+ async for movie in storage["movie"].find({}):
453
+ remaining = []
454
+ changed = False
455
+ for q in movie.get("telegram", []):
456
+ try:
457
+ decoded = await decode_string(q["id"])
458
+ if int(decoded["chat_id"]) == channel_int:
459
+ purged += 1
460
+ changed = True
461
+ continue
462
+ except Exception:
463
+ pass
464
+ remaining.append(q)
465
+ if changed:
466
+ if remaining:
467
+ movie["telegram"] = remaining
468
+ await storage["movie"].replace_one({"_id": movie["_id"]}, movie)
469
+ else:
470
+ await storage["movie"].delete_one({"_id": movie["_id"]})
471
+
472
+ async for tv in storage["tv"].find({}):
473
+ tv_changed = False
474
+ for season in tv.get("seasons", []):
475
+ for episode in season.get("episodes", []):
476
+ remaining = []
477
+ for q in episode.get("telegram", []):
478
+ try:
479
+ decoded = await decode_string(q["id"])
480
+ if int(decoded["chat_id"]) == channel_int:
481
+ purged += 1
482
+ tv_changed = True
483
+ continue
484
+ except Exception:
485
+ pass
486
+ remaining.append(q)
487
+ episode["telegram"] = remaining
488
+ season["episodes"] = [ep for ep in season["episodes"] if ep.get("telegram")]
489
+ tv["seasons"] = [se for se in tv["seasons"] if se.get("episodes")]
490
+ if tv_changed:
491
+ if tv["seasons"]:
492
+ await storage["tv"].replace_one({"_id": tv["_id"]}, tv)
493
+ else:
494
+ await storage["tv"].delete_one({"_id": tv["_id"]})
495
+ return purged
496
+
497
+
498
+ # ═════════════════════════════════════════════════════════════════════════════
499
+ # DbCheckManager — integrity checker + dead-link purge
500
+ # ═════════════════════════════════════════════════════════════════════════════
501
+ class DbCheckManager:
502
+ def __init__(self) -> None:
503
+ self._db = None
504
+ self._task: Optional[asyncio.Task] = None
505
+ self._cancel = False
506
+ self._lock = asyncio.Lock()
507
+ self.state: Dict[str, Any] = self._blank_state()
508
+
509
+ @staticmethod
510
+ def _blank_state() -> Dict[str, Any]:
511
+ return {
512
+ "status": "idle", # idle|running|completed|cancelled|error
513
+ "checked": 0,
514
+ "alive": 0,
515
+ "dead": 0,
516
+ "errors": 0,
517
+ "purged": 0,
518
+ "speed": 0,
519
+ "dead_entries": [], # [{"id": hash, "title": str}]
520
+ "started_at": 0.0,
521
+ "finished_at": 0.0,
522
+ "error": None,
523
+ }
524
+
525
+ def bind_db(self, db) -> None:
526
+ self._db = db
527
+
528
+ def get_status(self) -> Dict[str, Any]:
529
+ s = self.state
530
+ elapsed = 0.0
531
+ if s["started_at"]:
532
+ end = s["finished_at"] or _now()
533
+ elapsed = max(0.0, end - s["started_at"])
534
+ return {
535
+ "status": s["status"],
536
+ "is_running": s["status"] == "running",
537
+ "checked": s["checked"],
538
+ "alive": s["alive"],
539
+ "dead": s["dead"],
540
+ "errors": s["errors"],
541
+ "purged": s["purged"],
542
+ "speed": s["speed"],
543
+ "dead_count": len(s["dead_entries"]),
544
+ "dead_entries": list(s["dead_entries"]),
545
+ "elapsed": _fmt_elapsed(elapsed),
546
+ "elapsed_seconds": int(elapsed),
547
+ "error": s["error"],
548
+ }
549
+
550
+ # ── Control ───────────────────────────────────────────────────────────────
551
+ async def start(self, client) -> Dict[str, Any]:
552
+ async with self._lock:
553
+ if self.state["status"] == "running":
554
+ return {"ok": False, "message": "A DB check is already running."}
555
+ self.state = self._blank_state()
556
+ self.state["status"] = "running"
557
+ self.state["started_at"] = _now()
558
+ self._cancel = False
559
+ self._task = asyncio.create_task(self._run(client))
560
+ return {"ok": True, "message": "DB check started.", "status": self.get_status()}
561
+
562
+ async def cancel(self) -> Dict[str, Any]:
563
+ if self.state["status"] != "running":
564
+ return {"ok": False, "message": "No DB check is currently running."}
565
+ self._cancel = True
566
+ return {"ok": True, "message": "Stop requested — finishing the current batch."}
567
+
568
+ # ── Single-message check ───────────────────────────────────────────────────
569
+ async def _check_message(self, client, stream_hash: str):
570
+ try:
571
+ decoded = await decode_string(stream_hash)
572
+ # split files store a parts list — every part must be alive
573
+ if isinstance(decoded, dict) and "parts" in decoded:
574
+ parts = decoded.get("parts") or []
575
+ if not parts:
576
+ return False
577
+ for part in parts:
578
+ alive = await self._check_one(client, part.get("chat_id"), part.get("msg_id"))
579
+ if alive is None:
580
+ return None
581
+ if not alive:
582
+ return False
583
+ return True
584
+ return await self._check_one(client, decoded.get("chat_id"), decoded.get("msg_id"))
585
+ except FloodWait as e:
586
+ await asyncio.sleep(e.value)
587
+ return await self._check_message(client, stream_hash)
588
+ except Exception:
589
+ return None
590
+
591
+ async def _check_one(self, client, chat_id, msg_id):
592
+ if chat_id is None or msg_id is None:
593
+ return False
594
+ try:
595
+ chat_id = int(f"-100{chat_id}")
596
+ msg_id = int(msg_id)
597
+ msg = await client.get_messages(chat_id, msg_id)
598
+ if msg is None or msg.empty:
599
+ return False
600
+ return True
601
+ except FloodWait as e:
602
+ await asyncio.sleep(e.value)
603
+ return await self._check_one(client, str(chat_id).replace("-100", ""), msg_id)
604
+ except Exception:
605
+ return None
606
+
607
+ async def _process_batch(self, client, batch: List[str]):
608
+ tasks = [self._check_message(client, h) for h in batch]
609
+ return await asyncio.gather(*tasks, return_exceptions=True)
610
+
611
+ async def _record_results(self, batch: List[str], results) -> None:
612
+ s = self.state
613
+ for stream_hash, result in zip(batch, results):
614
+ s["checked"] += 1
615
+ if result is True:
616
+ s["alive"] += 1
617
+ elif result is False:
618
+ s["dead"] += 1
619
+ title = None
620
+ try:
621
+ title = await self._db.get_title_by_stream_id(stream_hash)
622
+ except Exception:
623
+ pass
624
+ s["dead_entries"].append({"id": stream_hash, "title": title or "Unknown"})
625
+ else:
626
+ s["errors"] += 1
627
+ elapsed = max(1, int(_now() - s["started_at"]))
628
+ s["speed"] = s["checked"] // elapsed
629
+
630
+ # ── Worker ──────────────────────────────────────────────────────────────────
631
+ async def _run(self, client) -> None:
632
+ db = self._db
633
+ s = self.state
634
+ try:
635
+ for i in range(1, db.current_db_index + 1):
636
+ storage = db.dbs.get(f"storage_{i}")
637
+ if storage is None:
638
+ continue
639
+
640
+ # Movies
641
+ last_id = None
642
+ while not self._cancel:
643
+ query = {"_id": {"$gt": last_id}} if last_id else {}
644
+ docs = await storage["movie"].find(query).sort("_id", 1) \
645
+ .limit(DBCHECK_PAGE_SIZE).to_list(length=DBCHECK_PAGE_SIZE)
646
+ if not docs:
647
+ break
648
+ for movie in docs:
649
+ last_id = movie["_id"]
650
+ stream_ids = [q.get("id") for q in movie.get("telegram", []) if q.get("id")]
651
+ for x in range(0, len(stream_ids), DBCHECK_CONCURRENCY):
652
+ if self._cancel:
653
+ break
654
+ batch = stream_ids[x:x + DBCHECK_CONCURRENCY]
655
+ results = await self._process_batch(client, batch)
656
+ await self._record_results(batch, results)
657
+ await asyncio.sleep(DBCHECK_BATCH_DELAY)
658
+
659
+ # TV
660
+ last_id = None
661
+ while not self._cancel:
662
+ query = {"_id": {"$gt": last_id}} if last_id else {}
663
+ docs = await storage["tv"].find(query).sort("_id", 1) \
664
+ .limit(DBCHECK_PAGE_SIZE).to_list(length=DBCHECK_PAGE_SIZE)
665
+ if not docs:
666
+ break
667
+ for show in docs:
668
+ last_id = show["_id"]
669
+ stream_ids = []
670
+ for season in show.get("seasons", []):
671
+ for episode in season.get("episodes", []):
672
+ for q in episode.get("telegram", []):
673
+ if q.get("id"):
674
+ stream_ids.append(q["id"])
675
+ for x in range(0, len(stream_ids), DBCHECK_CONCURRENCY):
676
+ if self._cancel:
677
+ break
678
+ batch = stream_ids[x:x + DBCHECK_CONCURRENCY]
679
+ results = await self._process_batch(client, batch)
680
+ await self._record_results(batch, results)
681
+ await asyncio.sleep(DBCHECK_BATCH_DELAY)
682
+
683
+ s["status"] = "cancelled" if self._cancel else "completed"
684
+ s["finished_at"] = _now()
685
+ LOGGER.info(f"[DbCheck] {s['status']} — checked {s['checked']}, dead {s['dead']}")
686
+ except asyncio.CancelledError:
687
+ s["status"] = "cancelled"
688
+ s["finished_at"] = _now()
689
+ raise
690
+ except Exception as e:
691
+ s["status"] = "error"
692
+ s["error"] = str(e)
693
+ s["finished_at"] = _now()
694
+ LOGGER.error(f"[DbCheck] Error: {e}")
695
+
696
+ # ── Purge ────────────────────────────────────────────────────────────────────
697
+ async def purge(self, stream_ids: Optional[List[str]] = None) -> Dict[str, Any]:
698
+ """Delete the given dead stream entries (defaults to the ones found in the
699
+ last check). Returns how many were purged."""
700
+ db = self._db
701
+ if stream_ids is None:
702
+ stream_ids = [d["id"] for d in self.state.get("dead_entries", [])]
703
+ stream_ids = [h for h in stream_ids if h]
704
+ if not stream_ids:
705
+ return {"ok": False, "message": "No dead links to purge.", "purged": 0}
706
+
707
+ purged = 0
708
+ for x in range(0, len(stream_ids), DBCHECK_CONCURRENCY):
709
+ batch = stream_ids[x:x + DBCHECK_CONCURRENCY]
710
+ results = await asyncio.gather(
711
+ *[db.delete_media_by_stream_id(h) for h in batch],
712
+ return_exceptions=True,
713
+ )
714
+ purged += sum(1 for r in results if r is True)
715
+
716
+ # Drop purged ids from the in-memory dead list
717
+ purged_set = set(stream_ids)
718
+ self.state["dead_entries"] = [
719
+ d for d in self.state.get("dead_entries", []) if d["id"] not in purged_set
720
+ ]
721
+ self.state["purged"] = self.state.get("purged", 0) + purged
722
+ return {"ok": True, "message": f"Purged {purged} dead entr{'y' if purged == 1 else 'ies'}.",
723
+ "purged": purged}
724
+
725
+
726
+ # ── Singletons ──────────────────────────────────────────────────────────────
727
+ scan_manager = ScanManager()
728
+ dbcheck_manager = DbCheckManager()
Backend/pyrofork/plugins/scanner.py DELETED
@@ -1,495 +0,0 @@
1
- """
2
- Channel Scanner Plugin — indexes existing channel content into the database.
3
-
4
- Commands (owner-only, private chat):
5
- /scan — Scan all AUTH_CHANNELs, skip already-indexed messages
6
- /scan <id> — Scan a specific channel by numeric ID
7
- /rescan — Wipe DB entries for AUTH_CHANNELs, then full re-index
8
- /scanstatus — Show progress of any running scan
9
- /cancelscan — Abort a running scan gracefully
10
- """
11
-
12
- import asyncio
13
- import time
14
- from pyrogram import filters, Client, enums
15
- from pyrogram.types import Message
16
- from pyrogram.errors import FloodWait, ChannelPrivate, ChatAdminRequired
17
-
18
- from Backend.helper.custom_filter import CustomFilters
19
- from Backend.logger import LOGGER
20
- from Backend import db
21
- from Backend.helper.settings_manager import SettingsManager
22
- from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
23
- from Backend.helper.metadata import metadata
24
- from Backend.helper.encrypt import encode_string
25
-
26
-
27
- # ── Scan state (singleton — only one scan at a time) ────────────────────
28
- class _ScanState:
29
- def __init__(self):
30
- self.reset()
31
-
32
- def reset(self):
33
- self.running = False
34
- self.cancelled = False
35
- self.channel_id = None
36
- self.channel_name = ""
37
- self.total_found = 0
38
- self.processed = 0
39
- self.indexed = 0
40
- self.skipped_dup = 0
41
- self.skipped_meta = 0
42
- self.skipped_nonvid = 0
43
- self.errors = 0
44
- self.started_at = 0.0
45
- self.status_msg: Message | None = None
46
-
47
- @property
48
- def elapsed(self) -> str:
49
- s = int(time.time() - self.started_at) if self.started_at else 0
50
- m, s = divmod(s, 60)
51
- h, m = divmod(m, 60)
52
- return f"{h}h {m}m {s}s" if h else f"{m}m {s}s"
53
-
54
-
55
- scan_state = _ScanState()
56
-
57
- PROGRESS_EVERY = 15
58
- RATE_LIMIT_DELAY = 0.3
59
-
60
-
61
- # ── Helpers ──────────────────────────────────────────────────────────────
62
-
63
- async def _stream_id_exists(channel: int, msg_id: int) -> bool:
64
- """Check if this (channel, msg_id) combo is already in the DB."""
65
- try:
66
- stream_hash = await encode_string({"chat_id": channel, "msg_id": msg_id})
67
- except Exception:
68
- return False
69
-
70
- # Check across all storage DBs
71
- for i in range(1, db.current_db_index + 1):
72
- storage = db.dbs.get(f"storage_{i}")
73
- if storage is None:
74
- continue
75
- if await storage["movie"].find_one({"telegram.id": stream_hash}):
76
- return True
77
- if await storage["tv"].find_one({"seasons.episodes.telegram.id": stream_hash}):
78
- return True
79
- return False
80
-
81
-
82
- async def _update_progress(force: bool = False):
83
- """Edit the status message with current scan progress."""
84
- s = scan_state
85
- if not s.status_msg:
86
- return
87
- if not force and s.processed % PROGRESS_EVERY != 0:
88
- return
89
- try:
90
- text = (
91
- f"<blockquote>📡 <b>Scanning:</b> {s.channel_name}</blockquote>\n\n"
92
- f"⏱ Elapsed: <code>{s.elapsed}</code>\n"
93
- f"📨 Processed: <code>{s.processed}</code>\n"
94
- f"✅ Indexed: <code>{s.indexed}</code>\n"
95
- f"⏭ Skipped (duplicate): <code>{s.skipped_dup}</code>\n"
96
- f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
97
- f"📎 Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
98
- f"❌ Errors: <code>{s.errors}</code>"
99
- )
100
- await s.status_msg.edit_text(text, parse_mode=enums.ParseMode.HTML)
101
- except FloodWait as e:
102
- await asyncio.sleep(e.value)
103
- except Exception:
104
- pass
105
-
106
-
107
- async def _scan_channel(client: Client, chat_id: int):
108
- """Iterate all video messages in a channel and index them.
109
-
110
- Bots cannot use get_chat_history or search_messages (both user-only).
111
- The only reliable bot method is get_messages with explicit IDs.
112
-
113
- Strategy: walk forward from ID 1 in batches of 200. Keep going even
114
- through empty batches (deleted messages / gaps). Stop after 5
115
- consecutive all-empty batches, which tolerates gaps of up to ~1000 IDs.
116
- Hard cap at 500,000 to prevent infinite loops.
117
- """
118
- s = scan_state
119
-
120
- try:
121
- chat = await client.get_chat(chat_id)
122
- s.channel_name = getattr(chat, "title", str(chat_id))
123
- except (ChannelPrivate, ChatAdminRequired) as e:
124
- LOGGER.error(f"Cannot access channel {chat_id}: {e}")
125
- raise
126
- except Exception as e:
127
- s.channel_name = str(chat_id)
128
- LOGGER.warning(f"Could not resolve channel name for {chat_id}: {e}")
129
-
130
- s.channel_id = chat_id
131
- LOGGER.info(f"[Scanner] Starting scan of {s.channel_name} ({chat_id})")
132
-
133
- BATCH_SIZE = 200
134
- MAX_EMPTY_BATCHES = 5
135
- MAX_ID_CAP = 500_000
136
- empty_streak = 0
137
- current = 1
138
-
139
- while empty_streak < MAX_EMPTY_BATCHES and current < MAX_ID_CAP:
140
- if s.cancelled:
141
- LOGGER.info("[Scanner] Scan cancelled by user.")
142
- break
143
-
144
- batch_ids = list(range(current, min(current + BATCH_SIZE, MAX_ID_CAP)))
145
-
146
- try:
147
- messages = await client.get_messages(chat_id, batch_ids)
148
- except FloodWait as e:
149
- LOGGER.info(f"[Scanner] FloodWait {e.value}s, sleeping…")
150
- await asyncio.sleep(e.value)
151
- try:
152
- messages = await client.get_messages(chat_id, batch_ids)
153
- except Exception as ex:
154
- LOGGER.error(f"[Scanner] Retry failed at {current}: {ex}")
155
- s.errors += 1
156
- current += BATCH_SIZE
157
- empty_streak += 1
158
- continue
159
- except Exception as e:
160
- LOGGER.error(f"[Scanner] Batch fetch error at {current}: {e}")
161
- s.errors += 1
162
- current += BATCH_SIZE
163
- empty_streak += 1
164
- continue
165
-
166
- if not isinstance(messages, list):
167
- messages = [messages]
168
-
169
- batch_had_content = False
170
-
171
- for message in messages:
172
- if s.cancelled:
173
- break
174
-
175
- if message.empty:
176
- continue
177
-
178
- batch_had_content = True
179
- s.total_found += 1
180
-
181
- # Only process videos / video documents
182
- is_video = bool(message.video)
183
- is_video_doc = False
184
- if message.document and not is_video:
185
- mime = getattr(message.document, "mime_type", "") or ""
186
- is_video_doc = mime.startswith("video/")
187
-
188
- if not (is_video or is_video_doc):
189
- s.skipped_nonvid += 1
190
- s.processed += 1
191
- await _update_progress()
192
- continue
193
-
194
- file = message.video or message.document
195
- title = message.caption or file.file_name
196
- msg_id = message.id
197
- size = get_readable_file_size(file.file_size)
198
- channel = str(chat_id).replace("-100", "")
199
- channel_int = int(channel)
200
-
201
- # ── Duplicate check ──────────────────────────────────
202
- try:
203
- if await _stream_id_exists(channel_int, msg_id):
204
- s.skipped_dup += 1
205
- s.processed += 1
206
- await _update_progress()
207
- continue
208
- except Exception as e:
209
- LOGGER.warning(f"[Scanner] Dup-check error msg {msg_id}: {e}")
210
-
211
- # ── Metadata extraction (same pipeline as receiver) ──
212
- try:
213
- metadata_info = await metadata(clean_filename(title), channel_int, msg_id)
214
- except Exception as e:
215
- LOGGER.warning(f"[Scanner] Metadata exception for msg {msg_id}: {e}")
216
- metadata_info = None
217
-
218
- if metadata_info is None:
219
- s.skipped_meta += 1
220
- s.processed += 1
221
- await _update_progress()
222
- continue
223
-
224
- title_clean = remove_urls(title)
225
- if not title_clean.endswith(('.mkv', '.mp4')):
226
- title_clean += '.mkv'
227
-
228
- # ── Insert into DB ───────────────────────────────────
229
- try:
230
- updated_id = await db.insert_media(
231
- metadata_info,
232
- channel=channel_int,
233
- msg_id=msg_id,
234
- size=size,
235
- name=title_clean,
236
- )
237
- if updated_id:
238
- s.indexed += 1
239
- LOGGER.info(f"[Scanner] Indexed msg {msg_id}: {title_clean}")
240
- else:
241
- s.skipped_meta += 1
242
- except Exception as e:
243
- LOGGER.error(f"[Scanner] DB insert error msg {msg_id}: {e}")
244
- s.errors += 1
245
-
246
- s.processed += 1
247
- await _update_progress()
248
-
249
- # Track empty batches to know when to stop
250
- if batch_had_content:
251
- empty_streak = 0
252
- else:
253
- empty_streak += 1
254
-
255
- current += BATCH_SIZE
256
- # Small delay between batches
257
- await asyncio.sleep(RATE_LIMIT_DELAY)
258
-
259
- LOGGER.info(f"[Scanner] Finished {s.channel_name}: scanned up to ID {current}, "
260
- f"{s.total_found} messages found, {s.indexed} indexed")
261
-
262
-
263
- # ── Bot Commands ─────────────────────────────────────────────────────────
264
-
265
- @Client.on_message(filters.command('scan') & filters.private & CustomFilters.owner, group=10)
266
- async def scan_command(client: Client, message: Message):
267
- """Scan AUTH_CHANNELs for existing content. Skips already-indexed messages."""
268
- if scan_state.running:
269
- await message.reply_text(
270
- "⚠️ A scan is already running. Use /scanstatus to check progress, "
271
- "or /cancelscan to abort it.",
272
- quote=True,
273
- )
274
- return
275
-
276
- # Optional: /scan -1001234567890 to scan a single channel
277
- args = message.text.split(maxsplit=1)
278
- if len(args) > 1:
279
- target_channels = [args[1].strip()]
280
- else:
281
- target_channels = list(SettingsManager.current().auth_channels)
282
-
283
- if not target_channels:
284
- await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
285
- return
286
-
287
- scan_state.reset()
288
- scan_state.running = True
289
- scan_state.started_at = time.time()
290
- scan_state.status_msg = await message.reply_text(
291
- "📡 <b>Channel scan starting…</b>",
292
- quote=True,
293
- parse_mode=enums.ParseMode.HTML,
294
- )
295
-
296
- try:
297
- for ch_id_str in target_channels:
298
- if scan_state.cancelled:
299
- break
300
- try:
301
- ch_id = int(ch_id_str)
302
- except ValueError:
303
- LOGGER.warning(f"[Scanner] Invalid channel ID: {ch_id_str}")
304
- continue
305
-
306
- await _scan_channel(client, ch_id)
307
-
308
- # Final summary
309
- s = scan_state
310
- status = "🛑 Cancelled" if s.cancelled else "✅ Complete"
311
- summary = (
312
- f"<blockquote>📡 <b>Scan {status}</b></blockquote>\n\n"
313
- f"⏱ Duration: <code>{s.elapsed}</code>\n"
314
- f"📨 Total messages seen: <code>{s.total_found}</code>\n"
315
- f"✅ Newly indexed: <code>{s.indexed}</code>\n"
316
- f"⏭ Skipped (already in DB): <code>{s.skipped_dup}</code>\n"
317
- f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
318
- f"📎 Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
319
- f"❌ Errors: <code>{s.errors}</code>"
320
- )
321
- try:
322
- await s.status_msg.edit_text(summary, parse_mode=enums.ParseMode.HTML)
323
- except Exception:
324
- await message.reply_text(summary, parse_mode=enums.ParseMode.HTML)
325
-
326
- # Send a separate notification so the user gets a Telegram ping
327
- # (editing a message doesn't trigger a notification)
328
- if s.processed > 20:
329
- notify = (
330
- f"{'🛑 Scan cancelled' if s.cancelled else '✅ Scan complete'} — "
331
- f"{s.indexed} indexed, {s.skipped_dup} skipped, "
332
- f"{s.errors} errors ({s.elapsed})"
333
- )
334
- await message.reply_text(notify)
335
-
336
- except (ChannelPrivate, ChatAdminRequired) as e:
337
- await message.reply_text(
338
- f"❌ <b>Access denied</b> to channel.\n\n"
339
- f"Make sure the bot is an admin in the channel.\n"
340
- f"<code>{e}</code>",
341
- parse_mode=enums.ParseMode.HTML,
342
- )
343
- except Exception as e:
344
- LOGGER.error(f"[Scanner] Unexpected error: {e}")
345
- await message.reply_text(f"❌ Scan failed: <code>{e}</code>",
346
- parse_mode=enums.ParseMode.HTML)
347
- finally:
348
- scan_state.running = False
349
-
350
-
351
- @Client.on_message(filters.command('rescan') & filters.private & CustomFilters.owner, group=10)
352
- async def rescan_command(client: Client, message: Message):
353
- """Wipe all DB entries that belong to AUTH_CHANNELs, then do a full scan.
354
-
355
- This is the nuclear option — it re-indexes everything from scratch.
356
- """
357
- if scan_state.running:
358
- await message.reply_text(
359
- "⚠️ A scan is already running. Cancel it first with /cancelscan.",
360
- quote=True,
361
- )
362
- return
363
-
364
- channels = list(SettingsManager.current().auth_channels)
365
- if not channels:
366
- await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
367
- return
368
-
369
- confirm_msg = await message.reply_text(
370
- "⚠️ <b>RESCAN</b> will <u>delete all existing DB entries</u> "
371
- "for your AUTH_CHANNELs and re-index from scratch.\n\n"
372
- "Send <code>/rescan confirm</code> to proceed.",
373
- quote=True,
374
- parse_mode=enums.ParseMode.HTML,
375
- )
376
-
377
- args = message.text.split()
378
- if len(args) < 2 or args[1].lower() != "confirm":
379
- return
380
-
381
- # Purge existing entries for these channels
382
- purge_msg = await message.reply_text(
383
- "🗑 Purging existing entries…", parse_mode=enums.ParseMode.HTML
384
- )
385
- purged = 0
386
- for ch_id_str in channels:
387
- channel_int = int(ch_id_str.replace("-100", ""))
388
- purged += await _purge_channel_entries(channel_int)
389
-
390
- await purge_msg.edit_text(
391
- f"🗑 Purged <code>{purged}</code> stream entries. Starting full scan…",
392
- parse_mode=enums.ParseMode.HTML,
393
- )
394
-
395
- # Now run a normal scan
396
- message.text = "/scan" # trick to reuse scan_command logic
397
- await scan_command(client, message)
398
-
399
-
400
- async def _purge_channel_entries(channel_int: int) -> int:
401
- """Delete all movie/tv stream entries whose encoded chat_id matches this channel."""
402
- from Backend.helper.encrypt import decode_string
403
-
404
- purged = 0
405
- for i in range(1, db.current_db_index + 1):
406
- storage = db.dbs.get(f"storage_{i}")
407
- if storage is None:
408
- continue
409
-
410
- # Purge movies
411
- async for movie in storage["movie"].find({}):
412
- remaining = []
413
- changed = False
414
- for q in movie.get("telegram", []):
415
- try:
416
- decoded = await decode_string(q["id"])
417
- if int(decoded["chat_id"]) == channel_int:
418
- purged += 1
419
- changed = True
420
- continue
421
- except Exception:
422
- pass
423
- remaining.append(q)
424
- if changed:
425
- if remaining:
426
- movie["telegram"] = remaining
427
- await storage["movie"].replace_one({"_id": movie["_id"]}, movie)
428
- else:
429
- await storage["movie"].delete_one({"_id": movie["_id"]})
430
-
431
- # Purge TV
432
- async for tv in storage["tv"].find({}):
433
- tv_changed = False
434
- for season in tv.get("seasons", []):
435
- for episode in season.get("episodes", []):
436
- remaining = []
437
- for q in episode.get("telegram", []):
438
- try:
439
- decoded = await decode_string(q["id"])
440
- if int(decoded["chat_id"]) == channel_int:
441
- purged += 1
442
- tv_changed = True
443
- continue
444
- except Exception:
445
- pass
446
- remaining.append(q)
447
- episode["telegram"] = remaining
448
- # Remove empty episodes
449
- season["episodes"] = [
450
- ep for ep in season["episodes"] if ep.get("telegram")
451
- ]
452
- # Remove empty seasons
453
- tv["seasons"] = [s for s in tv["seasons"] if s.get("episodes")]
454
- if tv_changed:
455
- if tv["seasons"]:
456
- await storage["tv"].replace_one({"_id": tv["_id"]}, tv)
457
- else:
458
- await storage["tv"].delete_one({"_id": tv["_id"]})
459
-
460
- return purged
461
-
462
-
463
- @Client.on_message(filters.command('scanstatus') & filters.private & CustomFilters.owner, group=10)
464
- async def scan_status_command(client: Client, message: Message):
465
- """Show current scan progress."""
466
- s = scan_state
467
- if not s.running:
468
- await message.reply_text("ℹ️ No scan is currently running.", quote=True)
469
- return
470
-
471
- text = (
472
- f"<blockquote>📡 <b>Scan in progress:</b> {s.channel_name}</blockquote>\n\n"
473
- f"⏱ Elapsed: <code>{s.elapsed}</code>\n"
474
- f"📨 Processed: <code>{s.processed}</code>\n"
475
- f"✅ Indexed: <code>{s.indexed}</code>\n"
476
- f"⏭ Skipped (duplicate): <code>{s.skipped_dup}</code>\n"
477
- f"⚠️ Skipped (metadata fail): <code>{s.skipped_meta}</code>\n"
478
- f"📎 Skipped (non-video): <code>{s.skipped_nonvid}</code>\n"
479
- f"❌ Errors: <code>{s.errors}</code>"
480
- )
481
- await message.reply_text(text, quote=True, parse_mode=enums.ParseMode.HTML)
482
-
483
-
484
- @Client.on_message(filters.command('cancelscan') & filters.private & CustomFilters.owner, group=10)
485
- async def cancel_scan_command(client: Client, message: Message):
486
- """Abort a running scan gracefully."""
487
- if not scan_state.running:
488
- await message.reply_text("ℹ️ No scan is currently running.", quote=True)
489
- return
490
-
491
- scan_state.cancelled = True
492
- await message.reply_text(
493
- "🛑 Scan cancellation requested. Will stop after current message.",
494
- quote=True,
495
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/pyrofork/plugins/utilities.py CHANGED
@@ -1,31 +1,12 @@
1
- """
2
- Utilities Plugin — stats, search, DB integrity check, channel backup/restore.
3
-
4
- Commands (owner-only, private chat):
5
- /stats — DB dashboard (counts, sizes, uptime)
6
- /search <title> — Search your DB for a movie or show
7
- /dbcheck — Find orphaned stream entries (dead Telegram messages)
8
- /dbcheck purge — Find and delete orphaned entries
9
- """
10
-
11
- import asyncio
12
- import json
13
  import time
14
  from pyrogram import filters, Client, enums
15
  from pyrogram.types import Message
16
- from pyrogram.errors import FloodWait
17
- from pymongo.errors import CursorNotFound
18
 
19
  from Backend.helper.custom_filter import CustomFilters
20
  from Backend.logger import LOGGER
21
  from Backend import db, StartTime, __version__
22
  from Backend.helper.settings_manager import SettingsManager
23
- from Backend.helper.encrypt import decode_string
24
-
25
 
26
- CONCURRENT_TASKS = 10
27
- BATCH_SIZE = 100
28
- PROGRESS_UPDATE_EVERY = 50
29
 
30
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
31
  # /stats — Quick dashboard
@@ -121,308 +102,3 @@ async def stats_command(client: Client, message: Message):
121
  LOGGER.error(f"[Stats] Error: {e}")
122
  await status_msg.edit_text(f"❌ Error gathering stats: <code>{e}</code>",
123
  parse_mode=enums.ParseMode.HTML)
124
-
125
-
126
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
127
- # /search <title> — Search own DB
128
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
129
-
130
- @Client.on_message(filters.command('search') & filters.private & CustomFilters.owner, group=10)
131
- async def search_command(client: Client, message: Message):
132
- """Search the DB for movies or TV shows by title."""
133
- args = message.text.split(maxsplit=1)
134
- if len(args) < 2:
135
- await message.reply_text(
136
- "Usage: /search <code>&lt;title&gt;</code>\n\n"
137
- "Example: <code>/search Breaking Bad</code>",
138
- quote=True,
139
- parse_mode=enums.ParseMode.HTML,
140
- )
141
- return
142
-
143
- query = args[1].strip()
144
- import re
145
- pattern = re.compile(re.escape(query), re.IGNORECASE)
146
- regex_filter = {"title": {"$regex": pattern.pattern, "$options": "i"}}
147
- results = []
148
-
149
- for i in range(1, db.current_db_index + 1):
150
- storage = db.dbs.get(f"storage_{i}")
151
- if storage is None:
152
- continue
153
-
154
- # Search movies
155
- try:
156
- movies = await storage["movie"].find(regex_filter).to_list(length=10)
157
- for movie in movies:
158
- qualities = movie.get("telegram", [])
159
- q_list = ", ".join(q.get("quality", "?") for q in qualities) or "none"
160
- results.append(
161
- f"🎬 <b>{movie.get('title', '?')}</b> ({movie.get('release_year', '?')})\n"
162
- f" TMDB: <code>{movie.get('tmdb_id', '?')}</code> | "
163
- f"IMDb: <code>{movie.get('imdb_id', '?')}</code>\n"
164
- f" Qualities: {q_list} | DB: storage_{i}"
165
- )
166
- except Exception as e:
167
- LOGGER.error(f"[Search] Movie search error in storage_{i}: {e}")
168
-
169
- # Search TV shows
170
- try:
171
- shows = await storage["tv"].find(regex_filter).to_list(length=10)
172
- for show in shows:
173
- seasons = show.get("seasons", [])
174
- ep_count = sum(len(s.get("episodes", [])) for s in seasons)
175
- stream_count = sum(
176
- len(ep.get("telegram", []))
177
- for s in seasons for ep in s.get("episodes", [])
178
- )
179
- season_nums = sorted(s.get("season_number", 0) for s in seasons)
180
- s_range = f"S{season_nums[0]}–S{season_nums[-1]}" if season_nums else "?"
181
- results.append(
182
- f"📺 <b>{show.get('title', '?')}</b> ({show.get('release_year', '?')})\n"
183
- f" TMDB: <code>{show.get('tmdb_id', '?')}</code> | "
184
- f"IMDb: <code>{show.get('imdb_id', '?')}</code>\n"
185
- f" {s_range} | {ep_count} episodes | {stream_count} streams | DB: storage_{i}"
186
- )
187
- except Exception as e:
188
- LOGGER.error(f"[Search] TV search error in storage_{i}: {e}")
189
-
190
- if not results:
191
- # Debug: check if DB has any data at all
192
- debug = ""
193
- try:
194
- for i in range(1, db.current_db_index + 1):
195
- storage = db.dbs.get(f"storage_{i}")
196
- if storage is None:
197
- continue
198
- mc = await storage["movie"].count_documents({})
199
- tc = await storage["tv"].count_documents({})
200
- # Grab a sample title to confirm data exists
201
- sample = await storage["movie"].find_one({}, {"title": 1})
202
- sample_title = sample.get("title", "?") if sample else "empty"
203
- debug = f"\n\n<i>Debug: storage_{i} has {mc} movies, {tc} tv. Sample: {sample_title}</i>"
204
- except Exception:
205
- pass
206
-
207
- await message.reply_text(
208
- f"🔍 No results for <b>{query}</b>{debug}",
209
- quote=True,
210
- parse_mode=enums.ParseMode.HTML,
211
- )
212
- return
213
-
214
- header = f"<blockquote>🔍 <b>Search results for:</b> {query}</blockquote>\n\n"
215
- body = "\n\n".join(results[:15]) # cap at 15 results
216
- footer = ""
217
- if len(results) > 15:
218
- footer = f"\n\n<i>…and {len(results) - 15} more. Try a more specific query.</i>"
219
-
220
- await message.reply_text(
221
- header + body + footer,
222
- quote=True,
223
- parse_mode=enums.ParseMode.HTML,
224
- )
225
-
226
-
227
-
228
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
229
- # Check single Telegram message
230
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
231
- async def check_message(client, stream_hash):
232
- try:
233
- decoded = await decode_string(stream_hash)
234
- chat_id = int(f"-100{decoded['chat_id']}")
235
- msg_id = int(decoded['msg_id'])
236
-
237
- msg = await client.get_messages(chat_id, msg_id)
238
-
239
- if msg.empty:
240
- return False
241
- return True
242
-
243
- except FloodWait as e:
244
- await asyncio.sleep(e.value)
245
- return await check_message(client, stream_hash)
246
-
247
- except Exception:
248
- return None
249
-
250
-
251
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
252
- # Batch processor
253
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
254
- async def process_batch(client, batch):
255
- tasks = [check_message(client, s) for s in batch]
256
- return await asyncio.gather(*tasks, return_exceptions=True)
257
-
258
-
259
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
260
- # /dbcheck — Integrity checker (find orphaned streams)
261
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
262
- @Client.on_message(filters.command('dbcheck') & filters.private & CustomFilters.owner, group=10)
263
- async def dbcheck_command(client: Client, message: Message):
264
-
265
- args = message.text.split()
266
- purge_mode = len(args) > 1 and args[1].lower() == "purge"
267
-
268
- status_msg = await message.reply_text(
269
- "🚀 DB Check started (Atlas-safe mode)...",
270
- quote=True
271
- )
272
-
273
- checked = 0
274
- dead = 0
275
- alive = 0
276
- errors = 0
277
- purged = 0
278
-
279
- dead_entries = []
280
-
281
- start_time = time.time()
282
-
283
- try:
284
- for i in range(1, db.current_db_index + 1):
285
- storage = db.dbs.get(f"storage_{i}")
286
-
287
- if storage is None:
288
- continue
289
-
290
- # ───────── MOVIES (PAGINATION) ─────────
291
- last_id = None
292
-
293
- while True:
294
- query = {"_id": {"$gt": last_id}} if last_id else {}
295
-
296
- docs = await storage["movie"] \
297
- .find(query) \
298
- .sort("_id", 1) \
299
- .limit(BATCH_SIZE) \
300
- .to_list(length=BATCH_SIZE)
301
-
302
- if not docs:
303
- break
304
-
305
- for movie in docs:
306
- last_id = movie["_id"]
307
- title = movie.get("title", "Unknown")
308
-
309
- stream_ids = [
310
- q.get("id") for q in movie.get("telegram", [])
311
- if q.get("id")
312
- ]
313
-
314
- for x in range(0, len(stream_ids), CONCURRENT_TASKS):
315
- batch = stream_ids[x:x + CONCURRENT_TASKS]
316
- results = await process_batch(client, batch)
317
-
318
- for stream_hash, result in zip(batch, results):
319
- checked += 1
320
-
321
- if result is True:
322
- alive += 1
323
- elif result is False:
324
- dead += 1
325
- dead_entries.append(stream_hash)
326
- else:
327
- errors += 1
328
-
329
- if checked % PROGRESS_UPDATE_EVERY == 0:
330
- elapsed = int(time.time() - start_time)
331
- speed = checked // max(1, elapsed)
332
-
333
- await status_msg.edit_text(
334
- f"🚀 DB Check Running...\n\n"
335
- f"Checked: {checked}\n"
336
- f"Alive: {alive}\n"
337
- f"Dead: {dead}\n"
338
- f"Errors: {errors}\n\n"
339
- f"⚡ Speed: {speed}/sec"
340
- )
341
-
342
- # ───────── TV (PAGINATION) ─────────
343
- last_id = None
344
-
345
- while True:
346
- query = {"_id": {"$gt": last_id}} if last_id else {}
347
-
348
- docs = await storage["tv"] \
349
- .find(query) \
350
- .sort("_id", 1) \
351
- .limit(BATCH_SIZE) \
352
- .to_list(length=BATCH_SIZE)
353
-
354
- if not docs:
355
- break
356
-
357
- for show in docs:
358
- last_id = show["_id"]
359
-
360
- stream_ids = []
361
-
362
- for season in show.get("seasons", []):
363
- for episode in season.get("episodes", []):
364
- for q in episode.get("telegram", []):
365
- if q.get("id"):
366
- stream_ids.append(q["id"])
367
-
368
- for x in range(0, len(stream_ids), CONCURRENT_TASKS):
369
- batch = stream_ids[x:x + CONCURRENT_TASKS]
370
- results = await process_batch(client, batch)
371
-
372
- for stream_hash, result in zip(batch, results):
373
- checked += 1
374
-
375
- if result is True:
376
- alive += 1
377
- elif result is False:
378
- dead += 1
379
- dead_entries.append(stream_hash)
380
- else:
381
- errors += 1
382
-
383
- if checked % PROGRESS_UPDATE_EVERY == 0:
384
- elapsed = int(time.time() - start_time)
385
- speed = checked // max(1, elapsed)
386
-
387
- await status_msg.edit_text(
388
- f"🚀 DB Check Running...\n\n"
389
- f"Checked: {checked}\n"
390
- f"Alive: {alive}\n"
391
- f"Dead: {dead}\n"
392
- f"Errors: {errors}\n\n"
393
- f"⚡ Speed: {speed}/sec"
394
- )
395
-
396
- # ───────── PURGE ─────────
397
- if purge_mode and dead_entries:
398
- purge_tasks = []
399
-
400
- for stream_hash in dead_entries:
401
- purge_tasks.append(db.delete_media_by_stream_id(stream_hash))
402
-
403
- if len(purge_tasks) >= CONCURRENT_TASKS:
404
- results = await asyncio.gather(*purge_tasks, return_exceptions=True)
405
- purged += sum(1 for r in results if r)
406
- purge_tasks = []
407
-
408
- if purge_tasks:
409
- results = await asyncio.gather(*purge_tasks, return_exceptions=True)
410
- purged += sum(1 for r in results if r)
411
-
412
- # ───────── FINAL RESULT ─────────
413
- elapsed = int(time.time() - start_time)
414
-
415
- await status_msg.edit_text(
416
- f"✅ DB CHECK COMPLETE\n\n"
417
- f"Checked: {checked}\n"
418
- f"Alive: {alive}\n"
419
- f"Dead: {dead}\n"
420
- f"Errors: {errors}\n\n"
421
- f"🗑 Purged: {purged}\n"
422
- f"⏱ Time: {elapsed}s\n"
423
- f"⚡ Avg Speed: {checked // max(1, elapsed)}/sec"
424
- )
425
-
426
- except Exception as e:
427
- LOGGER.error(f"[DBCheck] Error: {e}")
428
- await status_msg.edit_text(f"❌ DB check failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import time
2
  from pyrogram import filters, Client, enums
3
  from pyrogram.types import Message
 
 
4
 
5
  from Backend.helper.custom_filter import CustomFilters
6
  from Backend.logger import LOGGER
7
  from Backend import db, StartTime, __version__
8
  from Backend.helper.settings_manager import SettingsManager
 
 
9
 
 
 
 
10
 
11
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
12
  # /stats — Quick dashboard
 
102
  LOGGER.error(f"[Stats] Error: {e}")
103
  await status_msg.edit_text(f"❌ Error gathering stats: <code>{e}</code>",
104
  parse_mode=enums.ParseMode.HTML)