weebzone commited on
Commit
7232f1e
·
1 Parent(s): 746c953

fix metadata issue and fix_metadata command

Browse files
Backend/helper/database.py CHANGED
@@ -245,9 +245,8 @@ class Database:
245
  LOGGER.error(f"Validation error: {e}")
246
  return None
247
 
 
248
  tmdb_id = movie_dict["tmdb_id"]
249
-
250
-
251
  title = movie_dict["title"]
252
  release_year = movie_dict["release_year"]
253
  quality_to_update = movie_dict["telegram"][0]
@@ -262,9 +261,16 @@ class Database:
262
 
263
  for db_index in range(1, total_storage_dbs + 1):
264
  db_key = f"storage_{db_index}"
265
- movie = await self.dbs[db_key]["movie"].find_one(
266
- {"title": title, "release_year": release_year}
267
- )
 
 
 
 
 
 
 
268
  if movie:
269
  existing_db_key = db_key
270
  existing_db_index = db_index
@@ -326,10 +332,9 @@ class Database:
326
  except ValidationError as e:
327
  LOGGER.error(f"Validation error: {e}")
328
  return None
329
-
330
- tmdb_id = tv_show_dict["tmdb_id"]
331
 
332
-
 
333
  title = tv_show_dict["title"]
334
  release_year = tv_show_dict["release_year"]
335
  current_db_key = f"storage_{self.current_db_index}"
@@ -341,9 +346,16 @@ class Database:
341
 
342
  for db_index in range(1, total_storage_dbs + 1):
343
  db_key = f"storage_{db_index}"
344
- tv = await self.dbs[db_key]["tv"].find_one(
345
- {"title": title, "release_year": release_year}
346
- )
 
 
 
 
 
 
 
347
  if tv:
348
  existing_db_key = db_key
349
  existing_db_index = db_index
 
245
  LOGGER.error(f"Validation error: {e}")
246
  return None
247
 
248
+ imdb_id = movie_dict["imdb_id"]
249
  tmdb_id = movie_dict["tmdb_id"]
 
 
250
  title = movie_dict["title"]
251
  release_year = movie_dict["release_year"]
252
  quality_to_update = movie_dict["telegram"][0]
 
261
 
262
  for db_index in range(1, total_storage_dbs + 1):
263
  db_key = f"storage_{db_index}"
264
+ movie = None
265
+ if imdb_id:
266
+ movie = await self.dbs[db_key]["movie"].find_one({"imdb_id": imdb_id})
267
+ if not movie and tmdb_id:
268
+ movie = await self.dbs[db_key]["movie"].find_one({"tmdb_id": tmdb_id})
269
+ if not movie and title and release_year:
270
+ movie = await self.dbs[db_key]["movie"].find_one({
271
+ "title": title,
272
+ "release_year": release_year
273
+ })
274
  if movie:
275
  existing_db_key = db_key
276
  existing_db_index = db_index
 
332
  except ValidationError as e:
333
  LOGGER.error(f"Validation error: {e}")
334
  return None
 
 
335
 
336
+ imdb_id = tv_show_dict.get("imdb_id")
337
+ tmdb_id = tv_show_dict.get("tmdb_id")
338
  title = tv_show_dict["title"]
339
  release_year = tv_show_dict["release_year"]
340
  current_db_key = f"storage_{self.current_db_index}"
 
346
 
347
  for db_index in range(1, total_storage_dbs + 1):
348
  db_key = f"storage_{db_index}"
349
+ tv = None
350
+ if imdb_id:
351
+ tv = await self.dbs[db_key]["tv"].find_one({"imdb_id": imdb_id})
352
+ if not tv and tmdb_id:
353
+ tv = await self.dbs[db_key]["tv"].find_one({"tmdb_id": tmdb_id})
354
+ if not tv and title and release_year:
355
+ tv = await self.dbs[db_key]["tv"].find_one({
356
+ "title": title,
357
+ "release_year": release_year
358
+ })
359
  if tv:
360
  existing_db_key = db_key
361
  existing_db_index = db_index
Backend/helper/metadata.py CHANGED
@@ -57,7 +57,6 @@ def format_imdb_images(imdb_id: str) -> dict:
57
  }
58
 
59
  def extract_default_id(url: str) -> str | None:
60
- """Extract IMDb or TMDb ID from string."""
61
  # IMDb
62
  imdb_match = re.search(r'/title/(tt\d+)', url)
63
  if imdb_match:
@@ -189,7 +188,7 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
189
  LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
190
  return None
191
 
192
- # Extract default ID
193
  default_id = None
194
  try:
195
  default_id = extract_default_id(Backend.USE_DEFAULT_ID)
@@ -220,155 +219,239 @@ async def metadata(filename: str, channel: int, msg_id) -> dict | None:
220
 
221
  # ----------------- TV Metadata -----------------
222
  async def fetch_tv_metadata(title, season, episode, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
223
- imdb_id = tmdb_id = None
 
 
 
224
  use_tmdb = False
225
 
 
 
 
226
  if default_id:
227
- if str(default_id).startswith("tt"):
 
228
  imdb_id = default_id
229
- elif str(default_id).isdigit():
 
230
  tmdb_id = int(default_id)
231
  use_tmdb = True
232
 
 
 
 
233
  if not imdb_id and not tmdb_id:
234
  imdb_id = await safe_imdb_search(title, "tvSeries")
235
  use_tmdb = not bool(imdb_id)
236
 
237
- tv_details = ep_details = None
238
-
239
- # IMDb fetch
240
  if imdb_id and not use_tmdb:
241
  try:
 
242
  if imdb_id in IMDB_CACHE:
243
- tv_details = IMDB_CACHE[imdb_id]
244
  else:
245
  async with API_SEMAPHORE:
246
- tv_details = await get_detail(imdb_id=imdb_id, media_type="tvSeries")
247
- IMDB_CACHE[imdb_id] = tv_details
248
 
249
- cache_key = f"{imdb_id}::{season}::{episode}"
250
- if cache_key in EPISODE_CACHE:
251
- ep_details = EPISODE_CACHE[cache_key]
 
252
  else:
253
  async with API_SEMAPHORE:
254
- ep_details = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
255
- EPISODE_CACHE[cache_key] = ep_details
 
256
  except Exception as e:
257
- LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}]: {e}")
 
 
258
  use_tmdb = True
