Spaces:
Paused
Paused
Gemini CLI commited on
Commit Β·
9885cf3
1
Parent(s): afb618b
fix: web upload, terminal upload and bot ui polish
Browse files
app.py
CHANGED
|
@@ -272,6 +272,25 @@ async def download_file(filepath: str, request: Request, password: Optional[str]
|
|
| 272 |
|
| 273 |
return resp
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
@app.api_route("/upload/{filename}", methods=["PUT", "POST"])
|
| 276 |
@app.api_route("/upload", methods=["PUT", "POST"])
|
| 277 |
async def upload_files(
|
|
@@ -286,8 +305,8 @@ async def upload_files(
|
|
| 286 |
user_dir = os.path.join(UPLOAD_DIR, f"user_{user_id}")
|
| 287 |
os.makedirs(user_dir, exist_ok=True)
|
| 288 |
|
| 289 |
-
# Binary Upload
|
| 290 |
-
if request.method == "PUT" or (not files and not file):
|
| 291 |
content = await request.body()
|
| 292 |
if not content: raise HTTPException(status_code=400, detail="Empty file body.")
|
| 293 |
fname = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}"
|
|
@@ -296,11 +315,23 @@ async def upload_files(
|
|
| 296 |
with open(os.path.join(user_dir, safe_name), "wb") as b:
|
| 297 |
b.write(content)
|
| 298 |
if x_password: set_metadata(safe_name, {"password": x_password})
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
# Multipart Upload
|
| 302 |
target = (files or []) + ([file] if file else [])
|
| 303 |
-
if not target:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
urls = []
|
| 306 |
for f in target:
|
|
@@ -312,7 +343,7 @@ async def upload_files(
|
|
| 312 |
if x_password: set_metadata(name, {"password": x_password})
|
| 313 |
urls.append(f"{BASE_URL}/download/user_{user_id}/{name}")
|
| 314 |
|
| 315 |
-
return urls
|
| 316 |
|
| 317 |
@app.delete("/delete/{filename}")
|
| 318 |
async def delete_file(filename: str, x_user_id: str = Header(None)):
|
|
|
|
| 272 |
|
| 273 |
return resp
|
| 274 |
|
| 275 |
+
@app.get("/files")
|
| 276 |
+
async def list_files(x_user_id: str = Header(None)):
|
| 277 |
+
if not x_user_id: return []
|
| 278 |
+
user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}")
|
| 279 |
+
if not os.path.exists(user_dir): return []
|
| 280 |
+
|
| 281 |
+
files = []
|
| 282 |
+
for f in os.listdir(user_dir):
|
| 283 |
+
path = os.path.join(user_dir, f)
|
| 284 |
+
if os.path.isfile(path):
|
| 285 |
+
files.append({
|
| 286 |
+
"name": f,
|
| 287 |
+
"display_name": "_".join(f.split("_")[1:]) if "_" in f else f,
|
| 288 |
+
"size": os.path.getsize(path),
|
| 289 |
+
"mtime": os.path.getmtime(path)
|
| 290 |
+
})
|
| 291 |
+
files.sort(key=lambda x: x["mtime"], reverse=True)
|
| 292 |
+
return files
|
| 293 |
+
|
| 294 |
@app.api_route("/upload/{filename}", methods=["PUT", "POST"])
|
| 295 |
@app.api_route("/upload", methods=["PUT", "POST"])
|
| 296 |
async def upload_files(
|
|
|
|
| 305 |
user_dir = os.path.join(UPLOAD_DIR, f"user_{user_id}")
|
| 306 |
os.makedirs(user_dir, exist_ok=True)
|
| 307 |
|
| 308 |
+
# Binary Upload (curl -T style)
|
| 309 |
+
if request.method == "PUT" or (not files and not file and request.headers.get("content-type") != "application/x-www-form-urlencoded"):
|
| 310 |
content = await request.body()
|
| 311 |
if not content: raise HTTPException(status_code=400, detail="Empty file body.")
|
| 312 |
fname = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}"
|
|
|
|
| 315 |
with open(os.path.join(user_dir, safe_name), "wb") as b:
|
| 316 |
b.write(content)
|
| 317 |
if x_password: set_metadata(safe_name, {"password": x_password})
|
| 318 |
+
|
| 319 |
+
# Return plain text for terminal, JSON for web
|
| 320 |
+
if "curl" in request.headers.get("user-agent", "").lower():
|
| 321 |
+
return f"{BASE_URL}/download/user_{user_id}/{safe_name}\n"
|
| 322 |
+
return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"}
|
| 323 |
|
| 324 |
# Multipart Upload
|
| 325 |
target = (files or []) + ([file] if file else [])
|
| 326 |
+
if not target:
|
| 327 |
+
# Check if it was meant to be a binary upload but failed content-type check
|
| 328 |
+
content = await request.body()
|
| 329 |
+
if content:
|
| 330 |
+
fname = filename or f"upload_{int(time.time())}"
|
| 331 |
+
safe_name = f"{str(uuid.uuid4())[:8]}_{fname}"
|
| 332 |
+
with open(os.path.join(user_dir, safe_name), "wb") as b: b.write(content)
|
| 333 |
+
return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"}
|
| 334 |
+
raise HTTPException(status_code=400, detail="No files provided.")
|
| 335 |
|
| 336 |
urls = []
|
| 337 |
for f in target:
|
|
|
|
| 343 |
if x_password: set_metadata(name, {"password": x_password})
|
| 344 |
urls.append(f"{BASE_URL}/download/user_{user_id}/{name}")
|
| 345 |
|
| 346 |
+
return {"urls": urls} if len(urls) > 1 or x_user_id else urls[0]
|
| 347 |
|
| 348 |
@app.delete("/delete/{filename}")
|
| 349 |
async def delete_file(filename: str, x_user_id: str = Header(None)):
|
bot.py
CHANGED
|
@@ -9,11 +9,11 @@ from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton,
|
|
| 9 |
from config import API_ID, API_HASH, BOT_TOKEN, UPLOAD_DIR, BASE_URL
|
| 10 |
from db import set_metadata, get_metadata
|
| 11 |
|
| 12 |
-
print("--- Initializing
|
| 13 |
|
| 14 |
# Session management
|
| 15 |
-
user_sessions = {} # {uid: {"mode": "zip", "files": [], "name": "custom",
|
| 16 |
-
user_settings = {} # {uid: {"auto_delete": 24, "
|
| 17 |
user_locks = {}
|
| 18 |
|
| 19 |
def get_progress_bar(current, total, start_time):
|
|
@@ -24,17 +24,15 @@ def get_progress_bar(current, total, start_time):
|
|
| 24 |
speed = current / elapsed / 1024 / 1024 if elapsed > 0 else 0
|
| 25 |
eta = (total - current) / (current / elapsed) if current > 0 else 0
|
| 26 |
return (
|
| 27 |
-
f"β‘ **Progress:** {percentage:.1f}%\n"
|
| 28 |
-
f"π {bar}\n"
|
| 29 |
-
f"π **Speed:** {speed:.2f} MB/s\n"
|
| 30 |
-
f"π¦ **Size:** {current/1024/1024:.1f}/{total/1024/1024:.1f} MB\n"
|
| 31 |
-
f"β³ **ETA:** {int(eta)}s"
|
| 32 |
)
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
if _missing:
|
| 37 |
-
print(f"β Missing credentials: {', '.join(_missing)}")
|
| 38 |
bot = None
|
| 39 |
else:
|
| 40 |
bot = Client("nexus_bot", api_id=int(API_ID), api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
|
|
@@ -42,84 +40,115 @@ else:
|
|
| 42 |
@bot.on_message(filters.command("start") & filters.private)
|
| 43 |
async def start_cmd(client, message: Message):
|
| 44 |
await message.reply_text(
|
| 45 |
-
"
|
| 46 |
-
"The
|
| 47 |
-
"**
|
| 48 |
-
"π¦ /zip - Create compressed
|
| 49 |
-
"π /unzip - Extract
|
| 50 |
-
"π /pdf_merge - Combine
|
| 51 |
-
"π¬ /vcompress -
|
| 52 |
-
"π /search -
|
| 53 |
-
"π /files -
|
| 54 |
-
"βοΈ /settings
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
)
|
| 57 |
|
| 58 |
-
@bot.
|
| 59 |
-
async def
|
| 60 |
-
await message.
|
| 61 |
-
"π **Usage Guide
|
| 62 |
-
"1οΈβ£ **Hosting:** Send any file
|
| 63 |
-
"2οΈβ£ **
|
| 64 |
-
"3οΈβ£ **
|
| 65 |
-
"4οΈβ£ **
|
| 66 |
-
"
|
| 67 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
)
|
| 69 |
|
| 70 |
-
@bot.on_message(filters.command("
|
| 71 |
-
async def
|
| 72 |
uid = message.from_user.id
|
| 73 |
-
query = " ".join(message.command[1:]).lower()
|
| 74 |
-
if not query: return await message.reply_text("β Usage: /search <keyword>")
|
| 75 |
-
|
| 76 |
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
|
| 77 |
-
if not os.path.exists(udir)
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
text = f"
|
| 83 |
-
|
| 84 |
-
name = "_".join(r.split("_")[1:])
|
| 85 |
-
text += f"β’ `{name}`\n β {BASE_URL}/download/user_{uid}/{r}\n\n"
|
| 86 |
-
await message.reply_text(text)
|
| 87 |
|
| 88 |
@bot.on_message(filters.command("settings") & filters.private)
|
| 89 |
async def settings_cmd(client, message: Message):
|
| 90 |
uid = message.from_user.id
|
| 91 |
-
s = user_settings.get(uid, {"auto_delete": 24, "
|
| 92 |
user_settings[uid] = s
|
| 93 |
kb = InlineKeyboardMarkup([
|
| 94 |
[InlineKeyboardButton(f"β° Auto-Delete: {s['auto_delete']}h", callback_data="set_del_cycle")],
|
| 95 |
-
[InlineKeyboardButton(f"
|
| 96 |
-
[InlineKeyboardButton(
|
| 97 |
[InlineKeyboardButton("β Close", callback_data="close_settings")]
|
| 98 |
])
|
| 99 |
-
await message.reply_text("βοΈ **Settings**\nConfigure your global preferences:", reply_markup=kb)
|
| 100 |
|
| 101 |
@bot.on_callback_query(filters.regex("^set_"))
|
| 102 |
async def settings_callbacks(client, cb: CallbackQuery):
|
| 103 |
uid = cb.from_user.id
|
| 104 |
-
s = user_settings.get(uid, {"auto_delete": 24, "
|
| 105 |
|
| 106 |
if cb.data == "set_del_cycle":
|
| 107 |
opts = [1, 6, 12, 24, 48]
|
| 108 |
-
s["auto_delete"] = opts[(opts.index(s
|
| 109 |
-
elif cb.data == "set_sd_toggle":
|
| 110 |
-
s["self_destruct"] = not s["self_destruct"]
|
| 111 |
elif cb.data == "set_pass_init":
|
| 112 |
user_sessions[uid] = {"waiting_pass": True, "target": "settings", "status_msg_id": cb.message.id}
|
| 113 |
-
return await cb.answer("Send the password as a text message.", show_alert=True)
|
| 114 |
|
| 115 |
user_settings[uid] = s
|
| 116 |
kb = InlineKeyboardMarkup([
|
| 117 |
[InlineKeyboardButton(f"β° Auto-Delete: {s['auto_delete']}h", callback_data="set_del_cycle")],
|
| 118 |
-
[InlineKeyboardButton(f"
|
| 119 |
-
[InlineKeyboardButton(
|
| 120 |
[InlineKeyboardButton("β Close", callback_data="close_settings")]
|
| 121 |
])
|
| 122 |
-
await cb.edit_message_reply_markup(kb)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
@bot.on_callback_query(filters.regex("^close_settings$"))
|
| 125 |
async def close_settings(client, cb: CallbackQuery): await cb.message.delete()
|
|
@@ -131,33 +160,31 @@ else:
|
|
| 131 |
bid = str(uuid.uuid4())[:8]
|
| 132 |
|
| 133 |
if mode == "unzip":
|
| 134 |
-
msg = await message.reply_text("π **Unzip Mode Active**\nSend the ZIP file you want to extract.")
|
| 135 |
user_sessions[uid] = {"mode":mode, "batch_id":bid, "status_msg_id":msg.id}
|
| 136 |
return
|
| 137 |
|
| 138 |
if mode == "vcompress":
|
| 139 |
kb = InlineKeyboardMarkup([
|
| 140 |
-
[InlineKeyboardButton("π
|
| 141 |
-
[InlineKeyboardButton("
|
| 142 |
-
[InlineKeyboardButton("β¨ Quality: High (1080p)", callback_data="vc_q_high")],
|
| 143 |
[InlineKeyboardButton("β Cancel", callback_data="close_settings")]
|
| 144 |
])
|
| 145 |
msg = await message.reply_text(
|
| 146 |
"π¬ **Video Compression Mode**\nββββββββββββββββββββ\n"
|
| 147 |
-
"Send
|
| 148 |
-
"**Selected Quality:** `Medium (720p)`",
|
| 149 |
reply_markup=kb
|
| 150 |
)
|
| 151 |
-
user_sessions[uid] = {"mode":mode, "files":[], "quality":"
|
| 152 |
return
|
| 153 |
|
| 154 |
kb = InlineKeyboardMarkup([
|
| 155 |
-
[InlineKeyboardButton("βοΈ Level
|
| 156 |
[InlineKeyboardButton("βοΈ Set Custom Name", callback_data="tool_rename")],
|
| 157 |
-
[InlineKeyboardButton("β
|
| 158 |
])
|
| 159 |
msg = await message.reply_text(
|
| 160 |
-
f"π¦ **{mode.upper()} Mode Active**\nββββββββββββββββββββ\nπ **Name:** `Auto
|
| 161 |
reply_markup=kb
|
| 162 |
)
|
| 163 |
user_sessions[uid] = {"mode":mode, "files":[], "level":5, "batch_id":bid, "status_msg_id":msg.id, "name":None}
|
|
@@ -166,53 +193,27 @@ else:
|
|
| 166 |
async def video_quality_callback(client, cb: CallbackQuery):
|
| 167 |
uid = cb.from_user.id
|
| 168 |
if uid not in user_sessions: return
|
| 169 |
-
|
| 170 |
-
q_map = {"low": "Low (480p)", "med": "Medium (720p)", "high": "High (1080p)"}
|
| 171 |
quality = cb.data.split("_")[-1]
|
| 172 |
user_sessions[uid]["quality"] = quality
|
| 173 |
-
|
| 174 |
-
await cb.answer(f"Quality set to: {q_map[quality]}")
|
| 175 |
-
kb = InlineKeyboardMarkup([
|
| 176 |
-
[InlineKeyboardButton(f"{'β
' if quality=='low' else ''}π Low (480p)", callback_data="vc_q_low")],
|
| 177 |
-
[InlineKeyboardButton(f"{'β
' if quality=='med' else ''}π¬ Medium (720p)", callback_data="vc_q_med")],
|
| 178 |
-
[InlineKeyboardButton(f"{'β
' if quality=='high' else ''}β¨ High (1080p)", callback_data="vc_q_high")],
|
| 179 |
-
[InlineKeyboardButton("β Cancel", callback_data="close_settings")]
|
| 180 |
-
])
|
| 181 |
-
try:
|
| 182 |
-
await cb.message.edit_text(
|
| 183 |
-
"π¬ **Video Compression Mode**\nββββββββββββββββββββ\n"
|
| 184 |
-
"Send me the video you want to compress.\n\n"
|
| 185 |
-
f"**Selected Quality:** `{q_map[quality]}`",
|
| 186 |
-
reply_markup=kb
|
| 187 |
-
)
|
| 188 |
-
except: pass
|
| 189 |
|
| 190 |
@bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
|
| 191 |
async def zip_lvl_cycle(client, cb: CallbackQuery):
|
| 192 |
uid = cb.from_user.id
|
| 193 |
if uid not in user_sessions: return
|
| 194 |
-
|
| 195 |
-
levels = {0: "Store", 1: "Fast", 5: "Normal", 9: "Ultra"}
|
| 196 |
-
lvls_list = list(levels.keys())
|
| 197 |
curr = user_sessions[uid].get("level", 5)
|
| 198 |
-
|
|
|
|
| 199 |
user_sessions[uid]["level"] = new_lvl
|
| 200 |
-
|
| 201 |
-
await cb.answer(f"Compression: {levels[new_lvl]}")
|
| 202 |
-
kb = InlineKeyboardMarkup([
|
| 203 |
-
[InlineKeyboardButton(f"βοΈ Level: {levels[new_lvl]}", callback_data="zip_lvl_cycle")],
|
| 204 |
-
[InlineKeyboardButton("βοΈ Set Custom Name", callback_data="tool_rename")],
|
| 205 |
-
[InlineKeyboardButton("β
Done / Process", callback_data="tool_done")]
|
| 206 |
-
])
|
| 207 |
-
try: await cb.message.edit_reply_markup(kb)
|
| 208 |
-
except: pass
|
| 209 |
|
| 210 |
@bot.on_callback_query(filters.regex("^tool_rename$"))
|
| 211 |
async def tool_rename_init(client, cb: CallbackQuery):
|
| 212 |
uid = cb.from_user.id
|
| 213 |
if uid in user_sessions:
|
| 214 |
user_sessions[uid]["renaming"] = True
|
| 215 |
-
await cb.answer("Send new name as text.", show_alert=True)
|
| 216 |
|
| 217 |
@bot.on_message(filters.private & filters.text & ~filters.command(["zip", "pdf_merge", "start", "settings", "files", "help", "search", "unzip", "vcompress"]))
|
| 218 |
async def handle_text_logic(client, message: Message):
|
|
@@ -224,16 +225,14 @@ else:
|
|
| 224 |
new_name = "".join(x for x in message.text if x.isalnum() or x in "._-").replace(" ", "_")[:50]
|
| 225 |
sess["name"] = new_name
|
| 226 |
sess["renaming"] = False
|
| 227 |
-
|
| 228 |
-
await client.edit_message_text(uid, sess["status_msg_id"], f"π¦ **{sess['mode'].upper()} Active**\nββββββββββββ\nπ **Name:** `{new_name}`\nπ’ **Files:** {len(sess['files'])}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("βοΈ Rename", callback_data="tool_rename")],[InlineKeyboardButton("β
Done", callback_data="tool_done")]]))
|
| 229 |
-
except: pass
|
| 230 |
await message.delete()
|
| 231 |
|
| 232 |
elif sess.get("waiting_pass"):
|
| 233 |
pwd = message.text.strip()
|
| 234 |
if sess["target"] == "settings":
|
| 235 |
user_settings[uid]["password"] = pwd
|
| 236 |
-
await message.reply_text(f"β
|
| 237 |
del user_sessions[uid]
|
| 238 |
await message.delete()
|
| 239 |
|
|
@@ -241,52 +240,43 @@ else:
|
|
| 241 |
async def tool_complete(client, cb: CallbackQuery):
|
| 242 |
uid = cb.from_user.id
|
| 243 |
sess = user_sessions.get(uid)
|
| 244 |
-
if not sess or not sess
|
| 245 |
|
| 246 |
-
await cb.message.edit_text(f"β³ **Processing {sess['mode'].upper()}
|
| 247 |
udir = f"user_{uid}"
|
| 248 |
ext = ".zip" if sess["mode"]=="zip" else ".pdf"
|
| 249 |
-
oname = f"{sess['name']}{ext}" if sess.get("name") else f"{sess['batch_id']}
|
| 250 |
opath = os.path.join(UPLOAD_DIR, udir, oname)
|
| 251 |
|
| 252 |
try:
|
| 253 |
-
total_size = sum(os.path.getsize(f) for f in sess["files"] if os.path.exists(f))
|
| 254 |
if sess["mode"] == "zip":
|
| 255 |
lvl = sess.get("level", 5)
|
| 256 |
-
# Advance 7-Zip compression: Multi-threaded, optimized levels
|
| 257 |
cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
cwd=os.path.join(UPLOAD_DIR, udir),
|
| 261 |
-
stdout=asyncio.subprocess.PIPE,
|
| 262 |
-
stderr=asyncio.subprocess.PIPE
|
| 263 |
-
)
|
| 264 |
-
stdout, stderr = await process.communicate()
|
| 265 |
-
if process.returncode != 0:
|
| 266 |
-
raise Exception(f"7z Error: {stderr.decode()}")
|
| 267 |
else:
|
| 268 |
merger = PdfWriter()
|
| 269 |
for f in sess["files"]: merger.append(f)
|
| 270 |
with open(opath, "wb") as fo: merger.write(fo)
|
| 271 |
merger.close()
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
set_metadata(
|
| 276 |
-
set_metadata(sess["batch_id"], {"password": settings["password"]}) # For Web View
|
| 277 |
|
| 278 |
durl = f"{BASE_URL}/download/{udir}/{oname}"
|
| 279 |
-
vurl = f"{BASE_URL}/view/{udir}/{
|
| 280 |
-
saved = 100 - (os.path.getsize(opath)*100/total_size) if total_size>0 else 0
|
| 281 |
|
| 282 |
await cb.message.edit_text(
|
| 283 |
-
f"β
**
|
| 284 |
-
f"
|
| 285 |
-
f"
|
|
|
|
|
|
|
| 286 |
disable_web_page_preview=True
|
| 287 |
)
|
| 288 |
del user_sessions[uid]
|
| 289 |
-
except Exception as e: await cb.message.edit_text(f"β Error: {e}")
|
| 290 |
|
| 291 |
@bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.photo))
|
| 292 |
async def handle_uploads(client, message: Message):
|
|
@@ -299,20 +289,14 @@ else:
|
|
| 299 |
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
|
| 300 |
os.makedirs(udir, exist_ok=True)
|
| 301 |
|
| 302 |
-
#
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
ext = os.path.splitext(getattr(media, 'file_name', ""))[1] or (".jpg" if message.photo else "")
|
| 307 |
-
fname = f"{cname}{ext}"
|
| 308 |
-
else:
|
| 309 |
-
fname = os.path.basename(getattr(media, 'file_name', f"file_{int(time.time())}"))
|
| 310 |
-
|
| 311 |
is_tool = uid in user_sessions
|
| 312 |
sname = f"{user_sessions[uid]['batch_id'] if is_tool else str(uuid.uuid4())[:4]}_{fname}"
|
| 313 |
-
if is_tool: sname = f"{len(user_sessions[uid]['files'])+1:03d}_{sname}"
|
| 314 |
-
|
| 315 |
fpath = os.path.join(udir, sname)
|
|
|
|
| 316 |
status = await message.reply_text("π₯ **Initializing...**", quote=True)
|
| 317 |
start = time.time()
|
| 318 |
ledit = 0
|
|
@@ -321,115 +305,66 @@ else:
|
|
| 321 |
nonlocal ledit
|
| 322 |
if time.time() - ledit > 4:
|
| 323 |
try:
|
| 324 |
-
await status.edit_text(f"π₯ **
|
| 325 |
ledit = time.time()
|
| 326 |
except: pass
|
| 327 |
|
| 328 |
try:
|
| 329 |
await client.download_media(message, file_name=fpath, progress=progress)
|
| 330 |
-
|
| 331 |
-
except: pass
|
| 332 |
-
|
| 333 |
if is_tool:
|
| 334 |
if user_sessions[uid]["mode"] == "unzip":
|
| 335 |
-
await status.edit_text("π **Extracting
|
| 336 |
bid = user_sessions[uid]["batch_id"]
|
| 337 |
extract_dir = os.path.join(udir, bid)
|
| 338 |
os.makedirs(extract_dir, exist_ok=True)
|
| 339 |
-
|
| 340 |
-
# Use 7z to extract
|
| 341 |
cmd = ["7z", "x", fpath, f"-o{extract_dir}", "-y"]
|
| 342 |
settings = user_settings.get(uid, {"password":None})
|
| 343 |
-
if settings["password"]:
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
stdout=asyncio.subprocess.PIPE,
|
| 349 |
-
stderr=asyncio.subprocess.PIPE
|
| 350 |
-
)
|
| 351 |
-
stdout, stderr = await process.communicate()
|
| 352 |
-
|
| 353 |
-
if process.returncode != 0:
|
| 354 |
-
err = stderr.decode()
|
| 355 |
-
if "Wrong password" in err or "Password Error" in err:
|
| 356 |
-
await status.edit_text("π **Password Required!**\nThis ZIP is encrypted. Set your password in /settings and try again.")
|
| 357 |
-
else:
|
| 358 |
-
await status.edit_text(f"β Extraction failed: {err[:100]}")
|
| 359 |
-
return
|
| 360 |
-
|
| 361 |
-
extracted_count = 0
|
| 362 |
for root, dirs, files in os.walk(extract_dir):
|
| 363 |
for f in files:
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
try:
|
| 370 |
-
shutil.rmtree(extract_dir)
|
| 371 |
-
os.remove(fpath)
|
| 372 |
except: pass
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
kb = InlineKeyboardMarkup([[InlineKeyboardButton("π View Extracted Files", url=vurl)]])
|
| 376 |
-
await status.edit_text(
|
| 377 |
-
f"β
**Extraction Complete!**\nπ’ Files: {extracted_count}\n\n"
|
| 378 |
-
f"You can now view and download individual files from the web link below.",
|
| 379 |
-
reply_markup=kb
|
| 380 |
-
)
|
| 381 |
del user_sessions[uid]
|
| 382 |
return
|
| 383 |
|
| 384 |
if user_sessions[uid]["mode"] == "vcompress":
|
| 385 |
-
await status.edit_text("β³ **Compressing Video...**\
|
| 386 |
quality = user_sessions[uid].get("quality", "med")
|
| 387 |
-
|
| 388 |
-
"low": ["-vf", "scale=-2:480", "-c:v", "libx264", "-crf", "28", "-preset", "faster"],
|
| 389 |
-
"med": ["-vf", "scale=-2:720", "-c:v", "libx264", "-crf", "24", "-preset", "faster"],
|
| 390 |
-
"high": ["-vf", "scale=-2:1080", "-c:v", "libx264", "-crf", "22", "-preset", "faster"]
|
| 391 |
-
}
|
| 392 |
opath = fpath.rsplit(".", 1)[0] + "_compressed.mp4"
|
| 393 |
-
cmd = ["ffmpeg", "-i", fpath] +
|
| 394 |
-
|
| 395 |
-
await
|
| 396 |
|
| 397 |
-
orig_size = os.path.getsize(fpath)
|
| 398 |
if os.path.exists(opath):
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
except: pass
|
| 402 |
-
sname = os.path.basename(opath)
|
| 403 |
fpath = opath
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
else:
|
| 407 |
-
saved = 0
|
| 408 |
-
await status.edit_text("β Compression failed. Sending original.")
|
| 409 |
-
|
| 410 |
-
settings = user_settings.get(uid, {"auto_delete":24, "self_destruct":False, "password":None})
|
| 411 |
-
set_metadata(os.path.basename(fpath), {"password": settings["password"], "self_destruct": settings["self_destruct"]})
|
| 412 |
-
durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
|
| 413 |
-
purl = f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}"
|
| 414 |
-
kb = InlineKeyboardMarkup([[InlineKeyboardButton("π₯ Download", url=durl), InlineKeyboardButton("π¬ Watch Online", url=purl)]])
|
| 415 |
-
await status.edit_text(f"β
**Compression Ready!**\n`{fname}`\n\nπ **Saved:** {saved:.1f}%\nπ‘οΈ Pass: {'Yes' if settings['password'] else 'No'}", reply_markup=kb)
|
| 416 |
del user_sessions[uid]
|
| 417 |
return
|
| 418 |
|
| 419 |
user_sessions[uid]["files"].append(fpath)
|
| 420 |
-
try:
|
| 421 |
-
await client.edit_message_text(uid, user_sessions[uid]["status_msg_id"], f"π¦ **{user_sessions[uid]['mode'].upper()} Active**\nββββββββββββ\nπ Last: `{fname}`\nπ’ **Total:** {len(user_sessions[uid]['files'])}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("βοΈ Rename", callback_data="tool_rename")],[InlineKeyboardButton("β
Done", callback_data="tool_done")]]))
|
| 422 |
-
except: pass
|
| 423 |
await status.delete()
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
await status.edit_text(f"β
**Success!**\n`{fname}`\n\nπ‘οΈ Pass: {'Yes' if settings['password'] else 'No'} | π₯ SD: {'Yes' if settings['self_destruct'] else 'No'}", reply_markup=kb)
|
| 435 |
except Exception as e: await status.edit_text(f"β Error: {e}")
|
|
|
|
| 9 |
from config import API_ID, API_HASH, BOT_TOKEN, UPLOAD_DIR, BASE_URL
|
| 10 |
from db import set_metadata, get_metadata
|
| 11 |
|
| 12 |
+
print("--- π Initializing NexusShare Pro Engine ---")
|
| 13 |
|
| 14 |
# Session management
|
| 15 |
+
user_sessions = {} # {uid: {"mode": "zip", "files": [], "name": "custom", ...}}
|
| 16 |
+
user_settings = {} # {uid: {"auto_delete": 24, "password": None}}
|
| 17 |
user_locks = {}
|
| 18 |
|
| 19 |
def get_progress_bar(current, total, start_time):
|
|
|
|
| 24 |
speed = current / elapsed / 1024 / 1024 if elapsed > 0 else 0
|
| 25 |
eta = (total - current) / (current / elapsed) if current > 0 else 0
|
| 26 |
return (
|
| 27 |
+
f"β‘ **Progress:** `{percentage:.1f}%`\n"
|
| 28 |
+
f"π `{bar}`\n"
|
| 29 |
+
f"π **Speed:** `{speed:.2f} MB/s`\n"
|
| 30 |
+
f"π¦ **Size:** `{current/1024/1024:.1f}/{total/1024/1024:.1f} MB`\n"
|
| 31 |
+
f"β³ **ETA:** `{int(eta)}s`"
|
| 32 |
)
|
| 33 |
|
| 34 |
+
if not BOT_TOKEN:
|
| 35 |
+
print("β Missing BOT_TOKEN")
|
|
|
|
|
|
|
| 36 |
bot = None
|
| 37 |
else:
|
| 38 |
bot = Client("nexus_bot", api_id=int(API_ID), api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True)
|
|
|
|
| 40 |
@bot.on_message(filters.command("start") & filters.private)
|
| 41 |
async def start_cmd(client, message: Message):
|
| 42 |
await message.reply_text(
|
| 43 |
+
"π **Welcome to NexusShare Pro!**\n\n"
|
| 44 |
+
"The ultimate multi-tool for file management and high-speed hosting. π\n\n"
|
| 45 |
+
"π **Core Features:**\n"
|
| 46 |
+
"β π¦ `/zip` - Create compressed archives\n"
|
| 47 |
+
"β π `/unzip` - Extract and view ZIPs online\n"
|
| 48 |
+
"β π `/pdf_merge` - Combine multiple PDFs\n"
|
| 49 |
+
"β π¬ `/vcompress` - Advanced Video compression\n"
|
| 50 |
+
"β π `/search` - Find your uploaded files\n"
|
| 51 |
+
"β π `/files` - Manage your cloud storage\n\n"
|
| 52 |
+
"βοΈ Use `/settings` to set passwords or cleanup timers.",
|
| 53 |
+
reply_markup=InlineKeyboardMarkup([
|
| 54 |
+
[InlineKeyboardButton("π Open Web Dashboard", url=BASE_URL)],
|
| 55 |
+
[InlineKeyboardButton("π Usage Guide", callback_data="help_callback")]
|
| 56 |
+
])
|
| 57 |
)
|
| 58 |
|
| 59 |
+
@bot.on_callback_query(filters.regex("^help_callback$"))
|
| 60 |
+
async def help_callback(client, cb: CallbackQuery):
|
| 61 |
+
await cb.message.edit_text(
|
| 62 |
+
"π **NexusShare Usage Guide**\n\n"
|
| 63 |
+
"1οΈβ£ **Hosting:** Send any file to get a high-speed direct link instantly.\n\n"
|
| 64 |
+
"2οΈβ£ **Processing:** Use commands like `/zip` or `/pdf_merge`, then send all your files. Click **'β
Done'** when finished.\n\n"
|
| 65 |
+
"3οΈβ£ **Unzipping:** Send `/unzip`, then upload your ZIP. You'll get a web link to browse individual files.\n\n"
|
| 66 |
+
"4οΈβ£ **Security:** Use `/settings` to set a global password for your links.\n\n"
|
| 67 |
+
"β¨ *All files are auto-deleted after 24-48 hours.*",
|
| 68 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("β¬
οΈ Back", callback_data="back_to_start")]])
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
@bot.on_callback_query(filters.regex("^back_to_start$"))
|
| 72 |
+
async def back_to_start(client, cb: CallbackQuery):
|
| 73 |
+
await cb.message.edit_text(
|
| 74 |
+
"π **Welcome to NexusShare Pro!**\n\nSelect a feature below to get started or just send me a file!",
|
| 75 |
+
reply_markup=InlineKeyboardMarkup([
|
| 76 |
+
[InlineKeyboardButton("π Open Web Dashboard", url=BASE_URL)],
|
| 77 |
+
[InlineKeyboardButton("π Usage Guide", callback_data="help_callback")]
|
| 78 |
+
])
|
| 79 |
)
|
| 80 |
|
| 81 |
+
@bot.on_message(filters.command("files") & filters.private)
|
| 82 |
+
async def files_cmd(client, message: Message):
|
| 83 |
uid = message.from_user.id
|
|
|
|
|
|
|
|
|
|
| 84 |
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
|
| 85 |
+
if not os.path.exists(udir) or not os.listdir(udir):
|
| 86 |
+
return await message.reply_text("π **Your storage is empty!**\nSend some files to see them here.")
|
| 87 |
|
| 88 |
+
files = os.listdir(udir)
|
| 89 |
+
text = f"π **Your Cloud Files ({len(files)}):**\nββββββββββββββββββββ\n"
|
| 90 |
+
for f in files[:15]:
|
| 91 |
+
dname = "_".join(f.split("_")[1:])
|
| 92 |
+
size = os.path.getsize(os.path.join(udir, f)) / (1024*1024)
|
| 93 |
+
text += f"π `{dname}`\nβ π₯ [Download]({BASE_URL}/download/user_{uid}/{f}) β’ `{size:.1f}MB`\n\n"
|
| 94 |
|
| 95 |
+
if len(files) > 15: text += f"π *And {len(files)-15} more files...*"
|
| 96 |
+
await message.reply_text(text, disable_web_page_preview=True)
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
@bot.on_message(filters.command("settings") & filters.private)
|
| 99 |
async def settings_cmd(client, message: Message):
|
| 100 |
uid = message.from_user.id
|
| 101 |
+
s = user_settings.get(uid, {"auto_delete": 24, "password": None})
|
| 102 |
user_settings[uid] = s
|
| 103 |
kb = InlineKeyboardMarkup([
|
| 104 |
[InlineKeyboardButton(f"β° Auto-Delete: {s['auto_delete']}h", callback_data="set_del_cycle")],
|
| 105 |
+
[InlineKeyboardButton(f"π Password: {'β
Set' if s['password'] else 'β None'}", callback_data="set_pass_init")],
|
| 106 |
+
[InlineKeyboardButton("ποΈ Clear My Storage", callback_data="confirm_clear")],
|
| 107 |
[InlineKeyboardButton("β Close", callback_data="close_settings")]
|
| 108 |
])
|
| 109 |
+
await message.reply_text("βοΈ **Bot Settings**\nConfigure your global preferences:", reply_markup=kb)
|
| 110 |
|
| 111 |
@bot.on_callback_query(filters.regex("^set_"))
|
| 112 |
async def settings_callbacks(client, cb: CallbackQuery):
|
| 113 |
uid = cb.from_user.id
|
| 114 |
+
s = user_settings.get(uid, {"auto_delete": 24, "password": None})
|
| 115 |
|
| 116 |
if cb.data == "set_del_cycle":
|
| 117 |
opts = [1, 6, 12, 24, 48]
|
| 118 |
+
s["auto_delete"] = opts[(opts.index(s.get("auto_delete", 24)) + 1) % len(opts)]
|
|
|
|
|
|
|
| 119 |
elif cb.data == "set_pass_init":
|
| 120 |
user_sessions[uid] = {"waiting_pass": True, "target": "settings", "status_msg_id": cb.message.id}
|
| 121 |
+
return await cb.answer("β¨οΈ Send the password as a text message.", show_alert=True)
|
| 122 |
|
| 123 |
user_settings[uid] = s
|
| 124 |
kb = InlineKeyboardMarkup([
|
| 125 |
[InlineKeyboardButton(f"β° Auto-Delete: {s['auto_delete']}h", callback_data="set_del_cycle")],
|
| 126 |
+
[InlineKeyboardButton(f"π Password: {'β
Set' if s['password'] else 'β None'}", callback_data="set_pass_init")],
|
| 127 |
+
[InlineKeyboardButton("ποΈ Clear My Storage", callback_data="confirm_clear")],
|
| 128 |
[InlineKeyboardButton("β Close", callback_data="close_settings")]
|
| 129 |
])
|
| 130 |
+
try: await cb.edit_message_reply_markup(kb)
|
| 131 |
+
except: pass
|
| 132 |
+
|
| 133 |
+
@bot.on_callback_query(filters.regex("^confirm_clear$"))
|
| 134 |
+
async def confirm_clear(client, cb: CallbackQuery):
|
| 135 |
+
await cb.edit_message_text(
|
| 136 |
+
"β οΈ **Warning!**\nThis will delete all your uploaded files permanently. Are you sure?",
|
| 137 |
+
reply_markup=InlineKeyboardMarkup([
|
| 138 |
+
[InlineKeyboardButton("β
Yes, Delete All", callback_data="execute_clear"),
|
| 139 |
+
InlineKeyboardButton("β No, Keep Files", callback_data="set_del_cycle")]
|
| 140 |
+
])
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
@bot.on_callback_query(filters.regex("^execute_clear$"))
|
| 144 |
+
async def execute_clear(client, cb: CallbackQuery):
|
| 145 |
+
uid = cb.from_user.id
|
| 146 |
+
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
|
| 147 |
+
if os.path.exists(udir):
|
| 148 |
+
shutil.rmtree(udir)
|
| 149 |
+
os.makedirs(udir)
|
| 150 |
+
await cb.answer("ποΈ Storage cleared successfully!", show_alert=True)
|
| 151 |
+
await cb.message.delete()
|
| 152 |
|
| 153 |
@bot.on_callback_query(filters.regex("^close_settings$"))
|
| 154 |
async def close_settings(client, cb: CallbackQuery): await cb.message.delete()
|
|
|
|
| 160 |
bid = str(uuid.uuid4())[:8]
|
| 161 |
|
| 162 |
if mode == "unzip":
|
| 163 |
+
msg = await message.reply_text("π **Unzip Mode Active**\nββββββββββββ\nSend me the **ZIP file** you want to extract and view online.")
|
| 164 |
user_sessions[uid] = {"mode":mode, "batch_id":bid, "status_msg_id":msg.id}
|
| 165 |
return
|
| 166 |
|
| 167 |
if mode == "vcompress":
|
| 168 |
kb = InlineKeyboardMarkup([
|
| 169 |
+
[InlineKeyboardButton("π Low (480p)", callback_data="vc_q_low"), InlineKeyboardButton("π¬ Medium (720p)", callback_data="vc_q_med")],
|
| 170 |
+
[InlineKeyboardButton("β¨ High (1080p)", callback_data="vc_q_high")],
|
|
|
|
| 171 |
[InlineKeyboardButton("β Cancel", callback_data="close_settings")]
|
| 172 |
])
|
| 173 |
msg = await message.reply_text(
|
| 174 |
"π¬ **Video Compression Mode**\nββββββββββββββββββββ\n"
|
| 175 |
+
"Send the video you want to compress. Quality is set to `Medium` by default.",
|
|
|
|
| 176 |
reply_markup=kb
|
| 177 |
)
|
| 178 |
+
user_sessions[uid] = {"mode":mode, "files":[], "quality":"med", "batch_id":bid, "status_msg_id":msg.id}
|
| 179 |
return
|
| 180 |
|
| 181 |
kb = InlineKeyboardMarkup([
|
| 182 |
+
[InlineKeyboardButton("βοΈ Compression Level", callback_data="zip_lvl_cycle") if mode=="zip" else InlineKeyboardButton("π Mode: PDF Merge", callback_data="none")],
|
| 183 |
[InlineKeyboardButton("βοΈ Set Custom Name", callback_data="tool_rename")],
|
| 184 |
+
[InlineKeyboardButton("β
Process & Finish", callback_data="tool_done")]
|
| 185 |
])
|
| 186 |
msg = await message.reply_text(
|
| 187 |
+
f"π¦ **{mode.upper()} Mode Active**\nββββββββββββββββββββ\nπ **Name:** `Auto` β’ π’ **Files:** `0`\nβ¨ Send your files now...",
|
| 188 |
reply_markup=kb
|
| 189 |
)
|
| 190 |
user_sessions[uid] = {"mode":mode, "files":[], "level":5, "batch_id":bid, "status_msg_id":msg.id, "name":None}
|
|
|
|
| 193 |
async def video_quality_callback(client, cb: CallbackQuery):
|
| 194 |
uid = cb.from_user.id
|
| 195 |
if uid not in user_sessions: return
|
|
|
|
|
|
|
| 196 |
quality = cb.data.split("_")[-1]
|
| 197 |
user_sessions[uid]["quality"] = quality
|
| 198 |
+
await cb.answer(f"β
Quality set to {quality.upper()}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
@bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
|
| 201 |
async def zip_lvl_cycle(client, cb: CallbackQuery):
|
| 202 |
uid = cb.from_user.id
|
| 203 |
if uid not in user_sessions: return
|
| 204 |
+
lvls = {0: "Store", 1: "Fast", 5: "Normal", 9: "Ultra"}
|
|
|
|
|
|
|
| 205 |
curr = user_sessions[uid].get("level", 5)
|
| 206 |
+
keys = list(lvls.keys())
|
| 207 |
+
new_lvl = keys[(keys.index(curr) + 1) % len(keys)]
|
| 208 |
user_sessions[uid]["level"] = new_lvl
|
| 209 |
+
await cb.answer(f"β¨ Compression: {lvls[new_lvl]}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
@bot.on_callback_query(filters.regex("^tool_rename$"))
|
| 212 |
async def tool_rename_init(client, cb: CallbackQuery):
|
| 213 |
uid = cb.from_user.id
|
| 214 |
if uid in user_sessions:
|
| 215 |
user_sessions[uid]["renaming"] = True
|
| 216 |
+
await cb.answer("β¨οΈ Send new name as text.", show_alert=True)
|
| 217 |
|
| 218 |
@bot.on_message(filters.private & filters.text & ~filters.command(["zip", "pdf_merge", "start", "settings", "files", "help", "search", "unzip", "vcompress"]))
|
| 219 |
async def handle_text_logic(client, message: Message):
|
|
|
|
| 225 |
new_name = "".join(x for x in message.text if x.isalnum() or x in "._-").replace(" ", "_")[:50]
|
| 226 |
sess["name"] = new_name
|
| 227 |
sess["renaming"] = False
|
| 228 |
+
await message.reply_text(f"β
Name set to: `{new_name}`")
|
|
|
|
|
|
|
| 229 |
await message.delete()
|
| 230 |
|
| 231 |
elif sess.get("waiting_pass"):
|
| 232 |
pwd = message.text.strip()
|
| 233 |
if sess["target"] == "settings":
|
| 234 |
user_settings[uid]["password"] = pwd
|
| 235 |
+
await message.reply_text(f"β
Global Password set to: `{pwd}`")
|
| 236 |
del user_sessions[uid]
|
| 237 |
await message.delete()
|
| 238 |
|
|
|
|
| 240 |
async def tool_complete(client, cb: CallbackQuery):
|
| 241 |
uid = cb.from_user.id
|
| 242 |
sess = user_sessions.get(uid)
|
| 243 |
+
if not sess or not sess.get("files"): return await cb.answer("β No files provided!")
|
| 244 |
|
| 245 |
+
await cb.message.edit_text(f"β³ **Processing your request...**\nββββββββββββ\nMode: `{sess['mode'].upper()}`\nFiles: `{len(sess['files'])}`")
|
| 246 |
udir = f"user_{uid}"
|
| 247 |
ext = ".zip" if sess["mode"]=="zip" else ".pdf"
|
| 248 |
+
oname = f"{sess['name']}{ext}" if sess.get("name") else f"{sess['batch_id']}_processed{ext}"
|
| 249 |
opath = os.path.join(UPLOAD_DIR, udir, oname)
|
| 250 |
|
| 251 |
try:
|
|
|
|
| 252 |
if sess["mode"] == "zip":
|
| 253 |
lvl = sess.get("level", 5)
|
|
|
|
| 254 |
cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
|
| 255 |
+
p = await asyncio.create_subprocess_exec(*cmd, cwd=os.path.join(UPLOAD_DIR, udir), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 256 |
+
await p.communicate()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
else:
|
| 258 |
merger = PdfWriter()
|
| 259 |
for f in sess["files"]: merger.append(f)
|
| 260 |
with open(opath, "wb") as fo: merger.write(fo)
|
| 261 |
merger.close()
|
| 262 |
|
| 263 |
+
settings = user_settings.get(uid, {"password":None})
|
| 264 |
+
set_metadata(oname, {"password": settings["password"]})
|
| 265 |
+
set_metadata(sess["batch_id"], {"password": settings["password"]})
|
|
|
|
| 266 |
|
| 267 |
durl = f"{BASE_URL}/download/{udir}/{oname}"
|
| 268 |
+
vurl = f"{BASE_URL}/view/{udir}/{sess['batch_id']}"
|
|
|
|
| 269 |
|
| 270 |
await cb.message.edit_text(
|
| 271 |
+
f"β
**Processing Finished!**\nββββββββββββ\n"
|
| 272 |
+
f"π **File:** `{oname}`\n\n"
|
| 273 |
+
f"π₯ [Direct Download]({durl})\n"
|
| 274 |
+
f"π [Web Dashboard]({vurl})\n\n"
|
| 275 |
+
f"π‘οΈ **Security:** `{'Locked π' if settings['password'] else 'Public π'}`",
|
| 276 |
disable_web_page_preview=True
|
| 277 |
)
|
| 278 |
del user_sessions[uid]
|
| 279 |
+
except Exception as e: await cb.message.edit_text(f"β **Error:** `{e}`")
|
| 280 |
|
| 281 |
@bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.photo))
|
| 282 |
async def handle_uploads(client, message: Message):
|
|
|
|
| 289 |
udir = os.path.join(UPLOAD_DIR, f"user_{uid}")
|
| 290 |
os.makedirs(udir, exist_ok=True)
|
| 291 |
|
| 292 |
+
# Sanitize name
|
| 293 |
+
raw_fname = getattr(media, 'file_name', f"file_{int(time.time())}")
|
| 294 |
+
fname = os.path.basename(raw_fname).replace(" ", "_")
|
| 295 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
is_tool = uid in user_sessions
|
| 297 |
sname = f"{user_sessions[uid]['batch_id'] if is_tool else str(uuid.uuid4())[:4]}_{fname}"
|
|
|
|
|
|
|
| 298 |
fpath = os.path.join(udir, sname)
|
| 299 |
+
|
| 300 |
status = await message.reply_text("π₯ **Initializing...**", quote=True)
|
| 301 |
start = time.time()
|
| 302 |
ledit = 0
|
|
|
|
| 305 |
nonlocal ledit
|
| 306 |
if time.time() - ledit > 4:
|
| 307 |
try:
|
| 308 |
+
await status.edit_text(f"π₯ **Uploading:** `{fname}`\nββββββββββββ\n{get_progress_bar(c, t, start)}")
|
| 309 |
ledit = time.time()
|
| 310 |
except: pass
|
| 311 |
|
| 312 |
try:
|
| 313 |
await client.download_media(message, file_name=fpath, progress=progress)
|
| 314 |
+
|
|
|
|
|
|
|
| 315 |
if is_tool:
|
| 316 |
if user_sessions[uid]["mode"] == "unzip":
|
| 317 |
+
await status.edit_text("π **Extracting...**")
|
| 318 |
bid = user_sessions[uid]["batch_id"]
|
| 319 |
extract_dir = os.path.join(udir, bid)
|
| 320 |
os.makedirs(extract_dir, exist_ok=True)
|
|
|
|
|
|
|
| 321 |
cmd = ["7z", "x", fpath, f"-o{extract_dir}", "-y"]
|
| 322 |
settings = user_settings.get(uid, {"password":None})
|
| 323 |
+
if settings["password"]: cmd.append(f"-p{settings['password']}")
|
| 324 |
+
p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 325 |
+
await p.communicate()
|
| 326 |
+
|
| 327 |
+
count = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
for root, dirs, files in os.walk(extract_dir):
|
| 329 |
for f in files:
|
| 330 |
+
count += 1
|
| 331 |
+
os.rename(os.path.join(root, f), os.path.join(udir, f"{bid}_{count:03d}_{f.replace(' ','_')}"))
|
| 332 |
+
|
| 333 |
+
try: shutil.rmtree(extract_dir); os.remove(fpath)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
except: pass
|
| 335 |
+
|
| 336 |
+
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}")]]) )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
del user_sessions[uid]
|
| 338 |
return
|
| 339 |
|
| 340 |
if user_sessions[uid]["mode"] == "vcompress":
|
| 341 |
+
await status.edit_text("β³ **Compressing Video...**\n*This may take several minutes.*")
|
| 342 |
quality = user_sessions[uid].get("quality", "med")
|
| 343 |
+
q_s = {"low": ["-vf", "scale=-2:480", "-crf", "28"], "med": ["-vf", "scale=-2:720", "-crf", "24"], "high": ["-vf", "scale=-2:1080", "-crf", "22"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
opath = fpath.rsplit(".", 1)[0] + "_compressed.mp4"
|
| 345 |
+
cmd = ["ffmpeg", "-i", fpath] + q_s.get(quality, q_s["med"]) + ["-c:v", "libx264", "-preset", "faster", "-c:a", "aac", "-b:a", "128k", opath, "-y"]
|
| 346 |
+
p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
| 347 |
+
await p.communicate()
|
| 348 |
|
|
|
|
| 349 |
if os.path.exists(opath):
|
| 350 |
+
saved = 100 - (os.path.getsize(opath)*100/os.path.getsize(fpath))
|
| 351 |
+
os.remove(fpath)
|
|
|
|
|
|
|
| 352 |
fpath = opath
|
| 353 |
+
await status.edit_text(f"β
**Compressed!**\nπ Saved: `{saved:.1f}%`\n\nπ₯ [Download]({BASE_URL}/download/user_{uid}/{os.path.basename(opath)})", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("π₯ Download", url=f"{BASE_URL}/download/user_{uid}/{os.path.basename(opath)}")]]) )
|
| 354 |
+
else: await status.edit_text("β Compression failed.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
del user_sessions[uid]
|
| 356 |
return
|
| 357 |
|
| 358 |
user_sessions[uid]["files"].append(fpath)
|
|
|
|
|
|
|
|
|
|
| 359 |
await status.delete()
|
| 360 |
+
try: await client.edit_message_text(uid, user_sessions[uid]["status_msg_id"], f"π¦ **{user_sessions[uid]['mode'].upper()} Active**\nββββββββββββ\nπ Added: `{fname}`\nπ’ Total: `{len(user_sessions[uid]['files'])}`", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("βοΈ Rename", callback_data="tool_rename")],[InlineKeyboardButton("β
Done", callback_data="tool_done")]]))
|
| 361 |
+
except: pass
|
| 362 |
+
else:
|
| 363 |
+
settings = user_settings.get(uid, {"password":None})
|
| 364 |
+
set_metadata(os.path.basename(fpath), {"password": settings["password"]})
|
| 365 |
+
durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
|
| 366 |
+
kb = InlineKeyboardMarkup([[InlineKeyboardButton("π₯ Download", url=durl)]])
|
| 367 |
+
if fname.lower().endswith(('.mp4', '.mkv', '.webm')):
|
| 368 |
+
kb.add(InlineKeyboardButton("π¬ Watch Online", url=f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}"))
|
| 369 |
+
await status.edit_text(f"β
**Upload Success!**\n`{fname}`\n\nπ‘οΈ Pass: `{'Yes' if settings['password'] else 'No'}`", reply_markup=kb)
|
|
|
|
| 370 |
except Exception as e: await status.edit_text(f"β Error: {e}")
|