Download Backend/pyrofork/plugins/utilities.py from DevDoCode/stremio: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/spaces/DevDoCode/stremio/resolve/498fa78c309befbe82145c844ac171eae5f54cb2/Backend/pyrofork/plugins/utilities.py
- Command line
-
hf download hf://spaces/DevDoCode/stremio@498fa78c309befbe82145c844ac171eae5f54cb2/Backend/pyrofork/plugins/utilities.py
-
curl -L -o utilities.py https://huggingface.co/spaces/DevDoCode/stremio/resolve/498fa78c309befbe82145c844ac171eae5f54cb2/Backend/pyrofork/plugins/utilities.py
16.8 kB
| """ | |
| Utilities Plugin β stats, search, DB integrity check, channel backup/restore. | |
| Commands (owner-only, private chat): | |
| /stats β DB dashboard (counts, sizes, uptime) | |
| /search <title> β Search your DB for a movie or show | |
| /dbcheck β Find orphaned stream entries (dead Telegram messages) | |
| /dbcheck purge β Find and delete orphaned entries | |
| """ | |
| import asyncio | |
| import json | |
| import time | |
| from pyrogram import filters, Client, enums | |
| from pyrogram.types import Message | |
| from pyrogram.errors import FloodWait | |
| from pymongo.errors import CursorNotFound | |
| from Backend.helper.custom_filter import CustomFilters | |
| from Backend.logger import LOGGER | |
| from Backend import db, StartTime, __version__ | |
| from Backend.helper.settings_manager import SettingsManager | |
| from Backend.helper.encrypt import decode_string | |
| CONCURRENT_TASKS = 10 | |
| BATCH_SIZE = 100 | |
| PROGRESS_UPDATE_EVERY = 50 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # /stats β Quick dashboard | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _format_uptime(seconds: int) -> str: | |
| d, seconds = divmod(seconds, 86400) | |
| h, seconds = divmod(seconds, 3600) | |
| m, s = divmod(seconds, 60) | |
| parts = [] | |
| if d: | |
| parts.append(f"{d}d") | |
| if h: | |
| parts.append(f"{h}h") | |
| if m: | |
| parts.append(f"{m}m") | |
| parts.append(f"{s}s") | |
| return " ".join(parts) | |
| def _format_bytes(size_bytes: int) -> str: | |
| for unit in ["B", "KB", "MB", "GB"]: | |
| if size_bytes < 1024: | |
| return f"{size_bytes:.1f} {unit}" | |
| size_bytes /= 1024 | |
| return f"{size_bytes:.1f} TB" | |
| async def stats_command(client: Client, message: Message): | |
| """Show a DB and system dashboard.""" | |
| status_msg = await message.reply_text( | |
| "π Gathering statsβ¦", quote=True | |
| ) | |
| try: | |
| total_movies = 0 | |
| total_tv = 0 | |
| total_episodes = 0 | |
| total_streams = 0 | |
| total_db_size = 0 | |
| for i in range(1, db.current_db_index + 1): | |
| storage = db.dbs.get(f"storage_{i}") | |
| if storage is None: | |
| continue | |
| # Movie counts | |
| movie_count = await storage["movie"].count_documents({}) | |
| total_movies += movie_count | |
| # Count movie streams | |
| async for movie in storage["movie"].find({}, {"telegram": 1}): | |
| total_streams += len(movie.get("telegram", [])) | |
| # TV counts | |
| tv_count = await storage["tv"].count_documents({}) | |
| total_tv += tv_count | |
| # Count episodes and TV streams | |
| async for show in storage["tv"].find({}, {"seasons": 1}): | |
| for season in show.get("seasons", []): | |
| for episode in season.get("episodes", []): | |
| total_episodes += 1 | |
| total_streams += len(episode.get("telegram", [])) | |
| # DB size | |
| try: | |
| db_stats = await storage.command("dbStats") | |
| total_db_size += db_stats.get("dataSize", 0) | |
| except Exception: | |
| pass | |
| uptime_sec = int(time.time() - StartTime) | |
| channels_count = len(SettingsManager.current().auth_channels) | |
| text = ( | |
| f"<blockquote>π <b>Telegram-Stremio v{__version__}</b></blockquote>\n\n" | |
| f"<b>Content</b>\n" | |
| f" π¬ Movies: <code>{total_movies}</code>\n" | |
| f" πΊ TV Shows: <code>{total_tv}</code>\n" | |
| f" π Episodes: <code>{total_episodes}</code>\n" | |
| f" π Total streams: <code>{total_streams}</code>\n\n" | |
| f"<b>System</b>\n" | |
| f" β± Uptime: <code>{_format_uptime(uptime_sec)}</code>\n" | |
| f" πΎ DB size: <code>{_format_bytes(total_db_size)}</code>\n" | |
| f" π Storage DBs: <code>{db.current_db_index}</code>\n" | |
| f" π‘ AUTH channels: <code>{channels_count}</code>\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: <code>{e}</code>", | |
| parse_mode=enums.ParseMode.HTML) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # /search <title> β Search own DB | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def search_command(client: Client, message: Message): | |
| """Search the DB for movies or TV shows by title.""" | |
| args = message.text.split(maxsplit=1) | |
| if len(args) < 2: | |
| await message.reply_text( | |
| "Usage: /search <code><title></code>\n\n" | |
| "Example: <code>/search Breaking Bad</code>", | |
| 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"π¬ <b>{movie.get('title', '?')}</b> ({movie.get('release_year', '?')})\n" | |
| f" TMDB: <code>{movie.get('tmdb_id', '?')}</code> | " | |
| f"IMDb: <code>{movie.get('imdb_id', '?')}</code>\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"πΊ <b>{show.get('title', '?')}</b> ({show.get('release_year', '?')})\n" | |
| f" TMDB: <code>{show.get('tmdb_id', '?')}</code> | " | |
| f"IMDb: <code>{show.get('imdb_id', '?')}</code>\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\n<i>Debug: storage_{i} has {mc} movies, {tc} tv. Sample: {sample_title}</i>" | |
| except Exception: | |
| pass | |
| await message.reply_text( | |
| f"π No results for <b>{query}</b>{debug}", | |
| quote=True, | |
| parse_mode=enums.ParseMode.HTML, | |
| ) | |
| return | |
| header = f"<blockquote>π <b>Search results for:</b> {query}</blockquote>\n\n" | |
| body = "\n\n".join(results[:15]) # cap at 15 results | |
| footer = "" | |
| if len(results) > 15: | |
| footer = f"\n\n<i>β¦and {len(results) - 15} more. Try a more specific query.</i>" | |
| 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) | |
| # βββββββββββββββββββββββββββββββββββ | |
| 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}") | |