File size: 6,126 Bytes
8ce9e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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