Gemini CLI commited on
Commit
9885cf3
Β·
1 Parent(s): afb618b

fix: web upload, terminal upload and bot ui polish

Browse files
Files changed (2) hide show
  1. app.py +36 -5
  2. bot.py +156 -221
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
- return f"{BASE_URL}/download/user_{user_id}/{safe_name}"
 
 
 
 
300
 
301
  # Multipart Upload
302
  target = (files or []) + ([file] if file else [])
303
- if not target: raise HTTPException(status_code=400, detail="No files provided.")
 
 
 
 
 
 
 
 
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[0] if len(target) == 1 and not x_user_id else {"urls": 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 File Multi-Tool Professional ---")
13
 
14
  # Session management
15
- user_sessions = {} # {uid: {"mode": "zip", "files": [], "name": "custom", "renaming": False, "waiting_pass": False, ...}}
16
- user_settings = {} # {uid: {"auto_delete": 24, "self_destruct": False, "password": None}}
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
- # Validate credentials
35
- _missing = [k for k, v in {"API_ID": API_ID, "API_HASH": API_HASH, "BOT_TOKEN": BOT_TOKEN}.items() if not v]
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
- "πŸ› οΈ **File Multi-Tool Professional**\n\n"
46
- "The most advanced file management bot. Process PDFs, create ZIPs, and host files with high-speed links.\n\n"
47
- "**Main Commands:**\n"
48
- "πŸ“¦ /zip - Create compressed ZIP\n"
49
- "πŸ”“ /unzip - Extract ZIP files\n"
50
- "πŸ“„ /pdf_merge - Combine PDF files\n"
51
- "🎬 /vcompress - Reduce video size\n"
52
- "πŸ” /search - Search your uploads\n"
53
- "πŸ“‚ /files - View storage\n"
54
- "βš™οΈ /settings - Bot preferences\n"
55
- "πŸ“– /help - Usage guide"
 
 
 
56
  )
57
 
58
- @bot.on_message(filters.command("help") & filters.private)
59
- async def help_cmd(client, message: Message):
60
- await message.reply_text(
61
- "πŸ“– **Usage Guide:**\n\n"
62
- "1️⃣ **Hosting:** Send any file for a high-speed link.\n"
63
- "2️⃣ **ZIP/PDF:** Run /zip or /pdf_merge, send files, then click Done.\n"
64
- "3️⃣ **Unzip:** Run /unzip and send a ZIP file to view its contents online.\n"
65
- "4️⃣ **Naming:** Click 'Set Custom Name' during a session.\n"
66
- "5️⃣ **Security:** Use /settings to enable **Self-Destruct** or **Passwords**.\n"
67
- "6️⃣ **Search:** Use /search <keyword> to find your files."
 
 
 
 
 
 
 
 
 
 
68
  )
69
 
70
- @bot.on_message(filters.command("search") & filters.private)
71
- async def search_cmd(client, message: Message):
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): return await message.reply_text("No files found.")
 
78
 
79
- results = [f for f in os.listdir(udir) if query in f.lower()]
80
- if not results: return await message.reply_text(f"No results for '{query}'.")
 
 
 
 
81
 
82
- text = f"πŸ” **Search Results for '{query}':**\n\n"
83
- for r in results[:10]:
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, "self_destruct": False, "password": None})
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"πŸ’₯ Self-Destruct: {'ON' if s['self_destruct'] else 'OFF'}", callback_data="set_sd_toggle")],
96
- [InlineKeyboardButton(f"πŸ” Password: {'Set' if s['password'] else 'None'}", callback_data="set_pass_init")],
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, "self_destruct": False, "password": None})
105
 
106
  if cb.data == "set_del_cycle":
107
  opts = [1, 6, 12, 24, 48]
108
- s["auto_delete"] = opts[(opts.index(s["auto_delete"]) + 1) % len(opts)]
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"πŸ’₯ Self-Destruct: {'ON' if s['self_destruct'] else 'OFF'}", callback_data="set_sd_toggle")],
119
- [InlineKeyboardButton(f"πŸ” Password: {'Set' if s['password'] else 'None'}", callback_data="set_pass_init")],
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("πŸ“‰ Quality: Low (480p)", callback_data="vc_q_low")],
141
- [InlineKeyboardButton("🎬 Quality: Medium (720p)", callback_data="vc_q_med")],
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 me the video you want to compress.\n\n"
148
- "**Selected Quality:** `Medium (720p)`",
149
  reply_markup=kb
150
  )
151
- user_sessions[uid] = {"mode":mode, "files":[], "quality":"medium", "batch_id":bid, "status_msg_id":msg.id}
152
  return
153
 
