import os import json import time import asyncio import subprocess import math from pyrogram.errors import FloodWait from pyrogram.file_id import FileId from pyrogram.raw import functions, types # --- CONFIG --- HAS_FFMPEG = True # --- FUNCIONES DE MEDIA (FFMPEG) --- async def get_thumb(path, cid, ts, duration=0, seek_override=None): out = f"t_{cid}_{ts}.jpg" try: seek_time = "00:00:02" if seek_override: seek_time = seek_override elif duration > 0: s_sec = duration * 0.15 if duration < 5: s_sec = duration / 2 elif s_sec < 2: s_sec = 2 m, s = divmod(s_sec, 60) h, m = divmod(m, 60) seek_time = f"{int(h):02d}:{int(m):02d}:{s:06.3f}" cmd = ["ffmpeg", "-ss", seek_time, "-i", path, "-vf", "scale=iw*sar:ih", "-vframes", "1", "-q:v", "2", out, "-y"] process = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) await process.wait() if os.path.exists(out): return out except: pass return None async def get_meta(path): try: cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,duration,sample_aspect_ratio", "-of", "json", path] process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, _ = await process.communicate() d = json.loads(stdout) if not d.get('streams'): return 0, 0, 0 s = d['streams'][0] w = int(s.get('width', 0)) h = int(s.get('height', 0)) dur = int(float(s.get('duration', 0))) return w, h, dur except: return 0, 0, 0 async def progreso(cur, tot, msg, times, act): if not msg: return now = time.time() if (now - times[0]) > 4 or cur == tot: times[0] = now per = (cur * 100 / tot) if tot > 0 else 0 mb_cur, mb_tot = cur / 1048576, tot / 1048576 emoji = "⬇️" if "Descargando" in act else "📤" txt = f"{emoji} {act} 🚀 `{mb_cur:.1f}/{mb_tot:.1f} MB ({per:.1f}%)`" try: await msg.edit_text(txt) except: pass # --- PARALLEL DOWNLOADER (TURBO FIXED) --- async def fast_download(client, message, file_path, msg_status, act="Descargando"): media = message.video or message.document or message.audio or message.photo if not media: return None if isinstance(media, list): media = media[-1] file_id_obj = FileId.decode(media.file_id) file_size = media.file_size # Telegram GetFile limit is max 512KB (524288 bytes) chunk_size = 512 * 1024 # Pre-allocate file with open(file_path, "wb") as f: f.truncate(file_size) downloaded = 0 t_start = [time.time()] # Reducimos a 4 para evitar flood waits agresivos en HF sem = asyncio.Semaphore(4) location = types.InputDocumentFileLocation( id=file_id_obj.media_id, access_hash=file_id_obj.access_hash, file_reference=file_id_obj.file_reference, thumb_size="" ) if not message.photo else types.InputPhotoFileLocation( id=file_id_obj.media_id, access_hash=file_id_obj.access_hash, file_reference=file_id_obj.file_reference, thumb_size=file_id_obj.thumbnail_source.thumb_size if file_id_obj.thumbnail_source else "" ) async def download_chunk(offset, limit): nonlocal downloaded # Telegram requiere que 'limit' sea múltiplo de 4096 (4 KB) actual_limit = limit if actual_limit % 4096 != 0: actual_limit = ((actual_limit // 4096) + 1) * 4096 async with sem: for _ in range(3): try: r = await client.invoke( functions.upload.GetFile( location=location, offset=offset, limit=actual_limit ) ) if isinstance(r, types.upload.File): # Solo escribir hasta el límite real (sin el relleno de alineación) chunk_bytes = r.bytes[:limit] with open(file_path, "rb+") as out: out.seek(offset) out.write(chunk_bytes) downloaded += len(chunk_bytes) await progreso(downloaded, file_size, msg_status, t_start, act) return True elif isinstance(r, types.upload.FileMigrate): # No podemos manejar migración fácilmente en raw RPC sin recrear cliente o usar otro DC return False except FloodWait as e: await asyncio.sleep(e.value + 1) except Exception as e: print(f"Chunk error {offset}: {e}") await asyncio.sleep(2) return False tasks = [] for i in range(0, file_size, chunk_size): tasks.append(download_chunk(i, min(chunk_size, file_size - i))) results = await asyncio.gather(*tasks) if all(results) and downloaded >= file_size: return file_path # FALLBACK: Si el método Turbo falla, usar el método estándar de Pyrogram print("Turbo download failed or incomplete, falling back to standard method...") try: if os.path.exists(file_path): os.remove(file_path) path = await client.download_media( message, file_name=file_path, progress=progreso, progress_args=(msg_status, t_start, act) ) return path except Exception as e: print(f"Fallback download error: {e}") if os.path.exists(file_path): try: os.remove(file_path) except: pass return None