diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..ee889666ef01553b9e643877900de8289c38171f --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +assets/ diff --git a/Backend/__init__.py b/Backend/__init__.py index 8251658a2f689172626ffd4b5cd17879bed68ce4..45cdb621fbf4958b00d7ed52c06f29a901378d70 100644 --- a/Backend/__init__.py +++ b/Backend/__init__.py @@ -1,14 +1,17 @@ -from Backend.helper.database import Database -from time import time from datetime import datetime +from time import time + import pytz +from Backend.helper.database import Database + +#----- Shared application state timezone = pytz.timezone("Asia/Kolkata") now = datetime.now(timezone) StartTime = time() - USE_DEFAULT_ID: str = None -db = Database() +MANUAL_SESSION: dict = None +db = Database() -__version__ = "3.4.0" +__version__ = "5.3.5" diff --git a/Backend/__main__.py b/Backend/__main__.py index 955342b333b122ec933b6c1f70f9797fb5e9f9a5..310229909f421d8d1b61bc6557b0e62105e52832 100644 --- a/Backend/__main__.py +++ b/Backend/__main__.py @@ -1,91 +1,99 @@ -from asyncio import get_event_loop, sleep as asleep import asyncio import logging +import secrets from traceback import format_exc + from pyrogram import idle +from starlette.middleware.sessions import SessionMiddleware + from Backend import __version__, db -from Backend.helper.pinger import ping -from Backend.logger import LOGGER from Backend.fastapi import server -from Backend.helper.settings_manager import SettingsManager -from Backend.helper.pyro import restart_notification, setup_bot_commands -from Backend.pyrofork.bot import Userbot, StreamBot -from Backend.pyrofork.clients import initialize_clients +from Backend.fastapi.main import app from Backend.helper import subscription_task_manager -from Backend.helper.scan_manager import scan_manager, dbcheck_manager from Backend.helper.link_checker import DeadLinkChecker -from Backend.fastapi.main import app -from Backend.helper.auto_catalog import ( - start_auto_catalog_sync_background, start_auto_catalog_interval_loop -) +from Backend.helper.own_bots import reload_helpers, sweep_copies, warm_pools +from Backend.helper.pinger import ping +from Backend.helper.pyro import restart_notification, setup_bot_commands +from Backend.helper.scan_manager import dbcheck_manager, duplicate_manager, scan_manager +from Backend.helper.session_auth import get_active_session_string +from Backend.helper.settings_manager import SettingsManager +from Backend.logger import LOGGER +import Backend.pyrofork.bot as botmod +from Backend.pyrofork.bot import StreamBot +from Backend.pyrofork.clients import initialize_clients +loop = asyncio.get_event_loop() -loop = get_event_loop() +#----- Boot every subsystem then idle the bot async def start_services(): try: LOGGER.info(f"Initializing Telegram-Stremio v-{__version__}") - await asleep(1.2) - + await asyncio.sleep(1.2) + await db.connect() - await asleep(1.2) + await asyncio.sleep(1.2) await SettingsManager.initialize(db) - await asleep(0.5) - - try: - await scan_manager.load(db) - dbcheck_manager.bind_db(db) - except Exception as e: - LOGGER.error(f"Failed to restore scan manager state on startup: {e}") - await asleep(0.3) - - try: - await db.reload_extra_databases(SettingsManager.current().extra_databases) - except Exception as e: - LOGGER.error(f"Failed to reconnect extra storage databases on startup: {e}") - await asleep(0.5) + app.add_middleware(SessionMiddleware, secret_key=SettingsManager.current().session_secret or secrets.token_hex(32)) + await asyncio.sleep(0.5) + + await scan_manager.load(db) + dbcheck_manager.bind_db(db) + duplicate_manager.bind_db(db) + await asyncio.sleep(0.3) + + await db.reload_extra_databases(SettingsManager.current().extra_databases) + await asyncio.sleep(0.5) await StreamBot.start() StreamBot.username = StreamBot.me.username LOGGER.info(f"Bot Client : [@{StreamBot.username}]") - await asleep(1.2) - - if Userbot is not None: - await Userbot.start() - Userbot.username = Userbot.me.username - LOGGER.info(f"Userbot Client : [@{Userbot.username}] (Global Search / fallback enabled)") + await asyncio.sleep(1.2) + + if botmod.Userbot is None: + stored_session = await get_active_session_string() + if stored_session: + botmod.build_userbot(stored_session) + LOGGER.info("Loaded Userbot session from encrypted storage.") + + if botmod.Userbot is not None: + await botmod.Userbot.start() + botmod.Userbot.username = botmod.Userbot.me.username + LOGGER.info(f"Userbot Client : [@{botmod.Userbot.username}]") else: - LOGGER.info("Userbot not configured (USER_SESSION_STRING empty) — running with StreamBot only.") - await asleep(1.2) + LOGGER.info("Userbot not configured — running with StreamBot only.") + await asyncio.sleep(1.2) LOGGER.info("Initializing Multi Clients...") await initialize_clients() - await asleep(2) - + from Backend.fastapi.routes.stream_routes import warm_streamers + warm_streamers() + LOGGER.info(f"Helper bots: {await reload_helpers()} active") + loop.create_task(sweep_copies()) + loop.create_task(warm_pools()) + await asyncio.sleep(2) + await setup_bot_commands(StreamBot) - await asleep(2) + await asyncio.sleep(2) LOGGER.info('Initializing Telegram-Stremio Web Server...') await restart_notification() loop.create_task(server.serve()) loop.create_task(ping()) - + link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24) loop.create_task(link_checker_task.start()) - - loop.create_task(start_auto_catalog_sync_background(db, delay_seconds=20, full_rebuild=False)) - - loop.create_task(start_auto_catalog_interval_loop(db)) - await subscription_task_manager.sync(StreamBot) - + LOGGER.info("Telegram-Stremio Started Successfully!") await idle() except Exception: LOGGER.error("Error during startup:\n" + format_exc()) + +#----- Cancel pending tasks and shut clients down async def stop_services(): try: LOGGER.info("Stopping services...") @@ -93,19 +101,18 @@ async def stop_services(): pending_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] for task in pending_tasks: task.cancel() - await asyncio.gather(*pending_tasks, return_exceptions=True) await StreamBot.stop() - if Userbot is not None: - await Userbot.stop() + if botmod.Userbot is not None: + await botmod.Userbot.stop() await db.disconnect() - LOGGER.info("Services stopped successfully.") except Exception: LOGGER.error("Error during shutdown:\n" + format_exc()) + if __name__ == '__main__': try: loop.run_until_complete(start_services()) @@ -116,4 +123,4 @@ if __name__ == '__main__': finally: loop.run_until_complete(stop_services()) loop.stop() - logging.shutdown() + logging.shutdown() diff --git a/Backend/config.py b/Backend/config.py index 21eb507a40fea62e28ad093e55a8214d2f68c129..2a16663efef23d25f48c4a9ebe94a054af142063 100644 --- a/Backend/config.py +++ b/Backend/config.py @@ -1,38 +1,48 @@ from os import getenv, path + from dotenv import load_dotenv load_dotenv(path.join(path.dirname(path.dirname(__file__)), "config.env")) +def _int_env(key: str, default: int = 0) -> int: + try: + return int((getenv(key) or "").strip()) + except ValueError: + return default + + +#----- Environment-backed configuration class Telegram: - # ── Required: Telegram clients ─────────────────────────────────────────── - API_ID = int(getenv("API_ID", "0")) - API_HASH = getenv("API_HASH", "") - BOT_TOKEN = getenv("BOT_TOKEN", "") - USER_SESSION_STRING = getenv("USER_SESSION_STRING", "") + #----- Required: Telegram clients + API_ID = _int_env("API_ID") + API_HASH = getenv("API_HASH", "") + BOT_TOKEN = getenv("BOT_TOKEN", "") - # ── Required: Database URIs ─────────────────────────────────────────────── + #----- Required: Database URIs DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()] - # ── Required: Server ───────────────────────────────────────────────────── - PORT = int(getenv("PORT", "8000")) - OWNER_ID = int(getenv("OWNER_ID", "0")) - - # ── Legacy migration fallbacks ──────────────────────────────────────────── - # These are READ ONCE by SettingsManager._seed_from_env() on first startup - # and then stored in the database. Do NOT reference them elsewhere in the - # codebase — use SettingsManager.current(). instead. - REPLACE_MODE = getenv("REPLACE_MODE", "true").lower() == "true" - HIDE_CATALOG = getenv("HIDE_CATALOG", "false").lower() == "true" - AUTH_CHANNEL = [c.strip() for c in (getenv("AUTH_CHANNEL") or "").split(",") if c.strip()] - TMDB_API = getenv("TMDB_API", "") - BASE_URL = getenv("BASE_URL", "").rstrip("/") - UPSTREAM_REPO = getenv("UPSTREAM_REPO", "") - UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "") - ADMIN_USERNAME = getenv("ADMIN_USERNAME", "admin") - ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin") - SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true" - SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0")) - APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()] - HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "") + #----- Required: Server + PORT = _int_env("PORT", 8000) + OWNER_ID = _int_env("OWNER_ID") + + #----- Read/Write via SettingsManager + REPLACE_MODE = getenv("REPLACE_MODE", "true").lower() == "true" + HIDE_CATALOG = getenv("HIDE_CATALOG", "false").lower() == "true" + AUTH_CHANNEL = [c.strip() for c in (getenv("AUTH_CHANNEL") or "").split(",") if c.strip()] + TMDB_API = getenv("TMDB_API", "") + TVDB_API = getenv("TVDB_API", "") + BASE_URL = getenv("BASE_URL", "").rstrip("/") + UPSTREAM_REPO = getenv("UPSTREAM_REPO", "") + UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "") + ADMIN_USERNAME = getenv("ADMIN_USERNAME", "admin") + ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin") + SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true" + SUBSCRIPTION_GROUP_ID = _int_env("SUBSCRIPTION_GROUP_ID") + APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()] + HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "") SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true" + + #----- WebDAV (optional env fallback; prefer Settings page) + WEBDAV_USER = getenv("WEBDAV_USER", "") + WEBDAV_PASSWORD = getenv("WEBDAV_PASSWORD", "") diff --git a/Backend/fastapi/__init__.py b/Backend/fastapi/__init__.py index 24566f8f53243e90465d505bfd86a7f313b26843..0f77408f6911995151d1cc0d26f164042bfda59c 100644 --- a/Backend/fastapi/__init__.py +++ b/Backend/fastapi/__init__.py @@ -1,8 +1,9 @@ import uvicorn + from Backend.config import Telegram from Backend.fastapi.main import app - +#----- Uvicorn server bound to the FastAPI app Port = Telegram.PORT config = uvicorn.Config( app=app, @@ -10,7 +11,7 @@ config = uvicorn.Config( port=Port, loop="uvloop", http="httptools", - timeout_keep_alive=30, + timeout_keep_alive=60, timeout_graceful_shutdown=5, ) server = uvicorn.Server(config) diff --git a/Backend/fastapi/main.py b/Backend/fastapi/main.py index df13f83ea98ec22a7dc736f4e92c063e7f56ea8f..9ae7925ca088cc7abffb2e71d1862148b1692fe1 100644 --- a/Backend/fastapi/main.py +++ b/Backend/fastapi/main.py @@ -1,41 +1,145 @@ -from fastapi import FastAPI, Request, Form, Depends, Query -from fastapi.responses import HTMLResponse, RedirectResponse +import asyncio + +from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response from fastapi.staticfiles import StaticFiles -from starlette.middleware.sessions import SessionMiddleware from fastapi.templating import Jinja2Templates + from Backend import __version__ -from Backend.fastapi.security.credentials import require_auth -from Backend.fastapi.routes.stream_routes import router as stream_router, decay_client_failures +from Backend.fastapi.themes import get_theme, theme_key +from Backend.fastapi.routes.api_routes import ( + add_custom_catalog_item_api, + add_subscription_plan_api, + apply_media_rescan_api, + assign_plan_api, + auto_catalog_sync_status_api, + auto_sync_custom_catalogs_api, + cancel_dbcheck_api, + cancel_duplicate_check_api, + cancel_scan_api, + clear_cache_api, + clear_stream_analytics_api, + create_custom_catalog_api, + create_token_api, + grant_lifetime_api, + set_token_lifetime_api, + set_token_expiry_api, + subscription_preflight_api, + backfill_subscriber_names_api, + dbcheck_status_api, + duplicate_check_status_api, + delete_custom_catalog_api, + delete_media_api, + delete_movie_quality_api, + delete_request_api, + delete_subscription_plan_api, + export_config_api, + import_config_api, + delete_tv_episode_api, + delete_tv_quality_api, + delete_tv_season_api, + download_logs_api, + get_admin_stats_api, + get_db_stats_api, + get_all_subscribers_api, + get_all_tokens_api, + get_auto_catalog_settings_api, + get_catalog_order_api, + update_catalog_order_api, + get_user_activity_api, + session_send_code_api, + session_verify_code_api, + session_verify_password_api, + session_status_api, + session_disconnect_api, + session_reconnect_api, + session_remove_api, + get_custom_catalog_items_api, + get_dead_links_api, + get_media_visibility_api, + get_requests_api, + request_popular_api, + request_search_api, + request_submit_api, + get_stream_analytics_api, + get_subscription_plans_api, + get_settings_api, + get_logs_api, + get_manual_session_api, + get_system_stats_api, + get_tools_channels_api, + bot_admin_scan_api, + bot_admin_apply_api, + bot_admin_apply_status_api, + clear_manual_session_api, + search_manual_session_api, + set_manual_session_api, + health_api, + health_report_api, + version_status_api, + setup_status_api, + link_token_user_api, + list_custom_catalogs_api, + list_media_api, + manage_subscriber_api, + manual_add_media_api, + list_manual_add_catalogs_api, + resolve_manual_metadata_api, + purge_dead_links_api, + purge_duplicates_api, + remove_custom_catalog_item_api, + resolve_telegram_api, + resolve_subtitle_api, + list_subtitle_languages_api, + list_subtitles_api, + add_subtitles_api, + remove_subtitle_api, + restart_app_api, + revoke_token_api, + scan_status_api, + search_catalog_media_api, + set_media_visibility_api, + search_media_rescan_api, + tag_media_api, + speed_test_api, + speed_test_stream_api, + start_dbcheck_api, + start_duplicate_check_api, + start_scan_api, + update_auto_catalog_settings_api, + update_custom_catalog_api, + update_media_api, + update_request_api, + update_settings_api, + update_subscription_plan_api, + update_token_cf_api, + update_token_limits_api, +) +from Backend.fastapi.routes.stream_routes import decay_client_failures +from Backend.fastapi.routes.stream_routes import router as stream_router +from Backend.fastapi.routes.cf_routes import router as cf_router from Backend.fastapi.routes.stremio_routes import router as stremio_router +from Backend.fastapi.routes.webdav_routes import router as webdav_router from Backend.fastapi.routes.template_routes import ( - login_page, login_post, logout, set_theme, dashboard_page, - media_management_page, edit_media_page, public_status_page, stremio_guide_page, - admin_dashboard_page, admin_subscriptions_page, admin_access_page, - custom_catalogs_page, settings_page, tools_page -) -from Backend.fastapi.routes.api_routes import ( - list_media_api, delete_media_api, update_media_api, - delete_movie_quality_api, delete_tv_quality_api, - delete_tv_episode_api, delete_tv_season_api, - create_token_api, revoke_token_api, update_token_limits_api, - speed_test_api, speed_test_stream_api, - get_admin_stats_api, clear_cache_api, get_dead_links_api, - get_stream_analytics_api, clear_stream_analytics_api, - get_subscription_plans_api, add_subscription_plan_api, - update_subscription_plan_api, delete_subscription_plan_api, - get_all_subscribers_api, manage_subscriber_api, - get_all_tokens_api, assign_plan_api, link_token_user_api, - search_media_rescan_api, apply_media_rescan_api, - list_custom_catalogs_api, create_custom_catalog_api, update_custom_catalog_api, - delete_custom_catalog_api, get_custom_catalog_items_api, search_catalog_media_api, - add_custom_catalog_item_api, remove_custom_catalog_item_api, - auto_sync_custom_catalogs_api, auto_catalog_sync_status_api, - get_auto_catalog_settings_api, update_auto_catalog_settings_api, - get_settings_api, update_settings_api, - get_tools_channels_api, start_scan_api, cancel_scan_api, scan_status_api, - start_dbcheck_api, cancel_dbcheck_api, dbcheck_status_api, purge_dead_links_api + admin_access_page, + admin_dashboard_page, + admin_requests_page, + admin_subscriptions_page, + public_request_page, + custom_catalogs_page, + dashboard_page, + edit_media_page, + login_page, + login_post, + logout, + media_management_page, + settings_page, + set_theme, + tools_page, ) +from Backend.fastapi.security.credentials import require_auth +from Backend.pyrofork.bot import work_loads_summary templates = Jinja2Templates(directory="Backend/fastapi/templates") @@ -45,8 +149,7 @@ app = FastAPI( version=__version__ ) -# --- Middleware Setup --- -app.add_middleware(SessionMiddleware, secret_key="f6d2e3b9a0f43d9a2e6a56b2d3175cd9c05bbfe31d95ed2a7306b57cb1a8b6f0") +#----- Middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -60,16 +163,22 @@ try: except Exception: pass + @app.on_event("startup") async def _startup(): - import asyncio asyncio.create_task(decay_client_failures()) + from Backend.helper.version_check import version_check_loop + asyncio.create_task(version_check_loop()) -# --- Include existing API routers --- + +#----- Streaming and Stremio routers app.include_router(stream_router) +app.include_router(cf_router) app.include_router(stremio_router) +app.include_router(webdav_router) + -# --- Public Routes (No Authentication Required) --- +#----- Public routes (no authentication) @app.get("/login", response_class=HTMLResponse) async def login_get(request: Request): return await login_page(request) @@ -83,18 +192,99 @@ async def logout_route(request: Request): return await logout(request) @app.post("/set-theme") -async def set_theme_route(request: Request, theme: str = Form(...)): +async def set_theme_route(request: Request, theme: str = Form(None)): return await set_theme(request, theme) -@app.get("/status", response_class=HTMLResponse) -async def public_status(request: Request): - return await public_status_page(request) - -@app.get("/stremio", response_class=HTMLResponse) -async def stremio_guide(request: Request): - return await stremio_guide_page(request) - -# --- Protected Routes (Authentication Required) --- +@app.get("/manifest.webmanifest") +async def pwa_manifest(request: Request): + theme = get_theme(theme_key(request)) + return JSONResponse( + { + "name": "Telegram Stremio", + "short_name": "TG Stremio", + "description": "Telegram Stremio media management", + "start_url": "/", + "scope": "/", + "display": "standalone", + "orientation": "any", + "background_color": theme["colors"]["background"], + "theme_color": theme["colors"]["primary"], + "icons": [ + { + "src": "/pwa-icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any" + }, + { + "src": "/pwa-icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "maskable" + } + ] + }, + media_type="application/manifest+json", + headers={"Cache-Control": "no-cache"} + ) + +@app.get("/pwa-icon.svg") +async def pwa_icon(request: Request): + theme = get_theme(theme_key(request)) + primary = theme["colors"]["primary"] + svg = ( + f'' + f'' + f'' + f'' + ) + return Response( + content=svg, + media_type="image/svg+xml", + headers={"Cache-Control": "no-cache"} + ) + +@app.get("/sw.js") +async def service_worker(): + js = ( + "self.addEventListener('install',e=>self.skipWaiting());" + "self.addEventListener('activate',e=>e.waitUntil(clients.claim()));" + "self.addEventListener('fetch',e=>e.respondWith(fetch(e.request).catch(()=>caches.match(e.request))));" + ) + return Response( + content=js, + media_type="application/javascript", + headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"} + ) + +@app.get("/status") +async def public_status(): + return {"status": "ok", "version": __version__} + +@app.get("/open/{app_name}/{media_type}/{content_id}", response_class=HTMLResponse) +async def open_in_app(app_name: str, media_type: str, content_id: str): + stremio_type = "series" if media_type in ("series", "tv") else "movie" + web = f"https://web.stremio.com/#/detail/{stremio_type}/{content_id}/{content_id}" + schemes = { + "nuvio": f"nuvio://meta?type={stremio_type}&id={content_id}", + "stremio": f"stremio:///detail/{stremio_type}/{content_id}", + } + scheme = schemes.get(app_name, schemes["stremio"]) + label = "Nuvio" if app_name == "nuvio" else "Stremio" + html = f""" + +Opening {label}… + +

Opening in {label}…

+

If nothing happens, use the buttons below.

