Spaces:
Paused
Paused
File size: 32,048 Bytes
8f16c3d a6dbd9e 8f16c3d 3b5901f afb618b f210842 4b4c033 c727649 8f16c3d 99e48df 8f16c3d 9885cf3 3b5901f 0df39bc 9885cf3 0fae7dc 0df39bc a6dbd9e 0df39bc 99e48df 0df39bc 9885cf3 0df39bc 9b7d89e a6dbd9e fd60a63 a6dbd9e 9885cf3 7a29f73 4b4c033 9b7d89e 8f16c3d 7a29f73 b45ad87 a6dbd9e b45ad87 9885cf3 2f4da2d b45ad87 9885cf3 8f16c3d 7a29f73 9885cf3 2f4da2d 9885cf3 a6dbd9e 9885cf3 2f4da2d 9885cf3 e116e85 99e48df b45ad87 9885cf3 99e48df b45ad87 99e48df 2f4da2d 9885cf3 b45ad87 2f4da2d b45ad87 99e48df 9885cf3 b45ad87 99e48df b45ad87 2f4da2d e116e85 0fae7dc 99e48df e116e85 de711f2 0fae7dc 9885cf3 e116e85 9885cf3 e116e85 99e48df 0fae7dc 99e48df de711f2 9885cf3 0fae7dc 99e48df 9885cf3 99e48df f210842 de711f2 0fae7dc 9885cf3 99e48df f210842 9885cf3 99e48df 0df39bc a6dbd9e 99e48df 0df39bc 99e48df 0df39bc a6dbd9e afb618b 9885cf3 afb618b 197e4fa 2f4da2d 197e4fa 2f4da2d 197e4fa 9885cf3 197e4fa c727649 9885cf3 c727649 9885cf3 c727649 0df39bc 9885cf3 0df39bc 197e4fa 2f4da2d 9885cf3 197e4fa 9885cf3 197e4fa 9885cf3 197e4fa 9885cf3 e116e85 c727649 99e48df 9885cf3 c727649 a6dbd9e c727649 99e48df a6dbd9e 99e48df 9885cf3 99e48df f210842 99e48df 9885cf3 99e48df 9b7d89e 99e48df 9885cf3 0df39bc 2f4da2d 0df39bc 2f4da2d de711f2 2f4da2d 9885cf3 0df39bc 9b7d89e 2f4da2d 197e4fa 9885cf3 0df39bc f210842 0df39bc f210842 2f4da2d 0fae7dc 99e48df 0df39bc 9885cf3 0df39bc 99e48df 2f4da2d 9885cf3 c727649 0df39bc 9885cf3 7a29f73 f210842 0df39bc 45689cf 0df39bc 45689cf 9885cf3 0df39bc 99e48df 2f4da2d 0df39bc 9885cf3 99e48df 0df39bc 45689cf 0df39bc 9885cf3 0df39bc 45689cf 0df39bc 0fae7dc 9885cf3 0df39bc a6dbd9e afb618b 9885cf3 afb618b 9885cf3 afb618b 9885cf3 afb618b 9885cf3 afb618b 2f4da2d 0df39bc 2f4da2d 9885cf3 2f4da2d 9885cf3 de711f2 9885cf3 2f4da2d 9885cf3 2f4da2d 0fae7dc 99e48df | 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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | 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}")
|