Karan Adhikari commited on
Commit
02f9eb2
Β·
unverified Β·
1 Parent(s): bd22308

Enhance /dbcheck command with concurrency and error handling

Browse files

Refactor /dbcheck command to improve performance and add error handling. Introduce concurrent processing for message checks and update status messages during execution.

Files changed (1) hide show
  1. Backend/pyrofork/plugins/utilities.py +158 -128
Backend/pyrofork/plugins/utilities.py CHANGED
@@ -18,6 +18,7 @@ import time
18
  from pyrogram import filters, Client, enums
19
  from pyrogram.types import Message
20
  from pyrogram.errors import FloodWait
 
21
 
22
  from Backend.helper.custom_filter import CustomFilters
23
  from Backend.logger import LOGGER
@@ -26,6 +27,9 @@ from Backend.config import Telegram
26
  from Backend.helper.encrypt import decode_string
27
 
28
 
 
 
 
29
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
30
  # /stats β€” Quick dashboard
31
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@@ -223,22 +227,53 @@ async def search_command(client: Client, message: Message):
223
  )
224
 
225
 
226
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
227
- # /dbcheck β€” Integrity checker (find orphaned streams)
228
- # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  @Client.on_message(filters.command('dbcheck') & filters.private & CustomFilters.owner, group=10)
231
  async def dbcheck_command(client: Client, message: Message):
232
- """Check for orphaned DB entries where the Telegram message no longer exists."""
233
  args = message.text.split()
234
  purge_mode = len(args) > 1 and args[1].lower() == "purge"
235
 
236
- mode_label = "πŸ—‘ Purge" if purge_mode else "πŸ” Check"
237
  status_msg = await message.reply_text(
238
- f"<blockquote>{mode_label} mode β€” scanning all stream entries…</blockquote>\n\n"
239
- f"This may take a while for large databases.",
240
- quote=True,
241
- parse_mode=enums.ParseMode.HTML,
242
  )
243
 
244
  checked = 0
@@ -246,144 +281,139 @@ async def dbcheck_command(client: Client, message: Message):
246
  alive = 0
247
  errors = 0
248
  purged = 0
249
- dead_entries = [] # list of (collection, doc_id, stream_hash, title)
 
 
 
250
 
251
  try:
252
  for i in range(1, db.current_db_index + 1):
253
  storage = db.dbs.get(f"storage_{i}")
254
- if storage is None:
255
  continue
256
 
257
- # Check movies
258
- async for movie in storage["movie"].find({}):
259
- title = movie.get("title", "Unknown")
260
- for q in movie.get("telegram", []):
261
- stream_hash = q.get("id")
262
- if not stream_hash:
263
- continue
264
- try:
265
- decoded = await decode_string(stream_hash)
266
- chat_id = int(f"-100{decoded['chat_id']}")
267
- msg_id = int(decoded['msg_id'])
268
- msg = await client.get_messages(chat_id, msg_id)
269
- checked += 1
270
- if msg.empty:
271
- dead += 1
272
- dead_entries.append(("movie", stream_hash, title, q.get("quality", "?")))
273
- else:
274
- alive += 1
275
- except FloodWait as e:
276
- await asyncio.sleep(e.value)
277
- except Exception as e:
278
- errors += 1
279
- LOGGER.warning(f"[DBCheck] Error checking {stream_hash}: {e}")
280
-
281
- # Rate limit
282
- await asyncio.sleep(0.3)
283
-
284
- # Progress update every 25 checks
285
- if checked % 25 == 0:
286
- try:
 
287
  await status_msg.edit_text(
288
- f"<blockquote>{mode_label} β€” in progress…</blockquote>\n\n"
289
- f"Checked: <code>{checked}</code> | "
290
- f"Dead: <code>{dead}</code> | "
291
- f"Alive: <code>{alive}</code> | "
292
- f"Errors: <code>{errors}</code>",
293
- parse_mode=enums.ParseMode.HTML,
294
  )
