"""utils/helpers.py — URL parsing, media metadata, misc helpers.""" import re import html import asyncio from pathlib import Path from typing import Optional from pyrogram.types import Message # ── Telegram URL parser ─────────────────────────────────────────────────────── def parse_tg_url(url: str) -> dict: """ Returns dict with keys: chat_id (str or int), msg_id (int). Supports: t.me/username/msgid t.me/username/topicid/msgid ← topic groups t.me/c/channelid/msgid ← private (numeric) t.me/c/channelid/topicid/msgid """ url = url.strip().rstrip("/") url = url.replace("https://telegram.me/", "https://t.me/") patterns = [ (r"t\.me/c/(\d+)/(\d+)/(\d+)", "priv_topic"), (r"t\.me/c/(\d+)/(\d+)", "priv"), (r"t\.me/([A-Za-z][A-Za-z0-9_]{3,})/(\d+)/(\d+)", "pub_topic"), (r"t\.me/([A-Za-z][A-Za-z0-9_]{3,})/(\d+)", "pub"), ] for pat, kind in patterns: m = re.search(pat, url) if not m: continue g = m.groups() if kind == "priv_topic": return {"chat_id": int(f"-100{g[0]}"), "topic_id": int(g[1]), "msg_id": int(g[2])} if kind == "priv": return {"chat_id": int(f"-100{g[0]}"), "msg_id": int(g[1])} if kind == "pub_topic": return {"chat_id": g[0], "topic_id": int(g[1]), "msg_id": int(g[2])} if kind == "pub": return {"chat_id": g[0], "msg_id": int(g[1])} raise ValueError(f"URL de Telegram no reconocida: {url}") def first_url(text: str) -> Optional[str]: """Extract first t.me URL from text.""" m = re.search(r"https?://t(?:elegram)?\.me/\S+", text) return m.group(0) if m else None # ── Media metadata ──────────────────────────────────────────────────────────── def get_media_info(msg: Message) -> Optional[dict]: """Return {'type', 'name', 'size', 'mime'} or None if no media.""" if msg.document: return { "type": "document", "name": msg.document.file_name or f"doc_{msg.id}", "size": msg.document.file_size or 0, "mime": msg.document.mime_type or "application/octet-stream", } if msg.video: return { "type": "video", "name": msg.video.file_name or f"video_{msg.id}.mp4", "size": msg.video.file_size or 0, "mime": "video/mp4", } if msg.audio: if msg.audio.file_name: name = msg.audio.file_name else: parts = [msg.audio.performer, msg.audio.title] base = " - ".join(p for p in parts if p) or f"audio_{msg.id}" name = f"{base}.mp3" return {"type": "audio", "name": name, "size": msg.audio.file_size or 0, "mime": "audio/mpeg"} if msg.photo: return {"type": "photo", "name": f"photo_{msg.id}.jpg", "size": 0, "mime": "image/jpeg"} if msg.voice: return {"type": "voice", "name": f"voice_{msg.id}.ogg", "size": msg.voice.file_size or 0, "mime": "audio/ogg"} if msg.video_note: return {"type": "video_note", "name": f"videonote_{msg.id}.mp4", "size": msg.video_note.file_size or 0, "mime": "video/mp4"} if msg.animation: name = msg.animation.file_name or f"gif_{msg.id}.mp4" return {"type": "animation", "name": name, "size": msg.animation.file_size or 0, "mime": "video/mp4"} if msg.sticker: ext = ".tgs" if msg.sticker.is_animated else ".webm" if msg.sticker.is_video else ".webp" return {"type": "sticker", "name": f"sticker_{msg.id}{ext}", "size": msg.sticker.file_size or 0, "mime": "image/webp"} return None # ── File helpers ────────────────────────────────────────────────────────────── def safe_filename(name: str) -> str: name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", name).strip(". ") return name or "file" def unique_path(directory: Path, name: str) -> Path: """Return a path that doesn't already exist (adds _1, _2 … suffix).""" p = directory / name if not p.exists(): return p stem, suffix = Path(name).stem, Path(name).suffix i = 1 while True: p = directory / f"{stem}_{i}{suffix}" if not p.exists(): return p i += 1 # ── Text helpers ────────────────────────────────────────────────────────────── def escape_html(text: str) -> str: return html.escape(str(text)) async def run_cmd(cmd: str) -> str: proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await proc.communicate() out = (stdout + stderr).decode(errors="replace") return out or "(sin salida)"