259
 
260
- # TMDb fallback
261
- if use_tmdb or (tmdb_id and not tv_details):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  if not tmdb_id:
263
- tmdb_result = await safe_tmdb_search(title, "tv")
264
- if not tmdb_result:
265
- LOGGER.warning(f"No TMDb result for '{title}'")
266
  return None
267
- tmdb_id = tmdb_result.id
268
 
269
- tv_details = await _tmdb_tv_details(tmdb_id)
270
- if not tv_details:
271
- LOGGER.warning(f"TMDb TV details fetch failed for '{title}' (id={tmdb_id})")
 
272
  return None
273
- ep_details = await _tmdb_episode_details(tmdb_id, season, episode)
274
 
275
- credits = getattr(tv_details, "credits", None) or {}
276
- cast_names = [getattr(c, "name", getattr(c, "original_name", None)) for c in (getattr(credits, "cast", []) or [])]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  return {
279
- "tmdb_id": tv_details.id,
280
- "imdb_id": getattr(tv_details, "external_ids", {}).imdb_id if getattr(tv_details, "external_ids", None) else getattr(tv_details, "imdb_id", None),
281
- "title": tv_details.name,
282
- "year": getattr(tv_details.first_air_date, "year", 0) if getattr(tv_details, "first_air_date", None) else 0,
283
- "rate": getattr(tv_details, "vote_average", 0) or 0,
284
- "description": tv_details.overview or "",
285
- "poster": format_tmdb_image(tv_details.poster_path),
286
- "backdrop": format_tmdb_image(tv_details.backdrop_path, "original"),
287
- "logo": get_tmdb_logo(getattr(tv_details, "images", None)),
288
- "genres": [g.name for g in (tv_details.genres or [])],
289
  "media_type": "tv",
290
- "cast": cast_names,
291
- "runtime": (
292
- f"{(getattr(ep_details, 'runtime', None) or (tv_details.episode_run_time[0] if tv_details.episode_run_time else None))} min"
293
- if (getattr(ep_details, "runtime", None) or (tv_details.episode_run_time[0] if tv_details.episode_run_time else None))
294
- else ""
295
- ),
296
  "season_number": season,
297
  "episode_number": episode,
298
- "episode_title": getattr(ep_details, "name", f"S{season}E{episode}") if ep_details else f"Epidose {episode}",
299
- "episode_backdrop": format_tmdb_image(getattr(ep_details, "still_path", None), "original") if ep_details else "",
300
- "episode_overview": getattr(ep_details, "overview", "") if ep_details else "",
301
- "episode_released": (str(ep_details.air_date.strftime("%Y-%m-%dT05:00:00.000Z")) if getattr(ep_details, "air_date", None) else ""),
 
 
 
 
 
302
  "quality": quality,
303
  "encoded_string": encoded_string,
304
  }
305
 
306
- # IMDb fallback return
 
 
 
 
 
307
  images = format_imdb_images(imdb_id)
308
- if tv_details is None:
309
- tv_details = {}
310
- if ep_details is None:
311
- ep_details = {}
312
 
313
  return {
314
- "tmdb_id": tv_details.get("moviedb_id") or None,
315
  "imdb_id": imdb_id,
316
- "title": tv_details.get("title", title),
317
- "year": tv_details.get("releaseDetailed", {}).get("year", 0),
318
- "rate": tv_details.get("rating", {}).get("star", 0),
319
- "description": tv_details.get("plot", ""),
320
  "poster": images["poster"],
321
  "backdrop": images["backdrop"],
322
  "logo": images["logo"],
323
- "cast": tv_details.get("cast", []),
324
- "runtime": tv_details.get("runtime", ""),
325
- "genres": tv_details.get("genre", []),
326
  "media_type": "tv",
 
327
  "season_number": season,
328
  "episode_number": episode,
329
- "episode_title": ep_details.get("title", f"S{season}E{episode}") if ep_details else f"Episode {episode}",
330
- "episode_backdrop": ep_details.get("image", "") if ep_details else "",
331
- "episode_overview": ep_details.get("plot", "") if ep_details else "",
332
- "episode_released": str(ep_details.get("released", "")) if ep_details else "",
 
333
  "quality": quality,
334
  "encoded_string": encoded_string,
335
  }
336
 
 
337
  # ----------------- Movie Metadata -----------------
338
  async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
339
- imdb_id = tmdb_id = None
 
 
340
  use_tmdb = False
341
 
 
 
 
342
  if default_id:
343
- LOGGER.info(default_id)
344
- if str(default_id).startswith("tt"):
 
345
  imdb_id = default_id
346
- LOGGER.info(imdb_id)
347
- elif str(default_id).isdigit():
348
  tmdb_id = int(default_id)
349
- use_tmdb = True
350
 
 
 
 
351
  if not imdb_id and not tmdb_id:
352
- imdb_id = await safe_imdb_search(f"{title} {year}" if year else title, "movie")
 
 
 
353
  use_tmdb = not bool(imdb_id)
354
 
355
- movie_details = None
356
-
 
357
  if imdb_id and not use_tmdb:
358
-
359
  try:
360
  if imdb_id in IMDB_CACHE:
361
- movie_details = IMDB_CACHE[imdb_id]
362
  else:
363
  async with API_SEMAPHORE:
364
- movie_details = await get_detail(imdb_id=imdb_id, media_type="movie")
365
- LOGGER.info(movie_details)
366
- IMDB_CACHE[imdb_id] = movie_details
 
 
 
 
367
  except Exception as e:
