weebzone commited on
Commit
1404692
·
1 Parent(s): b65f321
Files changed (48) hide show
  1. .gitignore +13 -0
  2. .python-version +1 -0
  3. Backend/__init__.py +14 -0
  4. Backend/__main__.py +78 -0
  5. Backend/config.py +27 -0
  6. Backend/fastapi/__init__.py +8 -0
  7. Backend/fastapi/main.py +137 -0
  8. Backend/fastapi/routes/api_routes.py +164 -0
  9. Backend/fastapi/routes/stream_routes.py +106 -0
  10. Backend/fastapi/routes/stremio_routes.py +181 -0
  11. Backend/fastapi/routes/template_routes.py +189 -0
  12. Backend/fastapi/security/credentials.py +28 -0
  13. Backend/fastapi/templates/base.html +96 -0
  14. Backend/fastapi/templates/dashboard.html +273 -0
  15. Backend/fastapi/templates/login.html +47 -0
  16. Backend/fastapi/templates/media_edit.html +533 -0
  17. Backend/fastapi/templates/media_management.html +476 -0
  18. Backend/fastapi/templates/public_status.html +70 -0
  19. Backend/fastapi/templates/stremio_guide.html +114 -0
  20. Backend/fastapi/themes.py +74 -0
  21. Backend/helper/custom_dl.py +146 -0
  22. Backend/helper/custom_filter.py +12 -0
  23. Backend/helper/database.py +738 -0
  24. Backend/helper/encrypt.py +54 -0
  25. Backend/helper/exceptions.py +6 -0
  26. Backend/helper/imdb.py +106 -0
  27. Backend/helper/metadata.py +232 -0
  28. Backend/helper/modal.py +51 -0
  29. Backend/helper/pyro.py +172 -0
  30. Backend/helper/task_manager.py +32 -0
  31. Backend/logger.py +31 -0
  32. Backend/pyrofork/bot.py +29 -0
  33. Backend/pyrofork/clients.py +56 -0
  34. Backend/pyrofork/plugins/log.py +21 -0
  35. Backend/pyrofork/plugins/manual.py +39 -0
  36. Backend/pyrofork/plugins/reciever.py +75 -0
  37. Backend/pyrofork/plugins/restart.py +36 -0
  38. Backend/pyrofork/plugins/start.py +28 -0
  39. Dockerfile +24 -0
  40. README.md +501 -0
  41. bump-version.py +62 -0
  42. heroku.yml +3 -0
  43. pyproject.toml +28 -0
  44. requirements.txt +11 -0
  45. sample_config.env +30 -0
  46. start.sh +1 -0
  47. update.py +57 -0
  48. uv.lock +0 -0
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv
2
+ media/
3
+ *.strm
4
+ log.txt
5
+ **/__pycache__/
6
+ *.session
7
+ *.session-journal
8
+ *.session-shm
9
+ *.session-wal
10
+ /.vscode/
11
+ test.py
12
+ config.env
13
+ *.pyc
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
Backend/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from Backend.helper.database import Database
2
+ from time import time
3
+ from datetime import datetime
4
+ import pytz
5
+
6
+ timezone = pytz.timezone("Asia/Kolkata")
7
+ now = datetime.now(timezone)
8
+ StartTime = time()
9
+
10
+
11
+ USE_DEFAULT_ID: str = None
12
+ db = Database()
13
+
14
+ __version__ = "1.0.0"
Backend/__main__.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import get_event_loop, sleep as asleep
2
+ import asyncio
3
+ import logging
4
+ from traceback import format_exc
5
+ from pyrogram import idle
6
+ from Backend import __version__, db
7
+ from Backend.logger import LOGGER
8
+ from Backend.fastapi import server
9
+ from Backend.helper.pyro import restart_notification, setup_bot_commands
10
+ from Backend.pyrofork.bot import Helper, StreamBot
11
+ from Backend.pyrofork.clients import initialize_clients
12
+
13
+ loop = get_event_loop()
14
+
15
+ async def start_services():
16
+ try:
17
+ LOGGER.info(f"Initializing Telegram-Stremio v-{__version__}")
18
+ await asleep(1.2)
19
+
20
+ await db.connect()
21
+ await asleep(1.2)
22
+
23
+ await StreamBot.start()
24
+ StreamBot.username = StreamBot.me.username
25
+ LOGGER.info(f"Bot Client : [@{StreamBot.username}]")
26
+ await asleep(1.2)
27
+
28
+ await Helper.start()
29
+ Helper.username = Helper.me.username
30
+ LOGGER.info(f"Helper Bot Client : [@{Helper.username}]")
31
+ await asleep(1.2)
32
+
33
+ LOGGER.info("Initializing Multi Clients...")
34
+ await initialize_clients()
35
+ await asleep(2)
36
+
37
+ await setup_bot_commands(StreamBot)
38
+ await asleep(2)
39
+
40
+ LOGGER.info('Initializing Telegram-Stremio Web Server...')
41
+ await restart_notification()
42
+ loop.create_task(server.serve())
43
+
44
+ LOGGER.info("Telegram-Stremio Started Successfully!")
45
+ await idle()
46
+ except Exception:
47
+ LOGGER.error("Error during startup:\n" + format_exc())
48
+
49
+ async def stop_services():
50
+ try:
51
+ LOGGER.info("Stopping services...")
52
+
53
+ pending_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
54
+ for task in pending_tasks:
55
+ task.cancel()
56
+
57
+ await asyncio.gather(*pending_tasks, return_exceptions=True)
58
+
59
+ await StreamBot.stop()
60
+ await Helper.stop()
61
+
62
+ await db.disconnect()
63
+
64
+ LOGGER.info("Services stopped successfully.")
65
+ except Exception:
66
+ LOGGER.error("Error during shutdown:\n" + format_exc())
67
+
68
+ if __name__ == '__main__':
69
+ try:
70
+ loop.run_until_complete(start_services())
71
+ except KeyboardInterrupt:
72
+ LOGGER.info('Service Stopping...')
73
+ except Exception:
74
+ LOGGER.error(format_exc())
75
+ finally:
76
+ loop.run_until_complete(stop_services())
77
+ loop.stop()
78
+ logging.shutdown()
Backend/config.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import getenv, path
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv(path.join(path.dirname(path.dirname(__file__)), "config.env"))
5
+
6
+ class Telegram:
7
+ API_ID = int(getenv("API_ID", "0"))
8
+ API_HASH = getenv("API_HASH", "")
9
+ BOT_TOKEN = getenv("BOT_TOKEN", "")
10
+ HELPER_BOT_TOKEN = getenv("HELPER_BOT_TOKEN", "")
11
+
12
+ BASE_URL = getenv("BASE_URL", "").rstrip('/')
13
+ PORT = int(getenv("PORT", "8000"))
14
+
15
+ AUTH_CHANNEL = [channel.strip() for channel in (getenv("AUTH_CHANNEL") or "").split(",") if channel.strip()]
16
+ DATABASE = [db.strip() for db in (getenv("DATABASE") or "").split(",") if db.strip()]
17
+
18
+ TMDB_API = getenv("TMDB_API", "")
19
+
20
+ UPSTREAM_REPO = getenv("UPSTREAM_REPO", "")
21
+ UPSTREAM_BRANCH = getenv("UPSTREAM_BRANCH", "")
22
+
23
+ OWNER_ID = int(getenv("OWNER_ID", "5422223708"))
24
+
25
+ ADMIN_USERNAME = getenv("ADMIN_USERNAME", "fyvio")
26
+ ADMIN_PASSWORD = getenv("ADMIN_PASSWORD", "fyvio")
27
+
Backend/fastapi/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import uvicorn
2
+ from Backend.config import Telegram
3
+ from Backend.fastapi.main import app
4
+
5
+
6
+ Port = Telegram.PORT
7
+ config = uvicorn.Config(app=app, host='0.0.0.0', port=Port)
8
+ server = uvicorn.Server(config)
Backend/fastapi/main.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, Form, Depends, Query
2
+ from fastapi.responses import HTMLResponse, RedirectResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.staticfiles import StaticFiles
5
+ from starlette.middleware.sessions import SessionMiddleware
6
+ from Backend import __version__
7
+
8
+ from Backend.fastapi.security.credentials import require_auth
9
+ from Backend.fastapi.routes.stream_routes import router as stream_router
10
+ from Backend.fastapi.routes.stremio_routes import router as stremio_router
11
+ from Backend.fastapi.routes.template_routes import (
12
+ login_page, login_post, logout, set_theme, dashboard_page,
13
+ media_management_page, edit_media_page, public_status_page, stremio_guide_page
14
+ )
15
+ from Backend.fastapi.routes.api_routes import (
16
+ list_media_api, delete_media_api, update_media_api,
17
+ delete_movie_quality_api, delete_tv_quality_api,
18
+ delete_tv_episode_api, delete_tv_season_api
19
+ )
20
+
21
+ app = FastAPI(
22
+ title="Telegram Stremio Media Server",
23
+ description="A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery.",
24
+ version=__version__
25
+ )
26
+
27
+ # --- Middleware Setup ---
28
+ app.add_middleware(SessionMiddleware, secret_key="f6d2e3b9a0f43d9a2e6a56b2d3175cd9c05bbfe31d95ed2a7306b57cb1a8b6f0")
29
+ app.add_middleware(
30
+ CORSMiddleware,
31
+ allow_origins=["*"],
32
+ allow_credentials=True,
33
+ allow_methods=["*"],
34
+ allow_headers=["*"],
35
+ )
36
+
37
+ try:
38
+ app.mount("/static", StaticFiles(directory="Backend/fastapi/static"), name="static")
39
+ except Exception:
40
+ pass
41
+
42
+ # --- Include existing API routers ---
43
+ app.include_router(stream_router)
44
+ app.include_router(stremio_router)
45
+
46
+ # --- Public Routes (No Authentication Required) ---
47
+ @app.get("/login", response_class=HTMLResponse)
48
+ async def login_get(request: Request):
49
+ return await login_page(request)
50
+
51
+ @app.post("/login", response_class=HTMLResponse)
52
+ async def login_post_route(request: Request, username: str = Form(...), password: str = Form(...)):
53
+ return await login_post(request, username, password)
54
+
55
+ @app.get("/logout")
56
+ async def logout_route(request: Request):
57
+ return await logout(request)
58
+
59
+ @app.post("/set-theme")
60
+ async def set_theme_route(request: Request, theme: str = Form(...)):
61
+ return await set_theme(request, theme)
62
+
63
+ @app.get("/status", response_class=HTMLResponse)
64
+ async def public_status(request: Request):
65
+ return await public_status_page(request)
66
+
67
+ @app.get("/stremio", response_class=HTMLResponse)
68
+ async def stremio_guide(request: Request):
69
+ return await stremio_guide_page(request)
70
+
71
+ # --- Protected Routes (Authentication Required) ---
72
+ @app.get("/", response_class=HTMLResponse)
73
+ async def root(request: Request, _: bool = Depends(require_auth)):
74
+ return await dashboard_page(request, _)
75
+
76
+ @app.get("/media/manage", response_class=HTMLResponse)
77
+ async def media_management(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
78
+ return await media_management_page(request, media_type, _)
79
+
80
+ @app.get("/media/edit", response_class=HTMLResponse)
81
+ async def edit_media(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
82
+ return await edit_media_page(request, tmdb_id, db_index, media_type, _)
83
+
84
+ @app.get("/api/media/list")
85
+ async def list_media(
86
+ media_type: str = Query("movie", regex="^(movie|tv)$"),
87
+ page: int = Query(1, ge=1),
88
+ page_size: int = Query(24, ge=1, le=100),
89
+ search: str = Query("", max_length=100),
90
+ _: bool = Depends(require_auth)
91
+ ):
92
+ return await list_media_api(media_type, page, page_size, search)
93
+
94
+ @app.delete("/api/media/delete")
95
+ async def delete_media(tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
96
+ return await delete_media_api(tmdb_id, db_index, media_type)
97
+
98
+ @app.put("/api/media/update")
99
+ async def update_media(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
100
+ return await update_media_api(request, tmdb_id, db_index, media_type)
101
+
102
+ @app.delete("/api/media/delete-quality")
103
+ async def delete_movie_quality(tmdb_id: int, db_index: int, quality: str, _: bool = Depends(require_auth)):
104
+ return await delete_movie_quality_api(tmdb_id, db_index, quality)
105
+
106
+ @app.delete("/api/media/delete-tv-quality")
107
+ async def delete_tv_quality(tmdb_id: int, db_index: int, season: int, episode: int, quality: str, _: bool = Depends(require_auth)):
108
+ return await delete_tv_quality_api(tmdb_id, db_index, season, episode, quality)
109
+
110
+ @app.delete("/api/media/delete-tv-episode")
111
+ async def delete_tv_episode(tmdb_id: int, db_index: int, season: int, episode: int, _: bool = Depends(require_auth)):
112
+ return await delete_tv_episode_api(tmdb_id, db_index, season, episode)
113
+
114
+ @app.delete("/api/media/delete-tv-season")
115
+ async def delete_tv_season(tmdb_id: int, db_index: int, season: int, _: bool = Depends(require_auth)):
116
+ return await delete_tv_season_api(tmdb_id, db_index, season)
117
+
118
+
119
+ @app.get("/api/system/workloads")
120
+ async def get_workloads(_: bool = Depends(require_auth)):
121
+ try:
122
+ from Backend.pyrofork.bot import work_loads
123
+ return {
124
+ "loads": {
125
+ f"bot{c + 1}": l
126
+ for c, (_, l) in enumerate(
127
+ sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
128
+ )
129
+ } if work_loads else {}
130
+ }
131
+ except Exception as e:
132
+ return {"loads": {}}
133
+
134
+
135
+ @app.exception_handler(401)
136
+ async def auth_exception_handler(request: Request, exc):
137
+ return RedirectResponse(url="/login", status_code=302)
Backend/fastapi/routes/api_routes.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Request, Query, HTTPException
2
+ from Backend import db
3
+
4
+ # --- API Routes for Media Management ---
5
+
6
+ async def list_media_api(
7
+ media_type: str = Query("movie", regex="^(movie|tv)$"),
8
+ page: int = Query(1, ge=1),
9
+ page_size: int = Query(24, ge=1, le=100),
10
+ search: str = Query("", max_length=100)
11
+ ):
12
+ try:
13
+ if search:
14
+ result = await db.search_documents(search, page, page_size)
15
+ filtered_results = [item for item in result['results'] if item.get('media_type') == media_type]
16
+ total_filtered = len(filtered_results)
17
+ start_index = (page - 1) * page_size
18
+ end_index = start_index + page_size
19
+ paged_results = filtered_results[start_index:end_index]
20
+
21
+ return {
22
+ "total_count": total_filtered,
23
+ "current_page": page,
24
+ "total_pages": (total_filtered + page_size - 1) // page_size,
25
+ "movies" if media_type == "movie" else "tv_shows": paged_results
26
+ }
27
+ else:
28
+ if media_type == "movie":
29
+ return await db.sort_movies([], page, page_size)
30
+ else:
31
+ return await db.sort_tv_shows([], page, page_size)
32
+ except Exception as e:
33
+ raise HTTPException(status_code=500, detail=str(e))
34
+
35
+ async def delete_media_api(
36
+ tmdb_id: int,
37
+ db_index: int,
38
+ media_type: str = Query(regex="^(movie|tv)$")
39
+ ):
40
+ try:
41
+ media_type_formatted = "Movie" if media_type == "movie" else "Series"
42
+ result = await db.delete_document(media_type_formatted, tmdb_id, db_index)
43
+ if result:
44
+ return {"message": "Media deleted successfully"}
45
+ else:
46
+ raise HTTPException(status_code=404, detail="Media not found")
47
+ except Exception as e:
48
+ raise HTTPException(status_code=500, detail=str(e))
49
+
50
+ async def update_media_api(
51
+ request: Request,
52
+ tmdb_id: int,
53
+ db_index: int,
54
+ media_type: str = Query(regex="^(movie|tv)$")
55
+ ):
56
+ try:
57
+ update_data = await request.json()
58
+ if 'rating' in update_data and update_data['rating']:
59
+ try:
60
+ update_data['rating'] = float(update_data['rating'])
61
+ except (ValueError, TypeError):
62
+ update_data['rating'] = 0.0
63
+
64
+ if 'release_year' in update_data and update_data['release_year']:
65
+ try:
66
+ update_data['release_year'] = int(update_data['release_year'])
67
+ except (ValueError, TypeError):
68
+ pass
69
+ if 'genres' in update_data:
70
+ if isinstance(update_data['genres'], str):
71
+ update_data['genres'] = [g.strip() for g in update_data['genres'].split(',') if g.strip()]
72
+ elif not isinstance(update_data['genres'], list):
73
+ update_data['genres'] = []
74
+
75
+ if 'languages' in update_data:
76
+ if isinstance(update_data['languages'], str):
77
+ update_data['languages'] = [l.strip() for l in update_data['languages'].split(',') if l.strip()]
78
+ elif not isinstance(update_data['languages'], list):
79
+ update_data['languages'] = []
80
+ if media_type == "movie":
81
+ if 'runtime' in update_data and update_data['runtime']:
82
+ try:
83
+ update_data['runtime'] = int(update_data['runtime'])
84
+ except (ValueError, TypeError):
85
+ pass
86
+ elif media_type == "tv":
87
+ if 'total_seasons' in update_data and update_data['total_seasons']:
88
+ try:
89
+ update_data['total_seasons'] = int(update_data['total_seasons'])
90
+ except (ValueError, TypeError):
91
+ pass
92
+
93
+ if 'total_episodes' in update_data and update_data['total_episodes']:
94
+ try:
95
+ update_data['total_episodes'] = int(update_data['total_episodes'])
96
+ except (ValueError, TypeError):
97
+ pass
98
+ update_data = {k: v for k, v in update_data.items() if v != ""}
99
+ result = await db.update_document(media_type, tmdb_id, db_index, update_data)
100
+ if result:
101
+ return {"message": "Media updated successfully"}
102
+ else:
103
+ raise HTTPException(status_code=404, detail="Media not found or no changes made")
104
+
105
+ except Exception as e:
106
+ raise HTTPException(status_code=500, detail=str(e))
107
+
108
+ async def get_media_details_api(
109
+ tmdb_id: int,
110
+ db_index: int,
111
+ media_type: str = Query(regex="^(movie|tv)$")
112
+ ):
113
+ try:
114
+ result = await db.get_document(media_type, tmdb_id, db_index)
115
+ if result:
116
+ return result
117
+ else:
118
+ raise HTTPException(status_code=404, detail="Media not found")
119
+ except Exception as e:
120
+ raise HTTPException(status_code=500, detail=str(e))
121
+
122
+ async def delete_movie_quality_api(tmdb_id: int, db_index: int, quality: str):
123
+ try:
124
+ result = await db.delete_movie_quality(tmdb_id, db_index, quality)
125
+ if result:
126
+ return {"message": "Quality deleted successfully"}
127
+ else:
128
+ raise HTTPException(status_code=404, detail="Quality not found")
129
+ except Exception as e:
130
+ raise HTTPException(status_code=500, detail=str(e))
131
+
132
+ async def delete_tv_quality_api(
133
+ tmdb_id: int, db_index: int, season: int, episode: int, quality: str
134
+ ):
135
+ try:
136
+ result = await db.delete_tv_quality(tmdb_id, db_index, season, episode, quality)
137
+ if result:
138
+ return {"message": "Quality deleted successfully"}
139
+ else:
140
+ raise HTTPException(status_code=404, detail="Quality not found")
141
+ except Exception as e:
142
+ raise HTTPException(status_code=500, detail=str(e))
143
+
144
+ async def delete_tv_episode_api(
145
+ tmdb_id: int, db_index: int, season: int, episode: int
146
+ ):
147
+ try:
148
+ result = await db.delete_tv_episode(tmdb_id, db_index, season, episode)
149
+ if result:
150
+ return {"message": "Episode deleted successfully"}
151
+ else:
152
+ raise HTTPException(status_code=404, detail="Episode not found")
153
+ except Exception as e:
154
+ raise HTTPException(status_code=500, detail=str(e))
155
+
156
+ async def delete_tv_season_api(tmdb_id: int, db_index: int, season: int):
157
+ try:
158
+ result = await db.delete_tv_season(tmdb_id, db_index, season)
159
+ if result:
160
+ return {"message": "Season deleted successfully"}
161
+ else:
162
+ raise HTTPException(status_code=404, detail="Season not found")
163
+ except Exception as e:
164
+ raise HTTPException(status_code=500, detail=str(e))
Backend/fastapi/routes/stream_routes.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import secrets
3
+ import mimetypes
4
+ from typing import Tuple
5
+ from fastapi import APIRouter, Request, HTTPException
6
+ from fastapi.responses import StreamingResponse
7
+
8
+ from Backend.helper.encrypt import decode_string
9
+ from Backend.helper.exceptions import InvalidHash
10
+ from Backend.helper.custom_dl import ByteStreamer
11
+ from Backend.pyrofork.bot import StreamBot, work_loads, multi_clients
12
+
13
+ router = APIRouter(tags=["Streaming"])
14
+ class_cache = {}
15
+
16
+
17
+ def parse_range_header(range_header: str, file_size: int) -> Tuple[int, int]:
18
+ if not range_header:
19
+ return 0, file_size - 1
20
+ try:
21
+ range_value = range_header.replace("bytes=", "")
22
+ from_str, until_str = range_value.split("-")
23
+ from_bytes = int(from_str)
24
+ until_bytes = int(until_str) if until_str else file_size - 1
25
+ except Exception as e:
26
+ raise HTTPException(status_code=400, detail=f"Invalid Range header: {e}")
27
+
28
+ if (until_bytes > file_size - 1) or (from_bytes < 0) or (until_bytes < from_bytes):
29
+ raise HTTPException(
30
+ status_code=416,
31
+ detail="Range not satisfiable",
32
+ headers={"Content-Range": f"bytes */{file_size}"},
33
+ )
34
+
35
+ return from_bytes, until_bytes
36
+
37
+
38
+ @router.get("/dl/{id}/{name}")
39
+ async def stream_handler(request: Request, id: str, name: str):
40
+ decoded_data = await decode_string(id)
41
+ if not decoded_data.get("msg_id"):
42
+ raise HTTPException(status_code=400, detail="Missing id")
43
+
44
+ chat_id = f"-100{decoded_data['chat_id']}"
45
+ message = await StreamBot.get_messages(int(chat_id), int(decoded_data["msg_id"]))
46
+ file = message.video or message.document
47
+ file_hash = file.file_unique_id[:6]
48
+
49
+ return await media_streamer(
50
+ request,
51
+ chat_id=int(chat_id),
52
+ id=int(decoded_data["msg_id"]),
53
+ secure_hash=file_hash
54
+ )
55
+
56
+
57
+ async def media_streamer(
58
+ request: Request,
59
+ chat_id: int,
60
+ id: int,
61
+ secure_hash: str,
62
+ ) -> StreamingResponse:
63
+ range_header = request.headers.get("Range", "")
64
+ index = min(work_loads, key=work_loads.get)
65
+ faster_client = multi_clients[index]
66
+
67
+ tg_connect = class_cache.get(faster_client)
68
+ if not tg_connect:
69
+ tg_connect = ByteStreamer(faster_client)
70
+ class_cache[faster_client] = tg_connect
71
+
72
+ file_id = await tg_connect.get_file_properties(chat_id=chat_id, message_id=id)
73
+ if file_id.unique_id[:6] != secure_hash:
74
+ raise InvalidHash
75
+
76
+ file_size = file_id.file_size
77
+ from_bytes, until_bytes = parse_range_header(range_header, file_size)
78
+
79
+ chunk_size = 1024 * 1024
80
+ offset = from_bytes - (from_bytes % chunk_size)
81
+ first_part_cut = from_bytes - offset
82
+ last_part_cut = (until_bytes % chunk_size) + 1
83
+ req_length = until_bytes - from_bytes + 1
84
+ part_count = math.ceil(until_bytes / chunk_size) - math.floor(offset / chunk_size)
85
+
86
+ body = tg_connect.yield_file(
87
+ file_id, index, offset, first_part_cut, last_part_cut, part_count, chunk_size
88
+ )
89
+
90
+ file_name = file_id.file_name or f"{secrets.token_hex(2)}.unknown"
91
+ mime_type = file_id.mime_type or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
92
+ if not file_id.file_name and "/" in mime_type:
93
+ file_name = f"{secrets.token_hex(2)}.{mime_type.split('/')[1]}"
94
+
95
+ return StreamingResponse(
96
+ status_code=206 if range_header else 200,
97
+ content=body,
98
+ headers={
99
+ "Content-Type": mime_type,
100
+ "Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}",
101
+ "Content-Length": str(req_length),
102
+ "Content-Disposition": f'inline; filename="{file_name}"',
103
+ "Accept-Ranges": "bytes",
104
+ },
105
+ )
106
+
Backend/fastapi/routes/stremio_routes.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException
2
+ from typing import Optional
3
+ from urllib.parse import unquote
4
+ from Backend.config import Telegram
5
+ from Backend import db, __version__
6
+
7
+ # --- Configuration ---
8
+ BASE_URL = Telegram.BASE_URL
9
+ ADDON_NAME = "Telegram Stremio Media Server"
10
+ ADDON_VERSION = __version__
11
+ PAGE_SIZE = 15
12
+
13
+ router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
14
+
15
+
16
+ # --- Helper Functions ---
17
+ def convert_to_stremio_meta(item: dict) -> dict:
18
+ media_type = "series" if item.get("media_type") == "tv" else "movie"
19
+ stremio_id = f"{item.get('tmdb_id')}-{item.get('db_index')}"
20
+ return {
21
+ "id": stremio_id,
22
+ "type": media_type,
23
+ "name": item.get("title"),
24
+ "poster": item.get("poster"),
25
+ "logo": item.get("logo"),
26
+ "year": item.get("release_year"),
27
+ "background": item.get("backdrop", ""),
28
+ "genres": item.get("genres"),
29
+ "imdbRating": item.get("rating"),
30
+ "description": item.get("description"),
31
+ }
32
+
33
+
34
+ # --- Stremio Endpoints ---
35
+ @router.get("/manifest.json")
36
+ async def get_manifest():
37
+ return {
38
+ "id": "telegram.stremio.media.server",
39
+ "version": ADDON_VERSION,
40
+ "name": ADDON_NAME,
41
+ "logo": "https://i.postimg.cc/XqWnmDXr/Picsart-25-10-09-08-09-45-867.png",
42
+ "description": "Streams movies and series from your Telegram.",
43
+ "types": ["movie", "series"],
44
+ "resources": ["catalog", "meta", "stream"],
45
+ "catalogs": [
46
+ {
47
+ "type": "movie",
48
+ "id": "fyvio_movies",
49
+ "name": "Movies",
50
+ "extra": [{"name": "search"}, {"name": "skip"}]
51
+ },
52
+ {
53
+ "type": "series",
54
+ "id": "fyvio_series",
55
+ "name": "TvShows",
56
+ "extra": [{"name": "search"}, {"name": "skip"}]
57
+ }
58
+ ],
59
+ "idPrefixes": [""]
60
+ }
61
+
62
+
63
+ @router.get("/catalog/{media_type}/{id}/{extra:path}.json")
64
+ @router.get("/catalog/{media_type}/{id}.json")
65
+ async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
66
+ if media_type not in ["movie", "series"]:
67
+ raise HTTPException(status_code=404, detail="Invalid catalog type")
68
+
69
+ search_query = None
70
+ stremio_skip = 0
71
+
72
+ if extra:
73
+ if extra.startswith("search="):
74
+ search_query = unquote(extra.removeprefix("search="))
75
+ elif extra.startswith("skip="):
76
+ try:
77
+ stremio_skip = int(extra.removeprefix("skip="))
78
+ except ValueError:
79
+ stremio_skip = 0
80
+
81
+ page = (stremio_skip // PAGE_SIZE) + 1
82
+
83
+ try:
84
+ if search_query:
85
+ search_results = await db.search_documents(query=search_query, page=page, page_size=PAGE_SIZE)
86
+ all_items = search_results.get("results", [])
87
+ db_media_type = "tv" if media_type == "series" else "movie"
88
+ items = [item for item in all_items if item.get("media_type") == db_media_type]
89
+ else:
90
+ sort_params = [("updated_on", "desc")]
91
+ if media_type == "movie":
92
+ data = await db.sort_movies(sort_params, page=page, page_size=PAGE_SIZE)
93
+ items = data.get("movies", [])
94
+ else:
95
+ data = await db.sort_tv_shows(sort_params, page=page, page_size=PAGE_SIZE)
96
+ items = data.get("tv_shows", [])
97
+ except Exception as e:
98
+ print(f"Error fetching catalog data: {e}")
99
+ return {"metas": []}
100
+
101
+ metas = [convert_to_stremio_meta(item) for item in items]
102
+ return {"metas": metas}
103
+
104
+
105
+ @router.get("/meta/{media_type}/{id}.json")
106
+ async def get_meta(media_type: str, id: str):
107
+ try:
108
+ tmdb_id_str, db_index_str = id.split("-")
109
+ tmdb_id, db_index = int(tmdb_id_str), int(db_index_str)
110
+ except (ValueError, IndexError):
111
+ raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
112
+
113
+ media = await db.get_media_details(tmdb_id=tmdb_id, db_index=db_index)
114
+ if not media:
115
+ return {"meta": {}}
116
+
117
+ meta_obj = {
118
+ "id": id,
119
+ "type": "series" if media.get("media_type") == "tv" else "movie",
120
+ "name": media.get("title", ""),
121
+ "description": media.get("description", ""),
122
+ "year": str(media.get("release_year", "")),
123
+ "imdbRating": str(media.get("rating", "")),
124
+ "genres": media.get("genres", []),
125
+ "poster": media.get("poster", ""),
126
+ "logo": media.get("logo", ""),
127
+ "background": media.get("backdrop", ""),
128
+ "imdb_id": media.get("tmdb_id", "")
129
+ }
130
+
131
+ if media_type == "series" and "seasons" in media:
132
+ series_base_id = id
133
+ videos = []
134
+ for season in sorted(media.get("seasons", []), key=lambda s: s.get("season_number")):
135
+ for episode in sorted(season.get("episodes", []), key=lambda e: e.get("episode_number")):
136
+ episode_id = f"{series_base_id}:{season['season_number']}:{episode['episode_number']}"
137
+ videos.append({
138
+ "id": episode_id,
139
+ "title": episode.get("title", f"Episode {episode['episode_number']}"),
140
+ "season": season.get("season_number"),
141
+ "episode": episode.get("episode_number"),
142
+ "thumbnail": episode.get("episode_backdrop"),
143
+ "imdb_id": episode.get("imdb_id") or media.get("imdb_id"),
144
+ })
145
+ meta_obj["videos"] = videos
146
+
147
+ return {"meta": meta_obj}
148
+
149
+
150
+ @router.get("/stream/{media_type}/{id}.json")
151
+ async def get_streams(media_type: str, id: str):
152
+ try:
153
+ parts = id.split(":")
154
+ base_id = parts[0]
155
+ season_num = int(parts[1]) if len(parts) > 1 else None
156
+ episode_num = int(parts[2]) if len(parts) > 2 else None
157
+ tmdb_id, db_index = map(int, base_id.split("-"))
158
+ except (ValueError, IndexError):
159
+ raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
160
+
161
+ media_details = await db.get_media_details(
162
+ tmdb_id=tmdb_id,
163
+ db_index=db_index,
164
+ season_number=season_num,
165
+ episode_number=episode_num
166
+ )
167
+
168
+ if not media_details or "telegram" not in media_details:
169
+ return {"streams": []}
170
+
171
+ streams = [
172
+ {
173
+ "name": f"{quality.get('name', '')}",
174
+ "title": f"{quality.get('quality', 'HD')}\n💾 {quality.get('size', '')}",
175
+ "url": f"{BASE_URL}/dl/{quality.get('id')}/video.mkv"
176
+ }
177
+ for quality in media_details.get("telegram", [])
178
+ if quality.get("id")
179
+ ]
180
+
181
+ return {"streams": streams}
Backend/fastapi/routes/template_routes.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Request, Form, HTTPException, Depends
2
+ from fastapi.responses import RedirectResponse
3
+ from fastapi.templating import Jinja2Templates
4
+ from Backend.fastapi.security.credentials import verify_credentials, require_auth, is_authenticated, get_current_user
5
+ from Backend.fastapi.themes import get_theme, get_all_themes
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
+ from time import time
11
+
12
+
13
+ templates = Jinja2Templates(directory="Backend/fastapi/templates")
14
+
15
+ async def login_page(request: Request):
16
+ if is_authenticated(request):
17
+ return RedirectResponse(url="/", status_code=302)
18
+
19
+ theme_name = request.session.get("theme", "purple_gradient")
20
+ theme = get_theme(theme_name)
21
+
22
+ return templates.TemplateResponse("login.html", {
23
+ "request": request,
24
+ "theme": theme,
25
+ "themes": get_all_themes(),
26
+ "current_theme": theme_name
27
+ })
28
+
29
+ async def login_post(request: Request, username: str = Form(...), password: str = Form(...)):
30
+ if verify_credentials(username, password):
31
+ request.session["authenticated"] = True
32
+ request.session["username"] = username
33
+ return RedirectResponse(url="/", status_code=302)
34
+ else:
35
+ theme_name = request.session.get("theme", "purple_gradient")
36
+ theme = get_theme(theme_name)
37
+ return templates.TemplateResponse("login.html", {
38
+ "request": request,
39
+ "theme": theme,
40
+ "themes": get_all_themes(),
41
+ "current_theme": theme_name,
42
+ "error": "Invalid credentials"
43
+ })
44
+
45
+ async def logout(request: Request):
46
+ request.session.clear()
47
+ return RedirectResponse(url="/login", status_code=302)
48
+
49
+ async def set_theme(request: Request, theme: str = Form(...)):
50
+ if theme in get_all_themes():
51
+ request.session["theme"] = theme
52
+ return RedirectResponse(url=request.headers.get("referer", "/"), status_code=302)
53
+
54
+ async def dashboard_page(request: Request, _: bool = Depends(require_auth)):
55
+ theme_name = request.session.get("theme", "purple_gradient")
56
+ theme = get_theme(theme_name)
57
+ current_user = get_current_user(request)
58
+
59
+ try:
60
+ db_stats = await db.get_database_stats()
61
+ total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
62
+ total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
63
+
64
+ system_stats = {
65
+ "server_status": "running",
66
+ "uptime": get_readable_time(time() - StartTime),
67
+ "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
68
+ "connected_bots": len(multi_clients),
69
+ "loads": {
70
+ f"bot{c + 1}": l
71
+ for c, (_, l) in enumerate(
72
+ sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
73
+ )
74
+ } if work_loads else {},
75
+ "version": __version__,
76
+ "movies": total_movies,
77
+ "tv_shows": total_tv_shows,
78
+ "databases": db_stats,
79
+ "total_databases": len(db_stats),
80
+ "current_db_index": db.current_db_index
81
+ }
82
+ except Exception as e:
83
+ print(f"Dashboard error: {e}")
84
+ system_stats = {
85
+ "server_status": "error",
86
+ "error": str(e),
87
+ "uptime": "N/A",
88
+ "telegram_bot": "@StreamBot",
89
+ "connected_bots": 0,
90
+ "loads": {},
91
+ "version": "1.0.0",
92
+ "movies": 0,
93
+ "tv_shows": 0,
94
+ "databases": [],
95
+ "total_databases": 0,
96
+ "current_db_index": 1
97
+ }
98
+
99
+ return templates.TemplateResponse("dashboard.html", {
100
+ "request": request,
101
+ "theme": theme,
102
+ "themes": get_all_themes(),
103
+ "current_theme": theme_name,
104
+ "current_user": current_user,
105
+ "system_stats": system_stats
106
+ })
107
+
108
+
109
+ async def media_management_page(request: Request, media_type: str = "movie", _: bool = Depends(require_auth)):
110
+ theme_name = request.session.get("theme", "purple_gradient")
111
+ theme = get_theme(theme_name)
112
+ current_user = get_current_user(request)
113
+
114
+ return templates.TemplateResponse("media_management.html", {
115
+ "request": request,
116
+ "theme": theme,
117
+ "themes": get_all_themes(),
118
+ "current_theme": theme_name,
119
+ "current_user": current_user,
120
+ "media_type": media_type
121
+ })
122
+
123
+ async def edit_media_page(request: Request, tmdb_id: int, db_index: int, media_type: str, _: bool = Depends(require_auth)):
124
+ theme_name = request.session.get("theme", "purple_gradient")
125
+ theme = get_theme(theme_name)
126
+ current_user = get_current_user(request)
127
+
128
+ try:
129
+ media_details = await db.get_document(media_type, tmdb_id, db_index)
130
+ if not media_details:
131
+ raise HTTPException(status_code=404, detail="Media not found")
132
+ except Exception as e:
133
+ raise HTTPException(status_code=500, detail=str(e))
134
+
135
+ return templates.TemplateResponse("media_edit.html", {
136
+ "request": request,
137
+ "theme": theme,
138
+ "themes": get_all_themes(),
139
+ "current_theme": theme_name,
140
+ "current_user": current_user,
141
+ "tmdb_id": tmdb_id,
142
+ "db_index": db_index,
143
+ "media_type": media_type,
144
+ "media_details": media_details
145
+ })
146
+
147
+ async def public_status_page(request: Request):
148
+ theme_name = request.session.get("theme", "purple_gradient")
149
+ theme = get_theme(theme_name)
150
+
151
+ try:
152
+ db_stats = await db.get_database_stats()
153
+ total_movies = sum(stat.get("movie_count", 0) for stat in db_stats)
154
+ total_tv_shows = sum(stat.get("tv_count", 0) for stat in db_stats)
155
+
156
+ public_stats = {
157
+ "status": "operational",
158
+ "uptime": "99.9%",
159
+ "total_content": total_movies + total_tv_shows,
160
+ "databases_online": len(db_stats)
161
+ }
162
+ except Exception:
163
+ public_stats = {
164
+ "status": "maintenance",
165
+ "uptime": "N/A",
166
+ "total_content": 0,
167
+ "databases_online": 0
168
+ }
169
+
170
+ return templates.TemplateResponse("public_status.html", {
171
+ "request": request,
172
+ "theme": theme,
173
+ "themes": get_all_themes(),
174
+ "current_theme": theme_name,
175
+ "stats": public_stats,
176
+ "is_authenticated": is_authenticated(request)
177
+ })
178
+
179
+ async def stremio_guide_page(request: Request):
180
+ theme_name = request.session.get("theme", "purple_gradient")
181
+ theme = get_theme(theme_name)
182
+
183
+ return templates.TemplateResponse("stremio_guide.html", {
184
+ "request": request,
185
+ "theme": theme,
186
+ "themes": get_all_themes(),
187
+ "current_theme": theme_name,
188
+ "is_authenticated": is_authenticated(request)
189
+ })
Backend/fastapi/security/credentials.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
Backend/fastapi/templates/base.html ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{% block title %}Telegram Stremio{% endblock %}</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
9
+
10
+ <script>
11
+ tailwind.config = {
12
+ theme: {
13
+ extend: {
14
+ colors: {
15
+ primary: '{{ theme.colors.primary }}',
16
+ secondary: '{{ theme.colors.secondary }}',
17
+ accent: '{{ theme.colors.accent }}',
18
+ background: '{{ theme.colors.background }}',
19
+ card: '{{ theme.colors.card }}',
20
+ text: '{{ theme.colors.text }}',
21
+ 'text-secondary': '{{ theme.colors.text_secondary }}'
22
+ }
23
+ }
24
+ }
25
+ }
26
+ </script>
27
+ <style>
28
+ body { background-color: {{ theme.colors.background }}; color: {{ theme.colors.text }}; }
29
+ .theme-card { background-color: {{ theme.colors.card }}; }
30
+ .theme-primary { background-color: {{ theme.colors.primary }}; }
31
+ .theme-secondary { background-color: {{ theme.colors.secondary }}; }
32
+ .theme-accent { background-color: {{ theme.colors.accent }}; }
33
+ .theme-text-secondary { color: {{ theme.colors.text_secondary }}; }
34
+ </style>
35
+ </head>
36
+ <body class="min-h-screen">
37
+ <!-- Navigation -->
38
+ <nav class="theme-card shadow-lg border-b">
39
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
40
+ <div class="flex justify-between items-center h-16">
41
+ <div class="flex items-center space-x-4">
42
+ <h1 class="text-2xl font-bold text-primary">Telegram Stremio</h1>
43
+ {% if current_user %}
44
+ <div class="hidden md:flex space-x-4">
45
+ <a href="/" class="text-text hover:text-primary px-3 py-2 rounded-md transition-colors">Dashboard</a>
46
+ <a href="/media/manage" class="text-text hover:text-primary px-3 py-2 rounded-md transition-colors">Media</a>
47
+ </div>
48
+ {% endif %}
49
+ </div>
50
+
51
+ <div class="flex items-center space-x-4">
52
+ <!-- Theme Selector -->
53
+ <div class="relative">
54
+ <form method="post" action="/set-theme" id="theme-form">
55
+ <select name="theme" onchange="document.getElementById('theme-form').submit()" class="theme-card border border-gray-300 rounded-md px-3 py-2 text-sm">
56
+ {% for theme_key, theme_data in themes.items() %}
57
+ <option value="{{ theme_key }}" {% if current_theme == theme_key %}selected{% endif %}>
58
+ {{ theme_data.name }}
59
+ </option>
60
+ {% endfor %}
61
+ </select>
62
+ </form>
63
+ </div>
64
+
65
+ {% if current_user %}
66
+ <div class="flex items-center space-x-4">
67
+ <span class="text-sm theme-text-secondary">{{ current_user }}</span>
68
+ <a href="/logout" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 transition-colors">Logout</a>
69
+ </div>
70
+ {% else %}
71
+ <a href="/login" class="theme-primary text-white px-4 py-2 rounded-md hover:opacity-90 transition-opacity">Login</a>
72
+ {% endif %}
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </nav>
77
+
78
+ <!-- Main Content -->
79
+ <main class="flex-1">
80
+ {% block content %}{% endblock %}
81
+ </main>
82
+
83
+ <!-- Footer -->
84
+ <footer class="theme-card border-t mt-auto">
85
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
86
+ <div class="flex justify-between items-center">
87
+ <p class="theme-text-secondary text-sm">© 2025 Telegram Stremio. All rights reserved.</p>
88
+ <div class="flex space-x-4">
89
+ <a href="/status" class="theme-text-secondary hover:text-primary text-sm transition-colors">Status</a>
90
+ <a href="/stremio" class="theme-text-secondary hover:text-primary text-sm transition-colors">Stremio Guide</a>
91
+ </div>
92
+ </div>
93
+ </div>
94
+ </footer>
95
+ </body>
96
+ </html>
Backend/fastapi/templates/dashboard.html ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Dashboard - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="min-h-screen">
7
+ <!-- Header with just status pill -->
8
+ <header class="theme-card shadow-lg mb-8">
9
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
10
+ <div class="flex items-center justify-between">
11
+ <div class="flex items-center space-x-4">
12
+ <h1 class="text-3xl font-bold text-primary">System Overview</h1>
13
+ </div>
14
+ </div>
15
+ </div>
16
+ </header>
17
+
18
+ <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
19
+ <!-- System Status Section -->
20
+ <div class="mb-12">
21
+ <div class="grid lg:grid-cols-2 gap-8">
22
+ <!-- System Status Card -->
23
+ <div class="theme-card rounded-xl p-8 shadow-xl">
24
+ <div class="flex items-center mb-6">
25
+ <div class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
26
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="white">
27
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
28
+ </svg>
29
+ </div>
30
+ <h3 class="text-2xl font-semibold">System Status</h3>
31
+ </div>
32
+
33
+ <div class="space-y-4">
34
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
35
+ <span class="font-medium theme-text-secondary">Uptime</span>
36
+ <span class="text-primary font-semibold">{{ system_stats.uptime or 'N/A' }}</span>
37
+ </div>
38
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
39
+ <span class="font-medium theme-text-secondary">Telegram Bot</span>
40
+ <span class="text-primary font-semibold">{{ system_stats.telegram_bot or '@StreamBot' }}</span>
41
+ </div>
42
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
43
+ <span class="font-medium theme-text-secondary">Connected Bots</span>
44
+ <span class="text-primary font-semibold">{{ system_stats.connected_bots|default(0) }}</span>
45
+ </div>
46
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
47
+ <span class="font-medium theme-text-secondary">Backend Version</span>
48
+ <span class="text-primary font-semibold">v{{ system_stats.version or '1.0.0' }}</span>
49
+ </div>
50
+ </div>
51
+ </div>
52
+
53
+ <!-- Bot Workload Accordion (Collapsed by default) -->
54
+ <div class="theme-card rounded-xl p-8 shadow-xl">
55
+ <div class="flex items-center justify-between cursor-pointer" onclick="toggleAccordion('workload-content')">
56
+ <div class="flex items-center">
57
+ <div class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
58
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="white">
59
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
60
+ </svg>
61
+ </div>
62
+ <h3 class="text-2xl font-semibold">Bot Workloads</h3>
63
+ </div>
64
+ <svg id="workload-content-icon" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-primary transition-transform duration-200 transform rotate-0" fill="none" viewBox="0 0 24 24" stroke="white">
65
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
66
+ </svg>
67
+ </div>
68
+
69
+ <div id="workload-content" class="hidden mt-6 space-y-3">
70
+ {% if system_stats.loads and system_stats.loads|length > 0 %}
71
+ {% for bot_name, load in system_stats.loads.items() %}
72
+ <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
73
+ <span class="font-medium theme-text-secondary">{{ bot_name }}</span>
74
+ <div class="flex items-center space-x-2">
75
+ <div class="w-16 bg-gray-200 rounded-full h-2">
76
+ {% set max_load = system_stats.loads.values() | max if system_stats.loads.values() | max > 0 else 1 %}
77
+ <div class="theme-primary h-2 rounded-full" style="width: {{ (load / max_load * 100) | round }}%"></div>
78
+ </div>
79
+ <span class="text-primary font-semibold text-sm w-8" id="load-{{ loop.index0 }}">{{ load }}</span>
80
+ </div>
81
+ </div>
82
+ {% endfor %}
83
+ {% else %}
84
+ <div class="text-center theme-text-secondary py-4">No workload data available</div>
85
+ {% endif %}
86
+ </div>
87
+ </div>
88
+ </div>
89
+ </div>
90
+
91
+ <!-- Database Statistics Section -->
92
+ <div class="mb-12">
93
+ <h2 class="text-2xl font-bold mb-6">Database Overview</h2>
94
+ <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
95
+ {% if system_stats.databases %}
96
+ {% for db_stat in system_stats.databases %}
97
+ <div class="theme-card rounded-xl p-6 shadow-xl">
98
+ <div class="flex items-center justify-between mb-4">
99
+ <h3 class="text-lg font-semibold">{{ db_stat.db_name.replace("storage_", "Database ") }}</h3>
100
+ <div class="w-8 h-8 theme-primary rounded-lg flex items-center justify-center bg-opacity-20 text-primary">
101
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="white">
102
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"></path>
103
+ </svg>
104
+ </div>
105
+ </div>
106
+
107
+ <div class="space-y-3">
108
+ <div class="flex justify-between text-sm">
109
+ <span class="theme-text-secondary">Movies</span>
110
+ <span class="text-primary font-semibold">{{ "{:,}".format(db_stat.movie_count) }}</span>
111
+ </div>
112
+ <div class="flex justify-between text-sm">
113
+ <span class="theme-text-secondary">TV Shows</span>
114
+ <span class="text-primary font-semibold">{{ "{:,}".format(db_stat.tv_count) }}</span>
115
+ </div>
116
+ <div class="mt-4">
117
+ <div class="flex justify-between text-sm mb-1">
118
+ <span class="theme-text-secondary">Storage Used</span>
119
+ <span class="text-xs">{{ "%.1f"|format(db_stat.storageSize / 1024 / 1024) }} MB</span>
120
+ </div>
121
+ {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %}
122
+ <div class="w-full bg-gray-200 rounded-full h-2">
123
+ <div class="theme-primary h-2 rounded-full" style="width: {{ storage_percent }}%"></div>
124
+ </div>
125
+ </div>
126
+ </div>
127
+ </div>
128
+ {% endfor %}
129
+ {% else %}
130
+ <div class="col-span-full text-center theme-text-secondary py-8">No database statistics available</div>
131
+ {% endif %}
132
+ </div>
133
+ </div>
134
+
135
+ <!-- Media Management Section -->
136
+ <div class="mb-12">
137
+ <h2 class="text-2xl font-bold mb-6">Media Management</h2>
138
+ <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
139
+ <a href="/media/manage?media_type=movie" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
140
+ <div class="flex items-center">
141
+ <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
142
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
143
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z"></path>
144
+ </svg>
145
+ </div>
146
+ <div>
147
+ <h3 class="text-xl font-semibold mb-2">Manage Movies</h3>
148
+ <p class="theme-text-secondary">Edit and organize movie collections</p>
149
+ <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.movies|default(0) }} movies</div>
150
+ </div>
151
+ </div>
152
+ </a>
153
+
154
+ <a href="/media/manage?media_type=tv" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
155
+ <div class="flex items-center">
156
+ <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
157
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
158
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
159
+ </svg>
160
+ </div>
161
+ <div>
162
+ <h3 class="text-xl font-semibold mb-2">Manage TV Shows</h3>
163
+ <p class="theme-text-secondary">Edit and organize TV series</p>
164
+ <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.tv_shows|default(0) }} shows</div>
165
+ </div>
166
+ </div>
167
+ </a>
168
+
169
+ <a href="/stremio" class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group">
170
+ <div class="flex items-center">
171
+ <div class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
172
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
173
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
174
+ </svg>
175
+ </div>
176
+ <div>
177
+ <h3 class="text-xl font-semibold mb-2">Stremio Setup</h3>
178
+ <p class="theme-text-secondary">Configure addon installation</p>
179
+ </div>
180
+ </div>
181
+ </a>
182
+ </div>
183
+ </div>
184
+
185
+ <!-- Stremio Addon Section -->
186
+ <div class="theme-card rounded-xl p-8 shadow-xl">
187
+ <div class="text-center mb-8">
188
+ <div class="w-16 h-16 theme-primary rounded-full flex items-center justify-center mx-auto mb-4 bg-opacity-20 text-primary">
189
+ <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="white">
190
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
191
+ </svg>
192
+ </div>
193
+ <h3 class="text-2xl font-bold mb-2">Stremio Addon</h3>
194
+ <p class="theme-text-secondary">Install the addon to access media content through Stremio</p>
195
+ </div>
196
+
197
+ <!-- Installation Section -->
198
+ <div class="bg-gray-50 rounded-lg p-6 mb-6">
199
+ <h4 class="text-lg font-semibold mb-4">Installation Instructions</h4>
200
+ <div class="space-y-3 theme-text-secondary">
201
+ <div class="flex items-start space-x-3">
202
+ <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">1</div>
203
+ <p>Copy the manifest URL below</p>
204
+ </div>
205
+ <div class="flex items-start space-x-3">
206
+ <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">2</div>
207
+ <p>Open Stremio and go to Addons section</p>
208
+ </div>
209
+ <div class="flex items-start space-x-3">
210
+ <div class="w-6 h-6 theme-primary rounded-full flex items-center justify-center text-white text-sm font-semibold mt-0.5">3</div>
211
+ <p>Paste the URL in "Add Addon" field and install</p>
212
+ </div>
213
+ </div>
214
+ </div>
215
+
216
+ <!-- Manifest URL -->
217
+ <div class="bg-gray-50 rounded-lg p-4">
218
+ <label class="block text-sm font-medium theme-text-secondary mb-2">Manifest URL</label>
219
+ <div class="flex">
220
+ <input
221
+ type="text"
222
+ value="{{ (request.base_url|string).replace('http:', 'https:') }}stremio/manifest.json"
223
+ readonly
224
+ id="manifest-url"
225
+ class="flex-1 theme-card border border-gray-300 rounded-l-lg px-4 py-3 font-mono text-sm focus:outline-none focus:border-primary"
226
+ />
227
+ <button
228
+ onclick="copyToClipboard()"
229
+ class="theme-primary text-white px-6 py-3 rounded-r-lg font-semibold hover:opacity-90 transition-colors duration-200"
230
+ >
231
+ Copy
232
+ </button>
233
+ </div>
234
+ </div>
235
+ </div>
236
+ </main>
237
+ </div>
238
+
239
+ <script>
240
+ function copyToClipboard() {
241
+ const manifestUrl = document.getElementById('manifest-url').value;
242
+ navigator.clipboard.writeText(manifestUrl).then(function() {
243
+ showToast('Manifest URL copied to clipboard!');
244
+ });
245
+ }
246
+
247
+ function showToast(message) {
248
+ const toast = document.createElement('div');
249
+ toast.className = 'fixed top-4 right-4 theme-primary text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
250
+ toast.textContent = message;
251
+ document.body.appendChild(toast);
252
+
253
+ setTimeout(() => toast.classList.remove('translate-x-full'), 100);
254
+ setTimeout(() => {
255
+ toast.classList.add('translate-x-full');
256
+ setTimeout(() => document.body.removeChild(toast), 300);
257
+ }, 3000);
258
+ }
259
+
260
+ function toggleAccordion(id) {
261
+ const content = document.getElementById(id);
262
+ const icon = document.getElementById(id + '-icon');
263
+
264
+ if (content.classList.contains('hidden')) {
265
+ content.classList.remove('hidden');
266
+ icon.classList.add('rotate-180');
267
+ } else {
268
+ content.classList.add('hidden');
269
+ icon.classList.remove('rotate-180');
270
+ }
271
+ }
272
+ </script>
273
+ {% endblock %}
Backend/fastapi/templates/login.html ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Login - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
7
+ <div class="max-w-md w-full space-y-8">
8
+ <div class="text-center">
9
+ <h2 class="text-3xl font-bold">Admin Login</h2>
10
+ <p class="mt-2 theme-text-secondary">Sign in to access the admin panel</p>
11
+ </div>
12
+
13
+ {% if error %}
14
+ <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
15
+ {{ error }}
16
+ </div>
17
+ {% endif %}
18
+
19
+ <form method="post" class="theme-card p-8 rounded-lg shadow-lg space-y-6">
20
+ <div>
21
+ <label for="username" class="block text-sm font-medium mb-2">Username</label>
22
+ <input type="text" id="username" name="username" required
23
+ class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
24
+ </div>
25
+
26
+ <div>
27
+ <label for="password" class="block text-sm font-medium mb-2">Password</label>
28
+ <input type="password" id="password" name="password" required
29
+ class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
30
+ </div>
31
+
32
+ <button type="submit"
33
+ class="w-full theme-primary text-white py-2 px-4 rounded-md hover:opacity-90 transition-opacity font-medium">
34
+ Sign In
35
+ </button>
36
+ </form>
37
+
38
+ <div class="text-center">
39
+ <p class="theme-text-secondary text-sm">
40
+ Public pages:
41
+ <a href="/status" class="text-primary hover:underline">System Status</a> |
42
+ <a href="/stremio" class="text-primary hover:underline">Stremio Guide</a>
43
+ </p>
44
+ </div>
45
+ </div>
46
+ </div>
47
+ {% endblock %}
Backend/fastapi/templates/media_edit.html ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Edit {{ media_type|title }} - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
7
+ <!-- Header -->
8
+ <div class="mb-6 sm:mb-8">
9
+ <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
10
+ <a href="/media/manage?media_type={{ media_type }}" class="text-primary hover:underline flex items-center text-sm sm:text-base">
11
+ <svg class="w-4 h-4 sm:w-5 sm:h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
12
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
13
+ </svg>
14
+ Back to {{ media_type|title }}s
15
+ </a>
16
+ </div>
17
+ <h1 class="text-2xl sm:text-3xl font-bold mt-2">Edit {{ media_type|title }}</h1>
18
+ <p class="theme-text-secondary text-sm sm:text-base mt-1 sm:mt-2">TMDB ID: {{ tmdb_id }} | DB Index: {{ db_index }}</p>
19
+ </div>
20
+
21
+ <!-- Media Preview -->
22
+ {% if media_details %}
23
+ <div class="theme-card rounded-lg shadow mb-6 sm:mb-8 overflow-hidden">
24
+
25
+ <!-- Mobile Layout (Stack vertically) -->
26
+ <div class="block sm:hidden">
27
+ <!-- Poster Section -->
28
+ <div class="bg-gradient-to-br from-gray-800 to-gray-900 p-6">
29
+ <div class="flex flex-col items-center text-center">
30
+ <img src="{{ media_details.poster or '/static/placeholder.jpg' }}"
31
+ alt="{{ media_details.title }}"
32
+ class="w-32 h-48 object-cover rounded-lg shadow-xl border-4 border-white mb-4"
33
+ onerror="this.src='https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image'">
34
+ <h2 class="text-xl font-bold text-white mb-2">{{ media_details.title }}</h2>
35
+ <div class="flex flex-wrap justify-center items-center gap-2 mb-3">
36
+ {% if media_details.rating %}
37
+ <span class="bg-yellow-500 text-black px-2 py-1 rounded text-sm font-bold">
38
+ ⭐ {{ media_details.rating }}
39
+ </span>
40
+ {% endif %}
41
+ <span class="text-white text-sm bg-white/20 px-2 py-1 rounded">{{ media_details.release_year }}</span>
42
+ </div>
43
+ <div class="flex flex-wrap justify-center gap-1">
44
+ {% for genre in media_details.genres[:4] %}
45
+ <span class="bg-white/20 text-white px-2 py-1 rounded-full text-xs">{{ genre }}</span>
46
+ {% endfor %}
47
+ </div>
48
+ </div>
49
+ </div>
50
+
51
+ <!-- Backdrop Section -->
52
+ {% if media_details.backdrop %}
53
+ <div class="relative h-48 overflow-hidden">
54
+ <img src="{{ media_details.backdrop }}"
55
+ alt="{{ media_details.title }} backdrop"
56
+ class="w-full h-full object-cover"
57
+ onerror="this.style.display='none'">
58
+ <div class="absolute inset-0 bg-black/30"></div>
59
+ </div>
60
+ {% endif %}
61
+ </div>
62
+
63
+ <!-- Desktop Layout (Original backdrop style) -->
64
+ <div class="hidden sm:block">
65
+ {% if media_details.backdrop %}
66
+ <div class="relative h-64 md:h-80 bg-gradient-to-r from-gray-900 to-gray-700">
67
+ <img src="{{ media_details.backdrop }}"
68
+ alt="{{ media_details.title }} backdrop"
69
+ class="w-full h-full object-cover opacity-60"
70
+ onerror="this.style.display='none'">
71
+ <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
72
+ <div class="absolute bottom-0 left-0 right-0 p-6">
73
+ <div class="flex items-end gap-6">
74
+ <img src="{{ media_details.poster or '/static/placeholder.jpg' }}"
75
+ alt="{{ media_details.title }}"
76
+ class="w-32 md:w-48 h-48 md:h-72 object-cover rounded-lg shadow-2xl border-4 border-white"
77
+ onerror="this.src='https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image'">
78
+ <div class="text-white flex-1">
79
+ <h2 class="text-2xl md:text-4xl font-bold mb-2">{{ media_details.title }}</h2>
80
+ <div class="flex flex-wrap items-center gap-4 mb-4">
81
+ {% if media_details.rating %}
82
+ <span class="bg-yellow-500 text-black px-2 py-1 rounded text-sm font-bold">
83
+ ⭐ {{ media_details.rating }}
84
+ </span>
85
+ {% endif %}
86
+ <span class="text-lg">{{ media_details.release_year }}</span>
87
+
88
+ </div>
89
+ <div class="flex flex-wrap gap-2">
90
+ {% for genre in media_details.genres[:6] %}
91
+ <span class="bg-white/20 backdrop-blur-sm text-white px-3 py-1 rounded-full text-sm">{{ genre }}</span>
92
+ {% endfor %}
93
+ </div>
94
+ </div>
95
+ </div>
96
+ </div>
97
+ </div>
98
+ {% else %}
99
+ <!-- Fallback without backdrop for desktop -->
100
+ <div class="p-6">
101
+ <div class="flex items-start gap-6">
102
+ <div class="flex-shrink-0">
103
+ <img src="{{ media_details.poster or '/static/placeholder.jpg' }}"
104
+ alt="{{ media_details.title }}"
105
+ class="w-48 h-72 object-cover rounded-lg shadow-lg"
106
+ onerror="this.src='https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image'">
107
+ </div>
108
+ <div class="flex-1">
109
+ <h2 class="text-2xl font-bold mb-2">{{ media_details.title }}</h2>
110
+ <p class="theme-text-secondary mb-4">{{ media_details.release_year }} • Rating: {{ media_details.rating or 'N/A' }}</p>
111
+ <div class="flex flex-wrap gap-2 mb-4">
112
+ {% for genre in media_details.genres[:6] %}
113
+ <span class="bg-gray-200 text-gray-700 px-2 py-1 rounded-full text-sm">{{ genre }}</span>
114
+ {% endfor %}
115
+ </div>
116
+ </div>
117
+ </div>
118
+ </div>
119
+ {% endif %}
120
+ </div>
121
+
122
+ <!-- Description (common for both layouts) -->
123
+ {% if media_details.description %}
124
+ <div class="px-4 sm:px-6 pb-4 sm:pb-6">
125
+ <h3 class="text-base sm:text-lg font-semibold mb-2">Overview</h3>
126
+ <p class="theme-text-secondary leading-relaxed text-sm sm:text-base">{{ media_details.description }}</p>
127
+ </div>
128
+ {% endif %}
129
+ </div>
130
+ {% endif %}
131
+
132
+ <!-- Edit Form -->
133
+ <div class="theme-card p-4 sm:p-6 rounded-lg shadow mb-6 sm:mb-8">
134
+ <h3 class="text-lg sm:text-xl font-semibold mb-4 sm:mb-6">Edit Details</h3>
135
+ <form onsubmit="updateMedia(event)" id="edit-form">
136
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6 mb-6">
137
+ <div class="sm:col-span-2">
138
+ <label class="block text-sm font-medium mb-2">Title *</label>
139
+ <input type="text" id="title" name="title"
140
+ value="{{ media_details.title if media_details else '' }}"
141
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary" required>
142
+ </div>
143
+ <div>
144
+ <label class="block text-sm font-medium mb-2">Release Year *</label>
145
+ <input type="number" id="release_year" name="release_year"
146
+ value="{{ media_details.release_year if media_details else '' }}"
147
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary" required>
148
+ </div>
149
+ <div>
150
+ <label class="block text-sm font-medium mb-2">Rating (0-10)</label>
151
+ <input type="number" step="0.1" min="0" max="10" id="rating" name="rating"
152
+ value="{{ media_details.rating if media_details else '' }}"
153
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary">
154
+ </div>
155
+ <div class="sm:col-span-2">
156
+ <label class="block text-sm font-medium mb-2">Logo URL</label>
157
+ <input type="url" id="logo" name="logo"
158
+ value="{{ media_details.logo if media_details else '' }}"
159
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary">
160
+ </div>
161
+
162
+ <div class="sm:col-span-2">
163
+ <label class="block text-sm font-medium mb-2">Poster URL</label>
164
+ <input type="url" id="poster" name="poster"
165
+ value="{{ media_details.poster if media_details else '' }}"
166
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary">
167
+ </div>
168
+ <div class="sm:col-span-2">
169
+ <label class="block text-sm font-medium mb-2">Backdrop URL</label>
170
+ <input type="url" id="backdrop" name="backdrop"
171
+ value="{{ media_details.backdrop if media_details else '' }}"
172
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary">
173
+ </div>
174
+ </div>
175
+
176
+ <div class="mb-6">
177
+ <label class="block text-sm font-medium mb-2">Description</label>
178
+ <textarea id="description" name="description" rows="3"
179
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary">{{ media_details.description if media_details else '' }}</textarea>
180
+ </div>
181
+
182
+ <div class="mb-6">
183
+ <label class="block text-sm font-medium mb-2">Genres (comma-separated)</label>
184
+ <input type="text" id="genres" name="genres"
185
+ value="{% if media_details and media_details.genres %}{{ media_details.genres|join(', ') }}{% endif %}"
186
+ class="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
187
+ placeholder="Action, Comedy, Drama">
188
+ </div>
189
+
190
+ <div class="flex flex-col sm:flex-row justify-end gap-2 sm:gap-4">
191
+ <button type="button" onclick="window.history.back()"
192
+ class="w-full sm:w-auto px-6 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors text-sm">
193
+ Cancel
194
+ </button>
195
+ <button type="submit"
196
+ class="w-full sm:w-auto theme-primary text-white px-6 py-2 rounded-md hover:opacity-90 transition-opacity text-sm">
197
+ Save Changes
198
+ </button>
199
+ </div>
200
+ </form>
201
+ </div>
202
+
203
+ <!-- Quality Management -->
204
+ {% if media_details %}
205
+ <div class="theme-card p-4 sm:p-6 rounded-lg shadow">
206
+ <h3 class="text-lg sm:text-xl font-semibold mb-4 sm:mb-6">Available Content</h3>
207
+
208
+ {% if media_type == 'movie' and media_details.telegram %}
209
+ <!-- Movie Qualities (sorted by quality) -->
210
+ <div class="space-y-3">
211
+ {% set sorted_qualities = media_details.telegram|sort(attribute='quality') %}
212
+ {% for quality in sorted_qualities %}
213
+ <div class="flex flex-col sm:flex-row sm:items-center justify-between p-3 sm:p-4 bg-gray-50 rounded-lg border gap-3 sm:gap-0">
214
+ <div class="flex-1">
215
+ <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
216
+ <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800 w-fit">
217
+ {{ quality.quality }}
218
+ </span>
219
+ <span class="text-sm text-gray-600">{{ quality.size }}</span>
220
+ </div>
221
+ <p class="text-sm text-gray-500 mt-2 sm:mt-1 break-all">{{ quality.name }}</p>
222
+ </div>
223
+ <button onclick="deleteQuality('{{ quality.quality }}')"
224
+ class="self-start sm:self-center text-red-600 hover:text-red-800 hover:bg-red-50 px-3 py-1 rounded transition-colors text-sm">
225
+ Delete
226
+ </button>
227
+ </div>
228
+ {% endfor %}
229
+ </div>
230
+
231
+ {% elif media_type == 'tv' and media_details.seasons %}
232
+ <!-- TV Show Seasons and Episodes (sorted) -->
233
+ <div class="space-y-4 sm:space-y-6">
234
+ {% for season in media_details.seasons|sort(attribute='season_number') %}
235
+ <div class="border border-gray-200 rounded-lg overflow-hidden">
236
+ <!-- Season Header -->
237
+ <div class="bg-gradient-to-r from-blue-50 to-indigo-50 px-4 sm:px-6 py-3 sm:py-4 border-b border-gray-200">
238
+ <div class="flex items-center justify-between">
239
+ <h4 class="text-base sm:text-lg font-semibold text-gray-900">Season {{ season.season_number }}</h4>
240
+ <div class="flex items-center gap-2 sm:gap-4">
241
+ <span class="text-xs sm:text-sm text-gray-600">{{ season.episodes|length }} episode{{ 's' if season.episodes|length != 1 else '' }}</span>
242
+ <button onclick="toggleSeason({{ loop.index0 }})"
243
+ class="text-blue-600 hover:text-blue-800 transition-colors p-1">
244
+ <svg id="season-arrow-{{ loop.index0 }}" class="w-4 h-4 sm:w-5 sm:h-5 transform transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
245
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
246
+ </svg>
247
+ </button>
248
+ </div>
249
+ </div>
250
+ </div>
251
+
252
+ <!-- Episodes List (sorted by episode number) -->
253
+ <div id="season-content-{{ loop.index0 }}" class="season-content">
254
+ <div class="divide-y divide-gray-100">
255
+ {% for episode in season.episodes|sort(attribute='episode_number') %}
256
+ <div class="p-3 sm:p-4 hover:bg-gray-50 transition-colors">
257
+ <div class="flex flex-col sm:flex-row sm:items-start gap-3 sm:gap-4">
258
+ <!-- Episode Number -->
259
+ <div class="flex-shrink-0 w-10 h-10 sm:w-12 sm:h-12 bg-blue-100 rounded-lg flex items-center justify-center mx-auto sm:mx-0">
260
+ <span class="text-sm font-bold text-blue-800">{{ episode.episode_number }}</span>
261
+ </div>
262
+
263
+ <!-- Episode Info -->
264
+ <div class="flex-1 min-w-0">
265
+ <h5 class="text-sm font-medium text-gray-900 mb-2 text-center sm:text-left">{{ episode.title }}</h5>
266
+
267
+ <!-- Episode Qualities (sorted by quality) -->
268
+ {% if episode.telegram %}
269
+ <div class="space-y-2">
270
+ {% set sorted_episode_qualities = episode.telegram|sort(attribute='quality') %}
271
+ {% for quality in sorted_episode_qualities %}
272
+ <div class="flex flex-col sm:flex-row sm:items-center justify-between bg-white border border-gray-200 rounded-md p-3 gap-2 sm:gap-0">
273
+ <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3">
274
+ <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800 w-fit">
275
+ {{ quality.quality }}
276
+ </span>
277
+ <span class="text-xs text-gray-500">{{ quality.size }}</span>
278
+ <span class="text-xs text-gray-400 break-all">{{ quality.name }}</span>
279
+ </div>
280
+ <button onclick="deleteTVQuality({{ season.season_number }}, {{ episode.episode_number }}, '{{ quality.quality }}')"
281
+ class="self-start sm:self-center text-red-600 hover:text-red-800 hover:bg-red-50 px-2 py-1 rounded transition-colors text-xs">
282
+ Delete
283
+ </button>
284
+ </div>
285
+ {% endfor %}
286
+ </div>
287
+ {% else %}
288
+ <p class="text-xs text-gray-400 text-center sm:text-left">No qualities available</p>
289
+ {% endif %}
290
+ </div>
291
+
292
+ <!-- Episode Actions -->
293
+ <div class="flex-shrink-0 flex justify-center sm:justify-start">
294
+ <button onclick="deleteTVEpisode({{ season.season_number }}, {{ episode.episode_number }})"
295
+ class="text-red-600 hover:text-red-800 hover:bg-red-50 px-2 py-1 rounded text-xs transition-colors">
296
+ Delete Episode
297
+ </button>
298
+ </div>
299
+ </div>
300
+ </div>
301
+ {% endfor %}
302
+ </div>
303
+
304
+ <!-- Season Actions -->
305
+ <div class="px-3 sm:px-4 py-3 bg-gray-50 border-t border-gray-200 text-center sm:text-left">
306
+ <button onclick="deleteTVSeason({{ season.season_number }})"
307
+ class="text-red-600 hover:text-red-800 hover:bg-red-100 px-3 py-1 rounded text-sm transition-colors">
308
+ Delete Entire Season
309
+ </button>
310
+ </div>
311
+ </div>
312
+ </div>
313
+ {% endfor %}
314
+ </div>
315
+ {% else %}
316
+ <div class="text-center py-8">
317
+ <svg class="mx-auto h-12 w-12 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
318
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z"/>
319
+ </svg>
320
+ <p class="theme-text-secondary text-sm sm:text-base">No content available</p>
321
+ </div>
322
+ {% endif %}
323
+ </div>
324
+ {% endif %}
325
+ </div>
326
+
327
+ <script>
328
+ const tmdbId = {{ tmdb_id }};
329
+ const dbIndex = {{ db_index }};
330
+ const mediaType = '{{ media_type }}';
331
+
332
+ // Toggle season visibility
333
+ function toggleSeason(seasonIndex) {
334
+ const content = document.getElementById(`season-content-${seasonIndex}`);
335
+ const arrow = document.getElementById(`season-arrow-${seasonIndex}`);
336
+
337
+ if (content.style.display === 'none') {
338
+ content.style.display = 'block';
339
+ arrow.style.transform = 'rotate(0deg)';
340
+ } else {
341
+ content.style.display = 'none';
342
+ arrow.style.transform = 'rotate(-90deg)';
343
+ }
344
+ }
345
+
346
+ // Update media
347
+ async function updateMedia(event) {
348
+ event.preventDefault();
349
+
350
+ const formData = new FormData(event.target);
351
+ const updateData = {};
352
+
353
+ // Convert form data to object
354
+ for (let [key, value] of formData.entries()) {
355
+ if (key === 'genres') {
356
+ updateData[key] = value.split(',').map(g => g.trim()).filter(g => g);
357
+ } else if (key === 'rating' || key === 'release_year' || key === 'runtime') {
358
+ updateData[key] = value ? parseFloat(value) : null;
359
+ } else {
360
+ updateData[key] = value || null;
361
+ }
362
+ }
363
+
364
+ try {
365
+ const response = await fetch(`/api/media/update?tmdb_id=${tmdbId}&db_index=${dbIndex}&media_type=${mediaType}`, {
366
+ method: 'PUT',
367
+ headers: {
368
+ 'Content-Type': 'application/json'
369
+ },
370
+ body: JSON.stringify(updateData)
371
+ });
372
+
373
+ if (response.ok) {
374
+ showSuccessMessage('Media updated successfully');
375
+ setTimeout(() => location.reload(), 1000);
376
+ } else {
377
+ const error = await response.json();
378
+ showErrorMessage(`Error updating media: ${error.detail || 'Unknown error'}`);
379
+ }
380
+ } catch (error) {
381
+ console.error('Error updating media:', error);
382
+ showErrorMessage('Error updating media. Please try again.');
383
+ }
384
+ }
385
+
386
+ // Delete quality from movie
387
+ async function deleteQuality(quality) {
388
+ if (!confirm(`Are you sure you want to delete the ${quality} quality?`)) return;
389
+
390
+ try {
391
+ const response = await fetch(`/api/media/delete-quality?tmdb_id=${tmdbId}&db_index=${dbIndex}&quality=${encodeURIComponent(quality)}`, {
392
+ method: 'DELETE'
393
+ });
394
+
395
+ if (response.ok) {
396
+ showSuccessMessage(`${quality} quality deleted successfully`);
397
+ setTimeout(() => location.reload(), 1000);
398
+ } else {
399
+ const error = await response.json();
400
+ showErrorMessage(`Error deleting quality: ${error.detail || 'Unknown error'}`);
401
+ }
402
+ } catch (error) {
403
+ console.error('Error deleting quality:', error);
404
+ showErrorMessage('Error deleting quality. Please try again.');
405
+ }
406
+ }
407
+
408
+ // Delete TV quality
409
+ async function deleteTVQuality(season, episode, quality) {
410
+ if (!confirm(`Are you sure you want to delete the ${quality} quality from Season ${season} Episode ${episode}?`)) return;
411
+
412
+ try {
413
+ const response = await fetch(`/api/media/delete-tv-quality?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}&episode=${episode}&quality=${encodeURIComponent(quality)}`, {
414
+ method: 'DELETE'
415
+ });
416
+
417
+ if (response.ok) {
418
+ showSuccessMessage(`${quality} quality deleted successfully`);
419
+ setTimeout(() => location.reload(), 1000);
420
+ } else {
421
+ const error = await response.json();
422
+ showErrorMessage(`Error deleting quality: ${error.detail || 'Unknown error'}`);
423
+ }
424
+ } catch (error) {
425
+ console.error('Error deleting quality:', error);
426
+ showErrorMessage('Error deleting quality. Please try again.');
427
+ }
428
+ }
429
+
430
+ // Delete TV episode
431
+ async function deleteTVEpisode(season, episode) {
432
+ if (!confirm(`Are you sure you want to delete Season ${season} Episode ${episode}?\n\nThis will remove the entire episode and all its qualities.`)) return;
433
+
434
+ try {
435
+ const response = await fetch(`/api/media/delete-tv-episode?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}&episode=${episode}`, {
436
+ method: 'DELETE'
437
+ });
438
+
439
+ if (response.ok) {
440
+ showSuccessMessage(`Episode ${episode} deleted successfully`);
441
+ setTimeout(() => location.reload(), 1000);
442
+ } else {
443
+ const error = await response.json();
444
+ showErrorMessage(`Error deleting episode: ${error.detail || 'Unknown error'}`);
445
+ }
446
+ } catch (error) {
447
+ console.error('Error deleting episode:', error);
448
+ showErrorMessage('Error deleting episode. Please try again.');
449
+ }
450
+ }
451
+
452
+ // Delete TV season
453
+ async function deleteTVSeason(season) {
454
+ if (!confirm(`Are you sure you want to delete the entire Season ${season}?\n\nThis will remove all episodes and qualities in this season. This action cannot be undone.`)) return;
455
+
456
+ try {
457
+ const response = await fetch(`/api/media/delete-tv-season?tmdb_id=${tmdbId}&db_index=${dbIndex}&season=${season}`, {
458
+ method: 'DELETE'
459
+ });
460
+
461
+ if (response.ok) {
462
+ showSuccessMessage(`Season ${season} deleted successfully`);
463
+ setTimeout(() => location.reload(), 1000);
464
+ } else {
465
+ const error = await response.json();
466
+ showErrorMessage(`Error deleting season: ${error.detail || 'Unknown error'}`);
467
+ }
468
+ } catch (error) {
469
+ console.error('Error deleting season:', error);
470
+ showErrorMessage('Error deleting season. Please try again.');
471
+ }
472
+ }
473
+
474
+ // Show success message
475
+ function showSuccessMessage(message) {
476
+ const msg = document.createElement('div');
477
+ msg.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 sm:px-6 py-3 rounded-lg shadow-lg z-50 flex items-center max-w-sm';
478
+ msg.innerHTML = `
479
+ <svg class="w-4 h-4 sm:w-5 sm:h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
480
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
481
+ </svg>
482
+ <span class="text-sm">${message}</span>
483
+ `;
484
+ document.body.appendChild(msg);
485
+ setTimeout(() => {
486
+ if (document.body.contains(msg)) {
487
+ document.body.removeChild(msg);
488
+ }
489
+ }, 4000);
490
+ }
491
+
492
+ // Show error message
493
+ function showErrorMessage(message) {
494
+ const msg = document.createElement('div');
495
+ msg.className = 'fixed top-4 right-4 bg-red-500 text-white px-4 sm:px-6 py-3 rounded-lg shadow-lg z-50 flex items-center max-w-sm';
496
+ msg.innerHTML = `
497
+ <svg class="w-4 h-4 sm:w-5 sm:h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
498
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
499
+ </svg>
500
+ <span class="text-sm">${message}</span>
501
+ `;
502
+ document.body.appendChild(msg);
503
+ setTimeout(() => {
504
+ if (document.body.contains(msg)) {
505
+ document.body.removeChild(msg);
506
+ }
507
+ }, 5000);
508
+ }
509
+
510
+ // Initialize page
511
+ document.addEventListener('DOMContentLoaded', () => {
512
+ // Initialize all seasons as collapsed except the first one
513
+ document.querySelectorAll('.season-content').forEach((content, index) => {
514
+ if (index > 0) {
515
+ content.style.display = 'none';
516
+ document.getElementById(`season-arrow-${index}`).style.transform = 'rotate(-90deg)';
517
+ }
518
+ });
519
+ });
520
+ </script>
521
+
522
+ <style>
523
+ .season-content {
524
+ transition: all 0.3s ease;
525
+ }
526
+
527
+ /* Better responsive design */
528
+ .break-all {
529
+ word-break: break-all;
530
+ overflow-wrap: break-word;
531
+ }
532
+ </style>
533
+ {% endblock %}
Backend/fastapi/templates/media_management.html ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Media Management - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
7
+ <!-- Header -->
8
+ <div class="mb-8 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
9
+ <div>
10
+ <h1 class="text-3xl font-bold">Media Management</h1>
11
+ <p class="theme-text-secondary mt-2">Manage your movie and TV show collections</p>
12
+ </div>
13
+
14
+ <div class="flex space-x-2">
15
+ <a href="/media/manage?media_type=movie"
16
+ class="px-4 py-2 rounded-md transition-colors text-sm font-medium {% if media_type == 'movie' %}theme-primary text-white{% else %}theme-card border hover:bg-gray-50{% endif %}">
17
+ Movies
18
+ </a>
19
+ <a href="/media/manage?media_type=tv"
20
+ class="px-4 py-2 rounded-md transition-colors text-sm font-medium {% if media_type == 'tv' %}theme-primary text-white{% else %}theme-card border hover:bg-gray-50{% endif %}">
21
+ TV Shows
22
+ </a>
23
+ </div>
24
+ </div>
25
+
26
+ <!-- Search and Filters -->
27
+ <div class="theme-card p-6 rounded-lg shadow mb-8">
28
+ <div class="flex flex-col md:flex-row gap-4">
29
+ <div class="flex-1">
30
+ <input type="text" id="search-input" placeholder="Search {{ media_type }}s by title..."
31
+ class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-sm">
32
+ </div>
33
+ <div class="flex gap-2">
34
+ <button onclick="searchMedia()"
35
+ class="theme-primary text-white px-6 py-2 rounded-md hover:opacity-90 transition-opacity text-sm font-medium">
36
+ Search
37
+ </button>
38
+ <button onclick="clearSearch()"
39
+ class="border border-gray-300 px-6 py-2 rounded-md hover:bg-gray-50 transition-colors text-sm font-medium">
40
+ Clear
41
+ </button>
42
+ </div>
43
+ </div>
44
+ </div>
45
+
46
+ <!-- Loading Indicator -->
47
+ <div id="loading" class="text-center py-12 hidden">
48
+ <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
49
+ <p class="theme-text-secondary">Loading {{ media_type }}s...</p>
50
+ </div>
51
+
52
+ <!-- Error Display -->
53
+ <div id="error-display" class="hidden mb-8">
54
+ <div class="theme-card p-6 rounded-lg shadow border-l-4 border-red-500">
55
+ <div class="flex items-center mb-4">
56
+ <svg class="h-6 w-6 text-red-500 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
57
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.996-.833-2.764 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
58
+ </svg>
59
+ <h3 class="text-lg font-semibold text-red-700">Error Loading Media</h3>
60
+ </div>
61
+ <p id="error-message" class="text-red-600 mb-4"></p>
62
+ <button onclick="retryLoad()"
63
+ class="theme-primary text-white px-4 py-2 rounded-md hover:opacity-90 transition-opacity text-sm">
64
+ Try Again
65
+ </button>
66
+ </div>
67
+ </div>
68
+
69
+ <!-- Media Grid -->
70
+ <div id="media-grid" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8 gap-4 mb-8">
71
+ <!-- Media items will be loaded here via JavaScript -->
72
+ </div>
73
+
74
+ <!-- No Results Message -->
75
+ <div id="no-results" class="text-center py-12 hidden">
76
+ <div class="theme-card p-8 rounded-lg shadow">
77
+ <svg class="mx-auto h-16 w-16 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
78
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z"/>
79
+ </svg>
80
+ <h3 class="text-lg font-semibold theme-text-secondary mb-2">No {{ media_type }}s found</h3>
81
+ <p class="theme-text-secondary text-sm mb-4">
82
+ {% if media_type == 'movie' %}
83
+ No movies match your search criteria
84
+ {% else %}
85
+ No TV shows match your search criteria
86
+ {% endif %}
87
+ </p>
88
+ <button onclick="clearSearch()"
89
+ class="theme-primary text-white px-4 py-2 rounded-md hover:opacity-90 transition-opacity text-sm">
90
+ Show All {{ media_type|title }}s
91
+ </button>
92
+ </div>
93
+ </div>
94
+
95
+ <!-- Pagination -->
96
+ <div id="pagination" class="flex justify-center items-center space-x-2 mt-8 hidden">
97
+ <!-- Pagination will be loaded here via JavaScript -->
98
+ </div>
99
+
100
+ <!-- Media Info -->
101
+ <div id="media-info" class="theme-card p-4 rounded-lg shadow mt-6 hidden">
102
+ <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2 text-sm theme-text-secondary">
103
+ <span id="results-info"></span>
104
+ <span id="db-info"></span>
105
+ </div>
106
+ </div>
107
+ </div>
108
+
109
+ <script>
110
+ let currentPage = 1;
111
+ let currentSearch = '';
112
+ let isLoading = false;
113
+ const mediaType = '{{ media_type }}';
114
+
115
+ // Show loading state
116
+ function showLoading() {
117
+ isLoading = true;
118
+ document.getElementById('loading').classList.remove('hidden');
119
+ document.getElementById('media-grid').classList.add('hidden');
120
+ document.getElementById('no-results').classList.add('hidden');
121
+ document.getElementById('pagination').classList.add('hidden');
122
+ document.getElementById('media-info').classList.add('hidden');
123
+ document.getElementById('error-display').classList.add('hidden');
124
+ }
125
+
126
+ // Hide loading state
127
+ function hideLoading() {
128
+ isLoading = false;
129
+ document.getElementById('loading').classList.add('hidden');
130
+ document.getElementById('media-grid').classList.remove('hidden');
131
+ }
132
+
133
+ // Show error state
134
+ function showError(message) {
135
+ document.getElementById('error-message').textContent = message;
136
+ document.getElementById('error-display').classList.remove('hidden');
137
+ document.getElementById('loading').classList.add('hidden');
138
+ document.getElementById('media-grid').classList.add('hidden');
139
+ document.getElementById('no-results').classList.add('hidden');
140
+ }
141
+
142
+ // Load media with proper error handling
143
+ async function loadMedia(page = 1, search = '') {
144
+ if (isLoading) return; // Prevent multiple simultaneous requests
145
+
146
+ showLoading();
147
+ currentPage = page;
148
+ currentSearch = search;
149
+
150
+ try {
151
+ const url = `/api/media/list?media_type=${mediaType}&page=${page}&page_size=24&search=${encodeURIComponent(search)}`;
152
+ console.log('Fetching:', url);
153
+
154
+ const response = await fetch(url, {
155
+ method: 'GET',
156
+ credentials: 'same-origin',
157
+ headers: {
158
+ 'Accept': 'application/json',
159
+ 'Content-Type': 'application/json'
160
+ }
161
+ });
162
+
163
+ console.log('Response status:', response.status);
164
+
165
+ if (!response.ok) {
166
+ if (response.status === 401) {
167
+ window.location.href = '/login';
168
+ return;
169
+ }
170
+ throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
171
+ }
172
+
173
+ const data = await response.json();
174
+ console.log('Response data:', data);
175
+
176
+ hideLoading();
177
+
178
+ const grid = document.getElementById('media-grid');
179
+ const mediaKey = mediaType === 'movie' ? 'movies' : 'tv_shows';
180
+ const mediaItems = data[mediaKey] || [];
181
+
182
+ if (mediaItems.length === 0) {
183
+ grid.innerHTML = '';
184
+ document.getElementById('no-results').classList.remove('hidden');
185
+ document.getElementById('pagination').classList.add('hidden');
186
+ document.getElementById('media-info').classList.add('hidden');
187
+ return;
188
+ }
189
+
190
+ document.getElementById('no-results').classList.add('hidden');
191
+
192
+ // Render media items
193
+ grid.innerHTML = mediaItems.map(item => createMediaCard(item)).join('');
194
+
195
+ // Update pagination
196
+ updatePagination(data.current_page || page, data.total_pages || 1);
197
+
198
+ // Update info
199
+ updateMediaInfo(data);
200
+
201
+ } catch (error) {
202
+ console.error('Error loading media:', error);
203
+ hideLoading();
204
+ showError(`Failed to load ${mediaType}s: ${error.message}`);
205
+ }
206
+ }
207
+
208
+ // Create media card HTML
209
+ function createMediaCard(item) {
210
+ const title = item.title || item.name || 'Unknown Title';
211
+ const year = item.release_year || 'Unknown Year';
212
+ const rating = item.rating ? `⭐ ${parseFloat(item.rating).toFixed(1)}` : '';
213
+ const poster = item.poster || 'https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image';
214
+
215
+ return `
216
+ <div class="theme-card rounded-lg shadow hover:shadow-lg transition-all duration-300 group overflow-hidden">
217
+ <div class="relative">
218
+ <div class="aspect-w-2 aspect-h-3">
219
+ <img src="${poster}"
220
+ alt="${title}"
221
+ class="w-full h-64 object-cover"
222
+ onerror="this.src='https://via.placeholder.com/300x450/e5e7eb/9ca3af?text=No+Image'"
223
+ loading="lazy">
224
+ </div>
225
+ <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all duration-300"></div>
226
+ </div>
227
+ <div class="p-3">
228
+ <h3 class="font-semibold text-sm mb-1 line-clamp-2 min-h-[2.5rem]" title="${title}">
229
+ ${title}
230
+ </h3>
231
+ <div class="flex items-center justify-between text-xs theme-text-secondary mb-3">
232
+ <span>${year}</span>
233
+ ${rating ? `<span>${rating}</span>` : ''}
234
+ </div>
235
+ <div class="flex justify-between items-center">
236
+ <a href="/media/edit?tmdb_id=${item.tmdb_id}&db_index=${item.db_index}&media_type=${mediaType}"
237
+ class="text-primary hover:underline text-xs font-medium px-2 py-1 rounded transition-colors hover:bg-blue-50">
238
+ Edit
239
+ </a>
240
+ <button onclick="deleteMedia(${item.tmdb_id}, ${item.db_index}, '${title.replace(/'/g, "\\'")}')"
241
+ class="text-red-600 hover:underline text-xs font-medium px-2 py-1 rounded transition-colors hover:bg-red-50">
242
+ Delete
243
+ </button>
244
+ </div>
245
+ </div>
246
+ </div>
247
+ `;
248
+ }
249
+
250
+ // Update pagination
251
+ function updatePagination(currentPage, totalPages) {
252
+ const pagination = document.getElementById('pagination');
253
+
254
+ if (totalPages <= 1) {
255
+ pagination.classList.add('hidden');
256
+ return;
257
+ }
258
+
259
+ pagination.classList.remove('hidden');
260
+ let paginationHTML = '';
261
+
262
+ // Previous button
263
+ if (currentPage > 1) {
264
+ paginationHTML += `
265
+ <button onclick="loadMedia(${currentPage - 1}, '${currentSearch}')"
266
+ class="px-3 py-2 border rounded-md hover:bg-gray-50 transition-colors text-sm">
267
+ Previous
268
+ </button>
269
+ `;
270
+ }
271
+
272
+ // Page numbers
273
+ const startPage = Math.max(1, currentPage - 2);
274
+ const endPage = Math.min(totalPages, currentPage + 2);
275
+
276
+ // First page
277
+ if (startPage > 1) {
278
+ paginationHTML += `
279
+ <button onclick="loadMedia(1, '${currentSearch}')"
280
+ class="px-3 py-2 border rounded-md hover:bg-gray-50 transition-colors text-sm">
281
+ 1
282
+ </button>
283
+ `;
284
+ if (startPage > 2) {
285
+ paginationHTML += `<span class="px-3 py-2 text-sm">...</span>`;
286
+ }
287
+ }
288
+
289
+ // Page range
290
+ for (let i = startPage; i <= endPage; i++) {
291
+ const isActive = i === currentPage;
292
+ paginationHTML += `
293
+ <button onclick="loadMedia(${i}, '${currentSearch}')"
294
+ class="px-3 py-2 border rounded-md transition-colors text-sm ${
295
+ isActive ? 'theme-primary text-white border-primary' : 'hover:bg-gray-50'
296
+ }">
297
+ ${i}
298
+ </button>
299
+ `;
300
+ }
301
+
302
+ // Last page
303
+ if (endPage < totalPages) {
304
+ if (endPage < totalPages - 1) {
305
+ paginationHTML += `<span class="px-3 py-2 text-sm">...</span>`;
306
+ }
307
+ paginationHTML += `
308
+ <button onclick="loadMedia(${totalPages}, '${currentSearch}')"
309
+ class="px-3 py-2 border rounded-md hover:bg-gray-50 transition-colors text-sm">
310
+ ${totalPages}
311
+ </button>
312
+ `;
313
+ }
314
+
315
+ // Next button
316
+ if (currentPage < totalPages) {
317
+ paginationHTML += `
318
+ <button onclick="loadMedia(${currentPage + 1}, '${currentSearch}')"
319
+ class="px-3 py-2 border rounded-md hover:bg-gray-50 transition-colors text-sm">
320
+ Next
321
+ </button>
322
+ `;
323
+ }
324
+
325
+ pagination.innerHTML = paginationHTML;
326
+ }
327
+
328
+ // Update media info display
329
+ function updateMediaInfo(data) {
330
+ const mediaInfo = document.getElementById('media-info');
331
+ const resultsInfo = document.getElementById('results-info');
332
+ const dbInfo = document.getElementById('db-info');
333
+
334
+ const startItem = ((data.current_page - 1) * 24) + 1;
335
+ const endItem = Math.min(data.current_page * 24, data.total_count);
336
+
337
+ resultsInfo.textContent = `Showing ${startItem}-${endItem} of ${data.total_count} ${mediaType}s`;
338
+
339
+ if (data.databases_checked && data.databases_checked.length > 0) {
340
+ dbInfo.textContent = `Database${data.databases_checked.length > 1 ? 's' : ''}: ${data.databases_checked.join(', ')}`;
341
+ }
342
+
343
+ mediaInfo.classList.remove('hidden');
344
+ }
345
+
346
+ // Search functionality
347
+ function searchMedia() {
348
+ const searchInput = document.getElementById('search-input');
349
+ const search = searchInput.value.trim();
350
+ loadMedia(1, search);
351
+ }
352
+
353
+ // Clear search
354
+ function clearSearch() {
355
+ document.getElementById('search-input').value = '';
356
+ loadMedia(1, '');
357
+ }
358
+
359
+ // Retry load function
360
+ function retryLoad() {
361
+ loadMedia(currentPage, currentSearch);
362
+ }
363
+
364
+ // Delete media with confirmation
365
+ async function deleteMedia(tmdbId, dbIndex, title) {
366
+ if (!confirm(`Are you sure you want to delete "${title}"?\n\nThis action cannot be undone.`)) return;
367
+
368
+ try {
369
+ const response = await fetch(`/api/media/delete?tmdb_id=${tmdbId}&db_index=${dbIndex}&media_type=${mediaType}`, {
370
+ method: 'DELETE',
371
+ credentials: 'same-origin',
372
+ headers: {
373
+ 'Accept': 'application/json',
374
+ 'Content-Type': 'application/json'
375
+ }
376
+ });
377
+
378
+ if (response.ok) {
379
+ // Show success message briefly
380
+ const successMsg = document.createElement('div');
381
+ successMsg.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg z-50';
382
+ successMsg.textContent = `"${title}" deleted successfully`;
383
+ document.body.appendChild(successMsg);
384
+
385
+ setTimeout(() => {
386
+ document.body.removeChild(successMsg);
387
+ }, 3000);
388
+
389
+ // Reload current page
390
+ loadMedia(currentPage, currentSearch);
391
+ } else {
392
+ const error = await response.json();
393
+ alert(`Error deleting "${title}": ${error.detail || 'Unknown error'}`);
394
+ }
395
+ } catch (error) {
396
+ console.error('Error deleting media:', error);
397
+ alert(`Error deleting "${title}": ${error.message}`);
398
+ }
399
+ }
400
+
401
+ // Initialize page
402
+ document.addEventListener('DOMContentLoaded', () => {
403
+ // Load media on page load
404
+ loadMedia();
405
+
406
+ // Add enter key listener to search input
407
+ document.getElementById('search-input').addEventListener('keypress', (e) => {
408
+ if (e.key === 'Enter') {
409
+ e.preventDefault();
410
+ searchMedia();
411
+ }
412
+ });
413
+
414
+ // Add input event for real-time search (with debouncing)
415
+ let searchTimeout;
416
+ document.getElementById('search-input').addEventListener('input', (e) => {
417
+ clearTimeout(searchTimeout);
418
+ const searchValue = e.target.value.trim();
419
+
420
+ if (searchValue.length === 0) {
421
+ searchTimeout = setTimeout(() => {
422
+ loadMedia(1, '');
423
+ }, 300);
424
+ }
425
+ });
426
+ });
427
+ </script>
428
+
429
+ <style>
430
+ .line-clamp-2 {
431
+ display: -webkit-box;
432
+ -webkit-line-clamp: 2;
433
+ -webkit-box-orient: vertical;
434
+ overflow: hidden;
435
+ }
436
+
437
+ .aspect-w-2 {
438
+ position: relative;
439
+ padding-bottom: 150%; /* 2:3 aspect ratio */
440
+ }
441
+
442
+ .aspect-w-2 > img {
443
+ position: absolute;
444
+ height: 100%;
445
+ width: 100%;
446
+ top: 0;
447
+ right: 0;
448
+ bottom: 0;
449
+ left: 0;
450
+ }
451
+
452
+ @media (max-width: 640px) {
453
+ .grid {
454
+ grid-template-columns: repeat(2, minmax(0, 1fr));
455
+ gap: 0.75rem;
456
+ }
457
+ }
458
+
459
+ @media (min-width: 1536px) {
460
+ .grid {
461
+ grid-template-columns: repeat(8, minmax(0, 1fr));
462
+ }
463
+ }
464
+
465
+ /* Loading animation */
466
+ @keyframes spin {
467
+ to {
468
+ transform: rotate(360deg);
469
+ }
470
+ }
471
+
472
+ .animate-spin {
473
+ animation: spin 1s linear infinite;
474
+ }
475
+ </style>
476
+ {% endblock %}
Backend/fastapi/templates/public_status.html ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}System Status - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
7
+ <!-- Header -->
8
+ <div class="mb-8 text-center">
9
+ <h1 class="text-3xl font-bold">System Status</h1>
10
+ <p class="theme-text-secondary mt-2">Current status of Telegram Stremio services</p>
11
+ </div>
12
+
13
+ <!-- Status Cards -->
14
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
15
+ <div class="theme-card p-6 rounded-lg shadow text-center">
16
+ <div class="w-16 h-16 mx-auto mb-4 theme-primary rounded-full flex items-center justify-center">
17
+ <span class="text-white text-2xl">✓</span>
18
+ </div>
19
+ <h3 class="text-lg font-semibold mb-2">Backend Status</h3>
20
+ <p class="text-green-600 font-medium">{{ stats.status|title }}</p>
21
+ </div>
22
+
23
+ <div class="theme-card p-6 rounded-lg shadow text-center">
24
+ <div class="w-16 h-16 mx-auto mb-4 bg-blue-500 rounded-full flex items-center justify-center">
25
+ <span class="text-white text-2xl">↑</span>
26
+ </div>
27
+ <h3 class="text-lg font-semibold mb-2">Uptime</h3>
28
+ <p class="text-green-600 font-medium">{{ stats.uptime }}</p>
29
+ </div>
30
+
31
+ <div class="theme-card p-6 rounded-lg shadow text-center">
32
+ <div class="w-16 h-16 mx-auto mb-4 bg-purple-500 rounded-full flex items-center justify-center">
33
+ <span class="text-white text-2xl">v</span>
34
+ </div>
35
+ <h3 class="text-lg font-semibold mb-2">Version</h3>
36
+ <p class="theme-text-secondary font-medium">{{ stats.version }}</p>
37
+ </div>
38
+ </div>
39
+
40
+ <!-- Services Status -->
41
+ <div class="theme-card p-6 rounded-lg shadow mb-8">
42
+ <h2 class="text-xl font-semibold mb-4">Service Status</h2>
43
+ <div class="space-y-4">
44
+ <div class="flex justify-between items-center">
45
+ <span>API Endpoints</span>
46
+ <span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-sm">Active</span>
47
+ </div>
48
+ <div class="flex justify-between items-center">
49
+ <span>Stremio Addon</span>
50
+ <span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-sm">Active</span>
51
+ </div>
52
+ <div class="flex justify-between items-center">
53
+ <span>Database</span>
54
+ <span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-sm">Connected</span>
55
+ </div>
56
+ </div>
57
+ </div>
58
+
59
+ {% if not is_authenticated %}
60
+ <!-- Admin Access -->
61
+ <div class="theme-card p-6 rounded-lg shadow text-center">
62
+ <h2 class="text-xl font-semibold mb-4">Administrator Access</h2>
63
+ <p class="theme-text-secondary mb-4">Login to access the full admin dashboard</p>
64
+ <a href="/login" class="theme-primary text-white px-6 py-3 rounded-md hover:opacity-90 transition-opacity inline-block">
65
+ Admin Login
66
+ </a>
67
+ </div>
68
+ {% endif %}
69
+ </div>
70
+ {% endblock %}
Backend/fastapi/templates/stremio_guide.html ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Stremio Setup Guide - Telegram Stremio{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
7
+ <!-- Header -->
8
+ <div class="mb-8 text-center">
9
+ <h1 class="text-3xl font-bold">Stremio Addon Setup</h1>
10
+ <p class="theme-text-secondary mt-2">Install the Telegram Stremio addon to access your media through Stremio</p>
11
+ </div>
12
+
13
+ <!-- Installation Steps -->
14
+ <div class="space-y-6">
15
+ <div class="theme-card p-6 rounded-lg shadow">
16
+ <div class="flex items-start space-x-4">
17
+ <div class="w-8 h-8 theme-primary rounded-full flex items-center justify-center flex-shrink-0">
18
+ <span class="text-white font-semibold">1</span>
19
+ </div>
20
+ <div>
21
+ <h3 class="text-lg font-semibold mb-2">Copy the Addon URL</h3>
22
+ <p class="theme-text-secondary mb-4">Copy the manifest URL below to your clipboard</p>
23
+ <div class="bg-gray-100 p-4 rounded-md font-mono text-sm break-all">
24
+ <span id="addon-url">{{ request.base_url }}stremio/manifest.json</span>
25
+ <button onclick="copyToClipboard('addon-url')"
26
+ class="ml-2 text-primary hover:underline">Copy</button>
27
+ </div>
28
+ </div>
29
+ </div>
30
+ </div>
31
+
32
+ <div class="theme-card p-6 rounded-lg shadow">
33
+ <div class="flex items-start space-x-4">
34
+ <div class="w-8 h-8 theme-primary rounded-full flex items-center justify-center flex-shrink-0">
35
+ <span class="text-white font-semibold">2</span>
36
+ </div>
37
+ <div>
38
+ <h3 class="text-lg font-semibold mb-2">Open Stremio</h3>
39
+ <p class="theme-text-secondary">Launch the Stremio application on your device</p>
40
+ </div>
41
+ </div>
42
+ </div>
43
+
44
+ <div class="theme-card p-6 rounded-lg shadow">
45
+ <div class="flex items-start space-x-4">
46
+ <div class="w-8 h-8 theme-primary rounded-full flex items-center justify-center flex-shrink-0">
47
+ <span class="text-white font-semibold">3</span>
48
+ </div>
49
+ <div>
50
+ <h3 class="text-lg font-semibold mb-2">Navigate to Addons</h3>
51
+ <p class="theme-text-secondary">Go to the "Addons" section in Stremio's main menu</p>
52
+ </div>
53
+ </div>
54
+ </div>
55
+
56
+ <div class="theme-card p-6 rounded-lg shadow">
57
+ <div class="flex items-start space-x-4">
58
+ <div class="w-8 h-8 theme-primary rounded-full flex items-center justify-center flex-shrink-0">
59
+ <span class="text-white font-semibold">4</span>
60
+ </div>
61
+ <div>
62
+ <h3 class="text-lg font-semibold mb-2">Install the Addon</h3>
63
+ <p class="theme-text-secondary mb-4">Paste the URL in the "Add Addon" field and click install</p>
64
+ <div class="bg-blue-50 border border-blue-200 text-blue-700 p-4 rounded-md">
65
+ <strong>Tip:</strong> Make sure your device can access this server's IP address on the network
66
+ </div>
67
+ </div>
68
+ </div>
69
+ </div>
70
+ </div>
71
+
72
+ <!-- Additional Information -->
73
+ <div class="theme-card p-6 rounded-lg shadow mt-8">
74
+ <h2 class="text-xl font-semibold mb-4">Additional Information</h2>
75
+ <div class="space-y-4">
76
+ <div>
77
+ <h4 class="font-medium">Network Requirements</h4>
78
+ <p class="theme-text-secondary text-sm">Both Stremio and this server must be on the same network or the server must be accessible via internet</p>
79
+ </div>
80
+ <div>
81
+ <h4 class="font-medium">Supported Content</h4>
82
+ <p class="theme-text-secondary text-sm">The addon provides access to movies and TV shows in your media collection</p>
83
+ </div>
84
+ <div>
85
+ <h4 class="font-medium">Updates</h4>
86
+ <p class="theme-text-secondary text-sm">The addon will automatically sync with your media library changes</p>
87
+ </div>
88
+ </div>
89
+ </div>
90
+ </div>
91
+
92
+ <script>
93
+ function copyToClipboard(elementId) {
94
+ const element = document.getElementById(elementId);
95
+ const text = element.textContent;
96
+
97
+ navigator.clipboard.writeText(text).then(() => {
98
+ // Show success message
99
+ const button = element.nextElementSibling;
100
+ const originalText = button.textContent;
101
+ button.textContent = 'Copied!';
102
+ button.classList.add('text-green-600');
103
+
104
+ setTimeout(() => {
105
+ button.textContent = originalText;
106
+ button.classList.remove('text-green-600');
107
+ }, 2000);
108
+ }).catch(err => {
109
+ console.error('Failed to copy: ', err);
110
+ alert('Failed to copy to clipboard');
111
+ });
112
+ }
113
+ </script>
114
+ {% endblock %}
Backend/fastapi/themes.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Theme configurations based on your color palettes
2
+ THEMES = {
3
+ "purple_gradient": {
4
+ "name": "Purple Gradient",
5
+ "colors": {
6
+ "primary": "#A855F7",
7
+ "secondary": "#7C3AED",
8
+ "accent": "#C084FC",
9
+ "background": "#F8FAFC",
10
+ "card": "#FFFFFF",
11
+ "text": "#1E293B",
12
+ "text_secondary": "#64748B"
13
+ },
14
+ "css_classes": "theme-purple-gradient"
15
+ },
16
+ "blue_navy": {
17
+ "name": "Navy Blue",
18
+ "colors": {
19
+ "primary": "#1E40AF",
20
+ "secondary": "#1E3A8A",
21
+ "accent": "#3B82F6",
22
+ "background": "#F1F5F9",
23
+ "card": "#FFFFFF",
24
+ "text": "#1E293B",
25
+ "text_secondary": "#475569"
26
+ },
27
+ "css_classes": "theme-blue-navy"
28
+ },
29
+ "sunset_warm": {
30
+ "name": "Sunset Warm",
31
+ "colors": {
32
+ "primary": "#F59E0B",
33
+ "secondary": "#DC2626",
34
+ "accent": "#EC4899",
35
+ "background": "#FFFBEB",
36
+ "card": "#FFFFFF",
37
+ "text": "#1F2937",
38
+ "text_secondary": "#6B7280"
39
+ },
40
+ "css_classes": "theme-sunset-warm"
41
+ },
42
+ "ocean_mint": {
43
+ "name": "Ocean Mint",
44
+ "colors": {
45
+ "primary": "#10B981",
46
+ "secondary": "#059669",
47
+ "accent": "#06B6D4",
48
+ "background": "#F0FDF4",
49
+ "card": "#FFFFFF",
50
+ "text": "#1F2937",
51
+ "text_secondary": "#4B5563"
52
+ },
53
+ "css_classes": "theme-ocean-mint"
54
+ },
55
+ "dark_professional": {
56
+ "name": "Dark Professional",
57
+ "colors": {
58
+ "primary": "#06B6D4",
59
+ "secondary": "#0891B2",
60
+ "accent": "#22D3EE",
61
+ "background": "#0F172A",
62
+ "card": "#1E293B",
63
+ "text": "#F8FAFC",
64
+ "text_secondary": "#CBD5E1"
65
+ },
66
+ "css_classes": "theme-dark-professional"
67
+ }
68
+ }
69
+
70
+ def get_theme(theme_name: str = "purple_gradient"):
71
+ return THEMES.get(theme_name, THEMES["purple_gradient"])
72
+
73
+ def get_all_themes():
74
+ return THEMES
Backend/helper/custom_dl.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from pyrogram import utils, raw
3
+ from pyrogram.errors import AuthBytesInvalid
4
+ from pyrogram.file_id import FileId, FileType, ThumbnailSource
5
+ from pyrogram.session import Session, Auth
6
+ from typing import Dict, Union
7
+ from Backend.logger import LOGGER
8
+ from Backend.helper.exceptions import FIleNotFound
9
+ from Backend.helper.pyro import get_file_ids
10
+ from Backend.pyrofork.bot import work_loads
11
+ from pyrogram import Client, utils, raw
12
+
13
+
14
+ class ByteStreamer:
15
+ def __init__(self, client: Client):
16
+ self.clean_timer = 30 * 60
17
+ self.client: Client = client
18
+ self.__cached_file_ids: Dict[int, FileId] = {}
19
+ asyncio.create_task(self.clean_cache())
20
+
21
+ async def get_file_properties(self, chat_id: int, message_id: int) -> FileId:
22
+ if message_id not in self.__cached_file_ids:
23
+ file_id = await get_file_ids(self.client, int(chat_id), int(message_id))
24
+ if not file_id:
25
+ LOGGER.info('Message with ID %s not found!', message_id)
26
+ raise FIleNotFound
27
+ self.__cached_file_ids[message_id] = file_id
28
+ return self.__cached_file_ids[message_id]
29
+
30
+ async def yield_file(self, file_id: FileId, index: int, offset: int, first_part_cut: int, last_part_cut: int, part_count: int, chunk_size: int) -> Union[str, None]: # type: ignore
31
+ client = self.client
32
+ work_loads[index] += 1
33
+ LOGGER.debug(f"Starting to yielding file with client {index}.")
34
+ media_session = await self.generate_media_session(client, file_id)
35
+ current_part = 1
36
+ location = await self.get_location(file_id)
37
+ try:
38
+ r = await media_session.send(raw.functions.upload.GetFile(location=location, offset=offset, limit=chunk_size))
39
+ if isinstance(r, raw.types.upload.File):
40
+ while True:
41
+ chunk = r.bytes
42
+ if not chunk:
43
+ break
44
+ elif part_count == 1:
45
+ yield chunk[first_part_cut:last_part_cut]
46
+ elif current_part == 1:
47
+ yield chunk[first_part_cut:]
48
+ elif current_part == part_count:
49
+ yield chunk[:last_part_cut]
50
+ else:
51
+ yield chunk
52
+
53
+ current_part += 1
54
+ offset += chunk_size
55
+
56
+ if current_part > part_count:
57
+ break
58
+
59
+ r = await media_session.send(
60
+ raw.functions.upload.GetFile(
61
+ location=location, offset=offset, limit=chunk_size
62
+ ),
63
+ )
64
+ except (TimeoutError, AttributeError):
65
+ pass
66
+ finally:
67
+ LOGGER.debug("Finished yielding file with {current_part} parts.")
68
+ work_loads[index] -= 1
69
+
70
+ async def generate_media_session(self, client: Client, file_id: FileId) -> Session:
71
+ media_session = client.media_sessions.get(file_id.dc_id, None)
72
+ if media_session is None:
73
+ if file_id.dc_id != await client.storage.dc_id():
74
+ media_session = Session(
75
+ client,
76
+ file_id.dc_id,
77
+ await Auth(client, file_id.dc_id, await client.storage.test_mode()).create(),
78
+ await client.storage.test_mode(),
79
+ is_media=True,
80
+ )
81
+ await media_session.start()
82
+ for _ in range(6):
83
+ exported_auth = await client.invoke(raw.functions.auth.ExportAuthorization(dc_id=file_id.dc_id))
84
+ try:
85
+
86
+ await media_session.send(raw.functions.auth.ImportAuthorization(id=exported_auth.id, bytes=exported_auth.bytes))
87
+ break
88
+ except AuthBytesInvalid:
89
+ LOGGER.debug(f"Invalid authorization bytes for DC {file_id.dc_id}, retrying...")
90
+ except OSError:
91
+ LOGGER.debug(f"Connection error, retrying...")
92
+ await asyncio.sleep(2)
93
+ else:
94
+ await media_session.stop()
95
+ LOGGER.debug(f"Failed to establish media session for DC {file_id.dc_id} after multiple retries")
96
+ return None
97
+ else:
98
+ media_session = Session(
99
+ client,
100
+ file_id.dc_id,
101
+ await client.storage.auth_key(),
102
+ await client.storage.test_mode(),
103
+ is_media=True,
104
+ )
105
+ await media_session.start()
106
+ LOGGER.debug(f"Created media session for DC {file_id.dc_id}")
107
+ client.media_sessions[file_id.dc_id] = media_session
108
+ else:
109
+ LOGGER.debug(f"Using cached media session for DC {file_id.dc_id}")
110
+ return media_session
111
+
112
+
113
+ @staticmethod
114
+ async def get_location(file_id: FileId) -> Union[raw.types.InputPhotoFileLocation, raw.types.InputDocumentFileLocation, raw.types.InputPeerPhotoFileLocation]:
115
+ file_type = file_id.file_type
116
+ if file_type == FileType.CHAT_PHOTO:
117
+ if file_id.chat_id > 0:
118
+ peer = raw.types.InputPeerUser(
119
+ user_id=file_id.chat_id, access_hash=file_id.chat_access_hash)
120
+ else:
121
+ if file_id.chat_access_hash == 0:
122
+ peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
123
+ else:
124
+ peer = raw.types.InputPeerChannel(channel_id=utils.get_channel_id(
125
+ file_id.chat_id), access_hash=file_id.chat_access_hash)
126
+ location = raw.types.InputPeerPhotoFileLocation(peer=peer,
127
+ volume_id=file_id.volume_id,
128
+ local_id=file_id.local_id,
129
+ big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG)
130
+ elif file_type == FileType.PHOTO:
131
+ location = raw.types.InputPhotoFileLocation(id=file_id.media_id,
132
+ access_hash=file_id.access_hash,
133
+ file_reference=file_id.file_reference,
134
+ thumb_size=file_id.thumbnail_size)
135
+ else:
136
+ location = raw.types.InputDocumentFileLocation(id=file_id.media_id,
137
+ access_hash=file_id.access_hash,
138
+ file_reference=file_id.file_reference,
139
+ thumb_size=file_id.thumbnail_size)
140
+ return location
141
+
142
+ async def clean_cache(self) -> None:
143
+ while True:
144
+ await asyncio.sleep(self.clean_timer)
145
+ self.__cached_file_ids.clear()
146
+ LOGGER.debug("Cleaned the cache")
Backend/helper/custom_filter.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram.filters import create
2
+ from Backend.config import Telegram
3
+
4
+ class CustomFilters:
5
+
6
+ @staticmethod
7
+ async def owner_filter(client, message):
8
+ user = message.from_user or message.sender_chat
9
+ uid = user.id
10
+ return uid == Telegram.OWNER_ID
11
+
12
+ owner = create(owner_filter)
Backend/helper/database.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import create_task
2
+ from bson import ObjectId
3
+ import motor.motor_asyncio
4
+ from datetime import datetime
5
+ from pydantic import ValidationError
6
+ from pymongo import ASCENDING, DESCENDING
7
+ from typing import Dict, List, Optional, Tuple, Any
8
+
9
+ from Backend.logger import LOGGER
10
+ from Backend.config import Telegram
11
+ import re
12
+ from Backend.helper.encrypt import decode_string, encode_string
13
+ from Backend.helper.modal import Episode, MovieSchema, QualityDetail, Season, TVShowSchema
14
+ from Backend.helper.task_manager import delete_message
15
+
16
+
17
+ def convert_objectid_to_str(document: Dict[str, Any]) -> Dict[str, Any]:
18
+ for key, value in document.items():
19
+ if isinstance(value, ObjectId):
20
+ document[key] = str(value)
21
+ elif isinstance(value, list):
22
+ document[key] = [convert_objectid_to_str(item) if isinstance(item, dict) else item for item in value]
23
+ elif isinstance(value, dict):
24
+ document[key] = convert_objectid_to_str(value)
25
+ return document
26
+
27
+
28
+ class Database:
29
+ def __init__(self, db_name: str = "dbFyvio"):
30
+ self.db_uris = Telegram.DATABASE
31
+ self.db_name = db_name
32
+
33
+ if len(self.db_uris) < 2:
34
+ raise ValueError("At least 2 database URIs are required (1 for tracking + 1 for storage).")
35
+
36
+ self.clients: Dict[str, motor.motor_asyncio.AsyncIOMotorClient] = {}
37
+ self.dbs: Dict[str, motor.motor_asyncio.AsyncIOMotorDatabase] = {}
38
+
39
+ self.current_db_index = 1
40
+
41
+ async def connect(self):
42
+ try:
43
+ for index, uri in enumerate(self.db_uris):
44
+ client = motor.motor_asyncio.AsyncIOMotorClient(uri)
45
+ db_key = "tracking" if index == 0 else f"storage_{index}"
46
+ self.clients[db_key] = client
47
+ self.dbs[db_key] = client[self.db_name]
48
+ db_type = "Tracking" if index == 0 else f"Storage {index}"
49
+
50
+ masked_uri = re.sub(r"://(.*?):.*?@", r"://\1:*****@", uri)
51
+ masked_uri = masked_uri.split('?')[0]
52
+
53
+ LOGGER.info(f"{db_type} Database connected successfully: {masked_uri}")
54
+
55
+ state = await self.dbs["tracking"]["state"].find_one({"_id": "db_index"})
56
+ if not state:
57
+ await self.dbs["tracking"]["state"].insert_one({"_id": "db_index", "current_index": 1})
58
+ self.current_db_index = 1
59
+ else:
60
+ self.current_db_index = state["current_index"]
61
+
62
+ LOGGER.info(f"Active storage DB: storage_{self.current_db_index}")
63
+
64
+ except Exception as e:
65
+ LOGGER.error(f"Database connection error: {e}")
66
+
67
+ async def disconnect(self):
68
+ for client in self.clients.values():
69
+ client.close()
70
+ LOGGER.info("All database connections closed.")
71
+
72
+ async def update_current_db_index(self):
73
+ await self.dbs["tracking"]["state"].update_one(
74
+ {"_id": "db_index"},
75
+ {"$set": {"current_index": self.current_db_index}},
76
+ upsert=True
77
+ )
78
+
79
+
80
+ # -------------------------------
81
+ # Helper Methods for Repeated Logic
82
+ # -------------------------------
83
+ def _get_sort_dict(self, sort_params: List[Tuple[str, str]]) -> Dict[str, int]:
84
+ if sort_params:
85
+ sort_field, sort_direction = sort_params[0]
86
+ return {sort_field: DESCENDING if sort_direction.lower() == "desc" else ASCENDING}
87
+ return {"updated_on": DESCENDING}
88
+
89
+ async def _paginate_collection(
90
+ self, collection_name: str, sort_dict: Dict[str, int],
91
+ page: int, page_size: int
92
+ ) -> Tuple[List[Any], List[int], int]:
93
+ skip = (page - 1) * page_size
94
+ results = []
95
+ dbs_checked = [self.current_db_index]
96
+ active_db_key = f"storage_{self.current_db_index}"
97
+ active_db = self.dbs[active_db_key]
98
+ total_active = await active_db[collection_name].count_documents({})
99
+
100
+ if skip < total_active:
101
+ cursor = active_db[collection_name].find({}).sort(sort_dict).skip(skip).limit(page_size)
102
+ results = await cursor.to_list(None)
103
+ remaining = page_size - len(results)
104
+ if remaining > 0 and self.current_db_index > 1:
105
+ prev_db_index = self.current_db_index - 1
106
+ prev_db_key = f"storage_{prev_db_index}"
107
+ prev_db = self.dbs[prev_db_key]
108
+ dbs_checked.append(prev_db_index)
109
+ prev_cursor = prev_db[collection_name].find({}).sort(sort_dict).limit(remaining)
110
+ results.extend(await prev_cursor.to_list(None))
111
+ else:
112
+ if self.current_db_index > 1:
113
+ prev_db_index = self.current_db_index - 1
114
+ prev_db_key = f"storage_{prev_db_index}"
115
+ prev_db = self.dbs[prev_db_key]
116
+ dbs_checked.append(prev_db_index)
117
+ cursor = prev_db[collection_name].find({}).sort(sort_dict).skip(skip - total_active).limit(page_size)
118
+ results = await cursor.to_list(None)
119
+
120
+ total_prev = 0
121
+ if self.current_db_index > 1:
122
+ prev_db_key = f"storage_{self.current_db_index - 1}"
123
+ total_prev = await self.dbs[prev_db_key][collection_name].count_documents({})
124
+ total_count = total_active + total_prev
125
+ return results, dbs_checked, total_count
126
+
127
+ async def _move_document(
128
+ self, collection_name: str, document: dict, old_db_index: int
129
+ ) -> bool:
130
+ current_db_key = f"storage_{self.current_db_index}"
131
+ old_db_key = f"storage_{old_db_index}"
132
+ document["db_index"] = self.current_db_index
133
+ try:
134
+ await self.dbs[current_db_key][collection_name].insert_one(document)
135
+ await self.dbs[old_db_key][collection_name].delete_one({"_id": document["_id"]})
136
+ LOGGER.info(f"✅ Moved document {document.get('tmdb_id')} from {old_db_key} to {current_db_key}")
137
+ return True
138
+ except Exception as e:
139
+ LOGGER.error(f"Error moving document to {current_db_key}: {e}")
140
+ return False
141
+
142
+ async def _handle_storage_error(self, func, *args, total_storage_dbs: int) -> Optional[Any]:
143
+ next_db_index = (self.current_db_index % total_storage_dbs) + 1
144
+ if next_db_index == 1:
145
+ LOGGER.warning("⚠️ All storage databases are full! Add more.")
146
+ return None
147
+ self.current_db_index = next_db_index
148
+ await self.update_current_db_index()
149
+ LOGGER.info(f"Switched to storage_{self.current_db_index}")
150
+ return await func(*args)
151
+
152
+
153
+ # -------------------------------
154
+ # Multi Database Method for insert/update/delete/list
155
+ # -------------------------------
156
+
157
+ async def insert_media(
158
+ self, metadata_info: dict,
159
+ channel: int, msg_id: int, size: str, name: str
160
+ ) -> Optional[ObjectId]:
161
+
162
+ if metadata_info['media_type'] == "movie":
163
+ media = MovieSchema(
164
+ tmdb_id=metadata_info['tmdb_id'],
165
+ imdb_id=metadata_info['imdb_id'],
166
+ db_index=self.current_db_index,
167
+ title=metadata_info['title'],
168
+ genres=metadata_info['genres'],
169
+ description=metadata_info['description'],
170
+ rating=metadata_info['rate'],
171
+ release_year=metadata_info['year'],
172
+ poster=metadata_info['poster'],
173
+ backdrop=metadata_info['backdrop'],
174
+ logo=metadata_info['logo'],
175
+ media_type=metadata_info['media_type'],
176
+ telegram=[QualityDetail(
177
+ quality=metadata_info['quality'],
178
+ id=metadata_info['encoded_string'],
179
+ name=name,
180
+ size=size
181
+ )]
182
+ )
183
+ return await self.update_movie(media)
184
+ else:
185
+ tv_show = TVShowSchema(
186
+ tmdb_id=metadata_info['tmdb_id'],
187
+ imdb_id=metadata_info['imdb_id'],
188
+ db_index=self.current_db_index,
189
+ title=metadata_info['title'],
190
+ genres=metadata_info['genres'],
191
+ description=metadata_info['description'],
192
+ rating=metadata_info['rate'],
193
+ release_year=metadata_info['year'],
194
+ poster=metadata_info['poster'],
195
+ backdrop=metadata_info['backdrop'],
196
+ logo=metadata_info['logo'],
197
+ media_type=metadata_info['media_type'],
198
+ seasons=[Season(
199
+ season_number=metadata_info['season_number'],
200
+ episodes=[Episode(
201
+ episode_number=metadata_info['episode_number'],
202
+ title=metadata_info['episode_title'],
203
+ episode_backdrop=metadata_info['episode_backdrop'],
204
+ telegram=[QualityDetail(
205
+ quality=metadata_info['quality'],
206
+ id=metadata_info['encoded_string'],
207
+ name=name,
208
+ size=size
209
+ )]
210
+ )]
211
+ )]
212
+ )
213
+ return await self.update_tv_show(tv_show)
214
+
215
+ async def update_movie(self, movie_data: MovieSchema) -> Optional[ObjectId]:
216
+ try:
217
+ movie_dict = movie_data.dict()
218
+ except ValidationError as e:
219
+ LOGGER.error(f"Validation error: {e}")
220
+ return None
221
+
222
+ tmdb_id = movie_dict["tmdb_id"]
223
+
224
+
225
+ title = movie_dict["title"]
226
+ release_year = movie_dict["release_year"]
227
+ quality_to_update = movie_dict["telegram"][0]
228
+ target_quality = quality_to_update["quality"]
229
+ current_db_key = f"storage_{self.current_db_index}"
230
+
231
+ total_storage_dbs = len(self.dbs) - 1
232
+ existing_db_key = None
233
+ existing_db_index = None
234
+ existing_movie = None
235
+
236
+
237
+ for db_index in range(1, total_storage_dbs + 1):
238
+ db_key = f"storage_{db_index}"
239
+ movie = await self.dbs[db_key]["movie"].find_one(
240
+ {"title": title, "release_year": release_year}
241
+ )
242
+ if movie:
243
+ existing_db_key = db_key
244
+ existing_db_index = db_index
245
+ existing_movie = movie
246
+ break
247
+
248
+ if not existing_movie:
249
+ try:
250
+ movie_dict["db_index"] = self.current_db_index
251
+ result = await self.dbs[current_db_key]["movie"].insert_one(movie_dict)
252
+ return result.inserted_id
253
+ except Exception as e:
254
+ LOGGER.error(f"Insertion failed in {current_db_key}: {e}")
255
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
256
+ return await self._handle_storage_error(self.update_movie, movie_data, total_storage_dbs=total_storage_dbs)
257
+ return None
258
+
259
+ movie_id = existing_movie["_id"]
260
+ existing_qualities = existing_movie.get("telegram", [])
261
+ matching_quality = next((q for q in existing_qualities if q["quality"] == target_quality), None)
262
+ if matching_quality:
263
+
264
+ try:
265
+ old_id = matching_quality.get("id")
266
+ if old_id:
267
+ decoded_data = await decode_string(old_id)
268
+ chat_id = int(f"-100{decoded_data['chat_id']}")
269
+ msg_id = int(decoded_data['msg_id'])
270
+ create_task(delete_message(chat_id, msg_id))
271
+ except Exception as e:
272
+ LOGGER.error(f"Failed to queue old quality file for deletion: {e}")
273
+
274
+ matching_quality.update(quality_to_update)
275
+ else:
276
+ existing_qualities.append(quality_to_update)
277
+ existing_movie["telegram"] = existing_qualities
278
+ existing_movie["updated_on"] = datetime.utcnow()
279
+
280
+ if existing_db_index != self.current_db_index:
281
+ try:
282
+ if await self._move_document("movie", existing_movie, existing_db_index):
283
+ return movie_id
284
+ except Exception as e:
285
+ LOGGER.error(f"Error moving movie to {current_db_key}: {e}")
286
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
287
+ return await self._handle_storage_error(self.update_movie, movie_data, total_storage_dbs=total_storage_dbs)
288
+
289
+ try:
290
+ await self.dbs[existing_db_key]["movie"].replace_one({"_id": movie_id}, existing_movie)
291
+ return movie_id
292
+ except Exception as e:
293
+ LOGGER.error(f"Failed to update movie {tmdb_id} in {existing_db_key}: {e}")
294
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
295
+ return await self._handle_storage_error(self.update_movie, movie_data, total_storage_dbs=total_storage_dbs)
296
+
297
+ async def update_tv_show(self, tv_show_data: TVShowSchema) -> Optional[ObjectId]:
298
+ try:
299
+ tv_show_dict = tv_show_data.dict()
300
+ except ValidationError as e:
301
+ LOGGER.error(f"Validation error: {e}")
302
+ return None
303
+
304
+ tmdb_id = tv_show_dict["tmdb_id"]
305
+
306
+
307
+ title = tv_show_dict["title"]
308
+ release_year = tv_show_dict["release_year"]
309
+ current_db_key = f"storage_{self.current_db_index}"
310
+ total_storage_dbs = len(self.dbs) - 1
311
+
312
+ existing_db_key = None
313
+ existing_db_index = None
314
+ existing_tv = None
315
+
316
+ for db_index in range(1, total_storage_dbs + 1):
317
+ db_key = f"storage_{db_index}"
318
+ tv = await self.dbs[db_key]["tv"].find_one(
319
+ {"title": title, "release_year": release_year}
320
+ )
321
+ if tv:
322
+ existing_db_key = db_key
323
+ existing_db_index = db_index
324
+ existing_tv = tv
325
+ break
326
+
327
+ if not existing_tv:
328
+ try:
329
+ tv_show_dict["db_index"] = self.current_db_index
330
+ result = await self.dbs[current_db_key]["tv"].insert_one(tv_show_dict)
331
+ return result.inserted_id
332
+ except Exception as e:
333
+ LOGGER.error(f"Insertion failed in {current_db_key}: {e}")
334
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
335
+ return await self._handle_storage_error(self.update_tv_show, tv_show_data, total_storage_dbs=total_storage_dbs)
336
+ return None
337
+
338
+ tv_id = existing_tv["_id"]
339
+ for season in tv_show_dict["seasons"]:
340
+ existing_season = next(
341
+ (s for s in existing_tv["seasons"] if s["season_number"] == season["season_number"]), None
342
+ )
343
+ if existing_season:
344
+ for episode in season["episodes"]:
345
+ existing_episode = next(
346
+ (e for e in existing_season["episodes"] if e["episode_number"] == episode["episode_number"]), None
347
+ )
348
+ if existing_episode:
349
+ existing_episode.setdefault("telegram", [])
350
+ for quality in episode["telegram"]:
351
+ existing_quality = next(
352
+ (q for q in existing_episode["telegram"]
353
+ if q.get("quality") == quality.get("quality")),
354
+ None
355
+ )
356
+ if existing_quality:
357
+ try:
358
+ old_id = existing_quality.get("id")
359
+
360
+ if old_id:
361
+ decoded_data = await decode_string(old_id)
362
+
363
+ chat_id = int(f"-100{decoded_data['chat_id']}")
364
+ msg_id = int(decoded_data['msg_id'])
365
+ create_task(delete_message(chat_id, msg_id))
366
+
367
+ except Exception as e:
368
+ LOGGER.error(f"Failed to queue old quality file for deletion: {e}")
369
+ existing_quality.update(quality)
370
+ else:
371
+ existing_episode["telegram"].append(quality)
372
+ else:
373
+ existing_season["episodes"].append(episode)
374
+ else:
375
+ existing_tv["seasons"].append(season)
376
+ existing_tv["updated_on"] = datetime.utcnow()
377
+
378
+ if existing_db_index != self.current_db_index:
379
+ try:
380
+ if await self._move_document("tv", existing_tv, existing_db_index):
381
+ return tv_id
382
+ except Exception as e:
383
+ LOGGER.error(f"Error moving TV show to {current_db_key}: {e}")
384
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
385
+ return await self._handle_storage_error(self.update_tv_show, tv_show_data, total_storage_dbs=total_storage_dbs)
386
+ return tv_id
387
+
388
+ try:
389
+ await self.dbs[existing_db_key]["tv"].replace_one({"_id": tv_id}, existing_tv)
390
+ return tv_id
391
+ except Exception as e:
392
+ LOGGER.error(f"Failed to update TV show {tmdb_id} in {existing_db_key}: {e}")
393
+ if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
394
+ return await self._handle_storage_error(self.update_tv_show, tv_show_data, total_storage_dbs=total_storage_dbs)
395
+
396
+ async def sort_tv_shows(
397
+ self, sort_params: List[Tuple[str, str]], page: int, page_size: int
398
+ ) -> dict:
399
+ sort_dict = self._get_sort_dict(sort_params)
400
+ results, dbs_checked, total_count = await self._paginate_collection("tv", sort_dict, page, page_size)
401
+ total_pages = (total_count + page_size - 1) // page_size
402
+
403
+ return {
404
+ "total_count": total_count,
405
+ "total_pages": total_pages,
406
+ "databases_checked": dbs_checked,
407
+ "current_page": page,
408
+ "tv_shows": [convert_objectid_to_str(result) for result in results]
409
+ }
410
+
411
+ async def sort_movies(
412
+ self, sort_params: List[Tuple[str, str]], page: int, page_size: int
413
+ ) -> dict:
414
+ sort_dict = self._get_sort_dict(sort_params)
415
+ results, dbs_checked, total_count = await self._paginate_collection("movie", sort_dict, page, page_size)
416
+ total_pages = (total_count + page_size - 1) // page_size
417
+
418
+ return {
419
+ "total_count": total_count,
420
+ "total_pages": total_pages,
421
+ "databases_checked": dbs_checked,
422
+ "current_page": page,
423
+ "movies": [convert_objectid_to_str(result) for result in results]
424
+ }
425
+
426
+
427
+
428
+ async def search_documents(
429
+ self,
430
+ query: str,
431
+ page: int,
432
+ page_size: int
433
+ ) -> dict:
434
+
435
+ skip = (page - 1) * page_size
436
+
437
+ words = query.split()
438
+ regex_query = {
439
+ '$regex': '.*' + '.*'.join(words) + '.*',
440
+ '$options': 'i'
441
+ }
442
+
443
+ tv_pipeline = [
444
+ {"$match": {"$or": [
445
+ {"title": regex_query},
446
+ {"seasons.episodes.telegram.name": regex_query}
447
+ ]}},
448
+ {"$project": {
449
+ "_id": 1, "tmdb_id": 1, "title": 1, "genres": 1, "rating": 1, "imdb_id": 1,
450
+ "release_year": 1, "poster": 1, "backdrop": 1, "description": 1, "logo": 1,
451
+ "media_type": 1, "db_index": 1
452
+ }}
453
+ ]
454
+
455
+ movie_pipeline = [
456
+ {"$match": {"$or": [
457
+ {"title": regex_query},
458
+ {"telegram.name": regex_query}
459
+ ]}},
460
+ {"$project": {
461
+ "_id": 1, "tmdb_id": 1, "title": 1, "genres": 1, "rating": 1,
462
+ "release_year": 1, "poster": 1, "backdrop": 1, "description": 1,
463
+ "media_type": 1, "db_index": 1, "imdb_id": 1, "logo": 1
464
+ }}
465
+ ]
466
+
467
+ results = []
468
+ dbs_checked = []
469
+
470
+ active_db_key = f"storage_{self.current_db_index}"
471
+ active_db = self.dbs[active_db_key]
472
+ dbs_checked.append(self.current_db_index)
473
+
474
+ tv_results = await active_db["tv"].aggregate(tv_pipeline).to_list(None)
475
+ movie_results = await active_db["movie"].aggregate(movie_pipeline).to_list(None)
476
+ combined = tv_results + movie_results
477
+ results.extend(combined)
478
+
479
+ if len(results) < page_size:
480
+ previous_db_index = self.current_db_index - 1
481
+ while previous_db_index > 0 and len(results) < page_size:
482
+ prev_db_key = f"storage_{previous_db_index}"
483
+ prev_db = self.dbs[prev_db_key]
484
+ tv_results_prev = await prev_db["tv"].aggregate(tv_pipeline).to_list(None)
485
+ movie_results_prev = await prev_db["movie"].aggregate(movie_pipeline).to_list(None)
486
+ combined_prev = tv_results_prev + movie_results_prev
487
+ results.extend(combined_prev)
488
+ dbs_checked.append(previous_db_index)
489
+ previous_db_index -= 1
490
+
491
+ total_count = 0
492
+ for db_index in dbs_checked:
493
+ key = f"storage_{db_index}"
494
+ db = self.dbs[key]
495
+ tv_count = await db["tv"].count_documents({
496
+ "$or": [
497
+ {"title": regex_query},
498
+ {"seasons.episodes.telegram.name": regex_query}
499
+ ]
500
+ })
501
+ movie_count = await db["movie"].count_documents({
502
+ "$or": [
503
+ {"title": regex_query},
504
+ {"telegram.name": regex_query}
505
+ ]
506
+ })
507
+ total_count += (tv_count + movie_count)
508
+
509
+ paged_results = results[skip:skip + page_size]
510
+
511
+ return {
512
+ "total_count": total_count,
513
+ "results": [convert_objectid_to_str(doc) for doc in paged_results]
514
+ }
515
+
516
+
517
+ async def get_media_details(
518
+ self, tmdb_id: int, db_index: int,
519
+ season_number: Optional[int] = None, episode_number: Optional[int] = None
520
+ ) -> Optional[dict]:
521
+ db_key = f"storage_{db_index}"
522
+ if episode_number is not None and season_number is not None:
523
+ tv_show = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
524
+ if not tv_show:
525
+ return None
526
+ for season in tv_show.get("seasons", []):
527
+ if season.get("season_number") == season_number:
528
+ for episode in season.get("episodes", []):
529
+ if episode.get("episode_number") == episode_number:
530
+ details = convert_objectid_to_str(episode)
531
+ details.update({
532
+ "tmdb_id": tmdb_id,
533
+ "type": "tv",
534
+ "season_number": season_number,
535
+ "episode_number": episode_number,
536
+ "backdrop": episode.get("episode_backdrop")
537
+ })
538
+ return details
539
+ return None
540
+
541
+ elif season_number is not None:
542
+ tv_show = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
543
+ if not tv_show:
544
+ return None
545
+ for season in tv_show.get("seasons", []):
546
+ if season.get("season_number") == season_number:
547
+ details = convert_objectid_to_str(season)
548
+ details.update({
549
+ "tmdb_id": tmdb_id,
550
+ "type": "tv",
551
+ "season_number": season_number
552
+ })
553
+ return details
554
+ return None
555
+
556
+ else:
557
+ tv_doc = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
558
+ if tv_doc:
559
+ tv_doc = convert_objectid_to_str(tv_doc)
560
+ tv_doc["type"] = "tv"
561
+ return tv_doc
562
+ movie_doc = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
563
+ if movie_doc:
564
+ movie_doc = convert_objectid_to_str(movie_doc)
565
+ movie_doc["type"] = "movie"
566
+ return movie_doc
567
+ return None
568
+
569
+
570
+
571
+
572
+
573
+ # -------------------------------
574
+ # DB Method for Edit Post
575
+ # -------------------------------
576
+
577
+
578
+ async def get_document(self, media_type: str, tmdb_id: int, db_index: int) -> Optional[Dict[str, Any]]:
579
+ db_key = f"storage_{db_index}"
580
+ if media_type.lower() in ["tv", "series"]:
581
+ collection_name = "tv"
582
+ else:
583
+ collection_name = "movie"
584
+ document = await self.dbs[db_key][collection_name].find_one({"tmdb_id": int(tmdb_id)})
585
+ return convert_objectid_to_str(document) if document else None
586
+
587
+ async def update_document(
588
+ self, media_type: str, tmdb_id: int, db_index: int, update_data: Dict[str, Any]
589
+ ):
590
+ update_data.pop('_id', None)
591
+ db_key = f"storage_{db_index}"
592
+ if media_type.lower() in ["tv", "series"]:
593
+ collection_name = "tv"
594
+ else:
595
+ collection_name = "movie"
596
+ collection = self.dbs[db_key][collection_name]
597
+
598
+ try:
599
+ result = await collection.update_one({"tmdb_id": int(tmdb_id)}, {"$set": update_data})
600
+
601
+ return result.modified_count > 0
602
+
603
+ except Exception as e:
604
+ err_str = str(e).lower()
605
+ LOGGER.error(f"Error updating document in {db_key}: {e}")
606
+ if "storage" in err_str or "quota" in err_str:
607
+ total_storage_dbs = len(self.dbs) - 1
608
+ db_index_int = int(db_index)
609
+ next_db_index = (db_index_int % total_storage_dbs) + 1
610
+ if next_db_index == 1:
611
+ LOGGER.warning("⚠️ All storage databases are full! Add more.")
612
+ return False
613
+
614
+ new_db_key = f"storage_{next_db_index}"
615
+ LOGGER.info(f"Switching from {db_key} to {new_db_key} due to storage error.")
616
+
617
+ try:
618
+ old_doc = await self.dbs[db_key][collection_name].find_one({"tmdb_id": int(tmdb_id)})
619
+ if not old_doc:
620
+ LOGGER.error(f"Document with tmdb_id {tmdb_id} not found in {db_key} during migration.")
621
+ return False
622
+
623
+ old_doc.update(update_data)
624
+ old_doc["db_index"] = next_db_index
625
+ old_doc.pop("_id", None)
626
+ insert_result = await self.dbs[new_db_key][collection_name].insert_one(old_doc)
627
+ LOGGER.info(f"Inserted document {insert_result.inserted_id} into {new_db_key}")
628
+ await self.dbs[db_key][collection_name].delete_one({"tmdb_id": int(tmdb_id)})
629
+ LOGGER.info(f"Deleted document tmdb_id {tmdb_id} from {db_key}")
630
+ self.current_db_index = next_db_index
631
+ await self.update_current_db_index()
632
+ LOGGER.info(f"Switched to {new_db_key} and document migrated successfully.")
633
+ return True
634
+
635
+ except Exception as migrate_error:
636
+ LOGGER.error(f"Error migrating document tmdb_id {tmdb_id} to {new_db_key}: {migrate_error}")
637
+ return False
638
+ raise
639
+
640
+ # Delete a Movie or Tvshow completely
641
+ async def delete_document(self, media_type: str, tmdb_id: int, db_index: int) -> bool:
642
+ db_key = f"storage_{db_index}"
643
+ if media_type == "Movie":
644
+ result = await self.dbs[db_key]["movie"].delete_one({"tmdb_id": tmdb_id})
645
+ else:
646
+ result = await self.dbs[db_key]["tv"].delete_one({"tmdb_id": tmdb_id})
647
+ if result.deleted_count > 0:
648
+ LOGGER.info(f"{media_type} with tmdb_id {tmdb_id} deleted successfully.")
649
+ return True
650
+ LOGGER.info(f"No document found with tmdb_id {tmdb_id}.")
651
+ return False
652
+
653
+
654
+ # Delete a specific quality from movie
655
+ async def delete_movie_quality(self, tmdb_id: int, db_index: int, quality: str) -> bool:
656
+ db_key = f"storage_{db_index}"
657
+ movie = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
658
+ if not movie or "telegram" not in movie:
659
+ return False
660
+ original_len = len(movie["telegram"])
661
+ movie["telegram"] = [q for q in movie["telegram"] if q.get("quality") != quality]
662
+ if len(movie["telegram"]) == original_len:
663
+ return False
664
+ movie['updated_on'] = datetime.utcnow()
665
+ result = await self.dbs[db_key]["movie"].replace_one({"tmdb_id": tmdb_id}, movie)
666
+ return result.modified_count > 0
667
+
668
+ # Delete a specific episode from a TV show
669
+ async def delete_tv_episode(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int) -> bool:
670
+ db_key = f"storage_{db_index}"
671
+ tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
672
+ if not tv or "seasons" not in tv:
673
+ return False
674
+ found = False
675
+ for season in tv["seasons"]:
676
+ if season.get("season_number") == season_number:
677
+ original_len = len(season["episodes"])
678
+ season["episodes"] = [ep for ep in season["episodes"] if ep.get("episode_number") != episode_number]
679
+ found = original_len > len(season["episodes"])
680
+ break
681
+ if not found:
682
+ return False
683
+ tv['updated_on'] = datetime.utcnow()
684
+ result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
685
+ return result.modified_count > 0
686
+
687
+ # Delete a whole season from a TV show
688
+ async def delete_tv_season(self, tmdb_id: int, db_index: int, season_number: int) -> bool:
689
+ db_key = f"storage_{db_index}"
690
+ tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
691
+ if not tv or "seasons" not in tv:
692
+ return False
693
+ original_len = len(tv["seasons"])
694
+ tv["seasons"] = [s for s in tv["seasons"] if s.get("season_number") != season_number]
695
+ if len(tv["seasons"]) == original_len:
696
+ return False
697
+ tv['updated_on'] = datetime.utcnow()
698
+ result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
699
+ return result.modified_count > 0
700
+
701
+ # Delete a specific quality from a given TV episode
702
+ async def delete_tv_quality(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int, quality: str) -> bool:
703
+ db_key = f"storage_{db_index}"
704
+ tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
705
+ if not tv or "seasons" not in tv:
706
+ return False
707
+ found = False
708
+ for season in tv["seasons"]:
709
+ if season.get("season_number") == season_number:
710
+ for episode in season["episodes"]:
711
+ if episode.get("episode_number") == episode_number and "telegram" in episode:
712
+ original_len = len(episode["telegram"])
713
+ episode["telegram"] = [q for q in episode["telegram"] if q.get("quality") != quality]
714
+ found = original_len > len(episode["telegram"])
715
+ break
716
+ if not found:
717
+ return False
718
+ tv['updated_on'] = datetime.utcnow()
719
+ result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
720
+ return result.modified_count > 0
721
+
722
+ # Get per-DB statistics (movies, tv shows, used size, etc.)
723
+ async def get_database_stats(self):
724
+ stats = []
725
+ for key in self.dbs.keys():
726
+ if key.startswith("storage_"):
727
+ db = self.dbs[key]
728
+ movie_count = await db["movie"].count_documents({})
729
+ tv_count = await db["tv"].count_documents({})
730
+ db_stats = await db.command("dbstats")
731
+ stats.append({
732
+ "db_name": key,
733
+ "movie_count": movie_count,
734
+ "tv_count": tv_count,
735
+ "storageSize": db_stats.get("storageSize", 0),
736
+ "dataSize": db_stats.get("dataSize", 0)
737
+ })
738
+ return stats
Backend/helper/encrypt.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zlib
2
+ import json
3
+ import asyncio
4
+ from concurrent.futures import ThreadPoolExecutor
5
+
6
+ executor = ThreadPoolExecutor()
7
+
8
+ def compress_data(data):
9
+ return zlib.compress(data.encode(), level=zlib.Z_BEST_COMPRESSION)
10
+
11
+ def decompress_data(data):
12
+ return zlib.decompress(data).decode()
13
+
14
+ def base62_encode(data):
15
+ BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
16
+ num = int.from_bytes(data, 'big')
17
+ base62 = []
18
+ while num:
19
+ num, rem = divmod(num, 62)
20
+ base62.append(BASE62_ALPHABET[rem])
21
+ return ''.join(reversed(base62)) or '0'
22
+
23
+ def base62_decode(data):
24
+ BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
25
+ num = 0
26
+ for char in data:
27
+ num = num * 62 + BASE62_ALPHABET.index(char)
28
+ return num.to_bytes((num.bit_length() + 7) // 8, 'big') or b'\0'
29
+
30
+ async def async_compress_data(data):
31
+ loop = asyncio.get_running_loop()
32
+ return await loop.run_in_executor(executor, compress_data, data)
33
+
34
+ async def async_decompress_data(data):
35
+ loop = asyncio.get_running_loop()
36
+ return await loop.run_in_executor(executor, decompress_data, data)
37
+
38
+ async def async_base62_encode(data):
39
+ loop = asyncio.get_running_loop()
40
+ return await loop.run_in_executor(executor, base62_encode, data)
41
+
42
+ async def async_base62_decode(data):
43
+ loop = asyncio.get_running_loop()
44
+ return await loop.run_in_executor(executor, base62_decode, data)
45
+
46
+ async def encode_string(data):
47
+ json_data = json.dumps(data)
48
+ compressed_data = await async_compress_data(json_data)
49
+ return await async_base62_encode(compressed_data)
50
+
51
+ async def decode_string(encoded_data):
52
+ compressed_data = await async_base62_decode(encoded_data)
53
+ json_data = await async_decompress_data(compressed_data)
54
+ return json.loads(json_data)
Backend/helper/exceptions.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ class InvalidHash(Exception):
2
+ message = 'Invalid hash!'
3
+
4
+
5
+ class FIleNotFound(Exception):
6
+ message = 'File not found!'
Backend/helper/imdb.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ import re
3
+ from typing import Optional, Dict, Any
4
+
5
+ BASE_URL = "https://v3-cinemeta.strem.io"
6
+
7
+ def extract_first_year(year_string) -> int:
8
+ if not year_string:
9
+ return 0
10
+ year_str = str(year_string)
11
+ year_match = re.search(r'(\d{4})', year_str)
12
+ if year_match:
13
+ return int(year_match.group(1))
14
+ return 0
15
+
16
+
17
+ async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
18
+ async with httpx.AsyncClient() as client:
19
+ cinemeta_type = "series" if type == "tvSeries" else type
20
+ url = f"{BASE_URL}/catalog/{cinemeta_type}/imdb/search={query}.json"
21
+ try:
22
+ response = await client.get(url, timeout=10.0)
23
+ if response.status_code != 200:
24
+ return None
25
+ data = response.json()
26
+
27
+ if data and 'metas' in data and data['metas']:
28
+ meta = data['metas'][0]
29
+ return {
30
+ 'id': meta.get('imdb_id', meta.get('id', '')),
31
+ 'type': type,
32
+ 'title': meta.get('name', ''),
33
+ 'year': meta.get('releaseInfo', ''),
34
+ 'poster': meta.get('poster', '')
35
+ }
36
+
37
+ return None
38
+ except Exception:
39
+ return None
40
+
41
+ async def get_detail(imdb_id: str) -> Optional[Dict[str, Any]]:
42
+ async with httpx.AsyncClient() as client:
43
+ for media_type in ['movie', 'series']:
44
+ try:
45
+ url = f"{BASE_URL}/meta/{media_type}/{imdb_id}.json"
46
+ response = await client.get(url, timeout=10.0)
47
+ if response.status_code == 200:
48
+ data = response.json()
49
+ if 'meta' in data:
50
+ meta = data['meta']
51
+ year_value = 0
52
+ for year_field in ['year', 'releaseInfo', 'released']:
53
+ if meta.get(year_field):
54
+ year_value = extract_first_year(meta[year_field])
55
+ if year_value > 0:
56
+ break
57
+ return {
58
+ 'id': meta.get('imdb_id', meta.get('id', '')),
59
+ 'type': meta.get('type', media_type),
60
+ 'title': meta.get('name', ''),
61
+ 'plot': meta.get('description', ''),
62
+ 'genre': meta.get('genres', []) or meta.get('genre', []),
63
+ 'releaseDetailed': {
64
+ 'year': year_value
65
+ },
66
+ 'rating': {
67
+ 'star': float(meta.get('imdbRating', '0')) if meta.get('imdbRating') else 0
68
+ },
69
+ 'poster': meta.get('poster', ''),
70
+ 'background': meta.get('background', ''),
71
+ 'logo': meta.get('logo', ''),
72
+ 'runtime': meta.get('runtime', ''),
73
+ 'director': meta.get('director', []),
74
+ 'cast': meta.get('cast', []),
75
+ 'videos': meta.get('videos', [])
76
+ }
77
+
78
+ except Exception:
79
+ continue
80
+ return None
81
+
82
+ async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
83
+ async with httpx.AsyncClient() as client:
84
+ try:
85
+ url = f"{BASE_URL}/meta/series/{imdb_id}.json"
86
+ response = await client.get(url, timeout=10.0)
87
+ if response.status_code != 200:
88
+ return None
89
+ data = response.json()
90
+
91
+ if 'meta' in data and 'videos' in data['meta']:
92
+ for video in data['meta']['videos']:
93
+ if (str(video.get('season', '')) == str(season_id) and
94
+ str(video.get('episode', '')) == str(episode_id)):
95
+ return {
96
+ 'title': video.get('title', f'Episode {episode_id}'),
97
+ 'no': str(episode_id),
98
+ 'season': str(season_id),
99
+ 'image': video.get('thumbnail', ''),
100
+ 'plot': video.get('overview', ''),
101
+ 'released': video.get('released', '')
102
+ }
103
+
104
+ return None
105
+ except Exception:
106
+ return None
Backend/helper/metadata.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import traceback
3
+ import PTN
4
+
5
+ from Backend.helper.imdb import get_detail, get_season, search_title
6
+ from Backend.helper.pyro import extract_tmdb_id
7
+ from themoviedb import aioTMDb
8
+ from Backend.config import Telegram
9
+ import Backend
10
+ from Backend.logger import LOGGER
11
+ from Backend.helper.encrypt import encode_string
12
+
13
+ DELAY = 2
14
+ tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
15
+
16
+
17
+ # ----------------- Helpers -----------------
18
+ def format_tmdb_image(path: str, size="w500", fallback="https://i.ibb.co/mrfTVzyW/Screenshot-20251006-232731.png") -> str:
19
+ return f"https://image.tmdb.org/t/p/{size}{path}" if path else fallback
20
+
21
+
22
+ def format_imdb_images(imdb_id: str) -> dict:
23
+ return {
24
+ "poster": f"https://images.metahub.space/poster/small/{imdb_id}/img",
25
+ "backdrop": f"https://images.metahub.space/background/medium/{imdb_id}/img",
26
+ "logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
27
+ }
28
+
29
+
30
+ async def safe_imdb_search(title: str, type_: str) -> str | None:
31
+ try:
32
+ result = await search_title(query=title, type=type_)
33
+ return result["id"] if result else None
34
+ except Exception as e:
35
+ LOGGER.warning(f"IMDb search failed for '{title}' [{type_}]: {e}")
36
+ return None
37
+
38
+
39
+ async def safe_tmdb_search(title: str, type_: str, year=None):
40
+ try:
41
+ if type_ == "movie":
42
+ results = await tmdb.search().movies(query=title, year=year) if year else await tmdb.search().movies(query=title)
43
+ else:
44
+ results = await tmdb.search().tv(query=title)
45
+ return results[0] if results else None
46
+ except Exception as e:
47
+ LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
48
+ return None
49
+
50
+
51
+ # ----------------- Main -----------------
52
+ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
53
+ try:
54
+ parsed = PTN.parse(filename)
55
+ except Exception as e:
56
+ LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
57
+ return None
58
+
59
+ # Skip combined/invalid files
60
+ if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
61
+ LOGGER.info(f"Skipping {filename}: contains 'combined'")
62
+ return None
63
+
64
+ title, season, episode, year, quality = (
65
+ parsed.get("title"),
66
+ parsed.get("season"),
67
+ parsed.get("episode"),
68
+ parsed.get("year"),
69
+ parsed.get("resolution"),
70
+ )
71
+
72
+ if not quality:
73
+ LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
74
+ return None
75
+ if isinstance(season, list) or isinstance(episode, list):
76
+ LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
77
+ return None
78
+ if season and not episode:
79
+ LOGGER.warning(f"Missing episode in {filename}: {parsed}")
80
+ return None
81
+
82
+ # Extract TMDb ID hints
83
+ default_id = None
84
+ try:
85
+ default_id = extract_tmdb_id(Backend.USE_DEFAULT_ID)
86
+ except Exception:
87
+ pass
88
+ if not default_id:
89
+ try:
90
+ default_id = extract_tmdb_id(filename)
91
+ except Exception:
92
+ pass
93
+
94
+ if not title:
95
+ LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
96
+ return None
97
+
98
+ data = {"chat_id": channel, "msg_id": msg_id}
99
+ encoded_string = await encode_string(data)
100
+
101
+
102
+ try:
103
+ if season and episode:
104
+ LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
105
+ return await fetch_tv_metadata(title, season, episode, encoded_string, year, quality, default_id)
106
+ else:
107
+ LOGGER.info(f"Fetching Movie metadata: {title} ({year})")
108
+ return await fetch_movie_metadata(title, encoded_string, year, quality, default_id)
109
+ except Exception as e:
110
+ LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
111
+ return None
112
+
113
+
114
+ # ----------------- TV -----------------
115
+ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
116
+ imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(title, "tvSeries")
117
+ tv_details, ep_details, use_tmdb = None, None, False
118
+
119
+ if imdb_id:
120
+ try:
121
+ await asyncio.sleep(DELAY)
122
+ tv_details = await get_detail(imdb_id=imdb_id)
123
+ await asyncio.sleep(DELAY)
124
+ ep_details = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
125
+ except Exception as e:
126
+ LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
127
+
128
+ if not tv_details and not ep_details:
129
+ use_tmdb = True
130
+ tmdb_result = await safe_tmdb_search(title, "tv")
131
+ if not tmdb_result:
132
+ return None
133
+ tv_id = tmdb_result.id
134
+ tv_details = await tmdb.tv(tv_id).details()
135
+ ep_details = await tmdb.episode(tv_id, season, episode).details()
136
+
137
+ if use_tmdb:
138
+ return {
139
+ "tmdb_id": tv_details.id,
140
+ "imdb_id": "",
141
+ "title": tv_details.name,
142
+ "year": tv_details.first_air_date.year if tv_details.first_air_date else 0,
143
+ "rate": tv_details.vote_average or 0,
144
+ "description": tv_details.overview or "",
145
+ "poster": format_tmdb_image(tv_details.poster_path),
146
+ "backdrop": format_tmdb_image(tv_details.backdrop_path, "original"),
147
+ "logo": "",
148
+ "genres": [g.name for g in (tv_details.genres or [])],
149
+ "media_type": "tv",
150
+ "season_number": season,
151
+ "episode_number": episode,
152
+ "episode_title": getattr(ep_details, "name", f"S{season}E{episode}"),
153
+ "episode_backdrop": format_tmdb_image(getattr(ep_details, "still_path", None), "original"),
154
+ "quality": quality,
155
+ "encoded_string": encoded_string,
156
+ }
157
+
158
+ imdb_id = tv_details.get("id", "")
159
+ images = format_imdb_images(imdb_id)
160
+ return {
161
+ "tmdb_id": imdb_id.replace("tt", ""),
162
+ "imdb_id": imdb_id,
163
+ "title": tv_details.get("title", title),
164
+ "year": tv_details.get("releaseDetailed", {}).get("year", 0),
165
+ "rate": tv_details.get("rating", {}).get("star", 0),
166
+ "description": tv_details.get("plot", ""),
167
+ "poster": images["poster"],
168
+ "backdrop": images["backdrop"],
169
+ "logo": images["logo"],
170
+ "genres": tv_details.get("genre", []),
171
+ "media_type": "tv",
172
+ "season_number": season,
173
+ "episode_number": episode,
174
+ "episode_title": ep_details.get("title", f"S{season}E{episode}") if ep_details else f"S{season}E{episode}",
175
+ "episode_backdrop": ep_details.get("image", "") if ep_details else "https://i.ibb.co/mrfTVzyW/Screenshot-20251006-232731.png",
176
+ "quality": quality,
177
+ "encoded_string": encoded_string,
178
+ }
179
+
180
+
181
+ # ----------------- Movie -----------------
182
+ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
183
+ imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(f"{title} {year}" if year else title, "movie")
184
+ movie_details, use_tmdb = None, False
185
+
186
+ if imdb_id:
187
+ try:
188
+ movie_details = await get_detail(imdb_id=imdb_id)
189
+ except Exception as e:
190
+ LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
191
+
192
+ if not movie_details:
193
+ use_tmdb = True
194
+ tmdb_result = await safe_tmdb_search(title, "movie", year)
195
+ if not tmdb_result:
196
+ return None
197
+ movie_details = await tmdb.movie(tmdb_result.id).details()
198
+
199
+ if use_tmdb:
200
+ return {
201
+ "tmdb_id": movie_details.id,
202
+ "imdb_id": "",
203
+ "title": movie_details.title,
204
+ "year": movie_details.release_date.year if movie_details.release_date else 0,
205
+ "rate": movie_details.vote_average or 0,
206
+ "description": movie_details.overview or "",
207
+ "poster": format_tmdb_image(movie_details.poster_path),
208
+ "backdrop": format_tmdb_image(movie_details.backdrop_path, "original"),
209
+ "logo": "",
210
+ "media_type": "movie",
211
+ "genres": [g.name for g in (movie_details.genres or [])],
212
+ "quality": quality,
213
+ "encoded_string": encoded_string,
214
+ }
215
+
216
+ imdb_id = movie_details.get("id", "")
217
+ images = format_imdb_images(imdb_id)
218
+ return {
219
+ "tmdb_id": imdb_id.replace("tt", ""),
220
+ "imdb_id": imdb_id,
221
+ "title": movie_details.get("title", title),
222
+ "year": movie_details.get("releaseDetailed", {}).get("year", 0),
223
+ "rate": movie_details.get("rating", {}).get("star", 0),
224
+ "description": movie_details.get("plot", ""),
225
+ "poster": images["poster"],
226
+ "backdrop": images["backdrop"],
227
+ "logo": images["logo"],
228
+ "media_type": "movie",
229
+ "genres": movie_details.get("genre", []),
230
+ "quality": quality,
231
+ "encoded_string": encoded_string,
232
+ }
Backend/helper/modal.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import List, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+ class QualityDetail(BaseModel):
6
+ quality: str
7
+ id: str
8
+ name: str
9
+ size: str
10
+
11
+ class Episode(BaseModel):
12
+ episode_number: int
13
+ title: str
14
+ episode_backdrop: Optional[str] = None
15
+ telegram: Optional[List[QualityDetail]]
16
+
17
+ class Season(BaseModel):
18
+ season_number: int
19
+ episodes: List[Episode]
20
+
21
+ class TVShowSchema(BaseModel):
22
+ tmdb_id: int
23
+ imdb_id: Optional[str] = None
24
+ db_index: int
25
+ title: str
26
+ genres: List[str]
27
+ description: Optional[str] = None
28
+ rating: float
29
+ release_year: int
30
+ poster: Optional[str] = None
31
+ backdrop: Optional[str] = None
32
+ logo: Optional[str] = None
33
+ media_type: str
34
+ updated_on: datetime = Field(default_factory=datetime.utcnow)
35
+ seasons: List[Season]
36
+
37
+ class MovieSchema(BaseModel):
38
+ tmdb_id: int
39
+ imdb_id: Optional[str] = None
40
+ db_index: int
41
+ title: str
42
+ genres: List[str]
43
+ description: Optional[str] = None
44
+ rating: float
45
+ release_year: int
46
+ poster: Optional[str] = None
47
+ backdrop: Optional[str] = None
48
+ logo: Optional[str] = None
49
+ media_type: str
50
+ updated_on: datetime = Field(default_factory=datetime.utcnow)
51
+ telegram: Optional[List[QualityDetail]]
Backend/helper/pyro.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
9
+ from pyrogram import Client
10
+ from Backend.pyrofork.bot import StreamBot
11
+ import re
12
+ from pyrogram.types import BotCommand
13
+ from pyrogram import enums
14
+
15
+
16
+ def is_media(message):
17
+ return next((getattr(message, attr) for attr in ["document", "photo", "video", "audio", "voice", "video_note", "sticker", "animation"] if getattr(message, attr)), None)
18
+
19
+
20
+ async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optional[FileId]:
21
+ try:
22
+ message = await client.get_messages(chat_id, message_id)
23
+ if message.empty:
24
+ raise FIleNotFound("Message not found or empty")
25
+
26
+ if media := is_media(message):
27
+ file_id_obj = FileId.decode(media.file_id)
28
+ file_unique_id = media.file_unique_id
29
+
30
+ setattr(file_id_obj, 'file_name', getattr(media, 'file_name', ''))
31
+ setattr(file_id_obj, 'file_size', getattr(media, 'file_size', 0))
32
+ setattr(file_id_obj, 'mime_type', getattr(media, 'mime_type', ''))
33
+ setattr(file_id_obj, 'unique_id', file_unique_id)
34
+
35
+ return file_id_obj
36
+ else:
37
+ raise FIleNotFound("No supported media found in message")
38
+ except Exception as e:
39
+ LOGGER.error(f"Error getting file IDs: {e}")
40
+ raise
41
+
42
+
43
+
44
+ def get_readable_file_size(size_in_bytes):
45
+ size_in_bytes = int(size_in_bytes) if str(size_in_bytes).isdigit() else 0
46
+ if not size_in_bytes:
47
+ return '0B'
48
+
49
+ index, SIZE_UNITS = 0, ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
50
+ while size_in_bytes >= 1024 and index < len(SIZE_UNITS) - 1:
51
+ size_in_bytes /= 1024
52
+ index += 1
53
+
54
+ return f'{size_in_bytes:.2f}{SIZE_UNITS[index]}' if index > 0 else f'{size_in_bytes:.0f}B'
55
+
56
+
57
+ def clean_filename(filename):
58
+ if not filename:
59
+ return "unknown_file"
60
+
61
+ pattern = r'_@[A-Za-z]+_|@[A-Za-z]+_|[\[\]\s@]*@[^.\s\[\]]+[\]\[\s@]*'
62
+ cleaned_filename = re.sub(pattern, '', filename)
63
+
64
+ cleaned_filename = re.sub(
65
+ r'(?<=\W)(org|AMZN|DDP|DD|NF|AAC|TVDL|5\.1|2\.1|2\.0|7\.0|7\.1|5\.0|~|\b\w+kbps\b)(?=\W)',
66
+ ' ', cleaned_filename, flags=re.IGNORECASE
67
+ )
68
+
69
+ cleaned_filename = re.sub(r'\s+', ' ', cleaned_filename).strip().replace(' .', '.')
70
+
71
+ return cleaned_filename if cleaned_filename else "unknown_file"
72
+
73
+
74
+ def get_readable_time(seconds: int) -> str:
75
+ count = 0
76
+ readable_time = ""
77
+ time_list = []
78
+ time_suffix_list = ["s", "m", "h", " days"]
79
+
80
+ while count < 4:
81
+ count += 1
82
+ if count < 3:
83
+ remainder, result = divmod(seconds, 60)
84
+ else:
85
+ remainder, result = divmod(seconds, 24)
86
+
87
+ if seconds == 0 and remainder == 0:
88
+ break
89
+
90
+ time_list.append(int(result))
91
+ seconds = int(remainder)
92
+
93
+ for x in range(len(time_list)):
94
+ time_list[x] = str(time_list[x]) + time_suffix_list[x]
95
+
96
+ if len(time_list) == 4:
97
+ readable_time += time_list.pop() + ", "
98
+
99
+ time_list.reverse()
100
+ readable_time += ": ".join(time_list)
101
+
102
+ return readable_time
103
+
104
+
105
+ def extract_tmdb_id(url):
106
+ # Match IMDb URLs
107
+ imdb_match = re.search(r'/title/(tt\d+)', url)
108
+ if imdb_match:
109
+ return imdb_match.group(1)
110
+
111
+ return None
112
+
113
+
114
+ def remove_urls(text):
115
+ if not text:
116
+ return ""
117
+
118
+ url_pattern = r'\b(?:https?|ftp):\/\/[^\s/$.?#].[^\s]*'
119
+ text_without_urls = re.sub(url_pattern, '', text)
120
+ cleaned_text = re.sub(r'\s+', ' ', text_without_urls).strip()
121
+
122
+ return cleaned_text
123
+
124
+
125
+
126
+ async def restart_notification():
127
+ chat_id, msg_id = 0, 0
128
+ try:
129
+ if await aiopath.exists(".restartmsg"):
130
+ async with aiopen(".restartmsg", "r") as f:
131
+ data = await f.readlines()
132
+ chat_id, msg_id = map(int, data)
133
+
134
+ try:
135
+ repo = Telegram.UPSTREAM_REPO.split('/')
136
+ UPSTREAM_REPO = f"https://github.com/{repo[-2]}/{repo[-1]}"
137
+ await StreamBot.edit_message_text(
138
+ chat_id=chat_id,
139
+ message_id=msg_id,
140
+ text=f"... ♻️ Restart Successfully...! \n\nDate: {now.strftime('%d/%m/%y')}\nTime: {now.strftime('%I:%M:%S %p')}\nTimeZone: {timezone.zone}\n\nRepo: {UPSTREAM_REPO}\nBranch: {Telegram.UPSTREAM_BRANCH}\nVersion: {__version__}",
141
+ parse_mode=enums.ParseMode.HTML
142
+ )
143
+ except Exception as e:
144
+ LOGGER.error(f"Failed to edit restart message: {e}")
145
+
146
+ await aioremove(".restartmsg")
147
+
148
+ except Exception as e:
149
+ LOGGER.error(f"Error in restart_notification: {e}")
150
+
151
+
152
+ # Bot commands
153
+ commands = [
154
+ BotCommand("start", "🚀 Start the bot"),
155
+ BotCommand("set", "🎬 Manually add IMDb metadata"),
156
+ BotCommand("log", "📄 Send the log file"),
157
+ BotCommand("restart", "♻️ Restart the bot"),
158
+ ]
159
+
160
+
161
+ async def setup_bot_commands(bot: Client):
162
+ try:
163
+ current_commands = await bot.get_bot_commands()
164
+ if current_commands:
165
+ LOGGER.info(f"Found {len(current_commands)} existing commands. Deleting them...")
166
+ await bot.set_bot_commands([])
167
+
168
+ await bot.set_bot_commands(commands)
169
+ LOGGER.info("Bot commands updated successfully.")
170
+ except Exception as e:
171
+ LOGGER.error(f"Error setting up bot commands: {e}")
172
+
Backend/helper/task_manager.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import sleep
2
+ from pyrogram.errors import FloodWait
3
+ from Backend.logger import LOGGER
4
+ from Backend.pyrofork.bot import Helper
5
+
6
+ async def edit_message(chat_id: int, msg_id: int, new_caption: str):
7
+ try:
8
+ await Helper.edit_message_caption(
9
+ chat_id=chat_id,
10
+ message_id=msg_id,
11
+ caption=new_caption
12
+ )
13
+ await sleep(2)
14
+ except FloodWait as e:
15
+ LOGGER.warning(f"FloodWait for {e.value} seconds while editing message {msg_id} in {chat_id}")
16
+ await sleep(e.value)
17
+ except Exception as e:
18
+ LOGGER.error(f"Error while editing message {msg_id} in {chat_id}: {e}")
19
+
20
+ async def delete_message(chat_id: int, msg_id: int):
21
+ try:
22
+ await Helper.delete_messages(
23
+ chat_id=chat_id,
24
+ message_ids=msg_id
25
+ )
26
+ await sleep(2)
27
+ LOGGER.info(f"Deleted message {msg_id} in {chat_id}")
28
+ except FloodWait as e:
29
+ LOGGER.warning(f"FloodWait for {e.value} seconds while deleting message {msg_id} in {chat_id}")
30
+ await sleep(e.value)
31
+ except Exception as e:
32
+ LOGGER.error(f"Error while deleting message {msg_id} in {chat_id}: {e}")
Backend/logger.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytz
2
+ from logging import getLogger, FileHandler, StreamHandler, INFO, ERROR, Formatter, basicConfig
3
+ from datetime import datetime
4
+
5
+ IST = pytz.timezone("Asia/Kolkata")
6
+
7
+ class ISTFormatter(Formatter):
8
+ def formatTime(self, record, datefmt=None):
9
+ dt = datetime.fromtimestamp(record.created, IST)
10
+ return dt.strftime(datefmt or "%d-%b-%y %I:%M:%S %p")
11
+
12
+ file_handler = FileHandler("log.txt")
13
+ stream_handler = StreamHandler()
14
+ formatter = ISTFormatter("[%(asctime)s] [%(levelname)s] - %(message)s", "%d-%b-%y %I:%M:%S %p")
15
+ file_handler.setFormatter(formatter)
16
+ stream_handler.setFormatter(formatter)
17
+
18
+ basicConfig(
19
+ handlers=[file_handler, stream_handler],
20
+ level=INFO
21
+ )
22
+
23
+ getLogger("httpx").setLevel(ERROR)
24
+ getLogger("pyrogram").setLevel(ERROR)
25
+ getLogger("fastapi").setLevel(ERROR)
26
+
27
+
28
+ LOGGER = getLogger(__name__)
29
+ LOGGER.setLevel(INFO)
30
+
31
+ LOGGER.info("Logger initialized with IST timezone.")
Backend/pyrofork/bot.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import Client
2
+ from Backend.config import Telegram
3
+
4
+
5
+ StreamBot = Client(
6
+ name='bot',
7
+ api_id=Telegram.API_ID,
8
+ api_hash=Telegram.API_HASH,
9
+ bot_token=Telegram.BOT_TOKEN,
10
+ plugins={"root": "Backend/pyrofork/plugins"},
11
+ sleep_threshold=20,
12
+ workers=6,
13
+ max_concurrent_transmissions=10
14
+ )
15
+
16
+
17
+ Helper = Client(
18
+ "helper",
19
+ api_id=Telegram.API_ID,
20
+ api_hash=Telegram.API_HASH,
21
+ bot_token=Telegram.HELPER_BOT_TOKEN,
22
+ sleep_threshold=20,
23
+ workers=6,
24
+ max_concurrent_transmissions=10
25
+ )
26
+
27
+
28
+ multi_clients = {}
29
+ work_loads = {}
Backend/pyrofork/clients.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import gather, create_task
2
+ 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
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(
26
+ name=str(client_id),
27
+ api_id=Telegram.API_ID,
28
+ api_hash=Telegram.API_HASH,
29
+ bot_token=token,
30
+ sleep_threshold=100,
31
+ no_updates=True,
32
+ in_memory=True
33
+ ).start()
34
+ work_loads[client_id] = 0
35
+ return client_id, client
36
+ except Exception as e:
37
+ LOGGER.error(f"Failed to start Client - {client_id} Error: {e}", exc_info=True)
38
+ return None
39
+
40
+ async def initialize_clients():
41
+ multi_clients[0], work_loads[0] = StreamBot, 0
42
+ all_tokens = TokenParser.parse_from_env()
43
+ if not all_tokens:
44
+ LOGGER.info("No additional Bot Clients found, Using default client")
45
+ return
46
+
47
+ tasks = [create_task(start_client(i, token)) for i, token in all_tokens.items()]
48
+ clients = await gather(*tasks)
49
+ clients = {client_id: client for client_id, client in clients if client}
50
+ multi_clients.update(clients)
51
+
52
+ if len(multi_clients) != 1:
53
+ LOGGER.info(f"Multi-Client Mode Enabled with {len(multi_clients)} clients")
54
+ else:
55
+ LOGGER.info("No additional clients were initialized, using default client")
56
+
Backend/pyrofork/plugins/log.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import filters, Client
2
+ from pyrogram.types import Message
3
+ from os import path as ospath
4
+
5
+ from Backend.helper.custom_filter import CustomFilters
6
+
7
+ @Client.on_message(filters.command('log') & filters.private & CustomFilters.owner, group=10)
8
+ async def log(client: Client, message: Message):
9
+ try:
10
+ path = ospath.abspath('log.txt')
11
+ if not ospath.exists(path):
12
+ return await message.reply_text("> ❌ Log file not found.")
13
+
14
+ await message.reply_document(
15
+ document=path,
16
+ quote=True,
17
+ disable_notification=True
18
+ )
19
+ except Exception as e:
20
+ await message.reply_text(f"⚠️ Error: {e}")
21
+ print(f"Error in /log: {e}")
Backend/pyrofork/plugins/manual.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Backend
2
+ from Backend.helper.custom_filter import CustomFilters
3
+ from pyrogram import filters, Client, enums
4
+ from pyrogram.types import Message
5
+ from Backend.logger import LOGGER
6
+
7
+
8
+ @Client.on_message(filters.command('set') & filters.private & CustomFilters.owner, group=10)
9
+ async def manual(client: Client, message: Message):
10
+ try:
11
+ command = message.text.split(maxsplit=1)
12
+
13
+ if len(command) == 2:
14
+ url = command[1].strip()
15
+ Backend.USE_DEFAULT_ID = url
16
+
17
+ await message.reply_text(
18
+ f"✅ <b>Default IMDB URL Set!</b>\n\n"
19
+ f"Now the bot will use this URL for any files you send:\n"
20
+ f"<code>{Backend.USE_DEFAULT_ID}</code>\n\n"
21
+ f"<b>Instructions:</b>\n"
22
+ f"1. Forward the related movie or TV show files to your channel.\n"
23
+ f"2. Once all files are uploaded, clear the default URL by sending <code>/set</code> without any URL.",
24
+ quote=True,
25
+ parse_mode=enums.ParseMode.HTML
26
+ )
27
+ else:
28
+ Backend.USE_DEFAULT_ID = None
29
+ await message.reply_text(
30
+ "✅ <b>Default IMDB URL Removed!</b>\n\n"
31
+ "You can now manually upload files without linking to a default IMDB URL.",
32
+ quote=True,
33
+ parse_mode=enums.ParseMode.HTML
34
+ )
35
+
36
+ except Exception as e:
37
+ LOGGER.error(f"Error in /set handler: {e}")
38
+ await message.reply_text(f"⚠️ An error occurred: {e}")
39
+
Backend/pyrofork/plugins/reciever.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from asyncio import create_task, sleep as asleep, Queue, Lock
2
+ 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
10
+ from pyrogram.types import Message
11
+ from pyrogram.errors import FloodWait
12
+ from pyrogram.enums.parse_mode import ParseMode
13
+
14
+
15
+ file_queue = Queue()
16
+ db_lock = Lock()
17
+
18
+ async def process_file():
19
+ while True:
20
+ metadata_info, channel, msg_id, size, title = await file_queue.get()
21
+ async with db_lock:
22
+ updated_id = await db.insert_media(metadata_info, channel=channel, msg_id=msg_id, size=size, name=title)
23
+ if updated_id:
24
+ LOGGER.info(f"{metadata_info['media_type']} updated with ID: {updated_id}")
25
+ else:
26
+ LOGGER.info("Update failed due to validation errors.")
27
+ file_queue.task_done()
28
+
29
+ for _ in range(1):
30
+ create_task(process_file())
31
+
32
+
33
+ @Client.on_message(filters.channel & (filters.document | filters.video))
34
+ async def file_receive_handler(client: Client, message: Message):
35
+ if str(message.chat.id) in Telegram.AUTH_CHANNEL:
36
+ try:
37
+ if message.video or (message.document and message.document.mime_type.startswith("video/")):
38
+ file = message.video or message.document
39
+
40
+ caption = message.caption
41
+ title = caption or file.file_name
42
+ msg_id = message.id
43
+ size = get_readable_file_size(file.file_size)
44
+ channel = str(message.chat.id).replace("-100", "")
45
+
46
+ metadata_info = await metadata(clean_filename(title), int(channel), msg_id)
47
+ if metadata_info is None:
48
+ return await message.reply_text("> Not added, check log")
49
+
50
+ title = remove_urls(title)
51
+ if not title.endswith(('.mkv', '.mp4')):
52
+ title += '.mkv'
53
+
54
+ if Backend.USE_DEFAULT_ID:
55
+ new_caption = (message.caption + "\n\n" + Backend.USE_DEFAULT_ID) if message.caption else Backend.USE_DEFAULT_ID
56
+ create_task(edit_message(
57
+ chat_id=message.chat.id,
58
+ msg_id=message.id,
59
+ new_caption=new_caption
60
+ ))
61
+
62
+ await file_queue.put((metadata_info, int(channel), msg_id, size, title))
63
+ else:
64
+ await message.reply_text("> Not supported")
65
+ except FloodWait as e:
66
+ LOGGER.info(f"Sleeping for {str(e.value)}s")
67
+ await asleep(e.value)
68
+ await message.reply_text(
69
+ text=f"Got Floodwait of {str(e.value)}s",
70
+ disable_web_page_preview=True,
71
+ parse_mode=ParseMode.MARKDOWN
72
+ )
73
+ else:
74
+ await message.reply_text("> Channel is not in AUTH_CHANNEL")
75
+
Backend/pyrofork/plugins/restart.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import filters, Client, enums
2
+ from pyrogram.types import Message
3
+ from Backend.helper.custom_filter import CustomFilters
4
+ from Backend.logger import LOGGER
5
+ from asyncio import create_subprocess_exec, gather
6
+ from aiofiles import open as aiopen
7
+ from os import execl as osexecl
8
+ import shutil
9
+
10
+ @Client.on_message(filters.command('restart') & filters.private & CustomFilters.owner, group=10)
11
+ async def restart(client: Client, message: Message):
12
+ try:
13
+ restart_message = await message.reply_text(
14
+ '<blockquote>⚙️ Restarting Backend API... \n\n✨ Please wait as we bring everything back online! 🚀</blockquote>',
15
+ quote=True,
16
+ parse_mode=enums.ParseMode.HTML
17
+ )
18
+
19
+ proc1 = await create_subprocess_exec('uv', 'run', 'update.py')
20
+ await gather(proc1.wait())
21
+
22
+ async with aiopen(".restartmsg", "w") as f:
23
+ await f.write(f"{restart_message.chat.id}\n{restart_message.id}\n")
24
+
25
+ LOGGER.info("Restarting the bot using uv package manager...")
26
+
27
+ uv_path = shutil.which("uv")
28
+ if uv_path:
29
+ osexecl(uv_path, uv_path, "run", "-m", "Backend")
30
+ else:
31
+ raise RuntimeError("uv not found in PATH.")
32
+
33
+ except Exception as e:
34
+ LOGGER.error(f"Error during restart: {e}")
35
+ await message.reply_text("**❌ Failed to restart. Check logs for details.**")
36
+
Backend/pyrofork/plugins/start.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import filters, Client, enums
2
+ from Backend.helper.custom_filter import CustomFilters
3
+ from pyrogram.types import Message
4
+ from Backend.config import Telegram
5
+ from urllib.parse import urlparse
6
+
7
+ @Client.on_message(filters.command('start') & filters.private & CustomFilters.owner, group=10)
8
+ async def send_start_message(client: Client, message: Message):
9
+ try:
10
+ parsed_url = urlparse(Telegram.BASE_URL)
11
+ base_url = Telegram.BASE_URL
12
+
13
+ if parsed_url.hostname.replace('.', '').isdigit() and Telegram.PORT:
14
+ base_url = f"{parsed_url.scheme}://{parsed_url.hostname}:{Telegram.PORT}"
15
+
16
+ addon_url = f"{base_url}/stremio/manifest.json"
17
+
18
+ await message.reply_text(
19
+ '<b>Welcome to the main Telegram Stremio bot!</b>\n\n'
20
+ 'To install the Stremio addon, copy the URL below and add it in the Stremio addons:\n\n'
21
+ f'<b>Your Addon URL:</b>\n<code>{addon_url}</code>',
22
+ quote=True,
23
+ parse_mode=enums.ParseMode.HTML
24
+ )
25
+
26
+ except Exception as e:
27
+ await message.reply_text(f"⚠️ Error: {e}")
28
+ print(f"Error in /start handler: {e}")
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ghcr.io/astral-sh/uv:debian-slim
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+ ENV PYTHONUNBUFFERED=1
5
+ ENV LANG=en_US.UTF-8
6
+ ENV PATH="/app/.venv/bin:$PATH"
7
+
8
+ RUN apt-get update && \
9
+ apt-get install -y --no-install-recommends \
10
+ build-essential \
11
+ bash \
12
+ git \
13
+ curl \
14
+ ca-certificates \
15
+ locales && \
16
+ locale-gen en_US.UTF-8 && \
17
+ rm -rf /var/lib/apt/lists/*
18
+
19
+ WORKDIR /app
20
+ COPY . .
21
+ RUN uv lock
22
+ RUN uv sync --locked
23
+ RUN chmod +x start.sh
24
+ CMD ["bash", "start.sh"]
README.md ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <p align="center">
3
+ <img src="https://iili.io/KhN0ztj.png" alt="Logo" width="400"/>
4
+ </p>
5
+
6
+
7
+ <p align="center">
8
+ A powerful, self-hosted <b>Telegram Stremio Media Server</b> built with <b>FastAPI</b>, <b>MongoDB</b>, and <b>PyroFork</b> — seamlessly integrated with <b>Stremio</b> for automated media streaming and discovery.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <img src="https://img.shields.io/badge/UV%20Package%20Manager-2B7A77?logo=uv&logoColor=white" alt="UV Package Manager" />
13
+ <img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white" alt="Python" />
14
+ <img src="https://img.shields.io/badge/FastAPI-009688?logo=fastapi&logoColor=white" alt="FastAPI" />
15
+ <img src="https://img.shields.io/badge/MongoDB-47A248?logo=mongodb&logoColor=white" alt="MongoDB" />
16
+ <img src="https://img.shields.io/badge/PyroFork-EE3A3A?logo=python&logoColor=white" alt="PyroFork" />
17
+ <img src="https://img.shields.io/badge/Stremio-8D3DAF?logo=stremio&logoColor=white" alt="Stremio" />
18
+ <img src="https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white" alt="Docker" />
19
+ </p>
20
+
21
+ ---
22
+
23
+ ## 🧭 Quick Navigation
24
+
25
+ - [🚀 Introduction](#-introduction)
26
+ - [✨ Key Features](#-key-features)
27
+ - [⚙️ How It Works](#️-how-it-works)
28
+ - [Overview](#overview)
29
+ - [Upload Guidelines](#upload-guidelines)
30
+ - [Quality Replacement](#-quality-replacement-logic)
31
+ - [Updating CAMRip](#-updating-camrip-or-low-quality-files)
32
+ - [Behind The Scenes](#behind-the-scenes)
33
+ - [🤖 Bot Commands](#-bot-commands)
34
+ - [Command List](#command-list)
35
+ - [`/set` Command Usage](#set-command-usage)
36
+ - [🔧 Configuration Guide](#-configuration-guide)
37
+ - [🧩 Startup Config](#-startup-config)
38
+ - [🗄️ Storage](#️-storage)
39
+ - [🎬 API](#-api)
40
+ - [🌐 Server](#-server)
41
+ - [🔄 Update Settings](#-update-settings)
42
+ - [🔐 Admin Panel](#-admin-panel)
43
+ - [🧰 Additional CDN Bots (Multi-Token System)](#-additional-cdn-bots-multi-token-system)
44
+ - [🚀 Deployment Guide](#-deployment-guide)
45
+ - [✅ Recommended Prerequisites](#-recommended-prerequisites)
46
+ - [🐙 Heroku Guide](#-heroku-guide)
47
+ - [🐳 VPS Guide (Recommended)](#-vps-guide)
48
+ - [📺 Setting up Stremio](#-setting-up-stremio)
49
+ - [🌐 Add the Addon](#-step-3-add-the-addon)
50
+ - [⚙️ Optional: Remove Cinemeta](#️-optional-remove-cinemeta)
51
+ - [🏅 Contributor](#-contributor)
52
+
53
+
54
+ # 🚀 Introduction
55
+
56
+ This project is a **next-generation Telegram Stremio Media Server** that allows you to **stream your Telegram files directly through Stremio**, without any third-party dependencies or file expiration issues. It’s designed for **speed, scalability, and reliability**, making it ideal for both personal and community-based media hosting.
57
+
58
+
59
+ ## ✨ Key Features
60
+
61
+ - ⚙️ **Multiple MongoDB Support**
62
+ - 📡 **Multiple Channel Support**
63
+ - ⚡ **Fast Streaming Experience**
64
+ - 🔑 **Multi Token Load Balancer**
65
+ - 🎬 **IMDB and TMDB Metadata Integration**
66
+ - ♾️ **No File Expiration**
67
+ - 🧠 **Admin Panel Support**
68
+
69
+
70
+ ## ⚙️ How It Works
71
+
72
+ This project acts as a **bridge between Telegram storage and Stremio streaming**, connecting **Telegram**, **FastAPI**, and **Stremio** to enable seamless movie and TV show streaming directly from Telegram files.
73
+
74
+ ### Overview
75
+
76
+ When you **forward Telegram files** (movies or TV episodes) to your **AUTH CHANNEL**, the bot automatically:
77
+
78
+ 1. 🗃️ **Stores** the `message_id` and `chat_id` in the database.
79
+ 2. 🧠 **Processes** file captions to extract key metadata (title, year, quality, etc.).
80
+ 3. 🌐 **Generates a streaming URL** through the **PyroFork** module — routed by **FastAPI**.
81
+ 4. 🎞️ **Provides Stremio Addon APIs**:
82
+ - `/catalog` → Lists available media
83
+ - `/meta` → Shows detailed information for each item
84
+ - `/stream` → Streams the file directly via Telegram
85
+
86
+ ### Upload Guidelines
87
+
88
+ To ensure proper metadata extraction and seamless integration with **Stremio**, all uploaded Telegram media files **must include specific details** in their captions.
89
+
90
+ #### 🎥 For Movies
91
+
92
+ **Example Caption:**
93
+
94
+ ```
95
+ Ghosted 2023 720p 10bit WEBRip [Org APTV Hindi AAC 2.0CH + English 6CH] x265 HEVC Msub ~ PSA.mkv
96
+ ```
97
+
98
+ **Required Fields:**
99
+
100
+ - 🎞️ **Name** – Movie title (e.g., _Ghosted_)
101
+ - 📅 **Year** – Release year (e.g., _2023_)
102
+ - 📺 **Quality** – Resolution or quality (e.g., _720p_, _1080p_, _2160p_)
103
+
104
+ ✅ **Optional:** Include codec, audio format, or source (e.g., `WEBRip`, `x265`, `Dual Audio`).
105
+
106
+ #### 📺 For TV Shows
107
+
108
+ **Example Caption:**
109
+
110
+ ```
111
+ Harikatha.Sambhavami.Yuge.Yuge.S01E04.Dark.Hours.1080p.WEB-DL.DUAL.DDP5.1.Atmos.H.264-Spidey.mkv
112
+ ````
113
+
114
+ **Required Fields:**
115
+
116
+ - 🎞️ **Name** – TV show title (e.g., _Harikatha Sambhavami Yuge Yuge_)
117
+ - 📆 **Season Number** – Use `S` followed by two digits (e.g., `S01`)
118
+ - 🎬 **Episode Number** – Use `E` followed by two digits (e.g., `E04`)
119
+ - 📺 **Quality** – Resolution or quality (e.g., _1080p_, _720p_)
120
+
121
+ ✅ **Optional:** Include episode title, codec, or audio details (e.g., `WEB-DL`, `DDP5.1`, `Dual Audio`).
122
+
123
+ ### 🔁 Quality Replacement Logic
124
+
125
+ When you upload multiple files with the **same quality label** (like `720p` or `1080p`),
126
+ the **latest file automatically replaces the old one**.
127
+
128
+ > Example:
129
+ > If you already uploaded `Ghosted 2023 720p` and then upload another `720p` version,
130
+ > the bot **replaces the old file** to keep your catalog clean and organized.
131
+
132
+ This helps avoid duplicate entries in Stremio and ensures only the most recent file is used.
133
+
134
+ ---
135
+
136
+ ### 🆙 Updating CAMRip or Low-Quality Files
137
+
138
+ If you initially uploaded a **CAMRip or low-quality version**, you can easily replace it with a better one:
139
+
140
+ 1. Forward the **new, higher-quality file** (e.g., `1080p`, `WEB-DL`) to your **AUTH CHANNEL**.
141
+ 2. The bot will **automatically detect and replace** the old CAMRip file in the database.
142
+ 3. The Stremio addon will then **update automatically**, showing the new stream source.
143
+
144
+ ✅ No manual deletion or command is needed — forwarding the updated file is enough!
145
+
146
+ ---
147
+
148
+
149
+ ### Behind The Scenes
150
+
151
+ Here's how each component interacts:
152
+
153
+ | Component | Role |
154
+ | :--- | :--- |
155
+ | **Telegram Bot** | Handles uploads, forwards, and file tracking. |
156
+ | **MongoDB** | Stores message IDs, chat IDs, and metadata. |
157
+ | **PyroFork** | Generates Telegram-based streaming URLs. |
158
+ | **FastAPI** | Hosts REST endpoints for streaming, catalog, and metadata. |
159
+ | **Stremio Addon** | Consumes FastAPI endpoints for catalog display and playback. |
160
+
161
+ 📦 **Flow Summary:**
162
+
163
+ ```
164
+ Telegram ➜ MongoDB ➜ FastAPI ➜ Stremio ➜ User Stream
165
+ ```
166
+
167
+
168
+
169
+ # 🤖 Bot Commands
170
+
171
+ Below is the list of available bot commands and their usage within the Telegram bot.
172
+
173
+ ### Command List
174
+
175
+ | Command | Description |
176
+ | :--- | :--- |
177
+ | **`/start`** | Returns your **Addon URL** for direct installation in **Stremio**. |
178
+ | **`/log`** | Sends the latest **log file** for debugging or monitoring. |
179
+ | **`/set`** | Used for **manual uploads** by linking IMDB URLs. |
180
+ | **`/restart`** | Restarts the bot and pulls any **latest updates** from the upstream repository. |
181
+
182
+ ### `/set` Command Usage
183
+
184
+ The `/set` command is used to manually upload a specific Movie or TV show to your channel, linking it to its IMDB metadata.
185
+
186
+ **Command:**
187
+
188
+ ```
189
+ /set <imdb-url>
190
+ ```
191
+
192
+ **Example:**
193
+
194
+ ```
195
+ /set https://m.imdb.com/title/tt665723
196
+ ```
197
+
198
+ **Steps:**
199
+
200
+ 1. Send the `/set` command followed by the **IMDB URL** of the movie or show you want to upload.
201
+ 2. **Forward the related movie or TV show files** to your channel.
202
+ 3. Once all files are uploaded, **clear the default IMDB link** by simply sending the `/set` command without any URL.
203
+
204
+ 💡 **Tip:** Use `/log` if you encounter any upload or parsing issues.
205
+
206
+
207
+ # 🔧 Configuration Guide
208
+
209
+ All environment variables for this project are defined in the `config.env` file. A detailed explanation of each parameter is provided below.
210
+
211
+ ### 🧩 Startup Config
212
+
213
+ | Variable | Description |
214
+ | :--- | :--- |
215
+ | **`API_ID`** | Your Telegram **API ID** from [my.telegram.org](https://my.telegram.org). Used for authenticating your Telegram session. |
216
+ | **`API_HASH`** | Your Telegram **API Hash** from [my.telegram.org](https://my.telegram.org). |
217
+ | **`BOT_TOKEN`** | The main bot’s **access token** from [@BotFather](https://t.me/BotFather). Handles user requests and media fetching. |
218
+ | **`HELPER_BOT_TOKEN`** | **Secondary bot token** used to assist the main bot with tasks like deleting, editing, or managing. |
219
+ | **`OWNER_ID`** | Your **Telegram user ID**. This ID has full administrative access. |
220
+
221
+ ### 🗄️ Storage
222
+
223
+ | Variable | Description |
224
+ | :--- | :--- |
225
+ | **`AUTH_CHANNEL`** | One or more **Telegram channel IDs** (comma-separated) where the bot is authorized to fetch or stream content. *Example: `-1001234567890, -1009876543210`*. |
226
+ | **`DATABASE`** | MongoDB Atlas connection URI(s). You **must provide at least two databases**, separated by commas (`,`) for load balancing and redundancy. <br>Example: <br>`mongodb+srv://user:pass@cluster0.mongodb.net/db1, mongodb+srv://user:pass@cluster1.mongodb.net/db2` |
227
+
228
+ > 💡 **Tip:** Create your MongoDB Atlas cluster [here](https://www.mongodb.com/cloud/atlas).
229
+
230
+ ### 🎬 API
231
+
232
+ | Variable | Description |
233
+ | :--- | :--- |
234
+ | **`TMDB_API`** | Your **TMDB API key** from [themoviedb.org](https://www.themoviedb.org/settings/api). Used to fetch movie and TV metadata. |
235
+
236
+ ### 🌐 Server
237
+
238
+ | Variable | Description |
239
+ | :--- | :--- |
240
+ | **`BASE_URL`** | The Public IP of your server or domain or heroku app URL (e.g. `http://182.xxx.xxx.xxx` or `https://your-domain.com`). Crucial for Stremio addon setup. |
241
+ | **`PORT`** | The port number on which your FastAPI server will run. *Default: `8000`*. |
242
+
243
+ ### 🔄 Update Settings
244
+
245
+ | Variable | Description |
246
+ | :--- | :--- |
247
+ | **`UPSTREAM_REPO`** | GitHub repository URL for automatic updates. |
248
+ | **`UPSTREAM_BRANCH`** | The branch name to track in your upstream repo. *Default: `master`*. |
249
+
250
+ ### 🔐 Admin Panel
251
+
252
+ | Variable | Description |
253
+ | :--- | :--- |
254
+ | **`ADMIN_USERNAME`** | Username for logging into the Admin Panel. |
255
+ | **`ADMIN_PASSWORD`** | Password for Admin Panel access.|
256
+ **⚠️ Change from default values for security.**
257
+
258
+ ### 🧰 Additional CDN Bots (Multi-Token System)
259
+
260
+ | Variable | Description |
261
+ | :--- | :--- |
262
+ | **`MULTI_TOKEN1`**, **`MULTI_TOKEN2`**, ... | Extra bot tokens used to distribute traffic and prevent Telegram rate-limiting. Add each bot as an **Admin** in your `AUTH_CHANNEL`(s). |
263
+
264
+ #### About `MULTI_TOKEN`
265
+
266
+ If your bot handles a high number of downloads/requests at a time, Telegram may limit your main bot.
267
+ To avoid this, you can use **MULTI_TOKEN** system:
268
+
269
+ - Create multiple bots using [@BotFather](https://t.me/BotFather).
270
+ - Add each bot as **Admin** in your `AUTH_CHANNEL`(s).
271
+ - Add the tokens in your `config.env` as `MULTI_TOKEN1`, `MULTI_TOKEN2`, `MULTI_TOKEN3`, and so on.
272
+ - The system will automatically distribute the load among all these bots!
273
+
274
+
275
+ # 🚀 Deployment Guide
276
+
277
+ This guide will help you deploy your **Telegram Stremio Media Server** using either Heroku or a VPS with Docker.
278
+
279
+ ## ✅ Recommended Prerequisites
280
+
281
+ **Supported Servers:**
282
+
283
+ - 🟣 **Heroku**
284
+ - 🟢 **VPS**
285
+
286
+ Before you begin, ensure you have:
287
+
288
+ 1. ✅ A **VPS** with a public IP (e.g., Ubuntu on DigitalOcean, AWS, Vultr, etc.)
289
+ 2. ✅ A **Domain name** (Optional but Recommended)
290
+
291
+
292
+ ## 🐙 Heroku Guide
293
+
294
+ Follow the instructions provided in the Google Colab Tool to deploy on Heroku.
295
+
296
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/weebzone/Colab-Tools/blob/main/telegram%20media%20server.ipynb)
297
+
298
+
299
+ ## 🐳 VPS Guide
300
+
301
+ ### 1️⃣ Step 1: Clone & Configure the Project
302
+
303
+ ```bash
304
+ git clone https://github.com/weebzone/Telegram-Stremio
305
+ cd Telegram-Stremio
306
+ mv sample_config.env config.env
307
+ nano config.env
308
+ ```
309
+
310
+ - Fill in all required variables in `config.env`.
311
+ - Press `Ctrl + O`, then `Enter`, then `Ctrl + X` to save and exit.
312
+
313
+ ### 2️⃣ Step 2: Deploy with Docker
314
+
315
+ ```bash
316
+ docker build -t tsms .
317
+ docker run -d -p 8000:8000 tsms
318
+ ```
319
+
320
+ Your Code should now be running at:  
321
+ ➡️ `http://<your-vps-ip>:8000`
322
+
323
+ -----
324
+
325
+ ### 🌐 Step 3: Add Domain (Optional but Recommended)
326
+
327
+ #### A. Set Up DNS Records
328
+
329
+ Go to your domain's DNS settings and add the following **A record**:
330
+
331
+ | Type | Name | Value |
332
+ |------|------|-------------------|
333
+ | A | * | `195.xxx.xxx.xxx` |
334
+
335
+ #### B. Install Nginx & Certbot
336
+
337
+ ```bash
338
+ sudo apt update
339
+ sudo apt install nginx certbot python3-certbot-nginx -y
340
+ ```
341
+
342
+ #### C. Configure Nginx
343
+
344
+ 1. **Create a New Nginx Config:**
345
+
346
+ ```bash
347
+ sudo nano /etc/nginx/sites-available/domain.com
348
+ ```
349
+
350
+ Paste the following (replace `domain.com` with your domain):
351
+
352
+ ```nginx
353
+ server {
354
+ listen 80;
355
+ server_name domain.com;
356
+
357
+ location / {
358
+ proxy_pass http://localhost:8000;
359
+ proxy_set_header Host $host;
360
+ proxy_set_header X-Real-IP $remote_addr;
361
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
362
+ }
363
+ }
364
+ ```
365
+
366
+ 2. **Enable the Site:**
367
+
368
+ ```bash
369
+ sudo ln -s /etc/nginx/sites-available/domain.com /etc/nginx/sites-enabled/domain.com
370
+ ```
371
+ 3. **Reload Nginx:**
372
+
373
+ ```bash
374
+ sudo nginx -t
375
+ sudo systemctl restart nginx
376
+ ```
377
+
378
+
379
+ #### D. Secure with HTTPS (Let's Encrypt)
380
+
381
+ ```bash
382
+ sudo certbot --nginx -d domain.com
383
+ ```
384
+
385
+ Your API is now available at:  
386
+ ➡️ `https://domain.com`
387
+
388
+
389
+ # 📺 Setting up Stremio
390
+
391
+ Follow these steps to connect your deployed addon to the **Stremio** app.
392
+
393
+ ### 📥 Step 1: Download Stremio
394
+
395
+ Download Stremio for your device:
396
+ 👉 [https://www.stremio.com/downloads](https://www.stremio.com/downloads)
397
+
398
+ ### 👤 Step 2: Sign In
399
+
400
+ - Create or log in to your **Stremio account**.
401
+
402
+ ### 🌐 Step 3: Add the Addon
403
+
404
+ 1. Open the **Stremio App**.
405
+ 2. Go to the **Addon Section** (usually represented by a puzzle piece icon 🧩).
406
+ 3. In the search bar, paste the appropriate addon URL:
407
+
408
+ | Deployment Method | Addon URL |
409
+ | :--- | :--- |
410
+ | **Heroku** | `https://<your-heroku-app>.herokuapp.com/stremio/manifest.json` |
411
+ | **VPS (IP)** | `http://<your-server-ip>:8000/stremio/manifest.json` |
412
+ | **Custom Domain** | `https://<your-domain>/stremio/manifest.json` |
413
+
414
+
415
+ ## ⚙️ Optional: Remove Cinemeta
416
+
417
+ If you want to use **only** your **Telegram Stremio Media Server addon** for metadata and streaming, follow this guide to remove the default `Cinemeta` addon.
418
+
419
+ ### 1️⃣ Step 1: Uninstall Other Addons
420
+
421
+ 1. Go to the **Addon Section** in the Stremio App.
422
+ 2. **Uninstall all addons** except your Telegram Stremio Media Server.
423
+ 3. Attempt to remove **Cinemeta**. If Stremio prevents it, proceed to Step 2.
424
+
425
+ ### 2️⃣ Step 2: Remove “Cinemeta” Protection
426
+
427
+ 1. Log in to your **Stremio account** via your **web browser**:
428
+ 👉 [https://app.strem.io/shell-v4.4/\#/](https://app.strem.io/shell-v4.4/#/)
429
+ 2. Once logged in, open your **browser console** (`Ctrl + Shift + J` on Windows/Linux or `Cmd + Option + J` on macOS).
430
+ 3. Copy and paste the code below into the console and press **Enter**:
431
+
432
+ <!-- end list -->
433
+
434
+ ```js
435
+ (function() {
436
+
437
+ const token = JSON.parse(localStorage.getItem("profile")).auth.key;
438
+
439
+ const requestData = {
440
+ type: "AddonCollectionGet",
441
+ authKey: token,
442
+ update: true
443
+ };
444
+
445
+ fetch('https://api.strem.io/api/addonCollectionGet', {
446
+ method: 'POST',
447
+ body: JSON.stringify(requestData)
448
+ })
449
+ .then(response => response.json())
450
+ .then(data => {
451
+
452
+ if (data && data.result) {
453
+
454
+ let result = JSON.stringify(data.result).substring(1).replace(/"protected":true/g, '"protected":false').replace('"idPrefixes":["tmdb:"]', '"idPrefixes":["tmdb:","tt"]');
455
+
456
+ const index = result.indexOf("}}],");
457
+
458
+ if (index !== -1) {
459
+ result = result.substring(0, index + 3) + "}";
460
+ }
461
+
462
+ let addons = '{"type":"AddonCollectionSet","authKey":"' + token + '",' + result;
463
+
464
+ fetch('https://api.strem.io/api/addonCollectionSet', {
465
+ method: 'POST',
466
+ body: addons
467
+ })
468
+ .then(response => response.text())
469
+ .then(data => {
470
+ console.log('Success:', data);
471
+ })
472
+ .catch((error) => {
473
+ console.error('Error:', error);
474
+ });
475
+
476
+ } else {
477
+ console.error('Error:', error);
478
+ }
479
+ })
480
+ .catch((error) => {
481
+ console.error('Erro:', error);
482
+ });
483
+ })();
484
+ ```
485
+
486
+ ### 3️⃣ Step 3: Confirm Success
487
+
488
+ - Wait until you see this message in the console:
489
+ ```
490
+ Success: {"result":{"success":true}}
491
+ ```
492
+ - Refresh the page (**F5**). You will now be able to **remove Cinemeta** from your addons list.
493
+
494
+
495
+ ## 🏅 **Contributor**
496
+
497
+ |<img width="80" src="https://avatars.githubusercontent.com/u/113664541">|<img width="80" src="https://avatars.githubusercontent.com/u/13152917">|<img width="80" src="https://avatars.githubusercontent.com/u/14957082">|
498
+ |:---:|:---:|:---:|
499
+ |[`Karan`](https://github.com/Weebzone)|[`Stremio`](https://github.com/Stremio)|[`ChatGPT`](https://github.com/OPENAI)|
500
+ |Author|Stremio SDK|Refactor
501
+
bump-version.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ def bump_version(version: str, part: str) -> str:
6
+ major, minor, patch = map(int, version.split("."))
7
+ if part == "patch":
8
+ patch += 1
9
+ elif part == "minor":
10
+ minor += 1
11
+ patch = 0
12
+ elif part == "major":
13
+ major += 1
14
+ minor = patch = 0
15
+ else:
16
+ raise ValueError(f"Unknown part to bump: {part}")
17
+ return f"{major}.{minor}.{patch}"
18
+
19
+ def update_pyproject(path: Path, new_version: str):
20
+ content = path.read_text()
21
+ updated_content = re.sub(
22
+ r'version\s*=\s*"[0-9]+\.[0-9]+\.[0-9]+"',
23
+ f'version = "{new_version}"',
24
+ content
25
+ )
26
+ path.write_text(updated_content)
27
+ print(f"Updated pyproject.toml to version {new_version}")
28
+
29
+ def update_init(path: Path, new_version: str):
30
+ content = path.read_text()
31
+ updated_content = re.sub(
32
+ r'__version__\s*=\s*"[0-9]+\.[0-9]+\.[0-9]+"',
33
+ f'__version__ = "{new_version}"',
34
+ content
35
+ )
36
+ path.write_text(updated_content)
37
+ print(f"Updated Backend/__init__.py to version {new_version}")
38
+
39
+ def main(part: str = "patch"):
40
+ pyproject_path = Path("pyproject.toml")
41
+ init_path = Path("Backend/__init__.py")
42
+
43
+ if not pyproject_path.exists() or not init_path.exists():
44
+ print("Error: pyproject.toml or Backend/__init__.py not found.")
45
+ sys.exit(1)
46
+
47
+ # Read current version from pyproject.toml
48
+ content = pyproject_path.read_text()
49
+ match = re.search(r'version\s*=\s*"([0-9]+\.[0-9]+\.[0-9]+)"', content)
50
+ if not match:
51
+ print("Error: version not found in pyproject.toml")
52
+ sys.exit(1)
53
+
54
+ current_version = match.group(1)
55
+ new_version = bump_version(current_version, part)
56
+
57
+ update_pyproject(pyproject_path, new_version)
58
+ update_init(init_path, new_version)
59
+
60
+ if __name__ == "__main__":
61
+ part = sys.argv[1] if len(sys.argv) > 1 else "patch" # default bump is patch
62
+ main(part)
heroku.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ build:
2
+ docker:
3
+ web: Dockerfile
pyproject.toml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "Telegram-Stremio"
3
+ version = "1.0.0"
4
+ description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "aiofiles>=24.1.0",
9
+ "fastapi>=0.115.12",
10
+ "httpx>=0.28.1",
11
+ "itsdangerous>=2.2.0",
12
+ "jinja2>=3.1.6",
13
+ "motor>=3.7.0",
14
+ "parse-torrent-title>=2.8.1",
15
+ "pyrofork>=2.3.61",
16
+ "python-dotenv>=1.1.0",
17
+ "python-multipart>=0.0.20",
18
+ "pytz>=2025.2",
19
+ "requests>=2.32.3",
20
+ "tgcrypto>=1.2.5",
21
+ "themoviedb>=1.0.2",
22
+ "uvicorn>=0.34.2",
23
+ ]
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "deptry>=0.23.1",
28
+ ]
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles
2
+ fastapi
3
+ httpx
4
+ motor
5
+ parse-torrent-title
6
+ pyrofork
7
+ python-dotenv
8
+ pytz
9
+ tgcrypto
10
+ themoviedb
11
+ uvicorn
sample_config.env ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Startup Config
2
+ API_ID = ""
3
+ API_HASH = ""
4
+ BOT_TOKEN = ""
5
+ HELPER_BOT_TOKEN = ""
6
+ OWNER_ID = ""
7
+
8
+ # STORAGE
9
+ AUTH_CHANNEL = ""
10
+ DATABASE = ""
11
+
12
+ # API
13
+ TMDB_API = ""
14
+
15
+ # SERVER
16
+ BASE_URL = ""
17
+ PORT = "8000"
18
+
19
+ # Update
20
+ UPSTREAM_REPO = ""
21
+ UPSTREAM_BRANCH = ""
22
+
23
+ # Admin Pannel
24
+ ADMIN_USERNAME = "fyvio"
25
+ ADMIN_PASSWORD = "fyvio"
26
+
27
+ # Additional CDN Bots
28
+ # MULTI_TOKEN1 = ""
29
+
30
+
start.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ uv run update.py && uv run -m Backend
update.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import FileHandler, StreamHandler, INFO, ERROR, Formatter, basicConfig, error as log_error, info as log_info
2
+ from os import path as ospath, environ
3
+ from pathlib import Path
4
+ from subprocess import run as srun, PIPE
5
+ from dotenv import load_dotenv
6
+ from datetime import datetime
7
+ import pytz
8
+
9
+ IST = pytz.timezone("Asia/Kolkata")
10
+
11
+ class ISTFormatter(Formatter):
12
+ def formatTime(self, record, datefmt=None):
13
+ dt = datetime.fromtimestamp(record.created, IST)
14
+ return dt.strftime(datefmt or "%d-%b-%y %I:%M:%S %p")
15
+
16
+ log_file = "log.txt"
17
+ if ospath.exists(log_file):
18
+ with open(log_file, "w") as f:
19
+ f.truncate(0)
20
+
21
+ file_handler = FileHandler(log_file)
22
+ stream_handler = StreamHandler()
23
+
24
+ formatter = ISTFormatter("[%(asctime)s] [%(levelname)s] - %(message)s", "%d-%b-%y %I:%M:%S %p")
25
+ file_handler.setFormatter(formatter)
26
+ stream_handler.setFormatter(formatter)
27
+
28
+ basicConfig(handlers=[file_handler, stream_handler], level=INFO)
29
+
30
+ load_dotenv("config.env")
31
+
32
+ UPSTREAM_REPO = environ.get("UPSTREAM_REPO", "").strip() or None
33
+ UPSTREAM_BRANCH = environ.get("UPSTREAM_BRANCH", "").strip() or "main"
34
+
35
+ if UPSTREAM_REPO:
36
+ if Path(".git").exists():
37
+ srun(["rm", "-rf", ".git"])
38
+
39
+ update_cmd = (
40
+ f"git init -q && "
41
+ f"git config --global user.email 'doc.adhikari@gmail.com' && "
42
+ f"git config --global user.name 'weebzone' && "
43
+ f"git add . && git commit -sm 'update' -q && "
44
+ f"git remote add origin {UPSTREAM_REPO} && "
45
+ f"git fetch origin -q && "
46
+ f"git reset --hard origin/{UPSTREAM_BRANCH} -q"
47
+ )
48
+
49
+ update = srun(update_cmd, shell=True)
50
+ repo = UPSTREAM_REPO.strip("/").split("/")
51
+ repo_url = f"https://github.com/{repo[-2]}/{repo[-1]}"
52
+ log_info(f"UPSTREAM_REPO: {repo_url} | UPSTREAM_BRANCH: {UPSTREAM_BRANCH}")
53
+
54
+ if update.returncode == 0:
55
+ log_info("Successfully updated with latest commits!!")
56
+ else:
57
+ log_error("❌ Update failed! Retry or ask for support.")
uv.lock ADDED
The diff for this file is too large to render. See raw diff