DevDoCode commited on
Commit
36dde81
·
1 Parent(s): 853bd76

Replace Space code with weebzone/Telegram-Stremio (strip binaries)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +1 -0
  2. Backend/__init__.py +8 -5
  3. Backend/__main__.py +60 -53
  4. Backend/config.py +37 -27
  5. Backend/fastapi/__init__.py +3 -2
  6. Backend/fastapi/main.py +531 -73
  7. Backend/fastapi/routes/api_routes.py +0 -0
  8. Backend/fastapi/routes/cf_routes.py +77 -0
  9. Backend/fastapi/routes/stream_routes.py +479 -217
  10. Backend/fastapi/routes/stremio_routes.py +0 -0
  11. Backend/fastapi/routes/template_routes.py +139 -203
  12. Backend/fastapi/routes/webdav_routes.py +346 -0
  13. Backend/fastapi/security/credentials.py +26 -12
  14. Backend/fastapi/security/tokens.py +41 -29
  15. Backend/fastapi/static/placeholder.svg +1 -0
  16. Backend/fastapi/templates/access_manage.html +478 -818
  17. Backend/fastapi/templates/admin_dashboard.html +266 -363
  18. Backend/fastapi/templates/base.html +835 -533
  19. Backend/fastapi/templates/custom_catalogs.html +466 -387
  20. Backend/fastapi/templates/dashboard.html +303 -793
  21. Backend/fastapi/templates/login.html +40 -85
  22. Backend/fastapi/templates/media_edit.html +0 -0
  23. Backend/fastapi/templates/media_management.html +637 -159
  24. Backend/fastapi/templates/request_public.html +162 -0
  25. Backend/fastapi/templates/requests_manage.html +221 -0
  26. Backend/fastapi/templates/settings.html +0 -0
  27. Backend/fastapi/templates/stremio_configure.html +480 -0
  28. Backend/fastapi/templates/subscriptions_manage.html +183 -423
  29. Backend/fastapi/templates/tools.html +943 -56
  30. Backend/fastapi/themes.py +45 -125
  31. Backend/helper/analytics.py +278 -0
  32. Backend/helper/anime.py +0 -204
  33. Backend/helper/announcer.py +165 -0
  34. Backend/helper/auto_catalog.py +198 -162
  35. Backend/helper/backup.py +171 -0
  36. Backend/helper/bounded.py +9 -0
  37. Backend/helper/cf_live.py +86 -0
  38. Backend/helper/cf_stream.py +70 -0
  39. Backend/helper/custom_dl.py +133 -70
  40. Backend/helper/custom_filter.py +5 -3
  41. Backend/helper/database.py +0 -0
  42. Backend/helper/encrypt.py +20 -21
  43. Backend/helper/exceptions.py +1 -1
  44. Backend/helper/fanart.py +158 -0
  45. Backend/helper/global_search.py +615 -174
  46. Backend/helper/health.py +125 -0
  47. Backend/helper/imdb.py +0 -128
  48. Backend/helper/link_checker.py +92 -73
  49. Backend/helper/manual_add.py +156 -0
  50. Backend/helper/metadata.py +0 -956
.dockerignore ADDED
@@ -0,0 +1 @@
 
 
1
+ assets/
Backend/__init__.py CHANGED
@@ -1,14 +1,17 @@
1
- from Backend.helper.database import Database
2
- from time import time
3
  from datetime import datetime
 
 
4
  import pytz
5
 
 
 
 
6
  timezone = pytz.timezone("Asia/Kolkata")
7
  now = datetime.now(timezone)
8
  StartTime = time()
9
 
10
-
11
  USE_DEFAULT_ID: str = None
12
- db = Database()
 
13
 
14
- __version__ = "3.4.0"
 
 
 
1
  from datetime import datetime
2
+ from time import time
3
+
4
  import pytz
5
 
6
+ from Backend.helper.database import Database
7
+
8
+ #----- Shared application state
9
  timezone = pytz.timezone("Asia/Kolkata")
10
  now = datetime.now(timezone)
11
  StartTime = time()
12
 
 
13
  USE_DEFAULT_ID: str = None
14
+ MANUAL_SESSION: dict = None
15
+ db = Database()
16
 
17
+ __version__ = "5.3.5"
Backend/__main__.py CHANGED
@@ -1,91 +1,99 @@
1
- from asyncio import get_event_loop, sleep as asleep
2
  import asyncio
3
  import logging
 
4
  from traceback import format_exc
 
5
  from pyrogram import idle
 
 
6
  from Backend import __version__, db
7
- from Backend.helper.pinger import ping
8
- from Backend.logger import LOGGER
9
  from Backend.fastapi import server
10
- from Backend.helper.settings_manager import SettingsManager
11
- from Backend.helper.pyro import restart_notification, setup_bot_commands
12
- from Backend.pyrofork.bot import Userbot, StreamBot
13
- from Backend.pyrofork.clients import initialize_clients
14
  from Backend.helper import subscription_task_manager
15
- from Backend.helper.scan_manager import scan_manager, dbcheck_manager
16
  from Backend.helper.link_checker import DeadLinkChecker
17
- from Backend.fastapi.main import app
18
- from Backend.helper.auto_catalog import (
19
- start_auto_catalog_sync_background, start_auto_catalog_interval_loop
20
- )
 
 
 
 
 
 
21
 
 
22
 
23
- loop = get_event_loop()
24
 
 
25
  async def start_services():
26
  try:
27
  LOGGER.info(f"Initializing Telegram-Stremio v-{__version__}")
28
- await asleep(1.2)
29
-
30
  await db.connect()
31
- await asleep(1.2)
32
 
33
  await SettingsManager.initialize(db)
34
- await asleep(0.5)
35
-
36
- try:
37
- await scan_manager.load(db)
38
- dbcheck_manager.bind_db(db)
39
- except Exception as e:
40
- LOGGER.error(f"Failed to restore scan manager state on startup: {e}")
41
- await asleep(0.3)
42
-
43
- try:
44
- await db.reload_extra_databases(SettingsManager.current().extra_databases)
45
- except Exception as e:
46
- LOGGER.error(f"Failed to reconnect extra storage databases on startup: {e}")
47
- await asleep(0.5)
48
 
49
  await StreamBot.start()
50
  StreamBot.username = StreamBot.me.username
51
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
52
- await asleep(1.2)
53
-
54
- if Userbot is not None:
55
- await Userbot.start()
56
- Userbot.username = Userbot.me.username
57
- LOGGER.info(f"Userbot Client : [@{Userbot.username}] (Global Search / fallback enabled)")
 
 
 
 
 
 
58
  else:
59
- LOGGER.info("Userbot not configured (USER_SESSION_STRING empty) — running with StreamBot only.")
60
- await asleep(1.2)
61
 
62
  LOGGER.info("Initializing Multi Clients...")
63
  await initialize_clients()
64
- await asleep(2)
65
-
 
 
 
 
 
66
  await setup_bot_commands(StreamBot)
67
- await asleep(2)
68
 
69
  LOGGER.info('Initializing Telegram-Stremio Web Server...')
70
  await restart_notification()
71
  loop.create_task(server.serve())
72
  loop.create_task(ping())
73
-
74
  link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
75
  loop.create_task(link_checker_task.start())
76
 
77
-
78
- loop.create_task(start_auto_catalog_sync_background(db, delay_seconds=20, full_rebuild=False))
79
-
80
- loop.create_task(start_auto_catalog_interval_loop(db))
81
-
82
  await subscription_task_manager.sync(StreamBot)
83
-
84
  LOGGER.info("Telegram-Stremio Started Successfully!")
85
  await idle()
86
  except Exception:
87
  LOGGER.error("Error during startup:\n" + format_exc())
88
 
 
 
89
  async def stop_services():
90
  try:
91
  LOGGER.info("Stopping services...")
@@ -93,19 +101,18 @@ async def stop_services():
93
  pending_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
94
  for task in pending_tasks:
95
  task.cancel()
96
-
97
  await asyncio.gather(*pending_tasks, return_exceptions=True)
98
 
99
  await StreamBot.stop()
100
- if Userbot is not None:
101
- await Userbot.stop()
102
 
103
  await db.disconnect()
104
-
105
  LOGGER.info("Services stopped successfully.")
106
  except Exception:
107
  LOGGER.error("Error during shutdown:\n" + format_exc())
108
 
 
109
  if __name__ == '__main__':
110
  try:
111
  loop.run_until_complete(start_services())
@@ -116,4 +123,4 @@ if __name__ == '__main__':
116
  finally:
117
  loop.run_until_complete(stop_services())
118
  loop.stop()
119
- logging.shutdown()
 
 
1
  import asyncio
2
  import logging
3
+ import secrets
4
  from traceback import format_exc
5
+
6
  from pyrogram import idle
7
+ from starlette.middleware.sessions import SessionMiddleware
8
+
9
  from Backend import __version__, db
 
 
10
  from Backend.fastapi import server
11
+ from Backend.fastapi.main import app
 
 
 
12
  from Backend.helper import subscription_task_manager
 
13
  from Backend.helper.link_checker import DeadLinkChecker
14
+ from Backend.helper.own_bots import reload_helpers, sweep_copies, warm_pools
15
+ from Backend.helper.pinger import ping
16
+ from Backend.helper.pyro import restart_notification, setup_bot_commands
17
+ from Backend.helper.scan_manager import dbcheck_manager, duplicate_manager, scan_manager
18
+ from Backend.helper.session_auth import get_active_session_string
19
+ from Backend.helper.settings_manager import SettingsManager
20
+ from Backend.logger import LOGGER
21
+ import Backend.pyrofork.bot as botmod
22
+ from Backend.pyrofork.bot import StreamBot
23
+ from Backend.pyrofork.clients import initialize_clients
24
 
25
+ loop = asyncio.get_event_loop()
26
 
 
27
 
28
+ #----- Boot every subsystem then idle the bot
29
  async def start_services():
30
  try:
31
  LOGGER.info(f"Initializing Telegram-Stremio v-{__version__}")
32
+ await asyncio.sleep(1.2)
33
+
34
  await db.connect()
35
+ await asyncio.sleep(1.2)
36
 
37
  await SettingsManager.initialize(db)
38
+ app.add_middleware(SessionMiddleware, secret_key=SettingsManager.current().session_secret or secrets.token_hex(32))
39
+ await asyncio.sleep(0.5)
40
+
41
+ await scan_manager.load(db)
42
+ dbcheck_manager.bind_db(db)
43
+ duplicate_manager.bind_db(db)
44
+ await asyncio.sleep(0.3)
45
+
46
+ await db.reload_extra_databases(SettingsManager.current().extra_databases)
47
+ await asyncio.sleep(0.5)
 
 
 
 
48
 
49
  await StreamBot.start()
50
  StreamBot.username = StreamBot.me.username
51
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
52
+ await asyncio.sleep(1.2)
53
+
54
+ if botmod.Userbot is None:
55
+ stored_session = await get_active_session_string()
56
+ if stored_session:
57
+ botmod.build_userbot(stored_session)
58
+ LOGGER.info("Loaded Userbot session from encrypted storage.")
59
+
60
+ if botmod.Userbot is not None:
61
+ await botmod.Userbot.start()
62
+ botmod.Userbot.username = botmod.Userbot.me.username
63
+ LOGGER.info(f"Userbot Client : [@{botmod.Userbot.username}]")
64
  else:
65
+ LOGGER.info("Userbot not configured — running with StreamBot only.")
66
+ await asyncio.sleep(1.2)
67
 
68
  LOGGER.info("Initializing Multi Clients...")
69
  await initialize_clients()
70
+ from Backend.fastapi.routes.stream_routes import warm_streamers
71
+ warm_streamers()
72
+ LOGGER.info(f"Helper bots: {await reload_helpers()} active")
73
+ loop.create_task(sweep_copies())
74
+ loop.create_task(warm_pools())
75
+ await asyncio.sleep(2)
76
+
77
  await setup_bot_commands(StreamBot)
78
+ await asyncio.sleep(2)
79
 
80
  LOGGER.info('Initializing Telegram-Stremio Web Server...')
81
  await restart_notification()
82
  loop.create_task(server.serve())
83
  loop.create_task(ping())
84
+
85
  link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
86
  loop.create_task(link_checker_task.start())
87
 
 
 
 
 
 
88
  await subscription_task_manager.sync(StreamBot)
89
+
90
  LOGGER.info("Telegram-Stremio Started Successfully!")
91
  await idle()
92
  except Exception:
93
  LOGGER.error("Error during startup:\n" + format_exc())
94
 
95
+
96
+ #----- Cancel pending tasks and shut clients down
97
  async def stop_services():
98
  try:
99
  LOGGER.info("Stopping services...")
 
101
  pending_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
102
  for task in pending_tasks:
103
  task.cancel()
 
104
  await asyncio.gather(*pending_tasks, return_exceptions=True)
105
 
106
  await StreamBot.stop()
107
+ if botmod.Userbot is not None:
108
+ await botmod.Userbot.stop()
109
 
110
  await db.disconnect()
 
111
  LOGGER.info("Services stopped successfully.")
112
  except Exception:
113
  LOGGER.error("Error during shutdown:\n" + format_exc())
114
 
115
+
116
  if __name__ == '__main__':
117
  try:
118
  loop.run_until_complete(start_services())
 
123
  finally:
124
  loop.run_until_complete(stop_services())
125
  loop.stop()
126
+ logging.shutdown()
Backend/config.py CHANGED
@@ -1,38 +1,48 @@
1
  from os import getenv, path
 
2
  from dotenv import load_dotenv
3
 
4
  load_dotenv(path.join(path.dirname(path.dirname(__file__)), "config.env"))
5
 
6
 
 
 
 
 
 
 
 
 
7
  class Telegram:
8
- # ── Required: Telegram clients ───────────────────────────────────────────
9
- API_ID = int(getenv("API_ID", "0"))
10
- API_HASH = getenv("API_HASH", "")
11
- BOT_TOKEN = getenv("BOT_TOKEN", "")
12
- USER_SESSION_STRING = getenv("USER_SESSION_STRING", "")
13
 
14
- # ── Required: Database URIs ───────────────────────────────────────────────
15
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
16
 
17
- # ── Required: Server ─────────────────────────────────────────────────────
18
- PORT = int(getenv("PORT", "8000"))
19
- OWNER_ID = int(getenv("OWNER_ID", "0"))
20
-
21
- # ── Legacy migration fallbacks ────────────────────────────────────────────
22
- # These are READ ONCE by SettingsManager._seed_from_env() on first startup
23
- # and then stored in the database. Do NOT reference them elsewhere in the
24
- # codebase — use SettingsManager.current().<property> instead.
25
- REPLACE_MODE = getenv("REPLACE_MODE", "true").lower() == "true"
26
- HIDE_CATALOG = getenv("HIDE_CATALOG", "false").lower() == "true"
27
- AUTH_CHANNEL = [c.strip() for c in (getenv("AUTH_CHANNEL") or "").split(",") if c.strip()]
28
- TMDB_API = getenv("TMDB_API", "")
29
- BASE_URL = getenv("BASE_URL", "").rstrip("/")
30
- UPSTREAM_REPO = getenv("UPSTREAM_REPO", "")
31
- UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "")
32
- ADMIN_USERNAME = getenv("ADMIN_USERNAME", "admin")
33
- ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin")
34
- SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
35
- SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0"))
36
- APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
37
- HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
38
  SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
 
 
 
 
 
1
  from os import getenv, path
2
+
3
  from dotenv import load_dotenv
4
 
5
  load_dotenv(path.join(path.dirname(path.dirname(__file__)), "config.env"))
6
 
7
 
8
+ def _int_env(key: str, default: int = 0) -> int:
9
+ try:
10
+ return int((getenv(key) or "").strip())
11
+ except ValueError:
12
+ return default
13
+
14
+
15
+ #----- Environment-backed configuration
16
  class Telegram:
17
+ #----- Required: Telegram clients
18
+ API_ID = _int_env("API_ID")
19
+ API_HASH = getenv("API_HASH", "")
20
+ BOT_TOKEN = getenv("BOT_TOKEN", "")
 
21
 
22
+ #----- Required: Database URIs
23
  DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
24
 
25
+ #----- Required: Server
26
+ PORT = _int_env("PORT", 8000)
27
+ OWNER_ID = _int_env("OWNER_ID")
28
+
29
+ #----- Read/Write via SettingsManager
30
+ REPLACE_MODE = getenv("REPLACE_MODE", "true").lower() == "true"
31
+ HIDE_CATALOG = getenv("HIDE_CATALOG", "false").lower() == "true"
32
+ AUTH_CHANNEL = [c.strip() for c in (getenv("AUTH_CHANNEL") or "").split(",") if c.strip()]
33
+ TMDB_API = getenv("TMDB_API", "")
34
+ TVDB_API = getenv("TVDB_API", "")
35
+ BASE_URL = getenv("BASE_URL", "").rstrip("/")
36
+ UPSTREAM_REPO = getenv("UPSTREAM_REPO", "")
37
+ UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "")
38
+ ADMIN_USERNAME = getenv("ADMIN_USERNAME", "admin")
39
+ ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin")
40
+ SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
41
+ SUBSCRIPTION_GROUP_ID = _int_env("SUBSCRIPTION_GROUP_ID")
42
+ APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
43
+ HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
 
 
44
  SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
45
+
46
+ #----- WebDAV (optional env fallback; prefer Settings page)
47
+ WEBDAV_USER = getenv("WEBDAV_USER", "")
48
+ WEBDAV_PASSWORD = getenv("WEBDAV_PASSWORD", "")
Backend/fastapi/__init__.py CHANGED
@@ -1,8 +1,9 @@
1
  import uvicorn
 
2
  from Backend.config import Telegram
3
  from Backend.fastapi.main import app
4
 
5
-
6
  Port = Telegram.PORT
7
  config = uvicorn.Config(
8
  app=app,
@@ -10,7 +11,7 @@ config = uvicorn.Config(
10
  port=Port,
11
  loop="uvloop",
12
  http="httptools",
13
- timeout_keep_alive=30,
14
  timeout_graceful_shutdown=5,
15
  )
16
  server = uvicorn.Server(config)
 
1
  import uvicorn
2
+
3
  from Backend.config import Telegram
4
  from Backend.fastapi.main import app
5
 
6
+ #----- Uvicorn server bound to the FastAPI app
7
  Port = Telegram.PORT
8
  config = uvicorn.Config(
9
  app=app,
 
11
  port=Port,
12
  loop="uvloop",
13
  http="httptools",
14
+ timeout_keep_alive=60,
15
  timeout_graceful_shutdown=5,
16
  )
17
  server = uvicorn.Server(config)
Backend/fastapi/main.py CHANGED
@@ -1,41 +1,145 @@
1
- from fastapi import FastAPI, Request, Form, Depends, Query
2
- from fastapi.responses import HTMLResponse, RedirectResponse
 
3
  from fastapi.middleware.cors import CORSMiddleware
 
4
  from fastapi.staticfiles import StaticFiles
5
- from starlette.middleware.sessions import SessionMiddleware
6
  from fastapi.templating import Jinja2Templates
 
7
  from Backend import __version__
8
- from Backend.fastapi.security.credentials import require_auth
9
- from Backend.fastapi.routes.stream_routes import router as stream_router, decay_client_failures
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  from Backend.fastapi.routes.stremio_routes import router as stremio_router
 
11
  from Backend.fastapi.routes.template_routes import (
12
- login_page, login_post, logout, set_theme, dashboard_page,
13
- media_management_page, edit_media_page, public_status_page, stremio_guide_page,
14
- admin_dashboard_page, admin_subscriptions_page, admin_access_page,
15
- custom_catalogs_page, settings_page, tools_page
16
- )
17
- from Backend.fastapi.routes.api_routes import (
18
- list_media_api, delete_media_api, update_media_api,
19
- delete_movie_quality_api, delete_tv_quality_api,
20
- delete_tv_episode_api, delete_tv_season_api,
21
- create_token_api, revoke_token_api, update_token_limits_api,
22
- speed_test_api, speed_test_stream_api,
23
- get_admin_stats_api, clear_cache_api, get_dead_links_api,
24
- get_stream_analytics_api, clear_stream_analytics_api,
25
- get_subscription_plans_api, add_subscription_plan_api,
26
- update_subscription_plan_api, delete_subscription_plan_api,
27
- get_all_subscribers_api, manage_subscriber_api,
28
- get_all_tokens_api, assign_plan_api, link_token_user_api,
29
- search_media_rescan_api, apply_media_rescan_api,
30
- list_custom_catalogs_api, create_custom_catalog_api, update_custom_catalog_api,
31
- delete_custom_catalog_api, get_custom_catalog_items_api, search_catalog_media_api,
32
- add_custom_catalog_item_api, remove_custom_catalog_item_api,
33
- auto_sync_custom_catalogs_api, auto_catalog_sync_status_api,
34
- get_auto_catalog_settings_api, update_auto_catalog_settings_api,
35
- get_settings_api, update_settings_api,
36
- get_tools_channels_api, start_scan_api, cancel_scan_api, scan_status_api,
37
- start_dbcheck_api, cancel_dbcheck_api, dbcheck_status_api, purge_dead_links_api
38
  )
 
 
39
 
40
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
41
 
@@ -45,8 +149,7 @@ app = FastAPI(
45
  version=__version__
46
  )
47
 
48
- # --- Middleware Setup ---
49
- app.add_middleware(SessionMiddleware, secret_key="f6d2e3b9a0f43d9a2e6a56b2d3175cd9c05bbfe31d95ed2a7306b57cb1a8b6f0")
50
  app.add_middleware(
51
  CORSMiddleware,
52
  allow_origins=["*"],
@@ -60,16 +163,22 @@ try:
60
  except Exception:
61
  pass
62
 
 
63
  @app.on_event("startup")
64
  async def _startup():
65
- import asyncio
66
  asyncio.create_task(decay_client_failures())
 
 
67
 
68
- # --- Include existing API routers ---
 
69
  app.include_router(stream_router)
 
70
  app.include_router(stremio_router)
 
 
71
 
72
- # --- Public Routes (No Authentication Required) ---
73
  @app.get("/login", response_class=HTMLResponse)
74
  async def login_get(request: Request):
75
  return await login_page(request)
@@ -83,18 +192,99 @@ async def logout_route(request: Request):
83
  return await logout(request)
84
 
85
  @app.post("/set-theme")
86
- async def set_theme_route(request: Request, theme: str = Form(...)):
87
  return await set_theme(request, theme)
88
 
89
- @app.get("/status", response_class=HTMLResponse)
90
- async def public_status(request: Request):
91
- return await public_status_page(request)
92
-
93
- @app.get("/stremio", response_class=HTMLResponse)
94
- async def stremio_guide(request: Request):
95
- return await stremio_guide_page(request)
96
-
97
- # --- Protected Routes (Authentication Required) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  @app.get("/", response_class=HTMLResponse)
99
  async def root(request: Request, _: bool = Depends(require_auth)):
100
  return await dashboard_page(request, _)
@@ -104,9 +294,8 @@ async def admin_dashboard(request: Request, _: bool = Depends(require_auth)):
104
  return await admin_dashboard_page(request, _)
105
 
106
  @app.get("/media/manage", response_class=HTMLResponse)
107
- async def media_management(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
108
- return await media_management_page(request, media_type, _)
109
-
110
 
111
  @app.get("/catalogs", response_class=HTMLResponse)
112
  async def custom_catalogs(request: Request, _: bool = Depends(require_auth)):
@@ -122,9 +311,10 @@ async def list_media(
122
  page: int = Query(1, ge=1),
123
  page_size: int = Query(24, ge=1, le=100),
124
  search: str = Query("", max_length=100),
 
125
  _: bool = Depends(require_auth)
126
  ):
127
- return await list_media_api(media_type, page, page_size, search)
128
 
129
  @app.delete("/api/media/delete")
130
  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
153
  @app.get("/api/system/workloads")
154
  async def get_workloads(_: bool = Depends(require_auth)):
155
  try:
156
- from Backend.pyrofork.bot import work_loads
157
- return {
158
- "loads": {
159
- f"bot{c + 1}": l
160
- for c, (_, l) in enumerate(
161
- sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
162
- )
163
- } if work_loads else {}
164
- }
165
- except Exception as e:
166
  return {"loads": {}}
167
 
168
  @app.post("/api/tokens")
@@ -173,13 +355,16 @@ async def create_token(payload: dict, _: bool = Depends(require_auth)):
173
  async def update_token(token: str, payload: dict, _: bool = Depends(require_auth)):
174
  return await update_token_limits_api(token, payload)
175
 
 
 
 
 
176
  @app.delete("/api/tokens/{token}")
177
  async def revoke_token(token: str, _: bool = Depends(require_auth)):
178
  return await revoke_token_api(token)
179
 
180
  @app.get("/api/system/stats")
181
  async def get_system_stats(_: bool = Depends(require_auth)):
182
- from Backend.fastapi.routes.api_routes import get_system_stats_api
183
  return await get_system_stats_api()
184
 
185
  @app.get("/api/admin/system-stats")
@@ -198,6 +383,10 @@ async def get_dead_links(_: bool = Depends(require_auth)):
198
  async def get_stream_analytics(_: bool = Depends(require_auth)):
199
  return await get_stream_analytics_api()
200
 
 
 
 
 
201
  @app.post("/api/admin/clear-analytics")
202
  async def clear_analytics(_: bool = Depends(require_auth)):
203
  return await clear_stream_analytics_api()
@@ -230,7 +419,8 @@ async def get_subscribers(_: bool = Depends(require_auth)):
230
  async def manage_subscriber(user_id: int, payload: dict, _: bool = Depends(require_auth)):
231
  return await manage_subscriber_api(user_id, payload)
232
 
233
- # --- Access Management ---
 
234
  @app.get("/admin/access", response_class=HTMLResponse)
235
  async def admin_access(request: Request, _: bool = Depends(require_auth)):
236
  return await admin_access_page(request, _)
@@ -241,8 +431,7 @@ async def get_access_tokens(_: bool = Depends(require_auth)):
241
 
242
  @app.delete("/api/admin/access/tokens/{token}")
243
  async def delete_access_token(token: str, _: bool = Depends(require_auth)):
244
- from Backend.fastapi.routes.api_routes import revoke_token_api as _revoke_token_api
245
- return await _revoke_token_api(token)
246
 
247
  @app.post("/api/admin/access/users/{user_id}/assign-plan")
248
  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
253
  async def link_token_to_user(token: str, payload: dict, _: bool = Depends(require_auth)):
254
  user_id = int(payload.get("user_id", 0))
255
  if not user_id:
256
- from fastapi import HTTPException
257
  raise HTTPException(status_code=400, detail="user_id is required.")
258
  return await link_token_user_api(token, user_id)
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  @app.get("/api/system/speedtest")
261
  async def speed_test(
262
  quality_id: str = Query(...),
@@ -277,7 +522,6 @@ async def speed_test_stream(
277
  ):
278
  return await speed_test_stream_api(quality_id, tmdb_id, db_index, media_type)
279
 
280
-
281
  @app.get("/api/media/rescan/search")
282
  async def search_media_rescan(
283
  media_type: str,
@@ -287,7 +531,6 @@ async def search_media_rescan(
287
  ):
288
  return await search_media_rescan_api(media_type, query, year)
289
 
290
-
291
  @app.post("/api/media/rescan/apply")
292
  async def apply_media_rescan(
293
  request: Request,
@@ -298,8 +541,52 @@ async def apply_media_rescan(
298
  ):
299
  return await apply_media_rescan_api(request, tmdb_id, db_index, media_type)
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
 
302
- # --- Custom Catalog Management ---
 
303
  @app.get("/api/custom-catalogs")
304
  async def list_custom_catalogs(
305
  tmdb_id: int | None = None,
@@ -321,6 +608,19 @@ async def update_custom_catalog(catalog_id: str, payload: dict, _: bool = Depend
321
  async def delete_custom_catalog(catalog_id: str, _: bool = Depends(require_auth)):
322
  return await delete_custom_catalog_api(catalog_id)
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  @app.get("/api/custom-catalogs/search-media")
325
  async def search_catalog_media(
326
  query: str,
@@ -331,18 +631,25 @@ async def search_catalog_media(
331
  ):
332
  return await search_catalog_media_api(query, media_type, page, page_size)
333
 
334
-
335
  @app.post("/api/custom-catalogs/auto-sync")
336
  async def auto_sync_custom_catalogs(
337
- full_rebuild: bool = Query(False),
338
  _: bool = Depends(require_auth)
339
  ):
340
- return await auto_sync_custom_catalogs_api(full_rebuild)
341
 
342
  @app.get("/api/custom-catalogs/auto-sync/status")
343
  async def auto_catalog_sync_status(_: bool = Depends(require_auth)):
344
  return await auto_catalog_sync_status_api()
345
 
 
 
 
 
 
 
 
 
346
  @app.get("/api/custom-catalogs/auto-sync/settings")
347
  async def get_auto_catalog_settings_route(_: bool = Depends(require_auth)):
348
  return await get_auto_catalog_settings_api()
@@ -376,7 +683,7 @@ async def remove_custom_catalog_item(
376
  return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type)
377
 
378
 
379
-
380
  @app.get("/admin/settings", response_class=HTMLResponse)
381
  async def admin_settings(request: Request, _: bool = Depends(require_auth)):
382
  return await settings_page(request, _)
@@ -389,7 +696,103 @@ async def get_settings(_: bool = Depends(require_auth)):
389
  async def update_settings(payload: dict, _: bool = Depends(require_auth)):
390
  return await update_settings_api(payload)
391
 
392
- # --- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  @app.get("/admin/tools", response_class=HTMLResponse)
394
  async def admin_tools(request: Request, _: bool = Depends(require_auth)):
395
  return await tools_page(request, _)
@@ -398,6 +801,34 @@ async def admin_tools(request: Request, _: bool = Depends(require_auth)):
398
  async def tools_channels(_: bool = Depends(require_auth)):
399
  return await get_tools_channels_api()
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  @app.post("/api/admin/tools/scan/start")
402
  async def tools_scan_start(payload: dict, _: bool = Depends(require_auth)):
403
  return await start_scan_api(payload)
@@ -426,6 +857,33 @@ async def tools_dbcheck_status(_: bool = Depends(require_auth)):
426
  async def tools_purge_dead_links(payload: dict | None = None, _: bool = Depends(require_auth)):
427
  return await purge_dead_links_api(payload)
428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  @app.exception_handler(401)
430
  async def auth_exception_handler(request: Request, exc):
 
 
 
 
 
 
 
 
 
 
431
  return RedirectResponse(url="/login", status_code=302)
 
1
+ import asyncio
2
+
3
+ from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request
4
  from fastapi.middleware.cors import CORSMiddleware
5
+ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
6
  from fastapi.staticfiles import StaticFiles
 
7
  from fastapi.templating import Jinja2Templates
8
+
9
  from Backend import __version__
10
+ from Backend.fastapi.themes import get_theme, theme_key
11
+ from Backend.fastapi.routes.api_routes import (
12
+ add_custom_catalog_item_api,
13
+ add_subscription_plan_api,
14
+ apply_media_rescan_api,
15
+ assign_plan_api,
16
+ auto_catalog_sync_status_api,
17
+ auto_sync_custom_catalogs_api,
18
+ cancel_dbcheck_api,
19
+ cancel_duplicate_check_api,
20
+ cancel_scan_api,
21
+ clear_cache_api,
22
+ clear_stream_analytics_api,
23
+ create_custom_catalog_api,
24
+ create_token_api,
25
+ grant_lifetime_api,
26
+ set_token_lifetime_api,
27
+ set_token_expiry_api,
28
+ subscription_preflight_api,
29
+ backfill_subscriber_names_api,
30
+ dbcheck_status_api,
31
+ duplicate_check_status_api,
32
+ delete_custom_catalog_api,
33
+ delete_media_api,
34
+ delete_movie_quality_api,
35
+ delete_request_api,
36
+ delete_subscription_plan_api,
37
+ export_config_api,
38
+ import_config_api,
39
+ delete_tv_episode_api,
40
+ delete_tv_quality_api,
41
+ delete_tv_season_api,
42
+ download_logs_api,
43
+ get_admin_stats_api,
44
+ get_db_stats_api,
45
+ get_all_subscribers_api,
46
+ get_all_tokens_api,
47
+ get_auto_catalog_settings_api,
48
+ get_catalog_order_api,
49
+ update_catalog_order_api,
50
+ get_user_activity_api,
51
+ session_send_code_api,
52
+ session_verify_code_api,
53
+ session_verify_password_api,
54
+ session_status_api,
55
+ session_disconnect_api,
56
+ session_reconnect_api,
57
+ session_remove_api,
58
+ get_custom_catalog_items_api,
59
+ get_dead_links_api,
60
+ get_media_visibility_api,
61
+ get_requests_api,
62
+ request_popular_api,
63
+ request_search_api,
64
+ request_submit_api,
65
+ get_stream_analytics_api,
66
+ get_subscription_plans_api,
67
+ get_settings_api,
68
+ get_logs_api,
69
+ get_manual_session_api,
70
+ get_system_stats_api,
71
+ get_tools_channels_api,
72
+ bot_admin_scan_api,
73
+ bot_admin_apply_api,
74
+ bot_admin_apply_status_api,
75
+ clear_manual_session_api,
76
+ search_manual_session_api,
77
+ set_manual_session_api,
78
+ health_api,
79
+ health_report_api,
80
+ version_status_api,
81
+ setup_status_api,
82
+ link_token_user_api,
83
+ list_custom_catalogs_api,
84
+ list_media_api,
85
+ manage_subscriber_api,
86
+ manual_add_media_api,
87
+ list_manual_add_catalogs_api,
88
+ resolve_manual_metadata_api,
89
+ purge_dead_links_api,
90
+ purge_duplicates_api,
91
+ remove_custom_catalog_item_api,
92
+ resolve_telegram_api,
93
+ resolve_subtitle_api,
94
+ list_subtitle_languages_api,
95
+ list_subtitles_api,
96
+ add_subtitles_api,
97
+ remove_subtitle_api,
98
+ restart_app_api,
99
+ revoke_token_api,
100
+ scan_status_api,
101
+ search_catalog_media_api,
102
+ set_media_visibility_api,
103
+ search_media_rescan_api,
104
+ tag_media_api,
105
+ speed_test_api,
106
+ speed_test_stream_api,
107
+ start_dbcheck_api,
108
+ start_duplicate_check_api,
109
+ start_scan_api,
110
+ update_auto_catalog_settings_api,
111
+ update_custom_catalog_api,
112
+ update_media_api,
113
+ update_request_api,
114
+ update_settings_api,
115
+ update_subscription_plan_api,
116
+ update_token_cf_api,
117
+ update_token_limits_api,
118
+ )
119
+ from Backend.fastapi.routes.stream_routes import decay_client_failures
120
+ from Backend.fastapi.routes.stream_routes import router as stream_router
121
+ from Backend.fastapi.routes.cf_routes import router as cf_router
122
  from Backend.fastapi.routes.stremio_routes import router as stremio_router
123
+ from Backend.fastapi.routes.webdav_routes import router as webdav_router
124
  from Backend.fastapi.routes.template_routes import (
125
+ admin_access_page,
126
+ admin_dashboard_page,
127
+ admin_requests_page,
128
+ admin_subscriptions_page,
129
+ public_request_page,
130
+ custom_catalogs_page,
131
+ dashboard_page,
132
+ edit_media_page,
133
+ login_page,
134
+ login_post,
135
+ logout,
136
+ media_management_page,
137
+ settings_page,
138
+ set_theme,
139
+ tools_page,
 
 
 
 
 
 
 
 
 
 
 
140
  )
141
+ from Backend.fastapi.security.credentials import require_auth
142
+ from Backend.pyrofork.bot import work_loads_summary
143
 
144
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
145
 
 
149
  version=__version__
150
  )
151
 
152
+ #----- Middleware
 
153
  app.add_middleware(
154
  CORSMiddleware,
155
  allow_origins=["*"],
 
163
  except Exception:
164
  pass
165
 
166
+
167
  @app.on_event("startup")
168
  async def _startup():
 
169
  asyncio.create_task(decay_client_failures())
170
+ from Backend.helper.version_check import version_check_loop
171
+ asyncio.create_task(version_check_loop())
172
 
173
+
174
+ #----- Streaming and Stremio routers
175
  app.include_router(stream_router)
176
+ app.include_router(cf_router)
177
  app.include_router(stremio_router)
178
+ app.include_router(webdav_router)
179
+
180
 
181
+ #----- Public routes (no authentication)
182
  @app.get("/login", response_class=HTMLResponse)
183
  async def login_get(request: Request):
184
  return await login_page(request)
 
192
  return await logout(request)
193
 
194
  @app.post("/set-theme")
195
+ async def set_theme_route(request: Request, theme: str = Form(None)):
196
  return await set_theme(request, theme)
197
 
198
+ @app.get("/manifest.webmanifest")
199
+ async def pwa_manifest(request: Request):
200
+ theme = get_theme(theme_key(request))
201
+ return JSONResponse(
202
+ {
203
+ "name": "Telegram Stremio",
204
+ "short_name": "TG Stremio",
205
+ "description": "Telegram Stremio media management",
206
+ "start_url": "/",
207
+ "scope": "/",
208
+ "display": "standalone",
209
+ "orientation": "any",
210
+ "background_color": theme["colors"]["background"],
211
+ "theme_color": theme["colors"]["primary"],
212
+ "icons": [
213
+ {
214
+ "src": "/pwa-icon.svg",
215
+ "sizes": "any",
216
+ "type": "image/svg+xml",
217
+ "purpose": "any"
218
+ },
219
+ {
220
+ "src": "/pwa-icon.svg",
221
+ "sizes": "any",
222
+ "type": "image/svg+xml",
223
+ "purpose": "maskable"
224
+ }
225
+ ]
226
+ },
227
+ media_type="application/manifest+json",
228
+ headers={"Cache-Control": "no-cache"}
229
+ )
230
+
231
+ @app.get("/pwa-icon.svg")
232
+ async def pwa_icon(request: Request):
233
+ theme = get_theme(theme_key(request))
234
+ primary = theme["colors"]["primary"]
235
+ svg = (
236
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">'
237
+ f'<rect width="512" height="512" rx="96" fill="{primary}"/>'
238
+ f'<path d="M200 152l176 104-176 104z" fill="{theme["colors"]["on_primary"]}"/>'
239
+ f'</svg>'
240
+ )
241
+ return Response(
242
+ content=svg,
243
+ media_type="image/svg+xml",
244
+ headers={"Cache-Control": "no-cache"}
245
+ )
246
+
247
+ @app.get("/sw.js")
248
+ async def service_worker():
249
+ js = (
250
+ "self.addEventListener('install',e=>self.skipWaiting());"
251
+ "self.addEventListener('activate',e=>e.waitUntil(clients.claim()));"
252
+ "self.addEventListener('fetch',e=>e.respondWith(fetch(e.request).catch(()=>caches.match(e.request))));"
253
+ )
254
+ return Response(
255
+ content=js,
256
+ media_type="application/javascript",
257
+ headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"}
258
+ )
259
+
260
+ @app.get("/status")
261
+ async def public_status():
262
+ return {"status": "ok", "version": __version__}
263
+
264
+ @app.get("/open/{app_name}/{media_type}/{content_id}", response_class=HTMLResponse)
265
+ async def open_in_app(app_name: str, media_type: str, content_id: str):
266
+ stremio_type = "series" if media_type in ("series", "tv") else "movie"
267
+ web = f"https://web.stremio.com/#/detail/{stremio_type}/{content_id}/{content_id}"
268
+ schemes = {
269
+ "nuvio": f"nuvio://meta?type={stremio_type}&id={content_id}",
270
+ "stremio": f"stremio:///detail/{stremio_type}/{content_id}",
271
+ }
272
+ scheme = schemes.get(app_name, schemes["stremio"])
273
+ label = "Nuvio" if app_name == "nuvio" else "Stremio"
274
+ html = f"""<!doctype html><html><head><meta charset="utf-8">
275
+ <meta name="viewport" content="width=device-width,initial-scale=1">
276
+ <title>Opening {label}…</title>
277
+ <style>body{{font-family:system-ui,-apple-system,sans-serif;background:#0f172a;color:#f8fafc;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;text-align:center}}a{{color:#60a5fa}}.b{{display:inline-block;margin-top:16px;padding:12px 22px;background:#3b82f6;color:#fff;border-radius:12px;text-decoration:none;font-weight:700}}</style>
278
+ </head><body><div><h2>Opening in {label}…</h2>
279
+ <p>If nothing happens, use the buttons below.</p>
280
+ <a class="b" href="{scheme}">Open {label}</a><br>
281
+ <a class="b" style="background:#334155" href="{web}">Open Stremio Web</a></div>
282
+ <script>setTimeout(function(){{window.location.href="{scheme}";}},200);</script>
283
+ </body></html>"""
284
+ return HTMLResponse(html)
285
+
286
+
287
+ #----- Protected routes (authentication required)
288
  @app.get("/", response_class=HTMLResponse)
289
  async def root(request: Request, _: bool = Depends(require_auth)):
290
  return await dashboard_page(request, _)
 
294
  return await admin_dashboard_page(request, _)
295
 
296
  @app.get("/media/manage", response_class=HTMLResponse)
297
+ async def media_management(request: Request, media_type: str = "movie", custom: bool = False, _: bool = Depends(require_auth)):
298
+ return await media_management_page(request, media_type, custom, _)
 
299
 
300
  @app.get("/catalogs", response_class=HTMLResponse)
301
  async def custom_catalogs(request: Request, _: bool = Depends(require_auth)):
 
311
  page: int = Query(1, ge=1),
312
  page_size: int = Query(24, ge=1, le=100),
313
  search: str = Query("", max_length=100),
314
+ custom: bool = Query(False),
315
  _: bool = Depends(require_auth)
316
  ):
317
+ return await list_media_api(media_type, page, page_size, search, custom)
318
 
319
  @app.delete("/api/media/delete")
320
  async def delete_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
 
343
  @app.get("/api/system/workloads")
344
  async def get_workloads(_: bool = Depends(require_auth)):
345
  try:
346
+ return {"loads": work_loads_summary()}
347
+ except Exception:
 
 
 
 
 
 
 
 
348
  return {"loads": {}}
349
 
350
  @app.post("/api/tokens")
 
355
  async def update_token(token: str, payload: dict, _: bool = Depends(require_auth)):
356
  return await update_token_limits_api(token, payload)
357
 
358
+ @app.put("/api/tokens/{token}/cf")
359
+ async def update_token_cf(token: str, payload: dict, _: bool = Depends(require_auth)):
360
+ return await update_token_cf_api(token, payload)
361
+
362
  @app.delete("/api/tokens/{token}")
363
  async def revoke_token(token: str, _: bool = Depends(require_auth)):
364
  return await revoke_token_api(token)
365
 
366
  @app.get("/api/system/stats")
367
  async def get_system_stats(_: bool = Depends(require_auth)):
 
368
  return await get_system_stats_api()
369
 
370
  @app.get("/api/admin/system-stats")
 
383
  async def get_stream_analytics(_: bool = Depends(require_auth)):
384
  return await get_stream_analytics_api()
385
 
386
+ @app.get("/api/admin/user-activity")
387
+ async def get_user_activity(page: int = 1, per_page: int = 5, _: bool = Depends(require_auth)):
388
+ return await get_user_activity_api(page, per_page)
389
+
390
  @app.post("/api/admin/clear-analytics")
391
  async def clear_analytics(_: bool = Depends(require_auth)):
392
  return await clear_stream_analytics_api()
 
419
  async def manage_subscriber(user_id: int, payload: dict, _: bool = Depends(require_auth)):
420
  return await manage_subscriber_api(user_id, payload)
421
 
422
+
423
+ #----- Access management
424
  @app.get("/admin/access", response_class=HTMLResponse)
425
  async def admin_access(request: Request, _: bool = Depends(require_auth)):
426
  return await admin_access_page(request, _)
 
431
 
432
  @app.delete("/api/admin/access/tokens/{token}")
433
  async def delete_access_token(token: str, _: bool = Depends(require_auth)):
434
+ return await revoke_token_api(token)
 
435
 
436
  @app.post("/api/admin/access/users/{user_id}/assign-plan")
437
  async def assign_access_plan(user_id: int, payload: dict, _: bool = Depends(require_auth)):
 
442
  async def link_token_to_user(token: str, payload: dict, _: bool = Depends(require_auth)):
443
  user_id = int(payload.get("user_id", 0))
444
  if not user_id:
 
445
  raise HTTPException(status_code=400, detail="user_id is required.")
446
  return await link_token_user_api(token, user_id)
447
 
448
+ @app.patch("/api/admin/access/tokens/{token}/lifetime")
449
+ async def set_token_lifetime(token: str, payload: dict, _: bool = Depends(require_auth)):
450
+ return await set_token_lifetime_api(token, payload)
451
+
452
+ @app.post("/api/admin/access/tokens/{token}/expiry")
453
+ async def set_token_expiry(token: str, payload: dict, _: bool = Depends(require_auth)):
454
+ return await set_token_expiry_api(token, payload)
455
+
456
+ @app.post("/api/admin/access/grant-lifetime")
457
+ async def grant_lifetime(_: bool = Depends(require_auth)):
458
+ return await grant_lifetime_api()
459
+
460
+ @app.get("/api/admin/subscriptions/preflight")
461
+ async def subscription_preflight(_: bool = Depends(require_auth)):
462
+ return await subscription_preflight_api()
463
+
464
+ @app.post("/api/admin/subscriptions/backfill-names")
465
+ async def backfill_subscriber_names(_: bool = Depends(require_auth)):
466
+ return await backfill_subscriber_names_api()
467
+
468
+
469
+ #----- Public content request page (no auth)
470
+ @app.get("/request", response_class=HTMLResponse)
471
+ async def public_request(request: Request):
472
+ return await public_request_page(request)
473
+
474
+ @app.get("/api/request/search")
475
+ async def request_search(q: str = Query("")):
476
+ return await request_search_api(q)
477
+
478
+ @app.get("/api/request/popular")
479
+ async def request_popular():
480
+ return await request_popular_api()
481
+
482
+ @app.post("/api/request/submit")
483
+ async def request_submit(payload: dict, request: Request):
484
+ client_ip = request.client.host if request.client else None
485
+ return await request_submit_api(payload, client_ip)
486
+
487
+
488
+ #----- Admin content requests
489
+ @app.get("/admin/requests", response_class=HTMLResponse)
490
+ async def admin_requests(request: Request, _: bool = Depends(require_auth)):
491
+ return await admin_requests_page(request, _)
492
+
493
+ @app.get("/api/admin/requests")
494
+ async def get_requests(_: bool = Depends(require_auth)):
495
+ return await get_requests_api()
496
+
497
+ @app.patch("/api/admin/requests/{request_id}")
498
+ async def update_request(request_id: str, payload: dict, _: bool = Depends(require_auth)):
499
+ return await update_request_api(request_id, payload)
500
+
501
+ @app.delete("/api/admin/requests/{request_id}")
502
+ async def delete_request_route(request_id: str, _: bool = Depends(require_auth)):
503
+ return await delete_request_api(request_id)
504
+
505
  @app.get("/api/system/speedtest")
506
  async def speed_test(
507
  quality_id: str = Query(...),
 
522
  ):
523
  return await speed_test_stream_api(quality_id, tmdb_id, db_index, media_type)
524
 
 
525
  @app.get("/api/media/rescan/search")
526
  async def search_media_rescan(
527
  media_type: str,
 
531
  ):
532
  return await search_media_rescan_api(media_type, query, year)
533
 
 
534
  @app.post("/api/media/rescan/apply")
535
  async def apply_media_rescan(
536
  request: Request,
 
541
  ):
542
  return await apply_media_rescan_api(request, tmdb_id, db_index, media_type)
543
 
544
+ @app.post("/api/media/tag")
545
+ async def tag_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
546
+ return await tag_media_api(tmdb_id, db_index, media_type)
547
+
548
+
549
+ #----- Manual add (custom movie/tv/season/episode/stream)
550
+ @app.post("/api/media/resolve-telegram")
551
+ async def resolve_telegram(payload: dict, _: bool = Depends(require_auth)):
552
+ return await resolve_telegram_api(payload)
553
+
554
+ @app.post("/api/media/manual-add")
555
+ async def manual_add_media(payload: dict, _: bool = Depends(require_auth)):
556
+ return await manual_add_media_api(payload)
557
+
558
+ @app.get("/api/media/manual-add/catalogs")
559
+ async def manual_add_catalogs(_: bool = Depends(require_auth)):
560
+ return await list_manual_add_catalogs_api()
561
+
562
+ @app.get("/api/media/manual-add/resolve-meta")
563
+ async def manual_add_resolve_meta(media_type: str, selected_id: str, _: bool = Depends(require_auth)):
564
+ return await resolve_manual_metadata_api(media_type, selected_id)
565
+
566
+
567
+ #----- Manual subtitle management
568
+ @app.get("/api/media/subtitles/languages")
569
+ async def subtitle_languages(_: bool = Depends(require_auth)):
570
+ return list_subtitle_languages_api()
571
+
572
+ @app.get("/api/media/subtitles")
573
+ async def list_subtitles(media_type: str, tmdb_id: int, db_index: int, _: bool = Depends(require_auth)):
574
+ return await list_subtitles_api(media_type, tmdb_id, db_index)
575
+
576
+ @app.post("/api/media/subtitles/resolve")
577
+ async def resolve_subtitle(payload: dict, _: bool = Depends(require_auth)):
578
+ return await resolve_subtitle_api(payload)
579
+
580
+ @app.post("/api/media/subtitles/add")
581
+ async def add_subtitles(payload: dict, _: bool = Depends(require_auth)):
582
+ return await add_subtitles_api(payload)
583
+
584
+ @app.post("/api/media/subtitles/remove")
585
+ async def remove_subtitle_route(payload: dict, _: bool = Depends(require_auth)):
586
+ return await remove_subtitle_api(payload)
587
 
588
+
589
+ #----- Custom catalog management
590
  @app.get("/api/custom-catalogs")
591
  async def list_custom_catalogs(
592
  tmdb_id: int | None = None,
 
608
  async def delete_custom_catalog(catalog_id: str, _: bool = Depends(require_auth)):
609
  return await delete_custom_catalog_api(catalog_id)
610
 
611
+ @app.post("/api/custom-catalogs/media-visibility")
612
+ async def set_media_visibility(payload: dict, _: bool = Depends(require_auth)):
613
+ return await set_media_visibility_api(payload)
614
+
615
+ @app.get("/api/custom-catalogs/media-visibility")
616
+ async def get_media_visibility(
617
+ tmdb_id: int,
618
+ db_index: int,
619
+ media_type: str = Query("movie", regex="^(movie|tv|series)$"),
620
+ _: bool = Depends(require_auth)
621
+ ):
622
+ return await get_media_visibility_api(tmdb_id, db_index, media_type)
623
+
624
  @app.get("/api/custom-catalogs/search-media")
625
  async def search_catalog_media(
626
  query: str,
 
631
  ):
632
  return await search_catalog_media_api(query, media_type, page, page_size)
633
 
 
634
  @app.post("/api/custom-catalogs/auto-sync")
635
  async def auto_sync_custom_catalogs(
636
+ force_refresh: bool = Query(False),
637
  _: bool = Depends(require_auth)
638
  ):
639
+ return await auto_sync_custom_catalogs_api(force_refresh)
640
 
641
  @app.get("/api/custom-catalogs/auto-sync/status")
642
  async def auto_catalog_sync_status(_: bool = Depends(require_auth)):
643
  return await auto_catalog_sync_status_api()
644
 
645
+ @app.get("/api/custom-catalogs-order")
646
+ async def get_catalog_order_route(_: bool = Depends(require_auth)):
647
+ return await get_catalog_order_api()
648
+
649
+ @app.put("/api/custom-catalogs-order")
650
+ async def update_catalog_order_route(payload: dict, _: bool = Depends(require_auth)):
651
+ return await update_catalog_order_api(payload)
652
+
653
  @app.get("/api/custom-catalogs/auto-sync/settings")
654
  async def get_auto_catalog_settings_route(_: bool = Depends(require_auth)):
655
  return await get_auto_catalog_settings_api()
 
683
  return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type)
684
 
685
 
686
+ #----- Settings
687
  @app.get("/admin/settings", response_class=HTMLResponse)
688
  async def admin_settings(request: Request, _: bool = Depends(require_auth)):
689
  return await settings_page(request, _)
 
696
  async def update_settings(payload: dict, _: bool = Depends(require_auth)):
697
  return await update_settings_api(payload)
698
 
699
+
700
+ @app.post("/api/admin/settings/formatter-preview")
701
+ async def formatter_preview(payload: dict, _: bool = Depends(require_auth)):
702
+ from Backend.helper.stream_formatter import PRESETS, build_parse_value, render
703
+ tpl = PRESETS.get(payload.get("preset")) or {"name": str(payload.get("name") or ""), "description": str(payload.get("description") or "")}
704
+ pv = build_parse_value(str(payload.get("filename") or "video.mkv"), 2_500_000_000, channel="My Channel",
705
+ meta={"queryType": "movie", "type": "movie"})
706
+ return {"name": render(tpl["name"], pv), "description": render(tpl["description"], pv)}
707
+
708
+
709
+ #----- Telegram user session login (replaces manual USER_SESSION_STRING)
710
+ @app.get("/api/admin/settings/session")
711
+ async def session_status(_: bool = Depends(require_auth)):
712
+ return await session_status_api()
713
+
714
+ @app.post("/api/admin/settings/session/send-code")
715
+ async def session_send_code(payload: dict, _: bool = Depends(require_auth)):
716
+ return await session_send_code_api(payload)
717
+
718
+ @app.post("/api/admin/settings/session/verify-code")
719
+ async def session_verify_code(payload: dict, _: bool = Depends(require_auth)):
720
+ return await session_verify_code_api(payload)
721
+
722
+ @app.post("/api/admin/settings/session/verify-password")
723
+ async def session_verify_password(payload: dict, _: bool = Depends(require_auth)):
724
+ return await session_verify_password_api(payload)
725
+
726
+ @app.post("/api/admin/settings/session/disconnect")
727
+ async def session_disconnect(_: bool = Depends(require_auth)):
728
+ return await session_disconnect_api()
729
+
730
+ @app.post("/api/admin/settings/session/reconnect")
731
+ async def session_reconnect(_: bool = Depends(require_auth)):
732
+ return await session_reconnect_api()
733
+
734
+ @app.delete("/api/admin/settings/session")
735
+ async def session_remove(_: bool = Depends(require_auth)):
736
+ return await session_remove_api()
737
+
738
+
739
+ #----- System & Maintenance (WebUI replacement for /stats, /log, /restart bot commands)
740
+ @app.get("/api/admin/stats")
741
+ async def admin_db_stats(_: bool = Depends(require_auth)):
742
+ return await get_db_stats_api()
743
+
744
+ @app.get("/api/admin/health")
745
+ async def admin_health(_: bool = Depends(require_auth)):
746
+ return await health_api()
747
+
748
+ @app.get("/api/admin/health/report")
749
+ async def admin_health_report(fresh: bool = Query(False), _: bool = Depends(require_auth)):
750
+ return await health_report_api(force=fresh)
751
+
752
+ @app.get("/api/admin/version")
753
+ async def admin_version(force: bool = Query(False), _: bool = Depends(require_auth)):
754
+ return await version_status_api(force=force)
755
+
756
+ @app.get("/api/admin/setup-status")
757
+ async def admin_setup_status(_: bool = Depends(require_auth)):
758
+ return await setup_status_api()
759
+
760
+ @app.get("/api/admin/backup/export")
761
+ async def admin_backup_export(_: bool = Depends(require_auth)):
762
+ from fastapi.responses import JSONResponse
763
+ data = await export_config_api()
764
+ return JSONResponse(
765
+ content=data,
766
+ headers={"Content-Disposition": 'attachment; filename="telegram-stremio-backup.json"'},
767
+ )
768
+
769
+ @app.get("/api/admin/backup/library")
770
+ async def admin_backup_library(_: bool = Depends(require_auth)):
771
+ from fastapi.responses import StreamingResponse
772
+ from Backend.helper.backup import export_library
773
+ return StreamingResponse(
774
+ export_library(), media_type="application/gzip",
775
+ headers={"Content-Disposition": 'attachment; filename="telestremio-catalog.json.gz"'},
776
+ )
777
+
778
+ @app.post("/api/admin/backup/import")
779
+ async def admin_backup_import(payload: dict, _: bool = Depends(require_auth)):
780
+ return await import_config_api(payload)
781
+
782
+ @app.get("/api/admin/logs")
783
+ async def admin_logs(lines: int = Query(300, ge=1, le=2000), _: bool = Depends(require_auth)):
784
+ return await get_logs_api(lines)
785
+
786
+ @app.get("/api/admin/logs/download")
787
+ async def admin_logs_download(_: bool = Depends(require_auth)):
788
+ return await download_logs_api()
789
+
790
+ @app.post("/api/admin/restart")
791
+ async def admin_restart(_: bool = Depends(require_auth)):
792
+ return await restart_app_api()
793
+
794
+
795
+ #----- Tools (WebUI replacement for /scan, /rescan, /dbcheck bot commands)
796
  @app.get("/admin/tools", response_class=HTMLResponse)
797
  async def admin_tools(request: Request, _: bool = Depends(require_auth)):
798
  return await tools_page(request, _)
 
801
  async def tools_channels(_: bool = Depends(require_auth)):
802
  return await get_tools_channels_api()
803
 
804
+ @app.get("/api/admin/tools/bot-admin/scan")
805
+ async def tools_bot_admin_scan(_: bool = Depends(require_auth)):
806
+ return await bot_admin_scan_api()
807
+
808
+ @app.post("/api/admin/tools/bot-admin/apply")
809
+ async def tools_bot_admin_apply(payload: dict, _: bool = Depends(require_auth)):
810
+ return await bot_admin_apply_api(payload)
811
+
812
+ @app.get("/api/admin/tools/bot-admin/apply/status")
813
+ async def tools_bot_admin_apply_status(_: bool = Depends(require_auth)):
814
+ return await bot_admin_apply_status_api()
815
+
816
+ @app.get("/api/admin/tools/manual-session")
817
+ async def tools_manual_session_get(_: bool = Depends(require_auth)):
818
+ return await get_manual_session_api()
819
+
820
+ @app.get("/api/admin/tools/manual-session/search")
821
+ async def tools_manual_session_search(query: str = Query(""), _: bool = Depends(require_auth)):
822
+ return await search_manual_session_api(query)
823
+
824
+ @app.post("/api/admin/tools/manual-session")
825
+ async def tools_manual_session_set(payload: dict, _: bool = Depends(require_auth)):
826
+ return await set_manual_session_api(payload)
827
+
828
+ @app.delete("/api/admin/tools/manual-session")
829
+ async def tools_manual_session_clear(_: bool = Depends(require_auth)):
830
+ return await clear_manual_session_api()
831
+
832
  @app.post("/api/admin/tools/scan/start")
833
  async def tools_scan_start(payload: dict, _: bool = Depends(require_auth)):
834
  return await start_scan_api(payload)
 
857
  async def tools_purge_dead_links(payload: dict | None = None, _: bool = Depends(require_auth)):
858
  return await purge_dead_links_api(payload)
859
 
860
+ @app.post("/api/admin/tools/duplicates/start")
861
+ async def tools_duplicates_start(_: bool = Depends(require_auth)):
862
+ return await start_duplicate_check_api()
863
+
864
+ @app.post("/api/admin/tools/duplicates/cancel")
865
+ async def tools_duplicates_cancel(_: bool = Depends(require_auth)):
866
+ return await cancel_duplicate_check_api()
867
+
868
+ @app.get("/api/admin/tools/duplicates/status")
869
+ async def tools_duplicates_status(_: bool = Depends(require_auth)):
870
+ return await duplicate_check_status_api()
871
+
872
+ @app.post("/api/admin/tools/duplicates/purge")
873
+ async def tools_duplicates_purge(payload: dict | None = None, _: bool = Depends(require_auth)):
874
+ return await purge_duplicates_api(payload)
875
+
876
+
877
  @app.exception_handler(401)
878
  async def auth_exception_handler(request: Request, exc):
879
+ # API / stream / WebDAV clients must receive a real 401, not an HTML login redirect.
880
+ path = request.url.path or ""
881
+ if path.startswith(("/webdav", "/dl/", "/sub/", "/stremio/", "/api/", "/thumb/")):
882
+ from fastapi.responses import JSONResponse
883
+ detail = getattr(exc, "detail", "Unauthorized")
884
+ headers = {}
885
+ # Preserve WWW-Authenticate for WebDAV Basic auth prompts
886
+ if hasattr(exc, "headers") and exc.headers:
887
+ headers.update(exc.headers)
888
+ return JSONResponse(status_code=401, content={"detail": detail}, headers=headers)
889
  return RedirectResponse(url="/login", status_code=302)
Backend/fastapi/routes/api_routes.py CHANGED
The diff for this file is too large to render. See raw diff
 
Backend/fastapi/routes/cf_routes.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ from fastapi import APIRouter, HTTPException, Request
4
+
5
+ from Backend import db
6
+ from Backend.config import Telegram
7
+ from Backend.helper.analytics import record_stream_start
8
+ from Backend.helper.cf_live import apply_report
9
+ from Backend.helper.cf_stream import verify_worker_request
10
+ from Backend.helper.own_bots import worker_tokens
11
+ from Backend.helper.session_auth import get_active_session_string
12
+ from Backend.helper.settings_manager import SettingsManager
13
+ from Backend.logger import LOGGER
14
+
15
+ router = APIRouter(tags=["Cloudflare"])
16
+
17
+
18
+ #----- Only the Cloudflare Worker (holding the shared secret) may call these routes
19
+ async def _verified_body(request: Request) -> tuple:
20
+ body = await request.body()
21
+ signed = (request.method, request.url.path, body, request.headers.get("x-cf-time", ""), request.headers.get("x-cf-sig", ""))
22
+ if verify_worker_request(*signed):
23
+ return body, None
24
+ for doc in await worker_tokens():
25
+ if verify_worker_request(*signed, doc["cf"]["secret"]):
26
+ return body, doc
27
+ raise HTTPException(status_code=401, detail="Bad signature")
28
+
29
+
30
+ #----- Telegram credentials the Worker needs to stream: API app, bot pool, optional userbot
31
+ @router.get("/api/cf/config")
32
+ async def cf_config(request: Request):
33
+ _, owner = await _verified_body(request)
34
+ if owner:
35
+ bots = [b["token"] for b in (owner.get("own_bots") or {}).get("bots") or []]
36
+ return {"api_id": Telegram.API_ID, "api_hash": Telegram.API_HASH, "bots": bots, "user_session": ""}
37
+ tokens = [Telegram.BOT_TOKEN, *SettingsManager.current().multi_tokens]
38
+ try:
39
+ user_session = await get_active_session_string() or ""
40
+ except Exception as e:
41
+ LOGGER.warning(f"[CF] Could not load userbot session: {e}")
42
+ user_session = ""
43
+ return {
44
+ "api_id": Telegram.API_ID,
45
+ "api_hash": Telegram.API_HASH,
46
+ "bots": [t for t in dict.fromkeys(tokens) if t],
47
+ "user_session": user_session,
48
+ }
49
+
50
+
51
+ #----- Bytes streamed per token (for daily/monthly limits) and stream-start analytics
52
+ @router.post("/api/cf/usage")
53
+ async def cf_usage(request: Request):
54
+ body, _ = await _verified_body(request)
55
+ data = json.loads(body or b"{}")
56
+ for token, delta in (data.get("usage") or {}).items():
57
+ if isinstance(delta, int) and delta > 0:
58
+ try:
59
+ await db.update_token_usage(token, delta)
60
+ except Exception as e:
61
+ LOGGER.error(f"[CF] Usage update failed for token: {e}")
62
+ names = {}
63
+ for start in data.get("starts") or []:
64
+ token = str(start.get("token") or "")
65
+ if not token:
66
+ continue
67
+ if token not in names:
68
+ token_data = await db.get_api_token(token)
69
+ names[token] = token_data.get("name") if token_data else None
70
+ await record_stream_start(token, names[token], str(start.get("ip") or ""), str(start.get("ua") or ""))
71
+ #----- Live streams, so dashboards and user activity show Cloudflare streams too
72
+ if isinstance(data.get("streams"), list) and data.get("member"):
73
+ try:
74
+ await apply_report(str(data["member"]), data.get("client_index"), data.get("dc"), data["streams"])
75
+ except Exception as e:
76
+ LOGGER.error(f"[CF] Live stream report failed: {e}")
77
+ return {"ok": True}
Backend/fastapi/routes/stream_routes.py CHANGED
@@ -1,31 +1,52 @@
1
- import math
2
- import time
3
  import asyncio
4
- import secrets
5
  import mimetypes
6
- from typing import Dict
7
- from urllib.parse import unquote
8
- from math import ceil
9
- from fastapi import APIRouter, Request, HTTPException, Depends
10
- from fastapi.responses import Response as PlainResponse, StreamingResponse, JSONResponse
11
  from collections import deque
 
 
 
 
 
 
 
 
 
12
  from Backend import db
13
- from Backend.logger import LOGGER
14
- from Backend.helper.encrypt import decode_string
 
 
 
 
 
 
 
15
  from Backend.helper.utils import track_usage
16
- from Backend.helper.custom_dl import ByteStreamer, ACTIVE_STREAMS, RECENT_STREAMS
17
  from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
18
- from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps, Userbot, USERBOT_CLIENT_INDEX
19
- from Backend.fastapi.security.tokens import verify_token
 
 
 
 
 
 
 
 
20
 
21
  router = APIRouter(tags=["Streaming"])
22
 
23
  _streamer_by_client: Dict = {}
24
  _rr_counter: int = 0
 
25
 
26
- _title_cache: Dict[str, tuple] = {}
27
  _TITLE_CACHE_TTL = 300
28
 
 
 
29
  def make_json_safe(obj):
30
  if isinstance(obj, deque):
31
  return list(obj)
@@ -40,6 +61,7 @@ def make_json_safe(obj):
40
  return obj
41
 
42
 
 
43
  def parse_range_header(range_header: str, file_size: int):
44
  if not range_header:
45
  return 0, file_size - 1
@@ -57,38 +79,44 @@ def parse_range_header(range_header: str, file_size: int):
57
  start = int(start_str)
58
  end = int(end_str)
59
  except Exception:
60
- raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"}, )
61
  if start < 0:
62
  start = 0
63
  if end >= file_size:
64
  end = file_size - 1
65
  if end < start:
66
- raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"},)
67
  return start, end
68
 
69
 
 
 
 
 
 
70
  def select_best_client(target_dc: int) -> int:
71
  global _rr_counter
 
 
72
  def _score(idx: int) -> int:
73
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
 
74
  if target_dc > 0:
75
- matching = [
76
- idx for idx, dc in client_dc_map.items()
77
- if dc == target_dc and idx in multi_clients
78
- ]
79
  else:
80
  matching = []
81
  if not matching:
82
- matching = list(multi_clients.keys())
83
  if not matching:
84
  return 0
85
  min_score = min(_score(i) for i in matching)
86
  tied = sorted(i for i in matching if _score(i) == min_score)
87
  selected = tied[_rr_counter % len(tied)]
88
- _rr_counter = (_rr_counter + 1) % max(len(multi_clients), 1)
89
  return selected
90
 
91
 
 
92
  async def decay_client_failures() -> None:
93
  while True:
94
  await asyncio.sleep(300)
@@ -96,22 +124,217 @@ async def decay_client_failures() -> None:
96
  if client_failures.get(k, 0) > 0:
97
  client_failures[k] = max(0, client_failures[k] - 1)
98
 
 
 
99
  def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
100
- value = min(max(ceil(client_count / 5), 1), 5)
101
  return value, value
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  @router.get("/dl/{token}/{id}/{name}")
104
  @router.head("/dl/{token}/{id}/{name}")
105
- async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token),):
106
  decoded = await decode_string(id)
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  if decoded.get("global"):
 
 
 
 
 
 
 
 
 
 
109
  return await global_media_streamer(
110
  request=request, chat_id=int(decoded["chat_id"]), msg_id=int(decoded["msg_id"]),
111
  token=token, token_data=token_data, stream_id_hash=id,
112
  )
113
 
114
  if "parts" in decoded:
 
 
 
 
 
115
  return await virtual_media_streamer(
116
  request=request, parts_payload=decoded["parts"],
117
  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
121
  if not msg_id:
122
  raise HTTPException(status_code=400, detail="Missing id")
123
  chat_id = int(f"-100{decoded['chat_id']}")
124
- return await media_streamer(request=request, chat_id=chat_id, msg_id=int(msg_id),
 
125
  token=token, token_data=token_data, stream_id_hash=id,
126
  )
127
 
128
- async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,):
129
- index = select_best_client(0)
130
- tg_client = multi_clients[index]
131
- if tg_client not in _streamer_by_client:
132
- _streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
133
- streamer: ByteStreamer = _streamer_by_client[tg_client]
134
- file_id = await streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
135
- target_dc = file_id.dc_id
136
  file_size = file_id.file_size
137
  range_header = request.headers.get("Range", "")
138
  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
144
  part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
145
  stream_id = secrets.token_hex(8)
146
  decoded_name = unquote(request.path_params.get("name", ""))
147
- db_title = None
148
- if stream_id_hash:
149
- _now = time.time()
150
- _cached = _title_cache.get(stream_id_hash)
151
- if _cached and _now < _cached[1]:
152
- db_title = _cached[0]
153
- else:
154
- db_title = await db.get_title_by_stream_id(stream_id_hash)
155
- _title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL)
156
- final_title = db_title if db_title else decoded_name
157
  meta = {
158
  "request_path": str(request.url.path),
159
  "client_host": request.client.host if request.client else None,
160
- "title": final_title,
161
- "user_name": token_data.get("name", "Unknown") if token_data else "Unknown"
 
 
162
  }
163
 
164
- token_count = len(multi_clients) - 1
165
- parallelism, prefetch_count = get_parallel_prefetch(token_count)
166
  extra_clients_for_stream = []
167
- if parallelism > 1 and len(multi_clients) > 1:
168
- other_indices = sorted(
169
- (i for i in multi_clients if i != index),
170
- key=lambda i: work_loads.get(i, 0),
171
- )
172
  async def _get_extra_file_id(ec_idx: int):
173
- ec_client = multi_clients[ec_idx]
174
- if ec_client not in _streamer_by_client:
175
- _streamer_by_client[ec_client] = ByteStreamer(ec_client, ec_idx)
176
- ec_streamer = _streamer_by_client[ec_client]
177
  try:
178
  ec_fid = await ec_streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
179
  return (ec_idx, ec_streamer, ec_fid)
180
  except Exception as e:
181
  LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e)
182
  return None
183
- results = await asyncio.gather(*[
184
- _get_extra_file_id(i) for i in other_indices[:parallelism - 1]
185
- ])
186
  extra_clients_for_stream = [r for r in results if r is not None]
187
 
188
  body_gen = await streamer.prefetch_stream(
@@ -205,58 +414,16 @@ async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str
205
 
206
  asyncio.create_task(track_usage(stream_id, token, token_data))
207
 
208
- file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
209
- mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
210
 
211
- if "." not in file_name and "/" in mime_type:
212
- file_name = f"{file_name}.{mime_type.split('/')[1]}"
213
-
214
  if request.method == "HEAD":
215
- headers = {
216
- "Content-Type": mime_type,
217
- "Content-Length": str(req_length),
218
- "Content-Disposition": f'inline; filename="{file_name}"',
219
- "Accept-Ranges": "bytes",
220
- "Cache-Control": "public, max-age=3600",
221
- "Access-Control-Allow-Origin": "*",
222
- "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
223
- }
224
-
225
- if range_header:
226
- headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
227
-
228
- return PlainResponse(
229
- status_code=206 if range_header else 200,
230
- headers=headers,
231
- )
232
-
233
- headers = {
234
- "Content-Type": mime_type,
235
- "Content-Disposition": f'inline; filename="{file_name}"',
236
- "Accept-Ranges": "bytes",
237
- "Content-Length": str(req_length),
238
- "Cache-Control": "public, max-age=3600",
239
- "Access-Control-Allow-Origin": "*",
240
- "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
241
- }
242
-
243
- if range_header:
244
- headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
245
- status = 206
246
- else:
247
- status = 200
248
-
249
- return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
250
 
251
 
252
- async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None,):
253
- index = select_best_client(0)
254
- tg_client = multi_clients[index]
255
- if tg_client not in _streamer_by_client:
256
- _streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
257
- streamer: ByteStreamer = _streamer_by_client[tg_client]
258
-
259
- parts, file_size = await resolve_virtual_parts(parts_payload, streamer)
260
  if not parts or file_size <= 0:
261
  raise HTTPException(status_code=404, detail="Split media parts not found")
262
 
@@ -266,51 +433,24 @@ async def virtual_media_streamer(request: Request, parts_payload: list, token: s
266
  chunk_size = 1024 * 1024
267
  stream_id = secrets.token_hex(8)
268
  decoded_name = unquote(request.path_params.get("name", ""))
269
-
270
- db_title = None
271
- if stream_id_hash:
272
- _now = time.time()
273
- _cached = _title_cache.get(stream_id_hash)
274
- if _cached and _now < _cached[1]:
275
- db_title = _cached[0]
276
- else:
277
- db_title = await db.get_title_by_stream_id(stream_id_hash)
278
- _title_cache[stream_id_hash] = (db_title, _now + _TITLE_CACHE_TTL)
279
- final_title = db_title if db_title else decoded_name
280
 
281
  meta = {
282
  "request_path": str(request.url.path),
283
  "client_host": request.client.host if request.client else None,
284
- "title": final_title,
 
285
  "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
 
286
  "split_parts": len(parts),
287
  }
288
 
289
- token_count = len(multi_clients) - 1
290
- parallelism, prefetch_count = get_parallel_prefetch(token_count)
291
 
292
  asyncio.create_task(track_usage(stream_id, token, token_data))
293
 
294
- first_file_id = parts[0]["file_id"]
295
- file_name = first_file_id.file_name or f"{secrets.token_hex(4)}.bin"
296
- mime_type = first_file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
297
- if "." not in file_name and "/" in mime_type:
298
- file_name = f"{file_name}.{mime_type.split('/')[1]}"
299
-
300
- common_headers = {
301
- "Content-Type": mime_type,
302
- "Content-Disposition": f'inline; filename="{file_name}"',
303
- "Accept-Ranges": "bytes",
304
- "Content-Length": str(req_length),
305
- "Cache-Control": "public, max-age=3600",
306
- "Access-Control-Allow-Origin": "*",
307
- "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
308
- }
309
- if range_header:
310
- common_headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
311
- status = 206
312
- else:
313
- status = 200
314
 
315
  if request.method == "HEAD":
316
  return PlainResponse(status_code=status, headers=common_headers)
@@ -320,29 +460,24 @@ async def virtual_media_streamer(request: Request, parts_payload: list, token: s
320
  streamer=streamer, client_index=index, request=request, meta=meta,
321
  stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
322
  )
323
-
324
- return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type, )
325
 
326
 
327
  _userbot_streamer: ByteStreamer = None
328
 
329
 
 
330
  def _get_userbot_streamer() -> ByteStreamer:
331
- """Lazily build (and cache) the ByteStreamer wrapping the Userbot
332
- client. Returns None if no Userbot is configured."""
333
  global _userbot_streamer
334
- if Userbot is None:
335
  return None
336
- if _userbot_streamer is None:
337
- _userbot_streamer = ByteStreamer(Userbot, USERBOT_CLIENT_INDEX)
338
  return _userbot_streamer
339
 
340
 
341
- async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None,):
342
- """Streams a single file found via Global Search, played back through
343
- the Userbot session directly — these channels aren't part of the Auth
344
- Channel/MultiToken infrastructure, so the regular client pool can't
345
- (and shouldn't) be used here."""
346
  streamer = _get_userbot_streamer()
347
  if streamer is None:
348
  raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot configured)")
@@ -365,35 +500,20 @@ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, tok
365
  part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
366
  stream_id = secrets.token_hex(8)
367
 
 
368
  meta = {
369
  "request_path": str(request.url.path),
370
  "client_host": request.client.host if request.client else None,
371
- "title": file_id.file_name or "global-stream",
 
372
  "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
 
373
  "global_search": True,
374
  }
375
 
376
  asyncio.create_task(track_usage(stream_id, token, token_data))
377
 
378
- file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
379
- mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
380
- if "." not in file_name and "/" in mime_type:
381
- file_name = f"{file_name}.{mime_type.split('/')[1]}"
382
-
383
- headers = {
384
- "Content-Type": mime_type,
385
- "Content-Disposition": f'inline; filename="{file_name}"',
386
- "Accept-Ranges": "bytes",
387
- "Content-Length": str(req_length),
388
- "Cache-Control": "public, max-age=3600",
389
- "Access-Control-Allow-Origin": "*",
390
- "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
391
- }
392
- if range_header:
393
- headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
394
- status = 206
395
- else:
396
- status = 200
397
 
398
  if request.method == "HEAD":
399
  return PlainResponse(status_code=status, headers=headers)
@@ -414,9 +534,150 @@ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, tok
414
  chat_id=chat_id,
415
  message_id=msg_id,
416
  )
 
417
 
418
- return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type, )
419
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  @router.get("/stream/stats")
421
  async def get_stream_stats():
422
  now = time.time()
@@ -436,7 +697,7 @@ async def get_stream_stats():
436
  if now - info["last_activity_ts"] > INACTIVE_TIMEOUT:
437
  if status == "active":
438
  info["status"] = "cancelled"
439
- info["end_ts"] = now
440
  if info.get("status") in ("cancelled", "error", "finished", "inactive"):
441
  last_ts = info.get("end_ts", info.get("last_activity_ts", now))
442
  if now - last_ts > PRUNE_SECONDS:
@@ -444,51 +705,52 @@ async def get_stream_stats():
444
  RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
445
  except KeyError:
446
  pass
447
- active = []
448
- for sid, info in ACTIVE_STREAMS.items():
449
- active.append(
450
- {
451
- "stream_id": sid,
452
- "msg_id": info.get("msg_id"),
453
- "chat_id": info.get("chat_id"),
454
- "title": info.get("meta", {}).get("title"),
455
- "client_index": info.get("client_index"),
456
- "dc_id": info.get("dc_id"),
457
- "status": info.get("status"),
458
- "total_bytes": info.get("total_bytes"),
459
- "instant_mbps": round(info.get("instant_mbps", 0.0), 3),
460
- "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
461
- "peak_mbps": round(info.get("peak_mbps", 0.0), 3),
462
- "start_ts": info.get("start_ts"),
463
- }
464
- )
465
- recent = []
466
- for info in RECENT_STREAMS:
467
- recent.append(
468
- {
469
- "stream_id": info.get("stream_id"),
470
- "msg_id": info.get("msg_id"),
471
- "chat_id": info.get("chat_id"),
472
- "title": info.get("meta", {}).get("title"),
473
- "client_index": info.get("client_index"),
474
- "dc_id": info.get("dc_id"),
475
- "status": info.get("status"),
476
- "total_bytes": info.get("total_bytes"),
477
- "duration": info.get("duration"),
478
- "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
479
- "start_ts": info.get("start_ts"),
480
- "end_ts": info.get("end_ts"),
481
- }
482
- )
483
- return JSONResponse(
484
  {
485
- "active_streams": active,
486
- "recent_streams": recent,
487
- "client_dc_map": client_dc_map,
488
- "work_loads": work_loads,
 
 
 
 
 
 
 
 
 
489
  }
490
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
 
 
492
  @router.get("/stream/stats/{stream_id}")
493
  async def get_stream_detail(stream_id: str):
494
  info = ACTIVE_STREAMS.get(stream_id)
 
 
 
1
  import asyncio
2
+ import math
3
  import mimetypes
4
+ import secrets
5
+ import time
 
 
 
6
  from collections import deque
7
+ from contextvars import ContextVar
8
+ from typing import Dict
9
+ from urllib.parse import quote, unquote
10
+
11
+ from fastapi import APIRouter, Depends, HTTPException, Request
12
+ from fastapi.responses import JSONResponse, RedirectResponse
13
+ from fastapi.responses import Response as PlainResponse
14
+ from fastapi.responses import StreamingResponse
15
+
16
  from Backend import db
17
+ from Backend.fastapi.security.tokens import verify_token
18
+ from Backend.helper.bounded import BoundedDict
19
+ from Backend.helper.analytics import client_ip_from, record_stream_start
20
+ from Backend.helper import own_bots
21
+ from Backend.helper.cf_stream import cf_stream_url
22
+ from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS, ByteStreamer
23
+ from Backend.helper.encrypt import decode_string, encode_string
24
+ from Backend.helper.pyro import get_thumb_download_target
25
+ from Backend.helper.settings_manager import SettingsManager
26
  from Backend.helper.utils import track_usage
 
27
  from Backend.helper.virtual_dl import resolve_virtual_parts, virtual_stream_generator
28
+ from Backend.helper.zip_stream import resolve_zip_entry
29
+ from Backend.logger import LOGGER
30
+ import Backend.pyrofork.bot as botmod
31
+ from Backend.pyrofork.bot import (
32
+ USERBOT_CLIENT_INDEX,
33
+ client_dc_map,
34
+ client_failures,
35
+ multi_clients,
36
+ work_loads,
37
+ )
38
 
39
  router = APIRouter(tags=["Streaming"])
40
 
41
  _streamer_by_client: Dict = {}
42
  _rr_counter: int = 0
43
+ _pool: ContextVar = ContextVar("pool", default=None)
44
 
45
+ _title_cache = BoundedDict(2000)
46
  _TITLE_CACHE_TTL = 300
47
 
48
+
49
+ #----- Recursively convert non-JSON-native containers to serializable forms
50
  def make_json_safe(obj):
51
  if isinstance(obj, deque):
52
  return list(obj)
 
61
  return obj
62
 
63
 
64
+ #----- Parse an HTTP Range header into (start, end) bounds
65
  def parse_range_header(range_header: str, file_size: int):
66
  if not range_header:
67
  return 0, file_size - 1
 
79
  start = int(start_str)
80
  end = int(end_str)
81
  except Exception:
82
+ raise HTTPException(status_code=416, detail="Invalid Range header", headers={"Content-Range": f"bytes */{file_size}"})
83
  if start < 0:
84
  start = 0
85
  if end >= file_size:
86
  end = file_size - 1
87
  if end < start:
88
+ raise HTTPException(status_code=416, detail="Requested Range Not Satisfiable", headers={"Content-Range": f"bytes */{file_size}"})
89
  return start, end
90
 
91
 
92
+ def _clients() -> dict:
93
+ return _pool.get() or multi_clients
94
+
95
+
96
+ #----- Pick the least-loaded client, preferring the target DC, round-robin on ties
97
  def select_best_client(target_dc: int) -> int:
98
  global _rr_counter
99
+ clients = _clients()
100
+
101
  def _score(idx: int) -> int:
102
  return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
103
+
104
  if target_dc > 0:
105
+ matching = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in clients]
 
 
 
106
  else:
107
  matching = []
108
  if not matching:
109
+ matching = list(clients.keys())
110
  if not matching:
111
  return 0
112
  min_score = min(_score(i) for i in matching)
113
  tied = sorted(i for i in matching if _score(i) == min_score)
114
  selected = tied[_rr_counter % len(tied)]
115
+ _rr_counter = (_rr_counter + 1) % max(len(clients), 1)
116
  return selected
117
 
118
 
119
+ #----- Periodically decay recorded client failure counters
120
  async def decay_client_failures() -> None:
121
  while True:
122
  await asyncio.sleep(300)
 
124
  if client_failures.get(k, 0) > 0:
125
  client_failures[k] = max(0, client_failures[k] - 1)
126
 
127
+
128
+ #----- Parallelism/prefetch factor scaled by the number of clients
129
  def get_parallel_prefetch(client_count: int) -> tuple[int, int]:
130
+ value = min(max(math.ceil(client_count / 5), 1), 5)
131
  return value, value
132
 
133
+
134
+ #----- Reuse (or lazily create) the cached ByteStreamer for a client index
135
+ def _get_streamer(tg_client, index: int) -> ByteStreamer:
136
+ if tg_client not in _streamer_by_client:
137
+ _streamer_by_client[tg_client] = ByteStreamer(tg_client, index)
138
+ return _streamer_by_client[tg_client]
139
+
140
+
141
+ def warm_streamers() -> None:
142
+ for index, client in list(multi_clients.items()):
143
+ _get_streamer(client, index)
144
+
145
+
146
+ def _prefetch_for(index: int) -> tuple[int, int]:
147
+ return (1, 1) if index == USERBOT_CLIENT_INDEX else get_parallel_prefetch(len(_clients()) - 1)
148
+
149
+
150
+ #----- Run fetch(streamer) on the Userbot when it is the default streamer, else (or on failure) on the bot pool
151
+ async def _db_client(fetch):
152
+ if not _pool.get() and SettingsManager.current().default_streaming == "userbot" and (ub := _get_userbot_streamer()):
153
+ try:
154
+ return USERBOT_CLIENT_INDEX, ub, await fetch(ub)
155
+ except Exception as e:
156
+ LOGGER.warning(f"[USERBOT] Falling back to bots: {e}")
157
+ index = select_best_client(0)
158
+ streamer = _get_streamer(_clients()[index], index)
159
+ return index, streamer, await fetch(streamer)
160
+
161
+
162
+ #----- Resolve a stream title from the TTL cache, DB, or the decoded URL name
163
+ async def _lookup_title(stream_id_hash: str, decoded_name: str):
164
+ if not stream_id_hash:
165
+ return decoded_name
166
+ now = time.time()
167
+ cached = _title_cache.get(stream_id_hash)
168
+ if cached and now < cached[1]:
169
+ return cached[0] or decoded_name
170
+ db_title = await db.get_title_by_stream_id(stream_id_hash)
171
+ _title_cache[stream_id_hash] = (db_title, now + _TITLE_CACHE_TTL)
172
+ return db_title or decoded_name
173
+
174
+
175
+ #----- Derive a display file name and mime type from file properties
176
+ def _resolve_filename_mime(file_id):
177
+ file_name = file_id.file_name or f"{secrets.token_hex(4)}.bin"
178
+ mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
179
+ if "." not in file_name and "/" in mime_type:
180
+ file_name = f"{file_name}.{mime_type.split('/')[1]}"
181
+ return file_name, mime_type
182
+
183
+
184
+ def _content_disposition(file_name, disposition="inline"):
185
+ ascii_fallback = file_name.encode("ascii", "ignore").decode("ascii").replace('"', "").strip() or "file"
186
+ return f"{disposition}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(file_name, safe='')}"
187
+
188
+
189
+ #----- Build the shared streaming response headers and status code
190
+ def _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size):
191
+ headers = {
192
+ "Content-Type": mime_type,
193
+ "Content-Disposition": _content_disposition(file_name),
194
+ "Accept-Ranges": "bytes",
195
+ "Content-Length": str(req_length),
196
+ "Cache-Control": "public, max-age=3600",
197
+ "Access-Control-Allow-Origin": "*",
198
+ "Access-Control-Expose-Headers": "Content-Length, Content-Range, Accept-Ranges",
199
+ }
200
+ status = 200
201
+ if range_header:
202
+ headers["Content-Range"] = f"bytes {start}-{end}/{file_size}"
203
+ status = 206
204
+ return headers, status
205
+
206
+
207
+ _thumb_cache = BoundedDict(200)
208
+ _THUMB_CACHE_TTL = 3600
209
+
210
+
211
+ #----- Serve a Telegram video/document thumbnail (public, used as artwork)
212
+ @router.get("/thumb/{id}")
213
+ async def thumb_handler(id: str):
214
+ now = time.time()
215
+ cached = _thumb_cache.get(id)
216
+ if cached and now < cached[1]:
217
+ data = cached[0]
218
+ else:
219
+ try:
220
+ decoded = await decode_string(id)
221
+ chat_id = int(f"-100{decoded['chat_id']}")
222
+ msg_id = int(decoded["msg_id"])
223
+ except Exception:
224
+ raise HTTPException(status_code=400, detail="Invalid thumbnail id")
225
+ if not multi_clients:
226
+ raise HTTPException(status_code=503, detail="No client available")
227
+ client = multi_clients[select_best_client(0)]
228
+ try:
229
+ message = await client.get_messages(chat_id, msg_id)
230
+ target = get_thumb_download_target(message)
231
+ if not target:
232
+ raise HTTPException(status_code=404, detail="No thumbnail")
233
+ file_id = getattr(target, "file_id", None) or target
234
+ buf = await client.download_media(file_id, in_memory=True)
235
+ data = buf.getvalue()
236
+ except HTTPException:
237
+ raise
238
+ except Exception as e:
239
+ LOGGER.warning(f"[THUMB] fetch failed for {id}: {e}")
240
+ raise HTTPException(status_code=404, detail="Thumbnail unavailable")
241
+ _thumb_cache[id] = (data, now + _THUMB_CACHE_TTL)
242
+
243
+ return PlainResponse(
244
+ content=data,
245
+ media_type="image/jpeg",
246
+ headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"},
247
+ )
248
+
249
+
250
+ _SUBTITLE_MIME = {
251
+ ".srt": "application/x-subrip",
252
+ ".vtt": "text/vtt",
253
+ ".ass": "text/x-ssa",
254
+ ".ssa": "text/x-ssa",
255
+ ".sub": "text/plain",
256
+ }
257
+
258
+
259
+ #----- Serve a subtitle file fully in-memory (files are small)
260
+ @router.get("/sub/{token}/{id}/{name}")
261
+ async def subtitle_handler(token: str, id: str, name: str, token_data: dict = Depends(verify_token)):
262
+ try:
263
+ decoded = await decode_string(id)
264
+ chat_id = int(f"-100{decoded['chat_id']}")
265
+ msg_id = int(decoded["msg_id"])
266
+ except Exception:
267
+ raise HTTPException(status_code=400, detail="Invalid subtitle id")
268
+
269
+ if not multi_clients:
270
+ raise HTTPException(status_code=503, detail="No client available")
271
+
272
+ client = multi_clients[select_best_client(0)]
273
+ try:
274
+ message = await client.get_messages(chat_id, msg_id)
275
+ buf = await client.download_media(message, in_memory=True)
276
+ data = buf.getvalue()
277
+ except Exception as e:
278
+ LOGGER.warning(f"[SUBTITLE] fetch failed for {id}: {e}")
279
+ raise HTTPException(status_code=404, detail="Subtitle unavailable")
280
+
281
+ ext = "." + name.rsplit(".", 1)[-1].lower() if "." in name else ".srt"
282
+ return PlainResponse(
283
+ content=data,
284
+ media_type=_SUBTITLE_MIME.get(ext, "application/octet-stream"),
285
+ headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"},
286
+ )
287
+
288
+
289
+ #----- Entry point: decode the id and dispatch to the matching streamer
290
  @router.get("/dl/{token}/{id}/{name}")
291
  @router.head("/dl/{token}/{id}/{name}")
292
+ async def stream_handler(request: Request, token: str, id: str, name: str, token_data: dict = Depends(verify_token)):
293
  decoded = await decode_string(id)
294
 
295
+ if not decoded.get("global") and own_bots.active(token_data):
296
+ try:
297
+ moved = await own_bots.remap(token_data, decoded)
298
+ cf = own_bots.worker(token_data)
299
+ if cf and request.query_params.get("via") == "cf":
300
+ return RedirectResponse(cf_stream_url(token, await encode_string(moved), quote(name), cf["url"], cf["secret"]), status_code=302)
301
+ pool = await own_bots.pool_for(token_data)
302
+ if pool:
303
+ decoded = moved
304
+ _pool.set(pool)
305
+ except Exception as e:
306
+ LOGGER.warning(f"[OWN BOTS] Falling back to owner bots: {e}")
307
+
308
+ if request.method != "HEAD":
309
+ asyncio.create_task(record_stream_start(
310
+ token,
311
+ token_data.get("name") if token_data else None,
312
+ client_ip_from(request),
313
+ request.headers.get("user-agent", ""),
314
+ ))
315
+
316
  if decoded.get("global"):
317
+ if decoded.get("zip"):
318
+ return await global_zip_media_streamer(
319
+ request=request, parts_payload=decoded["parts"],
320
+ token=token, token_data=token_data, stream_id_hash=id,
321
+ )
322
+ if "parts" in decoded:
323
+ return await global_virtual_media_streamer(
324
+ request=request, parts_payload=decoded["parts"],
325
+ token=token, token_data=token_data, stream_id_hash=id,
326
+ )
327
  return await global_media_streamer(
328
  request=request, chat_id=int(decoded["chat_id"]), msg_id=int(decoded["msg_id"]),
329
  token=token, token_data=token_data, stream_id_hash=id,
330
  )
331
 
332
  if "parts" in decoded:
333
+ if decoded.get("zip"):
334
+ return await db_zip_media_streamer(
335
+ request=request, parts_payload=decoded["parts"],
336
+ token=token, token_data=token_data, stream_id_hash=id,
337
+ )
338
  return await virtual_media_streamer(
339
  request=request, parts_payload=decoded["parts"],
340
  token=token, token_data=token_data, stream_id_hash=id,
 
344
  if not msg_id:
345
  raise HTTPException(status_code=400, detail="Missing id")
346
  chat_id = int(f"-100{decoded['chat_id']}")
347
+ return await media_streamer(
348
+ request=request, chat_id=chat_id, msg_id=int(msg_id),
349
  token=token, token_data=token_data, stream_id_hash=id,
350
  )
351
 
352
+
353
+ #----- Stream a single Telegram file, with optional multi-client parallelism
354
+ async def media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None):
355
+ index, streamer, file_id = await _db_client(lambda s: s.get_file_properties(chat_id=chat_id, message_id=msg_id))
 
 
 
 
356
  file_size = file_id.file_size
357
  range_header = request.headers.get("Range", "")
358
  start, end = parse_range_header(range_header, file_size)
 
364
  part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
365
  stream_id = secrets.token_hex(8)
366
  decoded_name = unquote(request.path_params.get("name", ""))
367
+ final_title = await _lookup_title(stream_id_hash, decoded_name)
368
+ file_name, mime_type = _resolve_filename_mime(file_id)
 
 
 
 
 
 
 
 
369
  meta = {
370
  "request_path": str(request.url.path),
371
  "client_host": request.client.host if request.client else None,
372
+ "title": final_title or file_name,
373
+ "file_name": file_name,
374
+ "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
375
+ "token": token,
376
  }
377
 
378
+ parallelism, prefetch_count = _prefetch_for(index)
 
379
  extra_clients_for_stream = []
380
+ clients = _clients()
381
+ if parallelism > 1 and len(clients) > 1:
382
+ other_indices = sorted((i for i in clients if i != index), key=lambda i: work_loads.get(i, 0))
383
+
 
384
  async def _get_extra_file_id(ec_idx: int):
385
+ ec_client = clients[ec_idx]
386
+ ec_streamer = _get_streamer(ec_client, ec_idx)
 
 
387
  try:
388
  ec_fid = await ec_streamer.get_file_properties(chat_id=chat_id, message_id=msg_id)
389
  return (ec_idx, ec_streamer, ec_fid)
390
  except Exception as e:
391
  LOGGER.warning("Extra client %s file_id fetch failed: %s", ec_idx, e)
392
  return None
393
+
394
+ results = await asyncio.gather(*[_get_extra_file_id(i) for i in other_indices[:parallelism - 1]])
 
395
  extra_clients_for_stream = [r for r in results if r is not None]
396
 
397
  body_gen = await streamer.prefetch_stream(
 
414
 
415
  asyncio.create_task(track_usage(stream_id, token, token_data))
416
 
417
+ headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)
 
418
 
 
 
 
419
  if request.method == "HEAD":
420
+ return PlainResponse(status_code=status, headers=headers)
421
+ return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
 
423
 
424
+ #----- Stream media reconstructed from multiple split parts
425
+ async def virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
426
+ index, streamer, (parts, file_size) = await _db_client(lambda s: resolve_virtual_parts(parts_payload, s))
 
 
 
 
 
427
  if not parts or file_size <= 0:
428
  raise HTTPException(status_code=404, detail="Split media parts not found")
429
 
 
433
  chunk_size = 1024 * 1024
434
  stream_id = secrets.token_hex(8)
435
  decoded_name = unquote(request.path_params.get("name", ""))
436
+ final_title = await _lookup_title(stream_id_hash, decoded_name)
437
+ file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"])
 
 
 
 
 
 
 
 
 
438
 
439
  meta = {
440
  "request_path": str(request.url.path),
441
  "client_host": request.client.host if request.client else None,
442
+ "title": final_title or file_name,
443
+ "file_name": file_name,
444
  "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
445
+ "token": token,
446
  "split_parts": len(parts),
447
  }
448
 
449
+ parallelism, prefetch_count = _prefetch_for(index)
 
450
 
451
  asyncio.create_task(track_usage(stream_id, token, token_data))
452
 
453
+ common_headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
  if request.method == "HEAD":
456
  return PlainResponse(status_code=status, headers=common_headers)
 
460
  streamer=streamer, client_index=index, request=request, meta=meta,
461
  stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
462
  )
463
+ return StreamingResponse(body_gen, headers=common_headers, status_code=status, media_type=mime_type)
 
464
 
465
 
466
  _userbot_streamer: ByteStreamer = None
467
 
468
 
469
+ #----- Lazily build and cache the ByteStreamer for the Userbot (None if unconfigured)
470
  def _get_userbot_streamer() -> ByteStreamer:
 
 
471
  global _userbot_streamer
472
+ if botmod.Userbot is None:
473
  return None
474
+ if _userbot_streamer is None or _userbot_streamer.client is not botmod.Userbot:
475
+ _userbot_streamer = ByteStreamer(botmod.Userbot, USERBOT_CLIENT_INDEX)
476
  return _userbot_streamer
477
 
478
 
479
+ #----- Stream a Global Search file through the Userbot session directly
480
+ async def global_media_streamer(request: Request, chat_id: int, msg_id: int, token: str, token_data: dict = None, stream_id_hash: str = None):
 
 
 
481
  streamer = _get_userbot_streamer()
482
  if streamer is None:
483
  raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot configured)")
 
500
  part_count = math.ceil(end / chunk_size) - math.floor(offset / chunk_size)
501
  stream_id = secrets.token_hex(8)
502
 
503
+ file_name, mime_type = _resolve_filename_mime(file_id)
504
  meta = {
505
  "request_path": str(request.url.path),
506
  "client_host": request.client.host if request.client else None,
507
+ "title": file_name or "global-stream",
508
+ "file_name": file_name,
509
  "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
510
+ "token": token,
511
  "global_search": True,
512
  }
513
 
514
  asyncio.create_task(track_usage(stream_id, token, token_data))
515
 
516
+ headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
  if request.method == "HEAD":
519
  return PlainResponse(status_code=status, headers=headers)
 
534
  chat_id=chat_id,
535
  message_id=msg_id,
536
  )
537
+ return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)
538
 
 
539
 
540
+ #----- Stream a split Global Search file (multiple parts) through the Userbot session
541
+ async def global_virtual_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
542
+ streamer = _get_userbot_streamer()
543
+ if streamer is None:
544
+ raise HTTPException(status_code=503, detail="Global Search streaming is unavailable (no Userbot connected)")
545
+
546
+ parts, file_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=False)
547
+ if not parts or file_size <= 0:
548
+ raise HTTPException(status_code=404, detail="Split media parts not accessible via Global Search")
549
+
550
+ range_header = request.headers.get("Range", "")
551
+ start, end = parse_range_header(range_header, file_size)
552
+ req_length = end - start + 1
553
+ chunk_size = 1024 * 1024
554
+ stream_id = secrets.token_hex(8)
555
+ decoded_name = unquote(request.path_params.get("name", ""))
556
+ final_title = await _lookup_title(stream_id_hash, decoded_name)
557
+ file_name, mime_type = _resolve_filename_mime(parts[0]["file_id"])
558
+
559
+ meta = {
560
+ "request_path": str(request.url.path),
561
+ "client_host": request.client.host if request.client else None,
562
+ "title": final_title or file_name,
563
+ "file_name": file_name,
564
+ "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
565
+ "token": token,
566
+ "global_search": True,
567
+ "split_parts": len(parts),
568
+ }
569
+
570
+ asyncio.create_task(track_usage(stream_id, token, token_data))
571
+
572
+ headers, status = _build_stream_headers(mime_type, file_name, req_length, range_header, start, end, file_size)
573
+
574
+ if request.method == "HEAD":
575
+ return PlainResponse(status_code=status, headers=headers)
576
+
577
+ body_gen = virtual_stream_generator(
578
+ parts=parts, start=start, end=end, chunk_size=chunk_size,
579
+ streamer=streamer, client_index=USERBOT_CLIENT_INDEX, request=request, meta=meta,
580
+ stream_id=stream_id, parallelism=1, prefetch_count=1,
581
+ )
582
+ return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)
583
+
584
+
585
+ #----- Read a byte range from the concatenated virtual parts into memory
586
+ async def _read_virtual_range(parts, start, length, streamer, request, client_index=USERBOT_CLIENT_INDEX, parallelism=1, prefetch_count=1):
587
+ buf = bytearray()
588
+ gen = virtual_stream_generator(
589
+ parts=parts, start=start, end=start + length - 1, chunk_size=1024 * 1024,
590
+ streamer=streamer, client_index=client_index, request=request,
591
+ meta={"title": "zip-index", "user_name": "system", "token": ""},
592
+ stream_id=secrets.token_hex(6), parallelism=parallelism, prefetch_count=prefetch_count,
593
+ )
594
+ try:
595
+ async for chunk in gen:
596
+ buf.extend(chunk)
597
+ if len(buf) >= length:
598
+ break
599
+ finally:
600
+ await gen.aclose()
601
+ return bytes(buf[:length])
602
+
603
+
604
+ #----- Stream a split ZIP archive (.zip.001/.002 ...) as its inner video, with seeking.
605
+ #----- Only STORED (uncompressed) archives are seekable; the inner file bytes are served
606
+ #----- directly at their offset inside the concatenated zip (no stream-unzip needed).
607
+ async def _zip_media_streamer(request, parts_payload, token, token_data, stream_id_hash, streamer, client_index, prefix_100, parallelism, prefetch_count):
608
+ if streamer is None:
609
+ raise HTTPException(status_code=503, detail="ZIP streaming is unavailable (no client/session)")
610
+
611
+ parts, zip_size = await resolve_virtual_parts(parts_payload, streamer, prefix_100=prefix_100)
612
+ if not parts or zip_size <= 0:
613
+ raise HTTPException(status_code=404, detail="Split archive parts not accessible")
614
+
615
+ async def _read(off, length):
616
+ return await _read_virtual_range(parts, off, length, streamer, request, client_index, parallelism, prefetch_count)
617
+
618
+ entry = await resolve_zip_entry(_read, zip_size)
619
+ if not entry:
620
+ raise HTTPException(status_code=415, detail="Unreadable or incomplete split archive")
621
+ if entry["method"] != 0:
622
+ raise HTTPException(
623
+ status_code=415,
624
+ detail="This archive is compressed; only stored (uncompressed) ZIP archives can be seek-streamed.",
625
+ )
626
+
627
+ inner_size = entry["size"]
628
+ data_offset = entry["data_offset"]
629
+ if inner_size <= 0 or data_offset + inner_size > zip_size:
630
+ raise HTTPException(status_code=415, detail="Split archive has an unexpected layout")
631
+
632
+ range_header = request.headers.get("Range", "")
633
+ start, end = parse_range_header(range_header, inner_size)
634
+ req_length = end - start + 1
635
+ stream_id = secrets.token_hex(8)
636
+ inner_name = (entry.get("name") or "").split("/")[-1] or unquote(request.path_params.get("name", "")) or "video.mkv"
637
+ mime_type = mimetypes.guess_type(inner_name)[0] or "video/x-matroska"
638
+
639
+ meta = {
640
+ "request_path": str(request.url.path),
641
+ "client_host": request.client.host if request.client else None,
642
+ "title": (await _lookup_title(stream_id_hash, inner_name)) or inner_name,
643
+ "file_name": inner_name,
644
+ "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
645
+ "token": token,
646
+ "zip_parts": len(parts),
647
+ }
648
+ asyncio.create_task(track_usage(stream_id, token, token_data))
649
+
650
+ headers, status = _build_stream_headers(mime_type, inner_name, req_length, range_header, start, end, inner_size)
651
+ if request.method == "HEAD":
652
+ return PlainResponse(status_code=status, headers=headers)
653
+
654
+ body_gen = virtual_stream_generator(
655
+ parts=parts, start=data_offset + start, end=data_offset + end, chunk_size=1024 * 1024,
656
+ streamer=streamer, client_index=client_index, request=request, meta=meta,
657
+ stream_id=stream_id, parallelism=parallelism, prefetch_count=prefetch_count,
658
+ )
659
+ return StreamingResponse(body_gen, headers=headers, status_code=status, media_type=mime_type)
660
+
661
+
662
+ #----- ZIP split from Global Search (streamed via the Userbot session)
663
+ async def global_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
664
+ return await _zip_media_streamer(
665
+ request, parts_payload, token, token_data, stream_id_hash,
666
+ _get_userbot_streamer(), USERBOT_CLIENT_INDEX, False, 1, 1,
667
+ )
668
+
669
+
670
+ #----- ZIP split from the indexed library (streamed via the multi-bot pool)
671
+ async def db_zip_media_streamer(request: Request, parts_payload: list, token: str, token_data: dict = None, stream_id_hash: str = None):
672
+ index, streamer, _ = await _db_client(lambda s: resolve_virtual_parts(parts_payload[:1], s))
673
+ parallelism, prefetch_count = _prefetch_for(index)
674
+ return await _zip_media_streamer(
675
+ request, parts_payload, token, token_data, stream_id_hash,
676
+ streamer, index, True, parallelism, prefetch_count,
677
+ )
678
+
679
+
680
+ #----- Live and recent stream telemetry, pruning stale active entries
681
  @router.get("/stream/stats")
682
  async def get_stream_stats():
683
  now = time.time()
 
697
  if now - info["last_activity_ts"] > INACTIVE_TIMEOUT:
698
  if status == "active":
699
  info["status"] = "cancelled"
700
+ info["end_ts"] = now
701
  if info.get("status") in ("cancelled", "error", "finished", "inactive"):
702
  last_ts = info.get("end_ts", info.get("last_activity_ts", now))
703
  if now - last_ts > PRUNE_SECONDS:
 
705
  RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(sid))
706
  except KeyError:
707
  pass
708
+
709
+ active = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
710
  {
711
+ "stream_id": sid,
712
+ "msg_id": info.get("msg_id"),
713
+ "chat_id": info.get("chat_id"),
714
+ "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"),
715
+ "file_name": info.get("meta", {}).get("file_name"),
716
+ "client_index": info.get("client_index"),
717
+ "dc_id": info.get("dc_id"),
718
+ "status": info.get("status"),
719
+ "total_bytes": info.get("total_bytes"),
720
+ "instant_mbps": round(info.get("instant_mbps", 0.0), 3),
721
+ "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
722
+ "peak_mbps": round(info.get("peak_mbps", 0.0), 3),
723
+ "start_ts": info.get("start_ts"),
724
  }
725
+ for sid, info in ACTIVE_STREAMS.items()
726
+ ]
727
+ recent = [
728
+ {
729
+ "stream_id": info.get("stream_id"),
730
+ "msg_id": info.get("msg_id"),
731
+ "chat_id": info.get("chat_id"),
732
+ "title": info.get("meta", {}).get("title") or info.get("meta", {}).get("file_name"),
733
+ "file_name": info.get("meta", {}).get("file_name"),
734
+ "client_index": info.get("client_index"),
735
+ "dc_id": info.get("dc_id"),
736
+ "status": info.get("status"),
737
+ "total_bytes": info.get("total_bytes"),
738
+ "duration": info.get("duration"),
739
+ "avg_mbps": round(info.get("avg_mbps", 0.0), 3),
740
+ "start_ts": info.get("start_ts"),
741
+ "end_ts": info.get("end_ts"),
742
+ }
743
+ for info in RECENT_STREAMS
744
+ ]
745
+ return JSONResponse({
746
+ "active_streams": active,
747
+ "recent_streams": recent,
748
+ "client_dc_map": client_dc_map,
749
+ "work_loads": work_loads,
750
+ })
751
+
752
 
753
+ #----- Detailed telemetry for a single stream id
754
  @router.get("/stream/stats/{stream_id}")
755
  async def get_stream_detail(stream_id: str):
756
  info = ACTIVE_STREAMS.get(stream_id)
Backend/fastapi/routes/stremio_routes.py CHANGED
The diff for this file is too large to render. See raw diff
 
Backend/fastapi/routes/template_routes.py CHANGED
@@ -1,90 +1,108 @@
1
- from fastapi import Request, Form, HTTPException, Depends
 
 
 
2
  from fastapi.responses import RedirectResponse
3
  from fastapi.templating import Jinja2Templates
4
- from Backend.fastapi.security.credentials import verify_credentials, require_auth, is_authenticated, get_current_user
5
- from Backend.fastapi.themes import get_theme, get_all_themes, DEFAULT_THEME
6
- from Backend import db
7
  from Backend.config import Telegram
8
- from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
 
 
 
 
 
9
  from Backend.helper.pyro import get_readable_time
10
  from Backend.helper.settings_manager import SettingsManager
11
- from Backend import StartTime, __version__
12
- import time
13
- from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
14
 
15
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
 
16
 
17
- async def admin_dashboard_page(request: Request, _: bool = Depends(require_auth)):
18
- theme_name = request.session.get("theme", DEFAULT_THEME)
19
- theme = get_theme(theme_name)
20
- current_user = get_current_user(request)
21
-
22
- return templates.TemplateResponse("admin_dashboard.html", {
23
  "request": request,
24
- "theme": theme,
25
  "themes": get_all_themes(),
26
  "current_theme": theme_name,
27
- "current_user": current_user
28
- })
29
 
 
 
 
 
 
 
 
 
30
  async def login_page(request: Request):
31
  if is_authenticated(request):
32
  return RedirectResponse(url="/", status_code=302)
33
-
34
- theme_name = request.session.get("theme", DEFAULT_THEME)
35
- theme = get_theme(theme_name)
36
-
37
- return templates.TemplateResponse("login.html", {
38
- "request": request,
39
- "theme": theme,
40
- "themes": get_all_themes(),
41
- "current_theme": theme_name
42
- })
43
 
44
  async def login_post(request: Request, username: str = Form(...), password: str = Form(...)):
 
 
 
 
 
 
 
45
  if verify_credentials(username, password):
 
46
  request.session["authenticated"] = True
47
  request.session["username"] = username
 
48
  return RedirectResponse(url="/", status_code=302)
49
- else:
50
- theme_name = request.session.get("theme", DEFAULT_THEME)
51
- theme = get_theme(theme_name)
52
- return templates.TemplateResponse("login.html", {
53
- "request": request,
54
- "theme": theme,
55
- "themes": get_all_themes(),
56
- "current_theme": theme_name,
57
- "error": "Invalid credentials"
58
- })
59
 
 
 
60
  async def logout(request: Request):
61
- request.session.clear()
62
  return RedirectResponse(url="/login", status_code=302)
63
 
64
- async def set_theme(request: Request, theme: str = Form(...)):
65
- if theme in get_all_themes():
66
- request.session["theme"] = theme
67
- return RedirectResponse(url=request.headers.get("referer", "/"), status_code=302)
68
 
 
 
 
 
 
 
 
 
 
69
  async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
70
- theme_name = request.session.get("theme", DEFAULT_THEME)
71
- theme = get_theme(theme_name)
72
- current_user = get_current_user(request)
73
-
74
  try:
75
  db_stats = await db.get_database_stats()
76
- total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
77
- total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
78
 
79
  now = time.time()
80
  PRUNE_SECONDS = 3
81
  for sid, info in list(ACTIVE_STREAMS.items()):
82
  status = info.get("status")
83
- # Check end_ts first to see when it organically finished
84
  last_ts = info.get("end_ts") or info.get("last_ts") or info.get("start_ts", now)
85
-
86
  if status in ("cancelled", "error", "finished") and (now - last_ts > PRUNE_SECONDS):
87
-
88
  info["duration"] = round(now - info.get("start_ts", now), 1)
89
  info["stream_id"] = sid
90
  try:
@@ -93,9 +111,8 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
93
  except KeyError:
94
  pass
95
 
96
- active_streams_data = []
97
- for stream_id, info in ACTIVE_STREAMS.items():
98
- active_streams_data.append({
99
  "stream_id": stream_id,
100
  "msg_id": info.get("msg_id"),
101
  "chat_id": info.get("chat_id"),
@@ -108,17 +125,16 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
108
  "dc_id": info.get("dc_id", 0),
109
  "duration": round(now - info.get("start_ts", now), 1),
110
  "meta": info.get("meta", {})
111
- })
 
 
112
 
113
  system_stats = {
114
  "server_status": "running",
115
  "uptime": get_readable_time(now - StartTime),
116
  "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
117
  "connected_bots": len(multi_clients),
118
- "loads": {
119
- f"bot{c+1}": l
120
- for c, (_, l) in enumerate(sorted(work_loads.items(), key=lambda x: x[1], reverse=True))
121
- } if work_loads else {},
122
  "version": __version__,
123
  "movies": total_movies,
124
  "tv_shows": total_tv_shows,
@@ -148,37 +164,25 @@ async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
148
  "total_active_streams": 0
149
  }
150
 
151
- api_tokens = await db.get_all_api_tokens()
152
- return templates.TemplateResponse("dashboard.html", {
153
- "request": request,
154
- "theme": theme,
155
- "themes": get_all_themes(),
156
- "current_theme": theme_name,
157
- "current_user": current_user,
158
- "system_stats": system_stats,
159
- "api_tokens": api_tokens
160
- })
161
 
162
 
163
- async def media_management_page(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
164
- theme_name = request.session.get("theme", DEFAULT_THEME)
165
- theme = get_theme(theme_name)
166
- current_user = get_current_user(request)
167
-
168
- return templates.TemplateResponse("media_management.html", {
169
- "request": request,
170
- "theme": theme,
171
- "themes": get_all_themes(),
172
- "current_theme": theme_name,
173
- "current_user": current_user,
174
- "media_type": media_type
175
- })
176
 
 
177
  async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
178
- theme_name = request.session.get("theme", DEFAULT_THEME)
179
- theme = get_theme(theme_name)
180
- current_user = get_current_user(request)
181
-
182
  try:
183
  media_details = await db.get_document(media_type, tmdb_id, db_index)
184
  if not media_details:
@@ -187,150 +191,82 @@ async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_t
187
  raise HTTPException(status_code=500, detail=str(e))
188
 
189
  api_tokens = await db.get_all_api_tokens()
190
- api_token = api_tokens[0].get("token") if api_tokens else None
191
-
192
- return templates.TemplateResponse("media_edit.html", {
193
- "request": request,
194
- "theme": theme,
195
- "themes": get_all_themes(),
196
- "current_theme": theme_name,
197
- "current_user": current_user,
198
  "tmdb_id": tmdb_id,
199
  "db_index": db_index,
200
  "media_type": media_type,
201
  "media_details": media_details,
202
- "api_token": api_token
203
- })
204
-
205
- async def public_status_page(request: Request):
206
- theme_name = request.session.get("theme", DEFAULT_THEME)
207
- theme = get_theme(theme_name)
208
-
209
- try:
210
- db_stats = await db.get_database_stats()
211
- total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
212
- total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
213
-
214
- public_stats = {
215
- "status": "operational",
216
- "uptime": "99.9%",
217
- "total_content": total_movies + total_tv_shows,
218
- "databases_online": len(db_stats)
219
- }
220
- except Exception:
221
- public_stats = {
222
- "status": "maintenance",
223
- "uptime": "N/A",
224
- "total_content": 0,
225
- "databases_online": 0
226
- }
227
-
228
- return templates.TemplateResponse("public_status.html", {
229
- "request": request,
230
- "theme": theme,
231
- "themes": get_all_themes(),
232
- "current_theme": theme_name,
233
- "stats": public_stats,
234
- "is_authenticated": is_authenticated(request)
235
  })
 
236
 
237
- async def stremio_guide_page(request: Request):
238
- theme_name = request.session.get("theme", DEFAULT_THEME)
239
- theme = get_theme(theme_name)
240
-
241
- return templates.TemplateResponse("stremio_guide.html", {
242
- "request": request,
243
- "theme": theme,
244
- "themes": get_all_themes(),
245
- "current_theme": theme_name,
246
- "is_authenticated": is_authenticated(request)
247
- })
248
 
 
249
  async def admin_subscriptions_page(request: Request, _: bool = Depends(require_auth)):
250
- theme_name = request.session.get("theme", DEFAULT_THEME)
251
- theme = get_theme(theme_name)
252
- current_user = get_current_user(request)
253
-
254
- return templates.TemplateResponse("subscriptions_manage.html", {
255
- "request": request,
256
- "theme": theme,
257
- "themes": get_all_themes(),
258
- "current_theme": theme_name,
259
- "current_user": current_user
260
- })
261
 
262
 
 
263
  async def admin_access_page(request: Request, _: bool = Depends(require_auth)):
264
- theme_name = request.session.get("theme", DEFAULT_THEME)
265
- theme = get_theme(theme_name)
266
- current_user = get_current_user(request)
267
 
268
- return templates.TemplateResponse("access_manage.html", {
269
- "request": request,
270
- "theme": theme,
271
- "themes": get_all_themes(),
272
- "current_theme": theme_name,
273
- "current_user": current_user,
274
- })
275
 
 
 
 
 
 
276
 
277
 
278
- async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)):
279
- theme_name = request.session.get("theme", DEFAULT_THEME)
280
- theme = get_theme(theme_name)
281
- current_user = get_current_user(request)
 
282
 
283
- return templates.TemplateResponse("custom_catalogs.html", {
284
- "request": request,
285
- "theme": theme,
286
- "themes": get_all_themes(),
287
- "current_theme": theme_name,
288
- "current_user": current_user,
289
- })
290
 
 
 
 
 
 
291
 
292
 
 
293
  async def tools_page(request: Request, _: bool = Depends(require_auth)):
294
- theme_name = request.session.get("theme", DEFAULT_THEME)
295
- theme = get_theme(theme_name)
296
- current_user = get_current_user(request)
297
-
298
- return templates.TemplateResponse(
299
- "tools.html",
300
- {
301
- "request": request,
302
- "theme": theme,
303
- "themes": get_all_themes(),
304
- "current_theme": theme_name,
305
- "current_user": current_user,
306
- },
307
- )
308
 
309
 
 
310
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
311
- theme_name = request.session.get("theme", DEFAULT_THEME)
312
- theme = get_theme(theme_name)
313
- current_user = get_current_user(request)
314
-
315
  settings = SettingsManager.current().to_dict()
316
  settings["admin_password"] = ""
317
-
318
  try:
319
  settings["database_list"] = db.get_database_list()
320
  except Exception:
321
  settings["database_list"] = []
322
 
323
- userbot_configured = bool(Telegram.USER_SESSION_STRING and Telegram.USER_SESSION_STRING.strip())
324
-
325
- return templates.TemplateResponse(
326
- "settings.html",
327
- {
328
- "request": request,
329
- "theme": theme,
330
- "themes": get_all_themes(),
331
- "current_theme": theme_name,
332
- "current_user": current_user,
333
- "settings": settings,
334
- "userbot_configured": userbot_configured,
335
- },
336
- )
 
1
+ import secrets
2
+ import time
3
+
4
+ from fastapi import Depends, Form, HTTPException, Request
5
  from fastapi.responses import RedirectResponse
6
  from fastapi.templating import Jinja2Templates
7
+
8
+ from Backend import StartTime, __version__, db
 
9
  from Backend.config import Telegram
10
+ from Backend.fastapi.security.credentials import get_current_user, is_authenticated, require_auth, revoke_session, verify_credentials
11
+ from Backend.fastapi.themes import get_all_themes, get_theme, theme_key
12
+ from Backend.helper.analytics import client_ip_from, get_activity_overview
13
+ from Backend.helper.bounded import BoundedDict
14
+ from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
15
+ from Backend.helper.metadata import resolve_cover_url
16
  from Backend.helper.pyro import get_readable_time
17
  from Backend.helper.settings_manager import SettingsManager
18
+ from Backend.helper.stream_formatter import PRESETS
19
+ import Backend.pyrofork.bot as botmod
20
+ from Backend.pyrofork.bot import StreamBot, multi_clients, work_loads_summary
21
 
22
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
23
+ templates.env.globals["cover_url"] = resolve_cover_url
24
 
25
+
26
+ #----- Shared template context (request, theme metadata) for every page
27
+ def _base_context(request: Request) -> dict:
28
+ theme_name = theme_key(request)
29
+ return {
 
30
  "request": request,
31
+ "theme": get_theme(theme_name),
32
  "themes": get_all_themes(),
33
  "current_theme": theme_name,
34
+ }
35
+
36
 
37
+ #----- Admin dashboard shell
38
+ async def admin_dashboard_page(request: Request, _: bool = Depends(require_auth)):
39
+ ctx = _base_context(request)
40
+ ctx["current_user"] = get_current_user(request)
41
+ return templates.TemplateResponse("admin_dashboard.html", ctx)
42
+
43
+
44
+ #----- Login form (redirects to home when already authenticated)
45
  async def login_page(request: Request):
46
  if is_authenticated(request):
47
  return RedirectResponse(url="/", status_code=302)
48
+ return templates.TemplateResponse("login.html", _base_context(request))
49
+
50
+
51
+ #----- Handle login submission
52
+ _FAILED_LOGINS = BoundedDict(1000)
53
+ _LOGIN_MAX_FAILS = 5
54
+ _LOGIN_WINDOW = 15 * 60
55
+
 
 
56
 
57
  async def login_post(request: Request, username: str = Form(...), password: str = Form(...)):
58
+ ip = client_ip_from(request)
59
+ now = time.time()
60
+ fails = [t for t in _FAILED_LOGINS.get(ip, []) if now - t < _LOGIN_WINDOW]
61
+ if len(fails) >= _LOGIN_MAX_FAILS:
62
+ ctx = _base_context(request)
63
+ ctx["error"] = "Too many failed attempts. Try again in 15 minutes."
64
+ return templates.TemplateResponse("login.html", ctx, status_code=429)
65
  if verify_credentials(username, password):
66
+ _FAILED_LOGINS.pop(ip, None)
67
  request.session["authenticated"] = True
68
  request.session["username"] = username
69
+ request.session["sid"] = secrets.token_urlsafe(16)
70
  return RedirectResponse(url="/", status_code=302)
71
+ _FAILED_LOGINS[ip] = fails + [now]
72
+ ctx = _base_context(request)
73
+ ctx["error"] = "Invalid credentials"
74
+ return templates.TemplateResponse("login.html", ctx)
 
 
 
 
 
 
75
 
76
+
77
+ #----- Clear the session and return to login
78
  async def logout(request: Request):
79
+ revoke_session(request)
80
  return RedirectResponse(url="/login", status_code=302)
81
 
 
 
 
 
82
 
83
+ #----- Persist the chosen theme and return to the referring page
84
+ async def set_theme(request: Request, theme: str = Form(None)):
85
+ response = RedirectResponse(url=request.headers.get("referer", "/"), status_code=302)
86
+ if theme and theme in get_all_themes():
87
+ response.set_cookie("theme", theme, max_age=31536000, samesite="lax")
88
+ return response
89
+
90
+
91
+ #----- Main dashboard: aggregate DB stats and live/recent stream telemetry
92
  async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
93
+ ctx = _base_context(request)
94
+ ctx["current_user"] = get_current_user(request)
95
+
 
96
  try:
97
  db_stats = await db.get_database_stats()
98
+ total_movies, total_tv_shows = db.content_totals(db_stats)
 
99
 
100
  now = time.time()
101
  PRUNE_SECONDS = 3
102
  for sid, info in list(ACTIVE_STREAMS.items()):
103
  status = info.get("status")
 
104
  last_ts = info.get("end_ts") or info.get("last_ts") or info.get("start_ts", now)
 
105
  if status in ("cancelled", "error", "finished") and (now - last_ts > PRUNE_SECONDS):
 
106
  info["duration"] = round(now - info.get("start_ts", now), 1)
107
  info["stream_id"] = sid
108
  try:
 
111
  except KeyError:
112
  pass
113
 
114
+ active_streams_data = [
115
+ {
 
116
  "stream_id": stream_id,
117
  "msg_id": info.get("msg_id"),
118
  "chat_id": info.get("chat_id"),
 
125
  "dc_id": info.get("dc_id", 0),
126
  "duration": round(now - info.get("start_ts", now), 1),
127
  "meta": info.get("meta", {})
128
+ }
129
+ for stream_id, info in ACTIVE_STREAMS.items()
130
+ ]
131
 
132
  system_stats = {
133
  "server_status": "running",
134
  "uptime": get_readable_time(now - StartTime),
135
  "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
136
  "connected_bots": len(multi_clients),
137
+ "loads": work_loads_summary(),
 
 
 
138
  "version": __version__,
139
  "movies": total_movies,
140
  "tv_shows": total_tv_shows,
 
164
  "total_active_streams": 0
165
  }
166
 
167
+ ctx["system_stats"] = system_stats
168
+ try:
169
+ ctx["user_activity_initial"] = await get_activity_overview(1, 5)
170
+ except Exception:
171
+ ctx["user_activity_initial"] = {"users": [], "online_count": 0, "total": 0, "page": 1, "per_page": 5, "total_pages": 1}
172
+ return templates.TemplateResponse("dashboard.html", ctx)
 
 
 
 
173
 
174
 
175
+ #----- Media management shell (movie/tv)
176
+ async def media_management_page(request: Request, media_type: str = "movie", custom: bool = False, _: bool = Depends(require_auth)):
177
+ ctx = _base_context(request)
178
+ ctx["current_user"] = get_current_user(request)
179
+ ctx["media_type"] = media_type
180
+ ctx["custom"] = custom
181
+ return templates.TemplateResponse("media_management.html", ctx)
182
+
 
 
 
 
 
183
 
184
+ #----- Media edit page for a single title
185
  async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
 
 
 
 
186
  try:
187
  media_details = await db.get_document(media_type, tmdb_id, db_index)
188
  if not media_details:
 
191
  raise HTTPException(status_code=500, detail=str(e))
192
 
193
  api_tokens = await db.get_all_api_tokens()
194
+ ctx = _base_context(request)
195
+ ctx.update({
196
+ "current_user": get_current_user(request),
 
 
 
 
 
197
  "tmdb_id": tmdb_id,
198
  "db_index": db_index,
199
  "media_type": media_type,
200
  "media_details": media_details,
201
+ "api_token": api_tokens[0].get("token") if api_tokens else None,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  })
203
+ return templates.TemplateResponse("media_edit.html", ctx)
204
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
+ #----- Subscription management shell
207
  async def admin_subscriptions_page(request: Request, _: bool = Depends(require_auth)):
208
+ ctx = _base_context(request)
209
+ ctx["current_user"] = get_current_user(request)
210
+ return templates.TemplateResponse("subscriptions_manage.html", ctx)
 
 
 
 
 
 
 
 
211
 
212
 
213
+ #----- Access management shell
214
  async def admin_access_page(request: Request, _: bool = Depends(require_auth)):
215
+ ctx = _base_context(request)
216
+ ctx["current_user"] = get_current_user(request)
217
+ return templates.TemplateResponse("access_manage.html", ctx)
218
 
 
 
 
 
 
 
 
219
 
220
+ #----- Content requests shell (admin)
221
+ async def admin_requests_page(request: Request, _: bool = Depends(require_auth)):
222
+ ctx = _base_context(request)
223
+ ctx["current_user"] = get_current_user(request)
224
+ return templates.TemplateResponse("requests_manage.html", ctx)
225
 
226
 
227
+ #----- Public request page (no auth)
228
+ async def public_request_page(request: Request):
229
+ ctx = _base_context(request)
230
+ ctx["is_authenticated"] = is_authenticated(request)
231
+ return templates.TemplateResponse("request_public.html", ctx)
232
 
 
 
 
 
 
 
 
233
 
234
+ #----- Custom catalogs shell
235
+ async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)):
236
+ ctx = _base_context(request)
237
+ ctx["current_user"] = get_current_user(request)
238
+ return templates.TemplateResponse("custom_catalogs.html", ctx)
239
 
240
 
241
+ #----- Tools shell (WebUI replacement for scan/rescan/dbcheck commands)
242
  async def tools_page(request: Request, _: bool = Depends(require_auth)):
243
+ ctx = _base_context(request)
244
+ ctx["current_user"] = get_current_user(request)
245
+ #----- Bot Admin Manager needs a session string AND more than one bot token
246
+ ctx["userbot_configured"] = botmod.Userbot is not None
247
+ ctx["multi_token_available"] = len(multi_clients) > 1
248
+ return templates.TemplateResponse("tools.html", ctx)
 
 
 
 
 
 
 
 
249
 
250
 
251
+ #----- Settings page with current config and database list
252
  async def settings_page(request: Request, _: bool = Depends(require_auth)):
 
 
 
 
253
  settings = SettingsManager.current().to_dict()
254
  settings["admin_password"] = ""
 
255
  try:
256
  settings["database_list"] = db.get_database_list()
257
  except Exception:
258
  settings["database_list"] = []
259
 
260
+ titles = settings.get("channel_titles") or {}
261
+ if not isinstance(titles, dict):
262
+ titles = {}
263
+ settings["channel_titles"] = {str(k): str(v) for k, v in titles.items() if k and v}
264
+
265
+ ctx = _base_context(request)
266
+ ctx.update({
267
+ "current_user": get_current_user(request),
268
+ "settings": settings,
269
+ "userbot_configured": botmod.Userbot is not None,
270
+ "formatter_presets": PRESETS,
271
+ })
272
+ return templates.TemplateResponse("settings.html", ctx)
 
Backend/fastapi/routes/webdav_routes.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WebDAV endpoint for Telegram-Stremio.
3
+
4
+ URL: /webdav/{token}/...
5
+
6
+ Auth:
7
+ - Path token = valid API token (same as Stremio)
8
+ - Optional HTTP Basic: WEBDAV_USER / WEBDAV_PASSWORD from config.env
9
+
10
+ Methods: OPTIONS, PROPFIND, HEAD, GET (read-only)
11
+
12
+ Supports the same media as Stremio streams:
13
+ - single files
14
+ - multi-quality (each quality is a separate file in the folder)
15
+ - split parts (.001/.002) joined as one virtual file
16
+ - split zip archives (via existing zip streamer)
17
+
18
+ Compatibility notes (2026-08):
19
+ - Always returns absolute hrefs in PROPFIND (required by many Android / media apps)
20
+ - Avoids relative paths that cause clients to fall back to port 80 on HTTPS hosts
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ from datetime import datetime, timezone
27
+ from typing import List
28
+ from urllib.parse import quote, unquote, urljoin
29
+ from xml.etree.ElementTree import Element, SubElement, tostring
30
+
31
+ from fastapi import APIRouter, HTTPException, Request, Response
32
+
33
+ from Backend.config import Telegram
34
+ from Backend.fastapi.routes import stream_routes as sr
35
+ from Backend.fastapi.security.tokens import verify_token
36
+ from Backend.helper.encrypt import decode_string
37
+ from Backend.helper.settings_manager import SettingsManager
38
+ from Backend.helper.webdav_fs import VNode, fs, normalize_path
39
+ from Backend.logger import LOGGER
40
+
41
+ router = APIRouter(tags=["WebDAV"])
42
+
43
+ DAV_NS = "DAV:"
44
+
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Auth
48
+ # ---------------------------------------------------------------------------
49
+
50
+ def _webdav_credentials():
51
+ """Prefer live Settings page values; fall back to config.env."""
52
+ try:
53
+ s = SettingsManager.current()
54
+ user = (getattr(s, "webdav_user", None) or "").strip()
55
+ password = getattr(s, "webdav_password", None) or ""
56
+ if user or password:
57
+ return user, password
58
+ except Exception:
59
+ pass
60
+ return (getattr(Telegram, "WEBDAV_USER", "") or "", getattr(Telegram, "WEBDAV_PASSWORD", "") or "")
61
+
62
+
63
+ def _basic_ok(request: Request) -> bool:
64
+ user, password = _webdav_credentials()
65
+ if not user and not password:
66
+ return True # Basic auth disabled
67
+ header = request.headers.get("Authorization") or ""
68
+ if not header.lower().startswith("basic "):
69
+ return False
70
+ try:
71
+ decoded = base64.b64decode(header.split(" ", 1)[1]).decode("utf-8")
72
+ u, _, p = decoded.partition(":")
73
+ return u == user and p == password
74
+ except Exception:
75
+ return False
76
+
77
+
78
+ async def _require_webdav_auth(request: Request, token: str) -> dict:
79
+ if not _basic_ok(request):
80
+ raise HTTPException(
81
+ status_code=401,
82
+ detail="WebDAV Basic auth required. Set username/password in Settings → WebDAV, or clear both fields to disable Basic auth.",
83
+ headers={"WWW-Authenticate": 'Basic realm="Telegram-Stremio WebDAV"'},
84
+ )
85
+ try:
86
+ token_data = await verify_token(token)
87
+ except HTTPException as e:
88
+ # Re-raise as 401 JSON-friendly (do not use admin login redirect)
89
+ raise HTTPException(status_code=401, detail=f"Invalid API token for WebDAV: {e.detail}")
90
+ if token_data.get("subscription_expired") or token_data.get("limit_exceeded"):
91
+ raise HTTPException(status_code=403, detail="Token expired or limit exceeded")
92
+ return token_data
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # PROPFIND helpers (absolute hrefs for maximum client compatibility)
97
+ # ---------------------------------------------------------------------------
98
+
99
+ def _href(request: Request, token: str, path: str, is_dir: bool) -> str:
100
+ """
101
+ Return an absolute href.
102
+ Many Android / media WebDAV clients break on relative paths and fall back
103
+ to port 80 even when the original URL was https://.
104
+ """
105
+ path = normalize_path(path)
106
+ segments = [quote(s, safe="") for s in path.strip("/").split("/") if s]
107
+ rel = f"/webdav/{token}/" + "/".join(segments)
108
+ if is_dir and not rel.endswith("/"):
109
+ rel += "/"
110
+
111
+ # Prefer configured public BASE_URL, otherwise use the request itself
112
+ base = (getattr(Telegram, "BASE_URL", None) or "").rstrip("/")
113
+ if not base:
114
+ base = str(request.base_url).rstrip("/")
115
+ return urljoin(base + "/", rel.lstrip("/"))
116
+
117
+
118
+ def _http_date(ts: float) -> str:
119
+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT")
120
+
121
+
122
+ def _iso_date(ts: float) -> str:
123
+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
124
+
125
+
126
+ def _prop_response(request: Request, token: str, node: VNode) -> Element:
127
+ resp = Element(f"{{{DAV_NS}}}response")
128
+ href = SubElement(resp, f"{{{DAV_NS}}}href")
129
+ href.text = _href(request, token, node.path, node.is_dir)
130
+
131
+ propstat = SubElement(resp, f"{{{DAV_NS}}}propstat")
132
+ prop = SubElement(propstat, f"{{{DAV_NS}}}prop")
133
+
134
+ SubElement(prop, f"{{{DAV_NS}}}displayname").text = node.name or "root"
135
+ SubElement(prop, f"{{{DAV_NS}}}getlastmodified").text = _http_date(node.mtime)
136
+ SubElement(prop, f"{{{DAV_NS}}}getetag").text = (
137
+ f'"{hash((node.path, node.size, int(node.mtime))) & 0xFFFFFFFF:x}"'
138
+ )
139
+ SubElement(prop, f"{{{DAV_NS}}}creationdate").text = _iso_date(node.mtime)
140
+
141
+ if node.is_dir:
142
+ rt = SubElement(prop, f"{{{DAV_NS}}}resourcetype")
143
+ SubElement(rt, f"{{{DAV_NS}}}collection")
144
+ SubElement(prop, f"{{{DAV_NS}}}getcontentlength").text = "0"
145
+ else:
146
+ SubElement(prop, f"{{{DAV_NS}}}resourcetype")
147
+ SubElement(prop, f"{{{DAV_NS}}}getcontentlength").text = str(max(0, node.size))
148
+ SubElement(prop, f"{{{DAV_NS}}}getcontenttype").text = node.content_type
149
+
150
+ SubElement(propstat, f"{{{DAV_NS}}}status").text = "HTTP/1.1 200 OK"
151
+ return resp
152
+
153
+
154
+ def _multistatus_xml(request: Request, token: str, nodes: List[VNode]) -> bytes:
155
+ root = Element(f"{{{DAV_NS}}}multistatus")
156
+ for node in nodes:
157
+ root.append(_prop_response(request, token, node))
158
+ return tostring(root, encoding="utf-8", xml_declaration=True)
159
+
160
+
161
+ # ---------------------------------------------------------------------------
162
+ # Video streaming — reuses Stremio stream_routes (single / split / zip)
163
+ # ---------------------------------------------------------------------------
164
+
165
+ async def _stream_video(request: Request, node: VNode, token: str, token_data: dict):
166
+ if not node.stream_id:
167
+ raise HTTPException(status_code=404, detail="No stream id for this file")
168
+
169
+ try:
170
+ decoded = await decode_string(node.stream_id)
171
+ except Exception as e:
172
+ LOGGER.warning("[WebDAV] decode stream id failed: %s", e)
173
+ raise HTTPException(status_code=400, detail="Invalid stream id")
174
+
175
+ sid = node.stream_id
176
+
177
+ # Same dispatch order as stream_routes.stream_handler
178
+ if decoded.get("global"):
179
+ if decoded.get("zip"):
180
+ return await sr.global_zip_media_streamer(
181
+ request=request,
182
+ parts_payload=decoded["parts"],
183
+ token=token,
184
+ token_data=token_data,
185
+ stream_id_hash=sid,
186
+ )
187
+ if "parts" in decoded:
188
+ return await sr.global_virtual_media_streamer(
189
+ request=request,
190
+ parts_payload=decoded["parts"],
191
+ token=token,
192
+ token_data=token_data,
193
+ stream_id_hash=sid,
194
+ )
195
+ return await sr.global_media_streamer(
196
+ request=request,
197
+ chat_id=int(decoded["chat_id"]),
198
+ msg_id=int(decoded["msg_id"]),
199
+ token=token,
200
+ token_data=token_data,
201
+ stream_id_hash=sid,
202
+ )
203
+
204
+ if "parts" in decoded:
205
+ if decoded.get("zip"):
206
+ return await sr.db_zip_media_streamer(
207
+ request=request,
208
+ parts_payload=decoded["parts"],
209
+ token=token,
210
+ token_data=token_data,
211
+ stream_id_hash=sid,
212
+ )
213
+ return await sr.virtual_media_streamer(
214
+ request=request,
215
+ parts_payload=decoded["parts"],
216
+ token=token,
217
+ token_data=token_data,
218
+ stream_id_hash=sid,
219
+ )
220
+
221
+ msg_id = decoded.get("msg_id")
222
+ if not msg_id:
223
+ raise HTTPException(status_code=400, detail="Missing msg_id in stream id")
224
+ chat_id = int(f"-100{decoded['chat_id']}")
225
+ return await sr.media_streamer(
226
+ request=request,
227
+ chat_id=chat_id,
228
+ msg_id=int(msg_id),
229
+ token=token,
230
+ token_data=token_data,
231
+ stream_id_hash=sid,
232
+ )
233
+
234
+
235
+ # ---------------------------------------------------------------------------
236
+ # Routes
237
+ # ---------------------------------------------------------------------------
238
+
239
+ @router.options("/webdav/{token}")
240
+ @router.options("/webdav/{token}/{path:path}")
241
+ async def webdav_options(token: str, path: str = ""):
242
+ return Response(
243
+ status_code=200,
244
+ headers={
245
+ "Allow": "OPTIONS, GET, HEAD, PROPFIND",
246
+ "DAV": "1, 2",
247
+ "MS-Author-Via": "DAV",
248
+ "Accept-Ranges": "bytes",
249
+ },
250
+ )
251
+
252
+
253
+ @router.api_route("/webdav/{token}", methods=["PROPFIND"])
254
+ @router.api_route("/webdav/{token}/{path:path}", methods=["PROPFIND"])
255
+ async def webdav_propfind(request: Request, token: str, path: str = ""):
256
+ await _require_webdav_auth(request, token)
257
+ depth = request.headers.get("Depth", "1")
258
+ vpath = normalize_path("/" + unquote(path or ""))
259
+ node = await fs.resolve(vpath)
260
+ if node is None:
261
+ raise HTTPException(status_code=404, detail="Not found")
262
+
263
+ nodes: List[VNode] = [node]
264
+ if node.is_dir and depth != "0":
265
+ nodes.extend(await fs.list_dir(vpath))
266
+
267
+ return Response(
268
+ content=_multistatus_xml(request, token, nodes),
269
+ status_code=207,
270
+ media_type="application/xml; charset=utf-8",
271
+ headers={"DAV": "1, 2"},
272
+ )
273
+
274
+
275
+ @router.head("/webdav/{token}")
276
+ @router.head("/webdav/{token}/{path:path}")
277
+ @router.get("/webdav/{token}")
278
+ @router.get("/webdav/{token}/{path:path}")
279
+ async def webdav_get(request: Request, token: str, path: str = ""):
280
+ token_data = await _require_webdav_auth(request, token)
281
+ vpath = normalize_path("/" + unquote(path or ""))
282
+ node = await fs.resolve(vpath)
283
+ if node is None:
284
+ raise HTTPException(status_code=404, detail="Not found")
285
+
286
+ if node.is_dir:
287
+ children = await fs.list_dir(vpath)
288
+ rows = []
289
+ parent = normalize_path("/".join(vpath.rstrip("/").split("/")[:-1]) or "/")
290
+ if vpath not in ("", "/"):
291
+ rows.append(f'<li><a href="{_href(request, token, parent, True)}">../</a></li>')
292
+ for c in sorted(children, key=lambda n: (not n.is_dir, n.name.lower())):
293
+ href = _href(request, token, c.path, c.is_dir)
294
+ label = c.name + ("/" if c.is_dir else "")
295
+ size = "" if c.is_dir else f" ({c.size} bytes)"
296
+ rows.append(f'<li><a href="{href}">{label}</a>{size}</li>')
297
+ body = (
298
+ f"<!DOCTYPE html><html><head><meta charset=utf-8><title>Index of {vpath}</title></head>"
299
+ f"<body><h1>Index of {vpath}</h1><ul>{''.join(rows)}</ul>"
300
+ f"<p><em>Telegram-Stremio WebDAV</em></p></body></html>"
301
+ ).encode("utf-8")
302
+ return Response(content=body, media_type="text/html; charset=utf-8")
303
+
304
+ if node.nfo_body is not None:
305
+ headers = {
306
+ "Content-Type": node.content_type,
307
+ "Content-Length": str(len(node.nfo_body)),
308
+ "Accept-Ranges": "bytes",
309
+ }
310
+ if request.method == "HEAD":
311
+ return Response(status_code=200, headers=headers)
312
+ return Response(content=node.nfo_body, media_type=node.content_type, headers=headers)
313
+
314
+ if node.kind in ("movie_video", "episode_video"):
315
+ if request.method == "HEAD":
316
+ return Response(
317
+ status_code=200,
318
+ headers={
319
+ "Content-Type": node.content_type,
320
+ "Content-Length": str(max(1, node.size)),
321
+ "Accept-Ranges": "bytes",
322
+ },
323
+ )
324
+ return await _stream_video(request, node, token, token_data)
325
+
326
+ raise HTTPException(status_code=404, detail="Unsupported node type")
327
+
328
+
329
+ @router.api_route(
330
+ "/webdav/{token}",
331
+ methods=["PUT", "DELETE", "MKCOL", "MOVE", "COPY", "LOCK", "UNLOCK", "PROPPATCH"],
332
+ )
333
+ @router.api_route(
334
+ "/webdav/{token}/{path:path}",
335
+ methods=["PUT", "DELETE", "MKCOL", "MOVE", "COPY", "LOCK", "UNLOCK", "PROPPATCH"],
336
+ )
337
+ async def webdav_readonly(token: str, path: str = ""):
338
+ return Response(status_code=403, content="WebDAV is read-only")
339
+
340
+
341
+ @router.post("/webdav/{token}/refresh")
342
+ async def webdav_refresh(request: Request, token: str):
343
+ await _require_webdav_auth(request, token)
344
+ fs.invalidate()
345
+ await fs.ensure_tree()
346
+ return {"status": "ok", "message": "WebDAV filesystem cache refreshed"}
Backend/fastapi/security/credentials.py CHANGED
@@ -1,32 +1,46 @@
1
- from fastapi import Depends, HTTPException, Request
2
  from starlette.status import HTTP_401_UNAUTHORIZED
 
 
 
3
  from Backend.helper.settings_manager import SettingsManager
4
 
 
 
5
  def verify_credentials(username: str, password: str) -> bool:
6
- """Return True when *username* and *password* match the stored admin credentials."""
7
  s = SettingsManager.current()
8
- return username == s.admin_username and password == s.admin_password
 
 
 
 
9
 
10
 
11
  def is_authenticated(request: Request) -> bool:
12
- """Return True when the session carries a valid authentication flag."""
13
- return bool(request.session.get("authenticated"))
 
 
 
 
 
14
 
 
 
 
 
 
15
 
 
 
16
  def get_current_user(request: Request) -> str | None:
17
- """Return the logged-in username from the session, or None."""
18
  if is_authenticated(request):
19
  return request.session.get("username", "admin")
20
  return None
21
 
22
 
 
23
  async def require_auth(request: Request) -> bool:
24
- """
25
- FastAPI dependency: raises 401 when the request is not authenticated.
26
-
27
- The 401 exception handler in main.py redirects the browser to /login.
28
- """
29
  if not is_authenticated(request):
30
  raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated")
31
  return True
32
-
 
1
+ from fastapi import HTTPException, Request
2
  from starlette.status import HTTP_401_UNAUTHORIZED
3
+
4
+ from Backend.helper.bounded import BoundedDict
5
+ from Backend.helper.passwords import verify_password
6
  from Backend.helper.settings_manager import SettingsManager
7
 
8
+
9
+ #----- Match a username/password pair against the stored admin credentials
10
  def verify_credentials(username: str, password: str) -> bool:
 
11
  s = SettingsManager.current()
12
+ return username == s.admin_username and verify_password(password, s.admin_password)
13
+
14
+
15
+ #----- Whether the session carries a valid authentication flag
16
+ _revoked_sids = BoundedDict(1000)
17
 
18
 
19
  def is_authenticated(request: Request) -> bool:
20
+ if not request.session.get("authenticated"):
21
+ return False
22
+ if request.session.get("sid") in _revoked_sids:
23
+ request.session.clear()
24
+ return False
25
+ return True
26
+
27
 
28
+ def revoke_session(request: Request) -> None:
29
+ sid = request.session.get("sid")
30
+ if sid:
31
+ _revoked_sids[sid] = True
32
+ request.session.clear()
33
 
34
+
35
+ #----- Logged-in username from the session, or None
36
  def get_current_user(request: Request) -> str | None:
 
37
  if is_authenticated(request):
38
  return request.session.get("username", "admin")
39
  return None
40
 
41
 
42
+ #----- FastAPI dependency: raise 401 (redirected to /login) when unauthenticated
43
  async def require_auth(request: Request) -> bool:
 
 
 
 
 
44
  if not is_authenticated(request):
45
  raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated")
46
  return True
 
Backend/fastapi/security/tokens.py CHANGED
@@ -1,15 +1,17 @@
 
 
1
  from fastapi import HTTPException
2
- from datetime import datetime
3
  from Backend import db
 
4
  from Backend.helper.settings_manager import SettingsManager
5
 
6
-
7
-
8
  DAILY_LIMIT_VIDEO = "https://bit.ly/3YZFKT5"
9
  MONTHLY_LIMIT_VIDEO = "https://bit.ly/4rfjtgd"
10
  SUBSCRIPTION_EXPIRED_VIDEO = "https://bit.ly/4rfjtgd"
11
 
12
 
 
13
  async def verify_token(token: str):
14
  token_data = await db.get_api_token(token)
15
  if not token_data:
@@ -22,35 +24,45 @@ async def verify_token(token: str):
22
  token_data["limit_video"] = None
23
  token_data["subscription_expired"] = False
24
 
25
- # --- Subscription expiry check (only when SUBSCRIPTION feature is enabled) ---
26
- if SettingsManager.current().subscription:
27
- user_id = token_data.get("user_id")
28
- if not user_id:
29
- # Token has no linked user — treat as expired (unverified token)
30
- token_data["subscription_expired"] = True
31
- return token_data
 
32
 
33
- user = await db.get_user(int(user_id))
34
- if not user or user.get("subscription_status") != "active":
35
- token_data["subscription_expired"] = True
36
- return token_data
37
 
38
- expiry = user.get("subscription_expiry")
39
- if not expiry:
40
- token_data["subscription_expired"] = True
41
- return token_data
 
 
 
 
 
42
 
43
- # Compare correctly regardless of timezone awareness
44
- now = datetime.utcnow()
45
- try:
46
- if expiry.tzinfo is not None:
47
- from datetime import timezone
48
- now = datetime.now(timezone.utc)
49
- except AttributeError:
50
- pass
51
- if expiry < now:
52
- token_data["subscription_expired"] = True
53
- return token_data
 
 
 
 
 
 
54
 
55
  if daily_limit := limits.get("daily_limit_gb"):
56
  if daily_limit > 0:
 
1
+ from datetime import datetime, timezone
2
+
3
  from fastapi import HTTPException
4
+
5
  from Backend import db
6
+ from Backend.config import Telegram
7
  from Backend.helper.settings_manager import SettingsManager
8
 
 
 
9
  DAILY_LIMIT_VIDEO = "https://bit.ly/3YZFKT5"
10
  MONTHLY_LIMIT_VIDEO = "https://bit.ly/4rfjtgd"
11
  SUBSCRIPTION_EXPIRED_VIDEO = "https://bit.ly/4rfjtgd"
12
 
13
 
14
+ #----- Validate an API token and annotate it with subscription/limit status
15
  async def verify_token(token: str):
16
  token_data = await db.get_api_token(token)
17
  if not token_data:
 
24
  token_data["limit_video"] = None
25
  token_data["subscription_expired"] = False
26
 
27
+ #----- Owner-linked tokens are admins (honour persisted flag, else derive)
28
+ _uid = token_data.get("user_id")
29
+ try:
30
+ token_data["is_admin"] = bool(token_data.get("is_admin")) or (
31
+ _uid is not None and int(_uid) == int(Telegram.OWNER_ID)
32
+ )
33
+ except (TypeError, ValueError):
34
+ token_data["is_admin"] = bool(token_data.get("is_admin"))
35
 
36
+ #----- Access expiry checks. Admin and never-expires tokens always bypass.
37
+ if not token_data["is_admin"] and not token_data.get("subscription_exempt"):
 
 
38
 
39
+ #----- Compare correctly regardless of timezone awareness
40
+ def _expired(when):
41
+ ref = datetime.utcnow()
42
+ try:
43
+ if when.tzinfo is not None:
44
+ ref = datetime.now(timezone.utc)
45
+ except AttributeError:
46
+ pass
47
+ return when < ref
48
 
49
+ #----- A token's own expiry is enforced in every mode. With no token expiry,
50
+ #----- an active subscription is required only while subscription mode is on.
51
+ #----- (When valid, fall through so data-limit checks still apply.)
52
+ token_expiry = token_data.get("expires_at")
53
+ if token_expiry is not None:
54
+ if _expired(token_expiry):
55
+ token_data["subscription_expired"] = True
56
+ return token_data
57
+ elif SettingsManager.current().subscription:
58
+ user_id = token_data.get("user_id")
59
+ user = await db.get_user(int(user_id)) if user_id else None
60
+ expiry = user.get("subscription_expiry") if user else None
61
+ if (not user_id or not user
62
+ or user.get("subscription_status") != "active"
63
+ or not expiry or _expired(expiry)):
64
+ token_data["subscription_expired"] = True
65
+ return token_data
66
 
67
  if daily_limit := limits.get("daily_limit_gb"):
68
  if daily_limit > 0:
Backend/fastapi/static/placeholder.svg ADDED
Backend/fastapi/templates/access_manage.html CHANGED
@@ -1,437 +1,113 @@
1
  {% extends "base.html" %}
2
- {% block title %}Access Management{% endblock %}
3
 
4
  {% block content %}
5
  <style>
6
- .access-shell {
7
- display: flex;
8
- flex-direction: column;
9
- gap: 1.5rem;
10
- }
11
-
12
- .page-hero,
13
- .section-panel,
14
- .table-shell,
15
- .stat-card,
16
- .mobile-token-card,
17
- .empty-state,
18
- .modal-glass {
19
- background: color-mix(in srgb, var(--card) 50%, transparent);
20
- backdrop-filter: blur(20px);
21
- -webkit-backdrop-filter: blur(20px);
22
- border: 1px solid var(--border);
23
- box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
24
- }
25
-
26
- .page-hero,
27
- .section-panel,
28
- .table-shell,
29
- .stat-card,
30
- .mobile-token-card,
31
- .empty-state {
32
- border-radius: 1.5rem;
33
- }
34
-
35
- .hero-glow {
36
- position: relative;
37
- overflow: hidden;
38
- isolation: isolate;
39
- }
40
-
41
- .hero-glow::before {
42
- content: "";
43
- position: absolute;
44
- inset: -30% auto auto -10%;
45
- width: 16rem;
46
- height: 16rem;
47
- border-radius: 9999px;
48
- background: color-mix(in srgb, var(--primary) 18%, transparent);
49
- filter: blur(52px);
50
- z-index: -1;
51
- pointer-events: none;
52
- }
53
-
54
- .hero-glow::after {
55
- content: "";
56
- position: absolute;
57
- inset: auto -4% -34% auto;
58
- width: 14rem;
59
- height: 14rem;
60
- border-radius: 9999px;
61
- background: color-mix(in srgb, var(--accent) 16%, transparent);
62
- filter: blur(52px);
63
- z-index: -1;
64
- pointer-events: none;
65
- }
66
-
67
  .section-title { color: var(--text); }
68
- .section-muted { color: var(--text-sec); }
69
-
70
- .glass-btn {
71
- border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
72
- background: color-mix(in srgb, var(--card) 92%, var(--bg));
73
- color: var(--text);
74
- transition: all 0.25s ease;
75
- box-shadow: 0 8px 24px rgba(0,0,0,0.14);
76
- }
77
-
78
- .glass-btn:hover {
79
- transform: translateY(-1px);
80
- border-color: color-mix(in srgb, var(--primary) 35%, var(--border));
81
- box-shadow: 0 10px 28px rgba(0,0,0,0.18);
82
- }
83
-
84
- .glass-btn-primary {
85
- background: linear-gradient(
86
- 135deg,
87
- color-mix(in srgb, var(--primary) 88%, white 8%),
88
- color-mix(in srgb, var(--accent) 82%, var(--primary) 18%)
89
- );
90
- color: white;
91
- border: 1px solid color-mix(in srgb, var(--primary) 50%, transparent);
92
- box-shadow: 0 10px 26px color-mix(in srgb, var(--primary) 22%, transparent);
93
- }
94
-
95
- .glass-btn-primary:hover {
96
- filter: brightness(1.05);
97
- box-shadow: 0 14px 34px color-mix(in srgb, var(--primary) 28%, transparent);
98
- }
99
-
100
- .glass-btn-success {
101
- background: linear-gradient(135deg, #22c55e, #16a34a);
102
- color: #ffffff;
103
- border-color: transparent;
104
- }
105
-
106
- .glass-btn-warning {
107
- background: linear-gradient(135deg, #f59e0b, #d97706);
108
- color: #ffffff;
109
- border-color: transparent;
110
- }
111
-
112
- .glass-btn-danger {
113
- background: linear-gradient(135deg, #ef4444, #dc2626);
114
- color: #ffffff;
115
- border-color: transparent;
116
- }
117
-
118
- .glass-btn-purple {
119
- background: linear-gradient(135deg, #a855f7, #9333ea);
120
- color: #ffffff;
121
- border-color: transparent;
122
- }
123
-
124
- .glass-input,
125
- .glass-select {
126
- width: 100%;
127
- border-radius: 1rem;
128
- border: 1px solid color-mix(in srgb, var(--border) 90%, transparent);
129
- background: color-mix(in srgb, var(--bg) 68%, transparent);
130
- color: var(--text);
131
- padding: 0.85rem 1rem;
132
- outline: none;
133
- transition: all 0.2s ease;
134
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.02);
135
- }
136
-
137
- .glass-input::placeholder {
138
- color: color-mix(in srgb, var(--text-sec) 85%, transparent);
139
- }
140
-
141
- .glass-input:focus,
142
- .glass-select:focus {
143
- border-color: color-mix(in srgb, var(--primary) 65%, var(--border));
144
- box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 12%, transparent);
145
- }
146
-
147
- .stat-card {
148
- padding: 1.25rem;
149
- text-align: center;
150
- position: relative;
151
- overflow: hidden;
152
- }
153
-
154
- .stat-card::before {
155
- content: "";
156
- position: absolute;
157
- width: 7rem;
158
- height: 7rem;
159
- border-radius: 9999px;
160
- filter: blur(42px);
161
- top: -25%;
162
- right: -10%;
163
- opacity: 0.7;
164
- pointer-events: none;
165
- }
166
-
167
- .stat-primary::before { background: color-mix(in srgb, var(--primary) 24%, transparent); }
168
- .stat-success::before { background: color-mix(in srgb, #22c55e 24%, transparent); }
169
- .stat-danger::before { background: color-mix(in srgb, #ef4444 24%, transparent); }
170
-
171
- .stat-value {
172
- font-size: 1.9rem;
173
- font-weight: 800;
174
- line-height: 1;
175
- position: relative;
176
- z-index: 1;
177
- }
178
-
179
- .stat-label {
180
- margin-top: 0.55rem;
181
- font-size: 0.76rem;
182
- font-weight: 700;
183
- letter-spacing: 0.08em;
184
- text-transform: uppercase;
185
- color: var(--text-sec);
186
- position: relative;
187
- z-index: 1;
188
- }
189
-
190
- .table-shell { overflow: hidden; }
191
-
192
- .access-table {
193
- width: 100%;
194
- border-collapse: separate;
195
- border-spacing: 0;
196
- }
197
-
198
- .access-table thead th {
199
- background: color-mix(in srgb, var(--bg) 65%, transparent);
200
- color: var(--text-sec);
201
- font-size: 0.72rem;
202
- text-transform: uppercase;
203
- letter-spacing: 0.08em;
204
- border-bottom: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
205
- }
206
-
207
- .access-table tbody tr {
208
- transition: background 0.22s ease;
209
- }
210
-
211
- .access-table tbody tr:hover {
212
- background: color-mix(in srgb, var(--primary) 6%, transparent);
213
- }
214
-
215
- .access-table td {
216
- border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
217
- color: var(--text);
218
- vertical-align: top;
219
- }
220
-
221
- .access-table tbody tr:last-child td {
222
- border-bottom: none;
223
- }
224
-
225
- .row-expired {
226
- background: color-mix(in srgb, #ef4444 8%, transparent);
227
- }
228
-
229
- .status-badge {
230
- display: inline-flex;
231
- align-items: center;
232
- gap: 0.45rem;
233
- padding: 0.45rem 0.8rem;
234
- border-radius: 9999px;
235
- font-size: 0.78rem;
236
- font-weight: 700;
237
- letter-spacing: 0.02em;
238
- border: 1px solid transparent;
239
- }
240
-
241
- .status-active {
242
- background: color-mix(in srgb, #22c55e 16%, transparent);
243
- color: #86efac;
244
- border-color: color-mix(in srgb, #22c55e 28%, transparent);
245
- }
246
-
247
- .status-expired {
248
- background: color-mix(in srgb, #ef4444 14%, transparent);
249
- color: #fca5a5;
250
- border-color: color-mix(in srgb, #ef4444 28%, transparent);
251
- }
252
-
253
- .status-warning {
254
- background: color-mix(in srgb, #f59e0b 16%, transparent);
255
- color: #fde68a;
256
- border-color: color-mix(in srgb, #f59e0b 28%, transparent);
257
- }
258
-
259
- .action-chip {
260
- border-radius: 9999px;
261
- padding: 0.5rem 0.85rem;
262
- font-size: 0.72rem;
263
- font-weight: 700;
264
- border: 1px solid transparent;
265
- transition: all 0.2s ease;
266
- white-space: nowrap;
267
- }
268
-
269
- .action-chip:hover {
270
- transform: translateY(-1px);
271
- }
272
-
273
- .addon-box {
274
- padding: 0.8rem;
275
- border-radius: 1rem;
276
- background: color-mix(in srgb, var(--bg) 56%, transparent);
277
- border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
278
- }
279
-
280
- .mobile-token-card {
281
- padding: 1rem;
282
- }
283
-
284
- .mobile-token-card + .mobile-token-card {
285
- margin-top: 0.9rem;
286
- }
287
-
288
- .mobile-grid {
289
- display: none;
290
- }
291
-
292
- .pagination-shell {
293
- display: flex;
294
- align-items: center;
295
- justify-content: space-between;
296
- gap: 1rem;
297
- flex-wrap: wrap;
298
- }
299
-
300
- .pagination-text {
301
- color: var(--text-sec);
302
- }
303
-
304
- .pagination-btn {
305
- min-width: 92px;
306
- }
307
-
308
- .modal-backdrop {
309
- background: rgba(4, 8, 18, 0.58);
310
- backdrop-filter: blur(10px);
311
- -webkit-backdrop-filter: blur(10px);
312
- }
313
-
314
- .modal-glass {
315
- border-radius: 1.6rem;
316
- padding: 1.4rem;
317
- border: 1px solid color-mix(in srgb, var(--border) 95%, transparent);
318
- width: min(92vw, 32rem);
319
- }
320
-
321
- .modal-field label {
322
- color: var(--text-sec);
323
- font-size: 0.82rem;
324
- font-weight: 700;
325
- margin-bottom: 0.55rem;
326
- display: block;
327
- }
328
-
329
- .text-soft { color: var(--text-sec); }
330
 
331
  .no-scrollbar::-webkit-scrollbar { display: none; }
332
- .no-scrollbar {
333
- -ms-overflow-style: none;
334
- scrollbar-width: none;
335
- }
336
-
337
- @media (max-width: 1024px) {
338
- .access-table th,
339
- .access-table td {
340
- padding-left: 1rem;
341
- padding-right: 1rem;
342
- }
343
- }
344
-
345
- @media (max-width: 767px) {
346
- .desktop-table-wrap {
347
- display: none;
348
- }
349
-
350
- .mobile-grid {
351
- display: block;
352
- }
353
-
354
- .page-hero,
355
- .section-panel {
356
- padding: 1rem;
357
- border-radius: 1.35rem;
358
- }
359
-
360
- .pagination-shell {
361
- flex-direction: column;
362
- align-items: stretch;
363
- }
364
-
365
- .pagination-shell .controls {
366
- width: 100%;
367
- display: grid;
368
- grid-template-columns: 1fr auto 1fr;
369
- gap: 0.6rem;
370
- align-items: center;
371
- }
372
-
373
- .pagination-btn {
374
- width: 100%;
375
- }
376
  }
377
  </style>
378
 
379
- <div class="access-shell py-2 sm:py-4">
380
- <section class="page-hero hero-glow p-5 sm:p-6 lg:p-8">
381
- <div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
382
- <div>
383
- <div class="inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-bold tracking-[0.18em] uppercase mb-3"
384
- style="border-color: color-mix(in srgb, var(--primary) 28%, var(--border)); color: var(--text-sec); background: color-mix(in srgb, var(--primary) 10%, transparent);">
385
- <i class="fas fa-shield-halved text-[11px]" style="color: var(--primary);"></i>
386
- Access Control Hub
387
- </div>
388
- <h1 class="text-2xl sm:text-3xl lg:text-4xl font-extrabold tracking-tight section-title">
389
- Access Management
390
- </h1>
391
- <p class="mt-2 text-sm sm:text-base section-muted max-w-2xl">
392
- Manage addon access tokens, link users, assign plans, and control subscription access.
393
- </p>
394
- </div>
395
-
396
- <div class="flex flex-wrap gap-3">
397
- <button onclick="loadTokens()" class="glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold inline-flex items-center gap-2">
398
- <i class="fas fa-rotate-right"></i>
399
- Refresh
400
- </button>
401
- </div>
402
- </div>
403
- </section>
404
-
405
- <section class="grid grid-cols-1 sm:grid-cols-3 gap-4">
406
- <div class="stat-card stat-primary">
407
- <div class="stat-value" style="color: var(--primary);" id="stat-total">–</div>
408
- <div class="stat-label">Total Tokens</div>
409
- </div>
410
- <div class="stat-card stat-success">
411
- <div class="stat-value" style="color: #4ade80;" id="stat-active">–</div>
412
- <div class="stat-label">Active</div>
413
  </div>
414
- <div class="stat-card stat-danger">
415
- <div class="stat-value" style="color: #f87171;" id="stat-expired">–</div>
416
- <div class="stat-label">Expired / No Sub</div>
417
  </div>
 
 
 
 
 
 
418
  </section>
419
 
420
- <section class="section-panel p-4 sm:p-5 lg:p-6">
421
  <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
422
  <div>
423
- <h2 class="text-lg sm:text-xl font-bold section-title">Access Tokens</h2>
424
- <p class="text-sm section-muted mt-1">Search, filter, manage tokens, and control user access.</p>
425
  </div>
426
 
427
  <div class="w-full lg:w-auto grid grid-cols-1 sm:grid-cols-3 gap-3">
428
- <input
429
- id="search-input"
430
- type="text"
431
- placeholder="Search by name or user ID..."
432
- class="glass-input"
433
- oninput="currentPage=1; renderPage()"
434
- >
435
  <select id="filter-status" class="glass-select" onchange="currentPage=1; renderPage()">
436
  <option value="all">All Status</option>
437
  <option value="active">Active</option>
@@ -446,22 +122,20 @@
446
  </div>
447
 
448
  <div class="desktop-table-wrap table-shell">
449
- <div class="overflow-x-auto no-scrollbar">
450
- <table class="access-table min-w-[1120px] text-sm">
451
  <thead>
452
  <tr>
453
  <th class="px-4 py-4 text-left font-semibold">Status</th>
454
  <th class="px-4 py-4 text-left font-semibold">User</th>
455
  <th class="px-4 py-4 text-left font-semibold">Addon Link</th>
456
- <th class="px-4 py-4 text-left font-semibold">Created</th>
457
  <th class="px-4 py-4 text-left font-semibold">Expires</th>
458
- <th class="px-4 py-4 text-center font-semibold">Actions</th>
459
  </tr>
460
  </thead>
461
  <tbody id="token-table-body">
462
- <tr>
463
- <td colspan="6" class="text-center py-10 text-soft">Loading tokens…</td>
464
- </tr>
465
  </tbody>
466
  </table>
467
  </div>
@@ -474,88 +148,163 @@
474
  <div class="pagination-shell mt-5" id="pagination-bar">
475
  <div id="page-info" class="pagination-text text-sm"></div>
476
  <div class="controls">
477
- <button id="btn-prev" onclick="changePage(-1)"
478
- class="glass-btn pagination-btn rounded-xl px-4 py-2.5 text-sm font-semibold">
479
- ‹ Prev
480
- </button>
481
- <span id="page-num" class="text-sm font-bold text-center section-title px-2"></span>
482
- <button id="btn-next" onclick="changePage(1)"
483
- class="glass-btn pagination-btn rounded-xl px-4 py-2.5 text-sm font-semibold">
484
- Next ›
485
- </button>
486
  </div>
487
  </div>
488
  </section>
489
  </div>
490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  <div id="assign-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
492
  <div class="modal-glass">
493
  <div class="flex items-start justify-between gap-4 mb-5">
494
  <div>
495
- <h3 class="text-xl font-bold section-title">Assign Subscription Plan</h3>
496
  <p class="text-sm text-soft mt-1" id="assign-user-label">User: –</p>
497
  </div>
498
- <button onclick="closeAssignModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
499
- <i class="fas fa-xmark"></i>
500
- </button>
501
  </div>
502
-
503
  <input type="hidden" id="assign-user-id">
504
-
505
  <div class="space-y-4">
506
- <div class="modal-field">
507
  <label>Select a Plan</label>
508
- <select id="assign-plan-select" class="glass-select">
509
- <option value="">— Select plan —</option>
510
- </select>
511
  </div>
512
-
513
  <div class="modal-field">
514
- <label>Or enter custom days</label>
515
  <input type="number" id="assign-custom-days" placeholder="e.g. 30" min="1" class="glass-input">
516
- <p class="text-xs text-soft mt-2">Custom days override selected plan.</p>
 
 
 
 
 
517
  </div>
518
  </div>
519
-
520
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
521
- <button onclick="closeAssignModal()" class="glass-btn rounded-2xl px-5 py-3 text-sm font-bold">
522
- Cancel
523
- </button>
524
- <button onclick="assignPlan()" class="glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold">
525
- Assign & Activate
526
- </button>
527
  </div>
528
  </div>
529
  </div>
530
 
 
531
  <div id="sub-action-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
532
  <div class="modal-glass">
533
  <div class="flex items-start justify-between gap-4 mb-5">
534
  <div>
535
- <h3 class="text-xl font-bold section-title" id="sub-action-title">Manage Subscription</h3>
536
  <p class="text-sm text-soft mt-1" id="sub-action-desc"></p>
537
  </div>
538
- <button onclick="closeSubModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
539
- <i class="fas fa-xmark"></i>
540
- </button>
541
  </div>
542
-
543
  <input type="hidden" id="sub-action-user-id">
 
544
  <input type="hidden" id="sub-action-action">
545
-
546
  <div id="sub-action-days-group" class="modal-field">
547
  <label>Number of Days</label>
548
  <input type="number" id="sub-action-days" value="30" min="1" class="glass-input">
549
  </div>
550
-
551
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
552
- <button onclick="closeSubModal()" class="glass-btn rounded-2xl px-5 py-3 text-sm font-bold">
553
- Cancel
554
- </button>
555
- <button id="sub-action-btn" onclick="submitSubAction()"
556
- class="glass-btn glass-btn-success rounded-2xl px-5 py-3 text-sm font-bold">
557
- Confirm
558
- </button>
559
  </div>
560
  </div>
561
  </div>
@@ -563,225 +312,165 @@
563
  <script>
564
  let allTokens = [];
565
  let currentPage = 1;
 
566
 
567
  function fmtDate(iso) {
568
  if (!iso) return '—';
569
  const d = new Date(iso);
570
- return d.toLocaleDateString('en-IN', {
571
- timeZone: 'Asia/Kolkata',
572
- day: '2-digit',
573
- month: 'short',
574
- year: 'numeric'
575
- }) + ' ' + d.toLocaleTimeString('en-IN', {
576
- timeZone: 'Asia/Kolkata',
577
- hour: '2-digit',
578
- minute: '2-digit'
579
- });
580
  }
581
 
582
  function escHtml(s) {
583
- return String(s || '')
584
- .replace(/&/g, '&amp;')
585
- .replace(/</g, '&lt;')
586
- .replace(/>/g, '&gt;')
587
- .replace(/"/g, '&quot;')
588
- .replace(/'/g, '&#039;');
 
 
 
589
  }
590
 
591
  function getFiltered() {
592
  const q = document.getElementById('search-input').value.toLowerCase().trim();
593
  const status = document.getElementById('filter-status').value;
594
-
595
  return allTokens.filter(t => {
596
- const matchQ = !q ||
597
- (t.user_name && t.user_name.toLowerCase().includes(q)) ||
598
- (t.user_id && String(t.user_id).includes(q));
599
-
600
- const matchStatus =
601
- status === 'all' ||
602
- (status === 'active' && !t.is_expired) ||
603
- (status === 'expired' && t.is_expired);
604
-
605
  return matchQ && matchStatus;
606
  });
607
  }
608
 
609
- function getStatusBadge(t) {
 
610
  return t.is_expired
611
  ? `<span class="status-badge status-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>`
612
  : `<span class="status-badge status-active"><i class="fas fa-circle text-[8px]"></i> Active</span>`;
613
  }
614
 
615
- function buildAddonHtml(t) {
616
- if (!t.has_token) {
617
- return `
618
- <div class="addon-box">
619
- <span class="status-badge status-warning">No Token Yet</span>
620
- <div class="text-xs text-soft italic mt-2">User hasn't generated addon token via bot.</div>
621
- </div>
622
- `;
623
  }
624
-
625
- if (t.is_expired) {
626
- return `
627
- <div class="addon-box">
628
- <span class="status-badge status-expired">Subscription Expired</span>
629
- <div class="text-xs text-soft italic mt-2">
630
- ${t.user_found ? 'Subscription inactive/expired' : 'No subscription record'}
631
- </div>
632
- ${t.addon_url ? `
633
- <button onclick="copyLink('${escHtml(t.addon_url)}')"
634
- class="mt-3 text-xs font-semibold underline opacity-70 hover:opacity-100 transition">
635
- Copy URL (admin)
636
- </button>
637
- ` : ''}
638
- </div>
639
- `;
640
- }
641
-
642
  return t.addon_url
643
- ? `
644
- <div class="addon-box">
645
- <button onclick="copyLink('${escHtml(t.addon_url)}')"
646
- class="glass-btn glass-btn-primary rounded-xl px-3 py-2 text-xs font-bold inline-flex items-center gap-2">
647
- <i class="fas fa-copy"></i>
648
- Copy Install Link
649
- </button>
650
- </div>
651
- `
652
  : `<div class="addon-box text-soft text-xs">—</div>`;
653
  }
654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
  function buildActions(t) {
656
  const safeName = escHtml(t.user_name || String(t.user_id || ''));
657
- let actionBtns = '';
658
-
659
- if (t.user_id) {
660
- actionBtns = `
661
- <button onclick="openAssignModal(${t.user_id}, '${safeName}')" class="action-chip glass-btn-primary">
662
- Assign
663
- </button>
664
- <button onclick="openSubModal(${t.user_id}, '${safeName}', 'extend')" class="action-chip glass-btn-success">
665
- Extend
666
- </button>
667
- <button onclick="openSubModal(${t.user_id}, '${safeName}', 'reduce')" class="action-chip glass-btn-warning">
668
- Reduce
669
- </button>
670
- <button onclick="openSubModal(${t.user_id}, '${safeName}', 'delete')" class="action-chip glass-btn-danger">
671
- Revoke
672
- </button>
673
- `;
674
- } else if (t.token) {
675
- actionBtns = `
676
- <button onclick="linkUser('${escHtml(t.token)}')" class="action-chip glass-btn-purple">
677
- Link User ID
678
- </button>
679
- <div class="text-xs text-soft italic w-full mt-1">Enter Telegram user_id to enable management.</div>
680
- `;
681
- }
682
 
683
- const revokeTokenBtn = t.token ? `
684
- <button onclick="revokeToken('${escHtml(t.token)}')" class="action-chip glass-btn">
685
- Del Token
686
- </button>
687
- ` : '';
688
 
689
- return actionBtns + revokeTokenBtn;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690
  }
691
 
692
  function renderDesktopRows(slice) {
693
  const tbody = document.getElementById('token-table-body');
694
-
695
- if (!slice.length) {
696
- tbody.innerHTML = `
697
- <tr>
698
- <td colspan="6" class="text-center py-10 text-soft">No tokens match your search.</td>
699
- </tr>
700
- `;
701
- return;
702
- }
703
 
704
  tbody.innerHTML = slice.map(t => {
705
- const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Unknown');
706
- const idHtml = t.user_id ? `<div class="text-xs text-soft mt-1">ID: ${t.user_id}</div>` : '';
707
- const rowCls = t.is_expired ? 'row-expired' : '';
708
-
709
  return `
710
- <tr class="${rowCls}">
711
- <td class="px-4 py-4">${getStatusBadge(t)}</td>
712
- <td class="px-4 py-4">
713
- <div class="font-semibold section-title">${escHtml(displayName)}</div>
714
- ${idHtml}
715
- </td>
716
- <td class="px-4 py-4">${buildAddonHtml(t)}</td>
717
- <td class="px-4 py-4 text-soft text-xs">${t.created_at ? fmtDate(t.created_at) : '—'}</td>
718
- <td class="px-4 py-4 text-xs">
719
- ${t.expires_at
720
- ? `<span class="${t.is_expired ? 'text-red-300 font-semibold' : 'section-title'}">${fmtDate(t.expires_at)}</span>`
721
- : `<span class="text-red-300 italic">No expiry</span>`
722
- }
723
- </td>
724
- <td class="px-4 py-4">
725
- <div class="flex flex-wrap gap-2 justify-center">${buildActions(t)}</div>
726
- </td>
727
- </tr>
728
- `;
729
  }).join('');
730
  }
731
 
732
  function renderMobileCards(slice) {
733
- const mobileWrap = document.getElementById('token-mobile-list');
734
-
735
- if (!slice.length) {
736
- mobileWrap.innerHTML = `
737
- <div class="empty-state text-center px-4 py-8 text-soft">
738
- No tokens match your search.
739
- </div>
740
- `;
741
- return;
742
- }
743
-
744
- mobileWrap.innerHTML = slice.map(t => {
745
- const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Unknown');
746
 
 
 
747
  return `
748
  <div class="mobile-token-card ${t.is_expired ? 'row-expired' : ''}">
749
  <div class="flex items-start justify-between gap-3 mb-3">
750
  <div class="min-w-0">
751
  <div class="font-semibold section-title break-words">${escHtml(displayName)}</div>
752
- <div class="text-xs text-soft mt-1 break-all">${t.user_id ? 'ID: ' + t.user_id : 'No linked user'}</div>
753
  </div>
754
- <div class="shrink-0">${getStatusBadge(t)}</div>
755
  </div>
756
-
757
  <div class="grid grid-cols-1 gap-3 mb-3">
758
- <div class="rounded-2xl px-4 py-3"
759
- style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
760
- <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-bold mb-1">Addon Access</div>
761
- ${buildAddonHtml(t)}
762
  </div>
763
-
764
  <div class="grid grid-cols-2 gap-3">
765
- <div class="rounded-2xl px-4 py-3"
766
- style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
767
- <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-bold mb-1">Created</div>
768
- <div class="text-sm font-semibold section-title break-words">${t.created_at ? fmtDate(t.created_at) : '—'}</div>
769
  </div>
770
- <div class="rounded-2xl px-4 py-3"
771
- style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
772
- <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-bold mb-1">Expires</div>
773
  <div class="text-sm font-semibold ${t.is_expired ? 'text-red-300' : 'section-title'} break-words">
774
- ${t.expires_at ? fmtDate(t.expires_at) : 'No expiry'}
775
  </div>
776
  </div>
777
  </div>
778
  </div>
779
-
780
- <div class="flex flex-wrap gap-2">
781
- ${buildActions(t)}
782
- </div>
783
- </div>
784
- `;
785
  }).join('');
786
  }
787
 
@@ -789,27 +478,17 @@
789
  const filtered = getFiltered();
790
  const pageSize = parseInt(document.getElementById('page-size').value);
791
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
792
-
793
  if (currentPage > totalPages) currentPage = totalPages;
794
-
795
  const start = filtered.length ? (currentPage - 1) * pageSize : 0;
796
  const slice = filtered.slice(start, start + pageSize);
797
 
798
- document.getElementById('page-info').textContent =
799
- filtered.length
800
- ? `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}`
801
- : 'Showing 0 of 0';
802
-
803
  document.getElementById('page-num').textContent = `Page ${currentPage} / ${totalPages}`;
804
 
805
- const prevBtn = document.getElementById('btn-prev');
806
- const nextBtn = document.getElementById('btn-next');
807
-
808
- prevBtn.disabled = currentPage <= 1;
809
- nextBtn.disabled = currentPage >= totalPages;
810
-
811
- prevBtn.style.opacity = currentPage <= 1 ? '0.45' : '1';
812
- nextBtn.style.opacity = currentPage >= totalPages ? '0.45' : '1';
813
 
814
  renderDesktopRows(slice);
815
  renderMobileCards(slice);
@@ -819,256 +498,237 @@
819
  const filtered = getFiltered();
820
  const pageSize = parseInt(document.getElementById('page-size').value);
821
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
822
-
823
- currentPage += dir;
824
- if (currentPage < 1) currentPage = 1;
825
- if (currentPage > totalPages) currentPage = totalPages;
826
-
827
  renderPage();
828
  }
829
 
830
  async function loadTokens() {
831
- document.getElementById('token-table-body').innerHTML = `
832
- <tr><td colspan="6" class="text-center py-10 text-soft">Loading…</td></tr>
833
- `;
834
- document.getElementById('token-mobile-list').innerHTML = `
835
- <div class="empty-state text-center px-4 py-8 text-soft">Loading…</div>
836
- `;
837
-
838
  try {
839
  const resp = await fetch('/api/admin/access/tokens');
840
  const data = await resp.json();
841
  allTokens = data.tokens || [];
842
-
843
  document.getElementById('stat-total').textContent = allTokens.length;
844
  document.getElementById('stat-active').textContent = allTokens.filter(t => !t.is_expired).length;
845
  document.getElementById('stat-expired').textContent = allTokens.filter(t => t.is_expired).length;
846
-
847
  currentPage = 1;
848
  renderPage();
849
  } catch (err) {
850
- document.getElementById('token-table-body').innerHTML = `
851
- <tr><td colspan="6" class="text-center py-10 text-red-300">Error: ${err.message}</td></tr>
852
- `;
853
- document.getElementById('token-mobile-list').innerHTML = `
854
- <div class="empty-state text-center px-4 py-8 text-red-300">Error: ${err.message}</div>
855
- `;
856
  showToast('Failed to load access tokens.', 'error', 'Load Error');
857
  }
858
  }
859
 
860
  async function loadPlans() {
861
- try {
862
- const resp = await fetch('/api/admin/subscriptions/plans');
863
- if (!resp.ok) throw new Error(`HTTP error! status: ${resp.status}`);
864
- const result = await resp.json();
865
- const plans = result.data || [];
866
- const sel = document.getElementById('assign-plan-select');
867
- if (!sel) return;
868
- sel.innerHTML = '<option value="">— Select a plan —</option>' +
869
- plans.map(p => `
870
- <option value="${p.days}">
871
- ${p.days} days${p.price ? ' — ₹' + p.price : ''}
872
- </option>
873
- `).join('');
874
-
875
- } catch (e) {
876
- console.warn('Could not load plans', e);
877
- showToast('Could not load subscription plans.', 'error', 'Plan Error');
878
- }
879
- }
880
- function openModal(modalId) {
881
- const modal = document.getElementById(modalId);
882
- modal.classList.remove('hidden');
883
- modal.classList.add('flex');
884
  document.body.classList.add('overflow-hidden');
885
  }
886
-
887
- function closeModal(modalId) {
888
- const modal = document.getElementById(modalId);
889
- modal.classList.add('hidden');
890
- modal.classList.remove('flex');
891
  document.body.classList.remove('overflow-hidden');
892
  }
893
 
894
- function openAssignModal(userId, userName) {
895
- document.getElementById('assign-user-id').value = userId;
896
- document.getElementById('assign-user-label').textContent = `User: ${userName} (ID: ${userId})`;
897
- document.getElementById('assign-custom-days').value = '';
898
- document.getElementById('assign-plan-select').value = '';
899
- openModal('assign-modal');
900
  }
901
 
902
- function closeAssignModal() {
903
- closeModal('assign-modal');
 
 
 
 
 
 
 
 
 
 
 
 
904
  }
905
 
906
- async function assignPlan() {
907
- const userId = parseInt(document.getElementById('assign-user-id').value);
908
- const customDays = parseInt(document.getElementById('assign-custom-days').value) || 0;
909
- const planDays = parseInt(document.getElementById('assign-plan-select').value) || 0;
910
- const days = customDays || planDays;
911
-
912
- if (!days || days < 1) {
913
- showToast('Please select a plan or enter custom days.', 'error', 'Validation');
914
- return;
915
- }
916
 
 
 
 
 
 
 
917
  try {
918
- const resp = await fetch(`/api/admin/access/users/${userId}/assign-plan`, {
919
- method: 'POST',
920
- headers: { 'Content-Type': 'application/json' },
921
- body: JSON.stringify({ days })
922
- });
923
 
924
- const data = await resp.json();
 
 
 
 
 
 
925
 
926
- if (resp.ok) {
927
- showToast(`Assigned ${days} days to user ${userId}.`, 'success', 'Plan Assigned');
928
- closeAssignModal();
929
- loadTokens();
930
- } else {
931
- showToast(data.detail || 'Failed to assign plan.', 'error', 'Request Failed');
932
- }
933
- } catch (err) {
934
- showToast('Error: ' + err.message, 'error', 'Network Error');
935
- }
936
  }
937
 
938
  async function revokeToken(token) {
939
  if (!confirm('Delete this token? The user will lose addon access immediately.')) return;
940
-
941
  try {
942
- const resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}`, { method: 'DELETE' });
943
- const data = await resp.json();
944
-
945
- if (resp.ok) {
946
- showToast('Token deleted.', 'success', 'Access Updated');
947
- loadTokens();
948
- } else {
949
- showToast(data.detail || 'Failed.', 'error', 'Delete Failed');
950
- }
951
- } catch (err) {
952
- showToast('Error: ' + err.message, 'error', 'Network Error');
953
- }
954
  }
955
 
956
  async function linkUser(token) {
957
  const userId = prompt('Enter the Telegram User ID to link this token to:');
958
- if (!userId || isNaN(parseInt(userId))) {
959
- showToast('Invalid user ID.', 'error', 'Invalid Input');
960
- return;
961
- }
962
-
963
  try {
964
- const resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}/link-user`, {
965
- method: 'PATCH',
966
- headers: { 'Content-Type': 'application/json' },
967
- body: JSON.stringify({ user_id: parseInt(userId) })
968
  });
 
 
 
 
969
 
970
- const data = await resp.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971
 
972
- if (resp.ok) {
973
- showToast(`Token linked to user ${userId}.`, 'success', 'User Linked');
974
- loadTokens();
 
 
 
 
 
 
 
 
975
  } else {
976
- showToast(data.detail || 'Failed to link.', 'error', 'Link Failed');
 
 
 
 
 
 
977
  }
978
- } catch (err) {
979
- showToast('Error: ' + err.message, 'error', 'Network Error');
980
- }
 
981
  }
982
 
983
- function openSubModal(userId, userName, action) {
984
- document.getElementById('sub-action-user-id').value = userId;
 
985
  document.getElementById('sub-action-action').value = action;
986
-
987
- const titles = {
988
- extend: 'Extend Subscription',
989
- reduce: 'Reduce Subscription',
990
- delete: 'Revoke Subscription'
991
- };
992
-
993
  const descs = {
994
- extend: `Add days to <b>${userName}</b>'s subscription.`,
995
- reduce: `Remove days from <b>${userName}</b>'s subscription.`,
996
- delete: `<b>Warning:</b> Revoke <b>${userName}</b>'s subscription entirely.`
997
  };
998
-
999
  document.getElementById('sub-action-title').textContent = titles[action];
1000
  document.getElementById('sub-action-desc').innerHTML = descs[action];
1001
-
1002
  const daysGroup = document.getElementById('sub-action-days-group');
1003
  const btn = document.getElementById('sub-action-btn');
1004
-
1005
- if (action === 'delete') {
1006
- daysGroup.style.display = 'none';
1007
- btn.className = 'glass-btn glass-btn-danger rounded-2xl px-5 py-3 text-sm font-bold';
1008
- } else if (action === 'reduce') {
1009
- daysGroup.style.display = 'block';
1010
- btn.className = 'glass-btn glass-btn-warning rounded-2xl px-5 py-3 text-sm font-bold';
1011
- } else {
1012
- daysGroup.style.display = 'block';
1013
- btn.className = 'glass-btn glass-btn-success rounded-2xl px-5 py-3 text-sm font-bold';
1014
- }
1015
-
1016
  document.getElementById('sub-action-days').value = 30;
1017
  openModal('sub-action-modal');
1018
  }
1019
 
1020
- function closeSubModal() {
1021
- closeModal('sub-action-modal');
1022
- }
1023
-
1024
  async function submitSubAction() {
1025
- const userId = parseInt(document.getElementById('sub-action-user-id').value);
1026
  const action = document.getElementById('sub-action-action').value;
1027
  const days = parseInt(document.getElementById('sub-action-days').value) || 0;
1028
-
1029
  try {
1030
- const resp = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
1031
- method: 'POST',
1032
- headers: { 'Content-Type': 'application/json' },
1033
- body: JSON.stringify({ action, days })
1034
- });
1035
-
1036
- const data = await resp.json();
1037
-
1038
- if (resp.ok) {
1039
- showToast(`${action.charAt(0).toUpperCase() + action.slice(1)}d subscription for user ${userId}.`, 'success', 'Subscription Updated');
1040
- closeSubModal();
1041
- loadTokens();
1042
  } else {
1043
- showToast(data.detail || 'Failed.', 'error', 'Update Failed');
 
 
 
1044
  }
1045
- } catch (err) {
1046
- showToast('Error: ' + err.message, 'error', 'Network Error');
1047
- }
 
1048
  }
1049
 
1050
  async function copyLink(url) {
1051
- try {
1052
- await navigator.clipboard.writeText(url);
1053
- showToast('Link copied!', 'success', 'Copied');
1054
- } catch {
1055
- prompt('Copy this link:', url);
1056
- }
1057
  }
1058
 
1059
- document.getElementById('assign-modal').addEventListener('click', function (e) {
1060
- if (e.target === this) closeAssignModal();
1061
  });
1062
-
1063
- document.getElementById('sub-action-modal').addEventListener('click', function (e) {
1064
- if (e.target === this) closeSubModal();
1065
- });
1066
-
1067
- document.addEventListener('keydown', function (e) {
1068
- if (e.key === 'Escape') {
1069
- closeAssignModal();
1070
- closeSubModal();
1071
- }
1072
  });
1073
 
1074
  loadPlans();
 
1
  {% extends "base.html" %}
2
+ {% block title %}Tokens & Access{% endblock %}
3
 
4
  {% block content %}
5
  <style>
6
+ .access-shell { display: flex; flex-direction: column; gap: 2rem; }
7
+ .section-panel, .stat-card, .mobile-token-card, .modal-glass { background: var(--card); border: 1px solid var(--border); }
8
+ .section-panel { border-radius: var(--radius); }
9
+ .empty-state { border-radius: var(--radius-sm); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  .section-title { color: var(--text); }
11
+ .section-muted, .text-soft { color: var(--text-sec); }
12
+
13
+ .glass-btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px !important; font-weight: 500 !important; transition: background-color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
14
+ .glass-btn:hover { background: var(--card-high); }
15
+ .glass-btn:active { transform: scale(.97); }
16
+ .glass-btn:disabled { opacity: .45; }
17
+ .glass-btn-primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
18
+ .glass-btn-primary:hover { background: var(--primary); filter: brightness(1.07); }
19
+ .glass-btn-success { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 35%, transparent); background: color-mix(in srgb, var(--ok) 10%, transparent); }
20
+ .glass-btn-warning { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
21
+ .glass-btn-danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
22
+ .glass-btn-purple, .glass-btn-gold { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 35%, transparent); background: color-mix(in srgb, var(--primary) 10%, transparent); }
23
+
24
+ .glass-input, .glass-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .7rem 1rem; outline: none; font-size: .9rem; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
25
+ .glass-input::placeholder { color: var(--text-sec); }
26
+ .glass-input:focus, .glass-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
27
+
28
+ .stats-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.5rem; padding: 1.25rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
29
+ .stat-value { font-size: 1.5rem; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
30
+ .stat-label { margin-top: .2rem; font-size: .85rem; color: var(--text-sec); }
31
+
32
+ .table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
33
+ .access-table { width: 100%; border-collapse: separate; border-spacing: 0; }
34
+ .access-table thead th { background: var(--card); color: var(--text-sec); font-size: .72rem; font-weight: 500 !important; text-transform: uppercase; letter-spacing: .08em; border-bottom: 1px solid var(--border); }
35
+ .access-table tbody tr { transition: background-color .15s var(--ease); }
36
+ .access-table tbody tr:hover { background: var(--surface); }
37
+ .access-table td { border-bottom: 1px solid var(--border); color: var(--text); vertical-align: top; }
38
+ .access-table tbody tr:last-child td { border-bottom: none; }
39
+ .row-expired { background: color-mix(in srgb, var(--danger) 5%, transparent); }
40
+
41
+ .status-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
42
+ .status-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
43
+ .status-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
44
+ .status-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
45
+ .status-lifetime { background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); }
46
+ .status-gold { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
47
+
48
+ .action-chip { display: inline-flex; align-items: center; gap: .35rem; border-radius: 9999px; padding: .35rem .75rem; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); background: transparent; color: var(--text); transition: background-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
49
+ .action-chip:hover { background: var(--card-high); }
50
+ .action-chip:active { transform: scale(.96); }
51
+ .action-chip.text-danger { color: var(--danger); }
52
+
53
+ .addon-box { padding: .7rem .8rem; border-radius: 12px; background: var(--bg); border: 1px solid var(--border); min-width: 0; overflow-wrap: anywhere; }
54
+ .usage-box { font-size: .75rem; line-height: 1.55; }
55
+
56
+ .mobile-token-card { padding: 1rem; border-radius: var(--radius-sm); min-width: 0; }
57
+ .mobile-token-card + .mobile-token-card { margin-top: .75rem; }
58
+ .mobile-grid { display: none; }
59
+
60
+ .pagination-shell { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
61
+ .pagination-text { color: var(--text-sec); }
62
+ .pagination-shell .controls { display: flex; align-items: center; gap: .5rem; }
63
+ .pagination-btn { min-width: 88px; }
64
+
65
+ .modal-backdrop { background: var(--scrim); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }
66
+ .modal-glass { border-radius: var(--radius); padding: 1.4rem; width: min(100%, 32rem); max-height: calc(100dvh - 2rem); overflow-y: auto; box-shadow: var(--shadow-strong); }
67
+ .modal-field label { color: var(--text-sec); font-size: .78rem; font-weight: 500 !important; margin-bottom: .45rem; display: block; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  .no-scrollbar::-webkit-scrollbar { display: none; }
70
+ .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
71
+
72
+ @media (max-width: 1024px) { .access-table th, .access-table td { padding-left: 1rem; padding-right: 1rem; } }
73
+ @media (max-width: 767.98px) {
74
+ .desktop-table-wrap { display: none; }
75
+ .mobile-grid { display: block; }
76
+ .section-panel { padding: 1rem; }
77
+ .stats-row { padding: 1rem; gap: 1rem; }
78
+ .pagination-shell { flex-direction: column; align-items: stretch; }
79
+ .pagination-shell .controls { width: 100%; display: grid; grid-template-columns: 1fr auto 1fr; }
80
+ .pagination-btn { width: 100%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  }
82
  </style>
83
 
84
+ <div class="access-shell">
85
+ <header class="page-head" style="margin-bottom:0">
86
+ <div>
87
+ <h1 class="page-title">Tokens</h1>
88
+ <p class="page-sub">Addon tokens, data limits, lifetime access and linked users</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  </div>
90
+ <div class="page-actions">
91
+ <button onclick="loadTokens()" class="glass-btn px-4 py-2 text-sm"><i class="fa-solid fa-rotate-right"></i> Refresh</button>
92
+ <button onclick="openCreateModal()" class="glass-btn glass-btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> New token</button>
93
  </div>
94
+ </header>
95
+
96
+ <section class="stats-row">
97
+ <div><div class="stat-value" id="stat-total">–</div><div class="stat-label">Total</div></div>
98
+ <div><div class="stat-value" style="color: var(--ok);" id="stat-active">–</div><div class="stat-label">Active</div></div>
99
+ <div><div class="stat-value" style="color: var(--danger);" id="stat-expired">–</div><div class="stat-label">Expired</div></div>
100
  </section>
101
 
102
+ <section class="section-panel p-5">
103
  <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
104
  <div>
105
+ <h2 class="text-lg font-semibold section-title">All tokens</h2>
106
+ <p class="text-sm section-muted mt-1">Search, filter, and manage every token and its access.</p>
107
  </div>
108
 
109
  <div class="w-full lg:w-auto grid grid-cols-1 sm:grid-cols-3 gap-3">
110
+ <input id="search-input" type="text" data-shortcut-search placeholder="Search by name or user ID..." class="glass-input" oninput="currentPage=1; renderPage()">
 
 
 
 
 
 
111
  <select id="filter-status" class="glass-select" onchange="currentPage=1; renderPage()">
112
  <option value="all">All Status</option>
113
  <option value="active">Active</option>
 
122
  </div>
123
 
124
  <div class="desktop-table-wrap table-shell">
125
+ <div class="overflow-x-auto">
126
+ <table class="access-table min-w-[980px] text-sm">
127
  <thead>
128
  <tr>
129
  <th class="px-4 py-4 text-left font-semibold">Status</th>
130
  <th class="px-4 py-4 text-left font-semibold">User</th>
131
  <th class="px-4 py-4 text-left font-semibold">Addon Link</th>
132
+ <th class="px-4 py-4 text-left font-semibold">Usage / Limits</th>
133
  <th class="px-4 py-4 text-left font-semibold">Expires</th>
134
+ <th class="px-4 py-4 text-right font-semibold">Actions</th>
135
  </tr>
136
  </thead>
137
  <tbody id="token-table-body">
138
+ <tr><td colspan="6" class="text-center py-10 text-soft">Loading tokens…</td></tr>
 
 
139
  </tbody>
140
  </table>
141
  </div>
 
148
  <div class="pagination-shell mt-5" id="pagination-bar">
149
  <div id="page-info" class="pagination-text text-sm"></div>
150
  <div class="controls">
151
+ <button id="btn-prev" onclick="changePage(-1)" class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold"><i class="fa-solid fa-chevron-left text-xs"></i> Prev</button>
152
+ <span id="page-num" class="text-sm font-semibold text-center section-title px-2"></span>
153
+ <button id="btn-next" onclick="changePage(1)" class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">Next <i class="fa-solid fa-chevron-right text-xs"></i></button>
 
 
 
 
 
 
154
  </div>
155
  </div>
156
  </section>
157
  </div>
158
 
159
+ <!-- Create Token Modal -->
160
+ <div id="create-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
161
+ <div class="modal-glass">
162
+ <div class="flex items-start justify-between gap-4 mb-5">
163
+ <div>
164
+ <h3 class="text-xl font-semibold section-title">Create Token</h3>
165
+ <p class="text-sm text-soft mt-1">Generate a new Stremio addon token.</p>
166
+ </div>
167
+ <button onclick="closeModal('create-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
168
+ </div>
169
+
170
+ <div class="space-y-4">
171
+ <div class="modal-field">
172
+ <label>Token Name</label>
173
+ <input type="text" id="create-name" placeholder="e.g. Living Room TV" class="glass-input">
174
+ </div>
175
+ <div class="grid grid-cols-2 gap-3">
176
+ <div class="modal-field">
177
+ <label>Daily Limit (GB)</label>
178
+ <input type="number" id="create-daily" value="0" min="0" step="0.1" class="glass-input">
179
+ </div>
180
+ <div class="modal-field">
181
+ <label>Monthly Limit (GB)</label>
182
+ <input type="number" id="create-monthly" value="0" min="0" step="0.1" class="glass-input">
183
+ </div>
184
+ </div>
185
+ <label class="flex items-center gap-3 text-sm section-title cursor-pointer">
186
+ <input type="checkbox" id="create-lifetime" class="w-4 h-4" checked>
187
+ Never expires <span class="text-soft text-xs">(no expiry date; works even when subscription mode is ON)</span>
188
+ </label>
189
+ </div>
190
+
191
+ <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
192
+ <button onclick="closeModal('create-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
193
+ <button onclick="createToken()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Create Token</button>
194
+ </div>
195
+ </div>
196
+ </div>
197
+
198
+ <div id="cf-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
199
+ <div class="modal-glass">
200
+ <div class="flex items-start justify-between gap-4 mb-5">
201
+ <div>
202
+ <h3 class="text-xl font-semibold section-title">Cloudflare Proxy</h3>
203
+ <p class="text-sm text-soft mt-1">Worker for this user's own bots. Leave empty to turn it off.</p>
204
+ </div>
205
+ <button onclick="closeModal('cf-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
206
+ </div>
207
+ <input type="hidden" id="cf-token">
208
+ <div class="grid grid-cols-1 gap-3">
209
+ <div class="modal-field">
210
+ <label>Worker URL</label>
211
+ <input type="url" id="cf-url" placeholder="https://telestream-user.workers.dev" class="glass-input" spellcheck="false">
212
+ </div>
213
+ <div class="modal-field">
214
+ <label>Shared Secret</label>
215
+ <input type="text" id="cf-secret" class="glass-input" spellcheck="false">
216
+ </div>
217
+ </div>
218
+ <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
219
+ <button onclick="closeModal('cf-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
220
+ <button onclick="saveCf()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Save</button>
221
+ </div>
222
+ </div>
223
+ </div>
224
+
225
+ <!-- Edit Limits Modal -->
226
+ <div id="limits-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
227
+ <div class="modal-glass">
228
+ <div class="flex items-start justify-between gap-4 mb-5">
229
+ <div>
230
+ <h3 class="text-xl font-semibold section-title">Edit Data Limits</h3>
231
+ <p class="text-sm text-soft mt-1">Set 0 for unlimited.</p>
232
+ </div>
233
+ <button onclick="closeModal('limits-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
234
+ </div>
235
+ <input type="hidden" id="limits-token">
236
+ <div class="grid grid-cols-2 gap-3">
237
+ <div class="modal-field">
238
+ <label>Daily (GB)</label>
239
+ <input type="number" id="limits-daily" min="0" step="0.1" class="glass-input">
240
+ </div>
241
+ <div class="modal-field">
242
+ <label>Monthly (GB)</label>
243
+ <input type="number" id="limits-monthly" min="0" step="0.1" class="glass-input">
244
+ </div>
245
+ </div>
246
+ <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
247
+ <button onclick="closeModal('limits-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
248
+ <button onclick="saveLimits()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Save</button>
249
+ </div>
250
+ </div>
251
+ </div>
252
+
253
+ <!-- Assign Plan Modal -->
254
  <div id="assign-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
255
  <div class="modal-glass">
256
  <div class="flex items-start justify-between gap-4 mb-5">
257
  <div>
258
+ <h3 class="text-xl font-semibold section-title" id="assign-modal-title">Assign Subscription Plan</h3>
259
  <p class="text-sm text-soft mt-1" id="assign-user-label">User: –</p>
260
  </div>
261
+ <button onclick="closeModal('assign-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
 
 
262
  </div>
 
263
  <input type="hidden" id="assign-user-id">
264
+ <input type="hidden" id="assign-token">
265
  <div class="space-y-4">
266
+ <div class="modal-field" id="assign-plan-field">
267
  <label>Select a Plan</label>
268
+ <select id="assign-plan-select" class="glass-select"><option value="">— Select plan —</option></select>
 
 
269
  </div>
 
270
  <div class="modal-field">
271
+ <label id="assign-days-label">Or enter custom days</label>
272
  <input type="number" id="assign-custom-days" placeholder="e.g. 30" min="1" class="glass-input">
273
+ <p class="text-xs text-soft mt-2" id="assign-days-hint">Custom days override selected plan.</p>
274
+ </div>
275
+ <div class="modal-field" id="assign-userid-field" style="display:none">
276
+ <label>Link Telegram User ID <span class="text-soft text-xs">(optional)</span></label>
277
+ <input type="number" id="assign-userid" placeholder="e.g. 123456789" class="glass-input">
278
+ <p class="text-xs text-soft mt-2">Attaches this token to a user so it's reused when they press /start.</p>
279
  </div>
280
  </div>
 
281
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
282
+ <button onclick="closeModal('assign-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
283
+ <button onclick="assignPlan()" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">Assign &amp; Activate</button>
 
 
 
 
284
  </div>
285
  </div>
286
  </div>
287
 
288
+ <!-- Sub Action Modal -->
289
  <div id="sub-action-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
290
  <div class="modal-glass">
291
  <div class="flex items-start justify-between gap-4 mb-5">
292
  <div>
293
+ <h3 class="text-xl font-semibold section-title" id="sub-action-title">Manage Subscription</h3>
294
  <p class="text-sm text-soft mt-1" id="sub-action-desc"></p>
295
  </div>
296
+ <button onclick="closeModal('sub-action-modal')" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center"><i class="fas fa-xmark"></i></button>
 
 
297
  </div>
 
298
  <input type="hidden" id="sub-action-user-id">
299
+ <input type="hidden" id="sub-action-token">
300
  <input type="hidden" id="sub-action-action">
 
301
  <div id="sub-action-days-group" class="modal-field">
302
  <label>Number of Days</label>
303
  <input type="number" id="sub-action-days" value="30" min="1" class="glass-input">
304
  </div>
 
305
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6">
306
+ <button onclick="closeModal('sub-action-modal')" class="glass-btn px-4 py-2 text-sm font-semibold">Cancel</button>
307
+ <button id="sub-action-btn" onclick="submitSubAction()" class="glass-btn glass-btn-success px-4 py-2 text-sm font-semibold">Confirm</button>
 
 
 
 
 
308
  </div>
309
  </div>
310
  </div>
 
312
  <script>
313
  let allTokens = [];
314
  let currentPage = 1;
315
+ let subEnabled = true;
316
 
317
  function fmtDate(iso) {
318
  if (!iso) return '—';
319
  const d = new Date(iso);
320
+ return d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', day: '2-digit', month: 'short', year: 'numeric' }) +
321
+ ' ' + d.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour: '2-digit', minute: '2-digit' });
 
 
 
 
 
 
 
 
322
  }
323
 
324
  function escHtml(s) {
325
+ return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
326
+ }
327
+
328
+ function fmtBytes(bytes) {
329
+ const v = Number(bytes || 0);
330
+ if (!v) return '0 B';
331
+ const u = ['B', 'KB', 'MB', 'GB', 'TB'];
332
+ const i = Math.min(Math.floor(Math.log(v) / Math.log(1024)), u.length - 1);
333
+ return (v / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 2) + ' ' + u[i];
334
  }
335
 
336
  function getFiltered() {
337
  const q = document.getElementById('search-input').value.toLowerCase().trim();
338
  const status = document.getElementById('filter-status').value;
 
339
  return allTokens.filter(t => {
340
+ const matchQ = !q || (t.user_name && t.user_name.toLowerCase().includes(q)) || (t.user_id && String(t.user_id).includes(q));
341
+ const matchStatus = status === 'all' || (status === 'active' && !t.is_expired) || (status === 'expired' && t.is_expired);
 
 
 
 
 
 
 
342
  return matchQ && matchStatus;
343
  });
344
  }
345
 
346
+ function statusBadge(t) {
347
+ if (t.is_admin) return `<span class="status-badge status-gold"><i class="fas fa-crown text-[8px]"></i> Owner</span>`;
348
  return t.is_expired
349
  ? `<span class="status-badge status-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>`
350
  : `<span class="status-badge status-active"><i class="fas fa-circle text-[8px]"></i> Active</span>`;
351
  }
352
 
353
+ function addonHtml(t) {
354
+ if (!t.has_token) return `<div class="addon-box"><span class="status-badge status-warning">No Token</span></div>`;
355
+ if (t.is_expired && !t.never_expires && !t.is_admin) {
356
+ return `<div class="addon-box">
357
+ <span class="status-badge status-expired">Expired</span>
358
+ ${t.addon_url ? `<button onclick="copyLink('${escHtml(t.addon_url)}')" class="mt-3 text-xs font-semibold underline opacity-70 hover:opacity-100 transition">Copy URL (admin)</button>` : ''}
359
+ </div>`;
 
360
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  return t.addon_url
362
+ ? `<button onclick="copyLink('${escHtml(t.addon_url)}')" class="action-chip"><i class="fa-solid fa-link"></i> Copy install link</button>`
 
 
 
 
 
 
 
 
363
  : `<div class="addon-box text-soft text-xs">—</div>`;
364
  }
365
 
366
+ function ownBotsHtml(t) {
367
+ if (!t.own_bots) return '';
368
+ const names = t.own_bots.bots.map(b => '@' + (b.username || b.id)).join(', ');
369
+ return `<div class="flex flex-wrap gap-1.5 mt-2">
370
+ <span class="status-badge status-active" title="Channel ${escHtml(t.own_bots.channel)}"><i class="fa-solid fa-robot text-[10px]"></i> ${t.own_bots.bots.length} own bot${t.own_bots.bots.length === 1 ? '' : 's'}</span>
371
+ ${t.cf_url ? `<span class="status-badge status-gold"><i class="fa-solid fa-cloud text-[10px]"></i> Cloudflare</span>` : ''}
372
+ </div>
373
+ <div class="text-xs text-soft mt-1 break-all">${escHtml(names)}</div>`;
374
+ }
375
+
376
+ function usageHtml(t) {
377
+ const dl = t.daily_limit_gb ? t.daily_limit_gb + ' GB' : '∞';
378
+ const ml = t.monthly_limit_gb ? t.monthly_limit_gb + ' GB' : '∞';
379
+ return `<div class="usage-box text-soft">
380
+ <div><span class="section-title font-semibold">Day:</span> ${fmtBytes(t.daily_bytes)} / ${dl}</div>
381
+ <div><span class="section-title font-semibold">Mon:</span> ${fmtBytes(t.monthly_bytes)} / ${ml}</div>
382
+ </div>`;
383
+ }
384
+
385
+ function expiryHtml(t) {
386
+ if (t.never_expires) return `<span class="text-green-300 font-semibold">Never expires</span>`;
387
+ if (t.expires_at) return `<span class="${t.is_expired ? 'text-red-300 font-semibold' : 'section-title'}">${fmtDate(t.expires_at)}</span>`;
388
+ return `<span class="text-soft italic">—</span>`;
389
+ }
390
+
391
  function buildActions(t) {
392
  const safeName = escHtml(t.user_name || String(t.user_id || ''));
393
+ let btns = '';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
 
395
+ const tokenArg = t.token ? escHtml(t.token) : '';
 
 
 
 
396
 
397
+ if (t.has_token) {
398
+ btns += `<button onclick="openLimitsModal('${tokenArg}', ${t.daily_limit_gb || 0}, ${t.monthly_limit_gb || 0})" class="action-chip glass-btn">Limits</button>`;
399
+ }
400
+ if (t.own_bots) btns += `<button onclick="openCfModal('${tokenArg}')" class="action-chip"><i class="fa-solid fa-cloud"></i> Cloudflare</button>`;
401
+
402
+ if (subEnabled) {
403
+ if (t.user_id) {
404
+ btns += `<button onclick="openAssignModal(${t.user_id}, '${safeName}', '')" class="action-chip">Assign</button>`;
405
+ btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'extend', '')" class="action-chip">Extend</button>`;
406
+ btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'reduce', '')" class="action-chip">Reduce</button>`;
407
+ btns += `<button onclick="openSubModal(${t.user_id}, '${safeName}', 'delete', '')" class="action-chip text-danger">Revoke</button>`;
408
+ } else if (t.token) {
409
+ btns += `<button onclick="linkUser('${tokenArg}')" class="action-chip">Link User</button>`;
410
+ }
411
+ } else if (t.has_token) {
412
+ btns += `<button onclick="openAssignModal(${t.user_id || null}, '${safeName}', '${tokenArg}')" class="action-chip">Set Expiry</button>`;
413
+ btns += `<button onclick="openSubModal(${t.user_id || null}, '${safeName}', 'extend', '${tokenArg}')" class="action-chip">Extend</button>`;
414
+ btns += `<button onclick="openSubModal(${t.user_id || null}, '${safeName}', 'reduce', '${tokenArg}')" class="action-chip">Reduce</button>`;
415
+ if (!t.user_id) btns += `<button onclick="linkUser('${tokenArg}')" class="action-chip">Link User</button>`;
416
+ }
417
+
418
+ if (t.token) btns += `<button onclick="revokeToken('${tokenArg}')" class="action-chip text-danger">Delete</button>`;
419
+ return btns;
420
  }
421
 
422
  function renderDesktopRows(slice) {
423
  const tbody = document.getElementById('token-table-body');
424
+ if (!slice.length) { tbody.innerHTML = `<tr><td colspan="6" class="text-center py-10 text-soft">No tokens match your search.</td></tr>`; return; }
 
 
 
 
 
 
 
 
425
 
426
  tbody.innerHTML = slice.map(t => {
427
+ const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Web Token');
428
+ const idHtml = t.user_id ? `<div class="text-xs text-soft mt-1">ID: ${t.user_id}</div>` : `<div class="text-xs text-soft mt-1">No linked user</div>`;
 
 
429
  return `
430
+ <tr class="${t.is_expired ? 'row-expired' : ''}">
431
+ <td class="px-4 py-4">${statusBadge(t)}</td>
432
+ <td class="px-4 py-4"><div class="font-semibold section-title">${escHtml(displayName)}</div>${idHtml}${ownBotsHtml(t)}</td>
433
+ <td class="px-4 py-4">${addonHtml(t)}</td>
434
+ <td class="px-4 py-4">${usageHtml(t)}</td>
435
+ <td class="px-4 py-4 text-xs">${expiryHtml(t)}</td>
436
+ <td class="px-4 py-4" style="width:300px"><div class="flex flex-wrap gap-1.5 justify-end">${buildActions(t)}</div></td>
437
+ </tr>`;
 
 
 
 
 
 
 
 
 
 
 
438
  }).join('');
439
  }
440
 
441
  function renderMobileCards(slice) {
442
+ const wrap = document.getElementById('token-mobile-list');
443
+ if (!slice.length) { wrap.innerHTML = `<div class="empty-state text-center px-4 py-8 text-soft">No tokens match your search.</div>`; return; }
 
 
 
 
 
 
 
 
 
 
 
444
 
445
+ wrap.innerHTML = slice.map(t => {
446
+ const displayName = t.user_name || (t.user_id ? 'Telegram User' : 'Web Token');
447
  return `
448
  <div class="mobile-token-card ${t.is_expired ? 'row-expired' : ''}">
449
  <div class="flex items-start justify-between gap-3 mb-3">
450
  <div class="min-w-0">
451
  <div class="font-semibold section-title break-words">${escHtml(displayName)}</div>
452
+ <div class="text-xs text-soft mt-1 break-all">${t.user_id ? 'ID: ' + t.user_id : 'No linked user'}</div>${ownBotsHtml(t)}
453
  </div>
454
+ <div class="shrink-0">${statusBadge(t)}</div>
455
  </div>
 
456
  <div class="grid grid-cols-1 gap-3 mb-3">
457
+ <div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
458
+ <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Addon Access</div>${addonHtml(t)}
 
 
459
  </div>
 
460
  <div class="grid grid-cols-2 gap-3">
461
+ <div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
462
+ <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Usage / Limits</div>${usageHtml(t)}
 
 
463
  </div>
464
+ <div class="rounded-2xl px-4 py-3" style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
465
+ <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Expires</div>
 
466
  <div class="text-sm font-semibold ${t.is_expired ? 'text-red-300' : 'section-title'} break-words">
467
+ ${t.never_expires ? 'Never expires' : (t.expires_at ? fmtDate(t.expires_at) : '—')}
468
  </div>
469
  </div>
470
  </div>
471
  </div>
472
+ <div class="flex flex-wrap gap-2">${buildActions(t)}</div>
473
+ </div>`;
 
 
 
 
474
  }).join('');
475
  }
476
 
 
478
  const filtered = getFiltered();
479
  const pageSize = parseInt(document.getElementById('page-size').value);
480
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
 
481
  if (currentPage > totalPages) currentPage = totalPages;
 
482
  const start = filtered.length ? (currentPage - 1) * pageSize : 0;
483
  const slice = filtered.slice(start, start + pageSize);
484
 
485
+ document.getElementById('page-info').textContent = filtered.length
486
+ ? `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}` : 'Showing 0 of 0';
 
 
 
487
  document.getElementById('page-num').textContent = `Page ${currentPage} / ${totalPages}`;
488
 
489
+ const prevBtn = document.getElementById('btn-prev'), nextBtn = document.getElementById('btn-next');
490
+ prevBtn.disabled = currentPage <= 1; nextBtn.disabled = currentPage >= totalPages;
491
+ prevBtn.style.opacity = currentPage <= 1 ? '0.45' : '1'; nextBtn.style.opacity = currentPage >= totalPages ? '0.45' : '1';
 
 
 
 
 
492
 
493
  renderDesktopRows(slice);
494
  renderMobileCards(slice);
 
498
  const filtered = getFiltered();
499
  const pageSize = parseInt(document.getElementById('page-size').value);
500
  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
501
+ currentPage = Math.min(Math.max(1, currentPage + dir), totalPages);
 
 
 
 
502
  renderPage();
503
  }
504
 
505
  async function loadTokens() {
506
+ document.getElementById('token-table-body').innerHTML = `<tr><td colspan="6" class="text-center py-10 text-soft">Loading…</td></tr>`;
 
 
 
 
 
 
507
  try {
508
  const resp = await fetch('/api/admin/access/tokens');
509
  const data = await resp.json();
510
  allTokens = data.tokens || [];
511
+ subEnabled = !!data.subscription;
512
  document.getElementById('stat-total').textContent = allTokens.length;
513
  document.getElementById('stat-active').textContent = allTokens.filter(t => !t.is_expired).length;
514
  document.getElementById('stat-expired').textContent = allTokens.filter(t => t.is_expired).length;
 
515
  currentPage = 1;
516
  renderPage();
517
  } catch (err) {
518
+ document.getElementById('token-table-body').innerHTML = `<tr><td colspan="6" class="text-center py-10 text-red-300">Error: ${err.message}</td></tr>`;
 
 
 
 
 
519
  showToast('Failed to load access tokens.', 'error', 'Load Error');
520
  }
521
  }
522
 
523
  async function loadPlans() {
524
+ try {
525
+ const resp = await fetch('/api/admin/subscriptions/plans');
526
+ if (!resp.ok) return;
527
+ const result = await resp.json();
528
+ const plans = result.data || [];
529
+ const sel = document.getElementById('assign-plan-select');
530
+ if (!sel) return;
531
+ sel.innerHTML = '<option value="">— Select a plan —</option>' +
532
+ plans.map(p => { const sym = ({INR:'₹',USD:'$',EUR:'€',GBP:'£',JPY:'¥',AUD:'A$',CAD:'C$',SGD:'S$',AED:'د.إ',BRL:'R$'}[(p.currency||'INR').toUpperCase()]||((p.currency||'INR')+' ')); return `<option value="${p.days}">${p.days} days${p.price != null ? ' — ' + sym + p.price : ''}</option>`; }).join('');
533
+ } catch (e) { /* ignore */ }
534
+ }
535
+
536
+ function openModal(id) {
537
+ const m = document.getElementById(id);
538
+ m.classList.remove('hidden'); m.classList.add('flex');
 
 
 
 
 
 
 
 
539
  document.body.classList.add('overflow-hidden');
540
  }
541
+ function closeModal(id) {
542
+ const m = document.getElementById(id);
543
+ m.classList.add('hidden'); m.classList.remove('flex');
 
 
544
  document.body.classList.remove('overflow-hidden');
545
  }
546
 
547
+ function openCreateModal() {
548
+ document.getElementById('create-name').value = '';
549
+ document.getElementById('create-daily').value = 0;
550
+ document.getElementById('create-monthly').value = 0;
551
+ document.getElementById('create-lifetime').checked = true;
552
+ openModal('create-modal');
553
  }
554
 
555
+ async function createToken() {
556
+ const name = document.getElementById('create-name').value.trim();
557
+ if (!name) { showToast('Token name is required.', 'error', 'Validation'); return; }
558
+ const payload = {
559
+ name,
560
+ daily_limit_gb: Number(document.getElementById('create-daily').value || 0),
561
+ monthly_limit_gb: Number(document.getElementById('create-monthly').value || 0),
562
+ subscription_exempt: document.getElementById('create-lifetime').checked,
563
+ };
564
+ try {
565
+ const resp = await fetch('/api/tokens', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
566
+ if (resp.ok) { showToast('Token created.', 'success', 'Created'); closeModal('create-modal'); loadTokens(); }
567
+ else { const d = await resp.json(); showToast(d.detail || 'Failed to create token.', 'error', 'Failed'); }
568
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
569
  }
570
 
571
+ function openLimitsModal(token, daily, monthly) {
572
+ document.getElementById('limits-token').value = token;
573
+ document.getElementById('limits-daily').value = daily || 0;
574
+ document.getElementById('limits-monthly').value = monthly || 0;
575
+ openModal('limits-modal');
576
+ }
 
 
 
 
577
 
578
+ async function saveLimits() {
579
+ const token = document.getElementById('limits-token').value;
580
+ const payload = {
581
+ daily_limit_gb: Number(document.getElementById('limits-daily').value || 0),
582
+ monthly_limit_gb: Number(document.getElementById('limits-monthly').value || 0),
583
+ };
584
  try {
585
+ const resp = await fetch('/api/tokens/' + encodeURIComponent(token), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
586
+ if (resp.ok) { showToast('Limits updated.', 'success', 'Updated'); closeModal('limits-modal'); loadTokens(); }
587
+ else { showToast('Failed to update limits.', 'error', 'Failed'); }
588
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
589
+ }
590
 
591
+ function openCfModal(token) {
592
+ const t = allTokens.find(x => x.token === token) || {};
593
+ document.getElementById('cf-token').value = token;
594
+ document.getElementById('cf-url').value = t.cf_url || '';
595
+ document.getElementById('cf-secret').value = t.cf_secret || '';
596
+ openModal('cf-modal');
597
+ }
598
 
599
+ async function saveCf() {
600
+ const token = document.getElementById('cf-token').value;
601
+ const payload = { cf_url: document.getElementById('cf-url').value.trim(), cf_secret: document.getElementById('cf-secret').value.trim() };
602
+ try {
603
+ const resp = await fetch('/api/tokens/' + encodeURIComponent(token) + '/cf', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
604
+ if (resp.ok) { showToast('Cloudflare proxy saved.', 'success', 'Updated'); closeModal('cf-modal'); loadTokens(); }
605
+ else { showToast((await resp.json().catch(() => ({}))).detail || 'Failed to save.', 'error', 'Failed'); }
606
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
 
 
607
  }
608
 
609
  async function revokeToken(token) {
610
  if (!confirm('Delete this token? The user will lose addon access immediately.')) return;
 
611
  try {
612
+ const resp = await fetch('/api/admin/access/tokens/' + encodeURIComponent(token), { method: 'DELETE' });
613
+ if (resp.ok) { showToast('Token deleted.', 'success', 'Access Updated'); loadTokens(); }
614
+ else { const d = await resp.json(); showToast(d.detail || 'Failed.', 'error', 'Delete Failed'); }
615
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
 
 
 
 
 
 
 
 
616
  }
617
 
618
  async function linkUser(token) {
619
  const userId = prompt('Enter the Telegram User ID to link this token to:');
620
+ if (!userId || isNaN(parseInt(userId))) { showToast('Invalid user ID.', 'error', 'Invalid Input'); return; }
 
 
 
 
621
  try {
622
+ const resp = await fetch('/api/admin/access/tokens/' + encodeURIComponent(token) + '/link-user', {
623
+ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: parseInt(userId) }),
 
 
624
  });
625
+ if (resp.ok) { showToast(`Token linked to user ${userId}.`, 'success', 'User Linked'); loadTokens(); }
626
+ else { const d = await resp.json(); showToast(d.detail || 'Failed to link.', 'error', 'Link Failed'); }
627
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
628
+ }
629
 
630
+ function openAssignModal(userId, userName, token) {
631
+ document.getElementById('assign-user-id').value = userId || '';
632
+ document.getElementById('assign-token').value = token || '';
633
+ document.getElementById('assign-user-label').textContent = userId ? `User: ${userName} (ID: ${userId})` : `Token: ${userName}`;
634
+ document.getElementById('assign-custom-days').value = '';
635
+ document.getElementById('assign-plan-select').value = '';
636
+
637
+ //----- With subscription off there are no plans — just set an expiry
638
+ document.getElementById('assign-plan-field').style.display = subEnabled ? '' : 'none';
639
+ document.getElementById('assign-modal-title').textContent = subEnabled ? 'Assign Subscription Plan' : 'Set Expiry';
640
+ document.getElementById('assign-days-label').textContent = subEnabled ? 'Or enter custom days' : 'Expires in (days)';
641
+ document.getElementById('assign-days-hint').textContent = subEnabled
642
+ ? 'Custom days override the selected plan. Leave empty or 0 for never expires.'
643
+ : 'Leave empty or 0 for never expires.';
644
+
645
+ const uidField = document.getElementById('assign-userid-field');
646
+ uidField.style.display = subEnabled ? 'none' : '';
647
+ document.getElementById('assign-userid').value = (!subEnabled && userId) ? userId : '';
648
+ openModal('assign-modal');
649
+ }
650
 
651
+ async function assignPlan() {
652
+ const customDays = parseInt(document.getElementById('assign-custom-days').value) || 0;
653
+ const planDays = parseInt(document.getElementById('assign-plan-select').value) || 0;
654
+ const days = customDays || planDays; // 0 = never expires
655
+ try {
656
+ let resp;
657
+ if (subEnabled) {
658
+ const userId = parseInt(document.getElementById('assign-user-id').value);
659
+ resp = await fetch(`/api/admin/access/users/${userId}/assign-plan`, {
660
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days }),
661
+ });
662
  } else {
663
+ const token = document.getElementById('assign-token').value;
664
+ const uid = parseInt(document.getElementById('assign-userid').value) || 0;
665
+ const body = { action: 'set', days };
666
+ if (uid) body.user_id = uid;
667
+ resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}/expiry`, {
668
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
669
+ });
670
  }
671
+ const data = await resp.json();
672
+ if (resp.ok) { showToast(days > 0 ? `Expiry set: ${days} days.` : 'Set to never expire.', 'success', 'Updated'); closeModal('assign-modal'); loadTokens(); }
673
+ else { showToast(data.detail || 'Failed to update.', 'error', 'Request Failed'); }
674
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
675
  }
676
 
677
+ function openSubModal(userId, userName, action, token) {
678
+ document.getElementById('sub-action-user-id').value = userId || '';
679
+ document.getElementById('sub-action-token').value = token || '';
680
  document.getElementById('sub-action-action').value = action;
681
+ const noun = subEnabled ? 'Subscription' : 'Expiry';
682
+ const thing = subEnabled ? 'subscription' : 'access';
683
+ const titles = { extend: `Extend ${noun}`, reduce: `Reduce ${noun}`, delete: 'Revoke Subscription' };
 
 
 
 
684
  const descs = {
685
+ extend: `Add days to <b>${userName}</b>'s ${thing}.`,
686
+ reduce: `Remove days from <b>${userName}</b>'s ${thing}.`,
687
+ delete: `<b>Warning:</b> Revoke <b>${userName}</b>'s subscription entirely.`,
688
  };
 
689
  document.getElementById('sub-action-title').textContent = titles[action];
690
  document.getElementById('sub-action-desc').innerHTML = descs[action];
 
691
  const daysGroup = document.getElementById('sub-action-days-group');
692
  const btn = document.getElementById('sub-action-btn');
693
+ if (action === 'delete') { daysGroup.style.display = 'none'; btn.className = 'glass-btn glass-btn-danger px-4 py-2 text-sm font-semibold'; }
694
+ else if (action === 'reduce') { daysGroup.style.display = 'block'; btn.className = 'glass-btn glass-btn-warning px-4 py-2 text-sm font-semibold'; }
695
+ else { daysGroup.style.display = 'block'; btn.className = 'glass-btn glass-btn-success px-4 py-2 text-sm font-semibold'; }
 
 
 
 
 
 
 
 
 
696
  document.getElementById('sub-action-days').value = 30;
697
  openModal('sub-action-modal');
698
  }
699
 
 
 
 
 
700
  async function submitSubAction() {
 
701
  const action = document.getElementById('sub-action-action').value;
702
  const days = parseInt(document.getElementById('sub-action-days').value) || 0;
 
703
  try {
704
+ let resp;
705
+ if (subEnabled) {
706
+ const userId = parseInt(document.getElementById('sub-action-user-id').value);
707
+ resp = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
708
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, days }),
709
+ });
 
 
 
 
 
 
710
  } else {
711
+ const token = document.getElementById('sub-action-token').value;
712
+ resp = await fetch(`/api/admin/access/tokens/${encodeURIComponent(token)}/expiry`, {
713
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, days }),
714
+ });
715
  }
716
+ const data = await resp.json();
717
+ if (resp.ok) { showToast('Updated.', 'success', 'Updated'); closeModal('sub-action-modal'); loadTokens(); }
718
+ else { showToast(data.detail || 'Failed.', 'error', 'Update Failed'); }
719
+ } catch (err) { showToast('Error: ' + err.message, 'error', 'Network Error'); }
720
  }
721
 
722
  async function copyLink(url) {
723
+ try { await navigator.clipboard.writeText(url); showToast('Link copied!', 'success', 'Copied'); }
724
+ catch { prompt('Copy this link:', url); }
 
 
 
 
725
  }
726
 
727
+ ['create-modal', 'limits-modal', 'cf-modal', 'assign-modal', 'sub-action-modal'].forEach(id => {
728
+ document.getElementById(id).addEventListener('click', function (e) { if (e.target === this) closeModal(id); });
729
  });
730
+ document.addEventListener('keydown', e => {
731
+ if (e.key === 'Escape') ['create-modal', 'limits-modal', 'cf-modal', 'assign-modal', 'sub-action-modal'].forEach(closeModal);
 
 
 
 
 
 
 
 
732
  });
733
 
734
  loadPlans();
Backend/fastapi/templates/admin_dashboard.html CHANGED
@@ -4,337 +4,171 @@
4
 
5
  {% block content %}
6
  <style>
7
- .glass-card {
8
- background: color-mix(in srgb, var(--card) 94%, var(--bg));
9
- border: 1px solid color-mix(in srgb, var(--border) 95%, transparent);
10
- box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
11
- }
12
-
13
- .glass-card-soft {
14
- background: color-mix(in srgb, var(--card) 86%, var(--bg));
15
- border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
16
- }
17
-
18
- .section-title {
19
- color: var(--text);
20
- font-weight: 800;
21
- letter-spacing: -0.02em;
22
- }
23
-
24
- .muted {
25
- color: var(--text-sec);
26
- }
27
-
28
- .pill {
29
- display: inline-flex;
30
- align-items: center;
31
- gap: 0.45rem;
32
- padding: 0.45rem 0.85rem;
33
- border-radius: 9999px;
34
- font-size: 0.82rem;
35
- font-weight: 800;
36
- border: 1px solid color-mix(in srgb, var(--border) 82%, transparent);
37
- background: color-mix(in srgb, var(--bg) 66%, transparent);
38
- color: var(--text);
39
- white-space: nowrap;
40
- }
41
-
42
- .metric-card {
43
- position: relative;
44
- overflow: hidden;
45
- }
46
-
47
- .metric-card::before {
48
- content: "";
49
- position: absolute;
50
- inset: -30% auto auto -10%;
51
- width: 140px;
52
- height: 140px;
53
- border-radius: 9999px;
54
- background: color-mix(in srgb, var(--primary) 12%, transparent);
55
- filter: blur(18px);
56
- pointer-events: none;
57
- }
58
-
59
- .metric-icon {
60
- width: 3.25rem;
61
- height: 3.25rem;
62
- border-radius: 1.1rem;
63
- display: flex;
64
- align-items: center;
65
- justify-content: center;
66
- background: color-mix(in srgb, var(--primary) 14%, transparent);
67
- color: var(--primary);
68
- border: 1px solid color-mix(in srgb, var(--primary) 18%, transparent);
69
- box-shadow: inset 0 1px 0 rgba(255,255,255,.04);
70
- }
71
-
72
- .btn-ui {
73
- display: inline-flex;
74
- align-items: center;
75
- justify-content: center;
76
- gap: 0.55rem;
77
- border-radius: 1rem;
78
- padding: 0.82rem 1.1rem;
79
- font-size: 0.92rem;
80
- font-weight: 800;
81
- transition: all 0.2s ease;
82
- border: 1px solid transparent;
83
- white-space: nowrap;
84
- }
85
-
86
- .btn-ui:hover { transform: translateY(-1px); }
87
-
88
- .btn-danger {
89
- background: color-mix(in srgb, rgb(239 68 68) 16%, transparent);
90
- color: rgb(248 113 113);
91
- border-color: color-mix(in srgb, rgb(239 68 68) 26%, transparent);
92
- }
93
-
94
- .btn-primary {
95
- background: var(--primary);
96
- color: white;
97
- box-shadow: 0 10px 24px color-mix(in srgb, var(--primary) 26%, transparent);
98
- }
99
-
100
- .btn-ghost {
101
- background: color-mix(in srgb, var(--bg) 74%, transparent);
102
- color: var(--text);
103
- border-color: color-mix(in srgb, var(--border) 95%, transparent);
104
- }
105
-
106
- .workload-row,
107
- .table-row-card {
108
- background: color-mix(in srgb, var(--bg) 68%, transparent);
109
- border: 1px solid color-mix(in srgb, var(--border) 90%, transparent);
110
- }
111
-
112
- .status-badge {
113
- display: inline-flex;
114
- align-items: center;
115
- gap: 0.35rem;
116
- padding: 0.35rem 0.65rem;
117
- border-radius: 9999px;
118
- font-size: 0.72rem;
119
- font-weight: 800;
120
- letter-spacing: .05em;
121
- text-transform: uppercase;
122
- }
123
-
124
- .status-good {
125
- background: color-mix(in srgb, rgb(34 197 94) 16%, transparent);
126
- color: rgb(74 222 128);
127
- border: 1px solid color-mix(in srgb, rgb(34 197 94) 22%, transparent);
128
- }
129
-
130
- .status-warn {
131
- background: color-mix(in srgb, rgb(234 179 8) 16%, transparent);
132
- color: rgb(250 204 21);
133
- border: 1px solid color-mix(in srgb, rgb(234 179 8) 22%, transparent);
134
- }
135
-
136
- .status-bad {
137
- background: color-mix(in srgb, rgb(239 68 68) 16%, transparent);
138
- color: rgb(248 113 113);
139
- border: 1px solid color-mix(in srgb, rgb(239 68 68) 22%, transparent);
140
- }
141
-
142
- .table-shell {
143
- overflow: hidden;
144
- }
145
-
146
- .table-scroll {
147
- overflow-x: auto;
148
- }
149
-
150
- .table-ui {
151
- width: 100%;
152
- min-width: 920px;
153
- border-collapse: separate;
154
- border-spacing: 0;
155
- }
156
-
157
- .table-ui thead th {
158
- color: var(--text-sec);
159
- font-size: 0.72rem;
160
- font-weight: 800;
161
- text-transform: uppercase;
162
- letter-spacing: .06em;
163
- padding: 1rem 1.25rem;
164
- background: color-mix(in srgb, var(--bg) 40%, transparent);
165
- border-bottom: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
166
- }
167
-
168
- .table-ui tbody td {
169
- padding: 1rem 1.25rem;
170
- border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
171
- color: var(--text);
172
- vertical-align: middle;
173
- }
174
-
175
- .table-ui tbody tr:hover td {
176
- background: color-mix(in srgb, var(--card) 18%, transparent);
177
- }
178
-
179
- .stream-id {
180
- max-width: 140px;
181
- overflow: hidden;
182
- text-overflow: ellipsis;
183
- white-space: nowrap;
184
- display: inline-block;
185
- vertical-align: bottom;
186
- }
187
-
188
- .title-cell {
189
- max-width: 210px;
190
- overflow: hidden;
191
- text-overflow: ellipsis;
192
- white-space: nowrap;
193
- }
194
-
195
- .empty-state {
196
- color: var(--text-sec);
197
- text-align: center;
198
- padding: 2rem 1rem;
199
- }
200
-
201
- .mobile-list {
202
- display: none;
203
- }
204
-
205
- .mobile-card {
206
- background: color-mix(in srgb, var(--bg) 70%, transparent);
207
- border: 1px solid color-mix(in srgb, var(--border) 90%, transparent);
208
- border-radius: 1.25rem;
209
- padding: 1rem;
210
- }
211
-
212
- .mobile-kv {
213
- display: grid;
214
- grid-template-columns: 110px 1fr;
215
- gap: 0.45rem 0.75rem;
216
- font-size: 0.86rem;
217
- }
218
-
219
- .mobile-kv .key {
220
- color: var(--text-sec);
221
- }
222
-
223
- .loading-dot {
224
- display: inline-block;
225
- width: .5rem;
226
- height: .5rem;
227
- border-radius: 9999px;
228
- background: var(--primary);
229
- box-shadow: 0 0 12px color-mix(in srgb, var(--primary) 40%, transparent);
230
- animation: pulseDot 1.2s infinite ease-in-out;
231
- }
232
-
233
- @keyframes pulseDot {
234
- 0%, 100% { opacity: .45; transform: scale(.9); }
235
- 50% { opacity: 1; transform: scale(1.1); }
236
- }
237
-
238
- @media (max-width: 1024px) {
239
- .table-ui { min-width: 840px; }
240
- }
241
-
242
- @media (max-width: 768px) {
243
- .desktop-table {
244
- display: none;
245
- }
246
-
247
- .mobile-list {
248
- display: grid;
249
- gap: 0.9rem;
250
- }
251
-
252
- .mobile-kv {
253
- grid-template-columns: 95px 1fr;
254
- }
255
-
256
- .btn-ui {
257
- width: 100%;
258
- }
259
  }
260
  </style>
261
 
262
- <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5 sm:py-8 text-text">
263
- <div class="glass-card rounded-3xl p-5 sm:p-6 lg:p-8 mb-6 sm:mb-8">
264
- <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4">
265
- <div>
266
- <div class="flex flex-wrap items-center gap-2 mb-3">
267
- <span class="pill"><span class="loading-dot"></span> Live admin panel</span>
268
- </div>
269
- <h1 class="section-title text-2xl sm:text-3xl lg:text-4xl">Admin Dashboard</h1>
270
- <p class="muted mt-2 text-sm sm:text-base">Monitor system health, stream analytics, and flagged dead links from one responsive control panel.</p>
271
- </div>
 
272
 
273
- <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full lg:w-auto">
274
- <button onclick="clearCache()" class="btn-ui btn-danger">
275
- <i class="fas fa-trash-alt"></i>
276
- Clear File Cache
277
- </button>
278
- <button onclick="clearAnalytics()" class="btn-ui btn-ghost">
279
- <i class="fas fa-chart-line"></i>
280
- Clear Analytics
281
- </button>
282
  </div>
283
  </div>
284
  </div>
285
 
286
- <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-6 mb-6 sm:mb-8" id="stats-container">
287
- <div class="glass-card metric-card rounded-3xl p-5 sm:p-6">
288
- <div class="flex items-start gap-4">
289
- <div class="metric-icon">
290
- <i class="fas fa-memory text-xl"></i>
291
- </div>
292
- <div class="min-w-0">
293
- <p class="muted text-sm font-semibold">Cached File IDs</p>
294
- <p class="text-3xl sm:text-4xl font-black tracking-tight mt-2 text-text" id="stat-cache-size">-</p>
295
- <p class="muted text-xs sm:text-sm mt-2">Current file-id cache entries in memory.</p>
296
- </div>
297
  </div>
298
  </div>
299
 
300
- <div class="glass-card metric-card rounded-3xl p-5 sm:p-6">
301
- <div class="flex items-start gap-4">
302
- <div class="metric-icon">
303
- <i class="fas fa-robot text-xl"></i>
304
- </div>
305
- <div class="min-w-0">
306
- <p class="muted text-sm font-semibold">Connected Bots</p>
307
- <p class="text-3xl sm:text-4xl font-black tracking-tight mt-2 text-text" id="stat-bot-count">-</p>
308
- <p class="muted text-xs sm:text-sm mt-2">Active Telegram bot clients available right now.</p>
309
- </div>
310
  </div>
311
  </div>
312
  </div>
313
 
314
- <div class="glass-card rounded-3xl overflow-hidden mb-6 sm:mb-8">
315
- <div class="px-5 sm:px-6 lg:px-8 py-4 sm:py-5 border-b border-hairline bg-surface flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  <div>
317
- <h2 class="section-title text-xl sm:text-2xl">Bot Health & Load</h2>
318
- <p class="muted text-sm mt-1">Track stream load, average speed, and failure trends per bot.</p>
319
  </div>
320
- <span class="pill">Realtime status</span>
321
  </div>
322
-
323
- <div id="stat-workloads" class="p-4 sm:p-5 lg:p-6">
324
- <div class="empty-state">Loading bot data...</div>
 
 
 
 
 
 
 
 
 
325
  </div>
326
  </div>
327
 
328
- <div class="glass-card rounded-3xl overflow-hidden mb-6 sm:mb-8">
329
- <div class="px-5 sm:px-6 lg:px-8 py-4 sm:py-5 border-b border-hairline bg-surface flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
330
  <div>
331
- <h2 class="section-title text-xl sm:text-2xl">Recent Stream Analytics</h2>
332
  <p class="muted text-sm mt-1">Data transferred, speed, duration, and status for recent streams.</p>
333
  </div>
334
  <span class="pill">Recent activity</span>
335
  </div>
336
 
337
- <div class="p-4 sm:p-5 lg:p-6">
338
  <div class="desktop-table table-shell">
339
  <div class="table-scroll">
340
  <table class="table-ui">
@@ -361,7 +195,7 @@
361
  </div>
362
  </div>
363
 
364
- <div id="analytics-mobile" class="mobile-list">
365
  <div class="empty-state">
366
  <i class="fas fa-spinner fa-spin mr-2 text-primary"></i> Loading analytics...
367
  </div>
@@ -370,15 +204,15 @@
370
  </div>
371
 
372
  <div class="glass-card rounded-3xl overflow-hidden">
373
- <div class="px-5 sm:px-6 lg:px-8 py-4 sm:py-5 border-b border-hairline bg-surface flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
374
  <div>
375
- <h2 class="section-title text-xl sm:text-2xl">Flagged Dead Links</h2>
376
  <p class="muted text-sm mt-1">Purge broken qualities so users no longer see dead content.</p>
377
  </div>
378
  <span class="pill">Database cleanup</span>
379
  </div>
380
 
381
- <div class="p-4 sm:p-5 lg:p-6">
382
  <div class="desktop-table table-shell">
383
  <div class="table-scroll">
384
  <table class="table-ui">
@@ -402,7 +236,7 @@
402
  </div>
403
  </div>
404
 
405
- <div id="dead-links-mobile" class="mobile-list">
406
  <div class="empty-state">
407
  <i class="fas fa-spinner fa-spin mr-2 text-primary"></i> Loading dead links...
408
  </div>
@@ -438,44 +272,23 @@
438
  document.getElementById('stat-bot-count').textContent = data.total_bots ?? '-';
439
 
440
  const workloadsWrap = document.getElementById('stat-workloads');
441
-
442
- if (data.bot_workloads && data.bot_workloads.length > 0) {
443
- let html = '<div class="grid grid-cols-1 xl:grid-cols-2 gap-4">';
444
- data.bot_workloads.forEach(b => {
445
- html += `
446
- <div class="workload-row rounded-3xl p-4 sm:p-5">
447
- <div class="flex flex-col gap-4">
448
- <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
449
- <div class="min-w-0">
450
- <div class="text-base sm:text-lg font-bold text-text">${escapeHtml(b.display_name)}</div>
451
- <div class="muted text-xs sm:text-sm mt-1">Bot performance summary</div>
452
- </div>
453
- <span class="${getStatusBadge(b.status)}">${escapeHtml(b.status)}</span>
454
- </div>
455
-
456
- <div class="grid grid-cols-3 sm:grid-cols-3 gap-3">
457
- <div class="glass-card-soft rounded-2xl p-4">
458
- <div class="muted text-xs uppercase tracking-wider font-bold">Active Streams</div>
459
- <div class="text-2xl font-black mt-2 text-text">${b.current_load ?? 0}</div>
460
- </div>
461
-
462
- <div class="glass-card-soft rounded-2xl p-4">
463
- <div class="muted text-xs uppercase tracking-wider font-bold">Avg Speed</div>
464
- <div class="text-2xl font-black mt-2 text-text">${Number(b.avg_mbps ?? 0).toFixed(1)}</div>
465
- <div class="muted text-xs mt-1">MB/s</div>
466
- </div>
467
-
468
- <div class="glass-card-soft rounded-2xl p-4">
469
- <div class="muted text-xs uppercase tracking-wider font-bold">Recent Failures</div>
470
- <div class="text-2xl font-black mt-2 ${Number(b.failures ?? 0) > 0 ? 'text-red-400' : 'text-text'}">${b.failures ?? 0}</div>
471
- </div>
472
- </div>
473
- </div>
474
- </div>
475
- `;
476
- });
477
- html += '</div>';
478
- workloadsWrap.innerHTML = html;
479
  } else {
480
  workloadsWrap.innerHTML = '<div class="empty-state">No bot data available</div>';
481
  }
@@ -485,6 +298,92 @@
485
  }
486
  }
487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
  async function fetchAnalytics() {
489
  try {
490
  const res = await fetch('/api/admin/stream-analytics');
@@ -497,6 +396,7 @@
497
  }
498
 
499
  const data = await res.json();
 
500
  const streams = data?.data?.recent || [];
501
 
502
  if (!streams.length) {
@@ -512,7 +412,12 @@
512
  const avg = Number(s.avg_mbps ?? 0);
513
  const peak = Number(s.peak_mbps ?? 0);
514
  const bytesStr = ((Number(s.total_bytes ?? 0)) / (1024 * 1024)).toFixed(1) + ' MB';
515
- const timeStr = s.logged_at ? new Date(s.logged_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '—';
 
 
 
 
 
516
  const durationStr = s.duration_sec ? `${Number(s.duration_sec).toFixed(1)}s` : '—';
517
  const titleStr = s.title || s.meta?.title || '—';
518
  const status = s.status || 'unknown';
@@ -531,21 +436,17 @@
531
  `;
532
 
533
  mobileHtml += `
534
- <div class="mobile-card">
535
- <div class="flex items-start justify-between gap-3 mb-3">
536
- <div class="min-w-0">
537
- <div class="font-bold text-text">${escapeHtml(titleStr)}</div>
538
- <div class="muted text-xs font-mono mt-1 break-all">${escapeHtml(s.stream_id)}</div>
539
- </div>
540
  <span class="${getStatusBadge(status)}">${escapeHtml(status)}</span>
541
  </div>
542
-
543
- <div class="mobile-kv">
544
- <div class="key">Bot</div><div>Bot ${Number(s.client_index ?? 0) + 1} (DC${escapeHtml(s.dc_id)})</div>
545
- <div class="key">Transferred</div><div>${bytesStr}</div>
546
- <div class="key">Avg / Peak</div><div>${avg.toFixed(1)} / ${peak.toFixed(1)} MB/s</div>
547
- <div class="key">Duration</div><div>${durationStr}</div>
548
- <div class="key">Time</div><div>${timeStr}</div>
549
  </div>
550
  </div>
551
  `;
@@ -618,7 +519,7 @@
618
  <div class="mobile-card">
619
  <div class="flex items-start justify-between gap-3 mb-3">
620
  <div>
621
- <div class="font-bold text-text">${escapeHtml(l.title)}</div>
622
  <div class="muted text-xs mt-1">${escapeHtml(l.year || '')}</div>
623
  </div>
624
  ${typeBadge}
@@ -707,9 +608,11 @@
707
 
708
  document.addEventListener('DOMContentLoaded', () => {
709
  fetchStats();
 
710
  fetchAnalytics();
711
  fetchDeadLinks();
712
- setInterval(fetchStats, 10000);
 
713
  setInterval(fetchAnalytics, 15000);
714
  });
715
  </script>
 
4
 
5
  {% block content %}
6
  <style>
7
+ .glass-card { background: var(--card); border: 1px solid var(--border); }
8
+ .glass-card-soft { background: var(--bg); border: 1px solid var(--border); }
9
+ .section-title { color: var(--text); font-weight: 600; letter-spacing: -0.01em; }
10
+ .muted { color: var(--text-sec); }
11
+ .pill { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); color: var(--text-sec); white-space: nowrap; }
12
+ .metric-icon { width: 2.5rem; height: 2.5rem; border-radius: 9999px; display: grid; place-items: center; flex-shrink: 0; background: var(--card-high); color: var(--primary); }
13
+ .btn-ui { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border-radius: 9999px; padding: .55rem 1.05rem; font-size: .88rem; font-weight: 500; border: 1px solid transparent; white-space: nowrap; transition: background-color .18s var(--ease), border-color .18s var(--ease), transform .12s var(--ease); }
14
+ .btn-ui:active { transform: scale(.97); }
15
+ .btn-ui.btn-danger { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); border-color: color-mix(in srgb, var(--danger) 30%, transparent); }
16
+ .btn-ui.btn-primary { background: var(--primary); color: var(--on-primary); }
17
+ .btn-ui.btn-ghost { background: transparent; color: var(--text); border-color: var(--border); }
18
+ .btn-ui.btn-ghost:hover { background: var(--card-high); }
19
+ .workload-row, .table-row-card { background: var(--bg); border: 1px solid var(--border); }
20
+ .status-badge { display: inline-flex; align-items: center; gap: .3rem; padding: .15rem .6rem; border-radius: 9999px; font-size: .72rem; font-weight: 500; white-space: nowrap; }
21
+ .status-good { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
22
+ .status-warn { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
23
+ .status-bad { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
24
+ .table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
25
+ .table-scroll { overflow: auto; max-height: 62vh; }
26
+ .table-ui { width: 100%; min-width: 880px; border-collapse: separate; border-spacing: 0; font-size: .88rem; }
27
+ .table-ui thead th { position: sticky; top: 0; z-index: 2; padding: .75rem 1rem; text-align: left; font-size: .72rem; font-weight: 500; letter-spacing: .06em; text-transform: uppercase; color: var(--text-sec); background: var(--card); border-bottom: 1px solid var(--border); }
28
+ .table-ui tbody td { padding: .8rem 1rem; border-bottom: 1px solid var(--border); vertical-align: middle; }
29
+ .table-ui tbody tr:last-child td { border-bottom: 0; }
30
+ .table-ui tbody tr:hover td { background: var(--surface); }
31
+ .stream-id { max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: inline-block; vertical-align: bottom; }
32
+ .title-cell { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
33
+ .empty-state { color: var(--text-sec); text-align: center; padding: 2rem 1rem; font-size: .9rem; }
34
+ .mobile-list { display: none; }
35
+ .mobile-card { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 1rem; min-width: 0; }
36
+ .mobile-kv { display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: .4rem .75rem; font-size: .85rem; }
37
+ .mobile-kv > * { min-width: 0; overflow-wrap: anywhere; }
38
+ .mobile-kv .key { color: var(--text-sec); }
39
+ .bot-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem; }
40
+ .bot-card { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: .85rem; min-width: 0; }
41
+ .bot-stat-num { font-size: 1.1rem; font-weight: 600; line-height: 1.1; }
42
+ .bot-stat-label { font-size: .7rem; color: var(--text-sec); margin-top: .15rem; }
43
+ .analytics-mobile-card { padding: .85rem; border-radius: var(--radius-sm); }
44
+ .scroll-cap { max-height: 62vh; overflow-y: auto; }
45
+ .loading-dot { display: inline-block; width: .45rem; height: .45rem; border-radius: 9999px; background: var(--ok); animation: pulseDot 1.6s infinite ease-in-out; }
46
+ @keyframes pulseDot { 0%, 100% { opacity: .4; } 50% { opacity: 1; } }
47
+ @media (min-width: 640px) { .bot-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
48
+ @media (min-width: 1024px) { .bot-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
49
+ @media (max-width: 767.98px) {
50
+ .desktop-table { display: none; }
51
+ .mobile-list { display: grid; gap: .75rem; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  }
53
  </style>
54
 
55
+ <div class="text-text">
56
+ <header class="page-head">
57
+ <div>
58
+ <h1 class="page-title">Admin</h1>
59
+ <p class="page-sub">System health, stream analytics and dead links</p>
60
+ </div>
61
+ <div class="page-actions">
62
+ <button onclick="clearAnalytics()" class="btn-ui btn-ghost"><i class="fa-solid fa-chart-line"></i> Clear analytics</button>
63
+ <button onclick="clearCache()" class="btn-ui btn-danger"><i class="fa-solid fa-trash-can"></i> Clear file cache</button>
64
+ </div>
65
+ </header>
66
 
67
+ <div class="glass-card rounded-3xl p-5 mb-8" id="stats-container">
68
+ <div class="grid grid-cols-2 gap-6">
69
+ <div class="flex items-center gap-3 min-w-0">
70
+ <span class="metric-icon"><i class="fa-solid fa-memory"></i></span>
71
+ <div class="min-w-0"><p class="text-xl font-semibold tabular" id="stat-cache-size">-</p><p class="text-sm muted truncate">Cached file IDs</p></div>
72
+ </div>
73
+ <div class="flex items-center gap-3 min-w-0">
74
+ <span class="metric-icon"><i class="fa-solid fa-robot"></i></span>
75
+ <div class="min-w-0"><p class="text-xl font-semibold tabular" id="stat-bot-count">-</p><p class="text-sm muted truncate">Connected bots</p></div>
76
  </div>
77
  </div>
78
  </div>
79
 
80
+ <div class="glass-card rounded-3xl overflow-hidden mb-8">
81
+ <div class="px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-3">
82
+ <div>
83
+ <h2 class="section-title text-lg">Health &amp; Diagnostics</h2>
84
+ <p class="muted text-sm mt-1">Live bot load, plus database, TMDB and public-URL checks.</p>
85
+ </div>
86
+ <div class="flex items-center gap-2">
87
+ <span id="hz-overall-badge" class="hz-badge s-warning">checking…</span>
88
+ <button onclick="fetchHealthReport(true)" class="btn-ui btn-ghost"><i class="fa-solid fa-stethoscope"></i> Recheck</button>
 
 
89
  </div>
90
  </div>
91
 
92
+ <div class="p-4 sm:p-5">
93
+ <div id="hz-infra" class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-5">
94
+ <div class="empty-state">Running checks…</div>
95
+ </div>
96
+ <h3 class="hz-subhead"><i class="fa-solid fa-robot"></i> Telegram Clients <span class="pill" style="margin-left:.35rem"><span class="loading-dot"></span> live</span></h3>
97
+ <div id="stat-workloads">
98
+ <div class="empty-state">Loading bot data...</div>
 
 
 
99
  </div>
100
  </div>
101
  </div>
102
 
103
+ <style>
104
+ .hz-badge { padding: 0.15rem 0.6rem; border-radius: 999px; font-size: 0.72rem; font-weight: 500; white-space: nowrap; }
105
+ .s-ok { background: color-mix(in srgb, var(--ok) 13%, transparent); color: var(--ok); }
106
+ .s-degraded, .s-warning, .s-not_configured { background: color-mix(in srgb, var(--warn) 13%, transparent); color: var(--warn); }
107
+ .s-down, .s-error, .s-critical { background: color-mix(in srgb, var(--danger) 13%, transparent); color: var(--danger); }
108
+ .hz-card { border: 1px solid var(--border); background: var(--bg); border-radius: var(--radius-sm); padding: 1rem 1.1rem; }
109
+ .hz-top { display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
110
+ .hz-name { font-weight: 600; font-size: .92rem; display: flex; align-items: center; gap: .5rem; }
111
+ .hz-msg { color: var(--text-sec); font-size: .8rem; margin-top: .5rem; word-break: break-word; }
112
+ .hz-item { display: flex; align-items: center; justify-content: space-between; gap: .6rem; font-size: .82rem; border-top: 1px solid var(--hairline, color-mix(in srgb, var(--text) 6%, transparent)); padding-top: .45rem; margin-top: .45rem; }
113
+ .hz-item .lbl { display: flex; align-items: center; gap: .45rem; font-weight: 600; }
114
+ .hz-item .meta { color: var(--text-sec); font-size: .74rem; text-align: right; }
115
+ .hz-subhead { font-weight: 600; font-size: 0.95rem; margin: 0.25rem 0 0.85rem; display: flex; align-items: center; gap: .5rem; }
116
+ .mini-dot { width: .55rem; height: .55rem; border-radius: 999px; display: inline-block; }
117
+ .hz-usebar { height: 5px; border-radius: 999px; background: var(--hairline, color-mix(in srgb, var(--text) 12%, transparent)); overflow: hidden; width: 90px; margin-top: 3px; margin-left: auto; }
118
+ .hz-usebar > span { display: block; height: 100%; background: var(--primary); }
119
+ .bot-table-wrap { overflow-x: auto; }
120
+ .bot-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
121
+ .bot-table th { text-align: center; font-size: 0.68rem; text-transform: uppercase; letter-spacing: .05em; color: var(--text-sec); padding: 0.55rem 0.75rem; border-bottom: 1px solid var(--hairline, color-mix(in srgb, var(--text) 12%, transparent)); }
122
+ .bot-table th:first-child { text-align: left; }
123
+ .bot-table td { padding: 0.6rem 0.75rem; text-align: center; border-bottom: 1px solid var(--hairline, color-mix(in srgb, var(--text) 6%, transparent)); }
124
+ .bot-table tr:last-child td { border-bottom: none; }
125
+ .bot-table .bt-name { text-align: left; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
126
+ .ins-stat { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 0.9rem 1rem; text-align: center; }
127
+ .ins-v { font-size: 1.5rem; font-weight: 600; }
128
+ .ins-l { font-size: 0.8rem; color: var(--text-sec); margin-top: 0.2rem; }
129
+ .ins-col { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 1rem; }
130
+ .ins-h { font-weight: 600; font-size: 0.95rem; margin-bottom: 0.85rem; }
131
+ .ins-list { display: flex; flex-direction: column; gap: 0.55rem; }
132
+ .ins-row { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; font-size: 0.85rem; }
133
+ .ins-row .name { color: var(--text); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
134
+ .ins-row .val { color: var(--text-sec); font-size: 0.75rem; flex-shrink: 0; }
135
+ .ins-bar { height: 6px; border-radius: 999px; background: var(--primary); opacity: 0.75; margin-top: 3px; }
136
+ .ins-empty { color: var(--text-sec); font-size: 0.82rem; }
137
+ </style>
138
+
139
+ <div class="glass-card rounded-3xl overflow-hidden mb-8">
140
+ <div class="px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-3">
141
  <div>
142
+ <h2 class="section-title text-lg">Streaming Insights</h2>
143
+ <p class="muted text-sm mt-1">Most-watched titles, heaviest viewers and daily activity.</p>
144
  </div>
145
+ <span class="pill">Overview</span>
146
  </div>
147
+ <div class="p-4 sm:p-5">
148
+ <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
149
+ <div class="ins-stat"><div class="ins-v" id="ins-total-streams">—</div><div class="ins-l">Total Streams</div></div>
150
+ <div class="ins-stat"><div class="ins-v" id="ins-total-data">—</div><div class="ins-l">Data Transferred</div></div>
151
+ <div class="ins-stat"><div class="ins-v" id="ins-avg-speed">—</div><div class="ins-l">Avg Speed</div></div>
152
+ <div class="ins-stat"><div class="ins-v" id="ins-active-users">—</div><div class="ins-l">Active Viewers</div></div>
153
+ </div>
154
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
155
+ <div class="ins-col"><h3 class="ins-h"><i class="fa-solid fa-fire text-primary mr-2"></i>Top titles</h3><div id="ins-top-titles" class="ins-list"></div></div>
156
+ <div class="ins-col"><h3 class="ins-h"><i class="fa-solid fa-user text-primary mr-2"></i>Top viewers</h3><div id="ins-top-users" class="ins-list"></div></div>
157
+ <div class="ins-col"><h3 class="ins-h"><i class="fa-solid fa-calendar-days text-primary mr-2"></i>Last 14 days</h3><div id="ins-per-day" class="ins-list"></div></div>
158
+ </div>
159
  </div>
160
  </div>
161
 
162
+ <div class="glass-card rounded-3xl overflow-hidden mb-8">
163
+ <div class="px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-3">
164
  <div>
165
+ <h2 class="section-title text-lg">Recent Stream Analytics</h2>
166
  <p class="muted text-sm mt-1">Data transferred, speed, duration, and status for recent streams.</p>
167
  </div>
168
  <span class="pill">Recent activity</span>
169
  </div>
170
 
171
+ <div class="p-4 sm:p-5">
172
  <div class="desktop-table table-shell">
173
  <div class="table-scroll">
174
  <table class="table-ui">
 
195
  </div>
196
  </div>
197
 
198
+ <div id="analytics-mobile" class="mobile-list scroll-cap">
199
  <div class="empty-state">
200
  <i class="fas fa-spinner fa-spin mr-2 text-primary"></i> Loading analytics...
201
  </div>
 
204
  </div>
205
 
206
  <div class="glass-card rounded-3xl overflow-hidden">
207
+ <div class="px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-3">
208
  <div>
209
+ <h2 class="section-title text-lg">Flagged Dead Links</h2>
210
  <p class="muted text-sm mt-1">Purge broken qualities so users no longer see dead content.</p>
211
  </div>
212
  <span class="pill">Database cleanup</span>
213
  </div>
214
 
215
+ <div class="p-4 sm:p-5">
216
  <div class="desktop-table table-shell">
217
  <div class="table-scroll">
218
  <table class="table-ui">
 
236
  </div>
237
  </div>
238
 
239
+ <div id="dead-links-mobile" class="mobile-list scroll-cap">
240
  <div class="empty-state">
241
  <i class="fas fa-spinner fa-spin mr-2 text-primary"></i> Loading dead links...
242
  </div>
 
272
  document.getElementById('stat-bot-count').textContent = data.total_bots ?? '-';
273
 
274
  const workloadsWrap = document.getElementById('stat-workloads');
275
+ const bots = data.bot_workloads || [];
276
+ if (bots.length) {
277
+ const rows = bots.map(b => {
278
+ const idx = Number(b.client_index);
279
+ const name = idx < 0 ? 'Userbot' : ('Bot ' + (idx + 1));
280
+ const dc = (b.dc ?? b.dc_id);
281
+ const color = b.status === 'healthy' ? 'var(--ok)' : (b.status === 'degraded' ? 'var(--warn)' : 'var(--danger)');
282
+ return `<tr>
283
+ <td class="bt-name"><span class="mini-dot" style="background:${color}"></span> ${escapeHtml(name)}</td>
284
+ <td>${dc != null ? 'DC ' + escapeHtml(dc) : '—'}</td>
285
+ <td>${escapeHtml(b.current_load ?? 0)}</td>
286
+ <td>${Number(b.avg_mbps ?? 0).toFixed(1)}</td>
287
+ </tr>`;
288
+ }).join('');
289
+ workloadsWrap.innerHTML = `<div class="bot-table-wrap"><table class="bot-table">
290
+ <thead><tr><th>Client</th><th>DC</th><th>Load</th><th>Avg MB/s</th></tr></thead>
291
+ <tbody>${rows}</tbody></table></div>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  } else {
293
  workloadsWrap.innerHTML = '<div class="empty-state">No bot data available</div>';
294
  }
 
298
  }
299
  }
300
 
301
+ function hzBadge(status) { return `<span class="hz-badge s-${status}">${escapeHtml(String(status).replace('_', ' '))}</span>`; }
302
+ function hzMini(ok) { return `<span class="mini-dot" style="background:${ok ? 'var(--ok)' : 'var(--danger)'}"></span>`; }
303
+
304
+ function hzInfraCard(sec) {
305
+ const icon = { databases: 'fa-database', tmdb: 'fa-film', base_url: 'fa-link' }[sec.key] || 'fa-circle-check';
306
+ let body;
307
+ if (sec.key === 'databases') {
308
+ body = (sec.items || []).map(i => `
309
+ <div class="hz-item">
310
+ <div class="lbl">${hzMini(i.status === 'ok')} ${escapeHtml(i.name)}</div>
311
+ <div class="meta">${i.status === 'ok'
312
+ ? `${escapeHtml(i.size_mb)} MB<div class="hz-usebar"><span style="width:${Math.min(100, i.usage_pct || 0)}%"></span></div>`
313
+ : escapeHtml(i.message || 'unreachable')}</div>
314
+ </div>`).join('') || '<div class="hz-msg">No databases.</div>';
315
+ } else {
316
+ body = `<div class="hz-msg">${escapeHtml(sec.message || '')}${sec.url ? '<br><span style="opacity:.7">' + escapeHtml(sec.url) + '</span>' : ''}</div>`;
317
+ }
318
+ return `<div class="hz-card">
319
+ <div class="hz-top"><span class="hz-name"><i class="fa-solid ${icon}"></i> ${escapeHtml(sec.label)}</span>${hzBadge(sec.status)}</div>
320
+ ${body}
321
+ </div>`;
322
+ }
323
+
324
+ async function fetchHealthReport(force) {
325
+ try {
326
+ const res = await fetch('/api/admin/health/report' + (force ? '?fresh=1' : ''));
327
+ const data = await res.json();
328
+ if (data.status !== 'success') return;
329
+ const d = data.data || {};
330
+ const overall = d.overall || 'warning';
331
+ const label = { ok: 'Healthy', warning: 'Attention', critical: 'Critical' }[overall] || overall;
332
+ const badge = document.getElementById('hz-overall-badge');
333
+ if (badge) { badge.className = 'hz-badge s-' + overall; badge.textContent = label; }
334
+ const infra = (d.sections || []).filter(s => s.key !== 'bots');
335
+ document.getElementById('hz-infra').innerHTML = infra.map(hzInfraCard).join('');
336
+ if (force) showToast('Health re-checked.', 'success', 'Health');
337
+ } catch (e) { /* ignore transient errors */ }
338
+ }
339
+
340
+ function fmtBytes(bytes) {
341
+ let b = Number(bytes || 0);
342
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
343
+ let i = 0;
344
+ while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; }
345
+ return b.toFixed(b >= 10 || i === 0 ? 0 : 1) + ' ' + units[i];
346
+ }
347
+
348
+ function insText(id, val) {
349
+ const el = document.getElementById(id);
350
+ if (el) el.textContent = val;
351
+ }
352
+
353
+ function insRow(name, val, frac) {
354
+ const pct = Math.max(4, Math.round((frac || 0) * 100));
355
+ return `<div>
356
+ <div class="ins-row"><span class="name" title="${escapeHtml(name)}">${escapeHtml(name)}</span><span class="val">${escapeHtml(val)}</span></div>
357
+ <div class="ins-bar" style="width:${pct}%"></div>
358
+ </div>`;
359
+ }
360
+
361
+ function renderInsights(d) {
362
+ const s = d.summary || {};
363
+ insText('ins-total-streams', s.total_streams ?? 0);
364
+ insText('ins-total-data', fmtBytes(s.total_bytes));
365
+ insText('ins-avg-speed', (Number(s.avg_speed || 0)).toFixed(1) + ' MB/s');
366
+ insText('ins-active-users', s.active_users ?? 0);
367
+
368
+ const titles = d.top_titles || [];
369
+ const maxT = Math.max(1, ...titles.map(t => t.streams || 0));
370
+ document.getElementById('ins-top-titles').innerHTML = titles.length
371
+ ? titles.map(t => insRow(t.title || '—', `${t.streams} plays · ${fmtBytes(t.total_bytes)}`, t.streams / maxT)).join('')
372
+ : '<div class="ins-empty">No data yet.</div>';
373
+
374
+ const users = d.top_users || [];
375
+ const maxU = Math.max(1, ...users.map(u => u.total_bytes || 0));
376
+ document.getElementById('ins-top-users').innerHTML = users.length
377
+ ? users.map(u => insRow(u.user || '—', `${fmtBytes(u.total_bytes)} · ${u.streams} streams`, u.total_bytes / maxU)).join('')
378
+ : '<div class="ins-empty">No data yet.</div>';
379
+
380
+ const days = d.per_day || [];
381
+ const maxD = Math.max(1, ...days.map(x => x.streams || 0));
382
+ document.getElementById('ins-per-day').innerHTML = days.length
383
+ ? days.map(x => insRow(x.date, `${x.streams} · ${fmtBytes(x.total_bytes)}`, x.streams / maxD)).join('')
384
+ : '<div class="ins-empty">No data yet.</div>';
385
+ }
386
+
387
  async function fetchAnalytics() {
388
  try {
389
  const res = await fetch('/api/admin/stream-analytics');
 
396
  }
397
 
398
  const data = await res.json();
399
+ renderInsights(data.data || {});
400
  const streams = data?.data?.recent || [];
401
 
402
  if (!streams.length) {
 
412
  const avg = Number(s.avg_mbps ?? 0);
413
  const peak = Number(s.peak_mbps ?? 0);
414
  const bytesStr = ((Number(s.total_bytes ?? 0)) / (1024 * 1024)).toFixed(1) + ' MB';
415
+ const timeStr = s.logged_at
416
+ ? new Date(s.logged_at).toLocaleString([], {
417
+ year: 'numeric', month: 'short', day: 'numeric',
418
+ hour: '2-digit', minute: '2-digit', second: '2-digit'
419
+ })
420
+ : '—';
421
  const durationStr = s.duration_sec ? `${Number(s.duration_sec).toFixed(1)}s` : '—';
422
  const titleStr = s.title || s.meta?.title || '—';
423
  const status = s.status || 'unknown';
 
436
  `;
437
 
438
  mobileHtml += `
439
+ <div class="mobile-card analytics-mobile-card">
440
+ <div class="flex items-center justify-between gap-2">
441
+ <div class="font-semibold text-text truncate">${escapeHtml(titleStr)}</div>
 
 
 
442
  <span class="${getStatusBadge(status)}">${escapeHtml(status)}</span>
443
  </div>
444
+ <div class="flex flex-wrap gap-x-3 gap-y-1 muted text-xs mt-2">
445
+ <span>Bot ${Number(s.client_index ?? 0) + 1} · DC${escapeHtml(s.dc_id)}</span>
446
+ <span class="font-semibold text-text">${bytesStr}</span>
447
+ <span>${avg.toFixed(1)}/${peak.toFixed(1)} MB/s</span>
448
+ <span>${durationStr}</span>
449
+ <span>${timeStr}</span>
 
450
  </div>
451
  </div>
452
  `;
 
519
  <div class="mobile-card">
520
  <div class="flex items-start justify-between gap-3 mb-3">
521
  <div>
522
+ <div class="font-semibold text-text">${escapeHtml(l.title)}</div>
523
  <div class="muted text-xs mt-1">${escapeHtml(l.year || '')}</div>
524
  </div>
525
  ${typeBadge}
 
608
 
609
  document.addEventListener('DOMContentLoaded', () => {
610
  fetchStats();
611
+ fetchHealthReport();
612
  fetchAnalytics();
613
  fetchDeadLinks();
614
+ setInterval(fetchStats, 5000); // realtime bot load
615
+ setInterval(fetchHealthReport, 20000); // infra checks (cached server-side)
616
  setInterval(fetchAnalytics, 15000);
617
  });
618
  </script>
Backend/fastapi/templates/base.html CHANGED
@@ -1,638 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!DOCTYPE html>
2
- <html lang="en" class="{{ 'dark' if theme.is_dark else 'light' }}">
3
  <head>
4
  <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>{% block title %}Telegram Stremio{% endblock %}</title>
7
 
8
- <script src="https://cdn.tailwindcss.com"></script>
9
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"/>
 
 
 
 
 
10
 
 
 
11
  <link rel="preconnect" href="https://fonts.googleapis.com">
12
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
13
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
 
 
14
 
15
  <style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  :root {
17
- color-scheme: {{ 'dark' if theme.is_dark else 'light' }};
18
- --primary: {{ theme.colors.primary }};
19
- --secondary: {{ theme.colors.secondary }};
20
- --accent: {{ theme.colors.accent }};
21
- --bg: {{ theme.colors.background }};
22
- --card: {{ theme.colors.card }};
23
- --border: {{ theme.colors.border }};
24
- --text: {{ theme.colors.text }};
25
- --text-sec: {{ theme.colors.text_secondary }};
26
-
27
- --surface: color-mix(in srgb, var(--text) 5%, transparent);
28
- --surface-2: color-mix(in srgb, var(--text) 9%, transparent);
29
- --surface-3: color-mix(in srgb, var(--text) 14%, transparent);
30
- --hairline: color-mix(in srgb, var(--text) 12%, transparent);
31
- --hairline-strong: color-mix(in srgb, var(--text) 20%, transparent);
32
- --muted: color-mix(in srgb, var(--text) 42%, transparent);
33
- --ring: color-mix(in srgb, var(--primary) 35%, transparent);
34
- --shadow-color: {{ '0,0,0' if theme.is_dark else '15,23,42' }};
35
- --shadow-soft: 0 10px 30px rgba(var(--shadow-color), {{ '0.35' if theme.is_dark else '0.10' }});
36
- --shadow-strong: 0 24px 60px rgba(var(--shadow-color), {{ '0.45' if theme.is_dark else '0.16' }});
37
- }
38
-
39
- html { scroll-behavior: smooth; }
40
-
41
- @media (prefers-reduced-motion: reduce) {
42
- html { scroll-behavior: auto; }
43
- *, *::before, *::after {
44
- animation-duration: .001ms !important;
45
- animation-iteration-count: 1 !important;
46
- transition-duration: .001ms !important;
47
- }
48
- }
49
-
50
  body {
51
- font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;
 
 
 
52
  -webkit-font-smoothing: antialiased;
53
- background-color: var(--bg);
 
54
  color: var(--text);
55
- min-height: 100vh;
56
- display: flex;
57
- flex-direction: column;
58
- }
 
 
 
 
 
59
 
60
- body::before {
61
- content: "";
62
- position: fixed;
63
- inset: 0;
64
- z-index: -1;
65
- pointer-events: none;
66
- background-image:
67
- radial-gradient(circle at 15% 10%, color-mix(in srgb, var(--primary) 12%, transparent), transparent 40%),
68
- radial-gradient(circle at 85% 80%, color-mix(in srgb, var(--accent) 12%, transparent), transparent 40%),
69
- radial-gradient(circle at 50% 50%, color-mix(in srgb, var(--card) 40%, transparent), transparent 60%);
 
 
 
 
 
 
 
 
70
  }
71
-
72
- .glass-panel {
73
- background: color-mix(in srgb, var(--card) 90%, var(--bg));
74
- border: 1px solid var(--hairline);
75
- box-shadow: var(--shadow-soft);
 
 
76
  }
 
 
77
 
78
- .glass-nav {
79
- background: color-mix(in srgb, var(--card) 78%, transparent);
80
- backdrop-filter: blur(12px);
81
- -webkit-backdrop-filter: blur(12px);
 
82
  }
83
-
84
  .glass-pill { border-radius: 9999px; }
85
 
86
- .surface-card {
87
- background: color-mix(in srgb, var(--card) 92%, var(--bg));
88
- border: 1px solid var(--hairline);
89
- border-radius: 1.5rem;
90
- }
91
-
92
- .btn-primary {
93
- background: var(--primary);
94
- color: var(--bg);
95
- font-weight: 700;
96
- border-radius: 1rem;
97
- transition: filter .2s ease, transform .12s ease, box-shadow .2s ease;
98
- box-shadow: 0 8px 22px color-mix(in srgb, var(--primary) 30%, transparent);
99
- }
100
- .btn-primary:hover { filter: brightness(1.08); }
101
- .btn-primary:active { transform: scale(.97); }
102
-
103
- .btn-ghost {
104
- background: var(--surface);
105
- color: var(--text);
106
- border: 1px solid var(--hairline);
107
- border-radius: 1rem;
108
- font-weight: 700;
109
- transition: background .2s ease, border-color .2s ease;
110
  }
111
- .btn-ghost:hover { background: var(--surface-2); border-color: var(--hairline-strong); }
 
 
 
 
 
 
112
 
113
  .badge {
114
  display: inline-flex;
115
  align-items: center;
116
  gap: .35rem;
117
- font-size: .65rem;
118
- font-weight: 700;
 
119
  text-transform: uppercase;
120
- letter-spacing: .12em;
121
- padding: .25rem .6rem;
122
  border-radius: 9999px;
123
  background: color-mix(in srgb, var(--primary) 14%, transparent);
124
  color: var(--primary);
 
125
  }
126
 
127
  .field {
128
  width: 100%;
129
- background: color-mix(in srgb, var(--card) 88%, var(--bg));
130
  color: var(--text);
131
- border: 1px solid var(--hairline);
132
- border-radius: 1rem;
133
- transition: border-color .2s ease, box-shadow .2s ease;
134
- }
135
- .field:focus {
136
- outline: none;
137
- border-color: var(--primary);
138
- box-shadow: 0 0 0 3px var(--ring);
139
  }
 
 
140
 
141
- .tabular { font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; }
142
-
143
- ::selection { background: color-mix(in srgb, var(--primary) 30%, transparent); color: var(--text); }
144
-
145
- :focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
146
-
147
- * { scrollbar-width: thin; scrollbar-color: var(--hairline-strong) transparent; }
148
- *::-webkit-scrollbar { width: 10px; height: 10px; }
149
- *::-webkit-scrollbar-thumb { background: var(--hairline-strong); border-radius: 9999px; border: 2px solid transparent; background-clip: padding-box; }
150
- *::-webkit-scrollbar-thumb:hover { background: var(--muted); }
151
-
152
- .nav-link {
153
  color: var(--text-sec);
154
- border-radius: 9999px;
155
- padding: 0.5rem 1.25rem;
156
- transition: color 0.3s ease;
157
- position: relative;
158
- z-index: 1;
159
- white-space: nowrap;
160
- font-weight: 600;
161
  }
162
 
163
- .nav-link:hover, .nav-link.active-page {
164
- color: var(--bg) !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
- #active-pill {
168
- position: absolute;
169
- background: var(--primary);
 
 
 
 
 
170
  border-radius: 9999px;
171
- transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
172
- z-index: 0;
173
- box-shadow: 0 0 15px color-mix(in srgb, var(--primary) 40%, transparent);
174
  }
 
 
 
 
 
 
 
 
175
 
176
- .toast {
177
- pointer-events: auto;
178
- min-width: 260px;
179
- max-width: 360px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  border: 1px solid var(--border);
181
- background: color-mix(in srgb, var(--card) 88%, transparent);
182
- color: var(--text);
183
- box-shadow: 0 18px 40px rgba(0,0,0,0.2);
184
- border-radius: 1rem;
185
- padding: 0.9rem 1rem;
186
- display: flex;
187
- align-items: flex-start;
188
- gap: 0.75rem;
189
- backdrop-filter: blur(14px);
190
- animation: toast-in 220ms ease-out;
191
  }
 
192
 
193
- .toast.success { border-color: color-mix(in srgb, #22c55e 35%, var(--border)); }
194
- .toast.error { border-color: color-mix(in srgb, #ef4444 35%, var(--border)); }
195
- .toast.info { border-color: color-mix(in srgb, var(--primary) 35%, var(--border)); }
 
 
 
 
196
 
197
- .toast-title { font-weight: 800; font-size: 0.9rem; line-height: 1.2; }
198
- .toast-message { margin-top: 0.15rem; font-size: 0.82rem; color: var(--text-sec); line-height: 1.35; }
 
 
199
 
200
- @keyframes toast-in { from { opacity: 0; transform: translateY(-10px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
201
- @keyframes toast-out { from { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 0; transform: translateY(-8px) scale(0.98); } }
202
 
203
- @media (max-width: 640px) {
204
- #toast-container { top: 5rem; left: 0.75rem; right: 0.75rem; }
205
- .toast { max-width: none; width: 100%; }
206
- }
207
-
208
- .theme-select {
209
- appearance: none;
210
- background: var(--bg);
211
- color: var(--text);
 
 
212
  border: 1px solid var(--border);
213
- border-radius: 999px;
214
- padding: 0.5rem 2rem 0.5rem 1rem;
215
- font-size: 0.875rem;
216
- cursor: pointer;
217
- }
218
-
219
- input, select, textarea, button {
220
- font-family: inherit;
221
- }
222
- input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]),
223
- select,
224
- textarea {
225
  color: var(--text);
 
 
226
  }
227
- input::placeholder,
228
- textarea::placeholder {
229
- color: color-mix(in srgb, var(--text-sec) 78%, transparent);
230
- opacity: 1;
231
- }
232
- select option,
233
- select optgroup {
234
- background-color: var(--card);
235
- color: var(--text);
236
- }
237
- /* Autofill no longer paints white-on-white in dark themes */
238
- input:-webkit-autofill,
239
- input:-webkit-autofill:hover,
240
- input:-webkit-autofill:focus,
241
- textarea:-webkit-autofill {
242
- -webkit-text-fill-color: var(--text);
243
- -webkit-box-shadow: 0 0 0 1000px color-mix(in srgb, var(--card) 92%, transparent) inset;
244
- caret-color: var(--text);
245
- transition: background-color 9999s ease-in-out 0s;
246
- }
247
 
248
- /* ── Modern theme picker (nav) ──────────────────────────────────────────────*/
249
- .theme-grid {
250
- display: grid;
251
- grid-template-columns: 1fr 1fr;
252
- gap: 0.5rem;
253
- }
254
- .theme-chip {
255
- --sw-bg: var(--bg);
256
- --sw-primary: var(--primary);
257
- --sw-accent: var(--accent);
258
- --sw-text: var(--text);
259
- display: flex;
260
- align-items: center;
261
- gap: 0.5rem;
262
- padding: 0.5rem 0.6rem;
263
- border-radius: 0.85rem;
264
- border: 1px solid color-mix(in srgb, var(--sw-text) 18%, transparent);
265
- background: var(--sw-bg);
266
- cursor: pointer;
267
- position: relative;
268
- overflow: hidden;
269
- transition: transform 0.14s ease, box-shadow 0.14s ease, border-color 0.14s ease;
270
- }
271
- .theme-chip:hover {
272
- transform: translateY(-1px);
273
- border-color: var(--sw-primary);
274
  }
275
- .theme-chip.active {
276
- border-color: var(--sw-primary);
277
- box-shadow: 0 0 0 2px color-mix(in srgb, var(--sw-primary) 55%, transparent);
278
- }
279
- .theme-chip-dots { display: flex; gap: 3px; flex-shrink: 0; }
280
- .theme-chip-dots .dot {
281
- width: 0.7rem; height: 0.7rem; border-radius: 9999px;
282
- box-shadow: 0 0 6px color-mix(in srgb, var(--sw-primary) 70%, transparent);
283
- }
284
- .theme-chip-name {
285
- font-size: 0.7rem;
286
- font-weight: 700;
287
- color: var(--sw-text);
288
- white-space: nowrap;
289
- overflow: hidden;
290
- text-overflow: ellipsis;
291
- line-height: 1.1;
292
- }
293
- .theme-chip .chip-check {
294
- position: absolute;
295
- top: 0.3rem; right: 0.4rem;
296
- font-size: 0.6rem;
297
- color: var(--sw-primary);
298
- }
299
-
300
- #overlay {
301
- backdrop-filter: blur(8px);
302
- background: rgba(0,0,0,0.4);
303
- transition: opacity 0.3s ease;
304
  }
305
 
306
- .nav-scrolled {
307
- transform: translate(-50%, -5px) scale(0.97);
308
- background: color-mix(in srgb, var(--card) 80%, transparent);
309
  }
310
-
311
- #mobile-menu { will-change: max-height, opacity; }
312
  </style>
313
 
314
  <script>
315
- tailwind.config = {
316
- darkMode: 'class',
317
- theme: {
318
- extend: {
319
- fontFamily: {
320
- sans: ['Inter', 'system-ui', 'sans-serif'],
321
- mono: ['"JetBrains Mono"', 'ui-monospace', 'monospace']
322
- },
323
- colors: {
324
- primary: 'var(--primary)',
325
- secondary: 'var(--secondary)',
326
- accent: 'var(--accent)',
327
- background: 'var(--bg)',
328
- card: 'var(--card)',
329
- border: 'var(--border)',
330
- text: 'var(--text)',
331
- 'text-secondary': 'var(--text-sec)',
332
- surface: 'var(--surface)',
333
- 'surface-2': 'var(--surface-2)',
334
- 'surface-3': 'var(--surface-3)',
335
- hairline: 'var(--hairline)',
336
- 'hairline-strong': 'var(--hairline-strong)',
337
- muted: 'var(--muted)'
338
- },
339
- boxShadow: {
340
- soft: 'var(--shadow-soft)',
341
- strong: 'var(--shadow-strong)'
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  }
343
  }
344
- }
345
- }
 
 
 
 
 
 
 
346
  </script>
347
  </head>
348
 
349
- <body class="pt-24 pb-12 antialiased">
350
-
351
- <div id="overlay" class="fixed inset-0 z-40 opacity-0 pointer-events-none"></div>
352
-
353
- <nav id="navbar" class="fixed top-6 left-1/2 -translate-x-1/2 w-[95%] max-w-6xl z-50 glass-panel glass-nav glass-pill px-5 py-3 flex justify-between items-center transition-all duration-300">
354
-
355
- <a href="/" class="flex items-center gap-3 shrink-0">
356
- <div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center shadow-[0_0_15px_var(--primary)]">
357
- <i class="fa-solid fa-play text-white text-xs"></i>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  </div>
359
- <span class="text-lg md:text-xl font-extrabold tracking-wide text-transparent bg-clip-text bg-gradient-to-r from-primary to-accent">
360
- TG Stremio
361
- </span>
362
- </a>
363
-
364
- {% if current_user %}
365
- <div id="nav-container" class="hidden md:flex absolute left-1/2 -translate-x-1/2 items-center gap-1 p-1 bg-black/10 rounded-full border border-hairline">
366
- <div id="active-pill" class="pointer-events-none"></div>
367
- <a href="/" class="nav-link">Home</a>
368
- <a href="/media/manage" class="nav-link">Media</a>
369
- <a href="/catalogs" class="nav-link">Catalogs</a>
370
- <a href="/admin/dashboard" class="nav-link">Admin</a>
371
- <a href="/admin/subscriptions" class="nav-link">Subs</a>
372
- <a href="/admin/access" class="nav-link">Access</a>
373
- <a href="/admin/tools" class="nav-link">Tools</a>
374
- <a href="/admin/settings" class="nav-link">Settings</a>
375
  </div>
376
- {% endif %}
377
-
378
- <div class="flex items-center gap-3">
379
- {% if current_user %}
380
- <button id="menu-btn" class="md:hidden w-10 h-10 flex items-center justify-center text-xl hover:bg-surface-2 rounded-full transition">
381
- <i id="menu-icon" class="fa-solid fa-bars"></i>
382
- </button>
383
-
384
- <div class="relative">
385
- <button id="user-btn" class="w-10 h-10 rounded-full bg-primary/20 hover:bg-primary/30 flex items-center justify-center text-primary text-lg transition border border-primary/30">
386
- <i class="fa-solid fa-user"></i>
387
- </button>
388
-
389
- <div id="user-dropdown" class="absolute right-0 top-14 w-72 glass-panel rounded-2xl p-4 opacity-0 scale-95 pointer-events-none transition-all duration-200 origin-top-right z-50">
390
- <div class="mb-3 border-b border-hairline pb-3">
391
- <p class="text-sm font-bold text-text">{{ current_user }}</p>
392
- <p class="text-[10px] text-green-400 font-bold uppercase tracking-wider flex items-center gap-1">
393
- <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse"></span> Online
394
- </p>
395
- </div>
396
-
397
- <div class="mb-4">
398
- <label class="text-[10px] uppercase text-text-secondary font-bold mb-2 block ml-1">App Theme</label>
399
- <div class="theme-grid">
400
- {% for theme_key, theme_data in themes.items() %}
401
- <button type="button"
402
- onclick="selectTheme('{{ theme_key }}')"
403
- class="theme-chip {% if current_theme==theme_key %}active{% endif %}"
404
- title="{{ theme_data.name }}"
405
- style="--sw-bg:{{ theme_data.colors.background }};--sw-primary:{{ theme_data.colors.primary }};--sw-accent:{{ theme_data.colors.accent }};--sw-text:{{ theme_data.colors.text }}">
406
- <span class="theme-chip-dots">
407
- <span class="dot" style="background:{{ theme_data.colors.primary }}"></span>
408
- <span class="dot" style="background:{{ theme_data.colors.accent }}"></span>
409
- </span>
410
- <span class="theme-chip-name">{{ theme_data.name }}</span>
411
- {% if current_theme==theme_key %}<i class="fa-solid fa-check chip-check"></i>{% endif %}
412
- </button>
413
- {% endfor %}
414
- </div>
415
- <form id="theme-form" method="post" action="/set-theme" class="hidden">
416
- <input type="hidden" name="theme" id="theme-input">
417
- </form>
418
- </div>
419
-
420
- <a href="/admin/settings"
421
- class="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold mb-2 transition-all"
422
- style="background:color-mix(in srgb,var(--primary) 12%,transparent);color:var(--primary)">
423
- <i class="fa-solid fa-gear"></i> Settings
424
- </a>
425
-
426
- <a href="/logout" class="block text-center bg-red-500/10 hover:bg-red-500 text-red-500 hover:text-white px-4 py-2.5 rounded-xl text-sm font-bold transition-all">
427
- Logout
428
- </a>
429
- </div>
430
- </div>
431
- {% else %}
432
- <a href="/login" class="bg-primary hover:bg-primary/80 text-white px-6 py-2 rounded-full text-sm font-bold transition shadow-lg shadow-primary/20">
433
- Login
434
- </a>
435
- {% endif %}
436
  </div>
 
437
 
438
- <div id="mobile-menu" class="absolute top-[calc(100%+12px)] left-0 w-full overflow-hidden max-h-0 opacity-0 transition-all duration-300 ease-in-out md:hidden z-40">
439
- <div class="glass-panel mx-2 rounded-3xl p-4 flex flex-col gap-2">
440
- <a href="/" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-house"></i> Home</a>
441
- <a href="/media/manage" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-clapperboard"></i> Media</a>
442
- <a href="/catalogs" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-layer-group"></i> Catalogs</a>
443
- <a href="/admin/dashboard" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-chart-line"></i> Admin</a>
444
- <a href="/admin/subscriptions" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-credit-card"></i> Subs</a>
445
- <a href="/admin/access" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-shield"></i> Access</a>
446
- <a href="/admin/tools" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-screwdriver-wrench"></i> Tools</a>
447
- <!-- ↓ NEW -->
448
- <a href="/admin/settings" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-gear"></i> Settings</a>
 
 
 
449
  </div>
 
450
  </div>
451
- </nav>
452
 
453
- <main class="flex-1 w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-8">
454
- {% block content %}{% endblock %}
455
- </main>
456
 
457
- <footer class="mt-auto w-full max-w-5xl mx-auto px-6 py-8">
458
- <div class="glass-panel rounded-3xl p-6 flex flex-col md:flex-row justify-between items-center gap-4">
459
- <div class="flex items-center gap-2">
460
- <i class="fa-brands fa-telegram text-primary text-xl"></i>
461
- <p class="text-text-secondary text-sm">© 2026 Telegram Stremio</p>
 
 
 
 
462
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  </div>
464
- </footer>
465
-
466
- <div id="toast-container" class="fixed top-4 right-4 z-[9999] space-y-3 pointer-events-none"></div>
467
-
468
- <script>
469
- const btn = document.getElementById('menu-btn');
470
- const mobileMenu = document.getElementById('mobile-menu');
471
- const overlay = document.getElementById('overlay');
472
- const icon = document.getElementById('menu-icon');
473
- const navbar = document.getElementById('navbar');
474
- const userBtn = document.getElementById('user-btn');
475
- const userDropdown = document.getElementById('user-dropdown');
476
- const navContainer = document.getElementById('nav-container');
477
-
478
- let isMenuOpen = false;
479
- let isUserOpen = false;
480
-
481
- function toggleMenu() {
482
- isMenuOpen = !isMenuOpen;
483
- if(isUserOpen) closeUser();
484
- if (isMenuOpen) {
485
- mobileMenu.style.maxHeight = mobileMenu.scrollHeight + "px";
486
- mobileMenu.style.opacity = "1";
487
- overlay.style.opacity = "1";
488
- overlay.classList.remove("pointer-events-none");
489
- icon.classList.replace("fa-bars","fa-xmark");
490
- } else closeMenu();
491
- }
492
-
493
- function closeMenu() {
494
- mobileMenu.style.maxHeight = "0px";
495
- mobileMenu.style.opacity = "0";
496
- icon.classList.replace("fa-xmark","fa-bars");
497
- isMenuOpen = false;
498
- checkOverlay();
499
- }
500
 
501
- function toggleUser(e) {
502
- if(e) e.stopPropagation();
503
- isUserOpen = !isUserOpen;
504
- if(isMenuOpen) closeMenu();
505
- if (isUserOpen) {
506
- userDropdown.classList.remove("opacity-0", "scale-95", "pointer-events-none");
507
- overlay.style.opacity = "1";
508
- overlay.classList.remove("pointer-events-none");
509
- } else closeUser();
510
- }
511
 
512
- function closeUser() {
513
- if(userDropdown) userDropdown.classList.add("opacity-0", "scale-95", "pointer-events-none");
514
- isUserOpen = false;
515
- checkOverlay();
516
- }
517
 
518
- function checkOverlay() {
519
- if (!isMenuOpen && !isUserOpen) {
520
- overlay.style.opacity = "0";
521
- overlay.classList.add("pointer-events-none");
522
- }
 
 
523
  }
524
 
525
- function showToast(message, type = 'info', title = '') {
526
  const container = document.getElementById('toast-container');
527
  if (!container) return;
528
-
529
  const toast = document.createElement('div');
530
  toast.className = `toast ${type}`;
531
-
532
- const icon = type === 'success'
533
- ? 'fa-circle-check'
534
- : type === 'error'
535
- ? 'fa-triangle-exclamation'
536
- : 'fa-circle-info';
537
-
538
- toast.innerHTML = `
539
- <i class="fa-solid ${icon} mt-0.5"></i>
540
- <div class="min-w-0">
541
- ${title ? `<div class="toast-title">${escapeHtml(title)}</div>` : ''}
542
- <div class="toast-message">${escapeHtml(message)}</div>
543
- </div>
544
- `;
545
-
546
  container.appendChild(toast);
547
-
548
  setTimeout(() => {
549
- toast.style.animation = 'toast-out 180ms ease-in forwards';
550
- setTimeout(() => {
551
- if (toast.parentNode) toast.parentNode.removeChild(toast);
552
- }, 200);
553
- }, 2600);
554
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
 
556
- function escapeHtml(str) {
557
- return String(str || '')
558
- .replace(/&/g, '&amp;')
559
- .replace(/</g, '&lt;')
560
- .replace(/>/g, '&gt;')
561
- .replace(/"/g, '&quot;')
562
- .replace(/'/g, '&#039;');
563
- }
564
 
565
- function selectTheme(key) {
566
- const input = document.getElementById('theme-input');
567
- const form = document.getElementById('theme-form');
568
- if (!input || !form) return;
569
- input.value = key;
570
- form.submit();
571
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
 
573
- if(btn) btn.onclick = toggleMenu;
574
- if(userBtn) userBtn.onclick = toggleUser;
575
- overlay.onclick = () => { closeMenu(); closeUser(); };
576
-
577
- let scrollTicking = false;
578
- let navScrolled = false;
579
- window.addEventListener("scroll", () => {
580
- if (isMenuOpen) closeMenu();
581
- if (isUserOpen) closeUser();
582
- if (!scrollTicking) {
583
- scrollTicking = true;
584
- requestAnimationFrame(() => {
585
- const past = window.scrollY > 20;
586
- if (past !== navScrolled) {
587
- navScrolled = past;
588
- navbar.classList.toggle("nav-scrolled", past);
 
 
 
 
589
  }
590
- scrollTicking = false;
591
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
592
  }
593
- }, { passive: true });
594
-
595
- document.addEventListener("keydown", e => {
596
- if (e.key === "Escape") { closeMenu(); closeUser(); }
597
- });
598
 
599
- if (userDropdown) {
600
- userDropdown.addEventListener("click", e => e.stopPropagation());
601
- }
 
 
 
 
 
 
 
 
 
 
 
 
602
 
603
- const links = document.querySelectorAll(".nav-link");
604
- const pill = document.getElementById("active-pill");
605
- let activeLink = null;
606
-
607
- function movePill(el) {
608
- if(!pill || !el) return;
609
- const r = el.getBoundingClientRect();
610
- const pr = el.parentElement.getBoundingClientRect();
611
- pill.style.width = r.width + "px";
612
- pill.style.height = r.height + "px";
613
- pill.style.left = (r.left - pr.left) + "px";
614
- pill.style.top = (r.top - pr.top) + "px";
615
- }
 
 
 
 
 
 
616
 
617
- window.addEventListener('load', () => {
618
- const current = window.location.pathname;
619
- activeLink = [...links].find(l => l.getAttribute("href") === current) || links[0];
620
- if(activeLink) {
621
- activeLink.classList.add('active-page');
622
- movePill(activeLink);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  }
624
- });
625
 
626
- links.forEach(l => {
627
- l.addEventListener("mouseenter", () => movePill(l));
628
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
629
 
630
- if(navContainer) {
631
- navContainer.addEventListener("mouseleave", () => {
632
- if(activeLink) movePill(activeLink);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
  });
 
 
 
 
 
 
634
  }
635
  </script>
636
-
637
  </body>
638
  </html>
 
1
+ {%- macro rgb(h) -%}{{ h[1:3]|int(base=16) }} {{ h[3:5]|int(base=16) }} {{ h[5:7]|int(base=16) }}{%- endmacro -%}
2
+ {%- set path = request.url.path -%}
3
+ {%- set nav = [
4
+ ('/', 'Home', 'fa-house', '/'),
5
+ ('/media/manage', 'Media', 'fa-clapperboard', '/media'),
6
+ ('/catalogs', 'Catalogs', 'fa-layer-group', '/catalogs'),
7
+ ('/admin/dashboard', 'Admin', 'fa-chart-simple', '/admin/dashboard'),
8
+ ('/admin/subscriptions', 'Plans', 'fa-credit-card', '/admin/subscriptions'),
9
+ ('/admin/access', 'Tokens', 'fa-key', '/admin/access'),
10
+ ('/admin/requests', 'Requests', 'fa-inbox', '/admin/requests'),
11
+ ('/admin/tools', 'Tools', 'fa-screwdriver-wrench', '/admin/tools'),
12
+ ('/admin/settings', 'Settings', 'fa-gear', '/admin/settings'),
13
+ ] -%}
14
+ {%- set dock_count = 4 -%}
15
+ {%- macro is_active(prefix) -%}{{ 'true' if (prefix == '/' and path == '/') or (prefix != '/' and path.startswith(prefix)) else '' }}{%- endmacro -%}
16
  <!DOCTYPE html>
17
+ <html lang="en" data-theme="{{ current_theme }}" class="{{ 'dark' if theme.is_dark else 'light' }}">
18
  <head>
19
  <meta charset="UTF-8">
20
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
21
  <title>{% block title %}Telegram Stremio{% endblock %}</title>
22
 
23
+ <link rel="icon" type="image/svg+xml" href="/pwa-icon.svg">
24
+ <link rel="apple-touch-icon" href="/pwa-icon.svg">
25
+ <link rel="manifest" href="/manifest.webmanifest">
26
+ <meta name="theme-color" content="{{ theme.colors.background }}">
27
+ <meta name="apple-mobile-web-app-capable" content="yes">
28
+ <meta name="apple-mobile-web-app-status-bar-style" content="{{ 'black-translucent' if theme.is_dark else 'default' }}">
29
+ <meta name="mobile-web-app-capable" content="yes">
30
 
31
+ <link rel="preconnect" href="https://image.tmdb.org">
32
+ <link rel="preconnect" href="https://images.metahub.space">
33
  <link rel="preconnect" href="https://fonts.googleapis.com">
34
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
35
+ <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
36
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
37
+ <script src="https://cdn.tailwindcss.com/3.4.16"></script>
38
 
39
  <style>
40
+ {% for key, t in themes.items() %}
41
+ :root[data-theme="{{ key }}"] {
42
+ color-scheme: {{ 'dark' if t.is_dark else 'light' }};
43
+ --primary: {{ t.colors.primary }};
44
+ --on-primary: {{ t.colors.on_primary }};
45
+ --bg: {{ t.colors.background }};
46
+ --card: {{ t.colors.card }};
47
+ --card-high: {{ t.colors.card_high }};
48
+ --border: {{ t.colors.border }};
49
+ --text: {{ t.colors.text }};
50
+ --text-sec: {{ t.colors.text_secondary }};
51
+ --danger: {{ t.colors.danger }};
52
+ --ok: {{ t.colors.ok }};
53
+ --warn: {{ '#D9A63A' if key == 'ink' else ('#A15C07' if key == 'paper' else '#D6B370') }};
54
+ --info: {{ '#7FA7D9' if key == 'ink' else ('#2F5F9E' if key == 'paper' else '#8FA9C9') }};
55
+ --primary-rgb: {{ rgb(t.colors.primary) }};
56
+ --on-primary-rgb: {{ rgb(t.colors.on_primary) }};
57
+ --bg-rgb: {{ rgb(t.colors.background) }};
58
+ --card-rgb: {{ rgb(t.colors.card) }};
59
+ --card-high-rgb: {{ rgb(t.colors.card_high) }};
60
+ --border-rgb: {{ rgb(t.colors.border) }};
61
+ --text-rgb: {{ rgb(t.colors.text) }};
62
+ --text-sec-rgb: {{ rgb(t.colors.text_secondary) }};
63
+ --danger-rgb: {{ rgb(t.colors.danger) }};
64
+ --ok-rgb: {{ rgb(t.colors.ok) }};
65
+ --warn-rgb: {{ '217 166 58' if key == 'ink' else ('161 92 7' if key == 'paper' else '214 179 112') }};
66
+ --info-rgb: {{ '127 167 217' if key == 'ink' else ('47 95 158' if key == 'paper' else '143 169 201') }};
67
+ --scrim: {{ 'rgba(0,0,0,.6)' if t.is_dark else 'rgba(29,27,24,.35)' }};
68
+ }
69
+ {% endfor %}
70
  :root {
71
+ --secondary: var(--primary);
72
+ --accent: var(--primary);
73
+ --surface: color-mix(in srgb, var(--text) 4%, transparent);
74
+ --surface-2: color-mix(in srgb, var(--text) 7%, transparent);
75
+ --surface-3: color-mix(in srgb, var(--text) 11%, transparent);
76
+ --hairline: var(--border);
77
+ --hairline-strong: color-mix(in srgb, var(--text) 18%, var(--border));
78
+ --muted: var(--text-sec);
79
+ --ring: color-mix(in srgb, var(--primary) 28%, transparent);
80
+ --radius: 20px;
81
+ --radius-sm: 14px;
82
+ --ease: cubic-bezier(.2, .8, .2, 1);
83
+ --spring: cubic-bezier(.34, 1.4, .5, 1);
84
+ --rail: 88px;
85
+ --shadow-soft: none;
86
+ --shadow-strong: 0 18px 48px rgba(0,0,0,.28);
87
+ }
88
+
89
+ @view-transition { navigation: auto; }
90
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
91
+ #rail { view-transition-name: rail; }
92
+ #dock { view-transition-name: dock; }
93
+
94
+ html { scroll-behavior: auto; -webkit-tap-highlight-color: transparent; text-size-adjust: 100%; }
95
+ html, body { max-width: 100%; overflow-x: clip; }
 
 
 
 
 
 
 
 
96
  body {
97
+ margin: 0;
98
+ font-family: 'Space Grotesk', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
99
+ font-size: 15px;
100
+ line-height: 1.5;
101
  -webkit-font-smoothing: antialiased;
102
+ -moz-osx-font-smoothing: grayscale;
103
+ background: var(--bg);
104
  color: var(--text);
105
+ min-height: 100dvh;
106
+ transition: background-color .25s var(--ease), color .25s var(--ease);
107
+ }
108
+ img { max-width: 100%; }
109
+ code, pre, kbd, .font-mono { font-family: 'JetBrains Mono', ui-monospace, monospace; }
110
+ h1, h2, h3, h4 { letter-spacing: -0.015em; }
111
+ .tabular { font-variant-numeric: tabular-nums; }
112
+ ::selection { background: color-mix(in srgb, var(--primary) 32%, transparent); color: var(--text); }
113
+ :focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
114
 
115
+ * { scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
116
+ *::-webkit-scrollbar { width: 10px; height: 10px; }
117
+ *::-webkit-scrollbar-thumb { background: var(--border); border-radius: 99px; border: 3px solid transparent; background-clip: padding-box; }
118
+ *::-webkit-scrollbar-thumb:hover { background: var(--text-sec); background-clip: padding-box; }
119
+
120
+ input, select, textarea, button { font-family: inherit; }
121
+ input:not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]), select, textarea { color: var(--text); }
122
+ input::placeholder, textarea::placeholder { color: color-mix(in srgb, var(--text-sec) 80%, transparent); opacity: 1; }
123
+ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; }
124
+ select:not([multiple]):not([size]) {
125
+ -webkit-appearance: none;
126
+ appearance: none;
127
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23888' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 6l4 4 4-4'/%3E%3C/svg%3E") !important;
128
+ background-repeat: no-repeat !important;
129
+ background-position: right .85rem center !important;
130
+ background-size: 14px !important;
131
+ padding-right: 2.4rem !important;
132
+ cursor: pointer;
133
  }
134
+ select option, select optgroup { background-color: var(--card); color: var(--text); }
135
+ input[type="checkbox"], input[type="radio"], input[type="range"] { accent-color: var(--primary); }
136
+ input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:focus, textarea:-webkit-autofill {
137
+ -webkit-text-fill-color: var(--text);
138
+ -webkit-box-shadow: 0 0 0 1000px var(--card) inset;
139
+ caret-color: var(--text);
140
+ transition: background-color 9999s ease-in-out 0s;
141
  }
142
+ button, a, [role="button"] { touch-action: manipulation; }
143
+ button:disabled { cursor: not-allowed; opacity: .5; }
144
 
145
+ .glass-panel, .surface-card, .glass-card, .glass-card-soft {
146
+ background: var(--card);
147
+ border: 1px solid var(--border);
148
+ border-radius: var(--radius);
149
+ box-shadow: none;
150
  }
151
+ .glass-nav { background: var(--card); }
152
  .glass-pill { border-radius: 9999px; }
153
 
154
+ .btn-primary, .btn-ghost, .btn-danger {
155
+ display: inline-flex;
156
+ align-items: center;
157
+ justify-content: center;
158
+ gap: .5rem;
159
+ border-radius: 9999px;
160
+ font-weight: 500;
161
+ white-space: nowrap;
162
+ border: 1px solid transparent;
163
+ transition: background-color .18s var(--ease), border-color .18s var(--ease), color .18s var(--ease), transform .12s var(--ease), filter .18s var(--ease);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  }
165
+ .btn-primary { background: var(--primary); color: var(--on-primary); }
166
+ .btn-primary:hover { filter: brightness(1.07); }
167
+ .btn-ghost { background: transparent; color: var(--text); border-color: var(--border); }
168
+ .btn-ghost:hover { background: var(--card-high); }
169
+ .btn-danger { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); border-color: color-mix(in srgb, var(--danger) 30%, transparent); }
170
+ .btn-danger:hover { background: color-mix(in srgb, var(--danger) 20%, transparent); }
171
+ .btn-primary:active, .btn-ghost:active, .btn-danger:active { transform: scale(.97); }
172
 
173
  .badge {
174
  display: inline-flex;
175
  align-items: center;
176
  gap: .35rem;
177
+ font-size: .68rem;
178
+ font-weight: 500;
179
+ letter-spacing: .06em;
180
  text-transform: uppercase;
181
+ padding: .2rem .6rem;
 
182
  border-radius: 9999px;
183
  background: color-mix(in srgb, var(--primary) 14%, transparent);
184
  color: var(--primary);
185
+ white-space: nowrap;
186
  }
187
 
188
  .field {
189
  width: 100%;
190
+ background: var(--bg);
191
  color: var(--text);
192
+ border: 1px solid var(--border);
193
+ border-radius: var(--radius-sm);
194
+ transition: border-color .18s var(--ease), box-shadow .18s var(--ease);
 
 
 
 
 
195
  }
196
+ .field:hover { border-color: var(--hairline-strong); }
197
+ .field:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
198
 
199
+ .label-caps {
200
+ font-size: .72rem;
201
+ font-weight: 500;
202
+ letter-spacing: .1em;
203
+ text-transform: uppercase;
 
 
 
 
 
 
 
204
  color: var(--text-sec);
 
 
 
 
 
 
 
205
  }
206
 
207
+ .page-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 1rem; margin-bottom: 2rem; }
208
+ .page-head > div:first-child { min-width: 0; }
209
+ .page-title { font-size: 28px; font-weight: 600; line-height: 1.15; letter-spacing: -.02em; }
210
+ .page-sub { margin-top: .3rem; color: var(--text-sec); font-size: .92rem; }
211
+ .page-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
212
+ @media (min-width: 640px) { .page-title { font-size: 30px; } }
213
+ .section-label { display: flex; align-items: center; justify-content: space-between; gap: .75rem; margin: 0 .25rem .65rem; font-size: .72rem; font-weight: 500; letter-spacing: .1em; text-transform: uppercase; color: var(--text-sec); }
214
+
215
+ .seg { display: inline-flex; padding: 4px; gap: 2px; border-radius: 9999px; background: var(--card); border: 1px solid var(--border); }
216
+ .seg > a, .seg > button { display: inline-flex; align-items: center; gap: .45rem; padding: .45rem .95rem; border-radius: 9999px; font-size: .88rem; color: var(--text-sec); text-decoration: none; white-space: nowrap; transition: background-color .2s var(--ease), color .2s var(--ease); }
217
+ .seg > a:hover, .seg > button:hover { color: var(--text); }
218
+ .seg > [aria-selected="true"], .seg > .active { background: var(--card-high); color: var(--primary); }
219
+ .chip-toggle { display: inline-flex; align-items: center; gap: .45rem; padding: .5rem .95rem; border-radius: 9999px; font-size: .88rem; color: var(--text-sec); border: 1px solid var(--border); cursor: pointer; user-select: none; transition: all .18s var(--ease); }
220
+ .chip-toggle:hover { color: var(--text); }
221
+ .chip-toggle:has(input:checked) { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 50%, var(--border)); background: color-mix(in srgb, var(--primary) 10%, transparent); }
222
+ .pg-btn { min-width: 2.4rem; height: 2.4rem; padding: 0 .85rem; border-radius: 9999px; font-size: .88rem; color: var(--text); border: 1px solid var(--border); background: transparent; transition: background-color .15s var(--ease); }
223
+ .pg-btn:hover { background: var(--card-high); }
224
+ .pg-btn[aria-current="page"] { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
225
+
226
+ .hidden:not([class*=":flex"]):not([class*=":block"]):not([class*=":grid"]):not([class*=":inline"]):not([class*=":table"]) { display: none !important; }
227
+
228
+ #nav-progress { position: fixed; top: 0; left: 0; z-index: 10000; height: 3px; width: 0; background: var(--primary); box-shadow: 0 0 8px color-mix(in srgb, var(--primary) 60%, transparent); opacity: 0; pointer-events: none; border-radius: 0 3px 3px 0; }
229
+ #nav-progress.run { opacity: 1; animation: nav-progress 8s cubic-bezier(.08,.75,.2,1) forwards; }
230
+ @keyframes nav-progress { 0% { width: 0; } 6% { width: 35%; } 30% { width: 65%; } 100% { width: 92%; } }
231
+
232
+ #cmdk, #keys { padding: 0; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--text); box-shadow: var(--shadow-strong); width: min(640px, calc(100vw - 32px)); max-height: min(560px, calc(100dvh - 120px)); margin: 12vh auto auto; overflow: hidden; }
233
+ #cmdk[open], #keys[open] { display: flex; flex-direction: column; animation: cmdk-in .18s var(--ease); }
234
+ #cmdk::backdrop, #keys::backdrop { background: var(--scrim); }
235
+ @keyframes cmdk-in { from { opacity: 0; transform: translateY(-6px) scale(.985); } to { opacity: 1; transform: none; } }
236
+ .cmdk-head { display: flex; align-items: center; gap: .75rem; padding: .9rem 1.1rem; border-bottom: 1px solid var(--border); }
237
+ .cmdk-head i { color: var(--text-sec); }
238
+ .cmdk-head input { flex: 1; min-width: 0; background: none; border: 0; outline: none; font-size: 1rem; color: var(--text); }
239
+ .cmdk-list { overflow-y: auto; padding: .4rem; overscroll-behavior: contain; }
240
+ .cmdk-group { padding: .65rem .75rem .3rem; font-size: .7rem; letter-spacing: .1em; text-transform: uppercase; color: var(--text-sec); }
241
+ .cmdk-item { display: flex; align-items: center; gap: .75rem; width: 100%; padding: .55rem .75rem; border: 0; border-radius: 12px; background: none; color: var(--text); text-align: left; font-size: .92rem; cursor: pointer; }
242
+ .cmdk-item > i { width: 1.1rem; text-align: center; color: var(--text-sec); }
243
+ .cmdk-item img { width: 28px; height: 42px; border-radius: 5px; object-fit: cover; background: var(--card-high); flex-shrink: 0; }
244
+ .cmdk-item .t { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
245
+ .cmdk-item .t small { color: var(--text-sec); margin-left: .4rem; }
246
+ .cmdk-item[aria-selected="true"] { background: var(--card-high); }
247
+ .cmdk-item[aria-selected="true"] > i { color: var(--primary); }
248
+ .cmdk-empty { padding: 1.5rem; text-align: center; color: var(--text-sec); font-size: .9rem; }
249
+ .cmdk-foot { display: flex; flex-wrap: wrap; gap: .4rem 1rem; padding: .6rem 1.1rem; border-top: 1px solid var(--border); font-size: .76rem; color: var(--text-sec); }
250
+ kbd.k { display: inline-grid; place-items: center; min-width: 1.4rem; height: 1.4rem; padding: 0 .35rem; border-radius: 6px; border: 1px solid var(--border); border-bottom-width: 2px; background: var(--bg); color: var(--text-sec); font: 500 .72rem/1 'Space Grotesk', ui-sans-serif, system-ui, sans-serif; }
251
+ .keys-body { overflow-y: auto; padding: .5rem 1.1rem 1.1rem; }
252
+ #cmdk:focus-visible, #keys:focus-visible, .keys-body:focus-visible, .cmdk-list:focus-visible { outline: none; }
253
+ .keys-body h3 { font-size: .7rem; letter-spacing: .1em; text-transform: uppercase; color: var(--text-sec); margin: .9rem 0 .4rem; font-weight: 500; }
254
+ .keys-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: .4rem 0; font-size: .9rem; border-bottom: 1px solid var(--border); }
255
+ .keys-row:last-child { border-bottom: 0; }
256
+ .keys-row span:last-child { display: inline-flex; gap: .25rem; align-items: center; flex-shrink: 0; color: var(--text-sec); font-size: .78rem; }
257
+ .rail-search .ico { border: 1px solid var(--border); }
258
+ @media (max-width: 767.98px) { #cmdk { margin-top: 10vh; } }
259
+
260
+ .page-in { animation: page-in .32s var(--ease); }
261
+ @keyframes page-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
262
+
263
+ #rail {
264
+ position: fixed;
265
+ inset: 0 auto 0 0;
266
+ width: var(--rail);
267
+ z-index: 40;
268
+ display: flex;
269
+ flex-direction: column;
270
+ align-items: center;
271
+ gap: .25rem;
272
+ padding: 1rem 0 .9rem;
273
+ background: var(--bg);
274
+ border-right: 1px solid var(--border);
275
  }
276
+ .rail-logo { display: grid; place-items: center; width: 44px; height: 44px; margin-bottom: .9rem; border-radius: 14px; background: var(--primary); color: var(--on-primary); transition: transform .2s var(--spring); }
277
+ .rail-logo:hover { transform: scale(1.06) rotate(-4deg); }
278
+ .rail-nav { display: flex; flex-direction: column; align-items: center; gap: .15rem; overflow-y: auto; scrollbar-width: none; flex: 1; min-height: 0; width: 100%; padding: 0 .5rem; }
279
+ .rail-nav::-webkit-scrollbar { display: none; }
280
+ .rail-item {
281
+ display: flex;
282
+ flex-direction: column;
283
+ align-items: center;
284
+ gap: .3rem;
285
+ width: 100%;
286
+ padding: .35rem 0 .45rem;
287
+ font-size: .72rem;
288
+ color: var(--text-sec);
289
+ text-decoration: none;
290
+ border-radius: 14px;
291
+ transition: color .18s var(--ease);
292
+ }
293
+ .rail-item .ico { display: grid; place-items: center; width: 56px; height: 32px; border-radius: 9999px; font-size: 1rem; transition: background-color .22s var(--ease), color .18s var(--ease), transform .25s var(--spring); }
294
+ .rail-item:hover { color: var(--text); }
295
+ .rail-item:hover .ico { background: var(--surface-2); }
296
+ .rail-item:active .ico { transform: scale(.9); }
297
+ .rail-item[aria-current="page"] { color: var(--text); font-weight: 500; }
298
+ .rail-item[aria-current="page"] .ico { background: var(--card-high); color: var(--primary); }
299
+
300
+ #topbar {
301
+ position: sticky;
302
+ top: 0;
303
+ z-index: 30;
304
+ display: flex;
305
+ align-items: center;
306
+ justify-content: space-between;
307
+ gap: .75rem;
308
+ height: calc(56px + env(safe-area-inset-top));
309
+ padding: env(safe-area-inset-top) 16px 0;
310
+ background: var(--bg);
311
+ border-bottom: 1px solid transparent;
312
+ transition: border-color .2s var(--ease);
313
+ }
314
+ #topbar.scrolled { border-color: var(--border); }
315
+ .brand { display: flex; align-items: center; gap: .6rem; color: var(--text); text-decoration: none; font-weight: 600; font-size: 1.05rem; letter-spacing: -.01em; min-width: 0; }
316
+ .brand-mark { display: grid; place-items: center; flex-shrink: 0; width: 30px; height: 30px; border-radius: 10px; background: var(--primary); color: var(--on-primary); font-size: .7rem; }
317
+ .icon-btn { display: grid; place-items: center; width: 40px; height: 40px; flex-shrink: 0; border-radius: 9999px; color: var(--text-sec); background: transparent; border: 0; cursor: pointer; transition: background-color .18s var(--ease), color .18s var(--ease), transform .12s var(--ease); }
318
+ .icon-btn:hover { background: var(--surface-2); color: var(--text); }
319
+ .icon-btn:active { transform: scale(.92); }
320
 
321
+ #dock {
322
+ position: fixed;
323
+ left: 50%;
324
+ bottom: calc(12px + env(safe-area-inset-bottom));
325
+ z-index: 40;
326
+ width: min(calc(100% - 32px), 480px);
327
+ transform: translateX(-50%);
328
+ padding: 5px;
329
  border-radius: 9999px;
330
+ background: var(--card-high);
331
+ border: 1px solid var(--border);
332
+ box-shadow: 0 10px 30px rgba(0,0,0,{{ '.45' if theme.is_dark else '.12' }});
333
  }
334
+ .dock-row { position: relative; display: grid; grid-template-columns: repeat({{ dock_count + 1 }}, minmax(0, 1fr)); height: 52px; }
335
+ .dock-pill { position: absolute; top: 0; bottom: 0; left: 0; width: calc(100% / {{ dock_count + 1 }}); border-radius: 9999px; background: color-mix(in srgb, var(--primary) 18%, transparent); transition: transform .42s var(--spring); pointer-events: none; }
336
+ .dock-item { position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-width: 0; color: var(--text-sec); text-decoration: none; font-size: .68rem; letter-spacing: .02em; background: none; border: 0; cursor: pointer; border-radius: 9999px; transition: color .2s var(--ease); }
337
+ .dock-item i { font-size: 1.05rem; transition: transform .3s var(--spring); }
338
+ .dock-item span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 2px; }
339
+ .dock-item[aria-current="page"], .dock-item.on { color: var(--primary); }
340
+ .dock-item[aria-current="page"] i { transform: scale(1.08); }
341
+ .dock-item:active i { transform: scale(.84); }
342
 
343
+ .scrim { position: fixed; inset: 0; z-index: 45; background: var(--scrim); opacity: 0; pointer-events: none; transition: opacity .22s var(--ease); }
344
+ .scrim.open { opacity: 1; pointer-events: auto; }
345
+
346
+ #sheet {
347
+ position: fixed;
348
+ left: 0;
349
+ right: 0;
350
+ bottom: 0;
351
+ z-index: 46;
352
+ max-height: 86dvh;
353
+ overflow-y: auto;
354
+ overscroll-behavior: contain;
355
+ padding: 10px 16px calc(20px + env(safe-area-inset-bottom));
356
+ background: var(--card);
357
+ border-top: 1px solid var(--border);
358
+ border-radius: 24px 24px 0 0;
359
+ transform: translateY(105%);
360
+ visibility: hidden;
361
+ transition: transform .34s var(--ease), visibility 0s linear .34s;
362
+ }
363
+ #sheet.open { transform: none; visibility: visible; transition: transform .34s var(--ease), visibility 0s; }
364
+ .sheet-grip { width: 36px; height: 4px; margin: 0 auto 14px; border-radius: 99px; background: var(--border); }
365
+ .sheet-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .5rem; }
366
+ .sheet-link { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: .45rem; min-height: 76px; padding: .6rem .25rem; border-radius: 16px; border: 1px solid var(--border); background: var(--bg); color: var(--text); text-decoration: none; font-size: .8rem; text-align: center; transition: background-color .18s var(--ease), transform .12s var(--ease); }
367
+ .sheet-link i { color: var(--text-sec); font-size: 1.05rem; }
368
+ .sheet-link:active { transform: scale(.96); }
369
+ .sheet-link[aria-current="page"] { border-color: color-mix(in srgb, var(--primary) 50%, var(--border)); }
370
+ .sheet-link[aria-current="page"] i { color: var(--primary); }
371
+
372
+ #account-pop {
373
+ position: fixed;
374
+ left: calc(var(--rail) + 10px);
375
+ bottom: 14px;
376
+ z-index: 46;
377
+ width: 280px;
378
+ padding: .9rem;
379
+ background: var(--card);
380
  border: 1px solid var(--border);
381
+ border-radius: var(--radius);
382
+ box-shadow: var(--shadow-strong);
383
+ opacity: 0;
384
+ transform: translateX(-6px) scale(.98);
385
+ transform-origin: bottom left;
386
+ pointer-events: none;
387
+ visibility: hidden;
388
+ transition: opacity .18s var(--ease), transform .22s var(--ease), visibility 0s linear .22s;
 
 
389
  }
390
+ #account-pop.open { opacity: 1; transform: none; pointer-events: auto; visibility: visible; transition: opacity .18s var(--ease), transform .22s var(--ease), visibility 0s; }
391
 
392
+ .theme-opts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .5rem; }
393
+ .theme-opt { display: flex; flex-direction: column; align-items: center; gap: .45rem; padding: .6rem .25rem .5rem; border-radius: 14px; border: 1px solid var(--border); background: transparent; color: var(--text-sec); font-size: .78rem; cursor: pointer; transition: border-color .18s var(--ease), color .18s var(--ease), transform .12s var(--ease); }
394
+ .theme-opt:hover { color: var(--text); }
395
+ .theme-opt:active { transform: scale(.96); }
396
+ .theme-opt[aria-pressed="true"] { border-color: var(--primary); color: var(--text); }
397
+ .swatch { position: relative; width: 34px; height: 34px; border-radius: 9999px; overflow: hidden; border: 1px solid color-mix(in srgb, var(--text) 16%, transparent); }
398
+ .swatch::after { content: ""; position: absolute; right: 6px; bottom: 6px; width: 12px; height: 12px; border-radius: 9999px; background: var(--sw); }
399
 
400
+ .menu-row { display: flex; align-items: center; gap: .7rem; width: 100%; padding: .65rem .75rem; border-radius: 12px; color: var(--text); text-decoration: none; font-size: .9rem; background: none; border: 0; cursor: pointer; transition: background-color .15s var(--ease); }
401
+ .menu-row:hover { background: var(--surface-2); }
402
+ .menu-row i { width: 1rem; text-align: center; color: var(--text-sec); }
403
+ .menu-row.danger, .menu-row.danger i { color: var(--danger); }
404
 
405
+ #update-banner { display: flex; align-items: center; gap: .85rem; margin-bottom: 1.5rem; padding: .85rem 1rem; border-radius: var(--radius-sm); border: 1px solid color-mix(in srgb, var(--primary) 40%, var(--border)); background: color-mix(in srgb, var(--primary) 9%, var(--card)); }
406
+ #update-banner[hidden] { display: none; }
407
 
408
+ #toast-container { position: fixed; z-index: 9999; top: 16px; right: 16px; display: flex; flex-direction: column; gap: .5rem; pointer-events: none; }
409
+ .toast {
410
+ pointer-events: auto;
411
+ display: flex;
412
+ align-items: flex-start;
413
+ gap: .7rem;
414
+ width: 340px;
415
+ max-width: calc(100vw - 32px);
416
+ padding: .8rem 1rem;
417
+ border-radius: 16px;
418
+ background: var(--card-high);
419
  border: 1px solid var(--border);
 
 
 
 
 
 
 
 
 
 
 
 
420
  color: var(--text);
421
+ box-shadow: var(--shadow-strong);
422
+ animation: toast-in .26s var(--ease);
423
  }
424
+ .toast > i { margin-top: .2rem; }
425
+ .toast.success > i { color: var(--ok); }
426
+ .toast.error > i { color: var(--danger); }
427
+ .toast.info > i { color: var(--primary); }
428
+ .toast-title { font-weight: 600; font-size: .9rem; line-height: 1.25; }
429
+ .toast-message { font-size: .84rem; color: var(--text-sec); line-height: 1.4; overflow-wrap: anywhere; }
430
+ @keyframes toast-in { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: none; } }
431
+ @keyframes toast-out { to { opacity: 0; transform: translateY(-6px); } }
 
 
 
 
 
 
 
 
 
 
 
 
432
 
433
+ .shell { min-width: 0; }
434
+ @media (min-width: 768px) {
435
+ .shell { padding-left: var(--rail); }
436
+ #topbar, #dock, #sheet { display: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  }
438
+ @media (max-width: 767.98px) {
439
+ #rail, #account-pop { display: none; }
440
+ #toast-container { top: calc(64px + env(safe-area-inset-top)); left: 16px; right: 16px; align-items: stretch; }
441
+ .toast { width: auto; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  }
443
 
444
+ @media (prefers-reduced-motion: reduce) {
445
+ html { scroll-behavior: auto; }
446
+ *, *::before, *::after { animation-duration: .001ms !important; animation-iteration-count: 1 !important; transition-duration: .001ms !important; }
447
  }
 
 
448
  </style>
449
 
450
  <script>
451
+ (function () {
452
+ var c = function (v) { return 'rgb(var(--' + v + '-rgb) / <alpha-value>)'; };
453
+ var scale = function (v) { var o = {}; [50,100,200,300,400,500,600,700,800,900,950].forEach(function (k) { o[k] = c(v); }); return o; };
454
+ tailwind.config = {
455
+ darkMode: 'class',
456
+ theme: {
457
+ extend: {
458
+ fontFamily: {
459
+ sans: ['"Space Grotesk"', 'ui-sans-serif', 'system-ui', 'sans-serif'],
460
+ mono: ['"JetBrains Mono"', 'ui-monospace', 'monospace']
461
+ },
462
+ colors: {
463
+ primary: c('primary'),
464
+ secondary: c('primary'),
465
+ accent: c('primary'),
466
+ 'on-primary': c('on-primary'),
467
+ background: c('bg'),
468
+ card: c('card'),
469
+ 'card-high': c('card-high'),
470
+ border: c('border'),
471
+ hairline: c('border'),
472
+ text: c('text'),
473
+ 'text-secondary': c('text-sec'),
474
+ muted: c('text-sec'),
475
+ ok: c('ok'),
476
+ danger: c('danger'),
477
+ warn: c('warn'),
478
+ info: c('info'),
479
+ surface: 'var(--surface)',
480
+ 'surface-2': 'var(--surface-2)',
481
+ 'surface-3': 'var(--surface-3)',
482
+ 'hairline-strong': 'var(--hairline-strong)',
483
+ red: scale('danger'), rose: scale('danger'),
484
+ green: scale('ok'), emerald: scale('ok'), lime: scale('ok'), teal: scale('ok'),
485
+ amber: scale('warn'), yellow: scale('warn'), orange: scale('warn'),
486
+ blue: scale('info'), sky: scale('info'), cyan: scale('info'), indigo: scale('info'),
487
+ purple: scale('primary'), violet: scale('primary'), fuchsia: scale('primary'), pink: scale('primary')
488
+ },
489
+ borderRadius: { '3xl': '20px', '4xl': '24px' },
490
+ boxShadow: { soft: 'none', strong: 'var(--shadow-strong)', glow: 'none' }
491
  }
492
  }
493
+ };
494
+ })();
495
+ if (!navigator.clipboard) Object.defineProperty(navigator, 'clipboard', { value: { writeText: function (t) { return new Promise(function (ok, fail) {
496
+ var a = document.createElement('textarea');
497
+ a.value = t; a.style.cssText = 'position:fixed;opacity:0';
498
+ document.body.appendChild(a); a.select();
499
+ var done = document.execCommand('copy'); a.remove();
500
+ done ? ok() : fail(new Error('Copy failed'));
501
+ }); } } });
502
  </script>
503
  </head>
504
 
505
+ <body>
506
+ <div id="nav-progress" aria-hidden="true"></div>
507
+ {% if current_user %}
508
+ <aside id="rail" aria-label="Primary">
509
+ <a href="/" class="rail-logo" aria-label="Home"><i class="fa-solid fa-play text-sm"></i></a>
510
+ <nav class="rail-nav">
511
+ {% for href, label, icon, prefix in nav %}
512
+ <a href="{{ href }}" class="rail-item" {% if is_active(prefix) %}aria-current="page"{% endif %}>
513
+ <span class="ico"><i class="fa-solid {{ icon }}"></i></span>{{ label }}
514
+ </a>
515
+ {% endfor %}
516
+ </nav>
517
+ <button type="button" class="rail-item rail-search" id="cmdk-btn" style="background:none;border:0;cursor:pointer" data-kbd-title="Search">
518
+ <span class="ico"><i class="fa-solid fa-magnifying-glass"></i></span>Search
519
+ </button>
520
+ <button type="button" class="rail-item" id="account-btn" aria-haspopup="true" aria-expanded="false" style="background:none;border:0;cursor:pointer">
521
+ <span class="ico"><i class="fa-solid fa-circle-user"></i></span>Account
522
+ </button>
523
+ </aside>
524
+
525
+ <div id="account-pop" role="menu">
526
+ <div class="flex items-center gap-3 px-1 pb-3 mb-3 border-b border-border">
527
+ <span class="grid place-items-center w-9 h-9 rounded-full bg-card-high text-primary"><i class="fa-solid fa-user text-sm"></i></span>
528
+ <div class="min-w-0">
529
+ <p class="text-sm font-medium truncate">{{ current_user }}</p>
530
+ <p class="text-xs text-ok flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-ok"></span>Signed in</p>
531
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  </div>
533
+ <p class="label-caps px-1 mb-2">Theme</p>
534
+ <div class="theme-opts mb-3" data-theme-picker></div>
535
+ <a href="https://donate.weebzonex.workers.dev" target="_blank" rel="noopener" class="menu-row"><i class="fa-solid fa-heart"></i>Support the project</a>
536
+ <a href="/logout" class="menu-row danger"><i class="fa-solid fa-arrow-right-from-bracket"></i>Log out</a>
537
+ </div>
538
+
539
+ <header id="topbar">
540
+ <a href="/" class="brand"><span class="brand-mark"><i class="fa-solid fa-play"></i></span><span class="truncate">TG Stremio</span></a>
541
+ <button type="button" class="icon-btn" id="theme-cycle" aria-label="Change theme"><i class="fa-solid fa-circle-half-stroke"></i></button>
542
+ </header>
543
+
544
+ <nav id="dock" aria-label="Primary">
545
+ <div class="dock-row">
546
+ {%- set ns = namespace(pos=-1, more=false) -%}
547
+ {%- for href, label, icon, prefix in nav[:dock_count] -%}{%- if is_active(prefix) -%}{%- set ns.pos = loop.index0 -%}{%- endif -%}{%- endfor -%}
548
+ {%- set ns.more = false -%}
549
+ {%- for href, label, icon, prefix in nav[dock_count:] -%}{%- if is_active(prefix) -%}{%- set ns.more = true -%}{%- endif -%}{%- endfor -%}
550
+ {%- set more_active = ns.more -%}
551
+ <span class="dock-pill" id="dock-pill" style="transform: translateX({{ (ns.pos if ns.pos >= 0 else dock_count) * 100 }}%);{{ '' if ns.pos >= 0 or more_active else ' opacity: 0;' }}"></span>
552
+ {% for href, label, icon, prefix in nav[:dock_count] %}
553
+ <a href="{{ href }}" class="dock-item" {% if is_active(prefix) %}aria-current="page"{% endif %}><i class="fa-solid {{ icon }}"></i><span>{{ label }}</span></a>
554
+ {% endfor %}
555
+ <button type="button" class="dock-item" id="more-btn" aria-haspopup="dialog" aria-expanded="false"><i class="fa-solid fa-grip"></i><span>More</span></button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
  </div>
557
+ </nav>
558
 
559
+ <div id="sheet" role="dialog" aria-modal="true" aria-label="More">
560
+ <div class="sheet-grip"></div>
561
+ <div class="sheet-grid mb-5">
562
+ {% for href, label, icon, prefix in nav[dock_count:] %}
563
+ <a href="{{ href }}" class="sheet-link" {% if is_active(prefix) %}aria-current="page"{% endif %}><i class="fa-solid {{ icon }}"></i>{{ label }}</a>
564
+ {% endfor %}
565
+ <a href="https://donate.weebzonex.workers.dev" target="_blank" rel="noopener" class="sheet-link"><i class="fa-solid fa-heart"></i>Support</a>
566
+ </div>
567
+ <p class="label-caps mb-2">Theme</p>
568
+ <div class="theme-opts mb-4" data-theme-picker></div>
569
+ <div class="flex items-center justify-between gap-3 pt-3 border-t border-border">
570
+ <div class="min-w-0">
571
+ <p class="text-sm font-medium truncate">{{ current_user }}</p>
572
+ <p class="text-xs text-text-secondary">Signed in</p>
573
  </div>
574
+ <a href="/logout" class="btn-danger px-4 py-2 text-sm"><i class="fa-solid fa-arrow-right-from-bracket"></i>Log out</a>
575
  </div>
576
+ </div>
577
 
578
+ <div class="scrim" id="scrim"></div>
579
+ {% endif %}
 
580
 
581
+ <div class="shell">
582
+ <main class="w-full max-w-6xl mx-auto px-4 sm:px-6 lg:px-10 {{ 'pt-5 md:pt-10 pb-32 md:pb-14' if current_user else 'py-8' }} page-in">
583
+ {% if current_user %}
584
+ <div id="update-banner" hidden>
585
+ <span class="grid place-items-center w-9 h-9 shrink-0 rounded-full bg-primary text-on-primary"><i class="fa-solid fa-arrow-up text-sm"></i></span>
586
+ <div class="min-w-0 text-sm leading-snug">
587
+ <p class="font-medium">Version <span id="update-latest"></span> is available</p>
588
+ <p class="text-text-secondary">You are on <span id="update-current"></span>. Set the upstream repo and branch, then restart to update.</p>
589
+ </div>
590
  </div>
591
+ {% endif %}
592
+ {% block content %}{% endblock %}
593
+ </main>
594
+ </div>
595
+
596
+ <div id="toast-container" aria-live="polite"></div>
597
+
598
+ {% if current_user %}
599
+ <dialog id="cmdk" aria-label="Command palette">
600
+ <div class="cmdk-head">
601
+ <i class="fa-solid fa-magnifying-glass"></i>
602
+ <input id="cmdk-input" type="text" placeholder="Search pages, titles and actions" autocomplete="off" spellcheck="false" role="combobox" aria-expanded="true" aria-controls="cmdk-list">
603
+ <kbd class="k">Esc</kbd>
604
  </div>
605
+ <div class="cmdk-list" id="cmdk-list" role="listbox"></div>
606
+ <div class="cmdk-foot"><span><kbd class="k">↑</kbd> <kbd class="k">↓</kbd> move</span><span><kbd class="k">↵</kbd> open</span><span><kbd class="k">?</kbd> all shortcuts</span></div>
607
+ </dialog>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
 
609
+ <dialog id="keys" aria-label="Keyboard shortcuts">
610
+ <div class="cmdk-head"><i class="fa-solid fa-keyboard"></i><b class="flex-1 font-medium">Keyboard shortcuts</b><kbd class="k">Esc</kbd></div>
611
+ <div class="keys-body" id="keys-body"></div>
612
+ </dialog>
613
+ {% endif %}
 
 
 
 
 
614
 
615
+ <script>
616
+ const THEMES = {{ themes | tojson }};
617
+ const THEME_KEYS = Object.keys(THEMES);
 
 
618
 
619
+ function escapeHtml(str) {
620
+ return String(str ?? '')
621
+ .replace(/&/g, '&amp;')
622
+ .replace(/</g, '&lt;')
623
+ .replace(/>/g, '&gt;')
624
+ .replace(/"/g, '&quot;')
625
+ .replace(/'/g, '&#039;');
626
  }
627
 
628
+ function showToast(message, type = 'info', title = '', duration = 2600) {
629
  const container = document.getElementById('toast-container');
630
  if (!container) return;
631
+ const icon = type === 'success' ? 'fa-circle-check' : type === 'error' ? 'fa-circle-exclamation' : 'fa-circle-info';
632
  const toast = document.createElement('div');
633
  toast.className = `toast ${type}`;
634
+ toast.setAttribute('role', type === 'error' ? 'alert' : 'status');
635
+ toast.innerHTML = `<i class="fa-solid ${icon}"></i><div class="min-w-0">${title ? `<div class="toast-title">${escapeHtml(title)}</div>` : ''}<div class="toast-message">${escapeHtml(message)}</div></div>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
636
  container.appendChild(toast);
 
637
  setTimeout(() => {
638
+ toast.style.animation = 'toast-out .18s ease-in forwards';
639
+ setTimeout(() => toast.remove(), 190);
640
+ }, duration);
641
+ }
642
+
643
+ function applyTheme(key) {
644
+ const t = THEMES[key];
645
+ if (!t) return;
646
+ const root = document.documentElement;
647
+ root.dataset.theme = key;
648
+ root.classList.toggle('dark', t.is_dark);
649
+ root.classList.toggle('light', !t.is_dark);
650
+ document.querySelector('meta[name="theme-color"]')?.setAttribute('content', t.colors.background);
651
+ document.querySelectorAll('.theme-opt').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.key === key)));
652
+ document.cookie = `theme=${key}; path=/; max-age=31536000; samesite=lax`;
653
+ }
654
+
655
+ document.querySelectorAll('[data-theme-picker]').forEach(box => {
656
+ box.innerHTML = THEME_KEYS.map(k => {
657
+ const c = THEMES[k].colors;
658
+ return `<button type="button" class="theme-opt" data-key="${k}" aria-pressed="${k === document.documentElement.dataset.theme}">
659
+ <span class="swatch" style="background:${c.background};--sw:${c.primary}"></span>${escapeHtml(THEMES[k].name)}</button>`;
660
+ }).join('');
661
+ box.addEventListener('click', e => {
662
+ const b = e.target.closest('.theme-opt');
663
+ if (b) applyTheme(b.dataset.key);
664
+ });
665
+ });
666
 
667
+ document.getElementById('theme-cycle')?.addEventListener('click', () => {
668
+ const cur = THEME_KEYS.indexOf(document.documentElement.dataset.theme);
669
+ const next = THEME_KEYS[(cur + 1) % THEME_KEYS.length];
670
+ applyTheme(next);
671
+ showToast(`${THEMES[next].name} theme`, 'info', '', 1400);
672
+ });
 
 
673
 
674
+ (function shell() {
675
+ const scrim = document.getElementById('scrim');
676
+ const sheet = document.getElementById('sheet');
677
+ const pop = document.getElementById('account-pop');
678
+ const moreBtn = document.getElementById('more-btn');
679
+ const accBtn = document.getElementById('account-btn');
680
+ if (!scrim) return;
681
+
682
+ const setOpen = (el, btn, open) => {
683
+ el.classList.toggle('open', open);
684
+ btn?.setAttribute('aria-expanded', String(open));
685
+ btn?.classList.toggle('on', open);
686
+ };
687
+ const closeAll = () => {
688
+ setOpen(sheet, moreBtn, false);
689
+ setOpen(pop, accBtn, false);
690
+ scrim.classList.remove('open');
691
+ };
692
+ moreBtn?.addEventListener('click', () => {
693
+ const open = !sheet.classList.contains('open');
694
+ closeAll();
695
+ if (open) { setOpen(sheet, moreBtn, true); scrim.classList.add('open'); }
696
+ });
697
+ accBtn?.addEventListener('click', e => {
698
+ e.stopPropagation();
699
+ const open = !pop.classList.contains('open');
700
+ setOpen(pop, accBtn, open);
701
+ });
702
+ document.addEventListener('click', e => {
703
+ if (pop.classList.contains('open') && !pop.contains(e.target)) setOpen(pop, accBtn, false);
704
+ });
705
+ scrim.addEventListener('click', closeAll);
706
+ document.addEventListener('keydown', e => { if (e.key === 'Escape') closeAll(); });
707
+
708
+ const items = [...document.querySelectorAll('#dock .dock-item')];
709
+ const pill = document.getElementById('dock-pill');
710
+ items.forEach((a, i) => a.addEventListener('click', e => {
711
+ if (a.id === 'more-btn' || e.metaKey || e.ctrlKey || e.shiftKey) return;
712
+ pill.style.opacity = '1';
713
+ pill.style.transform = `translateX(${i * 100}%)`;
714
+ }));
715
+ const pillStyle = pill.getAttribute('style');
716
+ const navCurrent = [...document.querySelectorAll('[aria-current="page"]')];
717
+ window.addEventListener('pageshow', e => {
718
+ if (!e.persisted) return;
719
+ pill.setAttribute('style', pillStyle);
720
+ document.querySelectorAll('[aria-current="page"]').forEach(x => x.removeAttribute('aria-current'));
721
+ navCurrent.forEach(x => x.setAttribute('aria-current', 'page'));
722
+ });
723
 
724
+ const topbar = document.getElementById('topbar');
725
+ let ticking = false;
726
+ window.addEventListener('scroll', () => {
727
+ if (ticking) return;
728
+ ticking = true;
729
+ requestAnimationFrame(() => { topbar.classList.toggle('scrolled', window.scrollY > 4); ticking = false; });
730
+ }, { passive: true });
731
+ })();
732
+
733
+ {% if current_user %}
734
+ (function manualSessionReminder() {
735
+ if (window.location.pathname === '/admin/tools') return;
736
+ async function check() {
737
+ try {
738
+ const res = await fetch('/api/admin/tools/manual-session');
739
+ if (!res.ok) return;
740
+ const s = (await res.json()).session;
741
+ if (s && s.tmdb_id !== undefined && s.tmdb_id !== null) {
742
+ const label = s.title ? `"${s.title}"` : 'a title';
743
+ showToast(`Uploads are being added to ${label}. Open Tools to stop it when you're done.`, 'error', 'Upload session active', 5000);
744
  }
745
+ } catch (e) {}
746
+ }
747
+ check();
748
+ setInterval(check, 60000);
749
+ })();
750
+
751
+ (function versionBanner() {
752
+ const banner = document.getElementById('update-banner');
753
+ async function check() {
754
+ try {
755
+ const res = await fetch('/api/admin/version');
756
+ if (!res.ok) return;
757
+ const d = (await res.json()).data || {};
758
+ if (d.update_available && d.latest) {
759
+ document.getElementById('update-latest').textContent = d.latest;
760
+ document.getElementById('update-current').textContent = d.current || '';
761
+ banner.hidden = false;
762
+ } else banner.hidden = true;
763
+ } catch (e) {}
764
+ }
765
+ check();
766
+ setInterval(check, 3600000);
767
+ })();
768
+ {% endif %}
769
+
770
+ (function keyboard() {
771
+ const cmdk = document.getElementById('cmdk');
772
+ if (!cmdk) return;
773
+ const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
774
+ const MOD = isMac ? '⌘' : 'Ctrl';
775
+ const kbd = keys => keys.map(k => `<kbd class="k">${k}</kbd>`).join('');
776
+ const GO = { h: '/', m: '/media/manage', c: '/catalogs', a: '/admin/dashboard', p: '/admin/subscriptions', t: '/admin/access', r: '/admin/requests', o: '/admin/tools', s: '/admin/settings' };
777
+ const PAGES = [...document.querySelectorAll('#rail .rail-nav .rail-item')].map(a => ({
778
+ label: a.textContent.trim(), href: a.getAttribute('href'), icon: a.querySelector('i').className,
779
+ key: Object.keys(GO).find(k => GO[k] === a.getAttribute('href'))
780
+ }));
781
+ const go = href => { document.getElementById('nav-progress')?.classList.add('run'); location.href = href; };
782
+
783
+ const input = document.getElementById('cmdk-input');
784
+ const list = document.getElementById('cmdk-list');
785
+ let items = [], sel = 0, media = [], seq = 0, timer, searching = false;
786
+
787
+ function actions(q) {
788
+ const m = s => s.toLowerCase().includes(q);
789
+ const out = [];
790
+ const pages = PAGES.filter(p => !q || m(p.label)).map(p => ({ group: 'Go to', label: p.label, icon: p.icon, hint: p.key ? kbd(['G', p.key.toUpperCase()]) : '', run: () => go(p.href) }));
791
+ const themes = THEME_KEYS.filter(k => !q || m(THEMES[k].name) || m('theme')).map(k => ({ group: 'Theme', label: `${THEMES[k].name} theme`, icon: 'fa-solid fa-circle-half-stroke', hint: document.documentElement.dataset.theme === k ? '<span class="text-xs">Current</span>' : '', run: () => applyTheme(k) }));
792
+ const misc = [
793
+ { label: 'Add a title', icon: 'fa-solid fa-plus', run: () => go('/media/manage?add=1') },
794
+ { label: 'Keyboard shortcuts', icon: 'fa-solid fa-keyboard', hint: kbd(['?']), run: () => openKeys() },
795
+ { label: 'Log out', icon: 'fa-solid fa-arrow-right-from-bracket', run: () => go('/logout') },
796
+ ].filter(x => !q || m(x.label)).map(x => ({ group: 'Actions', ...x }));
797
+ const titles = media.map(x => ({ group: 'Titles', label: x.title, sub: [x.release_year, x.media_type === 'tv' ? 'Series' : 'Movie'].filter(Boolean).join(' · '), img: x.poster, run: () => go(`/media/edit?tmdb_id=${encodeURIComponent(x.tmdb_id)}&db_index=${encodeURIComponent(x.db_index)}&media_type=${x.media_type === 'tv' ? 'tv' : 'movie'}`) }));
798
+ return [...titles, ...pages, ...themes, ...misc];
799
  }
 
 
 
 
 
800
 
801
+ function render() {
802
+ const q = input.value.trim().toLowerCase();
803
+ items = actions(q);
804
+ sel = Math.min(sel, Math.max(items.length - 1, 0));
805
+ if (searching && q.length > 1) items.unshift({ group: 'Titles', label: 'Searching titles…', icon: 'fa-solid fa-circle-notch fa-spin', run: () => {} });
806
+ if (!items.length) { list.innerHTML = `<div class="cmdk-empty">${q.length > 1 ? 'Nothing matches “' + escapeHtml(input.value) + '”' : 'Type to search'}</div>`; return; }
807
+ let last = '';
808
+ list.innerHTML = items.map((it, i) => {
809
+ const head = it.group !== last ? `<div class="cmdk-group">${it.group}</div>` : '';
810
+ last = it.group;
811
+ const lead = it.img !== undefined ? (it.img ? `<img src="${escapeHtml(it.img)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'">` : '<img alt="">') : `<i class="${it.icon}"></i>`;
812
+ return `${head}<button type="button" class="cmdk-item" role="option" data-i="${i}" aria-selected="${i === sel}">${lead}<span class="t">${escapeHtml(it.label)}${it.sub ? `<small>${escapeHtml(it.sub)}</small>` : ''}</span>${it.hint || ''}</button>`;
813
+ }).join('');
814
+ list.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' });
815
+ }
816
 
817
+ function searchMedia() {
818
+ clearTimeout(timer);
819
+ const q = input.value.trim();
820
+ const id = ++seq;
821
+ if (q.length < 2) { media = []; searching = false; render(); return; }
822
+ searching = true;
823
+ timer = setTimeout(async () => {
824
+ try {
825
+ const res = await Promise.all(['movie', 'tv'].map(t => fetch(`/api/media/list?media_type=${t}&page_size=5&search=${encodeURIComponent(q)}`).then(r => r.ok ? r.json() : {})));
826
+ if (id !== seq) return;
827
+ media = [...(res[0].movies || []).map(x => ({ ...x, media_type: 'movie' })), ...(res[1].tv_shows || []).map(x => ({ ...x, media_type: 'tv' }))].slice(0, 8);
828
+ } catch (e) {
829
+ if (id !== seq) return;
830
+ media = [];
831
+ }
832
+ searching = false;
833
+ render();
834
+ }, 180);
835
+ }
836
 
837
+ function open() {
838
+ if (cmdk.open) return;
839
+ document.getElementById('keys').close();
840
+ input.value = ''; media = []; sel = 0; render();
841
+ cmdk.showModal();
842
+ input.focus();
843
+ }
844
+ function run(i) { const it = items[i]; if (!it || it.label === 'Searching titles…') return; cmdk.close(); it.run(); }
845
+
846
+ input.addEventListener('input', () => { sel = 0; searchMedia(); render(); });
847
+ input.addEventListener('keydown', e => {
848
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
849
+ e.preventDefault();
850
+ sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
851
+ render();
852
+ } else if (e.key === 'Enter') { e.preventDefault(); run(sel); }
853
+ });
854
+ list.addEventListener('click', e => { const b = e.target.closest('[data-i]'); if (b) run(+b.dataset.i); });
855
+ list.addEventListener('mousemove', e => {
856
+ const b = e.target.closest('[data-i]');
857
+ if (b && +b.dataset.i !== sel) { list.querySelector('[aria-selected="true"]')?.setAttribute('aria-selected', 'false'); sel = +b.dataset.i; b.setAttribute('aria-selected', 'true'); }
858
+ });
859
+ [cmdk, document.getElementById('keys')].forEach(d => d.addEventListener('click', e => { if (e.target === d) d.close(); }));
860
+ document.getElementById('cmdk-btn')?.addEventListener('click', open);
861
+ const cb = document.getElementById('cmdk-btn');
862
+ if (cb) cb.title = `Search (${MOD}+K)`;
863
+
864
+ const pageKeys = [];
865
+ if (typeof window.switchEditTab === 'function') {
866
+ [...document.querySelectorAll('.edit-tab')].forEach((t, i) => pageKeys.push([String(i + 1), `${t.textContent.trim()} tab`, () => switchEditTab(t.dataset.tab)]));
867
  }
 
868
 
869
+ function openKeys() {
870
+ cmdk.close();
871
+ const row = (label, keys) => `<div class="keys-row"><span>${label}</span><span>${keys}</span></div>`;
872
+ const or = '<span class="mx-1">or</span>';
873
+ document.getElementById('keys-body').innerHTML =
874
+ `<h3>General</h3>` +
875
+ row('Open search and commands', kbd([MOD, 'K'])) +
876
+ row('Search on this page', kbd(['/'])) +
877
+ row('Save', kbd([MOD, 'S'])) +
878
+ row('Next theme', kbd(['Shift', 'T'])) +
879
+ row('Close dialog or menu', kbd(['Esc'])) +
880
+ row('Show shortcuts', kbd(['?'])) +
881
+ `<h3>Go to</h3>` + PAGES.filter(p => p.key).map(p => row(p.label, kbd(['G', p.key.toUpperCase()]))).join('') +
882
+ (pageKeys.length ? `<h3>This page</h3>` + pageKeys.map(([k, l]) => row(l, kbd([k]))).join('') : '');
883
+ document.getElementById('keys').showModal();
884
+ }
885
 
886
+ const typing = el => el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
887
+ let gAt = 0;
888
+ document.addEventListener('keydown', e => {
889
+ const mod = isMac ? e.metaKey : e.ctrlKey;
890
+ const k = e.key.toLowerCase();
891
+ if (mod && !e.shiftKey && !e.altKey && k === 'k') { e.preventDefault(); cmdk.open ? cmdk.close() : open(); return; }
892
+ if (mod && !e.shiftKey && !e.altKey && k === 's') {
893
+ const btn = [...document.querySelectorAll('[data-shortcut-save]')].find(b => b.offsetParent !== null);
894
+ if (btn) { e.preventDefault(); btn.click(); }
895
+ return;
896
+ }
897
+ if (e.defaultPrevented || mod || e.altKey || typing(e.target) || document.querySelector('dialog[open], [aria-modal="true"]:not(.hidden):not([hidden]):not(#sheet)')) return;
898
+ if (e.key === '?') { e.preventDefault(); openKeys(); return; }
899
+ if (e.key === '/') {
900
+ const f = [...document.querySelectorAll('[data-shortcut-search], main input[type="search"]')].find(x => x.offsetParent !== null);
901
+ if (f) { e.preventDefault(); f.focus(); f.select?.(); }
902
+ return;
903
+ }
904
+ if (e.key === 'T' && e.shiftKey) { document.getElementById('theme-cycle')?.click(); return; }
905
+ if (k === 'g' && !e.shiftKey) { gAt = Date.now(); return; }
906
+ if (gAt && Date.now() - gAt < 1200 && GO[k]) { gAt = 0; go(GO[k]); return; }
907
+ gAt = 0;
908
+ const pk = pageKeys.find(([key]) => key === e.key);
909
+ if (pk) { e.preventDefault(); pk[2](); }
910
+ });
911
+ })();
912
+
913
+ (function navProgress() {
914
+ const bar = document.getElementById('nav-progress');
915
+ const start = () => { bar.classList.remove('run'); void bar.offsetWidth; bar.classList.add('run'); };
916
+ document.addEventListener('click', e => {
917
+ const a = e.target.closest('a[href]');
918
+ if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
919
+ if (a.target && a.target !== '_self') return;
920
+ if (a.hasAttribute('download')) return;
921
+ const url = new URL(a.href, location.href);
922
+ if (url.origin !== location.origin || url.pathname.startsWith('/api/')) return;
923
+ if (url.pathname === location.pathname && url.search === location.search && url.hash) return;
924
+ start();
925
+ const item = a.closest('.rail-item, .dock-item, .sheet-link');
926
+ if (item) {
927
+ document.querySelectorAll('.rail-item[aria-current], .dock-item[aria-current], .sheet-link[aria-current]').forEach(x => x.removeAttribute('aria-current'));
928
+ item.setAttribute('aria-current', 'page');
929
+ }
930
  });
931
+ document.addEventListener('submit', e => { if (!e.defaultPrevented && !e.target.closest('[data-no-progress]')) setTimeout(() => { if (!e.defaultPrevented) start(); }); });
932
+ window.addEventListener('pageshow', () => bar.classList.remove('run'));
933
+ })();
934
+
935
+ if ('serviceWorker' in navigator) {
936
+ window.addEventListener('load', () => navigator.serviceWorker.register('/sw.js').catch(() => {}));
937
  }
938
  </script>
 
939
  </body>
940
  </html>
Backend/fastapi/templates/custom_catalogs.html CHANGED
@@ -4,33 +4,12 @@
4
 
5
  {% block content %}
6
  <style>
7
- .catalog-page {
8
- --soft-bg: color-mix(in srgb, var(--bg) 78%, transparent);
9
- --card-bg: color-mix(in srgb, var(--card) 92%, var(--bg));
10
- --card-bg-strong: color-mix(in srgb, var(--card) 82%, transparent);
11
- --line: color-mix(in srgb, var(--border) 90%, transparent);
12
- --primary-soft: color-mix(in srgb, var(--primary) 15%, transparent);
13
- --accent-soft: color-mix(in srgb, var(--accent) 14%, transparent);
14
- }
15
 
16
- .glass-card {
17
- position: relative;
18
- overflow: hidden;
19
- background: var(--card-bg);
20
- border: 1px solid var(--line);
21
- box-shadow: 0 18px 50px rgba(0, 0, 0, 0.18);
22
- }
23
 
24
- .glass-card::before {
25
- content: "";
26
- position: absolute;
27
- inset: 0;
28
- pointer-events: none;
29
- background:
30
- radial-gradient(circle at 12% 0%, var(--primary-soft), transparent 36%),
31
- radial-gradient(circle at 95% 10%, var(--accent-soft), transparent 34%);
32
- opacity: .9;
33
- }
34
 
35
  .glass-card > * { position: relative; z-index: 1; }
36
 
@@ -40,200 +19,61 @@
40
  place-items: stretch;
41
  }
42
 
43
- .hero-orb {
44
- width: 4.25rem;
45
- height: 4.25rem;
46
- border-radius: 9999px;
47
- background: linear-gradient(135deg, var(--primary), var(--accent));
48
- box-shadow: 0 0 45px color-mix(in srgb, var(--primary) 45%, transparent);
49
- display: grid;
50
- place-items: center;
51
- color: var(--bg);
52
- }
53
 
54
- .section-title {
55
- color: var(--text);
56
- font-weight: 900;
57
- letter-spacing: -0.035em;
58
- }
59
 
60
  .muted { color: var(--text-sec); }
61
 
62
- .field-label {
63
- display: block;
64
- font-size: 0.875rem;
65
- font-weight: 800;
66
- margin-bottom: 0.55rem;
67
- color: var(--text);
68
- }
69
 
70
- .field-input,
71
- .field-select {
72
- width: 100%;
73
- border-radius: 1rem;
74
- border: 1px solid var(--line);
75
- background: color-mix(in srgb, var(--bg) 84%, var(--card) 16%);
76
- color: var(--text);
77
- padding: 0.9rem 1rem;
78
- outline: none;
79
- transition: all .2s ease;
80
- box-shadow: inset 0 1px 0 color-mix(in srgb, var(--text) 5%, transparent);
81
- }
82
 
83
  .field-input::placeholder { color: color-mix(in srgb, var(--text-sec) 82%, transparent); }
84
 
85
- .field-input:focus,
86
- .field-select:focus {
87
- border-color: var(--primary);
88
- box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 18%, transparent);
89
- }
90
 
91
- .btn-ui {
92
- display: inline-flex;
93
- align-items: center;
94
- justify-content: center;
95
- gap: .55rem;
96
- border-radius: 1rem;
97
- padding: .85rem 1.15rem;
98
- font-weight: 900;
99
- transition: all .2s ease;
100
- border: 1px solid transparent;
101
- white-space: nowrap;
102
- }
103
 
104
- .btn-ui:hover { transform: translateY(-1px); }
105
- .btn-ui:active { transform: translateY(0) scale(.99); }
106
 
107
- .btn-primary {
108
- background: linear-gradient(135deg, var(--primary), var(--accent));
109
- color: var(--bg);
110
- box-shadow: 0 14px 28px color-mix(in srgb, var(--primary) 24%, transparent);
111
- }
112
 
113
- .btn-ghost {
114
- background: color-mix(in srgb, var(--bg) 70%, transparent);
115
- color: var(--text);
116
- border-color: var(--line);
117
- }
118
 
119
- .btn-danger {
120
- background: color-mix(in srgb, rgb(239 68 68) 16%, var(--card));
121
- color: rgb(248 113 113);
122
- border-color: color-mix(in srgb, rgb(239 68 68) 32%, var(--border));
123
- }
124
 
125
- .pill {
126
- display: inline-flex;
127
- align-items: center;
128
- gap: .45rem;
129
- padding: .42rem .85rem;
130
- border-radius: 9999px;
131
- font-size: .78rem;
132
- font-weight: 900;
133
- border: 1px solid var(--line);
134
- background: color-mix(in srgb, var(--bg) 66%, transparent);
135
- color: var(--text);
136
- }
137
 
138
- .stat-card,
139
- .catalog-card,
140
- .media-card,
141
- .empty-state {
142
- background: color-mix(in srgb, var(--bg) 72%, var(--card) 28%);
143
- border: 1px solid var(--line);
144
- border-radius: 1.45rem;
145
- transition: transform .2s ease, border-color .2s ease, box-shadow .2s ease, background .2s ease;
146
- }
147
 
148
- .catalog-card:hover,
149
- .media-card:hover {
150
- transform: translateY(-2px);
151
- border-color: color-mix(in srgb, var(--primary) 42%, var(--border));
152
- box-shadow: 0 16px 34px rgba(0,0,0,.16);
153
- }
154
 
155
- .catalog-card.active {
156
- border-color: var(--primary);
157
- background:
158
- linear-gradient(135deg, color-mix(in srgb, var(--primary) 13%, transparent), transparent),
159
- color-mix(in srgb, var(--bg) 70%, var(--card) 30%);
160
- box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 14%, transparent);
161
- }
162
 
163
- .poster {
164
- width: 4.25rem;
165
- height: 6.35rem;
166
- object-fit: cover;
167
- border-radius: 1rem;
168
- border: 1px solid color-mix(in srgb, var(--text) 12%, transparent);
169
- background: color-mix(in srgb, var(--bg) 80%, transparent);
170
- flex-shrink: 0;
171
- }
172
 
173
- .switch {
174
- width: 3.1rem;
175
- height: 1.7rem;
176
- border-radius: 999px;
177
- background: color-mix(in srgb, var(--border) 80%, transparent);
178
- position: relative;
179
- cursor: pointer;
180
- transition: .2s ease;
181
- border: 1px solid var(--line);
182
- }
183
 
184
- .switch::after {
185
- content: "";
186
- width: 1.25rem;
187
- height: 1.25rem;
188
- border-radius: 999px;
189
- background: var(--text);
190
- position: absolute;
191
- left: .18rem;
192
- top: .17rem;
193
- transition: .2s ease;
194
- box-shadow: 0 4px 12px rgba(0,0,0,.24);
195
- }
196
 
197
- .switch-input:checked + .switch {
198
- background: linear-gradient(135deg, var(--primary), var(--accent));
199
- }
200
 
201
- .switch-input:checked + .switch::after {
202
- left: 1.55rem;
203
- background: var(--bg);
204
- }
205
 
206
- .mini-tab {
207
- border-radius: 999px;
208
- padding: .48rem .9rem;
209
- border: 1px solid var(--line);
210
- color: var(--text-sec);
211
- background: color-mix(in srgb, var(--bg) 56%, transparent);
212
- font-weight: 900;
213
- font-size: .8rem;
214
- }
215
 
216
- .mini-tab.active {
217
- color: var(--bg);
218
- border-color: transparent;
219
- background: linear-gradient(135deg, var(--primary), var(--accent));
220
- }
221
 
222
- .skeleton {
223
- min-height: 5.5rem;
224
- border-radius: 1.45rem;
225
- background: linear-gradient(90deg,
226
- color-mix(in srgb, var(--bg) 72%, var(--card) 28%),
227
- color-mix(in srgb, var(--primary) 9%, var(--card)),
228
- color-mix(in srgb, var(--bg) 72%, var(--card) 28%));
229
- background-size: 220% 100%;
230
- animation: shimmer 1.2s infinite linear;
231
- border: 1px solid var(--line);
232
- }
233
 
234
- @keyframes shimmer {
235
- to { background-position: -220% 0; }
236
- }
 
 
 
 
237
 
238
  /* ── Collapsible catalog list ── */
239
  .catalog-list-wrapper {
@@ -249,11 +89,9 @@
249
  position: absolute;
250
  bottom: 0; left: 0; right: 0;
251
  height: 76px;
252
- background: linear-gradient(to bottom,
253
- transparent,
254
- color-mix(in srgb, var(--bg) 94%, var(--card) 6%));
255
  pointer-events: none;
256
- border-radius: 0 0 1.45rem 1.45rem;
257
  }
258
 
259
  #catalog-expand-btn {
@@ -300,92 +138,97 @@
300
  opacity: 1;
301
  }
302
 
303
- @media (max-width: 640px) {
304
- .hero-card { min-height: 13rem; }
305
- .btn-ui { width: 100%; }
 
 
 
 
 
 
 
306
  }
307
- </style>
 
308
 
309
- <div class="catalog-page max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5 sm:py-8 space-y-6">
310
- <div class="glass-card hero-card rounded-3xl p-5 sm:p-7 lg:p-8">
311
- <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
312
- <div class="flex flex-col sm:flex-row sm:items-center gap-5">
313
- <div class="hero-orb text-3xl">🎞️</div>
314
- <div>
315
- <div class="flex flex-wrap items-center gap-2 mb-3">
316
- <span class="pill">Custom Stremio sections</span>
317
- <span class="pill">No Stremio search/filter</span>
318
- </div>
319
- <h1 class="section-title text-3xl sm:text-4xl lg:text-5xl">Custom Catalogs</h1>
320
- <p class="muted mt-3 max-w-2xl text-sm sm:text-base leading-7">
321
- Build dynamic curated rows like Bollywood, Anime, Kids, 4K, Watch Later, or hidden private lists from your existing Telegram media.
322
- </p>
323
- </div>
324
- </div>
325
 
326
- <div class="grid grid-cols-3 gap-3 min-w-full sm:min-w-[26rem] lg:min-w-[30rem]">
327
- <div class="stat-card p-4 text-center">
328
- <p id="stat-total" class="section-title text-2xl">0</p>
329
- <p class="muted text-xs font-bold mt-1">Catalogs</p>
330
- </div>
331
- <div class="stat-card p-4 text-center">
332
- <p id="stat-visible" class="section-title text-2xl">0</p>
333
- <p class="muted text-xs font-bold mt-1">Visible</p>
334
- </div>
335
- <div class="stat-card p-4 text-center">
336
- <p id="stat-items" class="section-title text-2xl">0</p>
337
- <p class="muted text-xs font-bold mt-1">Titles</p>
338
- </div>
339
- </div>
340
- </div>
341
- </div>
342
 
 
 
343
 
 
344
 
345
- <div class="glass-card rounded-3xl p-5 sm:p-6">
346
- <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
347
- <div>
348
- <div class="flex flex-wrap gap-2 mb-3">
349
- <span class="pill">✨ Auto catalogs</span>
350
- <span id="auto-sync-status" class="pill">Checking status...</span>
351
- </div>
352
- <h2 class="section-title text-2xl sm:text-3xl">Auto-create by selected language & OTT</h2>
353
- <p class="muted text-sm sm:text-base mt-2 leading-7 max-w-3xl">
354
- 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.
355
- </p>
356
- </div>
357
- <div class="flex flex-col sm:flex-row gap-3">
358
- <button id="auto-sync-btn" onclick="runAutoSync(false)" class="btn-ui btn-primary lg:w-auto">⚡ Quick Sync</button>
359
- <button id="auto-rebuild-btn" onclick="runAutoSync(true)" class="btn-ui btn-ghost lg:w-auto">♻️ Full Rebuild</button>
360
- </div>
361
- </div>
362
 
363
- <div class="mt-5 pt-5 border-t" style="border-color: color-mix(in srgb, var(--border) 80%, transparent);">
364
- <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
365
- <div>
366
- <h3 class="section-title text-xl">Choose Auto Catalogs</h3>
367
- <p class="muted text-sm mt-1">Disable anything you do not want to auto-create. Save, then run Full Rebuild once to apply removed catalogs.</p>
368
- </div>
369
- <button id="save-auto-settings-btn" onclick="saveAutoCatalogSettings()" class="btn-ui btn-ghost md:w-auto">💾 Save Selection</button>
370
- </div>
371
- <div id="auto-settings-list" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
372
- <div class="skeleton"></div>
373
- <div class="skeleton"></div>
374
- <div class="skeleton"></div>
375
- </div>
 
 
 
 
 
376
  </div>
 
 
 
 
 
 
377
  </div>
378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  <div class="grid grid-cols-1 xl:grid-cols-[0.88fr_1.12fr] gap-6">
380
  <div class="space-y-6">
381
- <div class="glass-card rounded-3xl p-5 sm:p-6">
382
- <div class="flex items-start justify-between gap-3 mb-5">
383
- <div>
384
- <h2 class="section-title text-2xl">Create Catalog</h2>
385
- <p class="muted text-sm mt-1">Visible catalogs appear in Stremio manifest. Hidden catalogs stay only in web panel.</p>
386
- </div>
387
- <span class="pill">New</span>
388
- </div>
389
 
390
  <form onsubmit="createCatalog(event)" class="space-y-4">
391
  <div>
@@ -393,26 +236,32 @@
393
  <input id="catalog-name" class="field-input" placeholder="Example: Bollywood Hits" required>
394
  </div>
395
 
396
- <label class="catalog-card p-4 flex items-center justify-between gap-4 cursor-pointer select-none">
397
- <div>
398
- <p class="font-black">Show in Stremio</p>
399
- <p class="muted text-xs mt-1">Turn off to keep this catalog private in web panel.</p>
400
- </div>
401
- <input id="catalog-visible" type="checkbox" checked class="switch-input hidden">
402
- <span class="switch"></span>
403
- </label>
 
404
 
405
- <button class="btn-ui btn-primary w-full" type="submit">➕ Create Catalog</button>
 
 
 
 
 
406
  </form>
407
- </div>
408
 
409
- <div class="glass-card rounded-3xl p-5 sm:p-6">
410
  <div class="flex items-center justify-between gap-3 mb-5">
411
  <div>
412
- <h2 class="section-title text-2xl">Your Catalogs</h2>
413
  <p class="muted text-sm mt-1">Select one to manage titles.</p>
414
  </div>
415
- <button onclick="loadCatalogs()" class="btn-ui btn-ghost px-3 py-2 text-sm">↻</button>
416
  </div>
417
  <div id="catalog-list-wrapper" class="catalog-list-wrapper collapsed">
418
  <div id="catalog-list" class="space-y-3">
@@ -420,30 +269,71 @@
420
  <div class="skeleton"></div>
421
  </div>
422
  </div>
423
- <button id="catalog-expand-btn" onclick="toggleCatalogExpand()" class="btn-ui btn-ghost w-full hidden">▾ Show all catalogs</button>
424
  </div>
425
  </div>
426
 
427
- <div class="glass-card rounded-3xl p-5 sm:p-6">
428
  <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3 mb-5">
429
  <div>
430
  <div class="flex flex-wrap gap-2 mb-3">
431
  <span id="selected-visibility-pill" class="pill hidden"></span>
432
  <span id="selected-count-pill" class="pill hidden"></span>
433
  </div>
434
- <h2 id="selected-title" class="section-title text-2xl">Select a catalog</h2>
435
  <p id="selected-subtitle" class="muted text-sm mt-1">Choose a catalog from the left side to add or remove titles.</p>
436
  </div>
437
  <button id="delete-catalog-btn" onclick="deleteSelectedCatalog()" class="btn-ui btn-danger hidden md:w-auto">Delete Catalog</button>
438
  </div>
439
 
440
  <div id="catalog-empty-guide" class="empty-state p-6 sm:p-8 text-center">
441
- <div class="text-4xl mb-3">📚</div>
442
- <h3 class="section-title text-xl">No catalog selected</h3>
443
  <p class="muted mt-2 text-sm leading-6">Create a catalog or select an existing one. Then search from your existing media library and add titles instantly.</p>
444
  </div>
445
 
446
  <div id="catalog-workspace" class="hidden space-y-6">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  <div class="catalog-card p-4 sm:p-5">
448
  <div class="flex flex-col sm:flex-row sm:items-end gap-3">
449
  <div class="flex-1">
@@ -457,7 +347,7 @@
457
  <option value="tv">Series</option>
458
  </select>
459
  </div>
460
- <button onclick="searchMedia()" class="btn-ui btn-primary sm:w-auto">🔎 Search</button>
461
  </div>
462
  </div>
463
 
@@ -488,9 +378,109 @@
488
  let catalogs = [];
489
  let selectedCatalogId = null;
490
  let catalogListExpanded = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
 
492
  function posterOrFallback(item) {
493
- return item.poster || 'https://via.placeholder.com/120x180/111827/94a3b8?text=No+Poster';
494
  }
495
 
496
  function escapeHtml(value) {
@@ -505,8 +495,8 @@ function getSelectedCatalog() {
505
 
506
  function updateStats() {
507
  const total = catalogs.length;
508
- const visible = catalogs.filter(c => c.visible).length;
509
- const items = catalogs.reduce((sum, c) => sum + ((c.items || []).length), 0);
510
  document.getElementById('stat-total').textContent = total;
511
  document.getElementById('stat-visible').textContent = visible;
512
  document.getElementById('stat-items').textContent = items;
@@ -516,11 +506,11 @@ function mediaCard(item, actionHtml) {
516
  const mediaType = item.media_type === 'tv' ? 'Series' : 'Movie';
517
  const genres = Array.isArray(item.genres) ? item.genres.slice(0, 2).join(' · ') : '';
518
  return `<div class="media-card p-3 flex gap-3">
519
- <img src="${escapeHtml(posterOrFallback(item))}" class="poster" onerror="this.src='https://via.placeholder.com/120x180/111827/94a3b8?text=No+Poster'" alt="Poster">
520
  <div class="min-w-0 flex-1">
521
  <div class="flex items-start justify-between gap-2">
522
  <div class="min-w-0">
523
- <h4 class="font-black truncate" title="${escapeHtml(item.title)}">${escapeHtml(item.title)}</h4>
524
  <p class="muted text-xs mt-1">${mediaType} · ${escapeHtml(item.release_year || 'Unknown')} · TMDb ${escapeHtml(item.tmdb_id || '')}</p>
525
  </div>
526
  <span class="pill text-[0.68rem] py-1 px-2">${escapeHtml(mediaType)}</span>
@@ -533,7 +523,7 @@ function mediaCard(item, actionHtml) {
533
 
534
  function emptyState(icon, title, message) {
535
  return `<div class="empty-state p-6 text-center col-span-full">
536
- <div class="text-3xl mb-2">${icon}</div>
537
  <h4 class="section-title text-lg">${escapeHtml(title)}</h4>
538
  <p class="muted text-sm mt-1">${escapeHtml(message)}</p>
539
  </div>`;
@@ -552,7 +542,7 @@ async function loadCatalogs() {
552
  renderCatalogs();
553
  updateSelectedHeader();
554
  } catch (error) {
555
- box.innerHTML = emptyState('⚠️', 'Unable to load catalogs', error.message || 'Please refresh and try again.');
556
  showToast(error.message || 'Unable to load catalogs', 'error', 'Error');
557
  }
558
  }
@@ -563,7 +553,7 @@ function renderCatalogs() {
563
  const wrapper = document.getElementById('catalog-list-wrapper');
564
 
565
  if (!catalogs.length) {
566
- box.innerHTML = emptyState('✨', 'No custom catalog yet', 'Create your first curated Stremio section above.');
567
  if (expandBtn) expandBtn.classList.add('hidden');
568
  if (wrapper) wrapper.classList.remove('collapsed');
569
  return;
@@ -571,22 +561,22 @@ function renderCatalogs() {
571
 
572
  box.innerHTML = catalogs.map(c => {
573
  const isActive = c._id === selectedCatalogId;
574
- const count = (c.items || []).length;
 
 
575
  return `<div class="catalog-card p-4 ${isActive ? 'active' : ''}">
576
- <div class="flex items-start justify-between gap-3">
577
- <button class="text-left min-w-0 flex-1" onclick="selectCatalog('${c._id}')">
578
- <div class="flex items-center gap-2 min-w-0">
579
- <span class="text-xl">${c.auto ? '✨' : (c.visible ? '🌐' : '🔒')}</span>
580
- <h3 class="font-black truncate">${escapeHtml(c.name)}</h3>
581
- ${c.auto ? '<span class="pill text-[0.62rem] px-2 py-0.5">Auto</span>' : ''}
582
- </div>
583
- <p class="muted text-xs mt-2">${count} title${count === 1 ? '' : 's'} · ${c.visible ? 'Visible in Stremio' : 'Hidden from Stremio'}</p>
584
- </button>
585
- <label class="flex items-center gap-2 shrink-0" title="Toggle Stremio visibility">
586
- <input type="checkbox" ${c.visible ? 'checked' : ''} onchange="toggleVisibility('${c._id}', this.checked)" class="switch-input hidden">
587
- <span class="switch"></span>
588
- </label>
589
- </div>
590
  </div>`;
591
  }).join('');
592
 
@@ -594,7 +584,7 @@ function renderCatalogs() {
594
  if (catalogs.length > 3) {
595
  if (expandBtn) {
596
  expandBtn.classList.remove('hidden');
597
- expandBtn.textContent = catalogListExpanded ? '▴ Collapse list' : '▾ Show all catalogs';
598
  }
599
  if (wrapper) wrapper.classList.toggle('collapsed', !catalogListExpanded);
600
  } else {
@@ -627,36 +617,62 @@ function updateSelectedHeader() {
627
  deleteBtn.classList.remove('hidden');
628
  visibilityPill.classList.remove('hidden');
629
  countPill.classList.remove('hidden');
630
- visibilityPill.textContent = catalog.visible ? '🌐 Visible in Stremio' : '🔒 Hidden from Stremio';
631
- countPill.textContent = `${(catalog.items || []).length} title${(catalog.items || []).length === 1 ? '' : 's'}`;
 
 
 
 
632
  document.getElementById('selected-title').textContent = catalog.name || 'Selected Catalog';
633
- document.getElementById('selected-subtitle').textContent = catalog.visible
634
- ? 'This catalog appears on the Stremio catalog screen.'
635
- : 'This catalog is private in the web panel and hidden from Stremio.';
 
 
 
 
 
 
 
 
636
  }
637
 
638
  async function createCatalog(event) {
639
  event.preventDefault();
640
  const name = document.getElementById('catalog-name').value.trim();
641
- const visible = document.getElementById('catalog-visible').checked;
 
642
  if (!name) return showToast('Catalog name is required', 'error', 'Error');
 
 
643
  const res = await fetch('/api/custom-catalogs', {
644
- method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, visible})
645
  });
646
  const data = await res.json().catch(() => ({}));
647
  if (!res.ok) return showToast(data.detail || 'Failed to create catalog', 'error', 'Error');
648
  document.getElementById('catalog-name').value = '';
 
 
649
  showToast('Catalog created', 'success', 'Success');
650
  await loadCatalogs();
651
  }
652
 
653
- async function toggleVisibility(id, visible) {
654
- const catalog = catalogs.find(c => c._id === id);
655
- const res = await fetch(`/api/custom-catalogs/${id}`, {
656
- method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: catalog?.name, visible})
 
 
 
 
 
 
 
 
657
  });
658
  const data = await res.json().catch(() => ({}));
659
- if (!res.ok) showToast(data.detail || 'Failed to update visibility', 'error', 'Error');
 
660
  await loadCatalogs();
661
  }
662
 
@@ -664,6 +680,7 @@ async function selectCatalog(id) {
664
  selectedCatalogId = id;
665
  renderCatalogs();
666
  updateSelectedHeader();
 
667
  await loadCatalogItems();
668
  }
669
 
@@ -683,9 +700,9 @@ async function searchMedia() {
683
  const results = data.results || [];
684
  box.innerHTML = results.length
685
  ? results.map(item => mediaCard(item, `<button class="btn-ui btn-primary px-3 py-2 text-sm" onclick="addItem(${item.tmdb_id}, ${item.db_index}, '${item.media_type}')">Add</button>`)).join('')
686
- : emptyState('🔍', 'No title found', 'Try a shorter title or change movie/series type.');
687
  } catch (error) {
688
- box.innerHTML = emptyState('⚠️', 'Search failed', error.message || 'Please try again.');
689
  }
690
  }
691
 
@@ -716,9 +733,9 @@ async function loadCatalogItems() {
716
  const items = data.items || [];
717
  box.innerHTML = items.length
718
  ? items.map(item => mediaCard(item, `<button class="btn-ui btn-danger px-3 py-2 text-sm" onclick="removeItem(${item.tmdb_id}, ${item.db_index}, '${item.media_type}')">Remove</button>`)).join('')
719
- : emptyState('➕', 'No titles added yet', 'Use search above to add media to this catalog.');
720
  } catch (error) {
721
- box.innerHTML = emptyState('⚠️', 'Unable to load titles', error.message || 'Please try again.');
722
  }
723
  }
724
 
@@ -759,34 +776,21 @@ async function loadAutoCatalogSettings() {
759
  box.innerHTML = `<div class="empty-state p-4 muted">No auto catalog options found.</div>`;
760
  return;
761
  }
762
-
763
  const groups = {};
764
- defs.forEach(def => {
765
- if (!groups[def.group]) groups[def.group] = [];
766
- groups[def.group].push(def);
767
- });
768
-
769
  box.innerHTML = Object.entries(groups).map(([group, items]) => `
770
- <div class="catalog-card p-4 auto-group-card">
771
- <button type="button" class="group-card-header" onclick="toggleAutoGroup(this.closest('.auto-group-card'))">
772
- <div class="flex items-center gap-2">
773
- <h4 class="section-title text-base">${escapeHtml(group)}</h4>
774
- <span class="pill text-[0.65rem] px-2 py-0.5">${items.length}</span>
775
- </div>
776
- <svg class="group-chevron" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
777
- <path d="M6 4l4 4-4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
778
- </svg>
779
- </button>
780
- <div class="group-items">
781
- <div class="group-items-inner space-y-2 pt-3">
782
- ${items.map(item => `
783
- <label class="flex items-center justify-between gap-3 rounded-2xl p-3 cursor-pointer" style="background: color-mix(in srgb, var(--bg) 64%, transparent); border: 1px solid color-mix(in srgb, var(--border) 72%, transparent);">
784
- <span class="font-bold text-sm">${escapeHtml(item.name)}</span>
785
- <input type="checkbox" class="auto-setting-checkbox switch-input hidden" value="${escapeHtml(item.key)}" ${item.enabled ? 'checked' : ''}>
786
- <span class="switch"></span>
787
- </label>
788
- `).join('')}
789
- </div>
790
  </div>
791
  </div>
792
  `).join('');
@@ -795,25 +799,101 @@ async function loadAutoCatalogSettings() {
795
  }
796
  }
797
 
798
- async function saveAutoCatalogSettings() {
799
- const btn = document.getElementById('save-auto-settings-btn');
800
- const old = btn ? btn.textContent : '';
801
- const enabledKeys = Array.from(document.querySelectorAll('.auto-setting-checkbox:checked')).map(el => el.value);
 
 
 
 
 
 
 
802
  try {
803
- if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }
804
  const res = await fetch('/api/custom-catalogs/auto-sync/settings', {
805
- method: 'PUT',
806
- headers: { 'Content-Type': 'application/json' },
807
  body: JSON.stringify({ enabled_keys: enabledKeys })
808
  });
809
  const data = await res.json().catch(() => ({}));
810
  if (!res.ok) throw new Error(data.detail || 'Failed to save settings');
811
- showToast('Auto catalog selection saved. Run Full Rebuild once to remove disabled catalog items.', 'success', 'Saved');
812
- await loadAutoCatalogSettings();
813
  } catch (error) {
814
  showToast(error.message || 'Failed to save settings', 'error', 'Error');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  } finally {
816
- if (btn) { btn.disabled = false; btn.textContent = old; }
817
  }
818
  }
819
 
@@ -822,31 +902,27 @@ let autoSyncPollTimer = null;
822
  async function loadAutoSyncStatus() {
823
  const pill = document.getElementById('auto-sync-status');
824
  const syncBtn = document.getElementById('auto-sync-btn');
825
- const rebuildBtn = document.getElementById('auto-rebuild-btn');
826
  if (!pill) return;
827
  try {
828
  const res = await fetch('/api/custom-catalogs/auto-sync/status');
829
  const data = await res.json().catch(() => ({}));
830
  const status = data.status || {};
831
- const mode = status.mode === 'full_rebuild' ? 'Full rebuild' : 'Quick sync';
832
 
833
  if (status.running) {
834
- pill.textContent = `${mode} running: ${status.scanned || 0} scanned · ${status.classified || 0} checked`;
835
  if (syncBtn) syncBtn.disabled = true;
836
- if (rebuildBtn) rebuildBtn.disabled = true;
837
  if (!autoSyncPollTimer) {
838
  autoSyncPollTimer = setInterval(loadAutoSyncStatus, 3000);
839
  }
840
  } else {
841
  if (status.finished_at) {
842
  pill.textContent = status.error
843
- ? `${mode} failed`
844
- : `${mode}: ${status.classified || 0} checked · ${status.skipped || 0} skipped`;
845
  } else {
846
- pill.textContent = 'Quick sync runs on boot';
847
  }
848
  if (syncBtn) syncBtn.disabled = false;
849
- if (rebuildBtn) rebuildBtn.disabled = false;
850
  if (autoSyncPollTimer) {
851
  clearInterval(autoSyncPollTimer);
852
  autoSyncPollTimer = null;
@@ -858,24 +934,20 @@ async function loadAutoSyncStatus() {
858
  }
859
  }
860
 
861
- async function runAutoSync(fullRebuild = false) {
862
- const btn = document.getElementById(fullRebuild ? 'auto-rebuild-btn' : 'auto-sync-btn');
863
- const otherBtn = document.getElementById(fullRebuild ? 'auto-sync-btn' : 'auto-rebuild-btn');
864
  const old = btn.textContent;
865
  btn.disabled = true;
866
- if (otherBtn) otherBtn.disabled = true;
867
- btn.textContent = fullRebuild ? '⏳ Rebuilding...' : '⏳ Syncing...';
868
  try {
869
- const url = `/api/custom-catalogs/auto-sync?full_rebuild=${fullRebuild ? 'true' : 'false'}`;
870
- const res = await fetch(url, { method: 'POST' });
871
  const data = await res.json().catch(() => ({}));
872
- if (!res.ok) throw new Error(data.detail || 'Auto sync failed');
873
  const result = data.result || {};
874
- const title = fullRebuild ? 'Full rebuild started' : 'Quick sync started';
875
- showToast(result.message || data.message || 'Auto sync started in background.', 'info', title);
876
  await loadAutoSyncStatus();
877
  } catch (error) {
878
- showToast(error.message || 'Auto sync failed', 'error', 'Error');
879
  } finally {
880
  btn.textContent = old;
881
  await loadAutoSyncStatus();
@@ -891,9 +963,16 @@ function toggleCatalogExpand() {
891
  const wrapper = document.getElementById('catalog-list-wrapper');
892
  const btn = document.getElementById('catalog-expand-btn');
893
  wrapper.classList.toggle('collapsed', !catalogListExpanded);
894
- if (btn) btn.textContent = catalogListExpanded ? '▴ Collapse list' : '▾ Show all catalogs';
895
  }
896
 
897
- document.addEventListener('DOMContentLoaded', () => { loadCatalogs(); loadAutoSyncStatus(); loadAutoCatalogSettings(); });
 
 
 
 
 
 
 
898
  </script>
899
  {% endblock %}
 
4
 
5
  {% block content %}
6
  <style>
 
 
 
 
 
 
 
 
7
 
8
+ .catalog-page { --line: var(--border); --soft-bg: var(--bg); --card-bg: var(--card); }
 
 
 
 
 
 
9
 
10
+ .glass-card { position: relative; background: var(--card); border: 1px solid var(--border); }
11
+
12
+ .glass-card::before { content: none; }
 
 
 
 
 
 
 
13
 
14
  .glass-card > * { position: relative; z-index: 1; }
15
 
 
19
  place-items: stretch;
20
  }
21
 
22
+ .hero-orb { width: 2.5rem; height: 2.5rem; border-radius: 9999px; display: grid; place-items: center; background: var(--card-high); color: var(--primary); }
 
 
 
 
 
 
 
 
 
23
 
24
+ .section-title { color: var(--text); font-weight: 600; letter-spacing: -0.015em; }
 
 
 
 
25
 
26
  .muted { color: var(--text-sec); }
27
 
28
+ .field-label { display: block; font-size: .72rem; font-weight: 500; letter-spacing: .1em; text-transform: uppercase; margin-bottom: .45rem; color: var(--text-sec); }
 
 
 
 
 
 
29
 
30
+ .field-input, .field-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .75rem 1rem; outline: none; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  .field-input::placeholder { color: color-mix(in srgb, var(--text-sec) 82%, transparent); }
33
 
34
+ .field-input:focus, .field-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
 
 
 
 
35
 
36
+ .btn-ui { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border-radius: 9999px; padding: .6rem 1.1rem; font-size: .9rem; font-weight: 500; transition: background-color .18s var(--ease), border-color .18s var(--ease), transform .12s var(--ease), filter .18s var(--ease); border: 1px solid transparent; white-space: nowrap; }
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ .btn-ui:hover { }
 
39
 
40
+ .btn-ui:active { transform: scale(.97); }
 
 
 
 
41
 
42
+ .btn-primary { background: var(--primary); color: var(--on-primary); }
 
 
 
 
43
 
44
+ .btn-ghost { background: transparent; color: var(--text); border-color: var(--border); }
 
 
 
 
45
 
46
+ .btn-danger { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); border-color: color-mix(in srgb, var(--danger) 30%, transparent); }
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ .pill { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); color: var(--text-sec); white-space: nowrap; }
 
 
 
 
 
 
 
 
49
 
50
+ .stat-card, .catalog-card, .media-card, .empty-state { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); min-width: 0; transition: border-color .2s var(--ease), background-color .2s var(--ease); }
 
 
 
 
 
51
 
52
+ .catalog-card:hover, .media-card:hover { border-color: color-mix(in srgb, var(--primary) 40%, var(--border)); }
 
 
 
 
 
 
53
 
54
+ .catalog-card.active { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 7%, var(--bg)); }
 
 
 
 
 
 
 
 
55
 
56
+ .poster { width: 3.5rem; height: 5.25rem; object-fit: cover; border-radius: 10px; background: var(--card-high); flex-shrink: 0; }
 
 
 
 
 
 
 
 
 
57
 
58
+ .switch { width: 2.9rem; height: 1.65rem; border-radius: 999px; background: var(--card-high); position: relative; cursor: pointer; transition: background-color .2s var(--ease); border: 1px solid var(--border); flex-shrink: 0; }
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ /* Toggle row (visibility exclusive / search) */
 
 
61
 
62
+ .toggle-row { display: flex; align-items: center; justify-content: space-between; gap: .75rem; border-radius: var(--radius-sm); padding: .75rem .85rem; background: var(--bg); border: 1px solid var(--border); cursor: pointer; }
 
 
 
63
 
64
+ .switch::after { content: ""; width: 1.15rem; height: 1.15rem; border-radius: 999px; background: var(--text-sec); position: absolute; left: .2rem; top: .2rem; transition: transform .25s var(--spring), background-color .2s var(--ease); }
 
 
 
 
 
 
 
 
65
 
66
+ .switch-input:checked + .switch { background: var(--primary); border-color: var(--primary); }
 
 
 
 
67
 
68
+ .switch-input:checked + .switch::after { transform: translateX(1.22rem); background: var(--on-primary); }
 
 
 
 
 
 
 
 
 
 
69
 
70
+ .mini-tab { border-radius: 999px; padding: .4rem .85rem; border: 1px solid var(--border); color: var(--text-sec); background: transparent; font-weight: 500; font-size: .82rem; }
71
+
72
+ .mini-tab.active { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 50%, var(--border)); background: color-mix(in srgb, var(--primary) 10%, transparent); }
73
+
74
+ .skeleton { min-height: 5.5rem; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--bg) 25%, var(--card-high) 37%, var(--bg) 63%); background-size: 400% 100%; animation: shimmer 1.4s infinite ease; border: 1px solid var(--border); }
75
+
76
+ @keyframes shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
77
 
78
  /* ── Collapsible catalog list ── */
79
  .catalog-list-wrapper {
 
89
  position: absolute;
90
  bottom: 0; left: 0; right: 0;
91
  height: 76px;
92
+ background: linear-gradient(to bottom, transparent, var(--card));
 
 
93
  pointer-events: none;
94
+ border-radius: 0 0 var(--radius-sm) var(--radius-sm);
95
  }
96
 
97
  #catalog-expand-btn {
 
138
  opacity: 1;
139
  }
140
 
141
+ .token-picker { max-height: 12rem; overflow-y: auto; border: 1px solid var(--border); border-radius: var(--radius-sm); padding: .4rem; display: flex; flex-direction: column; gap: .25rem; background: var(--bg); }
142
+ .token-row {
143
+ display: flex;
144
+ align-items: center;
145
+ gap: .6rem;
146
+ padding: .5rem .65rem;
147
+ border-radius: .75rem;
148
+ cursor: pointer;
149
+ border: 1px solid transparent;
150
+ transition: background .15s ease;
151
  }
152
+ .token-row:hover { background: color-mix(in srgb, var(--primary) 10%, transparent); }
153
+ .token-row input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); cursor: pointer; flex-shrink: 0; }
154
 
155
+ .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; }
156
+ .vis-public { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); border-color: color-mix(in srgb, var(--ok) 30%, transparent); }
157
+ .vis-tokens { color: var(--info); background: color-mix(in srgb, var(--info) 14%, transparent); border-color: color-mix(in srgb, var(--info) 30%, transparent); }
158
+ .vis-owner { color: var(--danger); background: color-mix(in srgb, var(--danger) 14%, transparent); border-color: color-mix(in srgb, var(--danger) 30%, transparent); }
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
+ .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); }
161
+ .auto-chip .dot { width: .6rem; height: .6rem; border-radius: 9999px; background: var(--border); transition: all .15s ease; }
162
+ .auto-chip:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); }
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ .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); }
165
+ .auto-chip.on .dot { background: var(--primary); }
166
 
167
+ .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; }
168
 
169
+ .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); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
+ .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); }
172
+ .order-arrow:hover:not(:disabled) { border-color: var(--primary); color: var(--primary); }
173
+ .order-arrow:disabled { opacity: .35; cursor: not-allowed; }
174
+ .fold > summary { list-style: none; cursor: pointer; display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
175
+ .fold > summary::-webkit-details-marker { display: none; }
176
+ .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); }
177
+ .fold[open] > summary::after { transform: rotate(180deg); }
178
+ .fold[open] > summary { margin-bottom: 1rem; }
179
+ #selected-title { scroll-margin-top: 6rem; }
180
+
181
+
182
+ </style>
183
+
184
+ <div class="catalog-page space-y-8">
185
+ <header class="page-head" style="margin-bottom:0">
186
+ <div>
187
+ <h1 class="page-title">Catalogs</h1>
188
+ <p class="page-sub">Custom and automatic sections shown in Stremio</p>
189
  </div>
190
+ </header>
191
+
192
+ <div class="glass-card rounded-3xl p-5 grid grid-cols-3 gap-6">
193
+ <div><p id="stat-total" class="text-xl font-semibold tabular">0</p><p class="muted text-sm">Catalogs</p></div>
194
+ <div><p id="stat-visible" class="text-xl font-semibold tabular">0</p><p class="muted text-sm">Visible</p></div>
195
+ <div><p id="stat-items" class="text-xl font-semibold tabular">0</p><p class="muted text-sm">Titles</p></div>
196
  </div>
197
 
198
+ <details class="fold glass-card rounded-3xl p-5">
199
+ <summary>
200
+ <span class="flex flex-wrap items-center gap-2 min-w-0">
201
+ <h2 class="section-title text-lg">Auto catalogs</h2>
202
+ <span id="auto-sync-status" class="pill">Checking status...</span>
203
+ </span>
204
+ </summary>
205
+ <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
206
+ <p class="muted text-sm">Toggles save instantly. Sync rebuilds them across your library.</p>
207
+ <button id="auto-sync-btn" onclick="runAutoSync()" class="btn-ui btn-primary sm:w-auto"><i class="fa-solid fa-bolt"></i> Sync</button>
208
+ </div>
209
+ <div id="auto-settings-list" class="mt-5 pt-5 border-t border-border grid grid-cols-1 lg:grid-cols-3 gap-4">
210
+ <div class="skeleton"></div>
211
+ <div class="skeleton"></div>
212
+ <div class="skeleton"></div>
213
+ </div>
214
+ </details>
215
+
216
+ <details class="fold glass-card rounded-3xl p-5">
217
+ <summary><h2 class="section-title text-lg">Order and hide</h2></summary>
218
+ <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">
219
+ <p class="muted text-sm">Arrange how catalogs appear in Stremio, or hide one from everyone.</p>
220
+ <button id="save-order-btn" onclick="saveCatalogOrder()" class="btn-ui btn-primary sm:w-auto hidden"><i class="fa-solid fa-floppy-disk"></i> Save order</button>
221
+ </div>
222
+ <div id="catalog-order-list" class="space-y-2">
223
+ <div class="skeleton"></div>
224
+ <div class="skeleton"></div>
225
+ </div>
226
+ </details>
227
+
228
  <div class="grid grid-cols-1 xl:grid-cols-[0.88fr_1.12fr] gap-6">
229
  <div class="space-y-6">
230
+ <details class="fold glass-card rounded-3xl p-5">
231
+ <summary><h2 class="section-title text-lg">Create catalog</h2></summary>
 
 
 
 
 
 
232
 
233
  <form onsubmit="createCatalog(event)" class="space-y-4">
234
  <div>
 
236
  <input id="catalog-name" class="field-input" placeholder="Example: Bollywood Hits" required>
237
  </div>
238
 
239
+ <div>
240
+ <label class="field-label">Who can see it</label>
241
+ <select id="catalog-visibility" class="field-select" onchange="onVisibilityModeChange('catalog')">
242
+ <option value="public">Everyone</option>
243
+ <option value="tokens">Specific users</option>
244
+ <option value="owner">Owner only (hidden)</option>
245
+ </select>
246
+ <p class="muted text-xs mt-2" id="catalog-visibility-hint">Shown to everyone who installed the addon.</p>
247
+ </div>
248
 
249
+ <div id="catalog-token-picker-wrap" class="hidden">
250
+ <label class="field-label">Allowed users</label>
251
+ <div id="catalog-token-picker" class="token-picker"></div>
252
+ </div>
253
+
254
+ <button class="btn-ui btn-primary w-full" type="submit"><i class="fa-solid fa-plus"></i> Create catalog</button>
255
  </form>
256
+ </details>
257
 
258
+ <div class="glass-card rounded-3xl p-5">
259
  <div class="flex items-center justify-between gap-3 mb-5">
260
  <div>
261
+ <h2 class="section-title text-lg">Your catalogs</h2>
262
  <p class="muted text-sm mt-1">Select one to manage titles.</p>
263
  </div>
264
+ <button onclick="loadCatalogs()" class="btn-ui btn-ghost w-10 h-10 !p-0" aria-label="Reload catalogs"><i class="fa-solid fa-rotate"></i></button>
265
  </div>
266
  <div id="catalog-list-wrapper" class="catalog-list-wrapper collapsed">
267
  <div id="catalog-list" class="space-y-3">
 
269
  <div class="skeleton"></div>
270
  </div>
271
  </div>
272
+ <button id="catalog-expand-btn" onclick="toggleCatalogExpand()" class="btn-ui btn-ghost w-full hidden">Show all catalogs</button>
273
  </div>
274
  </div>
275
 
276
+ <div class="glass-card rounded-3xl p-5">
277
  <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-3 mb-5">
278
  <div>
279
  <div class="flex flex-wrap gap-2 mb-3">
280
  <span id="selected-visibility-pill" class="pill hidden"></span>
281
  <span id="selected-count-pill" class="pill hidden"></span>
282
  </div>
283
+ <h2 id="selected-title" class="section-title text-lg">Select a catalog</h2>
284
  <p id="selected-subtitle" class="muted text-sm mt-1">Choose a catalog from the left side to add or remove titles.</p>
285
  </div>
286
  <button id="delete-catalog-btn" onclick="deleteSelectedCatalog()" class="btn-ui btn-danger hidden md:w-auto">Delete Catalog</button>
287
  </div>
288
 
289
  <div id="catalog-empty-guide" class="empty-state p-6 sm:p-8 text-center">
290
+ <div class="mx-auto mb-3 grid place-items-center w-12 h-12 rounded-full bg-card-high text-text-secondary"><i class="fa-solid fa-layer-group"></i></div>
291
+ <h3 class="section-title text-lg">No catalog selected</h3>
292
  <p class="muted mt-2 text-sm leading-6">Create a catalog or select an existing one. Then search from your existing media library and add titles instantly.</p>
293
  </div>
294
 
295
  <div id="catalog-workspace" class="hidden space-y-6">
296
+ <div class="catalog-card p-4 sm:p-5">
297
+ <div class="flex flex-col md:flex-row md:items-end gap-3">
298
+ <div class="flex-1">
299
+ <label class="field-label">Catalog visibility</label>
300
+ <select id="ws-visibility" class="field-select" onchange="onVisibilityModeChange('ws')">
301
+ <option value="public">Everyone</option>
302
+ <option value="tokens">Specific users</option>
303
+ <option value="owner">Owner only (hidden)</option>
304
+ </select>
305
+ </div>
306
+ <button onclick="applyCatalogVisibility()" class="btn-ui btn-primary md:w-auto">Apply to all titles</button>
307
+ </div>
308
+ <div id="ws-token-picker-wrap" class="hidden mt-3">
309
+ <label class="field-label">Allowed users</label>
310
+ <div id="ws-token-picker" class="token-picker"></div>
311
+ </div>
312
+
313
+ <div id="ws-exclusive-wrap" class="hidden mt-3 space-y-2">
314
+ <label class="toggle-row">
315
+ <span class="min-w-0">
316
+ <span class="font-semibold text-sm block"><i class="fa-solid fa-lock"></i> Only visible in this catalog</span>
317
+ <span class="muted text-xs block">Removed from Default, Auto and other catalogs.</span>
318
+ </span>
319
+ <input type="checkbox" id="ws-exclusive" class="switch-input hidden" onchange="onExclusiveChange()">
320
+ <span class="switch"></span>
321
+ </label>
322
+ <div id="ws-search-wrap" class="hidden">
323
+ <label class="toggle-row">
324
+ <span class="min-w-0">
325
+ <span class="font-semibold text-sm block"><i class="fa-solid fa-magnifying-glass"></i> Allow search</span>
326
+ <span class="muted text-xs block">Let allowed users find these titles via search.</span>
327
+ </span>
328
+ <input type="checkbox" id="ws-searchable" class="switch-input hidden">
329
+ <span class="switch"></span>
330
+ </label>
331
+ </div>
332
+ </div>
333
+
334
+ <p class="muted text-xs mt-3">Applies to every title in this catalog. Fine-tune a single title from its <b>Edit</b> page.</p>
335
+ </div>
336
+
337
  <div class="catalog-card p-4 sm:p-5">
338
  <div class="flex flex-col sm:flex-row sm:items-end gap-3">
339
  <div class="flex-1">
 
347
  <option value="tv">Series</option>
348
  </select>
349
  </div>
350
+ <button onclick="searchMedia()" class="btn-ui btn-primary sm:w-auto"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
351
  </div>
352
  </div>
353
 
 
378
  let catalogs = [];
379
  let selectedCatalogId = null;
380
  let catalogListExpanded = false;
381
+ let subscriptionOn = false;
382
+ let availableTokens = [];
383
+
384
+ const VIS_META = {
385
+ public: { icon: '<i class="fa-solid fa-globe"></i>', chip: 'vis-public' },
386
+ tokens: { icon: '<i class="fa-solid fa-bullseye"></i>', chip: 'vis-tokens' },
387
+ owner: { icon: '<i class="fa-solid fa-lock"></i>', chip: 'vis-owner' },
388
+ };
389
+
390
+ function publicLabel() { return subscriptionOn ? 'Active subscribers' : 'Everyone'; }
391
+
392
+ function visibilityLabel(mode) {
393
+ if (mode === 'tokens') return 'Specific users';
394
+ if (mode === 'owner') return 'Owner only';
395
+ return publicLabel();
396
+ }
397
+
398
+ function visibilityHint(mode) {
399
+ if (mode === 'tokens') return 'Shown only to the users you select below.';
400
+ if (mode === 'owner') return 'Hidden from all users. Visible only to you and in this panel.';
401
+ return subscriptionOn ? 'Shown to all active subscribers.' : 'Shown to everyone who installed the addon.';
402
+ }
403
+
404
+ function applyPublicLabels() {
405
+ document.querySelectorAll('#catalog-visibility option[value="public"], #ws-visibility option[value="public"]')
406
+ .forEach(o => o.textContent = publicLabel());
407
+ }
408
+
409
+ async function loadSettings() {
410
+ try {
411
+ const res = await fetch('/api/admin/settings');
412
+ const data = await res.json().catch(() => ({}));
413
+ subscriptionOn = !!(data.settings && data.settings.subscription);
414
+ } catch (e) {}
415
+ applyPublicLabels();
416
+ onVisibilityModeChange('catalog');
417
+ }
418
+
419
+ async function loadTokens() {
420
+ try {
421
+ const res = await fetch('/api/admin/access/tokens');
422
+ const data = await res.json().catch(() => ({}));
423
+ availableTokens = (data.tokens || []).filter(t => t.token);
424
+ } catch (e) { availableTokens = []; }
425
+ }
426
+
427
+ function renderTokenPicker(containerId, selected) {
428
+ const box = document.getElementById(containerId);
429
+ if (!box) return;
430
+ const sel = new Set(selected || []);
431
+ if (!availableTokens.length) {
432
+ box.innerHTML = '<p class="muted text-xs p-2">No users/tokens found. Create access tokens on the Access page first.</p>';
433
+ return;
434
+ }
435
+ box.innerHTML = availableTokens.map(t => `
436
+ <label class="token-row">
437
+ <input type="checkbox" value="${escapeHtml(t.token)}" ${sel.has(t.token) ? 'checked' : ''}>
438
+ <span class="min-w-0">
439
+ <span class="font-semibold text-sm block truncate">${escapeHtml(t.user_name || 'User')}</span>
440
+ <span class="muted text-xs block truncate">${escapeHtml((t.token || '').slice(0, 12))}…${t.user_id ? ' · ' + escapeHtml(t.user_id) : ''}</span>
441
+ </span>
442
+ </label>`).join('');
443
+ }
444
+
445
+ function getPickedTokens(containerId) {
446
+ return Array.from(document.querySelectorAll(`#${containerId} input:checked`)).map(i => i.value);
447
+ }
448
+
449
+ function onVisibilityModeChange(scope) {
450
+ const isWs = scope === 'ws';
451
+ const mode = document.getElementById(isWs ? 'ws-visibility' : 'catalog-visibility').value;
452
+ const wrap = document.getElementById(isWs ? 'ws-token-picker-wrap' : 'catalog-token-picker-wrap');
453
+ if (wrap) wrap.classList.toggle('hidden', mode !== 'tokens');
454
+ if (mode === 'tokens') {
455
+ const preset = isWs ? (getSelectedCatalog()?.allowed_tokens || []) : [];
456
+ renderTokenPicker(isWs ? 'ws-token-picker' : 'catalog-token-picker', preset);
457
+ }
458
+ if (!isWs) {
459
+ const hint = document.getElementById('catalog-visibility-hint');
460
+ if (hint) hint.textContent = visibilityHint(mode);
461
+ } else {
462
+ //----- Exclusive lock is only offered for restricted, non-auto catalogs
463
+ const isAuto = !!(getSelectedCatalog()?.auto);
464
+ const canExclusive = !isAuto && mode !== 'public';
465
+ const exclWrap = document.getElementById('ws-exclusive-wrap');
466
+ if (exclWrap) exclWrap.classList.toggle('hidden', !canExclusive);
467
+ if (!canExclusive) {
468
+ const ex = document.getElementById('ws-exclusive');
469
+ if (ex) ex.checked = false;
470
+ }
471
+ onExclusiveChange();
472
+ }
473
+ }
474
+
475
+ function onExclusiveChange() {
476
+ const on = !!document.getElementById('ws-exclusive')?.checked;
477
+ const wrapVisible = !document.getElementById('ws-exclusive-wrap')?.classList.contains('hidden');
478
+ const searchWrap = document.getElementById('ws-search-wrap');
479
+ if (searchWrap) searchWrap.classList.toggle('hidden', !(on && wrapVisible));
480
+ }
481
 
482
  function posterOrFallback(item) {
483
+ return item.poster || '/static/placeholder.svg';
484
  }
485
 
486
  function escapeHtml(value) {
 
495
 
496
  function updateStats() {
497
  const total = catalogs.length;
498
+ const visible = catalogs.filter(c => (c.visibility || 'public') !== 'owner').length;
499
+ const items = catalogs.reduce((sum, c) => sum + (c.item_count || 0), 0);
500
  document.getElementById('stat-total').textContent = total;
501
  document.getElementById('stat-visible').textContent = visible;
502
  document.getElementById('stat-items').textContent = items;
 
506
  const mediaType = item.media_type === 'tv' ? 'Series' : 'Movie';
507
  const genres = Array.isArray(item.genres) ? item.genres.slice(0, 2).join(' · ') : '';
508
  return `<div class="media-card p-3 flex gap-3">
509
+ <img src="${escapeHtml(posterOrFallback(item))}" class="poster" onerror="this.src='/static/placeholder.svg'" alt="Poster">
510
  <div class="min-w-0 flex-1">
511
  <div class="flex items-start justify-between gap-2">
512
  <div class="min-w-0">
513
+ <h4 class="font-semibold truncate" title="${escapeHtml(item.title)}">${escapeHtml(item.title)}</h4>
514
  <p class="muted text-xs mt-1">${mediaType} · ${escapeHtml(item.release_year || 'Unknown')} · TMDb ${escapeHtml(item.tmdb_id || '')}</p>
515
  </div>
516
  <span class="pill text-[0.68rem] py-1 px-2">${escapeHtml(mediaType)}</span>
 
523
 
524
  function emptyState(icon, title, message) {
525
  return `<div class="empty-state p-6 text-center col-span-full">
526
+ <div class="mx-auto mb-3 grid place-items-center w-11 h-11 rounded-full bg-card-high text-text-secondary">${icon}</div>
527
  <h4 class="section-title text-lg">${escapeHtml(title)}</h4>
528
  <p class="muted text-sm mt-1">${escapeHtml(message)}</p>
529
  </div>`;
 
542
  renderCatalogs();
543
  updateSelectedHeader();
544
  } catch (error) {
545
+ box.innerHTML = emptyState('<i class="fa-solid fa-triangle-exclamation"></i>', 'Unable to load catalogs', error.message || 'Please refresh and try again.');
546
  showToast(error.message || 'Unable to load catalogs', 'error', 'Error');
547
  }
548
  }
 
553
  const wrapper = document.getElementById('catalog-list-wrapper');
554
 
555
  if (!catalogs.length) {
556
+ box.innerHTML = emptyState('<i class="fa-solid fa-wand-magic-sparkles"></i>', 'No custom catalog yet', 'Create your first curated Stremio section above.');
557
  if (expandBtn) expandBtn.classList.add('hidden');
558
  if (wrapper) wrapper.classList.remove('collapsed');
559
  return;
 
561
 
562
  box.innerHTML = catalogs.map(c => {
563
  const isActive = c._id === selectedCatalogId;
564
+ const count = c.item_count || 0;
565
+ const mode = c.visibility || 'public';
566
+ const meta = VIS_META[mode] || VIS_META.public;
567
  return `<div class="catalog-card p-4 ${isActive ? 'active' : ''}">
568
+ <button class="text-left w-full min-w-0" onclick="selectCatalog('${c._id}')">
569
+ <div class="flex items-center gap-2 min-w-0">
570
+ <span class="text-primary w-5 text-center shrink-0">${c.auto ? '<i class="fa-solid fa-wand-magic-sparkles"></i>' : meta.icon}</span>
571
+ <h3 class="font-semibold truncate">${escapeHtml(c.name)}</h3>
572
+ ${c.auto ? '<span class="pill text-[0.62rem] px-2 py-0.5">Auto</span>' : ''}
573
+ </div>
574
+ <div class="flex items-center gap-2 mt-2 flex-wrap">
575
+ <span class="vis-chip ${meta.chip}">${meta.icon} ${escapeHtml(visibilityLabel(mode))}</span>
576
+ ${c.exclusive ? `<span class="vis-chip vis-owner"><i class="fa-solid fa-lock"></i> Exclusive${c.searchable ? ' · <i class="fa-solid fa-magnifying-glass"></i>' : ''}</span>` : ''}
577
+ <span class="muted text-xs">${count} title${count === 1 ? '' : 's'}</span>
578
+ </div>
579
+ </button>
 
 
580
  </div>`;
581
  }).join('');
582
 
 
584
  if (catalogs.length > 3) {
585
  if (expandBtn) {
586
  expandBtn.classList.remove('hidden');
587
+ expandBtn.textContent = catalogListExpanded ? 'Collapse list' : 'Show all catalogs';
588
  }
589
  if (wrapper) wrapper.classList.toggle('collapsed', !catalogListExpanded);
590
  } else {
 
617
  deleteBtn.classList.remove('hidden');
618
  visibilityPill.classList.remove('hidden');
619
  countPill.classList.remove('hidden');
620
+
621
+ const mode = catalog.visibility || 'public';
622
+ const meta = VIS_META[mode] || VIS_META.public;
623
+ visibilityPill.className = `pill vis-chip ${meta.chip}`;
624
+ visibilityPill.innerHTML = `${meta.icon} ${escapeHtml(visibilityLabel(mode))}`;
625
+ countPill.textContent = `${catalog.item_count || 0} title${catalog.item_count === 1 ? '' : 's'}`;
626
  document.getElementById('selected-title').textContent = catalog.name || 'Selected Catalog';
627
+ document.getElementById('selected-subtitle').textContent = 'Manage titles and choose who can see this catalog in Stremio.';
628
+
629
+ const sel = document.getElementById('ws-visibility');
630
+ if (sel) sel.value = mode;
631
+
632
+ const exToggle = document.getElementById('ws-exclusive');
633
+ const searchToggle = document.getElementById('ws-searchable');
634
+ if (exToggle) exToggle.checked = !!catalog.exclusive;
635
+ if (searchToggle) searchToggle.checked = !!catalog.searchable;
636
+
637
+ onVisibilityModeChange('ws');
638
  }
639
 
640
  async function createCatalog(event) {
641
  event.preventDefault();
642
  const name = document.getElementById('catalog-name').value.trim();
643
+ const visibility = document.getElementById('catalog-visibility').value;
644
+ const allowed_tokens = visibility === 'tokens' ? getPickedTokens('catalog-token-picker') : [];
645
  if (!name) return showToast('Catalog name is required', 'error', 'Error');
646
+ if (visibility === 'tokens' && !allowed_tokens.length)
647
+ return showToast('Select at least one user for a restricted catalog.', 'error', 'Error');
648
  const res = await fetch('/api/custom-catalogs', {
649
+ method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, visibility, allowed_tokens})
650
  });
651
  const data = await res.json().catch(() => ({}));
652
  if (!res.ok) return showToast(data.detail || 'Failed to create catalog', 'error', 'Error');
653
  document.getElementById('catalog-name').value = '';
654
+ document.getElementById('catalog-visibility').value = 'public';
655
+ onVisibilityModeChange('catalog');
656
  showToast('Catalog created', 'success', 'Success');
657
  await loadCatalogs();
658
  }
659
 
660
+ async function applyCatalogVisibility() {
661
+ const catalog = getSelectedCatalog();
662
+ if (!catalog) return;
663
+ const visibility = document.getElementById('ws-visibility').value;
664
+ const allowed_tokens = visibility === 'tokens' ? getPickedTokens('ws-token-picker') : [];
665
+ if (visibility === 'tokens' && !allowed_tokens.length)
666
+ return showToast('Select at least one user.', 'error', 'Error');
667
+ const canExclusive = !catalog.auto && visibility !== 'public';
668
+ const exclusive = canExclusive && !!document.getElementById('ws-exclusive')?.checked;
669
+ const searchable = exclusive && !!document.getElementById('ws-searchable')?.checked;
670
+ const res = await fetch(`/api/custom-catalogs/${catalog._id}`, {
671
+ method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: catalog.name, visibility, allowed_tokens, exclusive, searchable})
672
  });
673
  const data = await res.json().catch(() => ({}));
674
+ if (!res.ok) return showToast(data.detail || 'Failed to update visibility', 'error', 'Error');
675
+ showToast(exclusive ? 'Exclusive lock applied — titles now show only here' : 'Visibility applied to all titles in this catalog', 'success', 'Success');
676
  await loadCatalogs();
677
  }
678
 
 
680
  selectedCatalogId = id;
681
  renderCatalogs();
682
  updateSelectedHeader();
683
+ if (innerWidth < 1280) document.getElementById('selected-title').scrollIntoView({ behavior: 'smooth' });
684
  await loadCatalogItems();
685
  }
686
 
 
700
  const results = data.results || [];
701
  box.innerHTML = results.length
702
  ? results.map(item => mediaCard(item, `<button class="btn-ui btn-primary px-3 py-2 text-sm" onclick="addItem(${item.tmdb_id}, ${item.db_index}, '${item.media_type}')">Add</button>`)).join('')
703
+ : emptyState('<i class="fa-solid fa-magnifying-glass"></i>', 'No title found', 'Try a shorter title or change movie/series type.');
704
  } catch (error) {
705
+ box.innerHTML = emptyState('<i class="fa-solid fa-triangle-exclamation"></i>', 'Search failed', error.message || 'Please try again.');
706
  }
707
  }
708
 
 
733
  const items = data.items || [];
734
  box.innerHTML = items.length
735
  ? items.map(item => mediaCard(item, `<button class="btn-ui btn-danger px-3 py-2 text-sm" onclick="removeItem(${item.tmdb_id}, ${item.db_index}, '${item.media_type}')">Remove</button>`)).join('')
736
+ : emptyState('<i class="fa-solid fa-plus"></i>', 'No titles added yet', 'Use search above to add media to this catalog.');
737
  } catch (error) {
738
+ box.innerHTML = emptyState('<i class="fa-solid fa-triangle-exclamation"></i>', 'Unable to load titles', error.message || 'Please try again.');
739
  }
740
  }
741
 
 
776
  box.innerHTML = `<div class="empty-state p-4 muted">No auto catalog options found.</div>`;
777
  return;
778
  }
 
779
  const groups = {};
780
+ defs.forEach(def => { (groups[def.group] = groups[def.group] || []).push(def); });
 
 
 
 
781
  box.innerHTML = Object.entries(groups).map(([group, items]) => `
782
+ <div class="catalog-card p-4">
783
+ <div class="flex items-center gap-2 mb-3">
784
+ <h4 class="section-title text-base">${escapeHtml(group)}</h4>
785
+ <span class="pill text-[0.65rem] px-2 py-0.5">${items.length}</span>
786
+ </div>
787
+ <div class="flex flex-wrap gap-2">
788
+ ${items.map(item => `
789
+ <button type="button" class="auto-chip ${item.enabled ? 'on' : ''}"
790
+ data-key="${escapeHtml(item.key)}" aria-pressed="${item.enabled}"
791
+ onclick="toggleAutoCatalog(this)">
792
+ <span class="dot"></span>${escapeHtml(item.name)}
793
+ </button>`).join('')}
 
 
 
 
 
 
 
 
794
  </div>
795
  </div>
796
  `).join('');
 
799
  }
800
  }
801
 
802
+ let autoSaveTimer = null;
803
+ async function toggleAutoCatalog(btn) {
804
+ const on = !btn.classList.contains('on');
805
+ btn.classList.toggle('on', on);
806
+ btn.setAttribute('aria-pressed', on);
807
+ clearTimeout(autoSaveTimer);
808
+ autoSaveTimer = setTimeout(persistAutoCatalogs, 400);
809
+ }
810
+
811
+ async function persistAutoCatalogs() {
812
+ const enabledKeys = Array.from(document.querySelectorAll('.auto-chip.on')).map(el => el.dataset.key);
813
  try {
 
814
  const res = await fetch('/api/custom-catalogs/auto-sync/settings', {
815
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
 
816
  body: JSON.stringify({ enabled_keys: enabledKeys })
817
  });
818
  const data = await res.json().catch(() => ({}));
819
  if (!res.ok) throw new Error(data.detail || 'Failed to save settings');
820
+ showToast('Saved. Press Sync to rebuild catalogs.', 'success', 'Auto catalogs');
 
821
  } catch (error) {
822
  showToast(error.message || 'Failed to save settings', 'error', 'Error');
823
+ loadAutoCatalogSettings();
824
+ }
825
+ }
826
+
827
+ let catalogOrder = [];
828
+ async function loadCatalogOrder() {
829
+ const box = document.getElementById('catalog-order-list');
830
+ if (!box) return;
831
+ try {
832
+ const res = await fetch('/api/custom-catalogs-order');
833
+ const data = await res.json().catch(() => ({}));
834
+ if (!res.ok) throw new Error(data.detail || 'Failed to load order');
835
+ catalogOrder = data.entries || [];
836
+ renderCatalogOrder();
837
+ } catch (error) {
838
+ box.innerHTML = `<div class="empty-state p-4 text-red-400">${escapeHtml(error.message || 'Failed to load order')}</div>`;
839
+ }
840
+ }
841
+
842
+ const ORDER_GROUP_CLASS = { 'Default Movies': 'vis-tokens', 'Default TV': 'vis-tokens', 'Auto': 'vis-public', 'Custom': 'vis-owner' };
843
+
844
+ function renderCatalogOrder() {
845
+ const box = document.getElementById('catalog-order-list');
846
+ if (!catalogOrder.length) { box.innerHTML = emptyState('<i class="fa-solid fa-layer-group"></i>', 'No catalogs', 'Create catalogs to reorder them.'); return; }
847
+ box.innerHTML = catalogOrder.map((e, i) => {
848
+ const typeLabel = e.type === 'series' ? 'Series' : 'Movie';
849
+ return `<div class="order-row" style="${e.hidden ? 'opacity:.55' : ''}">
850
+ <span class="drag-idx">${i + 1}</span>
851
+ <span class="min-w-0 flex-1">
852
+ <span class="font-semibold truncate block">${escapeHtml(e.name)}</span>
853
+ <span class="flex items-center gap-2 mt-1">
854
+ <span class="vis-chip ${ORDER_GROUP_CLASS[e.group] || 'vis-tokens'}">${escapeHtml(e.group)}</span>
855
+ <span class="muted text-xs">${typeLabel}</span>
856
+ </span>
857
+ </span>
858
+ <label class="flex items-center gap-2 text-xs muted cursor-pointer"><input type="checkbox" ${e.hidden ? 'checked' : ''} onchange="toggleCatalogHidden(${i}, this.checked)"> Hide</label>
859
+ <span class="flex flex-col gap-1">
860
+ <button class="order-arrow" ${i === 0 ? 'disabled' : ''} onclick="moveCatalogOrder(${i}, -1)" aria-label="Move up"><i class="fa-solid fa-chevron-up"></i></button>
861
+ <button class="order-arrow" ${i === catalogOrder.length - 1 ? 'disabled' : ''} onclick="moveCatalogOrder(${i}, 1)" aria-label="Move down"><i class="fa-solid fa-chevron-down"></i></button>
862
+ </span>
863
+ </div>`;
864
+ }).join('');
865
+ }
866
+
867
+ function toggleCatalogHidden(i, v) {
868
+ catalogOrder[i].hidden = v;
869
+ renderCatalogOrder();
870
+ document.getElementById('save-order-btn').classList.remove('hidden');
871
+ }
872
+
873
+ function moveCatalogOrder(i, dir) {
874
+ const j = i + dir;
875
+ if (j < 0 || j >= catalogOrder.length) return;
876
+ [catalogOrder[i], catalogOrder[j]] = [catalogOrder[j], catalogOrder[i]];
877
+ renderCatalogOrder();
878
+ document.getElementById('save-order-btn').classList.remove('hidden');
879
+ }
880
+
881
+ async function saveCatalogOrder() {
882
+ const btn = document.getElementById('save-order-btn');
883
+ btn.disabled = true;
884
+ try {
885
+ const res = await fetch('/api/custom-catalogs-order', {
886
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
887
+ body: JSON.stringify({ order: catalogOrder.map(e => e.key), hidden: catalogOrder.filter(e => e.hidden).map(e => e.key) })
888
+ });
889
+ const data = await res.json().catch(() => ({}));
890
+ if (!res.ok) throw new Error(data.detail || 'Failed to save order');
891
+ showToast('Catalog order saved.', 'success', 'Order');
892
+ btn.classList.add('hidden');
893
+ } catch (error) {
894
+ showToast(error.message || 'Failed to save order', 'error', 'Error');
895
  } finally {
896
+ btn.disabled = false;
897
  }
898
  }
899
 
 
902
  async function loadAutoSyncStatus() {
903
  const pill = document.getElementById('auto-sync-status');
904
  const syncBtn = document.getElementById('auto-sync-btn');
 
905
  if (!pill) return;
906
  try {
907
  const res = await fetch('/api/custom-catalogs/auto-sync/status');
908
  const data = await res.json().catch(() => ({}));
909
  const status = data.status || {};
 
910
 
911
  if (status.running) {
912
+ pill.textContent = `Sync running: ${status.scanned || 0} scanned · ${status.classified || 0} checked`;
913
  if (syncBtn) syncBtn.disabled = true;
 
914
  if (!autoSyncPollTimer) {
915
  autoSyncPollTimer = setInterval(loadAutoSyncStatus, 3000);
916
  }
917
  } else {
918
  if (status.finished_at) {
919
  pill.textContent = status.error
920
+ ? 'Sync failed'
921
+ : `Synced: ${status.classified || 0} checked · ${status.skipped || 0} reused`;
922
  } else {
923
+ pill.textContent = 'Sync runs on boot';
924
  }
925
  if (syncBtn) syncBtn.disabled = false;
 
926
  if (autoSyncPollTimer) {
927
  clearInterval(autoSyncPollTimer);
928
  autoSyncPollTimer = null;
 
934
  }
935
  }
936
 
937
+ async function runAutoSync() {
938
+ const btn = document.getElementById('auto-sync-btn');
 
939
  const old = btn.textContent;
940
  btn.disabled = true;
941
+ btn.textContent = '⏳ Syncing...';
 
942
  try {
943
+ const res = await fetch('/api/custom-catalogs/auto-sync', { method: 'POST' });
 
944
  const data = await res.json().catch(() => ({}));
945
+ if (!res.ok) throw new Error(data.detail || 'Sync failed');
946
  const result = data.result || {};
947
+ showToast(result.message || data.message || 'Sync started in background.', 'info', 'Sync started');
 
948
  await loadAutoSyncStatus();
949
  } catch (error) {
950
+ showToast(error.message || 'Sync failed', 'error', 'Error');
951
  } finally {
952
  btn.textContent = old;
953
  await loadAutoSyncStatus();
 
963
  const wrapper = document.getElementById('catalog-list-wrapper');
964
  const btn = document.getElementById('catalog-expand-btn');
965
  wrapper.classList.toggle('collapsed', !catalogListExpanded);
966
+ if (btn) btn.textContent = catalogListExpanded ? 'Collapse list' : 'Show all catalogs';
967
  }
968
 
969
+ document.addEventListener('DOMContentLoaded', async () => {
970
+ if (innerWidth >= 1024) document.querySelectorAll('.fold').forEach(d => d.open = true);
971
+ await Promise.all([loadSettings(), loadTokens()]);
972
+ loadCatalogs();
973
+ loadAutoSyncStatus();
974
+ loadAutoCatalogSettings();
975
+ loadCatalogOrder();
976
+ });
977
  </script>
978
  {% endblock %}
Backend/fastapi/templates/dashboard.html CHANGED
@@ -3,658 +3,227 @@
3
  {% block title %}Dashboard - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
- <div class="min-h-screen pb-12">
7
- <header class="mb-8 sm:mb-10">
8
- <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
9
- <div>
10
- <h1 class="text-2xl sm:text-3xl font-extrabold tracking-tight text-transparent bg-clip-text bg-gradient-to-r from-primary to-accent">
11
- System Overview
12
- </h1>
13
- <p class="text-text-secondary text-xs sm:text-sm mt-1">Real-time performance, live stream activity, and token access management</p>
14
- </div>
15
-
16
- <button onclick="refreshDashboard()"
17
- class="w-full md:w-auto flex items-center justify-center space-x-2 px-6 py-3 rounded-2xl bg-primary/10 border border-primary/20 hover:bg-primary hover:text-background transition-all group active:scale-95">
18
- <i id="refresh-icon" class="fa-solid fa-arrows-rotate group-hover:rotate-180 transition-transform duration-700"></i>
19
- <span class="font-bold text-sm uppercase tracking-wider">Refresh Data</span>
20
- </button>
21
  </div>
 
 
 
22
  </header>
23
 
24
- <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
25
- <div class="glass-panel p-5 rounded-[2rem] flex items-center gap-4">
26
- <div class="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center text-primary shadow-glow">
27
- <i class="fa-solid fa-clock"></i>
28
- </div>
29
- <div>
30
- <p class="text-[10px] uppercase font-bold text-text-secondary tracking-widest">Uptime</p>
31
- <p id="sys-uptime" class="text-lg font-bold text-text">{{ system_stats.uptime or 'N/A' }}</p>
32
- </div>
33
- </div>
34
 
35
- <div class="glass-panel p-5 rounded-[2rem] flex items-center gap-4">
36
- <div class="w-12 h-12 rounded-2xl bg-accent/10 flex items-center justify-center text-accent shadow-[0_0_15px_color-mix(in_srgb,var(--accent)_35%,transparent)]">
37
- <i class="fa-solid fa-robot"></i>
 
 
 
 
 
 
38
  </div>
39
- <div>
40
- <p class="text-[10px] uppercase font-bold text-text-secondary tracking-widest">Active Bots</p>
41
- <p id="sys-bots-count" class="text-lg font-bold text-text">{{ system_stats.connected_bots|default(0) }} Nodes</p>
 
 
42
  </div>
43
  </div>
 
44
 
45
- <div class="glass-panel p-5 rounded-[2rem] flex items-center gap-4">
46
- <div class="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center text-primary shadow-glow">
47
- <i class="fa-solid fa-tower-broadcast"></i>
 
 
 
 
 
48
  </div>
49
- <div>
50
- <p class="text-[10px] uppercase font-bold text-text-secondary tracking-widest">Live Streams</p>
51
- <p id="sys-live-streams" class="text-lg font-bold text-text">{{ system_stats.total_active_streams }} Active</p>
 
 
 
 
 
 
 
52
  </div>
 
53
  </div>
 
54
 
55
- <div class="glass-panel p-5 rounded-[2rem] flex items-center gap-4">
56
- <div class="w-12 h-12 rounded-2xl bg-surface flex items-center justify-center text-text-secondary">
57
- <i class="fa-solid fa-code-branch"></i>
58
- </div>
59
- <div>
60
- <p class="text-[10px] uppercase font-bold text-text-secondary tracking-widest">Version</p>
61
- <p id="sys-version" class="text-lg font-bold text-text">v{{ system_stats.version or '1.0.0' }}</p>
62
- </div>
63
  </div>
64
- </div>
 
65
 
66
- <div class="grid lg:grid-cols-3 gap-8">
67
- <div class="lg:col-span-2 space-y-8">
68
  <section>
69
- <h3 class="flex items-center gap-2 text-lg font-bold mb-4 ml-2">
70
- <i class="fa-solid fa-database text-primary"></i> Storage Nodes
71
- </h3>
72
-
73
- <div class="grid md:grid-cols-2 gap-4">
74
- {% for db_stat in system_stats.databases %}
75
- <div class="glass-panel p-6 rounded-[2rem] border-hairline bg-card/10">
76
- <div class="flex justify-between items-start mb-6">
77
- <h4 class="font-bold text-text">{{ db_stat.db_name.replace("storage_", "Node ") }}</h4>
78
- <span class="text-[10px] bg-primary/10 text-primary px-2 py-1 rounded-lg font-bold uppercase">Online</span>
79
- </div>
80
-
81
- <div class="space-y-4">
82
- <div class="flex justify-between text-sm">
83
- <span class="text-text-secondary">Movies / TV</span>
84
- <span class="font-bold text-text">{{ db_stat.movie_count }} / {{ db_stat.tv_count }}</span>
85
- </div>
86
-
87
- <div class="space-y-2">
88
- <div class="flex justify-between text-xs font-bold uppercase tracking-widest">
89
- <span class="text-text-secondary">Disk Usage</span>
90
- <span class="text-primary">{{ "%.1f"|format(db_stat.storageSize / 1024 / 1024) }} MB</span>
91
- </div>
92
- <div class="w-full h-1.5 bg-surface rounded-full overflow-hidden">
93
- {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %}
94
- <div class="h-full bg-gradient-to-r from-primary to-accent transition-all duration-1000" style="width: {{ storage_percent }}%"></div>
95
- </div>
96
- </div>
97
- </div>
98
- </div>
99
- {% endfor %}
100
  </div>
101
  </section>
102
 
103
- <section class="grid grid-cols-1 sm:grid-cols-2 gap-4">
104
- <a href="/media/manage?media_type=movie" class="glass-panel p-6 rounded-[2rem] hover:bg-primary/5 transition-all group border border-hairline">
105
- <div class="flex items-center gap-4">
106
- <div class="w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center text-primary group-hover:scale-110 transition-transform">
107
- <i class="fa-solid fa-film text-2xl"></i>
108
- </div>
109
- <div>
110
- <h4 class="font-bold text-text">Manage Movies</h4>
111
- <p class="text-xs text-text-secondary">Organize and edit library</p>
112
- </div>
113
- <i class="fa-solid fa-chevron-right ml-auto text-muted group-hover:text-primary group-hover:translate-x-1 transition-all"></i>
114
- </div>
115
- </a>
116
-
117
- <a href="/media/manage?media_type=tv" class="glass-panel p-6 rounded-[2rem] hover:bg-accent/5 transition-all group border border-hairline">
118
- <div class="flex items-center gap-4">
119
- <div class="w-14 h-14 rounded-2xl bg-accent/10 flex items-center justify-center text-accent group-hover:scale-110 transition-transform">
120
- <i class="fa-solid fa-tv text-2xl"></i>
121
- </div>
122
- <div>
123
- <h4 class="font-bold text-text">Manage TV Shows</h4>
124
- <p class="text-xs text-text-secondary">Handle series and episodes</p>
125
- </div>
126
- <i class="fa-solid fa-chevron-right ml-auto text-muted group-hover:text-accent group-hover:translate-x-1 transition-all"></i>
127
- </div>
128
- </a>
129
- </section>
130
- </div>
131
-
132
- <div class="lg:col-span-1">
133
- <div class="glass-panel rounded-[2.5rem] overflow-hidden h-full">
134
- <div class="p-6 border-b border-hairline">
135
- <div class="flex items-center justify-between gap-3 mb-2">
136
- <h3 class="flex items-center gap-2 text-lg font-bold">
137
- <i class="fa-solid fa-circle-play text-red-500 animate-pulse"></i> Live Network
138
- </h3>
139
- <span id="live-stream-count" class="text-[10px] font-bold uppercase tracking-[0.2em] text-primary bg-primary/10 px-3 py-1 rounded-full">
140
- {{ system_stats.total_active_streams or 0 }} Active
141
- </span>
142
- </div>
143
- <p class="text-sm text-text-secondary">Current sessions only</p>
144
  </div>
145
-
146
- <div class="p-6 space-y-6">
147
- <div class="grid grid-cols-2 gap-3">
148
- <div class="glass-panel p-4 rounded-2xl">
149
- <p class="text-[10px] uppercase font-bold tracking-widest text-text-secondary">Live Now</p>
150
- <p id="live-now-count" class="text-2xl font-extrabold mt-1 text-text">{{ system_stats.total_active_streams or 0 }}</p>
151
- </div>
152
- <div class="glass-panel p-4 rounded-2xl">
153
- <p class="text-[10px] uppercase font-bold tracking-widest text-text-secondary">Recent</p>
154
- <p id="recent-stream-count" class="text-2xl font-extrabold mt-1 text-text">0</p>
155
- </div>
156
- </div>
157
-
158
- <div>
159
- <div class="flex items-center justify-between mb-3">
160
- <h4 class="text-sm font-bold text-text">Active Streams</h4>
161
- <span class="text-[10px] uppercase tracking-widest text-text-secondary">Real-time</span>
162
- </div>
163
- <div id="active-streams-container" class="space-y-4">
164
- {% if system_stats.active_streams %}
165
- {% for stream in system_stats.active_streams %}
166
- <div class="stream-card rounded-[2rem] p-5">
167
- <div class="flex justify-between items-start gap-3">
168
- <div class="min-w-0 pr-2">
169
- <h5 class="font-bold text-sm text-text truncate">{{ stream.title or stream.meta.get('title') or 'Unknown Stream' }}</h5>
170
- <div class="mt-1 flex flex-wrap items-center gap-2 text-[10px] uppercase tracking-widest text-text-secondary">
171
- <span>Bot {{ (stream.client_index or 0) + 1 }}</span>
172
- <span>•</span>
173
- <span>DC {{ stream.dc_id or '-' }}</span>
174
- <span>•</span>
175
- <span class="font-mono">{{ stream.stream_id[:12] if stream.stream_id else 'Unknown' }}{% if stream.stream_id %}…{% endif %}</span>
176
- </div>
177
- </div>
178
- <span class="text-[10px] font-bold px-2 py-1 rounded-lg uppercase whitespace-nowrap stream-badge-live">
179
- Live
180
- </span>
181
- </div>
182
-
183
- <div class="grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-hairline">
184
- <div class="text-center">
185
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Speed</p>
186
- <p class="text-xs font-bold text-text">{{ "%.3f"|format(stream.avg_mbps or 0) }} MB/s</p>
187
- </div>
188
- <div class="text-center">
189
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Total</p>
190
- <p class="text-xs font-bold text-text">{{ "%.1f"|format((stream.total_bytes or 0) / 1024 / 1024) }} MB</p>
191
- </div>
192
- <div class="text-center">
193
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Duration</p>
194
- <p class="text-xs font-bold text-text live-duration" data-start-ts="{{ stream.start_ts or 0 }}">0s</p>
195
- </div>
196
- <div class="text-center">
197
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Status</p>
198
- <p class="text-xs font-bold text-text">{{ stream.status or 'active' }}</p>
199
- </div>
200
- </div>
201
-
202
- <div class="mt-4 pt-4 border-t border-hairline space-y-2">
203
- <div class="flex items-center justify-between text-xs gap-3">
204
- <span class="text-text-secondary">Started</span>
205
- <span class="text-text text-right truncate max-w-[65%] live-started" data-start-ts="{{ stream.start_ts or 0 }}">—</span>
206
- </div>
207
- <div class="flex items-center justify-between text-xs gap-3">
208
- <span class="text-text-secondary">Stream ID</span>
209
- <span class="font-mono text-text text-right truncate max-w-[65%]">{{ stream.stream_id or 'Unknown' }}</span>
210
- </div>
211
- </div>
212
- </div>
213
- {% endfor %}
214
- {% else %}
215
- <div class="glass-panel p-8 rounded-[2rem] text-center border-dashed border-hairline">
216
- <i class="fa-solid fa-satellite-dish text-4xl text-muted mb-3"></i>
217
- <p class="text-sm text-text-secondary font-medium">No active streams right now</p>
218
- <p class="text-xs text-text-secondary mt-1">The live network is idle at the moment.</p>
219
  </div>
220
- {% endif %}
221
- </div>
222
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  </div>
224
- </div>
 
225
  </div>
226
- </div>
227
-
228
- <section class="mt-12">
229
- <div class="glass-panel rounded-[2.5rem] overflow-hidden">
230
- <div class="p-5 sm:p-8 border-b border-hairline flex flex-col md:flex-row md:justify-between md:items-center gap-4">
231
- <div>
232
- <h3 class="text-lg sm:text-xl font-bold text-text">Access Management</h3>
233
- <p class="text-xs sm:text-sm text-text-secondary">Control API tokens, daily quotas, and monthly quotas</p>
234
- </div>
235
- <button onclick="toggleCreateForm()" id="create-btn-container"
236
- class="w-full md:w-auto justify-center px-6 py-3 bg-primary text-background font-bold rounded-2xl hover:brightness-110 transition-all flex items-center gap-2">
237
- <i class="fa-solid fa-plus"></i> New Token
238
- </button>
239
- </div>
240
-
241
- <div id="create-form-container" class="hidden p-5 sm:p-8 bg-surface border-b border-hairline animate-in fade-in slide-in-from-top-4">
242
- <form onsubmit="createToken(event)" class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
243
- <div class="md:col-span-2">
244
- <label class="text-[10px] font-bold uppercase text-text-secondary tracking-widest ml-2 mb-1 block">Token Alias</label>
245
- <input type="text" id="token-name" placeholder="E.g., Living Room TV" required
246
- class="w-full px-4 py-3 rounded-xl border border-hairline focus:border-primary outline-none text-sm text-text placeholder:text-text-secondary bg-[color-mix(in_srgb,var(--card)_88%,var(--bg)_12%)]">
247
- </div>
248
-
249
- <div>
250
- <label class="text-[10px] font-bold uppercase text-text-secondary tracking-widest ml-2 mb-1 block">Daily (GB)</label>
251
- <input type="number" id="daily-limit" value="0" step="0.1" min="0"
252
- class="w-full px-4 py-3 rounded-xl border border-hairline focus:border-primary outline-none text-sm text-text placeholder:text-text-secondary bg-[color-mix(in_srgb,var(--card)_88%,var(--bg)_12%)]">
253
- </div>
254
-
255
- <div>
256
- <label class="text-[10px] font-bold uppercase text-text-secondary tracking-widest ml-2 mb-1 block">Monthly (GB)</label>
257
- <input type="number" id="monthly-limit" value="0" step="0.1" min="0"
258
- class="w-full px-4 py-3 rounded-xl border border-hairline focus:border-primary outline-none text-sm text-text placeholder:text-text-secondary bg-[color-mix(in_srgb,var(--card)_88%,var(--bg)_12%)]">
259
- </div>
260
-
261
- <div class="flex gap-2">
262
- <button type="submit" class="flex-1 py-3 bg-primary text-background font-bold rounded-xl text-sm">Create</button>
263
- <button type="button" onclick="toggleCreateForm()" class="px-4 py-3 bg-surface text-text-secondary rounded-xl hover:bg-surface-2 transition-colors">
264
- <i class="fa-solid fa-xmark"></i>
265
- </button>
266
- </div>
267
- </form>
268
- </div>
269
 
270
- <div class="overflow-x-auto hidden md:block">
271
- <table class="w-full text-left">
272
- <thead>
273
- <tr class="bg-surface text-[10px] uppercase tracking-[0.2em] font-bold text-text-secondary">
274
- <th class="py-5 px-8">Client Name</th>
275
- <th class="py-5 px-8">Usage</th>
276
- <th class="py-5 px-8">Limits</th>
277
- <th class="py-5 px-8">Manifest Link</th>
278
- <th class="py-5 px-8 text-right">Actions</th>
279
- </tr>
280
- </thead>
281
- <tbody class="divide-y divide-hairline">
282
- {% for token in api_tokens %}
283
- <tr class="group hover:bg-surface transition-colors" id="token-row-{{ loop.index0 }}">
284
- <td class="py-6 px-8">
285
- <p class="font-bold text-text">{{ token.name }}</p>
286
- <p class="text-[10px] text-text-secondary uppercase mt-1">
287
- {{ token.created_at.strftime('%Y-%m-%d') if token.created_at else 'Unknown date' }}
288
- </p>
289
- </td>
290
-
291
- <td class="py-6 px-8">
292
- <div class="flex flex-col gap-1">
293
- <span class="text-xs text-text font-medium">
294
- Daily: <span class="text-primary" data-bytes="{{ token.usage.daily.bytes|default(0) }}"></span>
295
- </span>
296
- <span class="text-xs text-text font-medium">
297
- Monthly: <span class="text-accent" data-bytes="{{ token.usage.monthly.bytes|default(0) }}"></span>
298
- </span>
299
- </div>
300
- </td>
301
-
302
- <td class="py-6 px-8">
303
- <div class="flex flex-col gap-1">
304
- <span class="text-[10px] text-text-secondary uppercase">
305
- Daily Limit: {{ token.limits.daily_limit_gb or '∞' }} GB
306
- </span>
307
- <span class="text-[10px] text-text-secondary uppercase">
308
- Monthly Limit: {{ token.limits.monthly_limit_gb or '∞' }} GB
309
- </span>
310
- </div>
311
- </td>
312
-
313
- <td class="py-6 px-8">
314
- <button onclick='copyUrl({{ ((request.base_url|string).replace("http:", "https:") ~ "stremio/" ~ token.token ~ "/manifest.json")|tojson }})'
315
- class="flex items-center gap-2 px-3 py-1.5 bg-background/50 rounded-lg border border-hairline text-[10px] font-bold text-text-secondary hover:text-primary hover:border-primary/30 transition-all">
316
- <i class="fa-solid fa-link text-[8px]"></i> COPY MANIFEST
317
- </button>
318
- </td>
319
-
320
- <td class="py-6 px-8 text-right">
321
- <div class="flex justify-end gap-2">
322
- <button onclick='openEditModal({{ token.token|tojson }}, {{ token.limits.daily_limit_gb|default(0)|tojson }}, {{ token.limits.monthly_limit_gb|default(0)|tojson }})'
323
- class="w-8 h-8 rounded-lg bg-surface flex items-center justify-center text-text-secondary hover:bg-blue-500 hover:text-white transition-all token-action-btn">
324
- <i class="fa-solid fa-pen-to-square text-xs"></i>
325
- </button>
326
- <button onclick='revokeToken({{ token.token|tojson }})'
327
- class="w-8 h-8 rounded-lg bg-surface flex items-center justify-center text-text-secondary hover:bg-red-500 hover:text-white transition-all token-action-btn">
328
- <i class="fa-solid fa-trash text-xs"></i>
329
- </button>
330
- </div>
331
- </td>
332
- </tr>
333
- {% endfor %}
334
-
335
- {% if not api_tokens %}
336
- <tr>
337
- <td colspan="5" class="py-10 px-8 text-center text-text-secondary">
338
- No tokens found.
339
- </td>
340
- </tr>
341
- {% endif %}
342
- </tbody>
343
- </table>
344
  </div>
345
-
346
- <div class="md:hidden divide-y divide-hairline">
347
- {% for token in api_tokens %}
348
- <div class="p-5 space-y-4" id="token-card-{{ loop.index0 }}">
349
- <div class="flex items-start justify-between gap-3">
350
- <div class="min-w-0">
351
- <p class="font-bold text-text truncate">{{ token.name }}</p>
352
- <p class="text-[10px] text-text-secondary uppercase mt-1">
353
- {{ token.created_at.strftime('%Y-%m-%d') if token.created_at else 'Unknown date' }}
354
- </p>
355
- </div>
356
- <div class="flex gap-2 shrink-0">
357
- <button onclick='openEditModal({{ token.token|tojson }}, {{ token.limits.daily_limit_gb|default(0)|tojson }}, {{ token.limits.monthly_limit_gb|default(0)|tojson }})'
358
- class="w-9 h-9 rounded-lg bg-surface flex items-center justify-center text-text-secondary hover:bg-blue-500 hover:text-white transition-all">
359
- <i class="fa-solid fa-pen-to-square text-xs"></i>
360
- </button>
361
- <button onclick='revokeToken({{ token.token|tojson }})'
362
- class="w-9 h-9 rounded-lg bg-surface flex items-center justify-center text-text-secondary hover:bg-red-500 hover:text-white transition-all">
363
- <i class="fa-solid fa-trash text-xs"></i>
364
- </button>
365
- </div>
366
- </div>
367
-
368
- <div class="grid grid-cols-2 gap-3 pt-3 border-t border-hairline">
369
- <div>
370
- <p class="text-[10px] uppercase font-bold tracking-widest text-text-secondary mb-1">Daily</p>
371
- <p class="text-xs font-medium text-text">
372
- <span class="text-primary" data-bytes="{{ token.usage.daily.bytes|default(0) }}"></span>
373
- <span class="text-text-secondary"> / {{ token.limits.daily_limit_gb or '∞' }} GB</span>
374
- </p>
375
- </div>
376
- <div>
377
- <p class="text-[10px] uppercase font-bold tracking-widest text-text-secondary mb-1">Monthly</p>
378
- <p class="text-xs font-medium text-text">
379
- <span class="text-accent" data-bytes="{{ token.usage.monthly.bytes|default(0) }}"></span>
380
- <span class="text-text-secondary"> / {{ token.limits.monthly_limit_gb or '∞' }} GB</span>
381
- </p>
382
- </div>
383
- </div>
384
-
385
- <button onclick='copyUrl({{ ((request.base_url|string).replace("http:", "https:") ~ "stremio/" ~ token.token ~ "/manifest.json")|tojson }})'
386
- class="w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-background/50 rounded-xl border border-hairline text-[10px] font-bold text-text-secondary hover:text-primary hover:border-primary/30 transition-all">
387
- <i class="fa-solid fa-link text-[8px]"></i> COPY MANIFEST
388
- </button>
389
  </div>
390
- {% endfor %}
391
-
392
- {% if not api_tokens %}
393
- <div class="p-10 text-center text-text-secondary">
394
- No tokens found.
395
- </div>
396
- {% endif %}
397
  </div>
398
- </div>
399
- </section>
400
- </div>
401
-
402
- <div id="edit-modal" class="fixed inset-0 bg-background/80 backdrop-blur-md hidden flex items-center justify-center z-50 p-4">
403
- <div class="glass-panel rounded-[2rem] p-8 w-full max-w-md border border-hairline shadow-2xl">
404
- <h3 class="text-xl font-bold mb-2">Edit Limits</h3>
405
- <p class="text-sm text-text-secondary mb-6">Modify daily and monthly data quotas for this token.</p>
406
-
407
- <input type="hidden" id="edit-token-id">
408
- <div class="space-y-4">
409
- <div>
410
- <label class="text-[10px] font-bold uppercase text-text-secondary tracking-widest ml-1 mb-1 block">Daily Limit (GB)</label>
411
- <input type="number" id="edit-daily" step="0.1" min="0"
412
- class="w-full px-4 py-3 rounded-xl border border-hairline focus:border-primary outline-none text-text placeholder:text-text-secondary bg-[color-mix(in_srgb,var(--card)_88%,var(--bg)_12%)]">
413
- </div>
414
- <div>
415
- <label class="text-[10px] font-bold uppercase text-text-secondary tracking-widest ml-1 mb-1 block">Monthly Limit (GB)</label>
416
- <input type="number" id="edit-monthly" step="0.1" min="0"
417
- class="w-full px-4 py-3 rounded-xl border border-hairline focus:border-primary outline-none text-text placeholder:text-text-secondary bg-[color-mix(in_srgb,var(--card)_88%,var(--bg)_12%)]">
418
- </div>
419
- </div>
420
-
421
- <div class="mt-8 flex gap-3">
422
- <button onclick="closeEditModal()" class="flex-1 py-3 bg-surface hover:bg-surface-2 text-text rounded-xl font-bold transition-all">Cancel</button>
423
- <button onclick="saveTokenLimits()" class="flex-1 py-3 bg-primary text-background rounded-xl font-bold transition-all">Save Changes</button>
424
- </div>
425
  </div>
426
  </div>
427
 
428
-
429
  <style>
430
- .shadow-glow {
431
- filter: drop-shadow(0 0 8px color-mix(in srgb, var(--primary) 45%, transparent));
432
- }
433
-
434
- .stream-card {
435
- background: color-mix(in srgb, var(--card) 55%, transparent);
436
- border: 1px solid var(--border);
437
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.16);
438
- }
439
-
440
- .stream-badge-live {
441
- background: color-mix(in srgb, var(--primary) 18%, transparent);
442
- color: var(--primary);
443
- }
444
-
445
- .stream-badge-recent {
446
- background: color-mix(in srgb, var(--accent) 16%, transparent);
447
- color: var(--accent);
448
- }
449
-
450
- input[type="text"],
451
- input[type="number"],
452
- input[type="email"],
453
- input[type="password"],
454
- input[type="search"],
455
- input[type="url"],
456
- textarea,
457
- select {
458
- color: var(--text) !important;
459
- border-color: var(--border) !important;
460
- caret-color: var(--primary);
461
- background: color-mix(in srgb, var(--card) 88%, var(--bg) 12%);
462
- }
463
-
464
- input[type="text"]::placeholder,
465
- input[type="number"]::placeholder,
466
- input[type="email"]::placeholder,
467
- input[type="password"]::placeholder,
468
- input[type="search"]::placeholder,
469
- input[type="url"]::placeholder,
470
- textarea::placeholder {
471
- color: var(--text-sec);
472
- opacity: 0.95;
473
- }
474
-
475
- input:focus,
476
- textarea:focus,
477
- select:focus {
478
- outline: none;
479
- border-color: var(--primary) !important;
480
- box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 18%, transparent);
481
- }
482
-
483
- input:-webkit-autofill,
484
- input:-webkit-autofill:hover,
485
- input:-webkit-autofill:focus {
486
- -webkit-text-fill-color: var(--text) !important;
487
- box-shadow: 0 0 0px 1000px color-mix(in srgb, var(--card) 88%, var(--bg) 12%) inset !important;
488
- transition: background-color 9999s ease-in-out 0s;
489
- }
490
-
491
-
492
  </style>
493
 
494
  <script>
495
- const streamState = {
496
- currentEditToken: null,
497
- activeStreams: []
498
- };
499
-
500
- function toggleCreateForm() {
501
- const formContainer = document.getElementById('create-form-container');
502
- const btnContainer = document.getElementById('create-btn-container');
503
- if (!formContainer || !btnContainer) return;
504
-
505
- if (formContainer.classList.contains('hidden')) {
506
- formContainer.classList.remove('hidden');
507
- btnContainer.classList.add('hidden');
508
- } else {
509
- formContainer.classList.add('hidden');
510
- btnContainer.classList.remove('hidden');
511
- }
512
- }
513
-
514
- function openEditModal(token, daily, monthly) {
515
- const tokenStr = String(token || '');
516
- streamState.currentEditToken = tokenStr;
517
- document.getElementById('edit-token-id').value = tokenStr;
518
- document.getElementById('edit-daily').value = (daily === null || daily === undefined) ? 0 : daily;
519
- document.getElementById('edit-monthly').value = (monthly === null || monthly === undefined) ? 0 : monthly;
520
- const modal = document.getElementById('edit-modal');
521
- modal.classList.remove('hidden');
522
- }
523
-
524
- function closeEditModal() {
525
- document.getElementById('edit-modal').classList.add('hidden');
526
- streamState.currentEditToken = null;
527
- }
528
-
529
- async function saveTokenLimits() {
530
- if (!streamState.currentEditToken) return;
531
-
532
- const daily = Number(document.getElementById('edit-daily').value || 0);
533
- const monthly = Number(document.getElementById('edit-monthly').value || 0);
534
-
535
- try {
536
- const response = await fetch('/api/tokens/' + encodeURIComponent(streamState.currentEditToken), {
537
- method: 'PUT',
538
- headers: { 'Content-Type': 'application/json' },
539
- body: JSON.stringify({
540
- daily_limit_gb: daily,
541
- monthly_limit_gb: monthly
542
- })
543
- });
544
-
545
- if (response.ok) {
546
- closeEditModal();
547
- showToast('Token limits updated successfully.', 'success', 'Updated');
548
- setTimeout(() => window.location.reload(), 500);
549
- return;
550
- }
551
-
552
- let message = 'Failed to update limits';
553
- try {
554
- const data = await response.json();
555
- message = data.detail || data.message || message;
556
- } catch (_) {}
557
- showToast(message, 'error', 'Update failed');
558
- } catch (error) {
559
- console.error(error);
560
- showToast('Error updating limits', 'error', 'Update failed');
561
- }
562
- }
563
-
564
- async function createToken(event) {
565
- event.preventDefault();
566
-
567
- const nameInput = document.getElementById('token-name');
568
- const dailyInput = document.getElementById('daily-limit');
569
- const monthlyInput = document.getElementById('monthly-limit');
570
-
571
- const payload = {
572
- name: nameInput.value.trim(),
573
- daily_limit_gb: Number(dailyInput.value || 0),
574
- monthly_limit_gb: Number(monthlyInput.value || 0)
575
- };
576
-
577
- if (!payload.name) {
578
- showToast('Token alias is required.', 'error', 'Validation');
579
- return;
580
- }
581
-
582
- try {
583
- const response = await fetch('/api/tokens', {
584
- method: 'POST',
585
- headers: { 'Content-Type': 'application/json' },
586
- body: JSON.stringify(payload)
587
- });
588
-
589
- if (response.ok) {
590
- showToast('Token created successfully.', 'success', 'Created');
591
- setTimeout(() => window.location.reload(), 500);
592
- return;
593
- }
594
-
595
- let message = 'Error creating token';
596
- try {
597
- const data = await response.json();
598
- message = data.detail || data.message || message;
599
- } catch (_) {}
600
- showToast(message, 'error', 'Create failed');
601
- } catch (error) {
602
- console.error(error);
603
- showToast('Error creating token', 'error', 'Create failed');
604
- }
605
- }
606
-
607
- async function revokeToken(token) {
608
- if (!confirm('Are you sure you want to revoke this token? The user will lose access immediately.')) return;
609
-
610
- try {
611
- const response = await fetch('/api/tokens/' + encodeURIComponent(String(token || '')), {
612
- method: 'DELETE'
613
- });
614
-
615
- if (response.ok) {
616
- showToast('Token deleted successfully.', 'success', 'Deleted');
617
- setTimeout(() => window.location.reload(), 500);
618
- return;
619
- }
620
-
621
- let message = 'Error deleting token';
622
- try {
623
- const data = await response.json();
624
- message = data.detail || data.message || message;
625
- } catch (_) {}
626
- showToast(message, 'error', 'Delete failed');
627
- } catch (error) {
628
- console.error(error);
629
- showToast('Error deleting token', 'error', 'Delete failed');
630
- }
631
- }
632
-
633
- async function copyUrl(url) {
634
- const text = String(url || '');
635
- try {
636
- if (navigator.clipboard && window.isSecureContext) {
637
- await navigator.clipboard.writeText(text);
638
- } else {
639
- const temp = document.createElement('textarea');
640
- temp.value = text;
641
- temp.setAttribute('readonly', '');
642
- temp.style.position = 'fixed';
643
- temp.style.left = '-9999px';
644
- temp.style.top = '0';
645
- document.body.appendChild(temp);
646
- temp.focus();
647
- temp.select();
648
- const ok = document.execCommand('copy');
649
- document.body.removeChild(temp);
650
- if (!ok) throw new Error('copy failed');
651
- }
652
- showToast('Manifest URL copied to clipboard.', 'success', 'Copied');
653
- } catch (error) {
654
- console.error(error);
655
- showToast('Failed to copy manifest URL.', 'error', 'Copy failed');
656
- }
657
- }
658
 
659
  function escapeHtml(unsafe) {
660
  if (unsafe === null || unsafe === undefined) return '';
@@ -675,19 +244,12 @@
675
  }
676
 
677
  function formatDuration(seconds) {
678
- const value = Math.max(0, Number(seconds || 0));
679
- const total = Math.floor(value);
680
-
681
  const h = Math.floor(total / 3600);
682
  const m = Math.floor((total % 3600) / 60);
683
  const s = total % 60;
684
-
685
- if (h > 0) {
686
- return `${h}h ${m}m ${s}s`;
687
- }
688
- if (m > 0) {
689
- return `${m}m ${s}s`;
690
- }
691
  return `${s}s`;
692
  }
693
 
@@ -695,12 +257,18 @@
695
  const value = Number(ts || 0);
696
  if (!value) return '—';
697
  const date = new Date(value * 1000);
698
- if (Number.isNaN(date.getTime())) return '—';
699
- return date.toLocaleString();
700
  }
701
 
702
  function getStreamTitle(stream) {
703
- return stream?.title || stream?.meta?.title || 'Unknown Stream';
 
 
 
 
 
 
 
704
  }
705
 
706
  function getClientLabel(stream) {
@@ -715,105 +283,82 @@
715
  }
716
 
717
  function getStatusBadge(status) {
718
- const normalized = String(status || '').toLowerCase();
719
-
720
- if (normalized === 'active') {
721
- return { className: 'stream-badge-live', text: 'Live' };
722
- }
723
- if (normalized === 'cancelled') {
724
- return { className: 'bg-yellow-500/15 text-yellow-300', text: 'Cancelled' };
725
- }
726
- if (normalized === 'completed' || normalized === 'finished') {
727
- return { className: 'bg-green-500/15 text-green-300', text: 'Completed' };
728
- }
729
- if (normalized === 'failed' || normalized === 'error') {
730
- return { className: 'bg-red-500/15 text-red-300', text: normalized.charAt(0).toUpperCase() + normalized.slice(1) };
731
- }
732
-
733
- return {
734
- className: 'stream-badge-recent',
735
- text: normalized ? normalized.charAt(0).toUpperCase() + normalized.slice(1) : 'Live'
736
- };
737
  }
738
 
739
  function getLiveDuration(stream) {
740
  const startTs = Number(stream?.start_ts || 0);
741
  if (!startTs) return '0s';
742
- const now = Date.now() / 1000;
743
- return formatDuration(now - startTs);
744
  }
745
 
746
  function renderStreamCard(stream) {
747
  const status = getStatusBadge(stream?.status);
748
  const title = escapeHtml(getStreamTitle(stream));
749
- const streamId = escapeHtml(stream?.stream_id ? String(stream.stream_id).slice(0, 12) + '…' : 'Unknown');
750
  const label = escapeHtml(getClientLabel(stream));
751
- const totalBytes = formatBytes(stream?.total_bytes || 0);
752
- const avgSpeed = stream?.avg_mbps !== null && stream?.avg_mbps !== undefined
753
- ? Number(stream.avg_mbps).toFixed(3) + ' MB/s'
754
- : '—';
755
- const started = formatTimestamp(stream?.start_ts);
756
- const liveDuration = getLiveDuration(stream);
757
-
758
  return `
759
- <div class="stream-card rounded-[2rem] p-5">
760
- <div class="flex justify-between items-start gap-3">
761
- <div class="min-w-0 pr-2">
762
- <h5 class="font-bold text-sm text-text truncate">${title}</h5>
763
- <div class="mt-1 flex flex-wrap items-center gap-2 text-[10px] uppercase tracking-widest text-text-secondary">
764
- <span>${label}</span>
765
- <span>•</span>
766
- <span>${streamId}</span>
767
- </div>
768
  </div>
769
- <span class="text-[10px] font-bold px-2 py-1 rounded-lg uppercase whitespace-nowrap ${status.className}">
770
- ${escapeHtml(status.text)}
771
- </span>
772
  </div>
773
-
774
- <div class="grid grid-cols-2 gap-3 mt-4 pt-4 border-t border-hairline">
775
- <div class="text-center">
776
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Speed</p>
777
- <p class="text-xs font-bold text-text">${avgSpeed}</p>
778
- </div>
779
- <div class="text-center">
780
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Total</p>
781
- <p class="text-xs font-bold text-text">${escapeHtml(totalBytes)}</p>
782
- </div>
783
- <div class="text-center">
784
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Duration</p>
785
- <p class="text-xs font-bold text-text live-duration">${escapeHtml(liveDuration)}</p>
786
- </div>
787
- <div class="text-center">
788
- <p class="text-[9px] text-text-secondary uppercase tracking-widest font-bold">Started</p>
789
- <p class="text-xs font-bold text-text truncate live-started">${escapeHtml(started)}</p>
790
- </div>
791
- </div>
792
-
793
- <div class="mt-4 pt-4 border-t border-hairline space-y-2">
794
- <div class="flex items-center justify-between text-xs gap-3">
795
- <span class="text-text-secondary">Stream ID</span>
796
- <span class="font-mono text-text text-right truncate max-w-[65%]">${streamId}</span>
797
- </div>
798
- <div class="flex items-center justify-between text-xs gap-3">
799
- <span class="text-text-secondary">Status</span>
800
- <span class="text-text text-right truncate max-w-[65%]">${escapeHtml(stream?.status || 'active')}</span>
801
- </div>
802
  </div>
 
803
  </div>
804
  `;
805
  }
806
 
807
  function renderEmptyState(icon, title, subtitle) {
808
  return `
809
- <div class="glass-panel p-8 rounded-[2rem] text-center border-dashed border-hairline">
810
- <i class="${icon} text-4xl text-muted mb-3"></i>
811
- <p class="text-sm text-text-secondary font-medium">${escapeHtml(title)}</p>
812
  <p class="text-xs text-text-secondary mt-1">${escapeHtml(subtitle)}</p>
813
  </div>
814
  `;
815
  }
816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
817
  async function loadStreamStats() {
818
  const activeContainer = document.getElementById('active-streams-container');
819
  const liveCount = document.getElementById('live-stream-count');
@@ -830,45 +375,34 @@
830
 
831
  streamState.activeStreams = activeStreams;
832
 
833
- if (liveCount) liveCount.textContent = activeStreams.length + ' Active';
834
  if (liveNowCount) liveNowCount.textContent = String(activeStreams.length);
835
  if (recentCount) recentCount.textContent = String(recentStreams.length);
836
 
837
  if (activeContainer) {
838
  activeContainer.innerHTML = activeStreams.length
839
  ? activeStreams.map(stream => renderStreamCard(stream)).join('')
840
- : renderEmptyState(
841
- 'fa-solid fa-satellite-dish',
842
- 'No active streams right now',
843
- 'The live network is idle at the moment.'
844
- );
845
  }
846
  } catch (error) {
847
  console.error(error);
848
  if (activeContainer) {
849
- activeContainer.innerHTML = renderEmptyState(
850
- 'fa-solid fa-triangle-exclamation',
851
- 'Unable to load live network',
852
- 'Please try refreshing the page.'
853
- );
854
  }
855
  }
856
  }
857
 
858
  function refreshLiveDurations() {
859
- const cards = document.querySelectorAll('#active-streams-container .stream-card');
860
- cards.forEach((card, index) => {
861
  const durationEl = card.querySelector('.live-duration');
862
  const stream = streamState.activeStreams[index];
863
- if (durationEl && stream) {
864
- durationEl.textContent = getLiveDuration(stream);
865
- }
866
  });
867
  }
868
 
869
  async function refreshDashboard() {
870
  const icon = document.getElementById('refresh-icon');
871
- if (icon) icon.classList.add('animate-spin');
872
 
873
  try {
874
  const response = await fetch('/api/system/stats', { cache: 'no-store' });
@@ -879,71 +413,13 @@
879
  if (elUptime) elUptime.innerText = stats.uptime || 'N/A';
880
 
881
  const elBotCount = document.getElementById('sys-bots-count');
882
- if (elBotCount) elBotCount.innerText = (stats.connected_bots ?? 0) + ' Nodes';
883
 
884
  const elLive = document.getElementById('sys-live-streams');
885
- if (elLive) elLive.innerText = (stats.total_active_streams ?? 0) + ' Active';
886
 
887
  const elVersion = document.getElementById('sys-version');
888
  if (elVersion) elVersion.innerText = 'v' + (stats.version || '1.0.0');
889
-
890
- if (stats.databases && Array.isArray(stats.databases)) {
891
- stats.databases.forEach((db, index) => {
892
- const elMovies = document.getElementById(`db-movies-${index}`);
893
- if (elMovies) elMovies.innerText = db.movie_count.toLocaleString();
894
-
895
- const elTv = document.getElementById(`db-tv-${index}`);
896
- if (elTv) elTv.innerText = db.tv_count.toLocaleString();
897
-
898
- const elStorage = document.getElementById(`db-storage-${index}`);
899
- if (elStorage) {
900
- const mb = db.storageSize / (1024 * 1024);
901
- elStorage.innerText = mb.toFixed(1) + ' MB';
902
- }
903
- });
904
- }
905
-
906
- if (stats.api_tokens && Array.isArray(stats.api_tokens)) {
907
- const rows = document.querySelectorAll('tbody tr');
908
- stats.api_tokens.forEach((token, index) => {
909
- const dailyBytes = (token.usage && token.usage.daily) ? (token.usage.daily.bytes || 0) : null;
910
- const monthlyBytes = (token.usage && token.usage.monthly) ? (token.usage.monthly.bytes || 0) : null;
911
-
912
- if (rows.length > index && !rows[index].querySelector('[colspan]')) {
913
- const row = rows[index];
914
-
915
- const dailyUsageSpan = row.querySelector('td:nth-child(2) span[data-bytes]');
916
- const monthlyUsageSpan = row.querySelectorAll('td:nth-child(2) span[data-bytes]')[1];
917
-
918
- if (dailyUsageSpan && dailyBytes !== null) {
919
- dailyUsageSpan.setAttribute('data-bytes', dailyBytes);
920
- dailyUsageSpan.textContent = formatBytes(dailyBytes);
921
- }
922
-
923
- if (monthlyUsageSpan && monthlyBytes !== null) {
924
- monthlyUsageSpan.setAttribute('data-bytes', monthlyBytes);
925
- monthlyUsageSpan.textContent = formatBytes(monthlyBytes);
926
- }
927
- }
928
-
929
- // Keep the mobile card view in sync as well
930
- const card = document.getElementById(`token-card-${index}`);
931
- if (card) {
932
- const cardDaily = card.querySelector('span.text-primary[data-bytes]');
933
- const cardMonthly = card.querySelector('span.text-accent[data-bytes]');
934
-
935
- if (cardDaily && dailyBytes !== null) {
936
- cardDaily.setAttribute('data-bytes', dailyBytes);
937
- cardDaily.textContent = formatBytes(dailyBytes);
938
- }
939
-
940
- if (cardMonthly && monthlyBytes !== null) {
941
- cardMonthly.setAttribute('data-bytes', monthlyBytes);
942
- cardMonthly.textContent = formatBytes(monthlyBytes);
943
- }
944
- }
945
- });
946
- }
947
  }
948
 
949
  await loadStreamStats();
@@ -951,24 +427,58 @@
951
  console.error('Failed to refresh dashboard:', error);
952
  showToast('Dashboard refresh failed.', 'error', 'Refresh failed');
953
  } finally {
954
- setTimeout(() => {
955
- if (icon) icon.classList.remove('animate-spin');
956
- }, 450);
957
  }
958
  }
959
 
960
- function formatInitialBytes() {
961
- document.querySelectorAll('[data-bytes]').forEach(el => {
962
- const raw = el.getAttribute('data-bytes');
963
- el.textContent = formatBytes(raw);
964
- });
965
- }
966
-
967
  document.addEventListener('DOMContentLoaded', () => {
968
- formatInitialBytes();
969
  loadStreamStats();
 
 
970
  setInterval(loadStreamStats, 30000);
971
  setInterval(refreshLiveDurations, 1000);
972
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
973
  </script>
974
  {% endblock %}
 
3
  {% block title %}Dashboard - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
+ <div class="space-y-8">
7
+ <header class="flex flex-wrap items-end justify-between gap-4">
8
+ <div class="min-w-0">
9
+ <h1 class="text-[28px] sm:text-3xl font-semibold leading-tight">Overview</h1>
10
+ <p class="text-text-secondary text-sm mt-1">Your Telegram channels as a Stremio addon</p>
 
 
 
 
 
 
 
 
 
 
11
  </div>
12
+ <button onclick="refreshDashboard()" class="btn-ghost px-4 py-2 text-sm">
13
+ <i id="refresh-icon" class="fa-solid fa-arrows-rotate"></i> Refresh
14
+ </button>
15
  </header>
16
 
17
+ <div id="setup-card" class="empty:hidden"></div>
 
 
 
 
 
 
 
 
 
18
 
19
+ <section>
20
+ <h2 class="label-caps mb-2.5 px-1">Server</h2>
21
+ <div class="glass-panel p-5">
22
+ <div class="flex items-center gap-3 pb-4 mb-4 border-b border-border">
23
+ <span class="w-2 h-2 rounded-full {{ 'bg-ok' if system_stats.server_status == 'running' else 'bg-danger' }} shrink-0"></span>
24
+ <div class="min-w-0">
25
+ <p class="font-medium leading-tight">{{ 'Addon server running' if system_stats.server_status == 'running' else 'Server needs attention' }}</p>
26
+ <p class="text-sm text-text-secondary truncate">{{ system_stats.telegram_bot }} · {{ system_stats.total_databases }} database{{ '' if system_stats.total_databases == 1 else 's' }}</p>
27
+ </div>
28
  </div>
29
+ <div class="grid grid-cols-2 sm:grid-cols-4 gap-y-4 gap-x-6">
30
+ <div class="min-w-0"><p id="sys-uptime" class="text-xl font-semibold tabular truncate">{{ system_stats.uptime or 'N/A' }}</p><p class="text-sm text-text-secondary">Uptime</p></div>
31
+ <div class="min-w-0"><p class="text-xl font-semibold tabular"><span id="sys-bots-count">{{ system_stats.connected_bots|default(0) }}</span></p><p class="text-sm text-text-secondary">Bots</p></div>
32
+ <div class="min-w-0"><p class="text-xl font-semibold tabular"><span id="sys-live-streams">{{ system_stats.total_active_streams }}</span></p><p class="text-sm text-text-secondary">Live streams</p></div>
33
+ <div class="min-w-0"><p id="sys-version" class="text-xl font-semibold tabular truncate">v{{ system_stats.version }}</p><p class="text-sm text-text-secondary">Version</p></div>
34
  </div>
35
  </div>
36
+ </section>
37
 
38
+ <section>
39
+ <h2 class="label-caps mb-2.5 px-1">Library</h2>
40
+ <div class="glass-panel p-5">
41
+ <div class="grid grid-cols-2 sm:grid-cols-4 gap-y-4 gap-x-6">
42
+ <div><p class="text-xl font-semibold tabular">{{ system_stats.movies }}</p><p class="text-sm text-text-secondary">Movies</p></div>
43
+ <div><p class="text-xl font-semibold tabular">{{ system_stats.tv_shows }}</p><p class="text-sm text-text-secondary">Series</p></div>
44
+ <div><p class="text-xl font-semibold tabular">{{ system_stats.total_databases }}</p><p class="text-sm text-text-secondary">Storage nodes</p></div>
45
+ <div><p class="text-xl font-semibold tabular">{{ "%.1f"|format((system_stats.databases|sum(attribute='storageSize')) / 1048576) }} MB</p><p class="text-sm text-text-secondary">Index size</p></div>
46
  </div>
47
+ {% if system_stats.databases %}
48
+ <div class="mt-4 pt-4 border-t border-border space-y-3">
49
+ {% for db_stat in system_stats.databases %}
50
+ {% set pct = [(db_stat.storageSize / (500 * 1024 * 1024) * 100) | round(1), 100] | min %}
51
+ <div class="flex items-center gap-4 text-sm">
52
+ <span class="w-16 shrink-0 font-medium">{{ db_stat.db_name.replace("storage_", "Node ") }}</span>
53
+ <span class="flex-1 h-1.5 rounded-full bg-card-high overflow-hidden"><span class="block h-full rounded-full bg-primary" style="width: {{ [pct, 1]|max }}%"></span></span>
54
+ <span class="shrink-0 text-text-secondary tabular">{{ db_stat.movie_count }} / {{ db_stat.tv_count }}</span>
55
+ </div>
56
+ {% endfor %}
57
  </div>
58
+ {% endif %}
59
  </div>
60
+ </section>
61
 
62
+ <section id="recent-wrap" hidden>
63
+ <div class="flex items-center justify-between mb-2.5 px-1">
64
+ <h2 class="label-caps">Recently added</h2>
65
+ <a href="/media/manage" class="text-sm text-primary hover:underline underline-offset-4">View all</a>
 
 
 
 
66
  </div>
67
+ <div id="recent-row" class="poster-row"></div>
68
+ </section>
69
 
70
+ <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
71
+ <div class="lg:col-span-3 space-y-8 min-w-0">
72
  <section>
73
+ <h2 class="label-caps mb-2.5 px-1">Shortcuts</h2>
74
+ <div class="glass-panel overflow-hidden divide-y divide-border">
75
+ <a href="/media/manage?media_type=movie" class="list-row"><i class="fa-solid fa-film"></i><span><b>Movies</b><small>Organize and edit the library</small></span><i class="fa-solid fa-chevron-right chev"></i></a>
76
+ <a href="/media/manage?media_type=tv" class="list-row"><i class="fa-solid fa-tv"></i><span><b>TV shows</b><small>Seasons, episodes and files</small></span><i class="fa-solid fa-chevron-right chev"></i></a>
77
+ <a href="/admin/access" class="list-row"><i class="fa-solid fa-key"></i><span><b>Tokens and access</b><small>Create tokens, set data limits and plans</small></span><i class="fa-solid fa-chevron-right chev"></i></a>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  </div>
79
  </section>
80
 
81
+ <section>
82
+ <div class="flex items-center justify-between gap-3 mb-2.5 px-1">
83
+ <h2 class="label-caps">Viewers <span id="ua-online" class="ml-2 normal-case tracking-normal text-primary">0 online</span></h2>
84
+ <button onclick="loadUserActivity()" class="text-sm text-text-secondary hover:text-text transition"><i class="fa-solid fa-rotate mr-1"></i>Refresh</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  </div>
86
+ <script>
87
+ function uaEsc(s) { return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
88
+ function uaFlag(cc) { if (!cc || cc.length !== 2) return ''; return String.fromCodePoint(...[...cc.toUpperCase()].map(c => 127397 + c.charCodeAt(0))); }
89
+ function uaAgo(iso) {
90
+ if (!iso) return '—';
91
+ const t = new Date(iso.endsWith('Z') ? iso : iso + 'Z').getTime();
92
+ const d = (Date.now() - t) / 1000;
93
+ if (d < 60) return 'just now';
94
+ if (d < 3600) return Math.floor(d / 60) + 'm ago';
95
+ if (d < 86400) return Math.floor(d / 3600) + 'h ago';
96
+ return Math.floor(d / 86400) + 'd ago';
97
+ }
98
+ let uaPage = 1;
99
+ const uaPerPage = 5;
100
+ window.__UA_INITIAL__ = {{ user_activity_initial | tojson }};
101
+ function renderUaPagination(data) {
102
+ const el = document.getElementById('ua-pagination');
103
+ if (!el) return;
104
+ const pages = data.total_pages || 1, cur = data.page || 1;
105
+ if (pages <= 1) { el.innerHTML = ''; return; }
106
+ el.innerHTML = `
107
+ <button onclick="loadUserActivity(${cur - 1})" ${cur <= 1 ? 'disabled' : ''} class="icon-btn border border-border disabled:opacity-40" aria-label="Previous page"><i class="fa-solid fa-chevron-left text-xs"></i></button>
108
+ <span class="text-sm text-text-secondary">Page ${cur} of ${pages} · ${data.total} users</span>
109
+ <button onclick="loadUserActivity(${cur + 1})" ${cur >= pages ? 'disabled' : ''} class="icon-btn border border-border disabled:opacity-40" aria-label="Next page"><i class="fa-solid fa-chevron-right text-xs"></i></button>`;
110
+ }
111
+ function renderUserActivity(data) {
112
+ const box = document.getElementById('ua-list');
113
+ const users = data.users || [];
114
+ document.getElementById('ua-online').textContent = (data.online_count || 0) + ' online';
115
+ if (!users.length) { box.innerHTML = '<div class="glass-panel sm:col-span-2 p-6 text-center text-sm text-text-secondary">No viewers yet. Activity shows up here once someone streams.</div>'; renderUaPagination(data); return; }
116
+ box.innerHTML = users.map(u => {
117
+ const loc = [u.country, u.city].filter(Boolean).join(': ') || 'Unknown';
118
+ const nowLine = u.now_playing
119
+ ? `<div class="ua-now"><i class="fa-solid fa-play text-[10px] mr-1"></i>${uaEsc(u.now_playing)}</div>`
120
+ : `<div class="text-text-secondary text-[13px] mt-2 truncate">${uaEsc(u.last_title || 'No history')}</div>`;
121
+ const fl = uaFlag(u.country_code);
122
+ return `<div class="ua-card glass-panel">
123
+ <div class="flex items-center justify-between gap-2 min-w-0">
124
+ <div class="flex items-center gap-2 min-w-0">
125
+ <span class="ua-dot ${u.online ? 'on' : ''}"></span>
126
+ <span class="font-medium truncate">${uaEsc(u.name)}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  </div>
128
+ <span class="ua-tag ${u.proxy ? 'vpn' : ''}">${u.proxy ? 'VPN' : 'Direct'}</span>
129
+ </div>
130
+ ${nowLine}
131
+ <div class="ua-meta">
132
+ <span><i class="fa-solid fa-signal"></i> <span>${u.online ? 'Online' : uaAgo(u.last_active)}</span></span>
133
+ <span><i class="fa-solid fa-location-dot"></i> <span>${fl ? fl + ' ' : ''}${uaEsc(loc)}</span></span>
134
+ <span><i class="fa-solid fa-network-wired"></i> <span>${uaEsc(u.isp || '—')}</span></span>
135
+ <span><i class="fa-solid fa-mobile-screen-button"></i> <span>${uaEsc(u.app)}${u.device ? ' · ' + uaEsc(u.device) : ''}</span></span>
136
+ <span><i class="fa-solid fa-globe"></i> <span>${uaEsc(u.ip || '—')}</span></span>
137
+ <span><i class="fa-solid fa-film"></i> <span>${u.streams} streams</span></span>
138
+ </div>
139
+ </div>`;
140
+ }).join('');
141
+ renderUaPagination(data);
142
+ }
143
+ function uaSkeleton() { return '<div class="ua-skel"></div>'; }
144
+ async function loadUserActivity(page, silent) {
145
+ if (page) uaPage = page;
146
+ const box = document.getElementById('ua-list');
147
+ if (!box) return;
148
+ if (!silent) box.innerHTML = uaSkeleton();
149
+ try {
150
+ const res = await fetch(`/api/admin/user-activity?page=${uaPage}&per_page=${uaPerPage}`);
151
+ renderUserActivity(await res.json());
152
+ } catch (e) {
153
+ box.innerHTML = '<p class="text-text-secondary text-sm">Unable to load user activity.</p>';
154
+ }
155
+ }
156
+ function uaInit() {
157
+ if (window.__UA_INITIAL__ && (window.__UA_INITIAL__.users || []).length) renderUserActivity(window.__UA_INITIAL__);
158
+ else loadUserActivity();
159
+ setInterval(() => loadUserActivity(null, true), 15000);
160
+ }
161
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', uaInit); else uaInit();
162
+ </script>
163
+ <div id="ua-list" class="grid grid-cols-1 sm:grid-cols-2 gap-3">
164
+ <div class="ua-skel"></div>
165
  </div>
166
+ <div id="ua-pagination" class="flex items-center justify-center flex-wrap gap-3 mt-4"></div>
167
+ </section>
168
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
+ <section class="lg:col-span-2 min-w-0">
171
+ <div class="flex items-center justify-between gap-3 mb-2.5 px-1">
172
+ <h2 class="label-caps">Live network</h2>
173
+ <span id="live-stream-count" class="text-sm text-text-secondary">{{ system_stats.total_active_streams or 0 }} active</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  </div>
175
+ <div class="glass-panel p-5">
176
+ <div class="grid grid-cols-2 gap-6 pb-4 mb-4 border-b border-border">
177
+ <div><p id="live-now-count" class="text-xl font-semibold tabular">{{ system_stats.total_active_streams or 0 }}</p><p class="text-sm text-text-secondary">Live now</p></div>
178
+ <div><p id="recent-stream-count" class="text-xl font-semibold tabular">0</p><p class="text-sm text-text-secondary">Recent</p></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  </div>
180
+ <div id="active-streams-container" class="space-y-3"></div>
 
 
 
 
 
 
181
  </div>
182
+ </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  </div>
184
  </div>
185
 
 
186
  <style>
187
+ .poster-row { display: grid; grid-auto-flow: column; grid-auto-columns: 132px; gap: 12px; overflow-x: auto; overscroll-behavior-x: contain; scroll-snap-type: x proximity; padding-bottom: 6px; scrollbar-width: none; }
188
+ .poster-row::-webkit-scrollbar { display: none; }
189
+ @media (min-width: 640px) { .poster-row { grid-auto-columns: 148px; } }
190
+ .poster { scroll-snap-align: start; min-width: 0; color: var(--text); text-decoration: none; }
191
+ .poster-img { position: relative; aspect-ratio: 2 / 3; border-radius: 14px; overflow: hidden; background: var(--card-high); }
192
+ .poster-img img { width: 100%; height: 100%; object-fit: cover; transition: transform .35s var(--ease); }
193
+ .poster:hover .poster-img img { transform: scale(1.04); }
194
+ .poster-rating { position: absolute; top: 6px; right: 6px; padding: 2px 7px; border-radius: 99px; font-size: .72rem; color: #fff; background: rgba(0,0,0,.72); }
195
+ .poster-title { margin-top: .5rem; font-size: .88rem; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
196
+ .poster-sub { font-size: .78rem; color: var(--text-sec); }
197
+
198
+ .list-row { display: flex; align-items: center; gap: 1rem; padding: .95rem 1.1rem; color: var(--text); text-decoration: none; transition: background-color .15s var(--ease); }
199
+ .list-row:hover { background: var(--surface); }
200
+ .list-row > i:first-child { width: 1.25rem; text-align: center; color: var(--primary); }
201
+ .list-row > span { display: flex; flex-direction: column; min-width: 0; flex: 1; }
202
+ .list-row b { font-weight: 500; }
203
+ .list-row small { font-size: .82rem; color: var(--text-sec); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
204
+ .list-row .chev { font-size: .75rem; color: var(--text-sec); transition: transform .2s var(--ease); }
205
+ .list-row:hover .chev { transform: translateX(3px); }
206
+
207
+ .ua-card { min-width: 0; padding: 1rem; }
208
+ .ua-dot { width: .5rem; height: .5rem; border-radius: 99px; background: var(--border); flex-shrink: 0; }
209
+ .ua-dot.on { background: var(--ok); }
210
+ .ua-tag { font-size: .7rem; padding: .1rem .5rem; border-radius: 99px; white-space: nowrap; border: 1px solid var(--border); color: var(--text-sec); }
211
+ .ua-tag.vpn { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); }
212
+ .ua-skel { height: 132px; border-radius: var(--radius); border: 1px solid var(--border); background: linear-gradient(90deg, var(--card) 25%, var(--card-high) 37%, var(--card) 63%); background-size: 400% 100%; animation: ua-shimmer 1.4s ease infinite; }
213
+ @keyframes ua-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
214
+ .ua-now { margin-top: .5rem; font-size: .82rem; color: var(--ok); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
215
+ .ua-meta { margin-top: .75rem; display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: .35rem .75rem; font-size: .78rem; }
216
+ .ua-meta > span { display: flex; align-items: center; gap: .4rem; min-width: 0; color: var(--text-sec); }
217
+ .ua-meta > span i { width: .9rem; text-align: center; font-size: .7rem; }
218
+ .ua-meta > span span { color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
219
+
220
+ .stream-card { padding: 1rem; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); min-width: 0; }
221
+ .stream-badge-live { background: color-mix(in srgb, var(--ok) 16%, transparent); color: var(--ok); }
222
+ .stream-badge-recent { background: var(--card-high); color: var(--text-sec); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  </style>
224
 
225
  <script>
226
+ const streamState = { activeStreams: [] };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
  function escapeHtml(unsafe) {
229
  if (unsafe === null || unsafe === undefined) return '';
 
244
  }
245
 
246
  function formatDuration(seconds) {
247
+ const total = Math.floor(Math.max(0, Number(seconds || 0)));
 
 
248
  const h = Math.floor(total / 3600);
249
  const m = Math.floor((total % 3600) / 60);
250
  const s = total % 60;
251
+ if (h > 0) return `${h}h ${m}m ${s}s`;
252
+ if (m > 0) return `${m}m ${s}s`;
 
 
 
 
 
253
  return `${s}s`;
254
  }
255
 
 
257
  const value = Number(ts || 0);
258
  if (!value) return '—';
259
  const date = new Date(value * 1000);
260
+ return Number.isNaN(date.getTime()) ? '—' : date.toLocaleString();
 
261
  }
262
 
263
  function getStreamTitle(stream) {
264
+ return stream?.title || stream?.file_name || stream?.meta?.title || stream?.meta?.file_name || 'Unknown Stream';
265
+ }
266
+
267
+ function getStreamFileName(stream) {
268
+ const fn = stream?.file_name || stream?.meta?.file_name || '';
269
+ const title = stream?.title || stream?.meta?.title || '';
270
+ if (fn && title && fn !== title) return fn;
271
+ return '';
272
  }
273
 
274
  function getClientLabel(stream) {
 
283
  }
284
 
285
  function getStatusBadge(status) {
286
+ const n = String(status || '').toLowerCase();
287
+ if (n === 'active') return { className: 'stream-badge-live', text: 'Live' };
288
+ if (n === 'cancelled') return { className: 'bg-yellow-500/15 text-yellow-300', text: 'Cancelled' };
289
+ if (n === 'completed' || n === 'finished') return { className: 'bg-green-500/15 text-green-300', text: 'Completed' };
290
+ if (n === 'failed' || n === 'error') return { className: 'bg-red-500/15 text-red-300', text: n.charAt(0).toUpperCase() + n.slice(1) };
291
+ return { className: 'stream-badge-recent', text: n ? n.charAt(0).toUpperCase() + n.slice(1) : 'Live' };
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  }
293
 
294
  function getLiveDuration(stream) {
295
  const startTs = Number(stream?.start_ts || 0);
296
  if (!startTs) return '0s';
297
+ return formatDuration(Date.now() / 1000 - startTs);
 
298
  }
299
 
300
  function renderStreamCard(stream) {
301
  const status = getStatusBadge(stream?.status);
302
  const title = escapeHtml(getStreamTitle(stream));
303
+ const fileName = escapeHtml(getStreamFileName(stream));
304
  const label = escapeHtml(getClientLabel(stream));
305
+ const avgSpeed = stream?.avg_mbps != null ? Number(stream.avg_mbps).toFixed(2) + ' MB/s' : '—';
 
 
 
 
 
 
306
  return `
307
+ <div class="stream-card">
308
+ <div class="flex items-start justify-between gap-3 min-w-0">
309
+ <div class="min-w-0">
310
+ <p class="font-medium text-sm truncate" title="${title}">${title}</p>
311
+ ${fileName ? `<p class="text-xs text-text-secondary truncate" title="${fileName}">${fileName}</p>` : ''}
 
 
 
 
312
  </div>
313
+ <span class="text-[11px] px-2 py-0.5 rounded-full whitespace-nowrap shrink-0 ${status.className}">${escapeHtml(status.text)}</span>
 
 
314
  </div>
315
+ <div class="grid grid-cols-3 gap-2 mt-3 text-xs">
316
+ <div class="min-w-0"><p class="text-text-secondary">Speed</p><p class="font-medium tabular truncate">${avgSpeed}</p></div>
317
+ <div class="min-w-0"><p class="text-text-secondary">Sent</p><p class="font-medium tabular truncate">${escapeHtml(formatBytes(stream?.total_bytes || 0))}</p></div>
318
+ <div class="min-w-0"><p class="text-text-secondary">Time</p><p class="font-medium tabular truncate live-duration">${escapeHtml(getLiveDuration(stream))}</p></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  </div>
320
+ <p class="mt-3 pt-3 border-t border-border text-xs text-text-secondary truncate">${label} · <span class="font-mono">${escapeHtml(String(stream?.stream_id || '').slice(0, 12))}</span> · ${escapeHtml(formatTimestamp(stream?.start_ts))}</p>
321
  </div>
322
  `;
323
  }
324
 
325
  function renderEmptyState(icon, title, subtitle) {
326
  return `
327
+ <div class="py-8 text-center">
328
+ <span class="mx-auto mb-3 grid place-items-center w-11 h-11 rounded-full bg-card-high text-text-secondary"><i class="${icon}"></i></span>
329
+ <p class="text-sm font-medium">${escapeHtml(title)}</p>
330
  <p class="text-xs text-text-secondary mt-1">${escapeHtml(subtitle)}</p>
331
  </div>
332
  `;
333
  }
334
 
335
+ async function loadRecent() {
336
+ const wrap = document.getElementById('recent-wrap');
337
+ const row = document.getElementById('recent-row');
338
+ try {
339
+ const [m, t] = await Promise.all(['movie', 'tv'].map(type =>
340
+ fetch(`/api/media/list?media_type=${type}&page_size=12`).then(r => r.ok ? r.json() : {}).catch(() => ({}))));
341
+ const items = [...(m.movies || m.media || []), ...(t.tv_shows || t.media || [])]
342
+ .filter(x => x && x.title)
343
+ .sort((a, b) => String(b.updated_on || '').localeCompare(String(a.updated_on || '')))
344
+ .slice(0, 14);
345
+ if (!items.length) return;
346
+ row.innerHTML = items.map(x => {
347
+ const type = x.media_type === 'tv' ? 'tv' : 'movie';
348
+ const href = `/media/edit?tmdb_id=${encodeURIComponent(x.tmdb_id)}&db_index=${encodeURIComponent(x.db_index)}&media_type=${type}`;
349
+ return `<a class="poster" href="${href}">
350
+ <div class="poster-img">
351
+ ${x.poster ? `<img src="${escapeHtml(x.poster)}" alt="" loading="lazy" decoding="async" onerror="this.remove()">` : ''}
352
+ ${x.rating ? `<span class="poster-rating">★ ${Number(x.rating).toFixed(1)}</span>` : ''}
353
+ </div>
354
+ <p class="poster-title">${escapeHtml(x.title)}</p>
355
+ <p class="poster-sub">${escapeHtml(x.release_year || '')}${x.release_year ? ' · ' : ''}${type === 'tv' ? 'Series' : 'Movie'}</p>
356
+ </a>`;
357
+ }).join('');
358
+ wrap.hidden = false;
359
+ } catch (e) {}
360
+ }
361
+
362
  async function loadStreamStats() {
363
  const activeContainer = document.getElementById('active-streams-container');
364
  const liveCount = document.getElementById('live-stream-count');
 
375
 
376
  streamState.activeStreams = activeStreams;
377
 
378
+ if (liveCount) liveCount.textContent = activeStreams.length + ' active';
379
  if (liveNowCount) liveNowCount.textContent = String(activeStreams.length);
380
  if (recentCount) recentCount.textContent = String(recentStreams.length);
381
 
382
  if (activeContainer) {
383
  activeContainer.innerHTML = activeStreams.length
384
  ? activeStreams.map(stream => renderStreamCard(stream)).join('')
385
+ : renderEmptyState('fa-solid fa-satellite-dish', 'No active streams right now', 'The live network is idle at the moment.');
 
 
 
 
386
  }
387
  } catch (error) {
388
  console.error(error);
389
  if (activeContainer) {
390
+ activeContainer.innerHTML = renderEmptyState('fa-solid fa-triangle-exclamation', 'Unable to load live network', 'Please try refreshing the page.');
 
 
 
 
391
  }
392
  }
393
  }
394
 
395
  function refreshLiveDurations() {
396
+ document.querySelectorAll('#active-streams-container .stream-card').forEach((card, index) => {
 
397
  const durationEl = card.querySelector('.live-duration');
398
  const stream = streamState.activeStreams[index];
399
+ if (durationEl && stream) durationEl.textContent = getLiveDuration(stream);
 
 
400
  });
401
  }
402
 
403
  async function refreshDashboard() {
404
  const icon = document.getElementById('refresh-icon');
405
+ if (icon) icon.classList.add('fa-spin');
406
 
407
  try {
408
  const response = await fetch('/api/system/stats', { cache: 'no-store' });
 
413
  if (elUptime) elUptime.innerText = stats.uptime || 'N/A';
414
 
415
  const elBotCount = document.getElementById('sys-bots-count');
416
+ if (elBotCount) elBotCount.innerText = stats.connected_bots ?? 0;
417
 
418
  const elLive = document.getElementById('sys-live-streams');
419
+ if (elLive) elLive.innerText = stats.total_active_streams ?? 0;
420
 
421
  const elVersion = document.getElementById('sys-version');
422
  if (elVersion) elVersion.innerText = 'v' + (stats.version || '1.0.0');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  }
424
 
425
  await loadStreamStats();
 
427
  console.error('Failed to refresh dashboard:', error);
428
  showToast('Dashboard refresh failed.', 'error', 'Refresh failed');
429
  } finally {
430
+ setTimeout(() => { if (icon) icon.classList.remove('fa-spin'); }, 450);
 
 
431
  }
432
  }
433
 
 
 
 
 
 
 
 
434
  document.addEventListener('DOMContentLoaded', () => {
 
435
  loadStreamStats();
436
+ loadSetupStatus();
437
+ loadRecent();
438
  setInterval(loadStreamStats, 30000);
439
  setInterval(refreshLiveDurations, 1000);
440
  });
441
+
442
+ async function loadSetupStatus() {
443
+ const wrap = document.getElementById('setup-card');
444
+ if (!wrap) return;
445
+ try {
446
+ const res = await fetch('/api/admin/setup-status');
447
+ if (!res.ok) return;
448
+ const data = await res.json();
449
+ const d = data.data || {};
450
+ const checks = d.checks || [];
451
+ if (!checks.length || d.complete) { wrap.innerHTML = ''; return; }
452
+
453
+ const rows = checks.map(c => `
454
+ <a href="/admin/settings" class="flex items-start gap-3 p-3 rounded-[14px] transition-colors hover:bg-surface ${c.done ? 'opacity-55' : ''}">
455
+ <span class="mt-0.5 w-5 h-5 rounded-full grid place-items-center shrink-0 ${c.done ? 'bg-ok/15 text-ok' : 'border border-border text-text-secondary'}">
456
+ <i class="fa-solid ${c.done ? 'fa-check' : 'fa-arrow-right'} text-[10px]"></i>
457
+ </span>
458
+ <span class="min-w-0">
459
+ <span class="block text-sm font-medium ${c.done ? 'line-through text-text-secondary' : ''}">${escapeHtmlSetup(c.label)}</span>
460
+ <span class="block text-[13px] text-text-secondary mt-0.5">${escapeHtmlSetup(c.hint)}</span>
461
+ </span>
462
+ </a>`).join('');
463
+
464
+ const pct = Math.round((d.done / d.total) * 100);
465
+ wrap.innerHTML = `
466
+ <div class="glass-panel p-5">
467
+ <div class="flex items-center justify-between gap-4">
468
+ <div class="min-w-0">
469
+ <h2 class="font-medium">Finish setting up</h2>
470
+ <p class="text-sm text-text-secondary mt-0.5">${d.done} of ${d.total} steps done</p>
471
+ </div>
472
+ <span class="text-xl font-semibold text-primary tabular">${pct}%</span>
473
+ </div>
474
+ <div class="h-1.5 rounded-full bg-card-high overflow-hidden my-4"><div class="h-full rounded-full bg-primary transition-[width] duration-700" style="width:${pct}%"></div></div>
475
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-1 -mx-1">${rows}</div>
476
+ </div>`;
477
+ } catch (e) { /* ignore */ }
478
+ }
479
+
480
+ function escapeHtmlSetup(v) {
481
+ return String(v ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
482
+ }
483
  </script>
484
  {% endblock %}
Backend/fastapi/templates/login.html CHANGED
@@ -1,107 +1,62 @@
1
  {% extends "base.html" %}
2
 
3
- {% block title %}Login - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
- <div class="flex-1 flex items-center justify-center py-4 min-h-0">
7
-
8
- <div class="w-full max-w-md rounded-[2rem] overflow-hidden glass-panel self-center">
9
-
10
- <div class="p-6 sm:p-10 flex flex-col justify-center bg-card/20">
11
-
12
- <div class="flex items-center gap-3 justify-center mb-6">
13
- <div class="w-10 h-10 rounded-full bg-primary flex items-center justify-center shadow-[0_0_15px_var(--primary)]">
14
- <i class="fa-solid fa-play text-white text-sm"></i>
15
- </div>
16
- <span class="text-2xl font-extrabold tracking-wide text-transparent bg-clip-text bg-gradient-to-r from-primary to-accent">
17
- TG Stremio
18
- </span>
19
  </div>
 
20
 
21
- <div class="text-center mb-6">
22
- <h2 class="text-lg font-bold tracking-tight text-text">Admin Authentication</h2>
23
- <p class="text-text-secondary text-xs mt-1">Access your management console</p>
24
- </div>
25
 
26
  {% if error %}
27
- <div class="flex items-center gap-3 bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-2.5 rounded-xl mb-6 animate-pulse">
28
- <i class="fa-solid fa-circle-exclamation text-xs"></i>
29
- <p class="text-xs font-medium">{{ error }}</p>
30
  </div>
31
  {% endif %}
32
 
33
  <form method="post" class="space-y-4">
34
-
35
- <div class="space-y-1.5">
36
- <label class="text-[10px] font-bold uppercase tracking-widest text-text-secondary ml-1">Username</label>
37
- <div class="relative group">
38
- <i class="fa-solid fa-user absolute left-4 top-1/2 -translate-y-1/2 text-text-secondary group-focus-within:text-primary transition-colors text-sm"></i>
39
- <input type="text" name="username" required
40
- class="w-full pl-11 pr-4 py-3 bg-background/50 rounded-2xl border border-hairline focus:border-primary/50 focus:ring-4 focus:ring-primary/10 outline-none transition-all text-text text-sm"
41
- placeholder="Admin ID">
42
- </div>
43
- </div>
44
-
45
- <div class="space-y-1.5">
46
- <label class="text-[10px] font-bold uppercase tracking-widest text-text-secondary ml-1">Password</label>
47
- <div class="relative group">
48
- <i class="fa-solid fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-text-secondary group-focus-within:text-primary transition-colors text-sm"></i>
49
-
50
- <input type="password" id="password" name="password" required
51
- class="w-full pl-11 pr-11 py-3 bg-background/50 rounded-2xl border border-hairline focus:border-primary/50 focus:ring-4 focus:ring-primary/10 outline-none transition-all text-text text-sm"
52
- placeholder="••••••••">
53
-
54
- <button type="button" onclick="togglePassword()"
55
- class="absolute right-4 top-1/2 -translate-y-1/2 text-text-secondary hover:text-primary transition-colors">
56
- <i id="eyeIcon" class="fa-solid fa-eye text-xs"></i>
57
  </button>
58
- </div>
59
- </div>
60
-
61
- <button type="submit"
62
- class="w-full py-3.5 rounded-2xl bg-primary hover:brightness-110 text-background font-bold transition-all shadow-lg shadow-primary/20 flex items-center justify-center gap-3 mt-4">
63
- <i class="fa-solid fa-right-to-bracket text-sm"></i>
64
- Sign In
65
  </button>
66
-
67
  </form>
68
-
69
  </div>
70
  </div>
71
  </div>
72
 
73
- <style>
74
- /* Strictly disable scrolling on the login screen */
75
- html, body {
76
- height: 100%;
77
- overflow: hidden !important;
78
- }
79
-
80
- /* Ensure the 'main' block from base.html takes full height */
81
- main {
82
- display: flex;
83
- flex-direction: column;
84
- height: 100%;
85
- }
86
-
87
- input::placeholder {
88
- color: color-mix(in srgb, var(--text-sec) 40%, transparent);
89
- }
90
- </style>
91
-
92
  <script>
93
- function togglePassword() {
94
- const input = document.getElementById("password");
95
- const icon = document.getElementById("eyeIcon");
96
-
97
- if (input.type === "password") {
98
- input.type = "text";
99
- icon.classList.replace("fa-eye", "fa-eye-slash");
100
- } else {
101
- input.type = "password";
102
- icon.classList.replace("fa-eye-slash", "fa-eye");
103
- }
104
- }
105
  </script>
106
-
107
  {% endblock %}
 
1
  {% extends "base.html" %}
2
 
3
+ {% block title %}Sign in - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
+ <div class="min-h-[calc(100dvh-4rem)] grid place-items-center">
7
+ <div class="w-full max-w-sm">
8
+ <div class="flex items-center gap-3 mb-8">
9
+ <span class="grid place-items-center w-11 h-11 rounded-[14px] bg-primary text-on-primary"><i class="fa-solid fa-play text-sm"></i></span>
10
+ <div>
11
+ <p class="text-lg font-semibold leading-tight">TG Stremio</p>
12
+ <p class="text-sm text-text-secondary">Admin console</p>
 
 
 
 
 
 
13
  </div>
14
+ </div>
15
 
16
+ <div class="glass-panel p-6 sm:p-7">
17
+ <h1 class="text-xl font-semibold">Sign in</h1>
18
+ <p class="text-sm text-text-secondary mt-1 mb-6">Use the admin account set in Settings.</p>
 
19
 
20
  {% if error %}
21
+ <div class="flex items-center gap-2.5 text-sm text-danger bg-danger/10 border border-danger/25 px-3.5 py-2.5 rounded-[14px] mb-5" role="alert">
22
+ <i class="fa-solid fa-circle-exclamation"></i>
23
+ <span>{{ error }}</span>
24
  </div>
25
  {% endif %}
26
 
27
  <form method="post" class="space-y-4">
28
+ <label class="block">
29
+ <span class="label-caps block mb-1.5">Username</span>
30
+ <input type="text" name="username" required autocomplete="username" autocapitalize="none" spellcheck="false"
31
+ class="field px-4 py-3 text-[15px]" placeholder="admin">
32
+ </label>
33
+ <label class="block">
34
+ <span class="label-caps block mb-1.5">Password</span>
35
+ <span class="relative block">
36
+ <input type="password" id="password" name="password" required autocomplete="current-password"
37
+ class="field pl-4 pr-12 py-3 text-[15px]" placeholder="••••••••">
38
+ <button type="button" onclick="togglePassword()" aria-label="Show password"
39
+ class="icon-btn absolute right-1 top-1/2 -translate-y-1/2 w-10 h-10">
40
+ <i id="eyeIcon" class="fa-solid fa-eye text-sm"></i>
 
 
 
 
 
 
 
 
 
 
41
  </button>
42
+ </span>
43
+ </label>
44
+ <button type="submit" class="btn-primary w-full py-3 mt-2 text-[15px]">
45
+ Sign in <i class="fa-solid fa-arrow-right text-sm"></i>
 
 
 
46
  </button>
 
47
  </form>
 
48
  </div>
49
  </div>
50
  </div>
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  <script>
53
+ function togglePassword() {
54
+ const input = document.getElementById('password');
55
+ const icon = document.getElementById('eyeIcon');
56
+ const show = input.type === 'password';
57
+ input.type = show ? 'text' : 'password';
58
+ icon.classList.toggle('fa-eye', !show);
59
+ icon.classList.toggle('fa-eye-slash', show);
60
+ }
 
 
 
 
61
  </script>
 
62
  {% endblock %}
Backend/fastapi/templates/media_edit.html CHANGED
The diff for this file is too large to render. See raw diff
 
Backend/fastapi/templates/media_management.html CHANGED
@@ -1,114 +1,61 @@
1
  {% extends "base.html" %}
2
 
3
- {% block title %}Media Management - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
- <div class="w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
7
- <!-- Header -->
8
- <section class="glass-panel rounded-3xl p-5 sm:p-6 lg:p-8 mb-6 sm:mb-8">
9
- <div class="flex flex-col gap-5">
10
- <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-4">
11
- <div>
12
- <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full border border-hairline bg-surface text-xs font-semibold text-text-secondary mb-3">
13
- <i class="fa-solid fa-clapperboard text-primary"></i>
14
- Library Control
15
- </div>
16
- <h1 class="text-2xl sm:text-3xl lg:text-4xl font-extrabold tracking-tight text-text">
17
- Media Management
18
- </h1>
19
- <p class="mt-2 text-sm sm:text-base text-text-secondary max-w-2xl">
20
- Manage your movie and TV show collections with search, filters, edit, and delete controls.
21
- </p>
22
- </div>
23
-
24
- <div class="flex flex-wrap gap-2">
25
- <a href="/media/manage?media_type=movie"
26
- class="inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-sm font-bold transition border
27
- {% if media_type == 'movie' %}
28
- bg-primary text-white border-primary shadow-lg shadow-primary/20
29
- {% else %}
30
- glass-panel text-text hover:bg-surface-2 border-hairline
31
- {% endif %}">
32
- <i class="fa-solid fa-film"></i>
33
- Movies
34
- </a>
35
- <a href="/media/manage?media_type=tv"
36
- class="inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-sm font-bold transition border
37
- {% if media_type == 'tv' %}
38
- bg-primary text-white border-primary shadow-lg shadow-primary/20
39
- {% else %}
40
- glass-panel text-text hover:bg-surface-2 border-hairline
41
- {% endif %}">
42
- <i class="fa-solid fa-tv"></i>
43
- TV Shows
44
- </a>
45
- </div>
46
- </div>
47
-
48
- <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
49
- <div class="rounded-2xl border border-hairline bg-surface px-4 py-3">
50
- <p class="text-[11px] uppercase tracking-wider text-text-secondary font-bold">Current view</p>
51
- <p class="mt-1 text-sm font-semibold text-text capitalize">{{ media_type }}</p>
52
- </div>
53
- <div class="rounded-2xl border border-hairline bg-surface px-4 py-3">
54
- <p class="text-[11px] uppercase tracking-wider text-text-secondary font-bold">Actions</p>
55
- <p class="mt-1 text-sm font-semibold text-text">Search, Edit, Delete</p>
56
- </div>
57
- </div>
58
  </div>
59
- </section>
60
-
61
- <!-- Search and Filters -->
62
- <section class="glass-panel rounded-3xl p-4 sm:p-6 mb-6 sm:mb-8">
63
- <div class="flex flex-col lg:flex-row gap-4 lg:items-center">
64
- <div class="flex-1">
65
- <label for="search-input" class="block text-xs font-bold uppercase tracking-wider text-text-secondary mb-2">
66
- Search {{ media_type|title }}
67
- </label>
68
- <div class="relative">
69
- <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-text-secondary text-sm"></i>
70
- <input type="text"
71
- id="search-input"
72
- placeholder="Search {{ media_type }}s by title..."
73
- class="w-full pl-11 pr-4 py-3 rounded-2xl bg-background text-text placeholder:text-text-secondary border border-border focus:outline-none focus:ring-2 focus:ring-primary/60 focus:border-primary transition shadow-sm">
74
- </div>
75
- </div>
76
 
77
- <div class="flex flex-col sm:flex-row gap-3 lg:pt-7">
78
- <button onclick="searchMedia()"
79
- class="inline-flex justify-center items-center gap-2 bg-primary hover:bg-primary/90 text-white px-5 py-3 rounded-2xl transition font-bold shadow-lg shadow-primary/20">
80
- <i class="fa-solid fa-magnifying-glass"></i>
81
- Search
82
- </button>
83
- <button onclick="clearSearch()"
84
- class="inline-flex justify-center items-center gap-2 glass-panel hover:bg-surface-2 text-text px-5 py-3 rounded-2xl transition font-bold border border-hairline">
85
- <i class="fa-solid fa-rotate-left"></i>
86
- Clear
87
- </button>
88
- </div>
 
 
 
 
 
 
 
 
 
89
  </div>
90
  </section>
91
 
92
  <!-- Loading Indicator -->
93
- <div id="loading" class="hidden text-center py-16">
94
- <div class="inline-flex items-center justify-center w-14 h-14 rounded-full border border-hairline glass-panel mb-4">
95
- <div class="animate-spin rounded-full h-7 w-7 border-b-2 border-primary"></div>
96
- </div>
97
  <p class="text-text-secondary">Loading {{ media_type }}s...</p>
98
  </div>
99
 
100
  <!-- Error Display -->
101
  <div id="error-display" class="hidden mb-6 sm:mb-8">
102
- <div class="glass-panel rounded-3xl p-5 sm:p-6 border border-red-500/30">
103
  <div class="flex items-start gap-3">
104
  <div class="w-11 h-11 rounded-2xl bg-red-500/15 flex items-center justify-center shrink-0">
105
  <i class="fa-solid fa-triangle-exclamation text-red-400"></i>
106
  </div>
107
  <div class="flex-1">
108
- <h3 class="text-lg font-bold text-red-300">Error Loading Media</h3>
109
  <p id="error-message" class="mt-2 text-sm text-red-200/90"></p>
110
  <button onclick="retryLoad()"
111
- class="mt-4 inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2.5 rounded-2xl transition font-bold shadow-lg shadow-primary/20">
112
  <i class="fa-solid fa-rotate-right"></i>
113
  Try Again
114
  </button>
@@ -119,17 +66,17 @@
119
 
120
  <!-- Media Grid -->
121
  <div id="media-grid"
122
- class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4 sm:gap-5 mb-6 sm:mb-8">
123
  <!-- Media items will be loaded here -->
124
  </div>
125
 
126
  <!-- No Results -->
127
  <div id="no-results" class="hidden text-center py-16">
128
- <div class="glass-panel rounded-3xl p-8 max-w-xl mx-auto">
129
- <div class="mx-auto w-16 h-16 rounded-2xl bg-surface flex items-center justify-center mb-4 border border-hairline">
130
- <i class="fa-solid fa-box-open text-3xl text-text-secondary"></i>
131
  </div>
132
- <h3 class="text-xl font-bold text-text mb-2">No {{ media_type }}s found</h3>
133
  <p class="text-sm text-text-secondary mb-6">
134
  {% if media_type == 'movie' %}
135
  No movies match your search criteria.
@@ -137,8 +84,7 @@
137
  No TV shows match your search criteria.
138
  {% endif %}
139
  </p>
140
- <button onclick="clearSearch()"
141
- class="inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-5 py-3 rounded-2xl transition font-bold shadow-lg shadow-primary/20">
142
  <i class="fa-solid fa-clapperboard"></i>
143
  Show All {{ media_type|title }}s
144
  </button>
@@ -147,15 +93,13 @@
147
 
148
  <!-- Pagination -->
149
  <div id="pagination" class="hidden mt-6 sm:mt-8">
150
- <div class="glass-panel rounded-3xl p-3 sm:p-4 overflow-x-auto">
151
- <div class="flex justify-center items-center gap-2 min-w-max px-1" id="pagination-inner"></div>
152
- </div>
153
  </div>
154
 
155
  <!-- Media Info -->
156
  <div id="media-info" class="hidden mt-6">
157
- <div class="glass-panel rounded-3xl p-4 sm:p-5">
158
- <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2 text-sm text-text-secondary">
159
  <span id="results-info"></span>
160
  <span id="db-info"></span>
161
  </div>
@@ -168,11 +112,15 @@
168
  let currentSearch = '';
169
  let isLoading = false;
170
  const mediaType = '{{ media_type }}';
 
 
 
171
 
172
  function showLoading() {
173
  isLoading = true;
174
- document.getElementById('loading').classList.remove('hidden');
175
- document.getElementById('media-grid').classList.add('hidden');
 
176
  document.getElementById('no-results').classList.add('hidden');
177
  document.getElementById('pagination').classList.add('hidden');
178
  document.getElementById('media-info').classList.add('hidden');
@@ -181,8 +129,8 @@
181
 
182
  function hideLoading() {
183
  isLoading = false;
184
- document.getElementById('loading').classList.add('hidden');
185
- document.getElementById('media-grid').classList.remove('hidden');
186
  }
187
 
188
  function showError(message) {
@@ -195,15 +143,25 @@
195
  document.getElementById('media-info').classList.add('hidden');
196
  }
197
 
 
 
 
 
 
 
 
 
 
198
  async function loadMedia(page = 1, search = '') {
199
  if (isLoading) return;
200
 
201
  showLoading();
202
  currentPage = page;
203
  currentSearch = search;
 
204
 
205
  try {
206
- const url = `/api/media/list?media_type=${mediaType}&page=${page}&page_size=24&search=${encodeURIComponent(search)}`;
207
  const response = await fetch(url, {
208
  method: 'GET',
209
  credentials: 'same-origin',
@@ -237,7 +195,7 @@
237
  }
238
 
239
  document.getElementById('no-results').classList.add('hidden');
240
- grid.innerHTML = mediaItems.map(item => createMediaCard(item)).join('');
241
  updatePagination(data.current_page || page, data.total_pages || 1);
242
  updateMediaInfo(data);
243
 
@@ -250,51 +208,77 @@
250
  }
251
 
252
 
253
- function createMediaCard(item) {
254
- const title = item.title || item.name || 'Unknown Title';
255
- const year = item.release_year || 'Unknown Year';
256
- const rating = item.rating ? `⭐ ${parseFloat(item.rating).toFixed(1)}` : '';
257
- const poster = item.poster || 'https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image';
 
258
 
259
- // Escape title for data attribute safety
260
- const safeTitle = title.replace(/"/g, '&quot;');
 
 
 
 
 
261
 
262
- return `
263
- <div class="group overflow-hidden rounded-3xl glass-panel border border-hairline hover:border-primary/30 transition-all duration-300 hover:-translate-y-1 hover:shadow-2xl">
264
- <div class="relative overflow-hidden">
265
- <img src="${poster}" alt="${title}" class="w-full aspect-[2/3] object-cover transition duration-300 group-hover:scale-105" onerror="this.src='https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image'" loading="lazy">
266
- <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
 
 
267
 
268
- <div class="absolute top-3 left-3">
269
- <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-black/60 text-white text-[11px] font-bold border border-hairline">
270
- <i class="fa-solid fa-calendar-days"></i> ${year}
271
- </span>
272
- </div>
273
- </div>
 
274
 
275
- <div class="p-4">
276
- <h3 class="font-bold text-sm sm:text-base text-text line-clamp-2 min-h-[2.75rem]" title="${title}">${title}</h3>
277
- <div class="mt-2 flex items-center justify-between text-xs text-text-secondary">
278
- <span>DB #${item.db_index ?? '-'}</span>
279
- <span>${mediaType === 'movie' ? 'Movie' : 'TV Show'}</span>
280
- </div>
 
 
281
 
282
- <div class="mt-4 flex gap-2">
283
- <a href="/media/edit?tmdb_id=${encodeURIComponent(item.tmdb_id)}&db_index=${encodeURIComponent(item.db_index)}&media_type=${encodeURIComponent(mediaType)}"
284
- class="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 rounded-2xl bg-primary hover:bg-primary/90 text-white text-xs font-bold transition shadow-lg shadow-primary/20">
285
- <i class="fa-solid fa-pen-to-square"></i> Edit
286
- </a>
287
- <button onclick="deleteMedia(this)"
288
- data-tmdb-id="${item.tmdb_id}"
289
- data-db-index="${item.db_index ?? ''}"
290
- data-title="${safeTitle}"
291
- class="inline-flex items-center justify-center gap-2 px-3 py-2 rounded-2xl glass-panel hover:bg-red-500/10 text-red-300 text-xs font-bold transition border border-hairline">
292
- <i class="fa-solid fa-trash"></i>
293
- </button>
294
- </div>
295
- </div>
296
- </div>
297
- `;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  }
299
 
300
  function updatePagination(currentPage, totalPages) {
@@ -313,7 +297,7 @@
313
  if (currentPage > 1) {
314
  paginationHTML += `
315
  <button onclick='loadMedia(${currentPage - 1}, ${JSON.stringify(currentSearch)})'
316
- class="px-4 py-2 rounded-2xl glass-panel hover:bg-surface-2 text-text text-sm font-bold transition border border-hairline">
317
  Previous
318
  </button>
319
  `;
@@ -325,7 +309,7 @@
325
  if (startPage > 1) {
326
  paginationHTML += `
327
  <button onclick='loadMedia(1, ${JSON.stringify(currentSearch)})'
328
- class="px-4 py-2 rounded-2xl glass-panel hover:bg-surface-2 text-text text-sm font-bold transition border border-hairline">
329
  1
330
  </button>
331
  `;
@@ -338,10 +322,7 @@
338
  const isActive = i === currentPage;
339
  paginationHTML += `
340
  <button onclick='loadMedia(${i}, ${JSON.stringify(currentSearch)})'
341
- class="px-4 py-2 rounded-2xl text-sm font-bold transition border
342
- ${isActive
343
- ? 'bg-primary text-white border-primary shadow-lg shadow-primary/20'
344
- : 'glass-panel hover:bg-surface-2 text-text border-hairline'}">
345
  ${i}
346
  </button>
347
  `;
@@ -353,7 +334,7 @@
353
  }
354
  paginationHTML += `
355
  <button onclick='loadMedia(${totalPages}, ${JSON.stringify(currentSearch)})'
356
- class="px-4 py-2 rounded-2xl glass-panel hover:bg-surface-2 text-text text-sm font-bold transition border border-hairline">
357
  ${totalPages}
358
  </button>
359
  `;
@@ -362,7 +343,7 @@
362
  if (currentPage < totalPages) {
363
  paginationHTML += `
364
  <button onclick='loadMedia(${currentPage + 1}, ${JSON.stringify(currentSearch)})'
365
- class="px-4 py-2 rounded-2xl glass-panel hover:bg-surface-2 text-text text-sm font-bold transition border border-hairline">
366
  Next
367
  </button>
368
  `;
@@ -377,12 +358,13 @@
377
  const dbInfo = document.getElementById('db-info');
378
 
379
  const totalCount = data.total_count || 0;
380
- const pageSize = 24;
381
  const current = data.current_page || 1;
382
  const startItem = totalCount === 0 ? 0 : ((current - 1) * pageSize) + 1;
383
  const endItem = Math.min(current * pageSize, totalCount);
384
 
385
- resultsInfo.textContent = `Showing ${startItem}-${endItem} of ${totalCount} ${mediaType}s`;
 
386
 
387
  if (data.databases_checked && data.databases_checked.length > 0) {
388
  dbInfo.textContent = `Databases checked: ${data.databases_checked.join(', ')}`;
@@ -439,9 +421,13 @@
439
  }
440
 
441
  document.addEventListener('DOMContentLoaded', () => {
442
- loadMedia();
 
 
443
 
444
  const searchInput = document.getElementById('search-input');
 
 
445
 
446
  searchInput.addEventListener('keypress', (e) => {
447
  if (e.key === 'Enter') {
@@ -487,7 +473,499 @@
487
 
488
  #pagination .overflow-x-auto::-webkit-scrollbar-thumb {
489
  border-radius: 999px;
490
- background: rgba(255, 255, 255, 0.2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  </style>
493
  {% endblock %}
 
1
  {% extends "base.html" %}
2
 
3
+ {% block title %}Media - Telegram Stremio{% endblock %}
4
 
5
  {% block content %}
6
+ <div>
7
+ <header class="page-head">
8
+ <div>
9
+ <h1 class="page-title">{{ 'Movies' if media_type == 'movie' else 'TV shows' }}</h1>
10
+ <p class="page-sub" id="page-count">Your indexed library</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  </div>
12
+ <div class="page-actions">
13
+ <button type="button" onclick="openManualAdd()" class="btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> Add title</button>
14
+ </div>
15
+ </header>
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ <section class="flex flex-col md:flex-row md:items-center gap-3 mb-6">
18
+ <div class="flex items-center gap-2 shrink-0">
19
+ <div class="seg shrink-0" role="tablist">
20
+ <a href="/media/manage?media_type=movie{% if custom %}&custom=1{% endif %}" role="tab" aria-selected="{{ 'true' if media_type == 'movie' else 'false' }}"><i class="fa-solid fa-film"></i>Movies</a>
21
+ <a href="/media/manage?media_type=tv{% if custom %}&custom=1{% endif %}" role="tab" aria-selected="{{ 'true' if media_type == 'tv' else 'false' }}"><i class="fa-solid fa-tv"></i>TV shows</a>
22
+ </div>
23
+ <label class="chip-toggle shrink-0">
24
+ <input type="checkbox" class="sr-only" {% if custom %}checked{% endif %}
25
+ onchange="window.location.href='/media/manage?media_type={{ media_type }}' + (this.checked ? '&custom=1' : '')">
26
+ <i class="fa-solid fa-star text-xs"></i> Custom
27
+ </label>
28
+ </div>
29
+ <div class="relative flex-1 min-w-0">
30
+ <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-text-secondary text-sm pointer-events-none"></i>
31
+ <input type="search" id="search-input" enterkeyhint="search" autocomplete="off"
32
+ placeholder="Search {{ 'movies' if media_type == 'movie' else 'TV shows' }}"
33
+ class="field pl-11 pr-12 py-2.5">
34
+ <button onclick="clearSearch()" title="Clear search" aria-label="Clear search"
35
+ class="icon-btn absolute right-1 top-1/2 -translate-y-1/2 w-9 h-9">
36
+ <i class="fa-solid fa-xmark"></i>
37
+ </button>
38
  </div>
39
  </section>
40
 
41
  <!-- Loading Indicator -->
42
+ <div id="loading" class="hidden">
43
+ <i class="fa-solid fa-circle-notch fa-spin text-2xl text-primary mb-3"></i>
 
 
44
  <p class="text-text-secondary">Loading {{ media_type }}s...</p>
45
  </div>
46
 
47
  <!-- Error Display -->
48
  <div id="error-display" class="hidden mb-6 sm:mb-8">
49
+ <div class="glass-panel p-5 border-danger/30">
50
  <div class="flex items-start gap-3">
51
  <div class="w-11 h-11 rounded-2xl bg-red-500/15 flex items-center justify-center shrink-0">
52
  <i class="fa-solid fa-triangle-exclamation text-red-400"></i>
53
  </div>
54
  <div class="flex-1">
55
+ <h3 class="text-lg font-semibold text-red-300">Error Loading Media</h3>
56
  <p id="error-message" class="mt-2 text-sm text-red-200/90"></p>
57
  <button onclick="retryLoad()"
58
+ class="mt-4 inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-on-primary px-4 py-2.5 rounded-2xl transition font-semibold">
59
  <i class="fa-solid fa-rotate-right"></i>
60
  Try Again
61
  </button>
 
66
 
67
  <!-- Media Grid -->
68
  <div id="media-grid"
69
+ class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-7 gap-x-3 gap-y-5 mb-8">
70
  <!-- Media items will be loaded here -->
71
  </div>
72
 
73
  <!-- No Results -->
74
  <div id="no-results" class="hidden text-center py-16">
75
+ <div class="max-w-md mx-auto">
76
+ <div class="mx-auto w-12 h-12 rounded-full bg-card-high grid place-items-center mb-4">
77
+ <i class="fa-solid fa-box-open text-text-secondary"></i>
78
  </div>
79
+ <h3 class="text-lg font-semibold mb-1">Nothing found</h3>
80
  <p class="text-sm text-text-secondary mb-6">
81
  {% if media_type == 'movie' %}
82
  No movies match your search criteria.
 
84
  No TV shows match your search criteria.
85
  {% endif %}
86
  </p>
87
+ <button onclick="clearSearch()" class="btn-ghost px-4 py-2 text-sm">
 
88
  <i class="fa-solid fa-clapperboard"></i>
89
  Show All {{ media_type|title }}s
90
  </button>
 
93
 
94
  <!-- Pagination -->
95
  <div id="pagination" class="hidden mt-6 sm:mt-8">
96
+ <div class="overflow-x-auto"><div class="flex justify-center items-center gap-1.5 min-w-max mx-auto" id="pagination-inner"></div></div>
 
 
97
  </div>
98
 
99
  <!-- Media Info -->
100
  <div id="media-info" class="hidden mt-6">
101
+ <div>
102
+ <div class="flex flex-col sm:flex-row justify-center items-center gap-1 sm:gap-4 text-sm text-text-secondary">
103
  <span id="results-info"></span>
104
  <span id="db-info"></span>
105
  </div>
 
112
  let currentSearch = '';
113
  let isLoading = false;
114
  const mediaType = '{{ media_type }}';
115
+ const isCustom = {{ 'true' if custom else 'false' }};
116
+
117
+ const PAGE_SIZE = 30;
118
 
119
  function showLoading() {
120
  isLoading = true;
121
+ const grid = document.getElementById('media-grid');
122
+ if (grid.children.length) grid.classList.add('is-busy');
123
+ else grid.innerHTML = Array.from({ length: 12 }, () => '<div class="m-skel"><div></div><p></p><p></p></div>').join('');
124
  document.getElementById('no-results').classList.add('hidden');
125
  document.getElementById('pagination').classList.add('hidden');
126
  document.getElementById('media-info').classList.add('hidden');
 
129
 
130
  function hideLoading() {
131
  isLoading = false;
132
+ const grid = document.getElementById('media-grid');
133
+ grid.classList.remove('hidden', 'is-busy');
134
  }
135
 
136
  function showError(message) {
 
143
  document.getElementById('media-info').classList.add('hidden');
144
  }
145
 
146
+ function syncPageUrl(page, search) {
147
+ const params = new URLSearchParams();
148
+ params.set('media_type', mediaType);
149
+ if (isCustom) params.set('custom', '1');
150
+ if (page > 1) params.set('page', page);
151
+ if (search) params.set('search', search);
152
+ history.replaceState(null, '', `${location.pathname}?${params.toString()}`);
153
+ }
154
+
155
  async function loadMedia(page = 1, search = '') {
156
  if (isLoading) return;
157
 
158
  showLoading();
159
  currentPage = page;
160
  currentSearch = search;
161
+ syncPageUrl(page, search);
162
 
163
  try {
164
+ const url = `/api/media/list?media_type=${mediaType}&page=${page}&page_size=${PAGE_SIZE}&search=${encodeURIComponent(search)}&custom=${isCustom ? 1 : 0}`;
165
  const response = await fetch(url, {
166
  method: 'GET',
167
  credentials: 'same-origin',
 
195
  }
196
 
197
  document.getElementById('no-results').classList.add('hidden');
198
+ grid.innerHTML = mediaItems.map((item, idx) => createMediaCard(item, idx)).join('');
199
  updatePagination(data.current_page || page, data.total_pages || 1);
200
  updateMediaInfo(data);
201
 
 
208
  }
209
 
210
 
211
+ function collectQualities(item) {
212
+ const out = [];
213
+ (item.telegram || []).forEach(q => out.push(q));
214
+ (item.seasons || []).forEach(s => (s.episodes || []).forEach(e => (e.telegram || []).forEach(q => out.push(q))));
215
+ return out;
216
+ }
217
 
218
+ function sizeToBytes(str) {
219
+ if (!str) return 0;
220
+ const m = String(str).trim().match(/([\d.]+)\s*([A-Za-z]+)/);
221
+ if (!m) return 0;
222
+ const mult = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
223
+ return parseFloat(m[1]) * (mult[m[2].toUpperCase()] || 1);
224
+ }
225
 
226
+ function bytesToSize(bytes) {
227
+ if (!bytes) return '';
228
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
229
+ let i = 0, v = bytes;
230
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
231
+ return `${v.toFixed(v >= 100 || i === 0 ? 0 : 1)} ${units[i]}`;
232
+ }
233
 
234
+ function allQualityLabels(qualities) {
235
+ const norm = { '2160p': '4K', '4k': '4K', '1080p': '1080p', '720p': '720p', '480p': '480p', '360p': '360p' };
236
+ const rank = { '4K': 5, '1080p': 4, '720p': 3, '480p': 2, '360p': 1 };
237
+ const set = new Set();
238
+ qualities.forEach(q => { const k = String(q.quality || '').toLowerCase(); if (norm[k]) set.add(norm[k]); });
239
+ return Array.from(set).sort((a, b) => (rank[b] || 0) - (rank[a] || 0));
240
+ }
241
 
242
+ function mediaBadges(item) {
243
+ const qs = collectQualities(item);
244
+ if (!qs.length) return '';
245
+ const isSplit = qs.some(q => q.group_key || (q.parts && q.parts.length));
246
+ const labels = allQualityLabels(qs);
247
+ const pills = labels.slice(0, 2).map(l => `<span class="q-chip">${l}</span>`).join('');
248
+ return `<div class="absolute left-2 bottom-2 flex gap-1">${pills}${isSplit ? '<span class="q-chip" title="Split file"><i class="fa-solid fa-puzzle-piece"></i></span>' : ''}</div>`;
249
+ }
250
 
251
+ function thumb(url) {
252
+ return String(url)
253
+ .replace(/(image\.tmdb\.org\/t\/p\/)(?:original|w\d+)\//, '$1w342/')
254
+ .replace(/(images\.metahub\.space\/poster\/)(?:medium|large)\//, '$1small/');
255
+ }
256
+
257
+ function createMediaCard(item, idx = 0) {
258
+ const title = escapeHtml(item.title || item.name || 'Unknown title');
259
+ const year = escapeHtml(item.release_year || '');
260
+ const qs = collectQualities(item);
261
+ const size = bytesToSize(qs.reduce((sum, q) => sum + sizeToBytes(q.size), 0));
262
+ const href = `/media/edit?tmdb_id=${encodeURIComponent(item.tmdb_id)}&db_index=${encodeURIComponent(item.db_index)}&media_type=${encodeURIComponent(mediaType)}&page=${currentPage}${currentSearch ? `&search=${encodeURIComponent(currentSearch)}` : ''}`;
263
+ const meta = [year, size].filter(Boolean).join(' · ');
264
+ return `
265
+ <article class="m-card">
266
+ <a href="${href}" class="m-poster" aria-label="Edit ${title}">
267
+ ${item.poster ? `<img src="${escapeHtml(thumb(item.poster))}" alt="" width="185" height="278" loading="${idx < 12 ? 'eager' : 'lazy'}" ${idx < 6 ? 'fetchpriority="high"' : ''} decoding="async" onerror="this.remove()">` : ''}
268
+ <span class="m-fallback"><i class="fa-solid ${mediaType === 'movie' ? 'fa-film' : 'fa-tv'}"></i></span>
269
+ ${item.rating ? `<span class="m-rating">★ ${parseFloat(item.rating).toFixed(1)}</span>` : ''}
270
+ ${Number(item.tmdb_id) < 0 ? '<span class="m-custom"><i class="fa-solid fa-star"></i> Custom</span>' : ''}
271
+ ${mediaBadges(item)}
272
+ </a>
273
+ <button onclick="deleteMedia(this)" data-tmdb-id="${escapeHtml(item.tmdb_id)}" data-db-index="${escapeHtml(item.db_index ?? '')}" data-title="${title}"
274
+ class="m-del" aria-label="Delete ${title}" title="Delete">
275
+ <i class="fa-solid fa-trash-can"></i>
276
+ </button>
277
+ <a href="${href}" class="block mt-2 min-w-0">
278
+ <h3 class="text-sm font-medium leading-snug truncate" title="${title}">${title}</h3>
279
+ <p class="text-xs text-text-secondary truncate">${meta}</p>
280
+ </a>
281
+ </article>`;
282
  }
283
 
284
  function updatePagination(currentPage, totalPages) {
 
297
  if (currentPage > 1) {
298
  paginationHTML += `
299
  <button onclick='loadMedia(${currentPage - 1}, ${JSON.stringify(currentSearch)})'
300
+ class="pg-btn">
301
  Previous
302
  </button>
303
  `;
 
309
  if (startPage > 1) {
310
  paginationHTML += `
311
  <button onclick='loadMedia(1, ${JSON.stringify(currentSearch)})'
312
+ class="pg-btn">
313
  1
314
  </button>
315
  `;
 
322
  const isActive = i === currentPage;
323
  paginationHTML += `
324
  <button onclick='loadMedia(${i}, ${JSON.stringify(currentSearch)})'
325
+ class="pg-btn" ${isActive ? 'aria-current="page"' : ''}>
 
 
 
326
  ${i}
327
  </button>
328
  `;
 
334
  }
335
  paginationHTML += `
336
  <button onclick='loadMedia(${totalPages}, ${JSON.stringify(currentSearch)})'
337
+ class="pg-btn">
338
  ${totalPages}
339
  </button>
340
  `;
 
343
  if (currentPage < totalPages) {
344
  paginationHTML += `
345
  <button onclick='loadMedia(${currentPage + 1}, ${JSON.stringify(currentSearch)})'
346
+ class="pg-btn">
347
  Next
348
  </button>
349
  `;
 
358
  const dbInfo = document.getElementById('db-info');
359
 
360
  const totalCount = data.total_count || 0;
361
+ const pageSize = PAGE_SIZE;
362
  const current = data.current_page || 1;
363
  const startItem = totalCount === 0 ? 0 : ((current - 1) * pageSize) + 1;
364
  const endItem = Math.min(current * pageSize, totalCount);
365
 
366
+ resultsInfo.textContent = `Showing ${startItem}-${endItem} of ${totalCount}`;
367
+ document.getElementById('page-count').textContent = `${totalCount} title${totalCount === 1 ? '' : 's'}${currentSearch ? ` matching “${currentSearch}”` : ''}`;
368
 
369
  if (data.databases_checked && data.databases_checked.length > 0) {
370
  dbInfo.textContent = `Databases checked: ${data.databases_checked.join(', ')}`;
 
421
  }
422
 
423
  document.addEventListener('DOMContentLoaded', () => {
424
+ const params = new URLSearchParams(location.search);
425
+ const startPage = Math.max(1, parseInt(params.get('page') || '1', 10) || 1);
426
+ const startSearch = params.get('search') || '';
427
 
428
  const searchInput = document.getElementById('search-input');
429
+ if (startSearch) searchInput.value = startSearch;
430
+ loadMedia(startPage, startSearch);
431
 
432
  searchInput.addEventListener('keypress', (e) => {
433
  if (e.key === 'Enter') {
 
473
 
474
  #pagination .overflow-x-auto::-webkit-scrollbar-thumb {
475
  border-radius: 999px;
476
+ background: color-mix(in srgb, var(--text) 20%, transparent);
477
+ }
478
+
479
+ .ma-input {
480
+ width: 100%;
481
+ background: var(--background, var(--bg));
482
+ border: 1px solid var(--border);
483
+ color: var(--text);
484
+ border-radius: 0.9rem;
485
+ padding: 0.7rem 0.9rem;
486
+ font-size: 0.9rem;
487
+ outline: none;
488
+ }
489
+ .ma-input:focus { border-color: var(--primary); }
490
+ .ma-label { display:block; font-size:0.72rem; font-weight: 600; text-transform:uppercase; letter-spacing:0.04em; color:var(--text-secondary,var(--text-sec)); margin-bottom:0.35rem; }
491
+ .ma-tab { flex:1; padding:0.55rem; border-radius:0.75rem; font-weight: 600; font-size:0.85rem; border:1px solid var(--border); background:transparent; color:var(--text); cursor:pointer; }
492
+ .ma-tab.active { background:var(--primary); color:#fff; border-color:var(--primary); }
493
+ .ma-catalog-picker { max-height:10rem; overflow-y:auto; border:1px solid var(--border); border-radius:0.85rem; padding:.4rem; display:flex; flex-direction:column; gap:.25rem; background:var(--background, var(--bg)); }
494
+ .ma-cat-row { display:flex; align-items:center; gap:.55rem; padding:.45rem .6rem; border-radius:.6rem; cursor:pointer; transition:background .15s ease; }
495
+ .ma-cat-row:hover { background:color-mix(in srgb, var(--primary) 10%, transparent); }
496
+ .ma-cat-row.disabled { opacity:.4; pointer-events:none; }
497
+ .ma-cat-row input { width:1rem; height:1rem; accent-color:var(--primary); cursor:pointer; flex-shrink:0; }
498
+ .ma-cat-excl { font-size:.65rem; font-weight: 600; padding:.15rem .4rem; border-radius:9999px; background:color-mix(in srgb, var(--danger) 16%, transparent); color:var(--danger); border:1px solid color-mix(in srgb, var(--danger) 30%, transparent); }
499
+ .ma-search-results { max-height:16rem; overflow-y:auto; margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem; }
500
+ .ma-result-row { display:flex; align-items:center; gap:.7rem; padding:.5rem; border-radius:.7rem; border:1px solid var(--border); background:var(--background, var(--bg)); cursor:pointer; text-align:left; transition:border-color .15s ease; }
501
+ .ma-result-row:hover { border-color:var(--primary); }
502
+ .ma-result-poster { width:2.5rem; height:3.75rem; object-fit:cover; border-radius:.4rem; flex-shrink:0; background:var(--surface,#222); }
503
+ .ma-result-meta { min-width:0; flex:1; }
504
+ .ma-src-badge { font-size:.6rem; font-weight: 600; padding:.1rem .4rem; border-radius:9999px; background:color-mix(in srgb, var(--primary) 16%, transparent); color:var(--primary); border:1px solid color-mix(in srgb, var(--primary) 30%, transparent); text-transform:uppercase; }
505
+ .ma-linked-chip { display:inline-flex; align-items:center; gap:.5rem; padding:.35rem .7rem; border-radius:9999px; font-size:.78rem; font-weight: 600; background:color-mix(in srgb, var(--ok) 14%, transparent); color:var(--ok); border:1px solid color-mix(in srgb, var(--ok) 30%, transparent); }
506
+ .ma-unlink-btn { background:none; border:none; color:inherit; font-size:1.1rem; line-height:1; cursor:pointer; padding:0 .1rem; }
507
+ </style>
508
+
509
+ <!-- Manual Add modal -->
510
+ <div id="manual-add-modal" class="fixed inset-0 z-50 hidden" aria-modal="true" role="dialog">
511
+ <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeManualAdd()"></div>
512
+ <div class="absolute inset-0 flex items-start sm:items-center justify-center p-2 sm:p-4 overflow-y-auto">
513
+ <div class="glass-panel rounded-3xl w-full max-w-2xl my-4">
514
+ <div class="flex items-center justify-between gap-3 px-5 sm:px-6 py-4 border-b border-hairline">
515
+ <h2 class="text-lg sm:text-xl font-semibold text-text"><i class="fa-solid fa-plus text-emerald-400"></i> Add Content Manually</h2>
516
+ <button onclick="closeManualAdd()" class="icon-btn shrink-0" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
517
+ </div>
518
+
519
+ <div class="px-5 sm:px-6 py-5 space-y-5 max-h-[75vh] overflow-y-auto">
520
+ <!-- Type -->
521
+ <div>
522
+ <label class="ma-label">Type</label>
523
+ <div class="flex gap-2">
524
+ <button type="button" class="ma-tab" data-ma-type="movie" onclick="maSetType('movie')"><i class="fa-solid fa-film"></i> Movie</button>
525
+ <button type="button" class="ma-tab" data-ma-type="tv" onclick="maSetType('tv')"><i class="fa-solid fa-tv"></i> TV Show</button>
526
+ </div>
527
+ </div>
528
+
529
+ <!-- Search TMDB/Cinemeta to auto-fill -->
530
+ <div>
531
+ <label class="ma-label">Search title (TMDB / Cinemeta) — optional</label>
532
+ <div class="flex flex-col sm:flex-row gap-2">
533
+ <input id="ma-search-query" class="ma-input" placeholder="Title, IMDb id/link or TMDB id/link">
534
+ <button type="button" onclick="maSearchTitles()" class="px-4 py-2.5 rounded-xl bg-primary text-on-primary font-semibold text-sm shrink-0"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
535
+ </div>
536
+ <p id="ma-search-state" class="text-xs text-text-secondary mt-1 hidden"></p>
537
+ <div id="ma-search-results" class="ma-search-results hidden"></div>
538
+ <div id="ma-linked-badge" class="hidden mt-2">
539
+ <span class="ma-linked-chip">
540
+ <i class="fa-solid fa-link"></i>
541
+ <span id="ma-linked-text"></span>
542
+ <button type="button" onclick="maUnlink()" title="Unlink and enter manually" class="ma-unlink-btn">&times;</button>
543
+ </span>
544
+ </div>
545
+ </div>
546
+
547
+ <!-- Title details -->
548
+ <div class="grid grid-cols-1 sm:grid-cols-4 gap-3">
549
+ <div class="sm:col-span-2">
550
+ <label class="ma-label">Title *</label>
551
+ <input id="ma-m-title" class="ma-input" placeholder="Custom title">
552
+ </div>
553
+ <div>
554
+ <label class="ma-label">Year (optional)</label>
555
+ <input id="ma-m-year" type="number" class="ma-input" placeholder="Telegram upload year">
556
+ </div>
557
+ <div>
558
+ <label class="ma-label">Rating (optional)</label>
559
+ <input id="ma-m-rating" type="number" step="0.1" min="0" max="10" class="ma-input" placeholder="Random">
560
+ </div>
561
+ </div>
562
+ <div>
563
+ <label class="ma-label">Genres (optional, comma-separated)</label>
564
+ <input id="ma-m-genres" class="ma-input" placeholder="Left empty = random">
565
+ </div>
566
+ <div>
567
+ <label class="ma-label">Description (optional)</label>
568
+ <textarea id="ma-m-description" rows="2" class="ma-input" placeholder="Left empty = random"></textarea>
569
+ </div>
570
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
571
+ <div>
572
+ <label class="ma-label">Poster URL (optional)</label>
573
+ <input id="ma-m-poster" type="url" class="ma-input" placeholder="Left empty = generated from title">
574
+ </div>
575
+ <div>
576
+ <label class="ma-label">Backdrop URL (optional)</label>
577
+ <input id="ma-m-backdrop" type="url" class="ma-input" placeholder="Left empty = generated from title">
578
+ </div>
579
+ </div>
580
+ <p class="text-xs text-text-secondary -mt-2">Only <span class="text-text font-semibold">Title *</span>, stream link and quality are required. Empty optional fields are auto-filled &mdash; poster &amp; backdrop become a random gradient cover with the title text.</p>
581
+
582
+ <!-- TV episode fields -->
583
+ <div id="ma-tv-fields" class="hidden grid grid-cols-2 sm:grid-cols-4 gap-3">
584
+ <div>
585
+ <label class="ma-label">Season *</label>
586
+ <input id="ma-season" type="number" min="0" class="ma-input" placeholder="1">
587
+ </div>
588
+ <div>
589
+ <label class="ma-label">Episode *</label>
590
+ <input id="ma-episode" type="number" min="0" class="ma-input" placeholder="1">
591
+ </div>
592
+ <div class="col-span-2">
593
+ <label class="ma-label">Episode Title (optional)</label>
594
+ <input id="ma-episode-title" class="ma-input" placeholder="Left empty = S01E01 style">
595
+ </div>
596
+ </div>
597
+
598
+ <!-- Stream -->
599
+ <div class="space-y-3">
600
+ <div class="flex items-center justify-between gap-2">
601
+ <label class="ma-label" style="margin-bottom:0">Stream link(s) *</label>
602
+ <button type="button" onclick="maAddPart()" class="text-xs font-semibold text-primary shrink-0"><i class="fa-solid fa-plus"></i> Add split part</button>
603
+ </div>
604
+ <div id="ma-parts" class="space-y-2"></div>
605
+ <p class="text-xs text-text-secondary">Add more parts only for a split file (they join into one stream, in order).</p>
606
+ <p id="ma-resolve-state" class="text-xs text-text-secondary hidden"></p>
607
+ <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
608
+ <div>
609
+ <label class="ma-label">Quality *</label>
610
+ <select id="ma-quality" class="ma-input">
611
+ <option value="">Select</option>
612
+ <option>480p</option><option>720p</option><option selected>1080p</option>
613
+ <option>2160p</option><option value="__custom">Custom…</option>
614
+ </select>
615
+ </div>
616
+ <div class="sm:col-span-2">
617
+ <label class="ma-label">File name</label>
618
+ <input id="ma-name" class="ma-input" placeholder="Auto-detected on resolve">
619
+ </div>
620
+ </div>
621
+ <input id="ma-quality-custom" class="ma-input hidden" placeholder="Custom quality label (e.g. 4K HDR)">
622
+ </div>
623
+
624
+ <!-- Custom Catalog selector -->
625
+ <div>
626
+ <label class="ma-label">Add to Custom Catalog</label>
627
+ <div id="ma-catalog-list" class="ma-catalog-picker">
628
+ <p class="text-xs text-text-secondary">Loading catalogs...</p>
629
+ </div>
630
+ <p class="text-xs text-text-secondary mt-1">Exclusive catalogs don't allow other selections.</p>
631
+ </div>
632
+ </div>
633
+
634
+ <div class="flex flex-col sm:flex-row justify-end gap-3 px-5 sm:px-6 py-4 border-t border-hairline">
635
+ <button onclick="closeManualAdd()" class="px-5 py-2.5 rounded-2xl glass-panel border border-hairline text-text font-semibold text-sm">Cancel</button>
636
+ <button id="ma-submit" onclick="submitManualAdd()" class="px-5 py-2.5 rounded-2xl bg-primary text-on-primary font-semibold text-sm">Add Content</button>
637
+ </div>
638
+ </div>
639
+ </div>
640
+ </div>
641
+
642
+ <script>
643
+ let maType = mediaType;
644
+ let maSelectedId = null;
645
+ let maSearchList = [];
646
+
647
+ function maEsc(s) {
648
+ return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
649
+ }
650
+
651
+ async function maSearchTitles() {
652
+ const q = document.getElementById('ma-search-query').value.trim();
653
+ const state = document.getElementById('ma-search-state');
654
+ const box = document.getElementById('ma-search-results');
655
+ if (!q) { showToast('Enter a title, IMDb or TMDB id/link.', 'error', 'Error'); return; }
656
+ state.textContent = 'Searching...';
657
+ state.classList.remove('hidden');
658
+ box.classList.add('hidden');
659
+ box.innerHTML = '';
660
+ try {
661
+ const params = new URLSearchParams({ media_type: maType, query: q });
662
+ const yearVal = document.getElementById('ma-m-year').value.trim();
663
+ if (yearVal) params.set('year', yearVal);
664
+ const res = await fetch(`/api/media/rescan/search?${params.toString()}`);
665
+ const data = await res.json().catch(() => ({}));
666
+ if (!res.ok) throw new Error(data.detail || 'Search failed');
667
+ maSearchList = data.results || [];
668
+ if (!maSearchList.length) {
669
+ state.textContent = 'No matches found.';
670
+ return;
671
+ }
672
+ state.textContent = `Found ${maSearchList.length} match${maSearchList.length > 1 ? 'es' : ''}. Pick one to auto-fill.`;
673
+ box.innerHTML = maSearchList.map((r, i) => `
674
+ <button type="button" class="ma-result-row" onclick="maPickResult(${i})">
675
+ <img class="ma-result-poster" src="${maEsc(r.poster) || '/static/placeholder.svg'}" onerror="this.src='/static/placeholder.svg'">
676
+ <span class="ma-result-meta">
677
+ <span class="flex items-center gap-2">
678
+ <span class="text-sm font-semibold text-text truncate">${maEsc(r.title)}</span>
679
+ <span class="ma-src-badge">${maEsc(r.source)}</span>
680
+ </span>
681
+ <span class="text-xs text-text-secondary block truncate">${maEsc(r.year || '—')} · IMDb: ${maEsc(r.imdb_id || 'N/A')} · TMDB: ${maEsc(r.tmdb_id || 'N/A')}</span>
682
+ </span>
683
+ </button>`).join('');
684
+ box.classList.remove('hidden');
685
+ } catch (e) {
686
+ state.textContent = e.message || 'Search failed.';
687
+ }
688
  }
689
+
690
+ async function maPickResult(index) {
691
+ const item = maSearchList[index];
692
+ if (!item) return;
693
+ const selectedId = item.tmdb_id || item.imdb_id;
694
+ if (!selectedId) { showToast('This result has no usable id.', 'error', 'Error'); return; }
695
+ const state = document.getElementById('ma-search-state');
696
+ state.textContent = 'Loading metadata...';
697
+ state.classList.remove('hidden');
698
+ try {
699
+ const params = new URLSearchParams({ media_type: maType, selected_id: String(selectedId) });
700
+ const res = await fetch(`/api/media/manual-add/resolve-meta?${params.toString()}`);
701
+ const data = await res.json().catch(() => ({}));
702
+ if (!res.ok) throw new Error(data.detail || 'Could not load metadata');
703
+ const m = data.metadata || {};
704
+ document.getElementById('ma-m-title').value = m.title || '';
705
+ document.getElementById('ma-m-year').value = m.release_year || '';
706
+ document.getElementById('ma-m-rating').value = m.rating || '';
707
+ document.getElementById('ma-m-genres').value = Array.isArray(m.genres) ? m.genres.join(', ') : (m.genres || '');
708
+ document.getElementById('ma-m-description').value = m.description || '';
709
+ document.getElementById('ma-m-poster').value = m.poster || '';
710
+ document.getElementById('ma-m-backdrop').value = m.backdrop || '';
711
+
712
+ maSelectedId = String(selectedId);
713
+ document.getElementById('ma-linked-text').textContent = `${m.title || 'Selected'} (${item.source})`;
714
+ document.getElementById('ma-linked-badge').classList.remove('hidden');
715
+ document.getElementById('ma-search-results').classList.add('hidden');
716
+ state.classList.add('hidden');
717
+ } catch (e) {
718
+ state.textContent = e.message || 'Could not load metadata.';
719
+ }
720
+ }
721
+
722
+ function maUnlink() {
723
+ maSelectedId = null;
724
+ document.getElementById('ma-linked-badge').classList.add('hidden');
725
+ }
726
+
727
+ async function loadMaCatalogs() {
728
+ const box = document.getElementById('ma-catalog-list');
729
+ if (!box) return;
730
+ box.innerHTML = '<p class="text-xs text-text-secondary">Loading...</p>';
731
+ try {
732
+ const res = await fetch('/api/media/manual-add/catalogs');
733
+ const data = await res.json().catch(() => ({}));
734
+ const catalogs = data.catalogs || [];
735
+ if (!catalogs.length) {
736
+ box.innerHTML = '<p class="text-xs text-text-secondary">No custom catalogs found.</p>';
737
+ return;
738
+ }
739
+ box.innerHTML = catalogs.map((c, i) => {
740
+ const safe = (s) => String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
741
+ return `<label class="ma-cat-row" data-exclusive="${c.exclusive ? '1' : '0'}">
742
+ <input type="checkbox" value="${safe(c._id)}" onchange="onMaCatalogCheck(this)">
743
+ <span class="text-sm font-semibold text-text truncate">${safe(c.name)}</span>
744
+ ${c.exclusive ? '<span class="ma-cat-excl">Exclusive</span>' : ''}
745
+ </label>`;
746
+ }).join('');
747
+ } catch (e) {
748
+ box.innerHTML = '<p class="text-xs text-text-secondary">Failed to load catalogs.</p>';
749
+ }
750
+ }
751
+
752
+ function onMaCatalogCheck(input) {
753
+ const box = document.getElementById('ma-catalog-list');
754
+ const rows = box.querySelectorAll('.ma-cat-row');
755
+ const row = input.closest('.ma-cat-row');
756
+ const isExclusive = row?.dataset.exclusive === '1';
757
+
758
+ if (input.checked && isExclusive) {
759
+ rows.forEach(r => {
760
+ if (r !== row) {
761
+ r.classList.add('disabled');
762
+ r.querySelector('input').checked = false;
763
+ }
764
+ });
765
+ } else if (!input.checked && isExclusive) {
766
+ rows.forEach(r => r.classList.remove('disabled'));
767
+ } else if (input.checked && !isExclusive) {
768
+ rows.forEach(r => {
769
+ if (r.dataset.exclusive === '1') {
770
+ r.classList.add('disabled');
771
+ r.querySelector('input').checked = false;
772
+ }
773
+ });
774
+ } else {
775
+ const anyNonExclChecked = [...box.querySelectorAll('.ma-cat-row:not([data-exclusive="1"]) input:checked')].length > 0;
776
+ if (!anyNonExclChecked) {
777
+ rows.forEach(r => r.classList.remove('disabled'));
778
+ }
779
+ }
780
+ }
781
+
782
+ function getMaSelectedCatalogIds() {
783
+ const box = document.getElementById('ma-catalog-list');
784
+ if (!box) return [];
785
+ return [...box.querySelectorAll('input:checked')].map(i => i.value);
786
+ }
787
+
788
+ function maResetParts() {
789
+ document.getElementById('ma-parts').innerHTML =
790
+ `<div class="flex flex-col sm:flex-row gap-2" data-part>
791
+ <input class="ma-input ma-part-url" placeholder="https://t.me/c/123456/789">
792
+ <button type="button" onclick="maResolve()" class="px-4 py-2.5 rounded-xl glass-panel border border-hairline text-text font-semibold text-sm shrink-0">Resolve</button>
793
+ </div>`;
794
+ }
795
+
796
+ function maAddPart() {
797
+ const div = document.createElement('div');
798
+ div.className = 'flex flex-col sm:flex-row gap-2';
799
+ div.setAttribute('data-part', '');
800
+ div.innerHTML = `<input class="ma-input ma-part-url" placeholder="Split part link (in order)">
801
+ <button type="button" onclick="this.closest('[data-part]').remove()" class="px-4 py-2.5 rounded-xl border border-hairline text-red-300 font-semibold text-sm shrink-0">Remove</button>`;
802
+ document.getElementById('ma-parts').appendChild(div);
803
+ }
804
+
805
+ function maCollectParts() {
806
+ return [...document.querySelectorAll('#ma-parts .ma-part-url')]
807
+ .map(i => i.value.trim()).filter(Boolean).map(url => ({ url }));
808
+ }
809
+
810
+ function openManualAdd() {
811
+ maSetType(mediaType);
812
+ ['ma-name','ma-season','ma-episode','ma-episode-title','ma-m-title','ma-m-year','ma-m-rating','ma-m-genres','ma-m-description','ma-m-poster','ma-m-backdrop','ma-quality-custom','ma-search-query'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
813
+ maResetParts();
814
+ document.getElementById('ma-quality').value = '1080p';
815
+ document.getElementById('ma-quality-custom').classList.add('hidden');
816
+ document.getElementById('ma-resolve-state').classList.add('hidden');
817
+ document.getElementById('ma-search-state').classList.add('hidden');
818
+ document.getElementById('ma-search-results').classList.add('hidden');
819
+ document.getElementById('ma-search-results').innerHTML = '';
820
+ maSelectedId = null;
821
+ maSearchList = [];
822
+ document.getElementById('ma-linked-badge').classList.add('hidden');
823
+ document.getElementById('manual-add-modal').classList.remove('hidden');
824
+ document.body.style.overflow = 'hidden';
825
+ loadMaCatalogs();
826
+ }
827
+
828
+ function closeManualAdd() {
829
+ document.getElementById('manual-add-modal').classList.add('hidden');
830
+ document.body.style.overflow = '';
831
+ }
832
+
833
+ function maSetType(type) {
834
+ maType = type;
835
+ document.querySelectorAll('[data-ma-type]').forEach(b => b.classList.toggle('active', b.dataset.maType === type));
836
+ document.getElementById('ma-tv-fields').classList.toggle('hidden', type !== 'tv');
837
+ }
838
+
839
+ async function maResolve() {
840
+ const first = document.querySelector('#ma-parts .ma-part-url');
841
+ const url = first ? first.value.trim() : '';
842
+ const state = document.getElementById('ma-resolve-state');
843
+ if (!url) { showToast('Paste a Telegram message link first.', 'error', 'Error'); return; }
844
+ state.textContent = 'Resolving...';
845
+ state.classList.remove('hidden');
846
+ try {
847
+ const res = await fetch('/api/media/resolve-telegram', {
848
+ method: 'POST', headers: {'Content-Type': 'application/json'},
849
+ body: JSON.stringify({ url })
850
+ });
851
+ const data = await res.json().catch(() => ({}));
852
+ if (!res.ok) throw new Error(data.detail || 'Could not resolve link');
853
+ const d = data.data || {};
854
+ document.getElementById('ma-name').value = d.name || '';
855
+ if (d.quality) {
856
+ const sel = document.getElementById('ma-quality');
857
+ const custom = document.getElementById('ma-quality-custom');
858
+ const opt = [...sel.options].find(o => o.value.toLowerCase() === String(d.quality).toLowerCase());
859
+ if (opt) {
860
+ sel.value = opt.value;
861
+ custom.classList.add('hidden');
862
+ } else {
863
+ sel.value = '__custom';
864
+ custom.value = d.quality;
865
+ custom.classList.remove('hidden');
866
+ }
867
+ }
868
+ if (maType === 'tv') {
869
+ if (d.season != null && !document.getElementById('ma-season').value) document.getElementById('ma-season').value = d.season;
870
+ if (d.episode != null && !document.getElementById('ma-episode').value) document.getElementById('ma-episode').value = d.episode;
871
+ }
872
+ state.textContent = `Found: ${d.name || 'file'} (${d.size || '—'})`;
873
+ } catch (e) {
874
+ state.textContent = e.message || 'Could not resolve link.';
875
+ showToast(e.message || 'Could not resolve link.', 'error', 'Error');
876
+ }
877
+ }
878
+
879
+ function maQuality() {
880
+ const sel = document.getElementById('ma-quality');
881
+ if (sel.value === '__custom') return document.getElementById('ma-quality-custom').value.trim();
882
+ return sel.value;
883
+ }
884
+
885
+ async function submitManualAdd() {
886
+ const btn = document.getElementById('ma-submit');
887
+ const parts = maCollectParts();
888
+ const quality = maQuality();
889
+ const title = document.getElementById('ma-m-title').value.trim();
890
+ if (!title) { showToast('Enter a title.', 'error', 'Error'); return; }
891
+ if (!parts.length) { showToast('Paste at least one Telegram message link.', 'error', 'Error'); return; }
892
+ if (!quality) { showToast('Select a quality.', 'error', 'Error'); return; }
893
+
894
+ const payload = {
895
+ media_type: maType,
896
+ stream: { quality, name: document.getElementById('ma-name').value.trim() || undefined, parts },
897
+ catalog_ids: getMaSelectedCatalogIds(),
898
+ manual_metadata: {
899
+ title,
900
+ year: document.getElementById('ma-m-year').value.trim(),
901
+ rate: document.getElementById('ma-m-rating').value.trim(),
902
+ genres: document.getElementById('ma-m-genres').value.trim(),
903
+ description: document.getElementById('ma-m-description').value.trim(),
904
+ poster: document.getElementById('ma-m-poster').value.trim(),
905
+ backdrop: document.getElementById('ma-m-backdrop').value.trim(),
906
+ }
907
+ };
908
+
909
+ if (maSelectedId) payload.selected_id = maSelectedId;
910
+
911
+ if (maType === 'tv') {
912
+ const s = document.getElementById('ma-season').value.trim();
913
+ const e = document.getElementById('ma-episode').value.trim();
914
+ if (s === '' || e === '') { showToast('Season and episode are required.', 'error', 'Error'); return; }
915
+ payload.season_number = Number(s);
916
+ payload.episode_number = Number(e);
917
+ payload.episode_title = document.getElementById('ma-episode-title').value.trim() || undefined;
918
+ }
919
+
920
+ btn.disabled = true;
921
+ try {
922
+ const res = await fetch('/api/media/manual-add', {
923
+ method: 'POST', headers: {'Content-Type': 'application/json'},
924
+ body: JSON.stringify(payload)
925
+ });
926
+ const data = await res.json().catch(() => ({}));
927
+ if (!res.ok) throw new Error(data.detail || 'Failed to add content');
928
+ showToast(data.message || 'Added successfully.', 'success', 'Added');
929
+ closeManualAdd();
930
+ if (data.media_type === mediaType) {
931
+ loadMedia(currentPage, currentSearch);
932
+ }
933
+ } catch (e) {
934
+ showToast(e.message || 'Failed to add content.', 'error', 'Error');
935
+ } finally {
936
+ btn.disabled = false;
937
+ }
938
+ }
939
+
940
+ document.addEventListener('DOMContentLoaded', () => {
941
+ document.getElementById('ma-quality').addEventListener('change', (e) => {
942
+ document.getElementById('ma-quality-custom').classList.toggle('hidden', e.target.value !== '__custom');
943
+ });
944
+ });
945
+ if (new URLSearchParams(location.search).get('add') === '1') document.addEventListener('DOMContentLoaded', () => { history.replaceState(null, '', location.pathname + '?media_type=' + mediaType); openManualAdd(); });
946
+ </script>
947
+ <style>
948
+ .m-card { position: relative; min-width: 0; contain: layout paint style; }
949
+ #media-grid { transition: opacity .2s var(--ease); }
950
+ #media-grid.is-busy { opacity: .45; pointer-events: none; }
951
+ .m-skel > div { aspect-ratio: 2 / 3; border-radius: 12px; }
952
+ .m-skel > p { height: .7rem; margin-top: .55rem; border-radius: 99px; width: 80%; }
953
+ .m-skel > p + p { width: 50%; margin-top: .4rem; }
954
+ .m-skel > * { background: linear-gradient(90deg, var(--card) 25%, var(--card-high) 37%, var(--card) 63%); background-size: 400% 100%; animation: m-shimmer 1.3s ease infinite; }
955
+ @keyframes m-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
956
+ .m-del { position: absolute; z-index: 3; top: 6px; left: 6px; width: 30px; height: 30px; display: grid; place-items: center; border-radius: 99px; border: 0; font-size: .75rem; color: #fff; background: rgba(0,0,0,.72); opacity: 0; transition: opacity .18s var(--ease), background-color .18s var(--ease); cursor: pointer; }
957
+ .m-card:hover .m-del, .m-del:focus-visible { opacity: 1; }
958
+ .m-del:hover { background: var(--danger); }
959
+ @media (hover: none) { .m-del { opacity: 1; width: 26px; height: 26px; } }
960
+ .m-poster { position: relative; display: block; aspect-ratio: 2 / 3; border-radius: 12px; overflow: hidden; background: var(--card-high); }
961
+ .m-poster img { position: relative; z-index: 1; width: 100%; height: 100%; object-fit: cover; transition: transform .4s var(--ease); }
962
+ @media (hover: none) { .m-poster:hover img { transform: none; } }
963
+ .m-poster:hover img { transform: scale(1.04); }
964
+ .m-fallback { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-sec); font-size: 1.5rem; }
965
+ .m-rating, .m-custom, .q-chip { position: absolute; z-index: 2; padding: 2px 7px; border-radius: 99px; font-size: .72rem; line-height: 1.4; color: #fff; background: rgba(0,0,0,.72); }
966
+ .m-rating { top: 6px; right: 6px; font-size: .66rem; padding: 1px 6px; }
967
+ .m-custom { bottom: 6px; right: 6px; background: var(--primary); color: var(--on-primary); }
968
+ .q-chip { position: static; font-size: .62rem; padding: 1px 6px; }
969
+ .m-poster > div { z-index: 2; }
970
  </style>
971
  {% endblock %}
Backend/fastapi/templates/request_public.html ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Request a Title{% endblock %}
3
+
4
+ {% block content %}
5
+ <style>
6
+ .rp-shell { max-width: 1040px; margin: 0 auto; }
7
+ .rp-brand { display: flex; align-items: center; gap: .6rem; font-weight: 600; margin-bottom: 2.5rem; }
8
+ .rp-hero { padding: .5rem 0 1rem; }
9
+ .rp-hero h1 { font-size: clamp(1.75rem, 4.5vw, 2.5rem); font-weight: 600; letter-spacing: -0.025em; line-height: 1.1; }
10
+ .rp-hero p { color: var(--text-sec); margin-top: .6rem; font-size: .98rem; max-width: 34rem; }
11
+ .rp-search { position: relative; display: flex; max-width: 640px; margin-top: 1.5rem; }
12
+ .rp-search input { flex: 1; min-width: 0; background: var(--card); border: 1px solid var(--border); color: var(--text); border-radius: 9999px; padding: .9rem 4rem .9rem 1.25rem; font-size: 1rem; outline: none; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
13
+ .rp-search input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
14
+ .rp-search button { position: absolute; right: 5px; top: 5px; bottom: 5px; aspect-ratio: 1; background: var(--primary); color: var(--on-primary); border: 0; border-radius: 9999px; cursor: pointer; transition: transform .12s var(--ease); }
15
+ .rp-search button:active { transform: scale(.94); }
16
+ .rp-hint { color: var(--text-sec); font-size: .82rem; margin-top: .7rem; }
17
+ .rp-hint b { color: var(--text); font-weight: 500; }
18
+ .rp-section-title { font-size: .72rem; font-weight: 500; letter-spacing: .1em; text-transform: uppercase; color: var(--text-sec); margin: 2.5rem .25rem .75rem; display: flex; align-items: center; gap: .5rem; }
19
+ .rp-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 1.25rem 1rem; }
20
+ .rp-card { min-width: 0; display: flex; flex-direction: column; }
21
+ .rp-poster { position: relative; aspect-ratio: 2/3; border-radius: 14px; overflow: hidden; background: var(--card-high); }
22
+ .rp-poster img { width: 100%; height: 100%; object-fit: cover; display: block; transition: transform .4s var(--ease); }
23
+ .rp-card:hover .rp-poster img { transform: scale(1.04); }
24
+ .rp-poster .noimg { position: absolute; inset: 0; display: grid; place-items: center; font-size: 1.5rem; color: var(--text-sec); }
25
+ .rp-type, .rp-count { position: absolute; top: 6px; padding: 2px 8px; border-radius: 9999px; font-size: .72rem; line-height: 1.4; background: rgba(0,0,0,.72); color: #fff; }
26
+ .rp-type { left: 6px; }
27
+ .rp-count { right: 6px; }
28
+ .rp-body { padding: .6rem .1rem 0; display: flex; flex-direction: column; gap: .6rem; flex: 1; }
29
+ .rp-title { font-weight: 500; font-size: .92rem; line-height: 1.3; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
30
+ .rp-btn { margin-top: auto; border: 1px solid var(--border); border-radius: 9999px; padding: .45rem; font-size: .84rem; cursor: pointer; background: transparent; color: var(--text); transition: background-color .15s var(--ease), color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); }
31
+ .rp-btn:hover { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
32
+ .rp-btn:active { transform: scale(.96); }
33
+ .rp-btn:disabled { opacity: .5; cursor: default; }
34
+ .rp-empty { color: var(--text-sec); padding: 2rem .25rem; }
35
+ .rp-spinner { color: var(--text-sec); padding: 2rem .25rem; }
36
+ </style>
37
+
38
+ <div class="rp-shell">
39
+ <div class="rp-brand"><span class="brand-mark"><i class="fa-solid fa-play"></i></span>TG Stremio</div>
40
+ <div class="rp-hero">
41
+ <h1>Request a movie or show</h1>
42
+ <p>Can't find something? Search below and send a request — we'll try to add it.</p>
43
+ <form class="rp-search" onsubmit="doSearch(event)">
44
+ <input id="rp-q" type="search" enterkeyhint="search" placeholder="Search by name, IMDb ID (tt…) or TMDB ID" autocomplete="off">
45
+ <button type="submit" aria-label="Search"><i class="fa-solid fa-magnifying-glass"></i></button>
46
+ </form>
47
+ <p class="rp-hint">Examples: <b>Inception</b> · <b>tt1375666</b> · <b>27205</b></p>
48
+ </div>
49
+
50
+ <div id="rp-results-wrap" style="display:none">
51
+ <div class="rp-section-title">Search results</div>
52
+ <div id="rp-results" class="rp-grid"></div>
53
+ </div>
54
+
55
+ <div id="rp-popular-wrap">
56
+ <div class="rp-section-title">Most requested</div>
57
+ <div id="rp-popular" class="rp-grid"></div>
58
+ </div>
59
+ </div>
60
+
61
+ <script>
62
+ let searchResults = [];
63
+
64
+ function esc(s) {
65
+ return String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;')
66
+ .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
67
+ }
68
+
69
+ function posterHtml(r, extra) {
70
+ const img = r.poster ? `<img src="${esc(r.poster)}" loading="lazy" alt="">`
71
+ : `<div class="noimg"><i class="fa-solid fa-film"></i></div>`;
72
+ const type = r.media_type === 'tv' ? 'TV' : 'Movie';
73
+ return `<div class="rp-poster">${img}<span class="rp-type">${type}</span>${extra || ''}</div>`;
74
+ }
75
+
76
+ function resultCard(r, idx) {
77
+ const yr = r.year ? ` (${esc(r.year)})` : '';
78
+ return `<div class="rp-card">
79
+ ${posterHtml(r)}
80
+ <div class="rp-body">
81
+ <div class="rp-title">${esc(r.title)}${yr}</div>
82
+ <button class="rp-btn" onclick="sendRequest(${idx})"><i class="fa-solid fa-paper-plane"></i> Request</button>
83
+ </div>
84
+ </div>`;
85
+ }
86
+
87
+ function popularCard(r) {
88
+ const yr = r.year ? ` (${esc(r.year)})` : '';
89
+ const count = `<span class="rp-count"><i class="fa-solid fa-user-group"></i> ${esc(r.request_count || 0)}</span>`;
90
+ return `<div class="rp-card">
91
+ ${posterHtml(r, count)}
92
+ <div class="rp-body"><div class="rp-title">${esc(r.title)}${yr}</div></div>
93
+ </div>`;
94
+ }
95
+
96
+ async function doSearch(e) {
97
+ if (e) e.preventDefault();
98
+ const q = document.getElementById('rp-q').value.trim();
99
+ if (q.length < 2) { showToast('Type at least 2 characters.', 'info'); return; }
100
+ const wrap = document.getElementById('rp-results-wrap');
101
+ const box = document.getElementById('rp-results');
102
+ wrap.style.display = '';
103
+ box.innerHTML = `<div class="rp-spinner" style="grid-column:1/-1"><i class="fa-solid fa-spinner fa-spin"></i> Searching…</div>`;
104
+ try {
105
+ const res = await fetch('/api/request/search?q=' + encodeURIComponent(q));
106
+ const data = await res.json();
107
+ searchResults = data.data || [];
108
+ box.innerHTML = searchResults.length
109
+ ? searchResults.map((r, i) => resultCard(r, i)).join('')
110
+ : `<div class="rp-empty" style="grid-column:1/-1">No matches found. Try a different name or an IMDb/TMDB ID.</div>`;
111
+ } catch (err) {
112
+ box.innerHTML = `<div class="rp-empty" style="grid-column:1/-1;color:var(--danger)">Search failed. Please try again.</div>`;
113
+ }
114
+ }
115
+
116
+ async function sendRequest(idx) {
117
+ const r = searchResults[idx];
118
+ if (!r) return;
119
+ try {
120
+ const res = await fetch('/api/request/submit', {
121
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
122
+ body: JSON.stringify({
123
+ media_type: r.media_type, tmdb_id: r.tmdb_id, imdb_id: r.imdb_id || null,
124
+ title: r.title, year: r.year, poster: r.poster,
125
+ }),
126
+ });
127
+ const data = await res.json();
128
+ const map = {
129
+ created: ['Request submitted! We\'ll try to add it soon.', 'success', 'Requested'],
130
+ added: ['Added your vote — this was already requested.', 'success', 'Requested'],
131
+ reopened: ['Request re-opened. Thanks!', 'success', 'Requested'],
132
+ already_available: ['Good news — this is already in the library!', 'info', 'Available'],
133
+ banned: ['This title has been banned and can\'t be requested.', 'error', 'Not allowed'],
134
+ invalid: ['Could not identify this title.', 'error', 'Error'],
135
+ };
136
+ const m = map[data.reason] || (data.ok ? ['Request submitted!', 'success', 'Requested']
137
+ : ['Something went wrong.', 'error', 'Error']);
138
+ showToast(m[0], m[1], m[2]);
139
+ if (data.ok) loadPopular();
140
+ } catch (err) {
141
+ showToast('Request failed. Please try again.', 'error', 'Error');
142
+ }
143
+ }
144
+
145
+ async function loadPopular() {
146
+ const box = document.getElementById('rp-popular');
147
+ const wrap = document.getElementById('rp-popular-wrap');
148
+ try {
149
+ const res = await fetch('/api/request/popular');
150
+ const data = await res.json();
151
+ const items = data.data || [];
152
+ if (!items.length) { wrap.style.display = 'none'; return; }
153
+ wrap.style.display = '';
154
+ box.innerHTML = items.map(popularCard).join('');
155
+ } catch (err) {
156
+ wrap.style.display = 'none';
157
+ }
158
+ }
159
+
160
+ document.addEventListener('DOMContentLoaded', loadPopular);
161
+ </script>
162
+ {% endblock %}
Backend/fastapi/templates/requests_manage.html ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Content Requests - Telegram Stremio{% endblock %}
3
+
4
+ {% block content %}
5
+ <style>
6
+ .rq-tabs { display: inline-flex; padding: 4px; gap: 2px; border-radius: 9999px; background: var(--card); border: 1px solid var(--border); }
7
+ .rq-tab { padding: .45rem 1rem; border-radius: 9999px; cursor: pointer; font-size: .88rem; color: var(--text-sec); background: transparent; border: 0; transition: background-color .2s var(--ease), color .2s var(--ease); }
8
+ .rq-tab span { margin-left: .3rem; font-size: .78rem; opacity: .75; }
9
+ .rq-tab.active { background: var(--card-high); color: var(--primary); }
10
+ .rq-filters { display: flex; gap: .4rem; flex-wrap: wrap; }
11
+ .rq-chip { padding: .35rem .85rem; border-radius: 9999px; border: 1px solid var(--border); cursor: pointer; font-size: .82rem; color: var(--text-sec); background: transparent; transition: all .15s var(--ease); }
12
+ .rq-chip:hover { color: var(--text); }
13
+ .rq-chip.active { background: color-mix(in srgb, var(--primary) 12%, transparent); color: var(--primary); border-color: color-mix(in srgb, var(--primary) 50%, var(--border)); }
14
+ .rq-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 1.25rem 1rem; }
15
+ .rq-card { min-width: 0; display: flex; flex-direction: column; }
16
+ .rq-poster { position: relative; aspect-ratio: 2/3; border-radius: 14px; overflow: hidden; background: var(--card-high); }
17
+ .rq-poster img { width: 100%; height: 100%; object-fit: cover; display: block; }
18
+ .rq-poster .noimg { position: absolute; inset: 0; display: grid; place-items: center; font-size: 1.5rem; color: var(--text-sec); }
19
+ .rq-count, .rq-badge { position: absolute; top: 6px; padding: 2px 8px; border-radius: 9999px; font-size: .72rem; line-height: 1.4; background: rgba(0,0,0,.72); color: #fff; }
20
+ .rq-count { left: 6px; }
21
+ .rq-badge { right: 6px; text-transform: capitalize; }
22
+ .b-pending { background: var(--warn); color: #1a1405; }
23
+ .b-uploaded { background: var(--ok); color: #0b1a07; }
24
+ .b-denied { background: rgba(0,0,0,.72); }
25
+ .b-banned { background: var(--danger); color: #fff; }
26
+ .rq-body { padding: .6rem .1rem .5rem; display: flex; flex-direction: column; gap: .1rem; min-width: 0; }
27
+ .rq-title { font-weight: 500; font-size: .92rem; line-height: 1.3; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
28
+ .rq-id { font-size: .75rem; color: var(--text-sec); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
29
+ .rq-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .35rem; margin-top: auto; }
30
+ .rq-btn { border: 1px solid var(--border); border-radius: 9999px; padding: .4rem .3rem; font-size: .78rem; cursor: pointer; background: transparent; color: var(--text); display: flex; align-items: center; justify-content: center; gap: .3rem; white-space: nowrap; transition: background-color .15s var(--ease), transform .12s var(--ease); }
31
+ .rq-btn:hover { background: var(--card-high); }
32
+ .rq-btn:active { transform: scale(.96); }
33
+ .rq-btn.wide { grid-column: 1 / -1; }
34
+ .btn-up i { color: var(--ok); }
35
+ .btn-deny i { color: var(--text-sec); }
36
+ .btn-ban i, .btn-del i { color: var(--danger); }
37
+ .btn-reopen i { color: var(--warn); }
38
+ .rq-empty { text-align: center; padding: 3.5rem 1rem; color: var(--text-sec); }
39
+ .rq-pager { display: flex; align-items: center; justify-content: center; gap: .75rem; margin-top: 2rem; }
40
+ .rq-pager button { min-width: 2.4rem; height: 2.4rem; padding: 0 .9rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px; cursor: pointer; }
41
+ .rq-pager button:hover:not(:disabled) { background: var(--card-high); }
42
+ .rq-pager button:disabled { opacity: .35; cursor: not-allowed; }
43
+ .rq-pager .pageinfo { color: var(--text-sec); font-size: .85rem; }
44
+ </style>
45
+
46
+ <div class="rq-shell">
47
+ <header class="page-head">
48
+ <div>
49
+ <h1 class="page-title">Requests</h1>
50
+ <p class="page-sub">Titles your users asked for on the public request page</p>
51
+ </div>
52
+ <div class="page-actions">
53
+ <button onclick="loadRequests()" class="btn-ghost px-4 py-2 text-sm"><i class="fa-solid fa-rotate"></i> Refresh</button>
54
+ <a href="/request" target="_blank" rel="noopener" class="btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-arrow-up-right-from-square"></i> Public page</a>
55
+ </div>
56
+ </header>
57
+
58
+ <div class="flex flex-col sm:flex-row sm:items-center gap-3 mb-6">
59
+ <div class="rq-tabs shrink-0 self-start">
60
+ <button class="rq-tab active" data-type="movie" onclick="setType(this,'movie')">Movies<span id="cnt-movie">0</span></button>
61
+ <button class="rq-tab" data-type="tv" onclick="setType(this,'tv')">TV shows<span id="cnt-tv">0</span></button>
62
+ </div>
63
+ <div class="rq-filters">
64
+ <button class="rq-chip active" data-status="" onclick="setStatusFilter(this,'')">All</button>
65
+ <button class="rq-chip" data-status="pending" onclick="setStatusFilter(this,'pending')">Pending</button>
66
+ <button class="rq-chip" data-status="uploaded" onclick="setStatusFilter(this,'uploaded')">Uploaded</button>
67
+ <button class="rq-chip" data-status="denied" onclick="setStatusFilter(this,'denied')">Denied</button>
68
+ <button class="rq-chip" data-status="banned" onclick="setStatusFilter(this,'banned')">Banned</button>
69
+ </div>
70
+ </div>
71
+
72
+ <div id="rq-grid" class="rq-grid"></div>
73
+ <div id="rq-pager" class="rq-pager"></div>
74
+ </div>
75
+
76
+ <script>
77
+ let allRequests = [];
78
+ let curType = 'movie';
79
+ let curStatus = '';
80
+ let curPage = 1;
81
+ const PER_PAGE = 18;
82
+
83
+ function esc(s) {
84
+ return String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;')
85
+ .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
86
+ }
87
+
88
+ function setType(btn, type) {
89
+ curType = type;
90
+ curPage = 1;
91
+ document.querySelectorAll('.rq-tab').forEach(t => t.classList.remove('active'));
92
+ btn.classList.add('active');
93
+ render();
94
+ }
95
+ function setStatusFilter(btn, status) {
96
+ curStatus = status;
97
+ curPage = 1;
98
+ document.querySelectorAll('.rq-chip').forEach(t => t.classList.remove('active'));
99
+ btn.classList.add('active');
100
+ render();
101
+ }
102
+ function goPage(delta) {
103
+ curPage += delta;
104
+ render();
105
+ window.scrollTo({ top: 0, behavior: 'smooth' });
106
+ }
107
+
108
+ function idLine(r) {
109
+ if (r.tmdb_id && r.imdb_id) return `TMDB ${esc(r.tmdb_id)} · ${esc(r.imdb_id)}`;
110
+ if (r.tmdb_id) return `TMDB ${esc(r.tmdb_id)}`;
111
+ if (r.imdb_id) return esc(r.imdb_id);
112
+ return '';
113
+ }
114
+
115
+ function cardHtml(r) {
116
+ const poster = r.poster
117
+ ? `<img src="${esc(r.poster)}" loading="lazy" alt="">`
118
+ : `<div class="noimg"><i class="fa-solid fa-film"></i></div>`;
119
+ const yr = r.year ? ` (${esc(r.year)})` : '';
120
+ let actions = '';
121
+ if (r.status !== 'uploaded')
122
+ actions += `<button class="rq-btn btn-up" onclick="setStatus('${r._id}','uploaded')"><i class="fa-solid fa-check"></i> Uploaded</button>`;
123
+ if (r.status !== 'denied')
124
+ actions += `<button class="rq-btn btn-deny" onclick="setStatus('${r._id}','denied')"><i class="fa-solid fa-xmark"></i> Deny</button>`;
125
+ if (r.status !== 'banned')
126
+ actions += `<button class="rq-btn btn-ban" onclick="setStatus('${r._id}','banned')"><i class="fa-solid fa-ban"></i> Ban</button>`;
127
+ if (r.status !== 'pending')
128
+ actions += `<button class="rq-btn btn-reopen" onclick="setStatus('${r._id}','pending')"><i class="fa-solid fa-rotate-left"></i> Reopen</button>`;
129
+ actions += `<button class="rq-btn btn-del wide" onclick="removeRequest('${r._id}')"><i class="fa-solid fa-trash"></i> Delete</button>`;
130
+
131
+ return `<div class="rq-card">
132
+ <div class="rq-poster">
133
+ ${poster}
134
+ <span class="rq-count"><i class="fa-solid fa-user-group"></i> ${esc(r.request_count || 0)}</span>
135
+ <span class="rq-badge b-${esc(r.status)}">${esc(r.status)}</span>
136
+ </div>
137
+ <div class="rq-body">
138
+ <div class="rq-title">${esc(r.title)}${yr}</div>
139
+ <div class="rq-id">${idLine(r)}</div>
140
+ </div>
141
+ <div class="rq-actions">${actions}</div>
142
+ </div>`;
143
+ }
144
+
145
+ function render() {
146
+ const movies = allRequests.filter(r => r.media_type === 'movie');
147
+ const tv = allRequests.filter(r => r.media_type === 'tv');
148
+ document.getElementById('cnt-movie').textContent = movies.length;
149
+ document.getElementById('cnt-tv').textContent = tv.length;
150
+
151
+ let items = curType === 'tv' ? tv : movies;
152
+ if (curStatus) items = items.filter(r => r.status === curStatus);
153
+
154
+ const totalPages = Math.max(1, Math.ceil(items.length / PER_PAGE));
155
+ if (curPage > totalPages) curPage = totalPages;
156
+ if (curPage < 1) curPage = 1;
157
+ const pageItems = items.slice((curPage - 1) * PER_PAGE, curPage * PER_PAGE);
158
+
159
+ const grid = document.getElementById('rq-grid');
160
+ grid.innerHTML = pageItems.length
161
+ ? pageItems.map(cardHtml).join('')
162
+ : `<div class="rq-empty" style="grid-column:1/-1"><span class="mx-auto mb-3 grid place-items-center w-12 h-12 rounded-full bg-card-high"><i class="fa-solid fa-inbox"></i></span><p>No ${curStatus || ''} ${curType === 'tv' ? 'TV' : 'movie'} requests.</p></div>`;
163
+
164
+ const pager = document.getElementById('rq-pager');
165
+ if (items.length > PER_PAGE) {
166
+ pager.innerHTML =
167
+ `<button onclick="goPage(-1)" ${curPage <= 1 ? 'disabled' : ''}><i class="fa-solid fa-chevron-left"></i> Prev</button>
168
+ <span class="pageinfo">Page ${curPage} of ${totalPages} · ${items.length} total</span>
169
+ <button onclick="goPage(1)" ${curPage >= totalPages ? 'disabled' : ''}>Next <i class="fa-solid fa-chevron-right"></i></button>`;
170
+ } else {
171
+ pager.innerHTML = '';
172
+ }
173
+ }
174
+
175
+ async function loadRequests() {
176
+ const grid = document.getElementById('rq-grid');
177
+ grid.innerHTML = `<p class="muted text-sm" style="grid-column:1/-1">Loading…</p>`;
178
+ try {
179
+ const res = await fetch('/api/admin/requests');
180
+ const data = await res.json();
181
+ if (data.status !== 'success') throw new Error(data.message || 'Failed');
182
+ allRequests = data.data || [];
183
+ render();
184
+ } catch (e) {
185
+ grid.innerHTML = `<p style="color:var(--danger);grid-column:1/-1">Failed to load requests.</p>`;
186
+ }
187
+ }
188
+
189
+ async function setStatus(id, status) {
190
+ try {
191
+ const res = await fetch('/api/admin/requests/' + id, {
192
+ method: 'PATCH', headers: { 'Content-Type': 'application/json' },
193
+ body: JSON.stringify({ status }),
194
+ });
195
+ const data = await res.json();
196
+ if (!res.ok) throw new Error(data.detail || 'Update failed');
197
+ const item = allRequests.find(r => r._id === id);
198
+ if (item) item.status = status;
199
+ render();
200
+ showToast('Marked ' + status + '.', 'success', 'Updated');
201
+ } catch (e) {
202
+ showToast(e.message || 'Update failed', 'error', 'Error');
203
+ }
204
+ }
205
+
206
+ async function removeRequest(id) {
207
+ try {
208
+ const res = await fetch('/api/admin/requests/' + id, { method: 'DELETE' });
209
+ const data = await res.json().catch(() => ({}));
210
+ if (!res.ok) throw new Error(data.detail || 'Delete failed');
211
+ allRequests = allRequests.filter(r => r._id !== id);
212
+ render();
213
+ showToast('Request deleted.', 'success', 'Deleted');
214
+ } catch (e) {
215
+ showToast(e.message || 'Delete failed', 'error', 'Error');
216
+ }
217
+ }
218
+
219
+ document.addEventListener('DOMContentLoaded', loadRequests);
220
+ </script>
221
+ {% endblock %}
Backend/fastapi/templates/settings.html CHANGED
The diff for this file is too large to render. See raw diff
 
Backend/fastapi/templates/stremio_configure.html ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" class="{{ 'dark' if theme.is_dark else 'light' }}">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Install Telegram Stremio Addon</title>
7
+
8
+ <meta name="theme-color" content="{{ theme.colors.background }}">
9
+ <link rel="icon" type="image/svg+xml" href="/pwa-icon.svg">
10
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
11
+ <link rel="preconnect" href="https://fonts.googleapis.com">
12
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
13
+ <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
14
+
15
+ <style>
16
+ :root {
17
+ color-scheme: {{ 'dark' if theme.is_dark else 'light' }};
18
+ --primary: {{ theme.colors.primary }};
19
+ --on-primary: {{ theme.colors.on_primary }};
20
+ --card-high: {{ theme.colors.card_high }};
21
+ --ok: {{ theme.colors.ok }};
22
+ --danger: {{ theme.colors.danger }};
23
+ --secondary: var(--primary);
24
+ --accent: var(--primary);
25
+ --bg: {{ theme.colors.background }};
26
+ --card: {{ theme.colors.card }};
27
+ --border: {{ theme.colors.border }};
28
+ --text: {{ theme.colors.text }};
29
+ --text-sec: {{ theme.colors.text_secondary }};
30
+ --surface: color-mix(in srgb, var(--text) 5%, transparent);
31
+ --surface-2: color-mix(in srgb, var(--text) 9%, transparent);
32
+ --hairline: var(--border);
33
+ --hairline-strong: color-mix(in srgb, var(--text) 20%, transparent);
34
+ --ring: color-mix(in srgb, var(--primary) 35%, transparent);
35
+ --shadow-color: {{ '0,0,0' if theme.is_dark else '15,23,42' }};
36
+ }
37
+
38
+ * { box-sizing: border-box; margin: 0; padding: 0; }
39
+ button, input, select, textarea { font-family: inherit; }
40
+
41
+ body {
42
+ font-family: 'Space Grotesk', system-ui, -apple-system, 'Segoe UI', sans-serif;
43
+ -webkit-font-smoothing: antialiased;
44
+ background-color: var(--bg);
45
+ color: var(--text);
46
+ min-height: 100vh;
47
+ display: flex;
48
+ align-items: flex-start;
49
+ justify-content: center;
50
+ padding: clamp(16px, 4vw, 40px);
51
+ }
52
+
53
+ .wrap { width: 100%; max-width: 960px; margin: auto; }
54
+ .layout { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); align-items: start; }
55
+ .layout > * { min-width: 0; }
56
+ @media (min-width: 860px) { .layout { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } }
57
+
58
+
59
+ .card {
60
+ background: var(--card);
61
+ border: 1px solid var(--border);
62
+ border-radius: 20px;
63
+ padding: clamp(24px, 4vw, 36px);
64
+ width: 100%;
65
+ text-align: center;
66
+ }
67
+
68
+ .brand { display: flex; align-items: center; justify-content: center; gap: 12px; margin-bottom: 20px; }
69
+ .brand-logo {
70
+ width: 44px; height: 44px; border-radius: 14px;
71
+ background: var(--primary); color: var(--on-primary);
72
+ display: flex; align-items: center; justify-content: center;
73
+ font-size: 1rem;
74
+ }
75
+ .brand-name {
76
+ font-size: 1.4rem; font-weight: 600; letter-spacing: -0.01em; color: var(--text);
77
+ }
78
+
79
+ h1 { font-size: 1.15rem; font-weight: 600; color: var(--text); margin-bottom: 6px; }
80
+ .sub-title { color: var(--text-sec); font-size: 0.85rem; margin-bottom: 26px; line-height: 1.5; }
81
+
82
+ .info-row {
83
+ display: flex; justify-content: space-between; align-items: center;
84
+ background: var(--surface); border: 1px solid var(--hairline);
85
+ border-radius: 0.85rem; padding: 12px 16px; margin-bottom: 10px; font-size: 0.88rem;
86
+ }
87
+ .info-label { color: var(--text-sec); font-weight: 500; }
88
+ .info-val { font-weight: 600; color: var(--text); }
89
+ .status-badge {
90
+ display: inline-flex; align-items: center; gap: 0.35rem;
91
+ padding: 3px 12px; border-radius: 9999px; font-size: 0.78rem; font-weight: 600;
92
+ background: color-mix(in srgb, {{ 'var(--ok)' if status_text == 'Active' else 'var(--danger)' }} 14%, transparent); color: {{ 'var(--ok)' if status_text == 'Active' else 'var(--danger)' }};
93
+ }
94
+
95
+ .btn-install {
96
+ display: flex; align-items: center; justify-content: center; gap: 0.6rem;
97
+ width: 100%; margin: 26px 0 12px;
98
+ background: var(--primary);
99
+ color: var(--on-primary); font-weight: 500; font-size: 0.98rem;
100
+ padding: 13px 24px; border-radius: 9999px; border: none;
101
+ cursor: pointer; text-decoration: none;
102
+ transition: filter .2s ease, transform .12s ease;
103
+ }
104
+ .btn-install:hover { filter: brightness(1.08); }
105
+ .btn-install:active { transform: scale(.98); }
106
+
107
+ .btn-web {
108
+ display: block; color: var(--primary); font-size: 0.82rem;
109
+ font-weight: 600; text-decoration: none; margin-bottom: 22px;
110
+ }
111
+ .btn-web:hover { text-decoration: underline; }
112
+
113
+ .steps {
114
+ background: var(--surface); border: 1px solid var(--hairline);
115
+ border-radius: 0.85rem; padding: 14px 18px; margin: 16px 0;
116
+ text-align: left; font-size: 0.85rem; color: var(--text-sec);
117
+ }
118
+ .steps b { color: var(--text); }
119
+ .steps ol { margin-top: 8px; margin-left: 18px; line-height: 1.9; }
120
+
121
+ .url-box {
122
+ background: color-mix(in srgb, var(--bg) 70%, var(--card));
123
+ border: 1px solid var(--hairline); border-radius: 0.7rem;
124
+ padding: 10px 14px; font-family: 'JetBrains Mono', ui-monospace, monospace;
125
+ font-size: 0.72rem; color: var(--text-sec);
126
+ word-break: break-all; text-align: left; margin-top: 16px;
127
+ }
128
+
129
+ .btn-copy {
130
+ margin-top: 10px; width: 100%; padding: 10px;
131
+ background: var(--surface); border: 1px solid var(--hairline); color: var(--text-sec);
132
+ border-radius: 9999px; cursor: pointer; font-size: 0.85rem; font-weight: 500;
133
+ transition: background .2s ease, color .2s ease, border-color .2s ease;
134
+ }
135
+ .btn-copy:hover { background: var(--surface-2); color: var(--text); border-color: var(--hairline-strong); }
136
+ </style>
137
+ <script>
138
+ /* Clipboard API needs HTTPS; fall back to execCommand on plain-HTTP LAN access */
139
+ if (!navigator.clipboard) Object.defineProperty(navigator, 'clipboard', { value: { writeText: t => new Promise((ok, fail) => {
140
+ const a = document.createElement('textarea');
141
+ a.value = t; a.style.cssText = 'position:fixed;opacity:0';
142
+ document.body.appendChild(a); a.select();
143
+ const done = document.execCommand('copy'); a.remove();
144
+ done ? ok() : fail(new Error('Copy failed'));
145
+ }) } });
146
+ </script>
147
+ </head>
148
+ <body>
149
+ <div class="wrap">
150
+ <div class="layout">
151
+ <div class="card">
152
+ <div class="brand">
153
+ <div class="brand-logo"><i class="fa-solid fa-play"></i></div>
154
+ <span class="brand-name">TG Stremio</span>
155
+ </div>
156
+
157
+ <h1>Install / Update Addon</h1>
158
+ <p class="sub-title">Add or refresh your personal Telegram library inside Stremio.</p>
159
+
160
+ <div class="info-row">
161
+ <span class="info-label">User</span>
162
+ <span class="info-val">{{ user_name }}</span>
163
+ </div>
164
+ <div class="info-row">
165
+ <span class="info-label">Status</span>
166
+ <span class="status-badge">{{ status_text }}</span>
167
+ </div>
168
+ <div class="info-row">
169
+ <span class="info-label">Expires</span>
170
+ <span class="info-val">{{ expiry_str }}</span>
171
+ </div>
172
+
173
+ <a href="{{ web_install_url }}" class="btn-install" target="_blank">
174
+ <i class="fa-solid fa-bolt"></i> Install / Update in Stremio
175
+ </a>
176
+
177
+ <div class="steps">
178
+ <b>Prefer to do it manually?</b>
179
+ <ol>
180
+ <li>Open Stremio and go to the <b>Add-ons</b> tab</li>
181
+ <li>Click the <b>Search / URL</b> field</li>
182
+ <li>Paste the URL below and press Enter</li>
183
+ </ol>
184
+ </div>
185
+
186
+ <div class="url-box" id="murl">{{ manifest_url }}</div>
187
+ <button onclick="copyUrl()" class="btn-copy"><i class="fa-solid fa-copy"></i> Copy URL</button>
188
+ </div>
189
+
190
+ <div class="card" style="text-align:left">
191
+ <h1 style="text-align:center"><i class="fa-solid fa-sliders"></i> Personalize</h1>
192
+ <p class="sub-title" style="text-align:center">Tune quality and catalogs for your install. Re-install after saving.</p>
193
+
194
+ <div class="cfg-block">
195
+ <div class="cfg-title">Stream quality order</div>
196
+ <div class="seg" id="cfg-sort">
197
+ <button type="button" data-val="desc" class="seg-btn active" onclick="setSort('desc')">Highest first</button>
198
+ <button type="button" data-val="asc" class="seg-btn" onclick="setSort('asc')">Lowest first</button>
199
+ </div>
200
+ </div>
201
+
202
+ <div class="cfg-block">
203
+ <div class="cfg-title">Show only these qualities</div>
204
+ <div class="chips" id="cfg-quality"></div>
205
+ <p class="cfg-hint">Leave all off to show every quality.</p>
206
+ </div>
207
+
208
+ <div class="cfg-block" id="cfg-via-block" style="display:none">
209
+ <div class="cfg-title">Stream with <span class="ob-badge"><i class="fa-solid fa-cloud"></i> Cloudflare proxy enabled</span></div>
210
+ <div class="seg" id="cfg-via">
211
+ <button type="button" data-val="bots" class="seg-btn" onclick="setVia('bots')">My bots</button>
212
+ <button type="button" data-val="cloudflare" class="seg-btn" onclick="setVia('cloudflare')">Cloudflare</button>
213
+ <button type="button" data-val="both" class="seg-btn" onclick="setVia('both')">Both</button>
214
+ </div>
215
+ </div>
216
+
217
+ <div class="cfg-block">
218
+ <div class="cfg-title">Catalogs</div>
219
+ <div id="cfg-catalogs" class="cfg-catalogs"></div>
220
+ <p class="cfg-hint">Toggle to hide a catalog; use arrows to reorder.</p>
221
+ </div>
222
+
223
+ <button onclick="saveConfig()" class="btn-install" id="cfg-save" style="margin-top:8px">
224
+ <i class="fa-solid fa-floppy-disk"></i> Save preferences
225
+ </button>
226
+ <p id="cfg-state" class="cfg-hint" style="text-align:center"></p>
227
+ </div>
228
+
229
+ <div class="card ob-card" id="ob-card" style="display:none">
230
+ <h1 style="text-align:center"><i class="fa-solid fa-robot"></i> Your own bots</h1>
231
+ <p class="sub-title" style="text-align:center">Stream through your own bots. Files are copied to your private channel and removed a day after you last watch them.</p>
232
+
233
+ <div class="steps">
234
+ <b>Setup</b>
235
+ <ol>
236
+ <li>Create a private Telegram channel</li>
237
+ <li>Add your bots to it as admins</li>
238
+ <li>Add <b id="ob-helpers"></b> as admin with <b>Post</b> and <b>Delete messages</b> rights</li>
239
+ <li>Paste the channel ID and your bot tokens below, then verify</li>
240
+ </ol>
241
+ </div>
242
+
243
+ <div class="cfg-block">
244
+ <div class="cfg-title">Channel ID</div>
245
+ <input id="ob-channel" class="ob-input" placeholder="-100xxxxxxxxxx" spellcheck="false">
246
+ </div>
247
+
248
+ <div class="cfg-block">
249
+ <div class="cfg-title">Bots</div>
250
+ <div id="ob-bots" class="cfg-catalogs"></div>
251
+ <div class="ob-add">
252
+ <input id="ob-token" class="ob-input" placeholder="Bot token (1234567890:ABC…)" spellcheck="false"
253
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addBot()}">
254
+ <button type="button" class="cfg-eye ob-plus" onclick="addBot()" aria-label="Add bot"><i class="fa-solid fa-plus"></i></button>
255
+ </div>
256
+ <p class="cfg-hint">Changes apply after you verify.</p>
257
+ </div>
258
+
259
+ <button onclick="saveBots()" class="btn-install" id="ob-save" style="margin-top:8px">
260
+ <i class="fa-solid fa-circle-check"></i> Save &amp; verify
261
+ </button>
262
+ <button onclick="disableBots()" class="btn-copy" id="ob-off" style="display:none">Turn off own bots</button>
263
+ <div id="ob-checks" class="cfg-catalogs" style="margin-top:12px"></div>
264
+ </div>
265
+ </div>
266
+ </div>
267
+
268
+ <style>
269
+ .cfg-block { margin: 14px 0; }
270
+ .cfg-title { font-size: .8rem; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; color: var(--text-sec); margin-bottom: 8px; }
271
+ .cfg-hint { font-size: .72rem; color: var(--text-sec); margin-top: 6px; }
272
+ .seg { display: flex; gap: 6px; background: var(--surface); border: 1px solid var(--hairline); border-radius: .8rem; padding: 4px; }
273
+ .seg-btn { flex: 1; padding: 9px; border-radius: .6rem; border: none; background: transparent; color: var(--text-sec); font-weight: 600; font-size: .82rem; cursor: pointer; }
274
+ .seg-btn.active { background: var(--primary); color: #fff; }
275
+ .chips { display: flex; flex-wrap: wrap; gap: 8px; }
276
+ .qchip { padding: 7px 14px; border-radius: 9999px; border: 1px solid var(--hairline); background: var(--surface); color: var(--text); font-weight: 600; font-size: .8rem; cursor: pointer; }
277
+ .qchip.on { background: linear-gradient(135deg, var(--primary), var(--accent)); color: #fff; border-color: transparent; }
278
+ .cfg-catalogs { display: flex; flex-direction: column; gap: 6px; }
279
+ .cfg-cat { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid var(--hairline); border-radius: .7rem; background: var(--surface); }
280
+ .cfg-cat.hidden-cat { opacity: .5; }
281
+ .cfg-cat .nm { flex: 1; min-width: 0; font-weight: 600; font-size: .85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
282
+ .cfg-eye, .cfg-arr { width: 30px; height: 26px; border-radius: .5rem; border: 1px solid var(--hairline); background: var(--bg); color: var(--text); cursor: pointer; font-size: .72rem; }
283
+ .cfg-arr:disabled { opacity: .35; cursor: not-allowed; }
284
+ .ob-card { text-align: left; grid-column: 1 / -1; }
285
+ .ob-input { width: 100%; padding: 10px 12px; border-radius: .7rem; border: 1px solid var(--hairline); background: var(--surface); color: var(--text); font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: .8rem; }
286
+ .ob-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
287
+ .ob-add { display: flex; gap: 8px; margin-top: 8px; }
288
+ .ob-plus { width: 42px; height: auto; flex-shrink: 0; }
289
+ .ob-badge { margin-left: 6px; padding: 2px 8px; border-radius: 9999px; font-size: .68rem; text-transform: none; letter-spacing: 0; color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
290
+ .ob-check small { display: block; font-weight: 500; color: var(--text-sec); white-space: normal; }
291
+ </style>
292
+
293
+ <script>
294
+ const QUALITIES = ['480p', '720p', '1080p', '4K'];
295
+ let cfg = { quality_sort: 'desc', quality_filter: [], hidden_catalogs: [], catalog_order: [], stream_via: 'bots' };
296
+ let cfgCatalogs = [];
297
+ let ob = { bots: [] };
298
+ let obAdd = [];
299
+ const TOKEN_RE = /^\d{5,}:[\w-]{30,}$/;
300
+
301
+ function setVia(v) {
302
+ cfg.stream_via = v;
303
+ document.querySelectorAll('#cfg-via .seg-btn').forEach(b => b.classList.toggle('active', b.dataset.val === v));
304
+ }
305
+
306
+ function renderBots() {
307
+ const rows = ob.bots.map((b, i) => `<div class="cfg-cat">
308
+ <span class="nm">@${escapeCfg(b.username || b.id)}</span>
309
+ <button class="cfg-eye" onclick="removeBot(${i})" aria-label="Remove"><i class="fa-solid fa-xmark"></i></button>
310
+ </div>`).concat(obAdd.map((t, i) => `<div class="cfg-cat">
311
+ <span class="nm">${escapeCfg(t.split(':')[0])} <small style="opacity:.6">· new</small></span>
312
+ <button class="cfg-eye" onclick="removeNew(${i})" aria-label="Remove"><i class="fa-solid fa-xmark"></i></button>
313
+ </div>`));
314
+ document.getElementById('ob-bots').innerHTML = rows.join('') || '<p class="cfg-hint">No bots added yet.</p>';
315
+ }
316
+
317
+ function renderOwnBots(v) {
318
+ ob = Object.assign({ bots: [] }, v);
319
+ obAdd = [];
320
+ document.getElementById('ob-card').style.display = ob.available ? '' : 'none';
321
+ document.getElementById('ob-helpers').textContent = (ob.helpers || []).map(h => '@' + h).join(', ');
322
+ document.getElementById('ob-channel').value = ob.channel || '';
323
+ document.getElementById('ob-off').style.display = ob.enabled ? '' : 'none';
324
+ document.getElementById('cfg-via-block').style.display = ob.enabled && ob.cloudflare ? '' : 'none';
325
+ renderBots();
326
+ }
327
+
328
+ function renderChecks(checks, ok) {
329
+ document.getElementById('ob-checks').innerHTML = checks.map(c => `<div class="cfg-cat ob-check">
330
+ <i class="fa-solid ${c.ok ? 'fa-circle-check' : 'fa-circle-xmark'}" style="color:var(${c.ok ? '--ok' : '--danger'})"></i>
331
+ <span class="nm">${escapeCfg(c.label)}${c.detail ? `<small>${escapeCfg(c.detail)}</small>` : ''}</span>
332
+ </div>`).join('') + `<p class="cfg-hint">${ok ? 'All checks passed. Your bots are on.' : 'Fix the failed checks and verify again.'}</p>`;
333
+ }
334
+
335
+ function addBot() {
336
+ const input = document.getElementById('ob-token');
337
+ const t = input.value.trim();
338
+ if (!TOKEN_RE.test(t)) { document.getElementById('ob-checks').innerHTML = '<p class="cfg-hint">That does not look like a bot token.</p>'; return; }
339
+ const id = Number(t.split(':')[0]);
340
+ if (!obAdd.includes(t) && !ob.bots.some(b => b.id === id)) obAdd.push(t);
341
+ input.value = '';
342
+ renderBots();
343
+ }
344
+
345
+ function removeBot(i) { ob.bots.splice(i, 1); renderBots(); }
346
+ function removeNew(i) { obAdd.splice(i, 1); renderBots(); }
347
+
348
+ async function saveBots() {
349
+ const btn = document.getElementById('ob-save');
350
+ const out = document.getElementById('ob-checks');
351
+ btn.disabled = true;
352
+ out.innerHTML = '<p class="cfg-hint">Verifying…</p>';
353
+ try {
354
+ const res = await fetch('own-bots', {
355
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
356
+ body: JSON.stringify({ channel: document.getElementById('ob-channel').value.trim(), keep: ob.bots.map(b => b.id), add: obAdd })
357
+ });
358
+ const data = await res.json();
359
+ if (!res.ok) throw new Error(data.detail || 'Could not verify.');
360
+ renderChecks(data.checks, data.ok);
361
+ if (data.ok) await loadConfig();
362
+ } catch (e) {
363
+ out.innerHTML = `<p class="cfg-hint">${escapeCfg(e.message || 'Could not verify.')}</p>`;
364
+ } finally {
365
+ btn.disabled = false;
366
+ }
367
+ }
368
+
369
+ async function disableBots() {
370
+ if (!confirm('Turn off your own bots?')) return;
371
+ try {
372
+ const res = await fetch('own-bots', { method: 'DELETE' });
373
+ if (!res.ok) throw new Error();
374
+ document.getElementById('ob-checks').innerHTML = '';
375
+ await loadConfig();
376
+ } catch (e) {
377
+ document.getElementById('ob-checks').innerHTML = '<p class="cfg-hint">Could not turn off. Please try again.</p>';
378
+ }
379
+ }
380
+
381
+ function setSort(v) {
382
+ cfg.quality_sort = v;
383
+ document.querySelectorAll('#cfg-sort .seg-btn').forEach(b => b.classList.toggle('active', b.dataset.val === v));
384
+ }
385
+
386
+ function renderQuality() {
387
+ document.getElementById('cfg-quality').innerHTML = QUALITIES.map(q =>
388
+ `<button type="button" class="qchip ${cfg.quality_filter.includes(q) ? 'on' : ''}" onclick="toggleQuality('${q}')">${q}</button>`
389
+ ).join('');
390
+ }
391
+
392
+ function toggleQuality(q) {
393
+ const i = cfg.quality_filter.indexOf(q);
394
+ if (i >= 0) cfg.quality_filter.splice(i, 1); else cfg.quality_filter.push(q);
395
+ renderQuality();
396
+ }
397
+
398
+ function catKey(c) { return c.key || (c.id + '::' + (c.type || 'movie')); }
399
+
400
+ function renderCatalogs() {
401
+ document.getElementById('cfg-catalogs').innerHTML = cfgCatalogs.map((c, i) => {
402
+ const key = catKey(c);
403
+ const hidden = cfg.hidden_catalogs.includes(key) || cfg.hidden_catalogs.includes(c.id);
404
+ const tag = c.type === 'series' ? 'Series' : 'Movie';
405
+ return `<div class="cfg-cat ${hidden ? 'hidden-cat' : ''}">
406
+ <button class="cfg-eye" title="Show/hide" onclick="toggleHide(${i})"><i class="fa-solid fa-eye${hidden ? '-slash' : ''}"></i></button>
407
+ <span class="nm">${escapeCfg(c.name)} <small style="opacity:.6">· ${tag}</small></span>
408
+ <button class="cfg-arr" ${i === 0 ? 'disabled' : ''} onclick="moveCat(${i}, -1)" aria-label="Move up"><i class="fa-solid fa-chevron-up"></i></button>
409
+ <button class="cfg-arr" ${i === cfgCatalogs.length - 1 ? 'disabled' : ''} onclick="moveCat(${i}, 1)" aria-label="Move down"><i class="fa-solid fa-chevron-down"></i></button>
410
+ </div>`;
411
+ }).join('') || '<p class="cfg-hint">No catalogs available.</p>';
412
+ }
413
+
414
+ function toggleHide(i) {
415
+ const key = catKey(cfgCatalogs[i]);
416
+ const at = cfg.hidden_catalogs.indexOf(key);
417
+ if (at >= 0) cfg.hidden_catalogs.splice(at, 1); else cfg.hidden_catalogs.push(key);
418
+ renderCatalogs();
419
+ }
420
+
421
+ function moveCat(i, dir) {
422
+ const j = i + dir;
423
+ if (j < 0 || j >= cfgCatalogs.length) return;
424
+ [cfgCatalogs[i], cfgCatalogs[j]] = [cfgCatalogs[j], cfgCatalogs[i]];
425
+ renderCatalogs();
426
+ }
427
+
428
+ function escapeCfg(s) {
429
+ return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
430
+ }
431
+
432
+ async function loadConfig() {
433
+ try {
434
+ const res = await fetch('addon-config');
435
+ const data = await res.json();
436
+ cfg = Object.assign(cfg, data.config || {});
437
+ cfgCatalogs = data.catalogs || [];
438
+ if (!Array.isArray(cfg.quality_filter)) cfg.quality_filter = [];
439
+ if (!Array.isArray(cfg.hidden_catalogs)) cfg.hidden_catalogs = [];
440
+ setSort(cfg.quality_sort || 'desc');
441
+ setVia(cfg.stream_via || 'bots');
442
+ renderQuality();
443
+ renderCatalogs();
444
+ renderOwnBots(data.own_bots || {});
445
+ } catch (e) {}
446
+ }
447
+
448
+ async function saveConfig() {
449
+ const btn = document.getElementById('cfg-save');
450
+ const state = document.getElementById('cfg-state');
451
+ btn.disabled = true;
452
+ cfg.catalog_order = cfgCatalogs.map(c => catKey(c));
453
+ try {
454
+ const res = await fetch('addon-config', {
455
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cfg)
456
+ });
457
+ if (!res.ok) throw new Error();
458
+ state.textContent = 'Saved! Re-install the addon to apply changes.';
459
+ } catch (e) {
460
+ state.textContent = 'Could not save. Please try again.';
461
+ } finally {
462
+ btn.disabled = false;
463
+ }
464
+ }
465
+
466
+ loadConfig();
467
+ </script>
468
+
469
+ <script>
470
+ function copyUrl() {
471
+ const url = document.getElementById('murl').textContent.trim();
472
+ navigator.clipboard.writeText(url).then(() => {
473
+ const b = document.querySelector('.btn-copy');
474
+ b.innerHTML = '<i class="fa-solid fa-check"></i> Copied!';
475
+ setTimeout(() => b.innerHTML = '<i class="fa-solid fa-copy"></i> Copy URL', 2000);
476
+ });
477
+ }
478
+ </script>
479
+ </body>
480
+ </html>
Backend/fastapi/templates/subscriptions_manage.html CHANGED
@@ -4,410 +4,107 @@
4
 
5
  {% block content %}
6
  <style>
7
- .subs-shell {
8
- display: flex;
9
- flex-direction: column;
10
- gap: 1.5rem;
11
- }
12
-
13
- .page-hero,
14
- .section-panel,
15
- .table-shell,
16
- .mobile-user-card,
17
- .empty-state,
18
- .modal-glass {
19
- background: color-mix(in srgb, var(--card) 50%, transparent);
20
- backdrop-filter: blur(20px);
21
- -webkit-backdrop-filter: blur(20px);
22
- border: 1px solid var(--border);
23
- box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
24
- }
25
-
26
- .page-hero,
27
- .section-panel,
28
- .table-shell,
29
- .empty-state {
30
- border-radius: 1.5rem;
31
- }
32
-
33
- .hero-glow {
34
- position: relative;
35
- overflow: hidden;
36
- isolation: isolate;
37
- }
38
-
39
- .hero-glow::before {
40
- content: "";
41
- position: absolute;
42
- inset: -30% auto auto -10%;
43
- width: 16rem;
44
- height: 16rem;
45
- border-radius: 9999px;
46
- background: color-mix(in srgb, var(--primary) 18%, transparent);
47
- filter: blur(50px);
48
- z-index: -1;
49
- pointer-events: none;
50
- }
51
-
52
- .hero-glow::after {
53
- content: "";
54
- position: absolute;
55
- inset: auto -5% -35% auto;
56
- width: 14rem;
57
- height: 14rem;
58
- border-radius: 9999px;
59
- background: color-mix(in srgb, var(--accent) 16%, transparent);
60
- filter: blur(50px);
61
- z-index: -1;
62
- pointer-events: none;
63
- }
64
-
65
- .section-title {
66
- color: var(--text);
67
- }
68
-
69
- .section-muted {
70
- color: var(--text-sec);
71
- }
72
-
73
- .glass-btn {
74
- border: 1px solid color-mix(in srgb, var(--border) 80%, transparent);
75
- background: color-mix(in srgb, var(--card) 92%, var(--bg));
76
- color: var(--text);
77
- transition: all 0.25s ease;
78
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.14);
79
- }
80
-
81
- .glass-btn:hover {
82
- transform: translateY(-1px);
83
- border-color: color-mix(in srgb, var(--primary) 35%, var(--border));
84
- box-shadow: 0 10px 28px rgba(0, 0, 0, 0.18);
85
- }
86
-
87
- .glass-btn-primary {
88
- background: linear-gradient(
89
- 135deg,
90
- color-mix(in srgb, var(--primary) 88%, white 8%),
91
- color-mix(in srgb, var(--accent) 82%, var(--primary) 18%)
92
- );
93
- color: white;
94
- border: 1px solid color-mix(in srgb, var(--primary) 50%, transparent);
95
- box-shadow: 0 10px 26px color-mix(in srgb, var(--primary) 22%, transparent);
96
- }
97
-
98
- .glass-btn-primary:hover {
99
- filter: brightness(1.05);
100
- box-shadow: 0 14px 34px color-mix(in srgb, var(--primary) 28%, transparent);
101
- }
102
-
103
- .glass-btn-danger {
104
- background: linear-gradient(135deg, #ef4444, #dc2626);
105
- color: #ffffff;
106
- border-color: transparent;
107
- }
108
-
109
- .glass-btn-warning {
110
- background: linear-gradient(135deg, #f59e0b, #d97706);
111
- color: #ffffff;
112
- border-color: transparent;
113
- }
114
-
115
- .glass-btn-success {
116
- background: linear-gradient(135deg, #22c55e, #16a34a);
117
- color: #ffffff;
118
- border-color: transparent;
119
- }
120
-
121
- .glass-input,
122
- .glass-select {
123
- width: 100%;
124
- border-radius: 1rem;
125
- border: 1px solid color-mix(in srgb, var(--border) 90%, transparent);
126
- background: color-mix(in srgb, var(--bg) 68%, transparent);
127
- color: var(--text);
128
- padding: 0.85rem 1rem;
129
- outline: none;
130
- transition: all 0.2s ease;
131
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.02);
132
- }
133
-
134
- .glass-input::placeholder {
135
- color: color-mix(in srgb, var(--text-sec) 85%, transparent);
136
- }
137
-
138
- .glass-input:focus,
139
- .glass-select:focus {
140
- border-color: color-mix(in srgb, var(--primary) 65%, var(--border));
141
- box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 12%, transparent);
142
- }
143
-
144
- .plan-card {
145
- position: relative;
146
- overflow: hidden;
147
- border-radius: 1.5rem;
148
- background: linear-gradient(
149
- 180deg,
150
- color-mix(in srgb, var(--card) 96%, var(--bg)),
151
- color-mix(in srgb, var(--card) 88%, var(--bg))
152
- );
153
- border: 1px solid color-mix(in srgb, var(--border) 90%, transparent);
154
- box-shadow: 0 12px 30px rgba(0,0,0,0.18);
155
- transition: transform 0.28s ease, border-color 0.28s ease, box-shadow 0.28s ease;
156
- }
157
-
158
- .plan-card::before {
159
- content: "";
160
- position: absolute;
161
- inset: -25% auto auto -5%;
162
- width: 8rem;
163
- height: 8rem;
164
- border-radius: 9999px;
165
- background: color-mix(in srgb, var(--primary) 18%, transparent);
166
- filter: blur(36px);
167
- pointer-events: none;
168
- }
169
-
170
- .plan-card:hover {
171
- transform: translateY(-4px);
172
- border-color: color-mix(in srgb, var(--primary) 30%, var(--border));
173
- box-shadow: 0 18px 42px rgba(0,0,0,0.24);
174
- }
175
-
176
- .plan-actions {
177
- opacity: 0;
178
- transform: translateY(-4px);
179
- transition: all 0.22s ease;
180
- }
181
-
182
- .plan-card:hover .plan-actions {
183
- opacity: 1;
184
- transform: translateY(0);
185
- }
186
-
187
- .metric-badge {
188
- display: inline-flex;
189
- align-items: center;
190
- gap: 0.45rem;
191
- padding: 0.45rem 0.8rem;
192
- border-radius: 9999px;
193
- font-size: 0.78rem;
194
- font-weight: 700;
195
- letter-spacing: 0.03em;
196
- border: 1px solid transparent;
197
- }
198
-
199
- .badge-active {
200
- background: color-mix(in srgb, #22c55e 16%, transparent);
201
- color: #86efac;
202
- border-color: color-mix(in srgb, #22c55e 28%, transparent);
203
- }
204
-
205
- .badge-expired {
206
- background: color-mix(in srgb, #ef4444 14%, transparent);
207
- color: #fca5a5;
208
- border-color: color-mix(in srgb, #ef4444 26%, transparent);
209
- }
210
-
211
- .table-shell {
212
- overflow: hidden;
213
- }
214
-
215
- .subs-table {
216
- width: 100%;
217
- border-collapse: separate;
218
- border-spacing: 0;
219
- }
220
-
221
- .subs-table thead th {
222
- background: color-mix(in srgb, var(--bg) 65%, transparent);
223
- color: var(--text-sec);
224
- font-size: 0.72rem;
225
- text-transform: uppercase;
226
- letter-spacing: 0.08em;
227
- border-bottom: 1px solid color-mix(in srgb, var(--border) 92%, transparent);
228
- }
229
-
230
- .subs-table tbody tr {
231
- transition: background 0.22s ease;
232
- }
233
-
234
- .subs-table tbody tr:hover {
235
- background: color-mix(in srgb, var(--primary) 6%, transparent);
236
- }
237
-
238
- .subs-table td {
239
- border-bottom: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
240
- color: var(--text);
241
- }
242
-
243
- .subs-table tbody tr:last-child td {
244
- border-bottom: none;
245
- }
246
-
247
- .action-chip {
248
- border-radius: 9999px;
249
- padding: 0.45rem 0.8rem;
250
- font-size: 0.72rem;
251
- font-weight: 700;
252
- border: 1px solid transparent;
253
- transition: all 0.2s ease;
254
- white-space: nowrap;
255
- }
256
-
257
- .action-chip:hover {
258
- transform: translateY(-1px);
259
- }
260
-
261
- .mobile-user-card {
262
- border-radius: 1.35rem;
263
- padding: 1rem;
264
- }
265
-
266
- .mobile-user-card + .mobile-user-card {
267
- margin-top: 0.9rem;
268
- }
269
-
270
- .mobile-grid {
271
- display: none;
272
- }
273
-
274
- .pagination-shell {
275
- display: flex;
276
- align-items: center;
277
- justify-content: space-between;
278
- gap: 1rem;
279
- flex-wrap: wrap;
280
- }
281
-
282
- .pagination-text {
283
- color: var(--text-sec);
284
- }
285
-
286
- .pagination-btn {
287
- min-width: 92px;
288
- }
289
-
290
- .modal-backdrop {
291
- background: rgba(4, 8, 18, 0.58);
292
- backdrop-filter: blur(10px);
293
- -webkit-backdrop-filter: blur(10px);
294
- }
295
-
296
- .modal-glass {
297
- border-radius: 1.6rem;
298
- padding: 1.4rem;
299
- border: 1px solid color-mix(in srgb, var(--border) 95%, transparent);
300
- width: min(92vw, 30rem);
301
- }
302
-
303
- .modal-field label {
304
- color: var(--text-sec);
305
- font-size: 0.82rem;
306
- font-weight: 700;
307
- margin-bottom: 0.55rem;
308
- display: block;
309
- }
310
-
311
- .text-soft {
312
- color: var(--text-sec);
313
- }
314
-
315
- .no-scrollbar::-webkit-scrollbar {
316
- display: none;
317
- }
318
-
319
- .no-scrollbar {
320
- -ms-overflow-style: none;
321
- scrollbar-width: none;
322
- }
323
-
324
- @media (max-width: 1024px) {
325
- .subs-table th,
326
- .subs-table td {
327
- padding-left: 1rem;
328
- padding-right: 1rem;
329
- }
330
- }
331
-
332
- @media (max-width: 767px) {
333
- .desktop-table-wrap {
334
- display: none;
335
- }
336
-
337
- .mobile-grid {
338
- display: block;
339
- }
340
-
341
- .page-hero {
342
- padding: 1.25rem;
343
- border-radius: 1.35rem;
344
- }
345
-
346
- .section-panel {
347
- padding: 1rem;
348
- border-radius: 1.35rem;
349
- }
350
-
351
- .pagination-shell {
352
- flex-direction: column;
353
- align-items: stretch;
354
- }
355
-
356
- .pagination-shell .controls {
357
- width: 100%;
358
- display: grid;
359
- grid-template-columns: 1fr auto 1fr;
360
- gap: 0.6rem;
361
- align-items: center;
362
- }
363
-
364
- .pagination-btn {
365
- width: 100%;
366
- }
367
-
368
- .plan-actions {
369
- opacity: 1;
370
- transform: none;
371
- }
372
- }
373
  </style>
374
 
375
- <div class="subs-shell py-2 sm:py-4">
376
  <!-- Hero -->
377
- <section class="page-hero hero-glow p-5 sm:p-6 lg:p-8">
378
- <div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
379
- <div>
380
- <div class="inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-bold tracking-[0.18em] uppercase mb-3"
381
- style="border-color: color-mix(in srgb, var(--primary) 28%, var(--border)); color: var(--text-sec); background: color-mix(in srgb, var(--primary) 10%, transparent);">
382
- <i class="fas fa-layer-group text-[11px]" style="color: var(--primary);"></i>
383
- Subscription Control Center
384
- </div>
385
- <h1 class="text-2xl sm:text-3xl lg:text-4xl font-extrabold tracking-tight section-title">
386
- Subscription Management
387
- </h1>
388
- <p class="mt-2 text-sm sm:text-base section-muted max-w-2xl">
389
- Create plans, manage users, and monitor active or expired subscriptions.
390
- </p>
391
- </div>
392
-
393
- <div class="flex flex-wrap gap-3">
394
- <button onclick="openPlanModal()" class="glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold inline-flex items-center gap-2">
395
- <i class="fas fa-plus"></i>
396
- Add Plan
397
- </button>
398
- <button onclick="fetchSubscribers()" class="glass-btn rounded-2xl px-5 py-3 text-sm font-bold inline-flex items-center gap-2">
399
- <i class="fas fa-rotate-right"></i>
400
- Refresh Users
401
- </button>
402
- </div>
403
  </div>
404
- </section>
 
 
 
 
 
405
 
406
  <!-- Plans -->
407
- <section class="section-panel p-4 sm:p-5 lg:p-6">
408
  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
409
  <div>
410
- <h2 class="text-lg sm:text-xl font-bold section-title">Subscription Plans</h2>
411
  </div>
412
  </div>
413
 
@@ -419,10 +116,10 @@
419
  </section>
420
 
421
  <!-- Users -->
422
- <section class="section-panel p-4 sm:p-5 lg:p-6">
423
  <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
424
  <div>
425
- <h2 class="text-lg sm:text-xl font-bold section-title">User Subscriptions</h2>
426
  <p class="text-sm section-muted mt-1">Search, filter, paginate, and manage subscription access.</p>
427
  </div>
428
 
@@ -482,13 +179,13 @@
482
  <div id="sub-page-info" class="pagination-text text-sm"></div>
483
  <div class="controls">
484
  <button id="sub-btn-prev" onclick="subChangePage(-1)"
485
- class="glass-btn pagination-btn rounded-xl px-4 py-2.5 text-sm font-semibold">
486
- ‹ Prev
487
  </button>
488
- <span id="sub-page-num" class="text-sm font-bold text-center section-title px-2"></span>
489
  <button id="sub-btn-next" onclick="subChangePage(1)"
490
- class="glass-btn pagination-btn rounded-xl px-4 py-2.5 text-sm font-semibold">
491
- Next ›
492
  </button>
493
  </div>
494
  </div>
@@ -500,7 +197,7 @@
500
  <div class="modal-glass">
501
  <div class="flex items-start justify-between gap-4 mb-5">
502
  <div>
503
- <h3 class="text-xl font-bold section-title" id="plan-modal-title">Add New Plan</h3>
504
  <p class="text-sm text-soft mt-1">Create or update a subscription plan.</p>
505
  </div>
506
  <button onclick="closePlanModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
@@ -517,15 +214,30 @@
517
  </div>
518
 
519
  <div class="modal-field">
520
- <label for="plan-price">Price (₹)</label>
521
  <input type="number" id="plan-price" class="glass-input" required min="0" step="0.01">
522
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
 
524
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
525
- <button type="button" onclick="closePlanModal()" class="glass-btn rounded-2xl px-5 py-3 text-sm font-bold">
526
  Cancel
527
  </button>
528
- <button type="submit" class="glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold">
529
  Save Plan
530
  </button>
531
  </div>
@@ -538,7 +250,7 @@
538
  <div class="modal-glass">
539
  <div class="flex items-start justify-between gap-4 mb-5">
540
  <div>
541
- <h3 class="text-xl font-bold section-title" id="user-modal-title">Manage User</h3>
542
  <div class="text-sm text-soft mt-1" id="user-modal-desc"></div>
543
  </div>
544
  <button onclick="closeUserModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
@@ -556,10 +268,10 @@
556
  </div>
557
 
558
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
559
- <button type="button" onclick="closeUserModal()" class="glass-btn rounded-2xl px-5 py-3 text-sm font-bold">
560
  Cancel
561
  </button>
562
- <button type="submit" class="glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold" id="btn-user-save">
563
  Confirm
564
  </button>
565
  </div>
@@ -599,6 +311,12 @@
599
  : '<span class="metric-badge badge-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>';
600
  }
601
 
 
 
 
 
 
 
602
  async function fetchPlans() {
603
  const container = document.getElementById('plans-container');
604
  container.innerHTML = `
@@ -625,9 +343,9 @@
625
  }
626
 
627
  container.innerHTML = plans.map(p => `
628
- <div class="plan-card p-5 sm:p-6">
629
  <div class="plan-actions absolute right-4 top-4 flex gap-2">
630
- <button onclick="openPlanModal('${p._id}', ${p.days}, ${p.price})"
631
  class="glass-btn rounded-full w-9 h-9 flex items-center justify-center" title="Edit plan">
632
  <i class="fas fa-pen text-sm"></i>
633
  </button>
@@ -645,8 +363,9 @@
645
 
646
  <div class="min-w-0">
647
  <div class="text-sm font-semibold section-muted">${p.days} Days Plan</div>
648
- <div class="mt-1 text-3xl font-extrabold section-title tracking-tight">₹${p.price}</div>
649
- <div class="mt-3 inline-flex items-center gap-2 text-xs font-bold rounded-full px-3 py-1"
 
650
  style="background: color-mix(in srgb, var(--accent) 12%, transparent); color: var(--text-sec); border: 1px solid color-mix(in srgb, var(--accent) 20%, transparent);">
651
  <i class="fas fa-bolt" style="color: var(--accent);"></i>
652
  Premium Access
@@ -665,10 +384,17 @@
665
  }
666
  }
667
 
668
- function openPlanModal(id = '', days = '', price = '') {
 
 
 
 
 
669
  document.getElementById('plan-id').value = id;
670
  document.getElementById('plan-days').value = days;
671
  document.getElementById('plan-price').value = price;
 
 
672
  document.getElementById('plan-modal-title').innerText = id ? 'Edit Plan' : 'Add New Plan';
673
 
674
  const modal = document.getElementById('plan-modal');
@@ -690,7 +416,8 @@
690
  const id = document.getElementById('plan-id').value;
691
  const payload = {
692
  days: parseInt(document.getElementById('plan-days').value),
693
- price: parseFloat(document.getElementById('plan-price').value)
 
694
  };
695
 
696
  try {
@@ -758,7 +485,7 @@
758
  return `
759
  <tr>
760
  <td class="px-6 py-4">
761
- <div class="font-semibold section-title">${name}</div>
762
  <div class="text-xs text-soft mt-1">ID: ${u._id}</div>
763
  </td>
764
  <td class="px-6 py-4 text-center">${statusBadge}</td>
@@ -777,6 +504,10 @@
777
  class="action-chip glass-btn-danger">
778
  Revoke
779
  </button>
 
 
 
 
780
  </div>
781
  </td>
782
  </tr>
@@ -806,7 +537,7 @@
806
  <div class="mobile-user-card">
807
  <div class="flex items-start justify-between gap-3 mb-3">
808
  <div class="min-w-0">
809
- <div class="font-semibold section-title break-words">${name}</div>
810
  <div class="text-xs text-soft mt-1 break-all">ID: ${u._id}</div>
811
  </div>
812
  <div class="shrink-0">${statusBadge}</div>
@@ -815,7 +546,7 @@
815
  <div class="grid grid-cols-1 gap-3 mb-4">
816
  <div class="rounded-2xl px-4 py-3"
817
  style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
818
- <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-bold mb-1">Expiry</div>
819
  <div class="text-sm font-semibold section-title">${expiry}</div>
820
  </div>
821
  </div>
@@ -834,6 +565,10 @@
834
  Revoke
835
  </button>
836
  </div>
 
 
 
 
837
  </div>
838
  `;
839
  }).join('');
@@ -928,24 +663,24 @@
928
 
929
  let title = '';
930
  let desc = '';
931
- let btnClasses = 'glass-btn glass-btn-primary rounded-2xl px-5 py-3 text-sm font-bold';
932
  let showDays = true;
933
 
934
  if (action === 'extend') {
935
  title = 'Extend Subscription';
936
  desc = `Add extra days to <b>${userName}</b>'s subscription.`;
937
  document.getElementById('days-action-label').innerText = 'add';
938
- btnClasses = 'glass-btn glass-btn-success rounded-2xl px-5 py-3 text-sm font-bold';
939
  } else if (action === 'reduce') {
940
  title = 'Reduce Subscription';
941
  desc = `Subtract days from <b>${userName}</b>'s subscription.`;
942
  document.getElementById('days-action-label').innerText = 'subtract';
943
- btnClasses = 'glass-btn glass-btn-warning rounded-2xl px-5 py-3 text-sm font-bold';
944
  } else {
945
  title = 'Revoke Subscription';
946
  desc = `<b>Warning:</b> This will remove <b>${userName}</b>'s subscription access completely.`;
947
  showDays = false;
948
- btnClasses = 'glass-btn glass-btn-danger rounded-2xl px-5 py-3 text-sm font-bold';
949
  }
950
 
951
  document.getElementById('user-modal-title').innerText = title;
@@ -1016,6 +751,31 @@
1016
  }
1017
  });
1018
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1019
  document.addEventListener('DOMContentLoaded', () => {
1020
  fetchPlans();
1021
  fetchSubscribers();
 
4
 
5
  {% block content %}
6
  <style>
7
+ .subs-shell { display: flex; flex-direction: column; gap: 2rem; }
8
+ .section-panel, .stat-card, .mobile-user-card, .modal-glass { background: var(--card); border: 1px solid var(--border); }
9
+ .section-panel { border-radius: var(--radius); }
10
+ .empty-state { border-radius: var(--radius-sm); }
11
+ .section-title { color: var(--text); }
12
+ .section-muted, .text-soft { color: var(--text-sec); }
13
+
14
+ .glass-btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px !important; font-weight: 500 !important; transition: background-color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
15
+ .glass-btn:hover { background: var(--card-high); }
16
+ .glass-btn:active { transform: scale(.97); }
17
+ .glass-btn:disabled { opacity: .45; }
18
+ .glass-btn-primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
19
+ .glass-btn-primary:hover { background: var(--primary); filter: brightness(1.07); }
20
+ .glass-btn-success { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 35%, transparent); background: color-mix(in srgb, var(--ok) 10%, transparent); }
21
+ .glass-btn-warning { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
22
+ .glass-btn-danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
23
+ .glass-btn-purple, .glass-btn-gold { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 35%, transparent); background: color-mix(in srgb, var(--primary) 10%, transparent); }
24
+
25
+ .glass-input, .glass-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .7rem 1rem; outline: none; font-size: .9rem; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
26
+ .glass-input::placeholder { color: var(--text-sec); }
27
+ .glass-input:focus, .glass-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
28
+
29
+ .stats-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.5rem; padding: 1.25rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
30
+ .stat-value { font-size: 1.5rem; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
31
+ .stat-label { margin-top: .2rem; font-size: .85rem; color: var(--text-sec); }
32
+
33
+ .table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
34
+ .subs-table { width: 100%; border-collapse: separate; border-spacing: 0; }
35
+ .subs-table thead th { background: var(--card); color: var(--text-sec); font-size: .72rem; font-weight: 500 !important; text-transform: uppercase; letter-spacing: .08em; border-bottom: 1px solid var(--border); }
36
+ .subs-table tbody tr { transition: background-color .15s var(--ease); }
37
+ .subs-table tbody tr:hover { background: var(--surface); }
38
+ .subs-table td { border-bottom: 1px solid var(--border); color: var(--text); vertical-align: top; }
39
+ .subs-table tbody tr:last-child td { border-bottom: none; }
40
+ .row-expired { background: color-mix(in srgb, var(--danger) 5%, transparent); }
41
+
42
+ .status-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
43
+ .status-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
44
+ .status-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
45
+ .status-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
46
+ .status-lifetime { background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); }
47
+ .status-gold { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
48
+
49
+ .action-chip { display: inline-flex; align-items: center; gap: .35rem; border-radius: 9999px; padding: .35rem .75rem; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); background: transparent; color: var(--text); transition: background-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
50
+ .action-chip:hover { background: var(--card-high); }
51
+ .action-chip:active { transform: scale(.96); }
52
+
53
+ .addon-box { padding: .7rem .8rem; border-radius: 12px; background: var(--bg); border: 1px solid var(--border); min-width: 0; overflow-wrap: anywhere; }
54
+ .usage-box { font-size: .75rem; line-height: 1.55; }
55
+
56
+ .mobile-user-card { padding: 1rem; border-radius: var(--radius-sm); min-width: 0; }
57
+ .mobile-user-card + .mobile-user-card { margin-top: .75rem; }
58
+ .mobile-grid { display: none; }
59
+
60
+ .pagination-shell { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
61
+ .pagination-text { color: var(--text-sec); }
62
+ .pagination-shell .controls { display: flex; align-items: center; gap: .5rem; }
63
+ .pagination-btn { min-width: 88px; }
64
+
65
+ .modal-backdrop { background: var(--scrim); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }
66
+ .modal-glass { border-radius: var(--radius); padding: 1.4rem; width: min(100%, 30rem); max-height: calc(100dvh - 2rem); overflow-y: auto; box-shadow: var(--shadow-strong); }
67
+ .modal-field label { color: var(--text-sec); font-size: .78rem; font-weight: 500 !important; margin-bottom: .45rem; display: block; }
68
+
69
+ .no-scrollbar::-webkit-scrollbar { display: none; }
70
+ .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
71
+
72
+ @media (max-width: 1024px) { .subs-table th, .subs-table td { padding-left: 1rem; padding-right: 1rem; } }
73
+ @media (max-width: 767.98px) {
74
+ .desktop-table-wrap { display: none; }
75
+ .mobile-grid { display: block; }
76
+ .section-panel { padding: 1rem; }
77
+ .stats-row { padding: 1rem; gap: 1rem; }
78
+ .pagination-shell { flex-direction: column; align-items: stretch; }
79
+ .pagination-shell .controls { width: 100%; display: grid; grid-template-columns: 1fr auto 1fr; }
80
+ .pagination-btn { width: 100%; }
81
+ }
82
+ .plan-card { position: relative; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); transition: border-color .2s var(--ease), transform .25s var(--ease); min-width: 0; }
83
+ .plan-card:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); transform: translateY(-2px); }
84
+ .metric-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
85
+ .badge-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
86
+ .badge-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  </style>
88
 
89
+ <div class="subs-shell">
90
  <!-- Hero -->
91
+ <header class="page-head" style="margin-bottom:0">
92
+ <div>
93
+ <h1 class="page-title">Plans</h1>
94
+ <p class="page-sub">Subscription plans and the users on them</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  </div>
96
+ <div class="page-actions">
97
+ <button onclick="backfillNames()" class="glass-btn px-4 py-2 text-sm" title="Fetch real Telegram names for 'User <id>' entries"><i class="fa-solid fa-id-badge"></i> Sync names</button>
98
+ <button onclick="fetchSubscribers()" class="glass-btn px-4 py-2 text-sm"><i class="fa-solid fa-rotate-right"></i> Refresh</button>
99
+ <button onclick="openPlanModal()" class="glass-btn glass-btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> Add plan</button>
100
+ </div>
101
+ </header>
102
 
103
  <!-- Plans -->
104
+ <section class="section-panel p-5">
105
  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
106
  <div>
107
+ <h2 class="text-lg font-semibold section-title">Plans</h2>
108
  </div>
109
  </div>
110
 
 
116
  </section>
117
 
118
  <!-- Users -->
119
+ <section class="section-panel p-5">
120
  <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
121
  <div>
122
+ <h2 class="text-lg font-semibold section-title">Subscribers</h2>
123
  <p class="text-sm section-muted mt-1">Search, filter, paginate, and manage subscription access.</p>
124
  </div>
125
 
 
179
  <div id="sub-page-info" class="pagination-text text-sm"></div>
180
  <div class="controls">
181
  <button id="sub-btn-prev" onclick="subChangePage(-1)"
182
+ class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
183
+ <i class="fa-solid fa-chevron-left text-xs"></i> Prev
184
  </button>
185
+ <span id="sub-page-num" class="text-sm font-semibold text-center section-title px-2"></span>
186
  <button id="sub-btn-next" onclick="subChangePage(1)"
187
+ class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
188
+ Next <i class="fa-solid fa-chevron-right text-xs"></i>
189
  </button>
190
  </div>
191
  </div>
 
197
  <div class="modal-glass">
198
  <div class="flex items-start justify-between gap-4 mb-5">
199
  <div>
200
+ <h3 class="text-xl font-semibold section-title" id="plan-modal-title">Add New Plan</h3>
201
  <p class="text-sm text-soft mt-1">Create or update a subscription plan.</p>
202
  </div>
203
  <button onclick="closePlanModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
 
214
  </div>
215
 
216
  <div class="modal-field">
217
+ <label for="plan-price">Price</label>
218
  <input type="number" id="plan-price" class="glass-input" required min="0" step="0.01">
219
  </div>
220
+ <div>
221
+ <label for="plan-currency">Currency</label>
222
+ <select id="plan-currency" class="glass-input">
223
+ <option value="INR">INR (₹)</option>
224
+ <option value="USD">USD ($)</option>
225
+ <option value="EUR">EUR (€)</option>
226
+ <option value="GBP">GBP (£)</option>
227
+ <option value="JPY">JPY (¥)</option>
228
+ <option value="AUD">AUD (A$)</option>
229
+ <option value="CAD">CAD (C$)</option>
230
+ <option value="SGD">SGD (S$)</option>
231
+ <option value="AED">AED (د.إ)</option>
232
+ <option value="BRL">BRL (R$)</option>
233
+ </select>
234
+ </div>
235
 
236
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
237
+ <button type="button" onclick="closePlanModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
238
  Cancel
239
  </button>
240
+ <button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">
241
  Save Plan
242
  </button>
243
  </div>
 
250
  <div class="modal-glass">
251
  <div class="flex items-start justify-between gap-4 mb-5">
252
  <div>
253
+ <h3 class="text-xl font-semibold section-title" id="user-modal-title">Manage User</h3>
254
  <div class="text-sm text-soft mt-1" id="user-modal-desc"></div>
255
  </div>
256
  <button onclick="closeUserModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
 
268
  </div>
269
 
270
  <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
271
+ <button type="button" onclick="closeUserModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
272
  Cancel
273
  </button>
274
+ <button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold" id="btn-user-save">
275
  Confirm
276
  </button>
277
  </div>
 
311
  : '<span class="metric-badge badge-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>';
312
  }
313
 
314
+ function getAdminBadge(u) {
315
+ return u.is_admin
316
+ ? '<span class="metric-badge" style="background: color-mix(in srgb, var(--warn) 16%, transparent); color: var(--warn);"><i class="fas fa-crown text-[8px]"></i> Owner</span>'
317
+ : '';
318
+ }
319
+
320
  async function fetchPlans() {
321
  const container = document.getElementById('plans-container');
322
  container.innerHTML = `
 
343
  }
344
 
345
  container.innerHTML = plans.map(p => `
346
+ <div class="plan-card p-5">
347
  <div class="plan-actions absolute right-4 top-4 flex gap-2">
348
+ <button onclick="openPlanModal('${p._id}', ${p.days}, ${p.price}, '${p.currency || 'INR'}')"
349
  class="glass-btn rounded-full w-9 h-9 flex items-center justify-center" title="Edit plan">
350
  <i class="fas fa-pen text-sm"></i>
351
  </button>
 
363
 
364
  <div class="min-w-0">
365
  <div class="text-sm font-semibold section-muted">${p.days} Days Plan</div>
366
+ <div class="mt-1 text-3xl font-semibold section-title tracking-tight">${currencySymbol(p.currency)}${p.price}</div>
367
+ <div class="text-xs text-soft mt-0.5">${(p.currency || 'INR').toUpperCase()}</div>
368
+ <div class="mt-3 inline-flex items-center gap-2 text-xs font-semibold rounded-full px-3 py-1"
369
  style="background: color-mix(in srgb, var(--accent) 12%, transparent); color: var(--text-sec); border: 1px solid color-mix(in srgb, var(--accent) 20%, transparent);">
370
  <i class="fas fa-bolt" style="color: var(--accent);"></i>
371
  Premium Access
 
384
  }
385
  }
386
 
387
+ function currencySymbol(code) {
388
+ const map = {INR:'₹',USD:'$',EUR:'€',GBP:'£',JPY:'¥',AUD:'A$',CAD:'C$',SGD:'S$',AED:'د.إ',BRL:'R$'};
389
+ return map[(code || 'INR').toUpperCase()] || ((code || 'INR') + ' ');
390
+ }
391
+
392
+ function openPlanModal(id = '', days = '', price = '', currency = 'INR') {
393
  document.getElementById('plan-id').value = id;
394
  document.getElementById('plan-days').value = days;
395
  document.getElementById('plan-price').value = price;
396
+ const cur = document.getElementById('plan-currency');
397
+ if (cur) cur.value = (currency || 'INR').toUpperCase();
398
  document.getElementById('plan-modal-title').innerText = id ? 'Edit Plan' : 'Add New Plan';
399
 
400
  const modal = document.getElementById('plan-modal');
 
416
  const id = document.getElementById('plan-id').value;
417
  const payload = {
418
  days: parseInt(document.getElementById('plan-days').value),
419
+ price: parseFloat(document.getElementById('plan-price').value),
420
+ currency: (document.getElementById('plan-currency') || {}).value || 'INR'
421
  };
422
 
423
  try {
 
485
  return `
486
  <tr>
487
  <td class="px-6 py-4">
488
+ <div class="font-semibold section-title flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
489
  <div class="text-xs text-soft mt-1">ID: ${u._id}</div>
490
  </td>
491
  <td class="px-6 py-4 text-center">${statusBadge}</td>
 
504
  class="action-chip glass-btn-danger">
505
  Revoke
506
  </button>
507
+ <button onclick="removeSubscriber(${u._id})"
508
+ class="action-chip glass-btn" title="Delete from list">
509
+ Remove
510
+ </button>
511
  </div>
512
  </td>
513
  </tr>
 
537
  <div class="mobile-user-card">
538
  <div class="flex items-start justify-between gap-3 mb-3">
539
  <div class="min-w-0">
540
+ <div class="font-semibold section-title break-words flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
541
  <div class="text-xs text-soft mt-1 break-all">ID: ${u._id}</div>
542
  </div>
543
  <div class="shrink-0">${statusBadge}</div>
 
546
  <div class="grid grid-cols-1 gap-3 mb-4">
547
  <div class="rounded-2xl px-4 py-3"
548
  style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
549
+ <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Expiry</div>
550
  <div class="text-sm font-semibold section-title">${expiry}</div>
551
  </div>
552
  </div>
 
565
  Revoke
566
  </button>
567
  </div>
568
+ <button onclick="removeSubscriber(${u._id})"
569
+ class="action-chip glass-btn w-full mt-2">
570
+ Remove from list
571
+ </button>
572
  </div>
573
  `;
574
  }).join('');
 
663
 
664
  let title = '';
665
  let desc = '';
666
+ let btnClasses = 'glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold';
667
  let showDays = true;
668
 
669
  if (action === 'extend') {
670
  title = 'Extend Subscription';
671
  desc = `Add extra days to <b>${userName}</b>'s subscription.`;
672
  document.getElementById('days-action-label').innerText = 'add';
673
+ btnClasses = 'glass-btn glass-btn-success px-4 py-2 text-sm font-semibold';
674
  } else if (action === 'reduce') {
675
  title = 'Reduce Subscription';
676
  desc = `Subtract days from <b>${userName}</b>'s subscription.`;
677
  document.getElementById('days-action-label').innerText = 'subtract';
678
+ btnClasses = 'glass-btn glass-btn-warning px-4 py-2 text-sm font-semibold';
679
  } else {
680
  title = 'Revoke Subscription';
681
  desc = `<b>Warning:</b> This will remove <b>${userName}</b>'s subscription access completely.`;
682
  showDays = false;
683
+ btnClasses = 'glass-btn glass-btn-danger px-4 py-2 text-sm font-semibold';
684
  }
685
 
686
  document.getElementById('user-modal-title').innerText = title;
 
751
  }
752
  });
753
 
754
+ async function removeSubscriber(userId) {
755
+ if (!confirm('Remove this user from the list? This deletes their subscription record (their token access is revoked).')) return;
756
+ try {
757
+ const res = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
758
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'remove', days: 0 })
759
+ });
760
+ if (!res.ok) throw new Error('Failed');
761
+ showToast('User removed.', 'success', 'Removed');
762
+ fetchSubscribers();
763
+ } catch (err) {
764
+ showToast('Failed to remove user.', 'error', 'Failed');
765
+ }
766
+ }
767
+
768
+ async function backfillNames() {
769
+ try {
770
+ const res = await fetch('/api/admin/subscriptions/backfill-names', { method: 'POST' });
771
+ const data = await res.json();
772
+ if (res.ok) { showToast(data.message || 'Names synced.', 'success', 'Synced'); fetchSubscribers(); }
773
+ else { showToast('Failed to sync names.', 'error', 'Failed'); }
774
+ } catch (err) {
775
+ showToast('Failed to sync names.', 'error', 'Failed');
776
+ }
777
+ }
778
+
779
  document.addEventListener('DOMContentLoaded', () => {
780
  fetchPlans();
781
  fetchSubscribers();
Backend/fastapi/templates/tools.html CHANGED
@@ -5,36 +5,37 @@
5
 
6
  <style>
7
  .tool-card {
8
- background: color-mix(in srgb, var(--card) 94%, var(--bg));
9
  border: 1px solid var(--border);
10
- border-radius: 1.5rem;
11
- padding: 1.5rem 1.75rem;
12
- box-shadow: 0 8px 32px rgba(0,0,0,0.15);
13
  }
 
14
  .tool-card h2 {
15
- font-size: 1rem; font-weight: 800;
16
- letter-spacing: 0.05em; text-transform: uppercase;
17
- color: var(--primary); margin-bottom: 1.25rem;
18
  display: flex; align-items: center; gap: 0.5rem;
19
  }
20
  .s-label {
21
- display: block; font-size: 0.78rem; font-weight: 700;
22
  color: var(--text-sec); text-transform: uppercase;
23
- letter-spacing: 0.04em; margin-bottom: 0.5rem;
24
  }
25
  .btn {
26
  display: inline-flex; align-items: center; gap: 0.5rem;
27
  padding: 0.6rem 1.25rem; border-radius: 9999px;
28
- font-size: 0.85rem; font-weight: 700; cursor: pointer;
29
  border: 1px solid transparent; transition: all 0.15s; white-space: nowrap;
30
  }
31
  .btn:disabled { opacity: 0.5; cursor: not-allowed; }
32
- .btn-primary { background: var(--primary); color: #fff; box-shadow: 0 0 18px color-mix(in srgb,var(--primary) 40%,transparent); }
33
- .btn-danger { background: rgba(239,68,68,0.12); border-color: rgba(239,68,68,0.3); color: #ef4444; }
34
- .btn-danger:hover:not(:disabled) { background: rgba(239,68,68,0.25); }
35
- .btn-ghost { background: color-mix(in srgb,var(--text-sec) 12%,transparent); color: var(--text); }
36
- .btn-warning { background: rgba(245,158,11,0.14); border-color: rgba(245,158,11,0.35); color: #f59e0b; }
37
- .btn-warning:hover:not(:disabled) { background: rgba(245,158,11,0.28); }
 
 
38
 
39
  /* channel chips */
40
  .chip-list { display: flex; flex-direction: column; gap: 0.5rem; max-height: 240px; overflow-y: auto; }
@@ -42,19 +43,19 @@
42
  display: flex; align-items: center; gap: 0.75rem;
43
  padding: 0.7rem 1rem; border-radius: 0.9rem;
44
  border: 1px solid var(--border);
45
- background: color-mix(in srgb, var(--bg) 60%, transparent);
46
  cursor: pointer; transition: border-color 0.15s, background 0.15s;
47
  }
48
  .chip:hover { border-color: var(--primary); }
49
  .chip.selected { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 12%, transparent); }
50
  .chip input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); }
51
- .chip .c-name { font-weight: 700; font-size: 0.9rem; }
52
  .chip .c-id { font-size: 0.72rem; color: var(--text-sec); }
53
 
54
  /* progress */
55
  .progress-track {
56
- width: 100%; height: 0.65rem; border-radius: 9999px;
57
- background: color-mix(in srgb, var(--text-sec) 18%, transparent);
58
  overflow: hidden;
59
  }
60
  .progress-fill {
@@ -69,48 +70,191 @@
69
 
70
  .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px,1fr)); gap: 0.75rem; }
71
  .stat-box {
72
- background: color-mix(in srgb, var(--bg) 55%, transparent);
73
  border: 1px solid var(--border); border-radius: 0.9rem;
74
  padding: 0.75rem 0.9rem;
75
  }
76
- .stat-box .v { font-size: 1.3rem; font-weight: 800; }
77
- .stat-box .l { font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-sec); }
78
 
79
  .status-pill {
80
  display: inline-flex; align-items: center; gap: 0.4rem;
81
  padding: 0.25rem 0.8rem; border-radius: 9999px;
82
- font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em;
83
  }
84
  .status-idle { background: color-mix(in srgb,var(--text-sec) 15%,transparent); color: var(--text-sec); }
85
- .status-running { background: rgba(34,197,94,0.15); color: #22c55e; }
86
- .status-paused { background: rgba(245,158,11,0.15); color: #f59e0b; }
87
- .status-cancelled { background: rgba(245,158,11,0.15); color: #f59e0b; }
88
- .status-completed { background: rgba(34,197,94,0.15); color: #22c55e; }
89
- .status-error { background: rgba(239,68,68,0.15); color: #ef4444; }
90
 
91
  .dead-row {
92
  display: flex; align-items: center; justify-content: space-between; gap: 0.75rem;
93
  padding: 0.6rem 0.9rem; border-radius: 0.75rem;
94
  border: 1px solid var(--border);
95
- background: color-mix(in srgb, var(--bg) 55%, transparent);
96
  }
97
  .dead-list { display: flex; flex-direction: column; gap: 0.4rem; max-height: 320px; overflow-y: auto; }
98
  .divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }
99
  .hint { font-size: 0.78rem; color: var(--text-sec); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  </style>
101
 
102
- <!-- Page header -->
103
- <div class="flex items-center justify-between mb-8 flex-wrap gap-3">
104
  <div>
105
- <h1 class="text-3xl font-extrabold">Tools</h1>
106
- <p class="mt-1 text-sm" style="color:var(--text-sec)">
107
- Scan your channels, verify the database, and clean up dead links — all from here.
108
- </p>
109
  </div>
110
- </div>
111
 
112
  <div class="space-y-6">
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  <!-- ══ Channel Scanner ══════════════════════════════════════════════ -->
115
  <div class="tool-card">
116
  <div class="flex items-center justify-between flex-wrap gap-2">
@@ -119,10 +263,7 @@
119
  </div>
120
 
121
  <p class="hint mt-3 mb-4">
122
- Index existing files from your AUTH channels into the database. A scan
123
- <strong>resumes from where it left off</strong> if the server restarts or you
124
- stop it — it only restarts from scratch when you choose <strong>Rescan</strong>.
125
- The bot must be an admin in each channel.
126
  </p>
127
 
128
  <label class="s-label">Select channels</label>
@@ -139,7 +280,7 @@
139
 
140
  <!-- live progress -->
141
  <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
142
- <div class="text-sm font-bold" id="scan-current">No scan running</div>
143
  <div class="text-sm" style="color:var(--text-sec)">
144
  <i class="fa-regular fa-clock"></i> <span id="scan-elapsed">0s</span>
145
  </div>
@@ -150,11 +291,13 @@
150
 
151
  <div class="stat-grid mb-4">
152
  <div class="stat-box"><div class="v" id="sc-processed">0</div><div class="l">Processed</div></div>
153
- <div class="stat-box"><div class="v" style="color:#22c55e" id="sc-indexed">0</div><div class="l">Indexed</div></div>
154
  <div class="stat-box"><div class="v" id="sc-dup">0</div><div class="l">Skipped (dup)</div></div>
155
  <div class="stat-box"><div class="v" id="sc-meta">0</div><div class="l">Skipped (meta)</div></div>
156
  <div class="stat-box"><div class="v" id="sc-nonvid">0</div><div class="l">Non-video</div></div>
157
- <div class="stat-box"><div class="v" style="color:#ef4444" id="sc-errors">0</div><div class="l">Errors</div></div>
 
 
158
  </div>
159
 
160
  <div class="flex items-center gap-2 flex-wrap">
@@ -168,7 +311,89 @@
168
  <i class="fa-solid fa-stop"></i> Stop
169
  </button>
170
  </div>
171
- <p class="hint mt-3" id="scan-error" style="color:#ef4444;display:none"></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  </div>
173
 
174
  <!-- ══ Database Check ════════════════════════════════════════════════ -->
@@ -179,12 +404,11 @@
179
  </div>
180
 
181
  <p class="hint mt-3 mb-4">
182
- Verify that every indexed file still exists on Telegram. Dead entries
183
- found here can be purged below. Runs are throttled to respect Telegram limits.
184
  </p>
185
 
186
  <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
187
- <div class="text-sm font-bold" id="dbc-current">No check running</div>
188
  <div class="text-sm" style="color:var(--text-sec)">
189
  <i class="fa-solid fa-gauge-high"></i> <span id="dbc-speed">0</span>/s ·
190
  <i class="fa-regular fa-clock"></i> <span id="dbc-elapsed">0s</span>
@@ -196,8 +420,8 @@
196
 
197
  <div class="stat-grid mb-4">
198
  <div class="stat-box"><div class="v" id="dbc-checked">0</div><div class="l">Checked</div></div>
199
- <div class="stat-box"><div class="v" style="color:#22c55e" id="dbc-alive">0</div><div class="l">Alive</div></div>
200
- <div class="stat-box"><div class="v" style="color:#ef4444" id="dbc-dead">0</div><div class="l">Dead</div></div>
201
  <div class="stat-box"><div class="v" id="dbc-errors">0</div><div class="l">Errors</div></div>
202
  <div class="stat-box"><div class="v" id="dbc-purged">0</div><div class="l">Purged</div></div>
203
  </div>
@@ -225,21 +449,263 @@
225
  </button>
226
  </div>
227
  </div>
228
- <p class="hint mb-3">
229
- "Load flagged" shows dead links detected automatically by the background checker.
230
- Running a DB Check above also fills this list. Purging removes those entries from the database.
231
- </p>
232
  <div class="dead-list" id="dead-list">
233
  <div class="hint">No dead links to show yet. Run a DB Check or load flagged links.</div>
234
  </div>
235
  </div>
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  </div>
238
 
239
  <script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  /* ─────────────── State ─────────────── */
241
  let scanTimer = null;
242
  let dbcTimer = null;
 
 
 
 
243
  let deadSource = "dbcheck"; // where the current dead list came from
244
  let purgeIds = []; // explicit ids to purge when source = flagged
245
 
@@ -264,7 +730,7 @@ async function loadChannels() {
264
  </label>
265
  `).join('');
266
  } catch (e) {
267
- list.innerHTML = `<div class="hint" style="color:#ef4444">Failed to load channels.</div>`;
268
  }
269
  }
270
 
@@ -353,6 +819,8 @@ function renderScan(s) {
353
  setText('sc-dup', c.skipped_dup || 0);
354
  setText('sc-meta', c.skipped_meta || 0);
355
  setText('sc-nonvid', c.skipped_nonvid || 0);
 
 
356
  setText('sc-errors', c.errors || 0);
357
  setText('scan-elapsed', s.elapsed || '0s');
358
 
@@ -498,7 +966,7 @@ function renderDeadList(entries) {
498
  list.innerHTML = entries.map(e => `
499
  <div class="dead-row">
500
  <span class="min-w-0 truncate">
501
- <i class="fa-solid fa-link-slash" style="color:#ef4444"></i>
502
  ${escapeHtml(e.title || 'Unknown')}
503
  ${e.quality ? `<span class="c-id">· ${escapeHtml(e.quality)}</span>` : ''}
504
  </span>
@@ -548,6 +1016,420 @@ async function purgeDeadLinks() {
548
  }
549
  }
550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
  /* ─────────────── Utils ─────────────── */
552
  function setText(id, val) { const el = document.getElementById(id); if (el) el.textContent = val; }
553
  function escapeHtml(str) {
@@ -559,6 +1441,7 @@ function escapeHtmlAttr(str) {
559
  }
560
 
561
  /* ─────────────── Init ─────────────── */
 
562
  loadChannels();
563
  pollScan().then(() => {
564
  const pill = document.getElementById('scan-status-pill');
@@ -568,6 +1451,10 @@ pollDbc().then(() => {
568
  const pill = document.getElementById('dbc-status-pill');
569
  if (pill.classList.contains('status-running')) startDbcPolling();
570
  });
 
 
 
 
571
  </script>
572
 
573
  {% endblock %}
 
5
 
6
  <style>
7
  .tool-card {
8
+ background: var(--card);
9
  border: 1px solid var(--border);
10
+ border-radius: var(--radius);
11
+ padding: 1.35rem 1.5rem;
 
12
  }
13
+ .tool-card h2 i { color: var(--primary); font-size: .95rem; }
14
  .tool-card h2 {
15
+ font-size: 1.05rem; font-weight: 600;
16
+ color: var(--text); margin-bottom: 1rem;
 
17
  display: flex; align-items: center; gap: 0.5rem;
18
  }
19
  .s-label {
20
+ display: block; font-size: 0.72rem; font-weight: 500;
21
  color: var(--text-sec); text-transform: uppercase;
22
+ letter-spacing: 0.1em; margin-bottom: 0.5rem;
23
  }
24
  .btn {
25
  display: inline-flex; align-items: center; gap: 0.5rem;
26
  padding: 0.6rem 1.25rem; border-radius: 9999px;
27
+ font-size: 0.88rem; font-weight: 500; cursor: pointer;
28
  border: 1px solid transparent; transition: all 0.15s; white-space: nowrap;
29
  }
30
  .btn:disabled { opacity: 0.5; cursor: not-allowed; }
31
+ .btn-primary { background: var(--primary); color: var(--on-primary); }
32
+ .btn-danger { background: color-mix(in srgb, var(--danger) 12%, transparent); border-color: color-mix(in srgb, var(--danger) 30%, transparent); color: var(--danger); }
33
+ .btn-danger:hover:not(:disabled) { background: color-mix(in srgb, var(--danger) 25%, transparent); }
34
+ .btn-ghost { background: transparent; border-color: var(--border); color: var(--text); }
35
+ .btn-ghost:hover:not(:disabled) { background: var(--card-high); }
36
+ .btn:active:not(:disabled) { transform: scale(.97); }
37
+ .btn-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); border-color: color-mix(in srgb, var(--warn) 35%, transparent); color: var(--warn); }
38
+ .btn-warning:hover:not(:disabled) { background: color-mix(in srgb, var(--warn) 28%, transparent); }
39
 
40
  /* channel chips */
41
  .chip-list { display: flex; flex-direction: column; gap: 0.5rem; max-height: 240px; overflow-y: auto; }
 
43
  display: flex; align-items: center; gap: 0.75rem;
44
  padding: 0.7rem 1rem; border-radius: 0.9rem;
45
  border: 1px solid var(--border);
46
+ background: var(--bg);
47
  cursor: pointer; transition: border-color 0.15s, background 0.15s;
48
  }
49
  .chip:hover { border-color: var(--primary); }
50
  .chip.selected { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 12%, transparent); }
51
  .chip input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); }
52
+ .chip .c-name { font-weight: 600; font-size: 0.9rem; }
53
  .chip .c-id { font-size: 0.72rem; color: var(--text-sec); }
54
 
55
  /* progress */
56
  .progress-track {
57
+ width: 100%; height: 0.4rem; border-radius: 9999px;
58
+ background: var(--card-high);
59
  overflow: hidden;
60
  }
61
  .progress-fill {
 
70
 
71
  .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px,1fr)); gap: 0.75rem; }
72
  .stat-box {
73
+ background: var(--bg);
74
  border: 1px solid var(--border); border-radius: 0.9rem;
75
  padding: 0.75rem 0.9rem;
76
  }
77
+ .stat-box .v { font-size: 1.3rem; font-weight: 600; }
78
+ .stat-box .l { font-size: 0.8rem; color: var(--text-sec); }
79
 
80
  .status-pill {
81
  display: inline-flex; align-items: center; gap: 0.4rem;
82
  padding: 0.25rem 0.8rem; border-radius: 9999px;
83
+ font-size: 0.75rem; font-weight: 500;
84
  }
85
  .status-idle { background: color-mix(in srgb,var(--text-sec) 15%,transparent); color: var(--text-sec); }
86
+ .status-running { background: color-mix(in srgb, var(--ok) 15%, transparent); color: var(--ok); }
87
+ .status-paused { background: color-mix(in srgb, var(--warn) 15%, transparent); color: var(--warn); }
88
+ .status-cancelled { background: color-mix(in srgb, var(--warn) 15%, transparent); color: var(--warn); }
89
+ .status-completed { background: color-mix(in srgb, var(--ok) 15%, transparent); color: var(--ok); }
90
+ .status-error { background: color-mix(in srgb, var(--danger) 15%, transparent); color: var(--danger); }
91
 
92
  .dead-row {
93
  display: flex; align-items: center; justify-content: space-between; gap: 0.75rem;
94
  padding: 0.6rem 0.9rem; border-radius: 0.75rem;
95
  border: 1px solid var(--border);
96
+ background: var(--bg);
97
  }
98
  .dead-list { display: flex; flex-direction: column; gap: 0.4rem; max-height: 320px; overflow-y: auto; }
99
  .divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }
100
  .hint { font-size: 0.78rem; color: var(--text-sec); }
101
+
102
+ .ba-cell { display: inline-flex; align-items: center; gap: 0.3rem; font-weight: 600; font-size: 0.75rem; }
103
+ .ba-ok { color: var(--ok); }
104
+ .ba-no { color: var(--danger); }
105
+ .ba-warn { color: var(--warn); }
106
+ .ba-muted { color: var(--text-sec); }
107
+ .ba-locked { opacity: 0.6; }
108
+ .ba-roles { display: inline-flex; gap: 0.25rem; flex-wrap: wrap; }
109
+ .ba-role {
110
+ font-size: 0.6rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em;
111
+ padding: 0.05rem 0.4rem; border-radius: 9999px;
112
+ background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary);
113
+ }
114
+ .ba-bot-chip input { width: 1.05rem; height: 1.05rem; accent-color: var(--primary); flex-shrink: 0; }
115
+
116
+ .ba-ch-list { display: flex; flex-direction: column; gap: 0.6rem; }
117
+ .ba-ch-card {
118
+ border: 1px solid var(--border); border-radius: 0.9rem;
119
+ padding: 0.85rem 1rem; background: var(--bg);
120
+ }
121
+ .ba-ch-card.selected { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 10%, transparent); }
122
+ .ba-ch-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 0.6rem; flex-wrap: wrap; }
123
+ .ba-ch-sel { display: flex; align-items: flex-start; gap: 0.6rem; cursor: pointer; min-width: 0; flex: 1; }
124
+ .ba-ch-sel input { width: 1.15rem; height: 1.15rem; accent-color: var(--primary); flex-shrink: 0; margin-top: 0.15rem; }
125
+ .ba-ch-name { font-weight: 600; font-size: 0.9rem; word-break: break-word; }
126
+ .ba-ch-id { font-size: 0.7rem; color: var(--text-sec); word-break: break-all; }
127
+ .ba-bot-grid {
128
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
129
+ gap: 0.4rem 0.9rem; margin-top: 0.7rem;
130
+ }
131
+ .ba-bstat { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; font-size: 0.78rem; }
132
+ .ba-bstat .n { font-weight: 600; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
133
+ .ba-res-row {
134
+ display: flex; flex-direction: column; align-items: stretch; gap: 0.4rem;
135
+ padding: 0.6rem 0.9rem; border-radius: 0.75rem;
136
+ border: 1px solid var(--border); background: var(--bg);
137
+ }
138
+
139
+ @media (max-width: 640px) {
140
+ .tool-card { padding: 1.1rem 1rem; }
141
+ .ba-bot-grid { grid-template-columns: 1fr; }
142
+ #ba-bots .chip { width: 100%; }
143
+ .ba-actions .btn { width: 100%; justify-content: center; }
144
+ }
145
  </style>
146
 
147
+ <header class="page-head">
 
148
  <div>
149
+ <h1 class="page-title">Tools</h1>
150
+ <p class="page-sub">Scan, index and maintain your library</p>
 
 
151
  </div>
152
+ </header>
153
 
154
  <div class="space-y-6">
155
 
156
+ <!-- ══ Manual Upload Session ═════════════════════════════════════════ -->
157
+ <div class="tool-card">
158
+ <div class="flex items-center justify-between flex-wrap gap-2">
159
+ <h2 style="margin-bottom:0"><i class="fa-solid fa-cloud-arrow-up"></i> Manual Upload Session</h2>
160
+ <span id="ms-status-pill" class="status-pill status-idle">No session</span>
161
+ </div>
162
+
163
+ <p class="hint mt-3 mb-4">
164
+ Pick a title, start a session, then forward files — each one attaches automatically.
165
+ </p>
166
+
167
+ <!-- Active session banner -->
168
+ <div id="ms-active" class="hidden mb-4" style="border:1px solid color-mix(in srgb, var(--ok) 35%, transparent);background:color-mix(in srgb, var(--ok) 10%, transparent);border-radius:0.9rem;padding:0.9rem 1.1rem">
169
+ <div class="flex items-center justify-between flex-wrap gap-2">
170
+ <div class="min-w-0">
171
+ <div class="text-sm font-semibold" id="ms-active-title">—</div>
172
+ <div class="hint" id="ms-active-detail"></div>
173
+ </div>
174
+ <button class="btn btn-danger" onclick="endManualSession()"><i class="fa-solid fa-stop"></i> End session</button>
175
+ </div>
176
+ <p class="hint mt-2" style="color:var(--ok)">
177
+ <i class="fa-solid fa-circle-check"></i> Session is live — forward the files now, then click <strong>End session</strong> when finished.
178
+ </p>
179
+ </div>
180
+
181
+ <!-- Setup (hidden while a session is active) -->
182
+ <div id="ms-setup">
183
+ <label class="s-label">Find a title (your library, IMDb / Cinemeta or TMDB)</label>
184
+ <div class="flex flex-col sm:flex-row gap-2">
185
+ <input id="ms-query" class="flex-1" placeholder="Title (with or without year), IMDb id/link, or TMDB id/link"
186
+ style="background:color-mix(in srgb,var(--bg) 60%,transparent);border:1px solid var(--border);border-radius:0.9rem;padding:0.7rem 1rem;color:var(--text);outline:none"
187
+ onkeydown="if(event.key==='Enter'){event.preventDefault();searchManualSession();}">
188
+ <button class="btn btn-primary" onclick="searchManualSession()"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
189
+ </div>
190
+ <p id="ms-search-state" class="hint mt-2" style="display:none"></p>
191
+
192
+ <div id="ms-results" class="chip-list mt-3" style="display:none"></div>
193
+
194
+ <!-- Selected + options -->
195
+ <div id="ms-selected-box" class="hidden mt-4" style="border:1px solid var(--border);border-radius:0.9rem;padding:0.9rem 1.1rem">
196
+ <div class="flex items-center gap-3">
197
+ <img id="ms-sel-poster" src="" alt="" style="width:2.75rem;height:4rem;object-fit:cover;border-radius:0.4rem;flex-shrink:0;background:var(--card)">
198
+ <div class="min-w-0 flex-1">
199
+ <div class="text-sm font-semibold truncate" id="ms-sel-title">—</div>
200
+ <div class="hint" id="ms-sel-sub"></div>
201
+ </div>
202
+ </div>
203
+
204
+ <!-- Real (TMDB/IMDb) title: metadata read from each file -->
205
+ <div id="ms-real-note" class="hidden mt-3">
206
+ <p class="hint" style="border:1px solid color-mix(in srgb, var(--info) 30%, transparent);background:color-mix(in srgb, var(--info) 8%, transparent);border-radius:0.75rem;padding:0.7rem 0.9rem">
207
+ <i class="fa-solid fa-wand-magic-sparkles" style="color:var(--info)"></i>
208
+ Season, episode and quality are read from each file's name/caption automatically.
209
+ Forward files to your <strong>auth</strong> or <strong>manual</strong> channel.
210
+ </p>
211
+ <div id="ms-real-tv-season" class="hidden mt-3">
212
+ <label class="s-label">Fallback season (optional)</label>
213
+ <input id="ms-real-season" type="number" min="0" placeholder="Only if files have no season, e.g. anime absolute numbers"
214
+ style="width:100%;background:color-mix(in srgb,var(--bg) 60%,transparent);border:1px solid var(--border);border-radius:0.9rem;padding:0.6rem 0.9rem;color:var(--text);outline:none">
215
+ <p class="hint mt-2">
216
+ <i class="fa-solid fa-circle-info"></i> Leave empty when files already contain <code>S01E05</code>-style numbering.
217
+ Set it for absolute-numbered files like <code>One Piece - 1142 (1080p).mkv</code> — the episode (1142)
218
+ is read from the name and placed in this season.
219
+ </p>
220
+ </div>
221
+ </div>
222
+
223
+ <!-- Personal title: manual metadata -->
224
+ <div id="ms-personal-fields" class="hidden mt-3">
225
+ <div id="ms-tv-fields" class="hidden grid grid-cols-2 gap-3">
226
+ <div>
227
+ <label class="s-label">Season <span style="color:var(--danger)">*</span></label>
228
+ <input id="ms-season" type="number" min="0" placeholder="e.g. 1"
229
+ style="width:100%;background:color-mix(in srgb,var(--bg) 60%,transparent);border:1px solid var(--border);border-radius:0.9rem;padding:0.6rem 0.9rem;color:var(--text);outline:none">
230
+ </div>
231
+ <div>
232
+ <label class="s-label">Episode (optional)</label>
233
+ <input id="ms-episode" type="number" min="0" placeholder="Empty = next episode"
234
+ style="width:100%;background:color-mix(in srgb,var(--bg) 60%,transparent);border:1px solid var(--border);border-radius:0.9rem;padding:0.6rem 0.9rem;color:var(--text);outline:none">
235
+ </div>
236
+ <p class="hint col-span-2" style="margin-top:-0.25rem">
237
+ Set an <strong>episode</strong> to pile every forwarded file onto that one episode (multiple qualities).
238
+ Leave it <strong>empty</strong> so each file becomes the next episode (E1, E2, E3…).
239
+ </p>
240
+ </div>
241
+ <div class="mt-3">
242
+ <label class="s-label">Quality (optional)</label>
243
+ <input id="ms-quality" placeholder="Auto-detected from video; fallback HD (e.g. 1080p)"
244
+ style="width:100%;background:color-mix(in srgb,var(--bg) 60%,transparent);border:1px solid var(--border);border-radius:0.9rem;padding:0.6rem 0.9rem;color:var(--text);outline:none">
245
+ </div>
246
+ <p class="hint mt-2">
247
+ <i class="fa-solid fa-circle-info"></i> Personal files carry no metadata — forward them to your
248
+ <strong>manual channel only</strong>.
249
+ </p>
250
+ </div>
251
+
252
+ <button class="btn btn-primary mt-3" onclick="startManualSession()"><i class="fa-solid fa-play"></i> Start session</button>
253
+ </div>
254
+ </div>
255
+
256
+ </div>
257
+
258
  <!-- ══ Channel Scanner ══════════════════════════════════════════════ -->
259
  <div class="tool-card">
260
  <div class="flex items-center justify-between flex-wrap gap-2">
 
263
  </div>
264
 
265
  <p class="hint mt-3 mb-4">
266
+ Index files from your AUTH channels. Scans resume automatically; use Rescan to re-index from scratch.
 
 
 
267
  </p>
268
 
269
  <label class="s-label">Select channels</label>
 
280
 
281
  <!-- live progress -->
282
  <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
283
+ <div class="text-sm font-semibold" id="scan-current">No scan running</div>
284
  <div class="text-sm" style="color:var(--text-sec)">
285
  <i class="fa-regular fa-clock"></i> <span id="scan-elapsed">0s</span>
286
  </div>
 
291
 
292
  <div class="stat-grid mb-4">
293
  <div class="stat-box"><div class="v" id="sc-processed">0</div><div class="l">Processed</div></div>
294
+ <div class="stat-box"><div class="v" style="color:var(--ok)" id="sc-indexed">0</div><div class="l">Indexed</div></div>
295
  <div class="stat-box"><div class="v" id="sc-dup">0</div><div class="l">Skipped (dup)</div></div>
296
  <div class="stat-box"><div class="v" id="sc-meta">0</div><div class="l">Skipped (meta)</div></div>
297
  <div class="stat-box"><div class="v" id="sc-nonvid">0</div><div class="l">Non-video</div></div>
298
+ <div class="stat-box"><div class="v" style="color:var(--info)" id="sc-sub-added">0</div><div class="l">Subtitles added</div></div>
299
+ <div class="stat-box"><div class="v" id="sc-sub-skipped">0</div><div class="l">Subtitles skipped</div></div>
300
+ <div class="stat-box"><div class="v" style="color:var(--danger)" id="sc-errors">0</div><div class="l">Errors</div></div>
301
  </div>
302
 
303
  <div class="flex items-center gap-2 flex-wrap">
 
311
  <i class="fa-solid fa-stop"></i> Stop
312
  </button>
313
  </div>
314
+ <p class="hint mt-3" id="scan-error" style="color:var(--danger);display:none"></p>
315
+ </div>
316
+
317
+ <!-- ══ Bot Admin Manager ════════════════════════════════════════════ -->
318
+ <div class="tool-card">
319
+ <div class="flex items-center justify-between flex-wrap gap-2">
320
+ <h2 style="margin-bottom:0"><i class="fa-solid fa-user-shield"></i> Bot Admin Manager</h2>
321
+ <span id="ba-status-pill" class="status-pill status-idle">Idle</span>
322
+ </div>
323
+
324
+ <p class="hint mt-3 mb-4">
325
+ Promote your bots to admin in the channels they serve, using your session account.
326
+ </p>
327
+
328
+ {% if not userbot_configured or not multi_token_available %}
329
+ <div style="border:1px solid var(--border);background:color-mix(in srgb,var(--bg) 55%,transparent);border-radius:0.9rem;padding:1rem 1.1rem">
330
+ <p class="hint" style="margin:0">
331
+ <i class="fa-solid fa-circle-info"></i>
332
+ {% if not userbot_configured %}
333
+ This tool needs a connected <strong>Telegram user session</strong>. Only a user account can
334
+ promote bots to admin. Connect one from
335
+ <a href="/admin/settings" style="color:var(--primary)">Settings → Telegram User Session</a>.
336
+ {% else %}
337
+ This tool needs <strong>more than one bot token</strong>. Add extra tokens under
338
+ <a href="/admin/settings" style="color:var(--primary)">Settings → Multi-Token Clients</a> to enable it.
339
+ {% endif %}
340
+ </p>
341
+ </div>
342
+ {% else %}
343
+
344
+ <div class="flex items-center gap-2 flex-wrap mb-3">
345
+ <button class="btn btn-ghost" type="button" id="ba-scan-btn" onclick="loadBotAdmin()">
346
+ <i class="fa-solid fa-arrows-rotate"></i> Scan
347
+ </button>
348
+ <span class="hint" style="display:flex;align-items:center;gap:0.9rem;flex-wrap:wrap">
349
+ <span><i class="fa-solid fa-check ba-ok"></i> Admin</span>
350
+ <span><i class="fa-solid fa-xmark ba-no"></i> Not in channel</span>
351
+ <span><span class="ba-warn">●</span> Member (not admin)</span>
352
+ <span><i class="fa-solid fa-lock ba-muted"></i> Can't manage</span>
353
+ </span>
354
+ </div>
355
+
356
+ <div id="ba-loading" class="hint" style="display:none"><i class="fa-solid fa-spinner fa-spin"></i> Scanning channels &amp; bots…</div>
357
+ <div id="ba-error" class="hint" style="color:var(--danger);display:none"></div>
358
+
359
+ <div id="ba-body" style="display:none">
360
+ <label class="s-label">Bots to add</label>
361
+ <div id="ba-bots" class="flex items-center gap-2 flex-wrap mb-4"></div>
362
+
363
+ <div class="flex items-center justify-between gap-2 flex-wrap mb-2">
364
+ <label class="s-label" style="margin-bottom:0">Channels</label>
365
+ <div class="flex items-center gap-2">
366
+ <button class="btn btn-ghost" type="button" onclick="selectAllBaChannels(true)"><i class="fa-solid fa-check-double"></i> All</button>
367
+ <button class="btn btn-ghost" type="button" onclick="selectAllBaChannels(false)"><i class="fa-solid fa-xmark"></i> Clear</button>
368
+ </div>
369
+ </div>
370
+ <div id="ba-channels" class="ba-ch-list"></div>
371
+
372
+ <label class="chip mt-4" style="cursor:pointer">
373
+ <input type="checkbox" id="ba-demote-orphans">
374
+ <span class="min-w-0">
375
+ <span class="c-name block">Also remove orphan bot-admins</span>
376
+ <span class="c-id">Revoke admin from bots that are admin in a channel but are no longer in your token list (they stay as members, not banned).</span>
377
+ </span>
378
+ </label>
379
+
380
+ <div id="ba-progress" class="mt-4" style="display:none">
381
+ <div class="flex items-center justify-between mb-2 text-sm flex-wrap gap-2">
382
+ <span class="font-semibold"><i class="fa-solid fa-user-shield"></i> Applying…</span>
383
+ <span style="color:var(--text-sec)"><span id="ba-prog-done">0</span>/<span id="ba-prog-total">0</span> channels</span>
384
+ </div>
385
+ <div class="progress-track"><div class="progress-fill" id="ba-prog-bar"></div></div>
386
+ </div>
387
+
388
+ <div class="ba-actions flex items-center gap-2 flex-wrap mt-4">
389
+ <button class="btn btn-primary" id="ba-apply-btn" onclick="applyBotAdmin()">
390
+ <i class="fa-solid fa-user-plus"></i> Add selected bots as admin
391
+ </button>
392
+ </div>
393
+
394
+ <div id="ba-results" class="dead-list mt-4" style="display:none"></div>
395
+ </div>
396
+ {% endif %}
397
  </div>
398
 
399
  <!-- ══ Database Check ════════════════════════════════════════════════ -->
 
404
  </div>
405
 
406
  <p class="hint mt-3 mb-4">
407
+ Verify indexed files still exist on Telegram, then purge dead entries below.
 
408
  </p>
409
 
410
  <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
411
+ <div class="text-sm font-semibold" id="dbc-current">No check running</div>
412
  <div class="text-sm" style="color:var(--text-sec)">
413
  <i class="fa-solid fa-gauge-high"></i> <span id="dbc-speed">0</span>/s ·
414
  <i class="fa-regular fa-clock"></i> <span id="dbc-elapsed">0s</span>
 
420
 
421
  <div class="stat-grid mb-4">
422
  <div class="stat-box"><div class="v" id="dbc-checked">0</div><div class="l">Checked</div></div>
423
+ <div class="stat-box"><div class="v" style="color:var(--ok)" id="dbc-alive">0</div><div class="l">Alive</div></div>
424
+ <div class="stat-box"><div class="v" style="color:var(--danger)" id="dbc-dead">0</div><div class="l">Dead</div></div>
425
  <div class="stat-box"><div class="v" id="dbc-errors">0</div><div class="l">Errors</div></div>
426
  <div class="stat-box"><div class="v" id="dbc-purged">0</div><div class="l">Purged</div></div>
427
  </div>
 
449
  </button>
450
  </div>
451
  </div>
452
+ <p class="hint mb-3">"Load flagged" lists links the background checker found. Purging removes them.</p>
 
 
 
453
  <div class="dead-list" id="dead-list">
454
  <div class="hint">No dead links to show yet. Run a DB Check or load flagged links.</div>
455
  </div>
456
  </div>
457
 
458
+ <!-- Duplicate check & cleanup -->
459
+ <div class="tool-card">
460
+ <div class="flex items-center justify-between flex-wrap gap-2">
461
+ <h2 style="margin-bottom:0"><i class="fa-solid fa-clone"></i> Duplicate Check &amp; Cleanup</h2>
462
+ <span id="dup-status-pill" class="status-pill status-idle">Idle</span>
463
+ </div>
464
+
465
+ <p class="hint mt-3 mb-4">
466
+ Find and remove streams stored more than once. Deleting also removes the Telegram file.
467
+ </p>
468
+
469
+ <div class="stat-grid mb-4">
470
+ <div class="stat-box"><div class="v" id="dup-scanned">0</div><div class="l">Scanned</div></div>
471
+ <div class="stat-box"><div class="v" id="dup-groups">0</div><div class="l">Groups</div></div>
472
+ <div class="stat-box"><div class="v" style="color:var(--warn)" id="dup-count">0</div><div class="l">Redundant</div></div>
473
+ <div class="stat-box"><div class="v" id="dup-purged">0</div><div class="l">Removed</div></div>
474
+ </div>
475
+
476
+ <div class="flex items-center gap-2 flex-wrap mb-2">
477
+ <button class="btn btn-primary" id="dup-start-btn" onclick="startDuplicateCheck()">
478
+ <i class="fa-solid fa-magnifying-glass"></i> Scan for duplicates
479
+ </button>
480
+ <button class="btn btn-danger" id="dup-cancel-btn" onclick="cancelDuplicateCheck()" disabled>
481
+ <i class="fa-solid fa-stop"></i> Stop
482
+ </button>
483
+ </div>
484
+ <div id="dup-current" class="text-sm mb-2" style="color:var(--text-sec)">No scan running</div>
485
+
486
+ <div id="dup-purge-progress" class="hidden mb-2">
487
+ <div class="flex items-center justify-between mb-1 text-sm flex-wrap gap-2">
488
+ <span class="font-semibold" id="dup-purge-label"><i class="fa-solid fa-broom"></i> Removing duplicates…</span>
489
+ <span style="color:var(--text-sec)">
490
+ <span id="dup-purge-done">0</span>/<span id="dup-purge-total">0</span> ·
491
+ <i class="fa-regular fa-clock"></i> <span id="dup-purge-elapsed">0s</span> ·
492
+ ETA <span id="dup-purge-eta">—</span>
493
+ </span>
494
+ </div>
495
+ <div class="progress-track"><div class="progress-fill" id="dup-purge-bar"></div></div>
496
+ </div>
497
+
498
+ <hr class="divider">
499
+
500
+ <div class="flex items-center justify-between mb-3 flex-wrap gap-2">
501
+ <label class="s-label" style="margin-bottom:0">Duplicate groups</label>
502
+ <div class="flex items-center gap-2">
503
+ <button class="btn btn-ghost" type="button" id="dup-selected-btn" onclick="purgeDuplicates(false)" disabled>
504
+ <i class="fa-solid fa-trash"></i> Delete selected
505
+ </button>
506
+ <button class="btn btn-danger" type="button" id="dup-all-btn" onclick="purgeDuplicates(true)" disabled>
507
+ <i class="fa-solid fa-broom"></i> Delete all
508
+ </button>
509
+ </div>
510
+ </div>
511
+ <p class="hint mb-3">Pick copies to delete, or "Delete all" to keep only the newest of each group.</p>
512
+ <div class="dead-list" id="dup-list">
513
+ <div class="hint">No duplicates to show yet. Run a scan above.</div>
514
+ </div>
515
+ </div>
516
+
517
  </div>
518
 
519
  <script>
520
+ /* ─────────────── Manual Upload Session ─────────────── */
521
+ let msResults = [];
522
+ let msSelected = null;
523
+
524
+ async function searchManualSession() {
525
+ const q = document.getElementById('ms-query').value.trim();
526
+ const state = document.getElementById('ms-search-state');
527
+ const box = document.getElementById('ms-results');
528
+ if (!q) { showToast('Type a title, IMDb or TMDB id/link.', 'error', 'Search'); return; }
529
+ state.style.display = '';
530
+ state.textContent = 'Searching your library and IMDb / TMDB…';
531
+ box.style.display = 'none';
532
+ box.innerHTML = '';
533
+ document.getElementById('ms-selected-box').classList.add('hidden');
534
+ msSelected = null;
535
+ try {
536
+ const res = await fetch('/api/admin/tools/manual-session/search?query=' + encodeURIComponent(q));
537
+ const data = await res.json();
538
+ if (!res.ok) throw new Error(data.detail || 'Search failed');
539
+ msResults = data.results || [];
540
+ if (!msResults.length) {
541
+ state.textContent = 'No matching title found. Try a different name, or an IMDb / TMDB id or link.';
542
+ return;
543
+ }
544
+ state.textContent = `Found ${msResults.length} title${msResults.length > 1 ? 's' : ''}. Select one:`;
545
+ box.innerHTML = msResults.map((r, i) => {
546
+ const badge = r.in_library
547
+ ? `<span class="c-id">${escapeHtml(String(r.year || '—'))} · In library · TMDB ${escapeHtml(String(r.tmdb_id))} · DB #${escapeHtml(String(r.db_index))}</span>`
548
+ : `<span class="c-id">${escapeHtml(String(r.year || '—'))} · New · ${escapeHtml(String(r.source || '').toUpperCase())} · ${escapeHtml(String(r.selected_id || ''))}</span>`;
549
+ return `
550
+ <label class="chip" onclick="pickManualResult(${i})">
551
+ <img src="${escapeHtmlAttr(r.poster) || '/static/placeholder.svg'}" onerror="this.src='/static/placeholder.svg'"
552
+ style="width:2.25rem;height:3.25rem;object-fit:cover;border-radius:0.35rem;flex-shrink:0;background:var(--card)">
553
+ <span class="min-w-0">
554
+ <span class="c-name block truncate">${escapeHtml(r.title)}
555
+ <span class="status-pill ${r.media_type === 'tv' ? 'status-running' : 'status-idle'}" style="margin-left:.4rem">${r.media_type === 'tv' ? 'TV' : 'Movie'}</span>
556
+ </span>
557
+ ${badge}
558
+ </span>
559
+ </label>`;
560
+ }).join('');
561
+ box.style.display = '';
562
+ } catch (e) {
563
+ state.textContent = e.message || 'Search failed.';
564
+ }
565
+ }
566
+
567
+ function pickManualResult(i) {
568
+ const r = msResults[i];
569
+ if (!r) return;
570
+ msSelected = r;
571
+ const isPersonal = !!r.is_personal;
572
+ const isTv = r.media_type === 'tv';
573
+
574
+ document.getElementById('ms-sel-poster').src = r.poster || '/static/placeholder.svg';
575
+ document.getElementById('ms-sel-title').textContent = r.title;
576
+ const locationText = r.in_library ? `TMDB ${r.tmdb_id} · DB #${r.db_index}` : `New · ${String(r.source || '').toUpperCase()} ${r.selected_id || ''}`;
577
+ document.getElementById('ms-sel-sub').textContent =
578
+ `${isTv ? 'TV Show' : 'Movie'} · ${isPersonal ? 'Personal' : 'TMDB/IMDb'} · ${r.year || '—'} · ${locationText}`;
579
+
580
+ document.getElementById('ms-real-note').classList.toggle('hidden', isPersonal);
581
+ document.getElementById('ms-real-tv-season').classList.toggle('hidden', isPersonal || !isTv);
582
+ document.getElementById('ms-personal-fields').classList.toggle('hidden', !isPersonal);
583
+ document.getElementById('ms-tv-fields').classList.toggle('hidden', !(isPersonal && isTv));
584
+
585
+ document.getElementById('ms-season').value = '';
586
+ document.getElementById('ms-episode').value = '';
587
+ document.getElementById('ms-quality').value = '';
588
+ document.getElementById('ms-real-season').value = '';
589
+ document.getElementById('ms-selected-box').classList.remove('hidden');
590
+ document.getElementById('ms-results').style.display = 'none';
591
+ }
592
+
593
+ async function startManualSession() {
594
+ if (!msSelected) { showToast('Select a title first.', 'error', 'Session'); return; }
595
+ const payload = {
596
+ tmdb_id: msSelected.tmdb_id,
597
+ db_index: msSelected.db_index,
598
+ media_type: msSelected.media_type,
599
+ selected_id: msSelected.selected_id,
600
+ in_library: msSelected.in_library !== false,
601
+ };
602
+ if (!msSelected.in_library && msSelected.media_type === 'tv') {
603
+ const rs = document.getElementById('ms-real-season').value.trim();
604
+ if (rs !== '') payload.season = rs;
605
+ }
606
+ if (msSelected.is_personal) {
607
+ if (msSelected.media_type === 'tv') {
608
+ const s = document.getElementById('ms-season').value.trim();
609
+ if (s === '') { showToast('Season number is required for personal TV shows.', 'error', 'Session'); return; }
610
+ payload.season = s;
611
+ const ep = document.getElementById('ms-episode').value.trim();
612
+ if (ep !== '') payload.episode = ep;
613
+ }
614
+ const q = document.getElementById('ms-quality').value.trim();
615
+ if (q !== '') payload.quality = q;
616
+ } else if (msSelected.media_type === 'tv') {
617
+ const rs = document.getElementById('ms-real-season').value.trim();
618
+ if (rs !== '') payload.season = rs;
619
+ }
620
+ try {
621
+ const res = await fetch('/api/admin/tools/manual-session', {
622
+ method: 'POST',
623
+ headers: { 'Content-Type': 'application/json' },
624
+ body: JSON.stringify(payload)
625
+ });
626
+ const data = await res.json();
627
+ if (!res.ok) throw new Error(data.detail || 'Could not start session');
628
+ showToast('Session started. Forward files to your manual channel.', 'success', 'Session');
629
+ renderManualSession(data.session);
630
+ } catch (e) {
631
+ showToast(e.message || 'Could not start session.', 'error', 'Session');
632
+ }
633
+ }
634
+
635
+ async function endManualSession() {
636
+ try {
637
+ const res = await fetch('/api/admin/tools/manual-session', { method: 'DELETE' });
638
+ const data = await res.json();
639
+ if (!res.ok) throw new Error(data.detail || 'Could not end session');
640
+ showToast('Session ended.', 'info', 'Session');
641
+ renderManualSession(null);
642
+ } catch (e) {
643
+ showToast(e.message || 'Could not end session.', 'error', 'Session');
644
+ }
645
+ }
646
+
647
+ function renderManualSession(session) {
648
+ const pill = document.getElementById('ms-status-pill');
649
+ const active = document.getElementById('ms-active');
650
+ const setup = document.getElementById('ms-setup');
651
+
652
+ if (session && session.tmdb_id !== undefined && session.tmdb_id !== null) {
653
+ pill.className = 'status-pill status-running';
654
+ pill.textContent = 'Active';
655
+ active.classList.remove('hidden');
656
+ setup.classList.add('hidden');
657
+
658
+ const isTv = session.media_type === 'tv';
659
+ document.getElementById('ms-active-title').textContent =
660
+ `${session.title || 'Title'}${session.year ? ' (' + session.year + ')' : ''}`;
661
+
662
+ let detail = isTv ? 'TV Show' : 'Movie';
663
+ if (session.is_personal) {
664
+ detail += ' · Personal';
665
+ if (isTv) {
666
+ detail += ` · Season ${session.season}`;
667
+ detail += (session.episode !== null && session.episode !== undefined)
668
+ ? ` · Episode ${session.episode} (all files → this episode)`
669
+ : ' · each file → next episode';
670
+ } else {
671
+ detail += ' · each file → a new quality';
672
+ }
673
+ detail += ' · forward to MANUAL channel only';
674
+ } else {
675
+ detail += ' · TMDB/IMDb · auto-detected from each file';
676
+ if (isTv && session.season !== null && session.season !== undefined) {
677
+ detail += ` · fallback Season ${session.season}`;
678
+ }
679
+ detail += ' · forward to AUTH or MANUAL channel';
680
+ }
681
+ document.getElementById('ms-active-detail').textContent = detail;
682
+ } else {
683
+ pill.className = 'status-pill status-idle';
684
+ pill.textContent = 'No session';
685
+ active.classList.add('hidden');
686
+ setup.classList.remove('hidden');
687
+ document.getElementById('ms-results').style.display = 'none';
688
+ document.getElementById('ms-selected-box').classList.add('hidden');
689
+ document.getElementById('ms-search-state').style.display = 'none';
690
+ msSelected = null;
691
+ }
692
+ }
693
+
694
+ async function loadManualSession() {
695
+ try {
696
+ const res = await fetch('/api/admin/tools/manual-session');
697
+ const data = await res.json();
698
+ renderManualSession(data.session);
699
+ } catch (e) { /* ignore */ }
700
+ }
701
+
702
  /* ─────────────── State ─────────────── */
703
  let scanTimer = null;
704
  let dbcTimer = null;
705
+ let dupTimer = null;
706
+ let dupPurgeTimer = null;
707
+ let dupPurgeActive = false;
708
+ let dupGroups = [];
709
  let deadSource = "dbcheck"; // where the current dead list came from
710
  let purgeIds = []; // explicit ids to purge when source = flagged
711
 
 
730
  </label>
731
  `).join('');
732
  } catch (e) {
733
+ list.innerHTML = `<div class="hint" style="color:var(--danger)">Failed to load channels.</div>`;
734
  }
735
  }
736
 
 
819
  setText('sc-dup', c.skipped_dup || 0);
820
  setText('sc-meta', c.skipped_meta || 0);
821
  setText('sc-nonvid', c.skipped_nonvid || 0);
822
+ setText('sc-sub-added', c.subtitles_added || 0);
823
+ setText('sc-sub-skipped', c.subtitles_skipped || 0);
824
  setText('sc-errors', c.errors || 0);
825
  setText('scan-elapsed', s.elapsed || '0s');
826
 
 
966
  list.innerHTML = entries.map(e => `
967
  <div class="dead-row">
968
  <span class="min-w-0 truncate">
969
+ <i class="fa-solid fa-link-slash" style="color:var(--danger)"></i>
970
  ${escapeHtml(e.title || 'Unknown')}
971
  ${e.quality ? `<span class="c-id">· ${escapeHtml(e.quality)}</span>` : ''}
972
  </span>
 
1016
  }
1017
  }
1018
 
1019
+ /* ─────────────── Duplicate check & cleanup ─────────────── */
1020
+ async function startDuplicateCheck() {
1021
+ try {
1022
+ const res = await fetch('/api/admin/tools/duplicates/start', { method: 'POST' });
1023
+ const data = await res.json();
1024
+ if (res.ok) {
1025
+ showToast('Duplicate scan started.', 'success', 'Duplicates');
1026
+ startDupPolling();
1027
+ } else {
1028
+ showToast(data.detail || 'Could not start.', 'error', 'Error');
1029
+ }
1030
+ } catch (e) { showToast('Network error.', 'error', 'Error'); }
1031
+ }
1032
+
1033
+ async function cancelDuplicateCheck() {
1034
+ try {
1035
+ const res = await fetch('/api/admin/tools/duplicates/cancel', { method: 'POST' });
1036
+ const data = await res.json();
1037
+ showToast(data.message || 'Stop requested.', data.ok ? 'info' : 'error', 'Duplicates');
1038
+ } catch (e) { showToast('Network error.', 'error', 'Error'); }
1039
+ }
1040
+
1041
+ function startDupPolling() {
1042
+ if (dupTimer) clearInterval(dupTimer);
1043
+ pollDup();
1044
+ dupTimer = setInterval(pollDup, 1500);
1045
+ }
1046
+
1047
+ async function pollDup() {
1048
+ try {
1049
+ const res = await fetch('/api/admin/tools/duplicates/status');
1050
+ const data = await res.json();
1051
+ renderDup(data.data || {});
1052
+ } catch (e) { /* ignore */ }
1053
+ }
1054
+
1055
+ function renderDup(s) {
1056
+ const pill = document.getElementById('dup-status-pill');
1057
+ const status = s.status || 'idle';
1058
+ pill.className = 'status-pill status-' + status;
1059
+ pill.textContent = status.charAt(0).toUpperCase() + status.slice(1);
1060
+
1061
+ setText('dup-scanned', s.scanned || 0);
1062
+ setText('dup-groups', s.group_count || 0);
1063
+ setText('dup-count', s.duplicate_count || 0);
1064
+ setText('dup-purged', s.purged || 0);
1065
+
1066
+ const startBtn = document.getElementById('dup-start-btn');
1067
+ const cancelBtn = document.getElementById('dup-cancel-btn');
1068
+ if (s.is_running) {
1069
+ startBtn.disabled = true; cancelBtn.disabled = false;
1070
+ document.getElementById('dup-current').textContent = `Scanning… ${s.scanned || 0} titles checked`;
1071
+ } else {
1072
+ startBtn.disabled = false; cancelBtn.disabled = true;
1073
+ document.getElementById('dup-current').textContent =
1074
+ status === 'completed' ? `Done — ${s.group_count || 0} duplicate group(s) found.` :
1075
+ status === 'cancelled' ? 'Stopped.' :
1076
+ status === 'error' ? 'Scan failed.' : 'No scan running';
1077
+ if (dupTimer && ['completed','cancelled','error','idle'].includes(status)) {
1078
+ clearInterval(dupTimer); dupTimer = null;
1079
+ }
1080
+ }
1081
+
1082
+ renderDupPurge(s);
1083
+ dupGroups = s.groups || [];
1084
+ renderDupList();
1085
+ }
1086
+
1087
+ /* Cleanup progress bar (poll-driven) */
1088
+ function renderDupPurge(s) {
1089
+ const box = document.getElementById('dup-purge-progress');
1090
+ const pStatus = s.purge_status || 'idle';
1091
+ const selBtn = document.getElementById('dup-selected-btn');
1092
+ const allBtn = document.getElementById('dup-all-btn');
1093
+ const startBtn = document.getElementById('dup-start-btn');
1094
+
1095
+ if (pStatus === 'running') {
1096
+ dupPurgeActive = true;
1097
+ box.classList.remove('hidden');
1098
+ setText('dup-purge-done', s.purge_done || 0);
1099
+ setText('dup-purge-total', s.purge_total || 0);
1100
+ setText('dup-purge-elapsed', s.purge_elapsed || '0s');
1101
+ setText('dup-purge-eta', s.purge_eta || '—');
1102
+ document.getElementById('dup-purge-bar').style.width = (s.purge_progress || 0) + '%';
1103
+ selBtn.disabled = true; allBtn.disabled = true; startBtn.disabled = true;
1104
+ if (!dupPurgeTimer) startDupPurgePolling();
1105
+ return;
1106
+ }
1107
+
1108
+ if (dupPurgeActive && (pStatus === 'completed' || pStatus === 'error')) {
1109
+ dupPurgeActive = false;
1110
+ if (dupPurgeTimer) { clearInterval(dupPurgeTimer); dupPurgeTimer = null; }
1111
+ setText('dup-purge-done', s.purge_done || 0);
1112
+ setText('dup-purge-total', s.purge_total || 0);
1113
+ setText('dup-purge-elapsed', s.purge_elapsed || '0s');
1114
+ setText('dup-purge-eta', '—');
1115
+ document.getElementById('dup-purge-bar').style.width = '100%';
1116
+ document.getElementById('dup-purge-label').innerHTML = pStatus === 'completed'
1117
+ ? '<i class="fa-solid fa-check"></i> Cleanup complete'
1118
+ : '<i class="fa-solid fa-triangle-exclamation"></i> Cleanup failed';
1119
+ showToast(
1120
+ pStatus === 'completed' ? `Removed ${s.purge_total || 0} duplicate(s).` : (s.error || 'Cleanup failed.'),
1121
+ pStatus === 'completed' ? 'success' : 'error', 'Duplicates'
1122
+ );
1123
+ setTimeout(() => document.getElementById('dup-purge-progress').classList.add('hidden'), 2500);
1124
+ }
1125
+ }
1126
+
1127
+ function renderDupList() {
1128
+ const list = document.getElementById('dup-list');
1129
+ const selBtn = document.getElementById('dup-selected-btn');
1130
+ const allBtn = document.getElementById('dup-all-btn');
1131
+ const purging = dupPurgeActive;
1132
+
1133
+ if (!dupGroups.length) {
1134
+ list.innerHTML = `<div class="hint">No duplicates to show.</div>`;
1135
+ selBtn.disabled = true; allBtn.disabled = true;
1136
+ return;
1137
+ }
1138
+ list.innerHTML = dupGroups.map(g => `
1139
+ <div class="dead-row" style="flex-direction:column;align-items:stretch;gap:0.5rem">
1140
+ <div class="min-w-0 truncate font-semibold">
1141
+ <i class="fa-solid fa-clone" style="color:var(--warn)"></i>
1142
+ ${escapeHtml(g.title || 'Unknown')}
1143
+ <span class="c-id">· ${escapeHtml(g.quality || '')} · ${g.entries.length} copies</span>
1144
+ </div>
1145
+ ${g.entries.map((e, i) => `
1146
+ <label class="flex items-center gap-2 text-sm" style="padding-left:1.25rem">
1147
+ <input type="checkbox" class="dup-cb" data-id="${escapeHtmlAttr(e.id)}"
1148
+ ${i === g.entries.length - 1 ? '' : 'checked'}>
1149
+ <span class="min-w-0 truncate">${escapeHtml(e.name || 'file')}
1150
+ <span class="c-id">· ${escapeHtml(e.size || '')}${i === g.entries.length - 1 ? ' · newest' : ''}</span>
1151
+ </span>
1152
+ </label>
1153
+ `).join('')}
1154
+ </div>
1155
+ `).join('');
1156
+ selBtn.disabled = purging; allBtn.disabled = purging;
1157
+ }
1158
+
1159
+ async function purgeDuplicates(deleteAll) {
1160
+ let body;
1161
+ if (deleteAll) {
1162
+ if (!confirm('Keep the newest copy of every group and permanently delete the rest (including the Telegram files)?')) return;
1163
+ body = { delete_all: true };
1164
+ } else {
1165
+ const ids = Array.from(document.querySelectorAll('#dup-list .dup-cb:checked')).map(cb => cb.dataset.id);
1166
+ if (!ids.length) { showToast('Select at least one copy to delete.', 'error', 'Duplicates'); return; }
1167
+ if (!confirm(`Permanently delete ${ids.length} selected cop${ids.length === 1 ? 'y' : 'ies'} (including the Telegram files)?`)) return;
1168
+ body = { stream_ids: ids };
1169
+ }
1170
+ document.getElementById('dup-selected-btn').disabled = true;
1171
+ document.getElementById('dup-all-btn').disabled = true;
1172
+ document.getElementById('dup-start-btn').disabled = true;
1173
+
1174
+ const box = document.getElementById('dup-purge-progress');
1175
+ box.classList.remove('hidden');
1176
+ document.getElementById('dup-purge-label').innerHTML = '<i class="fa-solid fa-broom"></i> Removing duplicates…';
1177
+ document.getElementById('dup-purge-bar').style.width = '0%';
1178
+ setText('dup-purge-done', 0);
1179
+ setText('dup-purge-eta', '—');
1180
+
1181
+ try {
1182
+ const res = await fetch('/api/admin/tools/duplicates/purge', {
1183
+ method: 'POST',
1184
+ headers: { 'Content-Type': 'application/json' },
1185
+ body: JSON.stringify(body)
1186
+ });
1187
+ const data = await res.json();
1188
+ if (res.ok && data.ok) {
1189
+ setText('dup-purge-total', data.total || 0);
1190
+ showToast(data.message || 'Cleanup started.', 'info', 'Duplicates');
1191
+ dupPurgeActive = true;
1192
+ startDupPurgePolling();
1193
+ } else {
1194
+ box.classList.add('hidden');
1195
+ showToast(data.message || data.detail || 'Nothing removed.', 'error', 'Duplicates');
1196
+ document.getElementById('dup-selected-btn').disabled = false;
1197
+ document.getElementById('dup-all-btn').disabled = false;
1198
+ document.getElementById('dup-start-btn').disabled = false;
1199
+ }
1200
+ } catch (e) {
1201
+ box.classList.add('hidden');
1202
+ showToast('Network error.', 'error', 'Error');
1203
+ document.getElementById('dup-selected-btn').disabled = false;
1204
+ document.getElementById('dup-all-btn').disabled = false;
1205
+ document.getElementById('dup-start-btn').disabled = false;
1206
+ }
1207
+ }
1208
+
1209
+ function startDupPurgePolling() {
1210
+ if (dupPurgeTimer) clearInterval(dupPurgeTimer);
1211
+ pollDup();
1212
+ dupPurgeTimer = setInterval(pollDup, 700);
1213
+ }
1214
+
1215
+ let baData = null;
1216
+ let baApplyTimer = null;
1217
+
1218
+ const BA_STAT = {
1219
+ admin: '<span class="ba-cell ba-ok"><i class="fa-solid fa-circle-check"></i> Admin</span>',
1220
+ member: '<span class="ba-cell ba-warn"><i class="fa-solid fa-circle"></i> Member</span>',
1221
+ restricted: '<span class="ba-cell ba-warn"><i class="fa-solid fa-ban"></i> Restricted</span>',
1222
+ banned: '<span class="ba-cell ba-no"><i class="fa-solid fa-ban"></i> Banned</span>',
1223
+ missing: '<span class="ba-cell ba-no"><i class="fa-solid fa-circle-xmark"></i> Not in</span>',
1224
+ };
1225
+ const BA_SESSION = {
1226
+ owner: '<span class="ba-cell ba-ok"><i class="fa-solid fa-crown"></i> Owner</span>',
1227
+ admin_can_promote: '<span class="ba-cell ba-ok"><i class="fa-solid fa-user-shield"></i> Admin · can add</span>',
1228
+ admin_no_promote: '<span class="ba-cell ba-warn"><i class="fa-solid fa-user-shield"></i> No add-admin</span>',
1229
+ not_admin: '<span class="ba-cell ba-no"><i class="fa-solid fa-lock"></i> Not admin</span>',
1230
+ unknown: '<span class="ba-cell ba-muted"><i class="fa-solid fa-question"></i> Unknown</span>',
1231
+ };
1232
+
1233
+ async function loadBotAdmin() {
1234
+ const body = document.getElementById('ba-body');
1235
+ if (!body) return;
1236
+ const loading = document.getElementById('ba-loading');
1237
+ const errEl = document.getElementById('ba-error');
1238
+ const pill = document.getElementById('ba-status-pill');
1239
+ loading.style.display = ''; errEl.style.display = 'none'; body.style.display = 'none';
1240
+ pill.className = 'status-pill status-running'; pill.textContent = 'Scanning';
1241
+ try {
1242
+ const res = await fetch('/api/admin/tools/bot-admin/scan');
1243
+ const data = await res.json();
1244
+ loading.style.display = 'none';
1245
+ if (data.status !== 'success') {
1246
+ errEl.style.display = ''; errEl.textContent = data.message || 'Scan failed.';
1247
+ pill.className = 'status-pill status-error'; pill.textContent = 'Error';
1248
+ return;
1249
+ }
1250
+ baData = data.data;
1251
+ renderBotAdmin();
1252
+ body.style.display = '';
1253
+ pill.className = 'status-pill status-idle'; pill.textContent = 'Ready';
1254
+ } catch (e) {
1255
+ loading.style.display = 'none';
1256
+ errEl.style.display = ''; errEl.textContent = 'Network error while scanning.';
1257
+ pill.className = 'status-pill status-error'; pill.textContent = 'Error';
1258
+ }
1259
+ }
1260
+
1261
+ function renderBotAdmin() {
1262
+ const bots = (baData && baData.bots) || [];
1263
+ const channels = (baData && baData.channels) || [];
1264
+
1265
+ document.getElementById('ba-bots').innerHTML = bots.map(b => `
1266
+ <label class="chip ba-bot-chip" style="width:auto">
1267
+ <input type="checkbox" class="ba-bot-cb" value="${escapeHtmlAttr(String(b.user_id))}" checked>
1268
+ <span class="min-w-0">
1269
+ <span class="c-name block">${escapeHtml(b.name)}${b.is_main ? ' <span class="c-id">(main)</span>' : ''}</span>
1270
+ <span class="c-id">${b.username ? '@' + escapeHtml(b.username) : escapeHtml(String(b.user_id))}</span>
1271
+ </span>
1272
+ </label>
1273
+ `).join('') || '<span class="hint">No bots detected.</span>';
1274
+
1275
+ const wrap = document.getElementById('ba-channels');
1276
+ if (!channels.length) {
1277
+ wrap.innerHTML = `<div class="hint" style="padding:0.5rem 0">
1278
+ No bot-served channels configured. Add auth / manual / anime / announce / skip channels in
1279
+ <a href="/admin/settings" style="color:var(--primary)">Settings</a>.</div>`;
1280
+ return;
1281
+ }
1282
+
1283
+ wrap.innerHTML = channels.map(ch => {
1284
+ const roles = (ch.roles || []).map(r => `<span class="ba-role">${escapeHtml(r)}</span>`).join('');
1285
+ const session = BA_SESSION[ch.session_status] || BA_SESSION.unknown;
1286
+ const disabled = ch.manageable ? '' : 'disabled';
1287
+ const reason = (!ch.manageable && ch.reason)
1288
+ ? `<div class="hint" style="color:var(--warn);margin-top:0.5rem"><i class="fa-solid fa-triangle-exclamation"></i> ${escapeHtml(ch.reason)}</div>` : '';
1289
+ const botStats = bots.map(b => `
1290
+ <div class="ba-bstat">
1291
+ <span class="n">${escapeHtml(b.name)}</span>
1292
+ ${BA_STAT[ch.bots[String(b.user_id)]] || BA_STAT.missing}
1293
+ </div>`).join('');
1294
+ const orphans = (ch.orphans || []).length
1295
+ ? `<div class="hint" style="margin-top:0.5rem"><i class="fa-solid fa-user-slash ba-warn"></i> Orphan admins: ${
1296
+ ch.orphans.map(o => escapeHtml(o.name || String(o.user_id))).join(', ')}</div>` : '';
1297
+ return `
1298
+ <div class="ba-ch-card${ch.manageable ? '' : ' ba-locked'}">
1299
+ <div class="ba-ch-top">
1300
+ <label class="ba-ch-sel">
1301
+ <input type="checkbox" class="ba-ch-cb" value="${escapeHtmlAttr(ch.id)}" ${disabled} onchange="onBaChipChange(this)">
1302
+ <span class="min-w-0">
1303
+ <span class="ba-ch-name">${escapeHtml(ch.name)}</span>
1304
+ <span class="ba-ch-id block">${escapeHtml(ch.id)}</span>
1305
+ </span>
1306
+ </label>
1307
+ <span style="flex-shrink:0">${session}</span>
1308
+ </div>
1309
+ <div class="ba-roles" style="margin-top:0.5rem">${roles}</div>
1310
+ <div class="ba-bot-grid">${botStats}</div>
1311
+ ${orphans}
1312
+ ${reason}
1313
+ </div>`;
1314
+ }).join('');
1315
+ }
1316
+
1317
+ function onBaChipChange(input) {
1318
+ input.closest('.ba-ch-card').classList.toggle('selected', input.checked);
1319
+ }
1320
+ function selectAllBaChannels(state) {
1321
+ document.querySelectorAll('#ba-channels .ba-ch-cb:not([disabled])').forEach(cb => {
1322
+ cb.checked = state; onBaChipChange(cb);
1323
+ });
1324
+ }
1325
+ function getSelectedBaChannels() {
1326
+ return [...document.querySelectorAll('#ba-channels .ba-ch-cb:checked')].map(cb => cb.value);
1327
+ }
1328
+ function getSelectedBaBots() {
1329
+ return [...document.querySelectorAll('#ba-bots .ba-bot-cb:checked')].map(cb => cb.value);
1330
+ }
1331
+
1332
+ async function applyBotAdmin() {
1333
+ const channels = getSelectedBaChannels();
1334
+ const botIds = getSelectedBaBots();
1335
+ const demote = document.getElementById('ba-demote-orphans').checked;
1336
+
1337
+ if (!channels.length) { showToast('Select at least one channel.', 'error', 'Bot Admin'); return; }
1338
+ if (!botIds.length) { showToast('Select at least one bot to add.', 'error', 'Bot Admin'); return; }
1339
+
1340
+ let msg = `Add ${botIds.length} bot(s) as admin to ${channels.length} channel(s)?`;
1341
+ if (demote) msg += '\n\nOrphan bot-admins (not in your token list) will also be demoted.';
1342
+ if (!confirm(msg)) return;
1343
+
1344
+ const btn = document.getElementById('ba-apply-btn');
1345
+ btn.disabled = true;
1346
+ btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Applying…';
1347
+ document.getElementById('ba-results').style.display = 'none';
1348
+ try {
1349
+ const res = await fetch('/api/admin/tools/bot-admin/apply', {
1350
+ method: 'POST',
1351
+ headers: { 'Content-Type': 'application/json' },
1352
+ body: JSON.stringify({ channel_ids: channels, bot_ids: botIds, demote_orphans: demote })
1353
+ });
1354
+ const data = await res.json();
1355
+ if (!res.ok || (data.status !== 'started' && data.status !== 'success')) {
1356
+ showToast(data.detail || data.message || 'Could not start.', 'error', 'Bot Admin');
1357
+ resetBaApplyBtn();
1358
+ return;
1359
+ }
1360
+ const total = data.total || channels.length;
1361
+ const prog = document.getElementById('ba-progress');
1362
+ prog.style.display = '';
1363
+ setText('ba-prog-total', total);
1364
+ setText('ba-prog-done', 0);
1365
+ document.getElementById('ba-prog-bar').style.width = '0%';
1366
+ startBaApplyPolling();
1367
+ } catch (e) {
1368
+ showToast('Could not reach the server.', 'error', 'Bot Admin');
1369
+ resetBaApplyBtn();
1370
+ }
1371
+ }
1372
+
1373
+ function resetBaApplyBtn() {
1374
+ const btn = document.getElementById('ba-apply-btn');
1375
+ btn.disabled = false;
1376
+ btn.innerHTML = '<i class="fa-solid fa-user-plus"></i> Add selected bots as admin';
1377
+ }
1378
+
1379
+ function startBaApplyPolling() {
1380
+ if (baApplyTimer) clearInterval(baApplyTimer);
1381
+ pollBaApply();
1382
+ baApplyTimer = setInterval(pollBaApply, 1500);
1383
+ }
1384
+
1385
+ async function pollBaApply() {
1386
+ let data;
1387
+ try {
1388
+ const res = await fetch('/api/admin/tools/bot-admin/apply/status');
1389
+ data = (await res.json()).data;
1390
+ } catch (e) { return; }
1391
+ if (!data) return;
1392
+
1393
+ const total = data.total || 0;
1394
+ const done = data.done || 0;
1395
+ setText('ba-prog-total', total);
1396
+ setText('ba-prog-done', done);
1397
+ document.getElementById('ba-prog-bar').style.width = (total ? Math.round((done / total) * 100) : 0) + '%';
1398
+
1399
+ if (data.running) return;
1400
+
1401
+ if (baApplyTimer) { clearInterval(baApplyTimer); baApplyTimer = null; }
1402
+ setTimeout(() => { document.getElementById('ba-progress').style.display = 'none'; }, 1200);
1403
+ resetBaApplyBtn();
1404
+
1405
+ if (data.state === 'error') {
1406
+ showToast(data.error || 'Apply failed.', 'error', 'Bot Admin');
1407
+ } else {
1408
+ showToast('Done. See the report below.', 'success', 'Bot Admin');
1409
+ }
1410
+ renderBotAdminResults(data.results || []);
1411
+ loadBotAdmin();
1412
+ }
1413
+
1414
+ function renderBotAdminResults(results) {
1415
+ const box = document.getElementById('ba-results');
1416
+ if (!results.length) { box.style.display = 'none'; return; }
1417
+ const icon = { added: '<i class="fa-solid fa-circle-check ba-ok"></i>', already: '<i class="fa-solid fa-circle-check ba-muted"></i>', demoted: '<i class="fa-solid fa-user-minus ba-warn"></i>', skipped: '<i class="fa-solid fa-forward ba-warn"></i>', error: '<i class="fa-solid fa-circle-xmark ba-no"></i>' };
1418
+ box.style.display = '';
1419
+ box.innerHTML = results.map(ch => `
1420
+ <div class="ba-res-row">
1421
+ <div class="font-semibold"><i class="fa-solid fa-hashtag ba-muted"></i> ${escapeHtml(ch.name)}</div>
1422
+ ${(ch.items || []).map(it => `
1423
+ <div style="display:flex;gap:0.5rem;align-items:flex-start;padding-left:1rem">
1424
+ ${icon[it.status] || ''}
1425
+ <span class="min-w-0"><span class="font-semibold">${escapeHtml(it.bot)}</span>
1426
+ <span class="c-id">— ${escapeHtml(it.message || it.status)}</span></span>
1427
+ </div>
1428
+ `).join('')}
1429
+ </div>
1430
+ `).join('');
1431
+ }
1432
+
1433
  /* ─────────────── Utils ─────────────── */
1434
  function setText(id, val) { const el = document.getElementById(id); if (el) el.textContent = val; }
1435
  function escapeHtml(str) {
 
1441
  }
1442
 
1443
  /* ─────────────── Init ─────────────── */
1444
+ loadManualSession();
1445
  loadChannels();
1446
  pollScan().then(() => {
1447
  const pill = document.getElementById('scan-status-pill');
 
1451
  const pill = document.getElementById('dbc-status-pill');
1452
  if (pill.classList.contains('status-running')) startDbcPolling();
1453
  });
1454
+ pollDup().then(() => {
1455
+ const pill = document.getElementById('dup-status-pill');
1456
+ if (pill.classList.contains('status-running')) startDupPolling();
1457
+ });
1458
  </script>
1459
 
1460
  {% endblock %}
Backend/fastapi/themes.py CHANGED
@@ -1,145 +1,65 @@
1
- DEFAULT_THEME = "graphite_amber"
2
 
3
  THEMES = {
4
- "graphite_amber": {
5
- "name": "Graphite Amber",
6
  "is_dark": True,
7
  "colors": {
8
- "primary": "#F59E0B",
9
- "secondary": "#D97706",
10
- "accent": "#FBBF24",
11
- "background": "#0C0C0D",
12
- "card": "#18181B",
13
- "border": "#2B2B30",
14
- "text": "#FAFAF9",
15
- "text_secondary": "#A9A8A4"
 
 
16
  },
17
- "css_classes": "theme-graphite-amber"
18
  },
19
- "amoled_midnight": {
20
- "name": "AMOLED Midnight",
21
- "is_dark": True,
22
- "colors": {
23
- "primary": "#38BDF8",
24
- "secondary": "#0EA5E9",
25
- "accent": "#818CF8",
26
- "background": "#000000",
27
- "card": "#0B0B0F",
28
- "border": "#1E2430",
29
- "text": "#F4F7FB",
30
- "text_secondary": "#9AA6B8"
31
- },
32
- "css_classes": "theme-amoled-midnight"
33
- },
34
- "obsidian_emerald": {
35
- "name": "Obsidian Emerald",
36
- "is_dark": True,
37
- "colors": {
38
- "primary": "#10B981",
39
- "secondary": "#059669",
40
- "accent": "#34D399",
41
- "background": "#08100C",
42
- "card": "#111C16",
43
- "border": "#203029",
44
- "text": "#ECFDF5",
45
- "text_secondary": "#92B6A4"
46
- },
47
- "css_classes": "theme-obsidian-emerald"
48
- },
49
- "royal_violet": {
50
- "name": "Royal Violet",
51
- "is_dark": True,
52
- "colors": {
53
- "primary": "#8B5CF6",
54
- "secondary": "#7C3AED",
55
- "accent": "#A78BFA",
56
- "background": "#0B0712",
57
- "card": "#171022",
58
- "border": "#2C2142",
59
- "text": "#F5F3FF",
60
- "text_secondary": "#B4A8CF"
61
- },
62
- "css_classes": "theme-royal-violet"
63
- },
64
- "slate_ocean": {
65
- "name": "Slate Ocean",
66
- "is_dark": True,
67
- "colors": {
68
- "primary": "#0EA5E9",
69
- "secondary": "#0284C7",
70
- "accent": "#38BDF8",
71
- "background": "#0A0F1A",
72
- "card": "#121C2B",
73
- "border": "#23324B",
74
- "text": "#EFF6FF",
75
- "text_secondary": "#93A7C4"
76
- },
77
- "css_classes": "theme-slate-ocean"
78
- },
79
- "rose_quartz": {
80
- "name": "Rose Quartz",
81
- "is_dark": False,
82
- "colors": {
83
- "primary": "#E11D48",
84
- "secondary": "#BE123C",
85
- "accent": "#F43F5E",
86
- "background": "#FFF1F2",
87
- "card": "#FFFFFF",
88
- "border": "#FBD5DB",
89
- "text": "#4C0519",
90
- "text_secondary": "#8A2B3E"
91
- },
92
- "css_classes": "theme-rose-quartz"
93
- },
94
- "daylight_sky": {
95
- "name": "Daylight Sky",
96
  "is_dark": False,
97
  "colors": {
98
- "primary": "#2563EB",
99
- "secondary": "#1D4ED8",
100
- "accent": "#3B82F6",
101
- "background": "#F8FAFC",
102
- "card": "#FFFFFF",
103
- "border": "#E2E8F0",
104
- "text": "#0F172A",
105
- "text_secondary": "#475569"
 
 
106
  },
107
- "css_classes": "theme-daylight-sky"
108
  },
109
- "sage_linen": {
110
- "name": "Sage Linen",
111
- "is_dark": False,
112
  "colors": {
113
- "primary": "#0F766E",
114
- "secondary": "#0D9488",
115
- "accent": "#14B8A6",
116
- "background": "#F5F8F6",
117
- "card": "#FFFFFF",
118
- "border": "#DCE7E3",
119
- "text": "#11271F",
120
- "text_secondary": "#4B5D58"
 
 
121
  },
122
- "css_classes": "theme-sage-linen"
123
  },
124
- "golden_hour": {
125
- "name": "Golden Hour",
126
- "is_dark": False,
127
- "colors": {
128
- "primary": "#B45309",
129
- "secondary": "#92400E",
130
- "accent": "#D97706",
131
- "background": "#FFFBF2",
132
- "card": "#FFFFFF",
133
- "border": "#F0E4CC",
134
- "text": "#3F2D12",
135
- "text_secondary": "#7A5A2E"
136
- },
137
- "css_classes": "theme-golden-hour"
138
- }
139
  }
140
 
 
141
  def get_theme(theme_name: str = DEFAULT_THEME):
142
  return THEMES.get(theme_name, THEMES[DEFAULT_THEME])
143
 
 
144
  def get_all_themes():
145
  return THEMES
 
 
 
 
 
 
1
+ DEFAULT_THEME = "paper"
2
 
3
  THEMES = {
4
+ "ink": {
5
+ "name": "Ink",
6
  "is_dark": True,
7
  "colors": {
8
+ "primary": "#E9A23B",
9
+ "on_primary": "#1A1405",
10
+ "background": "#121212",
11
+ "card": "#1A1A19",
12
+ "card_high": "#232321",
13
+ "border": "#2E2D2A",
14
+ "text": "#EFECE6",
15
+ "text_secondary": "#8F8A82",
16
+ "danger": "#E5534B",
17
+ "ok": "#7BB662",
18
  },
 
19
  },
20
+ "paper": {
21
+ "name": "Paper",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  "is_dark": False,
23
  "colors": {
24
+ "primary": "#B9471A",
25
+ "on_primary": "#FFFFFF",
26
+ "background": "#F3F0E8",
27
+ "card": "#FBF9F4",
28
+ "card_high": "#EAE5DA",
29
+ "border": "#DCD5C7",
30
+ "text": "#1D1B18",
31
+ "text_secondary": "#6E685E",
32
+ "danger": "#B42318",
33
+ "ok": "#3F7D2C",
34
  },
 
35
  },
36
+ "night": {
37
+ "name": "Night",
38
+ "is_dark": True,
39
  "colors": {
40
+ "primary": "#8CC4AE",
41
+ "on_primary": "#06140F",
42
+ "background": "#000000",
43
+ "card": "#0B0B0B",
44
+ "card_high": "#151515",
45
+ "border": "#222222",
46
+ "text": "#E6E6E6",
47
+ "text_secondary": "#7C7C7C",
48
+ "danger": "#E0625A",
49
+ "ok": "#8CC4AE",
50
  },
 
51
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  }
53
 
54
+
55
  def get_theme(theme_name: str = DEFAULT_THEME):
56
  return THEMES.get(theme_name, THEMES[DEFAULT_THEME])
57
 
58
+
59
  def get_all_themes():
60
  return THEMES
61
+
62
+
63
+ def theme_key(request) -> str:
64
+ key = request.cookies.get("theme") or request.session.get("theme")
65
+ return key if key in THEMES else DEFAULT_THEME
Backend/helper/analytics.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from datetime import datetime, timedelta
3
+
4
+ import httpx
5
+
6
+ from Backend import db
7
+ from Backend.helper.bounded import BoundedDict
8
+ from Backend.helper.custom_dl import ACTIVE_STREAMS
9
+ from Backend.logger import LOGGER
10
+
11
+ _IP_CACHE = BoundedDict(2000)
12
+ _IP_TTL = 6 * 3600
13
+ _LAST_FULL = BoundedDict(2000)
14
+ _FULL_INTERVAL = 60
15
+ ONLINE_WINDOW = 120
16
+
17
+ #----- App/device parsed from the ADDON-PROTOCOL User-Agent (manifest/stream requests),
18
+ #----- not the video-fetch UA which players spoof.
19
+ _APP_MAP = [
20
+ ("nuvio", "Nuvio"),
21
+ ("stremio", "Stremio"),
22
+ ("vidi", "Vidi"),
23
+ ("jellyfin", "Jellyfin"),
24
+ ("emby", "Emby"),
25
+ ("plex", "Plex"),
26
+ ("infuse", "Infuse"),
27
+ ("outplayer", "Outplayer"),
28
+ ("iina", "IINA"),
29
+ ("vlc", "VLC"),
30
+ ("mpv", "mpv"),
31
+ ("kodi", "Kodi"),
32
+ ("xbmc", "Kodi"),
33
+ ("mxplayer", "MX Player"),
34
+ ("mxtech", "MX Player"),
35
+ ("exoplayer", "ExoPlayer"),
36
+ ("media3", "ExoPlayer"),
37
+ ("applecoremedia", "Apple Player"),
38
+ ("lavf", "FFmpeg / .strm"),
39
+ ("ffmpeg", "FFmpeg / .strm"),
40
+ ("libav", "FFmpeg / .strm"),
41
+ ("okhttp", "Android App"),
42
+ ("dalvik", "Android App"),
43
+ ("ktor", "App"),
44
+ ("cfnetwork", "iOS App"),
45
+ ("edg", "Edge"),
46
+ ("opr", "Opera"),
47
+ ("firefox", "Firefox"),
48
+ ("chrome", "Chrome"),
49
+ ("safari", "Safari"),
50
+ ("mozilla", "Browser"),
51
+ ]
52
+
53
+ _DEVICE_MAP = [
54
+ ("android tv", "Android TV"),
55
+ ("androidtv", "Android TV"),
56
+ ("googletv", "Android TV"),
57
+ ("google tv", "Android TV"),
58
+ ("bravia", "Android TV"),
59
+ ("shield", "Android TV"),
60
+ ("aft", "Fire TV"),
61
+ ("appletv", "Apple TV"),
62
+ ("apple tv", "Apple TV"),
63
+ ("tvos", "Apple TV"),
64
+ ("tizen", "Samsung TV"),
65
+ ("web0s", "LG TV"),
66
+ ("webos", "LG TV"),
67
+ ("roku", "Roku"),
68
+ ("smarttv", "Smart TV"),
69
+ ("smart-tv", "Smart TV"),
70
+ ("crkey", "Chromecast"),
71
+ ("ipad", "iPad"),
72
+ ("iphone", "iPhone"),
73
+ ("ipod", "iPhone"),
74
+ ("android", "Android"),
75
+ ("windows nt", "Windows"),
76
+ ("macintosh", "macOS"),
77
+ ("mac os x", "macOS"),
78
+ ("cros", "ChromeOS"),
79
+ ("linux", "Linux"),
80
+ ]
81
+
82
+
83
+ #----- Real client IP behind Cloudflare / Caddy / reverse proxies
84
+ def client_ip_from(request) -> str:
85
+ for h in ("cf-connecting-ip", "x-real-ip"):
86
+ v = request.headers.get(h)
87
+ if v:
88
+ return v.strip()
89
+ xff = request.headers.get("x-forwarded-for")
90
+ if xff:
91
+ return xff.split(",")[0].strip()
92
+ return request.client.host if request.client else ""
93
+
94
+
95
+ def parse_app(user_agent: str) -> str:
96
+ if not user_agent:
97
+ return "Unknown"
98
+ low = user_agent.lower()
99
+ for needle, name in _APP_MAP:
100
+ if needle in low:
101
+ return name
102
+ return "Unknown"
103
+
104
+
105
+ def parse_device(user_agent: str) -> str:
106
+ if not user_agent:
107
+ return ""
108
+ low = user_agent.lower()
109
+ for needle, name in _DEVICE_MAP:
110
+ if needle in low:
111
+ return name
112
+ return ""
113
+
114
+
115
+ async def lookup_ip(ip: str) -> dict:
116
+ if not ip or ip.startswith(("127.", "10.", "192.168.", "172.")) or ip in ("::1", "localhost"):
117
+ return {"country": "Local", "country_code": "", "city": "", "isp": "", "proxy": False}
118
+ now = time.time()
119
+ cached = _IP_CACHE.get(ip)
120
+ if cached and now - cached[1] < _IP_TTL:
121
+ return cached[0]
122
+ data = {"country": "", "country_code": "", "city": "", "isp": "", "proxy": False}
123
+ try:
124
+ async with httpx.AsyncClient(timeout=6) as client:
125
+ resp = await client.get(
126
+ f"http://ip-api.com/json/{ip}",
127
+ params={"fields": "status,country,countryCode,city,isp,proxy,hosting"},
128
+ )
129
+ if resp.status_code == 200:
130
+ j = resp.json()
131
+ if j.get("status") == "success":
132
+ data = {
133
+ "country": j.get("country") or "",
134
+ "country_code": j.get("countryCode") or "",
135
+ "city": j.get("city") or "",
136
+ "isp": j.get("isp") or "",
137
+ "proxy": bool(j.get("proxy") or j.get("hosting")),
138
+ }
139
+ except Exception as e:
140
+ LOGGER.warning(f"[ANALYTICS] IP lookup failed for {ip}: {e}")
141
+ _IP_CACHE[ip] = (data, now)
142
+ return data
143
+
144
+
145
+ async def _record(token: str, name: str, ip: str, user_agent: str, is_client: bool) -> None:
146
+ if not token:
147
+ return
148
+ coll = db.dbs["tracking"]["user_activity"]
149
+ setf = {"last_active": datetime.utcnow(), "ip": ip or ""}
150
+ #----- Only the addon-protocol request carries a trustworthy app/device UA.
151
+ if is_client:
152
+ setf["app"] = parse_app(user_agent)
153
+ setf["device"] = parse_device(user_agent)
154
+ setf["user_agent"] = user_agent or ""
155
+ try:
156
+ await coll.update_one(
157
+ {"_id": token},
158
+ {"$set": setf, "$setOnInsert": {"name": name or "Unknown"}},
159
+ upsert=True,
160
+ )
161
+ except Exception as e:
162
+ LOGGER.warning(f"[ANALYTICS] activity ping failed: {e}")
163
+ return
164
+
165
+ #----- The IP geo/ISP/VPN lookup is the only slow part — throttle it per token.
166
+ now_ts = time.time()
167
+ if now_ts - _LAST_FULL.get(token, 0) < _FULL_INTERVAL:
168
+ return
169
+ _LAST_FULL[token] = now_ts
170
+
171
+ geo = await lookup_ip(ip)
172
+ try:
173
+ await coll.update_one({"_id": token}, {"$set": {
174
+ "country": geo.get("country"),
175
+ "country_code": geo.get("country_code"),
176
+ "city": geo.get("city"),
177
+ "isp": geo.get("isp"),
178
+ "proxy": geo.get("proxy", False),
179
+ }})
180
+ except Exception as e:
181
+ LOGGER.warning(f"[ANALYTICS] geo update failed: {e}")
182
+
183
+
184
+ #----- Called from the video byte-stream (/dl/): only refreshes presence, not device.
185
+ async def record_stream_start(token: str, name: str, ip: str, user_agent: str = "") -> None:
186
+ await _record(token, name, ip, user_agent, is_client=False)
187
+
188
+
189
+ #----- Called from the addon protocol (stream/manifest): captures the real app/device.
190
+ async def record_client(token: str, name: str, ip: str, user_agent: str = "") -> None:
191
+ await _record(token, name, ip, user_agent, is_client=True)
192
+
193
+
194
+ async def get_activity_overview(page: int = 1, per_page: int = 5) -> dict:
195
+ now = datetime.utcnow()
196
+ cutoff = now - timedelta(seconds=ONLINE_WINDOW)
197
+ coll = db.dbs["tracking"]["user_activity"]
198
+ tokens_coll = db.dbs["tracking"]["api_tokens"]
199
+
200
+ valid_tokens = set()
201
+ try:
202
+ async for doc in tokens_coll.find({}, {"token": 1}):
203
+ tok = doc.get("token")
204
+ if tok:
205
+ valid_tokens.add(tok)
206
+ except Exception:
207
+ valid_tokens = set()
208
+
209
+ if valid_tokens:
210
+ try:
211
+ await coll.delete_many({"_id": {"$nin": list(valid_tokens)}})
212
+ except Exception:
213
+ pass
214
+
215
+ playing = {}
216
+ for info in ACTIVE_STREAMS.values():
217
+ meta = info.get("meta", {}) or {}
218
+ tok = meta.get("token")
219
+ if tok and tok in valid_tokens:
220
+ playing[tok] = meta.get("title") or "Streaming"
221
+
222
+ match = {"_id": {"$in": list(valid_tokens)}} if valid_tokens else {"_id": {"$exists": False}}
223
+ try:
224
+ total = await coll.count_documents(match)
225
+ online_count = await coll.count_documents({**match, "last_active": {"$gte": cutoff}})
226
+ except Exception:
227
+ total, online_count = 0, 0
228
+ online_count = max(online_count, len(playing))
229
+
230
+ per_page = max(1, min(int(per_page or 5), 60))
231
+ total_pages = max(1, (total + per_page - 1) // per_page)
232
+ page = max(1, min(int(page or 1), total_pages))
233
+ offset = (page - 1) * per_page
234
+
235
+ try:
236
+ docs = await coll.find(match).sort("last_active", -1).skip(offset).limit(per_page).to_list(per_page)
237
+ except Exception:
238
+ docs = []
239
+
240
+ rows = []
241
+ for d in docs:
242
+ token = d.get("_id")
243
+ if token not in valid_tokens:
244
+ continue
245
+ last = d.get("last_active")
246
+ online = token in playing
247
+ if not online and last:
248
+ try:
249
+ online = last >= cutoff
250
+ except Exception:
251
+ online = False
252
+ rows.append({
253
+ "token": token,
254
+ "name": d.get("name") or "Unknown",
255
+ "online": online,
256
+ "now_playing": playing.get(token),
257
+ "last_title": d.get("last_title"),
258
+ "ip": d.get("ip") or "",
259
+ "country": d.get("country") or "",
260
+ "country_code": (d.get("country_code") or "").upper(),
261
+ "city": d.get("city") or "",
262
+ "isp": d.get("isp") or "",
263
+ "app": d.get("app") or "Unknown",
264
+ "device": d.get("device") or "",
265
+ "proxy": bool(d.get("proxy")),
266
+ "streams": int(d.get("streams") or 0),
267
+ "last_active": last.isoformat() if last else None,
268
+ })
269
+
270
+ rows.sort(key=lambda r: 0 if r["online"] else 1)
271
+ return {
272
+ "users": rows,
273
+ "online_count": online_count,
274
+ "total": total,
275
+ "page": page,
276
+ "per_page": per_page,
277
+ "total_pages": total_pages,
278
+ }
Backend/helper/anime.py DELETED
@@ -1,204 +0,0 @@
1
- import asyncio
2
- import re
3
- from typing import Optional, List
4
-
5
- import httpx
6
-
7
- from Backend.logger import LOGGER
8
-
9
- ANILIST_URL = "https://graphql.anilist.co"
10
- ANIZIP_URL = "https://api.ani.zip/mappings"
11
-
12
- _client: Optional[httpx.AsyncClient] = None
13
- _client_lock = asyncio.Lock()
14
-
15
- _SEARCH_CACHE: dict = {}
16
- _MAP_CACHE: dict = {}
17
-
18
- _HTML_RE = re.compile(r"<[^>]+>")
19
-
20
- _ANILIST_FIELDS = """
21
- id
22
- title { romaji english }
23
- seasonYear
24
- startDate { year }
25
- description(asHtml: false)
26
- genres
27
- averageScore
28
- duration
29
- coverImage { extraLarge large }
30
- bannerImage
31
- """
32
-
33
- _ANILIST_QUERY = """
34
- query ($search: String) {
35
- Media(search: $search, type: ANIME) {
36
- """ + _ANILIST_FIELDS + """
37
- }
38
- }
39
- """
40
-
41
- _ANILIST_MOVIE_QUERY = """
42
- query ($search: String) {
43
- Media(search: $search, type: ANIME, format: MOVIE) {
44
- """ + _ANILIST_FIELDS + """
45
- }
46
- }
47
- """
48
-
49
-
50
- async def _get_client() -> httpx.AsyncClient:
51
- global _client
52
- async with _client_lock:
53
- if _client is None or _client.is_closed:
54
- _client = httpx.AsyncClient(
55
- timeout=20.0,
56
- follow_redirects=True,
57
- headers={"User-Agent": "Telegram-Stremio (+https://github.com/weebzone/Telegram-Stremio)"},
58
- )
59
- return _client
60
-
61
-
62
- def _strip_html(text: str) -> str:
63
- if not text:
64
- return ""
65
- return re.sub(r"\s+", " ", _HTML_RE.sub(" ", text)).strip()
66
-
67
-
68
- def _season_queries(title: str, season: Optional[int]) -> List[str]:
69
- if season and int(season) > 1:
70
- return [f"{title} Season {season}", f"{title} {season}", title]
71
- return [title]
72
-
73
-
74
- async def _anilist_request(search: str, query: str = _ANILIST_QUERY) -> Optional[dict]:
75
- try:
76
- client = await _get_client()
77
- resp = await client.post(ANILIST_URL, json={"query": query, "variables": {"search": search}})
78
- if resp.status_code != 200:
79
- return None
80
- return ((resp.json() or {}).get("data") or {}).get("Media")
81
- except Exception as e:
82
- LOGGER.warning(f"[ANIME] AniList search failed for '{search}': {e}")
83
- return None
84
-
85
-
86
- async def search_anime(title: str, season: Optional[int] = None) -> Optional[dict]:
87
- cache_key = f"{title}::{season}"
88
- if cache_key in _SEARCH_CACHE:
89
- return _SEARCH_CACHE[cache_key]
90
- media = None
91
- for query in _season_queries(title, season):
92
- media = await _anilist_request(query)
93
- if media:
94
- break
95
- _SEARCH_CACHE[cache_key] = media
96
- return media
97
-
98
-
99
- async def search_anime_movie(title: str) -> Optional[dict]:
100
- cache_key = f"movie::{title}"
101
- if cache_key in _SEARCH_CACHE:
102
- return _SEARCH_CACHE[cache_key]
103
- media = await _anilist_request(title, _ANILIST_MOVIE_QUERY)
104
- _SEARCH_CACHE[cache_key] = media
105
- return media
106
-
107
-
108
- async def get_anizip_mappings(anilist_id: int) -> Optional[dict]:
109
- if anilist_id in _MAP_CACHE:
110
- return _MAP_CACHE[anilist_id]
111
- try:
112
- client = await _get_client()
113
- resp = await client.get(ANIZIP_URL, params={"anilist_id": anilist_id})
114
- data = resp.json() if resp.status_code == 200 else None
115
- except Exception as e:
116
- LOGGER.warning(f"[ANIME] ani.zip mappings failed for {anilist_id}: {e}")
117
- data = None
118
- _MAP_CACHE[anilist_id] = data
119
- return data
120
-
121
-
122
- def _anizip_image(images, cover_type: str) -> str:
123
- for img in images or []:
124
- if str(img.get("coverType", "")).lower() == cover_type.lower() and img.get("url"):
125
- return img["url"]
126
- return ""
127
-
128
-
129
- # Build the fields shared by anime movie/TV payloads from AniList + ani.zip data.
130
- # imdb_id may be None when ani.zip lacks it — the caller resolves it from tmdb_id.
131
- def _common_payload(media: dict, doc: dict, title: str) -> dict:
132
- mappings = doc.get("mappings") or {}
133
- tmdb_id = mappings.get("themoviedb_id")
134
- try:
135
- tmdb_id = int(tmdb_id) if tmdb_id else None
136
- except (ValueError, TypeError):
137
- tmdb_id = None
138
-
139
- titles = media.get("title") or {}
140
- images = doc.get("images") or []
141
- cover = media.get("coverImage") or {}
142
- score = media.get("averageScore")
143
- duration = media.get("duration")
144
- return {
145
- "tmdb_id": tmdb_id,
146
- "imdb_id": mappings.get("imdb_id"),
147
- "title": titles.get("english") or titles.get("romaji") or title,
148
- "year": media.get("seasonYear") or (media.get("startDate") or {}).get("year") or 0,
149
- "rate": round(score / 10, 1) if score else 0,
150
- "description": _strip_html(media.get("description") or ""),
151
- "poster": cover.get("extraLarge") or cover.get("large") or _anizip_image(images, "Poster"),
152
- "backdrop": media.get("bannerImage") or _anizip_image(images, "Fanart") or _anizip_image(images, "Banner"),
153
- "logo": _anizip_image(images, "Clearlogo"),
154
- "genres": media.get("genres") or [],
155
- "cast": [],
156
- "runtime": f"{duration} min" if duration else "",
157
- }
158
-
159
-
160
- # Resolve accurate anime TV metadata via AniList (search) + api.ani.zip (mappings/episodes).
161
- async def fetch_anime_metadata(title, season, episode, encoded_string, year=None, quality=None) -> Optional[dict]:
162
- media = await search_anime(title, season)
163
- if not media:
164
- LOGGER.info(f"[ANIME] No AniList match for '{title}' (season={season})")
165
- return None
166
-
167
- doc = await get_anizip_mappings(media["id"]) or {}
168
- payload = _common_payload(media, doc, title)
169
- if not payload["imdb_id"] and not payload["tmdb_id"]:
170
- LOGGER.info(f"[ANIME] No imdb/tmdb mapping for AniList {media['id']} ('{title}') -> fallback")
171
- return None
172
-
173
- ep = (doc.get("episodes") or {}).get(str(episode)) or {}
174
- ep_title = (ep.get("title") or {}).get("en") if isinstance(ep.get("title"), dict) else None
175
-
176
- payload.update({
177
- "media_type": "tv",
178
- "season_number": season,
179
- "episode_number": episode,
180
- "episode_title": ep_title or f"S{season:02d}E{episode:02d}",
181
- "episode_backdrop": ep.get("image", "") or "",
182
- "episode_overview": ep.get("overview") or ep.get("summary") or "",
183
- "episode_released": ep.get("airDate") or ep.get("airdate") or "",
184
- "quality": quality,
185
- "encoded_string": encoded_string,
186
- })
187
- return payload
188
-
189
-
190
- # Resolve accurate anime movie metadata via AniList (format MOVIE) + api.ani.zip.
191
- async def fetch_anime_movie_metadata(title, encoded_string, year=None, quality=None) -> Optional[dict]:
192
- media = await search_anime_movie(title)
193
- if not media:
194
- LOGGER.info(f"[ANIME] No AniList movie match for '{title}'")
195
- return None
196
-
197
- doc = await get_anizip_mappings(media["id"]) or {}
198
- payload = _common_payload(media, doc, title)
199
- if not payload["imdb_id"] and not payload["tmdb_id"]:
200
- LOGGER.info(f"[ANIME] No imdb/tmdb mapping for AniList movie {media['id']} ('{title}') -> fallback")
201
- return None
202
-
203
- payload.update({"media_type": "movie", "quality": quality, "encoded_string": encoded_string})
204
- return payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/helper/announcer.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import create_task
2
+ from datetime import datetime
3
+
4
+ from pyrogram.enums import ParseMode
5
+ from pyrogram.errors import FloodWait, MessageDeleteForbidden, MessageIdInvalid
6
+ from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
7
+
8
+ from Backend import db
9
+ from Backend.helper.settings_manager import SettingsManager
10
+ from Backend.logger import LOGGER
11
+ from Backend.pyrofork.bot import StreamBot, get_streambot_url
12
+
13
+
14
+ #----- Accept either a numeric channel id (-100...) or an @username
15
+ def _resolve_chat(value: str):
16
+ value = str(value or "").strip()
17
+ if not value:
18
+ return None
19
+ try:
20
+ return int(value)
21
+ except ValueError:
22
+ return value
23
+
24
+
25
+ #----- Atomically claim a title so it is announced at most once; returns True if newly claimed
26
+ async def _claim(media_type: str, tmdb_id) -> bool:
27
+ if not tmdb_id:
28
+ return False
29
+ result = await db.dbs["tracking"]["announced"].update_one(
30
+ {"_id": f"{media_type}:{tmdb_id}"},
31
+ {"$setOnInsert": {"at": datetime.utcnow()}},
32
+ upsert=True,
33
+ )
34
+ return result.upserted_id is not None
35
+
36
+
37
+ async def _store_announcement_msg(media_type: str, tmdb_id, chat_id, message_id: int) -> None:
38
+ if not tmdb_id or not message_id:
39
+ return
40
+ try:
41
+ await db.dbs["tracking"]["announced"].update_one(
42
+ {"_id": f"{media_type}:{tmdb_id}"},
43
+ {"$set": {"chat_id": chat_id, "message_id": message_id, "at": datetime.utcnow()}},
44
+ upsert=True,
45
+ )
46
+ except Exception as e:
47
+ LOGGER.warning(f"Failed to store announcement message id: {e}")
48
+
49
+
50
+ def _build_caption(info: dict) -> str:
51
+ is_tv = info.get("media_type") == "tv"
52
+ title = info.get("title") or "Unknown"
53
+ header = f"{'📺' if is_tv else '🎬'} <b>{title}</b>"
54
+ if info.get("year"):
55
+ header += f" ({info['year']})"
56
+
57
+ lines = [header, "", f"🗂 <b>Type:</b> {'Series' if is_tv else 'Movie'}"]
58
+ if info.get("rate"):
59
+ try:
60
+ lines.append(f"⭐ <b>Rating:</b> {round(float(info['rate']), 1)}")
61
+ except (TypeError, ValueError):
62
+ pass
63
+ genres = info.get("genres") or []
64
+ if genres:
65
+ lines.append(f"🎭 <b>Genres:</b> {', '.join(genres[:4])}")
66
+ if info.get("quality"):
67
+ lines.append(f"📶 <b>Quality:</b> {info['quality']}")
68
+
69
+ desc = (info.get("description") or "").strip()
70
+ if desc:
71
+ if len(desc) > 320:
72
+ desc = desc[:317].rstrip() + "..."
73
+ lines += ["", f"<i>{desc}</i>"]
74
+ return "\n".join(lines)
75
+
76
+
77
+ def _build_markup(info: dict):
78
+ rows = []
79
+ base = SettingsManager.current().base_url
80
+ imdb_id = str(info.get("imdb_id") or "").strip()
81
+ stremio_type = "series" if info.get("media_type") == "tv" else "movie"
82
+ if base and imdb_id:
83
+ rows.append([
84
+ InlineKeyboardButton("▶️ Stremio", url=f"{base}/open/stremio/{stremio_type}/{imdb_id}"),
85
+ InlineKeyboardButton("📱 Nuvio", url=f"{base}/open/nuvio/{stremio_type}/{imdb_id}"),
86
+ ])
87
+ bot_url = get_streambot_url()
88
+ if bot_url and bot_url != "https://t.me/":
89
+ rows.append([InlineKeyboardButton("🤖 Get Addon", url=bot_url)])
90
+ return InlineKeyboardMarkup(rows) if rows else None
91
+
92
+
93
+ async def _announce(info: dict) -> None:
94
+ settings = SettingsManager.current()
95
+ chat = _resolve_chat(settings.announcement_channel)
96
+ if not settings.announce_new_content or chat is None:
97
+ return
98
+ if not await _claim(info.get("media_type"), info.get("tmdb_id")):
99
+ return
100
+
101
+ caption = _build_caption(info)
102
+ poster = info.get("backdrop") or info.get("poster")
103
+ markup = _build_markup(info)
104
+
105
+ try:
106
+ sent = None
107
+ if poster:
108
+ try:
109
+ sent = await StreamBot.send_photo(chat, poster, caption=caption,
110
+ parse_mode=ParseMode.HTML, reply_markup=markup)
111
+ except FloodWait:
112
+ raise
113
+ except Exception:
114
+ sent = None
115
+ if sent is None:
116
+ sent = await StreamBot.send_message(chat, caption, parse_mode=ParseMode.HTML,
117
+ reply_markup=markup, disable_web_page_preview=True)
118
+ if sent is not None:
119
+ await _store_announcement_msg(info.get("media_type"), info.get("tmdb_id"), chat, sent.id)
120
+ except FloodWait as e:
121
+ LOGGER.warning(f"Announcement FloodWait for {e.value}s")
122
+ except Exception as e:
123
+ LOGGER.error(f"Announcement failed for '{info.get('title')}': {e}")
124
+
125
+
126
+ #----- Fire-and-forget announcement for a freshly added title
127
+ def announce_new_media(info: dict) -> None:
128
+ try:
129
+ create_task(_announce(dict(info)))
130
+ except RuntimeError:
131
+ LOGGER.warning("Announcement skipped: no running event loop.")
132
+
133
+
134
+ #----- Delete the announcement message when media is removed from the library
135
+ async def delete_announcement(media_type: str, tmdb_id) -> None:
136
+ if not tmdb_id:
137
+ return
138
+ key = f"{media_type}:{tmdb_id}"
139
+ try:
140
+ doc = await db.dbs["tracking"]["announced"].find_one_and_delete({"_id": key})
141
+ except Exception as e:
142
+ LOGGER.warning(f"Failed to lookup announcement for {key}: {e}")
143
+ return
144
+ if not doc:
145
+ return
146
+ chat_id = doc.get("chat_id")
147
+ message_id = doc.get("message_id")
148
+ if not chat_id or not message_id:
149
+ return
150
+ try:
151
+ await StreamBot.delete_messages(chat_id, message_id)
152
+ LOGGER.info(f"Deleted announcement message {message_id} for {key}")
153
+ except (MessageDeleteForbidden, MessageIdInvalid) as e:
154
+ LOGGER.warning(f"Could not delete announcement {message_id} for {key}: {e}")
155
+ except FloodWait as e:
156
+ LOGGER.warning(f"FloodWait deleting announcement for {key}: {e.value}s")
157
+ except Exception as e:
158
+ LOGGER.warning(f"Failed to delete announcement message for {key}: {e}")
159
+
160
+
161
+ def delete_announcement_async(media_type: str, tmdb_id) -> None:
162
+ try:
163
+ create_task(delete_announcement(media_type, tmdb_id))
164
+ except RuntimeError:
165
+ LOGGER.warning("Announcement delete skipped: no running event loop.")
Backend/helper/auto_catalog.py CHANGED
@@ -1,22 +1,18 @@
1
  import asyncio
 
2
  from datetime import datetime
3
  from typing import Dict, List, Optional, Set, Tuple
4
 
5
  import httpx
6
 
7
- from Backend.config import Telegram
 
8
  from Backend.logger import LOGGER
9
 
10
- # -----------------------------
11
- # Auto catalog settings
12
- # -----------------------------
13
  AUTO_CATALOG_REGION = "IN"
14
  AUTO_SYNC_CONCURRENCY = 5
15
 
16
- AUTO_CATALOG_INTERVAL_SYNC = True
17
- AUTO_CATALOG_SYNC_INTERVAL_MINUTES = 60
18
-
19
- # User can choose exactly which auto catalogs are enabled.
20
  AUTO_CATALOG_DEFINITIONS = [
21
  {"key": "bollywood", "name": "Bollywood", "group": "Language"},
22
  {"key": "hollywood", "name": "Hollywood", "group": "Language"},
@@ -32,7 +28,7 @@ AUTO_CATALOG_DEFINITIONS = [
32
  {"key": "korean", "name": "Korean", "group": "Language"},
33
 
34
  {"key": "top_rated", "name": "Top Rated", "group": "Smart"},
35
- {"key": "recently_added", "name": "Recently Added", "group": "Smart"},
36
 
37
  {"key": "netflix", "name": "Netflix", "group": "OTT"},
38
  {"key": "prime_video", "name": "Prime Video", "group": "OTT"},
@@ -47,13 +43,7 @@ AUTO_CATALOG_DEFINITIONS = [
47
  {"key": "crunchyroll", "name": "Crunchyroll", "group": "OTT"},
48
  ]
49
 
50
- CATALOG_BY_NAME = {item["name"]: item for item in AUTO_CATALOG_DEFINITIONS}
51
  CATALOG_BY_KEY = {item["key"]: item for item in AUTO_CATALOG_DEFINITIONS}
52
- DEFAULT_ENABLED_AUTO_CATALOG_KEYS = set(getattr(
53
- Telegram,
54
- "AUTO_CATALOG_ENABLED_KEYS",
55
- [item["key"] for item in AUTO_CATALOG_DEFINITIONS]
56
- ))
57
 
58
  _LANGUAGE_CATALOGS = {
59
  "hi": ["Bollywood"],
@@ -98,17 +88,6 @@ INSTANT_SYNC_CONCURRENCY = 3
98
  _instant_sync_semaphore = asyncio.Semaphore(INSTANT_SYNC_CONCURRENCY)
99
 
100
 
101
- def _tmdb_api_key() -> str:
102
- try:
103
- from Backend.helper.settings_manager import SettingsManager
104
- key = SettingsManager.current().tmdb_api
105
- if key:
106
- return key
107
- except Exception:
108
- pass
109
- return getattr(Telegram, "TMDB_API", "") or ""
110
-
111
-
112
  def _media_type(doc: dict) -> str:
113
  return "tv" if doc.get("media_type") in ["tv", "series"] else "movie"
114
 
@@ -131,9 +110,47 @@ def _doc_item(doc: dict) -> dict:
131
  "db_index": db_index,
132
  "media_type": media_type,
133
  "added_at": datetime.utcnow(),
 
 
 
134
  }
135
 
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  def _provider_bucket(provider_name: str) -> Optional[str]:
138
  value = (provider_name or "").strip().lower()
139
  if not value:
@@ -167,19 +184,40 @@ def _is_already_synced(doc: dict) -> bool:
167
 
168
  if not synced_at:
169
  return False
 
 
170
  if doc_updated_on and source_updated_on and doc_updated_on != source_updated_on:
171
  return False
172
  return True
173
 
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  async def has_auto_catalog_settings(db) -> bool:
176
- """Return True only after the admin saved auto-catalog options at least once."""
177
- state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"})
178
- return bool(state and isinstance(state.get("enabled_keys"), list))
179
 
180
 
181
  async def get_auto_catalog_settings(db) -> dict:
182
- state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_settings"}) or {}
183
  configured = isinstance(state.get("enabled_keys"), list)
184
 
185
  enabled_keys = state.get("enabled_keys") if configured else []
@@ -197,9 +235,6 @@ async def get_auto_catalog_settings(db) -> dict:
197
  "enabled_keys": sorted(enabled_set),
198
  "definitions": definitions,
199
  "region": AUTO_CATALOG_REGION,
200
- "genre_catalogs_removed": True,
201
- "interval_sync_enabled": bool(AUTO_CATALOG_INTERVAL_SYNC),
202
- "interval_minutes": AUTO_CATALOG_SYNC_INTERVAL_MINUTES,
203
  }
204
 
205
 
@@ -211,25 +246,9 @@ async def update_auto_catalog_settings(db, enabled_keys: List[str]) -> dict:
211
  {"$set": {"enabled_keys": clean_keys, "updated_at": now}},
212
  upsert=True,
213
  )
214
- await _invalidate_synced_flags(db)
215
  return await get_auto_catalog_settings(db)
216
 
217
 
218
- async def _invalidate_synced_flags(db) -> None:
219
- for db_index in range(1, db.current_db_index + 1):
220
- db_key = f"storage_{db_index}"
221
- if db_key not in db.dbs:
222
- continue
223
- for collection_name in ["movie", "tv"]:
224
- try:
225
- await db.dbs[db_key][collection_name].update_many(
226
- {"auto_catalog.synced": True},
227
- {"$set": {"auto_catalog.synced": False}},
228
- )
229
- except Exception as e:
230
- LOGGER.warning(f"Auto catalog: failed to reset synced flags in {db_key}.{collection_name}: {e}")
231
-
232
-
233
  async def _enabled_catalog_names(db) -> Set[str]:
234
  settings = await get_auto_catalog_settings(db)
235
  keys = settings.get("enabled_keys") or []
@@ -281,7 +300,7 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
281
  if doc.get("release_year"):
282
  try:
283
  if int(doc.get("release_year")) >= datetime.utcnow().year - 1:
284
- tags.add("Recently Added")
285
  except Exception:
286
  pass
287
 
@@ -292,8 +311,6 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
292
  if bucket:
293
  providers.add(bucket)
294
  else:
295
- # No live watch-provider data (fetch failed / quota / no key): reuse the
296
- # OTT buckets already stored on the doc so a re-classify keeps OTT tags.
297
  for stored in (doc.get("watch_providers") or []):
298
  if stored:
299
  providers.add(stored)
@@ -301,8 +318,6 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
301
  for bucket in providers:
302
  tags.add(bucket)
303
 
304
- tags = {tag for tag in tags if tag in enabled_names}
305
-
306
  return {
307
  "original_language": original_language,
308
  "origin_country": origin_country,
@@ -312,48 +327,91 @@ def classify_media_from_tmdb(doc: dict, details: dict, watch_data: dict, enabled
312
  }
313
 
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  async def _fetch_tmdb_data(client: httpx.AsyncClient, doc: dict) -> tuple[dict, dict]:
316
- api_key = _tmdb_api_key()
317
  if not api_key:
318
  return {}, {}
319
 
320
  media_type = _media_type(doc)
321
  tmdb_id = doc.get("tmdb_id")
322
 
 
323
  if not tmdb_id and doc.get("imdb_id"):
324
- find_url = f"https://api.themoviedb.org/3/find/{doc.get('imdb_id')}"
325
- params = {"api_key": api_key, "external_source": "imdb_id"}
326
- resp = await client.get(find_url, params=params)
327
- if resp.status_code == 200:
328
- data = resp.json()
 
 
 
 
329
  result_key = "tv_results" if media_type == "tv" else "movie_results"
330
- results = data.get(result_key) or []
331
- if results:
332
- tmdb_id = results[0].get("id")
 
333
 
334
  if not tmdb_id:
335
  return {}, {}
336
 
337
- detail_url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}"
338
- detail_params = {
339
- "api_key": api_key,
340
- "language": "en-US",
341
- "append_to_response": "keywords",
342
- }
343
- provider_url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}/watch/providers"
 
 
 
 
 
 
 
344
 
345
- detail_resp, provider_resp = await asyncio.gather(
346
- client.get(detail_url, params=detail_params),
347
- client.get(provider_url, params={"api_key": api_key}),
348
  return_exceptions=True,
349
  )
350
-
351
- details = detail_resp.json() if not isinstance(detail_resp, Exception) and detail_resp.status_code == 200 else {}
352
- providers = provider_resp.json() if not isinstance(provider_resp, Exception) and provider_resp.status_code == 200 else {}
353
  return details, providers
354
 
355
 
356
- async def _iter_all_media(db, *, full_rebuild: bool = False):
357
  for db_index in range(1, db.current_db_index + 1):
358
  db_key = f"storage_{db_index}"
359
  if db_key not in db.dbs:
@@ -364,7 +422,7 @@ async def _iter_all_media(db, *, full_rebuild: bool = False):
364
  async for doc in cursor:
365
  doc["db_index"] = db_index
366
  doc["media_type"] = "tv" if collection_name == "tv" else "movie"
367
- if not full_rebuild and _is_already_synced(doc):
368
  yield collection_name, db_index, doc, True
369
  else:
370
  yield collection_name, db_index, doc, False
@@ -377,7 +435,9 @@ async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaph
377
  classification = classify_media_from_tmdb(doc, details or {}, watch_data or {}, enabled_names)
378
 
379
  now = datetime.utcnow()
 
380
  update_data = {
 
381
  "original_language": classification.get("original_language"),
382
  "origin_country": classification.get("origin_country", []),
383
  "production_countries": classification.get("production_countries", []),
@@ -403,7 +463,7 @@ async def _classify_one(db, client: httpx.AsyncClient, semaphore: asyncio.Semaph
403
  return doc, classification
404
  except Exception as e:
405
  LOGGER.warning(f"Auto catalog classification failed for {doc.get('title')} ({doc.get('tmdb_id')}): {e}")
406
- return doc, {"auto_tags": [tag for tag in (doc.get("auto_tags", []) or []) if tag in enabled_names]}
407
 
408
 
409
  async def sync_single_media(db, *, tmdb_id, media_type: str) -> dict:
@@ -439,10 +499,11 @@ async def sync_single_media(db, *, tmdb_id, media_type: str) -> dict:
439
  async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
440
  media_doc, classification = await _classify_one(db, client, semaphore, doc, enabled_names)
441
 
442
- tags = [tag for tag in (classification.get("auto_tags") or []) if tag in enabled_names]
 
 
443
  if tags:
444
- item = _doc_item(media_doc)
445
- await _flush_quick_items(db, {tag: [item] for tag in tags})
446
 
447
  LOGGER.info(
448
  f"Auto catalog instant index: '{media_doc.get('title')}' "
@@ -452,7 +513,7 @@ async def sync_single_media(db, *, tmdb_id, media_type: str) -> dict:
452
 
453
 
454
  def start_single_media_catalog_sync(db, *, tmdb_id, media_type: str) -> None:
455
- """Fire-and-forget launcher for instant per-item categorization."""
456
  async def runner():
457
  try:
458
  await sync_single_media(db, tmdb_id=tmdb_id, media_type=media_type)
@@ -462,7 +523,7 @@ def start_single_media_catalog_sync(db, *, tmdb_id, media_type: str) -> None:
462
  try:
463
  asyncio.create_task(runner())
464
  except RuntimeError:
465
- # No running loop (shouldn't happen inside the bot); ignore.
466
  LOGGER.warning("Instant auto catalog index skipped: no running event loop.")
467
 
468
 
@@ -478,6 +539,8 @@ async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
478
  "$setOnInsert": {
479
  "name": name,
480
  "visible": True,
 
 
481
  "auto": True,
482
  "auto_key": auto_key,
483
  "items": [],
@@ -493,7 +556,7 @@ async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
493
  )
494
 
495
  for item in items:
496
- await collection.update_one(
497
  {
498
  "auto_key": auto_key,
499
  "items": {
@@ -512,6 +575,20 @@ async def _flush_quick_items(db, catalog_items: Dict[str, List[dict]]) -> None:
512
  "$inc": {"item_count": 1},
513
  },
514
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
 
516
 
517
  async def _rebuild_auto_catalogs(db, catalog_items: Dict[str, List[dict]], enabled_names: Set[str]) -> None:
@@ -528,6 +605,8 @@ async def _rebuild_auto_catalogs(db, catalog_items: Dict[str, List[dict]], enabl
528
  seen.add(key)
529
  unique_items.append(item)
530
 
 
 
531
  await collection.update_one(
532
  {"auto_key": _catalog_key(name)},
533
  {
@@ -541,7 +620,7 @@ async def _rebuild_auto_catalogs(db, catalog_items: Dict[str, List[dict]], enabl
541
  "updated_at": now,
542
  "last_auto_sync": now,
543
  },
544
- "$setOnInsert": {"created_at": now},
545
  },
546
  upsert=True,
547
  )
@@ -562,7 +641,7 @@ async def _write_status(db, data: dict) -> None:
562
  )
563
 
564
 
565
- async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool = False, delay_seconds: int = 0) -> dict:
566
  if delay_seconds:
567
  await asyncio.sleep(delay_seconds)
568
 
@@ -573,7 +652,7 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
573
  started_at = datetime.utcnow()
574
  await _write_status(db, {
575
  "running": True,
576
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
577
  "message": "Auto catalog sync running...",
578
  "started_at": started_at,
579
  "finished_at": None,
@@ -589,7 +668,6 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
589
  skipped = 0
590
  classified = 0
591
  tagged = 0
592
- error_message = None
593
  settings_configured = await has_auto_catalog_settings(db)
594
  enabled_names = await _enabled_catalog_names(db)
595
 
@@ -597,7 +675,7 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
597
  finished_at = datetime.utcnow()
598
  summary = {
599
  "running": False,
600
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
601
  "message": "Auto catalog skipped. Save auto catalog selection first.",
602
  "scanned": 0,
603
  "skipped": 0,
@@ -613,34 +691,37 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
613
  LOGGER.info(f"Auto catalog sync skipped: {summary}")
614
  return summary
615
 
616
- if not _tmdb_api_key():
617
  LOGGER.warning(
618
  "Auto catalog: no TMDB API key configured — only 'Top Rated' and "
619
- "'Recently Added' will populate; language & OTT catalogs need a TMDB key."
620
  )
621
 
 
 
 
 
 
 
 
 
 
 
 
622
  try:
623
  timeout = httpx.Timeout(18.0, connect=10.0)
624
  limits = httpx.Limits(max_connections=AUTO_SYNC_CONCURRENCY * 2 + 4, max_keepalive_connections=AUTO_SYNC_CONCURRENCY)
625
  semaphore = asyncio.Semaphore(AUTO_SYNC_CONCURRENCY)
626
 
627
- async def consume_result(media_doc: dict, classification: dict) -> None:
628
- nonlocal tagged
629
- tags = classification.get("auto_tags", []) or []
630
- if tags:
631
- tagged += 1
632
- item = _doc_item(media_doc)
633
- for tag in tags:
634
- if tag in enabled_names:
635
- catalog_items.setdefault(tag, []).append(item)
636
-
637
  async with httpx.AsyncClient(timeout=timeout, limits=limits, follow_redirects=True) as client:
638
  pending = []
639
- async for _, _, doc, already_synced in _iter_all_media(db, full_rebuild=full_rebuild):
640
  scanned += 1
641
 
642
- if already_synced and not full_rebuild:
 
643
  skipped += 1
 
644
  continue
645
 
646
  classified += 1
@@ -648,11 +729,11 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
648
 
649
  if len(pending) >= 40:
650
  for media_doc, classification in await asyncio.gather(*pending):
651
- await consume_result(media_doc, classification)
652
  pending = []
653
  await _write_status(db, {
654
  "running": True,
655
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
656
  "started_at": started_at,
657
  "scanned": scanned,
658
  "skipped": skipped,
@@ -663,17 +744,15 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
663
 
664
  if pending:
665
  for media_doc, classification in await asyncio.gather(*pending):
666
- await consume_result(media_doc, classification)
667
 
668
- if full_rebuild:
669
- await _rebuild_auto_catalogs(db, catalog_items, enabled_names)
670
- else:
671
- await _flush_quick_items(db, catalog_items)
672
 
673
  finished_at = datetime.utcnow()
674
  summary = {
675
  "running": False,
676
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
677
  "scanned": scanned,
678
  "skipped": skipped,
679
  "classified": classified,
@@ -688,11 +767,10 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
688
  LOGGER.info(f"Auto catalog sync complete: {summary}")
689
  return summary
690
  except Exception as exc:
691
- error_message = str(exc)
692
  finished_at = datetime.utcnow()
693
  summary = {
694
  "running": False,
695
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
696
  "scanned": scanned,
697
  "skipped": skipped,
698
  "classified": classified,
@@ -701,14 +779,14 @@ async def run_auto_catalog_sync(db, *, force: bool = False, full_rebuild: bool =
701
  "enabled_catalogs": sorted(enabled_names),
702
  "started_at": started_at,
703
  "finished_at": finished_at,
704
- "error": error_message,
705
  }
706
  await _write_status(db, summary)
707
  LOGGER.error(f"Auto catalog sync failed: {summary}")
708
  raise
709
 
710
 
711
- async def start_auto_catalog_sync_background(db, *, full_rebuild: bool = False, force: bool = False, delay_seconds: int = 0) -> dict:
712
  global _auto_sync_task
713
 
714
  if _auto_sync_lock.locked() or (_auto_sync_task and not _auto_sync_task.done()):
@@ -717,7 +795,7 @@ async def start_auto_catalog_sync_background(db, *, full_rebuild: bool = False,
717
  started_at = datetime.utcnow()
718
  await _write_status(db, {
719
  "running": True,
720
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
721
  "message": "Auto catalog sync queued...",
722
  "started_at": started_at,
723
  "finished_at": None,
@@ -730,61 +808,19 @@ async def start_auto_catalog_sync_background(db, *, full_rebuild: bool = False,
730
 
731
  async def runner():
732
  try:
733
- await run_auto_catalog_sync(db, force=force, full_rebuild=full_rebuild, delay_seconds=delay_seconds)
734
  except Exception:
735
  LOGGER.exception("Background auto catalog sync crashed")
736
 
737
  _auto_sync_task = asyncio.create_task(runner())
738
  return {
739
  "running": True,
740
- "message": "Full rebuild started in background." if full_rebuild else "Quick sync started in background.",
741
- "mode": "full_rebuild" if full_rebuild else "quick_sync",
742
  "started_at": started_at,
743
  }
744
 
745
 
746
- async def start_auto_catalog_interval_loop(db) -> None:
747
- """Run quick sync every N minutes after auto-catalog settings exist.
748
-
749
- This avoids per-upload TMDb calls and prevents first boot from creating
750
- catalogs until the admin chooses options from /catalogs.
751
- """
752
- if not AUTO_CATALOG_INTERVAL_SYNC:
753
- LOGGER.info("Auto catalog interval sync disabled.")
754
- return
755
-
756
- interval_minutes = max(1, int(AUTO_CATALOG_SYNC_INTERVAL_MINUTES or 60))
757
- interval_seconds = interval_minutes * 60
758
- LOGGER.info(f"Auto catalog interval sync loop started. Interval: {interval_minutes} minutes")
759
-
760
- while True:
761
- try:
762
- await asyncio.sleep(interval_seconds)
763
-
764
- if not await has_auto_catalog_settings(db):
765
- LOGGER.info("Hourly auto catalog quick sync skipped: no auto catalog selection saved yet.")
766
- continue
767
-
768
- if _auto_sync_lock.locked() or (_auto_sync_task and not _auto_sync_task.done()):
769
- LOGGER.info("Hourly auto catalog quick sync skipped: another sync is already running.")
770
- continue
771
-
772
- result = await start_auto_catalog_sync_background(
773
- db,
774
- full_rebuild=False,
775
- force=False,
776
- delay_seconds=0,
777
- )
778
- LOGGER.info(f"Hourly auto catalog quick sync queued: {result}")
779
-
780
- except asyncio.CancelledError:
781
- LOGGER.info("Auto catalog interval sync loop stopped.")
782
- break
783
- except Exception as exc:
784
- LOGGER.error(f"Hourly auto catalog quick sync failed: {exc}")
785
- await asyncio.sleep(300)
786
-
787
-
788
  async def get_auto_catalog_sync_status(db) -> dict:
789
  state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_sync"}) or {}
790
  state.pop("_id", None)
 
1
  import asyncio
2
+ import re
3
  from datetime import datetime
4
  from typing import Dict, List, Optional, Set, Tuple
5
 
6
  import httpx
7
 
8
+ from Backend.helper.metadata import tmdb_api_key
9
+ from Backend.helper.bounded import BoundedDict
10
  from Backend.logger import LOGGER
11
 
 
 
 
12
  AUTO_CATALOG_REGION = "IN"
13
  AUTO_SYNC_CONCURRENCY = 5
14
 
15
+ #----- User can choose exactly which auto catalogs are enabled.
 
 
 
16
  AUTO_CATALOG_DEFINITIONS = [
17
  {"key": "bollywood", "name": "Bollywood", "group": "Language"},
18
  {"key": "hollywood", "name": "Hollywood", "group": "Language"},
 
28
  {"key": "korean", "name": "Korean", "group": "Language"},
29
 
30
  {"key": "top_rated", "name": "Top Rated", "group": "Smart"},
31
+ {"key": "latest_releases", "name": "Latest Releases", "group": "Smart"},
32
 
33
  {"key": "netflix", "name": "Netflix", "group": "OTT"},
34
  {"key": "prime_video", "name": "Prime Video", "group": "OTT"},
 
43
  {"key": "crunchyroll", "name": "Crunchyroll", "group": "OTT"},
44
  ]
45
 
 
46
  CATALOG_BY_KEY = {item["key"]: item for item in AUTO_CATALOG_DEFINITIONS}
 
 
 
 
 
47
 
48
  _LANGUAGE_CATALOGS = {
49
  "hi": ["Bollywood"],
 
88
  _instant_sync_semaphore = asyncio.Semaphore(INSTANT_SYNC_CONCURRENCY)
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
91
  def _media_type(doc: dict) -> str:
92
  return "tv" if doc.get("media_type") in ["tv", "series"] else "movie"
93
 
 
110
  "db_index": db_index,
111
  "media_type": media_type,
112
  "added_at": datetime.utcnow(),
113
+ "updated_on": doc.get("updated_on"),
114
+ "visibility": doc.get("visibility") or "public",
115
+ "allowed_tokens": doc.get("allowed_tokens") or [],
116
  }
117
 
118
 
119
+ RECENT = "Latest Releases"
120
+ _LEGACY_RECENT = "Recently Added"
121
+ _DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
122
+
123
+
124
+ def release_date(doc: dict, details: Optional[dict] = None) -> Optional[str]:
125
+ details = details or {}
126
+ today = datetime.utcnow().strftime("%Y-%m-%d")
127
+ aired = sorted(
128
+ (d for d in (str(e.get("released") or "")[:10]
129
+ for s in doc.get("seasons") or [] for e in s.get("episodes") or [])
130
+ if _DATE_RE.match(d)),
131
+ reverse=True,
132
+ )
133
+ candidates = [*aired, details.get("release_date"), details.get("last_air_date"),
134
+ details.get("first_air_date"), doc.get("release_date")]
135
+ known = next((d for d in candidates if d and str(d) <= today), None)
136
+ return known or (f"{doc['release_year']}-01-01" if doc.get("release_year") else None)
137
+
138
+
139
+ def _stored_tags(doc: dict) -> List[str]:
140
+ return [RECENT if tag == _LEGACY_RECENT else tag for tag in (doc.get("auto_tags") or [])]
141
+
142
+
143
+ def _catalog_item(doc: dict, tag: str) -> dict:
144
+ item = _doc_item(doc)
145
+ if tag == RECENT and doc.get("release_date"):
146
+ item["release_date"] = doc["release_date"]
147
+ return item
148
+
149
+
150
+ def catalog_sort_key(item: dict) -> str:
151
+ return str(item.get("release_date") or item.get("updated_on") or item.get("added_at") or "")
152
+
153
+
154
  def _provider_bucket(provider_name: str) -> Optional[str]:
155
  value = (provider_name or "").strip().lower()
156
  if not value:
 
184
 
185
  if not synced_at:
186
  return False
187
+ if RECENT in _stored_tags(doc) and not doc.get("release_date"):
188
+ return False
189
  if doc_updated_on and source_updated_on and doc_updated_on != source_updated_on:
190
  return False
191
  return True
192
 
193
 
194
+ async def _settings_state(db) -> dict:
195
+ col = db.dbs["tracking"]["state"]
196
+ state = await col.find_one({"_id": "auto_catalog_settings"}) or {}
197
+ if state.get("latest_releases_default"):
198
+ return state
199
+ keys = {"latest_releases" if k == "recently_added" else k for k in (state.get("enabled_keys") or [])}
200
+ keys.add("latest_releases")
201
+ state = {**state, "enabled_keys": sorted(keys), "latest_releases_default": True}
202
+ await col.update_one(
203
+ {"_id": "auto_catalog_settings"},
204
+ {"$set": {"enabled_keys": state["enabled_keys"], "latest_releases_default": True}},
205
+ upsert=True,
206
+ )
207
+ await db.dbs["tracking"]["custom_catalogs"].update_one(
208
+ {"auto_key": "auto_recently_added"},
209
+ {"$set": {"auto_key": "auto_latest_releases", "name": RECENT}},
210
+ )
211
+ return state
212
+
213
+
214
  async def has_auto_catalog_settings(db) -> bool:
215
+ state = await _settings_state(db)
216
+ return isinstance(state.get("enabled_keys"), list)
 
217
 
218
 
219
  async def get_auto_catalog_settings(db) -> dict:
220
+ state = await _settings_state(db)
221
  configured = isinstance(state.get("enabled_keys"), list)
222
 
223
  enabled_keys = state.get("enabled_keys") if configured else []
 
235
  "enabled_keys": sorted(enabled_set),
236
  "definitions": definitions,
237
  "region": AUTO_CATALOG_REGION,
 
 
 
238
  }
239
 
240
 
 
246
  {"$set": {"enabled_keys": clean_keys, "updated_at": now}},
247
  upsert=True,
248
  )
 
249
  return await get_auto_catalog_settings(db)
250
 
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  async def _enabled_catalog_names(db) -> Set[str]:
253
  settings = await get_auto_catalog_settings(db)
254
  keys = settings.get("enabled_keys") or []
 
300
  if doc.get("release_year"):
301
  try:
302
  if int(doc.get("release_year")) >= datetime.utcnow().year - 1:
303
+ tags.add(RECENT)
304
  except Exception:
305
  pass
306
 
 
311
  if bucket:
312
  providers.add(bucket)
313
  else:
 
 
314
  for stored in (doc.get("watch_providers") or []):
315
  if stored:
316
  providers.add(stored)
 
318
  for bucket in providers:
319
  tags.add(bucket)
320
 
 
 
321
  return {
322
  "original_language": original_language,
323
  "origin_country": origin_country,
 
327
  }
328
 
329
 
330
+ _TMDB_FIND_CACHE = BoundedDict(500)
331
+ _TMDB_DETAILS_CACHE = BoundedDict(300)
332
+ _TMDB_PROVIDERS_CACHE = BoundedDict(300)
333
+ _TMDB_INFLIGHT: Dict[tuple, asyncio.Future] = {}
334
+
335
+
336
+ #----- Cache TMDB responses and de-duplicate concurrent identical requests (mirrors metadata.py)
337
+ async def _cached_call(store: dict, key, ns: str, producer):
338
+ if key in store:
339
+ return store[key]
340
+ flight_key = (ns, key)
341
+ fut = _TMDB_INFLIGHT.get(flight_key)
342
+ if fut is not None:
343
+ return await fut
344
+ fut = asyncio.get_running_loop().create_future()
345
+ _TMDB_INFLIGHT[flight_key] = fut
346
+ try:
347
+ result = await producer()
348
+ except Exception as e:
349
+ _TMDB_INFLIGHT.pop(flight_key, None)
350
+ if not fut.done():
351
+ fut.set_exception(e)
352
+ fut.exception()
353
+ raise
354
+ store[key] = result
355
+ _TMDB_INFLIGHT.pop(flight_key, None)
356
+ if not fut.done():
357
+ fut.set_result(result)
358
+ return result
359
+
360
+
361
  async def _fetch_tmdb_data(client: httpx.AsyncClient, doc: dict) -> tuple[dict, dict]:
362
+ api_key = tmdb_api_key()
363
  if not api_key:
364
  return {}, {}
365
 
366
  media_type = _media_type(doc)
367
  tmdb_id = doc.get("tmdb_id")
368
 
369
+ #----- Resolve tmdb_id from imdb_id when missing (cached by media_type + imdb_id)
370
  if not tmdb_id and doc.get("imdb_id"):
371
+ imdb_id = doc.get("imdb_id")
372
+
373
+ async def _find():
374
+ resp = await client.get(
375
+ f"https://api.themoviedb.org/3/find/{imdb_id}",
376
+ params={"api_key": api_key, "external_source": "imdb_id"},
377
+ )
378
+ if resp.status_code != 200:
379
+ return None
380
  result_key = "tv_results" if media_type == "tv" else "movie_results"
381
+ results = resp.json().get(result_key) or []
382
+ return results[0].get("id") if results else None
383
+
384
+ tmdb_id = await _cached_call(_TMDB_FIND_CACHE, (media_type, imdb_id), "find", _find)
385
 
386
  if not tmdb_id:
387
  return {}, {}
388
 
389
+ #----- Details (+keywords) and watch providers, each cached by media_type + tmdb_id
390
+ async def _details():
391
+ resp = await client.get(
392
+ f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}",
393
+ params={"api_key": api_key, "language": "en-US", "append_to_response": "keywords"},
394
+ )
395
+ return resp.json() if resp.status_code == 200 else {}
396
+
397
+ async def _providers():
398
+ resp = await client.get(
399
+ f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}/watch/providers",
400
+ params={"api_key": api_key},
401
+ )
402
+ return resp.json() if resp.status_code == 200 else {}
403
 
404
+ details, providers = await asyncio.gather(
405
+ _cached_call(_TMDB_DETAILS_CACHE, (media_type, tmdb_id), "details", _details),
406
+ _cached_call(_TMDB_PROVIDERS_CACHE, (media_type, tmdb_id), "providers", _providers),
407
  return_exceptions=True,
408
  )
409
+ details = details if not isinstance(details, Exception) else {}
410
+ providers = providers if not isinstance(providers, Exception) else {}
 
411
  return details, providers
412
 
413
 
414
+ async def _iter_all_media(db, *, force_refresh: bool = False):
415
  for db_index in range(1, db.current_db_index + 1):
416
  db_key = f"storage_{db_index}"
417
  if db_key not in db.dbs:
 
422
  async for doc in cursor:
423
  doc["db_index"] = db_index
424
  doc["media_type"] = "tv" if collection_name == "tv" else "movie"
425
+ if not force_refresh and _is_already_synced(doc):
426
  yield collection_name, db_index, doc, True
427
  else:
428
  yield collection_name, db_index, doc, False
 
435
  classification = classify_media_from_tmdb(doc, details or {}, watch_data or {}, enabled_names)
436
 
437
  now = datetime.utcnow()
438
+ doc["release_date"] = release_date(doc, details or {})
439
  update_data = {
440
+ "release_date": doc["release_date"],
441
  "original_language": classification.get("original_language"),
442
  "origin_country": classification.get("origin_country", []),
443
  "production_countries": classification.get("production_countries", []),
 
463
  return doc, classification
464
  except Exception as e:
465
  LOGGER.warning(f"Auto catalog classification failed for {doc.get('title')} ({doc.get('tmdb_id')}): {e}")
466
+ return doc, {"auto_tags": _stored_tags(doc)}
467
 
468
 
469
  async def sync_single_media(db, *, tmdb_id, media_type: str) -> dict:
 
499
  async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
500
  media_doc, classification = await _classify_one(db, client, semaphore, doc, enabled_names)
501
 
502
+ tags = [] if media_doc.get("exclusive_catalog_id") else [
503
+ tag for tag in (classification.get("auto_tags") or []) if tag in enabled_names
504
+ ]
505
  if tags:
506
+ await _flush_quick_items(db, {tag: [_catalog_item(media_doc, tag)] for tag in tags})
 
507
 
508
  LOGGER.info(
509
  f"Auto catalog instant index: '{media_doc.get('title')}' "
 
513
 
514
 
515
  def start_single_media_catalog_sync(db, *, tmdb_id, media_type: str) -> None:
516
+ #----- Fire-and-forget launcher for instant per-item categorization
517
  async def runner():
518
  try:
519
  await sync_single_media(db, tmdb_id=tmdb_id, media_type=media_type)
 
523
  try:
524
  asyncio.create_task(runner())
525
  except RuntimeError:
526
+ #----- No running loop (shouldn't happen inside the bot); ignore.
527
  LOGGER.warning("Instant auto catalog index skipped: no running event loop.")
528
 
529
 
 
539
  "$setOnInsert": {
540
  "name": name,
541
  "visible": True,
542
+ "visibility": "public",
543
+ "allowed_tokens": [],
544
  "auto": True,
545
  "auto_key": auto_key,
546
  "items": [],
 
556
  )
557
 
558
  for item in items:
559
+ result = await collection.update_one(
560
  {
561
  "auto_key": auto_key,
562
  "items": {
 
575
  "$inc": {"item_count": 1},
576
  },
577
  )
578
+ if not result.modified_count and item.get("release_date"):
579
+ await collection.update_one(
580
+ {
581
+ "auto_key": auto_key,
582
+ "items": {
583
+ "$elemMatch": {
584
+ "tmdb_id": item["tmdb_id"],
585
+ "db_index": item["db_index"],
586
+ "media_type": item["media_type"],
587
+ }
588
+ },
589
+ },
590
+ {"$set": {"items.$.release_date": item["release_date"]}},
591
+ )
592
 
593
 
594
  async def _rebuild_auto_catalogs(db, catalog_items: Dict[str, List[dict]], enabled_names: Set[str]) -> None:
 
605
  seen.add(key)
606
  unique_items.append(item)
607
 
608
+ unique_items.sort(key=catalog_sort_key, reverse=True)
609
+
610
  await collection.update_one(
611
  {"auto_key": _catalog_key(name)},
612
  {
 
620
  "updated_at": now,
621
  "last_auto_sync": now,
622
  },
623
+ "$setOnInsert": {"created_at": now, "visibility": "public", "allowed_tokens": []},
624
  },
625
  upsert=True,
626
  )
 
641
  )
642
 
643
 
644
+ async def run_auto_catalog_sync(db, *, force: bool = False, force_refresh: bool = False, delay_seconds: int = 0) -> dict:
645
  if delay_seconds:
646
  await asyncio.sleep(delay_seconds)
647
 
 
652
  started_at = datetime.utcnow()
653
  await _write_status(db, {
654
  "running": True,
655
+ "mode": "sync",
656
  "message": "Auto catalog sync running...",
657
  "started_at": started_at,
658
  "finished_at": None,
 
668
  skipped = 0
669
  classified = 0
670
  tagged = 0
 
671
  settings_configured = await has_auto_catalog_settings(db)
672
  enabled_names = await _enabled_catalog_names(db)
673
 
 
675
  finished_at = datetime.utcnow()
676
  summary = {
677
  "running": False,
678
+ "mode": "sync",
679
  "message": "Auto catalog skipped. Save auto catalog selection first.",
680
  "scanned": 0,
681
  "skipped": 0,
 
691
  LOGGER.info(f"Auto catalog sync skipped: {summary}")
692
  return summary
693
 
694
+ if not tmdb_api_key():
695
  LOGGER.warning(
696
  "Auto catalog: no TMDB API key configured — only 'Top Rated' and "
697
+ "'Latest Releases' will populate; language & OTT catalogs need a TMDB key."
698
  )
699
 
700
+ #----- Group a title's stored/fresh tags into the catalogs it belongs to
701
+ def collect(media_doc: dict, tags: List[str]) -> None:
702
+ nonlocal tagged
703
+ if media_doc.get("exclusive_catalog_id"):
704
+ return
705
+ active = [tag for tag in (tags or []) if tag in enabled_names]
706
+ if active:
707
+ tagged += 1
708
+ for tag in active:
709
+ catalog_items.setdefault(tag, []).append(_catalog_item(media_doc, tag))
710
+
711
  try:
712
  timeout = httpx.Timeout(18.0, connect=10.0)
713
  limits = httpx.Limits(max_connections=AUTO_SYNC_CONCURRENCY * 2 + 4, max_keepalive_connections=AUTO_SYNC_CONCURRENCY)
714
  semaphore = asyncio.Semaphore(AUTO_SYNC_CONCURRENCY)
715
 
 
 
 
 
 
 
 
 
 
 
716
  async with httpx.AsyncClient(timeout=timeout, limits=limits, follow_redirects=True) as client:
717
  pending = []
718
+ async for _, _, doc, already_synced in _iter_all_media(db, force_refresh=force_refresh):
719
  scanned += 1
720
 
721
+ #----- Already-tagged titles skip TMDB; reuse their stored tags
722
+ if already_synced:
723
  skipped += 1
724
+ collect(doc, _stored_tags(doc))
725
  continue
726
 
727
  classified += 1
 
729
 
730
  if len(pending) >= 40:
731
  for media_doc, classification in await asyncio.gather(*pending):
732
+ collect(media_doc, classification.get("auto_tags"))
733
  pending = []
734
  await _write_status(db, {
735
  "running": True,
736
+ "mode": "sync",
737
  "started_at": started_at,
738
  "scanned": scanned,
739
  "skipped": skipped,
 
744
 
745
  if pending:
746
  for media_doc, classification in await asyncio.gather(*pending):
747
+ collect(media_doc, classification.get("auto_tags"))
748
 
749
+ #----- Always rebuild fully so removed titles / disabled catalogs are pruned
750
+ await _rebuild_auto_catalogs(db, catalog_items, enabled_names)
 
 
751
 
752
  finished_at = datetime.utcnow()
753
  summary = {
754
  "running": False,
755
+ "mode": "sync",
756
  "scanned": scanned,
757
  "skipped": skipped,
758
  "classified": classified,
 
767
  LOGGER.info(f"Auto catalog sync complete: {summary}")
768
  return summary
769
  except Exception as exc:
 
770
  finished_at = datetime.utcnow()
771
  summary = {
772
  "running": False,
773
+ "mode": "sync",
774
  "scanned": scanned,
775
  "skipped": skipped,
776
  "classified": classified,
 
779
  "enabled_catalogs": sorted(enabled_names),
780
  "started_at": started_at,
781
  "finished_at": finished_at,
782
+ "error": str(exc),
783
  }
784
  await _write_status(db, summary)
785
  LOGGER.error(f"Auto catalog sync failed: {summary}")
786
  raise
787
 
788
 
789
+ async def start_auto_catalog_sync_background(db, *, force_refresh: bool = False, force: bool = False, delay_seconds: int = 0) -> dict:
790
  global _auto_sync_task
791
 
792
  if _auto_sync_lock.locked() or (_auto_sync_task and not _auto_sync_task.done()):
 
795
  started_at = datetime.utcnow()
796
  await _write_status(db, {
797
  "running": True,
798
+ "mode": "sync",
799
  "message": "Auto catalog sync queued...",
800
  "started_at": started_at,
801
  "finished_at": None,
 
808
 
809
  async def runner():
810
  try:
811
+ await run_auto_catalog_sync(db, force=force, force_refresh=force_refresh, delay_seconds=delay_seconds)
812
  except Exception:
813
  LOGGER.exception("Background auto catalog sync crashed")
814
 
815
  _auto_sync_task = asyncio.create_task(runner())
816
  return {
817
  "running": True,
818
+ "message": "Sync started in background.",
819
+ "mode": "sync",
820
  "started_at": started_at,
821
  }
822
 
823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
824
  async def get_auto_catalog_sync_status(db) -> dict:
825
  state = await db.dbs["tracking"]["state"].find_one({"_id": "auto_catalog_sync"}) or {}
826
  state.pop("_id", None)
Backend/helper/backup.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import zlib
4
+ from datetime import datetime
5
+
6
+ from bson import ObjectId
7
+
8
+ from Backend import __version__, db
9
+ from Backend.helper.encrypt import decode_string
10
+ from Backend.helper.settings_manager import SettingsManager
11
+ from Backend.logger import LOGGER
12
+
13
+ #----- Never export/restore credentials; everything else (incl. extra DBs and
14
+ #----- bot tokens) is included so a backup can fully migrate a deployment.
15
+ _SETTINGS_EXCLUDE = {"admin_password", "session_secret"}
16
+
17
+ #----- backup section -> tracking collection
18
+ _COLLECTIONS = {
19
+ "custom_catalogs": "custom_catalogs",
20
+ "subscription_plans": "sub_plans",
21
+ "tokens": "api_tokens",
22
+ }
23
+
24
+ _ISO_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
25
+
26
+
27
+ def _jsonify(obj):
28
+ if isinstance(obj, dict):
29
+ return {k: _jsonify(v) for k, v in obj.items()}
30
+ if isinstance(obj, list):
31
+ return [_jsonify(x) for x in obj]
32
+ if isinstance(obj, ObjectId):
33
+ return str(obj)
34
+ if isinstance(obj, datetime):
35
+ return obj.isoformat()
36
+ return obj
37
+
38
+
39
+ def _revive(obj):
40
+ if isinstance(obj, dict):
41
+ out = {}
42
+ for k, v in obj.items():
43
+ if k == "_id" and isinstance(v, str) and len(v) == 24:
44
+ try:
45
+ out[k] = ObjectId(v)
46
+ continue
47
+ except Exception:
48
+ pass
49
+ out[k] = _revive(v)
50
+ return out
51
+ if isinstance(obj, list):
52
+ return [_revive(x) for x in obj]
53
+ if isinstance(obj, str) and _ISO_RE.match(obj):
54
+ try:
55
+ return datetime.fromisoformat(obj.replace("Z", ""))
56
+ except Exception:
57
+ return obj
58
+ return obj
59
+
60
+
61
+ async def export_config() -> dict:
62
+ settings = {k: v for k, v in SettingsManager.current().to_dict().items() if k not in _SETTINGS_EXCLUDE}
63
+ data = {
64
+ "app": "telegram-stremio",
65
+ "version": __version__,
66
+ "exported_at": datetime.utcnow().isoformat(),
67
+ "settings": settings,
68
+ }
69
+ for label, coll in _COLLECTIONS.items():
70
+ data[label] = await db.dbs["tracking"][coll].find({}).to_list(None)
71
+ return _jsonify(data)
72
+
73
+
74
+ async def import_config(payload: dict) -> dict:
75
+ if not isinstance(payload, dict) or payload.get("app") != "telegram-stremio":
76
+ raise ValueError("This doesn't look like a Telegram-Stremio backup file.")
77
+
78
+ result = {}
79
+
80
+ #----- Settings: apply via SettingsManager.update so extra databases connect
81
+ #----- and multi-token clients start (password/secret are preserved).
82
+ settings = payload.get("settings")
83
+ if isinstance(settings, dict):
84
+ clean = {k: v for k, v in settings.items() if k not in _SETTINGS_EXCLUDE and k != "_id"}
85
+ if clean:
86
+ reinit = await SettingsManager.update(db, clean)
87
+ result["settings"] = f"{len(clean)} keys applied"
88
+ if reinit:
89
+ result["reinit"] = reinit
90
+
91
+ #----- Collections: replace with the backup's contents
92
+ for label, coll in _COLLECTIONS.items():
93
+ section = payload.get(label)
94
+ if not isinstance(section, list):
95
+ continue
96
+ docs = [_revive(d) for d in section if isinstance(d, dict)]
97
+ collection = db.dbs["tracking"][coll]
98
+ await collection.delete_many({})
99
+ if docs:
100
+ await collection.insert_many(docs)
101
+ result[label] = f"{len(docs)} restored"
102
+
103
+ LOGGER.info(f"[BACKUP] Config restored: {result}")
104
+ return result
105
+
106
+
107
+ #----- Library export in TeleStremio's catalog format (gzip, streamed doc by doc)
108
+ _UNITS = {"B": 1, "KB": 1 << 10, "MB": 1 << 20, "GB": 1 << 30, "TB": 1 << 40}
109
+
110
+
111
+ def _size_bytes(size) -> int:
112
+ m = re.match(r"([\d.]+)\s*([KMGT]?B)", str(size or "").upper())
113
+ return int(float(m.group(1)) * _UNITS[m.group(2)]) if m else 0
114
+
115
+
116
+ async def _quality(q: dict):
117
+ parts = q.get("parts") or []
118
+ if not parts:
119
+ try:
120
+ ref = await decode_string(q.get("id") or "")
121
+ parts = [{"part_number": 0, "chat_id": ref["chat_id"], "msg_id": ref["msg_id"], "size_bytes": _size_bytes(q.get("size"))}]
122
+ except Exception:
123
+ return None
124
+ parts = [{k: int(p.get(k) or 0) for k in ("part_number", "chat_id", "msg_id", "size_bytes")} for p in parts]
125
+ return {
126
+ "quality": q.get("quality") or "HD", "id": "", "name": q.get("name") or "", "size": q.get("size") or "",
127
+ "size_bytes": sum(p["size_bytes"] for p in parts) or _size_bytes(q.get("size")),
128
+ "group_key": q.get("group_key"), "parts": parts,
129
+ }
130
+
131
+
132
+ async def _qualities(items) -> list:
133
+ return [q for q in [await _quality(i) for i in items or []] if q]
134
+
135
+
136
+ async def _library_doc(doc: dict, kind: str) -> dict:
137
+ d = _jsonify({k: v for k, v in doc.items() if k not in ("_id", "updated_on")})
138
+ if isinstance(doc.get("updated_on"), datetime):
139
+ d["updated_on"] = d["added_on"] = int(doc["updated_on"].timestamp() * 1000)
140
+ if kind == "movie":
141
+ d["telegram"] = await _qualities(doc.get("telegram"))
142
+ else:
143
+ for season in d.get("seasons") or []:
144
+ for ep in season.get("episodes") or []:
145
+ ep["telegram"] = await _qualities(ep.get("telegram"))
146
+ return d
147
+
148
+
149
+ async def export_library():
150
+ s = SettingsManager.current().to_dict()
151
+ anime = {str(c) for c in s.get("anime_channels") or []}
152
+ titles = s.get("channel_titles") or {}
153
+ gz = zlib.compressobj(6, zlib.DEFLATED, 31)
154
+ yield gz.compress(b'{"format":"telestremio-catalog","version":2,"source":"telegram-stremio"')
155
+ for kind in ("movie", "tv"):
156
+ yield gz.compress(f',"{kind}":['.encode())
157
+ sep = ""
158
+ for key, store in db.dbs.items():
159
+ if not key.startswith("storage_"):
160
+ continue
161
+ async for doc in store[kind].find({}):
162
+ yield gz.compress((sep + json.dumps(await _library_doc(doc, kind))).encode())
163
+ sep = ","
164
+ yield gz.compress(b"]")
165
+ channels = [
166
+ {"ref": str(c), "anime": str(c) in anime, "title": titles.get(str(c), ""),
167
+ "chat_id": int(c) if str(c).lstrip("-").isdigit() else 0}
168
+ for c in s.get("auth_channels") or []
169
+ ]
170
+ yield gz.compress(f',"channels":{json.dumps(channels)}}}'.encode())
171
+ yield gz.flush()
Backend/helper/bounded.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ class BoundedDict(dict):
2
+ def __init__(self, maxlen: int):
3
+ super().__init__()
4
+ self.maxlen = maxlen
5
+
6
+ def __setitem__(self, key, value):
7
+ if key not in self and len(self) >= self.maxlen:
8
+ self.pop(next(iter(self)))
9
+ super().__setitem__(key, value)
Backend/helper/cf_live.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import time
3
+ from collections import deque
4
+
5
+ from Backend import db
6
+ from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
7
+ from Backend.pyrofork.bot import client_avg_mbps, work_loads
8
+
9
+ MIB = 1024 * 1024
10
+
11
+
12
+ #----- Show Cloudflare streams like local ones. Each Worker client reports its live streams every
13
+ #----- ~15s; they go into ACTIVE_STREAMS (dashboard, user activity, bot workloads) and, once they
14
+ #----- stop being reported, into RECENT_STREAMS and the stream history.
15
+ async def apply_report(member: str, client_index, dc, streams: list) -> None:
16
+ from Backend.fastapi.routes.stream_routes import _lookup_title
17
+
18
+ now = time.time()
19
+ seen = set()
20
+ for s in streams:
21
+ sid = f"cf-{s.get('id')}"
22
+ seen.add(sid)
23
+ last_ts = (s.get("last") or s.get("since") or now * 1000) / 1000
24
+ total = int(s.get("bytes") or 0)
25
+ entry = ACTIVE_STREAMS.get(sid)
26
+ if entry is None:
27
+ token = str(s.get("token") or "")
28
+ token_data = await db.get_api_token(token) if token else None
29
+ entry = {
30
+ "stream_id": sid,
31
+ "msg_id": s.get("msg"),
32
+ "chat_id": s.get("chat"),
33
+ "dc_id": dc,
34
+ "client_index": client_index,
35
+ "start_ts": (s.get("since") or now * 1000) / 1000,
36
+ "last_ts": last_ts,
37
+ "total_bytes": 0,
38
+ "avg_mbps": 0.0,
39
+ "instant_mbps": 0.0,
40
+ "peak_mbps": 0.0,
41
+ "recent_measurements": deque(maxlen=3),
42
+ "status": "active",
43
+ "part_count": 0,
44
+ "prefetch": 0,
45
+ "meta": {
46
+ "title": await _lookup_title(s.get("file"), s.get("name") or ""),
47
+ "file_name": s.get("name"),
48
+ "user_name": token_data.get("name", "Unknown") if token_data else "Unknown",
49
+ "token": token,
50
+ "client_host": s.get("ip"),
51
+ "source": "cloudflare",
52
+ "cf_member": member,
53
+ },
54
+ }
55
+ ACTIVE_STREAMS[sid] = entry
56
+ if client_index in work_loads:
57
+ work_loads[client_index] += 1
58
+ elapsed = last_ts - entry["last_ts"]
59
+ if elapsed > 0:
60
+ entry["instant_mbps"] = (total - entry["total_bytes"]) / MIB / elapsed
61
+ entry["peak_mbps"] = max(entry["peak_mbps"], entry["instant_mbps"])
62
+ entry["total_bytes"] = total
63
+ entry["last_ts"] = last_ts
64
+ duration = last_ts - entry["start_ts"]
65
+ entry["avg_mbps"] = total / MIB / duration if duration > 0 else 0.0
66
+
67
+ #----- Streams this client no longer reports have ended
68
+ for sid, entry in list(ACTIVE_STREAMS.items()):
69
+ if sid.startswith("cf-") and entry["meta"].get("cf_member") == member and sid not in seen:
70
+ _finish(sid, entry)
71
+
72
+
73
+ def _finish(sid: str, entry: dict) -> None:
74
+ ACTIVE_STREAMS.pop(sid, None)
75
+ entry.update({
76
+ "end_ts": entry["last_ts"],
77
+ "duration": max(0.0, entry["last_ts"] - entry["start_ts"]),
78
+ "status": "finished",
79
+ })
80
+ idx = entry.get("client_index")
81
+ if idx in work_loads:
82
+ work_loads[idx] = max(0, work_loads[idx] - 1)
83
+ prev = client_avg_mbps.get(idx, 0.0)
84
+ client_avg_mbps[idx] = entry["avg_mbps"] if prev == 0.0 else 0.5 * prev + 0.5 * entry["avg_mbps"]
85
+ RECENT_STREAMS.appendleft(entry)
86
+ asyncio.create_task(db.log_stream_stats(entry))
Backend/helper/cf_stream.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import hashlib
3
+ import hmac
4
+ import time
5
+
6
+ import httpx
7
+
8
+ from Backend.helper.settings_manager import SettingsManager
9
+ from Backend.logger import LOGGER
10
+
11
+ #----- Signed Cloudflare links stay valid this long. The Worker can't read the token DB, so a
12
+ #----- revoked or expired token keeps streaming on Cloudflare until its links run out.
13
+ LINK_TTL = 48 * 3600
14
+
15
+ #----- Max clock skew accepted on requests signed by the Worker
16
+ REQUEST_MAX_AGE = 300
17
+
18
+
19
+ def cf_enabled() -> bool:
20
+ s = SettingsManager.current()
21
+ return s.cf_stream_mode != "off" and bool(s.cf_stream_url and s.cf_stream_secret)
22
+
23
+
24
+ def _hmac(secret: str, message: str) -> str:
25
+ return hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
26
+
27
+
28
+ #----- Cloudflare twin of a /dl/{token}/{id}/{name} link. Only /dl/{token}/{id} and the expiry
29
+ #----- are signed, so players re-encoding the file name don't break the signature.
30
+ def cf_stream_url(token: str, file_id: str, name: str, url: str = None, secret: str = None) -> str:
31
+ s = SettingsManager.current()
32
+ exp = int(time.time()) + LINK_TTL
33
+ sig = _hmac(secret or s.cf_stream_secret, f"/dl/{token}/{file_id}:{exp}")[:32]
34
+ return f"{url or s.cf_stream_url}/dl/{token}/{file_id}/{name}?e={exp}&s={sig}"
35
+
36
+
37
+ #----- Check a Worker -> app request signed as HMAC(secret, "{ts}\n{METHOD} {path}\n{body}")
38
+ def verify_worker_request(method: str, path: str, body: bytes, ts: str, sig: str, secret: str = None) -> bool:
39
+ secret = secret or SettingsManager.current().cf_stream_secret
40
+ if not secret or not ts or not sig:
41
+ return False
42
+ try:
43
+ if abs(time.time() - int(ts)) > REQUEST_MAX_AGE:
44
+ return False
45
+ except ValueError:
46
+ return False
47
+ expected = _hmac(secret, f"{ts}\n{method} {path}\n{body.decode('utf-8', 'replace')}")
48
+ return hmac.compare_digest(expected, sig)
49
+
50
+
51
+ #----- Ask the Worker to reload bot tokens / the userbot session now instead of within 10 minutes
52
+ async def notify_worker(url: str = None, secret: str = None) -> None:
53
+ if not url and not cf_enabled():
54
+ return
55
+ s = SettingsManager.current()
56
+ url, secret = url or s.cf_stream_url, secret or s.cf_stream_secret
57
+ ts, body = str(int(time.time())), "{}"
58
+ headers = {"x-cf-time": ts, "x-cf-sig": _hmac(secret, f"{ts}\nPOST /api/sync\n{body}"), "content-type": "application/json"}
59
+ try:
60
+ async with httpx.AsyncClient(timeout=20) as client:
61
+ r = await client.post(f"{url}/api/sync", content=body, headers=headers)
62
+ if r.status_code != 200:
63
+ LOGGER.warning(f"[CF] Worker sync failed: HTTP {r.status_code} {r.text[:200]}")
64
+ except Exception as e:
65
+ LOGGER.warning(f"[CF] Worker sync failed: {e}")
66
+
67
+
68
+ #----- Fire-and-forget: never delays the save or login that triggered it
69
+ def sync_worker_soon(url: str = None, secret: str = None) -> None:
70
+ asyncio.create_task(notify_worker(url, secret))
Backend/helper/custom_dl.py CHANGED
@@ -1,56 +1,100 @@
1
  import asyncio
2
  import random
3
  import re
4
- import time
5
  import secrets
6
- from collections import deque
7
- from typing import Dict, List, Union, Optional, Tuple
8
  import traceback
 
 
 
9
  from fastapi import Request
10
- from pyrogram import Client, raw, utils
11
  from pyrogram.errors import AuthBytesInvalid
12
- from pyrogram.file_id import FileId, FileType, ThumbnailSource
13
- from pyrogram.session import Session, Auth
14
- from Backend.logger import LOGGER
15
- from Backend.helper.exceptions import FIleNotFound
16
- from Backend.helper.pyro import get_file_ids
17
  from Backend import db
18
- from Backend.pyrofork.bot import work_loads, multi_clients, client_dc_map, client_failures, client_avg_mbps
 
 
 
 
19
 
20
  ACTIVE_STREAMS: Dict[str, Dict] = {}
21
  RECENT_STREAMS = deque(maxlen=20)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
 
 
 
 
 
 
 
 
23
  class ByteStreamer:
24
- CHUNK_SIZE = 1024 * 1024 # 1 MB
25
- CLEAN_INTERVAL = 30 * 60 # 30 minutes
26
  _instances: Dict[int, "ByteStreamer"] = {}
27
 
28
  def __init__(self, client: Client, client_index: int = -1):
29
  self.client = client
30
  self.client_index = client_index
31
- self._file_id_cache: Dict[int, FileId] = {}
32
  self._session_lock = asyncio.Lock()
33
  if client_index >= 0:
34
  ByteStreamer._instances[client_index] = self
35
  asyncio.create_task(self._clean_cache())
36
  asyncio.create_task(self._prewarm_sessions())
 
37
 
38
  async def _prewarm_sessions(self):
39
  common_dcs = [1, 2, 4, 5]
40
  test_mode = await self.client.storage.test_mode()
41
  current_dc = await self.client.storage.dc_id()
42
  for dc in common_dcs:
43
- if dc in self.client.media_sessions or dc == current_dc:
44
  continue
45
  try:
46
- auth_key = await Auth(self.client, dc, test_mode).create()
47
  session = Session(self.client, dc, auth_key, test_mode, is_media=True)
48
  session.no_updates = True
49
  session.timeout = 30
50
  session.sleep_threshold = 60
51
  await session.start()
52
- imported = False
53
- for _ in range(6):
54
  try:
55
  exported = await self.client.invoke(raw.functions.auth.ExportAuthorization(dc_id=dc))
56
  await session.send(raw.functions.auth.ImportAuthorization(id=exported.id,bytes=exported.bytes,))
@@ -62,22 +106,25 @@ class ByteStreamer:
62
  await asyncio.sleep(1)
63
  except Exception:
64
  break
65
- if imported:
66
  self.client.media_sessions[dc] = session
67
  else:
68
  await session.stop()
69
  except Exception:
70
  continue
71
 
 
72
  async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
73
- if message_id not in self._file_id_cache:
 
74
  file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
75
  if not file_id:
76
- LOGGER.warning("Message %s not found", message_id)
77
- raise FIleNotFound
78
- self._file_id_cache[message_id] = file_id
79
- return self._file_id_cache[message_id]
80
 
 
81
  async def prefetch_stream(
82
  self,
83
  file_id: FileId,
@@ -117,9 +164,11 @@ class ByteStreamer:
117
  "part_count": part_count,
118
  "prefetch": prefetch,
119
  "meta": meta or {},
 
120
  }
121
 
122
  ACTIVE_STREAMS[stream_id] = registry_entry
 
123
  work_loads[client_index] += 1
124
 
125
  queue_maxsize = max(1, prefetch)
@@ -133,14 +182,15 @@ class ByteStreamer:
133
  if not chat_id or not message_id:
134
  return False
135
  try:
136
- streamer_ref._file_id_cache.pop(message_id, None)
 
137
  fresh = await get_file_ids(streamer_ref.client, chat_id, message_id)
138
  if fresh:
139
- streamer_ref._file_id_cache[message_id] = fresh
140
  loc_b[0] = await ByteStreamer._get_location(fresh)
141
  return True
142
  except Exception as exc:
143
- LOGGER.warning("Location refresh failed for msg_id=%s: %s", message_id, exc)
144
  return False
145
  return _refresh
146
 
@@ -158,12 +208,10 @@ class ByteStreamer:
158
  LOGGER.warning("Skipping extra client %s (session setup failed): %s", ec_idx, e)
159
 
160
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
161
- slot = seq_idx % len(session_pool)
162
- c_idx, c_session, c_loc_box, c_refresh = session_pool[slot]
163
-
164
  tries = 0
165
  flood_tries = 0
166
  while tries < 3 and flood_tries < 5 and not stop_event.is_set():
 
167
  try:
168
  r = await asyncio.wait_for(
169
  c_session.send(
@@ -205,13 +253,13 @@ class ByteStreamer:
205
  return seq_idx, None
206
 
207
  async def producer():
 
208
  try:
209
  if part_count <= 0:
210
  await q.put((None, None))
211
  return
212
 
213
  next_to_schedule = 0
214
- scheduled_tasks = {}
215
  results_buffer = {}
216
  next_to_put = 0
217
  max_parallel = max(1, parallelism)
@@ -290,6 +338,17 @@ class ByteStreamer:
290
  await q.put((None, None))
291
  except Exception:
292
  pass
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  async def consumer_generator():
295
  producer_task = asyncio.create_task(producer())
@@ -302,7 +361,8 @@ class ByteStreamer:
302
  if _disconnect_check_counter % 8 == 0:
303
  try:
304
  if request and await request.is_disconnected():
305
- ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
 
306
  break
307
  except Exception:
308
  pass
@@ -311,7 +371,8 @@ class ByteStreamer:
311
  off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
312
  except asyncio.TimeoutError:
313
  LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
314
- ACTIVE_STREAMS[stream_id]["status"] = "error"
 
315
  break
316
 
317
  if off_chunk is None:
@@ -321,17 +382,27 @@ class ByteStreamer:
321
  if off is None and chunk is None:
322
  break
323
 
 
 
 
 
 
 
 
 
 
324
  try:
325
- chunk_len = len(chunk)
326
  except Exception:
327
  chunk_len = 0
328
 
329
  now_ts = time.time()
330
- elapsed = now_ts - ACTIVE_STREAMS[stream_id]["last_ts"]
 
331
  if elapsed <= 0:
332
  elapsed = 1e-6
333
 
334
- recent = ACTIVE_STREAMS[stream_id]["recent_measurements"]
335
  recent.append((chunk_len, elapsed))
336
 
337
  if len(recent) >= 2:
@@ -341,41 +412,38 @@ class ByteStreamer:
341
  else:
342
  instant_mbps = 0.0
343
 
344
- ACTIVE_STREAMS[stream_id]["total_bytes"] += chunk_len
345
- ACTIVE_STREAMS[stream_id]["last_ts"] = now_ts
346
 
347
- total_time = now_ts - ACTIVE_STREAMS[stream_id]["start_ts"]
 
348
  if total_time <= 0:
349
  total_time = 1e-6
350
 
351
- ACTIVE_STREAMS[stream_id]["avg_mbps"] = (ACTIVE_STREAMS[stream_id]["total_bytes"] / (1024 * 1024)) / total_time
352
- ACTIVE_STREAMS[stream_id]["instant_mbps"] = instant_mbps
353
 
354
- if instant_mbps > ACTIVE_STREAMS[stream_id]["peak_mbps"]:
355
- ACTIVE_STREAMS[stream_id]["peak_mbps"] = instant_mbps
356
 
357
- if part_count == 1:
358
- yield chunk[first_part_cut:last_part_cut]
359
- elif current_part_idx == 1:
360
- yield chunk[first_part_cut:]
361
- elif current_part_idx == part_count:
362
- yield chunk[:last_part_cut]
363
- else:
364
- yield chunk
365
 
366
  current_part_idx += 1
367
 
368
  except asyncio.CancelledError:
 
369
  if not producer_task.done():
370
  producer_task.cancel()
371
- ACTIVE_STREAMS[stream_id]["status"] = "cancelled"
372
  raise
373
  except Exception as e:
374
  LOGGER.exception("Consumer error for stream %s: %s", stream_id, e)
375
- ACTIVE_STREAMS[stream_id]["status"] = "error"
 
376
  if not producer_task.done():
377
  producer_task.cancel()
378
  finally:
 
379
  if not producer_task.done():
380
  try:
381
  producer_task.cancel()
@@ -385,18 +453,18 @@ class ByteStreamer:
385
 
386
  try:
387
  end_ts = time.time()
388
- total_bytes = ACTIVE_STREAMS[stream_id]["total_bytes"]
389
- start_ts = ACTIVE_STREAMS[stream_id]["start_ts"]
390
  duration = end_ts - start_ts if end_ts > start_ts else 0.0
391
  avg_mbps = (total_bytes / (1024 * 1024)) / (duration if duration > 0 else 1e-6)
392
 
393
- entry = ACTIVE_STREAMS.get(stream_id, {})
394
- entry.update({
395
  "end_ts": end_ts,
396
  "duration": duration,
397
  "avg_mbps": avg_mbps,
398
- "status": "finished" if entry.get("status") == "active" else entry.get("status", "finished"),
399
  "parallelism": parallelism,
 
400
  })
401
 
402
  prev = client_avg_mbps.get(client_index, 0.0)
@@ -404,9 +472,8 @@ class ByteStreamer:
404
  client_avg_mbps[client_index] = avg_mbps
405
  else:
406
  client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps
407
-
408
- entry["chunk_size"] = chunk_size
409
- asyncio.create_task(db.log_stream_stats(entry))
410
 
411
  async def delayed_pop():
412
  await asyncio.sleep(3)
@@ -415,13 +482,11 @@ class ByteStreamer:
415
  RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(stream_id))
416
  except Exception:
417
  pass
418
-
419
  asyncio.create_task(delayed_pop())
420
  finally:
421
- try:
422
- work_loads[client_index] -= 1
423
- except Exception:
424
- pass
425
 
426
  stop_event.set()
427
 
@@ -486,13 +551,11 @@ class ByteStreamer:
486
  LOGGER.debug("ByteStreamer: cleared file_id cache")
487
 
488
 
489
- # ---------------------------------------------------------------------------
490
- # Speed Test helper – runs independently, on-demand per file
491
- # ---------------------------------------------------------------------------
492
-
493
  TEST_CHUNK_SIZE = 100 * 1024 * 1024
494
 
495
 
 
496
  async def _speed_test_single_client(
497
  client: Client,
498
  client_index: int,
@@ -555,7 +618,6 @@ async def _speed_test_single_client(
555
  chunk = getattr(r, "bytes", None)
556
  if not chunk:
557
  eof_reached = True
558
- queue.task_done()
559
  continue
560
  bytes_got = len(chunk)
561
  total_bytes += bytes_got
@@ -615,6 +677,7 @@ async def _speed_test_single_client(
615
  return result
616
 
617
 
 
618
  async def run_speed_test(chat_id: int, message_id: int) -> List[dict]:
619
  if not multi_clients:
620
  return [{"error": "No bot clients connected"}]
 
1
  import asyncio
2
  import random
3
  import re
 
4
  import secrets
5
+ import time
 
6
  import traceback
7
+ from collections import deque
8
+ from typing import Dict, List, Optional, Tuple, Union
9
+
10
  from fastapi import Request
11
+ from pyrogram import Client, raw
12
  from pyrogram.errors import AuthBytesInvalid
13
+ from pyrogram.file_id import FileId
14
+ from pyrogram.session import Auth, Session
15
+
 
 
16
  from Backend import db
17
+ from Backend.helper.exceptions import FileNotFound
18
+ from Backend.helper.pyro import get_file_ids
19
+ from Backend.logger import LOGGER
20
+ from Backend.helper.bounded import BoundedDict
21
+ from Backend.pyrofork.bot import client_avg_mbps, client_dc_map, client_failures, multi_clients, work_loads
22
 
23
  ACTIVE_STREAMS: Dict[str, Dict] = {}
24
  RECENT_STREAMS = deque(maxlen=20)
25
+ STALE_STREAM_IDLE = 180
26
+ _STALE_CLEANER_STARTED = False
27
+
28
+
29
+ async def _cleanup_stale_streams():
30
+ while True:
31
+ try:
32
+ await asyncio.sleep(30)
33
+ now = time.time()
34
+ stale = []
35
+ for sid, entry in list(ACTIVE_STREAMS.items()):
36
+ last = entry.get("last_ts") or entry.get("start_ts") or 0
37
+ status = entry.get("status") or "active"
38
+ total = entry.get("total_bytes") or 0
39
+ idle = now - last
40
+ if status != "active" or idle > STALE_STREAM_IDLE or (total == 0 and idle > 60):
41
+ stale.append(sid)
42
+ for sid in stale:
43
+ try:
44
+ entry = ACTIVE_STREAMS.pop(sid, None)
45
+ if entry:
46
+ entry["status"] = "stale"
47
+ entry["end_ts"] = now
48
+ RECENT_STREAMS.appendleft(entry)
49
+ idx = entry.get("client_index")
50
+ if entry.pop("load_held", False) and idx in work_loads:
51
+ work_loads[idx] = max(0, work_loads[idx] - 1)
52
+ except Exception:
53
+ pass
54
+ except Exception:
55
+ pass
56
+
57
 
58
+ def _ensure_stale_cleaner():
59
+ global _STALE_CLEANER_STARTED
60
+ if not _STALE_CLEANER_STARTED:
61
+ _STALE_CLEANER_STARTED = True
62
+ asyncio.create_task(_cleanup_stale_streams())
63
+
64
+
65
+ #----- Telegram file byte streamer with prefetch, multi-client parallelism, and telemetry
66
  class ByteStreamer:
67
+ CHUNK_SIZE = 1024 * 1024
68
+ CLEAN_INTERVAL = 30 * 60
69
  _instances: Dict[int, "ByteStreamer"] = {}
70
 
71
  def __init__(self, client: Client, client_index: int = -1):
72
  self.client = client
73
  self.client_index = client_index
74
+ self._file_id_cache = BoundedDict(2000)
75
  self._session_lock = asyncio.Lock()
76
  if client_index >= 0:
77
  ByteStreamer._instances[client_index] = self
78
  asyncio.create_task(self._clean_cache())
79
  asyncio.create_task(self._prewarm_sessions())
80
+ _ensure_stale_cleaner()
81
 
82
  async def _prewarm_sessions(self):
83
  common_dcs = [1, 2, 4, 5]
84
  test_mode = await self.client.storage.test_mode()
85
  current_dc = await self.client.storage.dc_id()
86
  for dc in common_dcs:
87
+ if dc in self.client.media_sessions:
88
  continue
89
  try:
90
+ auth_key = await self.client.storage.auth_key() if dc == current_dc else await Auth(self.client, dc, test_mode).create()
91
  session = Session(self.client, dc, auth_key, test_mode, is_media=True)
92
  session.no_updates = True
93
  session.timeout = 30
94
  session.sleep_threshold = 60
95
  await session.start()
96
+ imported = dc == current_dc
97
+ for _ in range(0 if imported else 6):
98
  try:
99
  exported = await self.client.invoke(raw.functions.auth.ExportAuthorization(dc_id=dc))
100
  await session.send(raw.functions.auth.ImportAuthorization(id=exported.id,bytes=exported.bytes,))
 
106
  await asyncio.sleep(1)
107
  except Exception:
108
  break
109
+ if imported and dc not in self.client.media_sessions:
110
  self.client.media_sessions[dc] = session
111
  else:
112
  await session.stop()
113
  except Exception:
114
  continue
115
 
116
+ #----- Fetch (and cache) Telegram FileId properties for a message
117
  async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
118
+ cache_key = (int(chat_id), int(message_id))
119
+ if cache_key not in self._file_id_cache:
120
  file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
121
  if not file_id:
122
+ LOGGER.warning("Message %s not found in chat %s", message_id, chat_id)
123
+ raise FileNotFound
124
+ self._file_id_cache[cache_key] = file_id
125
+ return self._file_id_cache[cache_key]
126
 
127
+ #----- Build a prefetching, range-aware streaming generator for a file
128
  async def prefetch_stream(
129
  self,
130
  file_id: FileId,
 
164
  "part_count": part_count,
165
  "prefetch": prefetch,
166
  "meta": meta or {},
167
+ "load_held": True,
168
  }
169
 
170
  ACTIVE_STREAMS[stream_id] = registry_entry
171
+ stream_entry = registry_entry
172
  work_loads[client_index] += 1
173
 
174
  queue_maxsize = max(1, prefetch)
 
182
  if not chat_id or not message_id:
183
  return False
184
  try:
185
+ cache_key = (int(chat_id), int(message_id))
186
+ streamer_ref._file_id_cache.pop(cache_key, None)
187
  fresh = await get_file_ids(streamer_ref.client, chat_id, message_id)
188
  if fresh:
189
+ streamer_ref._file_id_cache[cache_key] = fresh
190
  loc_b[0] = await ByteStreamer._get_location(fresh)
191
  return True
192
  except Exception as exc:
193
+ LOGGER.warning("Location refresh failed for chat=%s msg_id=%s: %s", chat_id, message_id, exc)
194
  return False
195
  return _refresh
196
 
 
208
  LOGGER.warning("Skipping extra client %s (session setup failed): %s", ec_idx, e)
209
 
210
  async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
 
 
 
211
  tries = 0
212
  flood_tries = 0
213
  while tries < 3 and flood_tries < 5 and not stop_event.is_set():
214
+ c_idx, c_session, c_loc_box, c_refresh = session_pool[(seq_idx + tries) % len(session_pool)]
215
  try:
216
  r = await asyncio.wait_for(
217
  c_session.send(
 
253
  return seq_idx, None
254
 
255
  async def producer():
256
+ scheduled_tasks = {}
257
  try:
258
  if part_count <= 0:
259
  await q.put((None, None))
260
  return
261
 
262
  next_to_schedule = 0
 
263
  results_buffer = {}
264
  next_to_put = 0
265
  max_parallel = max(1, parallelism)
 
338
  await q.put((None, None))
339
  except Exception:
340
  pass
341
+ finally:
342
+ stop_event.set()
343
+ if scheduled_tasks:
344
+ for t in scheduled_tasks.values():
345
+ if not t.done():
346
+ t.cancel()
347
+ try:
348
+ await asyncio.gather(*scheduled_tasks.values(), return_exceptions=True)
349
+ except Exception:
350
+ pass
351
+ scheduled_tasks.clear()
352
 
353
  async def consumer_generator():
354
  producer_task = asyncio.create_task(producer())
 
361
  if _disconnect_check_counter % 8 == 0:
362
  try:
363
  if request and await request.is_disconnected():
364
+ stop_event.set()
365
+ stream_entry["status"] = "cancelled"
366
  break
367
  except Exception:
368
  pass
 
371
  off_chunk = await asyncio.wait_for(q.get(), timeout=90.0)
372
  except asyncio.TimeoutError:
373
  LOGGER.error("Producer stall (90 s) for stream %s — aborting", stream_id)
374
+ stop_event.set()
375
+ stream_entry["status"] = "error"
376
  break
377
 
378
  if off_chunk is None:
 
382
  if off is None and chunk is None:
383
  break
384
 
385
+ if part_count == 1:
386
+ out_chunk = chunk[first_part_cut:last_part_cut]
387
+ elif current_part_idx == 1:
388
+ out_chunk = chunk[first_part_cut:]
389
+ elif current_part_idx == part_count:
390
+ out_chunk = chunk[:last_part_cut]
391
+ else:
392
+ out_chunk = chunk
393
+
394
  try:
395
+ chunk_len = len(out_chunk)
396
  except Exception:
397
  chunk_len = 0
398
 
399
  now_ts = time.time()
400
+ last_ts = stream_entry.get("last_ts") or stream_entry.get("start_ts") or now_ts
401
+ elapsed = now_ts - last_ts
402
  if elapsed <= 0:
403
  elapsed = 1e-6
404
 
405
+ recent = stream_entry.setdefault("recent_measurements", deque(maxlen=3))
406
  recent.append((chunk_len, elapsed))
407
 
408
  if len(recent) >= 2:
 
412
  else:
413
  instant_mbps = 0.0
414
 
415
+ stream_entry["total_bytes"] = stream_entry.get("total_bytes", 0) + chunk_len
416
+ stream_entry["last_ts"] = now_ts
417
 
418
+ start_ts = stream_entry.get("start_ts") or now_ts
419
+ total_time = now_ts - start_ts
420
  if total_time <= 0:
421
  total_time = 1e-6
422
 
423
+ stream_entry["avg_mbps"] = (stream_entry["total_bytes"] / (1024 * 1024)) / total_time
424
+ stream_entry["instant_mbps"] = instant_mbps
425
 
426
+ if instant_mbps > stream_entry.get("peak_mbps", 0.0):
427
+ stream_entry["peak_mbps"] = instant_mbps
428
 
429
+ yield out_chunk
 
 
 
 
 
 
 
430
 
431
  current_part_idx += 1
432
 
433
  except asyncio.CancelledError:
434
+ stop_event.set()
435
  if not producer_task.done():
436
  producer_task.cancel()
437
+ stream_entry["status"] = "cancelled"
438
  raise
439
  except Exception as e:
440
  LOGGER.exception("Consumer error for stream %s: %s", stream_id, e)
441
+ stop_event.set()
442
+ stream_entry["status"] = "error"
443
  if not producer_task.done():
444
  producer_task.cancel()
445
  finally:
446
+ stop_event.set()
447
  if not producer_task.done():
448
  try:
449
  producer_task.cancel()
 
453
 
454
  try:
455
  end_ts = time.time()
456
+ total_bytes = stream_entry.get("total_bytes", 0)
457
+ start_ts = stream_entry.get("start_ts") or end_ts
458
  duration = end_ts - start_ts if end_ts > start_ts else 0.0
459
  avg_mbps = (total_bytes / (1024 * 1024)) / (duration if duration > 0 else 1e-6)
460
 
461
+ stream_entry.update({
 
462
  "end_ts": end_ts,
463
  "duration": duration,
464
  "avg_mbps": avg_mbps,
465
+ "status": "finished" if stream_entry.get("status") == "active" else stream_entry.get("status", "finished"),
466
  "parallelism": parallelism,
467
+ "chunk_size": chunk_size,
468
  })
469
 
470
  prev = client_avg_mbps.get(client_index, 0.0)
 
472
  client_avg_mbps[client_index] = avg_mbps
473
  else:
474
  client_avg_mbps[client_index] = 0.5 * prev + 0.5 * avg_mbps
475
+
476
+ asyncio.create_task(db.log_stream_stats(stream_entry))
 
477
 
478
  async def delayed_pop():
479
  await asyncio.sleep(3)
 
482
  RECENT_STREAMS.appendleft(ACTIVE_STREAMS.pop(stream_id))
483
  except Exception:
484
  pass
485
+
486
  asyncio.create_task(delayed_pop())
487
  finally:
488
+ if stream_entry.pop("load_held", False):
489
+ work_loads[client_index] = max(0, work_loads.get(client_index, 0) - 1)
 
 
490
 
491
  stop_event.set()
492
 
 
551
  LOGGER.debug("ByteStreamer: cleared file_id cache")
552
 
553
 
554
+ #----- Speed test helper (runs independently, on-demand per file)
 
 
 
555
  TEST_CHUNK_SIZE = 100 * 1024 * 1024
556
 
557
 
558
+ #----- Download a fixed slice from one client and measure throughput
559
  async def _speed_test_single_client(
560
  client: Client,
561
  client_index: int,
 
618
  chunk = getattr(r, "bytes", None)
619
  if not chunk:
620
  eof_reached = True
 
621
  continue
622
  bytes_got = len(chunk)
623
  total_bytes += bytes_got
 
677
  return result
678
 
679
 
680
+ #----- Run the speed test across every connected client, fastest first
681
  async def run_speed_test(chat_id: int, message_id: int) -> List[dict]:
682
  if not multi_clients:
683
  return [{"error": "No bot clients connected"}]
Backend/helper/custom_filter.py CHANGED
@@ -1,12 +1,14 @@
1
  from pyrogram.filters import create
 
2
  from Backend.config import Telegram
3
 
 
 
4
  class CustomFilters:
5
 
6
  @staticmethod
7
  async def owner_filter(client, message):
8
  user = message.from_user or message.sender_chat
9
- uid = user.id
10
- return uid == Telegram.OWNER_ID
11
 
12
- owner = create(owner_filter)
 
1
  from pyrogram.filters import create
2
+
3
  from Backend.config import Telegram
4
 
5
+
6
+ #----- Pyrogram filters restricting handlers to the configured owner
7
  class CustomFilters:
8
 
9
  @staticmethod
10
  async def owner_filter(client, message):
11
  user = message.from_user or message.sender_chat
12
+ return user.id == Telegram.OWNER_ID
 
13
 
14
+ owner = create(owner_filter)
Backend/helper/database.py CHANGED
The diff for this file is too large to render. See raw diff
 
Backend/helper/encrypt.py CHANGED
@@ -1,18 +1,24 @@
1
- import zlib
2
- import json
3
  import asyncio
 
 
4
  from concurrent.futures import ThreadPoolExecutor
5
 
6
  executor = ThreadPoolExecutor()
7
 
 
 
 
 
8
  def compress_data(data):
9
  return zlib.compress(data.encode(), level=zlib.Z_BEST_COMPRESSION)
10
 
 
11
  def decompress_data(data):
12
  return zlib.decompress(data).decode()
13
 
 
 
14
  def base62_encode(data):
15
- BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
16
  num = int.from_bytes(data, 'big')
17
  base62 = []
18
  while num:
@@ -20,35 +26,28 @@ def base62_encode(data):
20
  base62.append(BASE62_ALPHABET[rem])
21
  return ''.join(reversed(base62)) or '0'
22
 
 
23
  def base62_decode(data):
24
- BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
25
  num = 0
26
  for char in data:
27
  num = num * 62 + BASE62_ALPHABET.index(char)
28
  return num.to_bytes((num.bit_length() + 7) // 8, 'big') or b'\0'
29
 
30
- async def async_compress_data(data):
31
- loop = asyncio.get_running_loop()
32
- return await loop.run_in_executor(executor, compress_data, data)
33
 
34
- async def async_decompress_data(data):
 
35
  loop = asyncio.get_running_loop()
36
- return await loop.run_in_executor(executor, decompress_data, data)
37
 
38
- async def async_base62_encode(data):
39
- loop = asyncio.get_running_loop()
40
- return await loop.run_in_executor(executor, base62_encode, data)
41
-
42
- async def async_base62_decode(data):
43
- loop = asyncio.get_running_loop()
44
- return await loop.run_in_executor(executor, base62_decode, data)
45
 
 
46
  async def encode_string(data):
47
- json_data = json.dumps(data)
48
- compressed_data = await async_compress_data(json_data)
49
- return await async_base62_encode(compressed_data)
50
 
 
51
  async def decode_string(encoded_data):
52
- compressed_data = await async_base62_decode(encoded_data)
53
- json_data = await async_decompress_data(compressed_data)
54
  return json.loads(json_data)
 
 
 
1
  import asyncio
2
+ import json
3
+ import zlib
4
  from concurrent.futures import ThreadPoolExecutor
5
 
6
  executor = ThreadPoolExecutor()
7
 
8
+ BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
9
+
10
+
11
+ #----- zlib (de)compression
12
  def compress_data(data):
13
  return zlib.compress(data.encode(), level=zlib.Z_BEST_COMPRESSION)
14
 
15
+
16
  def decompress_data(data):
17
  return zlib.decompress(data).decode()
18
 
19
+
20
+ #----- base62 (de)encoding of raw bytes
21
  def base62_encode(data):
 
22
  num = int.from_bytes(data, 'big')
23
  base62 = []
24
  while num:
 
26
  base62.append(BASE62_ALPHABET[rem])
27
  return ''.join(reversed(base62)) or '0'
28
 
29
+
30
  def base62_decode(data):
 
31
  num = 0
32
  for char in data:
33
  num = num * 62 + BASE62_ALPHABET.index(char)
34
  return num.to_bytes((num.bit_length() + 7) // 8, 'big') or b'\0'
35
 
 
 
 
36
 
37
+ #----- Offload a blocking callable to the thread pool
38
+ async def _run(fn, data):
39
  loop = asyncio.get_running_loop()
40
+ return await loop.run_in_executor(executor, fn, data)
41
 
 
 
 
 
 
 
 
42
 
43
+ #----- Encode a JSON-serializable value into a compact base62 string
44
  async def encode_string(data):
45
+ compressed_data = await _run(compress_data, json.dumps(data))
46
+ return await _run(base62_encode, compressed_data)
47
+
48
 
49
+ #----- Decode a base62 string back into the original value
50
  async def decode_string(encoded_data):
51
+ compressed_data = await _run(base62_decode, encoded_data)
52
+ json_data = await _run(decompress_data, compressed_data)
53
  return json.loads(json_data)
Backend/helper/exceptions.py CHANGED
@@ -2,5 +2,5 @@ class InvalidHash(Exception):
2
  message = 'Invalid hash!'
3
 
4
 
5
- class FIleNotFound(Exception):
6
  message = 'File not found!'
 
2
  message = 'Invalid hash!'
3
 
4
 
5
+ class FileNotFound(Exception):
6
  message = 'File not found!'
Backend/helper/fanart.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import random
3
+ import time
4
+ from typing import Optional
5
+ from urllib.parse import quote
6
+
7
+ import httpx
8
+
9
+ from Backend.helper.metadata import tmdb_api_key
10
+ from Backend.helper.settings_manager import SettingsManager
11
+ from Backend.helper.bounded import BoundedDict
12
+ from Backend.logger import LOGGER
13
+
14
+ _MOVIE_URL = "https://webservice.fanart.tv/v3/movies/{id}"
15
+ _TV_URL = "https://webservice.fanart.tv/v3/tv/{id}"
16
+ _EXTERNAL_IDS_URL = "https://api.themoviedb.org/3/tv/{id}/external_ids"
17
+
18
+ _MOVIE_FIELDS = {
19
+ "poster": ["movieposter"],
20
+ "logo": ["hdmovielogo", "movielogo", "clearlogo"],
21
+ "background": ["moviebackground"],
22
+ }
23
+ _TV_FIELDS = {
24
+ "poster": ["tvposter"],
25
+ "logo": ["hdtvlogo", "clearlogo", "hdclearlogo"],
26
+ "background": ["showbackground"],
27
+ }
28
+
29
+ def _preview(url: str) -> str:
30
+ return url.replace("/fanart/", "/preview/", 1) if url else url
31
+
32
+
33
+ def _medium(url: str) -> str:
34
+ return f"https://wsrv.nl/?url={quote(url, safe='')}&w=1280&output=webp&q=80" if url else url
35
+
36
+
37
+ _CACHE_TTL = 6 * 3600
38
+ _ERROR_TTL = 300
39
+ _CACHE_MAX = 4096
40
+ _cache: dict = {}
41
+ _tvdb_cache = BoundedDict(2000)
42
+ _inflight: dict = {}
43
+
44
+ _client: Optional[httpx.AsyncClient] = None
45
+ _client_lock = asyncio.Lock()
46
+ _fetch_sem = asyncio.Semaphore(10)
47
+
48
+
49
+ async def _get_client() -> httpx.AsyncClient:
50
+ global _client
51
+ async with _client_lock:
52
+ if _client is None or _client.is_closed:
53
+ _client = httpx.AsyncClient(
54
+ timeout=httpx.Timeout(8.0, connect=4.0),
55
+ follow_redirects=True,
56
+ )
57
+ return _client
58
+
59
+
60
+ async def _fetch_remote(url: str, params: dict) -> dict:
61
+ try:
62
+ async with _fetch_sem:
63
+ client = await _get_client()
64
+ resp = await client.get(url, params=params)
65
+ data = resp.json() if resp.status_code == 200 else {}
66
+ ttl = _CACHE_TTL if resp.status_code == 200 else _ERROR_TTL
67
+ except Exception as e:
68
+ LOGGER.warning(f"[FANART] fetch failed {url}: {e}")
69
+ data, ttl = {}, _ERROR_TTL
70
+ if not isinstance(data, dict):
71
+ data, ttl = {}, _ERROR_TTL
72
+ if len(_cache) >= _CACHE_MAX:
73
+ for k in sorted(_cache, key=lambda k: _cache[k][0])[: _CACHE_MAX // 10]:
74
+ _cache.pop(k, None)
75
+ _cache[url] = (time.monotonic(), data, ttl)
76
+ return data
77
+
78
+
79
+ async def _fetch(url: str, params: dict) -> dict:
80
+ cached = _cache.get(url)
81
+ if cached and time.monotonic() - cached[0] < cached[2]:
82
+ return cached[1]
83
+ task = _inflight.get(url)
84
+ if task is None:
85
+ task = asyncio.create_task(_fetch_remote(url, params))
86
+ _inflight[url] = task
87
+ task.add_done_callback(lambda _t, _u=url: _inflight.pop(_u, None))
88
+ return await task
89
+
90
+
91
+ async def _resolve_tvdb(tmdb_id) -> Optional[int]:
92
+ if not tmdb_id:
93
+ return None
94
+ if tmdb_id in _tvdb_cache:
95
+ return _tvdb_cache[tmdb_id]
96
+ key = tmdb_api_key()
97
+ if not key:
98
+ return None
99
+ data = await _fetch(_EXTERNAL_IDS_URL.format(id=tmdb_id), {"api_key": key})
100
+ tvdb = data.get("tvdb_id")
101
+ _tvdb_cache[tmdb_id] = tvdb
102
+ return tvdb
103
+
104
+
105
+ def _pick(items, shuffle: bool, interval: int, seed_key: str) -> str:
106
+ items = [i for i in (items or []) if i.get("url")]
107
+ if not items:
108
+ return ""
109
+ english = [i for i in items if (i.get("lang") or "").lower() == "en"]
110
+ pool = english or items
111
+ if not shuffle:
112
+ return max(pool, key=lambda i: int(i.get("likes") or 0)).get("url", "")
113
+ if interval <= 0:
114
+ return random.choice(pool).get("url", "")
115
+ bucket = int(time.time() // (interval * 60))
116
+ return random.Random(f"{seed_key}:{bucket}").choice(pool).get("url", "")
117
+
118
+
119
+ async def fanart_artwork(imdb_id, tmdb_id, media_type) -> dict:
120
+ settings = SettingsManager.current()
121
+ api_key = settings.fanart_api_key
122
+ if not api_key:
123
+ return {}
124
+
125
+ is_tv = media_type == "tv"
126
+ if is_tv:
127
+ lookup_id = await _resolve_tvdb(tmdb_id)
128
+ url_tmpl, fields = _TV_URL, _TV_FIELDS
129
+ else:
130
+ lookup_id = imdb_id
131
+ url_tmpl, fields = _MOVIE_URL, _MOVIE_FIELDS
132
+ if not lookup_id:
133
+ return {}
134
+
135
+ data = await _fetch(url_tmpl.format(id=lookup_id), {"api_key": api_key})
136
+ if not data:
137
+ return {}
138
+
139
+ shuffle = settings.fanart_shuffle
140
+ interval = settings.fanart_shuffle_interval
141
+ optimize = settings.fanart_low_res_poster
142
+ out = {}
143
+ for target, keys in fields.items():
144
+ items = []
145
+ for k in keys:
146
+ items = data.get(k) or []
147
+ if items:
148
+ break
149
+ url = _pick(items, shuffle, interval, f"{lookup_id}:{target}")
150
+ if not url:
151
+ continue
152
+ if optimize:
153
+ if target in ("poster", "logo"):
154
+ url = _preview(url)
155
+ elif target == "background":
156
+ url = _medium(url)
157
+ out[target] = url
158
+ return out
Backend/helper/global_search.py CHANGED
@@ -1,7 +1,7 @@
1
  import asyncio
2
  import re
3
  import time
4
- from typing import Dict, List, Optional, Tuple
5
 
6
  import PTN
7
  from pyrogram import enums
@@ -16,108 +16,190 @@ from pyrogram.errors import (
16
  RPCError,
17
  )
18
 
 
19
  from Backend.logger import LOGGER
20
  from Backend.helper.settings_manager import SettingsManager
21
  from Backend.helper.encrypt import encode_string
 
 
 
22
 
23
- MAX_RESULTS = 50
24
  MAX_RESULTS_PER_CHAT = 50
25
  SEARCH_COOLDOWN_SECONDS = 5
26
  MAX_CONCURRENT_SEARCHES = 3
27
- MIN_TITLE_SCORE = 0.6
 
 
28
 
29
- _last_search_ts: Dict[str, float] = {}
30
- _inflight_queries: set = set()
 
31
  _search_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEARCHES)
 
32
  _userbot_session_dead = False
33
-
34
- # Cache: chat_id -> title string so we don't call get_chat() per result
35
- _chat_title_cache: Dict[int, str] = {}
36
 
37
  _TOKEN_RE = re.compile(r"[a-z0-9]+")
38
  _MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
 
 
 
 
39
 
40
 
41
- # ── Availability ──────────────────────────────────────────────────────────────
42
-
43
  def is_userbot_available() -> bool:
44
- from Backend.pyrofork.bot import Userbot
45
- return Userbot is not None and not _userbot_session_dead
46
 
47
 
48
  def is_global_search_enabled() -> bool:
49
  if not is_userbot_available():
50
  return False
51
  s = SettingsManager.current()
52
- return bool(s.global_search and s.global_search_channels)
53
-
54
-
55
- # ── Helpers ───────────────────────────────────────────────────────────────────
56
-
57
- def _readable_size(num_bytes: int) -> str:
58
- from Backend.helper.pyro import get_readable_file_size
59
- return get_readable_file_size(num_bytes)
60
 
61
 
62
  def _tokens(s: str) -> set:
63
  return set(_TOKEN_RE.findall((s or "").lower()))
64
 
65
 
66
- def _title_score(result_title: str, expected_title: str) -> float:
 
 
 
67
  expected = _tokens(expected_title)
68
- if not expected:
 
 
69
  return 0.0
70
- return len(expected & _tokens(result_title)) / len(expected)
71
 
 
72
 
73
- def _matches_episode(parsed: dict, season: Optional[int], episode: Optional[int]) -> bool:
74
- if season is not None:
75
- rs = parsed.get("season")
76
- if rs is not None:
77
- if isinstance(rs, list):
78
- if season not in rs:
79
- return False
80
- elif int(rs) != int(season):
81
- return False
 
 
82
 
83
- if episode is not None:
84
- re_ = parsed.get("episode")
85
- if re_ is not None:
86
- if isinstance(re_, list):
87
- if episode not in re_:
88
- return False
89
- elif int(re_) != int(episode):
90
- return False
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  return True
93
 
94
 
95
- def _parse_and_validate(
96
- filename: str,
97
- expected_title: str,
98
- season: Optional[int],
99
- episode: Optional[int],
100
- ) -> Optional[dict]:
101
- # Skip split files (e.g. Part1, CD2, Disc3)
102
- if _MULTIPART_RE.search(filename):
103
- LOGGER.info(f"Skipping {filename}: seems to be a split video file")
104
- return None
 
105
 
 
 
106
  try:
107
  parsed = PTN.parse(filename)
108
  except Exception:
109
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- # Skip files marked as combined in PTN excess tags
112
- if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
113
- LOGGER.info(f"Skipping {filename}: contains 'combined'")
114
  return None
 
 
115
 
116
- if not _matches_episode(parsed, season, episode):
 
117
  return None
118
- if _title_score(parsed.get("title", ""), expected_title) < MIN_TITLE_SCORE:
 
 
 
 
119
  return None
120
- return parsed
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
 
123
  def _video_filename(message) -> Optional[str]:
@@ -125,17 +207,48 @@ def _video_filename(message) -> Optional[str]:
125
  return (message.caption or "").strip() or getattr(message.video, "file_name", None) or "video.mkv"
126
  if message.document:
127
  mime = message.document.mime_type or ""
128
- if mime.startswith("video/") or message.document.file_name and (
129
- message.document.file_name.lower().endswith(
130
- (".mkv", ".mp4", ".avi", ".ts", ".m4v", ".mov", ".wmv", ".webm", ".flv")
131
- )
132
- ):
133
- return (message.caption or "").strip() or message.document.file_name or "video.mkv"
134
  return None
135
 
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  def _resolve_channel_ids(channel_ids: List[str]) -> List[int]:
138
- resolved = []
139
  seen: set = set()
140
  for c in channel_ids:
141
  c = str(c).strip()
@@ -158,12 +271,78 @@ async def _get_chat_title(client, chat_id: int) -> str:
158
  try:
159
  chat = await client.get_chat(chat_id)
160
  title = chat.title or str(chat_id)
161
- except Exception:
 
162
  title = str(chat_id)
163
  _chat_title_cache[chat_id] = title
164
  return title
165
 
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  async def _search_channel(
168
  client,
169
  chat_id: int,
@@ -173,78 +352,137 @@ async def _search_channel(
173
  season: Optional[int],
174
  episode: Optional[int],
175
  ) -> List[Dict]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- results: List[Dict] = []
178
- seen_msg_ids: set = set()
179
- filters_to_try = [enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT]
180
-
181
- for msg_filter in filters_to_try:
182
- if len(results) >= MAX_RESULTS_PER_CHAT:
183
- break
184
- try:
185
- async for message in client.search_messages(
186
- chat_id=chat_id,
187
- query=search_query,
188
- filter=msg_filter,
189
- limit=MAX_RESULTS_PER_CHAT,
190
- ):
191
- if message.id in seen_msg_ids:
192
- continue
193
- seen_msg_ids.add(message.id)
194
-
195
- filename = _video_filename(message)
196
- if not filename:
197
- continue
198
-
199
- parsed = _parse_and_validate(filename, expected_title, season, episode)
200
- if parsed is None:
201
- continue
202
-
203
- media = message.video or message.document
204
- size_bytes = getattr(media, "file_size", 0) or 0
205
- quality = parsed.get("resolution") or "HD"
206
-
207
- token = await encode_string({
208
- "global": True,
209
- "chat_id": chat_id,
210
- "msg_id": message.id,
211
- "title": filename,
212
- "size": _readable_size(size_bytes),
213
- "quality": quality,
214
- "source": chat_title,
215
- })
216
-
217
- results.append({
218
- "token": token,
219
- "title": filename,
220
- "size": _readable_size(size_bytes),
221
- "source_chat": chat_title,
222
- "quality": quality,
223
- })
224
-
225
- LOGGER.debug(f"[GLOBAL SEARCH] Result found: {filename} in {chat_title}")
226
-
227
- if len(results) >= MAX_RESULTS_PER_CHAT:
228
- break
229
-
230
- except FloodWait as e:
231
- LOGGER.warning(f"[USERBOT] FloodWait for {chat_title}: sleeping {e.value}s")
232
- await asyncio.sleep(e.value)
233
- except (ChatAdminRequired, ChannelPrivate, PeerIdInvalid, UserNotParticipant) as e:
234
- LOGGER.warning(f"[USERBOT] Cannot access channel {chat_title}: {type(e).__name__}")
235
- break # no point trying second filter either
236
- except (AuthKeyUnregistered, SessionRevoked) as e:
237
- LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
238
- global _userbot_session_dead
239
- _userbot_session_dead = True
240
- break
241
- except RPCError as e:
242
- LOGGER.warning(f"[USERBOT] RPC error in {chat_title} ({msg_filter}): {e}")
243
-
244
- return results
245
-
246
-
247
- # ── Public API ────────────────────────────────────────────────────────────────
248
 
249
  async def global_search(
250
  expected_title: str,
@@ -258,64 +496,267 @@ async def global_search(
258
  if not expected_title or not is_global_search_enabled():
259
  return []
260
 
261
- from Backend.pyrofork.bot import Userbot
262
-
263
  settings = SettingsManager.current()
264
  target_ids = _resolve_channel_ids(settings.global_search_channels)
265
- if not target_ids:
266
- return []
267
 
268
- search_query = expected_title
269
- if season is not None and episode is not None:
270
- search_query = f"{expected_title} S{int(season):02d}E{int(episode):02d}"
271
- elif year is not None:
272
- search_query = f"{expected_title} {year}"
273
-
274
 
275
- key = search_query.lower()
276
  now = time.time()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  if now - _last_search_ts.get(key, 0) < SEARCH_COOLDOWN_SECONDS:
278
- LOGGER.info(f"[GLOBAL SEARCH] Cooldown active for '{search_query}'")
279
- return []
280
- if key in _inflight_queries:
281
- LOGGER.info(f"[GLOBAL SEARCH] Duplicate in-flight for '{search_query}'")
282
  return []
283
 
284
- _inflight_queries.add(key)
285
  _last_search_ts[key] = now
286
-
 
 
 
 
 
 
 
 
287
  try:
288
- async with _search_semaphore:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  LOGGER.info(
290
- f"[USERBOT] Search started: '{search_query}' "
291
- f"across {len(target_ids)} channel(s)"
292
  )
293
- title_tasks = [_get_chat_title(Userbot, cid) for cid in target_ids]
294
- chat_titles = await asyncio.gather(*title_tasks, return_exceptions=True)
295
-
296
- search_tasks = []
297
- for cid, title in zip(target_ids, chat_titles):
298
- if isinstance(title, Exception):
299
- title = str(cid)
300
- if _userbot_session_dead:
301
- break
302
- search_tasks.append(
303
- _search_channel(Userbot, cid, title, search_query, expected_title, season, episode)
304
- )
305
 
 
 
 
 
306
  per_channel_results = await asyncio.gather(*search_tasks, return_exceptions=True)
307
 
308
- all_results: List[Dict] = []
309
  for r in per_channel_results:
310
  if isinstance(r, list):
311
  all_results.extend(r)
312
 
313
- all_results = all_results[:MAX_RESULTS]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
  LOGGER.info(
316
- f"[USERBOT] Search completed: '{search_query}' "
317
- f"-> {len(all_results)} result(s)"
318
  )
319
- return all_results
320
- finally:
321
- _inflight_queries.discard(key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import asyncio
2
  import re
3
  import time
4
+ from typing import Dict, List, Optional
5
 
6
  import PTN
7
  from pyrogram import enums
 
16
  RPCError,
17
  )
18
 
19
+ from Backend.helper.bounded import BoundedDict
20
  from Backend.logger import LOGGER
21
  from Backend.helper.settings_manager import SettingsManager
22
  from Backend.helper.encrypt import encode_string
23
+ from Backend.helper.pyro import get_readable_file_size
24
+ from Backend.helper.split_files import parse_combined_episodes, parse_split_info, strip_part_suffix
25
+ import Backend.pyrofork.bot as botmod
26
 
27
+ MAX_RESULTS = 50
28
  MAX_RESULTS_PER_CHAT = 50
29
  SEARCH_COOLDOWN_SECONDS = 5
30
  MAX_CONCURRENT_SEARCHES = 3
31
+ MAX_CONCURRENT_CHANNELS = 5
32
+ MIN_TITLE_SCORE = 0.7
33
+ RESULT_CACHE_SECONDS = 60
34
 
35
+ _last_search_ts = BoundedDict(500)
36
+ _inflight_tasks: Dict[str, asyncio.Task] = {}
37
+ _result_cache = BoundedDict(200)
38
  _search_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEARCHES)
39
+ _channel_semaphore = asyncio.Semaphore(MAX_CONCURRENT_CHANNELS)
40
  _userbot_session_dead = False
41
+ _chat_title_cache = BoundedDict(500)
 
 
42
 
43
  _TOKEN_RE = re.compile(r"[a-z0-9]+")
44
  _MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
45
+ _VIDEO_EXTS = (".mkv", ".mp4", ".avi", ".ts", ".m4v", ".mov", ".wmv", ".webm", ".flv")
46
+ SPLIT_SCAN_WINDOW = 20
47
+ _APOSTROPHE_RE = re.compile(r"['\u2018\u2019`\u00B4]")
48
+ _SYMBOL_STRIP_RE = re.compile(r"[&.\-:]+")
49
 
50
 
 
 
51
  def is_userbot_available() -> bool:
52
+ return botmod.Userbot is not None and not _userbot_session_dead
 
53
 
54
 
55
  def is_global_search_enabled() -> bool:
56
  if not is_userbot_available():
57
  return False
58
  s = SettingsManager.current()
59
+ return bool(s.global_search)
 
 
 
 
 
 
 
60
 
61
 
62
  def _tokens(s: str) -> set:
63
  return set(_TOKEN_RE.findall((s or "").lower()))
64
 
65
 
66
+ def _title_score(
67
+ result_title: str,
68
+ expected_title: str,
69
+ ) -> float:
70
  expected = _tokens(expected_title)
71
+ result = _tokens(result_title)
72
+
73
+ if not expected or not result:
74
  return 0.0
 
75
 
76
+ common = len(expected & result)
77
 
78
+ if common == 0:
79
+ return 0.0
80
+
81
+ precision = common / len(result)
82
+ recall = common / len(expected)
83
+
84
+ return (2 * precision * recall) / (precision + recall)
85
+
86
+ _ABS_EP_BOUNDARY_RE = re.compile(
87
+ r"(?i)(?:^|[^0-9])(?:e|ep|episode)?\s*0*(\d{1,4})(?=[^0-9]|$)"
88
+ )
89
 
 
 
 
 
 
 
 
 
90
 
91
+ def _filename_has_exact_episode(filename: str, episode: int) -> bool:
92
+ if not filename or episode is None:
93
+ return False
94
+ target = int(episode)
95
+ for m in _ABS_EP_BOUNDARY_RE.finditer(filename):
96
+ try:
97
+ if int(m.group(1)) == target:
98
+ return True
99
+ except (TypeError, ValueError):
100
+ continue
101
+ return False
102
+
103
+
104
+ def _matches_episode(parsed: dict, season: Optional[int], episode: Optional[int], filename: str = "") -> bool:
105
+ wants_episode = season is not None or episode is not None
106
+ is_episode_like = parsed.get("season") is not None or parsed.get("episode") is not None
107
+
108
+ if season is None and episode is not None:
109
+ rv = parsed.get("episode")
110
+ if rv is not None:
111
+ if isinstance(rv, list):
112
+ try:
113
+ if int(episode) in [int(x) for x in rv]:
114
+ return True
115
+ except (TypeError, ValueError):
116
+ pass
117
+ else:
118
+ try:
119
+ if int(rv) == int(episode):
120
+ return True
121
+ except (TypeError, ValueError):
122
+ pass
123
+ return _filename_has_exact_episode(filename, int(episode))
124
+
125
+ if wants_episode and not is_episode_like:
126
+ return False
127
+ if not wants_episode and is_episode_like:
128
+ return False
129
+
130
+ for value, parsed_key in ((season, "season"), (episode, "episode")):
131
+ if value is None:
132
+ continue
133
+ rv = parsed.get(parsed_key)
134
+ if rv is None:
135
+ continue
136
+ if isinstance(rv, list):
137
+ if value not in rv:
138
+ return False
139
+ elif int(rv) != int(value):
140
+ return False
141
  return True
142
 
143
 
144
+ def _is_combined_filename(filename: str, parsed: Optional[dict] = None) -> bool:
145
+ if not filename:
146
+ return False
147
+ if parse_combined_episodes(filename):
148
+ return True
149
+ if re.search(r"(?i)\bcombined\b", filename):
150
+ return True
151
+ if parsed and "excess" in parsed:
152
+ if any("combined" in str(item).lower() for item in (parsed.get("excess") or [])):
153
+ return True
154
+ return False
155
 
156
+
157
+ def _validate_name(filename: str, expected_title: str, season: Optional[int], episode: Optional[int]) -> Optional[dict]:
158
  try:
159
  parsed = PTN.parse(filename)
160
  except Exception:
161
  return None
162
+ if _is_combined_filename(filename, parsed):
163
+ LOGGER.info(f"Skipping {filename}: combined episode pack")
164
+ return None
165
+ if not _matches_episode(parsed, season, episode, filename=filename):
166
+ return None
167
+
168
+ result_title = parsed.get("title", "")
169
+
170
+ score = _title_score(result_title, expected_title)
171
+ if score < MIN_TITLE_SCORE:
172
+ stripped_expected = _strip_symbols(expected_title)
173
+ if stripped_expected and stripped_expected.lower() != expected_title.lower():
174
+ score = _title_score(result_title, stripped_expected)
175
 
176
+ if score < MIN_TITLE_SCORE:
 
 
177
  return None
178
+ return parsed
179
+
180
 
181
+ def _parse_and_validate(filename: str, expected_title: str, season: Optional[int], episode: Optional[int]) -> Optional[dict]:
182
+ if _MULTIPART_RE.search(filename):
183
  return None
184
+ return _validate_name(filename, expected_title, season, episode)
185
+
186
+
187
+ def _split_part_info(filename: str) -> Optional[tuple]:
188
+ if not filename:
189
  return None
190
+ zm = _ZIP_SPLIT_RE.match(filename)
191
+ if zm:
192
+ base_raw = zm.group("base")
193
+ base = _NORMALIZE_ALT_RE.sub(".", base_raw).strip(".").lower() + ".zip"
194
+ return base, int(zm.group("num")), base_raw, True
195
+ info = parse_split_info(filename)
196
+ if info:
197
+ return info[0], info[1], strip_part_suffix(filename), False
198
+ return None
199
+
200
+
201
+ _NORMALIZE_ALT_RE = re.compile(r"[\s._-]+")
202
+ _ZIP_SPLIT_RE = re.compile(r"^(?P<base>.+)\.zip\.(?P<num>\d{2,3})$", re.IGNORECASE)
203
 
204
 
205
  def _video_filename(message) -> Optional[str]:
 
207
  return (message.caption or "").strip() or getattr(message.video, "file_name", None) or "video.mkv"
208
  if message.document:
209
  mime = message.document.mime_type or ""
210
+ name = message.document.file_name
211
+ # Include single .zip archives (STORED inner video is streamable)
212
+ if mime.startswith("video/") or (name and (name.lower().endswith(_VIDEO_EXTS) or name.lower().endswith(".zip"))):
213
+ return (message.caption or "").strip() or name or "video.mkv"
 
 
214
  return None
215
 
216
 
217
+ def _raw_media_name(message) -> Optional[str]:
218
+ media = message.video or message.document
219
+ if not media:
220
+ return None
221
+ return (message.caption or "").strip() or getattr(media, "file_name", None)
222
+
223
+
224
+ async def _gather_split_parts(client, chat_id: int, seed_id: int, base: str) -> Dict[int, dict]:
225
+ ids = list(range(max(1, seed_id - SPLIT_SCAN_WINDOW), seed_id + SPLIT_SCAN_WINDOW + 1))
226
+ parts: Dict[int, dict] = {}
227
+ t0 = time.monotonic()
228
+ try:
229
+ messages = await client.get_messages(chat_id, ids)
230
+ except Exception as e:
231
+ LOGGER.warning(f"[GLOBAL SEARCH] Could not gather split parts near {seed_id}: {e}")
232
+ return parts
233
+ finally:
234
+ elapsed = time.monotonic() - t0
235
+ LOGGER.info(f"[GLOBAL SEARCH] get_messages({len(ids)} ids, base={base}) took {elapsed:.1f}s")
236
+ for msg in (messages or []):
237
+ if not msg or getattr(msg, "empty", False):
238
+ continue
239
+ raw = _raw_media_name(msg)
240
+ if not raw:
241
+ continue
242
+ info = _split_part_info(raw)
243
+ if not info or info[0] != base:
244
+ continue
245
+ media = msg.video or msg.document
246
+ parts[info[1]] = {"msg_id": msg.id, "size_bytes": getattr(media, "file_size", 0) or 0}
247
+ return parts
248
+
249
+
250
  def _resolve_channel_ids(channel_ids: List[str]) -> List[int]:
251
+ resolved: List[int] = []
252
  seen: set = set()
253
  for c in channel_ids:
254
  c = str(c).strip()
 
271
  try:
272
  chat = await client.get_chat(chat_id)
273
  title = chat.title or str(chat_id)
274
+ except Exception as e:
275
+ LOGGER.warning(f"[USERBOT] Could not fetch chat title for {chat_id}: {e}")
276
  title = str(chat_id)
277
  _chat_title_cache[chat_id] = title
278
  return title
279
 
280
 
281
+ def _strip_symbols(text: str) -> str:
282
+ if not text:
283
+ return ""
284
+ text = _APOSTROPHE_RE.sub("", text)
285
+ text = _SYMBOL_STRIP_RE.sub(" ", text)
286
+ return re.sub(r"\s+", " ", text).strip()
287
+
288
+
289
+ def _absolute_ep_forms(episode: int) -> List[str]:
290
+ ep = int(episode)
291
+ if ep < 1:
292
+ return [str(ep)]
293
+ if ep < 10:
294
+ return [f"{ep:03d}", f"{ep:02d}", str(ep)]
295
+ if ep < 100:
296
+ return [f"{ep:03d}", str(ep)]
297
+ return [str(ep)]
298
+
299
+
300
+ def _build_search_query(expected_title: str, year: Optional[int], season: Optional[int], episode: Optional[int]) -> str:
301
+ if season is not None and episode is not None:
302
+ return f"{expected_title} S{int(season):02d}E{int(episode):02d}"
303
+ if season is None and episode is not None:
304
+ forms = _absolute_ep_forms(int(episode))
305
+ return f"{expected_title} {forms[0]}"
306
+ if year is not None:
307
+ return f"{expected_title} {year}"
308
+ return expected_title
309
+
310
+
311
+ def _build_query_candidates(
312
+ expected_title: str, year: Optional[int], season: Optional[int], episode: Optional[int]
313
+ ) -> List[str]:
314
+ candidates: List[str] = []
315
+
316
+ def add(q: Optional[str]) -> None:
317
+ q = (q or "").strip()
318
+ if q and q.lower() not in (c.lower() for c in candidates):
319
+ candidates.append(q)
320
+
321
+ if season is None and episode is not None:
322
+ titles = [expected_title]
323
+ stripped_title = _strip_symbols(expected_title)
324
+ if stripped_title and stripped_title.lower() != expected_title.lower():
325
+ titles.append(stripped_title)
326
+ for form in _absolute_ep_forms(int(episode)):
327
+ for title in titles:
328
+ add(f"{title} {form}")
329
+ add(f"{title} E{form}")
330
+ return candidates
331
+
332
+ add(_build_search_query(expected_title, year, season, episode))
333
+
334
+ if season is None and episode is None and year is not None:
335
+ add(expected_title)
336
+
337
+ stripped_title = _strip_symbols(expected_title)
338
+ if stripped_title and stripped_title.lower() != expected_title.lower():
339
+ add(_build_search_query(stripped_title, year, season, episode))
340
+ if season is None and episode is None and year is not None:
341
+ add(stripped_title)
342
+
343
+ return candidates
344
+
345
+
346
  async def _search_channel(
347
  client,
348
  chat_id: int,
 
352
  season: Optional[int],
353
  episode: Optional[int],
354
  ) -> List[Dict]:
355
+ global _userbot_session_dead
356
+
357
+ async with _channel_semaphore:
358
+ results: List[Dict] = []
359
+ split_groups: Dict[str, dict] = {}
360
+ seen_msg_ids: set = set()
361
+
362
+ for msg_filter in (enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT):
363
+ if len(results) >= MAX_RESULTS_PER_CHAT:
364
+ break
365
+ try:
366
+ async for message in client.search_messages(
367
+ chat_id=chat_id,
368
+ query=search_query,
369
+ filter=msg_filter,
370
+ limit=MAX_RESULTS_PER_CHAT,
371
+ ):
372
+ if message.id in seen_msg_ids:
373
+ continue
374
+ seen_msg_ids.add(message.id)
375
+
376
+ raw_name = _raw_media_name(message)
377
+ if not raw_name:
378
+ continue
379
+
380
+ split = _split_part_info(raw_name)
381
+ if split:
382
+ base, _part_num, display, is_zip = split
383
+ if base in split_groups:
384
+ continue
385
+ parsed = _validate_name(display, expected_title, season, episode)
386
+ if parsed is None:
387
+ continue
388
+ parts = await _gather_split_parts(client, chat_id, message.id, base)
389
+ if len(parts) < 2 or sorted(parts) != list(range(1, len(parts) + 1)):
390
+ continue
391
+ split_groups[base] = {
392
+ "parts": parts,
393
+ "display": display,
394
+ "quality": parsed.get("resolution") or "HD",
395
+ "zip": is_zip,
396
+ }
397
+ continue
398
+
399
+ filename = _video_filename(message)
400
+ if not filename:
401
+ continue
402
+ parsed = _parse_and_validate(filename, expected_title, season, episode)
403
+ if parsed is None:
404
+ continue
405
+
406
+ media = message.video or message.document
407
+ size = get_readable_file_size(getattr(media, "file_size", 0) or 0)
408
+ quality = parsed.get("resolution") or "HD"
409
+
410
+ is_single_zip = bool(filename and filename.lower().endswith(".zip"))
411
+ payload = {
412
+ "global": True,
413
+ "chat_id": chat_id,
414
+ "msg_id": message.id,
415
+ "title": filename,
416
+ "size": size,
417
+ "quality": quality,
418
+ "source": chat_title,
419
+ }
420
+ if is_single_zip:
421
+ # Represent as a one-part zip so stream routes use the zip path
422
+ payload["zip"] = True
423
+ payload["parts"] = [{"chat_id": chat_id, "msg_id": message.id}]
424
+ del payload["chat_id"]
425
+ del payload["msg_id"]
426
+ token = await encode_string(payload)
427
+
428
+ results.append({
429
+ "token": token,
430
+ "title": filename,
431
+ "size": size,
432
+ "source_chat": chat_title,
433
+ "quality": quality,
434
+ "is_zip": is_single_zip,
435
+ })
436
+ LOGGER.debug(f"[GLOBAL SEARCH] Result found: {filename} in {chat_title}")
437
+
438
+ if len(results) >= MAX_RESULTS_PER_CHAT:
439
+ break
440
+
441
+ except FloodWait as e:
442
+ LOGGER.warning(f"[USERBOT] FloodWait for {chat_title}: sleeping {e.value}s")
443
+ await asyncio.sleep(e.value)
444
+ except (ChatAdminRequired, ChannelPrivate, PeerIdInvalid, UserNotParticipant, RPCError) as e:
445
+ LOGGER.warning(f"[USERBOT] Cannot access channel {chat_title} ({chat_id}): {e}")
446
+ break
447
+ except (AuthKeyUnregistered, SessionRevoked) as e:
448
+ LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
449
+ _userbot_session_dead = True
450
+ break
451
+ except Exception as e:
452
+ LOGGER.warning(f"[USERBOT] Unexpected error searching {chat_title} ({chat_id}): {e}")
453
+ break
454
+
455
+ for group in split_groups.values():
456
+ ordered = [group["parts"][pn] for pn in sorted(group["parts"])]
457
+ total_bytes = sum(p["size_bytes"] for p in ordered)
458
+ size = get_readable_file_size(total_bytes)
459
+ is_zip = bool(group.get("zip"))
460
+ payload = {
461
+ "global": True,
462
+ "parts": [{"chat_id": chat_id, "msg_id": p["msg_id"]} for p in ordered],
463
+ "title": group["display"],
464
+ "size": size,
465
+ "quality": group["quality"],
466
+ "source": chat_title,
467
+ }
468
+ if is_zip:
469
+ payload["zip"] = True
470
+ token = await encode_string(payload)
471
+ results.append({
472
+ "token": token,
473
+ "title": group["display"],
474
+ "size": size,
475
+ "source_chat": chat_title,
476
+ "quality": group["quality"],
477
+ "is_split": True,
478
+ "is_zip": is_zip,
479
+ "part_count": len(ordered),
480
+ })
481
+ kind = "zip parts" if is_zip else "parts"
482
+ LOGGER.info(f"[GLOBAL SEARCH] Split stream: {group['display']} ({len(ordered)} {kind}) in {chat_title}")
483
+
484
+ return results
485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
 
487
  async def global_search(
488
  expected_title: str,
 
496
  if not expected_title or not is_global_search_enabled():
497
  return []
498
 
 
 
499
  settings = SettingsManager.current()
500
  target_ids = _resolve_channel_ids(settings.global_search_channels)
 
 
501
 
502
+ query_candidates = _build_query_candidates(expected_title, year, season, episode)
503
+ if not query_candidates:
504
+ return []
 
 
 
505
 
506
+ key = query_candidates[0].lower()
507
  now = time.time()
508
+
509
+ existing_task = _inflight_tasks.get(key)
510
+ if existing_task and not existing_task.done():
511
+ LOGGER.info(f"[GLOBAL SEARCH] Joining in-flight search for '{query_candidates[0]}'")
512
+ try:
513
+ return await existing_task
514
+ except Exception:
515
+ return []
516
+
517
+ cached = _result_cache.get(key)
518
+ if cached is not None and (now - cached[0]) < RESULT_CACHE_SECONDS:
519
+ LOGGER.info(f"[GLOBAL SEARCH] Serving cached results for '{query_candidates[0]}'")
520
+ return cached[1]
521
+
522
  if now - _last_search_ts.get(key, 0) < SEARCH_COOLDOWN_SECONDS:
523
+ if cached is not None:
524
+ LOGGER.info(f"[GLOBAL SEARCH] Serving cached results for '{query_candidates[0]}' (cooldown)")
525
+ return cached[1]
526
+ LOGGER.info(f"[GLOBAL SEARCH] Cooldown active for '{query_candidates[0]}'")
527
  return []
528
 
 
529
  _last_search_ts[key] = now
530
+ if target_ids:
531
+ task = asyncio.create_task(
532
+ _run_global_search(expected_title, query_candidates, target_ids, season, episode)
533
+ )
534
+ else:
535
+ task = asyncio.create_task(
536
+ _run_true_global_search(expected_title, query_candidates, season, episode)
537
+ )
538
+ _inflight_tasks[key] = task
539
  try:
540
+ results = await task
541
+ _result_cache[key] = (time.time(), results)
542
+ return results
543
+ finally:
544
+ _inflight_tasks.pop(key, None)
545
+
546
+
547
+ async def _run_global_search(
548
+ expected_title: str,
549
+ query_candidates: List[str],
550
+ target_ids: List[int],
551
+ season: Optional[int],
552
+ episode: Optional[int],
553
+ ) -> List[Dict]:
554
+ async with _search_semaphore:
555
+ chat_titles = await asyncio.gather(
556
+ *(_get_chat_title(botmod.Userbot, cid) for cid in target_ids),
557
+ return_exceptions=True,
558
+ )
559
+ resolved_titles = [
560
+ str(cid) if isinstance(t, Exception) else t
561
+ for cid, t in zip(target_ids, chat_titles)
562
+ ]
563
+
564
+ all_results: List[Dict] = []
565
+ for attempt_idx, search_query in enumerate(query_candidates):
566
+ if _userbot_session_dead:
567
+ break
568
+
569
  LOGGER.info(
570
+ f"[USERBOT] Search attempt {attempt_idx + 1}/{len(query_candidates)}: "
571
+ f"'{search_query}' across {len(target_ids)} channel(s)"
572
  )
 
 
 
 
 
 
 
 
 
 
 
 
573
 
574
+ search_tasks = [
575
+ _search_channel(botmod.Userbot, int(cid), title, search_query, expected_title, season, episode)
576
+ for cid, title in zip(target_ids, resolved_titles)
577
+ ]
578
  per_channel_results = await asyncio.gather(*search_tasks, return_exceptions=True)
579
 
 
580
  for r in per_channel_results:
581
  if isinstance(r, list):
582
  all_results.extend(r)
583
 
584
+ if all_results:
585
+ LOGGER.info(
586
+ f"[USERBOT] Succeeded on attempt {attempt_idx + 1} "
587
+ f"('{search_query}') -> {len(all_results)} result(s)"
588
+ )
589
+ break
590
+ if attempt_idx + 1 < len(query_candidates):
591
+ LOGGER.info(f"[USERBOT] No results for '{search_query}', trying next fallback")
592
+
593
+ all_results = all_results[:MAX_RESULTS]
594
+ LOGGER.info(f"[USERBOT] Search completed: '{expected_title}' -> {len(all_results)} result(s)")
595
+ return all_results
596
+
597
+
598
+ async def _run_true_global_search(
599
+ expected_title: str,
600
+ query_candidates: List[str],
601
+ season: Optional[int],
602
+ episode: Optional[int],
603
+ ) -> List[Dict]:
604
+ global _userbot_session_dead
605
+ async with _search_semaphore:
606
+ all_results: List[Dict] = []
607
+ split_groups: Dict[str, dict] = {}
608
+ seen_msg_ids: set = set()
609
+
610
+ for attempt_idx, search_query in enumerate(query_candidates):
611
+ if _userbot_session_dead:
612
+ break
613
 
614
  LOGGER.info(
615
+ f"[USERBOT] True global search attempt {attempt_idx + 1}/{len(query_candidates)}: '{search_query}'"
 
616
  )
617
+
618
+ for msg_filter in (enums.MessagesFilter.VIDEO, enums.MessagesFilter.DOCUMENT):
619
+ if len(all_results) + len(split_groups) >= MAX_RESULTS:
620
+ break
621
+ try:
622
+ async for message in botmod.Userbot.search_global(
623
+ query=search_query,
624
+ filter=msg_filter,
625
+ channels_only=True,
626
+ limit=MAX_RESULTS,
627
+ ):
628
+ if not message or not message.chat:
629
+ continue
630
+ chat = message.chat
631
+ if chat.type != enums.ChatType.CHANNEL:
632
+ continue
633
+ chat_id = chat.id
634
+ chat_title = chat.title or str(chat_id)
635
+ _chat_title_cache[chat_id] = chat_title
636
+
637
+ msg_key = (chat_id, message.id)
638
+ if msg_key in seen_msg_ids:
639
+ continue
640
+ seen_msg_ids.add(msg_key)
641
+
642
+ raw_name = _raw_media_name(message)
643
+ if not raw_name:
644
+ continue
645
+
646
+ split = _split_part_info(raw_name)
647
+ if split:
648
+ base, _part_num, display, is_zip = split
649
+ group_key = f"{chat_id}:{base}"
650
+ if group_key in split_groups:
651
+ continue
652
+ parsed = _validate_name(display, expected_title, season, episode)
653
+ if parsed is None:
654
+ continue
655
+ parts = await _gather_split_parts(botmod.Userbot, chat_id, message.id, base)
656
+ if len(parts) < 2 or sorted(parts) != list(range(1, len(parts) + 1)):
657
+ continue
658
+ split_groups[group_key] = {
659
+ "chat_id": chat_id,
660
+ "chat_title": chat_title,
661
+ "parts": parts,
662
+ "display": display,
663
+ "quality": parsed.get("resolution") or "HD",
664
+ "zip": is_zip,
665
+ }
666
+ continue
667
+
668
+ filename = _video_filename(message)
669
+ if not filename:
670
+ continue
671
+ parsed = _parse_and_validate(filename, expected_title, season, episode)
672
+ if parsed is None:
673
+ continue
674
+
675
+ media = message.video or message.document
676
+ size = get_readable_file_size(getattr(media, "file_size", 0) or 0)
677
+ quality = parsed.get("resolution") or "HD"
678
+
679
+ is_single_zip = bool(filename and filename.lower().endswith(".zip"))
680
+ payload = {
681
+ "global": True,
682
+ "chat_id": chat_id,
683
+ "msg_id": message.id,
684
+ "title": filename,
685
+ "size": size,
686
+ "quality": quality,
687
+ "source": chat_title,
688
+ }
689
+ if is_single_zip:
690
+ payload["zip"] = True
691
+ payload["parts"] = [{"chat_id": chat_id, "msg_id": message.id}]
692
+ del payload["chat_id"]
693
+ del payload["msg_id"]
694
+ token = await encode_string(payload)
695
+
696
+ all_results.append({
697
+ "token": token,
698
+ "title": filename,
699
+ "size": size,
700
+ "source_chat": chat_title,
701
+ "quality": quality,
702
+ "is_zip": is_single_zip,
703
+ })
704
+ LOGGER.debug(f"[GLOBAL SEARCH] True global result: {filename} in {chat_title}")
705
+
706
+ if len(all_results) >= MAX_RESULTS:
707
+ break
708
+
709
+ except FloodWait as e:
710
+ LOGGER.warning(f"[USERBOT] FloodWait on true global: sleeping {e.value}s")
711
+ await asyncio.sleep(e.value)
712
+ except (AuthKeyUnregistered, SessionRevoked) as e:
713
+ LOGGER.error(f"[USERBOT] Session invalid ({type(e).__name__}): {e}")
714
+ _userbot_session_dead = True
715
+ break
716
+ except Exception as e:
717
+ LOGGER.warning(f"[USERBOT] True global search error: {e}")
718
+ break
719
+
720
+ if all_results or split_groups:
721
+ LOGGER.info(
722
+ f"[USERBOT] True global succeeded on attempt {attempt_idx + 1} "
723
+ f"('{search_query}') -> {len(all_results)} + {len(split_groups)} split group(s)"
724
+ )
725
+ break
726
+ if attempt_idx + 1 < len(query_candidates):
727
+ LOGGER.info(f"[USERBOT] No results for '{search_query}', trying next fallback")
728
+
729
+ for group in split_groups.values():
730
+ chat_id = group["chat_id"]
731
+ chat_title = group["chat_title"]
732
+ ordered = [group["parts"][pn] for pn in sorted(group["parts"])]
733
+ total_bytes = sum(p["size_bytes"] for p in ordered)
734
+ size = get_readable_file_size(total_bytes)
735
+ is_zip = bool(group.get("zip"))
736
+ payload = {
737
+ "global": True,
738
+ "parts": [{"chat_id": chat_id, "msg_id": p["msg_id"]} for p in ordered],
739
+ "title": group["display"],
740
+ "size": size,
741
+ "quality": group["quality"],
742
+ "source": chat_title,
743
+ }
744
+ if is_zip:
745
+ payload["zip"] = True
746
+ token = await encode_string(payload)
747
+ all_results.append({
748
+ "token": token,
749
+ "title": group["display"],
750
+ "size": size,
751
+ "source_chat": chat_title,
752
+ "quality": group["quality"],
753
+ "is_split": True,
754
+ "is_zip": is_zip,
755
+ "part_count": len(ordered),
756
+ })
757
+ kind = "zip parts" if is_zip else "parts"
758
+ LOGGER.info(f"[GLOBAL SEARCH] Split stream: {group['display']} ({len(ordered)} {kind}) in {chat_title}")
759
+
760
+ all_results = all_results[:MAX_RESULTS]
761
+ LOGGER.info(f"[USERBOT] True global search completed: '{expected_title}' -> {len(all_results)} result(s)")
762
+ return all_results
Backend/helper/health.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import time
3
+ from datetime import datetime
4
+
5
+ import httpx
6
+
7
+ from Backend import db
8
+ from Backend.helper.metadata import get_tmdb_client, tmdb_api_key
9
+ from Backend.helper.settings_manager import SettingsManager
10
+ from Backend.pyrofork.bot import (
11
+ StreamBot,
12
+ client_dc_map,
13
+ client_failures,
14
+ multi_clients,
15
+ work_loads,
16
+ )
17
+
18
+ #----- Rough Atlas free-tier (M0) storage ceiling, used only as a usage guide
19
+ _FREE_TIER_BYTES = 512 * 1024 * 1024
20
+
21
+ #----- Cache TTLs (seconds) so the panel can poll often without hammering DB/TMDB.
22
+ #----- Bot clients are always computed fresh (in-memory) for realtime load.
23
+ _TTL = {"databases": 30, "tmdb": 300, "base_url": 60}
24
+ _cache: dict = {}
25
+
26
+
27
+ async def _cached(key: str, producer, force: bool = False):
28
+ now = time.monotonic()
29
+ entry = _cache.get(key)
30
+ if not force and entry and (now - entry[0]) < _TTL[key]:
31
+ return entry[1]
32
+ result = await producer()
33
+ _cache[key] = (now, result)
34
+ return result
35
+
36
+
37
+ async def _check_databases() -> dict:
38
+ items = []
39
+ for key, mdb in db.dbs.items():
40
+ entry = {"name": key, "status": "down", "size_mb": 0, "usage_pct": 0, "message": ""}
41
+ try:
42
+ await asyncio.wait_for(mdb.command("ping"), timeout=6)
43
+ entry["status"] = "ok"
44
+ try:
45
+ stats = await asyncio.wait_for(mdb.command("dbstats"), timeout=6)
46
+ size = stats.get("storageSize", 0) or 0
47
+ entry["size_mb"] = round(size / (1024 * 1024), 1)
48
+ entry["usage_pct"] = min(100, round(size / _FREE_TIER_BYTES * 100, 1))
49
+ except Exception:
50
+ pass
51
+ except Exception as e:
52
+ entry["message"] = str(e)[:140]
53
+ items.append(entry)
54
+
55
+ up = sum(1 for i in items if i["status"] == "ok")
56
+ status = "ok" if items and up == len(items) else ("degraded" if up else "down")
57
+ return {"key": "databases", "label": "Databases", "status": status, "up": up, "total": len(items), "items": items}
58
+
59
+
60
+ def _check_bots() -> dict:
61
+ clients = []
62
+ for idx in sorted(multi_clients.keys()):
63
+ client = multi_clients[idx]
64
+ clients.append({
65
+ "name": "Userbot" if idx < 0 else f"Bot {idx + 1}",
66
+ "connected": bool(getattr(client, "is_connected", False)),
67
+ "dc": client_dc_map.get(idx),
68
+ "workload": work_loads.get(idx, 0),
69
+ "failures": client_failures.get(idx, 0),
70
+ })
71
+ up = sum(1 for c in clients if c["connected"])
72
+ status = "ok" if clients and up == len(clients) else ("degraded" if up else "down")
73
+ return {
74
+ "key": "bots", "label": "Telegram Clients", "status": status,
75
+ "up": up, "total": len(clients), "items": clients,
76
+ "primary_connected": bool(getattr(StreamBot, "is_connected", False)),
77
+ }
78
+
79
+
80
+ async def _check_tmdb() -> dict:
81
+ if not tmdb_api_key():
82
+ return {"key": "tmdb", "label": "TMDB API", "status": "not_configured",
83
+ "message": "No TMDB API key set — metadata matching will be limited."}
84
+ try:
85
+ movie = await asyncio.wait_for(get_tmdb_client().movie(550).details(), timeout=10)
86
+ if getattr(movie, "title", None):
87
+ return {"key": "tmdb", "label": "TMDB API", "status": "ok", "message": "API key is valid."}
88
+ return {"key": "tmdb", "label": "TMDB API", "status": "error", "message": "Unexpected TMDB response."}
89
+ except Exception as e:
90
+ return {"key": "tmdb", "label": "TMDB API", "status": "error", "message": str(e)[:140]}
91
+
92
+
93
+ async def _check_base_url() -> dict:
94
+ base = SettingsManager.current().base_url
95
+ if not base:
96
+ return {"key": "base_url", "label": "Base URL", "status": "not_configured",
97
+ "message": "Base URL not set — Stremio can't reach your streams."}
98
+ try:
99
+ async with httpx.AsyncClient(timeout=8.0, follow_redirects=True) as client:
100
+ resp = await client.get(base)
101
+ return {"key": "base_url", "label": "Base URL", "status": "ok",
102
+ "message": f"Reachable (HTTP {resp.status_code}).", "url": base}
103
+ except Exception as e:
104
+ return {"key": "base_url", "label": "Base URL", "status": "error", "message": str(e)[:140], "url": base}
105
+
106
+
107
+ async def run_health_checks(force: bool = False) -> dict:
108
+ databases = await _cached("databases", _check_databases, force)
109
+ bots = _check_bots()
110
+ tmdb = await _cached("tmdb", _check_tmdb, force)
111
+ base_url = await _cached("base_url", _check_base_url, force)
112
+
113
+ statuses = [databases["status"], bots["status"], tmdb["status"], base_url["status"]]
114
+ if "down" in (databases["status"], bots["status"]):
115
+ overall = "critical"
116
+ elif any(s in ("down", "degraded", "error", "not_configured") for s in statuses):
117
+ overall = "warning"
118
+ else:
119
+ overall = "ok"
120
+
121
+ return {
122
+ "generated_at": datetime.utcnow().isoformat(),
123
+ "overall": overall,
124
+ "sections": [databases, bots, tmdb, base_url],
125
+ }
Backend/helper/imdb.py DELETED
@@ -1,128 +0,0 @@
1
- import asyncio
2
- import re
3
- from typing import Optional, Dict, Any, List
4
-
5
- import httpx
6
-
7
- BASE_URL = "https://v3-cinemeta.strem.io"
8
-
9
- _client: Optional[httpx.AsyncClient] = None
10
- _client_lock = asyncio.Lock()
11
-
12
- _EMOJI_RE = re.compile(
13
- "["
14
- "\U0001F600-\U0001F64F"
15
- "\U0001F300-\U0001F5FF"
16
- "\U0001F680-\U0001F6FF"
17
- "\U0001F700-\U0001FAFF"
18
- "\U00002702-\U000027B0"
19
- "\U000024C2-\U0001F251"
20
- "\u2600-\u26FF"
21
- "\u2700-\u27BF"
22
- "\uFE00-\uFE0F"
23
- "\U0001F1E0-\U0001F1FF"
24
- "]+",
25
- re.UNICODE,
26
- )
27
-
28
- async def _get_client() -> httpx.AsyncClient:
29
- global _client
30
- async with _client_lock:
31
- if _client is None or _client.is_closed:
32
- _client = httpx.AsyncClient(timeout=15.0, follow_redirects=True)
33
- return _client
34
-
35
- def _cinemeta_type(media_type: str) -> str:
36
- return "series" if media_type in ("tvSeries", "tv", "series") else "movie"
37
-
38
- async def _fetch_json(url: str) -> Optional[Dict[str, Any]]:
39
- try:
40
- client = await _get_client()
41
- resp = await client.get(url)
42
- if resp.status_code != 200:
43
- return None
44
- return resp.json()
45
- except Exception:
46
- return None
47
-
48
- def _clean_search_query(query: str) -> str:
49
- q = _EMOJI_RE.sub(" ", query)
50
- q = re.sub(r"[^\w\s\-\'&:.]", " ", q)
51
- return re.sub(r"\s+", " ", q).strip()
52
-
53
- def extract_first_year(year_string) -> int:
54
- if not year_string:
55
- return 0
56
- m = re.search(r"(\d{4})", str(year_string))
57
- return int(m.group(1)) if m else 0
58
-
59
- async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
60
- results = await search_title_multi(query=query, type=type, limit=1)
61
- return results[0] if results else None
62
-
63
- async def search_title_multi(query: str, type: str, limit: int = 8) -> List[Dict[str, Any]]:
64
- cleaned = _clean_search_query(query)
65
- normalized = ".".join(cleaned.strip().lower().split())
66
- url = f"{BASE_URL}/catalog/{_cinemeta_type(type)}/imdb/search={normalized}.json"
67
-
68
- data = await _fetch_json(url)
69
- metas = (data or {}).get("metas") or []
70
- results: List[Dict[str, Any]] = []
71
- for meta in metas[:limit]:
72
- imdb_id = meta.get("imdb_id") or meta.get("id", "")
73
- if not imdb_id:
74
- continue
75
- results.append({
76
- "id": imdb_id,
77
- "type": type,
78
- "title": meta.get("name", ""),
79
- "year": meta.get("releaseInfo", ""),
80
- "poster": meta.get("poster", ""),
81
- })
82
- return results
83
-
84
- async def get_detail(imdb_id: str, media_type: str) -> Optional[Dict[str, Any]]:
85
- data = await _fetch_json(f"{BASE_URL}/meta/{_cinemeta_type(media_type)}/{imdb_id}.json")
86
- meta = (data or {}).get("meta")
87
- if not meta or not meta.get("name"):
88
- return None
89
-
90
- year_value = 0
91
- for field in ("year", "releaseInfo", "released"):
92
- if meta.get(field):
93
- year_value = extract_first_year(meta[field])
94
- if year_value:
95
- break
96
-
97
- return {
98
- "id": meta.get("imdb_id") or meta.get("id"),
99
- "moviedb_id": meta.get("moviedb_id"),
100
- "type": meta.get("type") or media_type,
101
- "title": meta.get("name") or "",
102
- "plot": meta.get("description") or "",
103
- "genre": meta.get("genres") or meta.get("genre") or [],
104
- "releaseDetailed": {"year": year_value},
105
- "rating": {"star": float(meta.get("imdbRating") or 0)},
106
- "poster": meta.get("poster") or "",
107
- "background": meta.get("background") or "",
108
- "logo": meta.get("logo") or "",
109
- "runtime": meta.get("runtime") or 0,
110
- "director": meta.get("director") or [],
111
- "cast": meta.get("cast") or [],
112
- "videos": meta.get("videos") or [],
113
- }
114
-
115
- async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
116
- data = await _fetch_json(f"{BASE_URL}/meta/series/{imdb_id}.json")
117
- videos = (data or {}).get("meta", {}).get("videos") or []
118
- for video in videos:
119
- if str(video.get("season", "")) == str(season_id) and str(video.get("episode", "")) == str(episode_id):
120
- return {
121
- "title": video.get("title", f"Episode {episode_id}"),
122
- "no": str(episode_id),
123
- "season": str(season_id),
124
- "image": video.get("thumbnail", ""),
125
- "plot": video.get("overview", ""),
126
- "released": video.get("released", ""),
127
- }
128
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/helper/link_checker.py CHANGED
@@ -1,8 +1,16 @@
1
  import asyncio
2
- from datetime import datetime
3
- from Backend.logger import LOGGER
 
4
  from Backend.helper.encrypt import decode_string
 
 
 
5
 
 
 
 
 
6
  class DeadLinkChecker:
7
  def __init__(self, db, app, check_interval_hours: int = 24):
8
  self.db = db
@@ -18,9 +26,8 @@ class DeadLinkChecker:
18
  asyncio.create_task(self._run_loop())
19
 
20
  async def _run_loop(self):
21
- # Wait a minute before starting the first scan so the bots can boot up
22
- await asyncio.sleep(60)
23
-
24
  while self.is_running:
25
  try:
26
  LOGGER.info("Starting Dead Link Checker scan...")
@@ -28,102 +35,114 @@ class DeadLinkChecker:
28
  LOGGER.info("Dead Link Checker scan complete.")
29
  except Exception as e:
30
  LOGGER.error(f"Error in Dead Link Checker loop: {e}")
31
-
32
- # Sleep until the next interval
33
  await asyncio.sleep(self.check_interval_seconds)
34
 
35
  async def _scan_all_media(self):
36
- # We need at least one bot client to check messages
37
- from Backend.pyrofork.bot import multi_clients
38
  if not multi_clients:
39
  LOGGER.warning("No bot clients available for Dead Link Checker.")
40
  return
41
 
42
- # Use the primary client to fetch messages
43
- client = multi_clients.get(0) or next(iter(multi_clients.values()))
44
 
45
- # Iterate through all active storage DBs
46
  for i in range(1, self.db.current_db_index + 1):
47
- db_key = f"storage_{i}"
48
- active_db = self.db.dbs[db_key]
49
 
50
- # 1. Scan Movies
51
  try:
52
- # Find movies that have telegram links and are NOT already marked dead
53
- movie_cursor = active_db["movie"].find({
54
- "telegram": {"$exists": True, "$not": {"$size": 0}},
55
- "telegram.is_dead": {"$ne": True}
56
- })
57
- async for movie in movie_cursor:
 
 
58
  tmdb_id = movie.get("tmdb_id")
59
  for quality in movie.get("telegram", []):
60
- if not quality.get("is_dead"):
61
- is_alive = await self._check_file_alive(client, quality.get("id"))
62
- if not is_alive:
63
- LOGGER.warning(f"Found dead link for Movie {tmdb_id} (Quality: {quality.get('quality')})")
64
- await self.db.flag_dead_link("movie", tmdb_id, i, quality.get("id"))
65
- # Add a tiny sleep to avoid flooding Telegram API during scan
66
- await asyncio.sleep(0.5)
67
  except Exception as e:
68
  LOGGER.error(f"Error scanning movies in DB {i}: {e}")
69
 
70
- # 2. Scan TV Shows
71
  try:
72
- tv_cursor = active_db["tv"].find({
73
- "seasons.episodes.telegram": {"$exists": True, "$not": {"$size": 0}},
74
- "seasons.episodes.telegram.is_dead": {"$ne": True}
75
- })
76
- async for tv in tv_cursor:
 
 
 
77
  tmdb_id = tv.get("tmdb_id")
78
  for season in tv.get("seasons", []):
79
  for ep in season.get("episodes", []):
80
  for quality in ep.get("telegram", []):
81
- if not quality.get("is_dead"):
82
- is_alive = await self._check_file_alive(client, quality.get("id"))
83
- if not is_alive:
84
- LOGGER.warning(f"Found dead link for TV {tmdb_id} S{season.get('season_number')}E{ep.get('episode_number')} (Quality: {quality.get('quality')})")
85
- await self.db.flag_dead_link("tv", tmdb_id, i, quality.get("id"))
86
- await asyncio.sleep(0.5)
 
87
  except Exception as e:
88
  LOGGER.error(f"Error scanning TV shows in DB {i}: {e}")
89
 
90
- async def _check_file_alive(self, client, quality_id: str) -> bool:
91
  try:
92
  decoded = await decode_string(quality_id)
93
- if not decoded:
94
- return False
95
-
96
- # Split file: payload has a "parts" list of {chat_id, msg_id}
97
- if "parts" in decoded:
98
- parts = decoded.get("parts") or []
99
- if not parts:
100
- return False
101
- for part in parts:
102
- if not await self._check_single_message(
103
- client, part.get("chat_id"), part.get("msg_id")
104
- ):
105
- return False # any missing part => dead
106
- return True
107
-
108
- # Single file
109
- if "chat_id" not in decoded or "msg_id" not in decoded:
110
- return False
111
- return await self._check_single_message(
112
- client, decoded["chat_id"], decoded["msg_id"]
113
- )
114
  except Exception as e:
115
- LOGGER.error(f"Link checker failed to resolve {quality_id}: {e}")
116
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- async def _check_single_message(self, client, chat_id, msg_id) -> bool:
 
 
 
 
 
119
  if chat_id is None or msg_id is None:
120
- return False
 
121
  chat_id = int(f"-100{chat_id}")
122
  msg_id = int(msg_id)
123
- messages = await client.get_messages(chat_id, message_ids=[msg_id])
124
- if not messages:
125
- return False
126
- msg = messages[0]
127
- if msg.empty or (msg.document is None and msg.video is None and msg.audio is None):
128
- return False
129
- return True
 
 
 
 
 
 
 
 
 
 
 
 
1
  import asyncio
2
+
3
+ from pyrogram.errors import FloodWait
4
+
5
  from Backend.helper.encrypt import decode_string
6
+ from Backend.helper.pyro import is_media
7
+ from Backend.logger import LOGGER
8
+ from Backend.pyrofork.bot import multi_clients
9
 
10
+ ALIVE, DEAD, UNKNOWN = "alive", "dead", "unknown"
11
+
12
+
13
+ #----- Background task that periodically flags dead Telegram links
14
  class DeadLinkChecker:
15
  def __init__(self, db, app, check_interval_hours: int = 24):
16
  self.db = db
 
26
  asyncio.create_task(self._run_loop())
27
 
28
  async def _run_loop(self):
29
+ await asyncio.sleep(120)
30
+
 
31
  while self.is_running:
32
  try:
33
  LOGGER.info("Starting Dead Link Checker scan...")
 
35
  LOGGER.info("Dead Link Checker scan complete.")
36
  except Exception as e:
37
  LOGGER.error(f"Error in Dead Link Checker loop: {e}")
38
+
 
39
  await asyncio.sleep(self.check_interval_seconds)
40
 
41
  async def _scan_all_media(self):
 
 
42
  if not multi_clients:
43
  LOGGER.warning("No bot clients available for Dead Link Checker.")
44
  return
45
 
46
+ clients = list(multi_clients.values())
 
47
 
 
48
  for i in range(1, self.db.current_db_index + 1):
49
+ active_db = self.db.dbs[f"storage_{i}"]
 
50
 
51
+ #----- Movies (snapshot ids first so no cursor stays open during the slow Telegram checks)
52
  try:
53
+ movie_ids = [d["_id"] for d in await active_db["movie"].find(
54
+ {"telegram": {"$exists": True, "$not": {"$size": 0}}, "telegram.is_dead": {"$ne": True}},
55
+ {"_id": 1},
56
+ ).to_list(None)]
57
+ for movie_id in movie_ids:
58
+ movie = await active_db["movie"].find_one({"_id": movie_id})
59
+ if not movie:
60
+ continue
61
  tmdb_id = movie.get("tmdb_id")
62
  for quality in movie.get("telegram", []):
63
+ if quality.get("is_dead"):
64
+ continue
65
+ status = await self._check_file_alive(clients, quality.get("id"))
66
+ if status == DEAD:
67
+ LOGGER.warning(f"Found dead link for Movie {tmdb_id} (Quality: {quality.get('quality')})")
68
+ await self.db.flag_dead_link("movie", tmdb_id, i, quality.get("id"))
69
+ await asyncio.sleep(0.5)
70
  except Exception as e:
71
  LOGGER.error(f"Error scanning movies in DB {i}: {e}")
72
 
73
+ #----- TV Shows (snapshot ids first, then re-read each doc with a short query)
74
  try:
75
+ tv_ids = [d["_id"] for d in await active_db["tv"].find(
76
+ {"seasons.episodes.telegram": {"$exists": True, "$not": {"$size": 0}}, "seasons.episodes.telegram.is_dead": {"$ne": True}},
77
+ {"_id": 1},
78
+ ).to_list(None)]
79
+ for tv_id in tv_ids:
80
+ tv = await active_db["tv"].find_one({"_id": tv_id})
81
+ if not tv:
82
+ continue
83
  tmdb_id = tv.get("tmdb_id")
84
  for season in tv.get("seasons", []):
85
  for ep in season.get("episodes", []):
86
  for quality in ep.get("telegram", []):
87
+ if quality.get("is_dead"):
88
+ continue
89
+ status = await self._check_file_alive(clients, quality.get("id"))
90
+ if status == DEAD:
91
+ LOGGER.warning(f"Found dead link for TV {tmdb_id} S{season.get('season_number')}E{ep.get('episode_number')} (Quality: {quality.get('quality')})")
92
+ await self.db.flag_dead_link("tv", tmdb_id, i, quality.get("id"))
93
+ await asyncio.sleep(0.5)
94
  except Exception as e:
95
  LOGGER.error(f"Error scanning TV shows in DB {i}: {e}")
96
 
97
+ async def _check_file_alive(self, clients, quality_id: str) -> str:
98
  try:
99
  decoded = await decode_string(quality_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  except Exception as e:
101
+ LOGGER.error(f"Link checker failed to decode {quality_id}: {e}")
102
+ return UNKNOWN
103
+ if not decoded:
104
+ return UNKNOWN
105
+
106
+ #----- Split file: every part must be alive; one confirmed-dead part kills the link
107
+ if "parts" in decoded:
108
+ parts = decoded.get("parts") or []
109
+ if not parts:
110
+ return UNKNOWN
111
+ saw_unknown = False
112
+ for part in parts:
113
+ status = await self._check_message_status(clients, part.get("chat_id"), part.get("msg_id"))
114
+ if status == DEAD:
115
+ return DEAD
116
+ if status == UNKNOWN:
117
+ saw_unknown = True
118
+ return UNKNOWN if saw_unknown else ALIVE
119
 
120
+ #----- Single file
121
+ if "chat_id" not in decoded or "msg_id" not in decoded:
122
+ return UNKNOWN
123
+ return await self._check_message_status(clients, decoded["chat_id"], decoded["msg_id"])
124
+
125
+ async def _check_message_status(self, clients, chat_id, msg_id) -> str:
126
  if chat_id is None or msg_id is None:
127
+ return UNKNOWN
128
+
129
  chat_id = int(f"-100{chat_id}")
130
  msg_id = int(msg_id)
131
+ confirmed_dead = False
132
+ for client in clients:
133
+ try:
134
+ message = await client.get_messages(chat_id, msg_id)
135
+ except FloodWait as e:
136
+ await asyncio.sleep(getattr(e, "value", 5) + 1)
137
+ continue
138
+ except Exception:
139
+ continue
140
+
141
+ if message is None or message.empty:
142
+ confirmed_dead = True
143
+ continue
144
+ if is_media(message):
145
+ return ALIVE
146
+ confirmed_dead = True
147
+
148
+ return DEAD if confirmed_dead else UNKNOWN
Backend/helper/manual_add.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Optional, Tuple
3
+
4
+ from Backend.helper.encrypt import decode_string
5
+ from Backend.helper.metadata.common import ID_REFS
6
+ from Backend.helper.metadata import caption_with_id, caption_with_links, has_raw_ref, parse_media_name
7
+ from Backend.helper.pyro import clean_filename, finalize_media_name, get_readable_file_size, is_media, message_has_thumb
8
+ from Backend.helper.split_files import parse_split_info, strip_part_suffix
9
+ from Backend.logger import LOGGER
10
+ from Backend.helper.task_manager import edit_message
11
+
12
+ _PRIVATE_LINK = re.compile(r"t\.me/c/(\d+)(?:/\d+)*/(\d+)")
13
+ _PUBLIC_LINK = re.compile(r"t\.me/([A-Za-z][\w]{3,})/(?:\d+/)?(\d+)")
14
+
15
+
16
+ #----- Parse a Telegram post link into (chat_ref, msg_id).
17
+ #----- chat_ref is a full -100 int for private channels or a @username string for public ones.
18
+ def parse_telegram_link(url: str) -> Tuple[Optional[object], Optional[int]]:
19
+ url = (url or "").strip()
20
+ private = _PRIVATE_LINK.search(url)
21
+ if private:
22
+ return int(f"-100{private.group(1)}"), int(private.group(2))
23
+ public = _PUBLIC_LINK.search(url)
24
+ if public:
25
+ return public.group(1), int(public.group(2))
26
+ return None, None
27
+
28
+
29
+ #----- Map a video pixel height to a standard quality label
30
+ def quality_from_height(height: int) -> str:
31
+ if not height:
32
+ return ""
33
+ for threshold, label in ((1800, "2160p"), (1200, "1440p"), (900, "1080p"),
34
+ (620, "720p"), (400, "480p"), (260, "360p")):
35
+ if height >= threshold:
36
+ return label
37
+ return "240p"
38
+
39
+
40
+ #----- Fetch a message and return the stream fields the manual-add flow needs.
41
+ async def resolve_telegram_message(client, url: str = None, chat_id=None, msg_id=None) -> dict:
42
+ if url:
43
+ chat_ref, msg_id = parse_telegram_link(url)
44
+ if chat_ref is None:
45
+ raise ValueError("Could not read that Telegram link. Use a t.me/c/... or t.me/<channel>/... message link.")
46
+ elif chat_id and msg_id:
47
+ chat_ref = int(f"-100{str(chat_id).replace('-100', '')}")
48
+ msg_id = int(msg_id)
49
+ else:
50
+ raise ValueError("Provide a Telegram message link, or a chat id and message id.")
51
+
52
+ message = await client.get_messages(chat_ref, msg_id)
53
+ if not message or getattr(message, "empty", False):
54
+ raise ValueError("That message was not found. Make sure the bot is in the channel.")
55
+
56
+ media = is_media(message)
57
+ if not media:
58
+ raise ValueError("That message has no downloadable file.")
59
+
60
+ #----- Prefer the caption over the raw file name, then normalise it to the exact
61
+ #----- filename receiver.py stores (clean, split-suffix stripped, video extension).
62
+ caption = (getattr(message, "caption", None) or "").strip()
63
+ raw_name = caption or getattr(media, "file_name", None) or "video"
64
+ cleaned = clean_filename(raw_name)
65
+ split_info = parse_split_info(cleaned)
66
+ raw_size = getattr(media, "file_size", 0) or 0
67
+ parsed = parse_media_name(strip_part_suffix(cleaned) if split_info else cleaned)
68
+ file_name = finalize_media_name(raw_name, bool(split_info))
69
+
70
+ #----- Real video dimensions beat the filename; documents fall back to the name
71
+ height = getattr(media, "height", 0) or 0
72
+ quality = quality_from_height(height) or parsed.get("quality") or ""
73
+
74
+ #----- Original upload date (forward source if forwarded, else this message's date)
75
+ original_date = getattr(message, "forward_date", None) or getattr(message, "date", None)
76
+ upload_year = original_date.year if original_date else 0
77
+
78
+ return {
79
+ "chat_id": str(message.chat.id).replace("-100", ""),
80
+ "msg_id": message.id,
81
+ "name": file_name,
82
+ "raw_size": raw_size,
83
+ "size": get_readable_file_size(raw_size),
84
+ "quality": quality,
85
+ "season": parsed.get("season"),
86
+ "episode": parsed.get("episode"),
87
+ "width": getattr(media, "width", 0) or 0,
88
+ "height": height,
89
+ "has_thumb": message_has_thumb(message),
90
+ "upload_year": upload_year,
91
+ "split_key": split_info[0] if split_info else None,
92
+ "part_number": split_info[1] if split_info else None,
93
+ }
94
+
95
+
96
+
97
+ #----- True when every IMDb/TMDB reference in the text points at this title
98
+ def tagged_for(text: str, info: dict) -> bool:
99
+ imdb, tmdb = str(info.get("imdb_id") or ""), str(info.get("tmdb_id") or "")
100
+ path = "movie" if info.get("media_type", "movie") == "movie" else "tv"
101
+ refs = ID_REFS.findall(text or "")
102
+ return bool(refs) and all(
103
+ (imdb.startswith("tt") and re.search(rf"{imdb}(?!\d)", r, re.I))
104
+ or (tmdb.isdigit() and int(tmdb) > 0 and re.search(rf"/{path}/{tmdb}(?!\d)", r))
105
+ for r in refs
106
+ )
107
+
108
+
109
+ async def stamp_caption_with_id(message, metadata_info: dict) -> bool:
110
+ try:
111
+ if not has_raw_ref(message.caption) and tagged_for(caption_with_links(message), metadata_info):
112
+ return False
113
+ media = message.video or message.document
114
+ base = (getattr(message, "caption", None) or getattr(media, "file_name", None) or "")
115
+ new_caption = caption_with_id(base, metadata_info)
116
+ if not new_caption:
117
+ return False
118
+
119
+ await edit_message(message.chat.id, message.id, new_caption)
120
+ return True
121
+ except Exception as e:
122
+ LOGGER.warning(f"[Caption] Could not stamp id on message {getattr(message, 'id', '?')}: {e}")
123
+ return False
124
+
125
+
126
+ async def stamp_caption_by_ref(client, chat_id, msg_id, metadata_info: dict) -> bool:
127
+ try:
128
+ chat_ref = int(f"-100{str(chat_id).replace('-100', '')}")
129
+ message = await client.get_messages(chat_ref, int(msg_id))
130
+ if not message or getattr(message, "empty", False):
131
+ return False
132
+ return await stamp_caption_with_id(message, metadata_info)
133
+ except Exception as e:
134
+ LOGGER.warning(f"[Caption] Could not stamp id on message {msg_id}: {e}")
135
+ return False
136
+
137
+
138
+ #----- Re-tag every file of a title with its IMDB deeplink (wrong or raw links are replaced)
139
+ async def retag_media(client, media_type: str, doc: dict) -> int:
140
+ info = {"imdb_id": doc.get("imdb_id"), "tmdb_id": doc.get("tmdb_id"), "media_type": media_type}
141
+ qualities = (doc.get("telegram") or []) if media_type == "movie" else [
142
+ q for s in doc.get("seasons") or [] for e in s.get("episodes") or [] for q in e.get("telegram") or []
143
+ ]
144
+ refs = []
145
+ for q in qualities:
146
+ if q.get("parts"):
147
+ refs += [(p["chat_id"], p["msg_id"]) for p in q["parts"]]
148
+ else:
149
+ try:
150
+ d = await decode_string(q["id"])
151
+ refs.append((d["chat_id"], d["msg_id"]))
152
+ except Exception:
153
+ continue
154
+ for chat_id, msg_id in refs:
155
+ await stamp_caption_by_ref(client, chat_id, msg_id, info)
156
+ return len(refs)
Backend/helper/metadata.py DELETED
@@ -1,956 +0,0 @@
1
- import asyncio
2
- import re
3
- import traceback
4
- from typing import Optional, List
5
-
6
- import PTN
7
-
8
- import Backend
9
- from Backend.logger import LOGGER
10
- from Backend.helper.imdb import get_detail, get_season, search_title, search_title_multi
11
- from Backend.helper.settings_manager import SettingsManager
12
- from Backend.helper.encrypt import encode_string
13
- from Backend.helper.split_files import parse_split_info, parse_combined_episodes
14
- from Backend.helper.anime import fetch_anime_metadata, fetch_anime_movie_metadata
15
- from themoviedb import aioTMDb
16
- from rapidfuzz import fuzz
17
- from guessit import guessit as _guessit
18
- from difflib import SequenceMatcher
19
-
20
- def _fuzzy_ratio(a: str, b: str) -> float:
21
- if not a or not b:
22
- return 0.0
23
- try:
24
- set_ratio = fuzz.token_set_ratio(a, b) / 100.0
25
- sort_ratio = fuzz.token_sort_ratio(a, b) / 100.0
26
- a_tokens, b_tokens = a.split(), b.split()
27
- if a_tokens and b_tokens:
28
- coverage = min(len(a_tokens), len(b_tokens)) / max(len(a_tokens), len(b_tokens))
29
- else:
30
- coverage = 0.0
31
- return max(sort_ratio, set_ratio * coverage)
32
- except Exception:
33
- return SequenceMatcher(None, a, b).ratio()
34
-
35
-
36
- _CINEMETA_THRESHOLD = 0.60
37
- _TMDB_THRESHOLD = 0.55
38
- _STRONG_MATCH = 0.92
39
- _ALT_TITLE_LOOKUPS = 5
40
-
41
- IMDB_CACHE: dict = {}
42
- TMDB_SEARCH_CACHE: dict = {}
43
- TMDB_DETAILS_CACHE: dict = {}
44
- EPISODE_CACHE: dict = {}
45
- ALT_TITLES_CACHE: dict = {}
46
-
47
- API_SEMAPHORE = asyncio.Semaphore(12)
48
-
49
- _MULTIPART_RE = re.compile(r"(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)", re.IGNORECASE)
50
-
51
- # Combined files are grouped in the Specials folder (season 0) as a single
52
- # "Season N Combined" entry per real season.
53
- COMBINED_SEASON = 0
54
- COMBINED_EPISODE_BASE = 1000
55
-
56
-
57
- # Re-file a combined entry into its season's single Combined slot inside Specials.
58
- # A range/Full label is appended to the quality so distinct combined files coexist
59
- # while an identical re-upload still replaces correctly under replace mode.
60
- def _apply_combined_override(payload: dict, combined: dict) -> None:
61
- season, start, end = combined["season"], combined["start"], combined["end"]
62
- payload["season_number"] = COMBINED_SEASON
63
- payload["episode_number"] = COMBINED_EPISODE_BASE + season
64
- payload["episode_title"] = f"Season {season} Combined"
65
- label = "Full" if start is None else f"E{start:02d}-E{end:02d}"
66
- payload["quality"] = f"{payload.get('quality') or 'HD'} {label}"
67
- if not payload.get("episode_backdrop"):
68
- payload["episode_backdrop"] = payload.get("backdrop") or payload.get("poster") or ""
69
-
70
- _tmdb_client: aioTMDb | None = None
71
- _tmdb_client_key: str | None = None
72
-
73
-
74
- # Return a cached TMDb client, rebuilding it when the configured API key changes.
75
- def get_tmdb_client() -> aioTMDb:
76
- global _tmdb_client, _tmdb_client_key
77
- current_key = SettingsManager.current().tmdb_api
78
- if _tmdb_client is None or _tmdb_client_key != current_key:
79
- _tmdb_client = aioTMDb(key=current_key, language="en-US", region="US")
80
- _tmdb_client_key = current_key
81
- return _tmdb_client
82
-
83
-
84
- def format_tmdb_image(path: str, size="w500") -> str:
85
- return f"https://image.tmdb.org/t/p/{size}{path}" if path else ""
86
-
87
- def get_tmdb_logo(images) -> str:
88
- logos = getattr(images, "logos", None) if images else None
89
- if not logos:
90
- return ""
91
- for logo in logos:
92
- if getattr(logo, "iso_639_1", None) == "en" and getattr(logo, "file_path", None):
93
- return format_tmdb_image(logo.file_path, "w300")
94
- for logo in logos:
95
- if getattr(logo, "file_path", None):
96
- return format_tmdb_image(logo.file_path, "w300")
97
- return ""
98
-
99
- def format_imdb_images(imdb_id: str) -> dict:
100
- if not imdb_id:
101
- return {"poster": "", "backdrop": "", "logo": ""}
102
- return {
103
- "poster": f"https://images.metahub.space/poster/small/{imdb_id}/img",
104
- "backdrop": f"https://images.metahub.space/background/medium/{imdb_id}/img",
105
- "logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
106
- }
107
-
108
-
109
- def extract_default_id(text: str) -> str | None:
110
- if not text:
111
- return None
112
- bare_imdb = re.search(r"\b(tt\d{7,10})\b", text)
113
- if bare_imdb:
114
- return bare_imdb.group(1)
115
- imdb_url = re.search(r"/title/(tt\d+)", text)
116
- if imdb_url:
117
- return imdb_url.group(1)
118
- tmdb_url = re.search(r"/(?:movie|tv)/(\d+)", text)
119
- if tmdb_url:
120
- return tmdb_url.group(1)
121
- return None
122
-
123
- def _split_default_id(default_id) -> tuple[str | None, int | None, bool, bool]:
124
- if not default_id:
125
- return None, None, False, False
126
- value = str(default_id).strip()
127
- if value.startswith("tt"):
128
- return value, None, True, False
129
- if value.isdigit():
130
- return None, int(value), False, True
131
- return None, None, False, False
132
-
133
- def _normalize_title(title: str) -> str:
134
- if not title:
135
- return ""
136
- t = title.lower().strip()
137
- t = re.sub(r"^\b(the|a|an)\b\s+", "", t)
138
- t = re.sub(r"[^\w\s]", " ", t)
139
- return re.sub(r"\s+", " ", t).strip()
140
-
141
- def _title_similarity(t1: str, t2: str) -> float:
142
- n1, n2 = _normalize_title(t1), _normalize_title(t2)
143
- if not n1 or not n2:
144
- return 0.0
145
- return _fuzzy_ratio(n1, n2)
146
-
147
- def _year_from_str(year_val) -> int:
148
- if not year_val:
149
- return 0
150
- m = re.search(r"(\d{4})", str(year_val))
151
- return int(m.group(1)) if m else 0
152
-
153
- def _score_candidate(
154
- query_title: str,
155
- query_year: Optional[int],
156
- result_title: str,
157
- result_year: int,
158
- year_reliable: bool = True,
159
- ) -> float:
160
- score = _title_similarity(query_title, result_title)
161
-
162
- if score < 0.5:
163
- return score
164
-
165
- if query_year and result_year:
166
- diff = abs(int(query_year) - result_year)
167
- if year_reliable:
168
- if diff > 2:
169
- score = max(0.0, score - 0.10 * (diff - 2))
170
- elif score >= 0.80:
171
- if diff == 0:
172
- score = min(1.0, score + 0.20)
173
- elif diff == 1:
174
- score = min(1.0, score + 0.07)
175
- else:
176
- if diff == 0 and score >= 0.80:
177
- score = min(1.0, score + 0.05)
178
- return score
179
-
180
- def _build_query_variants(title: str, year: Optional[int] = None) -> List[str]:
181
- variants: List[str] = [title]
182
- if year:
183
- variants.append(f"{title} {year}")
184
-
185
- stripped = re.sub(r"\s+", " ", re.sub(r"[^\w\s]", " ", title)).strip()
186
- if stripped and stripped.lower() != title.lower():
187
- variants.append(stripped)
188
- if year:
189
- variants.append(f"{stripped} {year}")
190
-
191
- no_article = re.sub(r"^\b(the|a|an)\b\s+", "", title, flags=re.IGNORECASE).strip()
192
- if no_article and no_article.lower() != title.lower():
193
- variants.append(no_article)
194
-
195
- seen: set = set()
196
- ordered: List[str] = []
197
- for v in variants:
198
- key = v.lower()
199
- if v and key not in seen:
200
- seen.add(key)
201
- ordered.append(v)
202
- return ordered
203
-
204
- def _first(value):
205
- return value[0] if isinstance(value, list) else value
206
-
207
- def parse_media_name(name: str) -> dict:
208
- try:
209
- ptn = PTN.parse(name) or {}
210
- except Exception as e:
211
- LOGGER.warning(f"PTN parsing failed for {name}: {e}")
212
- ptn = {}
213
-
214
- parsed = {
215
- "title": ptn.get("title"),
216
- "year": ptn.get("year"),
217
- "season": ptn.get("season"),
218
- "episode": ptn.get("episode"),
219
- "quality": ptn.get("resolution"),
220
- "excess": ptn.get("excess"),
221
- }
222
-
223
- if _guessit:
224
- try:
225
- g = _guessit(name)
226
- parsed["title"] = parsed["title"] or _first(g.get("title"))
227
- parsed["year"] = parsed["year"] or _first(g.get("year"))
228
- parsed["season"] = parsed["season"] or _first(g.get("season"))
229
- parsed["episode"] = parsed["episode"] or _first(g.get("episode"))
230
- parsed["quality"] = parsed["quality"] or _first(g.get("screen_size"))
231
- except Exception as e:
232
- LOGGER.warning(f"GuessIt parsing failed for {name}: {e}")
233
-
234
- return parsed
235
-
236
- async def safe_imdb_search(title: str, type_: str, year: Optional[int] = None) -> str | None:
237
- cache_key = f"imdb::{type_}::{title}::{year}"
238
- if cache_key in IMDB_CACHE:
239
- return IMDB_CACHE[cache_key]
240
-
241
- query_variants = _build_query_variants(title, year)
242
- best_id: str | None = None
243
- best_score = 0.0
244
- best_title = ""
245
-
246
- year_reliable = type_ == "movie"
247
-
248
- for query in query_variants:
249
- try:
250
- async with API_SEMAPHORE:
251
- results = await search_title_multi(query=query, type=type_, limit=8)
252
- for r in results:
253
- score = _score_candidate(
254
- title, year, r.get("title", ""), _year_from_str(r.get("year", "")),
255
- year_reliable=year_reliable,
256
- )
257
- if score > best_score:
258
- best_score, best_id, best_title = score, r.get("id"), r.get("title", "")
259
- if best_score >= _STRONG_MATCH:
260
- break
261
- except Exception as e:
262
- LOGGER.warning(f"Cinemeta search variant '{query}' [{type_}] failed: {e}")
263
- if best_score >= _STRONG_MATCH:
264
- break
265
-
266
- if best_score >= _CINEMETA_THRESHOLD and best_id:
267
- LOGGER.info(f"Cinemeta match: '{title}' (year={year}) -> '{best_title}' [{best_id}] (score={best_score:.2f})")
268
- IMDB_CACHE[cache_key] = best_id
269
- return best_id
270
-
271
- if best_id:
272
- LOGGER.info(
273
- f"Cinemeta low-confidence for '{title}' (year={year}, type={type_}) | "
274
- f"best '{best_title}' [{best_id}] score={best_score:.2f} -> falling back to TMDb"
275
- )
276
- else:
277
- LOGGER.info(f"Cinemeta returned no results for '{title}' (year={year}, type={type_}) -> falling back to TMDb")
278
-
279
- IMDB_CACHE[cache_key] = None
280
- return None
281
-
282
- async def _tmdb_raw_search(title: str, media_type: str, year: Optional[int]):
283
- client = get_tmdb_client()
284
- async with API_SEMAPHORE:
285
- if media_type == "movie":
286
- results = await (client.search().movies(query=title, year=year) if year else client.search().movies(query=title))
287
- if not results and year:
288
- results = await client.search().movies(query=title)
289
- return results
290
- return await client.search().tv(query=title)
291
-
292
- async def safe_tmdb_search(title: str, type_: str, year: Optional[int] = None):
293
- cache_key = f"tmdb_search::{type_}::{title}::{year}"
294
- if cache_key in TMDB_SEARCH_CACHE:
295
- return TMDB_SEARCH_CACHE[cache_key]
296
-
297
- try:
298
- results = await _tmdb_raw_search(title, type_, year)
299
- best = await _pick_best_tmdb_result(results, title, year, type_)
300
- if best is None and results:
301
- top = results[0]
302
- top_title = getattr(top, "title" if type_ == "movie" else "name", "?")
303
- LOGGER.info(f"TMDb '{title}' (year={year}) top result '{top_title}' did not meet threshold")
304
- TMDB_SEARCH_CACHE[cache_key] = best
305
- return best
306
- except Exception as e:
307
- LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
308
- TMDB_SEARCH_CACHE[cache_key] = None
309
- return None
310
-
311
- def _tmdb_title_year(item, media_type: str) -> tuple[str, int]:
312
- if media_type == "movie":
313
- date = getattr(item, "release_date", None)
314
- return getattr(item, "title", "") or "", getattr(date, "year", 0) if date else 0
315
- date = getattr(item, "first_air_date", None)
316
- return getattr(item, "name", "") or "", getattr(date, "year", 0) if date else 0
317
-
318
- async def _pick_best_tmdb_result(results, query_title: str, query_year: Optional[int], media_type: str):
319
- if not results:
320
- return None
321
-
322
- year_reliable = media_type == "movie"
323
-
324
- scored = []
325
- best_item, best_score = None, 0.0
326
- for item in results:
327
- r_title, r_year = _tmdb_title_year(item, media_type)
328
- score = _score_candidate(query_title, query_year, r_title, r_year, year_reliable=year_reliable)
329
- scored.append((score, item, r_year))
330
- if score > best_score:
331
- best_score, best_item = score, item
332
-
333
- if best_score >= _STRONG_MATCH:
334
- return best_item
335
-
336
- scored.sort(key=lambda x: x[0], reverse=True)
337
- for _, item, r_year in scored[:_ALT_TITLE_LOOKUPS]:
338
- alt_titles = await _tmdb_alternative_titles(media_type, getattr(item, "id", None))
339
- for alt in alt_titles:
340
- alt_score = _score_candidate(query_title, query_year, alt, r_year, year_reliable=year_reliable)
341
- if alt_score > best_score:
342
- best_score, best_item = alt_score, item
343
- if best_score >= _STRONG_MATCH:
344
- break
345
- if best_score >= _STRONG_MATCH:
346
- break
347
-
348
- return best_item if best_score >= _TMDB_THRESHOLD and best_item is not None else None
349
-
350
- async def _tmdb_alternative_titles(media_type: str, tmdb_id) -> list[str]:
351
- if not tmdb_id:
352
- return []
353
- cache_key = (media_type, tmdb_id)
354
- if cache_key in ALT_TITLES_CACHE:
355
- return ALT_TITLES_CACHE[cache_key]
356
- titles: list[str] = []
357
- try:
358
- client = get_tmdb_client()
359
- async with API_SEMAPHORE:
360
- target = client.movie(tmdb_id) if media_type == "movie" else client.tv(tmdb_id)
361
- alt = await target.alternative_titles()
362
- entries = list(getattr(alt, "titles", None) or []) + list(getattr(alt, "results", None) or [])
363
- titles = [t for t in (getattr(e, "title", "") for e in entries) if t]
364
- except Exception as e:
365
- LOGGER.warning(f"TMDb alternative-titles fetch failed for {media_type} id={tmdb_id}: {e}")
366
- ALT_TITLES_CACHE[cache_key] = titles
367
- return titles
368
-
369
- async def _tmdb_details(media_type: str, item_id):
370
- cache_key = (media_type, item_id)
371
- if cache_key in TMDB_DETAILS_CACHE:
372
- return TMDB_DETAILS_CACHE[cache_key]
373
- try:
374
- client = get_tmdb_client()
375
- async with API_SEMAPHORE:
376
- target = client.movie(item_id) if media_type == "movie" else client.tv(item_id)
377
- details = await target.details(append_to_response="external_ids,credits")
378
- details.images = await target.images()
379
- TMDB_DETAILS_CACHE[cache_key] = details
380
- return details
381
- except Exception as e:
382
- LOGGER.warning(f"TMDb {media_type} details fetch failed for id={item_id}: {e}")
383
- TMDB_DETAILS_CACHE[cache_key] = None
384
- return None
385
-
386
- async def _tmdb_episode_details(tv_id, season, episode):
387
- key = (tv_id, season, episode)
388
- if key in EPISODE_CACHE:
389
- return EPISODE_CACHE[key]
390
- try:
391
- async with API_SEMAPHORE:
392
- details = await get_tmdb_client().episode(tv_id, season, episode).details()
393
- EPISODE_CACHE[key] = details
394
- return details
395
- except Exception:
396
- EPISODE_CACHE[key] = None
397
- return None
398
-
399
- async def _cached_imdb_detail(imdb_id: str, media_type: str):
400
- cached = IMDB_CACHE.get(imdb_id)
401
- if isinstance(cached, dict):
402
- return cached
403
- async with API_SEMAPHORE:
404
- detail = await get_detail(imdb_id=imdb_id, media_type=media_type)
405
- IMDB_CACHE[imdb_id] = detail
406
- return detail
407
-
408
- async def _cached_imdb_season(imdb_id: str, season, episode):
409
- key = f"{imdb_id}::{season}::{episode}"
410
- if key in EPISODE_CACHE:
411
- return EPISODE_CACHE[key]
412
- async with API_SEMAPHORE:
413
- ep = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
414
- EPISODE_CACHE[key] = ep
415
- return ep
416
-
417
- async def _tmdb_external_imdb_id(media_type: str, tmdb_id) -> str | None:
418
- try:
419
- details = await _tmdb_details(media_type, tmdb_id)
420
- ext = getattr(details, "external_ids", None) if details else None
421
- return getattr(ext, "imdb_id", None) if ext else None
422
- except Exception:
423
- return None
424
-
425
-
426
-
427
- def _extract_cast(details) -> list:
428
- credits = getattr(details, "credits", None) or {}
429
- cast = getattr(credits, "cast", []) or []
430
- return [getattr(c, "name", None) or getattr(c, "original_name", None) for c in cast]
431
-
432
-
433
- # Collect ISO 3166-1 country codes from a TMDb details object (origin_country
434
- # and production_countries), used by the auto-catalog classifier.
435
- def _tmdb_country_codes(details) -> list:
436
- codes: list = []
437
- for code in (getattr(details, "origin_country", None) or []):
438
- if code and code not in codes:
439
- codes.append(code)
440
- for country in (getattr(details, "production_countries", None) or []):
441
- code = getattr(country, "iso_3166_1", None) or (country.get("iso_3166_1") if isinstance(country, dict) else None)
442
- if code and code not in codes:
443
- codes.append(code)
444
- return codes
445
-
446
-
447
- def _format_runtime(minutes) -> str:
448
- return f"{minutes} min" if minutes else ""
449
-
450
-
451
- # Build the indexer movie payload from a TMDb details object.
452
- def _build_tmdb_movie_payload(movie, quality, encoded_string) -> dict:
453
- release = getattr(movie, "release_date", None)
454
- return {
455
- "tmdb_id": movie.id,
456
- "imdb_id": getattr(getattr(movie, "external_ids", None), "imdb_id", None),
457
- "title": movie.title,
458
- "year": getattr(release, "year", 0) if release else 0,
459
- "rate": getattr(movie, "vote_average", 0) or 0,
460
- "description": movie.overview or "",
461
- "poster": format_tmdb_image(movie.poster_path),
462
- "backdrop": format_tmdb_image(movie.backdrop_path, "original"),
463
- "logo": get_tmdb_logo(getattr(movie, "images", None)),
464
- "cast": _extract_cast(movie),
465
- "runtime": str(_format_runtime(getattr(movie, "runtime", None))),
466
- "media_type": "movie",
467
- "genres": [g.name for g in (movie.genres or [])],
468
- "original_language": getattr(movie, "original_language", None),
469
- "origin_country": _tmdb_country_codes(movie),
470
- "quality": quality,
471
- "encoded_string": encoded_string,
472
- }
473
-
474
-
475
- # Build the indexer TV payload from TMDb series + episode details.
476
- def _build_tmdb_tv_payload(tv, ep, season, episode, quality, encoded_string) -> dict:
477
- first_air = getattr(tv, "first_air_date", None)
478
- series_runtime = tv.episode_run_time[0] if getattr(tv, "episode_run_time", None) else None
479
- runtime = _format_runtime((getattr(ep, "runtime", None) if ep else None) or series_runtime)
480
- fallback_ep_title = f"S{season:02d}E{episode:02d}"
481
- return {
482
- "tmdb_id": tv.id,
483
- "imdb_id": getattr(getattr(tv, "external_ids", None), "imdb_id", None),
484
- "title": tv.name,
485
- "year": getattr(first_air, "year", 0) if first_air else 0,
486
- "rate": getattr(tv, "vote_average", 0) or 0,
487
- "description": tv.overview or "",
488
- "poster": format_tmdb_image(tv.poster_path),
489
- "backdrop": format_tmdb_image(tv.backdrop_path, "original"),
490
- "logo": get_tmdb_logo(getattr(tv, "images", None)),
491
- "genres": [g.name for g in (tv.genres or [])],
492
- "media_type": "tv",
493
- "cast": _extract_cast(tv),
494
- "runtime": str(runtime),
495
- "original_language": getattr(tv, "original_language", None),
496
- "origin_country": _tmdb_country_codes(tv),
497
- "season_number": season,
498
- "episode_number": episode,
499
- "episode_title": getattr(ep, "name", fallback_ep_title) if ep else fallback_ep_title,
500
- "episode_backdrop": format_tmdb_image(getattr(ep, "still_path", None), "original") if ep else "",
501
- "episode_overview": getattr(ep, "overview", "") if ep else "",
502
- "episode_released": ep.air_date.strftime("%Y-%m-%dT05:00:00.000Z") if (ep and getattr(ep, "air_date", None)) else "",
503
- "quality": quality,
504
- "encoded_string": encoded_string,
505
- }
506
-
507
-
508
- # Build the indexer movie payload from Cinemeta/IMDb details.
509
- def _build_imdb_movie_payload(imdb, imdb_id, title, quality, encoded_string) -> dict:
510
- images = format_imdb_images(imdb_id)
511
- return {
512
- "tmdb_id": imdb.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else None),
513
- "imdb_id": imdb_id,
514
- "title": imdb.get("title", title),
515
- "year": imdb.get("releaseDetailed", {}).get("year", 0),
516
- "rate": imdb.get("rating", {}).get("star", 0),
517
- "description": imdb.get("plot", ""),
518
- "poster": images["poster"],
519
- "backdrop": images["backdrop"],
520
- "logo": images["logo"],
521
- "cast": imdb.get("cast", []),
522
- "runtime": str(imdb.get("runtime") or ""),
523
- "media_type": "movie",
524
- "genres": imdb.get("genre", []),
525
- "quality": quality,
526
- "encoded_string": encoded_string,
527
- }
528
-
529
-
530
- # Build the indexer TV payload from Cinemeta/IMDb series + episode details.
531
- def _build_imdb_tv_payload(imdb, ep, imdb_id, title, season, episode, quality, encoded_string) -> dict:
532
- images = format_imdb_images(imdb_id)
533
- return {
534
- "tmdb_id": imdb.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else None),
535
- "imdb_id": imdb_id,
536
- "title": imdb.get("title", title),
537
- "year": imdb.get("releaseDetailed", {}).get("year", 0),
538
- "rate": imdb.get("rating", {}).get("star", 0),
539
- "description": imdb.get("plot", ""),
540
- "poster": images["poster"],
541
- "backdrop": images["backdrop"],
542
- "logo": images["logo"],
543
- "cast": imdb.get("cast", []),
544
- "runtime": str(imdb.get("runtime") or ""),
545
- "genres": imdb.get("genre", []),
546
- "media_type": "tv",
547
- "season_number": season,
548
- "episode_number": episode,
549
- "episode_title": ep.get("title", f"S{season:02d}E{episode:02d}"),
550
- "episode_backdrop": ep.get("image", ""),
551
- "episode_overview": ep.get("plot", ""),
552
- "episode_released": str(ep.get("released", "")),
553
- "quality": quality,
554
- "encoded_string": encoded_string,
555
- }
556
-
557
-
558
- # ----------------- Main entry-point -----------------
559
-
560
- # True when a file's channel is configured as an anime channel.
561
- def _is_anime_channel(channel) -> bool:
562
- anime_channels = SettingsManager.current().anime_channels
563
- if not anime_channels:
564
- return False
565
- target = str(channel).replace("-100", "")
566
- return any(str(c).strip().replace("-100", "") == target for c in anime_channels)
567
-
568
-
569
- # Resolve anime TV metadata, filling the imdb_id from tmdb when ani.zip lacks it.
570
- async def _fetch_anime_tv(title, season, episode, encoded_string, year, quality) -> dict | None:
571
- try:
572
- result = await fetch_anime_metadata(title, season, episode, encoded_string, year, quality)
573
- except Exception as e:
574
- LOGGER.warning(f"[ANIME] metadata error for '{title}': {e}")
575
- return None
576
- if result is None:
577
- return None
578
- if not result.get("imdb_id") and result.get("tmdb_id"):
579
- result["imdb_id"] = await _tmdb_external_imdb_id("tv", result["tmdb_id"])
580
- if not result.get("imdb_id"):
581
- LOGGER.info(f"[ANIME] No imdb id for '{title}' -> falling back to TMDb/Cinemeta")
582
- return None
583
- LOGGER.info(f"[ANIME] Matched '{result.get('title')}' [{result.get('imdb_id')}] S{season:02d}E{episode:02d}")
584
- return result
585
-
586
-
587
- # Resolve anime movie metadata, filling the imdb_id from tmdb when ani.zip lacks it.
588
- async def _fetch_anime_movie(title, encoded_string, year, quality) -> dict | None:
589
- try:
590
- result = await fetch_anime_movie_metadata(title, encoded_string, year, quality)
591
- except Exception as e:
592
- LOGGER.warning(f"[ANIME] movie metadata error for '{title}': {e}")
593
- return None
594
- if result is None:
595
- return None
596
- if not result.get("imdb_id") and result.get("tmdb_id"):
597
- result["imdb_id"] = await _tmdb_external_imdb_id("movie", result["tmdb_id"])
598
- if not result.get("imdb_id"):
599
- LOGGER.info(f"[ANIME] No imdb id for movie '{title}' -> falling back to TMDb/Cinemeta")
600
- return None
601
- LOGGER.info(f"[ANIME] Matched movie '{result.get('title')}' [{result.get('imdb_id')}]")
602
- return result
603
-
604
-
605
- # Parse a filename/caption and resolve full movie or TV metadata for the indexer.
606
- async def metadata(filename: str, channel: int, msg_id, override_id: str = None) -> dict | None:
607
- try:
608
- parsed = parse_media_name(filename)
609
- except Exception as e:
610
- LOGGER.error(f"Parsing failed for {filename}: {e}\n{traceback.format_exc()}")
611
- return None
612
-
613
- if _MULTIPART_RE.search(filename):
614
- LOGGER.info(f"Skipping {filename}: split video file not meant to be combined in Stremio")
615
- return None
616
-
617
- combined = parse_combined_episodes(filename)
618
-
619
- excess = parsed.get("excess")
620
- if not combined and excess and any("combined" in item.lower() for item in excess):
621
- LOGGER.info(f"Skipping {filename}: contains 'combined'")
622
- return None
623
-
624
- split_info = None if combined else parse_split_info(filename)
625
- part_number = split_info[1] if split_info else None
626
-
627
- title = parsed.get("title")
628
- season = parsed.get("season")
629
- episode = parsed.get("episode")
630
- year = parsed.get("year")
631
- quality = parsed.get("quality")
632
-
633
- if combined:
634
- season, episode = combined["season"], combined["start"] or 1
635
- elif isinstance(season, list) or isinstance(episode, list):
636
- LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
637
- return None
638
- elif season and not episode:
639
- # Season pack with no episode number (e.g. "Season 01") -> whole-season combined.
640
- combined = {"season": season, "start": None, "end": None}
641
- episode = 1
642
- if not quality:
643
- LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
644
- return None
645
- if not title:
646
- LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
647
- return None
648
-
649
- default_id = _resolve_default_id(override_id, filename)
650
-
651
- try:
652
- encoded_string = await encode_string({"chat_id": channel, "msg_id": msg_id})
653
- except Exception:
654
- encoded_string = None
655
-
656
- group_key = f"{channel}:{quality}:{split_info[0]}" if split_info else None
657
-
658
- anime_channel = _is_anime_channel(channel)
659
-
660
- try:
661
- if season and episode:
662
- LOGGER.info(f"Fetching TV metadata: {title} S{season:02d}E{episode:02d} (year={year})")
663
- result = None
664
- if not default_id and anime_channel:
665
- result = await _fetch_anime_tv(title, season, episode, encoded_string, year, quality)
666
- if result is None:
667
- result = await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
668
- if result is not None and combined:
669
- _apply_combined_override(result, combined)
670
- else:
671
- LOGGER.info(f"Fetching Movie metadata: {title} (year={year})")
672
- result = None
673
- if not default_id and anime_channel:
674
- result = await _fetch_anime_movie(title, encoded_string, year, quality)
675
- if result is None:
676
- result = await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
677
- if result is not None:
678
- if anime_channel:
679
- result["is_anime"] = True
680
- result["group_key"] = group_key
681
- result["part_number"] = part_number
682
- return result
683
- except Exception as e:
684
- LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
685
- return None
686
-
687
-
688
- # Pick a default id from the override, the global setting, then the filename itself.
689
- def _resolve_default_id(override_id, filename) -> str | None:
690
- for source in (override_id, getattr(Backend, "USE_DEFAULT_ID", None), filename):
691
- if not source:
692
- continue
693
- try:
694
- found = extract_default_id(source) or (override_id if source is override_id else None)
695
- except Exception:
696
- found = None
697
- if found:
698
- return found
699
- return None
700
-
701
-
702
- # ----------------- TV metadata -----------------
703
-
704
- # Resolve TV metadata, preferring Cinemeta and falling back to TMDb.
705
- async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
706
- imdb_id, tmdb_id, explicit_imdb_id, use_tmdb = _split_default_id(default_id)
707
- imdb_tv = None
708
- imdb_ep = None
709
-
710
- if not imdb_id and not tmdb_id:
711
- imdb_id = await safe_imdb_search(title, "tvSeries", year)
712
- use_tmdb = not bool(imdb_id)
713
-
714
- if imdb_id and not use_tmdb:
715
- try:
716
- imdb_tv = await _cached_imdb_detail(imdb_id, "tvSeries")
717
- imdb_ep = await _cached_imdb_season(imdb_id, season, episode)
718
- except Exception as e:
719
- LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}] -> {e}")
720
- imdb_tv = imdb_ep = None
721
- use_tmdb = True
722
-
723
- # Guard against Cinemeta returning a wrong hit (skipped for user-supplied ids).
724
- if imdb_tv and not use_tmdb and not explicit_imdb_id:
725
- sim = _title_similarity(title, imdb_tv.get("title", ""))
726
- if sim < _CINEMETA_THRESHOLD:
727
- LOGGER.info(f"IMDb TV title mismatch for '{title}': got '{imdb_tv.get('title', '')}' (sim={sim:.2f}) -> TMDb")
728
- imdb_tv = None
729
- use_tmdb = True
730
-
731
- if use_tmdb or not imdb_tv:
732
- LOGGER.info(f"No valid Cinemeta TV data for '{title}' S{season:02d}E{episode:02d} -> using TMDb")
733
- if not tmdb_id:
734
- tmdb_search = await safe_tmdb_search(title, "tv", year) or (await safe_tmdb_search(title, "tv", None) if year else None)
735
- if not tmdb_search:
736
- LOGGER.info(f"No TMDb TV result for '{title}' S{season:02d}E{episode:02d} (year={year})")
737
- return None
738
- tmdb_id = tmdb_search.id
739
-
740
- tv = await _tmdb_details("tv", tmdb_id)
741
- if not tv:
742
- LOGGER.info(f"TMDb TV details failed for id={tmdb_id} ('{title}')")
743
- return None
744
- ep = await _tmdb_episode_details(tmdb_id, season, episode)
745
- return _build_tmdb_tv_payload(tv, ep, season, episode, quality, encoded_string)
746
-
747
- return _build_imdb_tv_payload(imdb_tv, imdb_ep or {}, imdb_id, title, season, episode, quality, encoded_string)
748
-
749
-
750
- # ----------------- Movie metadata -----------------
751
-
752
- # Resolve movie metadata, preferring Cinemeta and falling back to TMDb.
753
- async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
754
- imdb_id, tmdb_id, explicit_imdb_id, use_tmdb = _split_default_id(default_id)
755
- imdb_details = None
756
-
757
- if not imdb_id and not tmdb_id:
758
- imdb_id = await safe_imdb_search(title, "movie", year)
759
- use_tmdb = not bool(imdb_id)
760
-
761
- if imdb_id and not use_tmdb:
762
- try:
763
- imdb_details = await _cached_imdb_detail(imdb_id, "movie")
764
- except Exception as e:
765
- LOGGER.warning(f"IMDb movie fetch failed [{title}] -> {e}")
766
- imdb_details = None
767
- use_tmdb = True
768
-
769
- # Guard against Cinemeta returning a wrong hit (skipped for user-supplied ids).
770
- if imdb_details and not use_tmdb and not explicit_imdb_id:
771
- sim = _title_similarity(title, imdb_details.get("title", ""))
772
- if sim < _CINEMETA_THRESHOLD:
773
- LOGGER.info(f"IMDb movie title mismatch for '{title}': got '{imdb_details.get('title', '')}' (sim={sim:.2f}) -> TMDb")
774
- imdb_details = None
775
- use_tmdb = True
776
-
777
- if use_tmdb or not imdb_details:
778
- LOGGER.info(f"No valid Cinemeta movie data for '{title}' (year={year}) -> using TMDb")
779
- if not tmdb_id:
780
- tmdb_result = await safe_tmdb_search(title, "movie", year) or (await safe_tmdb_search(title, "movie", None) if year else None)
781
- if not tmdb_result:
782
- LOGGER.info(f"No TMDb movie found for '{title}' (year={year})")
783
- return None
784
- tmdb_id = tmdb_result.id
785
-
786
- movie = await _tmdb_details("movie", tmdb_id)
787
- if not movie:
788
- LOGGER.info(f"TMDb movie details failed for id={tmdb_id} ('{title}')")
789
- return None
790
- return _build_tmdb_movie_payload(movie, quality, encoded_string)
791
-
792
- return _build_imdb_movie_payload(imdb_details, imdb_id, title, quality, encoded_string)
793
-
794
-
795
- # ----------------- Candidate search (used by the /set command UI) -----------------
796
-
797
- # Build a single candidate dict for the picker UI.
798
- def _candidate_entry(source, title, year, imdb_id, tmdb_id, poster, backdrop, subtitle) -> dict:
799
- return {
800
- "source": source,
801
- "title": title or "",
802
- "year": year or "",
803
- "imdb_id": imdb_id,
804
- "tmdb_id": tmdb_id,
805
- "poster": poster,
806
- "backdrop": backdrop,
807
- "subtitle": subtitle,
808
- }
809
-
810
-
811
- # Search IMDb + TMDb for picker candidates of the given media type.
812
- async def _search_candidates(query: str, media_type: str, year: int | None = None, limit: int = 8) -> list[dict]:
813
- query = (query or "").strip()
814
- if not query:
815
- return []
816
-
817
- imdb_type = "movie" if media_type == "movie" else "tvSeries"
818
- results: list[dict] = []
819
- seen: set[tuple[str, str]] = set()
820
-
821
- try:
822
- imdb_hit = await search_title(query=query, type=imdb_type)
823
- if imdb_hit and imdb_hit.get("id"):
824
- seen.add(("imdb", imdb_hit["id"]))
825
- results.append(_candidate_entry(
826
- "imdb", imdb_hit.get("title", ""), imdb_hit.get("year", ""),
827
- imdb_hit.get("id"), imdb_hit.get("moviedb_id"),
828
- imdb_hit.get("poster", ""), "", "IMDb / Cinemeta",
829
- ))
830
- except Exception as e:
831
- LOGGER.warning(f"IMDb {media_type} candidate search failed for '{query}': {e}")
832
-
833
- try:
834
- tmdb_results = await _tmdb_raw_search(query, media_type, year if media_type == "movie" else None)
835
- for item in (tmdb_results or [])[:limit]:
836
- tmdb_id = getattr(item, "id", None)
837
- if not tmdb_id or ("tmdb", str(tmdb_id)) in seen:
838
- continue
839
- seen.add(("tmdb", str(tmdb_id)))
840
- imdb_id = await _tmdb_external_imdb_id(media_type, tmdb_id)
841
- r_title, r_year = _tmdb_title_year(item, media_type)
842
- results.append(_candidate_entry(
843
- "tmdb", r_title, r_year or "", imdb_id, tmdb_id,
844
- format_tmdb_image(getattr(item, "poster_path", None)),
845
- format_tmdb_image(getattr(item, "backdrop_path", None), "original"),
846
- "TMDb",
847
- ))
848
- except Exception as e:
849
- LOGGER.warning(f"TMDb {media_type} candidate search failed for '{query}': {e}")
850
-
851
- return results[:limit]
852
-
853
-
854
- # Search movie candidates for the picker UI.
855
- async def search_movie_candidates(query: str, year: int | None = None, limit: int = 8) -> list[dict]:
856
- return await _search_candidates(query, "movie", year, limit)
857
-
858
-
859
- # Search TV candidates for the picker UI.
860
- async def search_tv_candidates(query: str, limit: int = 8) -> list[dict]:
861
- return await _search_candidates(query, "tv", None, limit)
862
-
863
-
864
- # ----------------- Manual /set command helpers -----------------
865
-
866
- # Reshape an indexer payload into the manual-rescan response shape.
867
- def _to_selection_payload(data: dict, media_type: str) -> dict:
868
- return {
869
- "tmdb_id": data.get("tmdb_id"),
870
- "imdb_id": data.get("imdb_id"),
871
- "title": data.get("title"),
872
- "release_year": data.get("year"),
873
- "rating": data.get("rate"),
874
- "description": data.get("description"),
875
- "poster": data.get("poster"),
876
- "backdrop": data.get("backdrop"),
877
- "logo": data.get("logo"),
878
- "genres": data.get("genres", []),
879
- "cast": data.get("cast", []),
880
- "runtime": data.get("runtime"),
881
- "media_type": media_type,
882
- }
883
-
884
-
885
- # Fetch full movie metadata for a manually selected id.
886
- async def fetch_selected_movie_metadata(selected_id: str) -> dict | None:
887
- selected_id = str(selected_id).strip()
888
- if not selected_id:
889
- return None
890
- data = await fetch_movie_metadata(
891
- title="manual-rescan", encoded_string=None, year=None, quality=None, default_id=selected_id
892
- )
893
- return _to_selection_payload(data, "movie") if data else None
894
-
895
-
896
- # Fetch full TV metadata for a manually selected id.
897
- async def fetch_selected_tv_metadata(selected_id: str) -> dict | None:
898
- selected_id = str(selected_id).strip()
899
- imdb_id, tmdb_id, _, use_tmdb = _split_default_id(selected_id)
900
- if not imdb_id and not tmdb_id:
901
- return None
902
-
903
- imdb_tv = None
904
- if imdb_id and not use_tmdb:
905
- try:
906
- imdb_tv = await get_detail(imdb_id=imdb_id, media_type="tvSeries")
907
- except Exception:
908
- imdb_tv = None
909
- use_tmdb = True
910
-
911
- if use_tmdb or not imdb_tv:
912
- if not tmdb_id and imdb_tv and imdb_tv.get("moviedb_id"):
913
- try:
914
- tmdb_id = int(imdb_tv["moviedb_id"])
915
- except Exception:
916
- tmdb_id = None
917
- if not tmdb_id:
918
- return None
919
-
920
- tv = await _tmdb_details("tv", tmdb_id)
921
- if not tv:
922
- return None
923
- first_air = getattr(tv, "first_air_date", None)
924
- runtime = _format_runtime(tv.episode_run_time[0] if getattr(tv, "episode_run_time", None) else None)
925
- return {
926
- "tmdb_id": tv.id,
927
- "imdb_id": getattr(getattr(tv, "external_ids", None), "imdb_id", None),
928
- "title": tv.name,
929
- "release_year": getattr(first_air, "year", 0) if first_air else 0,
930
- "rating": getattr(tv, "vote_average", 0) or 0,
931
- "description": tv.overview or "",
932
- "poster": format_tmdb_image(tv.poster_path),
933
- "backdrop": format_tmdb_image(tv.backdrop_path, "original"),
934
- "logo": get_tmdb_logo(getattr(tv, "images", None)),
935
- "genres": [g.name for g in (tv.genres or [])],
936
- "cast": _extract_cast(tv),
937
- "runtime": str(runtime),
938
- "media_type": "tv",
939
- }
940
-
941
- images = format_imdb_images(imdb_id)
942
- return {
943
- "tmdb_id": int(imdb_tv.get("moviedb_id")) if imdb_tv.get("moviedb_id") else None,
944
- "imdb_id": imdb_id,
945
- "title": imdb_tv.get("title", ""),
946
- "release_year": imdb_tv.get("releaseDetailed", {}).get("year", 0),
947
- "rating": imdb_tv.get("rating", {}).get("star", 0),
948
- "description": imdb_tv.get("plot", ""),
949
- "poster": images["poster"],
950
- "backdrop": images["backdrop"],
951
- "logo": images["logo"],
952
- "genres": imdb_tv.get("genre", []),
953
- "cast": imdb_tv.get("cast", []),
954
- "runtime": str(imdb_tv.get("runtime") or ""),
955
- "media_type": "tv",
956
- }