368
- LOGGER.warning(f"IMDb movie fetch failed [{title}]: {e}")
 
369
  use_tmdb = True
370
 
371
- if use_tmdb or (tmdb_id and not movie_details):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  if not tmdb_id:
373
  tmdb_result = await safe_tmdb_search(title, "movie", year)
374
  if not tmdb_result:
@@ -376,51 +459,61 @@ async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, d
376
  return None
377
  tmdb_id = tmdb_result.id
378
 
379
- movie_details = await _tmdb_movie_details(tmdb_id)
380
- if not movie_details:
381
- LOGGER.warning(f"TMDb movie details fetch failed for '{title}' (id={tmdb_id}), skipping.")
 
382
  return None
383
 
384
- credits = getattr(movie_details, "credits", None) or {}
385
- cast_names = [getattr(c, "name", getattr(c, "original_name", None)) for c in (getattr(credits, "cast", []) or [])]
 
 
 
 
 
 
 
 
386
 
387
  return {
388
- "tmdb_id": movie_details.id,
389
- "imdb_id": movie_details.external_ids.imdb_id if getattr(movie_details, "external_ids", None) else None,
390
- "title": movie_details.title,
391
- "year": getattr(movie_details.release_date, "year", 0) if getattr(movie_details, "release_date", None) else 0,
392
- "rate": getattr(movie_details, "vote_average", 0) or 0,
393
- "description": movie_details.overview or "",
394
- "poster": format_tmdb_image(movie_details.poster_path),
395
- "backdrop": format_tmdb_image(movie_details.backdrop_path, "original"),
396
- "logo": get_tmdb_logo(getattr(movie_details, "images", None)),
397
  "cast": cast_names,
398
- "runtime": f"{getattr(movie_details, 'runtime', 0)} min" if getattr(movie_details, "runtime", None) else "",
399
  "media_type": "movie",
400
- "genres": [g.name for g in (movie_details.genres or [])],
401
  "quality": quality,
402
  "encoded_string": encoded_string,
403
  }
404
 
405
- # IMDb fallback return
 
 
406
  images = format_imdb_images(imdb_id)
407
- if movie_details is None:
408
- movie_details = {}
409
 
410
  return {
411
- "tmdb_id": movie_details.get("moviedb_id") or None,
412
  "imdb_id": imdb_id,
413
- "title": movie_details.get("title", title),
414
- "year": movie_details.get("releaseDetailed", {}).get("year", 0),
415
- "rate": movie_details.get("rating", {}).get("star", 0),
416
- "description": movie_details.get("plot", ""),
417
  "poster": images["poster"],
418
  "backdrop": images["backdrop"],
419
  "logo": images["logo"],
420
- "cast": movie_details.get("cast", []),
421
- "runtime": movie_details.get("runtime", ""),
422
  "media_type": "movie",
423
- "genres": movie_details.get("genre", []),
424
  "quality": quality,
425
  "encoded_string": encoded_string,
426
- }
 
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:
 
188
  LOGGER.info(f"No title parsed from: {filename} (parsed={parsed})")
189
  return None
190
 
191
+
192
  default_id = None
193
  try:
194
  default_id = extract_default_id(Backend.USE_DEFAULT_ID)
 
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 = None
223
+ tmdb_id = None
224
+ imdb_tv = None
225
+ imdb_ep = None
226
  use_tmdb = False
227
 
228
+ # -------------------------------------------------------
229
+ # 1. Handle default ID (IMDb / TMDb)
230
+ # -------------------------------------------------------
231
  if default_id:
232
+ default_id = str(default_id)
233
+ if default_id.startswith("tt"):
234
  imdb_id = default_id
235
+ use_tmdb = False
236
+ elif default_id.isdigit():
237
  tmdb_id = int(default_id)
238
  use_tmdb = True
239
 
240
+ # -------------------------------------------------------
241
+ # 2. If no ID → Try IMDb search first
242
+ # -------------------------------------------------------
243
  if not imdb_id and not tmdb_id:
244
  imdb_id = await safe_imdb_search(title, "tvSeries")
245
  use_tmdb = not bool(imdb_id)
246
 
247
+ # -------------------------------------------------------
248
+ # 3. IMDb fetch (series + episode)
249
+ # -------------------------------------------------------
250
  if imdb_id and not use_tmdb:
251
  try:
252
+ # ----- series details
253
  if imdb_id in IMDB_CACHE:
254
+ imdb_tv = IMDB_CACHE[imdb_id]
255
  else:
256
  async with API_SEMAPHORE:
257
+ imdb_tv = await get_detail(imdb_id=imdb_id, media_type="tvSeries")
258
+ IMDB_CACHE[imdb_id] = imdb_tv
259
 
260
+ # ----- episode details
261
+ ep_key = f"{imdb_id}::{season}::{episode}"
262
+ if ep_key in EPISODE_CACHE:
263
+ imdb_ep = EPISODE_CACHE[ep_key]
264
  else:
265
  async with API_SEMAPHORE:
266
+ imdb_ep = await get_season(imdb_id=imdb_id, season_id=season, episode_id=episode)
267
+ EPISODE_CACHE[ep_key] = imdb_ep
268
+
269
  except Exception as e:
270
+ LOGGER.warning(f"IMDb TV fetch failed [{imdb_id}] → {e}")
271
+ imdb_tv = None
272
+ imdb_ep = None
273
  use_tmdb = True
274
 
275
+ # -------------------------------------------------------
276
+ # 4. Decide if TMDb required
277
+ # -------------------------------------------------------
278
+ must_use_tmdb = (
279
+ use_tmdb or
280
+ imdb_tv is None or
281
+ imdb_tv == {}
282
+ )
283
+
284
+ # =======================================================
285
+ # 5. TMDb MODE
286
+ # =======================================================
287
+ if must_use_tmdb:
288
+ LOGGER.info(f"No valid IMDb TV data for '{title}' → using TMDb")
289
+
290
+ # Search TMDb by title
291
  if not tmdb_id:
