Karan Adhikari commited on
Commit
6cbe4f0
·
unverified ·
1 Parent(s): c1df1c3

Delete Backend/pyrofork/plugins/fix_metadata.py

Browse files
Backend/pyrofork/plugins/fix_metadata.py DELETED
@@ -1,440 +0,0 @@
1
- import time
2
- import asyncio
3
- from pyrogram import Client, filters
4
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
5
-
6
- from Backend import db
7
- from Backend.helper.custom_filter import CustomFilters
8
- from Backend.helper.metadata import fetch_tv_metadata, fetch_movie_metadata
9
- from Backend.logger import LOGGER
10
-
11
- CANCEL_REQUESTED = False
12
-
13
- # -------------------------------
14
- # Progress Bar Helper
15
- # -------------------------------
16
- def progress_bar(done, total, length=20):
17
- filled = int(length * (done / total)) if total else length
18
- return f"[{'█' * filled}{'░' * (length - filled)}] {done}/{total}"
19
-
20
- # -------------------------------
21
- # ETA Helper
22
- # -------------------------------
23
- def format_eta(seconds):
24
- minutes, sec = divmod(int(seconds), 60)
25
- hours, minutes = divmod(minutes, 60)
26
-
27
- if hours > 0:
28
- return f"{hours}h {minutes}m {sec}s"
29
- if minutes > 0:
30
- return f"{minutes}m {sec}s"
31
- return f"{sec}s"
32
-
33
- # -------------------------------
34
- # CANCEL BUTTON HANDLER
35
- # -------------------------------
36
- @Client.on_callback_query(filters.regex("cancel_fix"))
37
- async def cancel_fix(_, query):
38
- global CANCEL_REQUESTED
39
- CANCEL_REQUESTED = True
40
- await query.message.edit_text("❌ Metadata fixing has been cancelled by the user.")
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) # Inactive Now
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({})
59
- total_tv += await db.dbs[key]["tv"].count_documents({})
60
-
61
- TOTAL = total_movies + total_tv
62
- DONE = 0
63
- start_time = time.time()
64
-
65
- status = await message.reply_text(
66
- "⏳ Initializing metadata fixing...",
67
- reply_markup=InlineKeyboardMarkup([
68
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_fix")]
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