154
  kb = InlineKeyboardMarkup([
155
- [InlineKeyboardButton("βš™οΈ Level: Normal" if mode=="zip" else "πŸ“„ PDF Info", callback_data="zip_lvl_cycle" if mode=="zip" else "pdf_info")],
156
  [InlineKeyboardButton("✏️ Set Custom Name", callback_data="tool_rename")],
157
- [InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]
158
  ])
159
  msg = await message.reply_text(
160
- f"πŸ“¦ **{mode.upper()} Mode Active**\n━━━━━━━━━━━━━━━━━━━━\nπŸ“‚ **Name:** `Auto-generated`\nπŸ”’ **Files:** 0\nπŸ“‰ **Status:** Waiting...",
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
- new_lvl = lvls_list[(lvls_list.index(curr) + 1) % len(lvls_list)]
 
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
- try:
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"βœ… Default Password set to: `{pwd}`")
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["files"]: return await cb.answer("No files!")
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']}_merged{ext}"
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
- process = await asyncio.create_subprocess_exec(
259
- *cmd,
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
- # Apply Metadata (Password/Self-Destruct from Settings)
274
- settings = user_settings.get(uid, {"auto_delete":24, "self_destruct":False, "password":None})
275
- set_metadata(oname, {"password": settings["password"], "self_destruct": settings["self_destruct"]})
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}/{oname.split('_')[0] if '_' in oname else sess['batch_id']}"
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"βœ… **{sess['mode'].upper()} Ready!**\n━━━━━━━━━━━━\nπŸ“‚ **Name:** `{oname}`\n"
284
- f"πŸ“₯ [Direct Link]({durl})\n🌐 [Web View]({vurl})\n\n"
285
- f"πŸ“Š Saved: {saved:.1f}% | πŸ›‘οΈ Pass: {'Yes' if settings['password'] else 'No'}",
 
 
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
- # Name Logic
303
- caption = message.caption
304
- if caption:
305
- cname = "".join(x for x in caption if x.isalnum() or x in "._-").replace(" ", "")[:40]
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"πŸ“₯ **Downloading:** `{fname}`\n━━━━━━━━━━━━\n{get_progress_bar(c, t, start)}")
325
  ledit = time.time()
326
  except: pass
327
 
328
  try:
329
  await client.download_media(message, file_name=fpath, progress=progress)
330
- try: await message.delete()
331
- except: pass
332
-
333
  if is_tool:
334
  if user_sessions[uid]["mode"] == "unzip":
335
- await status.edit_text("πŸ”“ **Extracting ZIP...**")
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
- cmd.append(f"-p{settings['password']}")
345
-
346
- process = await asyncio.create_subprocess_exec(
347
- *cmd,
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
- extracted_count += 1
365
- safe_f = "".join(x for x in f if x.isalnum() or x in "._-").replace(" ", "_")
366
- new_name = f"{bid}_{extracted_count:03d}_{safe_f}"
367
- os.rename(os.path.join(root, f), os.path.join(udir, new_name))
368
-
369
- try:
370
- shutil.rmtree(extract_dir)
371
- os.remove(fpath)
372
  except: pass
373
-
374
- vurl = f"{BASE_URL}/view/user_{uid}/{bid}"
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...**\nThis may take a while depending on size.")
386
  quality = user_sessions[uid].get("quality", "med")
387
- q_settings = {
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] + q_settings.get(quality, q_settings["med"]) + ["-c:a", "aac", "-b:a", "128k", opath, "-y"]
394
- process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
395
- await process.communicate()
396
 
397
- orig_size = os.path.getsize(fpath)
398
  if os.path.exists(opath):
399
- comp_size = os.path.getsize(opath)
400
- try: os.remove(fpath)
401
- except: pass
402
- sname = os.path.basename(opath)
403
  fpath = opath
404
- fname = sname
405
- saved = 100 - (comp_size * 100 / orig_size) if orig_size > 0 else 0
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
- return
425
-
426
- # Normal upload
427
- settings = user_settings.get(uid, {"auto_delete":24, "self_destruct":False, "password":None})
428
- set_metadata(sname, {"password": settings["password"], "self_destruct": settings["self_destruct"]})
429
- durl = f"{BASE_URL}/download/user_{uid}/{sname}"
430
- purl = f"{BASE_URL}/player/user_{uid}/{sname}"
431
- kb = InlineKeyboardMarkup([[InlineKeyboardButton("πŸ“₯ Download", url=durl)]])
432
- if fname.lower().endswith(('.mp4', '.mkv', '.webm')):
433
- kb = InlineKeyboardMarkup([[InlineKeyboardButton("πŸ“₯ Download", url=durl), InlineKeyboardButton("🎬 Watch Online", url=purl)]])
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}")