292
+ tmdb_search = await safe_tmdb_search(title, "tv", year)
293
+ if not tmdb_search:
294
+ LOGGER.warning(f"No TMDb TV result for '{title}'")
295
  return None
296
+ tmdb_id = tmdb_search.id
297
 
298
+ # Fetch full TV show details
299
+ tv = await _tmdb_tv_details(tmdb_id)
300
+ if not tv:
301
+ LOGGER.warning(f"TMDb TV details failed for id={tmdb_id}")
302
  return None
 
303
 
304
+ # Fetch episode
305
+ ep = await _tmdb_episode_details(tmdb_id, season, episode)
306
+
307
+ # Cast list
308
+ credits = getattr(tv, "credits", None) or {}
309
+ cast_arr = getattr(credits, "cast", []) or []
310
+ cast = [
311
+ getattr(c, "name", None) or getattr(c, "original_name", None)
312
+ for c in cast_arr
313
+ ]
314
+
315
+ # Runtime (prefer episode → series → empty)
316
+ ep_runtime = getattr(ep, "runtime", None) if ep else None
317
+ series_runtime = (
318
+ tv.episode_run_time[0] if getattr(tv, "episode_run_time", None) else None
319
+ )
320
+ runtime_val = ep_runtime or series_runtime
321
+ runtime = f"{runtime_val} min" if runtime_val else ""
322
 
323
  return {
324
+ "tmdb_id": tv.id,
325
+ "imdb_id": getattr(getattr(tv, "external_ids", None), "imdb_id", None),
326
+ "title": tv.name,
327
+ "year": getattr(tv.first_air_date, "year", 0) if getattr(tv, "first_air_date", None) else 0,
328
+ "rate": getattr(tv, "vote_average", 0) or 0,
329
+ "description": tv.overview or "",
330
+ "poster": format_tmdb_image(tv.poster_path),
331
+ "backdrop": format_tmdb_image(tv.backdrop_path, "original"),
332
+ "logo": get_tmdb_logo(getattr(tv, "images", None)),
333
+ "genres": [g.name for g in (tv.genres or [])],
334
  "media_type": "tv",
335
+ "cast": cast,
336
+ "runtime": runtime,
337
+
 
 
 
338
  "season_number": season,
339
  "episode_number": episode,
340
+ "episode_title": getattr(ep, "name", f"S{season}E{episode}") if ep else f"S{season}E{episode}",
341
+ "episode_backdrop": format_tmdb_image(getattr(ep, "still_path", None), "original") if ep else "",
342
+ "episode_overview": getattr(ep, "overview", "") if ep else "",
343
+ "episode_released": (
344
+ ep.air_date.strftime("%Y-%m-%dT05:00:00.000Z")
345
+ if getattr(ep, "air_date", None)
346
+ else ""
347
+ ),
348
+
349
  "quality": quality,
350
  "encoded_string": encoded_string,
351
  }
352
 
353
+ # =======================================================
354
+ # 6. IMDb MODE
355
+ # =======================================================
356
+ imdb = imdb_tv or {}
357
+ ep = imdb_ep or {}
358
+
359
  images = format_imdb_images(imdb_id)
 
 
 
 
360
 
361
  return {
362
+ "tmdb_id": imdb.get("moviedb_id"),
363
  "imdb_id": imdb_id,
364
+ "title": imdb.get("title", title),
365
+ "year": imdb.get("releaseDetailed", {}).get("year", 0),
366
+ "rate": imdb.get("rating", {}).get("star", 0),
367
+ "description": imdb.get("plot", ""),
368
  "poster": images["poster"],
369
  "backdrop": images["backdrop"],
370
  "logo": images["logo"],
371
+ "cast": imdb.get("cast", []),
372
+ "runtime": imdb.get("runtime", ""),
373
+ "genres": imdb.get("genre", []),
374
  "media_type": "tv",
375
+
376
  "season_number": season,
377
  "episode_number": episode,
378
+ "episode_title": ep.get("title", f"S{season}E{episode}"),
379
+ "episode_backdrop": ep.get("image", ""),
380
+ "episode_overview": ep.get("plot", ""),
381
+ "episode_released": str(ep.get("released", "")),
382
+
383
  "quality": quality,
384
  "encoded_string": encoded_string,
385
  }
386
 
387
+
388
  # ----------------- Movie Metadata -----------------
389
  async def fetch_movie_metadata(title, encoded_string, year=None, quality=None, default_id=None) -> dict | None:
390
+ imdb_id = None
391
+ tmdb_id = None
392
+ imdb_details = None
393
  use_tmdb = False
394
 
395
+ # -------------------------------------------------------
396
+ # 1. PROCESS DEFAULT ID (tt = IMDb, digits = TMDb)
397
+ # -------------------------------------------------------
398
  if default_id:
399
+ default_id = str(default_id).strip()
400
+
401
+ if default_id.startswith("tt"):
402
  imdb_id = default_id
403
+ use_tmdb = False # force IMDb
404
+ elif default_id.isdigit():
405
  tmdb_id = int(default_id)
406
+ use_tmdb = True # force TMDb
407
 
408
+ # -------------------------------------------------------
409
+ # 2. IF NO DEFAULT ID → SEARCH IMDb FIRST
410
+ # -------------------------------------------------------
411
  if not imdb_id and not tmdb_id:
412
+ imdb_id = await safe_imdb_search(
413
+ f"{title} {year}" if year else title,
414
+ "movie"
415
+ )
416
  use_tmdb = not bool(imdb_id)
417
 
418
+ # -------------------------------------------------------
419
+ # 3. FETCH IMDb DETAILS (only if imdb_id exists)
420
+ # -------------------------------------------------------
421
  if imdb_id and not use_tmdb:
 
422
  try:
423
  if imdb_id in IMDB_CACHE:
424
+ imdb_details = IMDB_CACHE[imdb_id]
425
  else:
