Karan Adhikari commited on
Commit
07f63a8
·
unverified ·
1 Parent(s): 2217e9d

Config Setup from WebUI

Browse files
Backend/__main__.py CHANGED
@@ -6,19 +6,16 @@ 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.config import Telegram
10
  from Backend.fastapi import server
 
11
  from Backend.helper.pyro import restart_notification, setup_bot_commands
12
  from Backend.pyrofork.bot import Helper, StreamBot
13
  from Backend.pyrofork.clients import initialize_clients
14
- from Backend.pyrofork.plugins.channels import _load_channels_from_db
15
- from Backend.helper.subscription_checker import subscription_checker_loop
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
- AUTO_SYNC_DELAY_SECONDS, AUTO_CATALOG_ON_STARTUP,
21
- AUTO_CATALOG_FULL_REBUILD_ON_STARTUP
22
  )
23
 
24
 
@@ -31,7 +28,16 @@ async def start_services():
31
 
32
  await db.connect()
33
  await asleep(1.2)
34
-
 
 
 
 
 
 
 
 
 
35
  await StreamBot.start()
36
  StreamBot.username = StreamBot.me.username
37
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
@@ -45,9 +51,6 @@ async def start_services():
45
  LOGGER.info("Initializing Multi Clients...")
46
  await initialize_clients()
47
  await asleep(2)
48
-
49
- await _load_channels_from_db()
50
- await asleep(2)
51
 
52
  await setup_bot_commands(StreamBot)
53
  await asleep(2)
@@ -60,18 +63,12 @@ async def start_services():
60
  link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
61
  loop.create_task(link_checker_task.start())
62
 
63
- if AUTO_CATALOG_ON_STARTUP:
64
- loop.create_task(start_auto_catalog_sync_background(
65
- db,
66
- delay_seconds=AUTO_SYNC_DELAY_SECONDS,
67
- full_rebuild=AUTO_CATALOG_FULL_REBUILD_ON_STARTUP,
68
- ))
69
 
70
  loop.create_task(start_auto_catalog_interval_loop(db))
71
-
72
- if Telegram.SUBSCRIPTION:
73
- loop.create_task(subscription_checker_loop(StreamBot))
74
- LOGGER.info("Subscription Checker Task Started.")
75
 
76
  LOGGER.info("Telegram-Stremio Started Successfully!")
77
  await 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 Helper, StreamBot
13
  from Backend.pyrofork.clients import initialize_clients
14
+ from Backend.helper import subscription_task_manager
 
15
  from Backend.helper.link_checker import DeadLinkChecker
16
  from Backend.fastapi.main import app
17
  from Backend.helper.auto_catalog import (
18
+ start_auto_catalog_sync_background, start_auto_catalog_interval_loop
 
 
19
  )
20
 
21
 
 
28
 
29
  await db.connect()
30
  await asleep(1.2)
31
+
32
+ await SettingsManager.initialize(db)
33
+ await asleep(0.5)
34
+
35
+ try:
36
+ await db.reload_extra_databases(SettingsManager.current().extra_databases)
37
+ except Exception as e:
38
+ LOGGER.error(f"Failed to reconnect extra storage databases on startup: {e}")
39
+ await asleep(0.5)
40
+
41
  await StreamBot.start()
42
  StreamBot.username = StreamBot.me.username
43
  LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
 
51
  LOGGER.info("Initializing Multi Clients...")
52
  await initialize_clients()
53
  await asleep(2)
 
 
 
54
 
55
  await setup_bot_commands(StreamBot)
56
  await asleep(2)
 
63
  link_checker_task = DeadLinkChecker(db, app, check_interval_hours=24)
64
  loop.create_task(link_checker_task.start())
65
 
66
+
67
+ loop.create_task(start_auto_catalog_sync_background(db, delay_seconds=20, full_rebuild=False))
 
 
 
 
68
 
69
  loop.create_task(start_auto_catalog_interval_loop(db))
70
+
71
+ await subscription_task_manager.sync(StreamBot)
 
 
72
 
73
  LOGGER.info("Telegram-Stremio Started Successfully!")
74
  await idle()
Backend/config.py CHANGED
@@ -3,37 +3,37 @@ from dotenv import load_dotenv
3
 
4
  load_dotenv(path.join(path.dirname(path.dirname(__file__)), "config.env"))
5
 
6
- class Telegram:
7
- API_ID = int(getenv("API_ID", "0"))
8
- API_HASH = getenv("API_HASH", "")
9
- BOT_TOKEN = getenv("BOT_TOKEN", "")
10
-
11
- DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
12
 
 
 
 
 
 
13
  HELPER_BOT_TOKEN = getenv("HELPER_BOT_TOKEN", "")
14
 
15
- BASE_URL = getenv("BASE_URL", "").rstrip('/')
16
- PORT = int(getenv("PORT", "8000"))
17
-
18
- AUTH_CHANNEL = [channel.strip() for channel in (getenv("AUTH_CHANNEL") or "").split(",") if channel.strip()]
19
-
20
- TMDB_API = getenv("TMDB_API", "")
21
-
22
- UPSTREAM_REPO = getenv("UPSTREAM_REPO", "")
23
- UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "")
24
-
25
- OWNER_ID = int(getenv("OWNER_ID", "5422223708"))
26
-
27
- REPLACE_MODE = getenv("REPLACE_MODE", "true").lower() == "true"
28
- HIDE_CATALOG = getenv("HIDE_CATALOG", "false").lower() == "true"
29
-
30
- ADMIN_USERNAME = getenv("ADMIN_USERNAME", "admin")
31
- ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "admin")
32
-
33
- SUBSCRIPTION = getenv("SUBSCRIPTION", "false").lower() == "true"
34
- SUBSCRIPTION_GROUP_ID = int(getenv("SUBSCRIPTION_GROUP_ID", "0"))
35
- SUBSCRIPTION_URL = getenv("SUBSCRIPTION_URL", "https://t.me/")
36
- APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
37
 
38
- HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
 
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
  HELPER_BOT_TOKEN = getenv("HELPER_BOT_TOKEN", "")
13
 
14
+ # ── Required: Database URIs ───────────────────────────────────────────────
15
+ DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ SUBSCRIPTION_URL = getenv("SUBSCRIPTION_URL", "https://t.me/")
37
+ APPROVER_IDS = [int(x.strip()) for x in (getenv("APPROVER_IDS") or "").split(",") if x.strip().isdigit()]
38
+ HTTP_PROXY_URL = getenv("HTTP_Proxy_URL", "")
39
  SHOW_PROXY_AND_NON_PROXY_BOTH = getenv("SHOW_ProxyAndNonProxyBoth", "false").lower() == "true"
Backend/fastapi/main.py CHANGED
@@ -12,7 +12,7 @@ from Backend.fastapi.routes.template_routes import (
12
  login_page, login_post, logout, set_theme, dashboard_page,
13
  media_management_page, edit_media_page, public_status_page, stremio_guide_page,
14
  admin_dashboard_page, admin_subscriptions_page, admin_access_page,
15
- custom_catalogs_page
16
  )
17
  from Backend.fastapi.routes.api_routes import (
18
  list_media_api, delete_media_api, update_media_api,
@@ -31,7 +31,8 @@ from Backend.fastapi.routes.api_routes import (
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
  )
36
 
37
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
@@ -372,6 +373,20 @@ async def remove_custom_catalog_item(
372
  ):
373
  return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type)
374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  @app.exception_handler(401)
376
  async def auth_exception_handler(request: Request, exc):
377
  return RedirectResponse(url="/login", status_code=302)
 
12
  login_page, login_post, logout, set_theme, dashboard_page,
13
  media_management_page, edit_media_page, public_status_page, stremio_guide_page,
14
  admin_dashboard_page, admin_subscriptions_page, admin_access_page,
15
+ custom_catalogs_page, settings_page
16
  )
17
  from Backend.fastapi.routes.api_routes import (
18
  list_media_api, delete_media_api, update_media_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
  )
37
 
38
  templates = Jinja2Templates(directory="Backend/fastapi/templates")
 
373
  ):
374
  return await remove_custom_catalog_item_api(catalog_id, tmdb_id, db_index, media_type)
375
 
376
+
377
+
378
+ @app.get("/admin/settings", response_class=HTMLResponse)
379
+ async def admin_settings(request: Request, _: bool = Depends(require_auth)):
380
+ return await settings_page(request, _)
381
+
382
+ @app.get("/api/admin/settings")
383
+ async def get_settings(_: bool = Depends(require_auth)):
384
+ return await get_settings_api()
385
+
386
+ @app.put("/api/admin/settings")
387
+ async def update_settings(payload: dict, _: bool = Depends(require_auth)):
388
+ return await update_settings_api(payload)
389
+
390
  @app.exception_handler(401)
391
  async def auth_exception_handler(request: Request, exc):
392
  return RedirectResponse(url="/login", status_code=302)
Backend/fastapi/routes/api_routes.py CHANGED
@@ -1,9 +1,11 @@
1
  import asyncio
2
  import json
 
3
  from fastapi import Request, Query, HTTPException
4
  from fastapi.responses import StreamingResponse
5
  from Backend import db, StartTime, __version__
6
  from Backend.logger import LOGGER
 
7
  from Backend.helper.pyro import get_readable_time
8
  from Backend.helper.metadata import (
9
  search_movie_candidates,
@@ -21,6 +23,10 @@ from Backend.helper.auto_catalog import (
21
  update_auto_catalog_settings,
22
  )
23
 
 
 
 
 
24
 
25
  # --- API Routes for System Stats ---
26
 
@@ -587,9 +593,6 @@ async def manage_subscriber_api(user_id: int, payload: dict) -> dict:
587
  # --- Access Management API ---
588
 
589
  async def get_all_tokens_api() -> dict:
590
- from Backend import db
591
- from Backend.config import Telegram
592
- from datetime import datetime
593
  try:
594
  tokens = await db.get_all_api_tokens()
595
  now = datetime.utcnow()
@@ -597,7 +600,7 @@ async def get_all_tokens_api() -> dict:
597
 
598
  # Pre-load all subscribers into a dict keyed by user_id for O(1) lookup
599
  subscriber_map = {} # user_id (str) -> user doc
600
- if Telegram.SUBSCRIPTION:
601
  try:
602
  for u in await db.get_all_subscribers():
603
  uid = str(u.get("_id"))
@@ -617,7 +620,7 @@ async def get_all_tokens_api() -> dict:
617
  return f"User {user_id}" if user_id else "Telegram User"
618
 
619
  def build_entry(user_id, user, token_doc):
620
- """Build a unified access entry from optional user + token records."""
621
  expiry = None
622
  sub_status = None
623
  user_found = bool(user)
@@ -633,7 +636,7 @@ async def get_all_tokens_api() -> dict:
633
  expiry = t_expiry
634
 
635
  # Determine status
636
- if Telegram.SUBSCRIPTION:
637
  if not user_found:
638
  is_expired = True
639
  elif sub_status != "active":
@@ -659,7 +662,7 @@ async def get_all_tokens_api() -> dict:
659
  "is_expired": is_expired,
660
  "sub_status": sub_status,
661
  "addon_url": (
662
- f"{Telegram.BASE_URL}/stremio/{token_str}/manifest.json"
663
  if token_str else None
664
  ),
665
  }
@@ -965,3 +968,85 @@ async def update_auto_catalog_settings_api(payload: dict):
965
  raise
966
  except Exception as e:
967
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import asyncio
2
  import json
3
+ from datetime import datetime
4
  from fastapi import Request, Query, HTTPException
5
  from fastapi.responses import StreamingResponse
6
  from Backend import db, StartTime, __version__
7
  from Backend.logger import LOGGER
8
+ from Backend.helper.settings_manager import SettingsManager
9
  from Backend.helper.pyro import get_readable_time
10
  from Backend.helper.metadata import (
11
  search_movie_candidates,
 
23
  update_auto_catalog_settings,
24
  )
25
 
26
+ from Backend.helper.settings_manager import SettingsManager
27
+
28
+
29
+
30
 
31
  # --- API Routes for System Stats ---
32
 
 
593
  # --- Access Management API ---
594
 
595
  async def get_all_tokens_api() -> dict:
 
 
 
596
  try:
597
  tokens = await db.get_all_api_tokens()
598
  now = datetime.utcnow()
 
600
 
601
  # Pre-load all subscribers into a dict keyed by user_id for O(1) lookup
602
  subscriber_map = {} # user_id (str) -> user doc
603
+ if SettingsManager.current().subscription:
604
  try:
605
  for u in await db.get_all_subscribers():
606
  uid = str(u.get("_id"))
 
620
  return f"User {user_id}" if user_id else "Telegram User"
621
 
622
  def build_entry(user_id, user, token_doc):
623
+ """ a unified access entry from optional user + token records."""
624
  expiry = None
625
  sub_status = None
626
  user_found = bool(user)
 
636
  expiry = t_expiry
637
 
638
  # Determine status
639
+ if SettingsManager.current().subscription:
640
  if not user_found:
641
  is_expired = True
642
  elif sub_status != "active":
 
662
  "is_expired": is_expired,
663
  "sub_status": sub_status,
664
  "addon_url": (
665
+ f"{SettingsManager.current().base_url}/stremio/{token_str}/manifest.json"
666
  if token_str else None
667
  ),
668
  }
 
968
  raise
969
  except Exception as e:
970
  raise HTTPException(status_code=500, detail=str(e))
971
+
972
+
973
+
974
+
975
+ # ─────────────────────────────────────────────────────────────────────────────
976
+ # Settings API
977
+ # ─────────────────────────────────────────────────────────────────────────────
978
+
979
+ async def get_settings_api() -> dict:
980
+
981
+ data = SettingsManager.current().to_dict()
982
+ # Never expose the raw password — let the UI know whether one is set
983
+ data["admin_password_set"] = bool(data.get("admin_password"))
984
+ data["admin_password"] = ""
985
+
986
+ try:
987
+ data["database_list"] = db.get_database_list()
988
+ except Exception as e:
989
+ LOGGER.error(f"get_settings_api: could not load database list: {e}")
990
+ data["database_list"] = []
991
+
992
+ return {"settings": data}
993
+
994
+
995
+ async def update_settings_api(payload: dict) -> dict:
996
+
997
+ # Empty password string → don't change it
998
+ if "admin_password" in payload and not str(payload["admin_password"]).strip():
999
+ del payload["admin_password"]
1000
+
1001
+ # ── Type coercion & validation ────────────────────────────────────────────
1002
+ bool_keys = {"replace_mode", "hide_catalog", "subscription", "show_proxy_and_non_proxy_both"}
1003
+ for key in bool_keys:
1004
+ if key in payload:
1005
+ payload[key] = bool(payload[key])
1006
+
1007
+ list_str_keys = {"auth_channels", "multi_tokens", "extra_databases"}
1008
+ for key in list_str_keys:
1009
+ if key in payload:
1010
+ if not isinstance(payload[key], list):
1011
+ raise HTTPException(status_code=400, detail=f"'{key}' must be a list.")
1012
+ payload[key] = [str(v).strip() for v in payload[key] if str(v).strip()]
1013
+
1014
+ if "extra_databases" in payload:
1015
+ for uri in payload["extra_databases"]:
1016
+ if not uri.startswith(("mongodb://", "mongodb+srv://")):
1017
+ raise HTTPException(
1018
+ status_code=400,
1019
+ detail=f"Invalid database URI (must start with mongodb:// or mongodb+srv://): {uri[:30]}…"
1020
+ )
1021
+
1022
+ if "approver_ids" in payload:
1023
+ if not isinstance(payload["approver_ids"], list):
1024
+ raise HTTPException(status_code=400, detail="'approver_ids' must be a list.")
1025
+ try:
1026
+ payload["approver_ids"] = [int(v) for v in payload["approver_ids"] if str(v).strip()]
1027
+ except (ValueError, TypeError):
1028
+ raise HTTPException(status_code=400, detail="All approver_ids must be integers.")
1029
+
1030
+ if "subscription_group_id" in payload:
1031
+ try:
1032
+ payload["subscription_group_id"] = int(payload["subscription_group_id"])
1033
+ except (ValueError, TypeError):
1034
+ raise HTTPException(status_code=400, detail="'subscription_group_id' must be an integer.")
1035
+
1036
+ # Strip whitespace from string fields
1037
+ for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
1038
+ "admin_username", "admin_password", "http_proxy_url", "subscription_url"):
1039
+ if key in payload and isinstance(payload[key], str):
1040
+ payload[key] = payload[key].strip()
1041
+
1042
+ try:
1043
+ reinit_results = await SettingsManager.update(db, payload)
1044
+ return {
1045
+ "message": "Settings saved successfully.",
1046
+ "reinit": reinit_results,
1047
+ }
1048
+ except ValueError as exc:
1049
+ # Raised by db.reload_extra_databases() for unsafe/invalid DB changes
1050
+ raise HTTPException(status_code=400, detail=str(exc))
1051
+ except Exception as exc:
1052
+ raise HTTPException(status_code=500, detail=str(exc))
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -2,6 +2,7 @@ from fastapi import APIRouter, HTTPException, Depends
2
  from typing import Optional
3
  from urllib.parse import unquote, quote
4
  from Backend.config import Telegram
 
5
  from Backend import db, __version__
6
  import PTN
7
  from fastapi.responses import HTMLResponse
@@ -11,7 +12,6 @@ from Backend.fastapi.security.tokens import verify_token
11
  router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
12
 
13
  # --- Configuration ---
14
- BASE_URL = Telegram.BASE_URL
15
  ADDON_NAME = "Telegram"
16
  ADDON_VERSION = __version__
17
  PAGE_SIZE = 15
@@ -108,7 +108,7 @@ def get_resolution_priority(stream_name: str) -> int:
108
 
109
  @router.get("/{token}/manifest.json")
110
  async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
111
- if Telegram.HIDE_CATALOG:
112
  resources = ["stream"]
113
  catalogs = []
114
  else:
@@ -186,7 +186,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
186
  addon_version = ADDON_VERSION
187
  expiry_obj = None
188
 
189
- if Telegram.SUBSCRIPTION:
190
  user_id = token_data.get("user_id")
191
  if user_id:
192
  try:
@@ -208,7 +208,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
208
  except Exception:
209
  pass
210
 
211
- configure_url = f"{Telegram.BASE_URL}/stremio/{token}/configure"
212
 
213
  return {
214
  "id": f"telegram.media.{token[:8]}",
@@ -229,7 +229,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
229
  "key": "manifest_url",
230
  "title": "Your Addon URL (copy to reinstall)",
231
  "type": "text",
232
- "default": f"{Telegram.BASE_URL}/stremio/{token}/manifest.json"
233
  }
234
  ]
235
  }
@@ -238,7 +238,7 @@ async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
238
  @router.get("/{token}/catalog/{media_type}/{id}/{extra:path}.json")
239
  @router.get("/{token}/catalog/{media_type}/{id}.json")
240
  async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] = None, token_data: dict = Depends(verify_token)):
241
- if Telegram.HIDE_CATALOG:
242
  raise HTTPException(status_code=404, detail="Catalog disabled")
243
 
244
  if media_type not in ["movie", "series"]:
@@ -306,7 +306,7 @@ async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str]
306
 
307
  @router.get("/{token}/meta/{media_type}/{id}.json")
308
  async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depends(verify_token)):
309
- if Telegram.HIDE_CATALOG:
310
  raise HTTPException(status_code=404, detail="Catalog disabled")
311
  try:
312
  imdb_id = id
@@ -374,7 +374,7 @@ async def get_streams(
374
  {
375
  "name": "🚫 Subscription Expired",
376
  "title": "Your subscription has expired.\nRenew via the bot to continue watching.",
377
- "url": Telegram.SUBSCRIPTION_URL
378
  }
379
  ]
380
  }
@@ -427,10 +427,10 @@ async def get_streams(
427
  filename, quality_str, size
428
  )
429
 
430
- original_url = f"{BASE_URL}/dl/{token}/{quality.get('id')}/video.mkv"
431
- proxy_url = f"{Telegram.HTTP_PROXY_URL}{original_url}" if Telegram.HTTP_PROXY_URL else None
432
 