+Open {label}
+Open Stremio Web
+ +""" + return HTMLResponse(html) + + +#----- Protected routes (authentication required) @app.get("/", response_class=HTMLResponse) async def root(request: Request, _: bool = Depends(require_auth)): return await dashboard_page(request, _) @@ -104,9 +294,8 @@ async def admin_dashboard(request: Request, _: bool = Depends(require_auth)): return await admin_dashboard_page(request, _) @app.get("/media/manage", response_class=HTMLResponse) -async def media_management(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)): - return await media_management_page(request, media_type, _) - +async def media_management(request: Request, media_type: str = "movie", custom: bool = False, _: bool = Depends(require_auth)): + return await media_management_page(request, media_type, custom, _) @app.get("/catalogs", response_class=HTMLResponse) async def custom_catalogs(request: Request, _: bool = Depends(require_auth)): @@ -122,9 +311,10 @@ async def list_media( page: int = Query(1, ge=1), page_size: int = Query(24, ge=1, le=100), search: str = Query("", max_length=100), + custom: bool = Query(False), _: bool = Depends(require_auth) ): - return await list_media_api(media_type, page, page_size, search) + return await list_media_api(media_type, page, page_size, search, custom) @app.delete("/api/media/delete") async def delete_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)): @@ -153,16 +343,8 @@ async def delete_tv_season(tmdb_id: int, db_index: int, season: int, _: bool = D @app.get("/api/system/workloads") async def get_workloads(_: bool = Depends(require_auth)): try: - from Backend.pyrofork.bot import work_loads - return { - "loads": { - f"bot{c + 1}": l - for c, (_, l) in enumerate( - sorted(work_loads.items(), key=lambda x: x[1], reverse=True) - ) - } if work_loads else {} - } - except Exception as e: + return {"loads": work_loads_summary()} + except Exception: return {"loads": {}} @app.post("/api/tokens") @@ -173,13 +355,16 @@ async def create_token(payload: dict, _: bool = Depends(require_auth)): async def update_token(token: str, payload: dict, _: bool = Depends(require_auth)): return await update_token_limits_api(token, payload) +@app.put("/api/tokens/{token}/cf") +async def update_token_cf(token: str, payload: dict, _: bool = Depends(require_auth)): + return await update_token_cf_api(token, payload) + @app.delete("/api/tokens/{token}") async def revoke_token(token: str, _: bool = Depends(require_auth)): return await revoke_token_api(token) @app.get("/api/system/stats") async def get_system_stats(_: bool = Depends(require_auth)): - from Backend.fastapi.routes.api_routes import get_system_stats_api return await get_system_stats_api() @app.get("/api/admin/system-stats") @@ -198,6 +383,10 @@ async def get_dead_links(_: bool = Depends(require_auth)): async def get_stream_analytics(_: bool = Depends(require_auth)): return await get_stream_analytics_api() +@app.get("/api/admin/user-activity") +async def get_user_activity(page: int = 1, per_page: int = 5, _: bool = Depends(require_auth)): + return await get_user_activity_api(page, per_page) + @app.post("/api/admin/clear-analytics") async def clear_analytics(_: bool = Depends(require_auth)): return await clear_stream_analytics_api() @@ -230,7 +419,8 @@ async def get_subscribers(_: bool = Depends(require_auth)): async def manage_subscriber(user_id: int, payload: dict, _: bool = Depends(require_auth)): return await manage_subscriber_api(user_id, payload) -# --- Access Management --- + +#----- Access management @app.get("/admin/access", response_class=HTMLResponse) async def admin_access(request: Request, _: bool = Depends(require_auth)): return await admin_access_page(request, _) @@ -241,8 +431,7 @@ async def get_access_tokens(_: bool = Depends(require_auth)): @app.delete("/api/admin/access/tokens/{token}") async def delete_access_token(token: str, _: bool = Depends(require_auth)): - from Backend.fastapi.routes.api_routes import revoke_token_api as _revoke_token_api - return await _revoke_token_api(token) + return await revoke_token_api(token) @app.post("/api/admin/access/users/{user_id}/assign-plan") async def assign_access_plan(user_id: int, payload: dict, _: bool = Depends(require_auth)): @@ -253,10 +442,66 @@ async def assign_access_plan(user_id: int, payload: dict, _: bool = Depends(requ async def link_token_to_user(token: str, payload: dict, _: bool = Depends(require_auth)): user_id = int(payload.get("user_id", 0)) if not user_id: - from fastapi import HTTPException raise HTTPException(status_code=400, detail="user_id is required.") return await link_token_user_api(token, user_id) +@app.patch("/api/admin/access/tokens/{token}/lifetime") +async def set_token_lifetime(token: str, payload: dict, _: bool = Depends(require_auth)): + return await set_token_lifetime_api(token, payload) + +@app.post("/api/admin/access/tokens/{token}/expiry") +async def set_token_expiry(token: str, payload: dict, _: bool = Depends(require_auth)): + return await set_token_expiry_api(token, payload) + +@app.post("/api/admin/access/grant-lifetime") +async def grant_lifetime(_: bool = Depends(require_auth)): + return await grant_lifetime_api() + +@app.get("/api/admin/subscriptions/preflight") +async def subscription_preflight(_: bool = Depends(require_auth)): + return await subscription_preflight_api() + +@app.post("/api/admin/subscriptions/backfill-names") +async def backfill_subscriber_names(_: bool = Depends(require_auth)): + return await backfill_subscriber_names_api() + + +#----- Public content request page (no auth) +@app.get("/request", response_class=HTMLResponse) +async def public_request(request: Request): + return await public_request_page(request) + +@app.get("/api/request/search") +async def request_search(q: str = Query("")): + return await request_search_api(q) + +@app.get("/api/request/popular") +async def request_popular(): + return await request_popular_api() + +@app.post("/api/request/submit") +async def request_submit(payload: dict, request: Request): + client_ip = request.client.host if request.client else None + return await request_submit_api(payload, client_ip) + + +#----- Admin content requests +@app.get("/admin/requests", response_class=HTMLResponse) +async def admin_requests(request: Request, _: bool = Depends(require_auth)): + return await admin_requests_page(request, _) + +@app.get("/api/admin/requests") +async def get_requests(_: bool = Depends(require_auth)): + return await get_requests_api() + +@app.patch("/api/admin/requests/{request_id}") +async def update_request(request_id: str, payload: dict, _: bool = Depends(require_auth)): + return await update_request_api(request_id, payload) + +@app.delete("/api/admin/requests/{request_id}") +async def delete_request_route(request_id: str, _: bool = Depends(require_auth)): + return await delete_request_api(request_id) + @app.get("/api/system/speedtest") async def speed_test( quality_id: str = Query(...), @@ -277,7 +522,6 @@ async def speed_test_stream( ): return await speed_test_stream_api(quality_id, tmdb_id, db_index, media_type) - @app.get("/api/media/rescan/search") async def search_media_rescan( media_type: str, @@ -287,7 +531,6 @@ async def search_media_rescan( ): return await search_media_rescan_api(media_type, query, year) - @app.post("/api/media/rescan/apply") async def apply_media_rescan( request: Request, @@ -298,8 +541,52 @@ async def apply_media_rescan( ): return await apply_media_rescan_api(request, tmdb_id, db_index, media_type) +@app.post("/api/media/tag") +async def tag_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)): + return await tag_media_api(tmdb_id, db_index, media_type) + + +#----- Manual add (custom movie/tv/season/episode/stream) +@app.post("/api/media/resolve-telegram") +async def resolve_telegram(payload: dict, _: bool = Depends(require_auth)): + return await resolve_telegram_api(payload) + +@app.post("/api/media/manual-add") +async def manual_add_media(payload: dict, _: bool = Depends(require_auth)): + return await manual_add_media_api(payload) + +@app.get("/api/media/manual-add/catalogs") +async def manual_add_catalogs(_: bool = Depends(require_auth)): + return await list_manual_add_catalogs_api() + +@app.get("/api/media/manual-add/resolve-meta") +async def manual_add_resolve_meta(media_type: str, selected_id: str, _: bool = Depends(require_auth)): + return await resolve_manual_metadata_api(media_type, selected_id) + + +#----- Manual subtitle management +@app.get("/api/media/subtitles/languages") +async def subtitle_languages(_: bool = Depends(require_auth)): + return list_subtitle_languages_api() + +@app.get("/api/media/subtitles") +async def list_subtitles(media_type: str, tmdb_id: int, db_index: int, _: bool = Depends(require_auth)): + return await list_subtitles_api(media_type, tmdb_id, db_index) + +@app.post("/api/media/subtitles/resolve") +async def resolve_subtitle(payload: dict, _: bool = Depends(require_auth)): + return await resolve_subtitle_api(payload) + +@app.post("/api/media/subtitles/add") +async def add_subtitles(payload: dict, _: bool = Depends(require_auth)): + return await add_subtitles_api(payload) + +@app.post("/api/media/subtitles/remove") +async def remove_subtitle_route(payload: dict, _: bool = Depends(require_auth)): + return await remove_subtitle_api(payload) -# --- Custom Catalog Management --- + +#----- Custom catalog management @app.get("/api/custom-catalogs") async def list_custom_catalogs( tmdb_id: int | None = None, @@ -321,6 +608,19 @@ async def update_custom_catalog(catalog_id: str, payload: dict, _: bool = Depend async def delete_custom_catalog(catalog_id: str, _: bool = Depends(require_auth)): return await delete_custom_catalog_api(catalog_id) +@app.post("/api/custom-catalogs/media-visibility") +async def set_media_visibility(payload: dict, _: bool = Depends(require_auth)): + return await set_media_visibility_api(payload) + +@app.get("/api/custom-catalogs/media-visibility") +async def get_media_visibility( + tmdb_id: int, + db_index: int, + media_type: str = Query("movie", regex="^(movie|tv|series)$"), + _: bool = Depends(require_auth) +): + return await get_media_visibility_api(tmdb_id, db_index, media_type) + @app.get("/api/custom-catalogs/search-media") async def search_catalog_media( query: str, @@ -331,18 +631,25 @@ async def search_catalog_media( ): return await search_catalog_media_api(query, media_type, page, page_size) - @app.post("/api/custom-catalogs/auto-sync") async def auto_sync_custom_catalogs( - full_rebuild: bool = Query(False), + force_refresh: bool = Query(False), _: bool = Depends(require_auth) ): - return await auto_sync_custom_catalogs_api(full_rebuild) + return await auto_sync_custom_catalogs_api(force_refresh) @app.get("/api/custom-catalogs/auto-sync/status") async def auto_catalog_sync_status(_: bool = Depends(require_auth)): return await auto_catalog_sync_status_api() +@app.get("/api/custom-catalogs-order") +async def get_catalog_order_route(_: bool = Depends(require_auth)): + return await get_catalog_order_api() + +@app.put("/api/custom-catalogs-order") +async def update_catalog_order_route(payload: dict, _: bool = Depends(require_auth)): + return await update_catalog_order_api(payload) + @app.get("/api/custom-catalogs/auto-sync/settings") async def get_auto_catalog_settings_route(_: bool = Depends(require_auth)): return await get_auto_catalog_settings_api() @@ -376,7 +683,7 @@ async def remove_custom_catalog_item( return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type) - +#----- Settings @app.get("/admin/settings", response_class=HTMLResponse) async def admin_settings(request: Request, _: bool = Depends(require_auth)): return await settings_page(request, _) @@ -389,7 +696,103 @@ async def get_settings(_: bool = Depends(require_auth)): async def update_settings(payload: dict, _: bool = Depends(require_auth)): return await update_settings_api(payload) -# --- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands) --- + +@app.post("/api/admin/settings/formatter-preview") +async def formatter_preview(payload: dict, _: bool = Depends(require_auth)): + from Backend.helper.stream_formatter import PRESETS, build_parse_value, render + tpl = PRESETS.get(payload.get("preset")) or {"name": str(payload.get("name") or ""), "description": str(payload.get("description") or "")} + pv = build_parse_value(str(payload.get("filename") or "video.mkv"), 2_500_000_000, channel="My Channel", + meta={"queryType": "movie", "type": "movie"}) + return {"name": render(tpl["name"], pv), "description": render(tpl["description"], pv)} + + +#----- Telegram user session login (replaces manual USER_SESSION_STRING) +@app.get("/api/admin/settings/session") +async def session_status(_: bool = Depends(require_auth)): + return await session_status_api() + +@app.post("/api/admin/settings/session/send-code") +async def session_send_code(payload: dict, _: bool = Depends(require_auth)): + return await session_send_code_api(payload) + +@app.post("/api/admin/settings/session/verify-code") +async def session_verify_code(payload: dict, _: bool = Depends(require_auth)): + return await session_verify_code_api(payload) + +@app.post("/api/admin/settings/session/verify-password") +async def session_verify_password(payload: dict, _: bool = Depends(require_auth)): + return await session_verify_password_api(payload) + +@app.post("/api/admin/settings/session/disconnect") +async def session_disconnect(_: bool = Depends(require_auth)): + return await session_disconnect_api() + +@app.post("/api/admin/settings/session/reconnect") +async def session_reconnect(_: bool = Depends(require_auth)): + return await session_reconnect_api() + +@app.delete("/api/admin/settings/session") +async def session_remove(_: bool = Depends(require_auth)): + return await session_remove_api() + + +#----- System & Maintenance (WebUI replacement for /stats, /log, /restart bot commands) +@app.get("/api/admin/stats") +async def admin_db_stats(_: bool = Depends(require_auth)): + return await get_db_stats_api() + +@app.get("/api/admin/health") +async def admin_health(_: bool = Depends(require_auth)): + return await health_api() + +@app.get("/api/admin/health/report") +async def admin_health_report(fresh: bool = Query(False), _: bool = Depends(require_auth)): + return await health_report_api(force=fresh) + +@app.get("/api/admin/version") +async def admin_version(force: bool = Query(False), _: bool = Depends(require_auth)): + return await version_status_api(force=force) + +@app.get("/api/admin/setup-status") +async def admin_setup_status(_: bool = Depends(require_auth)): + return await setup_status_api() + +@app.get("/api/admin/backup/export") +async def admin_backup_export(_: bool = Depends(require_auth)): + from fastapi.responses import JSONResponse + data = await export_config_api() + return JSONResponse( + content=data, + headers={"Content-Disposition": 'attachment; filename="telegram-stremio-backup.json"'}, + ) + +@app.get("/api/admin/backup/library") +async def admin_backup_library(_: bool = Depends(require_auth)): + from fastapi.responses import StreamingResponse + from Backend.helper.backup import export_library + return StreamingResponse( + export_library(), media_type="application/gzip", + headers={"Content-Disposition": 'attachment; filename="telestremio-catalog.json.gz"'}, + ) + +@app.post("/api/admin/backup/import") +async def admin_backup_import(payload: dict, _: bool = Depends(require_auth)): + return await import_config_api(payload) + +@app.get("/api/admin/logs") +async def admin_logs(lines: int = Query(300, ge=1, le=2000), _: bool = Depends(require_auth)): + return await get_logs_api(lines) + +@app.get("/api/admin/logs/download") +async def admin_logs_download(_: bool = Depends(require_auth)): + return await download_logs_api() + +@app.post("/api/admin/restart") +async def admin_restart(_: bool = Depends(require_auth)): + return await restart_app_api() + + +#----- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands) @app.get("/admin/tools", response_class=HTMLResponse) async def admin_tools(request: Request, _: bool = Depends(require_auth)): return await tools_page(request, _) @@ -398,6 +801,34 @@ async def admin_tools(request: Request, _: bool = Depends(require_auth)): async def tools_channels(_: bool = Depends(require_auth)): return await get_tools_channels_api() +@app.get("/api/admin/tools/bot-admin/scan") +async def tools_bot_admin_scan(_: bool = Depends(require_auth)): + return await bot_admin_scan_api() + +@app.post("/api/admin/tools/bot-admin/apply") +async def tools_bot_admin_apply(payload: dict, _: bool = Depends(require_auth)): + return await bot_admin_apply_api(payload) + +@app.get("/api/admin/tools/bot-admin/apply/status") +async def tools_bot_admin_apply_status(_: bool = Depends(require_auth)): + return await bot_admin_apply_status_api() + +@app.get("/api/admin/tools/manual-session") +async def tools_manual_session_get(_: bool = Depends(require_auth)): + return await get_manual_session_api() + +@app.get("/api/admin/tools/manual-session/search") +async def tools_manual_session_search(query: str = Query(""), _: bool = Depends(require_auth)): + return await search_manual_session_api(query) + +@app.post("/api/admin/tools/manual-session") +async def tools_manual_session_set(payload: dict, _: bool = Depends(require_auth)): + return await set_manual_session_api(payload) + +@app.delete("/api/admin/tools/manual-session") +async def tools_manual_session_clear(_: bool = Depends(require_auth)): + return await clear_manual_session_api() + @app.post("/api/admin/tools/scan/start") async def tools_scan_start(payload: dict, _: bool = Depends(require_auth)): return await start_scan_api(payload) @@ -426,6 +857,33 @@ async def tools_dbcheck_status(_: bool = Depends(require_auth)): async def tools_purge_dead_links(payload: dict | None = None, _: bool = Depends(require_auth)): return await purge_dead_links_api(payload) +@app.post("/api/admin/tools/duplicates/start") +async def tools_duplicates_start(_: bool = Depends(require_auth)): + return await start_duplicate_check_api() + +@app.post("/api/admin/tools/duplicates/cancel") +async def tools_duplicates_cancel(_: bool = Depends(require_auth)): + return await cancel_duplicate_check_api() + +@app.get("/api/admin/tools/duplicates/status") +async def tools_duplicates_status(_: bool = Depends(require_auth)): + return await duplicate_check_status_api() + +@app.post("/api/admin/tools/duplicates/purge") +async def tools_duplicates_purge(payload: dict | None = None, _: bool = Depends(require_auth)): + return await purge_duplicates_api(payload) + + @app.exception_handler(401) async def auth_exception_handler(request: Request, exc): + # API / stream / WebDAV clients must receive a real 401, not an HTML login redirect. + path = request.url.path or "" + if path.startswith(("/webdav", "/dl/", "/sub/", "/stremio/", "/api/", "/thumb/")): + from fastapi.responses import JSONResponse + detail = getattr(exc, "detail", "Unauthorized") + headers = {} + # Preserve WWW-Authenticate for WebDAV Basic auth prompts + if hasattr(exc, "headers") and exc.headers: + headers.update(exc.headers) + return JSONResponse(status_code=401, content={"detail": detail}, headers=headers) return RedirectResponse(url="/login", status_code=302) diff --git a/Backend/fastapi/routes/api_routes.py b/Backend/fastapi/routes/api_routes.py index 3c8c542d46e42a6d115ab7e8c3fe4364f5ac2bd9..e6d9542e7c5159d09a0b29fcf2f2c8ae42bb7997 100644 --- a/Backend/fastapi/routes/api_routes.py +++ b/Backend/fastapi/routes/api_routes.py @@ -1,40 +1,121 @@ import asyncio +import asyncio import json +import os +import random +import secrets +import shutil from datetime import datetime -from fastapi import Request, Query, HTTPException -from fastapi.responses import StreamingResponse -from Backend import db, StartTime, __version__ -from Backend.logger import LOGGER -from Backend.helper.settings_manager import SettingsManager -from Backend.helper.pyro import get_readable_time -from Backend.helper.metadata import ( - search_movie_candidates, - search_tv_candidates, - fetch_selected_movie_metadata, - fetch_selected_tv_metadata, -) -from Backend.pyrofork.bot import multi_clients, StreamBot -from Backend.helper.custom_dl import run_speed_test, _speed_test_single_client from time import time + +from fastapi import HTTPException, Query, Request +from fastapi.responses import FileResponse, StreamingResponse +from pyrogram.enums import ChatMemberStatus, ChatMembersFilter +from pyrogram.errors import FloodWait +from pyrogram.types import ChatPrivileges + +import Backend +from Backend import StartTime, __version__, db +from Backend.fastapi.routes.stream_routes import _streamer_by_client +from Backend.fastapi.routes.stremio_routes import invalidate_membership_cache +from Backend.helper.analytics import get_activity_overview from Backend.helper.auto_catalog import ( - start_auto_catalog_sync_background, - get_auto_catalog_sync_status, get_auto_catalog_settings, + get_auto_catalog_sync_status, + start_auto_catalog_sync_background, + start_single_media_catalog_sync, update_auto_catalog_settings, ) - +from Backend.helper.backup import export_config, import_config +from Backend.helper.custom_dl import ByteStreamer, _speed_test_single_client, run_speed_test +from Backend.helper.encrypt import decode_string, encode_string +from Backend.helper.health import run_health_checks +from Backend.helper.manual_add import resolve_telegram_message, retag_media, stamp_caption_by_ref +from Backend.helper import own_bots +from Backend.helper.pyro import resolve_video_thumb_url +from Backend.helper.requests_manager import ( + delete_request, + list_requests, + popular_pending, + search_titles, + set_status, + submit_request, +) +from Backend.helper.metadata import ( + build_id_link, + extract_default_id, + fetch_selected_movie_metadata, + fetch_selected_tv_metadata, + gradient_cover_path, + resolve_cover_url, + search_any_candidates, + search_movie_candidates, + search_tv_candidates, +) +from Backend.helper.passwords import hash_password, verify_password +from Backend.helper.pyro import get_readable_file_size, get_readable_time +from Backend.helper.scan_manager import dbcheck_manager, duplicate_manager, scan_manager +from Backend.helper.session_auth import ( + disconnect_session, + get_session_status, + reconnect_session, + remove_session, + start_login, + submit_code, + submit_password, +) from Backend.helper.settings_manager import SettingsManager +from Backend.helper.split_files import strip_part_suffix +from Backend.helper.subtitles import ( + list_languages, + list_title_subtitles, + manual_ingest_subtitle, + remove_subtitle, + resolve_subtitle_message, +) +from Backend.logger import LOGGER +import Backend.pyrofork.bot as botmod +from Backend.helper.announcer import delete_announcement_async +from Backend.pyrofork.bot import ( + StreamBot, + client_avg_mbps, + client_dc_map, + client_failures, + multi_clients, + work_loads, +) + + +def _coerce_tmdb_id(value): + """Accept int or string; treat 'null'/''/None as missing.""" + if value is None: + return None + if isinstance(value, int): + return value + s = str(value).strip() + if not s or s.lower() in ("null", "none", "undefined"): + return None + try: + return int(float(s)) + except (TypeError, ValueError): + return None + +def _require_tmdb_id(value) -> int: + tid = _coerce_tmdb_id(value) + if tid is None: + raise HTTPException(status_code=400, detail="tmdb_id is required and must be an integer") + return tid -# --- API Routes for System Stats --- + +#----- System stats async def get_system_stats_api(): try: db_stats = await db.get_database_stats() - total_movies = sum(stat.get("movie_count", 0) for stat in db_stats) - total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats) + total_movies, total_tv_shows = db.content_totals(db_stats) api_tokens = await db.get_all_api_tokens() return { @@ -56,47 +137,64 @@ async def get_system_stats_api(): "server_status": "error", "error": str(e) } - -# --- API Routes for Media Management --- + +#----- Expand stored gradient cover paths into full URLs for UI responses +def _resolve_covers(items) -> None: + for item in items or []: + for key in ("poster", "backdrop"): + if item.get(key): + item[key] = resolve_cover_url(item[key]) + + +_LIST_PROJECTION = {k: 0 for k in ( + "description", "cast", "telegram.name", "seasons.episodes.title", "seasons.episodes.overview", + "seasons.episodes.episode_backdrop", "seasons.episodes.telegram.name", +)} + + +#----- Media management async def list_media_api( media_type: str = Query("movie", regex="^(movie|tv)$"), page: int = Query(1, ge=1), page_size: int = Query(24, ge=1, le=100), - search: str = Query("", max_length=100) + search: str = Query("", max_length=100), + custom: bool = Query(False) ): try: + key = "movies" if media_type == "movie" else "tv_shows" + #----- Custom (manually added) titles carry a negative synthetic tmdb_id + extra_filter = {"tmdb_id": {"$lt": 0}} if custom else None if search: - result = await db.search_documents(search, page, page_size) - filtered_results = [item for item in result['results'] if item.get('media_type') == media_type] - total_filtered = len(filtered_results) - start_index = (page - 1) * page_size - end_index = start_index + page_size - paged_results = filtered_results[start_index:end_index] - - return { - "total_count": total_filtered, + result = await db.search_documents(search, page, page_size, extra_filter=extra_filter, media_type=media_type) + total = result["total_count"] + resp = { + "total_count": total, "current_page": page, - "total_pages": (total_filtered + page_size - 1) // page_size, - "movies" if media_type == "movie" else "tv_shows": paged_results + "total_pages": (total + page_size - 1) // page_size, + key: result["results"], } + elif media_type == "movie": + resp = await db.sort_movies([], page, page_size, extra_filter=extra_filter, projection=_LIST_PROJECTION) else: - if media_type == "movie": - return await db.sort_movies([], page, page_size) - else: - return await db.sort_tv_shows([], page, page_size) + resp = await db.sort_tv_shows([], page, page_size, extra_filter=extra_filter, projection=_LIST_PROJECTION) + _resolve_covers(resp.get(key)) + return resp except Exception as e: raise HTTPException(status_code=500, detail=str(e)) async def delete_media_api( - tmdb_id: int, + tmdb_id: str | int, db_index: int, media_type: str = Query(regex="^(movie|tv)$") ): + tmdb_id = _require_tmdb_id(tmdb_id) try: media_type_formatted = "Movie" if media_type == "movie" else "Series" result = await db.delete_document(media_type_formatted, tmdb_id, db_index) if result: + # Remove matching announcement post from the announcement channel + delete_announcement_async(media_type, tmdb_id) return {"message": "Media deleted successfully"} else: raise HTTPException(status_code=404, detail="Media not found") @@ -105,10 +203,11 @@ async def delete_media_api( async def update_media_api( request: Request, - tmdb_id: int, + tmdb_id: str | int, db_index: int, media_type: str = Query(regex="^(movie|tv)$") ): + tmdb_id = _require_tmdb_id(tmdb_id) try: update_data = await request.json() if 'rating' in update_data and update_data['rating']: @@ -152,6 +251,8 @@ async def update_media_api( except (ValueError, TypeError): pass update_data = {k: v for k, v in update_data.items() if v != ""} + if "title" in update_data: + update_data["title_english"] = update_data["title"] result = await db.update_document(media_type, tmdb_id, db_index, update_data) if result: return {"message": "Media updated successfully"} @@ -162,10 +263,11 @@ async def update_media_api( raise HTTPException(status_code=500, detail=str(e)) async def get_media_details_api( - tmdb_id: int, + tmdb_id: str | int, db_index: int, media_type: str = Query(regex="^(movie|tv)$") ): + tmdb_id = _require_tmdb_id(tmdb_id) try: result = await db.get_document(media_type, tmdb_id, db_index) if result: @@ -175,7 +277,8 @@ async def get_media_details_api( except Exception as e: raise HTTPException(status_code=500, detail=str(e)) -async def delete_movie_quality_api(tmdb_id: int, db_index: int, id: str): +async def delete_movie_quality_api(tmdb_id: str | int, db_index: int, id: str): + tmdb_id = _require_tmdb_id(tmdb_id) try: result = await db.delete_movie_quality(tmdb_id, db_index, id) if result: @@ -186,8 +289,9 @@ async def delete_movie_quality_api(tmdb_id: int, db_index: int, id: str): raise HTTPException(status_code=500, detail=str(e)) async def delete_tv_quality_api( - tmdb_id: int, db_index: int, season: int, episode: int, id: str + tmdb_id: str | int, db_index: int, season: int, episode: int, id: str ): + tmdb_id = _require_tmdb_id(tmdb_id) try: result = await db.delete_tv_quality(tmdb_id, db_index, season, episode, id) if result: @@ -198,8 +302,9 @@ async def delete_tv_quality_api( raise HTTPException(status_code=500, detail=str(e)) async def delete_tv_episode_api( - tmdb_id: int, db_index: int, season: int, episode: int + tmdb_id: str | int, db_index: int, season: int, episode: int ): + tmdb_id = _require_tmdb_id(tmdb_id) try: result = await db.delete_tv_episode(tmdb_id, db_index, season, episode) if result: @@ -209,7 +314,8 @@ async def delete_tv_episode_api( except Exception as e: raise HTTPException(status_code=500, detail=str(e)) -async def delete_tv_season_api(tmdb_id: int, db_index: int, season: int): +async def delete_tv_season_api(tmdb_id: str | int, db_index: int, season: int): + tmdb_id = _require_tmdb_id(tmdb_id) try: result = await db.delete_tv_season(tmdb_id, db_index, season) if result: @@ -220,98 +326,140 @@ async def delete_tv_season_api(tmdb_id: int, db_index: int, season: int): raise HTTPException(status_code=500, detail=str(e)) -# --- API Routes for Token Management --- +#----- Token management +#----- Parse a GB-limit value into a positive float, or None +def _parse_limit(val): + try: + v = float(val) + return v if v > 0 else None + except (ValueError, TypeError, AttributeError): + return None + async def create_token_api(payload: dict): try: token_name = payload.get("name") - daily_limit = payload.get("daily_limit_gb") - monthly_limit = payload.get("monthly_limit_gb") - if not token_name: - raise HTTPException(status_code=400, detail="Token name is required") - def parse_limit(val): - try: - v = float(val) - return v if v > 0 else None - except (ValueError, TypeError): - return None + raise HTTPException(status_code=400, detail="Token name is required") new_token = await db.add_api_token( - token_name, - parse_limit(daily_limit), - parse_limit(monthly_limit) + token_name, + _parse_limit(payload.get("daily_limit_gb")), + _parse_limit(payload.get("monthly_limit_gb")), + subscription_exempt=bool(payload.get("subscription_exempt")), ) return new_token + except HTTPException: + raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + +#----- Toggle a token's lifetime (subscription-exempt) flag +async def set_token_lifetime_api(token: str, payload: dict) -> dict: + exempt = bool(payload.get("subscription_exempt")) + if not await db.set_token_lifetime(token, exempt): + raise HTTPException(status_code=404, detail="Token not found.") + return {"status": "success", "subscription_exempt": exempt} + + +#----- Set/extend/reduce a token's own expiry (subscription-off mode). +#----- Optionally attach a Telegram user id at the same time. +async def set_token_expiry_api(token: str, payload: dict) -> dict: + user_id = payload.get("user_id") + if user_id not in (None, "", 0, "0"): + try: + uid = int(user_id) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Invalid Telegram user id.") + #----- Enforces one-user-one-token + pulls the real Telegram name + await link_token_user_api(token, uid) + + action = str(payload.get("action") or "set") + days = int(payload.get("days") or 0) + result = await db.update_token_expiry(token, action, days) + if not result: + raise HTTPException(status_code=404, detail="Token not found.") + return {"status": "success", "expires_at": result.get("expires_at").isoformat() if result.get("expires_at") else None} + + +#----- How many tokens would stop working if subscription mode is enabled +async def subscription_preflight_api() -> dict: + return {"status": "success", "uncovered": await db.count_uncovered_tokens()} + + +#----- Relabel "User " placeholder subscribers with their real Telegram name +async def backfill_subscriber_names_api() -> dict: + users = await db.get_all_subscribers() + updated = 0 + for u in users: + uid = u.get("_id") + if uid is None or (u.get("first_name") or "") != f"User {uid}": + continue + name = await _fetch_tg_name(uid) + if name and name != f"User {uid}": + await db.update_subscriber_name(uid, name) + updated += 1 + return {"status": "success", "updated": updated, "message": f"{updated} name(s) updated."} + + +#----- Mark all tokens that aren't linked to a user as lifetime +async def grant_lifetime_api() -> dict: + count = await db.grant_lifetime_to_unlinked() + return {"status": "success", "updated": count, "message": f"{count} token(s) marked as lifetime."} + +async def update_token_cf_api(token: str, payload: dict): + try: + await own_bots.set_worker(token, payload.get("cf_url"), payload.get("cf_secret")) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + return {"message": "Cloudflare proxy saved"} + async def update_token_limits_api(token: str, payload: dict): try: daily_limit = payload.get("daily_limit_gb") monthly_limit = payload.get("monthly_limit_gb") - - def parse_limit(val): - try: - v = float(val) - return v if v > 0 else None - except (ValueError, TypeError, AttributeError): - return None - result = await db.update_api_token_limits( + await db.update_api_token_limits( token, - parse_limit(daily_limit), - parse_limit(monthly_limit) + _parse_limit(daily_limit), + _parse_limit(monthly_limit) ) - - if result: - return {"message": "Limits updated successfully"} - else: - return {"message": "Limits updated successfully"} - - except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) + return {"message": "Limits updated successfully"} -async def revoke_token_api(token: str): - try: - result = await db.revoke_api_token(token) - if result: - return {"message": "Token revoked successfully"} - else: - raise HTTPException(status_code=404, detail="Token not found") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) -# --- Speed Test API --- +#----- Speed test +#----- Decode a quality_id into (chat_id, msg_id); split files use the first part +async def _resolve_speed_test_target(quality_id: str): + decoded = await decode_string(quality_id) + target = decoded["parts"][0] if decoded.get("parts") else decoded + msg_id = target.get("msg_id") + raw_cid = target.get("chat_id") + if not msg_id or not raw_cid: + return None, None, decoded + return int(f"-100{raw_cid}"), int(msg_id), decoded + +#----- Run a parallel download speed test across all connected clients async def speed_test_api( quality_id: str = Query(..., description="Encoded quality ID from DB"), - tmdb_id: int = Query(...), + tmdb_id: str | int = Query(...), db_index: int = Query(...), media_type: str = Query(..., regex="^(movie|tv)$"), ): - """ - Decode quality_id using the same decode_string logic as the stream handler, - then run a parallel download speed test across all connected bot clients. - """ - from Backend.helper.encrypt import decode_string - + tmdb_id = _require_tmdb_id(tmdb_id) try: - decoded = await decode_string(quality_id) - msg_id = decoded.get("msg_id") - raw_cid = decoded.get("chat_id") - - if not msg_id or not raw_cid: + chat_id, msg_id, decoded = await _resolve_speed_test_target(quality_id) + if not chat_id or not msg_id: raise HTTPException( status_code=422, detail=f"Decoded quality data is missing msg_id or chat_id. Decoded: {decoded}" ) - # Stream handler adds -100 prefix for channel IDs - chat_id = int(f"-100{raw_cid}") - - results = await run_speed_test(int(chat_id), int(msg_id)) + results = await run_speed_test(chat_id, msg_id) return {"results": results, "total_clients_tested": len(results)} except HTTPException: @@ -320,31 +468,22 @@ async def speed_test_api( raise HTTPException(status_code=500, detail=str(e)) -# --- Speed Test SSE Streaming API --- - +#----- SSE speed test streaming per-client results as they finish async def speed_test_stream_api( quality_id: str, - tmdb_id: int, + tmdb_id: str | int, db_index: int, media_type: str, ): - """ - SSE version of the speed test. Streams each per-client result as a - 'data:' event the moment that client finishes, so the UI can update live. - """ - from Backend.helper.encrypt import decode_string + tmdb_id = _require_tmdb_id(tmdb_id) async def event_generator(): - # Decode quality_id → chat_id + message_id try: - decoded = await decode_string(quality_id) - msg_id = decoded.get("msg_id") - raw_cid = decoded.get("chat_id") - if not msg_id or not raw_cid: + chat_id, msg_id, decoded = await _resolve_speed_test_target(quality_id) + if not chat_id or not msg_id: payload = json.dumps({"type": "error", "message": f"Cannot decode quality_id. Got: {decoded}"}) yield f"data: {payload}\n\n" return - chat_id = int(f"-100{raw_cid}") except Exception as exc: payload = json.dumps({"type": "error", "message": str(exc)}) yield f"data: {payload}\n\n" @@ -355,11 +494,10 @@ async def speed_test_stream_api( payload = json.dumps({"type": "error", "message": "No bot clients connected"}) yield f"data: {payload}\n\n" return - - # Try to resolve the FileId to get the target DC + + #----- Resolve the FileId to report the target DC target_dc = "?" try: - from Backend.helper.custom_dl import ByteStreamer primary_client = multi_clients.get(0) or next(iter(multi_clients.values())) streamer = ByteStreamer(primary_client) file_id = await streamer.get_file_properties(chat_id, int(msg_id)) @@ -367,16 +505,16 @@ async def speed_test_stream_api( except Exception: pass - # Send initial "start" event so the frontend can set up the table + #----- Initial start event so the frontend can build its table yield f"data: {json.dumps({'type': 'start', 'total': total, 'target_dc': target_dc})}\n\n" - # Run all clients in parallel; feed results into a queue as they finish + #----- Run all clients in parallel, feeding results into a queue queue: asyncio.Queue = asyncio.Queue() async def run_one(client, idx): async def on_progress(prog_data): await queue.put({"type": "progress", "data": prog_data}) - + result = await _speed_test_single_client( client, idx, chat_id, int(msg_id), progress_callback=on_progress ) @@ -390,11 +528,11 @@ async def speed_test_stream_api( completed = 0 while completed < total: msg = await queue.get() - + if msg["type"] == "progress": payload = json.dumps(msg) yield f"data: {payload}\n\n" - + elif msg["type"] == "result": completed += 1 payload = json.dumps({ @@ -405,10 +543,7 @@ async def speed_test_stream_api( }) yield f"data: {payload}\n\n" - # Wait for any remaining tasks (should already be done) await asyncio.gather(*tasks, return_exceptions=True) - - # Final done event yield f"data: {json.dumps({'type': 'done', 'total': total})}\n\n" return StreamingResponse( @@ -416,79 +551,74 @@ async def speed_test_stream_api( media_type="text/event-stream", headers={ "Cache-Control": "no-cache", - "X-Accel-Buffering": "no", # prevent nginx from buffering SSE + "X-Accel-Buffering": "no", }, ) -# --------------------------------------------------------------------------- -# Admin API Routes -# --------------------------------------------------------------------------- +#----- Admin stats async def get_admin_stats_api() -> dict: - from Backend.pyrofork.bot import work_loads, multi_clients, client_failures, client_avg_mbps - from Backend.fastapi.routes.stream_routes import _streamer_by_client - - # Sum cache entries across all active ByteStreamer instances cache_size = sum(len(s._file_id_cache) for s in _streamer_by_client.values()) - - # Calculate bot workloads and health + bot_stats = [] for client_index in multi_clients: load = work_loads.get(client_index, 0) failures = client_failures.get(client_index, 0) mbps = client_avg_mbps.get(client_index, 0.0) - + status = "healthy" if failures > 5: status = "degraded" if failures > 15: status = "failing" - + bot_stats.append({ "client_index": client_index, - "display_name": f"Bot {client_index + 1}", + "display_name": "Userbot" if client_index < 0 else f"Bot {client_index + 1}", + "dc": client_dc_map.get(client_index), "current_load": load, "failures": failures, "avg_mbps": round(mbps, 2), "status": status }) - + return { "cache_size": cache_size, "total_bots": len(multi_clients), "bot_workloads": bot_stats } + +#----- Clear the FileId cache across all active streamers async def clear_cache_api() -> dict: - from Backend.fastapi.routes.stream_routes import _streamer_by_client - from Backend.logger import LOGGER - - # Clear cache across all active ByteStreamer instances total_cleared = sum(len(s._file_id_cache) for s in _streamer_by_client.values()) for streamer in _streamer_by_client.values(): streamer._file_id_cache.clear() LOGGER.info(f"Admin cleared the FileId cache ({total_cleared} items purged across {len(_streamer_by_client)} clients).") - + return {"status": "success", "message": f"{total_cleared} cached items cleared."} + +#----- List dead links recorded in the DB async def get_dead_links_api() -> dict: - from Backend import db try: dead_links = await db.get_all_dead_links() return {"status": "success", "data": dead_links} except Exception as e: return {"status": "error", "message": str(e)} + +#----- Recent stream analytics async def get_stream_analytics_api() -> dict: - from Backend import db try: data = await db.get_stream_analytics(limit=200) return {"status": "success", "data": data} except Exception as e: - from Backend.logger import LOGGER LOGGER.error(f"Stream analytics API error: {e}") return {"status": "error", "message": str(e)} + +#----- Purge all stream analytics records async def clear_stream_analytics_api() -> dict: try: result = await db.dbs["tracking"]["stream_analytics"].delete_many({}) @@ -501,12 +631,64 @@ async def clear_stream_analytics_api() -> dict: except Exception as e: return {"status": "error", "message": str(e)} -# --------------------------------------------------------------------------- -# Admin Subscription Management API Routes -# --------------------------------------------------------------------------- +#----- Public: search titles to request (by name, IMDb id or TMDB id) +async def request_search_api(q: str) -> dict: + try: + return {"status": "success", "data": await search_titles(q)} + except Exception as e: + LOGGER.error(f"Request search error: {e}") + return {"status": "error", "message": str(e), "data": []} + + +#----- Public: submit a request for a title +async def request_submit_api(payload: dict, client_ip: str) -> dict: + result = await submit_request( + media_type=payload.get("media_type"), + tmdb_id=payload.get("tmdb_id"), + imdb_id=payload.get("imdb_id"), + title=payload.get("title"), + year=payload.get("year"), + poster=payload.get("poster"), + client_ip=client_ip, + ) + return {"status": "success" if result.get("ok") else "error", **result} + + +#----- Public: most-requested pending titles +async def request_popular_api() -> dict: + try: + return {"status": "success", "data": await popular_pending()} + except Exception as e: + return {"status": "error", "message": str(e), "data": []} + + +#----- Admin: list all content requests +async def get_requests_api() -> dict: + try: + return {"status": "success", "data": await list_requests()} + except Exception as e: + LOGGER.error(f"Requests API error: {e}") + return {"status": "error", "message": str(e)} + + +#----- Admin: uploaded / denied / banned / pending +async def update_request_api(request_id: str, payload: dict) -> dict: + new_status = str(payload.get("status", "")).strip() + doc = await set_status(request_id, new_status) + if not doc: + raise HTTPException(status_code=404, detail="Request not found or invalid status.") + return {"status": "success", "data": doc} + + +async def delete_request_api(request_id: str) -> dict: + if not await delete_request(request_id): + raise HTTPException(status_code=404, detail="Request not found.") + return {"status": "success", "message": "Request deleted."} + + +#----- Admin subscription management async def get_subscription_plans_api() -> dict: - from Backend import db try: plans = await db.get_subscription_plans() return {"status": "success", "data": plans} @@ -514,14 +696,14 @@ async def get_subscription_plans_api() -> dict: return {"status": "error", "message": str(e)} async def add_subscription_plan_api(payload: dict) -> dict: - from Backend import db try: days = int(payload.get("days", 0)) price = float(payload.get("price", 0.0)) + currency = str(payload.get("currency") or "INR").upper().strip() if days <= 0 or price < 0: raise HTTPException(status_code=400, detail="Invalid plan parameters") - plan_id = await db.add_subscription_plan(days, price) + plan_id = await db.add_subscription_plan(days, price, currency) if plan_id: return {"status": "success", "message": "Plan added successfully", "plan_id": plan_id} else: @@ -532,14 +714,14 @@ async def add_subscription_plan_api(payload: dict) -> dict: raise HTTPException(status_code=500, detail=str(e)) async def update_subscription_plan_api(plan_id: str, payload: dict) -> dict: - from Backend import db try: days = int(payload.get("days", 0)) price = float(payload.get("price", 0.0)) + currency = str(payload.get("currency") or "INR").upper().strip() if days <= 0 or price < 0: raise HTTPException(status_code=400, detail="Invalid plan parameters") - success = await db.update_subscription_plan(plan_id, days, price) + success = await db.update_subscription_plan(plan_id, days, price, currency) if success: return {"status": "success", "message": "Plan updated successfully"} else: @@ -550,7 +732,6 @@ async def update_subscription_plan_api(plan_id: str, payload: dict) -> dict: raise HTTPException(status_code=500, detail=str(e)) async def delete_subscription_plan_api(plan_id: str) -> dict: - from Backend import db try: success = await db.delete_subscription_plan(plan_id) if success: @@ -563,46 +744,43 @@ async def delete_subscription_plan_api(plan_id: str) -> dict: raise HTTPException(status_code=500, detail=str(e)) async def get_all_subscribers_api() -> dict: - from Backend import db try: users = await db.get_all_subscribers() + for u in users: + u["is_admin"] = db._is_owner(u.get("_id")) return {"status": "success", "data": users} except Exception as e: return {"status": "error", "message": str(e)} async def manage_subscriber_api(user_id: int, payload: dict) -> dict: - from Backend import db try: action = payload.get("action") days = int(payload.get("days", 0)) - - if action not in ["extend", "reduce", "delete"]: + + if action not in ["extend", "reduce", "delete", "remove"]: raise HTTPException(status_code=400, detail="Invalid action") - + success = await db.manage_subscriber(user_id, action, days) - # On revoke, also remove the user from the subscription group so the - # action takes effect immediately instead of waiting for the checker. - if success and action == "delete" and SettingsManager.current().subscription: + #----- On revoke/remove, kick the user from the group immediately (ban+unban) + if success and action in ("delete", "remove") and SettingsManager.current().subscription: group_id = SettingsManager.current().subscription_group_id if group_id: try: - # ban + unban kicks without permanently blocking re-join await StreamBot.ban_chat_member(group_id, user_id) await StreamBot.unban_chat_member(group_id, user_id) except Exception as exc: LOGGER.warning(f"Revoke: could not remove user {user_id} from group: {exc}") - # Reflect the change immediately in the stremio membership cache. + #----- Reflect the change immediately in the stremio membership cache if success: try: - from Backend.fastapi.routes.stremio_routes import invalidate_membership_cache invalidate_membership_cache(user_id) except Exception: pass if success: - verb = {"extend": "extended", "reduce": "reduced", "delete": "revoked"}.get(action, "updated") + verb = {"extend": "extended", "reduce": "reduced", "delete": "revoked", "remove": "removed"}.get(action, "updated") return {"status": "success", "message": f"User subscription {verb} successfully"} else: raise HTTPException(status_code=404, detail="User not found or update failed") @@ -612,16 +790,15 @@ async def manage_subscriber_api(user_id: int, payload: dict) -> dict: raise HTTPException(status_code=500, detail=str(e)) -# --- Access Management API --- - +#----- Access management async def get_all_tokens_api() -> dict: try: tokens = await db.get_all_api_tokens() now = datetime.utcnow() result = [] - # Pre-load all subscribers into a dict keyed by user_id for O(1) lookup - subscriber_map = {} # user_id (str) -> user doc + #----- Pre-load subscribers keyed by user_id for O(1) lookup + subscriber_map = {} if SettingsManager.current().subscription: try: for u in await db.get_all_subscribers(): @@ -630,79 +807,96 @@ async def get_all_tokens_api() -> dict: except Exception: pass + #----- Display name, preferring a real name/alias over the "User " placeholder def display_name(user, user_id, token_name=None): - """Return a non-empty display name for a user.""" + placeholder = f"User {user_id}" if user_id is not None else None + options = [token_name] if user: - n = user.get("first_name") or user.get("username") - if n: - return n - # Fall back to the name stored on the token itself (set at creation time) - if token_name: - return token_name - return f"User {user_id}" if user_id else "Telegram User" - + options += [user.get("first_name"), user.get("username")] + for o in options: + if o and o != placeholder: + return o + for o in options: + if o: + return o + return placeholder or "Telegram User" + + sub_on = SettingsManager.current().subscription + + #----- Unified access entry from optional user + token records def build_entry(user_id, user, token_doc): - """ a unified access entry from optional user + token records.""" - expiry = None - sub_status = None + token_doc = token_doc or {} user_found = bool(user) - - if user: - sub_status = user.get("subscription_status") - expiry = user.get("subscription_expiry") - - # Token-level expiry as fallback - if token_doc: - t_expiry = token_doc.get("subscription_expiry") or token_doc.get("expires_at") - if t_expiry and not expiry: - expiry = t_expiry - - # Determine status - if SettingsManager.current().subscription: - if not user_found: - is_expired = True - elif sub_status != "active": - is_expired = True - elif not expiry: - is_expired = True - else: - is_expired = expiry < now + sub_status = user.get("subscription_status") if user else None + is_admin = bool(token_doc.get("is_admin")) or db._is_owner(user_id) + lifetime = bool(token_doc.get("subscription_exempt")) + token_str = token_doc.get("token") + + token_expiry = token_doc.get("expires_at") + user_sub_expiry = user.get("subscription_expiry") if user else None + + #----- Sub OFF: token's own expiry (display only). Sub ON: token expiry is an + #----- admin grant, otherwise fall back to the subscription's expiry. + if not sub_on: + expiry = token_expiry + is_expired = False + elif is_admin or lifetime: + expiry = None + is_expired = False + elif token_expiry is not None: + expiry = token_expiry + is_expired = token_expiry < now + elif user_found and sub_status == "active" and user_sub_expiry: + expiry = user_sub_expiry + is_expired = user_sub_expiry < now else: - is_expired = bool(expiry and expiry < now) + expiry = user_sub_expiry + is_expired = True - token_str = token_doc.get("token") if token_doc else None - created = token_doc.get("created_at") if token_doc else (user.get("created_at") if user else None) + created = token_doc.get("created_at") or (user.get("created_at") if user else None) + limits = token_doc.get("limits") or {} + usage = token_doc.get("usage") or {} + has_active_sub = sub_on and user_found and sub_status == "active" and bool(user_sub_expiry) and user_sub_expiry > now + never_expires = not expiry and (is_admin or lifetime or not sub_on) return { "token": token_str, "user_id": user_id, - "user_name": display_name(user, user_id, token_doc.get("name") if token_doc else None), + "user_name": display_name(user, user_id, token_doc.get("name")), "user_found": user_found, + "is_admin": is_admin, + "lifetime": lifetime, + "never_expires": never_expires, "has_token": bool(token_str), + "has_active_sub": has_active_sub, "created_at": created.isoformat() if created else None, "expires_at": expiry.isoformat() if expiry else None, "is_expired": is_expired, "sub_status": sub_status, + "daily_limit_gb": limits.get("daily_limit_gb") or 0, + "monthly_limit_gb": limits.get("monthly_limit_gb") or 0, + "daily_bytes": (usage.get("daily") or {}).get("bytes", 0), + "monthly_bytes": (usage.get("monthly") or {}).get("bytes", 0), "addon_url": ( f"{SettingsManager.current().base_url}/stremio/{token_str}/manifest.json" if token_str else None ), + "own_bots": own_bots.public(token_doc["own_bots"]) if token_doc.get("own_bots") else None, + "cf_url": (token_doc.get("cf") or {}).get("url", ""), + "cf_secret": (token_doc.get("cf") or {}).get("secret", ""), } - # Track user_ids that are already represented via a token row seen_user_ids = set() - # --- 1. Process all existing tokens --- + #----- 1. Process all existing tokens for t in tokens: token_user_id = t.get("user_id") - # Try to resolve user from subscriber_map using token's user_id user = None if token_user_id: uid_str = str(token_user_id) user = subscriber_map.get(uid_str) if not user: - # Fallback: query DB if not in subscriber_map (e.g. non-active subscribers) try: user = await db.get_user(int(token_user_id)) except Exception: @@ -711,21 +905,20 @@ async def get_all_tokens_api() -> dict: result.append(build_entry(token_user_id, user, t)) - # --- 2. Add subscribers who have NO token --- + #----- 2. Add subscribers who have no token for uid_str, u in subscriber_map.items(): if uid_str in seen_user_ids: - continue # already covered by a token row + continue result.append(build_entry(u.get("_id"), u, None)) - # Sort: active-with-token first, then active-no-token, expired last + #----- Sort: active-with-token first, active-no-token next, expired last result.sort(key=lambda x: (x["is_expired"], not x["has_token"])) - return {"tokens": result} + return {"tokens": result, "subscription": sub_on} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) async def revoke_token_api(token: str) -> dict: - from Backend import db try: success = await db.revoke_api_token(token) if success: @@ -737,13 +930,16 @@ async def revoke_token_api(token: str) -> dict: raise HTTPException(status_code=500, detail=str(e)) +#----- Assign or extend a subscription for any user_id async def assign_plan_api(user_id: int, days: int) -> dict: - """Assign (or extend) a subscription for any user by user_id, even if not in DB.""" - from Backend import db try: - if days < 1: - raise HTTPException(status_code=400, detail="Days must be at least 1.") - result = await db.assign_subscription(user_id, days) + #----- Use the real Telegram name so the Plans page shows it (not "User ") + name = await _fetch_tg_name(user_id) + #----- 0 / empty days means "never expires" + if days and days > 0: + result = await db.assign_subscription(user_id, days, name) + else: + result = await db.set_user_never_expires(user_id, name) return {"status": "success", "data": result} except HTTPException: raise @@ -751,22 +947,44 @@ async def assign_plan_api(user_id: int, days: int) -> dict: raise HTTPException(status_code=500, detail=str(e)) +#----- Look up a Telegram user's display name via the bot (best-effort) +async def _fetch_tg_name(user_id: int): + try: + u = await StreamBot.get_users(user_id) + if not u: + return None + name = (u.first_name or "").strip() + if getattr(u, "last_name", None): + name = f"{name} {u.last_name}".strip() + return name or (u.username or None) + except Exception: + return None + + +#----- Link an orphan token to a Telegram user_id (one user_id = one token) async def link_token_user_api(token: str, user_id: int) -> dict: - """Link an orphan token (no user_id) to a Telegram user_id.""" - from Backend import db try: - success = await db.link_token_user(token, user_id) + existing = await db.get_api_token_by_user(user_id) + if existing and existing.get("token") == token: + return {"status": "success", "message": f"Already linked to user {user_id}."} + if existing: + raise HTTPException( + status_code=409, + detail=f"User {user_id} is already linked to token '{existing.get('name')}'. Unlink or delete that token first.", + ) + #----- Overwrite the token name with the user's real Telegram name when available + name = await _fetch_tg_name(user_id) + success = await db.link_token_user(token, user_id, name) if success: - return {"status": "success", "message": f"Token linked to user {user_id}."} - raise HTTPException(status_code=404, detail="Token not found or already linked.") + return {"status": "success", "message": f"Token linked to {name or user_id}."} + raise HTTPException(status_code=404, detail="Token not found.") except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) - - +#----- Rescan: search TMDB candidates for a title async def search_media_rescan_api(media_type: str, query: str, year: int | None = None): query = (query or "").strip() if not query: @@ -782,7 +1000,18 @@ async def search_media_rescan_api(media_type: str, query: str, year: int | None return {"results": results} -async def apply_media_rescan_api(request: Request, tmdb_id: int, db_index: int, media_type: str): +async def tag_media_api(tmdb_id: str | int, db_index: int, media_type: str): + doc = await db.get_document(media_type, _require_tmdb_id(tmdb_id), db_index) + if not doc: + raise HTTPException(status_code=404, detail="Media not found.") + if not build_id_link(doc.get("imdb_id"), doc.get("tmdb_id"), media_type): + raise HTTPException(status_code=400, detail="This title has no IMDb or TMDB id to tag with.") + asyncio.create_task(retag_media(_scan_client(), media_type, doc)) + return {"status": "success", "message": "Tagging files in the background."} + + +async def apply_media_rescan_api(request: Request, tmdb_id: str | int, db_index: int, media_type: str): + tmdb_id = _require_tmdb_id(tmdb_id) body = await request.json() selected_id = str(body.get("selected_id") or "").strip() @@ -812,6 +1041,7 @@ async def apply_media_rescan_api(request: Request, tmdb_id: int, db_index: int, if not updated_doc: raise HTTPException(status_code=500, detail="Failed to replace media metadata.") + asyncio.create_task(retag_media(_scan_client(), media_type, updated_doc)) return { "success": True, @@ -823,20 +1053,377 @@ async def apply_media_rescan_api(request: Request, tmdb_id: int, db_index: int, } -# --- Custom Catalog APIs --- +#----- Manual add: fetch full metadata for a selected TMDB/IMDB title to autofill the form +async def resolve_manual_metadata_api(media_type: str, selected_id: str) -> dict: + selected_id = str(selected_id or "").strip() + if not selected_id: + raise HTTPException(status_code=400, detail="selected_id is required.") + mt = _normalize_media_type(media_type) + data = await ( + fetch_selected_movie_metadata(selected_id) if mt == "movie" + else fetch_selected_tv_metadata(selected_id) + ) + if not data: + raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.") + if data.get("poster"): + data["poster"] = resolve_cover_url(data["poster"]) + if data.get("backdrop"): + data["backdrop"] = resolve_cover_url(data["backdrop"]) + return {"metadata": data} + + +#----- Manual add: resolve a Telegram post link into a streamable file +async def resolve_telegram_api(payload: dict) -> dict: + client = _scan_client() + if client is None: + raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") + try: + data = await resolve_telegram_message( + client, + url=payload.get("url"), + chat_id=payload.get("chat_id"), + msg_id=payload.get("msg_id"), + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except Exception as exc: + raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}") + return {"status": "success", "data": data} + + +async def resolve_subtitle_api(payload: dict) -> dict: + client = _scan_client() + if client is None: + raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") + try: + data = await resolve_subtitle_message( + client, url=payload.get("url"), + chat_id=payload.get("chat_id"), msg_id=payload.get("msg_id"), + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except Exception as exc: + raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}") + return {"status": "success", "data": data} + + +async def _resolve_imdb_id(media_type: str, tmdb_id, db_index) -> str: + tmdb_id = _coerce_tmdb_id(tmdb_id) + if not (tmdb_id and db_index): + raise HTTPException(status_code=400, detail="tmdb_id and db_index are required.") + doc = await db.get_document(media_type, int(tmdb_id), int(db_index)) + if not doc or not doc.get("imdb_id"): + raise HTTPException(status_code=404, detail="Title not found.") + return doc["imdb_id"] + + +def list_subtitle_languages_api() -> dict: + return {"status": "success", "languages": list_languages()} + + +async def list_subtitles_api(media_type: str, tmdb_id, db_index) -> dict: + tmdb_id = _require_tmdb_id(tmdb_id) + mt = "tv" if media_type in ("tv", "series") else "movie" + imdb_id = await _resolve_imdb_id(mt, tmdb_id, db_index) + return {"status": "success", "subtitles": await list_title_subtitles(imdb_id)} + + +async def add_subtitles_api(payload: dict) -> dict: + media_type = "tv" if payload.get("media_type") in ("tv", "series") else "movie" + imdb_id = await _resolve_imdb_id(media_type, payload.get("tmdb_id"), payload.get("db_index")) + items = payload.get("items") or [] + if not isinstance(items, list) or not items: + raise HTTPException(status_code=400, detail="Provide at least one subtitle to add.") + + client = _scan_client() + if client is None: + raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") + + added, errors = [], [] + for item in items: + try: + season = item.get("season") if media_type == "tv" else None + episode = item.get("episode") if media_type == "tv" else None + if media_type == "tv" and (not season or not episode): + raise ValueError("Season and episode are required for series subtitles.") + resolved = await resolve_subtitle_message( + client, url=item.get("url"), + chat_id=item.get("chat_id"), msg_id=item.get("msg_id"), + ) + doc = await manual_ingest_subtitle( + imdb_id, media_type, season, episode, + item.get("lang_code") or resolved["lang_code"], + resolved["chat_id"], resolved["msg_id"], resolved["name"], + ) + added.append({ + "name": doc["name"], "lang_label": doc["lang_label"], + "season": doc["season"], "episode": doc["episode"], + }) + except ValueError as exc: + errors.append(str(exc)) + except Exception as exc: + errors.append(f"Could not add subtitle: {exc}") + + if not added and errors: + raise HTTPException(status_code=400, detail=" ".join(errors)) + message = f"Added {len(added)} subtitle(s)." + if errors: + message += f" {len(errors)} failed: {' '.join(errors)}" + return {"status": "success", "message": message, "added": added, "errors": errors} + + +async def remove_subtitle_api(payload: dict) -> dict: + chat_id = payload.get("chat_id") + msg_id = payload.get("msg_id") + if chat_id in (None, "") or msg_id in (None, ""): + raise HTTPException(status_code=400, detail="chat_id and msg_id are required.") + if not await remove_subtitle(chat_id, msg_id): + raise HTTPException(status_code=404, detail="Subtitle not found.") + return {"status": "success", "message": "Subtitle removed."} + + +#----- Build a metadata base (title-level fields) from various sources +def _metadata_base(source: dict, from_doc: bool = False) -> dict: + genres = source.get("genres") + if isinstance(genres, str): + genres = [g.strip() for g in genres.split(",") if g.strip()] + year = source.get("release_year") if from_doc else source.get("year") + rate = source.get("rating") if from_doc else source.get("rate") + return { + "tmdb_id": source.get("tmdb_id"), + "imdb_id": source.get("imdb_id") or None, + "title": (source.get("title") or "").strip(), + "year": int(year) if str(year or "").strip().lstrip("-").isdigit() else 0, + "rate": float(rate) if str(rate or "").replace(".", "", 1).isdigit() else 0, + "description": source.get("description") or "", + "poster": source.get("poster") or "", + "backdrop": source.get("backdrop") or "", + "logo": source.get("logo") or "", + "genres": genres or [], + "cast": source.get("cast") or [], + "runtime": str(source.get("runtime") or ""), + "original_language": source.get("original_language"), + "origin_country": source.get("origin_country") or [], + } + + +_PLACEHOLDER_GENRES = ["Action", "Adventure", "Comedy", "Drama", "Fantasy", + "Thriller", "Mystery", "Sci-Fi", "Romance", "Family"] +_PLACEHOLDER_DESCRIPTIONS = [ + "A gripping story full of unexpected twists and turns.", + "An unforgettable journey that keeps you on the edge of your seat.", + "A captivating tale of drama, courage and emotion.", + "An entertaining experience packed with memorable moments.", + "A thrilling adventure blending heart, action and wonder.", +] + + +#----- Fill empty optional metadata with random values and a gradient cover path +def _fill_placeholder_metadata(meta: dict) -> None: + title = meta.get("title") or "Media" + if not meta.get("poster"): + meta["poster"] = gradient_cover_path(title, portrait=True) + if not meta.get("backdrop"): + meta["backdrop"] = gradient_cover_path(title) + if not meta.get("genres"): + meta["genres"] = random.sample(_PLACEHOLDER_GENRES, random.randint(1, 3)) + if not meta.get("rate"): + meta["rate"] = round(random.uniform(6.0, 8.9), 1) + if not meta.get("description"): + meta["description"] = random.choice(_PLACEHOLDER_DESCRIPTIONS) + + +#----- Manual add: create/append a movie, tv show, season, episode or stream by hand +async def manual_add_media_api(payload: dict) -> dict: + media_type = payload.get("media_type") + if media_type not in ("movie", "tv"): + raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'tv'.") + + stream = payload.get("stream") or {} + quality = str(stream.get("quality") or "").strip() + if not quality: + raise HTTPException(status_code=400, detail="A quality label (e.g. 1080p) is required.") + + #----- One source = single file, multiple sources = split file parts (in order) + part_sources = stream.get("parts") + if not isinstance(part_sources, list) or not part_sources: + part_sources = [{"url": stream.get("url"), "chat_id": stream.get("chat_id"), "msg_id": stream.get("msg_id")}] + part_sources = [p for p in part_sources if p and (p.get("url") or (p.get("chat_id") and p.get("msg_id")))] + if not part_sources: + raise HTTPException(status_code=400, detail="Provide at least one Telegram message link.") + + client = _scan_client() + if client is None: + raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") + + resolved_parts = [] + for src in part_sources: + try: + resolved_parts.append(await resolve_telegram_message( + client, url=src.get("url"), chat_id=src.get("chat_id"), msg_id=src.get("msg_id"), + )) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except Exception as exc: + raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}") + + primary = resolved_parts[0] + is_split = len(resolved_parts) > 1 + raw_name = (stream.get("name") or primary["name"]).strip() + name = strip_part_suffix(raw_name) if is_split else raw_name + + #----- Resolve the title-level metadata: existing doc, TMDB/IMDb pick, or manual entry + tmdb_id = payload.get("tmdb_id") + db_index = payload.get("db_index") + selected_id = str(payload.get("selected_id") or "").strip() + + base = None + if tmdb_id and db_index: + doc = await db.get_document(media_type, int(tmdb_id), int(db_index)) + if doc: + base = _metadata_base(doc, from_doc=True) + if base is None and selected_id: + selection = await ( + fetch_selected_movie_metadata(selected_id) if media_type == "movie" + else fetch_selected_tv_metadata(selected_id) + ) + if not selection: + raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.") + base = _metadata_base(selection, from_doc=True) + if base is None: + base = _metadata_base(payload.get("manual_metadata") or {}) + if not base["title"]: + raise HTTPException(status_code=400, detail="A title is required for manual entry.") + if not base["year"]: + base["year"] = int(primary.get("upload_year") or 0) + + #----- Brand-new hand-made titles get a negative synthetic id (never collides with TMDB) + if not base.get("tmdb_id"): + base["tmdb_id"] = -(secrets.randbelow(2_000_000_000) + 1) + #----- A synthetic "tg" imdb id is required so Stremio can request meta/streams + if not base.get("imdb_id"): + base["imdb_id"] = f"tg{abs(int(base['tmdb_id']))}" + _fill_placeholder_metadata(base) + + thumb_url = "" + if primary.get("has_thumb"): + thumb_enc = await encode_string({"chat_id": int(primary["chat_id"]), "msg_id": int(primary["msg_id"])}) + try: + chat_ref = int(f"-100{str(primary['chat_id']).replace('-100', '')}") + msg = await client.get_messages(chat_ref, int(primary["msg_id"])) + thumb_url = await resolve_video_thumb_url(client, msg, thumb_enc) + except Exception: + thumb_url = f"/thumb/{thumb_enc}" + + #----- Split parts share one quality entry via a common group key + group_key = f"manual:{primary['chat_id']}:{quality}:{secrets.token_hex(6)}" if is_split else None + + tv_extra = {} + if media_type == "tv": + try: + season_number = int(payload.get("season_number")) + episode_number = int(payload.get("episode_number")) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Season and episode numbers are required for TV.") + tv_extra = { + "season_number": season_number, + "episode_number": episode_number, + "episode_title": (payload.get("episode_title") or "").strip() or f"S{season_number:02d}E{episode_number:02d}", + "episode_backdrop": payload.get("episode_backdrop") or thumb_url or base.get("backdrop") or "", + "episode_overview": payload.get("episode_overview") or "", + "episode_released": payload.get("episode_released") or "", + } + elif thumb_url and not base.get("backdrop"): + base["backdrop"] = thumb_url + + for index, part in enumerate(resolved_parts, start=1): + p_channel = int(part["chat_id"]) + p_msg = int(part["msg_id"]) + encoded = await encode_string({"chat_id": p_channel, "msg_id": p_msg}) + metadata_info = dict(base) + metadata_info.update({ + "media_type": media_type, + "quality": quality, + "encoded_string": encoded, + "group_key": group_key, + "part_number": index if is_split else None, + "is_anime": False, + }) + metadata_info.update(tv_extra) + updated_id = await db.insert_media( + metadata_info, channel=p_channel, msg_id=p_msg, + size=part["size"], name=name, raw_size=int(part.get("raw_size") or 0), + ) + if not updated_id: + raise HTTPException(status_code=500, detail="Failed to add media (validation error).") + await stamp_caption_by_ref(client, p_channel, p_msg, metadata_info) + + result_tmdb_id = base["tmdb_id"] + location = await db.find_media_doc(media_type, result_tmdb_id) + result_db_index = location[1] if location else db.current_db_index + + #----- Assign to selected custom catalogs before triggering auto sync, so any + #----- exclusivity is stamped on the doc first and auto sync correctly skips it. + #----- Guarded on `location` so we never add a reference to a non-existent doc. + catalog_ids = payload.get("catalog_ids") or [] + catalogs_added = [] + if location: + for cat_id in catalog_ids: + try: + cat_id = str(cat_id).strip() + if not cat_id: + continue + added = await db.add_item_to_custom_catalog(cat_id, int(result_tmdb_id), int(result_db_index), media_type) + if added: + catalog = await db.get_custom_catalog(cat_id) + if catalog: + catalogs_added.append(catalog.get("name", cat_id)) + cat_vis = catalog.get("visibility") + if cat_vis in ("owner", "tokens"): + await db.set_media_visibility( + int(result_tmdb_id), int(result_db_index), media_type, + cat_vis, catalog.get("allowed_tokens") or [] + ) + if catalog.get("exclusive"): + await db.mark_item_exclusive( + cat_id, int(result_tmdb_id), int(result_db_index), + media_type, catalog.get("searchable", False) + ) + except Exception: + pass + + if result_tmdb_id and result_tmdb_id > 0: + try: + start_single_media_catalog_sync(db, tmdb_id=result_tmdb_id, media_type=media_type) + except Exception: + pass + + message = f"Split stream added ({len(resolved_parts)} parts)." if is_split else "Stream added successfully." + if catalogs_added: + message += f" Added to: {', '.join(catalogs_added)}." + return { + "status": "success", + "message": message, + "tmdb_id": result_tmdb_id, + "db_index": result_db_index, + "media_type": media_type, + } + +#----- Custom catalog APIs def _normalize_media_type(media_type: str) -> str: return "tv" if media_type in ["tv", "series"] else "movie" async def list_custom_catalogs_api( - tmdb_id: int | None = None, + tmdb_id: str | int | None = None, db_index: int | None = None, media_type: str | None = None, ): try: - catalogs = await db.get_custom_catalogs() - if tmdb_id is not None and db_index is not None and media_type: + check_current = tmdb_id is not None and db_index is not None and bool(media_type) + catalogs = await db.get_custom_catalogs(item_fields=("tmdb_id", "db_index", "media_type") if check_current else ()) + if check_current: normalized_type = _normalize_media_type(media_type) for catalog in catalogs: catalog["contains_current"] = any( @@ -845,18 +1432,47 @@ async def list_custom_catalogs_api( and item.get("media_type") == normalized_type for item in catalog.get("items", []) or [] ) + for catalog in catalogs: + catalog.pop("items", None) return {"catalogs": catalogs} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) +async def list_manual_add_catalogs_api(): + try: + catalogs = await db.get_custom_catalogs(slim=True) + filtered = [c for c in catalogs if not c.get("auto")] + filtered.sort(key=lambda c: (0 if c.get("exclusive") else 1, (c.get("name") or "").lower())) + return {"catalogs": [ + {"_id": c["_id"], "name": c["name"], "exclusive": bool(c.get("exclusive")), + "visibility": c.get("visibility", "public")} + for c in filtered + ]} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +_VISIBILITY_MODES = ("public", "tokens", "owner") + + +#----- Parse a (visibility, allowed_tokens) pair from a request payload +def _clean_visibility(payload: dict): + visibility = payload.get("visibility") + if visibility not in _VISIBILITY_MODES: + visibility = None + tokens = payload.get("allowed_tokens") + tokens = [str(t).strip() for t in tokens if str(t).strip()] if isinstance(tokens, list) else [] + return visibility, tokens + + async def create_custom_catalog_api(payload: dict): name = (payload.get("name") or "").strip() - visible = bool(payload.get("visible", True)) if not name: raise HTTPException(status_code=400, detail="Catalog name is required.") - catalog_id = await db.create_custom_catalog(name=name, visible=visible) + visibility, tokens = _clean_visibility(payload) + catalog_id = await db.create_custom_catalog(name=name, visibility=visibility or "public", allowed_tokens=tokens) if not catalog_id: raise HTTPException(status_code=500, detail="Failed to create catalog.") @@ -866,8 +1482,14 @@ async def create_custom_catalog_api(payload: dict): async def update_custom_catalog_api(catalog_id: str, payload: dict): name = payload.get("name") - visible = payload.get("visible") if "visible" in payload else None - result = await db.update_custom_catalog(catalog_id, name=name, visible=visible) + visibility, tokens = _clean_visibility(payload) + exclusive = payload.get("exclusive") + exclusive = bool(exclusive) if exclusive is not None else None + searchable = bool(payload.get("searchable")) + result = await db.update_custom_catalog( + catalog_id, name=name, visibility=visibility, allowed_tokens=tokens, + exclusive=exclusive, searchable=searchable, + ) if not result: catalog = await db.get_custom_catalog(catalog_id) if not catalog: @@ -875,6 +1497,35 @@ async def update_custom_catalog_api(catalog_id: str, payload: dict): return {"message": "Catalog updated successfully.", "catalog": await db.get_custom_catalog(catalog_id)} +#----- Set a title's visibility across every catalog it belongs to (used by media edit) +async def set_media_visibility_api(payload: dict): + tmdb_id = payload.get("tmdb_id") + db_index = payload.get("db_index") + media_type = payload.get("media_type") + if not tmdb_id or not db_index or media_type not in ("movie", "tv", "series"): + raise HTTPException(status_code=400, detail="tmdb_id, db_index and media_type are required.") + + visibility, tokens = _clean_visibility(payload) + if not visibility: + raise HTTPException(status_code=400, detail="A valid visibility is required.") + + count = await db.set_media_visibility( + int(tmdb_id), int(db_index), _normalize_media_type(media_type), visibility, tokens + ) + return { + "status": "success", + "updated_catalogs": count, + "message": "Visibility updated — applies to default catalogs and every catalog this title is in.", + } + + +#----- Current effective visibility of a title (from the catalogs it belongs to) +async def get_media_visibility_api(tmdb_id: str | int, db_index: int, media_type: str): + tmdb_id = _require_tmdb_id(tmdb_id) + data = await db.get_media_visibility(int(tmdb_id), int(db_index), _normalize_media_type(media_type)) + return {"visibility": data or {}} + + async def delete_custom_catalog_api(catalog_id: str): result = await db.delete_custom_catalog(catalog_id) if not result: @@ -892,6 +1543,7 @@ async def get_custom_catalog_items_api( data = await db.get_custom_catalog_items(catalog_id, media_type, page, page_size) if not data.get("catalog"): raise HTTPException(status_code=404, detail="Catalog not found.") + _resolve_covers(data.get("items")) return data except HTTPException: raise @@ -910,8 +1562,8 @@ async def search_catalog_media_api( return {"results": [], "total_count": 0} try: - result = await db.search_documents(query, page, page_size) normalized_type = _normalize_media_type(media_type) + result = await db.search_documents(query, page, page_size, media_type=normalized_type) filtered = [item for item in result.get("results", []) if item.get("media_type") == normalized_type] return {"results": filtered, "total_count": len(filtered)} except Exception as e: @@ -935,16 +1587,28 @@ async def add_custom_catalog_item_api(catalog_id: str, payload: dict): raise HTTPException(status_code=404, detail="Catalog not found.") added = await db.add_item_to_custom_catalog(catalog_id, int(tmdb_id), int(db_index), media_type) + visibility_synced = None + if added: + #----- Adding to a hidden/restricted catalog adopts that visibility onto the title + cat_vis = catalog.get("visibility") + if cat_vis in ("owner", "tokens"): + await db.set_media_visibility( + int(tmdb_id), int(db_index), media_type, cat_vis, catalog.get("allowed_tokens") or [] + ) + visibility_synced = cat_vis + if catalog.get("exclusive"): + await db.mark_item_exclusive(catalog_id, int(tmdb_id), int(db_index), media_type, catalog.get("searchable", False)) message = "Added to catalog." if added else "Already exists in this catalog." - return {"message": message, "added": added} + return {"message": message, "added": added, "visibility_synced": visibility_synced} async def remove_custom_catalog_item_api( catalog_id: str, - tmdb_id: int, + tmdb_id: str | int, db_index: int, media_type: str, ): + tmdb_id = _require_tmdb_id(tmdb_id) catalog = await db.get_custom_catalog(catalog_id) if not catalog: raise HTTPException(status_code=404, detail="Catalog not found.") @@ -954,12 +1618,14 @@ async def remove_custom_catalog_item_api( ) if not removed: return {"message": "Item was not in this catalog.", "removed": False} + if catalog.get("exclusive"): + await db.clear_item_exclusive(int(tmdb_id), int(db_index), _normalize_media_type(media_type)) return {"message": "Removed from catalog.", "removed": True} -async def auto_sync_custom_catalogs_api(full_rebuild: bool = False): +async def auto_sync_custom_catalogs_api(force_refresh: bool = False): try: - result = await start_auto_catalog_sync_background(db, force=True, full_rebuild=full_rebuild) + result = await start_auto_catalog_sync_background(db, force=True, force_refresh=force_refresh) return {"message": result.get("message", "Auto sync started."), "result": result} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @@ -992,47 +1658,210 @@ async def update_auto_catalog_settings_api(payload: dict): raise HTTPException(status_code=500, detail=str(e)) +_DEFAULT_CATALOG_ENTRIES = [ + {"id": "latest_movies", "name": "Recently Added Movies", "group": "Default Movies", "type": "movie"}, + {"id": "top_movies", "name": "Popular Movies", "group": "Default Movies", "type": "movie"}, + {"id": "latest_series", "name": "Recently Added Series", "group": "Default TV", "type": "series"}, + {"id": "top_series", "name": "Popular Series", "group": "Default TV", "type": "series"}, + {"id": "trending_movies", "name": "Trending Movies", "group": "Default Movies", "type": "movie"}, + {"id": "trending_series", "name": "Trending Series", "group": "Default TV", "type": "series"}, +] -# ───────────────────────────────────────────────────────────────────────────── -# Settings API -# ───────────────────────────────────────────────────────────────────────────── +async def get_catalog_order_api(): + try: + catalogs = await db.get_custom_catalogs(slim=True) + entries = [dict(e) for e in _DEFAULT_CATALOG_ENTRIES] + for c in catalogs: + items = c.get("items") or [] + cid = f"custom_{c['_id']}" + name = c.get("name") or "Catalog" + group = "Auto" if c.get("auto") else "Custom" + has_movie = any(i.get("media_type") == "movie" for i in items) + has_series = any(i.get("media_type") == "tv" for i in items) + if has_movie or not items: + entries.append({"id": cid, "name": name, "group": group, "type": "movie"}) + if has_series: + entries.append({"id": cid, "name": name, "group": group, "type": "series"}) + for e in entries: + e["key"] = f"{e['id']}::{e['type']}" + order = await db.get_catalog_order() + rank = {k: i for i, k in enumerate(order)} + entries.sort(key=lambda e: rank.get(e["key"], rank.get(e["id"], len(order) + 1))) + hidden = set(await db.get_hidden_catalogs()) + for e in entries: + e["hidden"] = e["key"] in hidden + return {"entries": entries, "order": order} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) -async def get_settings_api() -> dict: - data = SettingsManager.current().to_dict() - # Never expose the raw password — let the UI know whether one is set - data["admin_password_set"] = bool(data.get("admin_password")) - data["admin_password"] = "" +async def update_catalog_order_api(payload: dict): + order = payload.get("order") + if not isinstance(order, list): + raise HTTPException(status_code=400, detail="order must be a list.") + await db.save_catalog_order(order) + if isinstance(payload.get("hidden"), list): + await db.save_hidden_catalogs(payload["hidden"]) + return {"ok": True, "message": "Catalog order saved."} + +async def get_user_activity_api(page: int = 1, per_page: int = 5): try: - data["database_list"] = db.get_database_list() + return await get_activity_overview(page, per_page) except Exception as e: - LOGGER.error(f"get_settings_api: could not load database list: {e}") - data["database_list"] = [] + raise HTTPException(status_code=500, detail=str(e)) - return {"settings": data} + +async def session_send_code_api(payload: dict): + try: + return await start_login(payload.get("phone")) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +async def session_verify_code_api(payload: dict): + try: + return await submit_code(payload.get("login_id"), payload.get("code")) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +async def session_verify_password_api(payload: dict): + try: + return await submit_password(payload.get("login_id"), payload.get("password")) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +async def session_status_api(): + return await get_session_status() + + +async def session_disconnect_api(): + return await disconnect_session() + + +async def session_reconnect_api(): + try: + return await reconnect_session() + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + +async def session_remove_api(): + return await remove_session() + + + + +# ───────────────────────────────────────────────────────────────────────────── +# Settings API +# ───────────────────────────────────────────────────────────────────────────── + +async def get_settings_api() -> dict: + + data = SettingsManager.current().to_dict() + data["admin_password_set"] = bool(data.get("admin_password")) + data["admin_password"] = "" + data["session_secret_set"] = bool(data.get("session_secret")) + data["session_secret"] = "" + + try: + data["database_list"] = db.get_database_list() + except Exception as e: + LOGGER.error(f"get_settings_api: could not load database list: {e}") + data["database_list"] = [] + + active = SettingsManager._all_channel_ids(data) + titles = data.get("channel_titles") or {} + if not isinstance(titles, dict): + titles = {} + titles = {str(k): str(v) for k, v in titles.items() if str(k) in active and v} + missing = [cid for cid in active if cid not in titles] + if missing: + full = SettingsManager.current().to_dict() + await SettingsManager._sync_channel_titles(full) + try: + await db.save_settings(full) + SettingsManager._current = SettingsManager.current().__class__(full) + except Exception as e: + LOGGER.warning(f"get_settings_api: could not persist channel titles: {e}") + titles = full.get("channel_titles") or {} + data["channel_titles"] = {str(k): str(v) for k, v in (titles or {}).items() if k and v} + + return {"settings": data} async def update_settings_api(payload: dict) -> dict: - # Empty password string → don't change it + #----- Empty password string means leave it unchanged if "admin_password" in payload and not str(payload["admin_password"]).strip(): del payload["admin_password"] + if "session_secret" in payload and not str(payload["session_secret"]).strip(): + del payload["session_secret"] - # ── Type coercion & validation ──────────────────────────────────────────── - bool_keys = {"replace_mode", "hide_catalog", "subscription", "show_proxy_and_non_proxy_both"} + #----- Type coercion and validation + bool_keys = {"replace_mode", "duplicate_protection", "hide_catalog", "subscription", "show_proxy_and_non_proxy_both", "mediaflow_proxy", "announce_new_content", "delete_on_metadata_fail", "better_poster_enabled", "rpdb_enabled", "spatial_poster_enabled", "fanart_enabled", "fanart_shuffle", "fanart_low_res_poster"} for key in bool_keys: if key in payload: payload[key] = bool(payload[key]) - list_str_keys = {"auth_channels", "multi_tokens", "extra_databases", "global_search_channels", "anime_channels"} + list_str_keys = {"auth_channels", "multi_tokens", "helper_tokens", "extra_databases", "global_search_channels", "anime_channels", "manual_channels"} for key in list_str_keys: if key in payload: if not isinstance(payload[key], list): raise HTTPException(status_code=400, detail=f"'{key}' must be a list.") payload[key] = [str(v).strip() for v in payload[key] if str(v).strip()] + if "better_poster" in payload: + payload["better_poster"] = str(payload["better_poster"] or "").strip() + if payload["better_poster"] and "{imdb_id}" not in payload["better_poster"]: + raise HTTPException(status_code=400, detail="wrong betterposter url") + + if "spatial_poster" in payload: + payload["spatial_poster"] = str(payload["spatial_poster"] or "").strip() + if payload["spatial_poster"] and "{imdb_id}" not in payload["spatial_poster"]: + raise HTTPException(status_code=400, detail="SpatialPosters URL must contain {imdb_id}") + + if payload.get("spatial_poster_enabled") and not payload.get("spatial_poster"): + raise HTTPException(status_code=400, detail="SpatialPosters URL is required") + + if "stream_formatter" in payload: + from Backend.helper.stream_formatter import PRESETS + if payload["stream_formatter"] not in ("default", "custom", *PRESETS): + raise HTTPException(status_code=400, detail="Unknown stream formatter") + for key in ("formatter_name", "formatter_description"): + if key in payload: + payload[key] = str(payload[key] or "")[:20000] + + if "default_streaming" in payload and payload["default_streaming"] not in ("bots", "userbot"): + raise HTTPException(status_code=400, detail="default_streaming must be 'bots' or 'userbot'") + + if "rpdb_api_key" in payload: + payload["rpdb_api_key"] = str(payload["rpdb_api_key"] or "").strip() + + if "fanart_api_key" in payload: + payload["fanart_api_key"] = str(payload["fanart_api_key"] or "").strip() + + if "fanart_shuffle_interval" in payload: + try: + payload["fanart_shuffle_interval"] = max(0, int(payload["fanart_shuffle_interval"])) + except (ValueError, TypeError): + payload["fanart_shuffle_interval"] = 5 + + if len([k for k in ("better_poster_enabled", "rpdb_enabled", "spatial_poster_enabled", "fanart_enabled") if payload.get(k)]) > 1: + raise HTTPException(status_code=400, detail="Enable only one poster provider at a time") + + if payload.get("fanart_enabled") and not str(payload.get("fanart_api_key") or "").strip(): + raise HTTPException(status_code=400, detail="Fanart.tv API key is required") + if "extra_databases" in payload: for uri in payload["extra_databases"]: if not uri.startswith(("mongodb://", "mongodb+srv://")): @@ -1054,43 +1883,107 @@ async def update_settings_api(payload: dict) -> dict: payload["subscription_group_id"] = int(payload["subscription_group_id"]) except (ValueError, TypeError): raise HTTPException(status_code=400, detail="'subscription_group_id' must be an integer.") + def _validate_channel_id(channel: str, field: str) -> str: + channel = str(channel).strip() + if not channel: + return "" + if not channel.startswith("-100") or not channel[4:].isdigit() or len(channel) < 8: + raise HTTPException( + status_code=400, + detail=f"Invalid {field}: '{channel}'. Only channel IDs in -100xxxxxxxxxx format are accepted (channels only, no groups/users/bots)." + ) + return channel + + if "auth_channels" in payload: + cleaned = [] + for channel in payload["auth_channels"]: + c = _validate_channel_id(channel, "auth channel") + if c: + cleaned.append(c) + payload["auth_channels"] = cleaned + if "global_search_channels" in payload: cleaned = [] for channel in payload["global_search_channels"]: - channel = str(channel).strip() - if not channel: - continue - try: - int(channel) - except ValueError: - raise HTTPException(status_code=400, - detail=f"Invalid channel id: {channel}" - ) - cleaned.append(channel) + c = _validate_channel_id(channel, "global search channel") + if c: + cleaned.append(c) payload["global_search_channels"] = cleaned if "anime_channels" in payload: cleaned = [] for channel in payload["anime_channels"]: - channel = str(channel).strip() - if not channel: - continue - try: - int(channel.replace("-100", "")) - except ValueError: - raise HTTPException(status_code=400, - detail=f"Invalid anime channel id: {channel}" - ) - cleaned.append(channel) + c = _validate_channel_id(channel, "anime channel") + if c: + cleaned.append(c) payload["anime_channels"] = cleaned - # Strip whitespace from string fields + if "manual_channels" in payload: + cleaned = [] + for channel in payload["manual_channels"]: + c = _validate_channel_id(channel, "manual channel") + if c: + cleaned.append(c) + payload["manual_channels"] = cleaned + + if "announcement_channel" in payload and payload["announcement_channel"]: + payload["announcement_channel"] = _validate_channel_id( + payload["announcement_channel"], "announcement channel" + ) + + if "skip_channel" in payload and payload["skip_channel"]: + payload["skip_channel"] = _validate_channel_id( + payload["skip_channel"], "skip channel" + ) + + #----- The same channel id may not appear in more than one channel field. + #----- Only AUTH ∩ ANIME is allowed, because an anime channel is an auth channel + #----- that's flagged as anime (the receiver only indexes files from auth channels). + _channel_fields = ("auth_channels", "manual_channels", "global_search_channels", + "anime_channels", "announcement_channel", "skip_channel") + if any(field in payload for field in _channel_fields): + current = SettingsManager.current() + + def _norm_ids(values) -> set: + if isinstance(values, str): + values = [values] + return {str(c).strip().replace("-100", "") for c in (values or []) if str(c).strip()} + + groups = { + "AUTH": _norm_ids(payload.get("auth_channels", list(current.auth_channels))), + "MANUAL": _norm_ids(payload.get("manual_channels", list(current.manual_channels))), + "GLOBAL SEARCH": _norm_ids(payload.get("global_search_channels", list(current.global_search_channels))), + "ANIME": _norm_ids(payload.get("anime_channels", list(current.anime_channels))), + "ANNOUNCEMENT": _norm_ids(payload.get("announcement_channel", current.announcement_channel)), + "SKIP": _norm_ids(payload.get("skip_channel", current.skip_channel)), + } + + allowed_overlap = frozenset({"AUTH", "ANIME"}) + names = list(groups) + for i in range(len(names)): + for j in range(i + 1, len(names)): + a, b = names[i], names[j] + if frozenset({a, b}) == allowed_overlap: + continue + clash = groups[a] & groups[b] + if clash: + raise HTTPException( + status_code=400, + detail=f"Channel {', '.join(sorted(clash))} can't be in both {a} and {b} channels — each channel may only belong to one field." + ) + + #----- Strip whitespace from string fields for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch", - "admin_username", "admin_password", "http_proxy_url", - "payment_instructions", "payment_qr_url"): + "admin_username", "admin_password", "session_secret", "http_proxy_url", + "cf_stream_url", "cf_stream_secret", "cf_stream_mode", + "mediaflow_password", "payment_instructions", "payment_qr_url", + "announcement_channel", "skip_channel"): if key in payload and isinstance(payload[key], str): payload[key] = payload[key].strip() + if payload.get("admin_password"): + payload["admin_password"] = hash_password(payload["admin_password"]) + try: reinit_results = await SettingsManager.update(db, payload) return { @@ -1098,23 +1991,17 @@ async def update_settings_api(payload: dict) -> dict: "reinit": reinit_results, } except ValueError as exc: - # Raised by db.reload_extra_databases() for unsafe/invalid DB changes raise HTTPException(status_code=400, detail=str(exc)) except Exception as exc: raise HTTPException(status_code=500, detail=str(exc)) - # ───────────────────────────────────────────────────────────────────────────── -# Tools — WebUI replacement for /scan, /rescan, /scanstatus, /cancelscan, -# /dbcheck. All driven from the Tools page; no bot commands remain. +# Tools — WebUI replacement for /scan, /rescan, /scanstatus, /cancelscan, /dbcheck # ───────────────────────────────────────────────────────────────────────────── +#----- Pick a Telegram client capable of fetching channel messages def _scan_client(): - """Pick a Telegram client capable of fetching channel messages. - - Prefer the primary StreamBot (it must be an admin in the AUTH channels to - index them); fall back to any connected client.""" if StreamBot is not None: return StreamBot if multi_clients: @@ -1122,12 +2009,12 @@ def _scan_client(): return None +#----- Configured AUTH channels with friendly names for the picker async def get_tools_channels_api() -> dict: - """Return the configured AUTH channels with friendly names for the picker.""" channels = list(SettingsManager.current().auth_channels) client = _scan_client() - result = [] - for ch in channels: + + async def _resolve(ch): name = str(ch) try: if client is not None: @@ -1135,12 +2022,260 @@ async def get_tools_channels_api() -> dict: name = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(ch) except Exception as e: LOGGER.warning(f"[Tools] Could not resolve channel {ch}: {e}") - result.append({"id": str(ch), "name": name}) - return {"status": "success", "data": result} + return {"id": str(ch), "name": name} + + return {"status": "success", "data": await asyncio.gather(*(_resolve(ch) for ch in channels))} + + +#----- ── Manual upload session (web replacement for the /set bot command) ── + +#----- Personal (hand-made) titles get a negative synthetic tmdb_id; real ones are positive +def _is_personal_media(tmdb_id) -> bool: + try: + return int(tmdb_id) < 0 + except (TypeError, ValueError): + return False + + +#----- Normalize a media document into a compact session-picker result +def _session_result(doc: dict) -> dict: + mt = doc.get("media_type") or doc.get("type") or "movie" + mt = "tv" if str(mt).lower() in ("tv", "series") else "movie" + imdb_id = doc.get("imdb_id") or "" + tmdb_id = doc.get("tmdb_id") + selected_id = imdb_id if str(imdb_id).startswith("tt") else (str(tmdb_id) if tmdb_id is not None else "") + return { + "tmdb_id": tmdb_id, + "db_index": doc.get("db_index"), + "media_type": mt, + "title": doc.get("title") or "", + "year": doc.get("release_year") or "", + "poster": resolve_cover_url(doc.get("poster") or ""), + "imdb_id": imdb_id, + "selected_id": selected_id, + "is_personal": _is_personal_media(tmdb_id), + "in_library": True, + } + + +#----- Search the library, then IMDb/Cinemeta + TMDB, by title or an id/link +async def search_manual_session_api(query: str) -> dict: + query = (query or "").strip() + if not query: + return {"results": []} + + results: list[dict] = [] + seen: set = set() + + def _add(doc: dict) -> None: + entry = _session_result(doc) + key = (entry["tmdb_id"], entry["db_index"], entry["media_type"]) + if entry["tmdb_id"] is None or key in seen: + return + seen.add(key) + results.append(entry) + + default_id = extract_default_id(query) + if default_id: + try: + if str(default_id).startswith("tt"): + doc = await db.get_media_details(default_id) + if doc: + _add(doc) + else: + for mt in ("movie", "tv"): + location = await db.find_media_doc(mt, int(default_id)) + if location: + found, db_index = location + found["media_type"] = mt + found["db_index"] = db_index + _add(found) + except Exception as e: + LOGGER.warning(f"[Manual Session] id lookup failed for '{query}': {e}") + + if not default_id: + try: + data = await db.search_documents(query, 1, 20) + for doc in data.get("results", []): + _add(doc) + except Exception as e: + LOGGER.warning(f"[Manual Session] library search failed for '{query}': {e}") + + library_ids = {(e.get("imdb_id") or "", str(e.get("tmdb_id") or "")) for e in results} + try: + online = await search_any_candidates(query) + except Exception as e: + LOGGER.warning(f"[Manual Session] online search failed for '{query}': {e}") + online = [] + + for cand in online: + if not cand.get("selected_id") or not cand.get("title"): + continue + imdb_id = cand.get("imdb_id") or "" + tmdb_id = cand.get("tmdb_id") + if (imdb_id, str(tmdb_id or "")) in library_ids: + continue + results.append({ + "tmdb_id": tmdb_id, + "db_index": None, + "media_type": "tv" if cand.get("media_type") == "tv" else "movie", + "title": cand.get("title") or "", + "year": cand.get("year") or "", + "poster": resolve_cover_url(cand.get("poster") or ""), + "imdb_id": imdb_id, + "selected_id": str(cand.get("selected_id")), + "source": cand.get("source"), + "is_personal": False, + "in_library": False, + }) + + return {"results": results} +#----- Current active manual upload session (or None) +async def get_manual_session_api() -> dict: + return {"session": getattr(Backend, "MANUAL_SESSION", None)} + + +async def _set_online_manual_session(payload: dict, media_type: str, selected_id: str) -> dict: + if not selected_id: + raise HTTPException(status_code=400, detail="A library title or a selected id is required.") + + meta = await ( + fetch_selected_movie_metadata(selected_id) if media_type == "movie" + else fetch_selected_tv_metadata(selected_id) + ) + if not meta: + raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.") + + imdb_id = meta.get("imdb_id") or "" + default_id = imdb_id if str(imdb_id).startswith("tt") else selected_id + + season = payload.get("season") + if media_type == "tv" and season is not None and str(season).strip() != "": + try: + season = int(season) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Season must be a number.") + else: + season = None + + try: + display_tmdb = int(meta.get("tmdb_id")) if meta.get("tmdb_id") is not None else 0 + except (TypeError, ValueError): + display_tmdb = 0 + + session = { + "tmdb_id": display_tmdb, + "db_index": None, + "media_type": media_type, + "title": meta.get("title") or "", + "year": meta.get("release_year") or "", + "is_personal": False, + "kind": "real", + "default_id": default_id, + "season": season, + "episode": None, + "quality": None, + } + Backend.MANUAL_SESSION = session + return {"status": "success", "session": session} + + +#----- Activate a manual upload session targeting an existing library title. +#----- Real (TMDB/IMDb) titles parse season/episode/quality from each file; personal +#----- (hand-made) titles need a season for TV since their files carry no metadata. +async def set_manual_session_api(payload: dict) -> dict: + tmdb_id = payload.get("tmdb_id") + db_index = payload.get("db_index") + media_type = _normalize_media_type(payload.get("media_type", "movie")) + selected_id = str(payload.get("selected_id") or "").strip() + in_library = payload.get("in_library", True) and tmdb_id is not None and db_index is not None + + if not in_library: + return await _set_online_manual_session(payload, media_type, selected_id) + + doc = await db.get_document(media_type, int(tmdb_id), int(db_index)) + if not doc: + raise HTTPException(status_code=404, detail="That title was not found in your library.") + + is_personal = _is_personal_media(tmdb_id) + session = { + "tmdb_id": int(tmdb_id), + "db_index": int(db_index), + "media_type": media_type, + "title": doc.get("title") or "", + "year": doc.get("release_year") or "", + "is_personal": is_personal, + } + + if is_personal: + #----- Personal: files have no usable metadata, so season/episode come from here + season = payload.get("season") + episode = payload.get("episode") + quality = str(payload.get("quality") or "").strip() + + if media_type == "tv": + if season is None or str(season).strip() == "": + raise HTTPException(status_code=400, detail="A season number is required for personal TV shows.") + try: + season = int(season) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Season must be a number.") + if episode is not None and str(episode).strip() != "": + try: + episode = int(episode) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Episode must be a number.") + else: + episode = None + else: + season = None + episode = None + + session.update({ + "kind": "personal", + "default_id": None, + "season": season, + "episode": episode, + "quality": quality or None, + }) + else: + #----- Real: force the title's own id and let metadata() parse from each file. + #----- An optional season is only used as a fallback for files that carry an + #----- episode but no season (e.g. absolute-numbered anime). + imdb_id = doc.get("imdb_id") or "" + default_id = imdb_id if str(imdb_id).startswith("tt") else str(int(tmdb_id)) + + season = payload.get("season") + if media_type == "tv" and season is not None and str(season).strip() != "": + try: + season = int(season) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail="Season must be a number.") + else: + season = None + + session.update({ + "kind": "real", + "default_id": default_id, + "season": season, + "episode": None, + "quality": None, + }) + + Backend.MANUAL_SESSION = session + return {"status": "success", "session": session} + + +#----- Clear the active manual upload session +async def clear_manual_session_api() -> dict: + Backend.MANUAL_SESSION = None + return {"status": "success"} + + +#----- Start a scan or rescan job over the given channels async def start_scan_api(payload: dict) -> dict: - from Backend.helper.scan_manager import scan_manager client = _scan_client() if client is None: raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") @@ -1159,18 +2294,15 @@ async def start_scan_api(payload: dict) -> dict: async def cancel_scan_api() -> dict: - from Backend.helper.scan_manager import scan_manager result = await scan_manager.cancel() return {"status": "success" if result.get("ok") else "error", **result} async def scan_status_api() -> dict: - from Backend.helper.scan_manager import scan_manager return {"status": "success", "data": scan_manager.get_status()} async def start_dbcheck_api() -> dict: - from Backend.helper.scan_manager import dbcheck_manager client = _scan_client() if client is None: raise HTTPException(status_code=503, detail="No Telegram client is connected yet.") @@ -1181,26 +2313,44 @@ async def start_dbcheck_api() -> dict: async def cancel_dbcheck_api() -> dict: - from Backend.helper.scan_manager import dbcheck_manager result = await dbcheck_manager.cancel() return {"status": "success" if result.get("ok") else "error", **result} async def dbcheck_status_api() -> dict: - from Backend.helper.scan_manager import dbcheck_manager return {"status": "success", "data": dbcheck_manager.get_status()} +#----- ── Duplicate check & cleanup ── +async def start_duplicate_check_api() -> dict: + result = await duplicate_manager.start() + if not result.get("ok"): + raise HTTPException(status_code=409, detail=result.get("message", "Could not start duplicate scan.")) + return {"status": "success", **result} + + +async def cancel_duplicate_check_api() -> dict: + result = await duplicate_manager.cancel() + return {"status": "success" if result.get("ok") else "error", **result} + + +async def duplicate_check_status_api() -> dict: + return {"status": "success", "data": duplicate_manager.get_status()} + + +#----- Remove selected duplicate streams, or (delete_all) keep the newest per group +async def purge_duplicates_api(payload: dict | None = None) -> dict: + payload = payload or {} + delete_all = bool(payload.get("delete_all")) + stream_ids = payload.get("stream_ids") + if not delete_all and (not isinstance(stream_ids, list) or not stream_ids): + raise HTTPException(status_code=400, detail="Provide 'stream_ids' or set 'delete_all'.") + result = await duplicate_manager.purge(stream_ids, delete_all=delete_all) + return {"status": "success" if result.get("ok") else "error", **result} + + +#----- Purge dead links (from last dbcheck, flagged in DB, or a specific set) async def purge_dead_links_api(payload: dict | None = None) -> dict: - """Purge dead links. - - - With no body (or {"source": "dbcheck"}): purge the dead entries found by - the most recent DB check. - - {"source": "flagged"}: purge every entry flagged is_dead in the DB - (these come from the background Dead-Link Checker). - - {"stream_ids": [...]}: purge a specific set. - """ - from Backend.helper.scan_manager import dbcheck_manager payload = payload or {} source = str(payload.get("source", "dbcheck")).lower() stream_ids = payload.get("stream_ids") @@ -1218,3 +2368,518 @@ async def purge_dead_links_api(payload: dict | None = None) -> dict: result = await dbcheck_manager.purge() return {"status": "success" if result.get("ok") else "error", **result} + + + +#----- ── System & Maintenance (web replacements for /stats, /log, /restart) ── + +LOG_FILE = "log.txt" + + +#----- Aggregate content + system metrics across all storage DBs (was /stats) +async def get_db_stats_api() -> dict: + try: + total_movies = total_tv = total_episodes = total_streams = total_db_size = 0 + + for i in range(1, db.current_db_index + 1): + storage = db.dbs.get(f"storage_{i}") + if storage is None: + continue + + total_movies += await storage["movie"].count_documents({}) + async for movie in storage["movie"].find({}, {"telegram": 1}): + total_streams += len(movie.get("telegram", [])) + + total_tv += await storage["tv"].count_documents({}) + async for show in storage["tv"].find({}, {"seasons": 1}): + for season in show.get("seasons", []): + for episode in season.get("episodes", []): + total_episodes += 1 + total_streams += len(episode.get("telegram", [])) + + try: + total_db_size += (await storage.command("dbStats")).get("dataSize", 0) + except Exception: + pass + + return { + "status": "success", + "data": { + "version": __version__, + "movies": total_movies, + "tv_shows": total_tv, + "episodes": total_episodes, + "streams": total_streams, + "uptime": get_readable_time(int(time() - StartTime)), + "db_size": get_readable_file_size(total_db_size), + "storage_dbs": db.current_db_index, + "auth_channels": len(SettingsManager.current().auth_channels), + }, + } + except Exception as e: + LOGGER.error(f"[Stats] Error: {e}") + return {"status": "error", "message": str(e)} + + +#----- First-run setup checklist: what's configured vs still missing +async def setup_status_api() -> dict: + s = SettingsManager.current() + checks = [ + {"key": "tmdb", "label": "TMDB API key", "done": bool(s.tmdb_api), + "hint": "Powers automatic poster & metadata matching."}, + {"key": "tvdb", "label": "TVDB API key", "done": bool(s.tvdb_api), + "hint": "Improves TV show matching; used after TMDB / with anime pipelines."}, + {"key": "channels", "label": "AUTH channel added", "done": len(s.auth_channels) > 0, + "hint": "The channel(s) the bot indexes and streams from."}, + {"key": "base_url", "label": "Base URL set", "done": bool(s.base_url), + "hint": "Stremio uses this public address to reach your streams."}, + {"key": "password", "label": "Admin password changed", "done": not verify_password("admin", s.admin_password), + "hint": "Change the default admin / admin login for security."}, + ] + done = sum(1 for c in checks if c["done"]) + return {"status": "success", "data": { + "checks": checks, "done": done, "total": len(checks), "complete": done == len(checks), + }} + + +#----- Config backup export (settings minus secrets + catalogs, plans, tokens) +async def export_config_api() -> dict: + return await export_config() + + +#----- Config backup restore +async def import_config_api(payload: dict) -> dict: + try: + result = await import_config(payload) + return {"status": "success", "result": result, "message": "Backup restored successfully."} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + except Exception as e: + LOGGER.error(f"Config import error: {e}") + return {"status": "error", "message": str(e)} + + +#----- Lightweight liveness probe; start_time changes on every boot (restart detection) +async def health_api() -> dict: + return {"status": "ok", "start_time": StartTime, "version": __version__} + + +async def version_status_api(force: bool = False) -> dict: + from Backend.helper.version_check import check_upstream_version, get_version_status + if force: + await check_upstream_version(force=True) + return {"status": "success", "data": get_version_status()} + + +#----- Full diagnostics report (DBs, bot clients, TMDB, base URL) +async def health_report_api(force: bool = False) -> dict: + try: + return {"status": "success", "data": await run_health_checks(force=force)} + except Exception as e: + LOGGER.error(f"Health report error: {e}") + return {"status": "error", "message": str(e)} + + +#----- Tail of the log file for the web viewer (was /log) +async def get_logs_api(lines: int = 300) -> dict: + path = os.path.abspath(LOG_FILE) + if not os.path.exists(path): + return {"status": "error", "message": "Log file not found.", "log": ""} + try: + with open(path, "r", encoding="utf-8", errors="replace") as f: + tail = f.readlines()[-max(1, min(lines, 2000)):] + return {"status": "success", "log": "".join(tail)} + except Exception as e: + return {"status": "error", "message": str(e), "log": ""} + + +#----- Download the raw log file (was /log document) +async def download_logs_api(): + path = os.path.abspath(LOG_FILE) + if not os.path.exists(path): + raise HTTPException(status_code=404, detail="Log file not found.") + return FileResponse(path, filename="log.txt", media_type="text/plain") + + +#----- Run the updater then re-exec the app; runs after the HTTP response is flushed +async def _perform_restart(delay: float = 1.0) -> None: + await asyncio.sleep(delay) + try: + LOGGER.info("Web-triggered restart: running updater...") + proc = await asyncio.create_subprocess_exec("uv", "run", "update.py") + await proc.wait() + except Exception as e: + LOGGER.error(f"Restart updater failed: {e}") + + uv_path = shutil.which("uv") + if not uv_path: + LOGGER.error("Restart aborted: uv not found in PATH.") + return + LOGGER.info("Web-triggered restart: re-executing app...") + os.execl(uv_path, uv_path, "run", "-m", "Backend") + + +#----- Trigger a restart from the web (was /restart) +async def restart_app_api() -> dict: + asyncio.create_task(_perform_restart()) + return {"status": "success", "message": "Restart initiated — the server will be back shortly."} + + + +_bot_admin_apply_state: dict = { + "running": False, + "status": "idle", + "total": 0, + "done": 0, + "results": [], + "error": "", + "task": None, +} + + +def _norm_chat_id(ch): + s = str(ch).strip() + if not s: + return None + return int(s) if s.lstrip("-").isdigit() else s + + +async def _managed_bots() -> list[dict]: + bots: list[dict] = [] + for cid in sorted(multi_clients.keys()): + client = multi_clients.get(cid) + if client is None: + continue + me = getattr(client, "me", None) + if me is None: + try: + me = await client.get_me() + except Exception as e: + LOGGER.warning(f"[BotAdmin] Could not resolve bot client {cid}: {e}") + me = None + if not me: + continue + bots.append({ + "client_id": cid, + "user_id": me.id, + "username": me.username, + "name": me.first_name or me.username or f"Bot {cid + 1}", + "is_main": cid == 0, + }) + return bots + + +def _bot_served_channels() -> list[dict]: + s = SettingsManager.current() + order: list[str] = [] + mapping: dict[str, dict] = {} + + def add(ch, role): + nid = _norm_chat_id(ch) + if nid is None: + return + key = str(nid) + if key not in mapping: + mapping[key] = {"id": nid, "roles": []} + order.append(key) + if role not in mapping[key]["roles"]: + mapping[key]["roles"].append(role) + + for ch in s.auth_channels: + add(ch, "auth") + for ch in s.manual_channels: + add(ch, "manual") + for ch in s.anime_channels: + add(ch, "anime") + if s.announcement_channel: + add(s.announcement_channel, "announce") + if s.skip_channel: + add(s.skip_channel, "skip") + return [mapping[k] for k in order] + + +def _bot_admin_privileges() -> ChatPrivileges: + return ChatPrivileges( + can_manage_chat=True, + can_post_messages=True, + can_edit_messages=True, + can_delete_messages=True, + can_invite_users=True, + can_pin_messages=False, + can_promote_members=False, + can_change_info=False, + can_restrict_members=False, + can_manage_video_chats=False, + is_anonymous=False, + ) + + +def _no_privileges() -> ChatPrivileges: + return ChatPrivileges( + can_manage_chat=False, + can_post_messages=False, + can_edit_messages=False, + can_delete_messages=False, + can_invite_users=False, + can_pin_messages=False, + can_promote_members=False, + can_change_info=False, + can_restrict_members=False, + can_manage_video_chats=False, + is_anonymous=False, + ) + + +async def _bot_member_status(chat_id, bot_user_id) -> str: + try: + m = await botmod.Userbot.get_chat_member(chat_id, bot_user_id) + st = m.status + if st in (ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR): + return "admin" + if st == ChatMemberStatus.BANNED: + return "banned" + if st == ChatMemberStatus.RESTRICTED: + return "restricted" + if st == ChatMemberStatus.MEMBER: + return "member" + return "missing" + except Exception: + return "missing" + + +def _friendly_promote_error(exc) -> str: + msg = str(exc) + up = msg.upper() + if "CHAT_ADMIN_REQUIRED" in up: + return "Your session account isn't an admin with rights to do this here." + if "USER_CREATOR" in up or "ADMIN_RANK" in up: + return "Can't modify the channel creator." + if "ADD_ADMINS" in up or ("PROMOTE" in up and "RIGHT" in up): + return "Your session account can't grant these rights (it doesn't hold them itself)." + if "PARTICIPANT" in up or "USER_NOT_MUTUAL_CONTACT" in up: + return "The bot isn't in the channel and couldn't be added automatically." + if "BOTS_TOO_MUCH" in up: + return "This channel already has the maximum number of bots." + return msg + + +async def _session_rights(chat_id) -> dict: + try: + me = await botmod.Userbot.get_chat_member(chat_id, "me") + except Exception as e: + return {"manageable": False, "status": "unknown", "reason": f"Couldn't check your rights: {e}"} + st = me.status + if st == ChatMemberStatus.OWNER: + return {"manageable": True, "status": "owner", "reason": ""} + if st == ChatMemberStatus.ADMINISTRATOR: + can_promote = bool(getattr(me, "privileges", None) and me.privileges.can_promote_members) + return { + "manageable": can_promote, + "status": "admin_can_promote" if can_promote else "admin_no_promote", + "reason": "" if can_promote else "You're an admin here but without the 'Add New Admins' permission.", + } + return {"manageable": False, "status": "not_admin", "reason": "Your session account is not an admin here."} + + +async def bot_admin_scan_api() -> dict: + if botmod.Userbot is None: + return {"status": "error", "reason": "no_session", + "message": "Connect your Telegram session from the Settings page to manage channel admins."} + + bots = await _managed_bots() + if len(bots) <= 1: + return {"status": "error", "reason": "single_token", "bots": bots, + "message": "Add at least one extra bot token (multi-token) to use this tool."} + + channels = _bot_served_channels() + managed_ids = {b["user_id"] for b in bots} + out: list[dict] = [] + + for ch in channels: + cid = ch["id"] + entry = { + "id": str(cid), "roles": ch["roles"], "name": str(cid), + "accessible": False, "manageable": False, "session_status": "", + "reason": "", "bots": {}, "orphans": [], + } + + try: + chat = await botmod.Userbot.get_chat(cid) + entry["name"] = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(cid) + entry["accessible"] = True + except Exception as e: + entry["reason"] = f"Session account can't access this channel: {e}" + out.append(entry) + continue + + rights = await _session_rights(cid) + entry["manageable"] = rights["manageable"] + entry["session_status"] = rights["status"] + entry["reason"] = rights["reason"] + + for b in bots: + entry["bots"][str(b["user_id"])] = await _bot_member_status(cid, b["user_id"]) + + try: + async for m in botmod.Userbot.get_chat_members(cid, filter=ChatMembersFilter.ADMINISTRATORS): + u = getattr(m, "user", None) + if u and getattr(u, "is_bot", False) and u.id not in managed_ids: + entry["orphans"].append({ + "user_id": u.id, "username": u.username, + "name": u.first_name or u.username or str(u.id), + }) + except Exception as e: + LOGGER.warning(f"[BotAdmin] Could not list admins for {cid}: {e}") + + out.append(entry) + + return {"status": "success", "data": {"bots": bots, "channels": out}} + + +async def _promote_one(chat_id, bot: dict, privileges: ChatPrivileges, _retry: bool = True) -> dict: + label = bot.get("name") or (f"@{bot['username']}" if bot.get("username") else str(bot["user_id"])) + bid = bot["user_id"] + + if await _bot_member_status(chat_id, bid) == "admin": + return {"bot": label, "user_id": bid, "status": "already", "message": "Already an admin."} + + try: + await botmod.Userbot.promote_chat_member(chat_id, bid, privileges=privileges) + return {"bot": label, "user_id": bid, "status": "added", "message": "Promoted to admin."} + except FloodWait as fw: + wait = int(getattr(fw, "value", getattr(fw, "x", 5)) or 5) + if _retry: + await asyncio.sleep(wait + 1) + return await _promote_one(chat_id, bot, privileges, _retry=False) + return {"bot": label, "user_id": bid, "status": "error", + "message": f"Rate-limited by Telegram (wait {wait}s) — try again."} + except Exception as e: + up = str(e).upper() + if _retry and ("PARTICIPANT" in up or "USER_NOT_MUTUAL_CONTACT" in up): + try: + await botmod.Userbot.add_chat_members(chat_id, bid) + await asyncio.sleep(0.5) + await botmod.Userbot.promote_chat_member(chat_id, bid, privileges=privileges) + return {"bot": label, "user_id": bid, "status": "added", "message": "Added and promoted to admin."} + except Exception as e2: + return {"bot": label, "user_id": bid, "status": "error", "message": _friendly_promote_error(e2)} + return {"bot": label, "user_id": bid, "status": "error", "message": _friendly_promote_error(e)} + + +async def _demote_one(chat_id, user) -> dict: + label = getattr(user, "first_name", None) or (f"@{user.username}" if getattr(user, "username", None) else str(user.id)) + try: + await botmod.Userbot.promote_chat_member(chat_id, user.id, privileges=_no_privileges()) + return {"bot": label, "user_id": user.id, "status": "demoted", "message": "Admin rights removed (orphan)."} + except Exception as e: + return {"bot": label, "user_id": user.id, "status": "error", "message": _friendly_promote_error(e)} + + +async def _run_bot_admin_apply(channel_ids, selected, demote_orphans, managed_ids) -> None: + state = _bot_admin_apply_state + privileges = _bot_admin_privileges() + try: + for raw in channel_ids: + cid = _norm_chat_id(raw) + ch_result = {"id": str(cid), "name": str(cid), "items": []} + + try: + chat = await botmod.Userbot.get_chat(cid) + ch_result["name"] = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(cid) + except Exception as e: + ch_result["items"].append({"bot": "—", "status": "error", "message": f"Channel not accessible: {e}"}) + state["results"].append(ch_result) + state["done"] += 1 + continue + + rights = await _session_rights(cid) + if not rights["manageable"]: + ch_result["items"].append({ + "bot": "—", "status": "skipped", + "message": rights["reason"] or "Your session account can't add admins here.", + }) + state["results"].append(ch_result) + state["done"] += 1 + continue + + for b in selected: + ch_result["items"].append(await _promote_one(cid, b, privileges)) + await asyncio.sleep(0.3) + + if demote_orphans: + try: + async for m in botmod.Userbot.get_chat_members(cid, filter=ChatMembersFilter.ADMINISTRATORS): + u = getattr(m, "user", None) + if u and getattr(u, "is_bot", False) and u.id not in managed_ids: + ch_result["items"].append(await _demote_one(cid, u)) + await asyncio.sleep(0.3) + except Exception as e: + ch_result["items"].append({"bot": "orphans", "status": "error", "message": f"Couldn't scan orphans: {e}"}) + + state["results"].append(ch_result) + state["done"] += 1 + + state["status"] = "completed" + except Exception as e: + LOGGER.error(f"[BotAdmin] Apply run failed: {e}") + state["status"] = "error" + state["error"] = str(e) + finally: + state["running"] = False + + +async def bot_admin_apply_api(payload: dict | None = None) -> dict: + if botmod.Userbot is None: + raise HTTPException(status_code=503, detail="No Telegram session connected. Connect one from Settings.") + + if _bot_admin_apply_state["running"]: + raise HTTPException(status_code=409, detail="An apply run is already in progress.") + + payload = payload or {} + channel_ids = payload.get("channel_ids") or [] + if not isinstance(channel_ids, list) or not channel_ids: + raise HTTPException(status_code=400, detail="Select at least one channel.") + + bots = await _managed_bots() + if len(bots) <= 1: + raise HTTPException(status_code=400, detail="Need a session string and more than one bot token.") + + bot_by_id = {str(b["user_id"]): b for b in bots} + sel_ids = payload.get("bot_ids") + if isinstance(sel_ids, list) and sel_ids: + selected = [bot_by_id[str(x)] for x in sel_ids if str(x) in bot_by_id] + else: + selected = bots + if not selected: + raise HTTPException(status_code=400, detail="No matching bots selected.") + + demote_orphans = bool(payload.get("demote_orphans")) + managed_ids = {b["user_id"] for b in bots} + + _bot_admin_apply_state.update({ + "running": True, + "status": "running", + "total": len(channel_ids), + "done": 0, + "results": [], + "error": "", + }) + _bot_admin_apply_state["task"] = asyncio.create_task( + _run_bot_admin_apply(channel_ids, selected, demote_orphans, managed_ids) + ) + return {"status": "started", "total": len(channel_ids)} + + +async def bot_admin_apply_status_api() -> dict: + st = _bot_admin_apply_state + return { + "status": "success", + "data": { + "running": st["running"], + "state": st["status"], + "total": st["total"], + "done": st["done"], + "results": st["results"], + "error": st["error"], + }, + } diff --git a/Backend/fastapi/routes/cf_routes.py b/Backend/fastapi/routes/cf_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..29eeddb83595161befc4d0e0a8faf3f6805d3a2b --- /dev/null +++ b/Backend/fastapi/routes/cf_routes.py @@ -0,0 +1,77 @@ +import json + +from fastapi import APIRouter, HTTPException, Request + +from Backend import db +from Backend.config import Telegram +from Backend.helper.analytics import record_stream_start +from Backend.helper.cf_live import apply_report +from Backend.helper.cf_stream import verify_worker_request +from Backend.helper.own_bots import worker_tokens +from Backend.helper.session_auth import get_active_session_string +from Backend.helper.settings_manager import SettingsManager +from Backend.logger import LOGGER + +router = APIRouter(tags=["Cloudflare"]) + + +#----- Only the Cloudflare Worker (holding the shared secret) may call these routes +async def _verified_body(request: Request) -> tuple: + body = await request.body() + signed = (request.method, request.url.path, body, request.headers.get("x-cf-time", ""), request.headers.get("x-cf-sig", "")) + if verify_worker_request(*signed): + return body, None + for doc in await worker_tokens(): + if verify_worker_request(*signed, doc["cf"]["secret"]): + return body, doc + raise HTTPException(status_code=401, detail="Bad signature") + + +#----- Telegram credentials the Worker needs to stream: API app, bot pool, optional userbot +@router.get("/api/cf/config") +async def cf_config(request: Request): + _, owner = await _verified_body(request) + if owner: + bots = [b["token"] for b in (owner.get("own_bots") or {}).get("bots") or []] + return {"api_id": Telegram.API_ID, "api_hash": Telegram.API_HASH, "bots": bots, "user_session": ""} + tokens = [Telegram.BOT_TOKEN, *SettingsManager.current().multi_tokens] + try: + user_session = await get_active_session_string() or "" + except Exception as e: + LOGGER.warning(f"[CF] Could not load userbot session: {e}") + user_session = "" + return { + "api_id": Telegram.API_ID, + "api_hash": Telegram.API_HASH, + "bots": [t for t in dict.fromkeys(tokens) if t], + "user_session": user_session, + } + + +#----- Bytes streamed per token (for daily/monthly limits) and stream-start analytics +@router.post("/api/cf/usage") +async def cf_usage(request: Request): + body, _ = await _verified_body(request) + data = json.loads(body or b"{}") + for token, delta in (data.get("usage") or {}).items(): + if isinstance(delta, int) and delta > 0: + try: + await db.update_token_usage(token, delta) + except Exception as e: + LOGGER.error(f"[CF] Usage update failed for token: {e}") + names = {} + for start in data.get("starts") or []: + token = str(start.get("token") or "") + if not token: + continue + if token not in names: + token_data = await db.get_api_token(token) + names[token] = token_data.get("name") if token_data else None + await record_stream_start(token, names[token], str(start.get("ip") or ""), str(start.get("ua") or "")) + #----- Live streams, so dashboards and user activity show Cloudflare streams too + if isinstance(data.get("streams"), list) and data.get("member"): + try: + await apply_report(str(data["member"]), data.get("client_index"), data.get("dc"), data["streams"]) + except Exception as e: + LOGGER.error(f"[CF] Live stream report failed: {e}") + return {"ok": True} diff --git a/Backend/fastapi/routes/stream_routes.py b/Backend/fastapi/routes/stream_routes.py index 3be4ccea969992820b06c4458898d1bba349c82a..be9b286f0b3b5c142e45df3aef43cd39bf36deae 100644 --- a/Backend/fastapi/routes/stream_routes.py +++ b/Backend/fastapi/routes/stream_routes.py @@ -1,31 +1,52 @@ -import math -import time import asyncio -import secrets +import math import mimetypes -from typing import Dict -from urllib.parse import unquote -from math import ceil -from fastapi import APIRouter, Request, HTTPException, Depends -from fastapi.responses import Response as PlainResponse, StreamingResponse, JSONResponse +import secrets +import time from collections import deque +from contextvars import ContextVar +from typing import Dict +from urllib.parse import quote, unquote + +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.responses import JSONResponse, RedirectResponse +from fastapi.responses import Response as PlainResponse +from fastapi.responses import StreamingResponse + from Backend import db -from Backend.logger import LOGGER -from Backend.helper.encrypt import decode_string +from Backend.fastapi.security.tokens import verify_token +from Backend.helper.bounded import BoundedDict +from Backend.helper.analytics import client_ip_from, record_stream_start +from Backend.helper import own_bots +from Backend.helper.cf_stream import cf_stream_url +from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS, ByteStreamer +from Backend.helper.encrypt import decode_string, encode_string +from Backend.helper.pyro import get_thumb_download_target +from Backend.helper.settings_manager import SettingsManager from Backend.helper.utils import track_usage -from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator -from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps, Userbot, USERBOT_CLIENT_INDEX -from Backend.fastapi.security.tokens import verify_token +from Backend.helper.zip_stream import resolve_zip_entry +from Backend.logger import LOGGER +import Backend.pyrofork.bot as botmod +from Backend.pyrofork.bot import ( + USERBOT_CLIENT_INDEX, + client_dc_map, + client_failures, + multi_clients, + work_loads, +) router = APIRouter(tags=["Streaming"]) _streamer_by_client: Dict = {} _rr_counter: int = 0 +_pool: ContextVar = ContextVar("pool", default=None) -_title_cache: Dict[str, tuple] = {} +_title_cache = BoundedDict(2000) _TITLE_CACHE_TTL = 300 + +#----- Recursively convert non-JSON-native containers to serializable forms def make_json_safe(obj): if isinstance(obj, deque): return list(obj) @@ -40,6 +61,7 @@ def make_json_safe(obj): return obj +#----- Parse an HTTP Range header into (start, end) bounds def parse_range_header(range_header: str, file_size: int): if not range_header: return 0, file_size - 1 @@ -57,38 +79,44 @@ def parse_range_header(range_header: str, file_size: int): start = int(start_str) end = int(end_str) except Exception: - raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"}, ) + raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"}) if start < 0: start = 0 if end >= file_size: end = file_size - 1 if end < start: - raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"},) + raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"}) return start, end +def _clients() -> dict: + return _pool.get() or multi_clients + + +#----- Pick the least-loaded client, preferring the target DC, round-robin on ties def select_best_client(target_dc: int) -> int: global _rr_counter + clients = _clients() + def _score(idx: int) -> int: return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0) + if target_dc > 0: - matching = [ - idx for idx, dc in client_dc_map.items() - if dc == target_dc and idx in multi_clients - ] + matching = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in clients] else: matching = [] if not matching: - matching = list(multi_clients.keys()) + matching = list(clients.keys()) if not matching: return 0 min_score = min(_score(i) for i in matching) tied = sorted(i for i in matching if _score(i) == min_score) selected = tied[_rr_counter % len(tied)] - _rr_counter = (_rr_counter + 1) % max(len(multi_clients), 1) + _rr_counter = (_rr_counter + 1) % max(len(clients), 1) return selected +#----- Periodically decay recorded client failure counters async def decay_client_failures() -> None: while True: await asyncio.sleep(300) @@ -96,22 +124,217 @@ async def decay_client_failures() -> None: if client_failures.get(k, 0) > 0: client_failures[k] = max(0, client_failures[k] - 1) + +#----- Parallelism/prefetch factor scaled by the number of clients def get_parallel_prefetch(client_count: int) -> tuple[int, int]: - value = min(max(ceil(client_count / 5), 1), 5) + value = min(max(math.ceil(client_count / 5), 1), 5) return value, value + +#----- Reuse (or lazily create) the cached ByteStreamer for a client index +def _get_streamer(tg_client, index: int) -> ByteStreamer: + if tg_client not in _streamer_by_client: + _streamer_by_client[tg_client] = ByteStreamer(tg_client, index) + return _streamer_by_client[tg_client] + + +def warm_streamers() -> None: + for index, client in list(multi_clients.items()): + _get_streamer(client, index) + + +def _prefetch_for(index: int) -> tuple[int, int]: + return (1, 1) if index == USERBOT_CLIENT_INDEX else get_parallel_prefetch(len(_clients()) - 1) + + +#----- Run fetch(streamer) on the Userbot when it is the default streamer, else (or on failure) on the bot pool +async def _db_client(fetch): + if not _pool.get() and SettingsManager.current().default_streaming == "userbot" and (ub := _get_userbot_streamer()): + try: + return USERBOT_CLIENT_INDEX, ub, await fetch(ub) + except Exception as e: + LOGGER.warning(f"[USERBOT] Falling back to bots: {e}") + index = select_best_client(0) + streamer = _get_streamer(_clients()[index], index) + return index, streamer, await fetch(streamer) + + +#----- Resolve a stream title from the TTL cache, DB, or the decoded URL name +async def _lookup_title(stream_id_hash: str, decoded_name: str): + if not stream_id_hash: + return decoded_name + now = time.time() + cached = _title_cache.get(stream_id_hash) + if cached and now < cached[1]: + return cached[0] or decoded_name + db_title = await db.get_title_by_stream_id(stream_id_hash) + _title_cache[stream_id_hash] = (db_title, now + _TITLE_CACHE_TTL) + return db_title or decoded_name + + +#----- Derive a display file name and mime type from file properties +def _resolve_filename_mime(file_id): + file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin" + mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream" + if "." not in file_name and "/" in mime_type: + file_name = f"{file_name}.{mime_type.split('/')[1]}" + return file_name, mime_type + + +def _content_disposition(file_name, disposition="inline"): + ascii_fallback = file_name.encode("ascii", "ignore").decode("ascii").replace('"', "").strip() or "file" + return f"{disposition}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(file_name, safe='')}" + + +#----- Build the shared streaming response headers and status code +def _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size): + headers = { + "Content-Type": mime_type, + "Content-Disposition": _content_disposition(file_name), + "Accept-Ranges": "bytes", + "Content-Length": str(req_length), + "Cache-Control": "public, max-age=3600", + "Access-Control-Allow-Origin": "*", + "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges", + } + status = 200 + if range_header: + headers["Content-Range"] = f"bytes {start}-{end}/{file_size}" + status = 206 + return headers, status + + +_thumb_cache = BoundedDict(200) +_THUMB_CACHE_TTL = 3600 + + +#----- Serve a Telegram video/document thumbnail (public, used as artwork) +@router.get("/thumb/{id}") +async def thumb_handler(id: str): + now = time.time() + cached = _thumb_cache.get(id) + if cached and now < cached[1]: + data = cached[0] + else: + try: + decoded = await decode_string(id) + chat_id = int(f"-100{decoded['chat_id']}") + msg_id = int(decoded["msg_id"]) + except Exception: + raise HTTPException(status_code=400, detail="Invalid thumbnail id") + if not multi_clients: + raise HTTPException(status_code=503, detail="No client available") + client = multi_clients[select_best_client(0)] + try: + message = await client.get_messages(chat_id, msg_id) + target = get_thumb_download_target(message) + if not target: + raise HTTPException(status_code=404, detail="No thumbnail") + file_id = getattr(target, "file_id", None) or target + buf = await client.download_media(file_id, in_memory=True) + data = buf.getvalue() + except HTTPException: + raise + except Exception as e: + LOGGER.warning(f"[THUMB] fetch failed for {id}: {e}") + raise HTTPException(status_code=404, detail="Thumbnail unavailable") + _thumb_cache[id] = (data, now + _THUMB_CACHE_TTL) + + return PlainResponse( + content=data, + media_type="image/jpeg", + headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}, + ) + + +_SUBTITLE_MIME = { + ".srt": "application/x-subrip", + ".vtt": "text/vtt", + ".ass": "text/x-ssa", + ".ssa": "text/x-ssa", + ".sub": "text/plain", +} + + +#----- Serve a subtitle file fully in-memory (files are small) +@router.get("/sub/{token}/{id}/{name}") +async def subtitle_handler(token: str, id: str, name: str, token_data: dict = Depends(verify_token)): + try: + decoded = await decode_string(id) + chat_id = int(f"-100{decoded['chat_id']}") + msg_id = int(decoded["msg_id"]) + except Exception: + raise HTTPException(status_code=400, detail="Invalid subtitle id") + + if not multi_clients: + raise HTTPException(status_code=503, detail="No client available") + + client = multi_clients[select_best_client(0)] + try: + message = await client.get_messages(chat_id, msg_id) + buf = await client.download_media(message, in_memory=True) + data = buf.getvalue() + except Exception as e: + LOGGER.warning(f"[SUBTITLE] fetch failed for {id}: {e}") + raise HTTPException(status_code=404, detail="Subtitle unavailable") + + ext = "." + name.rsplit(".", 1)[-1].lower() if "." in name else ".srt" + return PlainResponse( + content=data, + media_type=_SUBTITLE_MIME.get(ext, "application/octet-stream"), + headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"}, + ) + + +#----- Entry point: decode the id and dispatch to the matching streamer @router.get("/dl/{token}/{id}/{name}") @router.head("/dl/{token}/{id}/{name}") -async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),): +async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token)): decoded = await decode_string(id) + if not decoded.get("global") and own_bots.active(token_data): + try: + moved = await own_bots.remap(token_data, decoded) + cf = own_bots.worker(token_data) + if cf and request.query_params.get("via") == "cf": + return RedirectResponse(cf_stream_url(token, await encode_string(moved), quote(name), cf["url"], cf["secret"]), status_code=302) + pool = await own_bots.pool_for(token_data) + if pool: + decoded = moved + _pool.set(pool) + except Exception as e: + LOGGER.warning(f"[OWN BOTS] Falling back to owner bots: {e}") + + if request.method != "HEAD": + asyncio.create_task(record_stream_start( + token, + token_data.get("name") if token_data else None, + client_ip_from(request), + request.headers.get("user-agent", ""), + )) + if decoded.get("global"): + if decoded.get("zip"): + return await global_zip_media_streamer( + request=request, parts_payload=decoded["parts"], + token=token, token_data=token_data, stream_id_hash=id, + ) + if "parts" in decoded: + return await global_virtual_media_streamer( + request=request, parts_payload=decoded["parts"], + token=token, token_data=token_data, stream_id_hash=id, + ) return await global_media_streamer( request=request, chat_id=int(decoded["chat_id"]), msg_id=int(decoded["msg_id"]), token=token, token_data=token_data, stream_id_hash=id, ) if "parts" in decoded: + if decoded.get("zip"): + return await db_zip_media_streamer( + request=request, parts_payload=decoded["parts"], + token=token, token_data=token_data, stream_id_hash=id, + ) return await virtual_media_streamer( request=request, parts_payload=decoded["parts"], token=token, token_data=token_data, stream_id_hash=id, @@ -121,18 +344,15 @@ async def stream_handler(request: Request, token: str, id: str, name: str, token if not msg_id: raise HTTPException(status_code=400, detail="Missing id") chat_id = int(f"-100{decoded['chat_id']}") - return await media_streamer(request=request, chat_id=chat_id, msg_id=int(msg_id), + return await media_streamer( + request=request, chat_id=chat_id, msg_id=int(msg_id), token=token, token_data=token_data, stream_id_hash=id, ) -async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,): - index = select_best_client(0) - tg_client = multi_clients[index] - if tg_client not in _streamer_by_client: - _streamer_by_client[tg_client] = ByteStreamer(tg_client, index) - streamer: ByteStreamer = _streamer_by_client[tg_client] - file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id) - target_dc = file_id.dc_id + +#----- Stream a single Telegram file, with optional multi-client parallelism +async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None): + index, streamer, file_id = await _db_client(lambda s: s.get_file_properties(chat_id=chat_id, message_id=msg_id)) file_size = file_id.file_size range_header = request.headers.get("Range", "") start, end = parse_range_header(range_header, file_size) @@ -144,45 +364,34 @@ async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size) stream_id = secrets.token_hex(8) decoded_name = unquote(request.path_params.get("name", "")) - db_title = None - if stream_id_hash: - _now = time.time() - _cached = _title_cache.get(stream_id_hash) - if _cached and _now < _cached[1]: - db_title = _cached[0] - else: - db_title = await db.get_title_by_stream_id(stream_id_hash) - _title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL) - final_title = db_title if db_title else decoded_name + final_title = await _lookup_title(stream_id_hash, decoded_name) + file_name, mime_type = _resolve_filename_mime(file_id) meta = { "request_path": str(request.url.path), "client_host": request.client.host if request.client else None, - "title": final_title, - "user_name": token_data.get("name", "Unknown") if token_data else "Unknown" + "title": final_title or file_name, + "file_name": file_name, + "user_name": token_data.get("name", "Unknown") if token_data else "Unknown", + "token": token, } - token_count = len(multi_clients) - 1 - parallelism, prefetch_count = get_parallel_prefetch(token_count) + parallelism, prefetch_count = _prefetch_for(index) extra_clients_for_stream = [] - if parallelism > 1 and len(multi_clients) > 1: - other_indices = sorted( - (i for i in multi_clients if i != index), - key=lambda i: work_loads.get(i, 0), - ) + clients = _clients() + if parallelism > 1 and len(clients) > 1: + other_indices = sorted((i for i in clients if i != index), key=lambda i: work_loads.get(i, 0)) + async def _get_extra_file_id(ec_idx: int): - ec_client = multi_clients[ec_idx] - if ec_client not in _streamer_by_client: - _streamer_by_client[ec_client] = ByteStreamer(ec_client, ec_idx) - ec_streamer = _streamer_by_client[ec_client] + ec_client = clients[ec_idx] + ec_streamer = _get_streamer(ec_client, ec_idx) try: ec_fid = await ec_streamer.get_file_properties(chat_id=chat_id, message_id=msg_id) return (ec_idx, ec_streamer, ec_fid) except Exception as e: LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e) return None - results = await asyncio.gather(*[ - _get_extra_file_id(i) for i in other_indices[:parallelism - 1] - ]) + + results = await asyncio.gather(*[_get_extra_file_id(i) for i in other_indices[:parallelism - 1]]) extra_clients_for_stream = [r for r in results if r is not None] body_gen = await streamer.prefetch_stream( @@ -205,58 +414,16 @@ async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str asyncio.create_task(track_usage(stream_id, token, token_data)) - file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin" - mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream" + headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size) - if "." not in file_name and "/" in mime_type: - file_name = f"{file_name}.{mime_type.split('/')[1]}" - if request.method == "HEAD": - headers = { - "Content-Type": mime_type, - "Content-Length": str(req_length), - "Content-Disposition": f'inline; filename="{file_name}"', - "Accept-Ranges": "bytes", - "Cache-Control": "public, max-age=3600", - "Access-Control-Allow-Origin": "*", - "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges", - } - - if range_header: - headers["Content-Range"] = f"bytes {start}-{end}/{file_size}" - - return PlainResponse( - status_code=206 if range_header else 200, - headers=headers, - ) - - headers = { - "Content-Type": mime_type, - "Content-Disposition": f'inline; filename="{file_name}"', - "Accept-Ranges": "bytes", - "Content-Length": str(req_length), - "Cache-Control": "public, max-age=3600", - "Access-Control-Allow-Origin": "*", - "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges", - } - - if range_header: - headers["Content-Range"] = f"bytes {start}-{end}/{file_size}" - status = 206 - else: - status = 200 - - return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, ) + return PlainResponse(status_code=status, headers=headers) + return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type) -async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None,): - index = select_best_client(0) - tg_client = multi_clients[index] - if tg_client not in _streamer_by_client: - _streamer_by_client[tg_client] = ByteStreamer(tg_client, index) - streamer: ByteStreamer = _streamer_by_client[tg_client] - - parts, file_size = await resolve_virtual_parts(parts_payload, streamer) +#----- Stream media reconstructed from multiple split parts +async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None): + index, streamer, (parts, file_size) = await _db_client(lambda s: resolve_virtual_parts(parts_payload, s)) if not parts or file_size <= 0: raise HTTPException(status_code=404, detail="Split media parts not found") @@ -266,51 +433,24 @@ async def virtual_media_streamer(request: Request, parts_payload: list, token: s chunk_size = 1024 * 1024 stream_id = secrets.token_hex(8) decoded_name = unquote(request.path_params.get("name", "")) - - db_title = None - if stream_id_hash: - _now = time.time() - _cached = _title_cache.get(stream_id_hash) - if _cached and _now < _cached[1]: - db_title = _cached[0] - else: - db_title = await db.get_title_by_stream_id(stream_id_hash) - _title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL) - final_title = db_title if db_title else decoded_name + final_title = await _lookup_title(stream_id_hash, decoded_name) + file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"]) meta = { "request_path": str(request.url.path), "client_host": request.client.host if request.client else None, - "title": final_title, + "title": final_title or file_name, + "file_name": file_name, "user_name": token_data.get("name", "Unknown") if token_data else "Unknown", + "token": token, "split_parts": len(parts), } - token_count = len(multi_clients) - 1 - parallelism, prefetch_count = get_parallel_prefetch(token_count) + parallelism, prefetch_count = _prefetch_for(index) asyncio.create_task(track_usage(stream_id, token, token_data)) - first_file_id = parts[0]["file_id"] - file_name = first_file_id.file_name or f"{secrets.token_hex(4)}.bin" - mime_type = first_file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream" - if "." not in file_name and "/" in mime_type: - file_name = f"{file_name}.{mime_type.split('/')[1]}" - - common_headers = { - "Content-Type": mime_type, - "Content-Disposition": f'inline; filename="{file_name}"', - "Accept-Ranges": "bytes", - "Content-Length": str(req_length), - "Cache-Control": "public, max-age=3600", - "Access-Control-Allow-Origin": "*", - "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges", - } - if range_header: - common_headers["Content-Range"] = f"bytes {start}-{end}/{file_size}" - status = 206 - else: - status = 200 + common_headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size) if request.method == "HEAD": return PlainResponse(status_code=status, headers=common_headers) @@ -320,29 +460,24 @@ async def virtual_media_streamer(request: Request, parts_payload: list, token: s streamer=streamer, client_index=index, request=request, meta=meta, stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count, ) - - return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type, ) + return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type) _userbot_streamer: ByteStreamer = None +#----- Lazily build and cache the ByteStreamer for the Userbot (None if unconfigured) def _get_userbot_streamer() -> ByteStreamer: - """Lazily build (and cache) the ByteStreamer wrapping the Userbot - client. Returns None if no Userbot is configured.""" global _userbot_streamer - if Userbot is None: + if botmod.Userbot is None: return None - if _userbot_streamer is None: - _userbot_streamer = ByteStreamer(Userbot, USERBOT_CLIENT_INDEX) + if _userbot_streamer is None or _userbot_streamer.client is not botmod.Userbot: + _userbot_streamer = ByteStreamer(botmod.Userbot, USERBOT_CLIENT_INDEX) return _userbot_streamer -async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,): - """Streams a single file found via Global Search, played back through - the Userbot session directly — these channels aren't part of the Auth - Channel/MultiToken infrastructure, so the regular client pool can't - (and shouldn't) be used here.""" +#----- Stream a Global Search file through the Userbot session directly +async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None): streamer = _get_userbot_streamer() if streamer is None: raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot configured)") @@ -365,35 +500,20 @@ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, tok part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size) stream_id = secrets.token_hex(8) + file_name, mime_type = _resolve_filename_mime(file_id) meta = { "request_path": str(request.url.path), "client_host": request.client.host if request.client else None, - "title": file_id.file_name or "global-stream", + "title": file_name or "global-stream", + "file_name": file_name, "user_name": token_data.get("name", "Unknown") if token_data else "Unknown", + "token": token, "global_search": True, } asyncio.create_task(track_usage(stream_id, token, token_data)) - file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin" - mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream" - if "." not in file_name and "/" in mime_type: - file_name = f"{file_name}.{mime_type.split('/')[1]}" - - headers = { - "Content-Type": mime_type, - "Content-Disposition": f'inline; filename="{file_name}"', - "Accept-Ranges": "bytes", - "Content-Length": str(req_length), - "Cache-Control": "public, max-age=3600", - "Access-Control-Allow-Origin": "*", - "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges", - } - if range_header: - headers["Content-Range"] = f"bytes {start}-{end}/{file_size}" - status = 206 - else: - status = 200 + headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size) if request.method == "HEAD": return PlainResponse(status_code=status, headers=headers) @@ -414,9 +534,150 @@ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, tok chat_id=chat_id, message_id=msg_id, ) + return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type) - return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, ) +#----- Stream a split Global Search file (multiple parts) through the Userbot session +async def global_virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None): + streamer = _get_userbot_streamer() + if streamer is None: + raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot connected)") + + parts, file_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=False) + if not parts or file_size <= 0: + raise HTTPException(status_code=404, detail="Split media parts not accessible via Global Search") + + range_header = request.headers.get("Range", "") + start, end = parse_range_header(range_header, file_size) + req_length = end - start + 1 + chunk_size = 1024 * 1024 + stream_id = secrets.token_hex(8) + decoded_name = unquote(request.path_params.get("name", "")) + final_title = await _lookup_title(stream_id_hash, decoded_name) + file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"]) + + meta = { + "request_path": str(request.url.path), + "client_host": request.client.host if request.client else None, + "title": final_title or file_name, + "file_name": file_name, + "user_name": token_data.get("name", "Unknown") if token_data else "Unknown", + "token": token, + "global_search": True, + "split_parts": len(parts), + } + + asyncio.create_task(track_usage(stream_id, token, token_data)) + + headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size) + + if request.method == "HEAD": + return PlainResponse(status_code=status, headers=headers) + + body_gen = virtual_stream_generator( + parts=parts, start=start, end=end, chunk_size=chunk_size, + streamer=streamer, client_index=USERBOT_CLIENT_INDEX, request=request, meta=meta, + stream_id=stream_id, parallelism=1, prefetch_count=1, + ) + return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type) + + +#----- Read a byte range from the concatenated virtual parts into memory +async def _read_virtual_range(parts, start, length, streamer, request, client_index=USERBOT_CLIENT_INDEX, parallelism=1, prefetch_count=1): + buf = bytearray() + gen = virtual_stream_generator( + parts=parts, start=start, end=start + length - 1, chunk_size=1024 * 1024, + streamer=streamer, client_index=client_index, request=request, + meta={"title": "zip-index", "user_name": "system", "token": ""}, + stream_id=secrets.token_hex(6), parallelism=parallelism, prefetch_count=prefetch_count, + ) + try: + async for chunk in gen: + buf.extend(chunk) + if len(buf) >= length: + break + finally: + await gen.aclose() + return bytes(buf[:length]) + + +#----- Stream a split ZIP archive (.zip.001/.002 ...) as its inner video, with seeking. +#----- Only STORED (uncompressed) archives are seekable; the inner file bytes are served +#----- directly at their offset inside the concatenated zip (no stream-unzip needed). +async def _zip_media_streamer(request, parts_payload, token, token_data, stream_id_hash, streamer, client_index, prefix_100, parallelism, prefetch_count): + if streamer is None: + raise HTTPException(status_code=503, detail="ZIP streaming is unavailable (no client/session)") + + parts, zip_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=prefix_100) + if not parts or zip_size <= 0: + raise HTTPException(status_code=404, detail="Split archive parts not accessible") + + async def _read(off, length): + return await _read_virtual_range(parts, off, length, streamer, request, client_index, parallelism, prefetch_count) + + entry = await resolve_zip_entry(_read, zip_size) + if not entry: + raise HTTPException(status_code=415, detail="Unreadable or incomplete split archive") + if entry["method"] != 0: + raise HTTPException( + status_code=415, + detail="This archive is compressed; only stored (uncompressed) ZIP archives can be seek-streamed.", + ) + + inner_size = entry["size"] + data_offset = entry["data_offset"] + if inner_size <= 0 or data_offset + inner_size > zip_size: + raise HTTPException(status_code=415, detail="Split archive has an unexpected layout") + + range_header = request.headers.get("Range", "") + start, end = parse_range_header(range_header, inner_size) + req_length = end - start + 1 + stream_id = secrets.token_hex(8) + inner_name = (entry.get("name") or "").split("/")[-1] or unquote(request.path_params.get("name", "")) or "video.mkv" + mime_type = mimetypes.guess_type(inner_name)[0] or "video/x-matroska" + + meta = { + "request_path": str(request.url.path), + "client_host": request.client.host if request.client else None, + "title": (await _lookup_title(stream_id_hash, inner_name)) or inner_name, + "file_name": inner_name, + "user_name": token_data.get("name", "Unknown") if token_data else "Unknown", + "token": token, + "zip_parts": len(parts), + } + asyncio.create_task(track_usage(stream_id, token, token_data)) + + headers, status = _build_stream_headers(mime_type, inner_name, req_length, range_header, start, end, inner_size) + if request.method == "HEAD": + return PlainResponse(status_code=status, headers=headers) + + body_gen = virtual_stream_generator( + parts=parts, start=data_offset + start, end=data_offset + end, chunk_size=1024 * 1024, + streamer=streamer, client_index=client_index, request=request, meta=meta, + stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count, + ) + return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type) + + +#----- ZIP split from Global Search (streamed via the Userbot session) +async def global_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None): + return await _zip_media_streamer( + request, parts_payload, token, token_data, stream_id_hash, + _get_userbot_streamer(), USERBOT_CLIENT_INDEX, False, 1, 1, + ) + + +#----- ZIP split from the indexed library (streamed via the multi-bot pool) +async def db_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None): + index, streamer, _ = await _db_client(lambda s: resolve_virtual_parts(parts_payload[:1], s)) + parallelism, prefetch_count = _prefetch_for(index) + return await _zip_media_streamer( + request, parts_payload, token, token_data, stream_id_hash, + streamer, index, True, parallelism, prefetch_count, + ) + + +#----- Live and recent stream telemetry, pruning stale active entries @router.get("/stream/stats") async def get_stream_stats(): now = time.time() @@ -436,7 +697,7 @@ async def get_stream_stats(): if now - info["last_activity_ts"] > INACTIVE_TIMEOUT: if status == "active": info["status"] = "cancelled" - info["end_ts"] = now + info["end_ts"] = now if info.get("status") in ("cancelled", "error", "finished", "inactive"): last_ts = info.get("end_ts", info.get("last_activity_ts", now)) if now - last_ts > PRUNE_SECONDS: @@ -444,51 +705,52 @@ async def get_stream_stats(): RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid)) except KeyError: pass - active = [] - for sid, info in ACTIVE_STREAMS.items(): - active.append( - { - "stream_id": sid, - "msg_id": info.get("msg_id"), - "chat_id": info.get("chat_id"), - "title": info.get("meta", {}).get("title"), - "client_index": info.get("client_index"), - "dc_id": info.get("dc_id"), - "status": info.get("status"), - "total_bytes": info.get("total_bytes"), - "instant_mbps": round(info.get("instant_mbps", 0.0), 3), - "avg_mbps": round(info.get("avg_mbps", 0.0), 3), - "peak_mbps": round(info.get("peak_mbps", 0.0), 3), - "start_ts": info.get("start_ts"), - } - ) - recent = [] - for info in RECENT_STREAMS: - recent.append( - { - "stream_id": info.get("stream_id"), - "msg_id": info.get("msg_id"), - "chat_id": info.get("chat_id"), - "title": info.get("meta", {}).get("title"), - "client_index": info.get("client_index"), - "dc_id": info.get("dc_id"), - "status": info.get("status"), - "total_bytes": info.get("total_bytes"), - "duration": info.get("duration"), - "avg_mbps": round(info.get("avg_mbps", 0.0), 3), - "start_ts": info.get("start_ts"), - "end_ts": info.get("end_ts"), - } - ) - return JSONResponse( + + active = [ { - "active_streams": active, - "recent_streams": recent, - "client_dc_map": client_dc_map, - "work_loads": work_loads, + "stream_id": sid, + "msg_id": info.get("msg_id"), + "chat_id": info.get("chat_id"), + "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"), + "file_name": info.get("meta", {}).get("file_name"), + "client_index": info.get("client_index"), + "dc_id": info.get("dc_id"), + "status": info.get("status"), + "total_bytes": info.get("total_bytes"), + "instant_mbps": round(info.get("instant_mbps", 0.0), 3), + "avg_mbps": round(info.get("avg_mbps", 0.0), 3), + "peak_mbps": round(info.get("peak_mbps", 0.0), 3), + "start_ts": info.get("start_ts"), } - ) + for sid, info in ACTIVE_STREAMS.items() + ] + recent = [ + { + "stream_id": info.get("stream_id"), + "msg_id": info.get("msg_id"), + "chat_id": info.get("chat_id"), + "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"), + "file_name": info.get("meta", {}).get("file_name"), + "client_index": info.get("client_index"), + "dc_id": info.get("dc_id"), + "status": info.get("status"), + "total_bytes": info.get("total_bytes"), + "duration": info.get("duration"), + "avg_mbps": round(info.get("avg_mbps", 0.0), 3), + "start_ts": info.get("start_ts"), + "end_ts": info.get("end_ts"), + } + for info in RECENT_STREAMS + ] + return JSONResponse({ + "active_streams": active, + "recent_streams": recent, + "client_dc_map": client_dc_map, + "work_loads": work_loads, + }) + +#----- Detailed telemetry for a single stream id @router.get("/stream/stats/{stream_id}") async def get_stream_detail(stream_id: str): info = ACTIVE_STREAMS.get(stream_id) diff --git a/Backend/fastapi/routes/stremio_routes.py b/Backend/fastapi/routes/stremio_routes.py index c05a67a97b3161c76dbef6566bbc95306ce68daf..60f3595c8484b6da2109d2a8c96be739065b3021 100644 --- a/Backend/fastapi/routes/stremio_routes.py +++ b/Backend/fastapi/routes/stremio_routes.py @@ -1,29 +1,204 @@ -from fastapi import APIRouter, HTTPException, Depends +import asyncio +import re +import time +from datetime import datetime, timedelta, timezone from typing import Optional -from urllib.parse import unquote, quote -from Backend.config import Telegram -from Backend.helper.settings_manager import SettingsManager -from Backend import db, __version__ +from urllib.parse import quote, unquote + import PTN -from fastapi.responses import HTMLResponse -from datetime import datetime, timezone, timedelta +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.templating import Jinja2Templates +from pyrogram.enums import ChatMemberStatus +from pyrogram.errors import UserNotParticipant + +import httpx + +from Backend import __version__, db +from Backend.helper.database import META_PROJECTION +from Backend.helper.auto_catalog import catalog_sort_key +from Backend.helper.bounded import BoundedDict +from Backend.config import Telegram +from Backend.helper.analytics import client_ip_from, record_client from Backend.fastapi.security.tokens import verify_token -from Backend.logger import LOGGER +from Backend.helper import own_bots +from Backend.helper.cf_stream import cf_enabled, cf_stream_url +from Backend.fastapi.themes import get_theme, theme_key +from Backend.helper.fanart import fanart_artwork from Backend.helper.global_search import global_search, is_global_search_enabled -from Backend.pyrofork.bot import get_streambot_url +from Backend.helper.metadata.providers.cinemeta import get_detail, get_season +from Backend.helper.metadata import resolve_cover_url, COMBINED_SEASON, COMBINED_EPISODE_BASE, tmdb_api_key, get_tmdb_client, format_tmdb_image +from Backend.helper.database import convert_objectid_to_str +from Backend.helper.split_files import parse_combined_episodes, combined_name_key +from Backend.helper.settings_manager import SettingsManager +from Backend.helper.stream_formatter import format_stream +from Backend.helper.subtitles import get_subtitles_for, stremio_subtitle_entries +from Backend.logger import LOGGER +from Backend.pyrofork.bot import StreamBot, get_streambot_url router = APIRouter(prefix="/stremio", tags=["Stremio Addon"]) +templates = Jinja2Templates(directory="Backend/fastapi/templates") -# --- Configuration --- +#----- Addon configuration ADDON_NAME = "Telegram" ADDON_VERSION = __version__ PAGE_SIZE = 15 +def _donation(): + text = "Enjoying Telegram Stremio?\nTap to support the developer" + return {"name": "❤️ Support", "title": text, "description": text, "externalUrl": "https://donate.weebzonex.workers.dev"} + +async def _external_meta_for_id(id: str, parsed: dict, media_type: str) -> Optional[dict]: + """Resolve basic metadata from TMDB or Cinemeta when an item is not in the database. + This prevents Stremio/Nuvio from crashing with 'Could not load details' on un-cached items.""" + try: + tmdb_id = parsed.get("tmdb_id") + if tmdb_id is not None and tmdb_api_key(): + client = get_tmdb_client() + is_movie = media_type == "movie" or parsed.get("tmdb_media_type") == "movie" + target = client.movie(tmdb_id) if is_movie else client.tv(tmdb_id) + item = await target.details(append_to_response="images,credits,external_ids") + if not item: + return None + + name = getattr(item, "title", None) if is_movie else getattr(item, "name", None) + name = name or getattr(item, "original_title", None) or getattr(item, "original_name", None) or "" + + rel_date = getattr(item, "release_date", None) if is_movie else getattr(item, "first_air_date", None) + year_str = str(rel_date.year) if (rel_date and getattr(rel_date, "year", None)) else "" + + ext_ids = getattr(item, "external_ids", None) + external_imdb = getattr(ext_ids, "imdb_id", None) if ext_ids else None + + images = getattr(item, "images", None) + logo_url = "" + if images and getattr(images, "logos", None): + for l in images.logos: + if getattr(l, "iso_639_1", None) == "en" and getattr(l, "file_path", None): + logo_url = format_tmdb_image(l.file_path, "w300") + break + if not logo_url and images.logos and getattr(images.logos[0], "file_path", None): + logo_url = format_tmdb_image(images.logos[0].file_path, "w300") + + genres = [getattr(g, "name", "") for g in (getattr(item, "genres", None) or []) if getattr(g, "name", None)] + runtime = getattr(item, "runtime", "") if is_movie else "" + if not runtime and not is_movie: + r_list = getattr(item, "episode_run_time", None) or [] + runtime = str(r_list[0]) if r_list else "" + + credits_data = getattr(item, "credits", None) + cast_list = [] + if credits_data and getattr(credits_data, "cast", None): + cast_list = [getattr(c, "name", "") for c in credits_data.cast[:10] if getattr(c, "name", None)] + + meta_id = id + videos = [] + if not is_movie: + seasons = getattr(item, "seasons", None) or [] + last = getattr(item, "last_episode_to_air", None) + last_aired = ( + (getattr(last, "season_number", 0) or 0, getattr(last, "episode_number", 0) or 0) + if last else None + ) + for s in seasons: + s_num = getattr(s, "season_number", 0) + if s_num == 0: + continue + air = getattr(s, "air_date", None) + released = f"{str(air)[:10]}T00:00:00.000Z" if air else None + ep_count = getattr(s, "episode_count", 0) or 0 + for ep in range(1, ep_count + 1): + if last_aired and (s_num, ep) > last_aired: + break + video = { + "id": f"{meta_id}:{s_num}:{ep}", + "title": f"Episode {ep}", + "season": s_num, + "episode": ep, + } + if released: + video["released"] = released + videos.append(video) + + return { + "id": meta_id, + "type": "movie" if is_movie else "series", + "name": name, + "description": getattr(item, "overview", "") or "", + "year": year_str, + "releaseInfo": year_str, + "poster": format_tmdb_image(getattr(item, "poster_path", None), "w500"), + "background": format_tmdb_image(getattr(item, "backdrop_path", None), "original"), + "logo": logo_url, + "genres": genres, + "imdbRating": str(round(getattr(item, "vote_average", 0), 1)) if getattr(item, "vote_average", None) else "", + "imdb_id": external_imdb or "", + "moviedb_id": tmdb_id, + "cast": cast_list, + "runtime": str(runtime) if runtime else "", + "videos": videos, + } + + imdb_id = parsed.get("imdb_id") + if imdb_id and imdb_id.startswith("tt"): + external = await get_detail(imdb_id, "movie" if media_type == "movie" else "series") + if external and external.get("title"): + release = external.get("releaseDetailed") or {} + year = release.get("year") or "" + return { + "id": imdb_id, + "type": "movie" if media_type == "movie" else "series", + "name": external.get("title") or "", + "description": external.get("plot") or "", + "year": str(year) if year else "", + "releaseInfo": str(year) if year else "", + "poster": external.get("poster") or "", + "background": external.get("background") or "", + "logo": external.get("logo") or "", + "genres": external.get("genre") or [], + "imdbRating": str((external.get("rating") or {}).get("star") or ""), + "imdb_id": imdb_id, + "moviedb_id": external.get("moviedb_id") or "", + "cast": external.get("cast") or [], + "runtime": external.get("runtime") or "", + "videos": external.get("videos") or [], + } + except Exception as exc: + LOGGER.warning(f"[EXTERNAL META] Failed to resolve fallback meta for {id}: {exc}") + return None + +_EXTERNAL_META_CACHE = BoundedDict(500) +_EXTERNAL_META_TTL = 6 * 3600 + + +async def _cached_external_meta(id: str, parsed: dict, media_type: str) -> Optional[dict]: + key = (id, media_type) + hit = _EXTERNAL_META_CACHE.get(key) + if hit and time.time() - hit[0] < _EXTERNAL_META_TTL: + return hit[1] + meta = await _external_meta_for_id(id, parsed, media_type) + if meta: + _EXTERNAL_META_CACHE[key] = (time.time(), meta) + return meta + + +def build_proxy_url(original_url: str) -> str | None: + settings = SettingsManager.current() + base = settings.http_proxy_url + if not base: + return None + if settings.mediaflow_proxy: + url = f"{base.rstrip('/')}/proxy/stream?d={quote(original_url, safe='')}" + if settings.mediaflow_password: + url += f"&api_password={quote(settings.mediaflow_password, safe='')}" + return url + return f"{base}{original_url}" + _membership_cache: dict = {} -_MEMBERSHIP_TTL = 60 # seconds -_MEMBERSHIP_CACHE_MAX = 5000 +_MEMBERSHIP_TTL = 60 +_MEMBERSHIP_CACHE_MAX = 5000 +#----- Drop cached membership results for one user or all users def invalidate_membership_cache(user_id: int | None = None) -> None: if user_id is None: _membership_cache.clear() @@ -31,7 +206,256 @@ def invalidate_membership_cache(user_id: int | None = None) -> None: for key in [k for k in _membership_cache if k[1] == user_id]: _membership_cache.pop(key, None) -# Define available genres + +#----- Effective (mode, allowed_tokens) for a title, honouring per-item overrides +def _effective_visibility(catalog: dict, item: dict) -> tuple: + if item.get("visibility") in ("public", "tokens", "owner"): + return item["visibility"], (item.get("allowed_tokens") or []) + return (catalog.get("visibility") or "public"), (catalog.get("allowed_tokens") or []) + + +#----- Whether a token may see content with the given visibility +def _token_can_view(mode: str, allowed_tokens: list, token_data: Optional[dict] = None) -> bool: + if not token_data: + return mode == "public" + user_id = token_data.get("user_id") + try: + if user_id is not None and int(user_id) == int(Telegram.OWNER_ID): + return True + except (TypeError, ValueError): + pass + if mode == "owner": + return False + if mode == "tokens": + return token_data.get("token") in (allowed_tokens or []) + if SettingsManager.current().subscription: + return not token_data.get("subscription_expired") + return True + + +#----- Mongo filter that hides owner-only / restricted titles from a token +def _visibility_query(token_data: Optional[dict] = None) -> dict: + if not token_data: + return {"$or": [ + {"visibility": {"$exists": False}}, + {"visibility": "public"}, + ]} + user_id = token_data.get("user_id") + try: + if user_id is not None and int(user_id) == int(Telegram.OWNER_ID): + return {} + except (TypeError, ValueError): + pass + return {"$or": [ + {"visibility": {"$exists": False}}, + {"visibility": "public"}, + {"visibility": "tokens", "allowed_tokens": token_data.get("token")}, + ]} + + +#----- Hide titles locked to a single catalog from default listings / search +def _not_exclusive_clause(allow_searchable: bool = False) -> dict: + ors = [{"exclusive_catalog_id": {"$exists": False}}, {"exclusive_catalog_id": None}] + if allow_searchable: + ors.append({"exclusive_searchable": True}) + return {"$or": ors} + + +#----- Combine non-empty Mongo filters under a single $and +def _merge_filters(*filters) -> dict: + parts = [f for f in filters if f] + if not parts: + return {} + return parts[0] if len(parts) == 1 else {"$and": parts} + + +_TMDB_TRENDING_CACHE: dict = {} +_TMDB_TRENDING_LOCKS: dict = {} +_TMDB_TRENDING_TTL = 600 # 10 minutes cache + + +async def _get_tmdb_trending_ids(media_type: str, time_window: str = "day") -> list[int]: + """Fetch daily trending TMDB IDs (cached for 10 minutes).""" + api_key = tmdb_api_key() + if not api_key: + return [] + + cache_key = (media_type, time_window) + now = time.monotonic() + cached = _TMDB_TRENDING_CACHE.get(cache_key) + if cached and now - cached[0] < _TMDB_TRENDING_TTL: + return list(cached[1]) + + lock = _TMDB_TRENDING_LOCKS.setdefault(cache_key, asyncio.Lock()) + async with lock: + now = time.monotonic() + cached = _TMDB_TRENDING_CACHE.get(cache_key) + if cached and now - cached[0] < _TMDB_TRENDING_TTL: + return list(cached[1]) + + ids: list[int] = [] + try: + url = f"https://api.themoviedb.org/3/trending/{media_type}/{time_window}" + async with httpx.AsyncClient(timeout=10.0) as client: + resp = await client.get(url, params={"api_key": api_key, "page": 1}) + if resp.status_code == 200: + data = resp.json() + for item in data.get("results") or []: + raw_id = item.get("id") + if raw_id: + try: + ids.append(int(raw_id)) + except (TypeError, ValueError): + pass + except Exception as exc: + LOGGER.warning(f"[TMDB Trending] Fetch failed for {media_type}: {exc}") + if cached: + return list(cached[1]) + return [] + + if ids: + _TMDB_TRENDING_CACHE[cache_key] = (time.monotonic(), ids) + return ids + + +async def _get_db_matches_in_tmdb_order( + media_type: str, tmdb_ids: list[int], token_data: dict, genre_filter: Optional[str] = None +) -> list[dict]: + """Match local MongoDB records for TMDB IDs while preserving exact TMDB trending rank.""" + if not tmdb_ids: + return [] + + collection_name = "tv" if media_type == "series" else "movie" + query_parts = [ + {"tmdb_id": {"$in": tmdb_ids}}, + _visibility_query(token_data), + _not_exclusive_clause(), + ] + if genre_filter: + query_parts.append({"genres": {"$in": [genre_filter]}}) + query = _merge_filters(*query_parts) + + by_tmdb_id: dict[int, dict] = {} + storage_keys = [key for key in db.dbs if str(key).startswith("storage_")] + storage_keys.sort(key=lambda k: int(str(k).split("_", 1)[1]) if str(k).split("_", 1)[1].isdigit() else 0, reverse=True) + + for db_key in storage_keys: + try: + cursor = db.dbs[db_key][collection_name].find(query, META_PROJECTION) + async for item in cursor: + try: + t_id = int(item.get("tmdb_id")) + except (TypeError, ValueError): + continue + if t_id in by_tmdb_id: + continue + if not _token_can_view( + item.get("visibility") or "public", + item.get("allowed_tokens") or [], + token_data, + ): + continue + by_tmdb_id[t_id] = convert_objectid_to_str(item) + except Exception as exc: + LOGGER.warning(f"[TMDB Trending] DB error querying {db_key}: {exc}") + + # Preserve the exact ranking from TMDB + ordered = [by_tmdb_id[tid] for tid in tmdb_ids if tid in by_tmdb_id] + return ordered + + +def _parse_stremio_id(id: str): + parts = id.split(":") + prefix = parts[0].lower() if parts else "" + is_kitsu = prefix == "kitsu" + is_tmdb = prefix == "tmdb" + imdb_id = None + kitsu_id = None + tmdb_id = None + tmdb_media_type = None + season_num = None + episode_num = None + absolute_episode = None + + if is_kitsu: + try: + kitsu_id = int(parts[1]) if len(parts) > 1 else None + except (TypeError, ValueError): + kitsu_id = None + if len(parts) == 3: + try: + absolute_episode = int(parts[2]) + except (TypeError, ValueError): + absolute_episode = None + episode_num = absolute_episode + elif len(parts) >= 4: + try: + season_num = int(parts[2]) if parts[2] not in ("", "null", "None") else None + except (TypeError, ValueError): + season_num = None + try: + episode_num = int(parts[3]) if parts[3] not in ("", "null", "None") else None + except (TypeError, ValueError): + episode_num = None + if season_num is None and episode_num is not None: + absolute_episode = episode_num + elif is_tmdb: + # Supports tmdb:movie:, tmdb:tv:, tmdb:, and tmdb::: + id_index = 1 + if len(parts) > 2 and parts[1].lower() in ("movie", "tv", "series"): + tmdb_media_type = "movie" if parts[1].lower() == "movie" else "tv" + id_index = 2 + try: + tmdb_id = int(parts[id_index]) if len(parts) > id_index else None + except (TypeError, ValueError): + tmdb_id = None + trailing = parts[id_index + 1:] + if len(trailing) >= 2: + try: + season_num = int(trailing[0]) if trailing[0] not in ("", "null", "None") else None + except (TypeError, ValueError): + season_num = None + try: + episode_num = int(trailing[1]) if trailing[1] not in ("", "null", "None") else None + except (TypeError, ValueError): + episode_num = None + elif len(trailing) == 1: + try: + episode_num = int(trailing[0]) + except (TypeError, ValueError): + episode_num = None + else: + imdb_id = parts[0] if parts else id + try: + season_num = int(parts[1]) if len(parts) > 1 and parts[1] not in ("", "null", "None") else None + except (TypeError, ValueError): + season_num = None + try: + episode_num = int(parts[2]) if len(parts) > 2 and parts[2] not in ("", "null", "None") else None + except (TypeError, ValueError): + episode_num = None + + return { + "imdb_id": imdb_id, + "kitsu_id": kitsu_id, + "tmdb_id": tmdb_id, + "tmdb_media_type": tmdb_media_type, + "season_num": season_num, + "episode_num": episode_num, + "absolute_episode": absolute_episode, + "is_kitsu": is_kitsu, + "is_tmdb": is_tmdb, + } + + +async def _title_allowed(imdb_id: str = None, token_data: dict = None, kitsu_id: int = None, tmdb_id: int = None, media_type: str = None) -> bool: + doc = await db.get_media_details(imdb_id=imdb_id, kitsu_id=kitsu_id, tmdb_id=tmdb_id, media_type=media_type, projection={"visibility": 1, "allowed_tokens": 1}) + if not doc: + return True + return _token_can_view(doc.get("visibility") or "public", doc.get("allowed_tokens") or [], token_data) + + +#----- Available catalog genres GENRES = [ "Action", "Adventure", "Animation", "Biography", "Comedy", "Crime", "Documentary", "Drama", "Family", "Fantasy", @@ -39,24 +463,111 @@ GENRES = [ "Sci-Fi", "Sport", "Thriller", "War", "Western" ] -# --------------- Helper Functions ----------------- + +#----- Turn a stored image reference into an absolute URL for Stremio clients. +#----- Rebinds gradient covers and app-served /thumb paths to the current hosts. +def _abs_media_url(value: str) -> str: + value = resolve_cover_url(value) + idx = value.find("/thumb/") + return f"{SettingsManager.current().base_url}{value[idx:]}" if idx != -1 else value + + +BETTERPOSTER_DEFAULT = "https://btttr.cc/poster/imdb/poster-default/{imdb_id}.jpg" +RPDB_FREE = "https://api.ratingposterdb.com/t0-free-rpdb/imdb/poster-default/{imdb_id}.jpg" + + +def _poster_url(imdb_id: str, fallback: str, media_type: str = "movie") -> str: + settings = SettingsManager.current() + if imdb_id: + if settings.spatial_poster_enabled and settings.spatial_poster: + return settings.spatial_poster.replace("{type}", media_type).replace("{imdb_id}", str(imdb_id)) + if settings.better_poster_enabled: + template = settings.better_poster or BETTERPOSTER_DEFAULT + return template.replace("{imdb_id}", str(imdb_id)) + if settings.rpdb_enabled: + key = settings.rpdb_api_key + template = ( + f"https://api.ratingposterdb.com/{key}/imdb/poster-default/{{imdb_id}}.jpg" + if key else RPDB_FREE + ) + return template.replace("{imdb_id}", str(imdb_id)) + return _abs_media_url(fallback) + + +async def _apply_fanart(meta: dict, item: dict) -> None: + if not SettingsManager.current().fanart_enabled: + return + try: + art = await fanart_artwork(item.get("imdb_id"), item.get("tmdb_id"), item.get("media_type")) + except Exception as e: + LOGGER.warning(f"[FANART] artwork lookup failed for {item.get('imdb_id')}: {e}") + return + if art.get("poster"): + meta["poster"] = art["poster"] + if art.get("logo"): + meta["logo"] = art["logo"] + if art.get("background"): + meta["background"] = art["background"] + + + +def _year_label(item: dict) -> str: + """Single year or range for Stremio releaseInfo (e.g. 1999-2024).""" + start = item.get("release_year") + end = item.get("release_year_end") + if not start: + return "" + try: + start_i = int(start) + except (TypeError, ValueError): + return str(start) + if end: + try: + end_i = int(end) + if end_i > start_i: + return f"{start_i}-{end_i}" + except (TypeError, ValueError): + pass + return str(start_i) + + +#----- Map an internal media item into a Stremio meta object +def _display_title(item: dict) -> str: + """Prefer English title when available, else canonical title.""" + eng = (item.get("title_english") or "").strip() + title = (item.get("title") or "").strip() + if eng and eng.lower() != title.lower(): + return eng + return eng or title or "Unknown" + + +def _safe_moviedb_id(item: dict): + """Never emit null/None for moviedb_id (breaks some Stremio clients).""" + v = item.get("tmdb_id") + if v is None or str(v).strip().lower() in ("", "null", "none"): + return "" + try: + return int(v) + except (TypeError, ValueError): + return str(v) + def convert_to_stremio_meta(item: dict) -> dict: media_type = "series" if item.get("media_type") == "tv" else "movie" - + imdb = item.get("imdb_id") or "" meta = { - "id": item.get('imdb_id'), + "id": imdb, "type": media_type, - "name": item.get("title"), - "poster": item.get("poster") or "", + "name": _display_title(item), + "poster": _poster_url(imdb, item.get("poster"), media_type), "logo": item.get("logo") or "", - "year": item.get("release_year"), - "releaseInfo": str(item.get("release_year", "")), - "imdb_id": item.get("imdb_id", ""), - "moviedb_id": item.get("tmdb_id", ""), - "background": item.get("backdrop") or "", + "year": _year_label(item) or item.get("release_year") or "", + "releaseInfo": _year_label(item) or "", + "imdb_id": imdb, + "moviedb_id": _safe_moviedb_id(item), + "background": _abs_media_url(item.get("backdrop")), "genres": item.get("genres") or [], - "imdbRating": str(item.get("rating") or ""), + "imdbRating": str(item.get("rating") or "") if item.get("rating") not in (None, "") else "", "description": item.get("description") or "", "cast": item.get("cast") or [], "runtime": item.get("runtime") or "", @@ -64,15 +575,19 @@ def convert_to_stremio_meta(item: dict) -> dict: return meta +#----- Format a movie release date as an ISO string, or None def format_released_date(media): year = media.get("release_year") if year: try: - return datetime(int(year), 1, 1).isoformat() + "Z" - except: + y = int(str(year)[:4]) + return datetime(y, 1, 1).isoformat() + "Z" + except Exception: return None return None + +#----- Build a Stremio stream display name/title from a filename def format_stream_details(filename: str, quality: str, size: str, is_split: bool = False) -> tuple[str, str]: size_emoji = "📦" if is_split else "💾" try: @@ -107,6 +622,17 @@ def format_stream_details(filename: str, quality: str, size: str, is_split: bool return (stream_name, stream_title) +def parse_size_to_bytes(size_str: str) -> int: + if not size_str: + return 0 + match = re.match(r"([\d.]+)\s*([A-Za-z]+)", size_str.strip()) + if not match: + return 0 + value, unit = float(match.group(1)), match.group(2).upper() + multipliers = {"B": 1, "KB": 1024, "MB": 1024**2, "GB": 1024**3, "TB": 1024**4} + return int(value * multipliers.get(unit, 1)) + + def get_resolution_priority(stream_name: str) -> int: resolution_map = { "2160p": 2160, "4k": 2160, "uhd": 2160, @@ -120,20 +646,27 @@ def get_resolution_priority(stream_name: str) -> int: return res_value return 1 -# ------------------ Routes ----------------------- +#----- Canonical quality label used by per-token quality filtering +def stream_res_label(stream_name: str) -> str: + return {2160: "4K", 1080: "1080p", 720: "720p", 480: "480p", 360: "360p"}.get( + get_resolution_priority(stream_name), "other" + ) + + +#----- Manifest describing the addon's catalogs/resources for this token @router.get("/{token}/manifest.json") async def get_manifest(token: str, token_data: dict = Depends(verify_token)): if SettingsManager.current().hide_catalog: - resources = ["stream"] + resources = ["stream", "subtitles"] catalogs = [] else: - resources = ["catalog", "meta", "stream"] + resources = ["catalog", "meta", "stream", "subtitles"] catalogs = [ { "type": "movie", "id": "latest_movies", - "name": "Latest", + "name": "Recently Added", "extra": [ {"name": "genre", "isRequired": False, "options": GENRES}, {"name": "skip"} @@ -154,7 +687,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)): { "type": "series", "id": "latest_series", - "name": "Latest", + "name": "Recently Added", "extra": [ {"name": "genre", "isRequired": False, "options": GENRES}, {"name": "skip"} @@ -171,15 +704,38 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)): {"name": "search", "isRequired": False} ], "extraSupported": ["genre", "skip", "search"] + }, + { + "type": "movie", + "id": "trending_movies", + "name": "Trending", + "extra": [ + {"name": "genre", "isRequired": False, "options": GENRES}, + {"name": "skip"} + ], + "extraSupported": ["genre", "skip"] + }, + { + "type": "series", + "id": "trending_series", + "name": "Trending", + "extra": [ + {"name": "genre", "isRequired": False, "options": GENRES}, + {"name": "skip"} + ], + "extraSupported": ["genre", "skip"] } ] try: - custom_catalogs = await db.get_custom_catalogs(visible_only=True) + custom_catalogs = await db.get_custom_catalogs(slim=True) for catalog in custom_catalogs: - items = catalog.get("items") or [] - has_movie = any(i.get("media_type") == "movie" for i in items) - has_series = any(i.get("media_type") == "tv" for i in items) + visible_items = [ + i for i in (catalog.get("items") or []) + if _token_can_view(*_effective_visibility(catalog, i), token_data) + ] + has_movie = any(i.get("media_type") == "movie" for i in visible_items) + has_series = any(i.get("media_type") == "tv" for i in visible_items) if not has_movie and not has_series: continue catalog_id = str(catalog.get("_id")) @@ -189,49 +745,67 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)): "type": "movie", "id": f"custom_{catalog_id}", "name": catalog_name, - "extra": [{"name": "skip"}], - "extraSupported": ["skip"], + "extra": [{"name": "search", "isRequired": False}, {"name": "skip"}], + "extraSupported": ["search", "skip"], }) if has_series: catalogs.append({ "type": "series", "id": f"custom_{catalog_id}", "name": catalog_name, - "extra": [{"name": "skip"}], - "extraSupported": ["skip"], + "extra": [{"name": "search", "isRequired": False}, {"name": "skip"}], + "extraSupported": ["search", "skip"], }) except Exception: pass + try: + order = await db.get_catalog_order() + token_order = (token_data.get("config") or {}).get("catalog_order") or [] + effective = token_order or order + if effective: + rank = {k: i for i, k in enumerate(effective)} + + def _crank(c): + key = f"{c.get('id')}::{c.get('type')}" + return rank.get(key, rank.get(c.get("id"), len(effective) + 1)) + + catalogs.sort(key=_crank) + hidden = set((token_data.get("config") or {}).get("hidden_catalogs") or []) + hidden |= set(await db.get_hidden_catalogs()) + if hidden: + catalogs = [ + c for c in catalogs + if c.get("id") not in hidden and f"{c.get('id')}::{c.get('type')}" not in hidden + ] + except Exception: + pass + addon_name = ADDON_NAME addon_desc = "Streams movies and series from your Telegram." addon_version = ADDON_VERSION - expiry_obj = None - if SettingsManager.current().subscription: - user_id = token_data.get("user_id") - if user_id: - try: + #----- Show expiry info in the addon: token's own expiry first, else the subscription + try: + expiry_obj = token_data.get("expires_at") + if expiry_obj is None and SettingsManager.current().subscription: + user_id = token_data.get("user_id") + if user_id: user = await db.get_user(int(user_id)) if user and user.get("subscription_status") == "active": expiry_obj = user.get("subscription_expiry") - if expiry_obj: - expiry_str = expiry_obj.strftime("%d %b %Y").lstrip("0") - addon_name = f"{ADDON_NAME} — Expires {expiry_str}" - addon_desc = ( - f"📅 Subscription active until {expiry_str}.\n" - f"Streams movies and series from your Telegram." - ) - epoch_tag = format(int(expiry_obj.timestamp()) & 0xFFFF, "x") - addon_version = f"{ADDON_VERSION}-{epoch_tag}" - else: - addon_name = f"{ADDON_NAME} — Active" - addon_desc = "✅ Subscription active.\nStreams movies and series from your Telegram." - except Exception: - pass - configure_url = f"{SettingsManager.current().base_url}/stremio/{token}/configure" + if expiry_obj: + expiry_str = expiry_obj.strftime("%d %b %Y").lstrip("0") + addon_desc = ( + f"📅 Access active until {expiry_str}.\n" + f"Streams movies and series from your Telegram." + ) + epoch_tag = format(int(expiry_obj.timestamp()) & 0xFFFF, "x") + addon_version = f"{ADDON_VERSION}-{epoch_tag}" + except Exception: + pass return { "id": f"telegram.media.{token[:8]}", @@ -242,7 +816,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)): "types": ["movie", "series"], "resources": resources, "catalogs": catalogs, - "idPrefixes": ["tt"], + "idPrefixes": ["tt", "tg", "kitsu"] + (["tmdb"] if tmdb_api_key() else []), "behaviorHints": { "configurable": True, "configurationRequired": False @@ -258,6 +832,777 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)): } +async def build_nuvio_collection_data(token: str, collection_type: str = "full", token_data: Optional[dict] = None) -> list: + addon_id = f"telegram.media.{token[:8]}" + + if token_data is None and token: + try: + token_data = await db.get_api_token(token) + except Exception: + token_data = None + + # Map catalog names to catalog IDs for this token, separated by media type + catalog_movies_map = {} + catalog_series_map = {} + auto_key_movies_map = {} + auto_key_series_map = {} + + try: + custom_catalogs = await db.get_custom_catalogs(slim=True) + for catalog in custom_catalogs: + # Check visibility and items + raw_items = catalog.get("items") or [] + visible_items = [ + i for i in raw_items + if _token_can_view(*_effective_visibility(catalog, i), token_data) + ] + + has_movie = any(i.get("media_type") == "movie" for i in visible_items) + has_series = any(i.get("media_type") == "tv" for i in visible_items) + + cid = f"custom_{catalog.get('_id')}" + name = (catalog.get("name") or "").lower().strip() + auto_key = (catalog.get("auto_key") or "").lower().strip() + + if has_movie: + catalog_movies_map[name] = cid + if auto_key: + auto_key_movies_map[auto_key] = cid + if has_series: + catalog_series_map[name] = cid + if auto_key: + auto_key_series_map[auto_key] = cid + except Exception: + pass + + # Helper to get catalog ID for movies and series only if they actually have content + def get_cat_id(name_query: str, auto_key: str = "", media_type: str = "movie", fallback: Optional[str] = None, strict: bool = True): + cmap = catalog_movies_map if media_type == "movie" else catalog_series_map + amap = auto_key_movies_map if media_type == "movie" else auto_key_series_map + if auto_key and auto_key.lower() in amap: + return amap[auto_key.lower()] + for name, cid in cmap.items(): + if name_query.lower() in name: + return cid + return None if strict else fallback + + hotstar_movie = get_cat_id("hotstar", "auto_hotstar", "movie", strict=True) + hotstar_series = get_cat_id("hotstar", "auto_hotstar", "series", strict=True) + netflix_movie = get_cat_id("netflix", "auto_netflix", "movie", strict=True) + netflix_series = get_cat_id("netflix", "auto_netflix", "series", strict=True) + prime_movie = get_cat_id("prime", "auto_prime_video", "movie", strict=True) + prime_series = get_cat_id("prime", "auto_prime_video", "series", strict=True) + apple_movie = get_cat_id("apple", "auto_apple_tv", "movie", strict=True) + apple_series = get_cat_id("apple", "auto_apple_tv", "series", strict=True) + hbo_movie = get_cat_id("hbo", "auto_hbo", "movie", strict=True) + hbo_series = get_cat_id("hbo", "auto_hbo", "series", strict=True) + hulu_movie = get_cat_id("hulu", "auto_hulu", "movie", strict=True) + hulu_series = get_cat_id("hulu", "auto_hulu", "series", strict=True) + mx_movie = get_cat_id("mx", "auto_mx_player", "movie", strict=True) + mx_series = get_cat_id("mx", "auto_mx_player", "series", strict=True) + sony_movie = get_cat_id("sony", "auto_sonyliv", "movie", strict=True) + sony_series = get_cat_id("sony", "auto_sonyliv", "series", strict=True) + zee5_movie = get_cat_id("zee", "auto_zee5", "movie", strict=True) + zee5_series = get_cat_id("zee", "auto_zee5", "series", strict=True) + crunchyroll_movie = get_cat_id("crunchyroll", "auto_crunchyroll", "movie", strict=True) + crunchyroll_series = get_cat_id("crunchyroll", "auto_crunchyroll", "series", strict=True) + bollywood_movie = get_cat_id("bollywood", "auto_bollywood", "movie", strict=True) + bollywood_series = get_cat_id("bollywood", "auto_bollywood", "series", strict=True) + south_indian_movie = get_cat_id("south indian", "auto_south_indian", "movie", strict=True) + south_indian_series = get_cat_id("south indian", "auto_south_indian", "series", strict=True) + kdrama_movie = get_cat_id("korean", "auto_korean", "movie", strict=True) + kdrama_series = get_cat_id("k-drama", "auto_kdrama", "series", strict=True) or get_cat_id("korean", "auto_korean", "series", strict=True) + anime_movie = get_cat_id("anime", "auto_anime", "movie", strict=True) + anime_series = get_cat_id("anime", "auto_anime", "series", strict=True) + latest_releases_movie = get_cat_id("latest releases", "auto_latest_releases", "movie", strict=True) + latest_releases_series = get_cat_id("latest releases", "auto_latest_releases", "series", strict=True) + + # ========================================================================= + # 01 ✦ DISCOVER COLLECTION (TMDB Global Trends + Local Addon Fallback) + # ========================================================================= + K_IMG = "https://raw.githubusercontent.com/Kaoxt/The-Kollection/main/images" + NUVIO_CDN = "https://cdn.jsdelivr.net/gh/weebzone/Telegram-Stremio@master/assets/nuvio" + + # ========================================================================= + # 01 ✦ DISCOVER COLLECTION (TMDB Global Trends + Local Addon Fallback) + # ========================================================================= + discover_collection = { + "id": "collection-discover-main", + "title": "Discover", + "folders": [ + { + "id": "folder-discover-trending", + "title": "Trending Now", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": "trending_movies"}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": "trending_series"}, + {"title": "Trending Movies", "sortBy": "popularity.desc", "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "DISCOVER"}, + {"title": "Trending TV Series", "sortBy": "popularity.desc", "provider": "tmdb", "mediaType": "TV", "tmdbSourceType": "DISCOVER"} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Discover/Trending/logo.webp", + "coverImageUrl": f"{K_IMG}/Discover/Trending/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Discover/Trending/backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": "trending_movies"}, + {"type": "series", "addonId": addon_id, "catalogId": "trending_series"} + ], + "focusGifEnabled": False + }, + { + "id": "folder-discover-latest-releases", + "title": "Latest Releases", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": latest_releases_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": latest_releases_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Discover/Premieres/logo.webp", + "coverImageUrl": f"{K_IMG}/Discover/Premieres/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Discover/Premieres/backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": latest_releases_movie}, + {"type": "series", "addonId": addon_id, "catalogId": latest_releases_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-discover-popular", + "title": "Popular Hits", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": "top_movies"}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": "top_series"}, + {"title": "Popular Movies", "sortBy": "popularity.desc", "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "DISCOVER"}, + {"title": "Popular Series", "sortBy": "popularity.desc", "provider": "tmdb", "mediaType": "TV", "tmdbSourceType": "DISCOVER"} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Discover/Popular/logo.webp", + "coverImageUrl": f"{K_IMG}/Discover/Popular/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Discover/Popular/backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": "top_movies"}, + {"type": "series", "addonId": addon_id, "catalogId": "top_series"} + ], + "focusGifEnabled": False + }, + { + "id": "folder-discover-latest", + "title": "Recently Added", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": "latest_movies"}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": "latest_series"}, + { + "title": "Latest Released Movies", + "sortBy": "primary_release_date.desc", + "filters": { + "voteCountGte": 15, + "releaseDateGte": (datetime.now(timezone.utc) - timedelta(days=90)).strftime("%Y-%m-%d"), + "releaseDateLte": datetime.now(timezone.utc).strftime("%Y-%m-%d") + }, + "provider": "tmdb", + "mediaType": "MOVIE", + "tmdbSourceType": "DISCOVER" + }, + { + "title": "New TV Series Episodes", + "sortBy": "first_air_date.desc", + "filters": { + "voteCountGte": 10, + "releaseDateGte": (datetime.now(timezone.utc) - timedelta(days=90)).strftime("%Y-%m-%d"), + "releaseDateLte": datetime.now(timezone.utc).strftime("%Y-%m-%d") + }, + "provider": "tmdb", + "mediaType": "TV", + "tmdbSourceType": "DISCOVER" + } + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/RecentlyAdded_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/RecentlyAdded_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/RecentlyAdded_backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": "latest_movies"}, + {"type": "series", "addonId": addon_id, "catalogId": "latest_series"} + ], + "focusGifEnabled": False + } + ], + "pinToTop": True, + "viewMode": "TABBED_GRID", + "showAllTab": True, + "focusGlowEnabled": True + } + + # ========================================================================= + # 02 ✦ STREAMING PLATFORMS (OTT Hubs) + # ========================================================================= + ott_collection = { + "id": "collection-erfs5gwk-community", + "title": "Streaming Platforms", + "folders": [ + { + "id": "folder-WFGY1XPD", + "title": "Netflix", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": netflix_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": netflix_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Netflix/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/Netflix.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Netflix.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": netflix_movie}, + {"type": "series", "addonId": addon_id, "catalogId": netflix_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-AT8KYHZO", + "title": "Prime Video", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": prime_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": prime_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Prime/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/PrimeVideo.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/PrimeVideo.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": prime_movie}, + {"type": "series", "addonId": addon_id, "catalogId": prime_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-8ZBZOMW9", + "title": "JioHotstar", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": hotstar_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": hotstar_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Disney+/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/JioHotstar.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/JioHotstar.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": hotstar_movie}, + {"type": "series", "addonId": addon_id, "catalogId": hotstar_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-IQTF27K8", + "title": "Apple TV", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": apple_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": apple_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Apple%20TV/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/AppleTV.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/AppleTV.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": apple_movie}, + {"type": "series", "addonId": addon_id, "catalogId": apple_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-OA4T8NYO", + "title": "HBO Max", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": hbo_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": hbo_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/HBO%20Max/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/HBOMax.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/HBOMax.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": hbo_movie}, + {"type": "series", "addonId": addon_id, "catalogId": hbo_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-LN9SPMQN", + "title": "Hulu", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": hulu_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": hulu_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Hulu/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/hulu.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/hulu.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": hulu_movie}, + {"type": "series", "addonId": addon_id, "catalogId": hulu_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-ZEE5-OTT", + "title": "ZEE5", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": zee5_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": zee5_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": "https://cdn.jsdelivr.net/gh/luckynumb3rs/stremio-perfect-setup/collections/streaming/title/zee5.webp", + "coverImageUrl": f"{NUVIO_CDN}/Zee5.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Zee5.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": zee5_movie}, + {"type": "series", "addonId": addon_id, "catalogId": zee5_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-SONY-OTT", + "title": "SonyLIV", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": sony_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": sony_series} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Studios/Sony%20Pictures/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/SonyLiv.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/SonyLiv.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": sony_movie}, + {"type": "series", "addonId": addon_id, "catalogId": sony_series} + ], + "focusGifEnabled": False + }, + { + "id": "85a10640-79f2-435f-9d63-348e921e37f4", + "title": "Crunchyroll", + "sources": [ + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": crunchyroll_series}, + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": crunchyroll_movie} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Streaming%20Platforms/Crunchyroll/logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/Crunchyroll.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Crunchyroll.webp", + "catalogSources": [ + {"type": "series", "addonId": addon_id, "catalogId": crunchyroll_series}, + {"type": "movie", "addonId": addon_id, "catalogId": crunchyroll_movie} + ], + "focusGifEnabled": False + } + ], + "pinToTop": True, + "viewMode": "TABBED_GRID", + "showAllTab": True, + "focusGlowEnabled": True + } + + # Sanitize OTT folders: keep only those with active sources and strip any null catalogIds + cleaned_ott_folders = [] + for f in ott_collection.get("folders") or []: + sources = [s for s in f.get("sources") or [] if s.get("catalogId")] + catalog_sources = [cs for cs in f.get("catalogSources") or [] if cs.get("catalogId")] + if sources: + folder_copy = dict(f) + folder_copy["sources"] = sources + folder_copy["catalogSources"] = catalog_sources + cleaned_ott_folders.append(folder_copy) + ott_collection["folders"] = cleaned_ott_folders + + # ========================================================================= + # 03 ✦ FRANCHISES & UNIVERSES (Curated Sagas - Kaoxt The-Kollection) + # ========================================================================= + franchises_collection = { + "id": "collection-franchises-main", + "title": "Franchises & Universes", + "folders": [ + { + "id": "folder-mcu-universe", + "title": "Marvel Cinematic Universe", + "sources": [ + {"title": "Marvel Studios Movies", "sortBy": "primary_release_date.desc", "tmdbId": 420, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COMPANY"}, + {"title": "Marvel Studios Series", "sortBy": "primary_release_date.desc", "tmdbId": 420, "provider": "tmdb", "mediaType": "TV", "tmdbSourceType": "COMPANY"}, + {"title": "Spider-Man Films", "sortBy": "rank", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 36436842}, + {"title": "X-Men Universe", "sortBy": "original", "tmdbId": 27741, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "LIST"} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Studios/Marvel/logo.webp", + "coverImageUrl": f"{K_IMG}/Studios/Marvel/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Studios/Marvel/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-dcu-universe", + "title": "DC Universe & Batman", + "sources": [ + {"title": "DC Extended Universe", "sortBy": "original", "tmdbId": 85568, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "LIST"}, + {"title": "Batman Collection", "sortBy": "original", "tmdbId": 263, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "DC Animated Originals", "sortBy": "original", "tmdbId": 3255, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "LIST"} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Studios/DC/logo.webp", + "coverImageUrl": f"{K_IMG}/Studios/DC/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Studios/DC/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-starwars-universe", + "title": "Star Wars Universe", + "sources": [ + {"title": "Star Wars Movies", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 22202556}, + {"title": "Star Wars: Shows & Series", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "TV", "traktListId": 22757470} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Franchises/Star%20Wars/logo.webp", + "coverImageUrl": f"{K_IMG}/Franchises/Star%20Wars/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Franchises/Star%20Wars/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-james-bond-007", + "title": "James Bond (007)", + "sources": [ + {"title": "The James Bond (007) Collection", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 1919354} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Franchises/007/logo.webp", + "coverImageUrl": f"{K_IMG}/Franchises/007/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Franchises/007/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-lotr-middleearth", + "title": "Middle-Earth (LOTR & The Hobbit)", + "sources": [ + {"title": "The Lord of the Rings Collection", "sortBy": "original", "tmdbId": 119, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "The Hobbit Collection", "sortBy": "original", "tmdbId": 121938, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "Middle-Earth Saga", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 1642688} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Franchises/The%20Lord%20of%20the%20Rings/logo.webp", + "coverImageUrl": f"{K_IMG}/Franchises/The%20Lord%20of%20the%20Rings/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Franchises/The%20Lord%20of%20the%20Rings/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-harry-potter", + "title": "Harry Potter & Wizarding World", + "sources": [ + {"title": "Harry Potter Collection", "sortBy": "original", "tmdbId": 1241, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "Fantastic Beasts Collection", "sortBy": "original", "tmdbId": 435259, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "Wizarding World", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 84} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Franchises/Harry%20Potter/logo.webp", + "coverImageUrl": f"{K_IMG}/Franchises/Harry%20Potter/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Franchises/Harry%20Potter/backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + }, + { + "id": "folder-ultimate-sagas", + "title": "The Ultimate Sagas & Marathons", + "sources": [ + {"title": "Dune Collection", "sortBy": "original", "tmdbId": 726871, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "COLLECTION"}, + {"title": "The Fast and the Furious", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 75}, + {"title": "John Wick", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 2435487}, + {"title": "The MonsterVerse", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 25439284}, + {"title": "Mission: Impossible", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 131}, + {"title": "Jurassic Park/World", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 29684902}, + {"title": "Transformers", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 176}, + {"title": "The Matrix", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 81}, + {"title": "Avatar", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 884}, + {"title": "Pirates of the Caribbean", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 10}, + {"title": "Jason Bourne", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 36572888}, + {"title": "Top Gun", "sortBy": "released", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 5022174} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/Sagas_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/Sagas_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Sagas_backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + } + ], + "pinToTop": True, + "viewMode": "TABBED_GRID", + "showAllTab": True, + "focusGlowEnabled": True + } + + # ========================================================================= + # 04 ✦ REGIONAL & SPOTLIGHT (Languages + Seasonal) + # ========================================================================= + spotlight_collection = { + "id": "collection-spotlight-regional", + "title": "Regional & Spotlight", + "folders": [ + { + "id": "folder-bollywood-hindi", + "title": "Bollywood 🇮🇳", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": bollywood_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": bollywood_series}, + { + "title": "Top Bollywood Hits", + "sortBy": "popularity.desc", + "filters": {"withOriginalLanguage": "hi"}, + "provider": "tmdb", + "mediaType": "MOVIE", + "tmdbSourceType": "DISCOVER" + } + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/Bollywood_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/Bollywood_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Bollywood_backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": bollywood_movie}, + {"type": "series", "addonId": addon_id, "catalogId": bollywood_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-south-indian", + "title": "South Indian Cinema", + "sources": [ + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": south_indian_movie}, + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": south_indian_series}, + { + "title": "South Indian Blockbusters", + "sortBy": "popularity.desc", + "filters": {"withOriginalLanguage": "te|ta|ml|kn"}, + "provider": "tmdb", + "mediaType": "MOVIE", + "tmdbSourceType": "DISCOVER" + } + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/SouthIndian_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/SouthIndian_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/SouthIndian_backdrop.webp", + "catalogSources": [ + {"type": "movie", "addonId": addon_id, "catalogId": south_indian_movie}, + {"type": "series", "addonId": addon_id, "catalogId": south_indian_series} + ], + "focusGifEnabled": False + }, + { + "id": "folder-anime-spotlight", + "title": "Anime Spotlight 🇯🇵", + "sources": [ + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": anime_series}, + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": anime_movie}, + { + "title": "Trending Anime Series", + "sortBy": "popularity.desc", + "filters": { + "withGenres": "16", + "voteCountGte": 60, + "withoutKeywords": "198385|378816|155477|256466|329280|570|1817|15078|13059|195669|325693|360629|284535|356759|337946", + "withOriginalLanguage": "ja" + }, + "provider": "tmdb", + "mediaType": "TV", + "tmdbSourceType": "DISCOVER" + }, + { + "title": "Trending Anime Films", + "sortBy": "popularity.desc", + "filters": { + "withGenres": "16", + "voteCountGte": 120, + "withoutKeywords": "198385|378816|155477|256466|329280|570|1817|15078|13059|195669|325693|360629|284535|356759|337946", + "withOriginalLanguage": "ja" + }, + "provider": "tmdb", + "mediaType": "MOVIE", + "tmdbSourceType": "DISCOVER" + } + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{K_IMG}/Anime/Popular/logo.webp", + "coverImageUrl": f"{K_IMG}/Anime/Popular/cover.webp", + "heroBackdropUrl": f"{K_IMG}/Anime/Popular/backdrop.webp", + "catalogSources": [ + {"type": "series", "addonId": addon_id, "catalogId": anime_series}, + {"type": "movie", "addonId": addon_id, "catalogId": anime_movie} + ], + "focusGifEnabled": False + }, + { + "id": "folder-kdrama-korean", + "title": "K-Drama & Korean Waves 🇰🇷", + "sources": [ + {"type": "series", "addonId": addon_id, "provider": "addon", "catalogId": kdrama_series}, + {"type": "movie", "addonId": addon_id, "provider": "addon", "catalogId": kdrama_movie}, + { + "title": "Trending K-Dramas", + "sortBy": "popularity.desc", + "filters": {"withOriginalLanguage": "ko"}, + "provider": "tmdb", + "mediaType": "TV", + "tmdbSourceType": "DISCOVER" + }, + { + "title": "Top Korean Cinema", + "sortBy": "vote_average.desc", + "filters": {"withOriginalLanguage": "ko", "voteCountGte": 200}, + "provider": "tmdb", + "mediaType": "MOVIE", + "tmdbSourceType": "DISCOVER" + } + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/KDrama_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/KDrama_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/KDrama_backdrop.webp", + "catalogSources": [ + {"type": "series", "addonId": addon_id, "catalogId": kdrama_series}, + {"type": "movie", "addonId": addon_id, "catalogId": kdrama_movie} + ], + "focusGifEnabled": False + }, + { + "id": "folder-seasonal-holidays", + "title": "Seasonal & Holiday Specials 🎃 🎄", + "sources": [ + {"title": "Christmas Holiday Collection", "sortBy": "rank", "sortHow": "asc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 20735298}, + {"title": "Halloween & Spooky Season", "sortBy": "released", "sortHow": "desc", "provider": "trakt", "mediaType": "MOVIE", "traktListId": 3877179}, + {"title": "Valentine's Day (Romance & Date Night)", "sortBy": "popularity.desc", "filters": {"withGenres": "10749", "voteCountGte": 150}, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "DISCOVER"}, + {"title": "Summer Blockbusters & Popcorn Hits", "sortBy": "popularity.desc", "filters": {"withGenres": "28|12", "voteCountGte": 300}, "provider": "tmdb", "mediaType": "MOVIE", "tmdbSourceType": "DISCOVER"} + ], + "hideTitle": False, + "tileShape": "landscape", + "focusGifUrl": "", + "titleLogoUrl": f"{NUVIO_CDN}/Seasonal_logo.webp", + "coverImageUrl": f"{NUVIO_CDN}/Seasonal_cover.webp", + "heroBackdropUrl": f"{NUVIO_CDN}/Seasonal_backdrop.webp", + "catalogSources": [], + "focusGifEnabled": False + } + ], + "pinToTop": True, + "viewMode": "TABBED_GRID", + "showAllTab": True, + "focusGlowEnabled": True + } + + # Sanitize all collections to guarantee Nuvio never encounters a null catalogId: + def _sanitize_collection(coll: dict) -> dict: + cleaned_folders = [] + for f in coll.get("folders") or []: + sources = [ + s for s in (f.get("sources") or []) + if s.get("provider") == "addon" and s.get("catalogId") + ] + if not sources: + continue + folder_copy = dict(f) + folder_copy["sources"] = sources + folder_copy["catalogSources"] = [ + cs for cs in (f.get("catalogSources") or []) + if cs.get("catalogId") + ] + cleaned_folders.append(folder_copy) + coll_copy = dict(coll) + coll_copy["folders"] = cleaned_folders + return coll_copy + + by_type = { + "discover": [discover_collection], + "ott": [ott_collection], + "franchises": [franchises_collection], + "spotlight": [spotlight_collection], + } + collections = by_type.get(collection_type, [discover_collection, ott_collection, franchises_collection, spotlight_collection]) + return [c for c in map(_sanitize_collection, collections) if c["folders"]] + + +#----- Dynamic Nuvio Collection JSON for this token +@router.get("/{token}/nuvio-collection.json") +async def get_nuvio_collection(token: str, token_data: dict = Depends(verify_token)): + return await build_nuvio_collection_data(token, "full", token_data) + + +@router.get("/{token}/nuvio-discover-collection.json") +async def get_nuvio_discover_collection(token: str, token_data: dict = Depends(verify_token)): + return await build_nuvio_collection_data(token, "discover", token_data) + + +@router.get("/{token}/nuvio-ott-collection.json") +async def get_nuvio_ott_collection(token: str, token_data: dict = Depends(verify_token)): + return await build_nuvio_collection_data(token, "ott", token_data) + + +@router.get("/{token}/nuvio-explore-collection.json") +@router.get("/{token}/nuvio-franchises-collection.json") +async def get_nuvio_franchises_collection(token: str, token_data: dict = Depends(verify_token)): + return await build_nuvio_collection_data(token, "franchises", token_data) + + +@router.get("/{token}/nuvio-spotlight-collection.json") +async def get_nuvio_spotlight_collection(token: str, token_data: dict = Depends(verify_token)): + return await build_nuvio_collection_data(token, "spotlight", token_data) + + +#----- Catalog listing (latest/popular/custom, with genre/search/skip) @router.get("/{token}/catalog/{media_type}/{id}/{extra:path}.json") @router.get("/{token}/catalog/{media_type}/{id}.json") async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] = None, token_data: dict = Depends(verify_token)): @@ -267,6 +1612,9 @@ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] if media_type not in ["movie", "series"]: raise HTTPException(status_code=404, detail="Invalid catalog type") + if {id, f"{id}::{media_type}"} & set(await db.get_hidden_catalogs()): + return {"metas": []} + genre_filter = None search_query = None stremio_skip = 0 @@ -287,25 +1635,74 @@ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] page = (stremio_skip // PAGE_SIZE) + 1 try: - if id.startswith("custom_"): + if id.startswith("custom_") or id.startswith("auto_"): catalog_id = id.removeprefix("custom_") catalog = await db.get_custom_catalog(catalog_id) - if not catalog or not catalog.get("visible", True): + if not catalog: return {"metas": []} db_media_type = "tv" if media_type == "series" else "movie" - data = await db.get_custom_catalog_items( - catalog_id=catalog_id, - media_type=db_media_type, - page=page, - page_size=PAGE_SIZE, - ) - items = data.get("items", []) + visible_items = [ + it for it in (catalog.get("items") or []) + if it.get("media_type") == db_media_type + and _token_can_view(*_effective_visibility(catalog, it), token_data) + ] + visible_items.sort(key=catalog_sort_key, reverse=True) + if search_query: + ids = [int(it["tmdb_id"]) for it in visible_items if it.get("tmdb_id") is not None] + found = await db.search_documents( + query=search_query, page=page, page_size=PAGE_SIZE, + extra_filter=_merge_filters({"tmdb_id": {"$in": ids}}, _visibility_query(token_data)), + media_type=db_media_type, + ) + items = [it for it in found.get("results", []) if it.get("media_type") == db_media_type] + else: + start = (page - 1) * PAGE_SIZE + items = await db.get_documents(visible_items[start:start + PAGE_SIZE]) + items = [it for it in items if _token_can_view(it.get("visibility") or "public", it.get("allowed_tokens") or [], token_data)] elif search_query: - search_results = await db.search_documents(query=search_query, page=page, page_size=PAGE_SIZE) + search_results = await db.search_documents( + query=search_query, page=page, page_size=PAGE_SIZE, + extra_filter=_merge_filters(_visibility_query(token_data), _not_exclusive_clause(allow_searchable=True)), + media_type="tv" if media_type == "series" else "movie", + ) all_items = search_results.get("results", []) db_media_type = "tv" if media_type == "series" else "movie" items = [item for item in all_items if item.get("media_type") == db_media_type] + elif id in {"trending_movies", "trending_series"}: + expected_type = "movie" if id == "trending_movies" else "series" + if media_type != expected_type: + return {"metas": []} + + items = [] + tmdb_type = "movie" if media_type == "movie" else "tv" + trending_ids = await _get_tmdb_trending_ids(tmdb_type, "day") + if trending_ids: + db_matches = await _get_db_matches_in_tmdb_order( + media_type, trending_ids, token_data, genre_filter=genre_filter + ) + if search_query: + q = search_query.lower() + db_matches = [ + it for it in db_matches + if q in (it.get("title") or "").lower() + or q in (it.get("name") or "").lower() + or q in (it.get("original_title") or "").lower() + ] + start = max(stremio_skip, 0) + items = db_matches[start:start + PAGE_SIZE] + + # Fallback to latest uploaded media if TMDB is unconfigured, empty, or returns no DB matches + if not items and stremio_skip == 0: + LOGGER.info(f"[TMDB Trending] Falling back to latest {media_type} for catalog {id}") + sort_params = [("updated_on", "desc")] + vis_filter = _merge_filters(_visibility_query(token_data), _not_exclusive_clause()) + if media_type == "movie": + data = await db.sort_movies(sort_params, page, PAGE_SIZE, genre_filter=genre_filter, extra_filter=vis_filter, projection=META_PROJECTION) + items = data.get("movies", []) + else: + data = await db.sort_tv_shows(sort_params, page, PAGE_SIZE, genre_filter=genre_filter, extra_filter=vis_filter, projection=META_PROJECTION) + items = data.get("tv_shows", []) else: if "latest" in id: sort_params = [("updated_on", "desc")] @@ -314,16 +1711,19 @@ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] else: sort_params = [("updated_on", "desc")] + vis_filter = _merge_filters(_visibility_query(token_data), _not_exclusive_clause()) if media_type == "movie": - data = await db.sort_movies(sort_params, page, PAGE_SIZE, genre_filter=genre_filter) + data = await db.sort_movies(sort_params, page, PAGE_SIZE, genre_filter=genre_filter, extra_filter=vis_filter, projection=META_PROJECTION) items = data.get("movies", []) else: - data = await db.sort_tv_shows(sort_params, page, PAGE_SIZE, genre_filter=genre_filter) + data = await db.sort_tv_shows(sort_params, page, PAGE_SIZE, genre_filter=genre_filter, extra_filter=vis_filter, projection=META_PROJECTION) items = data.get("tv_shows", []) - except Exception as e: + except Exception: return {"metas": []} metas = [convert_to_stremio_meta(item) for item in items] + if SettingsManager.current().fanart_enabled: + await asyncio.gather(*(_apply_fanart(m, it) for m, it in zip(metas, items))) return {"metas": metas} @@ -332,104 +1732,324 @@ async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depe if SettingsManager.current().hide_catalog: raise HTTPException(status_code=404, detail="Catalog disabled") - try: - imdb_id = id - except (ValueError, IndexError): - raise HTTPException(status_code=400, detail="Invalid Stremio ID format") + parsed = _parse_stremio_id(id) + imdb_id = parsed["imdb_id"] if not parsed["is_kitsu"] and not parsed["is_tmdb"] else None + kitsu_id = parsed["kitsu_id"] + tmdb_id = parsed["tmdb_id"] - media = await db.get_media_details(imdb_id=imdb_id) + media = await db.get_media_details( + imdb_id=imdb_id, + kitsu_id=kitsu_id, + tmdb_id=tmdb_id, + media_type=media_type, + projection={"telegram": 0, "seasons.episodes.telegram": 0} + ) if not media: + fallback_meta = await _cached_external_meta(id, parsed, media_type) + return {"meta": fallback_meta or {}} + + if not _token_can_view(media.get("visibility") or "public", media.get("allowed_tokens") or [], token_data): return {"meta": {}} + meta_id = id + if parsed["is_kitsu"] and kitsu_id is not None: + meta_id = f"kitsu:{kitsu_id}" + elif parsed.get("is_tmdb") and tmdb_id is not None: + meta_id = f"tmdb:{'movie' if (parsed.get('tmdb_media_type') or ('movie' if media_type == 'movie' else 'tv')) == 'movie' else 'tv'}:{tmdb_id}" + elif media.get("imdb_id"): + meta_id = media.get("imdb_id") + meta_obj = { - "id": id, + "id": meta_id, "type": "series" if media.get("media_type") == "tv" else "movie", - "name": media.get("title", ""), - "description": media.get("description", ""), - "year": str(media.get("release_year", "")), - "imdbRating": str(media.get("rating", "")), - "genres": media.get("genres", []), - "poster": media.get("poster", ""), - "logo": media.get("logo", ""), - "background": media.get("backdrop", ""), - "imdb_id": media.get("imdb_id", ""), - "releaseInfo": str(media.get("release_year", "")), - "moviedb_id": media.get("tmdb_id", ""), + "name": _display_title(media), + "description": media.get("description") or "", + "year": _year_label(media) or (str(media.get("release_year")) if media.get("release_year") else ""), + "imdbRating": str(media.get("rating") or "") if media.get("rating") not in (None, "") else "", + "genres": media.get("genres") or [], + "poster": _poster_url(media.get("imdb_id") or imdb_id, media.get("poster"), "series" if media.get("media_type") == "tv" else "movie"), + "logo": media.get("logo") or "", + "background": _abs_media_url(media.get("backdrop")), + "imdb_id": media.get("imdb_id") or (id if not parsed["is_kitsu"] and not parsed.get("is_tmdb") else ""), + "releaseInfo": _year_label(media) or "", + "moviedb_id": _safe_moviedb_id(media), "cast": media.get("cast") or [], "runtime": media.get("runtime") or "", } + await _apply_fanart(meta_obj, media) + if media.get("media_type") == "movie": released_date = format_released_date(media) if released_date: meta_obj["released"] = released_date - # --- Add Episodes --- - if media_type == "series" and "seasons" in media: + if media_type == "series": yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat() videos = [] - for season in sorted(media.get("seasons", []), key=lambda s: s.get("season_number")): - for episode in sorted(season.get("episodes", []), key=lambda e: e.get("episode_number")): - episode_id = f"{id}:{season['season_number']}:{episode['episode_number']}" + seasons = media.get("seasons") or [] + + def _snum(s): + try: + return int(s.get("season_number")) + except (TypeError, ValueError): + return 0 + + def _enum(e): + try: + return int(e.get("episode_number")) + except (TypeError, ValueError): + return 0 + + for season in sorted(seasons, key=_snum): + s_num = _snum(season) + episodes = season.get("episodes") or [] + for episode in sorted(episodes, key=_enum): + e_num = _enum(episode) + if not episodes: + continue + abs_ep = episode.get("absolute_episode") + if parsed["is_kitsu"] and kitsu_id is not None: + if abs_ep is not None: + episode_id = f"kitsu:{kitsu_id}:{abs_ep}" + else: + episode_id = f"kitsu:{kitsu_id}:{s_num}:{e_num}" + else: + episode_id = f"{meta_id}:{s_num}:{e_num}" + ep_title = ( + episode.get("title") + or episode.get("episode_title") + or (f"E{e_num:02d}" if s_num != 0 else f"Combined {e_num}") + ) videos.append({ "id": episode_id, - "title": episode.get("title", f"Episode {episode['episode_number']}"), - "season": season.get("season_number"), - "episode": episode.get("episode_number"), - "overview": episode.get("overview") or "No description available for this episode yet.", - "released": episode.get("released") or yesterday, - "thumbnail": episode.get("episode_backdrop") or "https://raw.githubusercontent.com/weebzone/Colab-Tools/refs/heads/main/no_episode_backdrop.png", - "imdb_id": episode.get("imdb_id") or media.get("imdb_id"), + "title": ep_title, + "season": s_num, + "episode": e_num, + "overview": ( + episode.get("overview") + or episode.get("episode_overview") + or "No description available for this episode yet." + ), + "released": episode.get("released") or episode.get("episode_released") or yesterday, + "thumbnail": _abs_media_url( + episode.get("episode_backdrop") or episode.get("thumbnail") + ) or "https://raw.githubusercontent.com/weebzone/Colab-Tools/refs/heads/main/no_episode_backdrop.png", + "imdb_id": episode.get("imdb_id") or media.get("imdb_id") or ("" if parsed.get("is_tmdb") or parsed["is_kitsu"] else id), }) meta_obj["videos"] = videos + if not videos: + LOGGER.warning(f"[META] series {id} has no episode entries in DB") return {"meta": meta_obj} -async def _global_streams_for(token: str, imdb_id: str, media_type: str, season_num: Optional[int], episode_num: Optional[int]) -> list: - from Backend.helper.imdb import get_detail, get_season - imdb_media_type = "tvSeries" if media_type == "series" else "movie" +#----- Subtitles for a title/episode, sourced from subtitle files in the channels +@router.get("/{token}/subtitles/{media_type}/{id}/{extra:path}.json") +@router.get("/{token}/subtitles/{media_type}/{id}.json") +async def get_subtitles(token: str, media_type: str, id: str, extra: Optional[str] = None, token_data: dict = Depends(verify_token)): + try: + parts = id.split(":") + imdb_id = parts[0] + season = int(parts[1]) if len(parts) > 1 else None + episode = int(parts[2]) if len(parts) > 2 else None + except (ValueError, IndexError): + return {"subtitles": []} + + db_media_type = "tv" if media_type == "series" else "movie" + subs = await get_subtitles_for(imdb_id, db_media_type, season, episode) + if not subs: + return {"subtitles": []} + return {"subtitles": stremio_subtitle_entries(subs, token, SettingsManager.current().base_url)} + - detail = await get_detail(imdb_id=imdb_id, media_type=imdb_media_type) - if not detail or not detail.get("title"): - return [] +async def _kitsu_title_year(kitsu_id: int) -> tuple: + try: + from Backend.helper.metadata.providers.kitsu import get_anizip_mappings, _get_client, KITSU_URL + client = await _get_client() + resp = await client.get(f"{KITSU_URL}/anime/{int(kitsu_id)}") + resp.raise_for_status() + data = (resp.json() or {}).get("data") or {} + attrs = data.get("attributes") or {} + titles = attrs.get("titles") or {} + title = ( + titles.get("en") + or titles.get("en_jp") + or attrs.get("canonicalTitle") + or titles.get("ja_jp") + or "" + ) + year = None + start = attrs.get("startDate") or "" + if start and len(str(start)) >= 4: + try: + year = int(str(start)[:4]) + except (TypeError, ValueError): + year = None + if not title: + doc = await get_anizip_mappings(int(kitsu_id)) or {} + title = (doc.get("title") or {}).get("en") or (doc.get("title") or {}).get("x-jat") or "" + return title, year + except Exception as e: + LOGGER.warning(f"[KITSU] title lookup failed for {kitsu_id}: {e}") + return "", None + + +#----- Autoplay-next keeps the same quality and route (Cloudflare/Proxy/Direct) +def _binge_group(quality: str, suffix: str = "") -> str: + route = suffix.strip("() ").lower() + return f"telegram-stremio-{quality}" + (f"-{route}" if route else "") + + +def _streams_from_global_results(token: str, global_results: list) -> list: + streams = [] + for r in global_results: + is_split = bool(r.get("is_split")) + _, stream_title = format_stream_details(r["title"], r["quality"], r["size"], is_split=is_split) + stream_name = sort_name = f"🌐 GLOBAL {r['quality']}" + stream_title = f"{stream_title}\n📡 {r['source_chat']}" + if is_split: + kind = "zip parts" if r.get("is_zip") else "parts" + stream_title += f" · 📦 {r.get('part_count', 0)} {kind}" + size_bytes = parse_size_to_bytes(r.get("size", "")) + custom = format_stream(SettingsManager.current(), r["title"], size_bytes, addon_name="🌐 Global", + is_split=is_split, parts=r.get("part_count", 0), channel=r.get("source_chat")) + if custom: + stream_name, stream_title = custom + url = f"{SettingsManager.current().base_url}/dl/{token}/{r['token']}/{quote(r['title'])}" + if cf_enabled(): + cf_url = cf_stream_url(token, r['token'], quote(r['title'])) + if SettingsManager.current().cf_stream_mode == "cloudflare": + url = cf_url + else: + streams.append({"name": f"{stream_name} (Cloudflare)", "title": stream_title, "url": cf_url, "size_bytes": size_bytes, "sort_name": sort_name, + "behaviorHints": {"bingeGroup": _binge_group(f"global-{r['quality']}", "(Cloudflare)")}}) + streams.append({"name": stream_name, "title": stream_title, "url": url, "size_bytes": size_bytes, "sort_name": sort_name, + "behaviorHints": {"bingeGroup": _binge_group(f"global-{r['quality']}")}}) + return streams + + +async def _global_streams_for( + token: str, + imdb_id: str = None, + media_type: str = "series", + season_num: Optional[int] = None, + episode_num: Optional[int] = None, + kitsu_id: Optional[int] = None, + absolute_episode: Optional[int] = None, + is_anime: bool = False, +) -> list: + expected_title = "" + year = None + cinemeta_videos = [] + + if kitsu_id is not None: + expected_title, year = await _kitsu_title_year(int(kitsu_id)) + is_anime = True + elif imdb_id: + imdb_media_type = "tvSeries" if media_type == "series" else "movie" + detail = await get_detail(imdb_id=imdb_id, media_type=imdb_media_type) + if not detail or not detail.get("title"): + return [] + expected_title = detail["title"] + year = (detail.get("releaseDetailed") or {}).get("year") or None + cinemeta_videos = detail.get("videos") or [] + if season_num is not None and episode_num is not None and absolute_episode is None: + try: + await get_season(imdb_id=imdb_id, season_id=season_num, episode_id=episode_num) + except Exception: + pass - expected_title = detail["title"] - year = (detail.get("releaseDetailed") or {}).get("year") or None + if not expected_title: + return [] - if season_num is not None and episode_num is not None: + search_season = season_num + search_episode = episode_num + if is_anime and absolute_episode is not None: + search_season = None + search_episode = absolute_episode + elif is_anime and season_num is None and episode_num is not None: + search_season = None + search_episode = episode_num + + abs_ep = absolute_episode + map_source = None + if ( + abs_ep is None + and media_type == "series" + and imdb_id + and season_num is not None + and episode_num is not None + ): try: - await get_season(imdb_id=imdb_id, season_id=season_num, episode_id=episode_num) - except Exception: - pass # best-effort only; absence doesn't block the search + from Backend.helper.metadata.episode_maps import absolute_from_imdb_episode + + mapped = await absolute_from_imdb_episode( + imdb_id, + int(season_num), + int(episode_num), + title=expected_title, + videos=cinemeta_videos, + ) + if mapped and mapped.get("is_anime"): + is_anime = True + map_source = mapped.get("source") + abs_ep = mapped.get("absolute_episode") + if abs_ep is None and int(season_num) == 1: + abs_ep = int(episode_num) + except Exception as e: + LOGGER.warning(f"[GLOBAL SEARCH] anime map lookup failed for {imdb_id}: {e}") + + mapped_from_sxx = ( + abs_ep is not None + and absolute_episode is None + and season_num is not None + and episode_num is not None + ) + if mapped_from_sxx: + search_season = None + search_episode = int(abs_ep) + LOGGER.info( + f"[GLOBAL SEARCH] Anime mapped S{int(season_num):02d}E{int(episode_num):02d} " + f"→ absolute {int(abs_ep)} for '{expected_title}'" + + (f" (via {map_source})" if map_source else "") + + "; trying absolute first" + ) + auth_channels = SettingsManager.current().auth_channels try: global_results = await global_search( expected_title, - SettingsManager.current().auth_channels, + auth_channels, year=year, - season=season_num, - episode=episode_num, + season=search_season, + episode=search_episode, ) except Exception as e: LOGGER.error(f"[GLOBAL SEARCH] search failed for '{expected_title}': {e}") - return [] + global_results = [] - streams = [] - for r in global_results: - _, stream_title = format_stream_details(r["title"], r["quality"], r["size"], is_split=False) - stream_name = f"🌐 GLOBAL {r['quality']}" - stream_title = f"{stream_title}\n📡 {r['source_chat']}" - url = f"{SettingsManager.current().base_url}/dl/{token}/{r['token']}/{quote(r['title'])}" - streams.append({"name": stream_name, "title": stream_title, "url": url}) - return streams + if not global_results and mapped_from_sxx: + LOGGER.info( + f"[GLOBAL SEARCH] Absolute {int(abs_ep)} empty for '{expected_title}'; " + f"falling back to S{int(season_num):02d}E{int(episode_num):02d}" + ) + try: + global_results = await global_search( + expected_title, + auth_channels, + year=year, + season=season_num, + episode=episode_num, + ) + except Exception as e: + LOGGER.error(f"[GLOBAL SEARCH] SxxExx fallback failed for '{expected_title}': {e}") + global_results = [] + return _streams_from_global_results(token, global_results) -async def _is_subscription_member(user_id: int) -> bool: - import time - from Backend.pyrofork.bot import StreamBot - from pyrogram.enums import ChatMemberStatus - from pyrogram.errors import UserNotParticipant +#----- Cached check that a user is still in the subscription group (fail-open) +async def _is_subscription_member(user_id: int) -> bool: group_id = SettingsManager.current().subscription_group_id if not group_id: return True @@ -446,7 +2066,6 @@ async def _is_subscription_member(user_id: int) -> bool: except UserNotParticipant: result = False except Exception as e: - # Fail open and do NOT cache, so the next request retries. LOGGER.warning(f"[SUBSCRIPTION] Membership check failed for user {user_id}: {e}") return True @@ -460,35 +2079,47 @@ async def _is_subscription_member(user_id: int) -> bool: return result +#----- Resolve playable streams for a title (Telegram library or Global Search) @router.get("/{token}/stream/{media_type}/{id}.json") async def get_streams( token: str, media_type: str, id: str, + request: Request, token_data: dict = Depends(verify_token) ): + #----- Capture the real app/device from the addon-protocol UA (not the spoofed video UA) + asyncio.create_task(record_client( + token, + token_data.get("name") if token_data else None, + client_ip_from(request), + request.headers.get("user-agent", ""), + )) if token_data.get("subscription_expired"): return { "streams": [ { "name": "🚫 Plan Expired", - "title": "Your plan is expired.\nRenew it from the bot to continue watching.", + "title": "Your plan has expired.\nRenew it from the bot to continue watching.\n\n📖 Need help? Check the README / Setup Guide or contact your admin.", "url": get_streambot_url() } ] } - # When the subscription feature is on, the user must be a current member of - # the configured subscription group/channel to stream anything. - if SettingsManager.current().subscription: + #----- Subscription users must currently be members of the configured group. + #----- Admin, lifetime and admin-set token-expiry grants skip this check. + if (SettingsManager.current().subscription + and not token_data.get("is_admin") + and not token_data.get("subscription_exempt") + and not token_data.get("expires_at")): user_id = token_data.get("user_id") if user_id and not await _is_subscription_member(int(user_id)): return { "streams": [ { "name": "📢 Join Required", - "title": "First join the channel to stream it.\nThen wait for 2 min for verification", + "title": "First join the channel to stream it.\nThen wait 2 min for verification.\n\n📖 Read the README or contact your bot admin for setup instructions.", "url": get_streambot_url() } ] @@ -498,9 +2129,9 @@ async def get_streams( limit_type = token_data["limit_exceeded"] title = ( - "🚫 Daily Limit Reached – Upgrade Required" + "🚫 Daily Limit Reached – Upgrade Required\n\n📖 Read the README or contact your bot admin to upgrade." if limit_type == "daily" - else "🚫 Monthly Limit Reached – Upgrade Required" + else "🚫 Monthly Limit Reached – Upgrade Required\n\n📖 Read the README or contact your bot admin to upgrade." ) return { @@ -514,226 +2145,308 @@ async def get_streams( } try: - parts = id.split(":") - imdb_id = parts[0] - season_num = int(parts[1]) if len(parts) > 1 else None - episode_num = int(parts[2]) if len(parts) > 2 else None + parsed = _parse_stremio_id(id) + imdb_id = parsed["imdb_id"] + kitsu_id = parsed["kitsu_id"] + season_num = parsed["season_num"] + episode_num = parsed["episode_num"] + absolute_episode = parsed["absolute_episode"] + is_kitsu = parsed["is_kitsu"] + tmdb_id = parsed.get("tmdb_id") except (ValueError, IndexError): raise HTTPException(status_code=400, detail="Invalid Stremio ID format") + if is_kitsu and kitsu_id is None: + raise HTTPException(status_code=400, detail="Invalid Kitsu ID format") + + if not await _title_allowed( + imdb_id=imdb_id, + token_data=token_data, + kitsu_id=kitsu_id, + tmdb_id=tmdb_id, + media_type=media_type, + ): + return {"streams": []} + media_details = await db.get_media_details( imdb_id=imdb_id, season_number=season_num, - episode_number=episode_num + episode_number=episode_num, + kitsu_id=kitsu_id, + tmdb_id=tmdb_id, + media_type=media_type, + absolute_episode=absolute_episode, ) streams = [] + is_combined = season_num == COMBINED_SEASON and episode_num is not None and episode_num >= COMBINED_EPISODE_BASE + if media_details and "telegram" in media_details: + fmt_meta = { + "queryType": media_type, "type": media_type, "isAnime": bool(media_details.get("is_anime")), + "title": media_details.get("title"), "year": media_details.get("release_year"), + "season": season_num, "episode": episode_num, + } + via = own_bots.stream_via(token_data) for quality in media_details.get("telegram", []): if quality.get("id"): filename = quality.get("name", "") quality_str = quality.get("quality", "HD") size = quality.get("size", "") + size_bytes = parse_size_to_bytes(size) + + combined = parse_combined_episodes(filename) if is_combined else None + episode_start = combined.get("start") or 0 if combined else 0 + name_key = combined_name_key(filename) if combined else "" stream_name, stream_title = format_stream_details( filename, quality_str, size, is_split=bool(quality.get("group_key")) ) + sort_name = stream_name original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv" - proxy_url = f"{SettingsManager.current().http_proxy_url}{original_url}" if SettingsManager.current().http_proxy_url else None - - if SettingsManager.current().show_proxy_and_non_proxy_both and proxy_url: - streams.append({ - "name": f"{stream_name} (Proxy)", - "title": stream_title, - "url": proxy_url - }) - streams.append({ - "name": f"{stream_name} (Direct)", - "title": stream_title, - "url": original_url - }) - elif proxy_url: - streams.append({ - "name": stream_name, - "title": stream_title, - "url": proxy_url - }) + proxy_url = build_proxy_url(original_url) + if via: + cf_url = f"{original_url}?via=cf" if via != "bots" else None + cf_only = via == "cloudflare" else: - streams.append({ - "name": stream_name, - "title": stream_title, - "url": original_url - }) + cf_url = cf_stream_url(token, quality.get('id'), "video.mkv") if cf_enabled() else None + cf_only = cf_url and SettingsManager.current().cf_stream_mode == "cloudflare" + + def add(suffix, url, proxied=False): + name, title = stream_name, stream_title + custom = format_stream( + SettingsManager.current(), filename, size_bytes, addon_name=ADDON_NAME, proxied=proxied, + is_split=bool(quality.get("group_key")), meta=fmt_meta, + ) + if custom: + name, title = custom + if combined: + label = "Full" if combined.get("start") is None else f"E{combined['start']:02d}-E{combined['end']:02d}" + if label.lower() not in name.lower(): + name = f"{name} {label}" + streams.append({"name": f"{name} {suffix}".strip(), "title": title, "url": url, "size_bytes": size_bytes, + "episode_start": episode_start, "name_key": name_key, "sort_name": sort_name, + "behaviorHints": {"bingeGroup": _binge_group(quality_str, suffix)}}) + + if cf_url: + add("" if cf_only else "(Cloudflare)", cf_url) + if not cf_only: + if SettingsManager.current().show_proxy_and_non_proxy_both and proxy_url: + add("(Proxy)", proxy_url, True) + add("(Direct)", original_url) + else: + add("", proxy_url or original_url, bool(proxy_url)) elif is_global_search_enabled(): try: + is_anime = bool(is_kitsu or (media_details and media_details.get("is_anime"))) + log_id = f"kitsu:{kitsu_id}" if is_kitsu else imdb_id + LOGGER.info(f"{log_id}:{season_num}:{episode_num}:abs={absolute_episode}|{media_type}") streams.extend( - await _global_streams_for(token, imdb_id, media_type, season_num, episode_num) + await _global_streams_for( + token, + imdb_id=imdb_id, + media_type=media_type, + season_num=season_num, + episode_num=episode_num, + kitsu_id=kitsu_id, + absolute_episode=absolute_episode, + is_anime=is_anime, + ) ) except Exception as e: - LOGGER.error(f"[GLOBAL SEARCH] stream search failed for {imdb_id}: {e}") + LOGGER.error(f"[GLOBAL SEARCH] stream search failed for {id}: {e}") + + #----- Per-token quality filter (fall back to all if it would hide everything) + config = token_data.get("config") or {} + quality_filter = set(config.get("quality_filter") or []) + if quality_filter and streams: + filtered = [s for s in streams if stream_res_label(s.get("sort_name", s.get("name", ""))) in quality_filter] + if filtered: + streams = filtered if not streams: - return {"streams": []} + return {"streams": [_donation()]} - streams.sort( - key=lambda s: get_resolution_priority(s.get("name", "")), - reverse=True - ) + ascending = config.get("quality_sort") == "asc" + if is_combined: + streams.sort(key=lambda s: s.get("episode_start", 0)) + streams.sort(key=lambda s: s.get("name_key", "")) + streams.sort(key=lambda s: get_resolution_priority(s.get("sort_name", s.get("name", ""))), reverse=not ascending) + else: + streams.sort( + key=lambda s: (get_resolution_priority(s.get("sort_name", s.get("name", ""))), s.get("size_bytes", 0)), + reverse=not ascending + ) name_count: dict = {} for s in streams: name_count[s["name"]] = name_count.get(s["name"], 0) + 1 seen: dict = {} for s in streams: - if name_count[s["name"]] > 1: + if name_count[s["name"]] > 1 and SettingsManager.current().stream_formatter == "default": seen[s["name"]] = seen.get(s["name"], 0) + 1 s["name"] = f"{s['name']} ({seen[s['name']]})" + streams.append(_donation()) return {"streams": streams} +#----- Configure/install landing page rendered as HTML for a token @router.get("/{token}/configure") -async def configure_addon(token: str): +async def configure_addon(token: str, request: Request): manifest_url = f"{SettingsManager.current().base_url}/stremio/{token}/manifest.json" web_install_url = f"https://web.stremio.com/#/?addon_manifest={quote(manifest_url, safe='')}" - # Fetch user info for display token_doc = await db.get_api_token(token) user_name = "Unknown" - expiry_str = "N/A" + expiry_str = "Never" status_color = "#ef4444" status_text = "Unknown" + def _expired(when): + ref = datetime.utcnow() + try: + if when.tzinfo is not None: + ref = datetime.now(timezone.utc) + except AttributeError: + pass + return when < ref + + def _fmt(when): + try: + return when.strftime("%d %b %Y").lstrip("0") + except Exception: + return "N/A" + if token_doc: uid = token_doc.get("user_id") + is_admin = bool(token_doc.get("is_admin")) + try: + is_admin = is_admin or (uid is not None and int(uid) == int(Telegram.OWNER_ID)) + except (TypeError, ValueError): + pass + + user = None if uid: try: user = await db.get_user(int(uid)) - if user: - user_name = user.get("first_name") or user.get("username") or f"User {uid}" - sub_status = user.get("subscription_status", "") - expiry = user.get("subscription_expiry") - if expiry: - expiry_str = expiry.strftime("%d %b %Y").lstrip("0") - if sub_status == "active": - status_color = "#22c55e" - status_text = "✅ Active" - else: - status_color = "#ef4444" - status_text = "🔴 Expired" except Exception: - pass + user = None + if user: + user_name = user.get("first_name") or user.get("username") or f"User {uid}" + elif uid: + user_name = f"User {uid}" + + token_expiry = token_doc.get("expires_at") + if is_admin: + status_color, status_text, expiry_str = "#22c55e", "Admin", "Never" + elif token_doc.get("subscription_exempt"): + status_color, status_text, expiry_str = "#22c55e", "Active", "Never" + elif token_expiry is not None: + expiry_str = _fmt(token_expiry) + if _expired(token_expiry): + status_color, status_text = "#ef4444", "Expired" + else: + status_color, status_text = "#22c55e", "Active" + elif SettingsManager.current().subscription: + expiry = user.get("subscription_expiry") if user else None + if user and user.get("subscription_status") == "active" and expiry and not _expired(expiry): + status_color, status_text, expiry_str = "#22c55e", "Active", _fmt(expiry) + else: + status_color, status_text = "#ef4444", "Expired" + expiry_str = _fmt(expiry) if expiry else "N/A" + else: + status_color, status_text, expiry_str = "#22c55e", "Active", "Never" + + return templates.TemplateResponse("stremio_configure.html", { + "request": request, + "theme": get_theme(theme_key(request)), + "manifest_url": manifest_url, + "web_install_url": web_install_url, + "user_name": user_name, + "expiry_str": expiry_str, + "status_text": status_text, + "status_color": status_color, + }) + + +#----- Catalogs this token can see, in effective (token or global) order +async def _addon_catalogs_for_token(token_data: dict) -> list: + entries = [ + {"id": "latest_movies", "name": "Recently Added Movies", "type": "movie"}, + {"id": "top_movies", "name": "Popular Movies", "type": "movie"}, + {"id": "latest_series", "name": "Recently Added Series", "type": "series"}, + {"id": "top_series", "name": "Popular Series", "type": "series"}, + {"id": "trending_movies", "name": "Trending Movies", "type": "movie"}, + {"id": "trending_series", "name": "Trending Series", "type": "series"}, + ] + try: + for c in await db.get_custom_catalogs(slim=True): + items = [i for i in (c.get("items") or []) if _token_can_view(*_effective_visibility(c, i), token_data)] + if not items: + continue + cid, name = f"custom_{c['_id']}", (c.get("name") or "Catalog") + if any(i.get("media_type") == "movie" for i in items): + entries.append({"id": cid, "name": name, "type": "movie"}) + if any(i.get("media_type") == "tv" for i in items): + entries.append({"id": cid, "name": name, "type": "series"}) + except Exception: + pass + for e in entries: + e["key"] = f"{e['id']}::{e['type']}" + admin_hidden = set(await db.get_hidden_catalogs()) + entries = [e for e in entries if e["key"] not in admin_hidden and e["id"] not in admin_hidden] + order = await db.get_catalog_order() + tconf = token_data.get("config") or {} + effective = tconf.get("catalog_order") or order + if effective: + rank = {k: i for i, k in enumerate(effective)} + entries.sort(key=lambda e: rank.get(e["key"], rank.get(e["id"], len(effective) + 1))) + return entries + + +#----- Read this token's addon config + catalog list (public, used by configure page) +@router.get("/{token}/addon-config") +async def get_addon_config(token: str): + doc = await db.get_api_token(token) + if not doc: + raise HTTPException(status_code=404, detail="Invalid token") + return {"config": doc.get("config") or {}, "catalogs": await _addon_catalogs_for_token(doc), "own_bots": own_bots.addon_view(doc)} + + +#----- Persist this token's addon config (public, used by configure page) +@router.post("/{token}/addon-config") +async def save_addon_config(token: str, payload: dict): + doc = await db.get_api_token(token) + if not doc: + raise HTTPException(status_code=404, detail="Invalid token") + valid_q = {"480p", "720p", "1080p", "4K"} + config = { + "quality_sort": "asc" if payload.get("quality_sort") == "asc" else "desc", + "quality_filter": [q for q in (payload.get("quality_filter") or []) if q in valid_q], + "hidden_catalogs": [str(x) for x in (payload.get("hidden_catalogs") or [])], + "catalog_order": [str(x) for x in (payload.get("catalog_order") or [])], + "stream_via": payload.get("stream_via") if payload.get("stream_via") in own_bots.STREAM_VIA else "bots", + } + await db.set_token_config(token, config) + return {"ok": True, "config": config} - html = f""" - - - - - Update Telegram Stremio Addon - - - -
- -

