weebzone commited on
Commit
522e2cd
·
1 Parent(s): e638588

`🚀 V1.4.3 Release`

Browse files

New Features & Improvements:
🎬 Manual Entry: Now supports both IMDB and TMDB IDs.
🔗 URL Format: Changed the URL structure from TMDB format to IMDB format.
⏱️ Metadata: Added the runtime field.

Fixes:
🐛 Metadata Fix: fix_metadata.py now uses both imdb_id and tmdb_id for more accurate results.

⚠️ Action Required: Please run /fixmetadata once for proper usage.

Backend/__init__.py CHANGED
@@ -11,4 +11,4 @@ StartTime = time()
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
- __version__ = "1.4.2"
 
11
  USE_DEFAULT_ID: str = None
12
  db = Database()
13
 
14
+ __version__ = "1.4.3"
Backend/fastapi/routes/stremio_routes.py CHANGED
@@ -27,7 +27,7 @@ GENRES = [
27
  # --- Helper Functions ---
28
  def convert_to_stremio_meta(item: dict) -> dict:
29
  media_type = "series" if item.get("media_type") == "tv" else "movie"
30
- stremio_id = f"{item.get('tmdb_id')}-{item.get('db_index')}"
31
 
32
  meta = {
33
  "id": stremio_id,
@@ -36,15 +36,17 @@ def convert_to_stremio_meta(item: dict) -> dict:
36
  "poster": item.get("poster") or "",
37
  "logo": item.get("logo") or "",
38
  "year": item.get("release_year"),
 
 
 
39
  "background": item.get("backdrop") or "",
40
  "genres": item.get("genres") or [],
41
  "imdbRating": item.get("rating") or "",
42
  "description": item.get("description") or "",
 
 
43
  }
44
 
45
- cast_list = item.get("cast") or []
46
- if cast_list:
47
- meta["cast"] = cast_list[:5]
48
  return meta
49
 
50
 
@@ -213,12 +215,12 @@ async def get_catalog(media_type: str, id: str, extra: Optional[str] = None):
213
  @router.get("/meta/{media_type}/{id}.json")
214
  async def get_meta(media_type: str, id: str):
215
  try:
216
- tmdb_id_str, db_index_str = id.split("-")
217
- tmdb_id, db_index = int(tmdb_id_str), int(db_index_str)
218
  except (ValueError, IndexError):
219
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
220
 
221
- media = await db.get_media_details(tmdb_id=tmdb_id, db_index=db_index)
222
  if not media:
223
  return {"meta": {}}
224
 
@@ -233,7 +235,12 @@ async def get_meta(media_type: str, id: str):
233
  "poster": media.get("poster", ""),
234
  "logo": media.get("logo", ""),
235
  "background": media.get("backdrop", ""),
236
- "imdb_id": media.get("imdb_id", "")
 
 
 
 
 
237
  }
238
 
239
  # --- Add Episodes ---
@@ -260,12 +267,6 @@ async def get_meta(media_type: str, id: str):
260
  })
261
 
262
  meta_obj["videos"] = videos
263
-
264
- # --- Add cast ---
265
- cast_list = media.get("cast") or []
266
- if cast_list:
267
- meta_obj["cast"] = cast_list[:10]
268
-
269
  return {"meta": meta_obj}
270
 
271
 
@@ -276,12 +277,14 @@ async def get_streams(media_type: str, id: str):
276
  base_id = parts[0]
277
  season_num = int(parts[1]) if len(parts) > 1 else None
278
  episode_num = int(parts[2]) if len(parts) > 2 else None
279
- tmdb_id, db_index = map(int, base_id.split("-"))
 
 
280
  except (ValueError, IndexError):
281
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
282
 
283
  media_details = await db.get_media_details(
284
- tmdb_id=tmdb_id,
285
  db_index=db_index,
286
  season_number=season_num,
287
  episode_number=episode_num
 
27
  # --- Helper Functions ---
28
  def convert_to_stremio_meta(item: dict) -> dict:
29
  media_type = "series" if item.get("media_type") == "tv" else "movie"
30
+ stremio_id = f"{item.get('imdb_id')}-{item.get('db_index')}"
31
 
32
  meta = {
33
  "id": stremio_id,
 
36
  "poster": item.get("poster") or "",
37
  "logo": item.get("logo") or "",
38
  "year": item.get("release_year"),
39
+ "releaseInfo": item.get("release_year"),
40
+ "imdb_id": item.get("imdb_id", ""),
41
+ "moviedb_id": item.get("tmdb_id", ""),
42
  "background": item.get("backdrop") or "",
43
  "genres": item.get("genres") or [],
44
  "imdbRating": item.get("rating") or "",
45
  "description": item.get("description") or "",
46
+ "cast": item.get("cast") or [],
47
+ "runtime": item.get("runtime") or "",
48
  }
49
 
 
 
 
50
  return meta
51
 
52
 
 
215
  @router.get("/meta/{media_type}/{id}.json")
216
  async def get_meta(media_type: str, id: str):
217
  try:
218
+ imdb_id_str, db_index_str = id.split("-")
219
+ imdb_id, db_index = str(imdb_id_str), int(db_index_str)
220
  except (ValueError, IndexError):
221
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
222
 
223
+ media = await db.get_media_details(imdb_id=imdb_id, db_index=db_index)
224
  if not media:
225
  return {"meta": {}}
226
 
 
235
  "poster": media.get("poster", ""),
236
  "logo": media.get("logo", ""),
237
  "background": media.get("backdrop", ""),
238
+ "imdb_id": media.get("imdb_id", ""),
239
+ "releaseInfo": media.get("release_year"),
240
+ "moviedb_id": media.get("tmdb_id", ""),
241
+ "cast": media.get("cast") or [],
242
+ "runtime": media.get("runtime") or "",
243
+
244
  }
245
 
246
  # --- Add Episodes ---
 
267
  })
268
 
269
  meta_obj["videos"] = videos
 
 
 
 
 
 
270
  return {"meta": meta_obj}
271
 
272
 
 
277
  base_id = parts[0]
278
  season_num = int(parts[1]) if len(parts) > 1 else None
279
  episode_num = int(parts[2]) if len(parts) > 2 else None
280
+ imdb_id_str, db_index_str = base_id.split("-")
281
+ imdb_id, db_index = str(imdb_id_str), int(db_index_str)
282
+
283
  except (ValueError, IndexError):
284
  raise HTTPException(status_code=400, detail="Invalid Stremio ID format")
285
 