426
  async with API_SEMAPHORE:
427
+ imdb_details = await get_detail(
428
+ imdb_id=imdb_id,
429
+ media_type="movie"
430
+ )
431
+
432
+ IMDB_CACHE[imdb_id] = imdb_details
433
+
434
  except Exception as e:
435
+ LOGGER.warning(f"IMDb movie fetch failed [{title}] → {e}")
436
+ imdb_details = None
437
  use_tmdb = True
438
 
439
+ # -------------------------------------------------------
440
+ # 4. DECIDE FINAL DATA SOURCE
441
+ # -------------------------------------------------------
442
+ must_use_tmdb = (
443
+ use_tmdb or
444
+ imdb_details is None or
445
+ imdb_details == {}
446
+ )
447
+
448
+ # =======================================================
449
+ # 5. TMDb MODE
450
+ # =======================================================
451
+ if must_use_tmdb:
452
+ LOGGER.info(f"No valid IMDb data for '{title}' → using TMDb")
453
+
454
+ # TMDb search if id unknown
455
  if not tmdb_id:
456
  tmdb_result = await safe_tmdb_search(title, "movie", year)
457
  if not tmdb_result:
 
459
  return None
460
  tmdb_id = tmdb_result.id
461
 
462
+ # Fetch TMDb details
463
+ movie = await _tmdb_movie_details(tmdb_id)
464
+ if not movie:
465
+ LOGGER.warning(f"TMDb details failed for {tmdb_id}")
466
  return None
467
 
468
+ # Cast extraction
469
+ credits = getattr(movie, "credits", None) or {}
470
+ cast_arr = getattr(credits, "cast", []) or []
471
+ cast_names = [
472
+ getattr(c, "name", None) or getattr(c, "original_name", None)
473
+ for c in cast_arr
474
+ ]
475
+
476
+ runtime_val = getattr(movie, "runtime", None)
477
+ runtime = f"{runtime_val} min" if runtime_val else ""
478
 
479
  return {
480
+ "tmdb_id": movie.id,
481
+ "imdb_id": getattr(movie.external_ids, "imdb_id", None),
482
+ "title": movie.title,
483
+ "year": getattr(movie.release_date, "year", 0) if getattr(movie, "release_date", None) else 0,
484
+ "rate": getattr(movie, "vote_average", 0) or 0,
485
+ "description": movie.overview or "",
486
+ "poster": format_tmdb_image(movie.poster_path),
487
+ "backdrop": format_tmdb_image(movie.backdrop_path, "original"),
488
+ "logo": get_tmdb_logo(getattr(movie, "images", None)),
489
  "cast": cast_names,
490
+ "runtime": runtime,
491
  "media_type": "movie",
492
+ "genres": [g.name for g in (movie.genres or [])],
493
  "quality": quality,
494
  "encoded_string": encoded_string,
495
  }
496
 
497
+ # =======================================================
498
+ # 6. IMDb MODE
499
+ # =======================================================
500
  images = format_imdb_images(imdb_id)
501
+ imdb = imdb_details or {}
 
502
 
503
  return {
504
+ "tmdb_id": imdb.get("moviedb_id") or None,
505
  "imdb_id": imdb_id,
506
+ "title": imdb.get("title", title),
507
+ "year": imdb.get("releaseDetailed", {}).get("year", 0),
508
+ "rate": imdb.get("rating", {}).get("star", 0),
509
+ "description": imdb.get("plot", ""),
510
  "poster": images["poster"],
511
  "backdrop": images["backdrop"],
512
  "logo": images["logo"],
513
+ "cast": imdb.get("cast", []),
514
+ "runtime": imdb.get("runtime", ""),
515
  "media_type": "movie",
516
+ "genres": imdb.get("genre", []),
517
  "quality": quality,
518
  "encoded_string": encoded_string,
519
+ }
Backend/pyrofork/plugins/fix_metadata.py CHANGED
@@ -41,17 +41,18 @@ async def cancel_fix(_, query):
41
  await query.answer("Cancelled")
42
 
43
  # -------------------------------
44
- # MAIN COMMAND
45
  # -------------------------------
46
  @Client.on_message(filters.command("fixmetadata") & filters.private & CustomFilters.owner, group=10)
47
  async def fix_metadata_handler(_, message):
48
  global CANCEL_REQUESTED
49
  CANCEL_REQUESTED = False
50
 
51
- # Count total items
 
 
52
  total_movies = 0
53
  total_tv = 0
54
-
55
  for i in range(1, db.current_db_index + 1):
56
  key = f"storage_{i}"
57
  total_movies += await db.dbs[key]["movie"].count_documents({})
@@ -68,331 +69,372 @@ async def fix_metadata_handler(_, message):
68
  ])
69
  )
70
 
71
- CONCURRENCY = 20
72
- semaphore = asyncio.Semaphore(CONCURRENCY)
73
-
74
  # -------------------------
75
- # MOVIE UPDATE
76
  # -------------------------
 
 
 
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
- 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:
175
- LOGGER.exception(f"Error updating movie {movie_doc.get('title')}: {e}")
176
- DONE += 1
177
 
178
- # -------------------------
179
- # TV UPDATE
180
- # -------------------------
 
 
 
181
 
182
- async def _safe_update_tv(collection, tv_doc):
183
- nonlocal DONE
184
  if CANCEL_REQUESTED:
185
  return
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
- # -------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  async def update_movies():
336
  tasks = []
337
  for i in range(1, db.current_db_index + 1):
338
  if CANCEL_REQUESTED:
339
  break
340
-
341
  collection = db.dbs[f"storage_{i}"]["movie"]
342
  cursor = collection.find({})
343
-
344
  async for movie in cursor:
345
  if CANCEL_REQUESTED:
346
  break
347
-
348
  tasks.append(_safe_update_movie(collection, movie))
349
-
350
- if len(tasks) >= CONCURRENCY * 2:
351
  await asyncio.gather(*tasks, return_exceptions=True)