Telegram Stremio Addon

-

Click the button below to install or update your addon in Stremio.

- -
- User - {user_name} -
-
- Status - {status_text} -
-
- Expires - {expiry_str} -
- - - ⚡ Install / Update in Stremio - - -
- Or install manually: -
    -
  1. Open Stremio → Add-ons tab
  2. -
  3. Click the 🔍 Search / URL icon
  4. -
  5. Paste the URL below and press Enter
  6. -
-
- -
{manifest_url}
- - -
- -""" - return HTMLResponse(html) + +@router.post("/{token}/own-bots") +async def save_own_bots(token: str, payload: dict): + doc = await db.get_api_token(token) + if not doc: + raise HTTPException(status_code=404, detail="Invalid token") + try: + return await own_bots.verify(doc, payload.get("channel"), payload.get("keep") or [], payload.get("add") or []) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + +@router.delete("/{token}/own-bots") +async def delete_own_bots(token: str): + doc = await db.get_api_token(token) + if not doc: + raise HTTPException(status_code=404, detail="Invalid token") + await own_bots.disable(doc) + return {"ok": True} diff --git a/Backend/fastapi/routes/template_routes.py b/Backend/fastapi/routes/template_routes.py index 72b191c656b721a5b3eb9d994bcb9d2b2f391ca6..c53ee432025b449fcc7a6ae60e4c1a238d9dd57c 100644 --- a/Backend/fastapi/routes/template_routes.py +++ b/Backend/fastapi/routes/template_routes.py @@ -1,90 +1,108 @@ -from fastapi import Request, Form, HTTPException, Depends +import secrets +import time + +from fastapi import Depends, Form, HTTPException, Request from fastapi.responses import RedirectResponse from fastapi.templating import Jinja2Templates -from Backend.fastapi.security.credentials import verify_credentials, require_auth, is_authenticated, get_current_user -from Backend.fastapi.themes import get_theme, get_all_themes, DEFAULT_THEME -from Backend import db + +from Backend import StartTime, __version__, db from Backend.config import Telegram -from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot +from Backend.fastapi.security.credentials import get_current_user, is_authenticated, require_auth, revoke_session, verify_credentials +from Backend.fastapi.themes import get_all_themes, get_theme, theme_key +from Backend.helper.analytics import client_ip_from, get_activity_overview +from Backend.helper.bounded import BoundedDict +from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS +from Backend.helper.metadata import resolve_cover_url from Backend.helper.pyro import get_readable_time from Backend.helper.settings_manager import SettingsManager -from Backend import StartTime, __version__ -import time -from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS +from Backend.helper.stream_formatter import PRESETS +import Backend.pyrofork.bot as botmod +from Backend.pyrofork.bot import StreamBot, multi_clients, work_loads_summary templates = Jinja2Templates(directory="Backend/fastapi/templates") +templates.env.globals["cover_url"] = resolve_cover_url -async def admin_dashboard_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - - return templates.TemplateResponse("admin_dashboard.html", { + +#----- Shared template context (request, theme metadata) for every page +def _base_context(request: Request) -> dict: + theme_name = theme_key(request) + return { "request": request, - "theme": theme, + "theme": get_theme(theme_name), "themes": get_all_themes(), "current_theme": theme_name, - "current_user": current_user - }) + } + +#----- Admin dashboard shell +async def admin_dashboard_page(request: Request, _: bool = Depends(require_auth)): + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + return templates.TemplateResponse("admin_dashboard.html", ctx) + + +#----- Login form (redirects to home when already authenticated) async def login_page(request: Request): if is_authenticated(request): return RedirectResponse(url="/", status_code=302) - - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - - return templates.TemplateResponse("login.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name - }) + return templates.TemplateResponse("login.html", _base_context(request)) + + +#----- Handle login submission +_FAILED_LOGINS = BoundedDict(1000) +_LOGIN_MAX_FAILS = 5 +_LOGIN_WINDOW = 15 * 60 + async def login_post(request: Request, username: str = Form(...), password: str = Form(...)): + ip = client_ip_from(request) + now = time.time() + fails = [t for t in _FAILED_LOGINS.get(ip, []) if now - t < _LOGIN_WINDOW] + if len(fails) >= _LOGIN_MAX_FAILS: + ctx = _base_context(request) + ctx["error"] = "Too many failed attempts. Try again in 15 minutes." + return templates.TemplateResponse("login.html", ctx, status_code=429) if verify_credentials(username, password): + _FAILED_LOGINS.pop(ip, None) request.session["authenticated"] = True request.session["username"] = username + request.session["sid"] = secrets.token_urlsafe(16) return RedirectResponse(url="/", status_code=302) - else: - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - return templates.TemplateResponse("login.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "error": "Invalid credentials" - }) + _FAILED_LOGINS[ip] = fails + [now] + ctx = _base_context(request) + ctx["error"] = "Invalid credentials" + return templates.TemplateResponse("login.html", ctx) + +#----- Clear the session and return to login async def logout(request: Request): - request.session.clear() + revoke_session(request) return RedirectResponse(url="/login", status_code=302) -async def set_theme(request: Request, theme: str = Form(...)): - if theme in get_all_themes(): - request.session["theme"] = theme - return RedirectResponse(url=request.headers.get("referer", "/"), status_code=302) +#----- Persist the chosen theme and return to the referring page +async def set_theme(request: Request, theme: str = Form(None)): + response = RedirectResponse(url=request.headers.get("referer", "/"), status_code=302) + if theme and theme in get_all_themes(): + response.set_cookie("theme", theme, max_age=31536000, samesite="lax") + return response + + +#----- Main dashboard: aggregate DB stats and live/recent stream telemetry async def dashboard_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + try: db_stats = await db.get_database_stats() - total_movies = sum(stat.get("movie_count", 0) for stat in db_stats) - total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats) + total_movies, total_tv_shows = db.content_totals(db_stats) now = time.time() PRUNE_SECONDS = 3 for sid, info in list(ACTIVE_STREAMS.items()): status = info.get("status") - # Check end_ts first to see when it organically finished last_ts = info.get("end_ts") or info.get("last_ts") or info.get("start_ts", now) - if status in ("cancelled", "error", "finished") and (now - last_ts > PRUNE_SECONDS): - info["duration"] = round(now - info.get("start_ts", now), 1) info["stream_id"] = sid try: @@ -93,9 +111,8 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)): except KeyError: pass - active_streams_data = [] - for stream_id, info in ACTIVE_STREAMS.items(): - active_streams_data.append({ + active_streams_data = [ + { "stream_id": stream_id, "msg_id": info.get("msg_id"), "chat_id": info.get("chat_id"), @@ -108,17 +125,16 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)): "dc_id": info.get("dc_id", 0), "duration": round(now - info.get("start_ts", now), 1), "meta": info.get("meta", {}) - }) + } + for stream_id, info in ACTIVE_STREAMS.items() + ] system_stats = { "server_status": "running", "uptime": get_readable_time(now - StartTime), "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot", "connected_bots": len(multi_clients), - "loads": { - f"bot{c+1}": l - for c, (_, l) in enumerate(sorted(work_loads.items(), key=lambda x: x[1], reverse=True)) - } if work_loads else {}, + "loads": work_loads_summary(), "version": __version__, "movies": total_movies, "tv_shows": total_tv_shows, @@ -148,37 +164,25 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)): "total_active_streams": 0 } - api_tokens = await db.get_all_api_tokens() - return templates.TemplateResponse("dashboard.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - "system_stats": system_stats, - "api_tokens": api_tokens - }) + ctx["system_stats"] = system_stats + try: + ctx["user_activity_initial"] = await get_activity_overview(1, 5) + except Exception: + ctx["user_activity_initial"] = {"users": [], "online_count": 0, "total": 0, "page": 1, "per_page": 5, "total_pages": 1} + return templates.TemplateResponse("dashboard.html", ctx) -async def media_management_page(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - - return templates.TemplateResponse("media_management.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - "media_type": media_type - }) +#----- Media management shell (movie/tv) +async def media_management_page(request: Request, media_type: str = "movie", custom: bool = False, _: bool = Depends(require_auth)): + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + ctx["media_type"] = media_type + ctx["custom"] = custom + return templates.TemplateResponse("media_management.html", ctx) + +#----- Media edit page for a single title async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - try: media_details = await db.get_document(media_type, tmdb_id, db_index) if not media_details: @@ -187,150 +191,82 @@ async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_t raise HTTPException(status_code=500, detail=str(e)) api_tokens = await db.get_all_api_tokens() - api_token = api_tokens[0].get("token") if api_tokens else None - - return templates.TemplateResponse("media_edit.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, + ctx = _base_context(request) + ctx.update({ + "current_user": get_current_user(request), "tmdb_id": tmdb_id, "db_index": db_index, "media_type": media_type, "media_details": media_details, - "api_token": api_token - }) - -async def public_status_page(request: Request): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - - try: - db_stats = await db.get_database_stats() - total_movies = sum(stat.get("movie_count", 0) for stat in db_stats) - total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats) - - public_stats = { - "status": "operational", - "uptime": "99.9%", - "total_content": total_movies + total_tv_shows, - "databases_online": len(db_stats) - } - except Exception: - public_stats = { - "status": "maintenance", - "uptime": "N/A", - "total_content": 0, - "databases_online": 0 - } - - return templates.TemplateResponse("public_status.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "stats": public_stats, - "is_authenticated": is_authenticated(request) + "api_token": api_tokens[0].get("token") if api_tokens else None, }) + return templates.TemplateResponse("media_edit.html", ctx) -async def stremio_guide_page(request: Request): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - - return templates.TemplateResponse("stremio_guide.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "is_authenticated": is_authenticated(request) - }) +#----- Subscription management shell async def admin_subscriptions_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - - return templates.TemplateResponse("subscriptions_manage.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user - }) + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + return templates.TemplateResponse("subscriptions_manage.html", ctx) +#----- Access management shell async def admin_access_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + return templates.TemplateResponse("access_manage.html", ctx) - return templates.TemplateResponse("access_manage.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - }) +#----- Content requests shell (admin) +async def admin_requests_page(request: Request, _: bool = Depends(require_auth)): + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + return templates.TemplateResponse("requests_manage.html", ctx) -async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) +#----- Public request page (no auth) +async def public_request_page(request: Request): + ctx = _base_context(request) + ctx["is_authenticated"] = is_authenticated(request) + return templates.TemplateResponse("request_public.html", ctx) - return templates.TemplateResponse("custom_catalogs.html", { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - }) +#----- Custom catalogs shell +async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)): + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + return templates.TemplateResponse("custom_catalogs.html", ctx) +#----- Tools shell (WebUI replacement for scan/rescan/dbcheck commands) async def tools_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - - return templates.TemplateResponse( - "tools.html", - { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - }, - ) + ctx = _base_context(request) + ctx["current_user"] = get_current_user(request) + #----- Bot Admin Manager needs a session string AND more than one bot token + ctx["userbot_configured"] = botmod.Userbot is not None + ctx["multi_token_available"] = len(multi_clients) > 1 + return templates.TemplateResponse("tools.html", ctx) +#----- Settings page with current config and database list async def settings_page(request: Request, _: bool = Depends(require_auth)): - theme_name = request.session.get("theme", DEFAULT_THEME) - theme = get_theme(theme_name) - current_user = get_current_user(request) - settings = SettingsManager.current().to_dict() settings["admin_password"] = "" - try: settings["database_list"] = db.get_database_list() except Exception: settings["database_list"] = [] - userbot_configured = bool(Telegram.USER_SESSION_STRING and Telegram.USER_SESSION_STRING.strip()) - - return templates.TemplateResponse( - "settings.html", - { - "request": request, - "theme": theme, - "themes": get_all_themes(), - "current_theme": theme_name, - "current_user": current_user, - "settings": settings, - "userbot_configured": userbot_configured, - }, -) + titles = settings.get("channel_titles") or {} + if not isinstance(titles, dict): + titles = {} + settings["channel_titles"] = {str(k): str(v) for k, v in titles.items() if k and v} + + ctx = _base_context(request) + ctx.update({ + "current_user": get_current_user(request), + "settings": settings, + "userbot_configured": botmod.Userbot is not None, + "formatter_presets": PRESETS, + }) + return templates.TemplateResponse("settings.html", ctx) diff --git a/Backend/fastapi/routes/webdav_routes.py b/Backend/fastapi/routes/webdav_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..f04efc5c8c3b59fefd118d5db4a381b3c8105313 --- /dev/null +++ b/Backend/fastapi/routes/webdav_routes.py @@ -0,0 +1,346 @@ +""" +WebDAV endpoint for Telegram-Stremio. + +URL: /webdav/{token}/... + +Auth: + - Path token = valid API token (same as Stremio) + - Optional HTTP Basic: WEBDAV_USER / WEBDAV_PASSWORD from config.env + +Methods: OPTIONS, PROPFIND, HEAD, GET (read-only) + +Supports the same media as Stremio streams: + - single files + - multi-quality (each quality is a separate file in the folder) + - split parts (.001/.002) joined as one virtual file + - split zip archives (via existing zip streamer) + +Compatibility notes (2026-08): + - Always returns absolute hrefs in PROPFIND (required by many Android / media apps) + - Avoids relative paths that cause clients to fall back to port 80 on HTTPS hosts +""" + +from __future__ import annotations + +import base64 +from datetime import datetime, timezone +from typing import List +from urllib.parse import quote, unquote, urljoin +from xml.etree.ElementTree import Element, SubElement, tostring + +from fastapi import APIRouter, HTTPException, Request, Response + +from Backend.config import Telegram +from Backend.fastapi.routes import stream_routes as sr +from Backend.fastapi.security.tokens import verify_token +from Backend.helper.encrypt import decode_string +from Backend.helper.settings_manager import SettingsManager +from Backend.helper.webdav_fs import VNode, fs, normalize_path +from Backend.logger import LOGGER + +router = APIRouter(tags=["WebDAV"]) + +DAV_NS = "DAV:" + + +# --------------------------------------------------------------------------- +# Auth +# --------------------------------------------------------------------------- + +def _webdav_credentials(): + """Prefer live Settings page values; fall back to config.env.""" + try: + s = SettingsManager.current() + user = (getattr(s, "webdav_user", None) or "").strip() + password = getattr(s, "webdav_password", None) or "" + if user or password: + return user, password + except Exception: + pass + return (getattr(Telegram, "WEBDAV_USER", "") or "", getattr(Telegram, "WEBDAV_PASSWORD", "") or "") + + +def _basic_ok(request: Request) -> bool: + user, password = _webdav_credentials() + if not user and not password: + return True # Basic auth disabled + header = request.headers.get("Authorization") or "" + if not header.lower().startswith("basic "): + return False + try: + decoded = base64.b64decode(header.split(" ", 1)[1]).decode("utf-8") + u, _, p = decoded.partition(":") + return u == user and p == password + except Exception: + return False + + +async def _require_webdav_auth(request: Request, token: str) -> dict: + if not _basic_ok(request): + raise HTTPException( + status_code=401, + detail="WebDAV Basic auth required. Set username/password in Settings → WebDAV, or clear both fields to disable Basic auth.", + headers={"WWW-Authenticate": 'Basic realm="Telegram-Stremio WebDAV"'}, + ) + try: + token_data = await verify_token(token) + except HTTPException as e: + # Re-raise as 401 JSON-friendly (do not use admin login redirect) + raise HTTPException(status_code=401, detail=f"Invalid API token for WebDAV: {e.detail}") + if token_data.get("subscription_expired") or token_data.get("limit_exceeded"): + raise HTTPException(status_code=403, detail="Token expired or limit exceeded") + return token_data + + +# --------------------------------------------------------------------------- +# PROPFIND helpers (absolute hrefs for maximum client compatibility) +# --------------------------------------------------------------------------- + +def _href(request: Request, token: str, path: str, is_dir: bool) -> str: + """ + Return an absolute href. + Many Android / media WebDAV clients break on relative paths and fall back + to port 80 even when the original URL was https://. + """ + path = normalize_path(path) + segments = [quote(s, safe="") for s in path.strip("/").split("/") if s] + rel = f"/webdav/{token}/" + "/".join(segments) + if is_dir and not rel.endswith("/"): + rel += "/" + + # Prefer configured public BASE_URL, otherwise use the request itself + base = (getattr(Telegram, "BASE_URL", None) or "").rstrip("/") + if not base: + base = str(request.base_url).rstrip("/") + return urljoin(base + "/", rel.lstrip("/")) + + +def _http_date(ts: float) -> str: + return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT") + + +def _iso_date(ts: float) -> str: + return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _prop_response(request: Request, token: str, node: VNode) -> Element: + resp = Element(f"{{{DAV_NS}}}response") + href = SubElement(resp, f"{{{DAV_NS}}}href") + href.text = _href(request, token, node.path, node.is_dir) + + propstat = SubElement(resp, f"{{{DAV_NS}}}propstat") + prop = SubElement(propstat, f"{{{DAV_NS}}}prop") + + SubElement(prop, f"{{{DAV_NS}}}displayname").text = node.name or "root" + SubElement(prop, f"{{{DAV_NS}}}getlastmodified").text = _http_date(node.mtime) + SubElement(prop, f"{{{DAV_NS}}}getetag").text = ( + f'"{hash((node.path, node.size, int(node.mtime))) & 0xFFFFFFFF:x}"' + ) + SubElement(prop, f"{{{DAV_NS}}}creationdate").text = _iso_date(node.mtime) + + if node.is_dir: + rt = SubElement(prop, f"{{{DAV_NS}}}resourcetype") + SubElement(rt, f"{{{DAV_NS}}}collection") + SubElement(prop, f"{{{DAV_NS}}}getcontentlength").text = "0" + else: + SubElement(prop, f"{{{DAV_NS}}}resourcetype") + SubElement(prop, f"{{{DAV_NS}}}getcontentlength").text = str(max(0, node.size)) + SubElement(prop, f"{{{DAV_NS}}}getcontenttype").text = node.content_type + + SubElement(propstat, f"{{{DAV_NS}}}status").text = "HTTP/1.1 200 OK" + return resp + + +def _multistatus_xml(request: Request, token: str, nodes: List[VNode]) -> bytes: + root = Element(f"{{{DAV_NS}}}multistatus") + for node in nodes: + root.append(_prop_response(request, token, node)) + return tostring(root, encoding="utf-8", xml_declaration=True) + + +# --------------------------------------------------------------------------- +# Video streaming — reuses Stremio stream_routes (single / split / zip) +# --------------------------------------------------------------------------- + +async def _stream_video(request: Request, node: VNode, token: str, token_data: dict): + if not node.stream_id: + raise HTTPException(status_code=404, detail="No stream id for this file") + + try: + decoded = await decode_string(node.stream_id) + except Exception as e: + LOGGER.warning("[WebDAV] decode stream id failed: %s", e) + raise HTTPException(status_code=400, detail="Invalid stream id") + + sid = node.stream_id + + # Same dispatch order as stream_routes.stream_handler + if decoded.get("global"): + if decoded.get("zip"): + return await sr.global_zip_media_streamer( + request=request, + parts_payload=decoded["parts"], + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + if "parts" in decoded: + return await sr.global_virtual_media_streamer( + request=request, + parts_payload=decoded["parts"], + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + return await sr.global_media_streamer( + request=request, + chat_id=int(decoded["chat_id"]), + msg_id=int(decoded["msg_id"]), + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + + if "parts" in decoded: + if decoded.get("zip"): + return await sr.db_zip_media_streamer( + request=request, + parts_payload=decoded["parts"], + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + return await sr.virtual_media_streamer( + request=request, + parts_payload=decoded["parts"], + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + + msg_id = decoded.get("msg_id") + if not msg_id: + raise HTTPException(status_code=400, detail="Missing msg_id in stream id") + chat_id = int(f"-100{decoded['chat_id']}") + return await sr.media_streamer( + request=request, + chat_id=chat_id, + msg_id=int(msg_id), + token=token, + token_data=token_data, + stream_id_hash=sid, + ) + + +# --------------------------------------------------------------------------- +# Routes +# --------------------------------------------------------------------------- + +@router.options("/webdav/{token}") +@router.options("/webdav/{token}/{path:path}") +async def webdav_options(token: str, path: str = ""): + return Response( + status_code=200, + headers={ + "Allow": "OPTIONS, GET, HEAD, PROPFIND", + "DAV": "1, 2", + "MS-Author-Via": "DAV", + "Accept-Ranges": "bytes", + }, + ) + + +@router.api_route("/webdav/{token}", methods=["PROPFIND"]) +@router.api_route("/webdav/{token}/{path:path}", methods=["PROPFIND"]) +async def webdav_propfind(request: Request, token: str, path: str = ""): + await _require_webdav_auth(request, token) + depth = request.headers.get("Depth", "1") + vpath = normalize_path("/" + unquote(path or "")) + node = await fs.resolve(vpath) + if node is None: + raise HTTPException(status_code=404, detail="Not found") + + nodes: List[VNode] = [node] + if node.is_dir and depth != "0": + nodes.extend(await fs.list_dir(vpath)) + + return Response( + content=_multistatus_xml(request, token, nodes), + status_code=207, + media_type="application/xml; charset=utf-8", + headers={"DAV": "1, 2"}, + ) + + +@router.head("/webdav/{token}") +@router.head("/webdav/{token}/{path:path}") +@router.get("/webdav/{token}") +@router.get("/webdav/{token}/{path:path}") +async def webdav_get(request: Request, token: str, path: str = ""): + token_data = await _require_webdav_auth(request, token) + vpath = normalize_path("/" + unquote(path or "")) + node = await fs.resolve(vpath) + if node is None: + raise HTTPException(status_code=404, detail="Not found") + + if node.is_dir: + children = await fs.list_dir(vpath) + rows = [] + parent = normalize_path("/".join(vpath.rstrip("/").split("/")[:-1]) or "/") + if vpath not in ("", "/"): + rows.append(f'
  • ../
  • ') + for c in sorted(children, key=lambda n: (not n.is_dir, n.name.lower())): + href = _href(request, token, c.path, c.is_dir) + label = c.name + ("/" if c.is_dir else "") + size = "" if c.is_dir else f" ({c.size} bytes)" + rows.append(f'
  • {label}{size}
  • ') + body = ( + f"Index of {vpath}" + f"

    Index of {vpath}

      {''.join(rows)}
    " + f"

    Telegram-Stremio WebDAV

    " + ).encode("utf-8") + return Response(content=body, media_type="text/html; charset=utf-8") + + if node.nfo_body is not None: + headers = { + "Content-Type": node.content_type, + "Content-Length": str(len(node.nfo_body)), + "Accept-Ranges": "bytes", + } + if request.method == "HEAD": + return Response(status_code=200, headers=headers) + return Response(content=node.nfo_body, media_type=node.content_type, headers=headers) + + if node.kind in ("movie_video", "episode_video"): + if request.method == "HEAD": + return Response( + status_code=200, + headers={ + "Content-Type": node.content_type, + "Content-Length": str(max(1, node.size)), + "Accept-Ranges": "bytes", + }, + ) + return await _stream_video(request, node, token, token_data) + + raise HTTPException(status_code=404, detail="Unsupported node type") + + +@router.api_route( + "/webdav/{token}", + methods=["PUT", "DELETE", "MKCOL", "MOVE", "COPY", "LOCK", "UNLOCK", "PROPPATCH"], +) +@router.api_route( + "/webdav/{token}/{path:path}", + methods=["PUT", "DELETE", "MKCOL", "MOVE", "COPY", "LOCK", "UNLOCK", "PROPPATCH"], +) +async def webdav_readonly(token: str, path: str = ""): + return Response(status_code=403, content="WebDAV is read-only") + + +@router.post("/webdav/{token}/refresh") +async def webdav_refresh(request: Request, token: str): + await _require_webdav_auth(request, token) + fs.invalidate() + await fs.ensure_tree() + return {"status": "ok", "message": "WebDAV filesystem cache refreshed"} diff --git a/Backend/fastapi/security/credentials.py b/Backend/fastapi/security/credentials.py index f5fab77d8b2a518e0afa42fecd4a2e5640ae5c20..23f903282e202f570196b05823bf2ffe6b5aeee0 100644 --- a/Backend/fastapi/security/credentials.py +++ b/Backend/fastapi/security/credentials.py @@ -1,32 +1,46 @@ -from fastapi import Depends, HTTPException, Request +from fastapi import HTTPException, Request from starlette.status import HTTP_401_UNAUTHORIZED + +from Backend.helper.bounded import BoundedDict +from Backend.helper.passwords import verify_password from Backend.helper.settings_manager import SettingsManager + +#----- Match a username/password pair against the stored admin credentials def verify_credentials(username: str, password: str) -> bool: - """Return True when *username* and *password* match the stored admin credentials.""" s = SettingsManager.current() - return username == s.admin_username and password == s.admin_password + return username == s.admin_username and verify_password(password, s.admin_password) + + +#----- Whether the session carries a valid authentication flag +_revoked_sids = BoundedDict(1000) def is_authenticated(request: Request) -> bool: - """Return True when the session carries a valid authentication flag.""" - return bool(request.session.get("authenticated")) + if not request.session.get("authenticated"): + return False + if request.session.get("sid") in _revoked_sids: + request.session.clear() + return False + return True + +def revoke_session(request: Request) -> None: + sid = request.session.get("sid") + if sid: + _revoked_sids[sid] = True + request.session.clear() + +#----- Logged-in username from the session, or None def get_current_user(request: Request) -> str | None: - """Return the logged-in username from the session, or None.""" if is_authenticated(request): return request.session.get("username", "admin") return None +#----- FastAPI dependency: raise 401 (redirected to /login) when unauthenticated async def require_auth(request: Request) -> bool: - """ - FastAPI dependency: raises 401 when the request is not authenticated. - - The 401 exception handler in main.py redirects the browser to /login. - """ if not is_authenticated(request): raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated") return True - diff --git a/Backend/fastapi/security/tokens.py b/Backend/fastapi/security/tokens.py index a4a95429bd1d96f6b994a1498c1294902aa887eb..a4c7b2b9efd95b20b0f32762e835343afb788da9 100644 --- a/Backend/fastapi/security/tokens.py +++ b/Backend/fastapi/security/tokens.py @@ -1,15 +1,17 @@ +from datetime import datetime, timezone + from fastapi import HTTPException -from datetime import datetime + from Backend import db +from Backend.config import Telegram from Backend.helper.settings_manager import SettingsManager - - DAILY_LIMIT_VIDEO = "https://bit.ly/3YZFKT5" MONTHLY_LIMIT_VIDEO = "https://bit.ly/4rfjtgd" SUBSCRIPTION_EXPIRED_VIDEO = "https://bit.ly/4rfjtgd" +#----- Validate an API token and annotate it with subscription/limit status async def verify_token(token: str): token_data = await db.get_api_token(token) if not token_data: @@ -22,35 +24,45 @@ async def verify_token(token: str): token_data["limit_video"] = None token_data["subscription_expired"] = False - # --- Subscription expiry check (only when SUBSCRIPTION feature is enabled) --- - if SettingsManager.current().subscription: - user_id = token_data.get("user_id") - if not user_id: - # Token has no linked user — treat as expired (unverified token) - token_data["subscription_expired"] = True - return token_data + #----- Owner-linked tokens are admins (honour persisted flag, else derive) + _uid = token_data.get("user_id") + try: + token_data["is_admin"] = bool(token_data.get("is_admin")) or ( + _uid is not None and int(_uid) == int(Telegram.OWNER_ID) + ) + except (TypeError, ValueError): + token_data["is_admin"] = bool(token_data.get("is_admin")) - user = await db.get_user(int(user_id)) - if not user or user.get("subscription_status") != "active": - token_data["subscription_expired"] = True - return token_data + #----- Access expiry checks. Admin and never-expires tokens always bypass. + if not token_data["is_admin"] and not token_data.get("subscription_exempt"): - expiry = user.get("subscription_expiry") - if not expiry: - token_data["subscription_expired"] = True - return token_data + #----- Compare correctly regardless of timezone awareness + def _expired(when): + ref = datetime.utcnow() + try: + if when.tzinfo is not None: + ref = datetime.now(timezone.utc) + except AttributeError: + pass + return when < ref - # Compare correctly regardless of timezone awareness - now = datetime.utcnow() - try: - if expiry.tzinfo is not None: - from datetime import timezone - now = datetime.now(timezone.utc) - except AttributeError: - pass - if expiry < now: - token_data["subscription_expired"] = True - return token_data + #----- A token's own expiry is enforced in every mode. With no token expiry, + #----- an active subscription is required only while subscription mode is on. + #----- (When valid, fall through so data-limit checks still apply.) + token_expiry = token_data.get("expires_at") + if token_expiry is not None: + if _expired(token_expiry): + token_data["subscription_expired"] = True + return token_data + elif SettingsManager.current().subscription: + user_id = token_data.get("user_id") + user = await db.get_user(int(user_id)) if user_id else None + expiry = user.get("subscription_expiry") if user else None + if (not user_id or not user + or user.get("subscription_status") != "active" + or not expiry or _expired(expiry)): + token_data["subscription_expired"] = True + return token_data if daily_limit := limits.get("daily_limit_gb"): if daily_limit > 0: diff --git a/Backend/fastapi/static/placeholder.svg b/Backend/fastapi/static/placeholder.svg new file mode 100644 index 0000000000000000000000000000000000000000..45add22c8a18c81f79a436bf4b26cc29af06dc7d --- /dev/null +++ b/Backend/fastapi/static/placeholder.svg @@ -0,0 +1 @@ + diff --git a/Backend/fastapi/templates/access_manage.html b/Backend/fastapi/templates/access_manage.html index ba4a3c23cc5fcd14e0f45f4c64604bf8f4e15b4e..50830d0ed837dd160e99a60a75a09435a3bd064d 100644 --- a/Backend/fastapi/templates/access_manage.html +++ b/Backend/fastapi/templates/access_manage.html @@ -1,437 +1,113 @@ {% extends "base.html" %} -{% block title %}Access Management{% endblock %} +{% block title %}Tokens & Access{% endblock %} {% block content %} -
    -
    -
    -
    -
    - - Access Control Hub -
    -

    - Access Management -

    -

    - Manage addon access tokens, link users, assign plans, and control subscription access. -

    -
    - -
    - -
    -
    -
    - -
    -
    -
    –
    -
    Total Tokens
    -
    -
    -
    –
    -
    Active
    +
    +
    +
    +

    Tokens

    +

    Addon tokens, data limits, lifetime access and linked users

    -
    -
    –
    -
    Expired / No Sub
    +
    + +
    +
    + +
    +
    –
    Total
    +
    –
    Active
    +
    –
    Expired
    -
    +
    -

    Access Tokens

    -

    Search, filter, manage tokens, and control user access.

    +

    All tokens

    +

    Search, filter, and manage every token and its access.

    - + +
    +
    + + +
    + +
    + +
    + + +
    +
    +
    + + + + + + + -
    - {% block content %}{% endblock %} -
    +
    +{% endif %} -
    -
    -
    - -

    © 2026 Telegram Stremio

    +
    +
    + {% if current_user %} + + {% endif %} + {% block content %}{% endblock %} +
    +
    + +
    + +{% if current_user %} + +
    + + + Esc
    -
    - -
    - - - diff --git a/Backend/fastapi/templates/custom_catalogs.html b/Backend/fastapi/templates/custom_catalogs.html index 03fa6cafb99a359259193f243b82d8546da5ca27..14700eb03b021fc17655d4bdcb7c6591fc4da92f 100644 --- a/Backend/fastapi/templates/custom_catalogs.html +++ b/Backend/fastapi/templates/custom_catalogs.html @@ -4,33 +4,12 @@ {% block content %} + .token-row:hover { background: color-mix(in srgb, var(--primary) 10%, transparent); } + .token-row input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); cursor: pointer; flex-shrink: 0; } -
    -
    -
    -
    -
    🎞️
    -
    -
    - Custom Stremio sections - No Stremio search/filter -
    -

    Custom Catalogs

    -

    - Build dynamic curated rows like Bollywood, Anime, Kids, 4K, Watch Later, or hidden private lists from your existing Telegram media. -

    -
    -
    + .vis-chip { display: inline-flex; align-items: center; gap: .35rem; padding: .15rem .6rem; border-radius: 9999px; font-size: .72rem; font-weight: 500; border: 1px solid transparent; } + .vis-public { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); border-color: color-mix(in srgb, var(--ok) 30%, transparent); } + .vis-tokens { color: var(--info); background: color-mix(in srgb, var(--info) 14%, transparent); border-color: color-mix(in srgb, var(--info) 30%, transparent); } + .vis-owner { color: var(--danger); background: color-mix(in srgb, var(--danger) 14%, transparent); border-color: color-mix(in srgb, var(--danger) 30%, transparent); } -
    -
    -

    0

    -

    Catalogs

    -
    -
    -

    0

    -

    Visible

    -
    -
    -

    0

    -

    Titles

    -
    -
    -
    -
    + .auto-chip { display: inline-flex; align-items: center; gap: .45rem; padding: .45rem .85rem; border-radius: 9999px; font-weight: 500; font-size: .84rem; border: 1px solid var(--border); color: var(--text-sec); background: transparent; cursor: pointer; transition: all .15s var(--ease); } + .auto-chip .dot { width: .6rem; height: .6rem; border-radius: 9999px; background: var(--border); transition: all .15s ease; } + .auto-chip:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); } + .auto-chip.on { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 55%, var(--border)); background: color-mix(in srgb, var(--primary) 10%, transparent); } + .auto-chip.on .dot { background: var(--primary); } + .order-row { display: flex; align-items: center; gap: .85rem; border-radius: var(--radius-sm); padding: .65rem .85rem; background: var(--bg); border: 1px solid var(--border); min-width: 0; } -
    -
    -
    -
    - ✨ Auto catalogs - Checking status... -
    -

    Auto-create by selected language & OTT

    -

    - On app startup this scans your movie and series library, fetches TMDb original language + watch providers, then creates only the auto catalogs you select below. Genre auto catalogs are removed. -

    -
    -
    - - -
    -
    + .drag-idx { width: 1.75rem; height: 1.75rem; flex-shrink: 0; display: grid; place-items: center; border-radius: 9999px; font-weight: 500; font-size: .78rem; color: var(--text-sec); background: var(--card-high); } -
    -
    -
    -

    Choose Auto Catalogs

    -

    Disable anything you do not want to auto-create. Save, then run Full Rebuild once to apply removed catalogs.

    -
    - -
    -
    -
    -
    -
    -
    + .order-arrow { width: 2rem; height: 1.6rem; border-radius: 9999px; font-size: .7rem; border: 1px solid var(--border); background: transparent; color: var(--text); cursor: pointer; transition: all .15s var(--ease); } + .order-arrow:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); } + .order-arrow:disabled { opacity: .35; cursor: not-allowed; } + .fold > summary { list-style: none; cursor: pointer; display: flex; align-items: center; justify-content: space-between; gap: .75rem; } + .fold > summary::-webkit-details-marker { display: none; } + .fold > summary::after { content: "\f078"; font-family: "Font Awesome 6 Free"; font-weight: 900; font-size: .8rem; color: var(--text-sec); transition: transform .2s var(--ease); } + .fold[open] > summary::after { transform: rotate(180deg); } + .fold[open] > summary { margin-bottom: 1rem; } + #selected-title { scroll-margin-top: 6rem; } + + + + +
    +
    +
    +

    Catalogs

    +

    Custom and automatic sections shown in Stremio

    +
    + +
    +

    0

    Catalogs

    +

    0

    Visible

    +

    0

    Titles

    +
    + + +

    Auto catalogs

    + Checking status... +
    +
    +
    +

    Toggles save instantly. Sync rebuilds them across your library.

    + +
    +
    +
    +
    +
    +
    +
    + +
    +

    Order and hide

    +
    +

    Arrange how catalogs appear in Stremio, or hide one from everyone.

    + +
    +
    +
    +
    +
    +
    +
    -
    -
    -
    -

    Create Catalog

    -

    Visible catalogs appear in Stremio manifest. Hidden catalogs stay only in web panel.

    -
    - New -
    +
    +

    Create catalog

    @@ -393,26 +236,32 @@
    - +
    + + +

    Shown to everyone who installed the addon.

    +
    - + + +
    -
    + -
    +
    -

    Your Catalogs

    +

    Your catalogs

    Select one to manage titles.

    - +
    - +
    -
    +
    -

    Select a catalog

    +

    Select a catalog

    Choose a catalog from the left side to add or remove titles.

    -
    📚
    -

    No catalog selected

    +
    +

    No catalog selected

    Create a catalog or select an existing one. Then search from your existing media library and add titles instantly.

    -
    -
    +
    +
    -

    - Storage Nodes -

    - -
    - {% for db_stat in system_stats.databases %} -
    -
    -

    {{ db_stat.db_name.replace("storage_", "Node ") }}

    - Online -
    - -
    -
    - Movies / TV - {{ db_stat.movie_count }} / {{ db_stat.tv_count }} -
    - -
    -
    - Disk Usage - {{ "%.1f"|format(db_stat.storageSize / 1024 / 1024) }} MB -
    -
    - {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %} -
    -
    -
    -
    -
    - {% endfor %} +

    Shortcuts

    +
    -
    - -
    -
    - -
    -
    -

    Manage Movies

    -

    Organize and edit library

    -
    - -
    -
    - - -
    -
    - -
    -
    -

    Manage TV Shows

    -

    Handle series and episodes

    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    -

    - Live Network -

    - - {{ system_stats.total_active_streams or 0 }} Active - -
    -

    Current sessions only

    +
    +
    +

    Viewers 0 online

    +
    - -
    -
    -
    -

    Live Now

    -

    {{ system_stats.total_active_streams or 0 }}

    -
    -
    -

    Recent

    -

    0

    -
    -
    - -
    -
    -

    Active Streams

    - Real-time -
    -
    - {% if system_stats.active_streams %} - {% for stream in system_stats.active_streams %} -
    -
    -
    -
    {{ stream.title or stream.meta.get('title') or 'Unknown Stream' }}
    -
    - Bot {{ (stream.client_index or 0) + 1 }} - • - DC {{ stream.dc_id or '-' }} - • - {{ stream.stream_id[:12] if stream.stream_id else 'Unknown' }}{% if stream.stream_id %}…{% endif %} -
    -
    - - Live - -
    - -
    -
    -

    Speed

    -

    {{ "%.3f"|format(stream.avg_mbps or 0) }} MB/s

    -
    -
    -

    Total

    -

    {{ "%.1f"|format((stream.total_bytes or 0) / 1024 / 1024) }} MB

    -
    -
    -

    Duration

    -

    0s

    -
    -
    -

    Status

    -

    {{ stream.status or 'active' }}

    -
    -
    - -
    -
    - Started - — -
    -
    - Stream ID - {{ stream.stream_id or 'Unknown' }} -
    -
    -
    - {% endfor %} - {% else %} -
    - -

    No active streams right now

    -

    The live network is idle at the moment.

    + +
    +
    -
    +
    +
    -
    - -
    -
    -
    -
    -

    Access Management

    -

    Control API tokens, daily quotas, and monthly quotas

    -
    - -
    - - - - -
    - {% endblock %} diff --git a/Backend/fastapi/templates/login.html b/Backend/fastapi/templates/login.html index d31afe8b8138b73325e39bbf7d9f522994cc29e4..1bf5be973dee5b21155b1c19d0dbbdcc3d4b17ee 100644 --- a/Backend/fastapi/templates/login.html +++ b/Backend/fastapi/templates/login.html @@ -1,107 +1,62 @@ {% extends "base.html" %} -{% block title %}Login - Telegram Stremio{% endblock %} +{% block title %}Sign in - Telegram Stremio{% endblock %} {% block content %} -
    - -
    - -
    - -
    -
    - -
    - - TG Stremio - +
    +
    +
    + +
    +

    TG Stremio

    +

    Admin console

    +
    -
    -

    Admin Authentication

    -

    Access your management console

    -
    +
    +

    Sign in

    +

    Use the admin account set in Settings.

    {% if error %} -
    - -

    {{ error }}

    + {% endif %}
    - -
    - -
    - - -
    -
    - -
    - -
    - - - - - -
    -
    - - -
    -
    - - - {% endblock %} diff --git a/Backend/fastapi/templates/media_edit.html b/Backend/fastapi/templates/media_edit.html index 67843c6c469db413108362cbf36252bb87248630..19840d32332ea28ac15910fa742db9ca63a8b2dd 100644 --- a/Backend/fastapi/templates/media_edit.html +++ b/Backend/fastapi/templates/media_edit.html @@ -1,48 +1,27 @@ {% extends "base.html" %} -{% block title %}Edit {{ media_type|title }} - Fyvio Backend{% endblock %} +{% block title %}{{ media_details.title if media_details else "Edit" }} - Telegram Stremio{% endblock %} {% block content %} -
    -
    -
    - - - - - Back to {{ media_type|title }}s - - -
    -
    -

    Edit {{ media_type|title }}

    -

    TMDB ID: {{ tmdb_id }} · DB Index: {{ db_index }}

    -
    -
    -
    -
    +
    +
    + + {{ 'Movies' if media_type == 'movie' else 'TV shows' }} + +

    Edit {{ 'movie' if media_type == 'movie' else 'series' }} · TMDB {{ tmdb_id }} · DB {{ db_index }}

    +
    {% if media_details %} -
    +
    {% if media_details.backdrop %} - {{ media_details.title }} backdrop + {% endif %}
    -
    -
    -
    - {{ media_details.title }} +
    + {{ media_details.title }} poster + +
    + {% if media_details.logo %} + + {% endif %} + + +
    + {% if media_details.rating %} {{ media_details.rating }}{% endif %} + {% if media_details.release_year %}{{ media_details.release_year }}{% if media_details.release_year_end and media_details.release_year_end != media_details.release_year %}–{{ media_details.release_year_end }}{% endif %}{% endif %} + {% if media_details.runtime %}{{ media_details.runtime }}{% endif %} + {{ 'Movie' if media_type == 'movie' else 'Series' }}
    -
    -

    - {{ media_details.title }} -

    - -
    - {% if media_details.rating %} - - ⭐ {{ media_details.rating }} - - {% endif %} - - {{ media_details.release_year }} - - {% if media_details.genres %} - - {{ media_details.genres|length }} genre{{ 's' if media_details.genres|length != 1 else '' }} - - {% endif %} -
    - - {% if media_details.genres %} -
    - {% for genre in media_details.genres[:8] %} - {{ genre }} - {% endfor %} -
    - {% endif %} + {% if media_details.genres %} +
    + {% for genre in media_details.genres[:6] %}{{ genre }}{% endfor %}
    + {% endif %}
    @@ -316,7 +298,17 @@ {% endif %} {% if media_details %} -
    +
    + + + + + +
    + {% endif %} + + {% if media_details %} +