Spaces:
Paused
Paused
Download bot.py from ttnikal/Filesharing: direct link, hf CLI and curl.
- Browser
- Download file 32 kB
-
https://huggingface.co/spaces/ttnikal/Filesharing/resolve/main/bot.py
- Command line
-
hf download hf://spaces/ttnikal/Filesharing/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/ttnikal/Filesharing/resolve/main/bot.py
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) | |
| 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")] | |
| ]) | |
| ) | |
| 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")]]) | |
| ) | |
| 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")] | |
| ]) | |
| ) | |
| 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)]])) | |
| 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) | |
| 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 | |
| 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")] | |
| ]) | |
| ) | |
| 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() | |
| async def close_settings(client, cb: CallbackQuery): await cb.message.delete() | |
| 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} | |
| 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()}") | |
| 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]}") | |
| 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) | |
| 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() | |
| 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}`") | |
| 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}") | |