Update app.py
Browse files
app.py
CHANGED
|
@@ -31,6 +31,9 @@ KEEPALIVE_INTERVAL: int = 300 # 5 minutes
|
|
| 31 |
UPLOAD_TIMEOUT: int = 7200 # 2 hours per upload job
|
| 32 |
DB_PATH: str = "bot_files.db"
|
| 33 |
|
|
|
|
|
|
|
|
|
|
| 34 |
# Logging
|
| 35 |
logging.basicConfig(
|
| 36 |
level=logging.INFO,
|
|
@@ -104,14 +107,24 @@ def db_remove_all_user_files(user_id: int) -> None:
|
|
| 104 |
cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
|
| 105 |
conn.commit()
|
| 106 |
|
| 107 |
-
def db_file_exists(user_id: int, orig_name: str) -> Optional[str]:
|
| 108 |
-
"""
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
row = cursor.fetchone()
|
| 114 |
-
return row[0] if row else None
|
| 115 |
|
| 116 |
# =============================================================================
|
| 117 |
# IN‑MEMORY TOKEN STORES
|
|
@@ -120,8 +133,7 @@ def db_file_exists(user_id: int, orig_name: str) -> Optional[str]:
|
|
| 120 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 121 |
upload_prompt_map: dict[str, List[Tuple]] = {} # token → list of entries
|
| 122 |
album_groups: dict[str, dict] = {}
|
| 123 |
-
|
| 124 |
-
duplicate_prompt_map: dict[str, dict] = {} # token → {user_id, chat_id, file_msg_or_id, orig_filename, job_id, file_id, expected_size}
|
| 125 |
|
| 126 |
def make_token() -> str:
|
| 127 |
return secrets.token_hex(8)
|
|
@@ -289,7 +301,6 @@ async def do_upload_job(
|
|
| 289 |
temp_dir = tempfile.mkdtemp()
|
| 290 |
local_path = None
|
| 291 |
try:
|
| 292 |
-
# ---- Download from Telegram (progress shown) ----
|
| 293 |
await status_msg.edit_text(
|
| 294 |
"⬇️ Downloading from Telegram...",
|
| 295 |
reply_markup=InlineKeyboardMarkup(
|
|
@@ -331,15 +342,18 @@ async def do_upload_job(
|
|
| 331 |
except Exception:
|
| 332 |
pass
|
| 333 |
|
|
|
|
| 334 |
if isinstance(file_msg_or_id, Message):
|
| 335 |
local_path = await file_msg_or_id.download(
|
| 336 |
file_name=os.path.join(temp_dir, orig_filename),
|
|
|
|
| 337 |
progress=download_progress,
|
| 338 |
)
|
| 339 |
else:
|
| 340 |
local_path = await app.download_media(
|
| 341 |
file_msg_or_id,
|
| 342 |
file_name=os.path.join(temp_dir, orig_filename),
|
|
|
|
| 343 |
progress=download_progress,
|
| 344 |
)
|
| 345 |
|
|
@@ -348,7 +362,7 @@ async def do_upload_job(
|
|
| 348 |
|
| 349 |
file_size = os.path.getsize(local_path)
|
| 350 |
|
| 351 |
-
# ---- Upload to Hugging Face
|
| 352 |
enc_folder = get_encrypted_folder(user_id)
|
| 353 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 354 |
repo_path = f"{enc_folder}/{enc_filename}"
|
|
@@ -361,8 +375,6 @@ async def do_upload_job(
|
|
| 361 |
)
|
| 362 |
|
| 363 |
loop = asyncio.get_event_loop()
|
| 364 |
-
upload_done = loop.create_future()
|
| 365 |
-
|
| 366 |
def sync_upload():
|
| 367 |
hf.upload_file(
|
| 368 |
path_or_fileobj=local_path,
|
|
@@ -372,8 +384,6 @@ async def do_upload_job(
|
|
| 372 |
)
|
| 373 |
|
| 374 |
task = loop.run_in_executor(None, sync_upload)
|
| 375 |
-
|
| 376 |
-
# Wait with a timeout
|
| 377 |
try:
|
| 378 |
await asyncio.wait_for(asyncio.wrap_future(task), timeout=UPLOAD_TIMEOUT)
|
| 379 |
except asyncio.TimeoutError:
|
|
@@ -534,11 +544,12 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 534 |
return await message.edit_text("You have no uploaded files.", reply_markup=None)
|
| 535 |
|
| 536 |
buttons = []
|
| 537 |
-
for enc_path, orig_name,
|
| 538 |
token = make_token()
|
| 539 |
file_callback_map[token] = enc_path
|
|
|
|
| 540 |
buttons.append([
|
| 541 |
-
InlineKeyboardButton(f"📥 {
|
| 542 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 543 |
])
|
| 544 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
|
@@ -549,6 +560,64 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 549 |
)
|
| 550 |
|
| 551 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
# =============================================================================
|
| 553 |
# ALBUM GROUPING
|
| 554 |
# =============================================================================
|
|
@@ -579,42 +648,78 @@ async def process_album_group(media_group_id: str):
|
|
| 579 |
)
|
| 580 |
return
|
| 581 |
|
| 582 |
-
#
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
await
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
await app.send_message(
|
| 616 |
chat_id,
|
| 617 |
-
f"⚠️ Skipped {len(skipped)} file(s)
|
| 618 |
)
|
| 619 |
|
| 620 |
|
|
@@ -673,7 +778,8 @@ async def cmd_help(_, message: Message):
|
|
| 673 |
"/help – This help\n\n"
|
| 674 |
"**Features:**\n"
|
| 675 |
"• Maximum file size: 45 GB – larger uploads are rejected.\n"
|
| 676 |
-
"• Duplicate detection – you'll be asked to skip or keep
|
|
|
|
| 677 |
"• File splitting for large downloads (>1.9 GB).\n"
|
| 678 |
"• Real‑time progress with speed and ETA."
|
| 679 |
)
|
|
@@ -681,26 +787,33 @@ async def cmd_help(_, message: Message):
|
|
| 681 |
|
| 682 |
@app.on_message(filters.command("status"))
|
| 683 |
async def cmd_status(_, message: Message):
|
|
|
|
| 684 |
free = get_free_disk()
|
| 685 |
disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
|
|
|
|
| 686 |
try:
|
| 687 |
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 688 |
used = info.used_storage or 0
|
| 689 |
-
except Exception:
|
|
|
|
| 690 |
used = 0
|
|
|
|
| 691 |
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
|
|
|
| 692 |
uptime_sec = int(time.time() - bot_start_time)
|
| 693 |
uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
|
|
|
|
| 694 |
mem_text = f"🧠 Memory: {get_memory_usage()}"
|
| 695 |
cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
|
|
|
|
| 696 |
try:
|
| 697 |
r = requests.head("https://huggingface.co", timeout=5)
|
| 698 |
hf_ping = "OK" if r.status_code < 400 else f"HTTP {r.status_code}"
|
| 699 |
except Exception:
|
| 700 |
hf_ping = "unreachable"
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
)
|
| 704 |
|
| 705 |
@app.on_message(filters.command("files"))
|
| 706 |
async def cmd_files(_, message: Message):
|
|
@@ -730,11 +843,12 @@ async def cmd_files(_, message: Message):
|
|
| 730 |
if not user_files:
|
| 731 |
return await message.reply_text("You have no uploaded files.")
|
| 732 |
buttons = []
|
| 733 |
-
for enc_path, orig_name,
|
| 734 |
token = make_token()
|
| 735 |
file_callback_map[token] = enc_path
|
|
|
|
| 736 |
buttons.append([
|
| 737 |
-
InlineKeyboardButton(f"📥 {
|
| 738 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 739 |
])
|
| 740 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
|
@@ -773,69 +887,56 @@ async def cmd_upload(_, message: Message):
|
|
| 773 |
return await message.reply_text(f"❌ Could not fetch the message: {e}")
|
| 774 |
if not msg.media:
|
| 775 |
return await message.reply_text("The linked message doesn't contain a downloadable file.")
|
| 776 |
-
file_id =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 777 |
expected_size = extract_file_size(msg)
|
| 778 |
if msg.document:
|
| 779 |
-
|
| 780 |
-
file_id = msg.document.file_id
|
| 781 |
elif msg.video:
|
| 782 |
-
|
| 783 |
-
file_id = msg.video.file_id
|
| 784 |
elif msg.audio:
|
| 785 |
-
|
| 786 |
-
file_id = msg.audio.file_id
|
| 787 |
elif msg.photo:
|
| 788 |
-
|
| 789 |
-
file_id = msg.photo.file_id
|
| 790 |
elif msg.animation:
|
| 791 |
-
|
| 792 |
-
file_id = msg.animation.file_id
|
| 793 |
elif msg.sticker:
|
| 794 |
if msg.sticker.is_animated:
|
| 795 |
-
|
| 796 |
elif msg.sticker.is_video:
|
| 797 |
-
|
| 798 |
else:
|
| 799 |
-
|
| 800 |
-
|
| 801 |
elif msg.video_note:
|
| 802 |
-
|
| 803 |
-
file_id = msg.video_note.file_id
|
| 804 |
elif msg.voice:
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
else:
|
| 808 |
-
filename = f"file_{msg_id}"
|
| 809 |
-
|
| 810 |
-
# Check file size limit first
|
| 811 |
-
limit_err = check_file_size_limit(filename, expected_size)
|
| 812 |
-
if limit_err:
|
| 813 |
-
return await message.reply_text(limit_err)
|
| 814 |
-
|
| 815 |
-
# Check for duplicate
|
| 816 |
-
existing = db_file_exists(message.from_user.id, filename)
|
| 817 |
-
if existing:
|
| 818 |
-
token = make_token()
|
| 819 |
-
duplicate_prompt_map[token] = {
|
| 820 |
-
'user_id': message.from_user.id,
|
| 821 |
-
'chat_id': message.chat.id,
|
| 822 |
-
'file_obj': file_id,
|
| 823 |
-
'orig_filename': filename,
|
| 824 |
-
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 825 |
-
'file_id': file_id,
|
| 826 |
-
'expected_size': expected_size,
|
| 827 |
-
}
|
| 828 |
-
kb = InlineKeyboardMarkup([
|
| 829 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 830 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 831 |
-
])
|
| 832 |
-
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 833 |
-
return
|
| 834 |
-
# No duplicate, queue directly
|
| 835 |
-
job_id = int(time.time() * 1000 + hash(filename))
|
| 836 |
-
active_jobs[job_id] = {"status": "queued"}
|
| 837 |
-
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size))
|
| 838 |
-
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
| 839 |
|
| 840 |
|
| 841 |
# =============================================================================
|
|
@@ -857,17 +958,16 @@ async def cb_dup_keep(_, query: CallbackQuery):
|
|
| 857 |
data = duplicate_prompt_map.pop(token, None)
|
| 858 |
if not data:
|
| 859 |
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 860 |
-
#
|
| 861 |
base, ext = os.path.splitext(data['orig_filename'])
|
| 862 |
new_filename = f"{base}_1{ext}"
|
| 863 |
-
# Queue with the modified filename
|
| 864 |
job_id = data['job_id']
|
| 865 |
active_jobs[job_id] = {"status": "queued"}
|
| 866 |
await upload_queue.put((
|
| 867 |
data['user_id'],
|
| 868 |
data['chat_id'],
|
| 869 |
data['file_obj'],
|
| 870 |
-
new_filename,
|
| 871 |
job_id,
|
| 872 |
data['file_id'],
|
| 873 |
data['expected_size'],
|
|
@@ -933,7 +1033,6 @@ async def cb_upload(_, query: CallbackQuery):
|
|
| 933 |
for entry in entries:
|
| 934 |
user_id = entry[0]
|
| 935 |
if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
|
| 936 |
-
# Local file: (user_id, msg_id, filename, file_id)
|
| 937 |
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
| 938 |
try:
|
| 939 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
|
@@ -945,34 +1044,22 @@ async def cb_upload(_, query: CallbackQuery):
|
|
| 945 |
continue
|
| 946 |
file_obj = file_msg
|
| 947 |
expected_size = extract_file_size(file_msg)
|
| 948 |
-
# Check size limit
|
| 949 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 950 |
if limit_err:
|
| 951 |
await query.message.reply_text(limit_err)
|
| 952 |
continue
|
| 953 |
-
# Duplicate check
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
'orig_filename': filename,
|
| 962 |
-
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 963 |
-
'file_id': file_id,
|
| 964 |
-
'expected_size': expected_size,
|
| 965 |
-
}
|
| 966 |
-
kb = InlineKeyboardMarkup([
|
| 967 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token2}")],
|
| 968 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token2}")],
|
| 969 |
-
])
|
| 970 |
-
await query.message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 971 |
continue
|
| 972 |
else:
|
| 973 |
# Remote file: (user_id, file_id, filename, expected_size)
|
| 974 |
file_id, filename, expected_size = entry[1], entry[2], entry[3] if len(entry) == 4 else (entry[1], entry[2], None)
|
| 975 |
-
# Check size limit
|
| 976 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 977 |
if limit_err:
|
| 978 |
await query.message.reply_text(limit_err)
|
|
@@ -993,7 +1080,6 @@ async def cb_upload_all(_, query: CallbackQuery):
|
|
| 993 |
for entry in entries:
|
| 994 |
user_id = entry[0]
|
| 995 |
if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
|
| 996 |
-
# Local file
|
| 997 |
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
| 998 |
try:
|
| 999 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
|
@@ -1003,32 +1089,19 @@ async def cb_upload_all(_, query: CallbackQuery):
|
|
| 1003 |
continue
|
| 1004 |
file_obj = file_msg
|
| 1005 |
expected_size = extract_file_size(file_msg)
|
| 1006 |
-
# Check size limit
|
| 1007 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1008 |
if limit_err:
|
| 1009 |
await query.message.reply_text(limit_err)
|
| 1010 |
continue
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
'file_obj': file_obj,
|
| 1019 |
-
'orig_filename': filename,
|
| 1020 |
-
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 1021 |
-
'file_id': file_id,
|
| 1022 |
-
'expected_size': expected_size,
|
| 1023 |
-
}
|
| 1024 |
-
kb = InlineKeyboardMarkup([
|
| 1025 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token2}")],
|
| 1026 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token2}")],
|
| 1027 |
-
])
|
| 1028 |
-
await query.message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 1029 |
continue
|
| 1030 |
else:
|
| 1031 |
-
# Remote file: (user_id, file_id, filename, expected_size)
|
| 1032 |
file_id, filename, expected_size = entry[1], entry[2], entry[3] if len(entry) == 4 else (entry[1], entry[2], None)
|
| 1033 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1034 |
if limit_err:
|
|
@@ -1047,7 +1120,7 @@ async def cb_cancel_upload_prompt(_, query: CallbackQuery):
|
|
| 1047 |
|
| 1048 |
|
| 1049 |
# =============================================================================
|
| 1050 |
-
# MESSAGE LINK INTERACTIVE PROMPT
|
| 1051 |
# =============================================================================
|
| 1052 |
|
| 1053 |
@app.on_message(
|
|
@@ -1072,72 +1145,31 @@ async def on_message_link(client, message: Message):
|
|
| 1072 |
if not msg.media:
|
| 1073 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 1074 |
return
|
| 1075 |
-
file_id = None
|
| 1076 |
-
expected_size = extract_file_size(msg)
|
| 1077 |
-
if msg.document:
|
| 1078 |
-
filename = msg.document.file_name
|
| 1079 |
-
file_id = msg.document.file_id
|
| 1080 |
-
elif msg.video:
|
| 1081 |
-
filename = msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
|
| 1082 |
-
file_id = msg.video.file_id
|
| 1083 |
-
elif msg.audio:
|
| 1084 |
-
filename = msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
|
| 1085 |
-
file_id = msg.audio.file_id
|
| 1086 |
-
elif msg.photo:
|
| 1087 |
-
filename = f"{msg.photo.file_unique_id}.jpg"
|
| 1088 |
-
file_id = msg.photo.file_id
|
| 1089 |
-
elif msg.animation:
|
| 1090 |
-
filename = msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
|
| 1091 |
-
file_id = msg.animation.file_id
|
| 1092 |
-
elif msg.sticker:
|
| 1093 |
-
if msg.sticker.is_animated:
|
| 1094 |
-
filename = f"{msg.sticker.file_unique_id}.tgs"
|
| 1095 |
-
elif msg.sticker.is_video:
|
| 1096 |
-
filename = f"{msg.sticker.file_unique_id}.webm"
|
| 1097 |
-
else:
|
| 1098 |
-
filename = f"{msg.sticker.file_unique_id}.webp"
|
| 1099 |
-
file_id = msg.sticker.file_id
|
| 1100 |
-
elif msg.video_note:
|
| 1101 |
-
filename = f"{msg.video_note.file_unique_id}.mp4"
|
| 1102 |
-
file_id = msg.video_note.file_id
|
| 1103 |
-
elif msg.voice:
|
| 1104 |
-
filename = f"{msg.voice.file_unique_id}.ogg"
|
| 1105 |
-
file_id = msg.voice.file_id
|
| 1106 |
-
else:
|
| 1107 |
-
filename = f"file_{msg_id}"
|
| 1108 |
|
| 1109 |
-
|
|
|
|
|
|
|
|
|
|
| 1110 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1111 |
if limit_err:
|
| 1112 |
return await message.reply_text(limit_err)
|
| 1113 |
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
|
| 1119 |
-
|
| 1120 |
-
|
| 1121 |
-
'file_obj': file_id,
|
| 1122 |
-
'orig_filename': filename,
|
| 1123 |
-
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 1124 |
-
'file_id': file_id,
|
| 1125 |
-
'expected_size': expected_size,
|
| 1126 |
-
}
|
| 1127 |
-
kb = InlineKeyboardMarkup([
|
| 1128 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 1129 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 1130 |
-
])
|
| 1131 |
-
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 1132 |
return
|
| 1133 |
|
| 1134 |
-
|
| 1135 |
-
upload_prompt_map[
|
| 1136 |
kb = InlineKeyboardMarkup([
|
| 1137 |
-
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{
|
| 1138 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1139 |
])
|
| 1140 |
-
await message.reply_text(f"Found file `{filename}`
|
| 1141 |
|
| 1142 |
|
| 1143 |
# =============================================================================
|
|
@@ -1149,40 +1181,11 @@ async def on_message_link(client, message: Message):
|
|
| 1149 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 1150 |
)
|
| 1151 |
async def on_direct_file(_, message: Message):
|
| 1152 |
-
expected_size =
|
| 1153 |
-
if
|
| 1154 |
-
filename = message.document.file_name
|
| 1155 |
-
file_id = message.document.file_id
|
| 1156 |
-
elif message.video:
|
| 1157 |
-
filename = message.video.file_name or f"{message.video.file_unique_id}.mp4"
|
| 1158 |
-
file_id = message.video.file_id
|
| 1159 |
-
elif message.audio:
|
| 1160 |
-
filename = message.audio.file_name or f"{message.audio.file_unique_id}.mp3"
|
| 1161 |
-
file_id = message.audio.file_id
|
| 1162 |
-
elif message.photo:
|
| 1163 |
-
filename = f"{message.photo.file_unique_id}.jpg"
|
| 1164 |
-
file_id = message.photo.file_id
|
| 1165 |
-
elif message.animation:
|
| 1166 |
-
filename = message.animation.file_name or f"{message.animation.file_unique_id}.mp4"
|
| 1167 |
-
file_id = message.animation.file_id
|
| 1168 |
-
elif message.sticker:
|
| 1169 |
-
if message.sticker.is_animated:
|
| 1170 |
-
filename = f"{message.sticker.file_unique_id}.tgs"
|
| 1171 |
-
elif message.sticker.is_video:
|
| 1172 |
-
filename = f"{message.sticker.file_unique_id}.webm"
|
| 1173 |
-
else:
|
| 1174 |
-
filename = f"{message.sticker.file_unique_id}.webp"
|
| 1175 |
-
file_id = message.sticker.file_id
|
| 1176 |
-
elif message.video_note:
|
| 1177 |
-
filename = f"{message.video_note.file_unique_id}.mp4"
|
| 1178 |
-
file_id = message.video_note.file_id
|
| 1179 |
-
elif message.voice:
|
| 1180 |
-
filename = f"{message.voice.file_unique_id}.ogg"
|
| 1181 |
-
file_id = message.voice.file_id
|
| 1182 |
-
else:
|
| 1183 |
return
|
| 1184 |
|
| 1185 |
-
# Album grouping
|
| 1186 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 1187 |
group_id = str(message.media_group_id)
|
| 1188 |
if group_id not in album_groups:
|
|
@@ -1203,35 +1206,24 @@ async def on_direct_file(_, message: Message):
|
|
| 1203 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1204 |
return
|
| 1205 |
|
| 1206 |
-
# Single file
|
| 1207 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1208 |
if limit_err:
|
| 1209 |
return await message.reply_text(limit_err)
|
| 1210 |
|
| 1211 |
-
|
| 1212 |
-
|
| 1213 |
-
|
| 1214 |
-
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
'file_obj': message,
|
| 1219 |
-
'orig_filename': filename,
|
| 1220 |
-
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 1221 |
-
'file_id': file_id,
|
| 1222 |
-
'expected_size': expected_size,
|
| 1223 |
-
}
|
| 1224 |
-
kb = InlineKeyboardMarkup([
|
| 1225 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 1226 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 1227 |
-
])
|
| 1228 |
-
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 1229 |
return
|
| 1230 |
|
| 1231 |
-
|
| 1232 |
-
upload_prompt_map[
|
| 1233 |
kb = InlineKeyboardMarkup([
|
| 1234 |
-
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{
|
| 1235 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1236 |
])
|
| 1237 |
await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)
|
|
@@ -1257,7 +1249,7 @@ def keepalive():
|
|
| 1257 |
async def main():
|
| 1258 |
asyncio.create_task(upload_worker())
|
| 1259 |
await app.start()
|
| 1260 |
-
logger.info("Bot started successfully (tgcrypto
|
| 1261 |
await asyncio.Event().wait()
|
| 1262 |
|
| 1263 |
|
|
|
|
| 31 |
UPLOAD_TIMEOUT: int = 7200 # 2 hours per upload job
|
| 32 |
DB_PATH: str = "bot_files.db"
|
| 33 |
|
| 34 |
+
# Optimisation: larger block size for faster Telegram downloads (1 MB)
|
| 35 |
+
DOWNLOAD_BLOCK_SIZE: int = 1024 * 1024 # 1 MB
|
| 36 |
+
|
| 37 |
# Logging
|
| 38 |
logging.basicConfig(
|
| 39 |
level=logging.INFO,
|
|
|
|
| 107 |
cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
|
| 108 |
conn.commit()
|
| 109 |
|
| 110 |
+
def db_file_exists(user_id: int, orig_name: str, size: Optional[int] = None) -> Optional[Tuple[str, int]]:
|
| 111 |
+
"""
|
| 112 |
+
Check if a file with given name (and optionally exact size) exists.
|
| 113 |
+
Returns (enc_path, size) if found, else None.
|
| 114 |
+
If size is provided, both name and size must match.
|
| 115 |
+
"""
|
| 116 |
+
if size is not None:
|
| 117 |
+
cursor.execute(
|
| 118 |
+
"SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ? AND size = ?",
|
| 119 |
+
(user_id, orig_name, size),
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
cursor.execute(
|
| 123 |
+
"SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ?",
|
| 124 |
+
(user_id, orig_name),
|
| 125 |
+
)
|
| 126 |
row = cursor.fetchone()
|
| 127 |
+
return (row[0], row[1]) if row else None
|
| 128 |
|
| 129 |
# =============================================================================
|
| 130 |
# IN‑MEMORY TOKEN STORES
|
|
|
|
| 133 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 134 |
upload_prompt_map: dict[str, List[Tuple]] = {} # token → list of entries
|
| 135 |
album_groups: dict[str, dict] = {}
|
| 136 |
+
duplicate_prompt_map: dict[str, dict] = {} # token → duplicate info
|
|
|
|
| 137 |
|
| 138 |
def make_token() -> str:
|
| 139 |
return secrets.token_hex(8)
|
|
|
|
| 301 |
temp_dir = tempfile.mkdtemp()
|
| 302 |
local_path = None
|
| 303 |
try:
|
|
|
|
| 304 |
await status_msg.edit_text(
|
| 305 |
"⬇️ Downloading from Telegram...",
|
| 306 |
reply_markup=InlineKeyboardMarkup(
|
|
|
|
| 342 |
except Exception:
|
| 343 |
pass
|
| 344 |
|
| 345 |
+
# Download with larger block_size for speed
|
| 346 |
if isinstance(file_msg_or_id, Message):
|
| 347 |
local_path = await file_msg_or_id.download(
|
| 348 |
file_name=os.path.join(temp_dir, orig_filename),
|
| 349 |
+
block_size=DOWNLOAD_BLOCK_SIZE,
|
| 350 |
progress=download_progress,
|
| 351 |
)
|
| 352 |
else:
|
| 353 |
local_path = await app.download_media(
|
| 354 |
file_msg_or_id,
|
| 355 |
file_name=os.path.join(temp_dir, orig_filename),
|
| 356 |
+
block_size=DOWNLOAD_BLOCK_SIZE,
|
| 357 |
progress=download_progress,
|
| 358 |
)
|
| 359 |
|
|
|
|
| 362 |
|
| 363 |
file_size = os.path.getsize(local_path)
|
| 364 |
|
| 365 |
+
# ---- Upload to Hugging Face ----
|
| 366 |
enc_folder = get_encrypted_folder(user_id)
|
| 367 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 368 |
repo_path = f"{enc_folder}/{enc_filename}"
|
|
|
|
| 375 |
)
|
| 376 |
|
| 377 |
loop = asyncio.get_event_loop()
|
|
|
|
|
|
|
| 378 |
def sync_upload():
|
| 379 |
hf.upload_file(
|
| 380 |
path_or_fileobj=local_path,
|
|
|
|
| 384 |
)
|
| 385 |
|
| 386 |
task = loop.run_in_executor(None, sync_upload)
|
|
|
|
|
|
|
| 387 |
try:
|
| 388 |
await asyncio.wait_for(asyncio.wrap_future(task), timeout=UPLOAD_TIMEOUT)
|
| 389 |
except asyncio.TimeoutError:
|
|
|
|
| 544 |
return await message.edit_text("You have no uploaded files.", reply_markup=None)
|
| 545 |
|
| 546 |
buttons = []
|
| 547 |
+
for enc_path, orig_name, size in user_files:
|
| 548 |
token = make_token()
|
| 549 |
file_callback_map[token] = enc_path
|
| 550 |
+
display = f"{orig_name[:25]} ({format_size(size)})" if size else orig_name[:25]
|
| 551 |
buttons.append([
|
| 552 |
+
InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),
|
| 553 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 554 |
])
|
| 555 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
|
|
|
| 560 |
)
|
| 561 |
|
| 562 |
|
| 563 |
+
# =============================================================================
|
| 564 |
+
# DUPLICATE DETECTION & PROMPT
|
| 565 |
+
# =============================================================================
|
| 566 |
+
|
| 567 |
+
def build_duplicate_prompt(
|
| 568 |
+
user_id: int,
|
| 569 |
+
chat_id: int,
|
| 570 |
+
file_obj: Union[Message, str],
|
| 571 |
+
orig_filename: str,
|
| 572 |
+
expected_size: Optional[int],
|
| 573 |
+
file_id: Optional[str] = None,
|
| 574 |
+
) -> Tuple[Optional[str], Optional[dict]]:
|
| 575 |
+
"""
|
| 576 |
+
Check for duplicate (name and size). If duplicate, return a token and store data.
|
| 577 |
+
If name exists but size differs, still prompt because encrypted filename would collide.
|
| 578 |
+
Returns (duplicate_token, duplicate_data) if duplicate found, else (None, None).
|
| 579 |
+
"""
|
| 580 |
+
existing = db_file_exists(user_id, orig_filename, expected_size)
|
| 581 |
+
if existing:
|
| 582 |
+
enc_path, existing_size = existing
|
| 583 |
+
else:
|
| 584 |
+
# Check if name exists with any size
|
| 585 |
+
existing_any = db_file_exists(user_id, orig_filename) # without size
|
| 586 |
+
if existing_any:
|
| 587 |
+
enc_path, existing_size = existing_any
|
| 588 |
+
else:
|
| 589 |
+
return None, None
|
| 590 |
+
|
| 591 |
+
token = make_token()
|
| 592 |
+
duplicate_prompt_map[token] = {
|
| 593 |
+
'user_id': user_id,
|
| 594 |
+
'chat_id': chat_id,
|
| 595 |
+
'file_obj': file_obj,
|
| 596 |
+
'orig_filename': orig_filename,
|
| 597 |
+
'job_id': int(time.time() * 1000 + hash(orig_filename)),
|
| 598 |
+
'file_id': file_id,
|
| 599 |
+
'expected_size': expected_size,
|
| 600 |
+
'existing_size': existing_size,
|
| 601 |
+
}
|
| 602 |
+
return token, duplicate_prompt_map[token]
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
async def send_duplicate_prompt(chat_id, token, orig_filename, expected_size, existing_size):
|
| 606 |
+
if expected_size is not None and existing_size is not None and expected_size == existing_size:
|
| 607 |
+
size_note = f" (same size: {format_size(expected_size)})"
|
| 608 |
+
else:
|
| 609 |
+
size_note = f" (existing size: {format_size(existing_size or 0)})" if existing_size else ""
|
| 610 |
+
kb = InlineKeyboardMarkup([
|
| 611 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 612 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 613 |
+
])
|
| 614 |
+
await app.send_message(
|
| 615 |
+
chat_id,
|
| 616 |
+
f"⚠️ File `{orig_filename}` already exists{size_note}.\nWhat do you want to do?",
|
| 617 |
+
reply_markup=kb,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
# =============================================================================
|
| 622 |
# ALBUM GROUPING
|
| 623 |
# =============================================================================
|
|
|
|
| 648 |
)
|
| 649 |
return
|
| 650 |
|
| 651 |
+
# Handle duplicates – for simplicity, we'll prompt for each valid file individually
|
| 652 |
+
# but that would be messy. Instead, we'll collect files that are not duplicates,
|
| 653 |
+
# and for those that are, prompt individually.
|
| 654 |
+
# For album upload, we can still do a combined prompt only for non-duplicates.
|
| 655 |
+
# We'll check each, and if any duplicate found, send a separate duplicate prompt,
|
| 656 |
+
# removing it from the batch.
|
| 657 |
+
non_dup = []
|
| 658 |
+
for msg_id, filename, file_id, size in valid:
|
| 659 |
+
token, data = build_duplicate_prompt(user_id, chat_id, None, filename, size, file_id)
|
| 660 |
+
if token:
|
| 661 |
+
# Will be handled separately
|
| 662 |
+
data['msg_id'] = msg_id # store msg_id for later use
|
| 663 |
+
# Don't send prompt here, we'll do it after
|
| 664 |
+
# We'll add to a list and process later
|
| 665 |
+
pass
|
| 666 |
+
else:
|
| 667 |
+
non_dup.append((msg_id, filename, file_id, size))
|
| 668 |
+
|
| 669 |
+
# Process duplicates (we'll send individual prompts)
|
| 670 |
+
dup_entries = []
|
| 671 |
+
for msg_id, filename, file_id, size in valid:
|
| 672 |
+
token, data = build_duplicate_prompt(user_id, chat_id, None, filename, size, file_id)
|
| 673 |
+
if token:
|
| 674 |
+
data['msg_id'] = msg_id
|
| 675 |
+
dup_entries.append((token, data))
|
| 676 |
+
|
| 677 |
+
# Send duplicate prompts after a short delay to avoid flooding
|
| 678 |
+
for token, data in dup_entries:
|
| 679 |
+
await send_duplicate_prompt(
|
| 680 |
+
chat_id,
|
| 681 |
+
token,
|
| 682 |
+
data['orig_filename'],
|
| 683 |
+
data['expected_size'],
|
| 684 |
+
data['existing_size'],
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
if non_dup:
|
| 688 |
+
# Build prompt for non-duplicate files
|
| 689 |
+
if len(non_dup) == 1:
|
| 690 |
+
msg_id, filename, file_id, _ = non_dup[0]
|
| 691 |
+
token = make_token()
|
| 692 |
+
upload_prompt_map[token] = [(user_id, msg_id, filename, file_id)]
|
| 693 |
+
kb = InlineKeyboardMarkup([
|
| 694 |
+
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 695 |
+
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 696 |
+
])
|
| 697 |
+
await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
|
| 698 |
+
else:
|
| 699 |
+
files_list = "\n".join(f"• {fname} ({format_size(fsize)})" for _, fname, _, fsize in non_dup)
|
| 700 |
+
token = make_token()
|
| 701 |
+
upload_prompt_map[token] = [(user_id, msg_id, fname, fid) for msg_id, fname, fid, _ in non_dup]
|
| 702 |
+
|
| 703 |
+
button_rows = [
|
| 704 |
+
[InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")]
|
| 705 |
+
]
|
| 706 |
+
for msg_id, fname, fid, _ in non_dup:
|
| 707 |
+
individual_token = make_token()
|
| 708 |
+
upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]
|
| 709 |
+
button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
|
| 710 |
+
button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])
|
| 711 |
+
|
| 712 |
+
prompt_text = f"Received {len(non_dup)} non‑duplicate files.\n{files_list}\n\nChoose:"
|
| 713 |
+
if skipped:
|
| 714 |
+
prompt_text += f"\n⚠️ Skipped (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped)
|
| 715 |
+
await app.send_message(chat_id, prompt_text, reply_markup=InlineKeyboardMarkup(button_rows))
|
| 716 |
+
|
| 717 |
+
# Inform about skipped files if any
|
| 718 |
+
if skipped:
|
| 719 |
+
skip_names = ", ".join(f"`{f}`" for f in skipped)
|
| 720 |
await app.send_message(
|
| 721 |
chat_id,
|
| 722 |
+
f"⚠️ Skipped {len(skipped)} file(s) (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): {skip_names}"
|
| 723 |
)
|
| 724 |
|
| 725 |
|
|
|
|
| 778 |
"/help – This help\n\n"
|
| 779 |
"**Features:**\n"
|
| 780 |
"• Maximum file size: 45 GB – larger uploads are rejected.\n"
|
| 781 |
+
"• Duplicate detection (name + size) – you'll be asked to skip or keep.\n"
|
| 782 |
+
"• Optimised download speed (1 MB block size).\n"
|
| 783 |
"• File splitting for large downloads (>1.9 GB).\n"
|
| 784 |
"• Real‑time progress with speed and ETA."
|
| 785 |
)
|
|
|
|
| 787 |
|
| 788 |
@app.on_message(filters.command("status"))
|
| 789 |
async def cmd_status(_, message: Message):
|
| 790 |
+
"""Fetch and display system status and dataset usage from Hugging Face."""
|
| 791 |
free = get_free_disk()
|
| 792 |
disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
|
| 793 |
+
|
| 794 |
try:
|
| 795 |
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 796 |
used = info.used_storage or 0
|
| 797 |
+
except Exception as e:
|
| 798 |
+
logger.warning("Failed to fetch dataset info: %s", e)
|
| 799 |
used = 0
|
| 800 |
+
|
| 801 |
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
| 802 |
+
|
| 803 |
uptime_sec = int(time.time() - bot_start_time)
|
| 804 |
uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
|
| 805 |
+
|
| 806 |
mem_text = f"🧠 Memory: {get_memory_usage()}"
|
| 807 |
cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
|
| 808 |
+
|
| 809 |
try:
|
| 810 |
r = requests.head("https://huggingface.co", timeout=5)
|
| 811 |
hf_ping = "OK" if r.status_code < 400 else f"HTTP {r.status_code}"
|
| 812 |
except Exception:
|
| 813 |
hf_ping = "unreachable"
|
| 814 |
+
|
| 815 |
+
status_msg = f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}\n{cpu_text}\n🌐 Hugging Face: {hf_ping}"
|
| 816 |
+
await message.reply_text(status_msg)
|
| 817 |
|
| 818 |
@app.on_message(filters.command("files"))
|
| 819 |
async def cmd_files(_, message: Message):
|
|
|
|
| 843 |
if not user_files:
|
| 844 |
return await message.reply_text("You have no uploaded files.")
|
| 845 |
buttons = []
|
| 846 |
+
for enc_path, orig_name, size in user_files:
|
| 847 |
token = make_token()
|
| 848 |
file_callback_map[token] = enc_path
|
| 849 |
+
display = f"{orig_name[:20]} ({format_size(size)})" if size else orig_name[:20]
|
| 850 |
buttons.append([
|
| 851 |
+
InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),
|
| 852 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 853 |
])
|
| 854 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
|
|
|
| 887 |
return await message.reply_text(f"❌ Could not fetch the message: {e}")
|
| 888 |
if not msg.media:
|
| 889 |
return await message.reply_text("The linked message doesn't contain a downloadable file.")
|
| 890 |
+
file_id, expected_size, filename = _extract_file_info(msg)
|
| 891 |
+
if not filename:
|
| 892 |
+
return await message.reply_text("Could not determine file name.")
|
| 893 |
+
|
| 894 |
+
limit_err = check_file_size_limit(filename, expected_size)
|
| 895 |
+
if limit_err:
|
| 896 |
+
return await message.reply_text(limit_err)
|
| 897 |
+
|
| 898 |
+
token, data = build_duplicate_prompt(
|
| 899 |
+
message.from_user.id, message.chat.id, file_id, filename, expected_size, file_id
|
| 900 |
+
)
|
| 901 |
+
if token:
|
| 902 |
+
await send_duplicate_prompt(
|
| 903 |
+
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 904 |
+
)
|
| 905 |
+
return
|
| 906 |
+
|
| 907 |
+
job_id = int(time.time() * 1000 + hash(filename))
|
| 908 |
+
active_jobs[job_id] = {"status": "queued"}
|
| 909 |
+
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size))
|
| 910 |
+
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
# Helper to extract file info from a message
|
| 914 |
+
def _extract_file_info(msg: Message) -> Tuple[Optional[str], Optional[int], Optional[str]]:
|
| 915 |
+
"""Returns (file_id, expected_size, filename) or None if not downloadable."""
|
| 916 |
expected_size = extract_file_size(msg)
|
| 917 |
if msg.document:
|
| 918 |
+
return msg.document.file_id, expected_size, msg.document.file_name
|
|
|
|
| 919 |
elif msg.video:
|
| 920 |
+
return msg.video.file_id, expected_size, msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
|
|
|
|
| 921 |
elif msg.audio:
|
| 922 |
+
return msg.audio.file_id, expected_size, msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
|
|
|
|
| 923 |
elif msg.photo:
|
| 924 |
+
return msg.photo.file_id, expected_size, f"{msg.photo.file_unique_id}.jpg"
|
|
|
|
| 925 |
elif msg.animation:
|
| 926 |
+
return msg.animation.file_id, expected_size, msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
|
|
|
|
| 927 |
elif msg.sticker:
|
| 928 |
if msg.sticker.is_animated:
|
| 929 |
+
fn = f"{msg.sticker.file_unique_id}.tgs"
|
| 930 |
elif msg.sticker.is_video:
|
| 931 |
+
fn = f"{msg.sticker.file_unique_id}.webm"
|
| 932 |
else:
|
| 933 |
+
fn = f"{msg.sticker.file_unique_id}.webp"
|
| 934 |
+
return msg.sticker.file_id, expected_size, fn
|
| 935 |
elif msg.video_note:
|
| 936 |
+
return msg.video_note.file_id, expected_size, f"{msg.video_note.file_unique_id}.mp4"
|
|
|
|
| 937 |
elif msg.voice:
|
| 938 |
+
return msg.voice.file_id, expected_size, f"{msg.voice.file_unique_id}.ogg"
|
| 939 |
+
return None, None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 940 |
|
| 941 |
|
| 942 |
# =============================================================================
|
|
|
|
| 958 |
data = duplicate_prompt_map.pop(token, None)
|
| 959 |
if not data:
|
| 960 |
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 961 |
+
# Rename the file to avoid collision
|
| 962 |
base, ext = os.path.splitext(data['orig_filename'])
|
| 963 |
new_filename = f"{base}_1{ext}"
|
|
|
|
| 964 |
job_id = data['job_id']
|
| 965 |
active_jobs[job_id] = {"status": "queued"}
|
| 966 |
await upload_queue.put((
|
| 967 |
data['user_id'],
|
| 968 |
data['chat_id'],
|
| 969 |
data['file_obj'],
|
| 970 |
+
new_filename,
|
| 971 |
job_id,
|
| 972 |
data['file_id'],
|
| 973 |
data['expected_size'],
|
|
|
|
| 1033 |
for entry in entries:
|
| 1034 |
user_id = entry[0]
|
| 1035 |
if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
|
|
|
|
| 1036 |
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
| 1037 |
try:
|
| 1038 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
|
|
|
| 1044 |
continue
|
| 1045 |
file_obj = file_msg
|
| 1046 |
expected_size = extract_file_size(file_msg)
|
|
|
|
| 1047 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1048 |
if limit_err:
|
| 1049 |
await query.message.reply_text(limit_err)
|
| 1050 |
continue
|
| 1051 |
+
# Duplicate check (already done in caller, but we re‑check for safety)
|
| 1052 |
+
token2, data = build_duplicate_prompt(
|
| 1053 |
+
user_id, query.message.chat.id, file_obj, filename, expected_size, file_id
|
| 1054 |
+
)
|
| 1055 |
+
if token2:
|
| 1056 |
+
await send_duplicate_prompt(
|
| 1057 |
+
query.message.chat.id, token2, filename, expected_size, data['existing_size']
|
| 1058 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1059 |
continue
|
| 1060 |
else:
|
| 1061 |
# Remote file: (user_id, file_id, filename, expected_size)
|
| 1062 |
file_id, filename, expected_size = entry[1], entry[2], entry[3] if len(entry) == 4 else (entry[1], entry[2], None)
|
|
|
|
| 1063 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1064 |
if limit_err:
|
| 1065 |
await query.message.reply_text(limit_err)
|
|
|
|
| 1080 |
for entry in entries:
|
| 1081 |
user_id = entry[0]
|
| 1082 |
if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
|
|
|
|
| 1083 |
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
| 1084 |
try:
|
| 1085 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
|
|
|
| 1089 |
continue
|
| 1090 |
file_obj = file_msg
|
| 1091 |
expected_size = extract_file_size(file_msg)
|
|
|
|
| 1092 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1093 |
if limit_err:
|
| 1094 |
await query.message.reply_text(limit_err)
|
| 1095 |
continue
|
| 1096 |
+
token2, data = build_duplicate_prompt(
|
| 1097 |
+
user_id, query.message.chat.id, file_obj, filename, expected_size, file_id
|
| 1098 |
+
)
|
| 1099 |
+
if token2:
|
| 1100 |
+
await send_duplicate_prompt(
|
| 1101 |
+
query.message.chat.id, token2, filename, expected_size, data['existing_size']
|
| 1102 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1103 |
continue
|
| 1104 |
else:
|
|
|
|
| 1105 |
file_id, filename, expected_size = entry[1], entry[2], entry[3] if len(entry) == 4 else (entry[1], entry[2], None)
|
| 1106 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1107 |
if limit_err:
|
|
|
|
| 1120 |
|
| 1121 |
|
| 1122 |
# =============================================================================
|
| 1123 |
+
# MESSAGE LINK INTERACTIVE PROMPT (for direct text links)
|
| 1124 |
# =============================================================================
|
| 1125 |
|
| 1126 |
@app.on_message(
|
|
|
|
| 1145 |
if not msg.media:
|
| 1146 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 1147 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1148 |
|
| 1149 |
+
file_id, expected_size, filename = _extract_file_info(msg)
|
| 1150 |
+
if not filename:
|
| 1151 |
+
return await message.reply_text("Could not determine file name.")
|
| 1152 |
+
|
| 1153 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1154 |
if limit_err:
|
| 1155 |
return await message.reply_text(limit_err)
|
| 1156 |
|
| 1157 |
+
token, data = build_duplicate_prompt(
|
| 1158 |
+
message.from_user.id, message.chat.id, file_id, filename, expected_size, file_id
|
| 1159 |
+
)
|
| 1160 |
+
if token:
|
| 1161 |
+
await send_duplicate_prompt(
|
| 1162 |
+
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 1163 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1164 |
return
|
| 1165 |
|
| 1166 |
+
upload_token = make_token()
|
| 1167 |
+
upload_prompt_map[upload_token] = [(message.from_user.id, file_id, filename, expected_size)]
|
| 1168 |
kb = InlineKeyboardMarkup([
|
| 1169 |
+
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],
|
| 1170 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1171 |
])
|
| 1172 |
+
await message.reply_text(f"Found file `{filename}`. Do you want to upload it?", reply_markup=kb)
|
| 1173 |
|
| 1174 |
|
| 1175 |
# =============================================================================
|
|
|
|
| 1181 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 1182 |
)
|
| 1183 |
async def on_direct_file(_, message: Message):
|
| 1184 |
+
file_id, expected_size, filename = _extract_file_info(message)
|
| 1185 |
+
if not filename:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1186 |
return
|
| 1187 |
|
| 1188 |
+
# Album grouping
|
| 1189 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 1190 |
group_id = str(message.media_group_id)
|
| 1191 |
if group_id not in album_groups:
|
|
|
|
| 1206 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1207 |
return
|
| 1208 |
|
| 1209 |
+
# Single file
|
| 1210 |
limit_err = check_file_size_limit(filename, expected_size)
|
| 1211 |
if limit_err:
|
| 1212 |
return await message.reply_text(limit_err)
|
| 1213 |
|
| 1214 |
+
token, data = build_duplicate_prompt(
|
| 1215 |
+
message.from_user.id, message.chat.id, message, filename, expected_size, file_id
|
| 1216 |
+
)
|
| 1217 |
+
if token:
|
| 1218 |
+
await send_duplicate_prompt(
|
| 1219 |
+
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 1220 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1221 |
return
|
| 1222 |
|
| 1223 |
+
upload_token = make_token()
|
| 1224 |
+
upload_prompt_map[upload_token] = [(message.from_user.id, message.id, filename, file_id)]
|
| 1225 |
kb = InlineKeyboardMarkup([
|
| 1226 |
+
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],
|
| 1227 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1228 |
])
|
| 1229 |
await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)
|
|
|
|
| 1249 |
async def main():
|
| 1250 |
asyncio.create_task(upload_worker())
|
| 1251 |
await app.start()
|
| 1252 |
+
logger.info("Bot started successfully (tgcrypto: %s)", "available" if hasattr(app, "tgcrypto") else "missing")
|
| 1253 |
await asyncio.Event().wait()
|
| 1254 |
|
| 1255 |
|