""" Utilities Plugin — stats, search, DB integrity check, channel backup/restore. Commands (owner-only, private chat): /stats — DB dashboard (counts, sizes, uptime) /search
📊 Telegram-Stremio v{__version__}\n\n" f"Content\n" f" 🎬 Movies:
{total_movies}\n"
f" 📺 TV Shows: {total_tv}\n"
f" 🎞 Episodes: {total_episodes}\n"
f" 📁 Total streams: {total_streams}\n\n"
f"System\n"
f" ⏱ Uptime: {_format_uptime(uptime_sec)}\n"
f" 💾 DB size: {_format_bytes(total_db_size)}\n"
f" 🗄 Storage DBs: {db.current_db_index}\n"
f" 📡 AUTH channels: {channels_count}\n"
)
await status_msg.edit_text(text, parse_mode=enums.ParseMode.HTML)
except Exception as e:
LOGGER.error(f"[Stats] Error: {e}")
await status_msg.edit_text(f"❌ Error gathering stats: {e}",
parse_mode=enums.ParseMode.HTML)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# /search <title>\n\n"
"Example: /search Breaking Bad",
quote=True,
parse_mode=enums.ParseMode.HTML,
)
return
query = args[1].strip()
import re
pattern = re.compile(re.escape(query), re.IGNORECASE)
regex_filter = {"title": {"$regex": pattern.pattern, "$options": "i"}}
results = []
for i in range(1, db.current_db_index + 1):
storage = db.dbs.get(f"storage_{i}")
if storage is None:
continue
# Search movies
try:
movies = await storage["movie"].find(regex_filter).to_list(length=10)
for movie in movies:
qualities = movie.get("telegram", [])
q_list = ", ".join(q.get("quality", "?") for q in qualities) or "none"
results.append(
f"🎬 {movie.get('title', '?')} ({movie.get('release_year', '?')})\n"
f" TMDB: {movie.get('tmdb_id', '?')} | "
f"IMDb: {movie.get('imdb_id', '?')}\n"
f" Qualities: {q_list} | DB: storage_{i}"
)
except Exception as e:
LOGGER.error(f"[Search] Movie search error in storage_{i}: {e}")
# Search TV shows
try:
shows = await storage["tv"].find(regex_filter).to_list(length=10)
for show in shows:
seasons = show.get("seasons", [])
ep_count = sum(len(s.get("episodes", [])) for s in seasons)
stream_count = sum(
len(ep.get("telegram", []))
for s in seasons for ep in s.get("episodes", [])
)
season_nums = sorted(s.get("season_number", 0) for s in seasons)
s_range = f"S{season_nums[0]}–S{season_nums[-1]}" if season_nums else "?"
results.append(
f"📺 {show.get('title', '?')} ({show.get('release_year', '?')})\n"
f" TMDB: {show.get('tmdb_id', '?')} | "
f"IMDb: {show.get('imdb_id', '?')}\n"
f" {s_range} | {ep_count} episodes | {stream_count} streams | DB: storage_{i}"
)
except Exception as e:
LOGGER.error(f"[Search] TV search error in storage_{i}: {e}")
if not results:
# Debug: check if DB has any data at all
debug = ""
try:
for i in range(1, db.current_db_index + 1):
storage = db.dbs.get(f"storage_{i}")
if storage is None:
continue
mc = await storage["movie"].count_documents({})
tc = await storage["tv"].count_documents({})
# Grab a sample title to confirm data exists
sample = await storage["movie"].find_one({}, {"title": 1})
sample_title = sample.get("title", "?") if sample else "empty"
debug = f"\n\nDebug: storage_{i} has {mc} movies, {tc} tv. Sample: {sample_title}"
except Exception:
pass
await message.reply_text(
f"🔍 No results for {query}{debug}",
quote=True,
parse_mode=enums.ParseMode.HTML,
)
return
header = f"🔍 Search results for: {query}\n\n" body = "\n\n".join(results[:15]) # cap at 15 results footer = "" if len(results) > 15: footer = f"\n\n…and {len(results) - 15} more. Try a more specific query." await message.reply_text( header + body + footer, quote=True, parse_mode=enums.ParseMode.HTML, ) # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ # Check single Telegram message # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ async def check_message(client, stream_hash): try: decoded = await decode_string(stream_hash) chat_id = int(f"-100{decoded['chat_id']}") msg_id = int(decoded['msg_id']) msg = await client.get_messages(chat_id, msg_id) if msg.empty: return False return True except FloodWait as e: await asyncio.sleep(e.value) return await check_message(client, stream_hash) except Exception: return None # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ # Batch processor # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ async def process_batch(client, batch): tasks = [check_message(client, s) for s in batch] return await asyncio.gather(*tasks, return_exceptions=True) # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ # /dbcheck — Integrity checker (find orphaned streams) # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ @Client.on_message(filters.command('dbcheck') & filters.private & CustomFilters.owner, group=10) async def dbcheck_command(client: Client, message: Message): args = message.text.split() purge_mode = len(args) > 1 and args[1].lower() == "purge" status_msg = await message.reply_text( "🚀 DB Check started (Atlas-safe mode)...", quote=True ) checked = 0 dead = 0 alive = 0 errors = 0 purged = 0 dead_entries = [] start_time = time.time() try: for i in range(1, db.current_db_index + 1): storage = db.dbs.get(f"storage_{i}") if storage is None: continue # ───────── MOVIES (PAGINATION) ───────── last_id = None while True: query = {"_id": {"$gt": last_id}} if last_id else {} docs = await storage["movie"] \ .find(query) \ .sort("_id", 1) \ .limit(BATCH_SIZE) \ .to_list(length=BATCH_SIZE) if not docs: break for movie in docs: last_id = movie["_id"] title = movie.get("title", "Unknown") stream_ids = [ q.get("id") for q in movie.get("telegram", []) if q.get("id") ] for x in range(0, len(stream_ids), CONCURRENT_TASKS): batch = stream_ids[x:x + CONCURRENT_TASKS] results = await process_batch(client, batch) for stream_hash, result in zip(batch, results): checked += 1 if result is True: alive += 1 elif result is False: dead += 1 dead_entries.append(stream_hash) else: errors += 1 if checked % PROGRESS_UPDATE_EVERY == 0: elapsed = int(time.time() - start_time) speed = checked // max(1, elapsed) await status_msg.edit_text( f"🚀 DB Check Running...\n\n" f"Checked: {checked}\n" f"Alive: {alive}\n" f"Dead: {dead}\n" f"Errors: {errors}\n\n" f"⚡ Speed: {speed}/sec" ) # ───────── TV (PAGINATION) ───────── last_id = None while True: query = {"_id": {"$gt": last_id}} if last_id else {} docs = await storage["tv"] \ .find(query) \ .sort("_id", 1) \ .limit(BATCH_SIZE) \ .to_list(length=BATCH_SIZE) if not docs: break for show in docs: last_id = show["_id"] stream_ids = [] for season in show.get("seasons", []): for episode in season.get("episodes", []): for q in episode.get("telegram", []): if q.get("id"): stream_ids.append(q["id"]) for x in range(0, len(stream_ids), CONCURRENT_TASKS): batch = stream_ids[x:x + CONCURRENT_TASKS] results = await process_batch(client, batch) for stream_hash, result in zip(batch, results): checked += 1 if result is True: alive += 1 elif result is False: dead += 1 dead_entries.append(stream_hash) else: errors += 1 if checked % PROGRESS_UPDATE_EVERY == 0: elapsed = int(time.time() - start_time) speed = checked // max(1, elapsed) await status_msg.edit_text( f"🚀 DB Check Running...\n\n" f"Checked: {checked}\n" f"Alive: {alive}\n" f"Dead: {dead}\n" f"Errors: {errors}\n\n" f"⚡ Speed: {speed}/sec" ) # ───────── PURGE ───────── if purge_mode and dead_entries: purge_tasks = [] for stream_hash in dead_entries: purge_tasks.append(db.delete_media_by_stream_id(stream_hash)) if len(purge_tasks) >= CONCURRENT_TASKS: results = await asyncio.gather(*purge_tasks, return_exceptions=True) purged += sum(1 for r in results if r) purge_tasks = [] if purge_tasks: results = await asyncio.gather(*purge_tasks, return_exceptions=True) purged += sum(1 for r in results if r) # ───────── FINAL RESULT ───────── elapsed = int(time.time() - start_time) await status_msg.edit_text( f"✅ DB CHECK COMPLETE\n\n" f"Checked: {checked}\n" f"Alive: {alive}\n" f"Dead: {dead}\n" f"Errors: {errors}\n\n" f"🗑 Purged: {purged}\n" f"⏱ Time: {elapsed}s\n" f"⚡ Avg Speed: {checked // max(1, elapsed)}/sec" ) except Exception as e: LOGGER.error(f"[DBCheck] Error: {e}") await status_msg.edit_text(f"❌ DB check failed: {e}")