Karan Adhikari commited on
Commit
c12bb0b
Β·
unverified Β·
1 Parent(s): 238a311

# πŸŽ‰ Release v3.3.0

Browse files

### ✨ Changes

* ❌ Removed `HELPER_BOT_TOKEN`
* πŸ‘€ Added optional `USER_SESSION_STRING`
* πŸ” Added Global Search support
* πŸ”’ Global Search can only be enabled when `USER_SESSION_STRING` is configured in `config.env`

### ⚠️ Limitation

* Multi-Token load balancing does **not** work for Global Search streams.
* Files found through Global Search are streamed using the Userbot session only.
* Multi-Token support continues to work normally for files in configured AUTH CHANNELS.

Backend/__init__.py CHANGED
@@ -11,4 +11,4 @@ StartTime = time()
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
- __version__ = "3.2.0"
 
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
+ __version__ = "3.3.0"
Backend/__main__.py CHANGED
@@ -9,7 +9,7 @@ from Backend.logger import LOGGER
9
  from Backend.fastapi import server
10
  from Backend.helper.settings_manager import SettingsManager
11
  from Backend.helper.pyro import restart_notification, setup_bot_commands
12
- from Backend.pyrofork.bot import Helper, 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
@@ -43,9 +43,12 @@ async def start_services():
43
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
44
  await asleep(1.2)
45
 
46
- await Helper.start()
47
- Helper.username = Helper.me.username
48
- LOGGER.info(f"Helper Bot Client : [@{Helper.username}]")
 
 
 
49
  await asleep(1.2)
50
 
51
  LOGGER.info("Initializing Multi Clients...")
@@ -86,7 +89,8 @@ async def stop_services():
86
  await asyncio.gather(*pending_tasks, return_exceptions=True)
87
 
88
  await StreamBot.stop()
89
- await Helper.stop()
 
90
 
91
  await db.disconnect()
92
 
 
9
  from Backend.fastapi import server
10
  from Backend.helper.settings_manager import SettingsManager
11
  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
 
43
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
44
  await asleep(1.2)
45
 
46
+ if Userbot is not None:
47
+ await Userbot.start()
48
+ Userbot.username = Userbot.me.username
49
+ LOGGER.info(f"Userbot Client : [@{Userbot.username}] (Global Search / fallback enabled)")
50
+ else:
51
+ LOGGER.info("Userbot not configured (USER_SESSION_STRING empty) β€” running with StreamBot only.")
52
  await asleep(1.2)
53
 
54
  LOGGER.info("Initializing Multi Clients...")
 
89
  await asyncio.gather(*pending_tasks, return_exceptions=True)
90
 
91
  await StreamBot.stop()
92
+ if Userbot is not None:
93
+ await Userbot.stop()
94
 
95
  await db.disconnect()
96
 
Backend/config.py CHANGED
@@ -9,7 +9,7 @@ class Telegram:
9
  API_ID = int(getenv("API_ID", "0"))
10
  API_HASH = getenv("API_HASH", "")
11
  BOT_TOKEN = getenv("BOT_TOKEN", "")
12
- HELPER_BOT_TOKEN = getenv("HELPER_BOT_TOKEN", "")
13
 
14
  # ── Required: Database URIs ───────────────────────────────────────────────
15
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
 
9
  API_ID = int(getenv("API_ID", "0"))
10
  API_HASH = getenv("API_HASH", "")
11
  BOT_TOKEN = getenv("BOT_TOKEN", "")
12
+ USER_SESSION_STRING = getenv("USER_SESSION_STRING", "")
13
 
14
  # ── Required: Database URIs ───────────────────────────────────────────────
15
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
Backend/fastapi/routes/api_routes.py CHANGED
@@ -1004,7 +1004,7 @@ async def update_settings_api(payload: dict) -> dict:
1004
  if key in payload:
1005
  payload[key] = bool(payload[key])
1006
 
1007
- list_str_keys = {"auth_channels", "multi_tokens", "extra_databases"}
1008
  for key in list_str_keys:
1009
  if key in payload:
1010
  if not isinstance(payload[key], list):
@@ -1032,6 +1032,20 @@ async def update_settings_api(payload: dict) -> dict:
1032
  payload["subscription_group_id"] = int(payload["subscription_group_id"])
1033
  except (ValueError, TypeError):
1034
  raise HTTPException(status_code=400, detail="'subscription_group_id' must be an integer.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1035
 
1036
  # Strip whitespace from string fields
1037
  for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
 
1004
  if key in payload:
1005
  payload[key] = bool(payload[key])
1006
 
1007
+ list_str_keys = {"auth_channels", "multi_tokens", "extra_databases", "global_search_channels"}
1008
  for key in list_str_keys:
1009
  if key in payload:
1010
  if not isinstance(payload[key], list):
 
1032
  payload["subscription_group_id"] = int(payload["subscription_group_id"])
1033
  except (ValueError, TypeError):
1034
  raise HTTPException(status_code=400, detail="'subscription_group_id' must be an integer.")
1035
+ if "global_search_channels" in payload:
1036
+ cleaned = []
1037
+ for channel in payload["global_search_channels"]:
1038
+ channel = str(channel).strip()
1039
+ if not channel:
1040
+ continue
1041
+ try:
1042
+ int(channel)
1043
+ except ValueError:
1044
+ raise HTTPException(status_code=400,
1045
+ detail=f"Invalid channel id: {channel}"
1046
+ )
1047
+ cleaned.append(channel)
1048
+ payload["global_search_channels"] = cleaned
1049
 
1050
  # Strip whitespace from string fields
1051
  for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
Backend/fastapi/routes/stream_routes.py CHANGED
@@ -15,7 +15,7 @@ from Backend.helper.encrypt import decode_string
15
  from Backend.helper.utils import track_usage
16
  from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
17
  from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
18
- from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
19
  from Backend.fastapi.security.tokens import verify_token
20
 
21
  router = APIRouter(tags=["Streaming"])
@@ -105,6 +105,12 @@ def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
105
  async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
106
  decoded = await decode_string(id)
107
 
 
 
 
 
 
 
108
  if "parts" in decoded:
109
  return await virtual_media_streamer(
110
  request=request, parts_payload=decoded["parts"],
@@ -317,6 +323,100 @@ async def virtual_media_streamer(request: Request, parts_payload: list, token: s
317
 
318
  return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type, )
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  @router.get("/stream/stats")
321
  async def get_stream_stats():
322
  now = time.time()
 
15
  from Backend.helper.utils import track_usage
16
  from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
17
  from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
18
+ from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps, Userbot, USERBOT_CLIENT_INDEX
19
  from Backend.fastapi.security.tokens import verify_token
20
 
21
  router = APIRouter(tags=["Streaming"])
 
105
  async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
106
  decoded = await decode_string(id)
107
 
108
+ if decoded.get("global"):
109
+ return await global_media_streamer(
110
+ request=request, chat_id=int(decoded["chat_id"]), msg_id=int(decoded["msg_id"]),
111
+ token=token, token_data=token_data, stream_id_hash=id,
112
+ )
113
+
114
  if "parts" in decoded:
115
  return await virtual_media_streamer(
116
  request=request, parts_payload=decoded["parts"],
 
323
 
324
  return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type, )
325
 
326
+
327
+ _userbot_streamer: ByteStreamer = None
328
+
329
+
330
+ def _get_userbot_streamer() -> ByteStreamer:
331
+ """Lazily build (and cache) the ByteStreamer wrapping the Userbot
332
+ client. Returns None if no Userbot is configured."""
333
+ global _userbot_streamer
334
+ if Userbot is None:
335
+ return None
336
+ if _userbot_streamer is None:
337
+ _userbot_streamer = ByteStreamer(Userbot, USERBOT_CLIENT_INDEX)
338
+ return _userbot_streamer
339
+
340
+
341
+ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,):
342
+ """Streams a single file found via Global Search, played back through
343
+ the Userbot session directly β€” these channels aren't part of the Auth
344
+ Channel/MultiToken infrastructure, so the regular client pool can't
345
+ (and shouldn't) be used here."""
346
+ streamer = _get_userbot_streamer()
347
+ if streamer is None:
348
+ raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot configured)")
349
+
350
+ LOGGER.info(f"[USERBOT] Stream request: chat={chat_id} msg={msg_id}")
351
+ try:
352
+ file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
353
+ except Exception as e:
354
+ LOGGER.error(f"[USERBOT] File not accessible: chat={chat_id} msg={msg_id}: {e}")
355
+ raise HTTPException(status_code=404, detail="File not accessible via Global Search")
356
+
357
+ file_size = file_id.file_size
358
+ range_header = request.headers.get("Range", "")
359
+ start, end = parse_range_header(range_header, file_size)
360
+ req_length = end - start + 1
361
+ chunk_size = 1024 * 1024
362
+ offset = start - (start % chunk_size)
363
+ first_part_cut = start - offset
364
+ last_part_cut = (end % chunk_size) + 1
365
+ part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
366
+ stream_id = secrets.token_hex(8)
367
+
368
+ meta = {
369
+ "request_path": str(request.url.path),
370
+ "client_host": request.client.host if request.client else None,
371
+ "title": file_id.file_name or "global-stream",
372
+ "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
373
+ "global_search": True,
374
+ }
375
+
376
+ asyncio.create_task(track_usage(stream_id, token, token_data))
377
+
378
+ file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
379
+ mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
380
+ if "." not in file_name and "/" in mime_type:
381
+ file_name = f"{file_name}.{mime_type.split('/')[1]}"
382
+
383
+ headers = {
384
+ "Content-Type": mime_type,
385
+ "Content-Disposition": f'inline; filename="{file_name}"',
386
+ "Accept-Ranges": "bytes",
387
+ "Content-Length": str(req_length),
388
+ "Cache-Control": "public, max-age=3600",
389
+ "Access-Control-Allow-Origin": "*",
390
+ "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
391
+ }
392
+ if range_header:
393
+ headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
394
+ status = 206
395
+ else:
396
+ status = 200
397
+
398
+ if request.method == "HEAD":
399
+ return PlainResponse(status_code=status, headers=headers)
400
+
401
+ body_gen = await streamer.prefetch_stream(
402
+ file_id=file_id,
403
+ client_index=USERBOT_CLIENT_INDEX,
404
+ offset=offset,
405
+ first_part_cut=first_part_cut,
406
+ last_part_cut=last_part_cut,
407
+ part_count=part_count,
408
+ chunk_size=chunk_size,
409
+ prefetch=1,
410
+ stream_id=stream_id,
411
+ meta=meta,
412
+ parallelism=1,
413
+ request=request,
414
+ chat_id=chat_id,
415
+ message_id=msg_id,
416
+ )
417
+
418
+ return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
419
+
420
  @router.get("/stream/stats")
