weebzone commited on
Commit ·
4232240
1
Parent(s): b8cbe09
`V-1.2.0 — Docker Compose Support, Stremio Enhancements & UI Fixes`
Browse files✨ New Features
- Added full Docker Compose support with mounted `config.env`
→ Users can now edit `config.env` directly without rebuilding containers.
- Introduced 4 new Stremio catalog sections:
• Latest - Movies
• Popular - Movies
• Latest - Shows
• Popular - Shows
- Added genre filtering support in Stremio with the following genres:
Action, Adventure, Animation, Biography, Comedy,
Crime, Documentary, Drama, Family, Fantasy,
History, Horror, Music, Mystery, Romance,
Sci-Fi, Sport, Thriller, War, Western
🐛 Fixes
- Fixed movie backdrop display issue in the “Continue Watching” section.
🧩 Improvements
- Updated README to include Docker Compose deployment instructions.
- Backend/__init__.py +1 -1
- Backend/fastapi/routes/stremio_routes.py +93 -44
- Backend/helper/database.py +64 -50
- Backend/helper/metadata.py +29 -33
- README.md +85 -32
- docker-compose.yaml +8 -0
- pyproject.toml +1 -1
- uv.lock +1 -1
Backend/__init__.py
CHANGED
|
@@ -11,4 +11,4 @@ StartTime = time()
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
-
__version__ = "1.
|
|
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
+
__version__ = "1.2.0"
|
Backend/fastapi/routes/stremio_routes.py
CHANGED
|
@@ -6,36 +6,43 @@ from Backend import db, __version__
|
|
| 6 |
|
| 7 |
# --- Configuration ---
|
| 8 |
BASE_URL = Telegram.BASE_URL
|
| 9 |
-
ADDON_NAME = "Telegram
|
| 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.
|
| 39 |
"version": ADDON_VERSION,
|
| 40 |
"name": ADDON_NAME,
|
| 41 |
"logo": "https://i.postimg.cc/XqWnmDXr/Picsart-25-10-09-08-09-45-867.png",
|
|
@@ -45,41 +52,75 @@ async def get_manifest():
|
|
| 45 |
"catalogs": [
|
| 46 |
{
|
| 47 |
"type": "movie",
|
| 48 |
-
"id": "
|
| 49 |
-
"name": "
|
| 50 |
-
"extra": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
},
|
| 52 |
{
|
| 53 |
"type": "series",
|
| 54 |
-
"id": "
|
| 55 |
-
"name": "
|
| 56 |
-
"extra": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 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)
|
|
@@ -87,21 +128,27 @@ async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
if media_type == "movie":
|
| 92 |
-
data = await db.sort_movies(sort_params, page
|
| 93 |
items = data.get("movies", [])
|
| 94 |
else:
|
| 95 |
-
data = await db.sort_tv_shows(sort_params, page
|
| 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:
|
|
@@ -109,11 +156,12 @@ async def get_meta(media_type: str, id: str):
|
|
| 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",
|
|
@@ -125,12 +173,13 @@ async def get_meta(media_type: str, id: str):
|
|
| 125 |
"poster": media.get("poster", ""),
|
| 126 |
"logo": media.get("logo", ""),
|
| 127 |
"background": media.get("backdrop", ""),
|
| 128 |
-
"imdb_id": media.get("
|
| 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']}"
|
|
@@ -139,14 +188,14 @@ async def get_meta(media_type: str, id: str):
|
|
| 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:
|
|
@@ -157,17 +206,17 @@ async def get_streams(media_type: str, id: str):
|
|
| 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', '')}",
|
|
@@ -177,5 +226,5 @@ async def get_streams(media_type: str, id: str):
|
|
| 177 |
for quality in media_details.get("telegram", [])
|
| 178 |
if quality.get("id")
|
| 179 |
]
|
| 180 |
-
|
| 181 |
-
return {"streams": streams}
|
|
|
|
| 6 |
|
| 7 |
# --- Configuration ---
|
| 8 |
BASE_URL = Telegram.BASE_URL
|
| 9 |
+
ADDON_NAME = "Telegram"
|
| 10 |
ADDON_VERSION = __version__
|
| 11 |
PAGE_SIZE = 15
|
| 12 |
|
| 13 |
router = APIRouter(prefix="/stremio", tags=["Stremio Addon"])
|
| 14 |
|
| 15 |
+
# Define available genres
|
| 16 |
+
GENRES = [
|
| 17 |
+
"Action", "Adventure", "Animation", "Biography", "Comedy",
|
| 18 |
+
"Crime", "Documentary", "Drama", "Family", "Fantasy",
|
| 19 |
+
"History", "Horror", "Music", "Mystery", "Romance",
|
| 20 |
+
"Sci-Fi", "Sport", "Thriller", "War", "Western"
|
| 21 |
+
]
|
| 22 |
|
| 23 |
# --- Helper Functions ---
|
| 24 |
def convert_to_stremio_meta(item: dict) -> dict:
|
| 25 |
media_type = "series" if item.get("media_type") == "tv" else "movie"
|
| 26 |
stremio_id = f"{item.get('tmdb_id')}-{item.get('db_index')}"
|
| 27 |
+
|
| 28 |
return {
|
| 29 |
"id": stremio_id,
|
| 30 |
"type": media_type,
|
| 31 |
"name": item.get("title"),
|
| 32 |
+
"poster": item.get("poster") or "",
|
| 33 |
+
"logo": item.get("logo") or "",
|
| 34 |
"year": item.get("release_year"),
|
| 35 |
+
"background": item.get("backdrop") or "",
|
| 36 |
+
"genres": item.get("genres") or [],
|
| 37 |
+
"imdbRating": item.get("rating") or "",
|
| 38 |
+
"description": item.get("description") or "",
|
| 39 |
}
|
| 40 |
|
|
|
|
| 41 |
# --- Stremio Endpoints ---
|
| 42 |
@router.get("/manifest.json")
|
| 43 |
async def get_manifest():
|
| 44 |
return {
|
| 45 |
+
"id": "telegram.media",
|
| 46 |
"version": ADDON_VERSION,
|
| 47 |
"name": ADDON_NAME,
|
| 48 |
"logo": "https://i.postimg.cc/XqWnmDXr/Picsart-25-10-09-08-09-45-867.png",
|
|
|
|
| 52 |
"catalogs": [
|
| 53 |
{
|
| 54 |
"type": "movie",
|
| 55 |
+
"id": "latest_movies",
|
| 56 |
+
"name": "Latest",
|
| 57 |
+
"extra": [
|
| 58 |
+
{"name": "genre", "isRequired": False},
|
| 59 |
+
{"name": "skip"}
|
| 60 |
+
],
|
| 61 |
+
"genres": GENRES
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"type": "movie",
|
| 65 |
+
"id": "top_movies",
|
| 66 |
+
"name": "Popular",
|
| 67 |
+
"extra": [
|
| 68 |
+
{"name": "genre", "isRequired": False},
|
| 69 |
+
{"name": "skip"},
|
| 70 |
+
{"name": "search"}
|
| 71 |
+
],
|
| 72 |
+
"genres": GENRES
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"type": "series",
|
| 76 |
+
"id": "latest_series",
|
| 77 |
+
"name": "Latest",
|
| 78 |
+
"extra": [
|
| 79 |
+
{"name": "genre", "isRequired": False},
|
| 80 |
+
{"name": "skip"}
|
| 81 |
+
],
|
| 82 |
+
"genres": GENRES
|
| 83 |
},
|
| 84 |
{
|
| 85 |
"type": "series",
|
| 86 |
+
"id": "top_series",
|
| 87 |
+
"name": "Popular",
|
| 88 |
+
"extra": [
|
| 89 |
+
{"name": "genre", "isRequired": False},
|
| 90 |
+
{"name": "skip"},
|
| 91 |
+
{"name": "search"}
|
| 92 |
+
],
|
| 93 |
+
"genres": GENRES
|
| 94 |
}
|
| 95 |
],
|
| 96 |
"idPrefixes": [""]
|
| 97 |
}
|
| 98 |
|
|
|
|
| 99 |
@router.get("/catalog/{media_type}/{id}/{extra:path}.json")
|
| 100 |
@router.get("/catalog/{media_type}/{id}.json")
|
| 101 |
async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
|
| 102 |
if media_type not in ["movie", "series"]:
|
| 103 |
raise HTTPException(status_code=404, detail="Invalid catalog type")
|
| 104 |
+
|
| 105 |
+
genre_filter = None
|
| 106 |
search_query = None
|
| 107 |
stremio_skip = 0
|
| 108 |
+
|
| 109 |
if extra:
|
| 110 |
+
params = extra.replace("&", "/").split("/")
|
| 111 |
+
for param in params:
|
| 112 |
+
if param.startswith("genre="):
|
| 113 |
+
genre_filter = unquote(param.removeprefix("genre="))
|
| 114 |
+
elif param.startswith("search="):
|
| 115 |
+
search_query = unquote(param.removeprefix("search="))
|
| 116 |
+
elif param.startswith("skip="):
|
| 117 |
+
try:
|
| 118 |
+
stremio_skip = int(param.removeprefix("skip="))
|
| 119 |
+
except ValueError:
|
| 120 |
+
stremio_skip = 0
|
| 121 |
+
|
| 122 |
page = (stremio_skip // PAGE_SIZE) + 1
|
| 123 |
+
|
| 124 |
try:
|
| 125 |
if search_query:
|
| 126 |
search_results = await db.search_documents(query=search_query, page=page, page_size=PAGE_SIZE)
|
|
|
|
| 128 |
db_media_type = "tv" if media_type == "series" else "movie"
|
| 129 |
items = [item for item in all_items if item.get("media_type") == db_media_type]
|
| 130 |
else:
|
| 131 |
+
if "latest" in id:
|
| 132 |
+
sort_params = [("updated_on", "desc")]
|
| 133 |
+
elif "top" in id:
|
| 134 |
+
sort_params = [("rating", "desc")]
|
| 135 |
+
else:
|
| 136 |
+
sort_params = [("updated_on", "desc")]
|
| 137 |
+
|
| 138 |
if media_type == "movie":
|
| 139 |
+
data = await db.sort_movies(sort_params, page, PAGE_SIZE, genre_filter=genre_filter)
|
| 140 |
items = data.get("movies", [])
|
| 141 |
else:
|
| 142 |
+
data = await db.sort_tv_shows(sort_params, page, PAGE_SIZE, genre_filter=genre_filter)
|
| 143 |
items = data.get("tv_shows", [])
|
| 144 |
+
|
| 145 |
except Exception as e:
|
| 146 |
print(f"Error fetching catalog data: {e}")
|
| 147 |
return {"metas": []}
|
| 148 |
+
|
| 149 |
metas = [convert_to_stremio_meta(item) for item in items]
|
| 150 |
return {"metas": metas}
|
| 151 |
|
|
|
|
| 152 |
@router.get("/meta/{media_type}/{id}.json")
|
| 153 |
async def get_meta(media_type: str, id: str):
|
| 154 |
try:
|
|
|
|
| 156 |
tmdb_id, db_index = int(tmdb_id_str), int(db_index_str)
|
| 157 |
except (ValueError, IndexError):
|
| 158 |
raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
|
| 159 |
+
|
| 160 |
media = await db.get_media_details(tmdb_id=tmdb_id, db_index=db_index)
|
| 161 |
+
|
| 162 |
if not media:
|
| 163 |
return {"meta": {}}
|
| 164 |
+
|
| 165 |
meta_obj = {
|
| 166 |
"id": id,
|
| 167 |
"type": "series" if media.get("media_type") == "tv" else "movie",
|
|
|
|
| 173 |
"poster": media.get("poster", ""),
|
| 174 |
"logo": media.get("logo", ""),
|
| 175 |
"background": media.get("backdrop", ""),
|
| 176 |
+
"imdb_id": media.get("imdb_id", "")
|
| 177 |
}
|
| 178 |
+
|
| 179 |
if media_type == "series" and "seasons" in media:
|
| 180 |
series_base_id = id
|
| 181 |
videos = []
|
| 182 |
+
|
| 183 |
for season in sorted(media.get("seasons", []), key=lambda s: s.get("season_number")):
|
| 184 |
for episode in sorted(season.get("episodes", []), key=lambda e: e.get("episode_number")):
|
| 185 |
episode_id = f"{series_base_id}:{season['season_number']}:{episode['episode_number']}"
|
|
|
|
| 188 |
"title": episode.get("title", f"Episode {episode['episode_number']}"),
|
| 189 |
"season": season.get("season_number"),
|
| 190 |
"episode": episode.get("episode_number"),
|
| 191 |
+
"thumbnail": episode.get("episode_backdrop") or "https://via.placeholder.com/1280x720/1a1a2e/eaeaea?text=No+Image",
|
| 192 |
"imdb_id": episode.get("imdb_id") or media.get("imdb_id"),
|
| 193 |
})
|
| 194 |
+
|
| 195 |
meta_obj["videos"] = videos
|
| 196 |
+
|
| 197 |
return {"meta": meta_obj}
|
| 198 |
|
|
|
|
| 199 |
@router.get("/stream/{media_type}/{id}.json")
|
| 200 |
async def get_streams(media_type: str, id: str):
|
| 201 |
try:
|
|
|
|
| 206 |
tmdb_id, db_index = map(int, base_id.split("-"))
|
| 207 |
except (ValueError, IndexError):
|
| 208 |
raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
|
| 209 |
+
|
| 210 |
media_details = await db.get_media_details(
|
| 211 |
tmdb_id=tmdb_id,
|
| 212 |
db_index=db_index,
|
| 213 |
season_number=season_num,
|
| 214 |
episode_number=episode_num
|
| 215 |
)
|
| 216 |
+
|
| 217 |
if not media_details or "telegram" not in media_details:
|
| 218 |
return {"streams": []}
|
| 219 |
+
|
| 220 |
streams = [
|
| 221 |
{
|
| 222 |
"name": f"{quality.get('name', '')}",
|
|
|
|
| 226 |
for quality in media_details.get("telegram", [])
|
| 227 |
if quality.get("id")
|
| 228 |
]
|
| 229 |
+
|
| 230 |
+
return {"streams": streams}
|
Backend/helper/database.py
CHANGED
|
@@ -9,7 +9,7 @@ from typing import Dict, List, Optional, Tuple, Any
|
|
| 9 |
from Backend.logger import LOGGER
|
| 10 |
from Backend.config import Telegram
|
| 11 |
import re
|
| 12 |
-
from Backend.helper.encrypt import decode_string
|
| 13 |
from Backend.helper.modal import Episode, MovieSchema, QualityDetail, Season, TVShowSchema
|
| 14 |
from Backend.helper.task_manager import delete_message
|
| 15 |
|
|
@@ -87,41 +87,58 @@ class Database:
|
|
| 87 |
return {"updated_on": DESCENDING}
|
| 88 |
|
| 89 |
async def _paginate_collection(
|
| 90 |
-
self,
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
skip = (page - 1) * page_size
|
| 94 |
results = []
|
| 95 |
-
dbs_checked = [
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
return results, dbs_checked, total_count
|
| 126 |
|
| 127 |
async def _move_document(
|
|
@@ -392,35 +409,35 @@ class Database:
|
|
| 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
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
"
|
| 409 |
}
|
| 410 |
|
| 411 |
-
async def
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
"
|
| 424 |
}
|
| 425 |
|
| 426 |
|
|
@@ -567,9 +584,6 @@ class Database:
|
|
| 567 |
return None
|
| 568 |
|
| 569 |
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
# -------------------------------
|
| 574 |
# DB Method for Edit Post
|
| 575 |
# -------------------------------
|
|
|
|
| 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 |
|
|
|
|
| 87 |
return {"updated_on": DESCENDING}
|
| 88 |
|
| 89 |
async def _paginate_collection(
|
| 90 |
+
self,
|
| 91 |
+
collection_name: str,
|
| 92 |
+
sort_dict: Dict[str, int],
|
| 93 |
+
page: int,
|
| 94 |
+
page_size: int,
|
| 95 |
+
filter_dict: Optional[dict] = None
|
| 96 |
+
):
|
| 97 |
+
filter_dict = filter_dict or {}
|
| 98 |
skip = (page - 1) * page_size
|
| 99 |
results = []
|
| 100 |
+
dbs_checked = []
|
| 101 |
+
total_count = 0
|
| 102 |
+
|
| 103 |
+
db_counts = []
|
| 104 |
+
for i in range(1, self.current_db_index + 1):
|
| 105 |
+
db_key = f"storage_{i}"
|
| 106 |
+
db = self.dbs[db_key]
|
| 107 |
+
count = await db[collection_name].count_documents(filter_dict)
|
| 108 |
+
db_counts.append((i, count))
|
| 109 |
+
total_count += count
|
| 110 |
+
|
| 111 |
+
start_db_index = None
|
| 112 |
+
for db_index, count in reversed(db_counts):
|
| 113 |
+
if skip < count:
|
| 114 |
+
start_db_index = db_index
|
| 115 |
+
break
|
| 116 |
+
skip -= count
|
| 117 |
+
|
| 118 |
+
if not start_db_index:
|
| 119 |
+
return [], [], total_count
|
| 120 |
+
|
| 121 |
+
for db_index, count in reversed(db_counts):
|
| 122 |
+
if db_index < start_db_index:
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
db_key = f"storage_{db_index}"
|
| 126 |
+
db = self.dbs[db_key]
|
| 127 |
+
dbs_checked.append(db_index)
|
| 128 |
+
|
| 129 |
+
cursor = (
|
| 130 |
+
db[collection_name]
|
| 131 |
+
.find(filter_dict)
|
| 132 |
+
.sort(sort_dict)
|
| 133 |
+
.skip(skip if db_index == start_db_index else 0)
|
| 134 |
+
.limit(page_size - len(results))
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
docs = await cursor.to_list(None)
|
| 138 |
+
results.extend(docs)
|
| 139 |
+
|
| 140 |
+
if len(results) >= page_size:
|
| 141 |
+
break
|
| 142 |
return results, dbs_checked, total_count
|
| 143 |
|
| 144 |
async def _move_document(
|
|
|
|
| 409 |
LOGGER.error(f"Failed to update TV show {tmdb_id} in {existing_db_key}: {e}")
|
| 410 |
if any(keyword in str(e).lower() for keyword in ["storage", "quota"]):
|
| 411 |
return await self._handle_storage_error(self.update_tv_show, tv_show_data, total_storage_dbs=total_storage_dbs)
|
| 412 |
+
|
| 413 |
+
async def sort_movies(self, sort_params, page, page_size, genre_filter=None):
|
|
|
|
|
|
|
| 414 |
sort_dict = self._get_sort_dict(sort_params)
|
| 415 |
+
filter_dict = {"genres": {"$in": [genre_filter]}} if genre_filter else {}
|
| 416 |
+
results, dbs_checked, total_count = await self._paginate_collection(
|
| 417 |
+
"movie", sort_dict, page, page_size, filter_dict=filter_dict
|
| 418 |
+
)
|
| 419 |
total_pages = (total_count + page_size - 1) // page_size
|
|
|
|
| 420 |
return {
|
| 421 |
"total_count": total_count,
|
| 422 |
"total_pages": total_pages,
|
| 423 |
"databases_checked": dbs_checked,
|
| 424 |
"current_page": page,
|
| 425 |
+
"movies": [convert_objectid_to_str(result) for result in results],
|
| 426 |
}
|
| 427 |
|
| 428 |
+
async def sort_tv_shows(self, sort_params, page, page_size, genre_filter=None):
|
|
|
|
|
|
|
| 429 |
sort_dict = self._get_sort_dict(sort_params)
|
| 430 |
+
filter_dict = {"genres": {"$in": [genre_filter]}} if genre_filter else {}
|
| 431 |
+
results, dbs_checked, total_count = await self._paginate_collection(
|
| 432 |
+
"tv", sort_dict, page, page_size, filter_dict=filter_dict
|
| 433 |
+
)
|
| 434 |
total_pages = (total_count + page_size - 1) // page_size
|
|
|
|
| 435 |
return {
|
| 436 |
"total_count": total_count,
|
| 437 |
"total_pages": total_pages,
|
| 438 |
"databases_checked": dbs_checked,
|
| 439 |
"current_page": page,
|
| 440 |
+
"tv_shows": [convert_objectid_to_str(result) for result in results],
|
| 441 |
}
|
| 442 |
|
| 443 |
|
|
|
|
| 584 |
return None
|
| 585 |
|
| 586 |
|
|
|
|
|
|
|
|
|
|
| 587 |
# -------------------------------
|
| 588 |
# DB Method for Edit Post
|
| 589 |
# -------------------------------
|
Backend/helper/metadata.py
CHANGED
|
@@ -2,7 +2,6 @@ import asyncio
|
|
| 2 |
import traceback
|
| 3 |
import PTN
|
| 4 |
from re import compile, IGNORECASE
|
| 5 |
-
|
| 6 |
from Backend.helper.imdb import get_detail, get_season, search_title
|
| 7 |
from Backend.helper.pyro import extract_tmdb_id
|
| 8 |
from themoviedb import aioTMDb
|
|
@@ -16,9 +15,8 @@ DELAY = 2
|
|
| 16 |
tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
|
| 17 |
|
| 18 |
# ----------------- Helpers -----------------
|
| 19 |
-
def format_tmdb_image(path: str, size="w500"
|
| 20 |
-
return f"https://image.tmdb.org/t/p/{size}{path}"
|
| 21 |
-
|
| 22 |
|
| 23 |
def format_imdb_images(imdb_id: str) -> dict:
|
| 24 |
return {
|
|
@@ -27,7 +25,6 @@ def format_imdb_images(imdb_id: str) -> dict:
|
|
| 27 |
"logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
|
| 28 |
}
|
| 29 |
|
| 30 |
-
|
| 31 |
async def safe_imdb_search(title: str, type_: str) -> str | None:
|
| 32 |
"""Safely search IMDb title and return its ID."""
|
| 33 |
try:
|
|
@@ -37,7 +34,6 @@ async def safe_imdb_search(title: str, type_: str) -> str | None:
|
|
| 37 |
LOGGER.warning(f"IMDb search failed for '{title}' [{type_}]: {e}")
|
| 38 |
return None
|
| 39 |
|
| 40 |
-
|
| 41 |
async def safe_tmdb_search(title: str, type_: str, year=None):
|
| 42 |
"""Safely search TMDb title."""
|
| 43 |
try:
|
|
@@ -53,7 +49,6 @@ async def safe_tmdb_search(title: str, type_: str, year=None):
|
|
| 53 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
| 54 |
return None
|
| 55 |
|
| 56 |
-
|
| 57 |
# ----------------- Main Entry -----------------
|
| 58 |
async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
| 59 |
try:
|
|
@@ -61,56 +56,56 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
|
| 61 |
except Exception as e:
|
| 62 |
LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
|
| 63 |
return None
|
| 64 |
-
|
| 65 |
# Skip combined/invalid files
|
| 66 |
if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
|
| 67 |
LOGGER.info(f"Skipping {filename}: contains 'combined'")
|
| 68 |
return None
|
| 69 |
-
|
| 70 |
# Skip split/multipart files
|
| 71 |
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 72 |
if multipart_pattern.search(filename):
|
| 73 |
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
| 74 |
return None
|
| 75 |
-
|
| 76 |
title = parsed.get("title")
|
| 77 |
season = parsed.get("season")
|
| 78 |
episode = parsed.get("episode")
|
| 79 |
year = parsed.get("year")
|
| 80 |
quality = parsed.get("resolution")
|
| 81 |
-
|
| 82 |
if not quality:
|
| 83 |
LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
|
| 84 |
return None
|
| 85 |
-
|
| 86 |
if isinstance(season, list) or isinstance(episode, list):
|
| 87 |
LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
|
| 88 |
return None
|
| 89 |
-
|
| 90 |
if season and not episode:
|
| 91 |
LOGGER.warning(f"Missing episode in {filename}: {parsed}")
|
| 92 |
return None
|
| 93 |
-
|
| 94 |
# Extract TMDb/IMDb hint
|
| 95 |
default_id = None
|
| 96 |
try:
|
| 97 |
default_id = extract_tmdb_id(Backend.USE_DEFAULT_ID)
|
| 98 |
except Exception:
|
| 99 |
pass
|
| 100 |
-
|
| 101 |
if not default_id:
|
| 102 |
try:
|
| 103 |
default_id = extract_tmdb_id(filename)
|
| 104 |
except Exception:
|
| 105 |
pass
|
| 106 |
-
|
| 107 |
if not title:
|
| 108 |
LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
|
| 109 |
return None
|
| 110 |
-
|
| 111 |
data = {"chat_id": channel, "msg_id": msg_id}
|
| 112 |
encoded_string = await encode_string(data)
|
| 113 |
-
|
| 114 |
try:
|
| 115 |
if season and episode:
|
| 116 |
LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
|
|
@@ -122,12 +117,11 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
|
| 122 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 123 |
return None
|
| 124 |
|
| 125 |
-
|
| 126 |
# ----------------- TV Metadata -----------------
|
| 127 |
async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 128 |
imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(title, "tvSeries")
|
| 129 |
tv_details, ep_details, use_tmdb = None, None, False
|
| 130 |
-
|
| 131 |
# Try IMDb first
|
| 132 |
if imdb_id:
|
| 133 |
try:
|
|
@@ -137,7 +131,7 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 137 |
ep_details = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
|
| 138 |
except Exception as e:
|
| 139 |
LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
|
| 140 |
-
|
| 141 |
# IMDb failed → fallback to TMDb
|
| 142 |
if not tv_details and not ep_details:
|
| 143 |
use_tmdb = True
|
|
@@ -145,21 +139,21 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 145 |
if not tmdb_result:
|
| 146 |
LOGGER.warning(f"No TMDb result for '{title}'")
|
| 147 |
return None
|
| 148 |
-
|
| 149 |
tv_id = tmdb_result.id
|
| 150 |
try:
|
| 151 |
tv_details = await tmdb.tv(tv_id).details()
|
| 152 |
except Exception as e:
|
| 153 |
LOGGER.warning(f"TMDb TV details failed for {title}: {e}")
|
| 154 |
return None
|
| 155 |
-
|
| 156 |
# Fetch episode safely
|
| 157 |
try:
|
| 158 |
ep_details = await tmdb.episode(tv_id, season, episode).details()
|
| 159 |
except Exception as e:
|
| 160 |
LOGGER.warning(f"TMDb episode not found for {title} S{season}E{episode}: {e}")
|
| 161 |
ep_details = None
|
| 162 |
-
|
| 163 |
# Return TMDb-based data
|
| 164 |
if use_tmdb and tv_details:
|
| 165 |
return {
|
|
@@ -177,18 +171,19 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 177 |
"season_number": season,
|
| 178 |
"episode_number": episode,
|
| 179 |
"episode_title": getattr(ep_details, "name", f"S{season}E{episode}") if ep_details else f"{tv_details.name} S{season}E{episode}",
|
| 180 |
-
"episode_backdrop": format_tmdb_image(getattr(ep_details, "still_path", None), "original") if ep_details else "
|
| 181 |
"quality": quality,
|
| 182 |
"encoded_string": encoded_string,
|
| 183 |
}
|
| 184 |
-
|
| 185 |
# IMDb-based data
|
| 186 |
if not tv_details:
|
| 187 |
LOGGER.warning(f"No valid IMDb data for {title}")
|
| 188 |
return None
|
| 189 |
-
|
| 190 |
imdb_id = tv_details.get("id", "")
|
| 191 |
images = format_imdb_images(imdb_id)
|
|
|
|
| 192 |
return {
|
| 193 |
"tmdb_id": imdb_id.replace("tt", ""),
|
| 194 |
"imdb_id": imdb_id,
|
|
@@ -204,24 +199,23 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 204 |
"season_number": season,
|
| 205 |
"episode_number": episode,
|
| 206 |
"episode_title": ep_details.get("title", f"S{season}E{episode}") if ep_details else f"{tv_details.get('title', title)} S{season}E{episode}",
|
| 207 |
-
"episode_backdrop": ep_details.get("image", "") if ep_details else "
|
| 208 |
"quality": quality,
|
| 209 |
"encoded_string": encoded_string,
|
| 210 |
}
|
| 211 |
|
| 212 |
-
|
| 213 |
# ----------------- Movie Metadata -----------------
|
| 214 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 215 |
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")
|
| 216 |
movie_details, use_tmdb = None, False
|
| 217 |
-
|
| 218 |
# Try IMDb first
|
| 219 |
if imdb_id:
|
| 220 |
try:
|
| 221 |
movie_details = await get_detail(imdb_id=imdb_id)
|
| 222 |
except Exception as e:
|
| 223 |
LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
|
| 224 |
-
|
| 225 |
# IMDb failed → fallback to TMDb
|
| 226 |
if not movie_details:
|
| 227 |
use_tmdb = True
|
|
@@ -229,12 +223,13 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 229 |
if not tmdb_result:
|
| 230 |
LOGGER.warning(f"No TMDb movie found for '{title}'")
|
| 231 |
return None
|
|
|
|
| 232 |
try:
|
| 233 |
movie_details = await tmdb.movie(tmdb_result.id).details()
|
| 234 |
except Exception as e:
|
| 235 |
LOGGER.warning(f"TMDb movie details failed for {title}: {e}")
|
| 236 |
return None
|
| 237 |
-
|
| 238 |
# TMDb result
|
| 239 |
if use_tmdb and movie_details:
|
| 240 |
return {
|
|
@@ -252,10 +247,11 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 252 |
"quality": quality,
|
| 253 |
"encoded_string": encoded_string,
|
| 254 |
}
|
| 255 |
-
|
| 256 |
# IMDb result
|
| 257 |
imdb_id = movie_details.get("id", "")
|
| 258 |
images = format_imdb_images(imdb_id)
|
|
|
|
| 259 |
return {
|
| 260 |
"tmdb_id": imdb_id.replace("tt", ""),
|
| 261 |
"imdb_id": imdb_id,
|
|
|
|
| 2 |
import traceback
|
| 3 |
import PTN
|
| 4 |
from re import compile, IGNORECASE
|
|
|
|
| 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
|
|
|
|
| 15 |
tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
|
| 16 |
|
| 17 |
# ----------------- Helpers -----------------
|
| 18 |
+
def format_tmdb_image(path: str, size="w500") -> str:
|
| 19 |
+
return f"https://image.tmdb.org/t/p/{size}{path}"
|
|
|
|
| 20 |
|
| 21 |
def format_imdb_images(imdb_id: str) -> dict:
|
| 22 |
return {
|
|
|
|
| 25 |
"logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
|
| 26 |
}
|
| 27 |
|
|
|
|
| 28 |
async def safe_imdb_search(title: str, type_: str) -> str | None:
|
| 29 |
"""Safely search IMDb title and return its ID."""
|
| 30 |
try:
|
|
|
|
| 34 |
LOGGER.warning(f"IMDb search failed for '{title}' [{type_}]: {e}")
|
| 35 |
return None
|
| 36 |
|
|
|
|
| 37 |
async def safe_tmdb_search(title: str, type_: str, year=None):
|
| 38 |
"""Safely search TMDb title."""
|
| 39 |
try:
|
|
|
|
| 49 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
| 50 |
return None
|
| 51 |
|
|
|
|
| 52 |
# ----------------- Main Entry -----------------
|
| 53 |
async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
| 54 |
try:
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
|
| 58 |
return None
|
| 59 |
+
|
| 60 |
# Skip combined/invalid files
|
| 61 |
if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
|
| 62 |
LOGGER.info(f"Skipping {filename}: contains 'combined'")
|
| 63 |
return None
|
| 64 |
+
|
| 65 |
# Skip split/multipart files
|
| 66 |
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 67 |
if multipart_pattern.search(filename):
|
| 68 |
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
| 69 |
return None
|
| 70 |
+
|
| 71 |
title = parsed.get("title")
|
| 72 |
season = parsed.get("season")
|
| 73 |
episode = parsed.get("episode")
|
| 74 |
year = parsed.get("year")
|
| 75 |
quality = parsed.get("resolution")
|
| 76 |
+
|
| 77 |
if not quality:
|
| 78 |
LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
|
| 79 |
return None
|
| 80 |
+
|
| 81 |
if isinstance(season, list) or isinstance(episode, list):
|
| 82 |
LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
|
| 83 |
return None
|
| 84 |
+
|
| 85 |
if season and not episode:
|
| 86 |
LOGGER.warning(f"Missing episode in {filename}: {parsed}")
|
| 87 |
return None
|
| 88 |
+
|
| 89 |
# Extract TMDb/IMDb hint
|
| 90 |
default_id = None
|
| 91 |
try:
|
| 92 |
default_id = extract_tmdb_id(Backend.USE_DEFAULT_ID)
|
| 93 |
except Exception:
|
| 94 |
pass
|
| 95 |
+
|
| 96 |
if not default_id:
|
| 97 |
try:
|
| 98 |
default_id = extract_tmdb_id(filename)
|
| 99 |
except Exception:
|
| 100 |
pass
|
| 101 |
+
|
| 102 |
if not title:
|
| 103 |
LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
|
| 104 |
return None
|
| 105 |
+
|
| 106 |
data = {"chat_id": channel, "msg_id": msg_id}
|
| 107 |
encoded_string = await encode_string(data)
|
| 108 |
+
|
| 109 |
try:
|
| 110 |
if season and episode:
|
| 111 |
LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
|
|
|
|
| 117 |
LOGGER.error(f"Error while fetching metadata for {filename}: {e}\n{traceback.format_exc()}")
|
| 118 |
return None
|
| 119 |
|
|
|
|
| 120 |
# ----------------- TV Metadata -----------------
|
| 121 |
async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 122 |
imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(title, "tvSeries")
|
| 123 |
tv_details, ep_details, use_tmdb = None, None, False
|
| 124 |
+
|
| 125 |
# Try IMDb first
|
| 126 |
if imdb_id:
|
| 127 |
try:
|
|
|
|
| 131 |
ep_details = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
|
| 132 |
except Exception as e:
|
| 133 |
LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
|
| 134 |
+
|
| 135 |
# IMDb failed → fallback to TMDb
|
| 136 |
if not tv_details and not ep_details:
|
| 137 |
use_tmdb = True
|
|
|
|
| 139 |
if not tmdb_result:
|
| 140 |
LOGGER.warning(f"No TMDb result for '{title}'")
|
| 141 |
return None
|
| 142 |
+
|
| 143 |
tv_id = tmdb_result.id
|
| 144 |
try:
|
| 145 |
tv_details = await tmdb.tv(tv_id).details()
|
| 146 |
except Exception as e:
|
| 147 |
LOGGER.warning(f"TMDb TV details failed for {title}: {e}")
|
| 148 |
return None
|
| 149 |
+
|
| 150 |
# Fetch episode safely
|
| 151 |
try:
|
| 152 |
ep_details = await tmdb.episode(tv_id, season, episode).details()
|
| 153 |
except Exception as e:
|
| 154 |
LOGGER.warning(f"TMDb episode not found for {title} S{season}E{episode}: {e}")
|
| 155 |
ep_details = None
|
| 156 |
+
|
| 157 |
# Return TMDb-based data
|
| 158 |
if use_tmdb and tv_details:
|
| 159 |
return {
|
|
|
|
| 171 |
"season_number": season,
|
| 172 |
"episode_number": episode,
|
| 173 |
"episode_title": getattr(ep_details, "name", f"S{season}E{episode}") if ep_details else f"{tv_details.name} S{season}E{episode}",
|
| 174 |
+
"episode_backdrop": format_tmdb_image(getattr(ep_details, "still_path", None), "original") if ep_details else "",
|
| 175 |
"quality": quality,
|
| 176 |
"encoded_string": encoded_string,
|
| 177 |
}
|
| 178 |
+
|
| 179 |
# IMDb-based data
|
| 180 |
if not tv_details:
|
| 181 |
LOGGER.warning(f"No valid IMDb data for {title}")
|
| 182 |
return None
|
| 183 |
+
|
| 184 |
imdb_id = tv_details.get("id", "")
|
| 185 |
images = format_imdb_images(imdb_id)
|
| 186 |
+
|
| 187 |
return {
|
| 188 |
"tmdb_id": imdb_id.replace("tt", ""),
|
| 189 |
"imdb_id": imdb_id,
|
|
|
|
| 199 |
"season_number": season,
|
| 200 |
"episode_number": episode,
|
| 201 |
"episode_title": ep_details.get("title", f"S{season}E{episode}") if ep_details else f"{tv_details.get('title', title)} S{season}E{episode}",
|
| 202 |
+
"episode_backdrop": ep_details.get("image", "") if ep_details else "",
|
| 203 |
"quality": quality,
|
| 204 |
"encoded_string": encoded_string,
|
| 205 |
}
|
| 206 |
|
|
|
|
| 207 |
# ----------------- Movie Metadata -----------------
|
| 208 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 209 |
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")
|
| 210 |
movie_details, use_tmdb = None, False
|
| 211 |
+
|
| 212 |
# Try IMDb first
|
| 213 |
if imdb_id:
|
| 214 |
try:
|
| 215 |
movie_details = await get_detail(imdb_id=imdb_id)
|
| 216 |
except Exception as e:
|
| 217 |
LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
|
| 218 |
+
|
| 219 |
# IMDb failed → fallback to TMDb
|
| 220 |
if not movie_details:
|
| 221 |
use_tmdb = True
|
|
|
|
| 223 |
if not tmdb_result:
|
| 224 |
LOGGER.warning(f"No TMDb movie found for '{title}'")
|
| 225 |
return None
|
| 226 |
+
|
| 227 |
try:
|
| 228 |
movie_details = await tmdb.movie(tmdb_result.id).details()
|
| 229 |
except Exception as e:
|
| 230 |
LOGGER.warning(f"TMDb movie details failed for {title}: {e}")
|
| 231 |
return None
|
| 232 |
+
|
| 233 |
# TMDb result
|
| 234 |
if use_tmdb and movie_details:
|
| 235 |
return {
|
|
|
|
| 247 |
"quality": quality,
|
| 248 |
"encoded_string": encoded_string,
|
| 249 |
}
|
| 250 |
+
|
| 251 |
# IMDb result
|
| 252 |
imdb_id = movie_details.get("id", "")
|
| 253 |
images = format_imdb_images(imdb_id)
|
| 254 |
+
|
| 255 |
return {
|
| 256 |
"tmdb_id": imdb_id.replace("tt", ""),
|
| 257 |
"imdb_id": imdb_id,
|
README.md
CHANGED
|
@@ -298,6 +298,9 @@ Follow the instructions provided in the Google Colab Tool to deploy on Heroku.
|
|
| 298 |
|
| 299 |
## 🐳 VPS Guide
|
| 300 |
|
|
|
|
|
|
|
|
|
|
| 301 |
### 1️⃣ Step 1: Clone & Configure the Project
|
| 302 |
|
| 303 |
```bash
|
|
@@ -307,32 +310,83 @@ mv sample_config.env config.env
|
|
| 307 |
nano config.env
|
| 308 |
```
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
```bash
|
| 316 |
-
docker
|
| 317 |
-
docker run -d -p 8000:8000 tsms
|
| 318 |
```
|
| 319 |
|
| 320 |
-
Your
|
| 321 |
➡️ `http://<your-vps-ip>:8000`
|
| 322 |
|
| 323 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
-
|
| 326 |
|
| 327 |
-
#### A. Set Up DNS Records
|
| 328 |
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
| Type | Name | Value |
|
| 332 |
-
|----
|
| 333 |
| A | @ | `195.xxx.xxx.xxx` |
|
| 334 |
|
| 335 |
-
|
|
|
|
| 336 |
|
| 337 |
```bash
|
| 338 |
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
|
|
@@ -344,35 +398,34 @@ sudo apt update
|
|
| 344 |
sudo apt install caddy
|
| 345 |
```
|
| 346 |
|
| 347 |
-
####
|
| 348 |
|
| 349 |
-
1.
|
| 350 |
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
|
| 355 |
-
|
| 356 |
-
- Replace `domain.com` with your actual domain
|
| 357 |
-
- If you changed PORT in config.env from the default 8000, update the port accordingly
|
| 358 |
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
|
| 365 |
-
|
|
|
|
| 366 |
|
| 367 |
-
|
| 368 |
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
|
| 373 |
|
| 374 |
-
Your API
|
| 375 |
-
➡️ `https://domain.com`
|
| 376 |
|
| 377 |
|
| 378 |
# 📺 Setting up Stremio
|
|
|
|
| 298 |
|
| 299 |
## 🐳 VPS Guide
|
| 300 |
|
| 301 |
+
This section explains how to deploy your **Telegram Stremio Media Server** on a VPS using **Docker Compose (recommended)** or **Docker**.
|
| 302 |
+
|
| 303 |
+
|
| 304 |
### 1️⃣ Step 1: Clone & Configure the Project
|
| 305 |
|
| 306 |
```bash
|
|
|
|
| 310 |
nano config.env
|
| 311 |
```
|
| 312 |
|
| 313 |
+
* Fill in all required variables in `config.env`.
|
| 314 |
+
* Press `Ctrl + O`, then `Enter`, then `Ctrl + X` to save and exit.
|
| 315 |
+
|
| 316 |
+
## ⚙️ Step 2: Choose Your Deployment Method
|
| 317 |
+
|
| 318 |
+
You can deploy the server using either **Docker Compose (recommended)** or **plain Docker**.
|
| 319 |
+
|
| 320 |
|
| 321 |
+
|
| 322 |
+
### 🟢 **Option 1: Deploy with Docker Compose (Recommended)**
|
| 323 |
+
|
| 324 |
+
Docker Compose provides an easier and more maintainable setup, environment mounting, and restart policies.
|
| 325 |
+
|
| 326 |
+
#### 🚀 Start the Container
|
| 327 |
|
| 328 |
```bash
|
| 329 |
+
docker compose up -d
|
|
|
|
| 330 |
```
|
| 331 |
|
| 332 |
+
Your server will now be running at:
|
| 333 |
➡️ `http://<your-vps-ip>:8000`
|
| 334 |
|
| 335 |
+
---
|
| 336 |
+
|
| 337 |
+
#### 🛠️ Update `config.env` While Running
|
| 338 |
+
|
| 339 |
+
If you need to modify environment values (like `BASE_URL`, `AUTH_CHANNEL`, etc.):
|
| 340 |
+
|
| 341 |
+
1. **Edit the file:**
|
| 342 |
+
|
| 343 |
+
```bash
|
| 344 |
+
nano config.env
|
| 345 |
+
```
|
| 346 |
+
2. **Save your changes:** (`Ctrl + O`, `Enter`, `Ctrl + X`)
|
| 347 |
+
3. **Restart the container to apply updates:**
|
| 348 |
+
|
| 349 |
+
```bash
|
| 350 |
+
docker compose restart
|
| 351 |
+
```
|
| 352 |
|
| 353 |
+
⚡ Since the config file is mounted, you **don’t need to rebuild** the image — changes apply automatically on restart.
|
| 354 |
|
|
|
|
| 355 |
|
| 356 |
+
|
| 357 |
+
### 🔵 **Option 2: Deploy with Docker (Manual Method)**
|
| 358 |
+
|
| 359 |
+
If you prefer not to use Docker Compose, you can manually build and run the container.
|
| 360 |
+
|
| 361 |
+
#### 🧩 Build the Image
|
| 362 |
+
|
| 363 |
+
```bash
|
| 364 |
+
docker build -t telegram-stremio .
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
#### 🚀 Run the Container
|
| 368 |
+
|
| 369 |
+
```bash
|
| 370 |
+
docker run -d -p 8000:8000 telegram-stremio
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
Your server should now be running at:
|
| 374 |
+
➡️ `http://<your-vps-ip>:8000`
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
### 🌐 Step 3: Add Domain (Required)
|
| 379 |
+
|
| 380 |
+
#### 🅰️ Set Up DNS Records
|
| 381 |
+
|
| 382 |
+
Go to your domain registrar and add an **A record** pointing to your VPS IP:
|
| 383 |
|
| 384 |
| Type | Name | Value |
|
| 385 |
+
| ---- | ---- | ----------------- |
|
| 386 |
| A | @ | `195.xxx.xxx.xxx` |
|
| 387 |
|
| 388 |
+
|
| 389 |
+
#### 🧱 Install Caddy (for HTTPS + Reverse Proxy)
|
| 390 |
|
| 391 |
```bash
|
| 392 |
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
|
|
|
|
| 398 |
sudo apt install caddy
|
| 399 |
```
|
| 400 |
|
| 401 |
+
#### ⚙️ Configure Caddy
|
| 402 |
|
| 403 |
+
1. **Edit the Caddyfile:**
|
| 404 |
|
| 405 |
+
```bash
|
| 406 |
+
sudo nano /etc/caddy/Caddyfile
|
| 407 |
+
```
|
| 408 |
|
| 409 |
+
2. **Replace contents with:**
|
|
|
|
|
|
|
| 410 |
|
| 411 |
+
```caddy
|
| 412 |
+
your-domain.com {
|
| 413 |
+
reverse_proxy localhost:8000
|
| 414 |
+
}
|
| 415 |
+
```
|
| 416 |
|
| 417 |
+
* Replace `your-domain.com` with your actual domain name.
|
| 418 |
+
* Adjust the port if you changed it in `config.env`.
|
| 419 |
|
| 420 |
+
3. **Save and reload Caddy:**
|
| 421 |
|
| 422 |
+
```bash
|
| 423 |
+
sudo systemctl reload caddy
|
| 424 |
+
```
|
| 425 |
|
| 426 |
|
| 427 |
+
✅ Your API will now be available securely at:
|
| 428 |
+
➡️ `https://your-domain.com`
|
| 429 |
|
| 430 |
|
| 431 |
# 📺 Setting up Stremio
|
docker-compose.yaml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
telegram-stremio:
|
| 3 |
+
build: .
|
| 4 |
+
ports:
|
| 5 |
+
- "8000:8000"
|
| 6 |
+
volumes:
|
| 7 |
+
- ./config.env:/app/config.env
|
| 8 |
+
restart: unless-stopped
|
pyproject.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
-
version = "1.
|
| 4 |
description = "A powerful, self-hosted Telegram Stremio Media Server built with FastAPI, MongoDB, and PyroFork seamlessly integrated with Stremio for automated media streaming and discovery."
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
+
version = "1.2.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"
|
uv.lock
CHANGED
|
@@ -901,7 +901,7 @@ wheels = [
|
|
| 901 |
|
| 902 |
[[package]]
|
| 903 |
name = "telegram-stremio"
|
| 904 |
-
version = "1.1.
|
| 905 |
source = { virtual = "." }
|
| 906 |
dependencies = [
|
| 907 |
{ name = "aiofiles" },
|
|
|
|
| 901 |
|
| 902 |
[[package]]
|
| 903 |
name = "telegram-stremio"
|
| 904 |
+
version = "1.1.2"
|
| 905 |
source = { virtual = "." }
|
| 906 |
dependencies = [
|
| 907 |
{ name = "aiofiles" },
|