352
  tasks = []
353
-
354
  if tasks:
355
  await asyncio.gather(*tasks, return_exceptions=True)
356
 
357
- # -------------------------
358
- # UPDATE TV
359
- # -------------------------
360
- async def update_tv():
361
  tasks = []
362
  for i in range(1, db.current_db_index + 1):
363
-
 
364
  collection = db.dbs[f"storage_{i}"]["tv"]
365
  cursor = collection.find({})
366
-
367
  async for tv in cursor:
368
  if CANCEL_REQUESTED:
369
  break
370
-
371
  tasks.append(_safe_update_tv(collection, tv))
372
-
373
- if len(tasks) >= CONCURRENCY * 2:
374
  await asyncio.gather(*tasks, return_exceptions=True)
375
  tasks = []
376
-
377
  if tasks:
378
  await asyncio.gather(*tasks, return_exceptions=True)
379
 
380
- # -------------------------
381
- # RUN ALL UPDATES
382
- # -------------------------
383
  try:
384
- await update_movies()
385
- if not CANCEL_REQUESTED:
386
- await update_tv()
387
  except Exception as e:
388
  LOGGER.exception(f"Error in fix_metadata run: {e}")
389
 
390
  if CANCEL_REQUESTED:
 
 
 
 
391
  return
392
 
393
  elapsed = time.time() - start_time
394
- await status.edit_text(
395
- f"🎉 **Metadata Fix Completed!**\n"
396
- f"{progress_bar(DONE, TOTAL)}\n"
397
- f"⏱ Time Taken: {format_eta(elapsed)}"
398
- )
 
 
 
 
41
  await query.answer("Cancelled")
42
 
43
  # -------------------------------
44
+ # MAIN COMMAND (REWRITTEN - Balanced)
45
  # -------------------------------
46
  @Client.on_message(filters.command("fixmetadata") & filters.private & CustomFilters.owner, group=10)
47
  async def fix_metadata_handler(_, message):
48
  global CANCEL_REQUESTED
49
  CANCEL_REQUESTED = False
50
 
51
+ # -------------------------
52
+ # Gather totals quickly (non-blocking)
53
+ # -------------------------
54
  total_movies = 0
55
  total_tv = 0
 
56
  for i in range(1, db.current_db_index + 1):
57
  key = f"storage_{i}"
58
  total_movies += await db.dbs[key]["movie"].count_documents({})
 
69
  ])
70
  )
71
 
 
 
 
72
  # -------------------------
73
+ # Tunables
74
  # -------------------------
75
+ CONCURRENCY = 20
76
+ TASK_BATCH = CONCURRENCY * 2
77
+ PROGRESS_INTERVAL = 5.0
78
 
79
+ semaphore = asyncio.Semaphore(CONCURRENCY)
80
+ meta_cache = {}
81
+ last_progress_edit = start_time
82
+
83
+ async def cached_fetch_movie(title, year, default_id, encoded_string=None, quality=None):
84
+ if default_id:
85
+ k = ("movie", str(default_id))
86
+ else:
87
+ k = ("movie", f"title::{title or ''}::year::{year or ''}")
88
+
89
+ if k in meta_cache:
90
+ return meta_cache[k]
91
 
92
  async with semaphore:
93
  try:
94
+ meta = await fetch_movie_metadata(title=title, encoded_string=encoded_string, year=year, quality=quality, default_id=default_id)
95
+ except Exception as e:
96
+ LOGGER.exception(f"fetch_movie_metadata error for {title} ({default_id}): {e}")
97
+ meta = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ meta_cache[k] = meta
100
+ return meta
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ async def cached_fetch_tv(title, season, episode, year, default_id, encoded_string=None, quality=None):
103
+ if default_id:
104
+ k = ("tv", str(default_id), int(season), int(episode))
105
+ else:
106
+ k = ("tv", f"title::{title or ''}::year::{year or ''}", int(season), int(episode))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
+ if k in meta_cache:
109
+ return meta_cache[k]
110
 
111
+ async with semaphore:
112
+ try:
113
+ meta = await fetch_tv_metadata(title=title, season=season, episode=episode,
114
+ encoded_string=encoded_string, year=year, quality=quality, default_id=default_id)
115
  except Exception as e:
116
+ LOGGER.exception(f"fetch_tv_metadata error for {title} S{season}E{episode} ({default_id}): {e}")
117
+ meta = None
118
 
119
+ meta_cache[k] = meta
120
+ return meta
121
+
122
+
123
+ async def _safe_update_movie(collection, movie_doc):
124
+ nonlocal DONE, last_progress_edit
125
 
 
 
126
  if CANCEL_REQUESTED:
127
  return
128
+ try:
129
+ doc_id = movie_doc.get("_id")
130
+ imdb_id = movie_doc.get("imdb_id")
131
+ tmdb_id = movie_doc.get("tmdb_id")
132
+ title = movie_doc.get("title")
133
+ year = movie_doc.get("release_year")
134
+
135
+ meta_primary = None
136
+ meta_secondary = None
137
+
138
+ if imdb_id:
139
+ meta_primary = await cached_fetch_movie(title, year, imdb_id)
140
+ fetched_tmdb = meta_primary.get("tmdb_id") if meta_primary else None
141
+ if (tmdb_id or fetched_tmdb) and (not all_fields_present(meta_primary)):
142
+ meta_secondary = await cached_fetch_movie(title, year, (tmdb_id or fetched_tmdb))
143
+ elif tmdb_id:
144
+ meta_primary = await cached_fetch_movie(title, year, tmdb_id)
145
+ fetched_imdb = meta_primary.get("imdb_id") if meta_primary else None
146
+ if fetched_imdb and (not all_fields_present(meta_primary)):
147
+ meta_secondary = await cached_fetch_movie(title, year, fetched_imdb)
148
+ else:
149
+ meta_primary = await cached_fetch_movie(title, year, None)
150
+ if meta_primary:
151
+ fetched_imdb = meta_primary.get("imdb_id")
152
+ fetched_tmdb = meta_primary.get("tmdb_id")
153
+ if fetched_imdb and (not all_fields_present(meta_primary)):
154
+ meta_secondary = await cached_fetch_movie(title, year, fetched_imdb)
155
+ elif fetched_tmdb and (not all_fields_present(meta_primary)):
156
+ meta_secondary = await cached_fetch_movie(title, year, fetched_tmdb)
157
+
158
+ update_query = {}
159
+ current = dict(movie_doc)
160
+
161
+ api_map = {
162
+ "imdb_id": "imdb_id",
163
+ "tmdb_id": "tmdb_id",
164
+ "rate": "rating",
165
+ "cast": "cast",
166
+ "description": "description",
167
+ "genres": "genres",
168
+ "poster": "poster",
169
+ "backdrop": "backdrop",
170
+ "runtime": "runtime",
171
+ "logo": "logo"
172
+ }
173
+
174
+ for meta in (meta_primary, meta_secondary):
175
+ if not meta:
176
+ continue
177
+ for api_key, db_key in api_map.items():
178
+ new_val = meta.get(api_key)
179
+ if new_val is None:
 
 
 
 
 
 
 
 
 
 
180
  continue