421
  async def get_stream_stats():
422
  now = time.time()
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -8,6 +8,8 @@ import PTN
8
  from fastapi.responses import HTMLResponse
9
  from datetime import datetime, timezone, timedelta
10
  from Backend.fastapi.security.tokens import verify_token
 
 
11
 
12
  router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
13
 
@@ -309,6 +311,7 @@ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str]
309
  async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depends(verify_token)):
310
  if SettingsManager.current().hide_catalog:
311
  raise HTTPException(status_code=404, detail="Catalog disabled")
 
312
  try:
313
  imdb_id = id
314
  except (ValueError, IndexError):
@@ -361,6 +364,51 @@ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depe
361
  meta_obj["videos"] = videos
362
  return {"meta": meta_obj}
363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  @router.get("/{token}/stream/{media_type}/{id}.json")
365
  async def get_streams(
366
  token: str,
@@ -399,7 +447,6 @@ async def get_streams(
399
  ]
400
  }
401
 
402
-
403
  try:
404
  parts = id.split(":")
405
  imdb_id = parts[0]
@@ -414,46 +461,58 @@ async def get_streams(
414
  episode_number=episode_num
415
  )
416
 
417
- if not media_details or "telegram" not in media_details:
418
- return {"streams": []}
419
-
420
  streams = []
421
- for quality in media_details.get("telegram", []):
422
- if quality.get("id"):
423
- filename = quality.get("name", "")
424
- quality_str = quality.get("quality", "HD")
425
- size = quality.get("size", "")
426
-
427
- stream_name, stream_title = format_stream_details(
428
- filename, quality_str, size, is_split=bool(quality.get("group_key"))
429
- )
430
 
431
- original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv"
432
- proxy_url = f"{SettingsManager.current().http_proxy_url}{original_url}" if SettingsManager.current().http_proxy_url else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
 
434
- if SettingsManager.current().show_proxy_and_non_proxy_both and proxy_url:
435
- streams.append({
436
- "name": f"{stream_name} (Proxy)",
437
- "title": stream_title,
438
- "url": proxy_url
439
- })
440
- streams.append({
441
- "name": f"{stream_name} (Direct)",
442
- "title": stream_title,
443
- "url": original_url
444
- })
445
- elif proxy_url:
446
- streams.append({
447
- "name": stream_name,
448
- "title": stream_title,
449
- "url": proxy_url
450
- })
451
- else:
452
- streams.append({
453
- "name": stream_name,
454
- "title": stream_title,
455
- "url": original_url
456
- })
457
 
458
  streams.sort(
459
  key=lambda s: get_resolution_priority(s.get("name", "")),
 
8
  from fastapi.responses import HTMLResponse
9
  from datetime import datetime, timezone, timedelta
10
  from Backend.fastapi.security.tokens import verify_token
11
+ from Backend.logger import LOGGER
12
+ from Backend.helper.global_search import global_search, is_global_search_enabled
13
 
14
  router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
15
 
 
311
  async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depends(verify_token)):
312
  if SettingsManager.current().hide_catalog:
313
  raise HTTPException(status_code=404, detail="Catalog disabled")
314
+
315
  try:
316
  imdb_id = id
317
  except (ValueError, IndexError):
 
364
  meta_obj["videos"] = videos
365
  return {"meta": meta_obj}
366
 
367
+ async def _global_streams_for(token: str, imdb_id: str, media_type: str, season_num: Optional[int], episode_num: Optional[int]) -> list:
368
+ """Builds Global Search stream entries for a catalog item that has no
369
+ local DB row at all. Since there's no local title to read, the
370
+ canonical title (and, for a specific episode, confirmation it exists)
371
+ is resolved from Cinemeta via Backend.helper.imdb β€” the same source
372
+ used everywhere else in this codebase for metadata."""
373
+ from Backend.helper.imdb import get_detail, get_season
374
+
375
+ imdb_media_type = "tvSeries" if media_type == "series" else "movie"
376
+
377
+ detail = await get_detail(imdb_id=imdb_id, media_type=imdb_media_type)
378
+ if not detail or not detail.get("title"):
379
+ return []
380
+
381
+ expected_title = detail["title"]
382
+ year = (detail.get("releaseDetailed") or {}).get("year") or None
383
+
384
+ if season_num is not None and episode_num is not None:
385
+ try:
386
+ await get_season(imdb_id=imdb_id, season_id=season_num, episode_id=episode_num)
387
+ except Exception:
388
+ pass # best-effort only; absence doesn't block the search
389
+
390
+ try:
391
+ global_results = await global_search(
392
+ expected_title,
393
+ SettingsManager.current().auth_channels,
394
+ year=year,
395
+ season=season_num,
396
+ episode=episode_num,
397
+ )
398
+ except Exception as e:
399
+ LOGGER.error(f"[GLOBAL SEARCH] search failed for '{expected_title}': {e}")
400
+ return []
401
+
402
+ streams = []
403
+ for r in global_results:
404
+ _, stream_title = format_stream_details(r["title"], r["quality"], r["size"], is_split=False)
405
+ stream_name = f"🌐 GLOBAL {r['quality']}"
406
+ stream_title = f"{stream_title}\nπŸ“‘ {r['source_chat']}"
407
+ url = f"{SettingsManager.current().base_url}/dl/{token}/{r['token']}/{quote(r['title'])}"
408
+ streams.append({"name": stream_name, "title": stream_title, "url": url})
409
+ return streams
410
+
411
+
412
  @router.get("/{token}/stream/{media_type}/{id}.json")
413
  async def get_streams(
414
  token: str,
 
447
  ]
448
  }
449
 
 
450
  try:
451
  parts = id.split(":")
452
  imdb_id = parts[0]
 
461
  episode_number=episode_num
462
  )
463
 
 
 
 
464
  streams = []
 
 
 
 
 
 
 
 
 
465
 
466
+ if media_details and "telegram" in media_details:
467
+ for quality in media_details.get("telegram", []):
468
+ if quality.get("id"):
469
+ filename = quality.get("name", "")
470
+ quality_str = quality.get("quality", "HD")
471
+ size = quality.get("size", "")
472
+
473
+ stream_name, stream_title = format_stream_details(
474
+ filename, quality_str, size, is_split=bool(quality.get("group_key"))
475
+ )
476
+
477
+ original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv"
478
+ proxy_url = f"{SettingsManager.current().http_proxy_url}{original_url}" if SettingsManager.current().http_proxy_url else None
479
+
480
+ if SettingsManager.current().show_proxy_and_non_proxy_both and proxy_url:
481
+ streams.append({
482
+ "name": f"{stream_name} (Proxy)",
483
+ "title": stream_title,
484
+ "url": proxy_url
485
+ })
486
+ streams.append({
487
+ "name": f"{stream_name} (Direct)",
488
+ "title": stream_title,
489
+ "url": original_url
490
+ })
491
+ elif proxy_url:
492
+ streams.append({
493
+ "name": stream_name,
494
+ "title": stream_title,
495
+ "url": proxy_url
496
+ })
497
+ else:
498
+ streams.append({
499
+ "name": stream_name,
500
+ "title": stream_title,
501
+ "url": original_url
502
+ })
503
+ elif is_global_search_enabled():
504
+ # Not in the local catalog at all β€” resolve the real title via
505
+ # Cinemeta (we have no local DB row to read a title from) and
506
+ # search for it across the Userbot's channels instead.
507
+ try:
508
+ streams.extend(
509
+ await _global_streams_for(token, imdb_id, media_type, season_num, episode_num)
510
+ )
511
+ except Exception as e:
512
+ LOGGER.error(f"[GLOBAL SEARCH] stream search failed for {imdb_id}: {e}")
513
 
514
+ if not streams:
515
+ return {"streams": []}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
516
 
517
  streams.sort(
518
  key=lambda s: get_resolution_priority(s.get("name", "")),
Backend/fastapi/routes/template_routes.py CHANGED
@@ -4,6 +4,7 @@ from fastapi.templating import Jinja2Templates
4
  from Backend.fastapi.security.credentials import verify_credentials, require_auth, is_authenticated, get_current_user
5
  from Backend.fastapi.themes import get_theme, get_all_themes
6
  from Backend import db
 
7
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
8
  from Backend.helper.pyro import get_readable_time
9
  from Backend.helper.settings_manager import SettingsManager
@@ -284,6 +285,7 @@ async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)
284
  })
285
 
286
 
 
287
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
288
  theme_name = request.session.get("theme", "dark_professional")
289
  theme = get_theme(theme_name)
@@ -291,16 +293,23 @@ async def settings_page(request: Request, _: bool = Depends(require_auth)):
291
 
292
  settings = SettingsManager.current().to_dict()
293
  settings["admin_password"] = ""
 
294
  try:
295
  settings["database_list"] = db.get_database_list()
296
  except Exception:
297
  settings["database_list"] = []
298
 
299
- return templates.TemplateResponse("settings.html", {
300
- "request": request,
301
- "theme": theme,
302
- "themes": get_all_themes(),
303
- "current_theme": theme_name,
304
- "current_user": current_user,
305
- "settings": settings,
306
- })
 
 
 
 
 
 
 
4
  from Backend.fastapi.security.credentials import verify_credentials, require_auth, is_authenticated, get_current_user
5
  from Backend.fastapi.themes import get_theme, get_all_themes
6
  from Backend import db
7
+ from Backend.config import Telegram
8
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
9
  from Backend.helper.pyro import get_readable_time
10
  from Backend.helper.settings_manager import SettingsManager
 
285
  })
286
 
287
 
288
+
289
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
290
  theme_name = request.session.get("theme", "dark_professional")
291
  theme = get_theme(theme_name)
 
293
 
294
  settings = SettingsManager.current().to_dict()
