nikhilyadavtemp1 commited on
Commit
45689cf
Β·
1 Parent(s): bcf954e

fix: sequential processing per user and add web view for zip batches

Browse files
Files changed (2) hide show
  1. app.py +56 -1
  2. bot.py +78 -64
app.py CHANGED
@@ -6,7 +6,7 @@ import asyncio
6
  from contextlib import asynccontextmanager
7
  from typing import List, Optional
8
  from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request
9
- from fastapi.responses import FileResponse, JSONResponse
10
  from fastapi.staticfiles import StaticFiles
11
  from config import UPLOAD_DIR, BASE_URL
12
 
@@ -169,6 +169,61 @@ async def upload_files(
169
 
170
  return urls[0] if len(target) == 1 and not x_user_id else {"urls": urls}
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  @app.get("/files")
173
  async def list_api_files(x_user_id: str = Header(None)):
174
  if not x_user_id:
 
6
  from contextlib import asynccontextmanager
7
  from typing import List, Optional
8
  from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request
9
+ from fastapi.responses import FileResponse, JSONResponse, HTMLResponse
10
  from fastapi.staticfiles import StaticFiles
11
  from config import UPLOAD_DIR, BASE_URL
12
 
 
169
 
170
  return urls[0] if len(target) == 1 and not x_user_id else {"urls": urls}
171
 
172
+ @app.get("/view/{user_id}/{batch_id}")
173
+ async def view_batch(user_id: str, batch_id: str):
174
+ user_dir = os.path.join(UPLOAD_DIR, user_id)
175
+ if not os.path.exists(user_dir):
176
+ raise HTTPException(status_code=404, detail="Batch not found.")
177
+
178
+ files_data = []
179
+ for f in os.listdir(user_dir):
180
+ if f.startswith(f"{batch_id}_") and not f.endswith(".zip"):
181
+ fpath = os.path.join(user_dir, f)
182
+ files_data.append({
183
+ "name": "_".join(f.split("_")[2:]), # Skip batch_id and numbering
184
+ "url": f"/download/{user_id}/{f}",
185
+ "size": round(os.path.getsize(fpath) / 1024 / 1024, 2),
186
+ "raw_name": f
187
+ })
188
+
189
+ if not files_data:
190
+ raise HTTPException(status_code=404, detail="No files found in this batch.")
191
+
192
+ # Sort files by their raw name (which includes the 001_ prefix) to maintain order
193
+ files_data.sort(key=lambda x: x["raw_name"])
194
+
195
+ files_html = "".join([
196
+ f'<div class="file-card"><span class="file-name">{f["name"]} ({f["size"]} MB)</span><a class="btn" href="{f["url"]}">Download</a></div>'
197
+ for f in files_data
198
+ ])
199
+
200
+ html_content = f"""
201
+ <html>
202
+ <head>
203
+ <title>Batch View - {batch_id}</title>
204
+ <meta name="viewport" content="width=device-width, initial-scale=1">
205
+ <style>
206
+ body {{ font-family: sans-serif; background: #121212; color: white; padding: 20px; }}
207
+ .container {{ max-width: 800px; margin: auto; }}
208
+ .file-card {{ background: #1e1e1e; padding: 15px; margin-bottom: 10px; border-radius: 8px; display: flex; justify-content: space-between; align-items: center; }}
209
+ .file-name {{ font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 70%; }}
210
+ .btn {{ background: #2196F3; color: white; text-decoration: none; padding: 8px 15px; border-radius: 4px; font-size: 14px; }}
211
+ h2 {{ color: #2196F3; }}
212
+ </style>
213
+ </head>
214
+ <body>
215
+ <div class="container">
216
+ <h2>πŸ“¦ Batch: {batch_id}</h2>
217
+ <p>Individual files in this ZIP archive:</p>
218
+ {files_html}
219
+ <br>
220
+ <a href="/" style="color: #888; text-decoration: none;">← Back to Home</a>
221
+ </div>
222
+ </body>
223
+ </html>
224
+ """
225
+ return HTMLResponse(content=html_content)
226
+
227
  @app.get("/files")
228
  async def list_api_files(x_user_id: str = Header(None)):
229
  if not x_user_id:
bot.py CHANGED
@@ -13,6 +13,7 @@ print("--- Initializing File Multi-Tool Bot ---")
13
  # Session management: user_id -> {"mode": "zip"/"pdf", "files": [], "zip_level": int, "auto_delete": int}
14
  user_sessions = {}
15
  user_settings = {} # user_id -> {"auto_delete": 24}
 
16
 
17
  # Validate credentials
18
  _missing = [k for k, v in {"API_ID": API_ID, "API_HASH": API_HASH, "BOT_TOKEN": BOT_TOKEN}.items() if not v]
@@ -61,12 +62,13 @@ else:
61
  @bot.on_message(filters.command("zip") & filters.private)
62
  async def zip_init(client, message: Message):
63
  user_id = message.from_user.id
64
- user_sessions[user_id] = {"mode": "zip", "files": [], "level": zipfile.ZIP_DEFLATED}
 
65
  kb = InlineKeyboardMarkup([
66
  [InlineKeyboardButton("Compression: Deflate (Normal)", callback_data="zip_lvl_cycle")],
67
  [InlineKeyboardButton("βœ… Done / Create ZIP", callback_data="tool_done")]
68
  ])
69
- await message.reply_text("πŸ“¦ **ZIP Mode Enabled**\nSend files to add. Change compression below if needed.", reply_markup=kb)
70
 
71
  @bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
72
  async def cycle_zip_level(client, callback_query: CallbackQuery):
@@ -109,12 +111,13 @@ else:
109
 
110
  sess = user_sessions[user_id]
111
  mode = sess["mode"]
 
112
  await callback_query.message.edit_text(f"⏳ **Processing {mode.upper()}...**")
113
 
114
- tg_id = f"tg{user_id}"
115
  ext = ".zip" if mode == "zip" else ".pdf"
116
- out_name = f"{tg_id}_{str(uuid.uuid4())[:8]}_multi_{mode}_{int(time.time())}{ext}"
117
- out_path = os.path.join(UPLOAD_DIR, out_name)
118
 
119
  try:
120
  if mode == "zip":
@@ -129,13 +132,21 @@ else:
129
  merger.write(f_out)
130
  merger.close()
131
 
132
- download_url = f"{BASE_URL}/download/{out_name}"
133
- await callback_query.message.edit_text(
134
- f"βœ… **Success! {mode.upper()} Created**\n\n"
135
- f"πŸ”— **Link:** `{download_url}`\n"
136
- f"⚠️ _Valid for {user_settings.get(user_id, {'auto_delete': 24})['auto_delete']} hours._",
137
- disable_web_page_preview=True
138
- )
 
 
 
 
 
 
 
 
139
  del user_sessions[user_id]
140
  except Exception as e:
141
  await callback_query.message.edit_text(f"❌ **Failed:** {str(e)}")
@@ -170,57 +181,60 @@ else:
170
  @bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.photo))
