Filesharing / bot.py
ttnikal's picture
torreny bot
fd60a63
Raw History Blame Contribute Delete
32 kB
import os
import re
import time
import uuid
import asyncio
import shutil
from PyPDF2 import PdfWriter
from pyrogram import Client, filters
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, BotCommand
from config import API_ID, API_HASH, BOT_TOKEN, UPLOAD_DIR, BASE_URL
from db import set_metadata, get_metadata
print("--- πŸš€ Initializing NexusShare Pro Engine ---")
# Session management
user_sessions = {} # {uid: {"mode": "zip", "files": [], "name": "custom", ...}}
user_settings = {} # {uid: {"auto_delete": 24, "password": None, "self_destruct": False}}
user_locks = {}
HASH_RE = re.compile(r"^[a-fA-F0-9]{40}$|^[a-zA-Z2-7]{32}$")
def to_magnet(text: str) -> str:
"""Convert a magnet link, raw info-hash, or torrent URL into a usable aria2c target."""
text = text.strip()
if text.startswith("magnet:?"):
return text
if HASH_RE.match(text):
return f"magnet:?xt=urn:btih:{text}&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://open.tracker.cl:1337/announce&tr=udp://tracker.torrent.eu.org:451/announce"
return text # could be a direct .torrent URL
def get_progress_bar(current, total, start_time):
percentage = current * 100 / total
completed = int(percentage / 10)
bar = f"[{'β– ' * completed}{'β–‘' * (10 - completed)}]"
elapsed = time.time() - start_time
speed = current / elapsed / 1024 / 1024 if elapsed > 0 else 0
eta = (total - current) / (current / elapsed) if current > 0 else 0
return (
f"⚑ **Progress:** `{percentage:.1f}%`\n"
f"πŸ“Š `{bar}`\n"
f"πŸš€ **Speed:** `{speed:.2f} MB/s`\n"
f"πŸ“¦ **Size:** `{current/1024/1024:.1f}/{total/1024/1024:.1f} MB`\n"
f"⏳ **ETA:** `{int(eta)}s`"
)
async def download_torrent(client, uid, status_msg, target, udir, bid, cleanup_path=None):
"""Download a magnet/hash/.torrent target via aria2c, then publish files like /unzip does."""
dl_dir = os.path.join(UPLOAD_DIR, udir, f"torrent_{bid}")
os.makedirs(dl_dir, exist_ok=True)
cmd = [
"aria2c", "--dir", dl_dir, "--seed-time=0", "--bt-stop-timeout=900",
"--summary-interval=3", "--console-log-level=warn", "--max-connection-per-server=8",
"--split=8", "--enable-dht=true", "--enable-dht6=false", "--disable-ipv6=true",
"--dht-file-path=/tmp/aria2-dht.dat", "--enable-peer-exchange=true",
"--bt-tracker=udp://tracker.opentrackr.org:1337/announce,udp://open.tracker.cl:1337/announce,udp://tracker.torrent.eu.org:451/announce,udp://exodus.desync.com:6969/announce,udp://tracker.openbittorrent.com:6969/announce,udp://opentracker.i2p.rocks:6969/announce,udp://tracker.tiny-vps.com:6969/announce",
"--follow-torrent=mem", "--bt-save-metadata=false", target
]
p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
last_edit = 0
last_line = ""
async def watch():
nonlocal last_edit, last_line
while True:
line = await p.stdout.readline()
if not line:
break
last_line = line.decode(errors="ignore").strip()
if time.time() - last_edit > 4 and last_line:
try:
snippet = last_line[-300:]
await status_msg.edit_text(f"🧲 **Downloading Torrent...**\n━━━━━━━━━━━━\n`{snippet}`")
last_edit = time.time()
except Exception:
pass
watcher = asyncio.create_task(watch())
await p.wait()
await watcher
if cleanup_path and os.path.exists(cleanup_path):
try: os.remove(cleanup_path)
except Exception: pass
if p.returncode != 0:
try: shutil.rmtree(dl_dir)
except Exception: pass
await status_msg.edit_text(f"❌ **Torrent download failed.**\n`{last_line[-300:] if last_line else 'Unknown error'}`")
return
count = 0
main_dir = os.path.join(UPLOAD_DIR, udir)
for root, dirs, files in os.walk(dl_dir):
for f in files:
if f.endswith(".aria2"):
continue
count += 1
os.rename(os.path.join(root, f), os.path.join(main_dir, f"{bid}_{count:03d}_{f.replace(' ', '_')}"))
try: shutil.rmtree(dl_dir)
except Exception: pass
if count == 0:
await status_msg.edit_text("❌ **No files were downloaded.** Check the link/hash and try again.")
return
view_url = f"{BASE_URL}/view/{udir}/{bid}"
await status_msg.edit_text(
f"βœ… **Torrent Downloaded! ({count} file{'s' if count != 1 else ''})**\n\n🌐 [Browse / Download]({view_url})",
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Open Files", url=view_url)]])
)
if not BOT_TOKEN:
print("❌ Missing BOT_TOKEN")
bot = None
else:
bot = Client("nexus_bot", api_id=int(API_ID), api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
@bot.on_message(filters.command("start") & filters.private)
async def start_cmd(client, message: Message):
await message.reply_text(
"πŸš€ **NexusShare Professional v2.0**\n"
"━━━━━━━━━━━━━━━━━━━━\n"
"Welcome back! I am your advanced cloud companion. Send me any file to host it with lightning speed. ⚑\n\n"
"πŸ“‚ **Quick Actions:**\n"
"β”œ πŸ“¦ `/zip` β€’ Create Archives\n"
"β”œ πŸ”“ `/unzip` β€’ Extract & View Online\n"
"β”œ 🧲 `/torrent` β€’ Download via Magnet/Hash\n"
"β”œ πŸ“„ `/pdf_merge` β€’ Combine PDF Files\n"
"β”œ 🎬 `/vcompress` β€’ Video Optimizer\n"
"β”œ πŸ” `/search` β€’ Keyword Search\n"
"β”” πŸ“ `/files` β€’ Personal Storage\n\n"
"✨ *All files are protected and encrypted.*",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🌐 Web Dashboard", url=f"{BASE_URL}/?uid={message.from_user.id}"), InlineKeyboardButton("βš™οΈ Settings", callback_data="set_del_cycle")],
[InlineKeyboardButton("πŸ“– Full Usage Guide", callback_data="help_callback")]
])
)
@bot.on_callback_query(filters.regex("^help_callback$"))
async def help_callback(client, cb: CallbackQuery):
await cb.message.edit_text(
"πŸ“– **NexusShare Usage Guide**\n\n"
"1️⃣ **Hosting:** Send any file to get a high-speed direct link instantly.\n\n"
"2️⃣ **Processing:** Use commands like `/zip`, `/pdf_merge` or `/vcompress` (H.265), then send all your files. Click **'βœ… Done'** when finished.\n\n"
"3️⃣ **Unzipping:** Send `/unzip`, then upload your ZIP. You'll get a web link to browse individual files.\n\n"
"4️⃣ **Torrent:** Send `/torrent`, then send a magnet link, info-hash, or a `.torrent` file. I'll download it and give you a web link.\n\n"
"5️⃣ **Security:** Use `/settings` to set a global password for your links.\n\n"
"✨ *All files are auto-deleted after 24-48 hours.*",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Back", callback_data="back_to_start")]])
)
@bot.on_callback_query(filters.regex("^back_to_start$"))
async def back_to_start(client, cb: CallbackQuery):
await cb.message.edit_text(
"πŸ‘‹ **Welcome to NexusShare Pro!**\n\nSelect a feature below to get started or just send me a file!",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🌐 Open Web Dashboard", url=f"{BASE_URL}/?uid={cb.from_user.id}")],
[InlineKeyboardButton("πŸ“– Usage Guide", callback_data="help_callback")]
])
)
@bot.on_message(filters.command(["files", "allfiles"]) & filters.private)
async def files_cmd(client, message: Message):
uid = message.from_user.id
mode = message.command[0]
if mode == "allfiles":
text = "🌍 **Global Cloud Storage (Admin View)**\n━━━━━━━━━━━━━━━━━━━━\n"
total_count = 0
for u in os.listdir(UPLOAD_DIR):
udir = os.path.join(UPLOAD_DIR, u)
if os.path.isdir(udir):
files = os.listdir(udir)
if not files: continue
text += f"πŸ‘€ **User:** `{u}`\n"
for f in files[:5]:
total_count += 1
dname = "_".join(f.split("_")[1:]) if "_" in f else f
text += f"β”œ πŸ“„ `{dname}`\n"
if len(files) > 5: text += f"β”” *...and {len(files)-5} more*\n"
text += "\n"
if total_count == 0: return await message.reply_text("πŸ“­ **Global storage is empty.**")
return await message.reply_text(text)
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
web_url = f"{BASE_URL}/?uid={uid}"
if not os.path.exists(udir) or not os.listdir(udir):
return await message.reply_text(
"πŸ“‚ **Your Cloud Storage is Empty!**\n\n"
"You haven't uploaded any files yet. Send me any file or use the web dashboard to get started.",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Web Dashboard", url=web_url)]])
)
files = os.listdir(udir)
files.sort(key=lambda x: os.path.getmtime(os.path.join(udir, x)), reverse=True)
text = f"πŸ“ **My Cloud Files ({len(files)})**\n━━━━━━━━━━━━━━━━━━━━\n\n"
for f in files[:10]:
dname = "_".join(f.split("_")[1:]) if "_" in f else f
fpath = os.path.join(udir, f)
size = os.path.getsize(fpath) / (1024*1024)
text += f"πŸ“„ **{dname}**\n"
text += f"β”œ πŸ“ `Size:` {size:.2f} MB\n"
text += f"β”” πŸ“₯ [Get Link]({BASE_URL}/download/user_{uid}/{f})\n\n"
if len(files) > 10:
text += f"✨ *+{len(files)-10} more files available in web view.*"
await message.reply_text(text, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Full Web Manager", url=web_url)]]))
@bot.on_message(filters.command("settings") & filters.private)
async def settings_cmd(client, message: Message):
uid = message.from_user.id
s = user_settings.get(uid, {"auto_delete": 24, "password": None, "self_destruct": False})
user_settings[uid] = s
kb = InlineKeyboardMarkup([
[InlineKeyboardButton(f"⏰ Auto-Delete: {s['auto_delete'] if s['auto_delete'] > 0 else 'Never'}h", callback_data="set_del_cycle")],
[InlineKeyboardButton(f"πŸ’₯ Self-Destruct: {'ON' if s['self_destruct'] else 'OFF'}", callback_data="set_sd_toggle")],
[InlineKeyboardButton(f"πŸ” Password: {'βœ… Set' if s['password'] else '❌ None'}", callback_data="set_pass_init")],
[InlineKeyboardButton("πŸ—‘οΈ Clear My Storage", callback_data="confirm_clear")],
[InlineKeyboardButton("❌ Close", callback_data="close_settings")]
])
await message.reply_text("βš™οΈ **Bot Settings**\nConfigure your global preferences:", reply_markup=kb)
@bot.on_callback_query(filters.regex("^set_"))
async def settings_callbacks(client, cb: CallbackQuery):
uid = cb.from_user.id
s = user_settings.get(uid, {"auto_delete": 24, "password": None, "self_destruct": False})
if cb.data == "set_del_cycle":
opts = [1, 6, 12, 24, 48, 0] # 0 = Never
s["auto_delete"] = opts[(opts.index(s.get("auto_delete", 24)) + 1) % len(opts)]
elif cb.data == "set_sd_toggle":
s["self_destruct"] = not s.get("self_destruct", False)
elif cb.data == "set_pass_init":
user_sessions[uid] = {"waiting_pass": True, "target": "settings", "status_msg_id": cb.message.id}
return await cb.answer("⌨️ Send the password as a text message.", show_alert=True)
user_settings[uid] = s
kb = InlineKeyboardMarkup([
[InlineKeyboardButton(f"⏰ Auto-Delete: {s['auto_delete'] if s['auto_delete'] > 0 else 'Never'}h", callback_data="set_del_cycle")],
[InlineKeyboardButton(f"πŸ’₯ Self-Destruct: {'ON' if s['self_destruct'] else 'OFF'}", callback_data="set_sd_toggle")],
[InlineKeyboardButton(f"πŸ” Password: {'βœ… Set' if s['password'] else '❌ None'}", callback_data="set_pass_init")],
[InlineKeyboardButton("πŸ—‘οΈ Clear My Storage", callback_data="confirm_clear")],
[InlineKeyboardButton("❌ Close", callback_data="close_settings")]
])
try: await cb.edit_message_reply_markup(kb)
except: pass
@bot.on_callback_query(filters.regex("^confirm_clear$"))
async def confirm_clear(client, cb: CallbackQuery):
await cb.edit_message_text(
"⚠️ **Warning!**\nThis will delete all your uploaded files permanently. Are you sure?",
reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("βœ… Yes, Delete All", callback_data="execute_clear"),
InlineKeyboardButton("❌ No, Keep Files", callback_data="set_del_cycle")]
])
)
@bot.on_callback_query(filters.regex("^execute_clear$"))
async def execute_clear(client, cb: CallbackQuery):
uid = cb.from_user.id
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
if os.path.exists(udir):
shutil.rmtree(udir)
os.makedirs(udir)
await cb.answer("πŸ—‘οΈ Storage cleared successfully!", show_alert=True)
await cb.message.delete()
@bot.on_callback_query(filters.regex("^close_settings$"))
async def close_settings(client, cb: CallbackQuery): await cb.message.delete()
@bot.on_message(filters.command(["zip", "pdf_merge", "vcompress", "unzip", "torrent"]) & filters.private)
async def tool_init(client, message: Message):
uid = message.from_user.id
mode = message.command[0]
bid = str(uuid.uuid4())[:8]
if mode == "torrent":
msg = await message.reply_text(
"🧲 **Torrent Mode Active**\n━━━━━━━━━━━━\n"
"Send me one of the following:\n"
"β€’ A **magnet link**\n"
"β€’ A 40-char (or 32-char) **info-hash**\n"
"β€’ A direct **.torrent file**\n\n"
"I'll download it on the server and give you a web link."
)
user_sessions[uid] = {"mode": mode, "batch_id": bid, "status_msg_id": msg.id}
return
if mode == "unzip":
msg = await message.reply_text("πŸ”“ **Unzip Mode Active**\n━━━━━━━━━━━━\nSend me the **ZIP file** you want to extract and view online.")
user_sessions[uid] = {"mode":mode, "batch_id":bid, "status_msg_id":msg.id}
return
if mode == "vcompress":
kb = InlineKeyboardMarkup([
[InlineKeyboardButton("πŸ”‹ Ultra Low (360p)", callback_data="vc_q_ulow"), InlineKeyboardButton("πŸ“‰ Low (480p)", callback_data="vc_q_low")],
[InlineKeyboardButton("🎬 Medium (720p)", callback_data="vc_q_med"), InlineKeyboardButton("✨ High (1080p)", callback_data="vc_q_high")],
[InlineKeyboardButton("❌ Cancel", callback_data="close_settings")]
])
msg = await message.reply_text(
"🎬 **Video Compression Mode**\n━━━━━━━━━━━━━━━━━━━━\n"
"Send the videos you want to compress. Quality is set to `Medium` by default.\n"
"You can send multiple videos to process them in a batch.",
reply_markup=kb
)
user_sessions[uid] = {"mode":mode, "files":[], "quality":"med", "batch_id":bid, "status_msg_id":msg.id}
return
kb = InlineKeyboardMarkup([
[InlineKeyboardButton("βš™οΈ Compression Level", callback_data="zip_lvl_cycle") if mode=="zip" else InlineKeyboardButton("πŸ“„ Mode: PDF Merge", callback_data="none")],
[InlineKeyboardButton("✏️ Set Custom Name", callback_data="tool_rename")],
[InlineKeyboardButton("βœ… Process & Finish", callback_data="tool_done")]
])
msg = await message.reply_text(
f"πŸ“¦ **{mode.upper()} Mode Active**\n━━━━━━━━━━━━━━━━━━━━\nπŸ“‚ **Name:** `Auto` β€’ πŸ”’ **Files:** `0`\n✨ Send your files now...",
reply_markup=kb
)
user_sessions[uid] = {"mode":mode, "files":[], "level":5, "batch_id":bid, "status_msg_id":msg.id, "name":None}
@bot.on_callback_query(filters.regex("^vc_q_"))
async def video_quality_callback(client, cb: CallbackQuery):
uid = cb.from_user.id
if uid not in user_sessions: return
quality = cb.data.split("_")[-1]
user_sessions[uid]["quality"] = quality
q_map = {"ulow": "360p", "low": "480p", "med": "720p", "high": "1080p"}
kb = InlineKeyboardMarkup([
[InlineKeyboardButton("βœ… Start Batch Compression", callback_data="tool_done")]
])
await cb.message.edit_text(
f"🎬 **Video Compression Mode**\n━━━━━━━━━━━━\n"
f"Quality: `{q_map.get(quality, '720p')}`\n\n"
"✨ Now send me all the videos you want to compress, then click 'Start' below.",
reply_markup=kb
)
await cb.answer(f"βœ… Quality set to {quality.upper()}")
@bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
async def zip_lvl_cycle(client, cb: CallbackQuery):
uid = cb.from_user.id
if uid not in user_sessions: return
lvls = {0: "Store", 1: "Fast", 5: "Normal", 9: "Ultra"}
curr = user_sessions[uid].get("level", 5)
keys = list(lvls.keys())
new_lvl = keys[(keys.index(curr) + 1) % len(keys)]
user_sessions[uid]["level"] = new_lvl
await cb.answer(f"✨ Compression: {lvls[new_lvl]}")
@bot.on_callback_query(filters.regex("^tool_rename$"))
async def tool_rename_init(client, cb: CallbackQuery):
uid = cb.from_user.id
if uid in user_sessions:
user_sessions[uid]["renaming"] = True
await cb.answer("⌨️ Send new name as text.", show_alert=True)
@bot.on_message(filters.private & filters.text & ~filters.command(["zip", "pdf_merge", "start", "settings", "files", "help", "search", "unzip", "vcompress", "torrent"]))
async def handle_text_logic(client, message: Message):
uid = message.from_user.id
sess = user_sessions.get(uid)
if not sess: return
if sess.get("mode") == "torrent" and not sess.get("renaming") and not sess.get("waiting_pass"):
target = to_magnet(message.text.strip())
if not (target.startswith("magnet:?") or target.startswith("http://") or target.startswith("https://")):
return await message.reply_text("⚠️ That doesn't look like a magnet link, info-hash, or .torrent URL. Try again.")
uid_dir = f"user_{uid}"
os.makedirs(os.path.join(UPLOAD_DIR, uid_dir), exist_ok=True)
status = await message.reply_text("🧲 **Starting torrent download...**")
try: await message.delete()
except: pass
asyncio.create_task(download_torrent(client, uid, status, target, uid_dir, sess["batch_id"]))
del user_sessions[uid]
return
if sess.get("renaming"):
new_name = "".join(x for x in message.text if x.isalnum() or x in "._-").replace(" ", "_")[:50]
sess["name"] = new_name
sess["renaming"] = False
await message.reply_text(f"βœ… Name set to: `{new_name}`")
await message.delete()
elif sess.get("waiting_pass"):
pwd = message.text.strip()
if sess["target"] == "settings":
user_settings[uid]["password"] = pwd
await message.reply_text(f"βœ… Global Password set to: `{pwd}`")
del user_sessions[uid]
await message.delete()
@bot.on_callback_query(filters.regex("^tool_done$"))
async def tool_complete(client, cb: CallbackQuery):
uid = cb.from_user.id
sess = user_sessions.get(uid)
if not sess or not sess.get("files"): return await cb.answer("❌ No files provided!")
mode = sess["mode"]
await cb.message.edit_text(f"⏳ **Processing your request...**\n━━━━━━━━━━━━\nMode: `{mode.upper()}`\nFiles: `{len(sess['files'])}`")
udir = f"user_{uid}"
if mode == "vcompress":
results_text = "🎬 **Batch Compression Results:**\n━━━━━━━━━━━━━━━━━━━━\n\n"
quality = sess.get("quality", "med")
q_s = {
"ulow": ["-vf", "scale=-2:360", "-c:v", "libx265", "-crf", "32", "-preset", "fast"],
"low": ["-vf", "scale=-2:480", "-c:v", "libx265", "-crf", "30", "-preset", "fast"],
"med": ["-vf", "scale=-2:720", "-c:v", "libx265", "-crf", "28", "-preset", "fast"],
"high": ["-vf", "scale=-2:1080", "-c:v", "libx265", "-crf", "26", "-preset", "fast"]
}
for i, fpath in enumerate(sess["files"]):
if not os.path.exists(fpath): continue
fname = os.path.basename(fpath)
await cb.message.edit_text(f"⏳ **Compressing Video ({i+1}/{len(sess['files'])})...**\n`{fname}`")
opath = fpath.rsplit(".", 1)[0] + "_batch_comp.mp4"
cmd = ["ffmpeg", "-i", fpath] + q_s.get(quality, q_s["med"]) + ["-c:a", "aac", "-b:a", "96k", opath, "-y"]
p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await p.communicate()
# Cleaning source files
if os.path.exists(opath):
orig_size = os.path.getsize(fpath)
new_size = os.path.getsize(opath)
saved = 100 - (new_size * 100 / orig_size) if orig_size > 0 else 0
try: os.remove(fpath)
except: pass
sname = os.path.basename(opath)
settings = user_settings.get(uid, {"password":None, "self_destruct":False, "auto_delete": 24})
set_metadata(sname, {
"password": settings.get("password"),
"self_destruct": settings.get("self_destruct", False),
"expire_hours": settings.get("auto_delete", 24)
})
durl = f"{BASE_URL}/download/user_{uid}/{sname}"
results_text += f"βœ… `{fname}`\nβ”” πŸ“Š Saved: `{saved:.1f}%` β€’ [Link]({durl})\n\n"
else:
results_text += f"❌ `{fname}` - Compression failed.\n\n"
await cb.message.edit_text(results_text, disable_web_page_preview=True)
del user_sessions[uid]
return
ext = ".zip" if mode=="zip" else ".pdf"
oname = f"{sess['name']}{ext}" if sess.get("name") else f"{sess['batch_id']}_processed{ext}"
opath = os.path.join(UPLOAD_DIR, udir, oname)
try:
if mode == "zip":
lvl = sess.get("level", 5)
cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
p = await asyncio.create_subprocess_exec(*cmd, cwd=os.path.join(UPLOAD_DIR, udir), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await p.communicate()
else:
merger = PdfWriter()
for f in sess["files"]: merger.append(f)
with open(opath, "wb") as fo: merger.write(fo)
merger.close()
# CLEANUP: Delete source files after successful processing
for f in sess["files"]:
try: os.remove(f)
except: pass
settings = user_settings.get(uid, {"password":None, "self_destruct": False})
set_metadata(oname, {"password": settings.get("password"), "self_destruct": settings.get("self_destruct", False)})
set_metadata(sess["batch_id"], {"password": settings.get("password")})
durl = f"{BASE_URL}/download/{udir}/{oname}"
vurl = f"{BASE_URL}/view/{udir}/{sess['batch_id']}"
await cb.message.edit_text(
f"βœ… **{mode.upper()} Finished!**\n━━━━━━━━━━━━\n"
f"πŸ“‚ **File:** `{oname}`\n\n"
f"πŸ“₯ [Direct Download]({durl})\n"
f"🌐 [Web Dashboard]({vurl})\n\n"
f"πŸ›‘οΈ **Security:** `{'Locked πŸ”' if settings['password'] else 'Public πŸ”“'}`",
disable_web_page_preview=True
)
del user_sessions[uid]
except Exception as e: await cb.message.edit_text(f"❌ **Error:** `{e}`")
@bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.photo))
async def handle_uploads(client, message: Message):
uid = message.from_user.id
if uid not in user_locks: user_locks[uid] = asyncio.Lock()
async with user_locks[uid]:
media = message.document or message.video or message.audio or message.photo
if isinstance(media, list): media = media[-1]
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
os.makedirs(udir, exist_ok=True)
# Sanitize name
raw_fname = getattr(media, 'file_name', f"file_{int(time.time())}")
fname = os.path.basename(raw_fname).replace(" ", "_")
is_tool = uid in user_sessions
sname = f"{user_sessions[uid]['batch_id'] if is_tool else str(uuid.uuid4())[:4]}_{fname}"
if is_tool: sname = f"{len(user_sessions[uid].get('files', []))+1:03d}_{sname}"
fpath = os.path.join(udir, sname)
status = await message.reply_text("πŸ“₯ **Initializing...**", quote=True)
start = time.time()
ledit = 0
async def progress(c, t):
nonlocal ledit
if time.time() - ledit > 4:
try:
await status.edit_text(f"πŸ“₯ **Uploading:** `{fname}`\n━━━━━━━━━━━━\n{get_progress_bar(c, t, start)}")
ledit = time.time()
except: pass
try:
await client.download_media(message, file_name=fpath, progress=progress)
# Cleanup user message from chat to keep it clean
try: await message.delete()
except: pass
if is_tool:
if user_sessions[uid]["mode"] == "torrent":
if not fname.lower().endswith(".torrent"):
await status.edit_text("⚠️ Please send a valid `.torrent` file (or use a magnet link/hash as text instead).")
del user_sessions[uid]
return
bid = user_sessions[uid]["batch_id"]
await status.edit_text("🧲 **Starting torrent download...**")
asyncio.create_task(download_torrent(client, uid, status, fpath, f"user_{uid}", bid, cleanup_path=fpath))
del user_sessions[uid]
return
if user_sessions[uid]["mode"] == "unzip":
await status.edit_text("πŸ”“ **Extracting...**")
bid = user_sessions[uid]["batch_id"]
extract_dir = os.path.join(udir, bid)
os.makedirs(extract_dir, exist_ok=True)
cmd = ["7z", "x", fpath, f"-o{extract_dir}", "-y"]
settings = user_settings.get(uid, {"password":None})
if settings["password"]: cmd.append(f"-p{settings['password']}")
p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await p.communicate()
count = 0
for root, dirs, files in os.walk(extract_dir):
for f in files:
count += 1
os.rename(os.path.join(root, f), os.path.join(udir, f"{bid}_{count:03d}_{f.replace(' ','_')}"))
try: shutil.rmtree(extract_dir); os.remove(fpath)
except: pass
await status.edit_text(f"βœ… **Extracted {count} files!**\n\n🌐 [Browse Online]({BASE_URL}/view/user_{uid}/{bid})", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🌐 Open Dashboard", url=f"{BASE_URL}/view/user_{uid}/{bid}")]]) )
del user_sessions[uid]
return
user_sessions[uid].setdefault("files", []).append(fpath)
await status.delete()
try:
btn_row1 = []
if user_sessions[uid]["mode"] != "vcompress":
btn_row1.append(InlineKeyboardButton("✏️ Rename", callback_data="tool_rename"))
await client.edit_message_text(
uid, user_sessions[uid]["status_msg_id"],
f"πŸ“¦ **{user_sessions[uid]['mode'].upper()} Active**\n━━━━━━━━━━━━\n"
f"πŸ“‚ Added: `{fname}`\nπŸ”’ Total: `{len(user_sessions[uid]['files'])}`",
reply_markup=InlineKeyboardMarkup([
btn_row1,
[InlineKeyboardButton("βœ… Done / Start Process", callback_data="tool_done")]
])
)
except: pass
return
else:
settings = user_settings.get(uid, {"password":None, "self_destruct": False, "auto_delete": 24})
set_metadata(os.path.basename(fpath), {
"password": settings.get("password"),
"self_destruct": settings.get("self_destruct", False),
"expire_hours": settings.get("auto_delete", 24)
})
durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
btns = [[InlineKeyboardButton("πŸ“₯ Download", url=durl)]]
if fname.lower().endswith(('.mp4', '.mkv', '.webm')):
btns.append([InlineKeyboardButton("🎬 Watch Online", url=f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}")])
kb = InlineKeyboardMarkup(btns)
await status.edit_text(f"βœ… **Upload Success!**\n`{fname}`\n\nπŸ›‘οΈ Pass: `{'Yes' if settings.get('password') else 'No'}`", reply_markup=kb)
except Exception as e: await status.edit_text(f"❌ Error: {e}")