295
  settings["admin_password"] = ""
296
+
297
  try:
298
  settings["database_list"] = db.get_database_list()
299
  except Exception:
300
  settings["database_list"] = []
301
 
302
+ userbot_configured = bool(Telegram.USER_SESSION_STRING and Telegram.USER_SESSION_STRING.strip())
303
+
304
+ return templates.TemplateResponse(
305
+ "settings.html",
306
+ {
307
+ "request": request,
308
+ "theme": theme,
309
+ "themes": get_all_themes(),
310
+ "current_theme": theme_name,
311
+ "current_user": current_user,
312
+ "settings": settings,
313
+ "userbot_configured": userbot_configured,
314
+ },
315
+ )
Backend/fastapi/templates/settings.html CHANGED
@@ -282,6 +282,102 @@
282
  </div>
283
  </div>
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  <!-- ── Proxy ───────────────────────────────────────────────────────── -->
286
  <div class="settings-card">
287
  <h2><i class="fa-solid fa-network-wired"></i> Proxy Settings</h2>
@@ -409,6 +505,15 @@ function toggleSubFields() {
409
  document.getElementById('sub-fields').style.display = enabled ? '' : 'none';
410
  }
411
 
 
 
 
 
 
 
 
 
 
412
  /* ── Password visibility ──────────────────────────────────────────────── */