295
- except Exception:
296
- pass
297
 
298
- # Check TV shows
299
- async for show in storage["tv"].find({}):
300
- title = show.get("title", "Unknown")
301
- for season in show.get("seasons", []):
302
- for episode in season.get("episodes", []):
303
- for q in episode.get("telegram", []):
304
- stream_hash = q.get("id")
305
- if not stream_hash:
306
- continue
307
- try:
308
- decoded = await decode_string(stream_hash)
309
- chat_id = int(f"-100{decoded['chat_id']}")
310
- msg_id = int(decoded['msg_id'])
311
- msg = await client.get_messages(chat_id, msg_id)
312
- checked += 1
313
- if msg.empty:
314
- dead += 1
315
- ep_label = f"S{season.get('season_number','?')}E{episode.get('episode_number','?')}"
316
- dead_entries.append(("tv", stream_hash, f"{title} {ep_label}", q.get("quality", "?")))
317
- else:
318
- alive += 1
319
- except FloodWait as e:
320
- await asyncio.sleep(e.value)
321
- except Exception as e:
 
 
 
 
 
 
 
322
  errors += 1
323
 
324
- await asyncio.sleep(0.3)
325
-
326
- if checked % 25 == 0:
327
- try:
328
- await status_msg.edit_text(
329
- f"<blockquote>{mode_label} β€” in progress…</blockquote>\n\n"
330
- f"Checked: <code>{checked}</code> | "
331
- f"Dead: <code>{dead}</code> | "
332
- f"Alive: <code>{alive}</code> | "
333
- f"Errors: <code>{errors}</code>",
334
- parse_mode=enums.ParseMode.HTML,
335
- )
336
- except Exception:
337
- pass
338
-
339
- # Purge dead entries if requested
340
- if purge_mode and dead_entries:
341
- for _, stream_hash, _, _ in dead_entries:
342
- try:
343
- deleted = await db.delete_media_by_stream_id(stream_hash)
344
- if deleted:
345
- purged += 1
346
- except Exception as e:
347
- LOGGER.error(f"[DBCheck] Purge failed for {stream_hash}: {e}")
348
-
349
- # Final summary
350
- summary = (
351
- f"<blockquote>{'πŸ—‘' if purge_mode else 'πŸ”'} <b>DB Integrity Check Complete</b></blockquote>\n\n"
352
- f"βœ… Alive: <code>{alive}</code>\n"
353
- f"πŸ’€ Dead (orphaned): <code>{dead}</code>\n"
354
- f"❌ Errors: <code>{errors}</code>\n"
355
- f"πŸ“ Total checked: <code>{checked}</code>\n"
356
- )
357
 
358
- if purge_mode:
359
- summary += f"\nπŸ—‘ Purged: <code>{purged}</code> / {dead}"
360
- elif dead > 0:
361
- summary += f"\nπŸ’‘ Run <code>/dbcheck purge</code> to clean up the {dead} dead entries."
362
 
363
- # Show sample of dead entries (first 10)
364
- if dead_entries and not purge_mode:
365
- summary += "\n\n<b>Sample dead entries:</b>\n"
366
- for _, _, title, quality in dead_entries[:10]:
367
- summary += f" β€’ {title} [{quality}]\n"
368
- if len(dead_entries) > 10:
369
- summary += f" <i>…and {len(dead_entries) - 10} more</i>"
370
 
371
- await status_msg.edit_text(summary, parse_mode=enums.ParseMode.HTML)
 
 
 
372
 
373
- # Send a separate notification so the user gets a ping
374
- if checked > 50:
375
- await message.reply_text(
376
- f"βœ… DB check finished β€” {dead} dead entries found out of {checked} checked.",
377
- parse_mode=enums.ParseMode.HTML,
378
- )
379
 