433
- if Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH and proxy_url:
434
  streams.append({
435
  "name": f"{stream_name} (Proxy)",
436
  "title": stream_title,
@@ -471,7 +471,7 @@ async def get_streams(
471
 
472
  @router.get("/{token}/configure")
473
  async def configure_addon(token: str):
474
- manifest_url = f"{Telegram.BASE_URL}/stremio/{token}/manifest.json"
475
  web_install_url = f"https://web.stremio.com/#/?addon_manifest={quote(manifest_url, safe='')}"
476
 
477
  # Fetch user info for display
 
2
  from typing import Optional
3
  from urllib.parse import unquote, quote
4
  from Backend.config import Telegram
5
+ from Backend.helper.settings_manager import SettingsManager
6
  from Backend import db, __version__
7
  import PTN
8
  from fastapi.responses import HTMLResponse
 
12
  router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
13
 
14
  # --- Configuration ---
 
15
  ADDON_NAME = "Telegram"
16
  ADDON_VERSION = __version__
17
  PAGE_SIZE = 15
 
108
 
109
  @router.get("/{token}/manifest.json")
110
  async def get_manifest(token: str, token_data: dict = Depends(verify_token)):
111
+ if SettingsManager.current().hide_catalog:
112
  resources = ["stream"]
113
  catalogs = []
114
  else:
 
186
  addon_version = ADDON_VERSION
187
  expiry_obj = None
188
 
189
+ if SettingsManager.current().subscription:
190
  user_id = token_data.get("user_id")
191
  if user_id:
192
  try:
 
208
  except Exception:
209
  pass
210
 
211
+ configure_url = f"{SettingsManager.current().base_url}/stremio/{token}/configure"
212
 
213
  return {
214
  "id": f"telegram.media.{token[:8]}",
 
229
  "key": "manifest_url",
230
  "title": "Your Addon URL (copy to reinstall)",
231
  "type": "text",
232
+ "default": f"{SettingsManager.current().base_url}/stremio/{token}/manifest.json"
233
  }
234
  ]
235
  }
 
238
  @router.get("/{token}/catalog/{media_type}/{id}/{extra:path}.json")
239
  @router.get("/{token}/catalog/{media_type}/{id}.json")
240
  async def get_catalog(token: str, media_type: str, id: str, extra: Optional[str] = None, token_data: dict = Depends(verify_token)):
241
+ if SettingsManager.current().hide_catalog:
242
  raise HTTPException(status_code=404, detail="Catalog disabled")
243
 
244
  if media_type not in ["movie", "series"]:
 
306
 
307
  @router.get("/{token}/meta/{media_type}/{id}.json")
308
  async def get_meta(token: str, media_type: str, id: str, token_data: dict = Depends(verify_token)):
309
+ if SettingsManager.current().hide_catalog:
310
  raise HTTPException(status_code=404, detail="Catalog disabled")
311
  try:
312
  imdb_id = id
 
374
  {
375
  "name": "🚫 Subscription Expired",
376
  "title": "Your subscription has expired.\nRenew via the bot to continue watching.",
377
+ "url": SettingsManager.current().subscription_url
378
  }
379
  ]
380
  }
 
427
  filename, quality_str, size
428
  )
429
 
430
+ original_url = f"{SettingsManager.current().base_url}/dl/{token}/{quality.get('id')}/video.mkv"
431
+ proxy_url = f"{SettingsManager.current().http_proxy_url}{original_url}" if SettingsManager.current().http_proxy_url else None
432
 
433
+ if SettingsManager.current().show_proxy_and_non_proxy_both and proxy_url:
434
  streams.append({
435
  "name": f"{stream_name} (Proxy)",
436
  "title": stream_title,
 
471
 
472
  @router.get("/{token}/configure")
473
  async def configure_addon(token: str):
474
+ manifest_url = f"{SettingsManager.current().base_url}/stremio/{token}/manifest.json"
475
  web_install_url = f"https://web.stremio.com/#/?addon_manifest={quote(manifest_url, safe='')}"
476
 
477
  # Fetch user info for display
Backend/fastapi/routes/template_routes.py CHANGED
@@ -6,6 +6,7 @@ from Backend.fastapi.themes import get_theme, get_all_themes
6
  from Backend import db
7
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
8
  from Backend.helper.pyro import get_readable_time
 
9
  from Backend import StartTime, __version__
10
  import time
11
  from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
@@ -281,3 +282,25 @@ async def custom_catalogs_page(request: Request, _: bool = Depends(require_auth)
281
  "current_theme": theme_name,
282
  "current_user": current_user,
283
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from Backend import db
7
  from Backend.pyrofork.bot import work_loads, multi_clients, StreamBot
8
  from Backend.helper.pyro import get_readable_time
9
+ from Backend.helper.settings_manager import SettingsManager
10
  from Backend import StartTime, __version__
11
  import time
12
  from Backend.helper.custom_dl import ACTIVE_STREAMS, RECENT_STREAMS
 
282
  "current_theme": theme_name,
283
  "current_user": current_user,
284
  })
285
+
286
+
287
+ async def settings_page(request: Request, _: bool = Depends(require_auth)):
288
+ theme_name = request.session.get("theme", "dark_professional")
289
+ theme = get_theme(theme_name)
290
+ current_user = get_current_user(request)
291
+
292
+ settings = SettingsManager.current().to_dict()
293
+ settings["admin_password"] = ""
294
+ try:
295
+ settings["database_list"] = db.get_database_list()
296
+ except Exception:
297
+ settings["database_list"] = []
298
+
299
+ return templates.TemplateResponse("settings.html", {
300
+ "request": request,
301
+ "theme": theme,
302
+ "themes": get_all_themes(),
303
+ "current_theme": theme_name,
304
+ "current_user": current_user,
305
+ "settings": settings,
306
+ })
Backend/fastapi/security/credentials.py CHANGED
@@ -1,28 +1,32 @@
1
- from fastapi import HTTPException, Request
2
- from fastapi.security import HTTPBearer
3
- from Backend.config import Telegram
4
- from typing import Optional
5
- import hashlib
6
-
7
- ADMIN_PASSWORD_HASH = hashlib.sha256(Telegram.ADMIN_PASSWORD.encode()).hexdigest()
8
-
9
- security = HTTPBearer(auto_error=False)
10
-
11
- def verify_password(password: str) -> bool:
12
- return hashlib.sha256(password.encode()).hexdigest() == ADMIN_PASSWORD_HASH
13
 
14
  def verify_credentials(username: str, password: str) -> bool:
15
- return username == Telegram.ADMIN_USERNAME and verify_password(password)
 
 
 
16
 
17
  def is_authenticated(request: Request) -> bool:
18
- return request.session.get("authenticated", False)
 
19
 
20
- def require_auth(request: Request):
21
- if not is_authenticated(request):
22
- raise HTTPException(status_code=401, detail="Authentication required")
23
- return True
24
 
25
- def get_current_user(request: Request) -> Optional[str]:
 
26
  if is_authenticated(request):
27
- return request.session.get("username")
28
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
Backend/fastapi/security/tokens.py CHANGED
@@ -1,7 +1,9 @@
1
  from fastapi import HTTPException
2
  from datetime import datetime
3
  from Backend import db
4
- from Backend.config import Telegram
 
 
5
 
6
  DAILY_LIMIT_VIDEO = "https://bit.ly/3YZFKT5"
7
  MONTHLY_LIMIT_VIDEO = "https://bit.ly/4rfjtgd"
@@ -21,7 +23,7 @@ async def verify_token(token: str):
21
  token_data["subscription_expired"] = False
22
 
23
  # --- Subscription expiry check (only when SUBSCRIPTION feature is enabled) ---
24
- if Telegram.SUBSCRIPTION:
25
  user_id = token_data.get("user_id")
26
  if not user_id:
27
  # Token has no linked user — treat as expired (unverified token)
 
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"
 
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)
Backend/fastapi/templates/base.html CHANGED
@@ -15,7 +15,7 @@
15
  --accent: {{ theme.colors.accent }};
16
  --bg: {{ theme.colors.background }};
17
  --card: {{ theme.colors.card }};
18
- --border: {{ theme.colors.border }}; /* Added theme border */
19
  --text: {{ theme.colors.text }};
20
  --text-sec: {{ theme.colors.text_secondary }};
21
  }
@@ -33,7 +33,6 @@ body {
33
  flex-direction: column;
34
  }
35
 