413
  function togglePwdVisibility() {
414
  const input = document.getElementById('admin_password');
@@ -485,6 +590,8 @@ async function saveSettings() {
485
  show_proxy_and_non_proxy_both: document.getElementById('show_proxy_and_non_proxy_both').checked,
486
  multi_tokens: collectList('multi_tokens'),
487
  extra_databases: collectList('extra_databases'),
 
 
488
  };
489
 
490
  try {
@@ -553,7 +660,9 @@ function renderSettings(s) {
553
  document.getElementById('hide_catalog').checked = !!s.hide_catalog;
554
  document.getElementById('subscription').checked = !!s.subscription;
555
  document.getElementById('show_proxy_and_non_proxy_both').checked = !!s.show_proxy_and_non_proxy_both;
 
556
  toggleSubFields();
 
557
 
558
  // Plain text/number fields
559
  document.getElementById('admin_username').value = s.admin_username || '';
@@ -570,6 +679,7 @@ function renderSettings(s) {
570
  rebuildSimpleList('auth_channels_items', s.auth_channels, 'text');
571
  rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
572
  rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
 
573
 
574
  // Databases β€” needs the live connection-status dot per entry
575
  rebuildDatabaseList(s.database_list || []);
 
282
  </div>
283
  </div>
284
 
285
+
286
+
287
+
288
+ <!-- ── Global Search (Userbot) ────────────────────────────────────── -->
289
+ <div class="settings-card">
290
+ <h2><i class="fa-solid fa-globe"></i> Global Search</h2>
291
+
292
+ <label class="toggle-wrap" style="{% if not userbot_configured %}opacity:0.5{% endif %}">
293
+ <input type="checkbox" class="toggle-input" id="global_search"
294
+ {% if settings.global_search %}checked{% endif %}
295
+ {% if not userbot_configured %}disabled{% endif %}
296
+ onchange="toggleGlobalSearchFields()">
297
+ <span class="toggle-track"></span>
298
+ <span class="toggle-label">
299
+ <strong>Enable Global Search</strong>
300
+ <span style="color:var(--text-sec);font-size:0.8rem;display:block">
301
+ Search media <strong>only in the channels listed below</strong>.
302
+ Results are tagged <strong>🌐 GLOBAL</strong> in the stream list
303
+ for items not in your local catalog.
304
+ </span>
305
+ </span>
306
+ </label>
307
+
308
+ {% if not userbot_configured %}
309
+ <p style="color:var(--text-sec);font-size:0.8rem;margin-top:0.75rem">
310
+ <i class="fa-solid fa-circle-info"></i>
311
+ Requires <code>USER_SESSION_STRING</code> to be set in
312
+ <code>config.env</code> (startup-critical, not editable here)
313
+ <strong>and a full app restart</strong>.
314
+ Restart the app after setting it to unlock this option.
315
+ </p>
316
+ {% endif %}
317
+
318
+ <div id="global-search-fields"
319
+ style="{% if not settings.global_search %}display:none{% endif %}">
320
+
321
+ <hr class="divider">
322
+
323
+ <div id="global-search-channels-wrap"
324
+ style="{% if not userbot_configured %}opacity:0.5;pointer-events:none{% endif %}">
325
+
326
+ <label class="s-label">
327
+ GLOBAL SEARCH CHANNELS
328
+ <span style="font-weight:400;text-transform:none;letter-spacing:0">
329
+ β€” search is restricted to these channel IDs only
330
+ </span>
331
+ </label>
332
+
333
+ <p style="font-size:0.78rem;color:var(--text-sec);margin-bottom:0.75rem">
334
+ <i class="fa-solid fa-triangle-exclamation"
335
+ style="color:var(--warning,#f59e0b)"></i>
336
+ Global Search will <strong>not run</strong> unless at least one
337
+ channel ID is added here.
338
+ Enter numeric channel IDs
339
+ (e.g. <code>-1001234567890</code> or bare
340
+ <code>1234567890</code>).
341
+ </p>
342
+
343
+ <div class="multi-list-items" id="global_search_channels_items">
344
+ {% for ch in settings.global_search_channels %}
345
+ <div class="multi-item">
346
+ <input type="text"
347
+ class="s-input"
348
+ value="{{ ch }}"
349
+ data-list="global_search_channels"
350
+ placeholder="-100xxxxxxxxxx">
351
+
352
+ <button class="remove-btn"
353
+ onclick="removeItem(this)"
354
+ title="Remove">
355
+ <i class="fa-solid fa-xmark"></i>
356
+ </button>
357
+ </div>
358
+ {% endfor %}
359
+ </div>
360
+
361
+ <div class="add-row">
362
+ <input type="text"
363
+ id="global_search_channels_new"
364
+ class="s-input"
365
+ placeholder="-100xxxxxxxxxx or bare numeric ID"
366
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('global_search_channels')}">
367
+
368
+ <button class="add-btn"
369
+ onclick="addItem('global_search_channels')">
370
+ + Add Channel
371
+ </button>
372
+ </div>
373
+
374
+ </div>
375
+ </div>
376
+ </div>
377
+
378
+
379
+
380
+
381
  <!-- ── Proxy ───────────────────────────────────────────────────────── -->
382
  <div class="settings-card">
383
  <h2><i class="fa-solid fa-network-wired"></i> Proxy Settings</h2>
 
505
  document.getElementById('sub-fields').style.display = enabled ? '' : 'none';
506
  }
507
 
508
+ function toggleGlobalSearchFields() {
509
+ const enabled = document.getElementById('global_search').checked;
510
+ const fields = document.getElementById('global-search-fields');
511
+
512
+ if (fields) {
513
+ fields.style.display = enabled ? '' : 'none';
514
+ }
515
+ }
516
+
517
  /* ── Password visibility ──────────────────────────────────────────────── */
518
  function togglePwdVisibility() {
519
  const input = document.getElementById('admin_password');
 
590
  show_proxy_and_non_proxy_both: document.getElementById('show_proxy_and_non_proxy_both').checked,
591
  multi_tokens: collectList('multi_tokens'),
592
  extra_databases: collectList('extra_databases'),
593
+ global_search: document.getElementById('global_search').checked,
594
+ global_search_channels: collectList('global_search_channels'),
595
  };
596
 
597
  try {
 
660
  document.getElementById('hide_catalog').checked = !!s.hide_catalog;
661
  document.getElementById('subscription').checked = !!s.subscription;
662
  document.getElementById('show_proxy_and_non_proxy_both').checked = !!s.show_proxy_and_non_proxy_both;
663
+ document.getElementById('global_search').checked = !!s.global_search;
664
  toggleSubFields();
665
+ toggleGlobalSearchFields();
666
 
667
  // Plain text/number fields
668
  document.getElementById('admin_username').value = s.admin_username || '';
 
679
  rebuildSimpleList('auth_channels_items', s.auth_channels, 'text');
680
  rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
681
  rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
682
+ rebuildSimpleList('global_search_channels_items', s.global_search_channels, 'text');
683
 
684
  // Databases β€” needs the live connection-status dot per entry
685
  rebuildDatabaseList(s.database_list || []);
Backend/helper/global_search.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import re
3
+ import time
4
+ from typing import Dict, List, Optional, Tuple
5
+
6
+ import PTN
7
+ from pyrogram import enums
8
+ from pyrogram.errors import (
9
+ FloodWait,
10
+ ChatAdminRequired,
11
+ ChannelPrivate,
12
+ PeerIdInvalid,
13
+ UserNotParticipant,
14
+ AuthKeyUnregistered,
15
+ SessionRevoked,
16
+ RPCError,
17
+ )
18
+
19
+ from Backend.logger import LOGGER
20
+ from Backend.helper.settings_manager import SettingsManager
21
+ from Backend.helper.encrypt import encode_string
22
+
23
+ MAX_RESULTS = 50
24
+ MAX_RESULTS_PER_CHAT = 50
25
+ SEARCH_COOLDOWN_SECONDS = 5
26
+ MAX_CONCURRENT_SEARCHES = 3
27
+ MIN_TITLE_SCORE = 0.6
28
+
29
+ _last_search_ts: Dict[str, float] = {}
30
+ _inflight_queries: set = set()
31
+ _search_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEARCHES)
32
+ _userbot_session_dead = False
33
+
34
+ # Cache: chat_id -> title string so we don't call get_chat() per result
35
+ _chat_title_cache: Dict[int, str] = {}
36
+
37
+ _TOKEN_RE = re.compile(r"[a-z0-9]+")
38
+
39
+
40
+ # ── Availability ──────────────────────────────────────────────────────────────
41
+
42
+ def is_userbot_available() -> bool:
43
+ from Backend.pyrofork.bot import Userbot
44
+ return Userbot is not None and not _userbot_session_dead
45
+
46
+
47
+ def is_global_search_enabled() -> bool:
48
+ if not is_userbot_available():
49
+ return False
50
+ s = SettingsManager.current()
51
+ return bool(s.global_search and s.global_search_channels)
52
+
53
+
54
+ # ── Helpers ───────────────────────────────────────────────────────────────────
55
+
56
+ def _readable_size(num_bytes: int) -> str:
57
+ from Backend.helper.pyro import get_readable_file_size
58
+ return get_readable_file_size(num_bytes)
59
+
60
+
61
+ def _tokens(s: str) -> set:
62
+ return set(_TOKEN_RE.findall((s or "").lower()))
63
+
64
+
65
+ def _title_score(result_title: str, expected_title: str) -> float:
66
+ expected = _tokens(expected_title)
67
+ if not expected:
68
+ return 0.0
69
+ return len(expected & _tokens(result_title)) / len(expected)
70
+
71
+
72
+ def _matches_episode(parsed: dict, season: Optional[int], episode: Optional[int]) -> bool:
73
+ if season is not None:
74
+ rs = parsed.get("season")
75
+ if rs is not None:
76
+ if isinstance(rs, list):
77
+ if season not in rs:
78
+ return False
79
+ elif int(rs) != int(season):
80
+ return False
81
+
82
+ if episode is not None:
83
+ re_ = parsed.get("episode")
84
+ if re_ is not None:
85
+ if isinstance(re_, list):
86
+ if episode not in re_:
87
+ return False
88
+ elif int(re_) != int(episode):
89
+ return False
90
+
91
+ return True
92
+
93
+
94
+ def _parse_and_validate(
95
+ filename: str,
96
+ expected_title: str,
97
+ season: Optional[int],
98
+ episode: Optional[int],
99
+ ) -> Optional[dict]:
100
+ try:
101
+ parsed = PTN.parse(filename)
102
+ except Exception:
103
+ return None
104
+ if not _matches_episode(parsed, season, episode):
105
+ return None
106
+ if _title_score(parsed.get("title", ""), expected_title) < MIN_TITLE_SCORE:
107
+ return None
108
+ return parsed
109
+
110
+
111
+ def _video_filename(message) -> Optional[str]:
112
+ if message.video:
113
+ return (message.caption or "").strip() or getattr(message.video, "file_name", None) or "video.mkv"
114
+ if message.document:
115
+ mime = message.document.mime_type or ""
116
+ if mime.startswith("video/") or message.document.file_name and (
117
+ message.document.file_name.lower().endswith(
118
+ (".mkv", ".mp4", ".avi", ".ts", ".m4v", ".mov", ".wmv", ".webm", ".flv")
119
+ )
120
+ ):
121
+ return (message.caption or "").strip() or message.document.file_name or "video.mkv"
122
+ return None
123
+
124
+
125
+ def _resolve_channel_ids(channel_ids: List[str]) -> List[int]:
126
+ resolved = []
127
+ seen: set = set()
128
+ for c in channel_ids:
129
+ c = str(c).strip()
130
+ if not c:
131
+ continue
132
+ try:
133
+ raw = int(c)
134
+ except ValueError:
135
+ continue
136
+ canonical = raw if raw < 0 else int(f"-100{raw}")
137
+ if canonical not in seen:
138
+ seen.add(canonical)
139
+ resolved.append(canonical)
140
+ return resolved
141
+
142
+
143
+ async def _get_chat_title(client, chat_id: int) -> str:
144
+ if chat_id in _chat_title_cache:
145
+ return _chat_title_cache[chat_id]
146
+ try:
147
+ chat = await client.get_chat(chat_id)
148
+ title = chat.title or str(chat_id)
149
+ except Exception:
150
+ title = str(chat_id)
151
+ _chat_title_cache[chat_id] = title
152
+ return title
153
+
154
+
155
+ async def _search_channel(
156
+ client,
157
+ chat_id: int,
158
+ chat_title: str,
159
+ search_query: str,
160
+ expected_title: str,
161
+ season: Optional[int],
162
+ episode: Optional[int],
163
+ ) -> List[Dict]:
164
+
165
+ results: List[Dict] = []
166
+ seen_msg_ids: set = set()
167
+ filters_to_try = [enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT]
168
+
169
+ for msg_filter in filters_to_try:
170
+ if len(results) >= MAX_RESULTS_PER_CHAT:
171
+ break
172
+ try:
173
+ async for message in client.search_messages(
174
+ chat_id=chat_id,
175
+ query=search_query,
176
+ filter=msg_filter,
177
+ limit=MAX_RESULTS_PER_CHAT,
178
+ ):
179
+ if message.id in seen_msg_ids:
180
+ continue
181
+ seen_msg_ids.add(message.id)
182
+
183
+ filename = _video_filename(message)
184
+ if not filename:
185
+ continue
186
+
187
+ parsed = _parse_and_validate(filename, expected_title, season, episode)
188
+ if parsed is None:
189
+ continue
190
+
191
+ media = message.video or message.document
192
+ size_bytes = getattr(media, "file_size", 0) or 0
193
+ quality = parsed.get("resolution") or "HD"
194
+
195
+ token = await encode_string({
196
+ "global": True,
197
+ "chat_id": chat_id,
198
+ "msg_id": message.id,
199
+ "title": filename,
200
+ "size": _readable_size(size_bytes),
201
+ "quality": quality,
202
+ "source": chat_title,
203
+ })
204
+
205
+ results.append({
206
+ "token": token,
207
+ "title": filename,
208
+ "size": _readable_size(size_bytes),
209
+ "source_chat": chat_title,
210
+ "quality": quality,
211
+ })
212
+
213
+ LOGGER.debug(f"[GLOBAL SEARCH] Result found: {filename} in {chat_title}")
214
+
215
+ if len(results) >= MAX_RESULTS_PER_CHAT:
216
+ break
217
+
218
+ except FloodWait as e:
219
+ LOGGER.warning(f"[USERBOT] FloodWait for {chat_title}: sleeping {e.value}s")
220
+ await asyncio.sleep(e.value)
221
+ except (ChatAdminRequired, ChannelPrivate, PeerIdInvalid, UserNotParticipant) as e:
222
+ LOGGER.warning(f"[USERBOT] Cannot access channel {chat_title}: {type(e).__name__}")
223
+ break # no point trying second filter either
224
+ except (AuthKeyUnregistered, SessionRevoked) as e:
225
+ LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
226
+ global _userbot_session_dead
227
+ _userbot_session_dead = True
228
+ break
229
+ except RPCError as e:
230
+ LOGGER.warning(f"[USERBOT] RPC error in {chat_title} ({msg_filter}): {e}")
231
+
232
+ return results
233
+
234
+
235
+ # ── Public API ────────────────────────────────────────────────────────────────
236
+
237
+ async def global_search(
238
+ expected_title: str,
239
+ auth_channels: List[str],
240
+ *,
241
+ year: Optional[int] = None,
242
+ season: Optional[int] = None,
243
+ episode: Optional[int] = None,
244
+ ) -> List[Dict]:
245
+ expected_title = (expected_title or "").strip()
246
+ if not expected_title or not is_global_search_enabled():
247
+ return []
248
+
249
+ from Backend.pyrofork.bot import Userbot
250
+
251
+ settings = SettingsManager.current()
252
+ target_ids = _resolve_channel_ids(settings.global_search_channels)
253
+ if not target_ids:
254
+ return []
255
+
256
+ search_query = expected_title
257
+ if season is not None and episode is not None:
258
+ search_query = f"{expected_title} S{int(season):02d}E{int(episode):02d}"
259
+ elif year is not None:
260
+ search_query = f"{expected_title} {year}"
261
+
262
+
263
+ key = search_query.lower()
264
+ now = time.time()
265
+ if now - _last_search_ts.get(key, 0) < SEARCH_COOLDOWN_SECONDS:
266
+ LOGGER.info(f"[GLOBAL SEARCH] Cooldown active for '{search_query}'")
267
+ return []
268
+ if key in _inflight_queries:
269
+ LOGGER.info(f"[GLOBAL SEARCH] Duplicate in-flight for '{search_query}'")
270
+ return []
271
+
272
+ _inflight_queries.add(key)
273
+ _last_search_ts[key] = now
274
+
275
+ try:
276
+ async with _search_semaphore:
277
+ LOGGER.info(
278
+ f"[USERBOT] Search started: '{search_query}' "
279
+ f"across {len(target_ids)} channel(s)"
280
+ )
281
+ title_tasks = [_get_chat_title(Userbot, cid) for cid in target_ids]
282
+ chat_titles = await asyncio.gather(*title_tasks, return_exceptions=True)
283
+
284
+ search_tasks = []
285
+ for cid, title in zip(target_ids, chat_titles):
286
+ if isinstance(title, Exception):
287
+ title = str(cid)
288
+ if _userbot_session_dead:
289
+ break
290
+ search_tasks.append(
291
+ _search_channel(Userbot, cid, title, search_query, expected_title, season, episode)
292
+ )
293
+
294
+ per_channel_results = await asyncio.gather(*search_tasks, return_exceptions=True)
295
+
296
+ all_results: List[Dict] = []
297
+ for r in per_channel_results:
298
+ if isinstance(r, list):
299
+ all_results.extend(r)
300
+
301
+ all_results = all_results[:MAX_RESULTS]
302
+
303
+ LOGGER.info(
304
+ f"[USERBOT] Search completed: '{search_query}' "
305
+ f"-> {len(all_results)} result(s)"
306
+ )
307
+ return all_results
308
+ finally:
309
+ _inflight_queries.discard(key)
Backend/helper/settings_manager.py CHANGED
@@ -23,6 +23,8 @@ _DEFAULTS: Dict[str, Any] = {
23
  "show_proxy_and_non_proxy_both": False,
24
  "multi_tokens": [],
25
  "extra_databases": [],
 
 
26
  }
27
 
28
 
@@ -45,6 +47,7 @@ def _seed_from_env() -> Dict[str, Any]:
45
  "subscription_group_id": Telegram.SUBSCRIPTION_GROUP_ID,
46
  "subscription_url": Telegram.SUBSCRIPTION_URL,
47
  "approver_ids": list(Telegram.APPROVER_IDS),
 
48
  "http_proxy_url": Telegram.HTTP_PROXY_URL,
49
  "show_proxy_and_non_proxy_both": Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH,
50
  "multi_tokens": [],
@@ -81,6 +84,14 @@ class Settings:
81
  def show_proxy_and_non_proxy_both(self) -> bool:
82
  return bool(self._d["show_proxy_and_non_proxy_both"])
83
 
 
 
 
 
 
 
 
 
84
  # ── Strings ──────────────────────────────────────────────────────────────
85
  @property
86
  def tmdb_api(self) -> str:
@@ -183,6 +194,18 @@ class SettingsManager:
183
 
184
  results: Dict[str, str] = {}
185
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  # ── Phase 1: validate / apply things that can abort the save ───────
187
  old_extra = old.get("extra_databases") or []
188
  new_extra = merged.get("extra_databases") or []
@@ -255,4 +278,9 @@ class SettingsManager:
255
  if any(old.get(k) != new.get(k) for k in cred_keys):
256
  results["admin_credentials"] = "updated β€” takes effect on next login"
257
 
 
 
 
 
 
258
  return results
 
23
  "show_proxy_and_non_proxy_both": False,
24
  "multi_tokens": [],
25
  "extra_databases": [],
26
+ "global_search": False,
27
+ "global_search_channels": [],
28
  }
29
 
30
 
 
47
  "subscription_group_id": Telegram.SUBSCRIPTION_GROUP_ID,
48
  "subscription_url": Telegram.SUBSCRIPTION_URL,
49
  "approver_ids": list(Telegram.APPROVER_IDS),
50
+ "global_search_channels": [],
51
  "http_proxy_url": Telegram.HTTP_PROXY_URL,
52
  "show_proxy_and_non_proxy_both": Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH,
53
  "multi_tokens": [],
 
84
  def show_proxy_and_non_proxy_both(self) -> bool:
85
  return bool(self._d["show_proxy_and_non_proxy_both"])
86
 
87
+ @property
88
+ def global_search(self) -> bool:
89
+ return bool(self._d.get("global_search", False))
90
+
91
+ @property
92
+ def global_search_channels(self):
93
+ return list(self._d.get("global_search_channels") or [])
94
+
95
  # ── Strings ──────────────────────────────────────────────────────────────
96
  @property
97
  def tmdb_api(self) -> str:
 
194
 
195
  results: Dict[str, str] = {}
196
 
197
+ # Global Search hard requires a Userbot session β€” never trust the
198
+ # client to have enforced this; guard it here too.
199
+ if merged.get("global_search"):
200
+ from Backend.config import Telegram
201
+ if not Telegram.USER_SESSION_STRING:
202
+ merged["global_search"] = False
203
+ LOGGER.warning(
204
+ "SettingsManager: rejected global_search=True β€” "
205
+ "USER_SESSION_STRING is not configured."
206
+ )
207
+ results["global_search"] = "rejected β€” no Userbot session configured"
208
+
209
  # ── Phase 1: validate / apply things that can abort the save ───────
210
  old_extra = old.get("extra_databases") or []
211
  new_extra = merged.get("extra_databases") or []
 
278
  if any(old.get(k) != new.get(k) for k in cred_keys):
279
  results["admin_credentials"] = "updated β€” takes effect on next login"
280
 
281
+ # Global Search toggle changed (only meaningful logging here; the
282
+ # search module reads SettingsManager.current() live each call)
283
+ if old.get("global_search") != new.get("global_search") and "global_search" not in results:
284
+ results["global_search"] = "enabled" if new.get("global_search") else "disabled"
285
+
286
  return results
Backend/helper/task_manager.py CHANGED
@@ -1,32 +1,133 @@
1
  from asyncio import sleep
2
- from pyrogram.errors import FloodWait
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from Backend.logger import LOGGER
4
- from Backend.pyrofork.bot import Helper
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- async def edit_message(chat_id: int, msg_id: int, new_caption: str):
7
  try:
8
- await Helper.edit_message_caption(
9
- chat_id=chat_id,
10
- message_id=msg_id,
11
- caption=new_caption
12
- )
13
  await sleep(2)
 
14
  except FloodWait as e:
15
- LOGGER.warning(f"FloodWait for {e.value} seconds while editing message {msg_id} in {chat_id}")
16
  await sleep(e.value)
 
 
 
 
 
 
 
 
 
 
 
17
  except Exception as e:
18
  LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
19
 
20
- async def delete_message(chat_id: int, msg_id: int):
 
 
21
  try:
22
- await Helper.delete_messages(
23
- chat_id=chat_id,
24
- message_ids=msg_id
25
- )
26
  await sleep(2)
27
- LOGGER.info(f"Deleted message {msg_id} in {chat_id}")
28
  except FloodWait as e:
29
- LOGGER.warning(f"FloodWait for {e.value} seconds while deleting message {msg_id} in {chat_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  await sleep(e.value)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  except Exception as e:
32
- LOGGER.error(f"Error while deleting message {msg_id} in {chat_id}: {e}")
 
 
1
  from asyncio import sleep
2
+ from typing import List, Optional
3
+
4
+ from pyrogram.errors import (
5
+ FloodWait,
6
+ ChatAdminRequired,
7
+ ChannelPrivate,
8
+ MessageDeleteForbidden,
9
+ MessageAuthorRequired,
10
+ PeerIdInvalid,
11
+ UserNotParticipant,
12
+ AuthKeyUnregistered,
13
+ SessionRevoked,
14
+ RPCError,
15
+ )
16
+
17
  from Backend.logger import LOGGER
18
+ from Backend.pyrofork.bot import StreamBot, Userbot
19
+
20
+ DELETE_BATCH_SIZE = 10
21
+ _FALLBACK_WORTHY = (
22
+ ChatAdminRequired,
23
+ ChannelPrivate,
24
+ MessageDeleteForbidden,
25
+ MessageAuthorRequired,
26
+ PeerIdInvalid,
27
+ UserNotParticipant,
28
+ RPCError,
29
+ )
30
+ _SESSION_DEAD = (AuthKeyUnregistered, SessionRevoked)
31
+ _userbot_session_dead = False
32
+
33
+
34
+ def _userbot_usable() -> bool:
35
+ return Userbot is not None and not _userbot_session_dead
36
+
37
 
38
+ async def edit_message(chat_id: int, msg_id: int, new_caption: str):
39
  try:
40
+ await StreamBot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption)
 
 
 
 
41
  await sleep(2)
42
+ return
43
  except FloodWait as e:
44
+ LOGGER.warning(f"FloodWait for {e.value}s while editing message {msg_id} in {chat_id}")
45
  await sleep(e.value)
46
+ try:
47
+ await StreamBot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption)
48
+ return
49
+ except Exception as e2:
50
+ LOGGER.error(f"Retry after FloodWait failed while editing {msg_id} in {chat_id}: {e2}")
51
+ except _FALLBACK_WORTHY as e:
52
+ if not _userbot_usable():
53
+ LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
54
+ return
55
+ LOGGER.info(f"[USERBOT] Fallback triggered: edit_message {msg_id} in {chat_id} (StreamBot: {e})")
56
+ await _userbot_edit(chat_id, msg_id, new_caption)
57
  except Exception as e:
58
  LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
59
 
60
+
61
+ async def _userbot_edit(chat_id: int, msg_id: int, new_caption: str):
62
+ global _userbot_session_dead
63
  try:
64
+ await Userbot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption)
 
 
 
65
  await sleep(2)
 
66
  except FloodWait as e:
67
+ LOGGER.warning(f"[USERBOT] FloodWait detected: sleeping {e.value}s (edit {msg_id} in {chat_id})")
68
+ await sleep(e.value)
69
+ try:
70
+ await Userbot.edit_message_caption(chat_id=chat_id, message_id=msg_id, caption=new_caption)
71
+ except Exception as e2:
72
+ LOGGER.error(f"[USERBOT] Retry after FloodWait failed while editing {msg_id} in {chat_id}: {e2}")
73
+ except _SESSION_DEAD as e:
74
+ _userbot_session_dead = True
75
+ LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}. Disabling Userbot fallback for this run.")
76
+ except Exception as e:
77
+ LOGGER.error(f"[USERBOT] Error while editing message {msg_id} in {chat_id}: {e}")
78
+
79
+
80
+ async def delete_message(chat_id: int, msg_id: int):
81
+ await delete_messages_batch(chat_id, [msg_id])
82
+
83
+
84
+ async def delete_messages_batch(chat_id: int, msg_ids: List[int]):
85
+ if not msg_ids:
86
+ return
87
+
88
+ for i in range(0, len(msg_ids), DELETE_BATCH_SIZE):
89
+ chunk = msg_ids[i:i + DELETE_BATCH_SIZE]
90
+
91
+ remaining = await _delete_chunk(StreamBot, "StreamBot", chat_id, chunk)
92
+
93
+ if remaining and _userbot_usable():
94
+ LOGGER.info(f"[USERBOT] Fallback triggered: deleting {len(remaining)} message(s) in {chat_id}")
95
+ remaining = await _delete_chunk(Userbot, "Userbot", chat_id, remaining)
96
+
97
+ if remaining:
98
+ LOGGER.error(
99
+ f"Could not delete {len(remaining)} message(s) in {chat_id} "
100
+ f"(no usable Userbot fallback)" if not _userbot_usable() else
101
+ f"Could not delete {len(remaining)} message(s) in {chat_id} even with Userbot fallback"
102
+ )
103
+
104
+ await sleep(1)
105
+
106
+
107
+ async def _delete_chunk(client, client_label: str, chat_id: int, msg_ids: List[int]) -> List[int]:
108
+ global _userbot_session_dead
109
+ try:
110
+ await client.delete_messages(chat_id=chat_id, message_ids=msg_ids)
111
+ LOGGER.info(f"[{client_label.upper()}] Deleted {len(msg_ids)} message(s) in {chat_id}")
112
+ return []
113
+ except FloodWait as e:
114
+ LOGGER.warning(f"[{client_label.upper()}] FloodWait detected: sleeping {e.value}s ({len(msg_ids)} msg(s) in {chat_id})")
115
  await sleep(e.value)