380
- except Exception as e:
381
- LOGGER.error(f"[DBCheck] Error: {e}")
382
  await status_msg.edit_text(
383
- f"❌ DB check failed: <code>{e}</code>",
384
- parse_mode=enums.ParseMode.HTML,
 
 
 
 
 
 
385
  )
386
 
 
 
387
 
388
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
389
  # /exportchannels & /importchannels β€” Backup/restore channel config
 
18
  from pyrogram import filters, Client, enums
19
  from pyrogram.types import Message
20
  from pyrogram.errors import FloodWait
21
+ from pymongo.errors import CursorNotFound
22
 
23
  from Backend.helper.custom_filter import CustomFilters
24
  from Backend.logger import LOGGER
 
27
  from Backend.helper.encrypt import decode_string
28
 
29
 
30
+ CONCURRENT_TASKS = 15
31
+ PROGRESS_UPDATE_EVERY = 50
32
+
33
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
34
  # /stats β€” Quick dashboard
35
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
227
  )
228
 
229
 
 
 
 
230
 
231
+
232
+
233
+
234
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
235
+ # Helper: check single message
236
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
237
+ async def check_message(client, stream_hash):
238
+ try:
239
+ decoded = await decode_string(stream_hash)
240
+ chat_id = int(f"-100{decoded['chat_id']}")
241
+ msg_id = int(decoded['msg_id'])
242
+
243
+ msg = await client.get_messages(chat_id, msg_id)
244
+
245
+ if msg.empty:
246
+ return False
247
+ return True
248
+
249
+ except FloodWait as e:
250
+ await asyncio.sleep(e.value)
251
+ return await check_message(client, stream_hash)
252
+
253
+ except Exception:
254
+ return None
255
+
256
+
257
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
258
+ # Batch processor
259
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
260
+ async def process_batch(client, batch):
261
+ tasks = [check_message(client, s) for s in batch]
262
+ return await asyncio.gather(*tasks, return_exceptions=True)
263
+
264
+
265
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
266
+ # /dbcheck β€” Integrity checker (find orphaned streams)
267
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
268
  @Client.on_message(filters.command('dbcheck') & filters.private & CustomFilters.owner, group=10)
269
  async def dbcheck_command(client: Client, message: Message):
270
+
271
  args = message.text.split()
272
  purge_mode = len(args) > 1 and args[1].lower() == "purge"
273
 
 
274
  status_msg = await message.reply_text(
275
+ "πŸš€ Advanced DB Check started...\nThis will run fast ⚑",
276
+ quote=True
 
 
277
  )
278
 
279
  checked = 0
 
281
  alive = 0
282
  errors = 0
283
  purged = 0
284
+
285
+ dead_entries = []
286
+
287
+ start_time = time.time()
288
 
289
  try:
290
  for i in range(1, db.current_db_index + 1):
291
  storage = db.dbs.get(f"storage_{i}")
292
+ if not storage:
293
  continue
294
 
295
+ # ───────── MOVIES ─────────
296
+ cursor = storage["movie"].find({}, no_cursor_timeout=True)
297
+
298
+ try:
299
+ async for movie in cursor:
300
+ title = movie.get("title", "Unknown")
301
+
302
+ stream_ids = [
303
+ q.get("id") for q in movie.get("telegram", [])
304
+ if q.get("id")
305
+ ]
306
+
307
+ for x in range(0, len(stream_ids), CONCURRENT_TASKS):
308
+ batch = stream_ids[x:x + CONCURRENT_TASKS]
309
+ results = await process_batch(client, batch)
310
+
311
+ for stream_hash, result in zip(batch, results):
312
+ checked += 1
313
+
314
+ if result is True:
315
+ alive += 1
316
+ elif result is False:
317
+ dead += 1
318
+ dead_entries.append(stream_hash)
319
+ else:
320
+ errors += 1
321
+
322
+ if checked % PROGRESS_UPDATE_EVERY == 0:
323
+ elapsed = int(time.time() - start_time)
324
+ speed = checked // max(1, elapsed)
325
+
326
  await status_msg.edit_text(
327
+ f"πŸš€ DB Check Running...\n\n"
328
+ f"Checked: {checked}\n"
329
+ f"Alive: {alive}\n"
330
+ f"Dead: {dead}\n"
331
+ f"Errors: {errors}\n\n"
332
+ f"⚑ Speed: {speed}/sec"
333
  )
 
 