286
  media_details = await db.get_media_details(
287
+ imdb_id=imdb_id,
288
  db_index=db_index,
289
  season_number=season_num,
290
  episode_number=episode_num
Backend/helper/database.py CHANGED
@@ -139,8 +139,11 @@ class Database:
139
 
140
  if len(results) >= page_size:
141
  break
 
142
  return results, dbs_checked, total_count
143
 
 
 
144
  async def _move_document(
145
  self, collection_name: str, document: dict, old_db_index: int
146
  ) -> bool:
@@ -190,6 +193,7 @@ class Database:
190
  backdrop=metadata_info['backdrop'],
191
  logo=metadata_info['logo'],
192
  cast=metadata_info['cast'],
 
193
  media_type=metadata_info['media_type'],
194
  telegram=[QualityDetail(
195
  quality=metadata_info['quality'],
@@ -213,6 +217,7 @@ class Database:
213
  backdrop=metadata_info['backdrop'],
214
  logo=metadata_info['logo'],
215
  cast=metadata_info['cast'],
 
216
  media_type=metadata_info['media_type'],
217
  seasons=[Season(
218
  season_number=metadata_info['season_number'],
@@ -536,12 +541,12 @@ class Database:
536
 
537
 
538
  async def get_media_details(
539
- self, tmdb_id: int, db_index: int,
540
  season_number: Optional[int] = None, episode_number: Optional[int] = None
541
  ) -> Optional[dict]:
542
  db_key = f"storage_{db_index}"
543
  if episode_number is not None and season_number is not None:
544
- tv_show = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
545
  if not tv_show:
546
  return None
547
  for season in tv_show.get("seasons", []):
@@ -550,7 +555,7 @@ class Database:
550
  if episode.get("episode_number") == episode_number:
551
  details = convert_objectid_to_str(episode)
552
  details.update({
553
- "tmdb_id": tmdb_id,
554
  "type": "tv",
555
  "season_number": season_number,
556
  "episode_number": episode_number,
@@ -560,14 +565,14 @@ class Database:
560
  return None
561
 
562
  elif season_number is not None:
563
- tv_show = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
564
  if not tv_show:
565
  return None
566
  for season in tv_show.get("seasons", []):
567
  if season.get("season_number") == season_number:
568
  details = convert_objectid_to_str(season)
569
  details.update({
570
- "tmdb_id": tmdb_id,
571
  "type": "tv",
572
  "season_number": season_number
573
  })
@@ -575,12 +580,12 @@ class Database:
575
  return None
576
 
577
  else:
578
- tv_doc = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
579
  if tv_doc:
580
  tv_doc = convert_objectid_to_str(tv_doc)
581
  tv_doc["type"] = "tv"
582
  return tv_doc
583
- movie_doc = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
584
  if movie_doc:
585
  movie_doc = convert_objectid_to_str(movie_doc)
586
  movie_doc["type"] = "movie"
@@ -655,7 +660,6 @@ class Database:
655
  return False
656
  raise
657
 
658
- # Delete a Movie or Tvshow completely
659
  async def delete_document(self, media_type: str, tmdb_id: int, db_index: int) -> bool:
660
  db_key = f"storage_{db_index}"
661
 
@@ -698,8 +702,6 @@ class Database:
698
  LOGGER.info(f"No document found with tmdb_id {tmdb_id}.")
699
  return False
700
 
701
-
702
- # Delete a specific quality from movie
703
  async def delete_movie_quality(self, tmdb_id: int, db_index: int, quality: str) -> bool:
704
  db_key = f"storage_{db_index}"
705
  movie = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
@@ -730,7 +732,6 @@ class Database:
730
  result = await self.dbs[db_key]["movie"].replace_one({"tmdb_id": tmdb_id}, movie)
731
  return result.modified_count > 0
732
 
733
- # Delete a specific episode from a TV show
734
  async def delete_tv_episode(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int) -> bool:
735
  db_key = f"storage_{db_index}"
736
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
@@ -767,7 +768,6 @@ class Database:
767
  result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
768
  return result.modified_count > 0
769
 
770
- # Delete a whole season from a TV show
771
  async def delete_tv_season(self, tmdb_id: int, db_index: int, season_number: int) -> bool:
772
  db_key = f"storage_{db_index}"
773
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
@@ -800,7 +800,6 @@ class Database:
800
  result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
801
  return result.modified_count > 0
802
 
803
- # Delete a specific quality from a given TV episode
804
  async def delete_tv_quality(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int, quality: str) -> bool:
805
  db_key = f"storage_{db_index}"
806
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
@@ -854,4 +853,4 @@ class Database:
854
  "storageSize": db_stats.get("storageSize", 0),
855
  "dataSize": db_stats.get("dataSize", 0)
856
  })
857
- return stats
 
139
 
140
  if len(results) >= page_size:
141
  break
142
+
143
  return results, dbs_checked, total_count
144
 
145
+
146
+
147
  async def _move_document(
148
  self, collection_name: str, document: dict, old_db_index: int
149
  ) -> bool:
 
193
  backdrop=metadata_info['backdrop'],
194
  logo=metadata_info['logo'],
195
  cast=metadata_info['cast'],
196
+ runtime=metadata_info['runtime'],
197
  media_type=metadata_info['media_type'],
198
  telegram=[QualityDetail(
199
  quality=metadata_info['quality'],
 
217
  backdrop=metadata_info['backdrop'],
218
  logo=metadata_info['logo'],
219
  cast=metadata_info['cast'],
220
+ runtime=metadata_info['runtime'],
221
  media_type=metadata_info['media_type'],
222
  seasons=[Season(
223
  season_number=metadata_info['season_number'],
 
541
 
542
 
543
  async def get_media_details(
544
+ self, imdb_id: str, db_index: int,
545
  season_number: Optional[int] = None, episode_number: Optional[int] = None
546
  ) -> Optional[dict]:
547
  db_key = f"storage_{db_index}"
548
  if episode_number is not None and season_number is not None:
549
+ tv_show = await self.dbs[db_key]["tv"].find_one({"imdb_id": imdb_id})
550
  if not tv_show:
551
  return None
552
  for season in tv_show.get("seasons", []):
 
555
  if episode.get("episode_number") == episode_number:
556
  details = convert_objectid_to_str(episode)
557
  details.update({
558
+ "imdb_id": imdb_id,
559
  "type": "tv",
560
  "season_number": season_number,
561
  "episode_number": episode_number,
 
565
  return None
566
 
567
  elif season_number is not None:
568
+ tv_show = await self.dbs[db_key]["tv"].find_one({"imdb_id": imdb_id})
569
  if not tv_show:
570
  return None
571
  for season in tv_show.get("seasons", []):
572
  if season.get("season_number") == season_number:
573
  details = convert_objectid_to_str(season)
574
  details.update({
575
+ "imdb_id": imdb_id,
576
  "type": "tv",
577
  "season_number": season_number
578
  })
 
580
  return None
581
 
582
  else:
583
+ tv_doc = await self.dbs[db_key]["tv"].find_one({"imdb_id": imdb_id})
584
  if tv_doc:
585
  tv_doc = convert_objectid_to_str(tv_doc)
586
  tv_doc["type"] = "tv"
587
  return tv_doc
588
+ movie_doc = await self.dbs[db_key]["movie"].find_one({"imdb_id": imdb_id})
589
  if movie_doc:
590
  movie_doc = convert_objectid_to_str(movie_doc)
591
  movie_doc["type"] = "movie"
 
660
  return False
661
  raise
662
 
 
663
  async def delete_document(self, media_type: str, tmdb_id: int, db_index: int) -> bool:
664
  db_key = f"storage_{db_index}"
665
 
 
702
  LOGGER.info(f"No document found with tmdb_id {tmdb_id}.")
703
  return False
704
 
 
 
705
  async def delete_movie_quality(self, tmdb_id: int, db_index: int, quality: str) -> bool:
706
  db_key = f"storage_{db_index}"
707
  movie = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
 
732
  result = await self.dbs[db_key]["movie"].replace_one({"tmdb_id": tmdb_id}, movie)
733
  return result.modified_count > 0
734
 
 
735
  async def delete_tv_episode(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int) -> bool:
736
  db_key = f"storage_{db_index}"
737
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
 
768
  result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
769
  return result.modified_count > 0
770
 
 
771
  async def delete_tv_season(self, tmdb_id: int, db_index: int, season_number: int) -> bool:
772
  db_key = f"storage_{db_index}"
773
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
 
800
  result = await self.dbs[db_key]["tv"].replace_one({"tmdb_id": tmdb_id}, tv)
801
  return result.modified_count > 0
802
 
 
803
  async def delete_tv_quality(self, tmdb_id: int, db_index: int, season_number: int, episode_number: int, quality: str) -> bool:
804
  db_key = f"storage_{db_index}"
805
  tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
 
853
  "storageSize": db_stats.get("storageSize", 0),
854
  "dataSize": db_stats.get("dataSize", 0)
855
  })
856
+ return stats
Backend/helper/imdb.py CHANGED
@@ -78,7 +78,7 @@ async def get_detail(imdb_id: str) -> Optional[Dict[str, Any]]:
78
  break
79
  return {
80
  'id': meta.get('imdb_id', meta.get('id', '')),
81
- 'moviedb_id': meta.get('moviedb_id', ''),
82
  'type': meta.get('type', media_type),
83
  'title': meta.get('name', ''),
84
  'plot': meta.get('description', ''),
 
78
  break
79
  return {
80
  'id': meta.get('imdb_id', meta.get('id', '')),
81
+ 'moviedb_id': meta.get('moviedb_id', None),
82
  'type': meta.get('type', media_type),
83
  'title': meta.get('name', ''),
84
  'plot': meta.get('description', ''),
Backend/helper/metadata.py CHANGED
@@ -1,9 +1,9 @@
1
  import asyncio
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
8
  from Backend.config import Telegram
9
  import Backend
@@ -18,7 +18,7 @@ tmdb = aioTMDb(key=Telegram.TMDB_API, language="en-US", region="US")
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)
@@ -30,15 +30,22 @@ def format_tmdb_image(path: str, size="w500") -> str:
30
  return f"https://image.tmdb.org/t/p/{size}{path}"
31
 
32
  def get_tmdb_logo(images) -> str:
33
- if not images or not getattr(images, "logos", None):
 
 
 
34
  return ""
35
-
36
- logos = images.logos
37
-
38
  for logo in logos:
39
- if getattr(logo, "iso_639_1", None) == "en":
40
- return format_tmdb_image(logo.file_path, "original")
41
- return format_tmdb_image(logos[0].file_path, "original") if logos else ""
 
 
 
 
 
 
 
42
 
43
  def format_imdb_images(imdb_id: str) -> dict:
44
  if not imdb_id:
@@ -49,8 +56,20 @@ def format_imdb_images(imdb_id: str) -> dict:
49
  "logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
50
  }
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  async def safe_imdb_search(title: str, type_: str) -> str | None:
53
- """Safely search IMDb title and return its ID, with simple caching."""
54
  key = f"imdb::{type_}::{title}"
55
  if key in IMDB_CACHE:
56
  return IMDB_CACHE[key]
@@ -65,17 +84,13 @@ async def safe_imdb_search(title: str, type_: str) -> str | None:
65
  return None
66
 
67
  async def safe_tmdb_search(title: str, type_: str, year=None):
68
- """Safely search TMDb title with caching."""
69
  key = f"tmdb_search::{type_}::{title}::{year}"
70
  if key in TMDB_SEARCH_CACHE:
71
  return TMDB_SEARCH_CACHE[key]
72
  try:
73
  async with API_SEMAPHORE:
74
  if type_ == "movie":
75
- if year:
76
- results = await tmdb.search().movies(query=title, year=year)
77
- else:
78
- results = await tmdb.search().movies(query=title)
79
  else:
80
  results = await tmdb.search().tv(query=title)
81
  res = results[0] if results else None
@@ -86,12 +101,35 @@ async def safe_tmdb_search(title: str, type_: str, year=None):
86
  TMDB_SEARCH_CACHE[key] = None
87
  return None
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  async def _tmdb_tv_details(tv_id):
90
  if tv_id in TMDB_DETAILS_CACHE:
91
  return TMDB_DETAILS_CACHE[tv_id]
92
  try:
93
  async with API_SEMAPHORE:
94
- details = await tmdb.tv(tv_id).details(append_to_response="external_ids,credits,images")
 
 
 
 
95
  TMDB_DETAILS_CACHE[tv_id] = details
96
  return details
97
  except Exception as e:
@@ -99,18 +137,6 @@ async def _tmdb_tv_details(tv_id):
99
  TMDB_DETAILS_CACHE[tv_id] = None
100
  return None
101
 
102
- async def _tmdb_movie_details(movie_id):
103
- if movie_id in TMDB_DETAILS_CACHE:
104
- return TMDB_DETAILS_CACHE[movie_id]
105
- try:
106
- async with API_SEMAPHORE:
107
- details = await tmdb.movie(movie_id).details(append_to_response="external_ids,credits,images")
108
- TMDB_DETAILS_CACHE[movie_id] = details
109
- return details
110
- except Exception as e:
111
- LOGGER.warning(f"TMDb movie details fetch failed for id={movie_id}: {e}")
112
- TMDB_DETAILS_CACHE[movie_id] = None
113
- return None
114
 
115
  async def _tmdb_episode_details(tv_id, season, episode):
116
  key = (tv_id, season, episode)
@@ -125,7 +151,7 @@ async def _tmdb_episode_details(tv_id, season, episode):
125
  EPISODE_CACHE[key] = None
126
  return None
127
 
128
- # ----------------- Main Entry -----------------
129
  async def metadata(filename: str, channel: int, msg_id) -> dict | None:
130
  try:
131
  parsed = PTN.parse(filename)
@@ -149,36 +175,31 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
149
  episode = parsed.get("episode")
150
  year = parsed.get("year")
151
  quality = parsed.get("resolution")
152
-
153
- if not quality:
154
- LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
155
- return None
156
-
157
  if isinstance(season, list) or isinstance(episode, list):
158
  LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
159
  return None
160
-
161
  if season and not episode:
162
  LOGGER.warning(f"Missing episode in {filename}: {parsed}")
163
  return None
 
 
 
 
 
 
164
 
165
- # Extract TMDb/IMDb hint
166
  default_id = None
167
  try:
168
- default_id = extract_tmdb_id(Backend.USE_DEFAULT_ID)
169
  except Exception:
170
  pass
171
-
172
  if not default_id:
173
  try:
174
- default_id = extract_tmdb_id(filename)
175
  except Exception:
176
  pass
177
 
178
- if not title:
179
- LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
180
- return None
181
-
182
  data = {"chat_id": channel, "msg_id": msg_id}
183
  try:
184
  encoded_string = await encode_string(data)
@@ -198,11 +219,24 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
198
 
199
  # ----------------- TV Metadata -----------------
200
  async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
201
- imdb_id = default_id if default_id and default_id.startswith("tt") else await safe_imdb_search(title, "tvSeries")
202
- tv_details, ep_details, use_tmdb = None, None, False
 
 
 
 
 
 
 
 
 
 
 
203
 
204
- # Try IMDb (cinemeta) first if imdb_id present
205
- if imdb_id:
 
 
206
  try:
207
  if imdb_id in IMDB_CACHE:
208
  tv_details = IMDB_CACHE[imdb_id]
@@ -210,6 +244,7 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
210
  async with API_SEMAPHORE:
211
  tv_details = await get_detail(imdb_id=imdb_id)
212
  IMDB_CACHE[imdb_id] = tv_details
 
213
  cache_key = f"{imdb_id}::{season}::{episode}"
214
  if cache_key in EPISODE_CACHE:
215
  ep_details = EPISODE_CACHE[cache_key]
@@ -219,33 +254,25 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
219
  EPISODE_CACHE[cache_key] = ep_details
220
  except Exception as e:
221
  LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
222
-
223
- # If IMDb failed, fallback to TMDb
224
- if not tv_details:
225
- use_tmdb = True
226
- tmdb_result = await safe_tmdb_search(title, "tv")
227
- if not tmdb_result:
228
- LOGGER.warning(f"No TMDb result for '{title}'")
229
- return None
230
-
231
- tv_id = tmdb_result.id
232
- tv_details = await _tmdb_tv_details(tv_id)
 
233
  if not tv_details:
234
- LOGGER.warning(f"TMDb TV details fetch failed for '{title}' (id={tv_id})")
235
  return None
 
236
 
237
- ep_details = await _tmdb_episode_details(tv_id, season, episode)
238
-
239
- # TMDb-based return path
240
- if use_tmdb and tv_details:
241
  credits = getattr(tv_details, "credits", None) or {}
242
- cast_names = []
243
- if credits:
244
- cast_list = getattr(credits, "cast", []) or []
245
- for member in cast_list:
246
- name = getattr(member, "name", None) or getattr(member, "original_name", None)
247
- if name:
248
- cast_names.append(name)
249
 
250
  return {
251
  "tmdb_id": tv_details.id,
@@ -260,6 +287,11 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
260
  "genres": [g.name for g in (tv_details.genres or [])],
261
  "media_type": "tv",
262
  "cast": cast_names,
 
 
 
 
 
263
  "season_number": season,
264
  "episode_number": episode,
265
  "episode_title": getattr(ep_details, "name", f"S{season}E{episode}") if ep_details else f"{tv_details.name} S{season}E{episode}",
@@ -270,15 +302,15 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
270
  "encoded_string": encoded_string,
271
  }
272
 
273
- if not tv_details:
274
- LOGGER.warning(f"No valid IMDb data for {title}")
275
- return None
276
-
277
- imdb_id = tv_details.get("id", "")
278
  images = format_imdb_images(imdb_id)
 
 
 
 
279
 
280
  return {
281
- "tmdb_id": (tv_details.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else "")),
282
  "imdb_id": imdb_id,
283
  "title": tv_details.get("title", title),
284
  "year": tv_details.get("releaseDetailed", {}).get("year", 0),
@@ -288,6 +320,7 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
288
  "backdrop": images["backdrop"],
289
  "logo": images["logo"],
290
  "cast": tv_details.get("cast", []),
 
291
  "genres": tv_details.get("genre", []),
292
  "media_type": "tv",
293
  "season_number": season,
@@ -302,11 +335,23 @@ async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, q
302
 
303
  # ----------------- Movie Metadata -----------------
304
  async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
305
- 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")
306
- movie_details, use_tmdb = None, False
 
 
 
 
 
 
 
307
 
308
- # Try IMDb first
309
- if imdb_id:
 
 
 
 
 
310
  try:
311
  if imdb_id in IMDB_CACHE:
312
  movie_details = IMDB_CACHE[imdb_id]
@@ -316,31 +361,24 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
316
  IMDB_CACHE[imdb_id] = movie_details
317
  except Exception as e:
318
  LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
319
-
320
- # Fallback to TMDb
321
- if not movie_details:
322
- use_tmdb = True
323
- tmdb_result = await safe_tmdb_search(title, "movie", year)
324
- if not tmdb_result:
325
- LOGGER.warning(f"No TMDb movie found for '{title}'")
326
- return None
327
-
328
- try:
329
- movie_details = await _tmdb_movie_details(tmdb_result.id)
330
- except Exception as e:
331
- LOGGER.warning(f"TMDb movie details failed for {title}: {e}")
332
  return None
333
 
334
- # TMDb result return
335
- if use_tmdb and movie_details:
336
  credits = getattr(movie_details, "credits", None) or {}
337
- cast_names = []
338
- if credits:
339
- cast_list = getattr(credits, "cast", []) or []
340
- for member in cast_list:
341
- name = getattr(member, "name", None) or getattr(member, "original_name", None)
342
- if name:
343
- cast_names.append(name)
344
  return {
345
  "tmdb_id": movie_details.id,
346
  "imdb_id": movie_details.external_ids.imdb_id if getattr(movie_details, "external_ids", None) else None,
@@ -352,18 +390,20 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
352
  "backdrop": format_tmdb_image(movie_details.backdrop_path, "original"),
353
  "logo": get_tmdb_logo(getattr(movie_details, "images", None)),
354
  "cast": cast_names,
 
355
  "media_type": "movie",
356
  "genres": [g.name for g in (movie_details.genres or [])],
357
  "quality": quality,
358
  "encoded_string": encoded_string,
359
  }
360
 
361
- # IMDb result return
362
- imdb_id = movie_details.get("id", "")
363
  images = format_imdb_images(imdb_id)
 
 
364
 
365
  return {
366
- "tmdb_id": (movie_details.get("moviedb_id") or (imdb_id.replace("tt", "") if imdb_id else "")),
367
  "imdb_id": imdb_id,
368
  "title": movie_details.get("title", title),
369
  "year": movie_details.get("releaseDetailed", {}).get("year", 0),
@@ -373,6 +413,7 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
373
  "backdrop": images["backdrop"],
374
  "logo": images["logo"],
375
  "cast": movie_details.get("cast", []),
 
376
  "media_type": "movie",
377
  "genres": movie_details.get("genre", []),
378
  "quality": quality,
 
1
  import asyncio
2
  import traceback
3
  import PTN
4
+ import re
5
  from re import compile, IGNORECASE
6
  from Backend.helper.imdb import get_detail, get_season, search_title
 
7
  from themoviedb import aioTMDb
8
  from Backend.config import Telegram
9
  import Backend
 
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)
 
30
  return f"https://image.tmdb.org/t/p/{size}{path}"
31
 
32
  def get_tmdb_logo(images) -> str:
33
+ if not images:
34
+ return ""
35
+ logos = getattr(images, "logos", None)
36
+ if not logos:
37
  return ""
 
 
 
38
  for logo in logos:
39
+ iso_lang = getattr(logo, "iso_639_1", None)
40
+ file_path = getattr(logo, "file_path", None)
41
+ if iso_lang == "en" and file_path:
42
+ return format_tmdb_image(file_path, "w300")
43
+ for logo in logos:
44
+ file_path = getattr(logo, "file_path", None)
45
+ if file_path:
46
+ return format_tmdb_image(file_path, "w300")
47
+ return ""
48
+
49
 
50
  def format_imdb_images(imdb_id: str) -> dict:
51
  if not imdb_id:
 
56
  "logo": f"https://images.metahub.space/logo/medium/{imdb_id}/img",
57
  }
58
 
59
+ def extract_default_id(url: str) -> str | None:
60
+ # IMDb
61
+ imdb_match = re.search(r'/title/(tt\d+)', url)
62
+ if imdb_match:
63
+ return imdb_match.group(1)
64
+
65
+ # TMDb movie or TV
66
+ tmdb_match = re.search(r'/((movie|tv))/(\d+)', url)
67
+ if tmdb_match:
68
+ return tmdb_match.group(3)
69
+
70
+ return None
71
+
72
  async def safe_imdb_search(title: str, type_: str) -> str | None:
 
73
  key = f"imdb::{type_}::{title}"
74
  if key in IMDB_CACHE:
75
  return IMDB_CACHE[key]
 
84
  return None
85
 
86
  async def safe_tmdb_search(title: str, type_: str, year=None):
 
87
  key = f"tmdb_search::{type_}::{title}::{year}"
88
  if key in TMDB_SEARCH_CACHE:
89
  return TMDB_SEARCH_CACHE[key]
90
  try:
91
  async with API_SEMAPHORE:
92
  if type_ == "movie":
93
+ results = await tmdb.search().movies(query=title, year=year) if year else await tmdb.search().movies(query=title)
 
 
 
94
  else:
95
  results = await tmdb.search().tv(query=title)
96
  res = results[0] if results else None
 
101
  TMDB_SEARCH_CACHE[key] = None
102
  return None
103
 
104
+ async def _tmdb_movie_details(movie_id):
105
+ if movie_id in TMDB_DETAILS_CACHE:
106
+ return TMDB_DETAILS_CACHE[movie_id]
107
+ try:
108
+ async with API_SEMAPHORE:
109
+ details = await tmdb.movie(movie_id).details(
110
+ append_to_response="external_ids,credits"
111
+ )
112
+ images = await tmdb.movie(movie_id).images()
113
+ details.images = images
114
+
115
+ TMDB_DETAILS_CACHE[movie_id] = details
116
+ return details
117
+ except Exception as e:
118
+ LOGGER.warning(f"TMDb movie details fetch failed for id={movie_id}: {e}")
119
+ TMDB_DETAILS_CACHE[movie_id] = None
120
+ return None
121
+
122
+
123
  async def _tmdb_tv_details(tv_id):
124
  if tv_id in TMDB_DETAILS_CACHE:
125
  return TMDB_DETAILS_CACHE[tv_id]
126
  try:
127
  async with API_SEMAPHORE:
128
+ details = await tmdb.tv(tv_id).details(
129
+ append_to_response="external_ids,credits"
130
+ )
131
+ images = await tmdb.tv(tv_id).images()
132
+ details.images = images
133
  TMDB_DETAILS_CACHE[tv_id] = details
134
  return details
135
  except Exception as e:
 
137
  TMDB_DETAILS_CACHE[tv_id] = None
138
  return None
139
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  async def _tmdb_episode_details(tv_id, season, episode):
142
  key = (tv_id, season, episode)
 
151
  EPISODE_CACHE[key] = None
152
  return None
153
 
154
+ # ----------------- Main Metadata -----------------
155
  async def metadata(filename: str, channel: int, msg_id) -> dict | None:
156
  try:
157
  parsed = PTN.parse(filename)
 
175
  episode = parsed.get("episode")
176
  year = parsed.get("year")
177
  quality = parsed.get("resolution")
 
 
 
 
 
178
  if isinstance(season, list) or isinstance(episode, list):
179
  LOGGER.warning(f"Invalid season/episode format for {filename}: {parsed}")
180
  return None
 
181
  if season and not episode:
182
  LOGGER.warning(f"Missing episode in {filename}: {parsed}")
183
  return None
184
+ if not quality:
185
+ LOGGER.warning(f"Skipping {filename}: No resolution (parsed={parsed})")
186
+ return None
187
+ if not title:
188
+ LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
189
+ return None
190
 
191
+ # Extract default ID
192
  default_id = None
193
  try:
194
+ default_id = extract_default_id(Backend.USE_DEFAULT_ID)
195
  except Exception:
196
  pass
 
197
  if not default_id:
198
  try:
199
+ default_id = extract_default_id(filename)
200
  except Exception:
201
  pass
202
 
 
 
 
 
203
  data = {"chat_id": channel, "msg_id": msg_id}
204
  try:
205
  encoded_string = await encode_string(data)
 
219
 
220
  # ----------------- TV Metadata -----------------
221
  async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
222
+ imdb_id = tmdb_id = None
223
+ use_tmdb = False
224
+
225
+ if default_id:
226
+ if str(default_id).startswith("tt"):
227
+ imdb_id = default_id
228
+ elif str(default_id).isdigit():
229
+ tmdb_id = int(default_id)
230
+ use_tmdb = True
231
+
232
+ if not imdb_id and not tmdb_id:
233
+ imdb_id = await safe_imdb_search(title, "tvSeries")
234
+ use_tmdb = not bool(imdb_id)
235
 
236
+ tv_details = ep_details = None
237
+
238
+ # IMDb fetch
239
+ if imdb_id and not use_tmdb:
240
  try:
241
  if imdb_id in IMDB_CACHE:
242
  tv_details = IMDB_CACHE[imdb_id]
 
244
  async with API_SEMAPHORE:
245
  tv_details = await get_detail(imdb_id=imdb_id)
246
  IMDB_CACHE[imdb_id] = tv_details
247
+
248
  cache_key = f"{imdb_id}::{season}::{episode}"
249
  if cache_key in EPISODE_CACHE:
250
  ep_details = EPISODE_CACHE[cache_key]
 
254
  EPISODE_CACHE[cache_key] = ep_details
255
  except Exception as e:
256
  LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
257
+ use_tmdb = True
258
+
259
+ # TMDb fallback
260
+ if use_tmdb or (tmdb_id and not tv_details):
261
+ if not tmdb_id:
262
+ tmdb_result = await safe_tmdb_search(title, "tv")
263
+ if not tmdb_result:
264
+ LOGGER.warning(f"No TMDb result for '{title}'")
265
+ return None
266
+ tmdb_id = tmdb_result.id
267
+
268
+ tv_details = await _tmdb_tv_details(tmdb_id)
269
  if not tv_details:
270
+ LOGGER.warning(f"TMDb TV details fetch failed for '{title}' (id={tmdb_id})")
271
  return None
272
+ ep_details = await _tmdb_episode_details(tmdb_id, season, episode)
273
 
 
 
 
 
274
  credits = getattr(tv_details, "credits", None) or {}
275
+ cast_names = [getattr(c, "name", getattr(c, "original_name", None)) for c in (getattr(credits, "cast", []) or [])]
 
 
 
 
 
 
276
 
277
  return {
278
  "tmdb_id": tv_details.id,
 
287
  "genres": [g.name for g in (tv_details.genres or [])],
288
  "media_type": "tv",
289
  "cast": cast_names,
290
+ "runtime": (
291
+ f"{(getattr(ep_details, 'runtime', None) or (tv_details.episode_run_time[0] if tv_details.episode_run_time else None))} min"
292
+ if (getattr(ep_details, "runtime", None) or (tv_details.episode_run_time[0] if tv_details.episode_run_time else None))
293
+ else ""
294
+ ),
295
  "season_number": season,
296
  "episode_number": episode,
297
  "episode_title": getattr(ep_details, "name", f"S{season}E{episode}") if ep_details else f"{tv_details.name} S{season}E{episode}",
 
302
  "encoded_string": encoded_string,
303
  }
304
 
305
+ # IMDb fallback return
 
 
 
 
306
  images = format_imdb_images(imdb_id)
307
+ if tv_details is None:
308
+ tv_details = {}
309
+ if ep_details is None:
310
+ ep_details = {}
311
 
312
  return {
313
+ "tmdb_id": tv_details.get("moviedb_id", ""),
314
  "imdb_id": imdb_id,
315
  "title": tv_details.get("title", title),
316
  "year": tv_details.get("releaseDetailed", {}).get("year", 0),
 
320
  "backdrop": images["backdrop"],
321
  "logo": images["logo"],
322
  "cast": tv_details.get("cast", []),
323
+ "runtime": tv_details.get("runtime", ""),
324
  "genres": tv_details.get("genre", []),
325
  "media_type": "tv",
326
  "season_number": season,
 
335
 
336
  # ----------------- Movie Metadata -----------------
337
  async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
338
+ imdb_id = tmdb_id = None
339
+ use_tmdb = False
340
+
341
+ if default_id:
342
+ if str(default_id).startswith("tt"):
343
+ imdb_id = default_id
344
+ elif str(default_id).isdigit():
345
+ tmdb_id = int(default_id)
346
+ use_tmdb = True
347
 
348
+ if not imdb_id and not tmdb_id:
349
+ imdb_id = await safe_imdb_search(f"{title} {year}" if year else title, "movie")
350
+ use_tmdb = not bool(imdb_id)
351
+
352
+ movie_details = None
353
+
354
+ if imdb_id and not use_tmdb:
355
  try:
356
  if imdb_id in IMDB_CACHE:
357
  movie_details = IMDB_CACHE[imdb_id]
 
361
  IMDB_CACHE[imdb_id] = movie_details
362
  except Exception as e:
363
  LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
364
+ use_tmdb = True
365
+
366
+ if use_tmdb or (tmdb_id and not movie_details):
367
+ if not tmdb_id:
368
+ tmdb_result = await safe_tmdb_search(title, "movie", year)
369
+ if not tmdb_result:
370
+ LOGGER.warning(f"No TMDb movie found for '{title}'")
371
+ return None
372
+ tmdb_id = tmdb_result.id
373
+
374
+ movie_details = await _tmdb_movie_details(tmdb_id)
375
+ if not movie_details:
376
+ LOGGER.warning(f"TMDb movie details fetch failed for '{title}' (id={tmdb_id}), skipping.")
377
  return None
378
 
 
 
379
  credits = getattr(movie_details, "credits", None) or {}
380
+ cast_names = [getattr(c, "name", getattr(c, "original_name", None)) for c in (getattr(credits, "cast", []) or [])]
381
+
 
 
 
 
 
382
  return {
383
  "tmdb_id": movie_details.id,
384
  "imdb_id": movie_details.external_ids.imdb_id if getattr(movie_details, "external_ids", None) else None,
 
390
  "backdrop": format_tmdb_image(movie_details.backdrop_path, "original"),
391
  "logo": get_tmdb_logo(getattr(movie_details, "images", None)),
392
  "cast": cast_names,
393
+ "runtime": f"{getattr(movie_details, 'runtime', 0)} min" if getattr(movie_details, "runtime", None) else "",
394
  "media_type": "movie",
395
  "genres": [g.name for g in (movie_details.genres or [])],
396
  "quality": quality,
397
  "encoded_string": encoded_string,
398
  }
399
 
400
+ # IMDb fallback return
 
401
  images = format_imdb_images(imdb_id)
402
+ if movie_details is None:
403
+ movie_details = {}
404
 
405
  return {
406
+ "tmdb_id": movie_details.get("moviedb_id", ""),
407
  "imdb_id": imdb_id,
408
  "title": movie_details.get("title", title),
409
  "year": movie_details.get("releaseDetailed", {}).get("year", 0),
 
413
  "backdrop": images["backdrop"],
414
  "logo": images["logo"],
415
  "cast": movie_details.get("cast", []),
416
+ "runtime": movie_details.get("runtime", ""),
417
  "media_type": "movie",
418
  "genres": movie_details.get("genre", []),
419
  "quality": quality,
Backend/helper/modal.py CHANGED
@@ -33,6 +33,7 @@ class TVShowSchema(BaseModel):
33
  backdrop: Optional[str] = None
34
  logo: Optional[str] = None
35
  cast: Optional[List[str]] = None
 
36
  media_type: str
37
  updated_on: datetime = Field(default_factory=datetime.utcnow)
38
  seasons: List[Season]
@@ -50,6 +51,7 @@ class MovieSchema(BaseModel):
50
  backdrop: Optional[str] = None
51
  logo: Optional[str] = None
52
  cast: Optional[List[str]] = None
 
53
  media_type: str
54
  updated_on: datetime = Field(default_factory=datetime.utcnow)
55
  telegram: Optional[List[QualityDetail]]
 
33
  backdrop: Optional[str] = None
34
  logo: Optional[str] = None
35
  cast: Optional[List[str]] = None
36
+ runtime: Optional[str] = None
37
  media_type: str
38
  updated_on: datetime = Field(default_factory=datetime.utcnow)
39
  seasons: List[Season]
 
51
  backdrop: Optional[str] = None
52
  logo: Optional[str] = None
53
  cast: Optional[List[str]] = None
54
+ runtime: Optional[str] = None
55
  media_type: str
56
  updated_on: datetime = Field(default_factory=datetime.utcnow)
57
  telegram: Optional[List[QualityDetail]]
Backend/helper/pyro.py CHANGED
@@ -102,14 +102,6 @@ def get_readable_time(seconds: int) -> str:
102
  return readable_time
103
 
104
 
105
- def extract_tmdb_id(url):
106
- # Match IMDb URLs
107
- imdb_match = re.search(r'/title/(tt\d+)', url)
108
- if imdb_match:
109
- return imdb_match.group(1)
110
-
111
- return None
112
-
113
 
114
  def remove_urls(text):
115
  if not text:
 
102
  return readable_time
103
 
104
 
 
 
 
 
 
 
 
 
105
 
106
  def remove_urls(text):
107
  if not text:
Backend/pyrofork/plugins/fix_metadata.py CHANGED
@@ -74,6 +74,7 @@ async def fix_metadata_handler(_, message):
74
  # -------------------------
75
  # MOVIE UPDATE
76
  # -------------------------
 
77
  async def _safe_update_movie(collection, movie_doc):
78
  nonlocal DONE
79
  if CANCEL_REQUESTED:
@@ -81,36 +82,93 @@ async def fix_metadata_handler(_, message):
81
 
82
  async with semaphore:
83
  try:
 
84
  imdb_id = movie_doc.get("imdb_id")
85
- title = movie_doc["title"]
 
86
  year = movie_doc.get("release_year")
87
-
88
- # Always fetch metadata to update tmdb_id + imdb_id
89
- meta = await fetch_movie_metadata(
90
- title=title,
91
- encoded_string=None,
92
- year=year,
93
- quality=None,
94
- default_id=None
95
- )
96
-
97
- if meta:
98
- update_data = {
99
- "tmdb_id": meta.get("tmdb_id"),
100
- "imdb_id": meta.get("imdb_id"),
101
- "rating": meta.get("rate"),
102
- }
103
-
104
- # only overwrite empty fields (not IDs)
105
- for key in ["cast", "description", "genres", "poster", "backdrop", "logo"]:
106
- if not movie_doc.get(key):
107
- update_data[key] = meta.get(key)
108
-
109
- await collection.update_one(
110
- {"imdb_id": imdb_id},
111
- {"$set": update_data}
 
 
112
  )
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  DONE += 1
115
 
116
  except Exception as e:
@@ -120,6 +178,7 @@ async def fix_metadata_handler(_, message):
120
  # -------------------------
121
  # TV UPDATE
122
  # -------------------------
 
123
  async def _safe_update_tv(collection, tv_doc):
124
  nonlocal DONE
125
  if CANCEL_REQUESTED:
@@ -127,90 +186,149 @@ async def fix_metadata_handler(_, message):
127
 
128
  async with semaphore:
129
  try:
 
130
  imdb_id = tv_doc.get("imdb_id")
131
- title = tv_doc["title"]
 
132
  year = tv_doc.get("release_year")
133
-
134
- # Always fetch metadata for refreshed imdb_id + tmdb_id
135
- meta = await fetch_tv_metadata(
136
- title=title,
137
- season=1,
138
- episode=1,
139
- encoded_string=None,
140
- year=year,
141
- quality=None,
142
- default_id=None
143
- )
144
-
145
- if meta:
146
- update_data = {
147
- "tmdb_id": meta.get("tmdb_id"),
148
- "imdb_id": meta.get("imdb_id"),
149
- "rating": meta.get("rate"),
150
- }
151
-
152
- # Only overwrite fields that are empty
153
- for key in ["cast", "description", "genres", "poster", "backdrop", "logo"]:
154
- if not tv_doc.get(key):
155
- update_data[key] = meta.get(key)
156
-
157
- await collection.update_one(
158
- {"imdb_id": imdb_id},
159
- {"$set": update_data}
160
  )
161
-
162
- # EPISODES UPDATE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  tasks = []
164
- for season in tv_doc.get("seasons", []):
165
- s_num = season.get("season_number")
166
-
167
- for ep in season.get("episodes", []):
168
- e_num = ep.get("episode_number")
169
-
170
- # Skip if already complete
171
- if ep.get("overview") and ep.get("released") and ep.get("episode_backdrop"):
172
- continue
173
-
174
- async def ep_task(s_local=s_num, e_local=e_num):
175
- try:
176
- ep_meta = await fetch_tv_metadata(
177
- title=title,
178
- season=s_local,
179
- episode=e_local,
180
- encoded_string=None,
181
- year=year,
182
- quality=None,
183
- default_id=None
184
- )
185
-
186
- if ep_meta:
187
- await collection.update_one(
188
- {"imdb_id": imdb_id},
189
- {"$set": {
190
- "seasons.$[s].episodes.$[e].overview": ep_meta.get("episode_overview"),
191
- "seasons.$[s].episodes.$[e].released": ep_meta.get("episode_released"),
192
- "seasons.$[s].episodes.$[e].episode_backdrop": ep_meta.get("episode_backdrop"),
193
- }},
194
- array_filters=[
195
- {"s.season_number": s_local},
196
- {"e.episode_number": e_local}
197
- ]
198
- )
199
- except Exception as e:
200
- LOGGER.exception(f"Error updating episode {title} S{s_local}E{e_local}: {e}")
201
 
202
- tasks.append(asyncio.create_task(ep_task()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
- if tasks:
205
- for i in range(0, len(tasks), CONCURRENCY):
206
- await asyncio.gather(*tasks[i:i+CONCURRENCY], return_exceptions=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
  DONE += 1
209
 
210
  except Exception as e:
211
  LOGGER.exception(f"Error updating TV show {tv_doc.get('title')}: {e}")
212
  DONE += 1
213
-
214
  # -------------------------
215
  # UPDATE MOVIES
216
  # -------------------------
 
74
  # -------------------------
75
  # MOVIE UPDATE
76
  # -------------------------
77
+
78
  async def _safe_update_movie(collection, movie_doc):
79
  nonlocal DONE
80
  if CANCEL_REQUESTED:
 
82
 
83
  async with semaphore:
84
  try:
85
+ doc_id = movie_doc.get("_id")
86
  imdb_id = movie_doc.get("imdb_id")
87
+ tmdb_id = movie_doc.get("tmdb_id")
88
+ title = movie_doc.get("title")
89
  year = movie_doc.get("release_year")
90
+
91
+ meta_1 = None
92
+ meta_2 = None
93
+
94
+
95
+ if imdb_id:
96
+ meta_1 = await fetch_movie_metadata(
97
+ title=title, encoded_string=None, year=year, quality=None, default_id=imdb_id
98
+ )
99
+ fetched_tmdb_id = meta_1.get("tmdb_id") if meta_1 else None
100
+ if tmdb_id or fetched_tmdb_id:
101
+ meta_2 = await fetch_movie_metadata(
102
+ title=title, encoded_string=None, year=year, quality=None, default_id=(tmdb_id or fetched_tmdb_id)
103
+ )
104
+
105
+ elif tmdb_id:
106
+ meta_1 = await fetch_movie_metadata(
107
+ title=title, encoded_string=None, year=year, quality=None, default_id=tmdb_id
108
+ )
109
+ fetched_imdb_id = meta_1.get("imdb_id") if meta_1 else None
110
+ if fetched_imdb_id:
111
+ meta_2 = await fetch_movie_metadata(
112
+ title=title, encoded_string=None, year=year, quality=None, default_id=fetched_imdb_id
113
+ )
114
+ else:
115
+ meta_1 = await fetch_movie_metadata(
116
+ title=title, encoded_string=None, year=year, quality=None, default_id=None
117
  )
118
 
119
+ fetched_imdb_id = meta_1.get("imdb_id") if meta_1 else None
120
+ fetched_tmdb_id = meta_1.get("tmdb_id") if meta_1 else None
121
+
122
+ if fetched_imdb_id:
123
+ meta_2 = await fetch_movie_metadata(
124
+ title=title, encoded_string=None, year=year, quality=None, default_id=fetched_imdb_id
125
+ )
126
+ elif fetched_tmdb_id:
127
+ meta_2 = await fetch_movie_metadata(
128
+ title=title, encoded_string=None, year=year, quality=None, default_id=fetched_tmdb_id
129
+ )
130
+
131
+ final_set_query = {}
132
+ current_data = dict(movie_doc)
133
+ api_map = {
134
+ "imdb_id": "imdb_id",
135
+ "tmdb_id": "tmdb_id",
136
+ "rate": "rating",
137
+ "cast": "cast",
138
+ "description": "description",
139
+ "genres": "genres",
140
+ "poster": "poster",
141
+ "backdrop": "backdrop",
142
+ "runtime": "runtime",
143
+ "logo": "logo"
144
+ }
145
+ for meta in [meta_1, meta_2]:
146
+ if not meta:
147
+ continue
148
+
149
+ for api_key, db_key in api_map.items():
150
+ new_val = meta.get(api_key)
151
+ is_empty = False
152
+ if db_key == "rating":
153
+ is_empty = not current_data.get(db_key) or current_data.get(db_key) == 0
154
+ else:
155
+ is_empty = not current_data.get(db_key)
156
+ if is_empty and new_val:
157
+ final_set_query[db_key] = new_val
158
+ current_data[db_key] = new_val
159
+
160
+ if final_set_query:
161
+ if doc_id:
162
+ await collection.update_one(
163
+ {"_id": doc_id},
164
+ {"$set": final_set_query}
165
+ )
166
+ else:
167
+ await collection.update_one(
168
+ {"imdb_id": movie_doc.get("imdb_id")},
169
+ {"$set": final_set_query}
170
+ )
171
+
172
  DONE += 1
173
 
174
  except Exception as e:
 
178
  # -------------------------
179
  # TV UPDATE
180
  # -------------------------
181
+
182
  async def _safe_update_tv(collection, tv_doc):
183
  nonlocal DONE
184
  if CANCEL_REQUESTED:
 
186
 
187
  async with semaphore:
188
  try:
189
+ doc_id = tv_doc.get("_id")
190
  imdb_id = tv_doc.get("imdb_id")
191
+ tmdb_id = tv_doc.get("tmdb_id")
192
+ title = tv_doc.get("title")
193
  year = tv_doc.get("release_year")
194
+
195
+ meta_1 = None
196
+ meta_2 = None
197
+ if imdb_id:
198
+ meta_1 = await fetch_tv_metadata(
199
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=imdb_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  )
201
+ fetched_tmdb_id = meta_1.get("tmdb_id") if meta_1 else None
202
+ if tmdb_id or fetched_tmdb_id:
203
+ meta_2 = await fetch_tv_metadata(
204
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=(tmdb_id or fetched_tmdb_id)
205
+ )
206
+ elif tmdb_id:
207
+ meta_1 = await fetch_tv_metadata(
208
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=tmdb_id
209
+ )
210
+ fetched_imdb_id = meta_1.get("imdb_id") if meta_1 else None
211
+ if fetched_imdb_id:
212
+ meta_2 = await fetch_tv_metadata(
213
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=fetched_imdb_id
214
+ )
215
+ else:
216
+ meta_1 = await fetch_tv_metadata(
217
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=None # Title search
218
+ )
219
+ fetched_imdb_id = meta_1.get("imdb_id") if meta_1 else None
220
+ fetched_tmdb_id = meta_1.get("tmdb_id") if meta_1 else None
221
+
222
+ if fetched_imdb_id:
223
+ meta_2 = await fetch_tv_metadata(
224
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=fetched_imdb_id
225
+ )
226
+ elif fetched_tmdb_id:
227
+ meta_2 = await fetch_tv_metadata(
228
+ title=title, season=1, episode=1, encoded_string=None, year=year, quality=None, default_id=fetched_tmdb_id
229
+ )
230
+
231
+ final_set_query = {}
232
+ current_data = dict(tv_doc)
233
+ api_map = {
234
+ "imdb_id": "imdb_id",
235
+ "tmdb_id": "tmdb_id",
236
+ "rate": "rating",
237
+ "cast": "cast",
238
+ "description": "description",
239
+ "genres": "genres",
240
+ "poster": "poster",
241
+ "backdrop": "backdrop",
242
+ "runtime": "runtime",
243
+ "logo": "logo"
244
+ }
245
+
246
+ for meta in [meta_1, meta_2]:
247
+ if not meta:
248
+ continue
249
+
250
+ for api_key, db_key in api_map.items():
251
+ new_val = meta.get(api_key)
252
+
253
+ is_empty = False
254
+ if db_key == "rating":
255
+ is_empty = not current_data.get(db_key) or current_data.get(db_key) == 0
256
+ else:
257
+ is_empty = not current_data.get(db_key)
258
+
259
+ if is_empty and new_val:
260
+ final_set_query[db_key] = new_val
261
+ current_data[db_key] = new_val
262
+ if final_set_query:
263
+ if doc_id:
264
+ await collection.update_one(
265
+ {"_id": doc_id},
266
+ {"$set": final_set_query}
267
+ )
268
+ else:
269
+ await collection.update_one(
270
+ {"imdb_id": tv_doc.get("imdb_id")},
271
+ {"$set": final_set_query}
272
+ )
273
  tasks = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
+ final_imdb_id = current_data.get("imdb_id")
276
+
277
+ if final_imdb_id:
278
+ for season in tv_doc.get("seasons", []):
279
+ s_num = season.get("season_number")
280
+
281
+ for ep in season.get("episodes", []):
282
+ e_num = ep.get("episode_number")
283
+
284
+ if ep.get("overview") and ep.get("released") and ep.get("episode_backdrop"):
285
+ continue
286
+
287
+ async def ep_task(s_local=s_num, e_local=e_num):
288
+ try:
289
+ ep_meta = await fetch_tv_metadata(
290
+ title=title,
291
+ season=s_local,
292
+ episode=e_local,
293
+ encoded_string=None,
294
+ year=year,
295
+ quality=None,
296
+ default_id=final_imdb_id
297
+ )
298
 
299
+ if ep_meta:
300
+ ep_update_query = {}
301
+ if ep_meta.get("episode_overview"):
302
+ ep_update_query["seasons.$[s].episodes.$[e].overview"] = ep_meta.get("episode_overview")
303
+ if ep_meta.get("episode_released"):
304
+ ep_update_query["seasons.$[s].episodes.$[e].released"] = ep_meta.get("episode_released")
305
+ if ep_meta.get("episode_backdrop"):
306
+ ep_update_query["seasons.$[s].episodes.$[e].episode_backdrop"] = ep_meta.get("episode_backdrop")
307
+
308
+ if ep_update_query:
309
+ filter_query = {"_id": doc_id} if doc_id else {"imdb_id": tv_doc.get("imdb_id")}
310
+ await collection.update_one(
311
+ filter_query,
312
+ {"$set": ep_update_query},
313
+ array_filters=[
314
+ {"s.season_number": s_local},
315
+ {"e.episode_number": e_local}
316
+ ]
317
+ )
318
+ except Exception as e:
319
+ LOGGER.exception(f"Error updating episode {title} S{s_local}E{e_local}: {e}")
320
+
321
+ tasks.append(asyncio.create_task(ep_task()))
322
+
323
+ if tasks:
324
+ for i in range(0, len(tasks), CONCURRENCY):
325
+ await asyncio.gather(*tasks[i:i+CONCURRENCY], return_exceptions=True)
326
 
327
  DONE += 1
328
 
329
  except Exception as e:
330
  LOGGER.exception(f"Error updating TV show {tv_doc.get('title')}: {e}")
331
  DONE += 1
 
332
  # -------------------------
333
  # UPDATE MOVIES
334
  # -------------------------
Backend/pyrofork/plugins/manual.py CHANGED
@@ -15,7 +15,7 @@ async def manual(client: Client, message: Message):
15
  Backend.USE_DEFAULT_ID = url
16
 
17
  await message.reply_text(
18
- f"✅ <b>Default IMDB URL Set!</b>\n\n"
19
  f"Now the bot will use this URL for any files you send:\n"
20
  f"<code>{Backend.USE_DEFAULT_ID}</code>\n\n"
21
  f"<b>Instructions:</b>\n"
@@ -27,7 +27,7 @@ async def manual(client: Client, message: Message):
27
  else:
28
  Backend.USE_DEFAULT_ID = None
29
  await message.reply_text(
30
- "✅ <b>Default IMDB URL Removed!</b>\n\n"
31
  "You can now manually upload files without linking to a default IMDB URL.",
32
  quote=True,
33
  parse_mode=enums.ParseMode.HTML
@@ -36,4 +36,4 @@ async def manual(client: Client, message: Message):
36
  except Exception as e:
37
  LOGGER.error(f"Error in /set handler: {e}")
38
  await message.reply_text(f"⚠️ An error occurred: {e}")
39
-
 
15
  Backend.USE_DEFAULT_ID = url
16
 
17
  await message.reply_text(
18
+ f"✅ <b>Default IMDB/TMDB URL Set!</b>\n\n"
19
  f"Now the bot will use this URL for any files you send:\n"
20
  f"<code>{Backend.USE_DEFAULT_ID}</code>\n\n"
21
  f"<b>Instructions:</b>\n"
 
27
  else:
28
  Backend.USE_DEFAULT_ID = None
29
  await message.reply_text(
30
+ "✅ <b>Default IMDB/TMDB URL Removed!</b>\n\n"
31
  "You can now manually upload files without linking to a default IMDB URL.",
32
  quote=True,
33
  parse_mode=enums.ParseMode.HTML
 
36
  except Exception as e:
37
  LOGGER.error(f"Error in /set handler: {e}")
38
  await message.reply_text(f"⚠️ An error occurred: {e}")
39
+
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "Telegram-Stremio"
3
- version = "1.4.2"
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.3"
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.4.1"
905
  source = { virtual = "." }
906
  dependencies = [
907
  { name = "aiofiles" },
 
901
 
902
  [[package]]
903
  name = "telegram-stremio"
904
+ version = "1.4.2"
905
  source = { virtual = "." }
906
  dependencies = [
907
  { name = "aiofiles" },