116
+ try:
117
+ await client.delete_messages(chat_id=chat_id, message_ids=msg_ids)
118
+ LOGGER.info(f"[{client_label.upper()}] Deleted {len(msg_ids)} message(s) in {chat_id} after FloodWait retry")
119
+ return []
120
+ except Exception as e2:
121
+ LOGGER.error(f"[{client_label.upper()}] Retry after FloodWait failed in {chat_id}: {e2}")
122
+ return msg_ids
123
+ except _SESSION_DEAD as e:
124
+ if client_label == "Userbot":
125
+ _userbot_session_dead = True
126
+ LOGGER.error(f"[{client_label.upper()}] Session invalid ({type(e).__name__}): {e}")
127
+ return msg_ids
128
+ except _FALLBACK_WORTHY as e:
129
+ LOGGER.warning(f"[{client_label.upper()}] Cannot delete in {chat_id} ({type(e).__name__}): {e}")
130
+ return msg_ids
131
  except Exception as e:
132
+ LOGGER.error(f"[{client_label.upper()}] Unexpected error deleting in {chat_id}: {e}")
133
+ return msg_ids
Backend/pyrofork/bot.py CHANGED
@@ -12,18 +12,28 @@ StreamBot = Client(
12
  max_concurrent_transmissions=10
13
  )
14
 
15
- Helper = Client(
16
- "helper",
17
- api_id=Telegram.API_ID,
18
- api_hash=Telegram.API_HASH,
19
- bot_token=Telegram.HELPER_BOT_TOKEN,
20
- sleep_threshold=20,
21
- workers=6,
22
- max_concurrent_transmissions=10
23
- )
 
 
 
 
 
24
 
25
  multi_clients = {}
26
  work_loads = {}
27
  client_dc_map = {}
28
- client_failures = {}
29
- client_avg_mbps = {}
 
 
 
 
 
 
12
  max_concurrent_transmissions=10
13
  )
14
 
15
+ USERBOT_CLIENT_INDEX = -1
16
+
17
+ Userbot = None
18
+ if Telegram.USER_SESSION_STRING:
19
+ Userbot = Client(
20
+ name='userbot',
21
+ api_id=Telegram.API_ID,
22
+ api_hash=Telegram.API_HASH,
23
+ session_string=Telegram.USER_SESSION_STRING,
24
+ sleep_threshold=20,
25
+ workers=6,
26
+ max_concurrent_transmissions=10,
27
+ no_updates=True,
28
+ )
29
 
30
  multi_clients = {}
31
  work_loads = {}
32
  client_dc_map = {}
33
+ client_failures = {}
34
+ client_avg_mbps = {}
35
+
36
+ if Userbot is not None:
37
+ work_loads[USERBOT_CLIENT_INDEX] = 0
38
+ client_failures[USERBOT_CLIENT_INDEX] = 0
39
+ client_avg_mbps[USERBOT_CLIENT_INDEX] = 0.0
README.md CHANGED
@@ -22,77 +22,77 @@
22
 
23
  ## 🧭 Quick Navigation
24
 
