Karan Adhikari commited on
# π 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 +1 -1
- Backend/__main__.py +9 -5
- Backend/config.py +1 -1
- Backend/fastapi/routes/api_routes.py +15 -1
- Backend/fastapi/routes/stream_routes.py +101 -1
- Backend/fastapi/routes/stremio_routes.py +97 -38
- Backend/fastapi/routes/template_routes.py +17 -8
- Backend/fastapi/templates/settings.html +110 -0
- Backend/helper/global_search.py +309 -0
- Backend/helper/settings_manager.py +28 -0
- Backend/helper/task_manager.py +118 -17
- Backend/pyrofork/bot.py +21 -11
- README.md +177 -138
- pyproject.toml +1 -1
- sample_config.env +2 -2
Backend/__init__.py
CHANGED
|
@@ -11,4 +11,4 @@ StartTime = time()
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
-
__version__ = "3.
|
|
|
|
| 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
|
| 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 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
| 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 |
-
|
| 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 |
-
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
-
|
| 435 |
-
|
| 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 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
"
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from Backend.logger import LOGGER
|
| 4 |
-
from Backend.pyrofork.bot import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
async def edit_message(chat_id: int, msg_id: int, new_caption: str):
|
| 7 |
try:
|
| 8 |
-
await
|
| 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}
|
| 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 |
-
|
|
|
|
|
|
|
| 21 |
try:
|
| 22 |
-
await
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
await sleep(e.value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
except Exception as e:
|
| 32 |
-
LOGGER.error(f"
|
|
|
|
|
|
| 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 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 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 |
-
|
| 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 |
-
|
| 64 |
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
|
|
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
|
| 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 |
-
|
| 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 |
-
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
-
|
| 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
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
1.
|
| 182 |
-
2.
|
| 183 |
-
3.
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
β
The
|
| 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 |
-
|
| 251 |
|
| 252 |
-
|
| 253 |
|
| 254 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
|
| 276 |
|
| 277 |
-
|
| 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 |
-
|
| 282 |
|
| 283 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
|
| 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 |
-
##
|
| 296 |
|
| 297 |
-
| Variable
|
| 298 |
-
| :--- | :--- |
|
| 299 |
-
| **`
|
| 300 |
-
| **`
|
| 301 |
-
**β οΈ Change from default values for security.**
|
| 302 |
|
| 303 |
-
|
| 304 |
|
| 305 |
-
|
| 306 |
|
| 307 |
-
| Variable
|
| 308 |
-
| :--- | :--- |
|
| 309 |
-
| **`SUBSCRIPTION`**
|
| 310 |
-
| **`SUBSCRIPTION_GROUP_ID`** | Telegram
|
| 311 |
-
| **`APPROVER_IDS`**
|
| 312 |
-
| **`SUBSCRIPTION_URL`**
|
| 313 |
|
| 314 |
-
|
| 315 |
|
| 316 |
-
##
|
| 317 |
|
| 318 |
-
| Variable
|
| 319 |
-
| :--- | :--- |
|
| 320 |
-
| **`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
-
##
|
| 323 |
|
| 324 |
-
|
| 325 |
-
To avoid this, you can use **MULTI_TOKEN** system:
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
|
| 332 |
-
> β οΈ
|
| 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.
|
| 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 |
-
|
| 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"
|