181
 
182
+ if db_key == "rating":
183
+ is_empty = (not current.get(db_key)) or current.get(db_key) == 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  else:
185
+ is_empty = not current.get(db_key)
186
+ # # If want to add missing data
187
+ # if is_empty and new_val:
188
+ # update_query[db_key] = new_val
189
+ # current[db_key] = new_val
190
+ # # If want to add complete data
191
+ if new_val is not None:
192
+ update_query[db_key] = new_val
193
+ current[db_key] = new_val
194
+
195
+
196
+ if update_query:
197
+ filter_q = {"_id": doc_id} if doc_id else {"imdb_id": imdb_id}
198
+ try:
199
+ await collection.update_one(filter_q, {"$set": update_query})
200
+ except Exception as e:
201
+ LOGGER.exception(f"DB update failed for movie {title}: {e}")
202
+
203
+ DONE += 1
204
+
205
+ now = time.time()
206
+ if now - last_progress_edit > PROGRESS_INTERVAL:
207
+ last_progress_edit = now
208
+ try:
209
+ await status.edit_text(
210
+ f"⏳ Fixing metadata...\n{progress_bar(DONE, TOTAL)}\n⏱ Elapsed: {format_eta(now - start_time)}"
211
+ )
212
+ except Exception:
213
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
+ except Exception as e:
216
+ LOGGER.exception(f"Error updating movie {movie_doc.get('title')}: {e}")
217
+ DONE += 1
218
 
219
+ async def _safe_update_tv(collection, tv_doc):
220
+ nonlocal DONE, last_progress_edit
221
+
222
+ if CANCEL_REQUESTED:
223
+ return
224
+
225
+ try:
226
+ doc_id = tv_doc.get("_id")
227
+ imdb_id = tv_doc.get("imdb_id")
228
+ tmdb_id = tv_doc.get("tmdb_id")
229
+ title = tv_doc.get("title")
230
+ year = tv_doc.get("release_year")
231
+
232
+ meta_primary = None
233
+ meta_secondary = None
234
+
235
+ if imdb_id:
236
+ meta_primary = await cached_fetch_tv(title, 1, 1, year, imdb_id)
237
+ fetched_tmdb = meta_primary.get("tmdb_id") if meta_primary else None
238
+ if (tmdb_id or fetched_tmdb) and (not all_fields_present(meta_primary)):
239
+ meta_secondary = await cached_fetch_tv(title, 1, 1, year, (tmdb_id or fetched_tmdb))
240
+ elif tmdb_id:
241
+ meta_primary = await cached_fetch_tv(title, 1, 1, year, tmdb_id)
242
+ fetched_imdb = meta_primary.get("imdb_id") if meta_primary else None
243
+ if fetched_imdb and (not all_fields_present(meta_primary)):
244
+ meta_secondary = await cached_fetch_tv(title, 1, 1, year, fetched_imdb)
245
+ else:
246
+ meta_primary = await cached_fetch_tv(title, 1, 1, year, None)
247
+ if meta_primary:
248
+ fetched_imdb = meta_primary.get("imdb_id")
249
+ fetched_tmdb = meta_primary.get("tmdb_id")
250
+ if fetched_imdb and (not all_fields_present(meta_primary)):
251
+ meta_secondary = await cached_fetch_tv(title, 1, 1, year, fetched_imdb)
252
+ elif fetched_tmdb and (not all_fields_present(meta_primary)):
253
+ meta_secondary = await cached_fetch_tv(title, 1, 1, year, fetched_tmdb)
254
+
255
+ update_query = {}
256
+ current = dict(tv_doc)
257
+ api_map = {
258
+ "imdb_id": "imdb_id",
259
+ "tmdb_id": "tmdb_id",
260
+ "rate": "rating",
261
+ "cast": "cast",
262
+ "description": "description",
263
+ "genres": "genres",
264
+ "poster": "poster",
265
+ "backdrop": "backdrop",
266
+ "runtime": "runtime",
267
+ "logo": "logo"
268
+ }
269
+
270
+ for meta in (meta_primary, meta_secondary):
271
+ if not meta:
272
+ continue
273
+ for api_key, db_key in api_map.items():
274
+ new_val = meta.get(api_key)
275
+ if new_val is None:
276
+ continue
277
+ if db_key == "rating":
278
+ is_empty = (not current.get(db_key)) or current.get(db_key) == 0
279
+ else:
280
+ is_empty = not current.get(db_key)
281
+ # # If want to add missing data
282
+ # if is_empty and new_val:
283
+ # update_query[db_key] = new_val
284
+ # current[db_key] = new_val
285
+ # # If want to add complete data
286
+ if new_val is not None:
287
+ update_query[db_key] = new_val
288
+ current[db_key] = new_val
289
+
290
+
291
+ if update_query:
292
+ filter_q = {"_id": doc_id} if doc_id else {"imdb_id": imdb_id}
293
+ try:
294
+ await collection.update_one(filter_q, {"$set": update_query})
295
+ except Exception as e:
296
+ LOGGER.exception(f"DB update failed for TV {title}: {e}")
297
+
298
+ final_imdb = current.get("imdb_id")
299
+ if not final_imdb:
300
  DONE += 1