36
- /* GLASS PANELS */
37
  .glass-panel {
38
  background: color-mix(in srgb, var(--card) 45%, transparent);
39
  backdrop-filter: blur(20px);
@@ -43,7 +42,6 @@ body {
43
 
44
  .glass-pill { border-radius: 9999px; }
45
 
46
- /* NAV LINKS */
47
  .nav-link {
48
  color: var(--text-sec);
49
  border-radius: 9999px;
@@ -55,12 +53,10 @@ body {
55
  font-weight: 600;
56
  }
57
 
58
- /* FIX: Text becomes dark background color when pill is behind it for readability */
59
  .nav-link:hover, .nav-link.active-page {
60
  color: var(--bg) !important;
61
  }
62
 
63
- /* ACTIVE PILL */
64
  #active-pill {
65
  position: absolute;
66
  background: var(--primary);
@@ -70,65 +66,38 @@ body {
70
  box-shadow: 0 0 15px color-mix(in srgb, var(--primary) 40%, transparent);
71
  }
72
 
73
- .toast {
74
- pointer-events: auto;
75
- min-width: 260px;
76
- max-width: 360px;
77
- border: 1px solid var(--border);
78
- background: color-mix(in srgb, var(--card) 88%, transparent);
79
- color: var(--text);
80
- box-shadow: 0 18px 40px rgba(0,0,0,0.2);
81
- border-radius: 1rem;
82
- padding: 0.9rem 1rem;
83
- display: flex;
84
- align-items: flex-start;
85
- gap: 0.75rem;
86
- backdrop-filter: blur(14px);
87
- animation: toast-in 220ms ease-out;
88
- }
89
 
90
- .toast.success { border-color: color-mix(in srgb, #22c55e 35%, var(--border)); }
91
- .toast.error { border-color: color-mix(in srgb, #ef4444 35%, var(--border)); }
92
- .toast.info { border-color: color-mix(in srgb, var(--primary) 35%, var(--border)); }
93
 
94
- .toast-title {
95
- font-weight: 800;
96
- font-size: 0.9rem;
97
- line-height: 1.2;
98
- }
99
 
100
- .toast-message {
101
- margin-top: 0.15rem;
102
- font-size: 0.82rem;
103
- color: var(--text-secondary);
104
- line-height: 1.35;
105
- }
106
 
107
- @keyframes toast-in {
108
- from { opacity: 0; transform: translateY(-10px) scale(0.98); }
109
- to { opacity: 1; transform: translateY(0) scale(1); }
110
- }
111
-
112
- @keyframes toast-out {
113
- from { opacity: 1; transform: translateY(0) scale(1); }
114
- to { opacity: 0; transform: translateY(-8px) scale(0.98); }
115
- }
116
-
117
- /* Mobile improvement */
118
  @media (max-width: 640px) {
119
- #toast-container {
120
- top: 5rem;
121
- left: 0.75rem;
122
- right: 0.75rem;
123
- }
124
-
125
- .toast {
126
- max-width: none;
127
- width: 100%;
128
- }
129
  }
130
-
131
- /* THEME SELECT */
132
  .theme-select {
133
  appearance: none;
134
  background: var(--bg);
@@ -140,14 +109,12 @@ body {
140
  cursor: pointer;
141
  }
142
 
143
- /* OVERLAY */
144
  #overlay {
145
  backdrop-filter: blur(8px);
146
  background: rgba(0,0,0,0.4);
147
  transition: opacity 0.3s ease;
148
  }
149
 
150
- /* SCROLL ANIMATION - Fixed "Jumping" issue */
151
  .nav-scrolled {
152
  transform: translate(-50%, -5px) scale(0.97);
153
  background: color-mix(in srgb, var(--card) 80%, transparent);
@@ -201,6 +168,7 @@ tailwind.config = {
201
  <a href="/admin/dashboard" class="nav-link">Admin</a>
202
  <a href="/admin/subscriptions" class="nav-link">Subs</a>
203
  <a href="/admin/access" class="nav-link">Access</a>
 
204
  </div>
205
  {% endif %}
206
 
@@ -234,6 +202,12 @@ tailwind.config = {
234
  </select>
235
  </form>
236
 
 
 
 
 
 
 
237
  <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">
238
  Logout
239
  </a>
@@ -254,6 +228,8 @@ tailwind.config = {
254
  <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>
255
  <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>
256
  <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>
 
 
257
  </div>
258
  </div>
259
  </nav>
@@ -271,8 +247,7 @@ tailwind.config = {
271
  </div>
272
  </footer>
273
 
274
- <div id="toast-container"
275
- class="fixed top-4 right-4 z-[9999] space-y-3 pointer-events-none"></div>
276
 
277
  <script>
278
  const btn = document.getElementById('menu-btn');
@@ -287,7 +262,6 @@ const navContainer = document.getElementById('nav-container');
287
  let isMenuOpen = false;
288
  let isUserOpen = false;
289
 
290
- // --- MENU & DROPDOWN TOGGLE ---
291
  function toggleMenu() {
292
  isMenuOpen = !isMenuOpen;
293
  if(isUserOpen) closeUser();
@@ -331,48 +305,47 @@ function checkOverlay() {
331
  overlay.classList.add("pointer-events-none");
332
  }
333
  }
334
- function showToast(message, type = 'info', title = '') {
335
- const container = document.getElementById('toast-container');
336
- if (!container) return;
337
-
338
- const toast = document.createElement('div');
339
- toast.className = `toast ${type}`;
340
-
341
- const icon = type === 'success'
342
- ? 'fa-circle-check'
343
- : type === 'error'
344
- ? 'fa-triangle-exclamation'
345
- : 'fa-circle-info';
346
-
347
- toast.innerHTML = `
348
- <i class="fa-solid ${icon} mt-0.5"></i>
349
- <div class="min-w-0">
350
- ${title ? `<div class="toast-title">${escapeHtml(title)}</div>` : ''}
351
- <div class="toast-message">${escapeHtml(message)}</div>
352
- </div>
353
- `;
354
 
355
- container.appendChild(toast);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
 
 
 
 
357
  setTimeout(() => {
358
- toast.style.animation = 'toast-out 180ms ease-in forwards';
359
- setTimeout(() => {
360
- if (toast.parentNode) toast.parentNode.removeChild(toast);
361
- }, 200);
362
- }, 2600);
363
- }
 
 
 
 
 
 
 
364
 
365
- // GLOBAL SAFE ESCAPE (important!)
366
- function escapeHtml(str) {
367
- return String(str || '')
368
- .replace(/&/g, '&amp;')
369
- .replace(/</g, '&lt;')
370
- .replace(/>/g, '&gt;')
371
- .replace(/"/g, '&quot;')
372
- .replace(/'/g, '&#039;');
373
- }
374
-
375
- // Events
376
  if(btn) btn.onclick = toggleMenu;
377
  if(userBtn) userBtn.onclick = toggleUser;
378
  overlay.onclick = () => { closeMenu(); closeUser(); };
@@ -391,7 +364,6 @@ if (userDropdown) {
391
  userDropdown.addEventListener("click", e => e.stopPropagation());
392
  }
393
 
394
- // --- SMART ACTIVE PILL LOGIC ---
395
  const links = document.querySelectorAll(".nav-link");
396
  const pill = document.getElementById("active-pill");
397
  let activeLink = null;
@@ -419,7 +391,6 @@ links.forEach(l => {
419
  l.addEventListener("mouseenter", () => movePill(l));
420
  });
421
 
422
- // Returns pill to active page when mouse leaves the navbar
423
  if(navContainer) {
424
  navContainer.addEventListener("mouseleave", () => {
425
  if(activeLink) movePill(activeLink);
 
15
  --accent: {{ theme.colors.accent }};
16
  --bg: {{ theme.colors.background }};
17
  --card: {{ theme.colors.card }};
18
+ --border: {{ theme.colors.border }};
19
  --text: {{ theme.colors.text }};
20
  --text-sec: {{ theme.colors.text_secondary }};
21
  }
 
33
  flex-direction: column;
34
  }
35
 
 
36
  .glass-panel {
37
  background: color-mix(in srgb, var(--card) 45%, transparent);
38
  backdrop-filter: blur(20px);
 
42
 
43
  .glass-pill { border-radius: 9999px; }
44
 
 
45
  .nav-link {
46
  color: var(--text-sec);
47
  border-radius: 9999px;
 
53
  font-weight: 600;
54
  }
55
 
 
56
  .nav-link:hover, .nav-link.active-page {
57
  color: var(--bg) !important;
58
  }
59
 
 
60
  #active-pill {
61
  position: absolute;
62
  background: var(--primary);
 
66
  box-shadow: 0 0 15px color-mix(in srgb, var(--primary) 40%, transparent);
67
  }
68
 
69
+ .toast {
70
+ pointer-events: auto;
71
+ min-width: 260px;
72
+ max-width: 360px;
73
+ border: 1px solid var(--border);
74
+ background: color-mix(in srgb, var(--card) 88%, transparent);
75
+ color: var(--text);
76
+ box-shadow: 0 18px 40px rgba(0,0,0,0.2);
77
+ border-radius: 1rem;
78
+ padding: 0.9rem 1rem;
79
+ display: flex;
80
+ align-items: flex-start;
81
+ gap: 0.75rem;
82
+ backdrop-filter: blur(14px);
83
+ animation: toast-in 220ms ease-out;
84
+ }
85
 
86
+ .toast.success { border-color: color-mix(in srgb, #22c55e 35%, var(--border)); }
87
+ .toast.error { border-color: color-mix(in srgb, #ef4444 35%, var(--border)); }
88
+ .toast.info { border-color: color-mix(in srgb, var(--primary) 35%, var(--border)); }
89
 
90
+ .toast-title { font-weight: 800; font-size: 0.9rem; line-height: 1.2; }
91
+ .toast-message { margin-top: 0.15rem; font-size: 0.82rem; color: var(--text-secondary); line-height: 1.35; }
 
 
 
92
 
93
+ @keyframes toast-in { from { opacity: 0; transform: translateY(-10px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
94
+ @keyframes toast-out { from { opacity: 1; transform: translateY(0) scale(1); } to { opacity: 0; transform: translateY(-8px) scale(0.98); } }
 
 
 
 
95
 
 
 
 
 
 
 
 
 
 
 
 
96
  @media (max-width: 640px) {
97
+ #toast-container { top: 5rem; left: 0.75rem; right: 0.75rem; }
98
+ .toast { max-width: none; width: 100%; }
 
 
 
 
 
 
 
 
99
  }
100
+
 
101
  .theme-select {
102
  appearance: none;
103
  background: var(--bg);
 
109
  cursor: pointer;
110
  }
111
 
 
112
  #overlay {
113
  backdrop-filter: blur(8px);
114
  background: rgba(0,0,0,0.4);
115
  transition: opacity 0.3s ease;
116
  }
117
 
 
118
  .nav-scrolled {
119
  transform: translate(-50%, -5px) scale(0.97);
120
  background: color-mix(in srgb, var(--card) 80%, transparent);
 
168
  <a href="/admin/dashboard" class="nav-link">Admin</a>
169
  <a href="/admin/subscriptions" class="nav-link">Subs</a>
170
  <a href="/admin/access" class="nav-link">Access</a>
171
+ <a href="/admin/settings" class="nav-link">Settings</a>
172
  </div>
173
  {% endif %}
174
 
 
202
  </select>
203
  </form>
204
 
205
+ <a href="/admin/settings"
206
+ class="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold mb-2 transition-all"
207
+ style="background:color-mix(in srgb,var(--primary) 12%,transparent);color:var(--primary)">
208
+ <i class="fa-solid fa-gear"></i> Settings
209
+ </a>
210
+
211
  <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">
212
  Logout
213
  </a>
 
228
  <a href="/admin/dashboard" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-chart-line"></i> Admin</a>
229
  <a href="/admin/subscriptions" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-credit-card"></i> Subs</a>
230
  <a href="/admin/access" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-shield"></i> Access</a>
231
+ <!-- ↓ NEW -->
232
+ <a href="/admin/settings" class="px-4 py-3 rounded-xl hover:bg-primary hover:text-background transition flex items-center gap-3 font-semibold"><i class="fa-solid fa-gear"></i> Settings</a>
233
  </div>
234
  </div>
235
  </nav>
 
247
  </div>
248
  </footer>
249
 
250
+ <div id="toast-container" class="fixed top-4 right-4 z-[9999] space-y-3 pointer-events-none"></div>
 
251
 
252
  <script>
253
  const btn = document.getElementById('menu-btn');
 
262
  let isMenuOpen = false;
263
  let isUserOpen = false;
264
 
 
265
  function toggleMenu() {
266
  isMenuOpen = !isMenuOpen;
267
  if(isUserOpen) closeUser();
 
305
  overlay.classList.add("pointer-events-none");
306
  }
307
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
+ function showToast(message, type = 'info', title = '') {
310
+ const container = document.getElementById('toast-container');
311
+ if (!container) return;
312
+
313
+ const toast = document.createElement('div');
314
+ toast.className = `toast ${type}`;
315
+
316
+ const icon = type === 'success'
317
+ ? 'fa-circle-check'
318
+ : type === 'error'
319
+ ? 'fa-triangle-exclamation'
320
+ : 'fa-circle-info';
321
+
322
+ toast.innerHTML = `
323
+ <i class="fa-solid ${icon} mt-0.5"></i>
324
+ <div class="min-w-0">
325
+ ${title ? `<div class="toast-title">${escapeHtml(title)}</div>` : ''}
326
+ <div class="toast-message">${escapeHtml(message)}</div>
327
+ </div>
328
+ `;
329
 
330
+ container.appendChild(toast);
331
+
332
+ setTimeout(() => {
333
+ toast.style.animation = 'toast-out 180ms ease-in forwards';
334
  setTimeout(() => {
335
+ if (toast.parentNode) toast.parentNode.removeChild(toast);
336
+ }, 200);
337
+ }, 2600);
338
+ }
339
+
340
+ function escapeHtml(str) {
341
+ return String(str || '')
342
+ .replace(/&/g, '&amp;')
343
+ .replace(/</g, '&lt;')
344
+ .replace(/>/g, '&gt;')
345
+ .replace(/"/g, '&quot;')
346
+ .replace(/'/g, '&#039;');
347
+ }
348
 
 
 
 
 
 
 
 
 
 
 
 
349
  if(btn) btn.onclick = toggleMenu;
350
  if(userBtn) userBtn.onclick = toggleUser;
351
  overlay.onclick = () => { closeMenu(); closeUser(); };
 
364
  userDropdown.addEventListener("click", e => e.stopPropagation());
365
  }
366
 
 
367
  const links = document.querySelectorAll(".nav-link");
368
  const pill = document.getElementById("active-pill");
369
  let activeLink = null;
 
391
  l.addEventListener("mouseenter", () => movePill(l));
392
  });
393
 
 
394
  if(navContainer) {
395
  navContainer.addEventListener("mouseleave", () => {
396
  if(activeLink) movePill(activeLink);
Backend/fastapi/templates/settings.html ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Settings — TG Stremio{% endblock %}
3
+
4
+ {% block content %}
5
+
6
+ <style>
7
+ /* ── Toggle switch ───────────────────────────────────────────────────────── */
8
+ .toggle-wrap { display: flex; align-items: center; gap: 0.75rem; cursor: pointer; }
9
+ .toggle-input { position: absolute; opacity: 0; width: 0; height: 0; }
10
+ .toggle-track {
11
+ display: inline-block; width: 3rem; height: 1.625rem;
12
+ border-radius: 9999px; background: var(--border);
13
+ position: relative; transition: background 0.2s ease; flex-shrink: 0;
14
+ }
15
+ .toggle-track::after {
16
+ content: ''; position: absolute;
17
+ top: 3px; left: 3px;
18
+ width: 20px; height: 20px;
19
+ border-radius: 50%; background: white;
20
+ transition: transform 0.2s ease;
21
+ box-shadow: 0 1px 4px rgba(0,0,0,0.3);
22
+ }
23
+ .toggle-input:checked + .toggle-track { background: var(--primary); }
24
+ .toggle-input:checked + .toggle-track::after { transform: translateX(1.375rem); }
25
+ .toggle-label { font-size: 0.9rem; color: var(--text); user-select: none; }
26
+
27
+ /* ── Section cards ───────────────────────────────────────────────────────── */
28
+ .settings-card {
29
+ background: color-mix(in srgb, var(--card) 45%, transparent);
30
+ backdrop-filter: blur(20px);
31
+ border: 1px solid var(--border);
32
+ border-radius: 1.5rem;
33
+ padding: 1.5rem 1.75rem;
34
+ box-shadow: 0 8px 32px rgba(0,0,0,0.15);
35
+ }
36
+ .settings-card h2 {
37
+ font-size: 1rem; font-weight: 800;
38
+ letter-spacing: 0.05em; text-transform: uppercase;
39
+ color: var(--primary); margin-bottom: 1.25rem;
40
+ display: flex; align-items: center; gap: 0.5rem;
41
+ }
42
+
43
+ /* ── Inputs ──────────────────────────────────────────────────────────────── */
44
+ .s-input {
45
+ width: 100%;
46
+ background: color-mix(in srgb, var(--bg) 70%, transparent);
47
+ border: 1px solid var(--border);
48
+ color: var(--text);
49
+ border-radius: 0.75rem;
50
+ padding: 0.6rem 1rem;
51
+ font-size: 0.88rem;
52
+ outline: none;
53
+ transition: border-color 0.2s;
54
+ }
55
+ .s-input:focus { border-color: var(--primary); }
56
+ .s-label {
57
+ display: block; font-size: 0.78rem; font-weight: 700;
58
+ color: var(--text-sec); text-transform: uppercase;
59
+ letter-spacing: 0.04em; margin-bottom: 0.4rem;
60
+ }
61
+
62
+ /* ── Multi-value list ────────────────────────────────────────────────────── */
63
+ .multi-list-items { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.6rem; }
64
+ .multi-item {
65
+ display: flex; align-items: center; gap: 0.5rem;
66
+ }
67
+ .multi-item .s-input { flex: 1; }
68
+ .remove-btn {
69
+ width: 2rem; height: 2rem; flex-shrink: 0;
70
+ background: rgba(239,68,68,0.12); border: 1px solid rgba(239,68,68,0.25);
71
+ color: #ef4444; border-radius: 0.5rem;
72
+ font-size: 1rem; line-height: 1;
73
+ cursor: pointer; transition: background 0.15s;
74
+ display: flex; align-items: center; justify-content: center;
75
+ }
76
+ .remove-btn:hover { background: rgba(239,68,68,0.25); }
77
+ .add-row { display: flex; gap: 0.5rem; }
78
+ .add-btn {
79
+ flex-shrink: 0; padding: 0.6rem 1rem;
80
+ background: color-mix(in srgb, var(--primary) 15%, transparent);
81
+ border: 1px solid color-mix(in srgb, var(--primary) 40%, transparent);
82
+ color: var(--primary); border-radius: 0.75rem;
83
+ font-size: 0.82rem; font-weight: 700; cursor: pointer;
84
+ transition: background 0.15s; white-space: nowrap;
85
+ }
86
+ .add-btn:hover { background: color-mix(in srgb, var(--primary) 28%, transparent); }
87
+
88
+ /* ── Grid helpers ────────────────────────────────────────────────────────── */
89
+ .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
90
+ @media (max-width: 640px) { .grid-2 { grid-template-columns: 1fr; } }
91
+ .divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }
92
+ </style>
93
+
94
+ <!-- Page header -->
95
+ <div class="flex items-center justify-between mb-8">
96
+ <div>
97
+ <h1 class="text-3xl font-extrabold">Settings</h1>
98
+ <p class="mt-1 text-sm" style="color:var(--text-sec)">
99
+ Runtime configuration — stored in the database, no restart needed.
100
+ </p>
101
+ </div>
102
+ <button id="save-btn" onclick="saveSettings()"
103
+ class="flex items-center gap-2 px-6 py-2.5 rounded-full font-bold text-sm text-white shadow-lg transition-all"
104
+ style="background:var(--primary); box-shadow:0 0 18px color-mix(in srgb,var(--primary) 40%,transparent)">
105
+ <i class="fa-solid fa-floppy-disk"></i>
106
+ <span id="save-label">Save Settings</span>
107
+ </button>
108
+ </div>
109
+
110
+ <div class="space-y-6" id="settings-root">
111
+
112
+ <!-- ── General ─────────────────────────────────────────────────────── -->
113
+ <div class="settings-card">
114
+ <h2><i class="fa-solid fa-sliders"></i> General</h2>
115
+ <div class="space-y-4">
116
+ <label class="toggle-wrap">
117
+ <input type="checkbox" class="toggle-input" id="replace_mode"
118
+ {% if settings.replace_mode %}checked{% endif %}>
119
+ <span class="toggle-track"></span>
120
+ <span class="toggle-label">
121
+ <strong>Replace Mode</strong>
122
+ <span style="color:var(--text-sec);font-size:0.8rem;display:block">
123
+ Overwrite existing media entries on re-index
124
+ </span>
125
+ </span>
126
+ </label>
127
+ <label class="toggle-wrap">
128
+ <input type="checkbox" class="toggle-input" id="hide_catalog"
129
+ {% if settings.hide_catalog %}checked{% endif %}>
130
+ <span class="toggle-track"></span>
131
+ <span class="toggle-label">
132
+ <strong>Hide Catalog</strong>
133
+ <span style="color:var(--text-sec);font-size:0.8rem;display:block">
134
+ Hide the public Stremio catalog from unauthenticated users
135
+ </span>
136
+ </span>
137
+ </label>
138
+ </div>
139
+ </div>
140
+
141
+ <!-- ── Authentication ──────────────────────────────────────────────── -->
142
+ <div class="settings-card">
143
+ <h2><i class="fa-solid fa-shield-halved"></i> Admin Authentication</h2>
144
+ <div class="grid-2">
145
+ <div>
146
+ <label class="s-label" for="admin_username">Admin Username</label>
147
+ <input type="text" id="admin_username" class="s-input"
148
+ value="{{ settings.admin_username }}" autocomplete="off">
149
+ </div>
150
+ <div>
151
+ <label class="s-label" for="admin_password">Admin Password</label>
152
+ <div style="position:relative">
153
+ <input type="password" id="admin_password" class="s-input"
154
+ placeholder="Leave blank to keep current password"
155
+ style="padding-right:2.5rem" autocomplete="new-password">
156
+ <button type="button" onclick="togglePwdVisibility()"
157
+ style="position:absolute;right:0.75rem;top:50%;transform:translateY(-50%);
158
+ background:none;border:none;color:var(--text-sec);cursor:pointer">
159
+ <i class="fa-solid fa-eye" id="eye-icon"></i>
160
+ </button>
161
+ </div>
162
+ <p style="font-size:0.75rem;color:var(--text-sec);margin-top:0.3rem">
163
+ {% if settings.admin_password_set is defined and settings.admin_password_set %}
164
+ <i class="fa-solid fa-circle-check" style="color:#22c55e"></i> Password is set
165
+ {% endif %}
166
+ </p>
167
+ </div>
168
+ </div>
169
+
170
+ <hr class="divider">
171
+
172
+ <!-- Auth Channels -->
173
+ <label class="s-label">AUTH_CHANNELS
174
+ <span style="font-weight:400;text-transform:none;letter-spacing:0">
175
+ — users must be a member of at least one</span>
176
+ </label>
177
+ <div class="multi-list-items" id="auth_channels_items">
178
+ {% for ch in settings.auth_channels %}
179
+ <div class="multi-item">
180
+ <input type="text" class="s-input" value="{{ ch }}" data-list="auth_channels">
181
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
182
+ <i class="fa-solid fa-xmark"></i>
183
+ </button>
184
+ </div>
185
+ {% endfor %}
186
+ </div>
187
+ <div class="add-row">
188
+ <input type="text" id="auth_channels_new" class="s-input"
189
+ placeholder="Channel username or -100xxxxx ID"
190
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('auth_channels')}">
191
+ <button class="add-btn" onclick="addItem('auth_channels')">+ Add Channel</button>
192
+ </div>
193
+ </div>
194
+
195
+ <!-- ── Media & Content ─────────────────────────────────────────────── -->
196
+ <div class="settings-card">
197
+ <h2><i class="fa-solid fa-film"></i> Media &amp; Content</h2>
198
+ <div class="grid-2">
199
+ <div>
200
+ <label class="s-label" for="tmdb_api">TMDB API Key</label>
201
+ <input type="text" id="tmdb_api" class="s-input"
202
+ value="{{ settings.tmdb_api }}" autocomplete="off"
203
+ placeholder="Your TMDB v3 API key" spellcheck="false">
204
+ </div>
205
+ <div>
206
+ <label class="s-label" for="base_url">Base URL</label>
207
+ <input type="url" id="base_url" class="s-input"
208
+ value="{{ settings.base_url }}"
209
+ placeholder="https://your-domain.com">
210
+ </div>
211
+ </div>
212
+ <hr class="divider">
213
+ <div class="grid-2">
214
+ <div>
215
+ <label class="s-label" for="upstream_repo">Upstream Repo</label>
216
+ <input type="text" id="upstream_repo" class="s-input"
217
+ value="{{ settings.upstream_repo }}"
218
+ placeholder="user/repo">
219
+ </div>
220
+ <div>
221
+ <label class="s-label" for="upstream_branch">Upstream Branch</label>
222
+ <input type="text" id="upstream_branch" class="s-input"
223
+ value="{{ settings.upstream_branch }}"
224
+ placeholder="main">
225
+ </div>
226
+ </div>
227
+ </div>
228
+
229
+ <!-- ── Subscription ────────────────────────────────────────────────── -->
230
+ <div class="settings-card">
231
+ <h2><i class="fa-solid fa-credit-card"></i> Subscription</h2>
232
+ <label class="toggle-wrap" style="margin-bottom:1.25rem">
233
+ <input type="checkbox" class="toggle-input" id="subscription"
234
+ {% if settings.subscription %}checked{% endif %}
235
+ onchange="toggleSubFields()">
236
+ <span class="toggle-track"></span>
237
+ <span class="toggle-label">
238
+ <strong>Enable Subscription System</strong>
239
+ <span style="color:var(--text-sec);font-size:0.8rem;display:block">
240
+ Restrict Stremio access to subscribed members
241
+ </span>
242
+ </span>
243
+ </label>
244
+
245
+ <div id="sub-fields" style="{% if not settings.subscription %}display:none{% endif %}">
246
+ <div class="grid-2" style="margin-bottom:1rem">
247
+ <div>
248
+ <label class="s-label" for="subscription_group_id">Subscription Group ID</label>
249
+ <input type="number" id="subscription_group_id" class="s-input"
250
+ value="{{ settings.subscription_group_id }}"
251
+ placeholder="-100xxxxxxxx">
252
+ </div>
253
+ <div>
254
+ <label class="s-label" for="subscription_url">Subscription URL</label>
255
+ <input type="url" id="subscription_url" class="s-input"
256
+ value="{{ settings.subscription_url }}"
257
+ placeholder="https://t.me/your_group">
258
+ </div>
259
+ </div>
260
+
261
+ <!-- Approver IDs -->
262
+ <label class="s-label">APPROVER_IDS
263
+ <span style="font-weight:400;text-transform:none;letter-spacing:0">
264
+ — Telegram user IDs allowed to approve subscriptions</span>
265
+ </label>
266
+ <div class="multi-list-items" id="approver_ids_items">
267
+ {% for uid in settings.approver_ids %}
268
+ <div class="multi-item">
269
+ <input type="number" class="s-input" value="{{ uid }}" data-list="approver_ids">
270
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
271
+ <i class="fa-solid fa-xmark"></i>
272
+ </button>
273
+ </div>
274
+ {% endfor %}
275
+ </div>
276
+ <div class="add-row">
277
+ <input type="number" id="approver_ids_new" class="s-input"
278
+ placeholder="Telegram user ID (numeric)"
279
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('approver_ids')}">
280
+ <button class="add-btn" onclick="addItem('approver_ids')">+ Add Approver</button>
281
+ </div>
282
+ </div>
283
+ </div>
284
+
285
+ <!-- ── Proxy ───────────────────────────────────────────────────────── -->
286
+ <div class="settings-card">
287
+ <h2><i class="fa-solid fa-network-wired"></i> Proxy Settings</h2>
288
+ <div style="margin-bottom:1rem">
289
+ <label class="s-label" for="http_proxy_url">HTTP Proxy URL</label>
290
+ <input type="url" id="http_proxy_url" class="s-input"
291
+ value="{{ settings.http_proxy_url }}"
292
+ placeholder="http://user:pass@host:port or leave empty">
293
+ </div>
294
+ <label class="toggle-wrap">
295
+ <input type="checkbox" class="toggle-input" id="show_proxy_and_non_proxy_both"
296
+ {% if settings.show_proxy_and_non_proxy_both %}checked{% endif %}>
297
+ <span class="toggle-track"></span>
298
+ <span class="toggle-label">
299
+ <strong>Show Proxy &amp; Non-Proxy Streams</strong>
300
+ <span style="color:var(--text-sec);font-size:0.8rem;display:block">
301
+ Expose both proxied and direct stream links in Stremio
302
+ </span>
303
+ </span>
304
+ </label>
305
+ </div>
306
+
307
+ <!-- ── Databases ────────────────────────────────────────────────────── -->
308
+ <div class="settings-card">
309
+ <h2><i class="fa-solid fa-database"></i> Databases</h2>
310
+ <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
311
+ Tracking and Storage 1 are required to boot the app and can't be edited
312
+ here. Additional storage databases connect/disconnect instantly when
313
+ saved — no restart needed. For data-safety reasons you can only
314
+ <strong>append</strong> new databases or <strong>remove from the end</strong>
315
+ of the list — editing or deleting one in the middle is rejected on save,
316
+ since existing media documents reference databases by position.
317
+ </p>
318
+
319
+ <!-- Locked databases (rendered from db.get_database_list()) -->
320
+ <div class="space-y-2 mb-4">
321
+ {% for entry in settings.database_list %}
322
+ {% if entry.locked %}
323
+ <div class="multi-item" style="opacity:0.65">
324
+ <input type="text" class="s-input" value="{{ entry.uri_masked }}" disabled
325
+ style="cursor:not-allowed">
326
+ <span style="flex-shrink:0;font-size:0.7rem;font-weight:700;text-transform:uppercase;
327
+ padding:0.4rem 0.7rem;border-radius:0.5rem;
328
+ background:color-mix(in srgb,var(--text-sec) 15%,transparent);
329
+ color:var(--text-sec);white-space:nowrap">
330
+ <i class="fa-solid fa-lock"></i>
331
+ {{ "Tracking" if entry.type == "tracking" else "Storage 1" }}
332
+ </span>
333
+ </div>
334
+ {% endif %}
335
+ {% endfor %}
336
+ </div>
337
+
338
+ <hr class="divider">
339
+
340
+ <label class="s-label">EXTRA STORAGE DATABASES
341
+ <span style="font-weight:400;text-transform:none;letter-spacing:0">
342
+ — additional Mongo URIs for media storage rotation</span>
343
+ </label>
344
+ <div class="multi-list-items" id="extra_databases_items">
345
+ {% for entry in settings.database_list %}
346
+ {% if not entry.locked %}
347
+ <div class="multi-item">
348
+ <input type="text" class="s-input" value="{{ entry.full_uri }}" spellcheck="false"
349
+ data-list="extra_databases" placeholder="mongodb+srv://user:pass@host/...">
350
+ <span title="{{ 'Connected' if entry.connected else 'Disconnected' }}"
351
+ style="flex-shrink:0;width:0.6rem;height:0.6rem;border-radius:50%;
352
+ background:{{ '#22c55e' if entry.connected else '#ef4444' }}"></span>
353
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove (only safe from the end of the list)">
354
+ <i class="fa-solid fa-xmark"></i>
355
+ </button>
356
+ </div>
357
+ {% endif %}
358
+ {% endfor %}
359
+ </div>
360
+ <div class="add-row">
361
+ <input type="text" id="extra_databases_new" class="s-input" spellcheck="false"
362
+ placeholder="mongodb+srv://user:pass@host/..."
363
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('extra_databases')}">
364
+ <button class="add-btn" onclick="addItem('extra_databases')">+ Add Database</button>
365
+ </div>
366
+ </div>
367
+
368
+ <!-- ── Multi-Token Clients ─────────────────────────────────────────── -->
369
+ <div class="settings-card">
370
+ <h2><i class="fa-brands fa-telegram"></i> Multi-Token Clients</h2>
371
+ <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
372
+ Additional bot tokens used for parallel streaming. Changes reinitialise
373
+ the client pool immediately (no restart needed).
374
+ </p>
375
+ <div class="multi-list-items" id="multi_tokens_items">
376
+ {% for tok in settings.multi_tokens %}
377
+ <div class="multi-item">
378
+ <input type="text" class="s-input" value="{{ tok }}" spellcheck="false"
379
+ data-list="multi_tokens" placeholder="Bot token">
380
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
381
+ <i class="fa-solid fa-xmark"></i>
382
+ </button>
383
+ </div>
384
+ {% endfor %}
385
+ </div>
386
+ <div class="add-row">
387
+ <input type="text" id="multi_tokens_new" class="s-input" spellcheck="false"
388
+ placeholder="New bot token (1234567890:ABCdef…)"
389
+ onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('multi_tokens')}">
390
+ <button class="add-btn" onclick="addItem('multi_tokens')">+ Add Token</button>
391
+ </div>
392
+ </div>
393
+
394
+ </div><!-- /settings-root -->
395
+
396
+ <!-- Floating save (mobile) -->
397
+ <div class="fixed bottom-6 right-6 md:hidden z-50">
398
+ <button onclick="saveSettings()"
399
+ class="w-14 h-14 rounded-full flex items-center justify-center text-white shadow-xl"
400
+ style="background:var(--primary)">
401
+ <i class="fa-solid fa-floppy-disk text-lg"></i>
402
+ </button>
403
+ </div>
404
+
405
+ <script>
406
+ /* ── Toggle sub-fields visibility ─────────────────────────────────────── */
407
+ function toggleSubFields() {
408
+ const enabled = document.getElementById('subscription').checked;
409
+ document.getElementById('sub-fields').style.display = enabled ? '' : 'none';
410
+ }
411
+
412
+ /* ── Password visibility ──────────────────────────────────────────────── */
413
+ function togglePwdVisibility() {
414
+ const input = document.getElementById('admin_password');
415
+ const icon = document.getElementById('eye-icon');
416
+ if (input.type === 'password') {
417
+ input.type = 'text';
418
+ icon.className = 'fa-solid fa-eye-slash';
419
+ } else {
420
+ input.type = 'password';
421
+ icon.className = 'fa-solid fa-eye';
422
+ }
423
+ }
424
+
425
+ /* ── Multi-value list helpers ─────────────────────────────────────────── */
426
+ function addItem(listKey) {
427
+ const newInput = document.getElementById(listKey + '_new');
428
+ const value = newInput.value.trim();
429
+ if (!value) return;
430
+
431
+ const container = document.getElementById(listKey + '_items');
432
+ const isNumeric = listKey === 'approver_ids';
433
+
434
+ const item = document.createElement('div');
435
+ item.className = 'multi-item';
436
+ item.innerHTML = `
437
+ <input type="${isNumeric ? 'number' : 'text'}"
438
+ class="s-input"
439
+ value="${escapeHtmlAttr(value)}"
440
+ data-list="${listKey}">
441
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
442
+ <i class="fa-solid fa-xmark"></i>
443
+ </button>
444
+ `;
445
+ container.appendChild(item);
446
+ newInput.value = '';
447
+ newInput.focus();
448
+ }
449
+
450
+ function removeItem(btn) {
451
+ btn.closest('.multi-item').remove();
452
+ }
453
+
454
+ function collectList(listKey) {
455
+ const container = document.getElementById(listKey + '_items');
456
+ if (!container) return [];
457
+ return [...container.querySelectorAll('input[data-list]')]
458
+ .map(i => i.value.trim())
459
+ .filter(Boolean);
460
+ }
461
+
462
+ /* ── Save ──────────────────────────────────────────────────────────────── */
463
+ async function saveSettings() {
464
+ const btn = document.getElementById('save-btn');
465
+ const label = document.getElementById('save-label');
466
+
467
+ btn.disabled = true;
468
+ label.textContent = 'Saving…';
469
+
470
+ const payload = {
471
+ replace_mode: document.getElementById('replace_mode').checked,
472
+ hide_catalog: document.getElementById('hide_catalog').checked,
473
+ admin_username: document.getElementById('admin_username').value.trim(),
474
+ admin_password: document.getElementById('admin_password').value, // blank = keep
475
+ tmdb_api: document.getElementById('tmdb_api').value.trim(),
476
+ base_url: document.getElementById('base_url').value.trim(),
477
+ upstream_repo: document.getElementById('upstream_repo').value.trim(),
478
+ upstream_branch: document.getElementById('upstream_branch').value.trim(),
479
+ auth_channels: collectList('auth_channels'),
480
+ subscription: document.getElementById('subscription').checked,
481
+ subscription_group_id: parseInt(document.getElementById('subscription_group_id').value || '0', 10),
482
+ subscription_url: document.getElementById('subscription_url').value.trim(),
483
+ approver_ids: collectList('approver_ids').map(Number),
484
+ http_proxy_url: document.getElementById('http_proxy_url').value.trim(),
485
+ show_proxy_and_non_proxy_both: document.getElementById('show_proxy_and_non_proxy_both').checked,
486
+ multi_tokens: collectList('multi_tokens'),
487
+ extra_databases: collectList('extra_databases'),
488
+ };
489
+
490
+ try {
491
+ const res = await fetch('/api/admin/settings', {
492
+ method: 'PUT',
493
+ headers: { 'Content-Type': 'application/json' },
494
+ body: JSON.stringify(payload),
495
+ });
496
+ const data = await res.json();
497
+
498
+ if (res.ok) {
499
+ showToast('Settings saved successfully!', 'success', 'Saved');
500
+
501
+ // Show reinit notices
502
+ const reinit = data.reinit || {};
503
+ for (const [subsystem, msg] of Object.entries(reinit)) {
504
+ showToast(`${capitalize(subsystem)}: ${msg}`, 'info');
505
+ }
506
+
507
+ // Pull the freshly-saved state back from the server and patch
508
+ // the UI in place — no full page reload needed. This also
509
+ // picks up server-computed bits the form can't know on its
510
+ // own (e.g. each database's live connection-status dot).
511
+ await refreshSettingsFromServer();
512
+ } else {
513
+ showToast(data.detail || 'Save failed', 'error', 'Error');
514
+ }
515
+ } catch (err) {
516
+ showToast('Network error — could not reach server.', 'error', 'Error');
517
+ console.error(err);
518
+ } finally {
519
+ btn.disabled = false;
520
+ label.textContent = 'Save Settings';
521
+ }
522
+ }
523
+
524
+ /* ── Utilities ─────────────────────────────────────────────────────────── */
525
+ function escapeHtmlAttr(str) {
526
+ return String(str)
527
+ .replace(/&/g, '&amp;')
528
+ .replace(/"/g, '&quot;')
529
+ .replace(/'/g, '&#039;')
530
+ .replace(/</g, '&lt;')
531
+ .replace(/>/g, '&gt;');
532
+ }
533
+
534
+ function capitalize(str) {
535
+ return str.charAt(0).toUpperCase() + str.slice(1).replace(/_/g, ' ');
536
+ }
537
+
538
+ /* ── Post-save refresh, no page reload ──────────────────────────────────── */
539
+ async function refreshSettingsFromServer() {
540
+ try {
541
+ const res = await fetch('/api/admin/settings');
542
+ if (!res.ok) return;
543
+ const data = await res.json();
544
+ renderSettings(data.settings || {});
545
+ } catch (err) {
546
+ console.error('Failed to refresh settings UI:', err);
547
+ }
548
+ }
549
+
550
+ function renderSettings(s) {
551
+ // Toggles
552
+ document.getElementById('replace_mode').checked = !!s.replace_mode;
553
+ document.getElementById('hide_catalog').checked = !!s.hide_catalog;
554
+ document.getElementById('subscription').checked = !!s.subscription;
555
+ document.getElementById('show_proxy_and_non_proxy_both').checked = !!s.show_proxy_and_non_proxy_both;
556
+ toggleSubFields();
557
+
558
+ // Plain text/number fields
559
+ document.getElementById('admin_username').value = s.admin_username || '';
560
+ document.getElementById('admin_password').value = ''; // never re-fill password
561
+ document.getElementById('tmdb_api').value = s.tmdb_api || '';
562
+ document.getElementById('base_url').value = s.base_url || '';
563
+ document.getElementById('upstream_repo').value = s.upstream_repo || '';
564
+ document.getElementById('upstream_branch').value = s.upstream_branch || '';
565
+ document.getElementById('subscription_group_id').value = s.subscription_group_id || 0;
566
+ document.getElementById('subscription_url').value = s.subscription_url || '';
567
+ document.getElementById('http_proxy_url').value = s.http_proxy_url || '';
568
+
569
+ // Simple multi-value lists
570
+ rebuildSimpleList('auth_channels_items', s.auth_channels, 'text');
571
+ rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
572
+ rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
573
+
574
+ // Databases — needs the live connection-status dot per entry
575
+ rebuildDatabaseList(s.database_list || []);
576
+ }
577
+
578
+ function rebuildSimpleList(containerId, values, inputType) {
579
+ const container = document.getElementById(containerId);
580
+ if (!container) return;
581
+ const listKey = containerId.replace('_items', '');
582
+
583
+ container.innerHTML = '';
584
+ (values || []).forEach(val => {
585
+ const item = document.createElement('div');
586
+ item.className = 'multi-item';
587
+ item.innerHTML = `
588
+ <input type="${inputType}" class="s-input"
589
+ value="${escapeHtmlAttr(val)}" data-list="${listKey}">
590
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove">
591
+ <i class="fa-solid fa-xmark"></i>
592
+ </button>
593
+ `;
594
+ container.appendChild(item);
595
+ });
596
+ }
597
+
598
+ function rebuildDatabaseList(dbList) {
599
+ const container = document.getElementById('extra_databases_items');
600
+ if (!container) return;
601
+
602
+ container.innerHTML = '';
603
+ dbList.filter(entry => !entry.locked).forEach(entry => {
604
+ const item = document.createElement('div');
605
+ item.className = 'multi-item';
606
+ item.innerHTML = `
607
+ <input type="text" class="s-input" spellcheck="false"
608
+ value="${escapeHtmlAttr(entry.full_uri || '')}" data-list="extra_databases">
609
+ <span title="${entry.connected ? 'Connected' : 'Disconnected'}"
610
+ style="flex-shrink:0;width:0.6rem;height:0.6rem;border-radius:50%;
611
+ background:${entry.connected ? '#22c55e' : '#ef4444'}"></span>
612
+ <button class="remove-btn" onclick="removeItem(this)" title="Remove (only safe from the end of the list)">
613
+ <i class="fa-solid fa-xmark"></i>
614
+ </button>
615
+ `;
616
+ container.appendChild(item);
617
+ });
618
+ }
619
+ </script>
620
+
621
+ {% endblock %}
Backend/helper/auto_catalog.py CHANGED
@@ -10,16 +10,13 @@ from Backend.logger import LOGGER
10
  # -----------------------------
11
  # Auto catalog settings
12
  # -----------------------------
13
- AUTO_CATALOG_REGION = getattr(Telegram, "AUTO_CATALOG_REGION", "IN")
14
- AUTO_CATALOG_ON_STARTUP = getattr(Telegram, "AUTO_CATALOG_ON_STARTUP", True)
15
- AUTO_CATALOG_FULL_REBUILD_ON_STARTUP = getattr(Telegram, "AUTO_CATALOG_FULL_REBUILD_ON_STARTUP", False)
16
- AUTO_SYNC_DELAY_SECONDS = getattr(Telegram, "AUTO_SYNC_DELAY_SECONDS", 20)
17
- AUTO_SYNC_CONCURRENCY = getattr(Telegram, "AUTO_SYNC_CONCURRENCY", 5)
18
 
19
  # Hourly quick sync. It only starts after the admin has saved at least one
20
  # auto-catalog option from /catalogs, so first boot stays clean.
21
- AUTO_CATALOG_INTERVAL_SYNC = getattr(Telegram, "AUTO_CATALOG_INTERVAL_SYNC", True)
22
- AUTO_CATALOG_SYNC_INTERVAL_MINUTES = int(getattr(Telegram, "AUTO_CATALOG_SYNC_INTERVAL_MINUTES", 60))
23
 
24
  # User can choose exactly which auto catalogs are enabled.
25
  AUTO_CATALOG_DEFINITIONS = [
 
10
  # -----------------------------
11
  # Auto catalog settings
12
  # -----------------------------
13
+ AUTO_CATALOG_REGION = "IN"
14
+ AUTO_SYNC_CONCURRENCY = 5
 
 
 
15
 
16
  # Hourly quick sync. It only starts after the admin has saved at least one
17
  # auto-catalog option from /catalogs, so first boot stays clean.
18
+ AUTO_CATALOG_INTERVAL_SYNC = True
19
+ AUTO_CATALOG_SYNC_INTERVAL_MINUTES = 60
20
 
21
  # User can choose exactly which auto catalogs are enabled.
22
  AUTO_CATALOG_DEFINITIONS = [
Backend/helper/database.py CHANGED
@@ -10,12 +10,14 @@ from typing import Dict, List, Optional, Tuple, Any
10
 
11
  from Backend.logger import LOGGER
12
  from Backend.config import Telegram
 
13
  import re
14
  from Backend.helper.encrypt import decode_string
15
  from Backend.helper.modal import Episode, MovieSchema, QualityDetail, Season, TVShowSchema
16
  from Backend.helper.task_manager import delete_message
17
 
18
 
 
19
  def convert_objectid_to_str(document: Dict[str, Any]) -> Dict[str, Any]:
20
  for key, value in document.items():
21
  if isinstance(value, ObjectId):
@@ -78,6 +80,141 @@ class Database:
78
  upsert=True
79
  )
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  # -------------------------------
82
  # User Subscription Management
83
  # -------------------------------
@@ -677,7 +814,7 @@ class Database:
677
  movie_id = existing_movie["_id"]
678
  existing_qualities = existing_movie.get("telegram", [])
679
 
680
- if Telegram.REPLACE_MODE:
681
  to_delete = [q for q in existing_qualities if q.get("quality") == target_quality]
682
 
683
  for q in to_delete:
@@ -801,7 +938,7 @@ class Database:
801
  for quality in episode["telegram"]:
802
  target_quality = quality.get("quality")
803
 
804
- if Telegram.REPLACE_MODE:
805
  to_delete = [
806
  q for q in existing_episode["telegram"]
807
  if q.get("quality") == target_quality
 
10
 
11
  from Backend.logger import LOGGER
12
  from Backend.config import Telegram
13
+ from Backend.helper.settings_manager import SettingsManager
14
  import re
15
  from Backend.helper.encrypt import decode_string
16
  from Backend.helper.modal import Episode, MovieSchema, QualityDetail, Season, TVShowSchema
17
  from Backend.helper.task_manager import delete_message
18
 
19
 
20
+
21
  def convert_objectid_to_str(document: Dict[str, Any]) -> Dict[str, Any]:
22
  for key, value in document.items():
23
  if isinstance(value, ObjectId):
 
80
  upsert=True
81
  )
82
 
83
+
84
+ async def get_settings(self) -> dict:
85
+ """Return the full runtime settings document, or {} if none exists yet."""
86
+ try:
87
+ doc = await self.dbs["tracking"]["settings"].find_one({"_id": "app_settings"})
88
+ return doc or {}
89
+ except Exception as e:
90
+ LOGGER.error(f"Database.get_settings error: {e}")
91
+ return {}
92
+
93
+ async def save_settings(self, settings: dict) -> bool:
94
+ """
95
+ Persist *settings* to the tracking database.
96
+ Uses upsert so the first call creates the document automatically.
97
+ """
98
+ try:
99
+ clean = {k: v for k, v in settings.items() if k != "_id"}
100
+ await self.dbs["tracking"]["settings"].update_one(
101
+ {"_id": "app_settings"},
102
+ {"$set": clean},
103
+ upsert=True,
104
+ )
105
+ return True
106
+ except Exception as e:
107
+ LOGGER.error(f"Database.save_settings error: {e}")
108
+ return False
109
+
110
+
111
+
112
+ async def connect_storage_db(self, uri: str, index: int) -> bool:
113
+ """Connect and register a single database at `index`. Verifies the
114
+ connection actually works (via a ping) before registering it, so a
115
+ bad URI never leaves stale half-registered state behind."""
116
+ try:
117
+ client = motor.motor_asyncio.AsyncIOMotorClient(uri)
118
+ await client.admin.command("ping")
119
+
120
+ db_key = "tracking" if index == 0 else f"storage_{index}"
121
+ self.clients[db_key] = client
122
+ self.dbs[db_key] = client[self.db_name]
123
+
124
+ db_type = "Tracking" if index == 0 else f"Storage {index}"
125
+ masked_uri = re.sub(r"://(.*?):.*?@", r"://\1:*****@", uri).split('?')[0]
126
+ LOGGER.info(f"{db_type} Database connected successfully: {masked_uri}")
127
+ return True
128
+ except Exception as e:
129
+ LOGGER.error(f"Failed to connect database at index {index}: {e}")
130
+ return False
131
+
132
+ async def disconnect_storage_db(self, index: int) -> None:
133
+ """Close and unregister the storage database at `index`. Never call
134
+ this with index 0 or 1 — those are the locked essential databases."""
135
+ db_key = f"storage_{index}"
136
+ client = self.clients.pop(db_key, None)
137
+ self.dbs.pop(db_key, None)
138
+ if client:
139
+ client.close()
140
+ LOGGER.info(f"Disconnected {db_key}.")
141
+
142
+ def get_database_list(self) -> List[Dict[str, Any]]:
143
+ """
144
+ Return every configured database for the admin Settings page.
145
+
146
+ Locked entries (tracking + storage_1) only expose a masked URI since
147
+ they're never editable. Unlocked "extra" entries also include the
148
+ full, unmasked URI (`full_uri`) so the admin can actually edit it in
149
+ the Settings panel — they're already authenticated, so this is safe.
150
+ """
151
+ result = []
152
+ for index, uri in enumerate(self.db_uris):
153
+ masked = re.sub(r"://(.*?):.*?@", r"://\1:*****@", uri).split('?')[0]
154
+ db_key = "tracking" if index == 0 else f"storage_{index}"
155
+ entry = {
156
+ "index": index,
157
+ "uri_masked": masked,
158
+ "locked": index <= 1,
159
+ "type": "tracking" if index == 0 else "storage",
160
+ "connected": db_key in self.clients,
161
+ }
162
+ if index > 1:
163
+ entry["full_uri"] = uri
164
+ result.append(entry)
165
+ return result
166
+
167
+ async def reload_extra_databases(self, new_extra_uris: List[str]) -> Dict[str, Any]:
168
+ """
169
+ Hot-reload additional storage databases (index >= 2) without touching
170
+ the locked tracking (0) and storage_1 (1) databases.
171
+
172
+ Raises ValueError (caught by SettingsManager / the API layer and
173
+ reported to the admin) if the requested change would alter or remove
174
+ a database that isn't at the end of the list, or if a new database
175
+ URI fails to connect.
176
+ """
177
+ old_extra = self.db_uris[2:]
178
+ new_extra = [u.strip() for u in (new_extra_uris or []) if u and u.strip()]
179
+
180
+ common_len = min(len(old_extra), len(new_extra))
181
+ for i in range(common_len):
182
+ if old_extra[i] != new_extra[i]:
183
+ raise ValueError(
184
+ f"Cannot modify storage_{i + 2} in place — existing media "
185
+ f"documents reference it by position. Only appending new "
186
+ f"databases or removing the last one(s) is supported."
187
+ )
188
+
189
+ added = 0
190
+ removed = 0
191
+
192
+ if len(new_extra) > len(old_extra):
193
+ for offset, uri in enumerate(new_extra[len(old_extra):]):
194
+ index = len(old_extra) + 2 + offset
195
+ ok = await self.connect_storage_db(uri, index)
196
+ if not ok:
197
+ raise ValueError(
198
+ f"Failed to connect new database at storage_{index}. "
199
+ f"Check the URI and try again — no changes were saved."
200
+ )
201
+ added += 1
202
+
203
+ elif len(new_extra) < len(old_extra):
204
+ for index in range(len(old_extra) + 1, len(new_extra) + 1, -1):
205
+ await self.disconnect_storage_db(index)
206
+ removed += 1
207
+
208
+ self.db_uris = self.db_uris[:2] + new_extra
209
+
210
+ message = f"{added} database(s) added, {removed} database(s) removed."
211
+ LOGGER.info(f"reload_extra_databases: {message}")
212
+ return {"added": added, "removed": removed, "message": message}
213
+
214
+
215
+
216
+
217
+
218
  # -------------------------------
219
  # User Subscription Management
220
  # -------------------------------
 
814
  movie_id = existing_movie["_id"]
815
  existing_qualities = existing_movie.get("telegram", [])
816
 
817
+ if SettingsManager.current().replace_mode:
818
  to_delete = [q for q in existing_qualities if q.get("quality") == target_quality]
819
 
820
  for q in to_delete:
 
938
  for quality in episode["telegram"]:
939
  target_quality = quality.get("quality")
940
 
941
+ if SettingsManager.current().replace_mode:
942
  to_delete = [
943
  q for q in existing_episode["telegram"]
944
  if q.get("quality") == target_quality
Backend/helper/metadata.py CHANGED
@@ -8,14 +8,15 @@ from typing import Optional, List
8
 
9
  from Backend.helper.imdb import get_detail, get_season, search_title, search_title_multi
10
  from themoviedb import aioTMDb
11
- from Backend.config import Telegram
12
  import Backend
13
  from Backend.logger import LOGGER
14
  from Backend.helper.encrypt import encode_string
15
 
16
  # ----------------- Configuration -----------------
 
17
  DELAY = 0
18
- tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
19
 
20
  # Cache dictionaries (per run)
21
  IMDB_CACHE: dict = {}
 
8
 
9
  from Backend.helper.imdb import get_detail, get_season, search_title, search_title_multi
10
  from themoviedb import aioTMDb
11
+ from Backend.helper.settings_manager import SettingsManager
12
  import Backend
13
  from Backend.logger import LOGGER
14
  from Backend.helper.encrypt import encode_string
15
 
16
  # ----------------- Configuration -----------------
17
+
18
  DELAY = 0
19
+ tmdb = aioTMDb(key=SettingsManager.current().tmdb_api, language="en-US", region="US")
20
 
21
  # Cache dictionaries (per run)
22
  IMDB_CACHE: dict = {}
Backend/helper/pinger.py CHANGED
@@ -1,13 +1,14 @@
1
  import asyncio
2
  import traceback
3
  import aiohttp
4
- from Backend.config import Telegram
5
  from Backend.logger import LOGGER
6
 
 
7
  async def ping():
8
 
9
  sleep_time = 1200
10
- manifest_url = f"{Telegram.BASE_URL}/api/system/stats"
11
 
12
  while True:
13
  await asyncio.sleep(sleep_time)
 
1
  import asyncio
2
  import traceback
3
  import aiohttp
4
+ from Backend.helper.settings_manager import SettingsManager
5
  from Backend.logger import LOGGER
6
 
7
+
8
  async def ping():
9
 
10
  sleep_time = 1200
11
+ manifest_url = f"{SettingsManager.current().base_url}/api/system/stats"
12
 
13
  while True:
14
  await asyncio.sleep(sleep_time)
Backend/helper/pyro.py CHANGED
@@ -2,7 +2,7 @@ from pyrogram.file_id import FileId
2
  from typing import Optional
3
  from Backend.logger import LOGGER
4
  from Backend import __version__, now, timezone
5
- from Backend.config import Telegram
6
  from Backend.helper.exceptions import FIleNotFound
7
  from aiofiles import open as aiopen
8
  from aiofiles.os import path as aiopath, remove as aioremove
@@ -192,7 +192,7 @@ async def restart_notification():
192
  chat_id, msg_id = map(int, data)
193
 
194
  try:
195
- repo = Telegram.UPSTREAM_REPO.split('/')
196
  UPSTREAM_REPO = f"https://github.com/{repo[-2]}/{repo[-1]}"
197
  await StreamBot.edit_message_text(
198
  chat_id=chat_id,
@@ -203,7 +203,7 @@ async def restart_notification():
203
  f"Time: {now.strftime('%I:%M:%S %p')}\n"
204
  f"TimeZone: {timezone.zone}\n\n"
205
  f"Repo: {UPSTREAM_REPO}\n"
206
- f"Branch: {Telegram.UPSTREAM_BRANCH}\n"
207
  f"Version: {__version__}"
208
  ),
209
  parse_mode=enums.ParseMode.HTML
 
2
  from typing import Optional
3
  from Backend.logger import LOGGER
4
  from Backend import __version__, now, timezone
5
+ from Backend.helper.settings_manager import SettingsManager
6
  from Backend.helper.exceptions import FIleNotFound
7
  from aiofiles import open as aiopen
8
  from aiofiles.os import path as aiopath, remove as aioremove
 
192
  chat_id, msg_id = map(int, data)
193
 
194
  try:
195
+ repo = SettingsManager.current().upstream_repo.split('/')
196
  UPSTREAM_REPO = f"https://github.com/{repo[-2]}/{repo[-1]}"
197
  await StreamBot.edit_message_text(
198
  chat_id=chat_id,
 
203
  f"Time: {now.strftime('%I:%M:%S %p')}\n"
204
  f"TimeZone: {timezone.zone}\n\n"
205
  f"Repo: {UPSTREAM_REPO}\n"
206
+ f"Branch: {SettingsManager.current().upstream_branch}\n"
207
  f"Version: {__version__}"
208
  ),
209
  parse_mode=enums.ParseMode.HTML
Backend/helper/settings_manager.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any, Dict, List
3
+ from Backend.logger import LOGGER
4
+
5
+ # ─────────────────────────────────────────────────────────────────────────────
6
+ # Default values (used when nothing exists in the DB yet)
7
+ # ─────────────────────────────────────────────────────────────────────────────
8
+ _DEFAULTS: Dict[str, Any] = {
9
+ "replace_mode": True,
10
+ "hide_catalog": False,
11
+ "auth_channels": [],
12
+ "tmdb_api": "",
13
+ "base_url": "",
14
+ "upstream_repo": "",
15
+ "upstream_branch": "",
16
+ "admin_username": "admin",
17
+ "admin_password": "admin",
18
+ "subscription": False,
19
+ "subscription_group_id": 0,
20
+ "subscription_url": "https://t.me/",
21
+ "approver_ids": [],
22
+ "http_proxy_url": "",
23
+ "show_proxy_and_non_proxy_both": False,
24
+ "multi_tokens": [],
25
+ "extra_databases": [],
26
+ }
27
+
28
+
29
+ def _seed_from_env() -> Dict[str, Any]:
30
+ """Read legacy Telegram config env values. Called only on FIRST startup."""
31
+ from Backend.config import Telegram # lazy import — see note at top of file
32
+
33
+ seed = dict(_DEFAULTS)
34
+ seed.update({
35
+ "replace_mode": Telegram.REPLACE_MODE,
36
+ "hide_catalog": Telegram.HIDE_CATALOG,
37
+ "auth_channels": list(Telegram.AUTH_CHANNEL),
38
+ "tmdb_api": Telegram.TMDB_API,
39
+ "base_url": Telegram.BASE_URL,
40
+ "upstream_repo": Telegram.UPSTREAM_REPO,
41
+ "upstream_branch": Telegram.UPSTREAM_BRANCH,
42
+ "admin_username": Telegram.ADMIN_USERNAME,
43
+ "admin_password": Telegram.ADMIN_PASSWORD,
44
+ "subscription": Telegram.SUBSCRIPTION,
45
+ "subscription_group_id": Telegram.SUBSCRIPTION_GROUP_ID,
46
+ "subscription_url": Telegram.SUBSCRIPTION_URL,
47
+ "approver_ids": list(Telegram.APPROVER_IDS),
48
+ "http_proxy_url": Telegram.HTTP_PROXY_URL,
49
+ "show_proxy_and_non_proxy_both": Telegram.SHOW_PROXY_AND_NON_PROXY_BOTH,
50
+ "multi_tokens": [],
51
+ "extra_databases": list(Telegram.DATABASE[2:]) if len(Telegram.DATABASE) > 2 else [],
52
+ })
53
+ return seed
54
+
55
+
56
+ # ─────────────────────────────────────────────────────────────────────────────
57
+ # Immutable settings snapshot
58
+ # ─────────────────────────────────────────────────────────────────────────────
59
+ class Settings:
60
+ __slots__ = ("_d",)
61
+
62
+ def __init__(self, data: Dict[str, Any]) -> None:
63
+ merged = dict(_DEFAULTS)
64
+ merged.update({k: v for k, v in data.items() if k != "_id"})
65
+ self._d = merged
66
+
67
+ # ── Booleans ─────────────────────────────────────────────────────────────
68
+ @property
69
+ def replace_mode(self) -> bool:
70
+ return bool(self._d["replace_mode"])
71
+
72
+ @property
73
+ def hide_catalog(self) -> bool:
74
+ return bool(self._d["hide_catalog"])
75
+
76
+ @property
77
+ def subscription(self) -> bool:
78
+ return bool(self._d["subscription"])
79
+
80
+ @property
81
+ def show_proxy_and_non_proxy_both(self) -> bool:
82
+ return bool(self._d["show_proxy_and_non_proxy_both"])
83
+
84
+ # ── Strings ──────────────────────────────────────────────────────────────
85
+ @property
86
+ def tmdb_api(self) -> str:
87
+ return str(self._d.get("tmdb_api") or "")
88
+
89
+ @property
90
+ def base_url(self) -> str:
91
+ return str(self._d.get("base_url") or "").rstrip("/")
92
+
93
+ @property
94
+ def upstream_repo(self) -> str:
95
+ return str(self._d.get("upstream_repo") or "")
96
+
97
+ @property
98
+ def upstream_branch(self) -> str:
99
+ return str(self._d.get("upstream_branch") or "")
100
+
101
+ @property
102
+ def admin_username(self) -> str:
103
+ return str(self._d.get("admin_username") or "admin")
104
+
105
+ @property
106
+ def admin_password(self) -> str:
107
+ return str(self._d.get("admin_password") or "admin")
108
+
109
+ @property
110
+ def http_proxy_url(self) -> str:
111
+ return str(self._d.get("http_proxy_url") or "")
112
+
113
+ @property
114
+ def subscription_url(self) -> str:
115
+ return str(self._d.get("subscription_url") or "https://t.me/")
116
+
117
+ # ── Integers ─────────────────────────────────────────────────────────────
118
+ @property
119
+ def subscription_group_id(self) -> int:
120
+ return int(self._d.get("subscription_group_id") or 0)
121
+
122
+ # ── Lists ─────────────────────────────────────────────────────────────────
123
+ @property
124
+ def auth_channels(self) -> List[str]:
125
+ return list(self._d.get("auth_channels") or [])
126
+
127
+ @property
128
+ def approver_ids(self) -> List[int]:
129
+ return [int(x) for x in (self._d.get("approver_ids") or [])]
130
+
131
+ @property
132
+ def multi_tokens(self) -> List[str]:
133
+ return list(self._d.get("multi_tokens") or [])
134
+
135
+ @property
136
+ def extra_databases(self) -> List[str]:
137
+ return list(self._d.get("extra_databases") or [])
138
+
139
+ # ── Serialisation ─────────────────────────────────────────────────────────
140
+ def to_dict(self) -> Dict[str, Any]:
141
+ return dict(self._d)
142
+
143
+
144
+ # ─────────────────────────────────────────────────────────────────────────────
145
+ # Manager singleton
146
+ # ─────────────────────────────────────────────────────────────────────────────
147
+ class SettingsManager:
148
+ _current: Settings | None = None
149
+
150
+ # ── Bootstrap ────────────────────────────────────────────────────────────
151
+ @classmethod
152
+ async def initialize(cls, db) -> None:
153
+ raw = await db.get_settings()
154
+ if not raw:
155
+ LOGGER.info("SettingsManager: no settings in DB — seeding from config.env.")
156
+ seed = _seed_from_env()
157
+ await db.save_settings(seed)
158
+ cls._current = Settings(seed)
159
+ else:
160
+ cls._current = Settings(raw)
161
+ LOGGER.info("SettingsManager: settings loaded successfully.")
162
+
163
+ @classmethod
164
+ async def reload(cls, db) -> None:
165
+ """Reload settings from DB (call after an external change)."""
166
+ raw = await db.get_settings()
167
+ if raw:
168
+ cls._current = Settings(raw)
169
+
170
+ # ── Read ─────────────────────────────────────────────────────────────────
171
+ @classmethod
172
+ def current(cls) -> Settings:
173
+ if cls._current is None:
174
+ return Settings({})
175
+ return cls._current
176
+
177
+ # ── Write + reinitialise ─────────────────────────────────────────────────
178
+ @classmethod
179
+ async def update(cls, db, new_values: Dict[str, Any]) -> Dict[str, str]:
180
+ old = cls.current().to_dict()
181
+ merged = dict(old)
182
+ merged.update(new_values)
183
+
184
+ results: Dict[str, str] = {}
185
+
186
+ # ── Phase 1: validate / apply things that can abort the save ───────
187
+ old_extra = old.get("extra_databases") or []
188
+ new_extra = merged.get("extra_databases") or []
189
+ if old_extra != new_extra:
190
+ result = await db.reload_extra_databases(new_extra) # may raise ValueError
191
+ results["databases"] = result.get("message", "databases reloaded")
192
+
193
+ # ── Phase 2: persist + flip in-memory snapshot ──────────────────────
194
+ await db.save_settings(merged)
195
+ cls._current = Settings(merged)
196
+
197
+ # ── Phase 3: reinit everything that reads current() ─────────────────
198
+ results.update(await cls._reinit_dependent(old, merged))
199
+
200
+ return results
201
+
202
+ # ── Internal reinit logic (runs AFTER _current has been updated) ────────
203
+ @classmethod
204
+ async def _reinit_dependent(cls, old: dict, new: dict) -> Dict[str, str]:
205
+ results: Dict[str, str] = {}
206
+
207
+ # Multi-tokens changed → hot-reload Pyrogram helper clients
208
+ old_tokens = old.get("multi_tokens") or []
209
+ new_tokens = new.get("multi_tokens") or []
210
+ if old_tokens != new_tokens:
211
+ try:
212
+ from Backend.pyrofork.clients import reload_multi_token_clients
213
+ result = await reload_multi_token_clients()
214
+ results["multi_tokens"] = (
215
+ f"{result['started']} started, {result['stopped']} stopped "
216
+ f"({result['total_clients']} active)"
217
+ )
218
+ except Exception as exc:
219
+ LOGGER.error(f"SettingsManager reinit multi_tokens: {exc}")
220
+ results["multi_tokens"] = f"error: {exc}"
221
+
222
+ # Auth channels — only report when they actually changed. This was
223
+ old_channels = old.get("auth_channels") or []
224
+ new_channels = new.get("auth_channels") or []
225
+ if old_channels != new_channels:
226
+ results["auth_channels"] = f"{len(new_channels)} channel(s) saved"
227
+
228
+ # Proxy settings changed
229
+ proxy_keys = {"http_proxy_url", "show_proxy_and_non_proxy_both"}
230
+ if any(old.get(k) != new.get(k) for k in proxy_keys):
231
+ results["proxy"] = "updated — applies to next outbound request"
232
+
233
+ # Subscription ENABLED/DISABLED toggle → actually start/stop the
234
+ if old.get("subscription") != new.get("subscription"):
235
+ try:
236
+ from Backend.helper import subscription_task_manager
237
+ from Backend.pyrofork.bot import StreamBot
238
+
239
+ if new.get("subscription"):
240
+ await subscription_task_manager.start(StreamBot)
241
+ results["subscription"] = "checker task started"
242
+ else:
243
+ await subscription_task_manager.stop()
244
+ results["subscription"] = "checker task stopped"
245
+ except Exception as exc:
246
+ LOGGER.error(f"SettingsManager reinit subscription: {exc}")
247
+ results["subscription"] = f"error: {exc}"
248
+ else:
249
+ sub_keys = {"subscription_group_id", "approver_ids", "subscription_url"}
250
+ if any(old.get(k) != new.get(k) for k in sub_keys):
251
+ results["subscription"] = "settings reloaded in-memory"
252
+
253
+ # Admin credentials changed
254
+ cred_keys = {"admin_username", "admin_password"}
255
+ if any(old.get(k) != new.get(k) for k in cred_keys):
256
+ results["admin_credentials"] = "updated — takes effect on next login"
257
+
258
+ return results
Backend/helper/subscription_checker.py CHANGED
@@ -1,15 +1,18 @@
1
  import asyncio
2
  from pyrogram import Client
3
- from Backend.config import Telegram
4
  from Backend import db
5
  from datetime import datetime
6
  from Backend.logger import LOGGER
7
 
 
 
 
8
  async def subscription_checker_loop(bot: Client):
9
  while True:
10
  try:
11
- if not Telegram.SUBSCRIPTION:
12
- await asyncio.sleep(3600)
13
  continue
14
 
15
  LOGGER.info("Running subscription checker...")
@@ -19,18 +22,19 @@ async def subscription_checker_loop(bot: Client):
19
  for user in expired_users:
20
  user_id = user["_id"]
21
  try:
 
22
  # Ban then unban to kick the user without permanently banning them
23
- await bot.ban_chat_member(Telegram.SUBSCRIPTION_GROUP_ID, user_id)
24
- await bot.unban_chat_member(Telegram.SUBSCRIPTION_GROUP_ID, user_id)
25
-
26
  await db.mark_user_expired(user_id)
27
-
28
  # Notify user
29
  await bot.send_message(
30
  user_id,
31
  "❌ <b>Subscription Expired</b>\n\n"
32
  "Your subscription has expired, and you have been removed from the private group.\n"
33
- f"Please go to {Telegram.SUBSCRIPTION_URL} and send /start to renew your subscription and regain access."
34
  )
35
  LOGGER.info(f"Kicked expired user {user_id}")
36
  except Exception as e:
@@ -46,16 +50,20 @@ async def subscription_checker_loop(bot: Client):
46
  user_id,
47
  f"⚠️ <b>Subscription Expiring Soon</b>\n\n"
48
  f"Your subscription will expire on <b>{expiry.strftime('%Y-%m-%d %H:%M UTC')}</b>.\n"
49
- f"Please go to {Telegram.SUBSCRIPTION_URL} and send /start to renew your plan before you lose access to the group!"
50
  )
51
  await db.mark_reminder_sent(user_id)
52
  LOGGER.info(f"Sent expiry reminder to user {user_id}")
53
  except Exception as e:
54
  LOGGER.error(f"Failed to send reminder to user {user_id}: {e}")
55
 
56
- # Check every hour
57
  await asyncio.sleep(3600)
58
 
 
 
 
 
 
59
  except Exception as e:
60
  LOGGER.error(f"Error in subscription checker loop: {e}")
61
- await asyncio.sleep(300) # Wait 5 minutes before retrying on error
 
1
  import asyncio
2
  from pyrogram import Client
3
+ from Backend.helper.settings_manager import SettingsManager
4
  from Backend import db
5
  from datetime import datetime
6
  from Backend.logger import LOGGER
7
 
8
+
9
+
10
+
11
  async def subscription_checker_loop(bot: Client):
12
  while True:
13
  try:
14
+ if not SettingsManager.current().subscription:
15
+ await asyncio.sleep(60)
16
  continue
17
 
18
  LOGGER.info("Running subscription checker...")
 
22
  for user in expired_users:
23
  user_id = user["_id"]
24
  try:
25
+
26
  # Ban then unban to kick the user without permanently banning them
27
+ await bot.ban_chat_member(SettingsManager.current().subscription_group_id, user_id)
28
+ await bot.unban_chat_member(SettingsManager.current().subscription_group_id, user_id)
29
+
30
  await db.mark_user_expired(user_id)
31
+
32
  # Notify user
33
  await bot.send_message(
34
  user_id,
35
  "❌ <b>Subscription Expired</b>\n\n"
36
  "Your subscription has expired, and you have been removed from the private group.\n"
37
+ f"Please go to {config.subscription_url} and send /start to renew your subscription and regain access."
38
  )
39
  LOGGER.info(f"Kicked expired user {user_id}")
40
  except Exception as e:
 
50
  user_id,
51
  f"⚠️ <b>Subscription Expiring Soon</b>\n\n"
52
  f"Your subscription will expire on <b>{expiry.strftime('%Y-%m-%d %H:%M UTC')}</b>.\n"
53
+ f"Please go to {config.subscription_url} and send /start to renew your plan before you lose access to the group!"
54
  )
55
  await db.mark_reminder_sent(user_id)
56
  LOGGER.info(f"Sent expiry reminder to user {user_id}")
57
  except Exception as e:
58
  LOGGER.error(f"Failed to send reminder to user {user_id}: {e}")
59
 
 
60
  await asyncio.sleep(3600)
61
 
62
+ except asyncio.CancelledError:
63
+ # Raised by subscription_task_manager.stop() — exit cleanly,
64
+ # don't swallow it as a generic error.
65
+ LOGGER.info("Subscription checker loop cancelled.")
66
+ raise
67
  except Exception as e:
68
  LOGGER.error(f"Error in subscription checker loop: {e}")
69
+ await asyncio.sleep(300) # Wait 5 minutes before retrying on error
Backend/helper/subscription_task_manager.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Optional
3
+ from Backend.helper.subscription_checker import subscription_checker_loop
4
+ from Backend.helper.settings_manager import SettingsManager
5
+ from Backend.logger import LOGGER
6
+
7
+ _task: Optional[asyncio.Task] = None
8
+
9
+
10
+ def is_running() -> bool:
11
+ return _task is not None and not _task.done()
12
+
13
+ async def start(bot) -> bool:
14
+ global _task
15
+ if is_running():
16
+ return False
17
+ _task = asyncio.create_task(subscription_checker_loop(bot))
18
+ LOGGER.info("Subscription Checker Task Started.")
19
+ return True
20
+
21
+
22
+ async def stop() -> bool:
23
+ global _task
24
+ if not is_running():
25
+ _task = None
26
+ return False
27
+
28
+ _task.cancel()
29
+ try:
30
+ await _task
31
+ except asyncio.CancelledError:
32
+ pass
33
+ except Exception as e:
34
+ LOGGER.warning(f"Error while stopping subscription checker task: {e}")
35
+ finally:
36
+ _task = None
37
+
38
+ LOGGER.info("Subscription Checker Task Stopped.")
39
+ return True
40
+
41
+
42
+ async def sync(bot) -> None:
43
+ if SettingsManager.current().subscription:
44
+ await start(bot)
Backend/pyrofork/clients.py CHANGED
@@ -3,23 +3,19 @@ from pyrogram import Client
3
  from Backend.logger import LOGGER
4
  from Backend.config import Telegram
5
  from Backend.pyrofork.bot import multi_clients, work_loads, StreamBot, client_dc_map
6
- from os import environ
 
 
 
7
 
8
  class TokenParser:
9
  @staticmethod
10
- def parse_from_env():
11
- tokens = {
12
- c + 1: t
13
- for c, (_, t) in enumerate(
14
- filter(
15
- lambda n: n[0].startswith("MULTI_TOKEN"),
16
- sorted(environ.items())
17
- )
18
- )
19
- }
20
- return tokens
21
-
22
- async def start_client(client_id, token):
23
  try:
24
  LOGGER.info(f"Starting - Bot Client {client_id}")
25
  client = await Client(
@@ -31,7 +27,7 @@ async def start_client(client_id, token):
31
  no_updates=True,
32
  in_memory=True
33
  ).start()
34
-
35
  try:
36
  client_dc = await client.storage.dc_id()
37
  client_dc_map[client_id] = client_dc
@@ -39,16 +35,39 @@ async def start_client(client_id, token):
39
  except Exception as e:
40
  LOGGER.warning(f"Could not get DC for Client {client_id}: {e}")
41
  client_dc_map[client_id] = None
42
-
43
  work_loads[client_id] = 0
44
  return client_id, client
45
  except Exception as e:
46
  LOGGER.error(f"Failed to start Client - {client_id} Error: {e}", exc_info=True)
47
  return None
48
 
49
- async def initialize_clients():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  multi_clients[0], work_loads[0] = StreamBot, 0
51
-
52
  try:
53
  main_dc = await StreamBot.storage.dc_id()
54
  client_dc_map[0] = main_dc
@@ -56,19 +75,61 @@ async def initialize_clients():
56
  except Exception as e:
57
  LOGGER.warning(f"Could not get DC for StreamBot: {e}")
58
  client_dc_map[0] = None
59
-
60
- all_tokens = TokenParser.parse_from_env()
61
  if not all_tokens:
62
  LOGGER.info("No additional Bot Clients found, Using default client")
63
  return
64
 
65
  tasks = [create_task(start_client(i, token)) for i, token in all_tokens.items()]
66
- clients = await gather(*tasks)
67
- clients = {client_id: client for client_id, client in clients if client}
68
- multi_clients.update(clients)
 
 
 
 
69
 
70
  if len(multi_clients) != 1:
71
  LOGGER.info(f"Multi-Client Mode Enabled with {len(multi_clients)} clients")
72
  LOGGER.info(f"DC Distribution: {client_dc_map}")
73
  else:
74
- LOGGER.info("No additional clients were initialized, using default client")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from Backend.logger import LOGGER
4
  from Backend.config import Telegram
5
  from Backend.pyrofork.bot import multi_clients, work_loads, StreamBot, client_dc_map
6
+ from Backend.helper.settings_manager import SettingsManager
7
+
8
+ client_tokens: dict[int, str] = {}
9
+
10
 
11
  class TokenParser:
12
  @staticmethod
13
+ def parse_from_settings() -> dict[int, str]:
14
+ tokens = SettingsManager.current().multi_tokens
15
+ return {i + 1: tok.strip() for i, tok in enumerate(tokens) if tok and tok.strip()}
16
+
17
+
18
+ async def start_client(client_id: int, token: str):
 
 
 
 
 
 
 
19
  try:
20
  LOGGER.info(f"Starting - Bot Client {client_id}")
21
  client = await Client(
 
27
  no_updates=True,
28
  in_memory=True
29
  ).start()
30
+
31
  try:
32
  client_dc = await client.storage.dc_id()
33
  client_dc_map[client_id] = client_dc
 
35
  except Exception as e:
36
  LOGGER.warning(f"Could not get DC for Client {client_id}: {e}")
37
  client_dc_map[client_id] = None
38
+
39
  work_loads[client_id] = 0
40
  return client_id, client
41
  except Exception as e:
42
  LOGGER.error(f"Failed to start Client - {client_id} Error: {e}", exc_info=True)
43
  return None
44
 
45
+
46
+ async def stop_client(client_id: int) -> None:
47
+ client = multi_clients.pop(client_id, None)
48
+ work_loads.pop(client_id, None)
49
+ client_dc_map.pop(client_id, None)
50
+ client_tokens.pop(client_id, None)
51
+
52
+ if client:
53
+ try:
54
+ await client.stop()
55
+ LOGGER.info(f"Stopped Bot Client {client_id}")
56
+ except Exception as e:
57
+ LOGGER.warning(f"Error stopping Client {client_id}: {e}")
58
+
59
+ # Drop any cached ByteStreamer tied to this client so stale FileId cache
60
+ # entries referencing a now-dead connection are never reused.
61
+ try:
62
+ from Backend.fastapi.routes.stream_routes import _streamer_by_client
63
+ _streamer_by_client.pop(client_id, None)
64
+ except Exception:
65
+ pass
66
+
67
+
68
+ async def initialize_clients() -> None:
69
  multi_clients[0], work_loads[0] = StreamBot, 0
70
+
71
  try:
72
  main_dc = await StreamBot.storage.dc_id()
73
  client_dc_map[0] = main_dc
 
75
  except Exception as e:
76
  LOGGER.warning(f"Could not get DC for StreamBot: {e}")
77
  client_dc_map[0] = None
78
+
79
+ all_tokens = TokenParser.parse_from_settings()
80
  if not all_tokens:
81
  LOGGER.info("No additional Bot Clients found, Using default client")
82
  return
83
 
84
  tasks = [create_task(start_client(i, token)) for i, token in all_tokens.items()]
85
+ results = await gather(*tasks)
86
+
87
+ started = {client_id: client for client_id, client in results if client}
88
+ multi_clients.update(started)
89
+ for client_id, token in all_tokens.items():
90
+ if client_id in started:
91
+ client_tokens[client_id] = token
92
 
93
  if len(multi_clients) != 1:
94
  LOGGER.info(f"Multi-Client Mode Enabled with {len(multi_clients)} clients")
95
  LOGGER.info(f"DC Distribution: {client_dc_map}")
96
  else:
97
+ LOGGER.info("No additional clients were initialized, using default client")
98
+
99
+
100
+ async def reload_multi_token_clients() -> dict:
101
+ new_tokens = TokenParser.parse_from_settings()
102
+
103
+ old_ids = set(client_tokens.keys())
104
+ new_ids = set(new_tokens.keys())
105
+
106
+ to_stop = [
107
+ cid for cid in old_ids
108
+ if cid not in new_ids or client_tokens.get(cid) != new_tokens.get(cid)
109
+ ]
110
+ for cid in to_stop:
111
+ await stop_client(cid)
112
+
113
+ to_start = {
114
+ cid: tok for cid, tok in new_tokens.items()
115
+ if cid not in old_ids or client_tokens.get(cid) != tok
116
+ }
117
+
118
+ if to_start:
119
+ tasks = [create_task(start_client(cid, tok)) for cid, tok in to_start.items()]
120
+ results = await gather(*tasks)
121
+ started = {cid: client for cid, client in results if client}
122
+ multi_clients.update(started)
123
+ for cid, tok in to_start.items():
124
+ if cid in started:
125
+ client_tokens[cid] = tok
126
+
127
+ LOGGER.info(
128
+ f"Multi-token reload complete — {len(to_stop)} stopped, "
129
+ f"{len(to_start)} (re)started, {len(multi_clients)} total clients active."
130
+ )
131
+ return {
132
+ "stopped": len(to_stop),
133
+ "started": len(to_start),
134
+ "total_clients": len(multi_clients),
135
+ }
Backend/pyrofork/plugins/channels.py DELETED
@@ -1,226 +0,0 @@
1
- """
2
- Channel Manager Plugin — add, remove, and list AUTH_CHANNELs via the bot.
3
-
4
- Commands (owner-only, private chat):
5
- /channels — List all active AUTH_CHANNELs with names
6
- /addchannel <id> — Add a channel (validates bot access first)
7
- /removechannel <id> — Remove a channel
8
-
9
- Changes take effect immediately (no restart needed) and are persisted to MongoDB.
10
-
11
- """
12
-
13
- from pyrogram import filters, Client, enums
14
- from pyrogram.types import Message
15
- from pyrogram.errors import ChannelPrivate, ChatAdminRequired, PeerIdInvalid
16
-
17
- from Backend import db
18
- from Backend.helper.custom_filter import CustomFilters
19
- from Backend.logger import LOGGER
20
- from Backend.config import Telegram
21
-
22
-
23
- # ── DB persistence helpers ───────────────────────────────────────────────
24
-
25
- CHANNEL_DOC_ID = "auth_channels"
26
-
27
-
28
- async def _load_channels_from_db():
29
- try:
30
- doc = await db.dbs["tracking"]["config"].find_one({"_id": CHANNEL_DOC_ID})
31
- if doc and "channels" in doc:
32
- db_channels = doc["channels"]
33
- for ch in db_channels:
34
- if ch not in Telegram.AUTH_CHANNEL:
35
- Telegram.AUTH_CHANNEL.append(ch)
36
- LOGGER.info(
37
- f"[ChannelMgr] Loaded {len(db_channels)} channels from DB, "
38
- f"total active: {len(Telegram.AUTH_CHANNEL)}"
39
- )
40
- except Exception as e:
41
- LOGGER.error(f"[ChannelMgr] Failed to load channels from DB: {e}")
42
-
43
-
44
- async def _save_channels_to_db():
45
- try:
46
- await db.dbs["tracking"]["config"].update_one(
47
- {"_id": CHANNEL_DOC_ID},
48
- {"$set": {"channels": list(Telegram.AUTH_CHANNEL)}},
49
- upsert=True,
50
- )
51
- except Exception as e:
52
- LOGGER.error(f"[ChannelMgr] Failed to save channels to DB: {e}")
53
-
54
-
55
- # ── Bot Commands ─────────────────────────────────────────────────────────
56
-
57
- @Client.on_message(filters.command('channels') & filters.private & CustomFilters.owner, group=10)
58
- async def list_channels(client: Client, message: Message):
59
- if not Telegram.AUTH_CHANNEL:
60
- await message.reply_text(
61
- "📭 No AUTH_CHANNELs configured.\n\n"
62
- "Use /addchannel <code>&lt;channel_id&gt;</code> to add one.",
63
- quote=True,
64
- parse_mode=enums.ParseMode.HTML,
65
- )
66
- return
67
-
68
- lines = []
69
- for i, ch_id in enumerate(Telegram.AUTH_CHANNEL, 1):
70
- name = ch_id
71
- try:
72
- chat = await client.get_chat(int(ch_id))
73
- name = getattr(chat, "title", ch_id)
74
- members = getattr(chat, "members_count", "?")
75
- lines.append(f"{i}. <b>{name}</b>\n ID: <code>{ch_id}</code> | Members: {members}")
76
- except Exception:
77
- lines.append(f"{i}. <b>[inaccessible]</b>\n ID: <code>{ch_id}</code>")
78
-
79
- text = (
80
- "<blockquote>📡 <b>Active AUTH_CHANNELs</b></blockquote>\n\n"
81
- + "\n\n".join(lines)
82
- + "\n\n<i>Use /addchannel or /removechannel to manage.</i>"
83
- )
84
- await message.reply_text(text, quote=True, parse_mode=enums.ParseMode.HTML)
85
-
86
-
87
- @Client.on_message(filters.command('addchannel') & filters.private & CustomFilters.owner, group=10)
88
- async def add_channel(client: Client, message: Message):
89
- args = message.text.split(maxsplit=1)
90
- if len(args) < 2:
91
- await message.reply_text(
92
- "Usage: /addchannel <code>&lt;channel_id&gt;</code>\n\n"
93
- "Example: <code>/addchannel -1001234567890</code>\n\n"
94
- "💡 <i>To find a channel ID, forward a message from it to "
95
- "@userinfobot or check the channel's invite link.</i>",
96
- quote=True,
97
- parse_mode=enums.ParseMode.HTML,
98
- )
99
- return
100
-
101
- ch_id = args[1].strip()
102
-
103
- try:
104
- int(ch_id)
105
- except ValueError:
106
- await message.reply_text(
107
- f"❌ <code>{ch_id}</code> is not a valid channel ID.\n"
108
- "Channel IDs are numeric, usually starting with <code>-100</code>.",
109
- quote=True,
110
- parse_mode=enums.ParseMode.HTML,
111
- )
112
- return
113
-
114
- if ch_id in Telegram.AUTH_CHANNEL:
115
- await message.reply_text(
116
- f"ℹ️ Channel <code>{ch_id}</code> is already in AUTH_CHANNELs.",
117
- quote=True,
118
- parse_mode=enums.ParseMode.HTML,
119
- )
120
- return
121
-
122
- status_msg = await message.reply_text(
123
- "🔍 Validating channel access…",
124
- quote=True,
125
- parse_mode=enums.ParseMode.HTML,
126
- )
127
-
128
- try:
129
- chat = await client.get_chat(int(ch_id))
130
- ch_name = getattr(chat, "title", ch_id)
131
- except (ChannelPrivate, ChatAdminRequired):
132
- await status_msg.edit_text(
133
- f"❌ <b>Access denied</b> to channel <code>{ch_id}</code>.\n\n"
134
- "Make sure the bot is added as an <b>admin</b> in the channel first.",
135
- parse_mode=enums.ParseMode.HTML,
136
- )
137
- return
138
- except PeerIdInvalid:
139
- await status_msg.edit_text(
140
- f"❌ Channel <code>{ch_id}</code> not found.\n"
141
- "Double-check the ID.",
142
- parse_mode=enums.ParseMode.HTML,
143
- )
144
- return
145
- except Exception as e:
146
- await status_msg.edit_text(
147
- f"❌ Error accessing channel: <code>{e}</code>",
148
- parse_mode=enums.ParseMode.HTML,
149
- )
150
- return
151
-
152
- Telegram.AUTH_CHANNEL.append(ch_id)
153
- await _save_channels_to_db()
154
-
155
- LOGGER.info(f"[ChannelMgr] Added channel {ch_id} ({ch_name})")
156
-
157
- await status_msg.edit_text(
158
- f"✅ <b>Channel added!</b>\n\n"
159
- f"📡 <b>{ch_name}</b>\n"
160
- f"ID: <code>{ch_id}</code>\n\n"
161
- f"The bot will now index new videos from this channel.\n"
162
- f"Use /scan <code>{ch_id}</code> to index existing content.",
163
- parse_mode=enums.ParseMode.HTML,
164
- )
165
-
166
-
167
- @Client.on_message(filters.command('removechannel') & filters.private & CustomFilters.owner, group=10)
168
- async def remove_channel(client: Client, message: Message):
169
- args = message.text.split(maxsplit=1)
170
- if len(args) < 2:
171
- if Telegram.AUTH_CHANNEL:
172
- lines = []
173
- for ch_id in Telegram.AUTH_CHANNEL:
174
- try:
175
- chat = await client.get_chat(int(ch_id))
176
- name = getattr(chat, "title", ch_id)
177
- except Exception:
178
- name = "[inaccessible]"
179
- lines.append(f"• <code>{ch_id}</code> — {name}")
180
-
181
- await message.reply_text(
182
- "Usage: /removechannel <code>&lt;channel_id&gt;</code>\n\n"
183
- "<b>Current channels:</b>\n" + "\n".join(lines),
184
- quote=True,
185
- parse_mode=enums.ParseMode.HTML,
186
- )
187
- else:
188
- await message.reply_text(
189
- "📭 No channels to remove.",
190
- quote=True,
191
- )
192
- return
193
-
194
- ch_id = args[1].strip()
195
-
196
- if ch_id not in Telegram.AUTH_CHANNEL:
197
- await message.reply_text(
198
- f"❌ Channel <code>{ch_id}</code> is not in AUTH_CHANNELs.",
199
- quote=True,
200
- parse_mode=enums.ParseMode.HTML,
201
- )
202
- return
203
-
204
- ch_name = ch_id
205
- try:
206
- chat = await client.get_chat(int(ch_id))
207
- ch_name = getattr(chat, "title", ch_id)
208
- except Exception:
209
- pass
210
-
211
- Telegram.AUTH_CHANNEL.remove(ch_id)
212
- await _save_channels_to_db()
213
-
214
- LOGGER.info(f"[ChannelMgr] Removed channel {ch_id} ({ch_name})")
215
-
216
- await message.reply_text(
217
- f"✅ <b>Channel removed!</b>\n\n"
218
- f"📡 <b>{ch_name}</b> (<code>{ch_id}</code>)\n\n"
219
- f"⚠️ Existing DB entries from this channel are <b>not</b> deleted.\n"
220
- f"Videos already indexed will still be streamable.\n"
221
- f"New videos in this channel will no longer be indexed.",
222
- quote=True,
223
- parse_mode=enums.ParseMode.HTML,
224
- )
225
-
226
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/pyrofork/plugins/group_security.py CHANGED
@@ -1,18 +1,20 @@
1
  from pyrogram import Client, filters
2
  from pyrogram.types import ChatMemberUpdated
3
- from Backend.config import Telegram
4
  from Backend import db
5
  from datetime import datetime
6
  from Backend.logger import LOGGER
7
  from pyrogram.enums import ChatMemberStatus
8
 
 
 
9
  @Client.on_chat_member_updated()
10
  async def on_user_join(client: Client, chat_member_updated: ChatMemberUpdated):
11
- if not Telegram.SUBSCRIPTION:
12
  return
13
 
14
  # Check if this update is for the subscription group
15
- if chat_member_updated.chat.id != Telegram.SUBSCRIPTION_GROUP_ID:
16
  return
17
 
18
  # Check if it's a join event (user was not a member, now is a member)
 
1
  from pyrogram import Client, filters
2
  from pyrogram.types import ChatMemberUpdated
3
+ from Backend.helper.settings_manager import SettingsManager
4
  from Backend import db
5
  from datetime import datetime
6
  from Backend.logger import LOGGER
7
  from pyrogram.enums import ChatMemberStatus
8
 
9
+
10
+
11
  @Client.on_chat_member_updated()
12
  async def on_user_join(client: Client, chat_member_updated: ChatMemberUpdated):
13
+ if not SettingsManager.current().subscription:
14
  return
15
 
16
  # Check if this update is for the subscription group
17
+ if chat_member_updated.chat.id != SettingsManager.current().subscription_group_id:
18
  return
19
 
20
  # Check if it's a join event (user was not a member, now is a member)
Backend/pyrofork/plugins/help.py CHANGED
@@ -1,11 +1,13 @@
1
  from pyrogram import Client, filters
2
  from pyrogram.types import Message
3
- from Backend.config import Telegram
4
  from Backend.helper.custom_filter import CustomFilters
5
 
 
 
6
  @Client.on_message(filters.command("help"))
7
  async def help_command(client: Client, message: Message):
8
- if Telegram.SUBSCRIPTION:
9
  text = (
10
  "<b>Bot Commands:</b>\n\n"
11
  "/start - Main menu / Purchase membership\n"
 
1
  from pyrogram import Client, filters
2
  from pyrogram.types import Message
3
+ from Backend.helper.settings_manager import SettingsManager
4
  from Backend.helper.custom_filter import CustomFilters
5
 
6
+
7
+
8
  @Client.on_message(filters.command("help"))
9
  async def help_command(client: Client, message: Message):
10
+ if SettingsManager.current().subscription:
11
  text = (
12
  "<b>Bot Commands:</b>\n\n"
13
  "/start - Main menu / Purchase membership\n"
Backend/pyrofork/plugins/reciever.py CHANGED
@@ -3,7 +3,7 @@ import Backend
3
  from Backend.helper.task_manager import edit_message
4
  from Backend.logger import LOGGER
5
  from Backend import db
6
- from Backend.config import Telegram
7
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
8
  from Backend.helper.metadata import metadata
9
  from pyrogram import filters, Client
@@ -15,6 +15,7 @@ from Backend.helper.encrypt import encode_string
15
  from Backend.helper.metadata import extract_default_id
16
 
17
 
 
18
  file_queue = Queue()
19
  db_lock = Lock()
20
 
@@ -35,7 +36,7 @@ for _ in range(1):
35
 
36
  @Client.on_message(filters.channel & (filters.document | filters.video))
37
  async def file_receive_handler(client: Client, message: Message):
38
- if str(message.chat.id) in Telegram.AUTH_CHANNEL:
39
  try:
40
  if message.video or (message.document and message.document.mime_type.startswith("video/")):
41
  file = message.video or message.document
@@ -78,7 +79,7 @@ async def file_receive_handler(client: Client, message: Message):
78
 
79
  @Client.on_edited_message(filters.channel & (filters.document | filters.video))
80
  async def file_edited_handler(client: Client, message: Message):
81
- if str(message.chat.id) in Telegram.AUTH_CHANNEL:
82
  try:
83
  if message.video or (message.document and message.document.mime_type.startswith("video/")):
84
  file = message.video or message.document
@@ -116,7 +117,7 @@ async def file_deleted_handler(client: Client, messages: list[Message]):
116
  try:
117
 
118
  for message in messages:
119
- if message.chat and str(message.chat.id) in Telegram.AUTH_CHANNEL:
120
  channel = str(message.chat.id).replace("-100", "")
121
  msg_id = message.id
122
 
 
3
  from Backend.helper.task_manager import edit_message
4
  from Backend.logger import LOGGER
5
  from Backend import db
6
+ from Backend.helper.settings_manager import SettingsManager
7
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
8
  from Backend.helper.metadata import metadata
9
  from pyrogram import filters, Client
 
15
  from Backend.helper.metadata import extract_default_id
16
 
17
 
18
+
19
  file_queue = Queue()
20
  db_lock = Lock()
21
 
 
36
 
37
  @Client.on_message(filters.channel & (filters.document | filters.video))
38
  async def file_receive_handler(client: Client, message: Message):
39
+ if str(message.chat.id) in SettingsManager.current().auth_channels:
40
  try:
41
  if message.video or (message.document and message.document.mime_type.startswith("video/")):
42
  file = message.video or message.document
 
79
 
80
  @Client.on_edited_message(filters.channel & (filters.document | filters.video))
81
  async def file_edited_handler(client: Client, message: Message):
82
+ if str(message.chat.id) in SettingsManager.current().auth_channels:
83
  try:
84
  if message.video or (message.document and message.document.mime_type.startswith("video/")):
85
  file = message.video or message.document
 
117
  try:
118
 
119
  for message in messages:
120
+ if message.chat and str(message.chat.id) in SettingsManager.current().auth_channels:
121
  channel = str(message.chat.id).replace("-100", "")
122
  msg_id = message.id
123
 
Backend/pyrofork/plugins/scanner.py CHANGED
@@ -18,7 +18,7 @@ from pyrogram.errors import FloodWait, ChannelPrivate, ChatAdminRequired
18
  from Backend.helper.custom_filter import CustomFilters
19
  from Backend.logger import LOGGER
20
  from Backend import db
21
- from Backend.config import Telegram
22
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
23
  from Backend.helper.metadata import metadata
24
  from Backend.helper.encrypt import encode_string
@@ -278,7 +278,7 @@ async def scan_command(client: Client, message: Message):
278
  if len(args) > 1:
279
  target_channels = [args[1].strip()]
280
  else:
281
- target_channels = list(Telegram.AUTH_CHANNEL)
282
 
283
  if not target_channels:
284
  await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
@@ -361,7 +361,7 @@ async def rescan_command(client: Client, message: Message):
361
  )
362
  return
363
 
364
- channels = list(Telegram.AUTH_CHANNEL)
365
  if not channels:
366
  await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
367
  return
 
18
  from Backend.helper.custom_filter import CustomFilters
19
  from Backend.logger import LOGGER
20
  from Backend import db
21
+ from Backend.helper.settings_manager import SettingsManager
22
  from Backend.helper.pyro import clean_filename, get_readable_file_size, remove_urls
23
  from Backend.helper.metadata import metadata
24
  from Backend.helper.encrypt import encode_string
 
278
  if len(args) > 1:
279
  target_channels = [args[1].strip()]
280
  else:
281
+ target_channels = list(SettingsManager.current().auth_channels)
282
 
283
  if not target_channels:
284
  await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
 
361
  )
362
  return
363
 
364
+ channels = list(SettingsManager.current().auth_channels)
365
  if not channels:
366
  await message.reply_text("❌ No AUTH_CHANNELs configured.", quote=True)
367
  return
Backend/pyrofork/plugins/start.py CHANGED
@@ -1,18 +1,20 @@
1
  from pyrogram import filters, Client, enums
2
  from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
3
  from Backend.helper.custom_filter import CustomFilters
 
4
  from Backend.config import Telegram
5
  from Backend import db
6
  from datetime import datetime
7
 
 
8
  @Client.on_message(filters.command('start') & filters.private, group=10)
9
  async def send_start_message(client: Client, message: Message):
10
  try:
11
  user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
12
- base_url = Telegram.BASE_URL
13
  addon_url = f"{base_url}/stremio/manifest.json"
14
 
15
- if not Telegram.SUBSCRIPTION:
16
  if user_id != Telegram.OWNER_ID:
17
  return
18
  user_name = (message.from_user.first_name or message.from_user.username or f"User {user_id}") if message.from_user else f"Chat {user_id}"
 
1
  from pyrogram import filters, Client, enums
2
  from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
3
  from Backend.helper.custom_filter import CustomFilters
4
+ from Backend.helper.settings_manager import SettingsManager
5
  from Backend.config import Telegram
6
  from Backend import db
7
  from datetime import datetime
8
 
9
+
10
  @Client.on_message(filters.command('start') & filters.private, group=10)
11
  async def send_start_message(client: Client, message: Message):
12
  try:
13
  user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
14
+ base_url = SettingsManager.current().base_url
15
  addon_url = f"{base_url}/stremio/manifest.json"
16
 
17
+ if not SettingsManager.current().subscription:
18
  if user_id != Telegram.OWNER_ID:
19
  return
20
  user_name = (message.from_user.first_name or message.from_user.username or f"User {user_id}") if message.from_user else f"Chat {user_id}"
Backend/pyrofork/plugins/subscription.py CHANGED
@@ -1,15 +1,18 @@
1
  from pyrogram import Client, filters
2
  from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
3
  from Backend.config import Telegram
 
4
  from Backend import db
5
  from datetime import datetime, timedelta
6
  import asyncio
7
 
8
  from bson.objectid import ObjectId
9
 
 
 
10
  @Client.on_callback_query(filters.regex(r"^plan_([a-fA-F0-9]{24})$"))
11
  async def plan_selection(client: Client, callback_query: CallbackQuery):
12
- if not Telegram.SUBSCRIPTION:
13
  return await callback_query.answer("Subscriptions are not enabled.", show_alert=True)
14
 
15
  plan_id = callback_query.matches[0].group(1)
@@ -85,7 +88,7 @@ async def plan_selection(client: Client, callback_query: CallbackQuery):
85
 
86
  @Client.on_message(filters.photo & filters.private)
87
  async def handle_payment_screenshot(client: Client, message: Message):
88
- if not Telegram.SUBSCRIPTION:
89
  return
90
 
91
  # Safely resolve sender ID
@@ -134,7 +137,7 @@ async def handle_payment_screenshot(client: Client, message: Message):
134
  f"Please review the screenshot above and approve or reject."
135
  )
136
 
137
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
138
  admin_messages = []
139
  for approver_id in approver_ids:
140
  try:
@@ -171,7 +174,7 @@ async def handle_payment_screenshot(client: Client, message: Message):
171
 
172
  @Client.on_callback_query(filters.regex(r"^(approve|reject)_(\d+)$"))
173
  async def admin_review(client: Client, callback_query: CallbackQuery):
174
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
175
  if callback_query.from_user.id not in approver_ids:
176
  return await callback_query.answer("You are not authorized to perform this action.", show_alert=True)
177
 
@@ -196,7 +199,7 @@ async def admin_review(client: Client, callback_query: CallbackQuery):
196
  user_name = (user_obj.get("first_name") or user_obj.get("username") or str(target_user_id)) if user_obj else str(target_user_id)
197
  token_doc = await db.add_api_token(name=user_name, user_id=target_user_id)
198
  token_str = token_doc.get("token")
199
- addon_url = f"{Telegram.BASE_URL}/stremio/{token_str}/manifest.json"
200
  except Exception as te:
201
  token_str = None
202
  addon_url = None
@@ -204,7 +207,7 @@ async def admin_review(client: Client, callback_query: CallbackQuery):
204
  # Generate invite link for the group
205
  try:
206
  invite_link = await client.create_chat_invite_link(
207
- chat_id=Telegram.SUBSCRIPTION_GROUP_ID,
208
  member_limit=1,
209
  expire_date=datetime.utcnow() + timedelta(days=1)
210
  )
@@ -318,7 +321,7 @@ async def admin_review(client: Client, callback_query: CallbackQuery):
318
 
319
  @Client.on_message(filters.command("status"))
320
  async def check_status(client: Client, message: Message):
321
- if not Telegram.SUBSCRIPTION:
322
  return
323
 
324
  user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
 
1
  from pyrogram import Client, filters
2
  from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
3
  from Backend.config import Telegram
4
+ from Backend.helper.settings_manager import SettingsManager
5
  from Backend import db
6
  from datetime import datetime, timedelta
7
  import asyncio
8
 
9
  from bson.objectid import ObjectId
10
 
11
+
12
+
13
  @Client.on_callback_query(filters.regex(r"^plan_([a-fA-F0-9]{24})$"))
14
  async def plan_selection(client: Client, callback_query: CallbackQuery):
15
+ if not SettingsManager.current().subscription:
16
  return await callback_query.answer("Subscriptions are not enabled.", show_alert=True)
17
 
18
  plan_id = callback_query.matches[0].group(1)
 
88
 
89
  @Client.on_message(filters.photo & filters.private)
90
  async def handle_payment_screenshot(client: Client, message: Message):
91
+ if not SettingsManager.current().subscription:
92
  return
93
 
94
  # Safely resolve sender ID
 
137
  f"Please review the screenshot above and approve or reject."
138
  )
139
 
140
+ approver_ids = SettingsManager.current().approver_ids if SettingsManager.current().approver_ids else [Telegram.OWNER_ID]
141
  admin_messages = []
142
  for approver_id in approver_ids:
143
  try:
 
174
 
175
  @Client.on_callback_query(filters.regex(r"^(approve|reject)_(\d+)$"))
176
  async def admin_review(client: Client, callback_query: CallbackQuery):
177
+ approver_ids = SettingsManager.current().approver_ids if SettingsManager.current().approver_ids else [Telegram.OWNER_ID]
178
  if callback_query.from_user.id not in approver_ids:
179
  return await callback_query.answer("You are not authorized to perform this action.", show_alert=True)
180
 
 
199
  user_name = (user_obj.get("first_name") or user_obj.get("username") or str(target_user_id)) if user_obj else str(target_user_id)
200
  token_doc = await db.add_api_token(name=user_name, user_id=target_user_id)
201
  token_str = token_doc.get("token")
202
+ addon_url = f"{SettingsManager.current().base_url}/stremio/{token_str}/manifest.json"
203
  except Exception as te:
204
  token_str = None
205
  addon_url = None
 
207
  # Generate invite link for the group
208
  try:
209
  invite_link = await client.create_chat_invite_link(
210
+ chat_id=SettingsManager.current().subscription_group_id,
211
  member_limit=1,
212
  expire_date=datetime.utcnow() + timedelta(days=1)
213
  )
 
321
 
322
  @Client.on_message(filters.command("status"))
323
  async def check_status(client: Client, message: Message):
324
+ if not SettingsManager.current().subscription:
325
  return
326
 
327
  user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
Backend/pyrofork/plugins/utilities.py CHANGED
@@ -6,8 +6,6 @@ Commands (owner-only, private chat):
6
  /search <title> — Search your DB for a movie or show
7
  /dbcheck — Find orphaned stream entries (dead Telegram messages)
8
  /dbcheck purge — Find and delete orphaned entries
9
- /exportchannels — Export AUTH_CHANNEL list as JSON
10
- /importchannels <json> — Import channels from JSON
11
  """
12
 
13
  import asyncio
@@ -21,7 +19,7 @@ from pymongo.errors import CursorNotFound
21
  from Backend.helper.custom_filter import CustomFilters
22
  from Backend.logger import LOGGER
23
  from Backend import db, StartTime, __version__
24
- from Backend.config import Telegram
25
  from Backend.helper.encrypt import decode_string
26
 
27
 
@@ -102,7 +100,7 @@ async def stats_command(client: Client, message: Message):
102
  pass
103
 
104
  uptime_sec = int(time.time() - StartTime)
105
- channels_count = len(Telegram.AUTH_CHANNEL)
106
 
107
  text = (
108
  f"<blockquote>📊 <b>Telegram-Stremio v{__version__}</b></blockquote>\n\n"
@@ -428,104 +426,3 @@ async def dbcheck_command(client: Client, message: Message):
428
  except Exception as e:
429
  LOGGER.error(f"[DBCheck] Error: {e}")
430
  await status_msg.edit_text(f"❌ DB check failed: {e}")
431
-
432
-
433
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
434
- # /exportchannels & /importchannels — Backup/restore channel config
435
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
436
-
437
- @Client.on_message(filters.command('exportchannels') & filters.private & CustomFilters.owner, group=10)
438
- async def export_channels(client: Client, message: Message):
439
- """Export current AUTH_CHANNEL list as a copyable JSON block."""
440
- channels_data = []
441
- for ch_id in Telegram.AUTH_CHANNEL:
442
- entry = {"id": ch_id}
443
- try:
444
- chat = await client.get_chat(int(ch_id))
445
- entry["name"] = getattr(chat, "title", "")
446
- entry["members"] = getattr(chat, "members_count", 0)
447
- except Exception:
448
- entry["name"] = "[inaccessible]"
449
- channels_data.append(entry)
450
-
451
- export = {
452
- "version": __version__,
453
- "exported_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
454
- "channels": channels_data,
455
- }
456
-
457
- json_str = json.dumps(export, indent=2, ensure_ascii=False)
458
-
459
- await message.reply_text(
460
- f"<blockquote>📤 <b>Channel Export</b></blockquote>\n\n"
461
- f"<pre>{json_str}</pre>\n\n"
462
- f"<i>Use /importchannels to restore this on another instance.</i>",
463
- quote=True,
464
- parse_mode=enums.ParseMode.HTML,
465
- )
466
-
467
-
468
- @Client.on_message(filters.command('importchannels') & filters.private & CustomFilters.owner, group=10)
469
- async def import_channels(client: Client, message: Message):
470
- """Import channels from a JSON export block."""
471
- args = message.text.split(maxsplit=1)
472
- if len(args) < 2:
473
- await message.reply_text(
474
- "Usage: /importchannels <code>&lt;json&gt;</code>\n\n"
475
- "Paste the JSON output from /exportchannels after the command.",
476
- quote=True,
477
- parse_mode=enums.ParseMode.HTML,
478
- )
479
- return
480
-
481
- raw = args[1].strip()
482
- try:
483
- data = json.loads(raw)
484
- except json.JSONDecodeError as e:
485
- await message.reply_text(
486
- f"❌ Invalid JSON: <code>{e}</code>",
487
- quote=True,
488
- parse_mode=enums.ParseMode.HTML,
489
- )
490
- return
491
-
492
- channels = data.get("channels", [])
493
- if not channels:
494
- await message.reply_text("❌ No channels found in the JSON.", quote=True)
495
- return
496
-
497
- added = 0
498
- skipped = 0
499
- failed = 0
500
-
501
- for entry in channels:
502
- ch_id = str(entry.get("id", "")).strip()
503
- if not ch_id:
504
- continue
505
-
506
- if ch_id in Telegram.AUTH_CHANNEL:
507
- skipped += 1
508
- continue
509
-
510
- # Validate access
511
- try:
512
- await client.get_chat(int(ch_id))
513
- Telegram.AUTH_CHANNEL.append(ch_id)
514
- added += 1
515
- except Exception:
516
- failed += 1
517
-
518
- # Persist
519
- if added > 0:
520
- from Backend.pyrofork.plugins.channels import _save_channels_to_db
521
- await _save_channels_to_db()
522
-
523
- await message.reply_text(
524
- f"<blockquote>📥 <b>Channel Import Complete</b></blockquote>\n\n"
525
- f"✅ Added: <code>{added}</code>\n"
526
- f"⏭ Skipped (already exists): <code>{skipped}</code>\n"
527
- f"❌ Failed (no access): <code>{failed}</code>\n\n"
528
- f"Total AUTH_CHANNELs: <code>{len(Telegram.AUTH_CHANNEL)}</code>",
529
- quote=True,
530
- parse_mode=enums.ParseMode.HTML,
531
- )
 
6
  /search <title> — Search your DB for a movie or show
7
  /dbcheck — Find orphaned stream entries (dead Telegram messages)
8
  /dbcheck purge — Find and delete orphaned entries
 
 
9
  """
10
 
11
  import asyncio
 
19
  from Backend.helper.custom_filter import CustomFilters
20
  from Backend.logger import LOGGER
21
  from Backend import db, StartTime, __version__
22
+ from Backend.helper.settings_manager import SettingsManager
23
  from Backend.helper.encrypt import decode_string
24
 
25
 
 
100
  pass
101
 
102
  uptime_sec = int(time.time() - StartTime)
103
+ channels_count = len(SettingsManager.current().auth_channels)
104
 
105
  text = (
106
  f"<blockquote>📊 <b>Telegram-Stremio v{__version__}</b></blockquote>\n\n"
 
426
  except Exception as e:
427
  LOGGER.error(f"[DBCheck] Error: {e}")
428
  await status_msg.edit_text(f"❌ DB check failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/pyrofork/subscription_plugins/start.py DELETED
@@ -1,98 +0,0 @@
1
- from pyrogram import filters, Client, enums
2
- from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
3
- from Backend.config import Telegram
4
- from Backend import db
5
- from datetime import datetime
6
-
7
- print("DEBUG: Subscription Bot start.py PLUGIN LOADED SUCCESSFULLY!")
8
-
9
- @Client.on_message(filters.command('start'), group=10)
10
- async def send_start_message(client: Client, message: Message):
11
- try:
12
- user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
13
- print(f"DEBUG: Subscription Bot received /start command from {user_id}")
14
-
15
- base_url = Telegram.BASE_URL
16
- addon_url = f"{base_url}/stremio/manifest.json"
17
-
18
- # If subscriptions are NOT enabled
19
- if not Telegram.SUBSCRIPTION:
20
- # Generate or fetch API token for free user
21
- user_name = (message.from_user.first_name or message.from_user.username or f"User {user_id}") if message.from_user else f"Chat {user_id}"
22
- try:
23
- # Ensure user gets a token
24
- token_doc = await db.add_api_token(name=user_name, user_id=user_id)
25
- token_str = token_doc.get("token")
26
- addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
27
- except Exception as e:
28
- print(f"DEBUG: Error ensuring token for free user: {e}")
29
-
30
- await message.reply_text(
31
- '🎉 <b>Welcome to the Telegram Stremio Media Server!</b>\n\n'
32
- 'Here is your personal Stremio Addon link:\n\n'
33
- '🎬 <b>Stremio Addon — Install Link:</b>\n'
34
- f'<code>{addon_url}</code>\n\n'
35
- 'Tap the link above → <b>Install</b> in Stremio to start watching!',
36
- quote=True,
37
- parse_mode=enums.ParseMode.HTML
38
- )
39
- return
40
-
41
- # Subscription logic (When SUBSCRIPTION=True)
42
- user = await db.get_user(user_id)
43
- now = datetime.utcnow()
44
-
45
- # Check if user has an active subscription
46
- is_active = False
47
- if user and user.get("subscription_status") == "active":
48
- if user.get("subscription_expiry") and user.get("subscription_expiry") > now:
49
- is_active = True
50
- else:
51
- await db.mark_user_expired(user_id)
52
-
53
- if not is_active:
54
- plans = await db.get_subscription_plans()
55
- if not plans:
56
- return await message.reply_text(
57
- '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
58
- 'Currently, no subscription plans are set up. Please contact the administrator.',
59
- quote=True,
60
- parse_mode=enums.ParseMode.HTML
61
- )
62
-
63
- keyboard_buttons = []
64
- for plan in plans:
65
- keyboard_buttons.append([InlineKeyboardButton(f"{plan['days']} Days - ₹{plan['price']}", callback_data=f"plan_{plan['_id']}")])
66
-
67
- keyboard = InlineKeyboardMarkup(keyboard_buttons)
68
-
69
- return await message.reply_text(
70
- '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
71
- 'Access to the Stremio Addon requires an active subscription.\n'
72
- 'Please select a subscription plan below to continue:',
73
- reply_markup=keyboard,
74
- quote=True,
75
- parse_mode=enums.ParseMode.HTML
76
- )
77
-
78
- # User is active, fetch their token
79
- all_tokens = await db.get_all_api_tokens()
80
- token_doc = next((t for t in all_tokens if t.get("user_id") == user_id), None)
81
-
82
- if token_doc and "token" in token_doc:
83
- token_str = token_doc["token"]
84
- addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
85
-
86
- await message.reply_text(
87
- '🎉 <b>Welcome back to the Telegram Stremio Subscription Manager!</b>\n\n'
88
- 'Your subscription is active. Here is your personal addon link:\n\n'
89
- '🎬 <b>Stremio Addon — Install Link:</b>\n'
90
- f'<code>{addon_url}</code>\n\n'
91
- 'Tap the link above → <b>Install</b> in Stremio to start watching!',
92
- quote=True,
93
- parse_mode=enums.ParseMode.HTML
94
- )
95
-
96
- except Exception as e:
97
- await message.reply_text(f"⚠️ Error: {e}")
98
- print(f"Error in Subscription Bot /start handler: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/pyrofork/subscription_plugins/subscription.py DELETED
@@ -1,377 +0,0 @@
1
- from pyrogram import Client, filters
2
- from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
3
- from Backend.config import Telegram
4
- from Backend import db
5
- from datetime import datetime, timedelta
6
- import asyncio
7
-
8
- from bson.objectid import ObjectId
9
-
10
- @Client.on_callback_query(filters.regex(r"^plan_([a-fA-F0-9]{24})$"))
11
- async def plan_selection(client: Client, callback_query: CallbackQuery):
12
- if not Telegram.SUBSCRIPTION:
13
- return await callback_query.answer("Subscriptions are not enabled.", show_alert=True)
14
-
15
- plan_id = callback_query.matches[0].group(1)
16
-
17
- plans = await db.get_subscription_plans()
18
- plan = next((p for p in plans if p["_id"] == plan_id), None)
19
-
20
- if not plan:
21
- return await callback_query.answer("Invalid plan.", show_alert=True)
22
-
23
- duration = plan["days"]
24
- await callback_query.answer()
25
-
26
- user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
27
- first_name = callback_query.from_user.first_name if callback_query.from_user else callback_query.message.chat.title
28
- username = callback_query.from_user.username if callback_query.from_user else callback_query.message.chat.username
29
-
30
- # Store initial user interaction if needed
31
- await db.update_user_interaction(user_id, first_name, username)
32
-
33
- # Calculate expiry
34
- user = await db.get_user(user_id)
35
- now = datetime.utcnow()
36
- current_expiry = user.get("subscription_expiry") if user else None
37
-
38
- if current_expiry and current_expiry > now:
39
- new_expiry = current_expiry + timedelta(days=int(duration))
40
- else:
41
- new_expiry = now + timedelta(days=int(duration))
42
-
43
- expiry_str = new_expiry.strftime("%Y-%m-%d %H:%M UTC")
44
-
45
- text = (
46
- f"<b>✅ Plan Selected: {plan['days']} Days</b>\n\n"
47
- f"<b>💰 Price:</b> ₹{plan['price']}\n"
48
- f"<b>📅 Expiry (if approved now):</b> {expiry_str}\n\n"
49
- f"<b>📋 Payment Instructions:</b>\n"
50
- f"1. Pay ₹{plan['price']} to the admin.\n"
51
- f"2. <b>Send your payment screenshot directly here (in this chat)</b>.\n"
52
- f" The admin will review and activate your subscription."
53
- )
54
-
55
- # Set pending payment state (price stored for admin display)
56
- await db.set_pending_payment(user_id, int(duration), 0, price=plan.get("price", 0))
57
-
58
- # Add cancel button
59
- keyboard = InlineKeyboardMarkup([
60
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_payment")]
61
- ])
62
-
63
- dm_sent = False
64
- try:
65
- msg = await client.send_message(
66
- chat_id=user_id,
67
- text=text,
68
- reply_markup=keyboard,
69
- )
70
- dm_sent = True
71
-
72
- async def delete_msg(message):
73
- await asyncio.sleep(120)
74
- try:
75
- await message.delete()
76
- except Exception:
77
- pass
78
-
79
- asyncio.create_task(delete_msg(msg))
80
- except Exception as e:
81
- print(f"Could not DM user {user_id}: {e}")
82
-
83
- if dm_sent:
84
- await callback_query.answer("✅ Check your DM for payment instructions!", show_alert=True)
85
- else:
86
- # Fallback: reply in current chat if DM fails (user hasn't started bot)
87
- fallback_msg = await callback_query.message.reply_text(
88
- text + "\n\n⚠️ <i>Please start a DM with the bot first by clicking its username, then send your screenshot there.</i>",
89
- reply_markup=keyboard,
90
- quote=True,
91
- )
92
- await callback_query.answer()
93
-
94
- async def delete_msg(message):
95
- await asyncio.sleep(120)
96
- try:
97
- await message.delete()
98
- except Exception:
99
- pass
100
-
101
- asyncio.create_task(delete_msg(fallback_msg))
102
-
103
- @Client.on_callback_query(filters.regex(r"^cancel_payment$"))
104
- async def cancel_payment_handler(client: Client, callback_query: CallbackQuery):
105
- user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
106
-
107
- # Remove pending payment
108
- await db.reject_payment(user_id)
109
-
110
- await callback_query.answer("Payment process cancelled.", show_alert=True)
111
- try:
112
- await callback_query.message.delete()
113
- except Exception:
114
- pass
115
-
116
-
117
- @Client.on_message(filters.photo & filters.private)
118
- async def handle_payment_screenshot(client: Client, message: Message):
119
- if not Telegram.SUBSCRIPTION:
120
- return
121
-
122
- # Safely resolve sender ID
123
- sender_id = (message.from_user.id if message.from_user else None) \
124
- or (message.sender_chat.id if message.sender_chat else None) \
125
- or message.chat.id
126
-
127
- try:
128
- print(f"DEBUG: handle_payment_screenshot triggered by {sender_id}")
129
- # Check if user has a pending payment request
130
- user = await db.get_user(sender_id)
131
- print(f"DEBUG: user from DB = {user}")
132
- if not user or "pending_payment" not in user:
133
- # No active payment flow - tell the user what to do
134
- print(f"DEBUG: No pending_payment found for {sender_id}")
135
- await message.reply_text(
136
- "ℹ️ We received your photo, but you don't have an active payment request.\n\n"
137
- "Please use /start to select a subscription plan first, then send your payment screenshot.",
138
- quote=True
139
- )
140
- return
141
-
142
- pending = user["pending_payment"]
143
- duration = pending.get("duration", "?")
144
- price = pending.get("price", "?")
145
-
146
- # --- Admin notification ---
147
- keyboard = InlineKeyboardMarkup([
148
- [
149
- InlineKeyboardButton("✅ Approve", callback_data=f"approve_{sender_id}"),
150
- InlineKeyboardButton("❌ Reject", callback_data=f"reject_{sender_id}")
151
- ]
152
- ])
153
-
154
- user_mention = message.from_user.mention if message.from_user else f"User {sender_id}"
155
- username_str = f"@{message.from_user.username}" if (message.from_user and message.from_user.username) else "N/A"
156
-
157
- admin_text = (
158
- f"<b>💰 New Payment Screenshot Received</b>\n\n"
159
- f"<b>👤 User:</b> {user_mention}\n"
160
- f"<b>🆔 User ID:</b> <code>{sender_id}</code>\n"
161
- f"<b>🔗 Username:</b> {username_str}\n\n"
162
- f"<b>📦 Plan Details:</b>\n"
163
- f" • Duration: <b>{duration} days</b>\n"
164
- f" • Price: <b>₹{price}</b>\n\n"
165
- f"Please review the screenshot above and approve or reject."
166
- )
167
-
168
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
169
- admin_messages = []
170
- for approver_id in approver_ids:
171
- try:
172
- sent = await message.copy(approver_id, caption=admin_text, reply_markup=keyboard)
173
- admin_messages.append({"chat_id": approver_id, "message_id": sent.id})
174
- except Exception as e:
175
- print(f"Failed to forward screenshot to approver {approver_id}: {e}")
176
-
177
- # Update pending state with screenshot message ID + all admin message IDs
178
- await db.set_pending_payment(sender_id, duration, message.id, price=price,
179
- admin_messages=admin_messages)
180
-
181
- if admin_messages:
182
- await message.reply_text(
183
- "✅ <b>Screenshot Received!</b>\n\n"
184
- "Your payment screenshot has been forwarded to the admin for review.\n"
185
- "You will be notified once it's approved. Thank you! 🙏",
186
- quote=True
187
- )
188
- else:
189
- await message.reply_text(
190
- "⚠️ Your screenshot was received but we could not reach the admin. "
191
- "Please contact the admin directly.",
192
- quote=True
193
- )
194
-
195
- except Exception as e:
196
- print(f"Error in handle_payment_screenshot: {e}")
197
- await message.reply_text(
198
- f"⚠️ Something went wrong while processing your screenshot. Please try again or contact the admin.\n\nError: {e}",
199
- quote=True
200
- )
201
-
202
-
203
- @Client.on_callback_query(filters.regex(r"^(approve|reject)_(\d+)$"))
204
- async def admin_review(client: Client, callback_query: CallbackQuery):
205
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
206
- if callback_query.from_user.id not in approver_ids:
207
- return await callback_query.answer("You are not authorized to perform this action.", show_alert=True)
208
-
209
- action = callback_query.matches[0].group(1)
210
- target_user_id = int(callback_query.matches[0].group(2))
211
- acting_admin = callback_query.from_user
212
- admin_name = acting_admin.first_name or acting_admin.username or f"Admin {acting_admin.id}"
213
-
214
- # Fetch admin_messages BEFORE any DB write (approve/reject unsets pending_payment)
215
- user_pre = await db.get_user(target_user_id)
216
- if not user_pre or "pending_payment" not in user_pre:
217
- return await callback_query.answer("This request has already been processed.", show_alert=True)
218
-
219
- admin_messages = user_pre["pending_payment"].get("admin_messages", [])
220
-
221
- if action == "approve":
222
- user_data = await db.approve_payment(target_user_id)
223
- if user_data:
224
- # Generate or retrieve existing API token for this user
225
- try:
226
- user_obj = await db.get_user(target_user_id)
227
- user_name = (user_obj.get("first_name") or user_obj.get("username") or str(target_user_id)) if user_obj else str(target_user_id)
228
- token_doc = await db.add_api_token(name=user_name, user_id=target_user_id)
229
- token_str = token_doc.get("token")
230
- addon_url = f"{Telegram.BASE_URL}/stremio/{token_str}/manifest.json"
231
- except Exception as te:
232
- token_str = None
233
- addon_url = None
234
-
235
- # Generate invite link for the group
236
- try:
237
- invite_link = await client.create_chat_invite_link(
238
- chat_id=Telegram.SUBSCRIPTION_GROUP_ID,
239
- member_limit=1,
240
- expire_date=datetime.utcnow() + timedelta(days=1)
241
- )
242
- invite_text = f"\n\n🔗 <b>Group Invite:</b> {invite_link.invite_link}"
243
- except Exception:
244
- invite_text = ""
245
-
246
- expiry_str = user_data["subscription_expiry"].strftime("%Y-%m-%d")
247
-
248
- # Build confirmation message for user
249
- success_text = (
250
- f"🎉 <b>Payment Approved!</b>\n\n"
251
- f"Your subscription is now active until <b>{expiry_str}</b>."
252
- f"{invite_text}"
253
- )
254
- if addon_url:
255
- success_text += (
256
- f"\n\n🎬 <b>Stremio Addon — Install Link:</b>\n"
257
- f"<code>{addon_url}</code>\n\n"
258
- f"Tap the link above → <b>Install</b> in Stremio to start watching!"
259
- )
260
-
261
- await client.send_message(target_user_id, success_text)
262
-
263
- # Determine how to format the user/payment info
264
- duration = user_pre["pending_payment"].get("duration", "?")
265
- price = user_pre["pending_payment"].get("price", "?")
266
-
267
- try:
268
- target_user = await client.get_users(target_user_id)
269
- user_mention = target_user.mention
270
- username_str = f"@{target_user.username}" if target_user.username else "N/A"
271
- except Exception:
272
- user_mention = f"User {target_user_id}"
273
- username_str = "N/A"
274
-
275
- info_text = (
276
- f"👤 <b>User:</b> {user_mention}\n"
277
- f"🆔 <b>User ID:</b> <code>{target_user_id}</code>\n"
278
- f"🔗 <b>Username:</b> {username_str}\n\n"
279
- f"📦 <b>Plan:</b> {duration} days (₹{price})"
280
- )
281
-
282
- # Update acting admin's message
283
- status_caption = f"✅ <b>Approved by {admin_name}</b>\n\n{info_text}"
284
- await callback_query.message.edit_caption(status_caption)
285
-
286
- # Update all OTHER admins' copies
287
- acting_msg_id = callback_query.message.id
288
- for am in admin_messages:
289
- if am["message_id"] == acting_msg_id:
290
- continue
291
- try:
292
- await client.edit_message_caption(
293
- chat_id=am["chat_id"],
294
- message_id=am["message_id"],
295
- caption=status_caption
296
- )
297
- except Exception:
298
- pass
299
- else:
300
- await callback_query.answer("Could not approve — no pending payment found.", show_alert=True)
301
-
302
- elif action == "reject":
303
- success = await db.reject_payment(target_user_id)
304
- if success:
305
- await client.send_message(
306
- target_user_id,
307
- "❌ <b>Payment Rejected</b>\n\nYour recent payment submission was rejected by the admin. Please contact the admin or try submitting again."
308
- )
309
-
310
- # Determine how to format the user/payment info
311
- duration = user_pre["pending_payment"].get("duration", "?")
312
- price = user_pre["pending_payment"].get("price", "?")
313
-
314
- try:
315
- target_user = await client.get_users(target_user_id)
316
- user_mention = target_user.mention
317
- username_str = f"@{target_user.username}" if target_user.username else "N/A"
318
- except Exception:
319
- user_mention = f"User {target_user_id}"
320
- username_str = "N/A"
321
-
322
- info_text = (
323
- f"👤 <b>User:</b> {user_mention}\n"
324
- f"🆔 <b>User ID:</b> <code>{target_user_id}</code>\n"
325
- f"🔗 <b>Username:</b> {username_str}\n\n"
326
- f"📦 <b>Plan:</b> {duration} days (₹{price})"
327
- )
328
-
329
- # Update acting admin's message
330
- status_caption = f"❌ <b>Rejected by {admin_name}</b>\n\n{info_text}"
331
- await callback_query.message.edit_caption(status_caption)
332
-
333
- # Update all OTHER admins' copies
334
- acting_msg_id = callback_query.message.id
335
- for am in admin_messages:
336
- if am["message_id"] == acting_msg_id:
337
- continue
338
- try:
339
- await client.edit_message_caption(
340
- chat_id=am["chat_id"],
341
- message_id=am["message_id"],
342
- caption=status_caption
343
- )
344
- except Exception:
345
- pass
346
- else:
347
- await callback_query.answer("Could not reject — no pending payment found.", show_alert=True)
348
-
349
-
350
- @Client.on_message(filters.command("status"))
351
- async def check_status(client: Client, message: Message):
352
- if not Telegram.SUBSCRIPTION:
353
- return
354
-
355
- user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
356
-
357
- user = await db.get_user(user_id)
358
- if not user or user.get("subscription_status") != "active":
359
- return await message.reply_text("You do not have an active subscription.")
360
-
361
- expiry = user.get("subscription_expiry")
362
- if not expiry:
363
- return await message.reply_text("Error retrieving expiry date.")
364
-
365
- now = datetime.utcnow()
366
- if now > expiry:
367
- return await message.reply_text("Your subscription has expired.")
368
-
369
- remaining = expiry - now
370
- days = remaining.days
371
- hours = remaining.seconds // 3600
372
-
373
- await message.reply_text(
374
- f"<b>Subscription Status:</b> Active ✅\n"
375
- f"<b>Expiry Date:</b> {expiry.strftime('%Y-%m-%d %H:%M UTC')}\n"
376
- f"<b>Time Remaining:</b> {days} days and {hours} hours"
377
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sample_config.env CHANGED
@@ -1,42 +1,12 @@
1
- # Startup Config
2
  API_ID=""
3
  API_HASH=""
4
  BOT_TOKEN=""
5
  HELPER_BOT_TOKEN=""
6
  OWNER_ID=""
7
 
8
- # Optional
9
- REPLACE_MODE="true"
10
- HIDE_CATALOG="false"
11
-
12
- # STORAGE
13
- AUTH_CHANNEL=""
14
  DATABASE=""
15
 
16
- # API
17
- TMDB_API=""
18
-
19
- # SERVER
20
- BASE_URL=""
21
  PORT="8000"
22
-
23
- # UPDATE REPO
24
- UPSTREAM_REPO="https://github.com/weebzone/Telegram-Stremio"
25
- UPSTREAM_BRANCH="master"
26
-
27
- # ADMIN PANNEL
28
- ADMIN_USERNAME="admin"
29
- ADMIN_PASSWORD="admin"
30
-
31
- # SUBSCRIPTION CONFIG
32
- SUBSCRIPTION=False
33
- SUBSCRIPTION_GROUP_ID=""
34
- APPROVER_IDS=""
35
- SUBSCRIPTION_URL=""
36
-
37
- # PROXY CONFIG
38
- HTTP_Proxy_URL=""
39
- SHOW_ProxyAndNonProxyBoth=True
40
-
41
- # MULTI TOKEN CONFIG
42
- # MULTI_TOKEN1="" #Remove the hashtag sign
 
1
+ # Telegram (required)
2
  API_ID=""
3
  API_HASH=""
4
  BOT_TOKEN=""
5
  HELPER_BOT_TOKEN=""
6
  OWNER_ID=""
7
 
8
+ # Database (required — comma-separated URIs, exactly 2: tracking, storage_1)
 
 
 
 
 
9
  DATABASE=""
10
 
11
+ # Server (required)
 
 
 
 
12
  PORT="8000"