File size: 7,439 Bytes
5321464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
plugins/dl_mega.py β€” Descargador de Mega.nz.

Descarga archivos de mega.nz/file/... o mega.nz/folder/... y los sube a Telegram
detectando automΓ‘ticamente el tipo (video, audio, imagen, documento).

Comandos:
  .mega <url>   β€” Descarga archivo de Mega.nz
  .mcancel      β€” Cancela descarga activa en este chat

Requiere: pip install mega.py pycryptodome
"""
import asyncio
import os
import re
import time
from pathlib import Path

import requests
from pyrogram import filters
from pyrogram.types import Message

from bot import app
from config import Config

P      = Config.CMD_PREFIX
DL_DIR = Path("downloads"); DL_DIR.mkdir(exist_ok=True)

_active: dict = {}

VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm"}
AUDIO_EXT = {".mp3", ".m4a", ".wav", ".flac", ".aac", ".ogg"}
PHOTO_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}


# ── Helpers ───────────────────────────────────────────────────────────────────

def _format_size(b: int) -> str:
    for u in ("B", "KB", "MB", "GB"):
        if b < 1024:
            return f"{b:.1f} {u}"
        b /= 1024
    return f"{b:.1f} TB"


def _extract_url(text: str) -> str | None:
    for pat in [r"https?://mega\.nz/file/[^\s]+", r"https?://mega\.nz/folder/[^\s]+"]:
        found = re.findall(pat, text)
        if found:
            return found[0]
    return None


def _thumb(path: str) -> str | None:
    try:
        import subprocess
        out = path + ".jpg"
        subprocess.run(["ffmpeg", "-y", "-i", path, "-ss", "00:00:01", "-vframes", "1", out],
                       capture_output=True, timeout=15)
        return out if Path(out).exists() else None
    except Exception:
        return None


# ── .mega ─────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("mega", prefixes=P))
async def cmd_mega(client, msg: Message):
    await msg.delete()
    args = msg.text.split(None, 1)
    text = ""
    if len(args) > 1:
        text = args[1].strip()
    elif msg.reply_to_message:
        text = msg.reply_to_message.text or msg.reply_to_message.caption or ""

    url = _extract_url(text)
    if not url:
        m = await client.send_message(msg.chat.id,
                                      f"❓ **Uso:** `{P}mega <url_mega.nz>`\n"
                                      f"Soporta: `mega.nz/file/...` y `mega.nz/folder/...`")
        await asyncio.sleep(8); await m.delete(); return

    chat_id = msg.chat.id
    if chat_id in _active and not _active[chat_id].get("cancelled"):
        m = await client.send_message(msg.chat.id,
                                      f"⚠️ Descarga activa. Usa `{P}mcancel` para cancelar.")
        await asyncio.sleep(8); await m.delete(); return

    status = await client.send_message(msg.chat.id, "πŸ”— **Procesando enlace de Mega...**")
    ev = asyncio.Event()
    _active[chat_id] = {"cancelled": False, "cancel_event": ev}

    async def _run():
        try:
            await _process(client, msg, url, status, ev)
        except Exception as e:
            try: await status.edit(f"❌ `{e}`")
            except Exception: pass
        finally:
            _active.pop(chat_id, None)

    _active[chat_id]["task"] = asyncio.create_task(_run())


async def _process(client, msg: Message, url: str, status, ev: asyncio.Event):
    if ev.is_set():
        await status.edit("❌ Cancelada."); await asyncio.sleep(5); await status.delete(); return

    await status.edit("πŸ” **Obteniendo informaciΓ³n del archivo...**")

    try:
        import mega as mega_lib
    except ImportError:
        await status.edit("❌ **mega.py** no instalado.\nAñade `mega.py` a requirements.txt.")
        await asyncio.sleep(8); await status.delete(); return

    try:
        m = mega_lib.Mega()
        m.login_anonymous()
        file_info = m.get_public_url_info(url)
    except Exception as e:
        await status.edit(f"❌ Error obteniendo info de Mega: `{e}`")
        await asyncio.sleep(8); await status.delete(); return

    if not file_info:
        await status.edit("❌ No se pudo obtener información del archivo.")
        await asyncio.sleep(8); await status.delete(); return

    filename = file_info.get("name", "mega_file")
    filesize = file_info.get("size", 0)

    await status.edit(
        f"πŸ“„ **Archivo encontrado:**\n"
        f"**Nombre:** `{filename}`\n"
        f"**TamaΓ±o:** `{_format_size(filesize)}`\n\n"
        f"⬇️ **Descargando...**"
    )

    if ev.is_set():
        await status.edit("❌ Cancelada."); await asyncio.sleep(5); await status.delete(); return

    loop = asyncio.get_event_loop()
    safe_name = "".join(c for c in filename if c.isalnum() or c in "._- ")
    dest_path  = str(DL_DIR / safe_name)

    try:
        def _dl():
            m.download_url(url, dest_path=str(DL_DIR), dest_filename=safe_name)
        await loop.run_in_executor(None, _dl)
    except Exception as e:
        await status.edit(f"❌ Error descargando: `{e}`")
        await asyncio.sleep(8); await status.delete(); return

    if not Path(dest_path).exists():
        await status.edit("❌ El archivo no se descargó correctamente.")
        await asyncio.sleep(8); await status.delete(); return

    await status.edit("πŸ“€ **Subiendo a Telegram...**")

    ext   = Path(filename).suffix.lower()
    stem  = Path(filename).stem

    try:
        if ext in VIDEO_EXT:
            thumb = _thumb(dest_path)
            await client.send_video(
                msg.chat.id, dest_path,
                caption=f"`{stem}`",
                thumb=thumb,
            )
            if thumb: Path(thumb).unlink(missing_ok=True)
        elif ext in AUDIO_EXT:
            await client.send_audio(msg.chat.id, dest_path, caption=f"`{stem}`")
        elif ext in PHOTO_EXT:
            await client.send_photo(msg.chat.id, dest_path, caption=f"`{stem}`")
        else:
            await client.send_document(msg.chat.id, dest_path, caption=f"`{stem}`")
    except Exception as e:
        await client.send_message(msg.chat.id, f"❌ Error al subir: `{e}`")

    Path(dest_path).unlink(missing_ok=True)
    await status.delete()
    m2 = await client.send_message(msg.chat.id, f"βœ… **Descargado:** `{filename}`")
    await asyncio.sleep(5); await m2.delete()


# ── .mcancel ──────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("mcancel", prefixes=P))
async def cmd_mcancel(client, msg: Message):
    await msg.delete()
    chat_id = msg.chat.id
    entry   = _active.get(chat_id)
    if entry and not entry.get("cancelled"):
        entry["cancelled"] = True
        ev = entry.get("cancel_event")
        if ev: ev.set()
        t = entry.get("task")
        if t and not t.done(): t.cancel()
        m = await client.send_message(chat_id, "β›” **Descarga de Mega cancelada.**")
    else:
        m = await client.send_message(chat_id, "ℹ️ No hay descarga activa de Mega.")
    await asyncio.sleep(6); await m.delete()