301
+ return
302
+
303
+ ep_tasks = []
304
+ for season in tv_doc.get("seasons", []):
305
+ s_num = season.get("season_number")
306
+ for ep in season.get("episodes", []):
307
+ e_num = ep.get("episode_number")
308
+
309
+ # skip if episode appears complete
310
+ if ep.get("overview") and ep.get("released") and ep.get("episode_backdrop"):
311
+ continue
312
+
313
+ async def ep_task(sn=s_num, en=e_num):
314
+ try:
315
+ meta = await cached_fetch_tv(title, sn, en, year, final_imdb)
316
+ if not meta:
317
+ return
318
+
319
+ ep_update = {}
320
+ if meta.get("episode_overview"):
321
+ ep_update["seasons.$[s].episodes.$[e].overview"] = meta["episode_overview"]
322
+ if meta.get("episode_released"):
323
+ ep_update["seasons.$[s].episodes.$[e].released"] = meta["episode_released"]
324
+ if meta.get("episode_backdrop"):
325
+ ep_update["seasons.$[s].episodes.$[e].episode_backdrop"] = meta["episode_backdrop"]
326
+
327
+ if ep_update:
328
+ filt = {"_id": doc_id} if doc_id else {"imdb_id": final_imdb}
329
+ await collection.update_one(
330
+ filt,
331
+ {"$set": ep_update},
332
+ array_filters=[
333
+ {"s.season_number": sn},
334
+ {"e.episode_number": en}
335
+ ]
336
+ )
337
+ except Exception as e:
338
+ LOGGER.exception(f"Error updating episode {title} S{sn}E{en}: {e}")
339
+
340
+ ep_tasks.append(ep_task())
341
+
342
+ for i in range(0, len(ep_tasks), TASK_BATCH):
343
+ if CANCEL_REQUESTED:
344
+ break
345
+ batch = ep_tasks[i:i+TASK_BATCH]
346
+ running = [asyncio.create_task(t) for t in batch]
347
+ await asyncio.gather(*running, return_exceptions=True)
348
+
349
+ DONE += 1
350
+
351
+ now = time.time()
352
+ if now - last_progress_edit > PROGRESS_INTERVAL:
353
+ last_progress_edit = now
354
+ try:
355
+ await status.edit_text(
356
+ f"⏳ Fixing metadata...\n{progress_bar(DONE, TOTAL)}\n⏱ Elapsed: {format_eta(now - start_time)}"
357
+ )
358
+ except Exception:
359
+ pass
360
+
361
+ except Exception as e:
362
+ LOGGER.exception(f"Error updating TV show {tv_doc.get('title')}: {e}")
363
+ DONE += 1
364
+
365
+ def all_fields_present(meta: dict) -> bool:
366
+ if not meta:
367
+ return False
368
+
369
+ if not (meta.get("poster") or meta.get("backdrop")):
370
+ return False
371
+
372
+ has_desc = meta.get("description") or meta.get("genres") or meta.get("cast")
373
+ if not has_desc:
374
+ return False
375
+
376
+ if meta.get("rate") in [0, None]:
377
+ return False
378
+
379
+ if meta.get("runtime") in [0, None]:
380
+ return False
381
+
382
+ return True
383
+
384
+
385
+
386
  async def update_movies():
387
  tasks = []
388
  for i in range(1, db.current_db_index + 1):
389
  if CANCEL_REQUESTED:
390
  break
 
391
  collection = db.dbs[f"storage_{i}"]["movie"]
392
  cursor = collection.find({})
 
393
  async for movie in cursor:
394
  if CANCEL_REQUESTED:
395
  break
 
396
  tasks.append(_safe_update_movie(collection, movie))
397
+ if len(tasks) >= TASK_BATCH:
 
398
  await asyncio.gather(*tasks, return_exceptions=True)
399
  tasks = []
 
400
  if tasks:
401
  await asyncio.gather(*tasks, return_exceptions=True)
402
 
403
+ async def update_tv_shows():
 
 
 
404
  tasks = []
405
  for i in range(1, db.current_db_index + 1):
406
+ if CANCEL_REQUESTED:
407
+ break
408
  collection = db.dbs[f"storage_{i}"]["tv"]
409
  cursor = collection.find({})
 
410
  async for tv in cursor:
411
  if CANCEL_REQUESTED:
412
  break
 
413
  tasks.append(_safe_update_tv(collection, tv))
414
+ if len(tasks) >= TASK_BATCH:
 
415
  await asyncio.gather(*tasks, return_exceptions=True)
416
  tasks = []
 
417
  if tasks:
418
  await asyncio.gather(*tasks, return_exceptions=True)
419
 
 
 
 
420
  try:
421
+ await asyncio.gather(update_movies(), update_tv_shows())
 
 
422
  except Exception as e:
423
  LOGGER.exception(f"Error in fix_metadata run: {e}")
424
 
425
  if CANCEL_REQUESTED:
426
+ try:
427
+ await status.edit_text("❌ Metadata fixing cancelled by user.")
428
+ except Exception:
429
+ pass
430
  return
431
 
432
  elapsed = time.time() - start_time
433
+ try:
434
+ await status.edit_text(
435
+ f"🎉 **Metadata Fix Completed!**\n"
436
+ f"{progress_bar(DONE, TOTAL)}\n"
437
+ f"⏱ Time Taken: {format_eta(elapsed)}"
438
+ )
439
+ except Exception:
440
+ pass