334
 
335
+ except CursorNotFound:
336
+ await status_msg.edit_text("⚠️ Cursor expired (movies), retrying...")
337
+ finally:
338
+ await cursor.close()
339
+
340
+ # ───────── TV ─────────
341
+ cursor = storage["tv"].find({}, no_cursor_timeout=True)
342
+
343
+ try:
344
+ async for show in cursor:
345
+ stream_ids = []
346
+
347
+ for season in show.get("seasons", []):
348
+ for episode in season.get("episodes", []):
349
+ for q in episode.get("telegram", []):
350
+ if q.get("id"):
351
+ stream_ids.append(q["id"])
352
+
353
+ for x in range(0, len(stream_ids), CONCURRENT_TASKS):
354
+ batch = stream_ids[x:x + CONCURRENT_TASKS]
355
+ results = await process_batch(client, batch)
356
+
357
+ for stream_hash, result in zip(batch, results):
358
+ checked += 1
359
+
360
+ if result is True:
361
+ alive += 1
362
+ elif result is False:
363
+ dead += 1
364
+ dead_entries.append(stream_hash)
365
+ else:
366
  errors += 1
367
 
368
+ if checked % PROGRESS_UPDATE_EVERY == 0:
369
+ elapsed = int(time.time() - start_time)
370
+ speed = checked // max(1, elapsed)
371
+
372
+ await status_msg.edit_text(
373
+ f"πŸš€ DB Check Running...\n\n"
374
+ f"Checked: {checked}\n"
375
+ f"Alive: {alive}\n"
376
+ f"Dead: {dead}\n"
377
+ f"Errors: {errors}\n\n"
378
+ f"⚑ Speed: {speed}/sec"
379
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
+ except CursorNotFound:
382
+ await status_msg.edit_text("⚠️ Cursor expired (tv), retrying...")
383
+ finally:
384
+ await cursor.close()
385
 
386
+ # ───────── PURGE ─────────
387
+ if purge_mode and dead_entries:
388
+ purge_tasks = []
389
+ for stream_hash in dead_entries:
390
+ purge_tasks.append(db.delete_media_by_stream_id(stream_hash))
 
 
391
 
392
+ if len(purge_tasks) >= CONCURRENT_TASKS:
393
+ results = await asyncio.gather(*purge_tasks, return_exceptions=True)
394
+ purged += sum(1 for r in results if r)
395
+ purge_tasks = []
396
 
397
+ if purge_tasks:
398
+ results = await asyncio.gather(*purge_tasks, return_exceptions=True)
399
+ purged += sum(1 for r in results if r)
400
+
401
+ # ───────── FINAL RESULT ─────────
402
+ elapsed = int(time.time() - start_time)
403
 
 
 
404
  await status_msg.edit_text(
405
+ f"βœ… DB CHECK COMPLETE\n\n"
406
+ f"Checked: {checked}\n"
407
+ f"Alive: {alive}\n"
408
+ f"Dead: {dead}\n"
409
+ f"Errors: {errors}\n\n"
410
+ f"πŸ—‘ Purged: {purged}\n"
411
+ f"⏱ Time: {elapsed}s\n"
412
+ f"⚑ Avg Speed: {checked // max(1, elapsed)}/sec"
413
  )
414
 
415
+ except Exception as e:
416
+ await status_msg.edit_text(f"❌ DB check failed: {e}")
417
 
418
  # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
419
  # /exportchannels & /importchannels β€” Backup/restore channel config