Karan Adhikari commited on
Commit
e638588
·
unverified ·
1 Parent(s): 2ca3b86

Refactor metadata update logic for movies and TV shows

Browse files

Refactor metadata fetching and updating logic for movies and TV shows. Simplify concurrency controls and enhance data handling for empty fields.

Backend/pyrofork/plugins/fix_metadata.py CHANGED
@@ -68,7 +68,6 @@ async def fix_metadata_handler(_, message):
68
  ])
69
  )
70
 
71
- # concurrency controls
72
  CONCURRENCY = 20
73
  semaphore = asyncio.Semaphore(CONCURRENCY)
74
 
@@ -82,14 +81,11 @@ async def fix_metadata_handler(_, message):
82
 
83
  async with semaphore:
84
  try:
85
- if movie_doc.get("cast") and movie_doc.get("description") and movie_doc.get("genres") and movie_doc.get("logo") not in [None, ""]:
86
- DONE += 1
87
- return
88
-
89
- tmdb_id = movie_doc["tmdb_id"]
90
  title = movie_doc["title"]
91
  year = movie_doc.get("release_year")
92
 
 
93
  meta = await fetch_movie_metadata(
94
  title=title,
95
  encoded_string=None,
@@ -99,19 +95,20 @@ async def fix_metadata_handler(_, message):
99
  )
100
 
101
  if meta:
 
 
 
 
 
 
 
 
 
 
 
102
  await collection.update_one(
103
- {"tmdb_id": tmdb_id},
104
- {"$set": {
105
- "tmdb_id": meta.get("tmdb_id"),
106
- "imdb_id": meta.get("imdb_id"),
107
- "cast": meta.get("cast"),
108
- "description": meta.get("description"),
109
- "genres": meta.get("genres"),
110
- "poster": meta.get("poster"),
111
- "backdrop": meta.get("backdrop"),
112
- "logo": meta.get("logo"),
113
- "rating": meta.get("rate"),
114
- }}
115
  )
116
 
117
  DONE += 1
@@ -130,59 +127,51 @@ async def fix_metadata_handler(_, message):
130
 
131
  async with semaphore:
132
  try:
133
- tmdb_id = tv_doc["tmdb_id"]
134
  title = tv_doc["title"]
135
  year = tv_doc.get("release_year")
136
 
137
- # SHOW-LEVEL UPDATE
138
- has_meta = tv_doc.get("cast") and tv_doc.get("description") and tv_doc.get("genres") and tv_doc.get("logo") not in [None, ""]
139
- if not has_meta:
140
- meta = await fetch_tv_metadata(
141
- title=title,
142
- season=1,
143
- episode=1,
144
- encoded_string=None,
145
- year=year,
146
- quality=None,
147
- default_id=None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  )
149
 
150
- if meta:
151
- await collection.update_one(
152
- {"tmdb_id": tmdb_id},
153
- {"$set": {
154
- "tmdb_id": meta.get("tmdb_id"),
155
- "imdb_id": meta.get("imdb_id"),
156
- "cast": meta.get("cast"),
157
- "description": meta.get("description"),
158
- "genres": meta.get("genres"),
159
- "poster": meta.get("poster"),
160
- "backdrop": meta.get("backdrop"),
161
- "logo": meta.get("logo"),
162
- "rating": meta.get("rate"),
163
- }}
164
- )
165
-
166
- # EPISODE UPDATES (NO DONE += 1 HERE — AS YOU REQUESTED)
167
  tasks = []
168
-
169
  for season in tv_doc.get("seasons", []):
170
- if CANCEL_REQUESTED:
171
- break
172
-
173
- s = season.get("season_number")
174
 
175
  for ep in season.get("episodes", []):
176
- if CANCEL_REQUESTED:
177
- break
178
-
179
- e = ep.get("episode_number")
180
 
181
- # Skip if episode complete
182
  if ep.get("overview") and ep.get("released") and ep.get("episode_backdrop"):
183
- continue
184
 
185
- async def ep_task(s_local=s, e_local=e, tv_tmdb=tmdb_id):
186
  try:
187
  ep_meta = await fetch_tv_metadata(
188
  title=title,
@@ -196,7 +185,7 @@ async def fix_metadata_handler(_, message):
196
 
197
  if ep_meta:
198
  await collection.update_one(
199
- {"tmdb_id": tv_tmdb},
200
  {"$set": {
201
  "seasons.$[s].episodes.$[e].overview": ep_meta.get("episode_overview"),
202
  "seasons.$[s].episodes.$[e].released": ep_meta.get("episode_released"),
@@ -207,21 +196,16 @@ async def fix_metadata_handler(_, message):
207
  {"e.episode_number": e_local}
208
  ]
209
  )
210
-
211
  except Exception as e:
212
  LOGGER.exception(f"Error updating episode {title} S{s_local}E{e_local}: {e}")
213
 
214
  tasks.append(asyncio.create_task(ep_task()))
215
 
216
- # RUN EPISODE TASKS
217
  if tasks:
218
  for i in range(0, len(tasks), CONCURRENCY):
219
- if CANCEL_REQUESTED:
220
- break
221
- batch = tasks[i:i+CONCURRENCY]
222
- await asyncio.gather(*batch, return_exceptions=True)
223
 
224
- DONE += 1
225
 
226
  except Exception as e:
227
  LOGGER.exception(f"Error updating TV show {tv_doc.get('title')}: {e}")
@@ -242,6 +226,7 @@ async def fix_metadata_handler(_, message):
242
  async for movie in cursor:
243
  if CANCEL_REQUESTED:
244
  break
 
245
  tasks.append(_safe_update_movie(collection, movie))
246
 
247
  if len(tasks) >= CONCURRENCY * 2:
@@ -252,13 +237,11 @@ async def fix_metadata_handler(_, message):
252
  await asyncio.gather(*tasks, return_exceptions=True)
253
 
254
  # -------------------------
255
- # UPDATE TV SHOWS
256
  # -------------------------
257
  async def update_tv():
258
  tasks = []
259
  for i in range(1, db.current_db_index + 1):
260
- if CANCEL_REQUESTED:
261
- break
262
 
263
  collection = db.dbs[f"storage_{i}"]["tv"]
264
  cursor = collection.find({})
@@ -266,6 +249,7 @@ async def fix_metadata_handler(_, message):
266
  async for tv in cursor:
267
  if CANCEL_REQUESTED:
268
  break
 
269
  tasks.append(_safe_update_tv(collection, tv))
270
 
271
  if len(tasks) >= CONCURRENCY * 2:
@@ -289,7 +273,6 @@ async def fix_metadata_handler(_, message):
289
  return
290
 
291
  elapsed = time.time() - start_time
292
-
293
  await status.edit_text(
294
  f"🎉 **Metadata Fix Completed!**\n"
295
  f"{progress_bar(DONE, TOTAL)}\n"
 
68
  ])
69
  )
70
 
 
71
  CONCURRENCY = 20
72
  semaphore = asyncio.Semaphore(CONCURRENCY)
73
 
 
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,
 
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
 
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,
 
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"),
 
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}")
 
226
  async for movie in cursor:
227
  if CANCEL_REQUESTED:
228
  break
229
+
230
  tasks.append(_safe_update_movie(collection, movie))
231
 
232
  if len(tasks) >= CONCURRENCY * 2:
 
237
  await asyncio.gather(*tasks, return_exceptions=True)
238
 
239
  # -------------------------
240
+ # UPDATE TV
241
  # -------------------------
242
  async def update_tv():
243
  tasks = []
244
  for i in range(1, db.current_db_index + 1):
 
 
245
 
246
  collection = db.dbs[f"storage_{i}"]["tv"]
247
  cursor = collection.find({})
 
249
  async for tv in cursor:
250
  if CANCEL_REQUESTED:
251
  break
252
+
253
  tasks.append(_safe_update_tv(collection, tv))
254
 
255
  if len(tasks) >= CONCURRENCY * 2:
 
273
  return
274
 
275
  elapsed = time.time() - start_time
 
276
  await status.edit_text(
277
  f"🎉 **Metadata Fix Completed!**\n"
278
  f"{progress_bar(DONE, TOTAL)}\n"