nvd commited on
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -205,12 +205,6 @@ def compress_to_zip(file_path: str, original_filename: str, zip_path: str):
|
|
| 205 |
zf.write(file_path, arcname=original_filename)
|
| 206 |
logger.info(f"π¦ Compressed to ZIP: {zip_path}")
|
| 207 |
|
| 208 |
-
def compress_chunk_to_zip(chunk_path: str, arcname: str, zip_path: str):
|
| 209 |
-
"""Wrap a binary chunk into a ZIP with the given arcname."""
|
| 210 |
-
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 211 |
-
zf.write(chunk_path, arcname=arcname)
|
| 212 |
-
logger.info(f"π¦ Chunk zipped: {zip_path}")
|
| 213 |
-
|
| 214 |
# ---------- File splitting ----------
|
| 215 |
CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB per chunk
|
| 216 |
|
|
@@ -218,7 +212,7 @@ def split_file(source_path: str, base_name: str, parts_dir: str):
|
|
| 218 |
"""
|
| 219 |
Splits a file into chunks.
|
| 220 |
Yields (chunk_path, part_number, total_parts).
|
| 221 |
-
chunk_path is the raw binary chunk
|
| 222 |
"""
|
| 223 |
file_size = os.path.getsize(source_path)
|
| 224 |
total_parts = math.ceil(file_size / CHUNK_SIZE)
|
|
@@ -330,86 +324,74 @@ async def handle_callback(callback: dict):
|
|
| 330 |
size_mb = file_size / (1024 * 1024)
|
| 331 |
logger.info(f"β
Downloaded: {size_mb:.2f} MB")
|
| 332 |
|
| 333 |
-
if
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
if status_message_id:
|
| 338 |
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 339 |
|
| 340 |
-
# Prepare a safe base name for the ZIP files (avoid .apk in ZIP name)
|
| 341 |
-
if original_filename.lower().endswith('.apk'):
|
| 342 |
-
safe_base = original_filename[:-4] # remove .apk
|
| 343 |
-
else:
|
| 344 |
-
safe_base = original_filename
|
| 345 |
-
|
| 346 |
with tempfile.TemporaryDirectory() as parts_dir:
|
| 347 |
-
total_parts = math.ceil(
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
zip_name = f"{safe_base}.part{part_num}.zip"
|
| 351 |
-
zip_path = os.path.join(parts_dir, zip_name)
|
| 352 |
-
# The arcname inside the ZIP should be something like "original.apk.part1"
|
| 353 |
-
arcname = f"{original_filename}.part{part_num}"
|
| 354 |
-
compress_chunk_to_zip(chunk_path, arcname, zip_path)
|
| 355 |
-
|
| 356 |
caption = (
|
| 357 |
-
f"π¦ Part {part_num}/{total}
|
| 358 |
f"Original file: `{original_filename}`\n\n"
|
| 359 |
"After downloading all parts:\n"
|
| 360 |
-
"1.
|
| 361 |
-
f"
|
| 362 |
-
f"
|
| 363 |
-
|
| 364 |
)
|
| 365 |
-
result = await send_document_file(chat_id,
|
| 366 |
caption=caption,
|
| 367 |
-
display_filename=
|
| 368 |
if not result.get("ok"):
|
| 369 |
await send_message(chat_id, f"β Failed to send part {part_num}. Error: {result.get('description')}")
|
| 370 |
-
break
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
pass
|
| 380 |
-
|
| 381 |
-
await answer_callback(callback_id, "All parts sent." if file_size > CHUNK_SIZE else "Part sent.")
|
| 382 |
|
| 383 |
else:
|
| 384 |
-
# Small
|
| 385 |
if status_message_id:
|
| 386 |
await bale_request("editMessageText", {
|
| 387 |
"chat_id": chat_id,
|
| 388 |
"message_id": status_message_id,
|
| 389 |
-
"text": f"π₯ Downloaded {
|
| 390 |
})
|
| 391 |
else:
|
| 392 |
-
await send_message(chat_id, f"π₯ Downloaded {
|
| 393 |
-
|
| 394 |
-
need_compress = not is_compressed(original_filename)
|
| 395 |
-
if need_compress:
|
| 396 |
-
zip_filename = original_filename + ".zip"
|
| 397 |
-
caption = f"π¦ File compressed to ZIP for delivery.\nOriginal: `{original_filename}`"
|
| 398 |
-
await send_message(chat_id, "π¦ Compressing file into ZIP...")
|
| 399 |
-
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 400 |
-
zip_path = zip_tmp.name
|
| 401 |
-
zip_tmp.close()
|
| 402 |
-
compress_to_zip(tmp_path, original_filename, zip_path)
|
| 403 |
-
os.unlink(tmp_path) # remove original
|
| 404 |
-
upload_path = zip_path
|
| 405 |
-
upload_filename = zip_filename
|
| 406 |
-
else:
|
| 407 |
-
upload_path = tmp_path
|
| 408 |
-
upload_filename = original_filename
|
| 409 |
-
caption = "Here you go!"
|
| 410 |
|
| 411 |
-
result = await send_document_file(chat_id,
|
| 412 |
-
caption=
|
| 413 |
display_filename=upload_filename)
|
| 414 |
if result.get("ok"):
|
| 415 |
if status_message_id:
|
|
@@ -419,17 +401,13 @@ async def handle_callback(callback: dict):
|
|
| 419 |
raw_error = result.get("description", str(result))
|
| 420 |
await send_message(chat_id, f"β Upload failed. Bale response:\n{raw_error}")
|
| 421 |
await answer_callback(callback_id, "Failed to send.")
|
| 422 |
-
# Clean up temp files
|
| 423 |
-
try:
|
| 424 |
-
os.unlink(upload_path)
|
| 425 |
-
except:
|
| 426 |
-
pass
|
| 427 |
|
| 428 |
except Exception as e:
|
| 429 |
logger.error(f"β Download/Upload error: {e}", exc_info=True)
|
| 430 |
await send_message(chat_id, f"β Error: {e}")
|
| 431 |
await answer_callback(callback_id, "Failed.")
|
| 432 |
finally:
|
|
|
|
| 433 |
if os.path.exists(tmp_path):
|
| 434 |
try:
|
| 435 |
os.unlink(tmp_path)
|
|
|
|
| 205 |
zf.write(file_path, arcname=original_filename)
|
| 206 |
logger.info(f"π¦ Compressed to ZIP: {zip_path}")
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
# ---------- File splitting ----------
|
| 209 |
CHUNK_SIZE = 19 * 1024 * 1024 # 19 MB per chunk
|
| 210 |
|
|
|
|
| 212 |
"""
|
| 213 |
Splits a file into chunks.
|
| 214 |
Yields (chunk_path, part_number, total_parts).
|
| 215 |
+
chunk_path is the raw binary chunk.
|
| 216 |
"""
|
| 217 |
file_size = os.path.getsize(source_path)
|
| 218 |
total_parts = math.ceil(file_size / CHUNK_SIZE)
|
|
|
|
| 324 |
size_mb = file_size / (1024 * 1024)
|
| 325 |
logger.info(f"β
Downloaded: {size_mb:.2f} MB")
|
| 326 |
|
| 327 |
+
# Compress if not already compressed
|
| 328 |
+
need_compress = not is_compressed(original_filename)
|
| 329 |
+
if need_compress:
|
| 330 |
+
zip_filename = original_filename + ".zip"
|
| 331 |
+
# Create a temporary ZIP file
|
| 332 |
+
zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix="_" + zip_filename)
|
| 333 |
+
zip_path = zip_tmp.name
|
| 334 |
+
zip_tmp.close()
|
| 335 |
+
compress_to_zip(tmp_path, original_filename, zip_path)
|
| 336 |
+
os.unlink(tmp_path) # remove the original
|
| 337 |
+
tmp_path = zip_path
|
| 338 |
+
upload_filename = zip_filename
|
| 339 |
+
caption_prefix = f"π¦ File compressed to ZIP for delivery.\nOriginal: `{original_filename}`"
|
| 340 |
+
else:
|
| 341 |
+
upload_filename = original_filename
|
| 342 |
+
caption_prefix = "Here you go!"
|
| 343 |
+
|
| 344 |
+
upload_size = os.path.getsize(tmp_path)
|
| 345 |
+
upload_size_mb = upload_size / (1024 * 1024)
|
| 346 |
+
|
| 347 |
+
# Decision: split or send directly
|
| 348 |
+
if upload_size > CHUNK_SIZE:
|
| 349 |
+
# Split the (possibly compressed) file
|
| 350 |
+
await send_message(chat_id, f"π¦ File is {upload_size_mb:.2f} MB β splitting into parts...")
|
| 351 |
if status_message_id:
|
| 352 |
await bale_request("deleteMessage", {"chat_id": chat_id, "message_id": status_message_id})
|
| 353 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
with tempfile.TemporaryDirectory() as parts_dir:
|
| 355 |
+
total_parts = math.ceil(upload_size / CHUNK_SIZE)
|
| 356 |
+
parts_sent = 0
|
| 357 |
+
for chunk_path, part_num, total in split_file(tmp_path, upload_filename, parts_dir):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
caption = (
|
| 359 |
+
f"π¦ Part {part_num}/{total} of `{upload_filename}`\n"
|
| 360 |
f"Original file: `{original_filename}`\n\n"
|
| 361 |
"After downloading all parts:\n"
|
| 362 |
+
f"1. Combine them into one file:\n"
|
| 363 |
+
f" Windows: `copy /b *.part* {upload_filename}`\n"
|
| 364 |
+
f" Linux/Mac: `cat *.part* > {upload_filename}`\n"
|
| 365 |
+
"2. Extract the combined file (if it's a ZIP) to get the original asset."
|
| 366 |
)
|
| 367 |
+
result = await send_document_file(chat_id, chunk_path,
|
| 368 |
caption=caption,
|
| 369 |
+
display_filename=os.path.basename(chunk_path))
|
| 370 |
if not result.get("ok"):
|
| 371 |
await send_message(chat_id, f"β Failed to send part {part_num}. Error: {result.get('description')}")
|
| 372 |
+
break
|
| 373 |
+
parts_sent += 1
|
| 374 |
+
|
| 375 |
+
if parts_sent == total_parts:
|
| 376 |
+
await answer_callback(callback_id, "All parts sent.")
|
| 377 |
+
elif parts_sent > 0:
|
| 378 |
+
await answer_callback(callback_id, f"Only {parts_sent}/{total_parts} parts sent.")
|
| 379 |
+
else:
|
| 380 |
+
await answer_callback(callback_id, "Failed to send any part.")
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
else:
|
| 383 |
+
# Small enough β send directly
|
| 384 |
if status_message_id:
|
| 385 |
await bale_request("editMessageText", {
|
| 386 |
"chat_id": chat_id,
|
| 387 |
"message_id": status_message_id,
|
| 388 |
+
"text": f"π₯ Downloaded {upload_size_mb:.2f} MB β uploading to Bale..."
|
| 389 |
})
|
| 390 |
else:
|
| 391 |
+
await send_message(chat_id, f"π₯ Downloaded {upload_size_mb:.2f} MB β uploading to Bale...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
+
result = await send_document_file(chat_id, tmp_path,
|
| 394 |
+
caption=caption_prefix,
|
| 395 |
display_filename=upload_filename)
|
| 396 |
if result.get("ok"):
|
| 397 |
if status_message_id:
|
|
|
|
| 401 |
raw_error = result.get("description", str(result))
|
| 402 |
await send_message(chat_id, f"β Upload failed. Bale response:\n{raw_error}")
|
| 403 |
await answer_callback(callback_id, "Failed to send.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
except Exception as e:
|
| 406 |
logger.error(f"β Download/Upload error: {e}", exc_info=True)
|
| 407 |
await send_message(chat_id, f"β Error: {e}")
|
| 408 |
await answer_callback(callback_id, "Failed.")
|
| 409 |
finally:
|
| 410 |
+
# Clean up the uploaded file (either original compressed or the original download)
|
| 411 |
if os.path.exists(tmp_path):
|
| 412 |
try:
|
| 413 |
os.unlink(tmp_path)
|