171
  async def handle_uploads(client, message: Message):
172
  uid = message.from_user.id
173
- media = message.document or message.video or message.audio or message.photo
174
- if isinstance(media, list): media = media[-1]
175
-
176
- # 1. Create User-Specific Folder
177
- user_dir = os.path.join(UPLOAD_DIR, f"user_{uid}")
178
- os.makedirs(user_dir, exist_ok=True)
179
-
180
- # 2. Advanced Filename Logic (Caption-based + Sanitization)
181
- caption = message.caption
182
- if caption:
183
- # Remove spaces, take first 30 chars, and clean special chars
184
- clean_name = "".join(x for x in caption if x.isalnum() or x in "._-")[:30]
185
- # Keep extension if original had one
186
- orig_name = getattr(media, 'file_name', "")
187
- ext = os.path.splitext(orig_name)[1] if orig_name else (".jpg" if message.photo else "")
188
- file_name = f"{clean_name}{ext}"
189
- else:
190
- file_name = os.path.basename(getattr(media, 'file_name', f"img_{int(time.time())}.jpg" if message.photo else f"file_{int(time.time())}"))
191
-
192
- # 3. Handle Ordering for ZIP/PDF sessions
193
- if uid in user_sessions:
194
- # Add numbering prefix to preserve order in the archive
195
- count = len(user_sessions[uid]["files"]) + 1
196
- file_name = f"{count:03d}_{file_name}"
197
-
198
- # Final Unique Save Name to avoid collisions in the user folder
199
- unique_id = str(uuid.uuid4())[:4]
200
- save_name = f"{unique_id}_{file_name}"
201
- fpath = os.path.abspath(os.path.join(user_dir, save_name))
202
-
203
- # Check PDF mode restriction
204
- if uid in user_sessions and user_sessions[uid]["mode"] == "pdf":
205
- if not message.document or not file_name.lower().endswith(".pdf"):
206
- return await message.reply_text("❌ Please send PDF documents only.")
207
-
208
- status = await message.reply_text("πŸ“₯ **Downloading...**", quote=True)
209
- try:
210
- await client.download_media(message, file_name=fpath)
211
-
212
- # The URL needs to include the user folder for the FastAPI route to find it
213
- # We'll use a slash or a separator that app.py can understand
214
- web_path = f"user_{uid}/{save_name}"
215
-
216
  if uid in user_sessions:
217
- user_sessions[uid]["files"].append(fpath)
218
- await status.edit_text(
219
- f"βœ… **Added to {user_sessions[uid]['mode'].upper()}!**\n"
220
- f"πŸ“‚ `{file_name}`\nπŸ”’ Files: {len(user_sessions[uid]['files'])}",
221
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]])
222
- )
223
  else:
224
- await status.edit_text(f"βœ… **Upload Success!**\n\n`{BASE_URL}/download/{web_path}`", disable_web_page_preview=True)
225
- except Exception as e:
226
- await status.edit_text(f"❌ **Failed:** {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  # Session management: user_id -> {"mode": "zip"/"pdf", "files": [], "zip_level": int, "auto_delete": int}
14
  user_sessions = {}
15
  user_settings = {} # user_id -> {"auto_delete": 24}
16
+ user_locks = {} # user_id -> asyncio.Lock()
17
 
18
  # Validate credentials
19
  _missing = [k for k, v in {"API_ID": API_ID, "API_HASH": API_HASH, "BOT_TOKEN": BOT_TOKEN}.items() if not v]
 
62
  @bot.on_message(filters.command("zip") & filters.private)
63
  async def zip_init(client, message: Message):
64
  user_id = message.from_user.id
65
+ batch_id = str(uuid.uuid4())[:8]
66
+ user_sessions[user_id] = {"mode": "zip", "files": [], "level": zipfile.ZIP_DEFLATED, "batch_id": batch_id}
67
  kb = InlineKeyboardMarkup([
68
  [InlineKeyboardButton("Compression: Deflate (Normal)", callback_data="zip_lvl_cycle")],
69
  [InlineKeyboardButton("βœ… Done / Create ZIP", callback_data="tool_done")]
70
  ])
71
+ await message.reply_text("πŸ“¦ **ZIP Mode Enabled**\nSend files to add. They will be processed sequentially.", reply_markup=kb)
72
 
73
  @bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
74
  async def cycle_zip_level(client, callback_query: CallbackQuery):
 
111
 
112
  sess = user_sessions[user_id]
113
  mode = sess["mode"]
114
+ batch_id = sess.get("batch_id", "default")
115
  await callback_query.message.edit_text(f"⏳ **Processing {mode.upper()}...**")
116
 
117
+ tg_id = f"user_{user_id}"
118
  ext = ".zip" if mode == "zip" else ".pdf"
119
+ out_name = f"{batch_id}_merged{ext}"
120
+ out_path = os.path.join(UPLOAD_DIR, tg_id, out_name)
121
 
122
  try:
123
  if mode == "zip":
 
132
  merger.write(f_out)
133
  merger.close()
134
 
135
+ web_path = f"{tg_id}/{out_name}"
136
+ direct_url = f"{BASE_URL}/download/{web_path}"
137
+ view_url = f"{BASE_URL}/view/{tg_id}/{batch_id}"
138
+
139
+ if mode == "zip":
140
+ msg = (
141
+ f"βœ… **ZIP Archive Created!**\n\n"
142
+ f"πŸ“₯ **Direct Download:**\n`{direct_url}`\n\n"
143
+ f"🌐 **Web View (Individual Files):**\n`{view_url}`\n\n"
144
+ f"πŸ“¦ **Contains:** {len(sess['files'])} files"
145
+ )
146
+ else:
147
+ msg = f"βœ… **PDF Merged!**\n\nπŸ”— **Link:** `{direct_url}`"
148
+
149
+ await callback_query.message.edit_text(msg, disable_web_page_preview=True)
150
  del user_sessions[user_id]
151
  except Exception as e:
152
  await callback_query.message.edit_text(f"❌ **Failed:** {str(e)}")
 
181
  @bot.on_message(filters.private & (filters.document | filters.video | filters.audio | filters.photo))
182
  async def handle_uploads(client, message: Message):
183
  uid = message.from_user.id
184
+
185
+ # Sequential Processing Lock
186
+ if uid not in user_locks:
187
+ user_locks[uid] = asyncio.Lock()
188
+
189
+ async with user_locks[uid]:
190
+ media = message.document or message.video or message.audio or message.photo
191
+ if isinstance(media, list): media = media[-1]
192
+
193
+ user_dir = os.path.join(UPLOAD_DIR, f"user_{uid}")
194
+ os.makedirs(user_dir, exist_ok=True)
195
+
196
+ # Caption Handling & Sanitization (remove spaces)
197
+ caption = message.caption
198
+ if caption:
199
+ # Remove spaces and sanitize
200
+ clean_name = "".join(x for x in caption if x.isalnum() or x in "._-").replace(" ", "")[:40]
201
+ orig_name = getattr(media, 'file_name', "")
202
+ ext = os.path.splitext(orig_name)[1] if orig_name else (".jpg" if message.photo else "")
203
+ file_name = f"{clean_name}{ext}"
204
+ else:
205
+ file_name = os.path.basename(getattr(media, 'file_name', f"img_{int(time.time())}.jpg" if message.photo else f"file_{int(time.time())}"))
206
+
207
+ # Ordering Prefix
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  if uid in user_sessions:
209
+ count = len(user_sessions[uid]["files"]) + 1
210
+ file_name = f"{count:03d}_{file_name}"
211
+ batch_id = user_sessions[uid]["batch_id"]
212
+ # Group files by batch_id in the filename for the View page
213
+ save_name = f"{batch_id}_{file_name}"
 
214
  else:
215
+ save_name = f"{str(uuid.uuid4())[:4]}_{file_name}"
216
+
217
+ fpath = os.path.abspath(os.path.join(user_dir, save_name))
218
+
219
+ # Check PDF mode restriction
220
+ if uid in user_sessions and user_sessions[uid]["mode"] == "pdf":
221
+ if not message.document or not file_name.lower().endswith(".pdf"):
222
+ return await message.reply_text("❌ Please send PDF documents only.")
223
+
224
+ status = await message.reply_text("πŸ“₯ **Waiting in queue...**" if user_locks[uid].locked() else "πŸ“₯ **Downloading...**", quote=True)
225
+ try:
226
+ if user_locks[uid].locked(): await status.edit_text("πŸ“₯ **Downloading and Sequencing...**")
227
+ await client.download_media(message, file_name=fpath)
228
+
229
+ web_path = f"user_{uid}/{save_name}"
230
+
231
+ if uid in user_sessions:
232
+ user_sessions[uid]["files"].append(fpath)
233
+ await status.edit_text(
234
+ f"βœ… **Added ({len(user_sessions[uid]['files'])}):** `{file_name}`",
235
+ reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]])
236
+ )
237
+ else:
238
+ await status.edit_text(f"βœ… **Upload Success!**\n\n`{BASE_URL}/download/{web_path}`", disable_web_page_preview=True)
239
+ except Exception as e:
240
+ await status.edit_text(f"❌ **Failed:** {str(e)}")