weebzone commited on
Commit ·
2928c2f
1
Parent(s): 4a67ae0
`v-1.4.1 — Enhanced Metadata Fixer`
Browse files- Full metadata update for movies & TV shows
- Episode overview/release/backdrop support
- Added concurrency, progress bar & cancel option
- Improved skipping logic + stability fixes
⚠️ Run /fixmetadata after update
- Backend/__init__.py +1 -1
- Backend/helper/imdb.py +101 -82
- Backend/helper/metadata.py +144 -69
- Backend/pyrofork/plugins/fix_metadata.py +172 -120
- 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.4.
|
|
|
|
| 11 |
USE_DEFAULT_ID: str = None
|
| 12 |
db = Database()
|
| 13 |
|
| 14 |
+
__version__ = "1.4.1"
|
Backend/helper/imdb.py
CHANGED
|
@@ -1,9 +1,22 @@
|
|
| 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
|
|
@@ -15,92 +28,98 @@ def extract_first_year(year_string) -> int:
|
|
| 15 |
|
| 16 |
|
| 17 |
async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 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 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import httpx
|
| 2 |
import re
|
| 3 |
+
import asyncio
|
| 4 |
from typing import Optional, Dict, Any
|
| 5 |
|
| 6 |
BASE_URL = "https://v3-cinemeta.strem.io"
|
| 7 |
|
| 8 |
+
_client: Optional[httpx.AsyncClient] = None
|
| 9 |
+
_client_lock = asyncio.Lock()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def _get_client() -> httpx.AsyncClient:
|
| 13 |
+
global _client
|
| 14 |
+
async with _client_lock:
|
| 15 |
+
if _client is None or _client.is_closed:
|
| 16 |
+
_client = httpx.AsyncClient(timeout=15.0)
|
| 17 |
+
return _client
|
| 18 |
+
|
| 19 |
+
|
| 20 |
def extract_first_year(year_string) -> int:
|
| 21 |
if not year_string:
|
| 22 |
return 0
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
async def search_title(query: str, type: str) -> Optional[Dict[str, Any]]:
|
| 31 |
+
"""
|
| 32 |
+
Query Cinemeta search endpoint for a title.
|
| 33 |
+
type = 'tvSeries' or 'movie' (your code uses 'tvSeries' for TV)
|
| 34 |
+
"""
|
| 35 |
+
client = await _get_client()
|
| 36 |
+
cinemeta_type = "series" if type == "tvSeries" else type
|
| 37 |
+
url = f"{BASE_URL}/catalog/{cinemeta_type}/imdb/search={query}.json"
|
| 38 |
+
try:
|
| 39 |
+
resp = await client.get(url)
|
| 40 |
+
if resp.status_code != 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
return None
|
| 42 |
+
data = resp.json()
|
| 43 |
+
if data and 'metas' in data and data['metas']:
|
| 44 |
+
meta = data['metas'][0]
|
| 45 |
+
return {
|
| 46 |
+
'id': meta.get('imdb_id', meta.get('id', '')),
|
| 47 |
+
'type': type,
|
| 48 |
+
'title': meta.get('name', ''),
|
| 49 |
+
'year': meta.get('releaseInfo', ''),
|
| 50 |
+
'poster': meta.get('poster', '')
|
| 51 |
+
}
|
| 52 |
+
return None
|
| 53 |
+
except Exception:
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
|
| 57 |
async def get_detail(imdb_id: str) -> Optional[Dict[str, Any]]:
|
| 58 |
+
"""
|
| 59 |
+
Fetch meta details for given imdb_id from Cinemeta.
|
| 60 |
+
Tries /meta/movie/ID and /meta/series/ID (caller expects type inference).
|
| 61 |
+
"""
|
| 62 |
+
client = await _get_client()
|
| 63 |
+
for media_type in ['movie', 'series']:
|
| 64 |
+
try:
|
| 65 |
+
url = f"{BASE_URL}/meta/{media_type}/{imdb_id}.json"
|
| 66 |
+
resp = await client.get(url)
|
| 67 |
+
if resp.status_code != 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
continue
|
| 69 |
+
data = resp.json()
|
| 70 |
+
if 'meta' not in data:
|
| 71 |
+
continue
|
| 72 |
+
meta = data['meta']
|
| 73 |
+
year_value = 0
|
| 74 |
+
for year_field in ['year', 'releaseInfo', 'released']:
|
| 75 |
+
if meta.get(year_field):
|
| 76 |
+
year_value = extract_first_year(meta[year_field])
|
| 77 |
+
if year_value > 0:
|
| 78 |
+
break
|
| 79 |
+
return {
|
| 80 |
+
'id': meta.get('imdb_id', meta.get('id', '')),
|
| 81 |
+
'type': meta.get('type', media_type),
|
| 82 |
+
'title': meta.get('name', ''),
|
| 83 |
+
'plot': meta.get('description', ''),
|
| 84 |
+
'genre': meta.get('genres', []) or meta.get('genre', []),
|
| 85 |
+
'releaseDetailed': {'year': year_value},
|
| 86 |
+
'rating': {'star': float(meta.get('imdbRating', '0')) if meta.get('imdbRating') else 0},
|
| 87 |
+
'poster': meta.get('poster', ''),
|
| 88 |
+
'background': meta.get('background', ''),
|
| 89 |
+
'logo': meta.get('logo', ''),
|
| 90 |
+
'runtime': meta.get('runtime', ''),
|
| 91 |
+
'director': meta.get('director', []),
|
| 92 |
+
'cast': meta.get('cast', []),
|
| 93 |
+
'videos': meta.get('videos', [])
|
| 94 |
+
}
|
| 95 |
+
except Exception:
|
| 96 |
+
continue
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
|
| 100 |
async def get_season(imdb_id: str, season_id: int, episode_id: int) -> Optional[Dict[str, Any]]:
|
| 101 |
+
"""
|
| 102 |
+
Return episode meta for a specific season/episode using Cinemeta series endpoint.
|
| 103 |
+
"""
|
| 104 |
+
client = await _get_client()
|
| 105 |
+
try:
|
| 106 |
+
url = f"{BASE_URL}/meta/series/{imdb_id}.json"
|
| 107 |
+
resp = await client.get(url)
|
| 108 |
+
if resp.status_code != 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
return None
|
| 110 |
+
data = resp.json()
|
| 111 |
+
if 'meta' in data and 'videos' in data['meta']:
|
| 112 |
+
for video in data['meta']['videos']:
|
| 113 |
+
if (str(video.get('season', '')) == str(season_id) and
|
| 114 |
+
str(video.get('episode', '')) == str(episode_id)):
|
| 115 |
+
return {
|
| 116 |
+
'title': video.get('title', f'Episode {episode_id}'),
|
| 117 |
+
'no': str(episode_id),
|
| 118 |
+
'season': str(season_id),
|
| 119 |
+
'image': video.get('thumbnail', ''),
|
| 120 |
+
'plot': video.get('overview', ''),
|
| 121 |
+
'released': video.get('released', '')
|
| 122 |
+
}
|
| 123 |
+
return None
|
| 124 |
+
except Exception:
|
| 125 |
+
return None
|
Backend/helper/metadata.py
CHANGED
|
@@ -11,14 +11,27 @@ from Backend.logger import LOGGER
|
|
| 11 |
from Backend.helper.encrypt import encode_string
|
| 12 |
|
| 13 |
# ----------------- Configuration -----------------
|
| 14 |
-
DELAY =
|
| 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 {
|
| 23 |
"poster": f"https://images.metahub.space/poster/small/{imdb_id}/img",
|
| 24 |
"backdrop": f"https://images.metahub.space/background/medium/{imdb_id}/img",
|
|
@@ -26,27 +39,79 @@ def format_imdb_images(imdb_id: str) -> dict:
|
|
| 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:
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 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:
|
| 40 |
-
|
| 41 |
-
if
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
else:
|
| 44 |
-
results = await tmdb.search().
|
| 45 |
-
else
|
| 46 |
-
|
| 47 |
-
return
|
| 48 |
except Exception as e:
|
| 49 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return None
|
| 51 |
|
| 52 |
# ----------------- Main Entry -----------------
|
|
@@ -56,56 +121,59 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
|
| 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 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
try:
|
| 110 |
if season and episode:
|
| 111 |
LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
|
|
@@ -121,40 +189,43 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
|
|
| 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:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
|
| 134 |
-
|
| 135 |
-
# IMDb failed
|
| 136 |
-
if not tv_details
|
| 137 |
use_tmdb = True
|
| 138 |
tmdb_result = await safe_tmdb_search(title, "tv")
|
| 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 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
LOGGER.warning(f"TMDb TV details failed for {title}: {e}")
|
| 148 |
return None
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 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 |
credits = getattr(tv_details, "credits", None) or {}
|
| 160 |
cast_names = []
|
|
@@ -164,12 +235,12 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 164 |
name = getattr(member, "name", None) or getattr(member, "original_name", None)
|
| 165 |
if name:
|
| 166 |
cast_names.append(name)
|
| 167 |
-
|
| 168 |
return {
|
| 169 |
"tmdb_id": tv_details.id,
|
| 170 |
-
"imdb_id": tv_details
|
| 171 |
"title": tv_details.name,
|
| 172 |
-
"year": getattr(tv_details.first_air_date, "year", 0),
|
| 173 |
"rate": getattr(tv_details, "vote_average", 0) or 0,
|
| 174 |
"description": tv_details.overview or "",
|
| 175 |
"poster": format_tmdb_image(tv_details.poster_path),
|
|
@@ -187,17 +258,16 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 187 |
"quality": quality,
|
| 188 |
"encoded_string": encoded_string,
|
| 189 |
}
|
| 190 |
-
|
| 191 |
-
# IMDb-based data
|
| 192 |
if not tv_details:
|
| 193 |
LOGGER.warning(f"No valid IMDb data for {title}")
|
| 194 |
return None
|
| 195 |
-
|
| 196 |
imdb_id = tv_details.get("id", "")
|
| 197 |
images = format_imdb_images(imdb_id)
|
| 198 |
-
|
| 199 |
return {
|
| 200 |
-
"tmdb_id": imdb_id.replace("tt", ""),
|
| 201 |
"imdb_id": imdb_id,
|
| 202 |
"title": tv_details.get("title", title),
|
| 203 |
"year": tv_details.get("releaseDetailed", {}).get("year", 0),
|
|
@@ -223,29 +293,34 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
|
|
| 223 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 224 |
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")
|
| 225 |
movie_details, use_tmdb = None, False
|
| 226 |
-
|
| 227 |
# Try IMDb first
|
| 228 |
if imdb_id:
|
| 229 |
try:
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
except Exception as e:
|
| 232 |
LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
|
| 233 |
-
|
| 234 |
-
#
|
| 235 |
if not movie_details:
|
| 236 |
use_tmdb = True
|
| 237 |
tmdb_result = await safe_tmdb_search(title, "movie", year)
|
| 238 |
if not tmdb_result:
|
| 239 |
LOGGER.warning(f"No TMDb movie found for '{title}'")
|
| 240 |
return None
|
| 241 |
-
|
| 242 |
try:
|
| 243 |
-
movie_details = await
|
| 244 |
except Exception as e:
|
| 245 |
LOGGER.warning(f"TMDb movie details failed for {title}: {e}")
|
| 246 |
return None
|
| 247 |
-
|
| 248 |
-
# TMDb result
|
| 249 |
if use_tmdb and movie_details:
|
| 250 |
credits = getattr(movie_details, "credits", None) or {}
|
| 251 |
cast_names = []
|
|
@@ -257,9 +332,9 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 257 |
cast_names.append(name)
|
| 258 |
return {
|
| 259 |
"tmdb_id": movie_details.id,
|
| 260 |
-
"imdb_id": movie_details.external_ids.imdb_id,
|
| 261 |
"title": movie_details.title,
|
| 262 |
-
"year": getattr(movie_details.release_date, "year", 0),
|
| 263 |
"rate": getattr(movie_details, "vote_average", 0) or 0,
|
| 264 |
"description": movie_details.overview or "",
|
| 265 |
"poster": format_tmdb_image(movie_details.poster_path),
|
|
@@ -271,13 +346,13 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
|
|
| 271 |
"quality": quality,
|
| 272 |
"encoded_string": encoded_string,
|
| 273 |
}
|
| 274 |
-
|
| 275 |
-
# IMDb result
|
| 276 |
imdb_id = movie_details.get("id", "")
|
| 277 |
images = format_imdb_images(imdb_id)
|
| 278 |
-
|
| 279 |
return {
|
| 280 |
-
"tmdb_id": imdb_id.replace("tt", ""),
|
| 281 |
"imdb_id": imdb_id,
|
| 282 |
"title": movie_details.get("title", title),
|
| 283 |
"year": movie_details.get("releaseDetailed", {}).get("year", 0),
|
|
|
|
| 11 |
from Backend.helper.encrypt import encode_string
|
| 12 |
|
| 13 |
# ----------------- Configuration -----------------
|
| 14 |
+
DELAY = 0
|
| 15 |
tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
|
| 16 |
|
| 17 |
+
# Cache dictionaries (per run)
|
| 18 |
+
IMDB_CACHE: dict = {}
|
| 19 |
+
TMDB_SEARCH_CACHE: dict = {}
|
| 20 |
+
TMDB_DETAILS_CACHE: dict = {}
|
| 21 |
+
EPISODE_CACHE: dict = {}
|
| 22 |
+
|
| 23 |
+
# Concurrency semaphore for external API calls
|
| 24 |
+
API_SEMAPHORE = asyncio.Semaphore(12)
|
| 25 |
+
|
| 26 |
# ----------------- Helpers -----------------
|
| 27 |
def format_tmdb_image(path: str, size="w500") -> str:
|
| 28 |
+
if not path:
|
| 29 |
+
return ""
|
| 30 |
return f"https://image.tmdb.org/t/p/{size}{path}"
|
| 31 |
|
| 32 |
def format_imdb_images(imdb_id: str) -> dict:
|
| 33 |
+
if not imdb_id:
|
| 34 |
+
return {"poster": "", "backdrop": "", "logo": ""}
|
| 35 |
return {
|
| 36 |
"poster": f"https://images.metahub.space/poster/small/{imdb_id}/img",
|
| 37 |
"backdrop": f"https://images.metahub.space/background/medium/{imdb_id}/img",
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
async def safe_imdb_search(title: str, type_: str) -> str | None:
|
| 42 |
+
"""Safely search IMDb title and return its ID, with simple caching."""
|
| 43 |
+
key = f"imdb::{type_}::{title}"
|
| 44 |
+
if key in IMDB_CACHE:
|
| 45 |
+
return IMDB_CACHE[key]
|
| 46 |
try:
|
| 47 |
+
async with API_SEMAPHORE:
|
| 48 |
+
result = await search_title(query=title, type=type_)
|
| 49 |
+
imdb_id = result["id"] if result else None
|
| 50 |
+
IMDB_CACHE[key] = imdb_id
|
| 51 |
+
return imdb_id
|
| 52 |
except Exception as e:
|
| 53 |
LOGGER.warning(f"IMDb search failed for '{title}' [{type_}]: {e}")
|
| 54 |
return None
|
| 55 |
|
| 56 |
async def safe_tmdb_search(title: str, type_: str, year=None):
|
| 57 |
+
"""Safely search TMDb title with caching."""
|
| 58 |
+
key = f"tmdb_search::{type_}::{title}::{year}"
|
| 59 |
+
if key in TMDB_SEARCH_CACHE:
|
| 60 |
+
return TMDB_SEARCH_CACHE[key]
|
| 61 |
try:
|
| 62 |
+
async with API_SEMAPHORE:
|
| 63 |
+
if type_ == "movie":
|
| 64 |
+
if year:
|
| 65 |
+
results = await tmdb.search().movies(query=title, year=year)
|
| 66 |
+
else:
|
| 67 |
+
results = await tmdb.search().movies(query=title)
|
| 68 |
else:
|
| 69 |
+
results = await tmdb.search().tv(query=title)
|
| 70 |
+
res = results[0] if results else None
|
| 71 |
+
TMDB_SEARCH_CACHE[key] = res
|
| 72 |
+
return res
|
| 73 |
except Exception as e:
|
| 74 |
LOGGER.error(f"TMDb search failed for '{title}' [{type_}]: {e}")
|
| 75 |
+
TMDB_SEARCH_CACHE[key] = None
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
async def _tmdb_tv_details(tv_id):
|
| 79 |
+
if tv_id in TMDB_DETAILS_CACHE:
|
| 80 |
+
return TMDB_DETAILS_CACHE[tv_id]
|
| 81 |
+
try:
|
| 82 |
+
async with API_SEMAPHORE:
|
| 83 |
+
details = await tmdb.tv(tv_id).details(append_to_response="external_ids,credits")
|
| 84 |
+
TMDB_DETAILS_CACHE[tv_id] = details
|
| 85 |
+
return details
|
| 86 |
+
except Exception as e:
|
| 87 |
+
LOGGER.warning(f"TMDb tv details fetch failed for id={tv_id}: {e}")
|
| 88 |
+
TMDB_DETAILS_CACHE[tv_id] = None
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
async def _tmdb_movie_details(movie_id):
|
| 92 |
+
if movie_id in TMDB_DETAILS_CACHE:
|
| 93 |
+
return TMDB_DETAILS_CACHE[movie_id]
|
| 94 |
+
try:
|
| 95 |
+
async with API_SEMAPHORE:
|
| 96 |
+
details = await tmdb.movie(movie_id).details(append_to_response="external_ids,credits")
|
| 97 |
+
TMDB_DETAILS_CACHE[movie_id] = details
|
| 98 |
+
return details
|
| 99 |
+
except Exception as e:
|
| 100 |
+
LOGGER.warning(f"TMDb movie details fetch failed for id={movie_id}: {e}")
|
| 101 |
+
TMDB_DETAILS_CACHE[movie_id] = None
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
async def _tmdb_episode_details(tv_id, season, episode):
|
| 105 |
+
key = (tv_id, season, episode)
|
| 106 |
+
if key in EPISODE_CACHE:
|
| 107 |
+
return EPISODE_CACHE[key]
|
| 108 |
+
try:
|
| 109 |
+
async with API_SEMAPHORE:
|
| 110 |
+
details = await tmdb.episode(tv_id, season, episode).details()
|
| 111 |
+
EPISODE_CACHE[key] = details
|
| 112 |
+
return details
|
| 113 |
+
except Exception:
|
| 114 |
+
EPISODE_CACHE[key] = None
|
| 115 |
return None
|
| 116 |
|
| 117 |
# ----------------- Main Entry -----------------
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
LOGGER.error(f"PTN parsing failed for {filename}: {e}\n{traceback.format_exc()}")
|
| 123 |
return None
|
| 124 |
+
|
| 125 |
# Skip combined/invalid files
|
| 126 |
if "excess" in parsed and any("combined" in item.lower() for item in parsed["excess"]):
|
| 127 |
LOGGER.info(f"Skipping {filename}: contains 'combined'")
|
| 128 |
return None
|
| 129 |
+
|
| 130 |
# Skip split/multipart files
|
| 131 |
multipart_pattern = compile(r'(?:part|cd|disc|disk)[s._-]*\d+(?=\.\w+$)', IGNORECASE)
|
| 132 |
if multipart_pattern.search(filename):
|
| 133 |
LOGGER.info(f"Skipping {filename}: seems to be a split/multipart file")
|
| 134 |
return None
|
| 135 |
+
|
| 136 |
title = parsed.get("title")
|
| 137 |
season = parsed.get("season")
|
| 138 |
episode = parsed.get("episode")
|
| 139 |
year = parsed.get("year")
|
| 140 |
quality = parsed.get("resolution")
|
| 141 |
+
|
| 142 |
if not quality:
|
| 143 |
LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
|
| 144 |
return None
|
| 145 |
+
|
| 146 |
if isinstance(season, list) or isinstance(episode, list):
|
| 147 |
LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
|
| 148 |
return None
|
| 149 |
+
|
| 150 |
if season and not episode:
|
| 151 |
LOGGER.warning(f"Missing episode in {filename}: {parsed}")
|
| 152 |
return None
|
| 153 |
+
|
| 154 |
# Extract TMDb/IMDb hint
|
| 155 |
default_id = None
|
| 156 |
try:
|
| 157 |
default_id = extract_tmdb_id(Backend.USE_DEFAULT_ID)
|
| 158 |
except Exception:
|
| 159 |
pass
|
| 160 |
+
|
| 161 |
if not default_id:
|
| 162 |
try:
|
| 163 |
default_id = extract_tmdb_id(filename)
|
| 164 |
except Exception:
|
| 165 |
pass
|
| 166 |
+
|
| 167 |
if not title:
|
| 168 |
LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
|
| 169 |
return None
|
| 170 |
+
|
| 171 |
data = {"chat_id": channel, "msg_id": msg_id}
|
| 172 |
+
try:
|
| 173 |
+
encoded_string = await encode_string(data)
|
| 174 |
+
except Exception:
|
| 175 |
+
encoded_string = None
|
| 176 |
+
|
| 177 |
try:
|
| 178 |
if season and episode:
|
| 179 |
LOGGER.info(f"Fetching TV metadata: {title} S{season}E{episode}")
|
|
|
|
| 189 |
async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 190 |
imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(title, "tvSeries")
|
| 191 |
tv_details, ep_details, use_tmdb = None, None, False
|
| 192 |
+
|
| 193 |
+
# Try IMDb (cinemeta) first if imdb_id present
|
| 194 |
if imdb_id:
|
| 195 |
try:
|
| 196 |
+
if imdb_id in IMDB_CACHE:
|
| 197 |
+
tv_details = IMDB_CACHE[imdb_id]
|
| 198 |
+
else:
|
| 199 |
+
async with API_SEMAPHORE:
|
| 200 |
+
tv_details = await get_detail(imdb_id=imdb_id)
|
| 201 |
+
IMDB_CACHE[imdb_id] = tv_details
|
| 202 |
+
cache_key = f"{imdb_id}::{season}::{episode}"
|
| 203 |
+
if cache_key in EPISODE_CACHE:
|
| 204 |
+
ep_details = EPISODE_CACHE[cache_key]
|
| 205 |
+
else:
|
| 206 |
+
async with API_SEMAPHORE:
|
| 207 |
+
ep_details = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
|
| 208 |
+
EPISODE_CACHE[cache_key] = ep_details
|
| 209 |
except Exception as e:
|
| 210 |
LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
|
| 211 |
+
|
| 212 |
+
# If IMDb failed, fallback to TMDb
|
| 213 |
+
if not tv_details:
|
| 214 |
use_tmdb = True
|
| 215 |
tmdb_result = await safe_tmdb_search(title, "tv")
|
| 216 |
if not tmdb_result:
|
| 217 |
LOGGER.warning(f"No TMDb result for '{title}'")
|
| 218 |
return None
|
| 219 |
+
|
| 220 |
tv_id = tmdb_result.id
|
| 221 |
+
tv_details = await _tmdb_tv_details(tv_id)
|
| 222 |
+
if not tv_details:
|
| 223 |
+
LOGGER.warning(f"TMDb TV details fetch failed for '{title}' (id={tv_id})")
|
|
|
|
| 224 |
return None
|
| 225 |
+
|
| 226 |
+
ep_details = await _tmdb_episode_details(tv_id, season, episode)
|
| 227 |
+
|
| 228 |
+
# TMDb-based return path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
if use_tmdb and tv_details:
|
| 230 |
credits = getattr(tv_details, "credits", None) or {}
|
| 231 |
cast_names = []
|
|
|
|
| 235 |
name = getattr(member, "name", None) or getattr(member, "original_name", None)
|
| 236 |
if name:
|
| 237 |
cast_names.append(name)
|
| 238 |
+
|
| 239 |
return {
|
| 240 |
"tmdb_id": tv_details.id,
|
| 241 |
+
"imdb_id": getattr(tv_details, "external_ids", {}).imdb_id if getattr(tv_details, "external_ids", None) else getattr(tv_details, "imdb_id", None),
|
| 242 |
"title": tv_details.name,
|
| 243 |
+
"year": getattr(tv_details.first_air_date, "year", 0) if getattr(tv_details, "first_air_date", None) else 0,
|
| 244 |
"rate": getattr(tv_details, "vote_average", 0) or 0,
|
| 245 |
"description": tv_details.overview or "",
|
| 246 |
"poster": format_tmdb_image(tv_details.poster_path),
|
|
|
|
| 258 |
"quality": quality,
|
| 259 |
"encoded_string": encoded_string,
|
| 260 |
}
|
| 261 |
+
|
|
|
|
| 262 |
if not tv_details:
|
| 263 |
LOGGER.warning(f"No valid IMDb data for {title}")
|
| 264 |
return None
|
| 265 |
+
|
| 266 |
imdb_id = tv_details.get("id", "")
|
| 267 |
images = format_imdb_images(imdb_id)
|
| 268 |
+
|
| 269 |
return {
|
| 270 |
+
"tmdb_id": imdb_id.replace("tt", "") if imdb_id else "",
|
| 271 |
"imdb_id": imdb_id,
|
| 272 |
"title": tv_details.get("title", title),
|
| 273 |
"year": tv_details.get("releaseDetailed", {}).get("year", 0),
|
|
|
|
| 293 |
async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
|
| 294 |
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")
|
| 295 |
movie_details, use_tmdb = None, False
|
| 296 |
+
|
| 297 |
# Try IMDb first
|
| 298 |
if imdb_id:
|
| 299 |
try:
|
| 300 |
+
if imdb_id in IMDB_CACHE:
|
| 301 |
+
movie_details = IMDB_CACHE[imdb_id]
|
| 302 |
+
else:
|
| 303 |
+
async with API_SEMAPHORE:
|
| 304 |
+
movie_details = await get_detail(imdb_id=imdb_id)
|
| 305 |
+
IMDB_CACHE[imdb_id] = movie_details
|
| 306 |
except Exception as e:
|
| 307 |
LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
|
| 308 |
+
|
| 309 |
+
# Fallback to TMDb
|
| 310 |
if not movie_details:
|
| 311 |
use_tmdb = True
|
| 312 |
tmdb_result = await safe_tmdb_search(title, "movie", year)
|
| 313 |
if not tmdb_result:
|
| 314 |
LOGGER.warning(f"No TMDb movie found for '{title}'")
|
| 315 |
return None
|
| 316 |
+
|
| 317 |
try:
|
| 318 |
+
movie_details = await _tmdb_movie_details(tmdb_result.id)
|
| 319 |
except Exception as e:
|
| 320 |
LOGGER.warning(f"TMDb movie details failed for {title}: {e}")
|
| 321 |
return None
|
| 322 |
+
|
| 323 |
+
# TMDb result return
|
| 324 |
if use_tmdb and movie_details:
|
| 325 |
credits = getattr(movie_details, "credits", None) or {}
|
| 326 |
cast_names = []
|
|
|
|
| 332 |
cast_names.append(name)
|
| 333 |
return {
|
| 334 |
"tmdb_id": movie_details.id,
|
| 335 |
+
"imdb_id": movie_details.external_ids.imdb_id if getattr(movie_details, "external_ids", None) else None,
|
| 336 |
"title": movie_details.title,
|
| 337 |
+
"year": getattr(movie_details.release_date, "year", 0) if getattr(movie_details, "release_date", None) else 0,
|
| 338 |
"rate": getattr(movie_details, "vote_average", 0) or 0,
|
| 339 |
"description": movie_details.overview or "",
|
| 340 |
"poster": format_tmdb_image(movie_details.poster_path),
|
|
|
|
| 346 |
"quality": quality,
|
| 347 |
"encoded_string": encoded_string,
|
| 348 |
}
|
| 349 |
+
|
| 350 |
+
# IMDb result return
|
| 351 |
imdb_id = movie_details.get("id", "")
|
| 352 |
images = format_imdb_images(imdb_id)
|
| 353 |
+
|
| 354 |
return {
|
| 355 |
+
"tmdb_id": imdb_id.replace("tt", "") if imdb_id else "",
|
| 356 |
"imdb_id": imdb_id,
|
| 357 |
"title": movie_details.get("title", title),
|
| 358 |
"year": movie_details.get("releaseDetailed", {}).get("year", 0),
|
Backend/pyrofork/plugins/fix_metadata.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
import time
|
|
|
|
| 2 |
from pyrogram import Client, filters
|
| 3 |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 4 |
|
| 5 |
from Backend import db
|
| 6 |
from Backend.helper.custom_filter import CustomFilters
|
| 7 |
-
from Backend.helper.metadata import fetch_tv_metadata, fetch_movie_metadata
|
| 8 |
-
|
| 9 |
|
| 10 |
CANCEL_REQUESTED = False
|
| 11 |
|
|
@@ -13,10 +14,9 @@ CANCEL_REQUESTED = False
|
|
| 13 |
# Progress Bar Helper
|
| 14 |
# -------------------------------
|
| 15 |
def progress_bar(done, total, length=20):
|
| 16 |
-
filled = int(length * (done / total))
|
| 17 |
return f"[{'█' * filled}{'░' * (length - filled)}] {done}/{total}"
|
| 18 |
|
| 19 |
-
|
| 20 |
# -------------------------------
|
| 21 |
# ETA Helper
|
| 22 |
# -------------------------------
|
|
@@ -30,7 +30,6 @@ def format_eta(seconds):
|
|
| 30 |
return f"{minutes}m {sec}s"
|
| 31 |
return f"{sec}s"
|
| 32 |
|
| 33 |
-
|
| 34 |
# -------------------------------
|
| 35 |
# CANCEL BUTTON HANDLER
|
| 36 |
# -------------------------------
|
|
@@ -41,7 +40,6 @@ async def cancel_fix(_, query):
|
|
| 41 |
await query.message.edit_text("❌ Metadata fixing has been cancelled by the user.")
|
| 42 |
await query.answer("Cancelled")
|
| 43 |
|
| 44 |
-
|
| 45 |
# -------------------------------
|
| 46 |
# MAIN COMMAND
|
| 47 |
# -------------------------------
|
|
@@ -70,26 +68,27 @@ async def fix_metadata_handler(_, message):
|
|
| 70 |
])
|
| 71 |
)
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
# -------------------------
|
| 74 |
-
#
|
| 75 |
# -------------------------
|
| 76 |
-
async def
|
| 77 |
nonlocal DONE
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
return
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
async for movie in cursor:
|
| 87 |
-
if CANCEL_REQUESTED:
|
| 88 |
return
|
| 89 |
|
| 90 |
-
tmdb_id =
|
| 91 |
-
title =
|
| 92 |
-
year =
|
| 93 |
|
| 94 |
meta = await fetch_movie_metadata(
|
| 95 |
title=title,
|
|
@@ -116,128 +115,181 @@ async def fix_metadata_handler(_, message):
|
|
| 116 |
|
| 117 |
DONE += 1
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
avg_time = elapsed / DONE
|
| 123 |
-
eta = avg_time * (TOTAL - DONE)
|
| 124 |
-
|
| 125 |
-
await status.edit_text(
|
| 126 |
-
f"🎬 Updating Movies…\n"
|
| 127 |
-
f"{progress_bar(DONE, TOTAL)}\n"
|
| 128 |
-
f"⏱ ETA: {format_eta(eta)}",
|
| 129 |
-
reply_markup=InlineKeyboardMarkup([
|
| 130 |
-
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_fix")]
|
| 131 |
-
])
|
| 132 |
-
)
|
| 133 |
|
| 134 |
# -------------------------
|
| 135 |
-
#
|
| 136 |
# -------------------------
|
| 137 |
-
async def
|
| 138 |
nonlocal DONE
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
if CANCEL_REQUESTED:
|
| 149 |
-
return
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
default_id=None
|
| 164 |
-
)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
{"tmdb_id": tmdb_id},
|
| 169 |
-
{"$set": {
|
| 170 |
-
"imdb_id": meta.get("imdb_id"),
|
| 171 |
-
"cast": meta.get("cast"),
|
| 172 |
-
"description": meta.get("description"),
|
| 173 |
-
"genres": meta.get("genres"),
|
| 174 |
-
"poster": meta.get("poster"),
|
| 175 |
-
"backdrop": meta.get("backdrop"),
|
| 176 |
-
"logo": meta.get("logo"),
|
| 177 |
-
"rating": meta.get("rate"),
|
| 178 |
-
}}
|
| 179 |
-
)
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
)
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
{"tmdb_id": tmdb_id},
|
| 204 |
-
{"$set": {
|
| 205 |
-
"seasons.$[s].episodes.$[e].overview": ep_meta.get("episode_overview"),
|
| 206 |
-
"seasons.$[s].episodes.$[e].released": ep_meta.get("episode_released"),
|
| 207 |
-
"seasons.$[s].episodes.$[e].episode_backdrop": ep_meta.get("episode_backdrop"),
|
| 208 |
-
}},
|
| 209 |
-
array_filters=[
|
| 210 |
-
{"s.season_number": s},
|
| 211 |
-
{"e.episode_number": e}
|
| 212 |
-
]
|
| 213 |
-
)
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
if
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
eta = avg_time * (TOTAL - DONE)
|
| 221 |
-
|
| 222 |
-
await status.edit_text(
|
| 223 |
-
f"📺 Updating TV Shows…\n"
|
| 224 |
-
f"{progress_bar(DONE, TOTAL)}\n"
|
| 225 |
-
f"⏱ ETA: {format_eta(eta)}",
|
| 226 |
-
reply_markup=InlineKeyboardMarkup([
|
| 227 |
-
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_fix")]
|
| 228 |
-
])
|
| 229 |
-
)
|
| 230 |
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
if CANCEL_REQUESTED:
|
| 237 |
return
|
| 238 |
|
|
|
|
|
|
|
| 239 |
await status.edit_text(
|
| 240 |
f"🎉 **Metadata Fix Completed!**\n"
|
| 241 |
f"{progress_bar(DONE, TOTAL)}\n"
|
| 242 |
-
f"⏱ Time Taken: {format_eta(
|
| 243 |
)
|
|
|
|
| 1 |
import time
|
| 2 |
+
import asyncio
|
| 3 |
from pyrogram import Client, filters
|
| 4 |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 5 |
|
| 6 |
from Backend import db
|
| 7 |
from Backend.helper.custom_filter import CustomFilters
|
| 8 |
+
from Backend.helper.metadata import fetch_tv_metadata, fetch_movie_metadata, API_SEMAPHORE
|
| 9 |
+
from Backend.logger import LOGGER
|
| 10 |
|
| 11 |
CANCEL_REQUESTED = False
|
| 12 |
|
|
|
|
| 14 |
# Progress Bar Helper
|
| 15 |
# -------------------------------
|
| 16 |
def progress_bar(done, total, length=20):
|
| 17 |
+
filled = int(length * (done / total)) if total else length
|
| 18 |
return f"[{'█' * filled}{'░' * (length - filled)}] {done}/{total}"
|
| 19 |
|
|
|
|
| 20 |
# -------------------------------
|
| 21 |
# ETA Helper
|
| 22 |
# -------------------------------
|
|
|
|
| 30 |
return f"{minutes}m {sec}s"
|
| 31 |
return f"{sec}s"
|
| 32 |
|
|
|
|
| 33 |
# -------------------------------
|
| 34 |
# CANCEL BUTTON HANDLER
|
| 35 |
# -------------------------------
|
|
|
|
| 40 |
await query.message.edit_text("❌ Metadata fixing has been cancelled by the user.")
|
| 41 |
await query.answer("Cancelled")
|
| 42 |
|
|
|
|
| 43 |
# -------------------------------
|
| 44 |
# MAIN COMMAND
|
| 45 |
# -------------------------------
|
|
|
|
| 68 |
])
|
| 69 |
)
|
| 70 |
|
| 71 |
+
# concurrency controls
|
| 72 |
+
CONCURRENCY = 20
|
| 73 |
+
semaphore = asyncio.Semaphore(CONCURRENCY)
|
| 74 |
+
|
| 75 |
# -------------------------
|
| 76 |
+
# MOVIE UPDATE
|
| 77 |
# -------------------------
|
| 78 |
+
async def _safe_update_movie(collection, movie_doc):
|
| 79 |
nonlocal DONE
|
| 80 |
+
if CANCEL_REQUESTED:
|
| 81 |
+
return
|
|
|
|
| 82 |
|
| 83 |
+
async with semaphore:
|
| 84 |
+
try:
|
| 85 |
+
if movie_doc.get("cast") and movie_doc.get("description") and movie_doc.get("genres"):
|
| 86 |
+
DONE += 1
|
|
|
|
|
|
|
| 87 |
return
|
| 88 |
|
| 89 |
+
tmdb_id = movie_doc["tmdb_id"]
|
| 90 |
+
title = movie_doc["title"]
|
| 91 |
+
year = movie_doc.get("release_year")
|
| 92 |
|
| 93 |
meta = await fetch_movie_metadata(
|
| 94 |
title=title,
|
|
|
|
| 115 |
|
| 116 |
DONE += 1
|
| 117 |
|
| 118 |
+
except Exception as e:
|
| 119 |
+
LOGGER.exception(f"Error updating movie {movie_doc.get('title')}: {e}")
|
| 120 |
+
DONE += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
# -------------------------
|
| 123 |
+
# TV UPDATE
|
| 124 |
# -------------------------
|
| 125 |
+
async def _safe_update_tv(collection, tv_doc):
|
| 126 |
nonlocal DONE
|
| 127 |
+
if CANCEL_REQUESTED:
|
| 128 |
+
return
|
| 129 |
+
|
| 130 |
+
async with semaphore:
|
| 131 |
+
try:
|
| 132 |
+
tmdb_id = tv_doc["tmdb_id"]
|
| 133 |
+
title = tv_doc["title"]
|
| 134 |
+
year = tv_doc.get("release_year")
|
| 135 |
+
|
| 136 |
+
# SHOW-LEVEL UPDATE
|
| 137 |
+
has_meta = tv_doc.get("cast") and tv_doc.get("description") and tv_doc.get("genres")
|
| 138 |
+
if not has_meta:
|
| 139 |
+
meta = await fetch_tv_metadata(
|
| 140 |
+
title=title,
|
| 141 |
+
season=1,
|
| 142 |
+
episode=1,
|
| 143 |
+
encoded_string=None,
|
| 144 |
+
year=year,
|
| 145 |
+
quality=None,
|
| 146 |
+
default_id=None
|
| 147 |
+
)
|
| 148 |
|
| 149 |
+
if meta:
|
| 150 |
+
await collection.update_one(
|
| 151 |
+
{"tmdb_id": tmdb_id},
|
| 152 |
+
{"$set": {
|
| 153 |
+
"imdb_id": meta.get("imdb_id"),
|
| 154 |
+
"cast": meta.get("cast"),
|
| 155 |
+
"description": meta.get("description"),
|
| 156 |
+
"genres": meta.get("genres"),
|
| 157 |
+
"poster": meta.get("poster"),
|
| 158 |
+
"backdrop": meta.get("backdrop"),
|
| 159 |
+
"logo": meta.get("logo"),
|
| 160 |
+
"rating": meta.get("rate"),
|
| 161 |
+
}}
|
| 162 |
+
)
|
| 163 |
|
| 164 |
+
# EPISODE UPDATES (NO DONE += 1 HERE — AS YOU REQUESTED)
|
| 165 |
+
tasks = []
|
|
|
|
|
|
|
| 166 |
|
| 167 |
+
for season in tv_doc.get("seasons", []):
|
| 168 |
+
if CANCEL_REQUESTED:
|
| 169 |
+
break
|
| 170 |
+
|
| 171 |
+
s = season.get("season_number")
|
| 172 |
+
|
| 173 |
+
for ep in season.get("episodes", []):
|
| 174 |
+
if CANCEL_REQUESTED:
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
e = ep.get("episode_number")
|
| 178 |
+
|
| 179 |
+
# Skip if episode complete
|
| 180 |
+
if ep.get("overview") and ep.get("released") and ep.get("episode_backdrop"):
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
async def ep_task(s_local=s, e_local=e, tv_tmdb=tmdb_id):
|
| 184 |
+
try:
|
| 185 |
+
ep_meta = await fetch_tv_metadata(
|
| 186 |
+
title=title,
|
| 187 |
+
season=s_local,
|
| 188 |
+
episode=e_local,
|
| 189 |
+
encoded_string=None,
|
| 190 |
+
year=year,
|
| 191 |
+
quality=None,
|
| 192 |
+
default_id=None
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
if ep_meta:
|
| 196 |
+
await collection.update_one(
|
| 197 |
+
{"tmdb_id": tv_tmdb},
|
| 198 |
+
{"$set": {
|
| 199 |
+
"seasons.$[s].episodes.$[e].overview": ep_meta.get("episode_overview"),
|
| 200 |
+
"seasons.$[s].episodes.$[e].released": ep_meta.get("episode_released"),
|
| 201 |
+
"seasons.$[s].episodes.$[e].episode_backdrop": ep_meta.get("episode_backdrop"),
|
| 202 |
+
}},
|
| 203 |
+
array_filters=[
|
| 204 |
+
{"s.season_number": s_local},
|
| 205 |
+
{"e.episode_number": e_local}
|
| 206 |
+
]
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
except Exception as e:
|
| 210 |
+
LOGGER.exception(f"Error updating episode {title} S{s_local}E{e_local}: {e}")
|
| 211 |
+
|
| 212 |
+
tasks.append(asyncio.create_task(ep_task()))
|
| 213 |
+
|
| 214 |
+
# RUN EPISODE TASKS
|
| 215 |
+
if tasks:
|
| 216 |
+
for i in range(0, len(tasks), CONCURRENCY):
|
| 217 |
+
if CANCEL_REQUESTED:
|
| 218 |
+
break
|
| 219 |
+
batch = tasks[i:i+CONCURRENCY]
|
| 220 |
+
await asyncio.gather(*batch, return_exceptions=True)
|
| 221 |
+
|
| 222 |
+
DONE += 1
|
| 223 |
+
|
| 224 |
+
except Exception as e:
|
| 225 |
+
LOGGER.exception(f"Error updating TV show {tv_doc.get('title')}: {e}")
|
| 226 |
+
DONE += 1
|
| 227 |
|
| 228 |
+
# -------------------------
|
| 229 |
+
# UPDATE MOVIES
|
| 230 |
+
# -------------------------
|
| 231 |
+
async def update_movies():
|
| 232 |
+
tasks = []
|
| 233 |
+
for i in range(1, db.current_db_index + 1):
|
| 234 |
+
if CANCEL_REQUESTED:
|
| 235 |
+
break
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
collection = db.dbs[f"storage_{i}"]["movie"]
|
| 238 |
+
cursor = collection.find({})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
+
async for movie in cursor:
|
| 241 |
+
if CANCEL_REQUESTED:
|
| 242 |
+
break
|
| 243 |
+
tasks.append(_safe_update_movie(collection, movie))
|
| 244 |
|
| 245 |
+
if len(tasks) >= CONCURRENCY * 2:
|
| 246 |
+
await asyncio.gather(*tasks, return_exceptions=True)
|
| 247 |
+
tasks = []
|
| 248 |
|
| 249 |
+
if tasks:
|
| 250 |
+
await asyncio.gather(*tasks, return_exceptions=True)
|
| 251 |
|
| 252 |
+
# -------------------------
|
| 253 |
+
# UPDATE TV SHOWS
|
| 254 |
+
# -------------------------
|
| 255 |
+
async def update_tv():
|
| 256 |
+
tasks = []
|
| 257 |
+
for i in range(1, db.current_db_index + 1):
|
| 258 |
+
if CANCEL_REQUESTED:
|
| 259 |
+
break
|
|
|
|
| 260 |
|
| 261 |
+
collection = db.dbs[f"storage_{i}"]["tv"]
|
| 262 |
+
cursor = collection.find({})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
async for tv in cursor:
|
| 265 |
+
if CANCEL_REQUESTED:
|
| 266 |
+
break
|
| 267 |
+
tasks.append(_safe_update_tv(collection, tv))
|
| 268 |
|
| 269 |
+
if len(tasks) >= CONCURRENCY * 2:
|
| 270 |
+
await asyncio.gather(*tasks, return_exceptions=True)
|
| 271 |
+
tasks = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
+
if tasks:
|
| 274 |
+
await asyncio.gather(*tasks, return_exceptions=True)
|
| 275 |
+
|
| 276 |
+
# -------------------------
|
| 277 |
+
# RUN ALL UPDATES
|
| 278 |
+
# -------------------------
|
| 279 |
+
try:
|
| 280 |
+
await update_movies()
|
| 281 |
+
if not CANCEL_REQUESTED:
|
| 282 |
+
await update_tv()
|
| 283 |
+
except Exception as e:
|
| 284 |
+
LOGGER.exception(f"Error in fix_metadata run: {e}")
|
| 285 |
|
| 286 |
if CANCEL_REQUESTED:
|
| 287 |
return
|
| 288 |
|
| 289 |
+
elapsed = time.time() - start_time
|
| 290 |
+
|
| 291 |
await status.edit_text(
|
| 292 |
f"🎉 **Metadata Fix Completed!**\n"
|
| 293 |
f"{progress_bar(DONE, TOTAL)}\n"
|
| 294 |
+
f"⏱ Time Taken: {format_eta(elapsed)}"
|
| 295 |
)
|
pyproject.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "Telegram-Stremio"
|
| 3 |
-
version = "1.4.
|
| 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.4.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"
|
uv.lock
CHANGED
|
@@ -901,7 +901,7 @@ wheels = [
|
|
| 901 |
|
| 902 |
[[package]]
|
| 903 |
name = "telegram-stremio"
|
| 904 |
-
version = "1.
|
| 905 |
source = { virtual = "." }
|
| 906 |
dependencies = [
|
| 907 |
{ name = "aiofiles" },
|
|
|
|
| 901 |
|
| 902 |
[[package]]
|
| 903 |
name = "telegram-stremio"
|
| 904 |
+
version = "1.4.0"
|
| 905 |
source = { virtual = "." }
|
| 906 |
dependencies = [
|
| 907 |
{ name = "aiofiles" },
|