25
- - [πŸš€ Introduction](#-introduction)
26
- - [✨ Key Features](#-key-features)
27
- - [πŸ†• New Features](#-new-features)
28
- - [οΏ½ Subscription Management](#-subscription-management)
29
- - [πŸ’³ Subscription Management](#-subscription-management-config)
30
- - [πŸ“‹ Plans](#-subscription-plans)
31
- - [πŸ€– Bot Payment Flow](#-bot-payment-flow)
32
- - [πŸ—ƒοΈ Access Management](#️-access-management)
33
- - [🎬 Stremio Addon Integration](#-stremio-addon-integration)
34
- - [βš™οΈ How It Works](#️-how-it-works)
35
- - [Overview](#overview)
36
- - [Upload Guidelines](#upload-guidelines)
37
- - [Quality Replacement](#-quality-replacement-logic)
38
- - [Updating CAMRip](#-updating-camrip-or-low-quality-files)
39
- - [Behind The Scenes](#behind-the-scenes)
40
- - [πŸ€– Bot Commands](#-bot-commands)
41
- - [Command List](#command-list)
42
- - [`/set` Command Usage](#set-command-usage)
43
- - [πŸ”§ Configuration Guide](#-configuration-guide)
44
- - [🧩 Startup Config](#-startup-config)
45
- - [πŸ—„οΈ Storage](#️-storage)
46
- - [🎬 API](#-api)
47
- - [🌐 Server](#-server)
48
- - [πŸ”„ Update Settings](#-update-settings)
49
- - [πŸ” Admin Panel](#-admin-panel)
50
-
51
- - [🧰 Additional CDN Bots (Multi-Token System)](#-additional-cdn-bots-multi-token-system)
52
-
53
- - [οΏ½πŸš€ Deployment Guide](#-deployment-guide)
54
- - [βœ… Recommended Prerequisites](#-recommended-prerequisites)
55
- - [πŸ™ Heroku Guide](#-heroku-guide)
56
- - [🐳 VPS Guide (Recommended)](#-vps-guide)
57
- - [πŸ“Ί Setting up Stremio](#-setting-up-stremio)
58
- - [🌐 Add the Addon](#-step-3-add-the-addon)
59
- - [βš™οΈ Optional: Remove Cinemeta](#️-optional-remove-cinemeta)
60
- - [πŸ… Contributor](#-contributor)
61
 
 
 
 
 
 
 
62
 
63
- # πŸš€ Introduction
64
 
65
- This project is a **next-generation Telegram Stremio Media Server** that allows you to **stream your Telegram files directly through Stremio**, without any third-party dependencies or file expiration issues. It’s designed for **speed, scalability, and reliability**, making it ideal for both personal and community-based media hosting.
 
 
 
 
66
 
 
67
 
68
- ## ✨ Key Features
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- - βš™οΈ **Multiple MongoDB Support**
71
- - πŸ“‘ **Multiple Channel Support**
72
- - ⚑ **Fast Streaming Experience**
73
- - πŸ”‘ **Multi Token Load Balancer**
74
- - 🎬 **IMDB and TMDB Metadata Integration**
75
- - ♾️ **No File Expiration**
76
- - 🧠 **Admin Panel Support**
77
- - πŸ’³ **Subscription Management** β€” Plans, payment approval, auto token generation, and expiry enforcement
78
- - πŸ” **Access Management** β€” View, extend, reduce, revoke, and reassign subscriptions from the admin UI
79
 
 
 
 
 
 
 
 
 
 
80
 
81
- ## πŸ†• New Features
82
 
83
- - ⚑ **Speed Test** – Speed testing added for all bots on each file to optimize streaming performance.
84
- - πŸ”„ **Improved Load Balancer** – Enhanced load balancing algorithm for better traffic distribution across multiple tokens.
85
- - 🚫 **Failed Bot Management** – Max failed bots will be marked as shadow or idle for buffer optimization. This is due to some data center bots having rate-limiting constraints.
86
- - πŸ“Š **Bot-wise Analysis** – Detailed bot performance analytics available in the admin dashboard for monitoring and optimization.
87
- - 🧹 **Deleted File Detection** – Automatic detection of deleted files on every restart, with admin capability to manually remove them from the database.
88
- - πŸ› οΈ **Additional Admin Features** – Various small enhancements and improvements for administrators.
89
- - πŸ†“ **Free Mode Toggle** – Administrators can turn off the `SUBSCRIPTION` requirement in `config.env` to allow all users immediate access via an automatically generated API token.
90
- - πŸ”„ **Automatic Stream Cleanup** – Deleting a source message in the Telegram channel instantly deletes all corresponding streams and qualities from the Stremio Addon Database and Admin Panel, preventing dead links.
91
- - 🏷️ **Manual IMDb/TMDb Override** – Users can instantly update or fix incorrect metadata for a file by simply editing the Telegram channel message caption and pasting the correct IMDb/TMDB URL.
92
- - πŸ›‘οΈ **Stream Stability & Recovery** – Intelligent `b""` empty-chunk fallback that securely pads video streams with zero bytes, and reduced chunk retry lockups (from 6 to 3) to instantaneously recover from stalled parts without breaking the video player.
93
- - 🎯 **DC-Aware Bot Selection** – The underlying streaming load-balancer now ensures that a bot located in the exact same Data Center as the media file is prioritized. This substantially minimizes cross-DC round-trips and timeouts.
94
- - 🌐 **Addon Proxy Integration** – Built-in functionality targeting `config.env` configurations (`Proxy`, `ProxyType`, `HTTP_Proxy_URL`, `SHOW_ProxyAndNonProxyBoth`) allows instant proxying or caching of video streams (such as routing through Cloudflare Workers) natively on Stremio.
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
 
98
 
@@ -151,19 +151,20 @@ Harikatha.Sambhavami.Yuge.Yuge.S01E04.Dark.Hours.1080p.WEB-DL.DUAL.DDP5.1.Atmos.
151
 
152
  ### πŸ” Quality Replacement Logic
153
 
154
- When you upload multiple files with the **same quality label** (like `720p` or `1080p`),
155
- the **latest file automatically replaces the old one**.
 
156
 
157
- > Example:
158
- > If you already uploaded `Ghosted 2023 720p` and then upload another `720p` version,
159
- > the bot **replaces the old file** to keep your catalog clean and organized.
160
 
161
- This helps avoid duplicate entries in Stremio and ensures only the most recent file is used.
162
 
163
  ---
164
 
165
  ### πŸ†™ Updating CAMRip or Low-Quality Files
166
 
 
 
167
  If you initially uploaded a **CAMRip or low-quality version**, you can easily replace it with a better one:
168
 
169
  1. Forward the **new, higher-quality file** (e.g., `1080p`, `WEB-DL`) to your **AUTH CHANNEL**.
@@ -176,13 +177,27 @@ If you initially uploaded a **CAMRip or low-quality version**, you can easily re
176
 
177
  ### 🏷️ Fixing Incorrect Metadata (Manual Override)
178
 
179
- If the addon incorrectly identifies a movie or TV show, or if the metadata is entirely missing, you can fix it effortlessly by editing the message in your Telegram channel:
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- 1. Copy the correct **IMDb URL** or **TMDB URL** for the movie/show.
182
- 2. Edit the message caption in your Telegram **AUTH CHANNEL** and paste the URL.
183
- 3. The bot will automatically wipe the old, incorrect database entry for that file and instantly re-fetch the metadata using your provided link.
 
 
184
 
185
- βœ… The Stremio addon catalog will update dynamically to reflect the correctly identified media.
186
 
187
  ---
188
 
@@ -245,95 +260,119 @@ The `/set` command is used to manually upload a specific Movie or TV show to you
245
  πŸ’‘ **Tip:** Use `/log` if you encounter any upload or parsing issues.
246
 
247
 
 
248
  # πŸ”§ Configuration Guide
249
 
250
- All environment variables for this project are defined in the `config.env` file. A detailed explanation of each parameter is provided below.
251
 
252
- ### 🧩 Startup Config
253
 
254
- | Variable | Description |
255
- | :--- | :--- |
256
- | **`API_ID`** | Your Telegram **API ID** from [my.telegram.org](https://my.telegram.org). Used for authenticating your Telegram session. |
257
- | **`API_HASH`** | Your Telegram **API Hash** from [my.telegram.org](https://my.telegram.org). |
258
- | **`BOT_TOKEN`** | The main bot’s **access token** from [@BotFather](https://t.me/BotFather). Handles user requests and media fetching. |
259
- | **`HELPER_BOT_TOKEN`** | **Secondary bot token** used to assist the main bot with tasks like deleting, editing, or managing. |
260
- | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
261
- | **`REPLACE_MODE`** | When `true`, new files replace existing files of the same quality. When `false`, multiple files of the same quality are allowed. |
262
- | **`HIDE_CATALOG`** | When `true`, the default Telegram Stremio Catalog is hidden, and streams only show in the Cinemata catalog (i.e., Cinemata addon is mandatory). Default is `false`. |
263
- | **`PARALLEL`** | Controls the queue size for chunks buffered ahead. Keeps the player buffer full without overloading Telegram. Example: `PARALLEL = 4` means 4 chunks are buffered ahead. Default is `1`. |
264
- | **`PRE_FETCH`** | Controls the number of workers downloading chunks simultaneously. Example: `PRE_FETCH = 3` means 3 workers download concurrently. Higher values can improve speed but increase API load. Default is `1`. |
265
-
266
- ### πŸ—„οΈ Storage
267
-
268
- | Variable | Description |
269
- | :--- | :--- |
270
- | **`AUTH_CHANNEL`** | One or more **Telegram channel IDs** (comma-separated) where the bot is authorized to fetch or stream content. *Example: `-1001234567890, -1009876543210`*. |
271
- | **`DATABASE`** | MongoDB Atlas connection URI(s). You **must provide at least two databases**, separated by commas (`,`) for load balancing and redundancy. <br>Example: <br>`mongodb+srv://user:pass@cluster0.mongodb.net/db1, mongodb+srv://user:pass@cluster1.mongodb.net/db2` |
272
 
273
- > πŸ’‘ **Tip:** Create your MongoDB Atlas cluster [here](https://www.mongodb.com/cloud/atlas).
 
 
 
 
 
 
 
 
274
 
275
- ### 🎬 API
276
 
277
- | Variable | Description |
278
- | :--- | :--- |
279
- | **`TMDB_API`** | Your **TMDB API key** from [themoviedb.org](https://www.themoviedb.org/settings/api). Used to fetch movie and TV metadata. |
280
 
281
- ### 🌐 Server
282
 
283
- | Variable | Description |
284
- | :--- | :--- |
285
- | **`BASE_URL`** | The Domain or Heroku app URL (e.g. `https://your-domain.com`). Crucial for Stremio addon setup. |
286
- | **`PORT`** | The port number on which your FastAPI server will run. *Default: `8000`*. |
287
 
288
- ### πŸ”„ Update Settings
 
 
 
 
 
 
 
289
 
290
- | Variable | Description |
291
- | :--- | :--- |
292
- | **`UPSTREAM_REPO`** | GitHub repository URL for automatic updates. |
293
- | **`UPSTREAM_BRANCH`** | The branch name to track in your upstream repo. *Default: `master`*. |
294
 
295
- ### πŸ” Admin Panel
296
 
297
- | Variable | Description |
298
- | :--- | :--- |
299
- | **`ADMIN_USERNAME`** | Username for logging into the Admin Panel. |
300
- | **`ADMIN_PASSWORD`** | Password for Admin Panel access.|
301
- **⚠️ Change from default values for security.**
302
 
303
- ### πŸ’³ Subscription Management Config
304
 
305
- Enable the subscription feature to gate access to streams behind a paid plan. When `SUBSCRIPTION=True`, every user must have an active subscription to stream content.
306
 
307
- | Variable | Description |
308
- | :--- | :--- |
309
- | **`SUBSCRIPTION`** | Enable (`True`) or disable (`False`) the subscription gate. When enabled, users without an active subscription see an expired message in Stremio instead of streams. *Default: `False`*. |
310
- | **`SUBSCRIPTION_GROUP_ID`** | Telegram **group/channel ID** where approved subscribers are invited. Users receive an invite link upon payment approval. |
311
- | **`APPROVER_IDS`** | Comma-separated Telegram user IDs of admins who can **approve or reject** subscription payment requests. |
312
- | **`SUBSCRIPTION_URL`** | Telegram bot URL (e.g. `https://t.me/your_bot`) shown to expired users in Stremio so they can renew. |
313
 
314
- > πŸ’‘ `SUBSCRIPTION_GROUP_ID` and `APPROVER_IDS` must be set **without quotes** in `config.env`.
315
 
316
- ### 🧰 Additional CDN Bots (Multi-Token System)
317
 
318
- | Variable | Description |
319
- | :--- | :--- |
320
- | **`MULTI_TOKEN1`**, **`MULTI_TOKEN2`**, ... | Extra bot tokens used to distribute traffic and prevent Telegram rate-limiting. Add each bot as an **Admin** in your `AUTH_CHANNEL`(s). |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
- #### About `MULTI_TOKEN`
323
 
324
- If your bot handles a high number of downloads/requests at a time, Telegram may limit your main bot.
325
- To avoid this, you can use **MULTI_TOKEN** system:
326
 
327
- - Create multiple bots using [@BotFather](https://t.me/BotFather).
328
- - Add each bot as **Admin** in your `AUTH_CHANNEL`(s).
329
- - Add the tokens in your `config.env` as `MULTI_TOKEN1`, `MULTI_TOKEN2`, `MULTI_TOKEN3`, and so on.
330
- - The system will automatically distribute the load among all these bots!
331
 
332
- > ⚠️ **Real Limitation:**
333
- > Even if you configure 10 bots in your system, **a single stream will typically only use 1 bot**. Extra bots do not make a single stream download 10x faster. Their primary purpose is to help handle **multiple users streaming simultaneously** without hitting rate limits:
334
- > - User 1 β†’ assigned to Bot 1
335
- > - User 2 β†’ assigned to Bot 2
336
- > - User 3 β†’ assigned to Bot 3
337
 
338
 
339
  ---
 
22
 
23
  ## 🧭 Quick Navigation
24
 
25
+ * [πŸš€ Introduction](#-introduction)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ * [✨ Key Features](#-key-features)
28
+ * [πŸ’³ Subscription Management](#-subscription-management)
29
+ * [πŸ“‹ Subscription Plans](#-subscription-plans)
30
+ * [πŸ€– Bot Payment Flow](#-bot-payment-flow)
31
+ * [πŸ—ƒοΈ Access Management](#️-access-management)
32
+ * [🎬 Stremio Addon Integration](#-stremio-addon-integration)
33
 
34
+ * [βš™οΈ How It Works](#️-how-it-works)
35
 
36
+ * [πŸ“– Overview](#overview)
37
+ * [πŸ“€ Upload Guidelines](#upload-guidelines)
38
+ * [πŸ” Quality Replacement Logic](#-quality-replacement-logic)
39
+ * [πŸŽ₯ Updating CAMRip or Low-Quality Files](#-updating-camrip-or-low-quality-files)
40
+ * [βš™οΈ Behind the Scenes](#behind-the-scenes)
41
 
42
+ * [πŸ€– Bot Commands](#-bot-commands)
43
 
44
+ * [πŸ“œ Command List](#command-list)
45
+ * [βš™οΈ /set Command Usage](#set-command-usage)
46
+
47
+ * [πŸ”§ Configuration Guide](#-configuration-guide)
48
+
49
+ * [πŸš€ Quick Setup](#-quick-setup)
50
+ * [🧩 Startup Configuration](#-startup-configuration)
51
+ * [πŸ“š Media & Catalog Settings](#-media--catalog-settings)
52
+ * [🌐 Proxy Settings](#-proxy-settings)
53
+ * [πŸ’³ Subscription System](#-subscription-system)
54
+ * [🧠 Admin Panel](#-admin-panel)
55
+ * [πŸ”„ Update Settings](#-update-settings)
56
+ * [πŸ—„οΈ Multi-Database Support](#️-multi-database-support)
57
+ * [πŸ”‘ Multi-Token System](#-multi-token-system)
58
+ * [πŸ” Global Search Requirements](#-global-search-requirements)
59
+
60
+ * [πŸš€ Deployment Guide](#-deployment-guide)
61
+
62
+ * [βœ… Recommended Prerequisites](#-recommended-prerequisites)
63
+ * [πŸ™ Heroku Guide](#-heroku-guide)
64
+ * [🐳 VPS Guide (Recommended)](#-vps-guide-recommended)
65
 
66
+ * [πŸ“Ί Setting Up Stremio](#-setting-up-stremio)
 
 
 
 
 
 
 
 
67
 
68
+ * [🌐 Add the Addon](#-step-3-add-the-addon)
69
+ * [βš™οΈ Optional: Remove Cinemeta](#️-optional-remove-cinemeta)
70
+
71
+ * [πŸ… Contributors](#-contributors)
72
+
73
+
74
+ # πŸš€ Introduction
75
+
76
+ This project is a **next-generation Telegram Stremio Media Server** that allows you to **stream your Telegram files directly through Stremio**, without any third-party dependencies or file expiration issues. It’s designed for **speed, scalability, and reliability**, making it ideal for both personal and community-based media hosting.
77
 
 
78
 
79
+ ## ✨ Key Features
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ - βš™οΈ **Multiple MongoDB Database Support**
82
+ - πŸ“‘ **Multiple Telegram Channel Support**
83
+ - ⚑ **Ultra-Fast Streaming Experience**
84
+ - πŸ”‘ **Multi-Token Load Balancer**
85
+ - 🎬 **IMDb & TMDb Metadata Integration**
86
+ - 🧩 **Seamless Split File Streaming Support**
87
+ - 🎞️ **Play Multi-Part Videos as a Single Stream**
88
+ - ♾️ **Permanent Streaming Links (No Expiration)**
89
+ - 🧠 **Powerful Admin Dashboard**
90
+ - πŸ’³ **Subscription & Premium Management**
91
+ - πŸ” **Advanced Access Control System**
92
+ - πŸ“š **Custom & Automatic Catalog Generation**
93
+ - πŸ–₯️ **Web-Based Configuration Panel**
94
+ - 🌐 **Built-in Addon Proxy Support**
95
+ - πŸ” **Global Search Across Selected Channels**
96
 
97
 
98
 
 
151
 
152
  ### πŸ” Quality Replacement Logic
153
 
154
+ > Works only when **Replace Mode** is enabled.
155
+
156
+ If a newly uploaded file has the same quality label (`720p`, `1080p`, `4K`, etc.) as an existing file, the bot automatically replaces the older entry with the new one.
157
 
158
+ **Example:** Uploading a new `Ghosted (2023) 720p` file will replace the existing `720p` version in the catalog.
 
 
159
 
160
+ This prevents duplicate quality entries and ensures only the latest version is available for streaming.
161
 
162
  ---
163
 
164
  ### πŸ†™ Updating CAMRip or Low-Quality Files
165
 
166
+ > Works only when **Replace Mode** is enabled.
167
+
168
  If you initially uploaded a **CAMRip or low-quality version**, you can easily replace it with a better one:
169
 
170
  1. Forward the **new, higher-quality file** (e.g., `1080p`, `WEB-DL`) to your **AUTH CHANNEL**.
 
177
 
178
  ### 🏷️ Fixing Incorrect Metadata (Manual Override)
179
 
180
+ If the addon identifies a movie or TV show incorrectly, or if metadata is missing altogether, you can easily correct it using one of the following methods:
181
+
182
+ #### Method 1: IMDb / TMDb URL Override
183
+
184
+ 1. Copy the correct **IMDb** or **TMDb** URL for the movie or TV show.
185
+ 2. Edit the message caption in your Telegram **AUTH CHANNEL** and paste the URL anywhere in the caption.
186
+ 3. The bot will automatically:
187
+
188
+ * Remove the existing metadata entry associated with that file.
189
+ * Re-scan the provided URL.
190
+ * Fetch and save the correct metadata.
191
+
192
+ #### Method 2: Scan Metadata from the Web Panel
193
 
194
+ 1. Open the media entry from the Movies or TV Shows section.
195
+ 2. Click **Edit**.
196
+ 3. Select **Scan Metadata**.
197
+ 4. Search for the correct title and choose the matching result.
198
+ 5. Apply the changes.
199
 
200
+ βœ… The addon will update the metadata instantly and refresh the catalog entry.
201
 
202
  ---
203
 
 
260
  πŸ’‘ **Tip:** Use `/log` if you encounter any upload or parsing issues.
261
 
262
 
263
+
264
  # πŸ”§ Configuration Guide
265
 
266
+ > πŸ’‘ You only need to edit `config.env` for startup credentials, database connection, and optional Userbot configuration. Everything else can be managed from the Web UI.
267
 
268
+ ---
269
 
270
+ ## 🧩 Startup Configuration
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
+ | Variable | Description |
273
+ | :------------------------ | :---------------------------------------------------------------------------------------------------------- |
274
+ | **`API_ID`** | Telegram API ID obtained from `my.telegram.org`. Required for all Telegram client connections. |
275
+ | **`API_HASH`** | Telegram API Hash obtained from `my.telegram.org`. Required for Telegram authentication. |
276
+ | **`BOT_TOKEN`** | Main bot token generated via `@BotFather`. Used for streaming, indexing, and user interactions. |
277
+ | **`OWNER_ID`** | Your Telegram User ID. Grants full administrative access to the system. |
278
+ | **`DATABASE`** | MongoDB connection URI(s). Used to store metadata, settings, catalogs, subscriptions, and application data. |
279
+ | **`PORT`** | Port on which the FastAPI server runs. Default: `8000`. |
280
+ | **`USER_SESSION_STRING`** | Optional Userbot session string. Required only for Global Search functionality. |
281
 
282
+ ---
283
 
284
+ # βš™οΈ Web Panel Configuration
 
 
285
 
286
+ The following settings are automatically loaded from the database and can be managed through the Web Admin Panel.
287
 
288
+ ## πŸ“š Media & Catalog Settings
 
 
 
289
 
290
+ | Variable | Description |
291
+ | :--------------------------- | :------------------------------------------------------------------------------------------------------------- |
292
+ | **`REPLACE_MODE`** | When enabled, newly uploaded files replace existing files with the same quality label (`720p`, `1080p`, etc.). |
293
+ | **`HIDE_CATALOG`** | Hides the default Telegram Stremio catalog and shows streams only through Cinemata integration. |
294
+ | **`AUTH_CHANNEL`** | Telegram channel IDs used for media indexing and streaming. Multiple channels are supported. |
295
+ | **`TMDB_API`** | TMDb API key used to fetch movie and TV show metadata automatically. |
296
+ | **`GLOBAL_SEARCH`** | Enables searching media across configured Global Search channels. Requires a valid `USER_SESSION_STRING`. |
297
+ | **`GLOBAL_SEARCH_CHANNELS`** | List of channel IDs included in Global Search. Searches are restricted to these channels only. |
298
 
299
+ ---
 
 
 
300
 
301
+ ## 🌐 Proxy Settings
302
 
303
+ | Variable | Description |
304
+ | :---------------------------------- | :---------------------------------------------------------------------- |
305
+ | **`HTTP_PROXY_URL`** | Optional HTTP proxy used for metadata requests and external API access. |
306
+ | **`SHOW_PROXY_AND_NON_PROXY_BOTH`** | Shows both proxied and direct stream links simultaneously. |
 
307
 
308
+ ---
309
 
310
+ ## πŸ’³ Subscription System
311
 
312
+ | Variable | Description |
313
+ | :-------------------------- | :------------------------------------------------------------------------- |
314
+ | **`SUBSCRIPTION`** | Enables subscription-based access control for streams. |
315
+ | **`SUBSCRIPTION_GROUP_ID`** | Telegram group/channel where approved subscribers are invited. |
316
+ | **`APPROVER_IDS`** | Telegram user IDs allowed to approve or reject subscription requests. |
317
+ | **`SUBSCRIPTION_URL`** | Bot or payment URL displayed to users when their subscription has expired. |
318
 
319
+ ---
320
 
321
+ ## 🧠 Admin Panel
322
 
323
+ | Variable | Description |
324
+ | :------------------- | :----------------------------------------------------------------------------------------------- |
325
+ | **`ADMIN_USERNAME`** | Username used to access the Web Admin Panel. |
326
+ | **`ADMIN_PASSWORD`** | Password used to access the Web Admin Panel. Change the default values immediately for security. |
327
+
328
+ ---
329
+
330
+ ## πŸ”„ Update Settings
331
+
332
+ | Variable | Description |
333
+ | :-------------------- | :-------------------------------------------- |
334
+ | **`UPSTREAM_REPO`** | Git repository URL used by the update system. |
335
+ | **`UPSTREAM_BRANCH`** | Branch that the updater should track. |
336
+
337
+ ---
338
+
339
+ ## πŸ—„οΈ Multi-Database Support
340
+
341
+ | Variable | Description |
342
+ | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
343
+ | **`EXTRA_DATABASES`** | Additional MongoDB databases used for load balancing, scalability, and redundancy. Can be added or removed directly from the Web Panel. |
344
+
345
+ ---
346
+
347
+ ## πŸ”‘ Multi-Token System
348
+
349
+ | Variable | Description |
350
+ | :----------------- | :----------------------------------------------------------------------------------------- |
351
+ | **`MULTI_TOKENS`** | Additional bot tokens used to distribute download traffic and reduce Telegram rate limits. |
352
+
353
+ ### About Multi-Token Support
354
+
355
+ If your addon handles a large number of concurrent streams or downloads, Telegram may rate-limit a single bot.
356
+
357
+ To avoid this:
358
+
359
+ 1. Create multiple bots using `@BotFather`.
360
+ 2. Add each bot as an admin in all AUTH CHANNELS.
361
+ 3. Add their tokens in the **Multi Token** section of the Web Panel.
362
+ 4. The system automatically distributes traffic across all available bots.
363
+
364
+ ---
365
 
366
+ ## πŸ” Global Search Requirements
367
 
368
+ Global Search requires a valid Userbot session.
 
369
 
370
+ * Configure `USER_SESSION_STRING` in `config.env`.
371
+ * Enable **Global Search** from the Web Panel.
372
+ * Add one or more **Global Search Channels**.
373
+ * Searches will only be performed within the configured Global Search channels.
374
 
375
+ > ⚠️ If `USER_SESSION_STRING` is not configured, Global Search cannot be enabled.
 
 
 
 
376
 
377
 
378
  ---
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "Telegram-Stremio"
3
- version = "3.2.0"
4
  description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
5
  readme = "README.md"
6
  requires-python = ">=3.11"
 
1
  [project]
2
  name = "Telegram-Stremio"
3
+ version = "3.3.0"
4
  description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
5
  readme = "README.md"
6
  requires-python = ">=3.11"
sample_config.env CHANGED
@@ -2,11 +2,11 @@
2
  API_ID=""
3
  API_HASH=""
4
  BOT_TOKEN=""
5
- HELPER_BOT_TOKEN=""
6
  OWNER_ID=""
7
 
8
  # Database (required β€” comma-separated URIs, exactly 2: tracking, storage_1)
9
  DATABASE=""
10
 
11
  # Server (required)
12
- PORT="8000"
 
2
  API_ID=""
3
  API_HASH=""
4
  BOT_TOKEN=""
5
+ USER_SESSION_STRING=""
6
  OWNER_ID=""
7
 
8
  # Database (required β€” comma-separated URIs, exactly 2: tracking, storage_1)
9
  DATABASE=""
10
 
11
  # Server (required)
12
+ PORT="8000"