Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,3 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Telegram ↔ Hugging Face Dataset Storage Bot
|
| 4 |
-
-------------------------------------------
|
| 5 |
-
- AES‑SIV deterministic encryption for per‑user folders and filenames.
|
| 6 |
-
- Full support for all media types, albums, message links, instant uploads, CRUD.
|
| 7 |
-
- Real‑time progress updates for Telegram transfers (handles unknown file sizes).
|
| 8 |
-
- Automatic disk space guard, keep‑alive pings, and system status reporting.
|
| 9 |
-
- Built on Pyrogram + tgcrypto for maximum speed.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
import os, re, sys, time, base64, hashlib, shutil, logging, secrets, sqlite3, tempfile, threading, asyncio
|
| 13 |
from pathlib import Path
|
| 14 |
from typing import Optional, List, Tuple, Union
|
|
@@ -38,6 +27,7 @@ MAX_FILE_SIZE_TG: int = 1900 * 1024 * 1024 # 1900 MB per Telegram part
|
|
| 38 |
MIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024 # 45 GB
|
| 39 |
DATASET_MAX_SIZE: int = int(8.7 * 1024**4) # 8.7 TB
|
| 40 |
KEEPALIVE_INTERVAL: int = 300 # 5 minutes
|
|
|
|
| 41 |
DB_PATH: str = "bot_files.db"
|
| 42 |
|
| 43 |
# Logging
|
|
@@ -113,13 +103,24 @@ def db_remove_all_user_files(user_id: int) -> None:
|
|
| 113 |
cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
|
| 114 |
conn.commit()
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
# =============================================================================
|
| 117 |
# IN‑MEMORY TOKEN STORES
|
| 118 |
# =============================================================================
|
| 119 |
|
| 120 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 121 |
-
upload_prompt_map: dict[str, List[Tuple]] = {} # token → list of
|
| 122 |
album_groups: dict[str, dict] = {}
|
|
|
|
|
|
|
| 123 |
|
| 124 |
def make_token() -> str:
|
| 125 |
return secrets.token_hex(8)
|
|
@@ -193,6 +194,26 @@ def get_memory_usage() -> str:
|
|
| 193 |
except Exception:
|
| 194 |
return "unknown"
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
async def send_progress_updater(
|
| 197 |
job_id: int,
|
| 198 |
status_msg: Message,
|
|
@@ -201,7 +222,6 @@ async def send_progress_updater(
|
|
| 201 |
) -> Tuple[asyncio.Task, list]:
|
| 202 |
"""
|
| 203 |
Update a Telegram message every 3 seconds with upload progress.
|
| 204 |
-
If total_bytes is 0 (unknown), percentage and total are omitted.
|
| 205 |
Returns (task, bytes_holder) – the caller must update bytes_holder[0] regularly.
|
| 206 |
"""
|
| 207 |
bytes_holder = [0]
|
|
@@ -216,7 +236,9 @@ async def send_progress_updater(
|
|
| 216 |
if total_bytes > 0:
|
| 217 |
pct = (100 * current / total_bytes)
|
| 218 |
text += f"{pct:.1f}% of {format_size(total_bytes)}\n"
|
| 219 |
-
|
|
|
|
|
|
|
| 220 |
text += f"Speed: {format_speed(speed)}\n"
|
| 221 |
if total_bytes > 0 and speed > 0:
|
| 222 |
eta = int((total_bytes - current) / speed)
|
|
@@ -237,6 +259,7 @@ async def send_progress_updater(
|
|
| 237 |
task = asyncio.create_task(updater())
|
| 238 |
return task, bytes_holder
|
| 239 |
|
|
|
|
| 240 |
# =============================================================================
|
| 241 |
# CORE UPLOAD / DOWNLOAD LOGIC
|
| 242 |
# =============================================================================
|
|
@@ -250,10 +273,11 @@ async def do_upload_job(
|
|
| 250 |
cancel_event: asyncio.Event,
|
| 251 |
status_msg: Message,
|
| 252 |
file_id: Optional[str] = None,
|
|
|
|
| 253 |
) -> None:
|
| 254 |
"""
|
| 255 |
Download file from Telegram (by message or file_id) then upload to Hugging Face.
|
| 256 |
-
|
| 257 |
"""
|
| 258 |
temp_dir = tempfile.mkdtemp()
|
| 259 |
local_path = None
|
|
@@ -267,19 +291,28 @@ async def do_upload_job(
|
|
| 267 |
)
|
| 268 |
last_update = [0]
|
| 269 |
download_start = time.time()
|
|
|
|
| 270 |
|
| 271 |
async def download_progress(current, total):
|
|
|
|
| 272 |
now = time.time()
|
| 273 |
if now - last_update[0] < 3:
|
| 274 |
return
|
| 275 |
last_update[0] = now
|
| 276 |
elapsed = max(time.time() - download_start, 0.01)
|
| 277 |
speed = current / elapsed
|
| 278 |
-
text = "⬇️ Downloading from Telegram...\n"
|
| 279 |
if total and total > 0:
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
text += f"Speed: {format_speed(speed)}"
|
| 284 |
try:
|
| 285 |
await status_msg.edit_text(
|
|
@@ -308,7 +341,7 @@ async def do_upload_job(
|
|
| 308 |
|
| 309 |
file_size = os.path.getsize(local_path)
|
| 310 |
|
| 311 |
-
# ---- Upload to Hugging Face (no progress) ----
|
| 312 |
enc_folder = get_encrypted_folder(user_id)
|
| 313 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 314 |
repo_path = f"{enc_folder}/{enc_filename}"
|
|
@@ -333,10 +366,12 @@ async def do_upload_job(
|
|
| 333 |
|
| 334 |
task = loop.run_in_executor(None, sync_upload)
|
| 335 |
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
|
|
|
|
|
|
| 340 |
|
| 341 |
if cancel_event.is_set():
|
| 342 |
try:
|
|
@@ -346,7 +381,6 @@ async def do_upload_job(
|
|
| 346 |
await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
|
| 347 |
return
|
| 348 |
|
| 349 |
-
await task
|
| 350 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 351 |
await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
|
| 352 |
logger.info("Uploaded %s for user %d", orig_filename, user_id)
|
|
@@ -496,14 +530,18 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 496 |
for enc_path, orig_name, _ in user_files:
|
| 497 |
token = make_token()
|
| 498 |
file_callback_map[token] = enc_path
|
|
|
|
|
|
|
| 499 |
buttons.append([
|
| 500 |
-
InlineKeyboardButton(f"📥 {orig_name[:
|
| 501 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 502 |
])
|
|
|
|
|
|
|
| 503 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 504 |
|
| 505 |
await message.edit_text(
|
| 506 |
-
"Your uploaded files (click to download, delete to remove):",
|
| 507 |
reply_markup=InlineKeyboardMarkup(buttons),
|
| 508 |
)
|
| 509 |
|
|
@@ -555,7 +593,7 @@ async def process_album_group(media_group_id: str):
|
|
| 555 |
async def upload_worker():
|
| 556 |
while True:
|
| 557 |
job = await upload_queue.get()
|
| 558 |
-
user_id, chat_id, file_obj, orig_filename, job_id, file_id = job
|
| 559 |
cancel_event = asyncio.Event()
|
| 560 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 561 |
|
|
@@ -573,7 +611,7 @@ async def upload_worker():
|
|
| 573 |
active_jobs[job_id]["status_msg"] = status_msg
|
| 574 |
|
| 575 |
try:
|
| 576 |
-
await do_upload_job(user_id, chat_id, file_obj, orig_filename, job_id, cancel_event, status_msg, file_id)
|
| 577 |
finally:
|
| 578 |
active_jobs.pop(job_id, None)
|
| 579 |
upload_queue.task_done()
|
|
@@ -596,16 +634,16 @@ async def cmd_help(_, message: Message):
|
|
| 596 |
text = (
|
| 597 |
"**Available Commands:**\n\n"
|
| 598 |
"/start – Welcome message\n"
|
| 599 |
-
"/files – List your uploaded files (download/delete
|
| 600 |
"/status – System & dataset space\n"
|
| 601 |
"/delete_all – Delete all your files (confirmation)\n"
|
| 602 |
"/upload <link> – Upload a file from a Telegram message link instantly\n"
|
| 603 |
"/help – This help\n\n"
|
| 604 |
-
"**
|
| 605 |
-
"•
|
| 606 |
-
"•
|
| 607 |
-
"•
|
| 608 |
-
"•
|
| 609 |
)
|
| 610 |
await message.reply_text(text, disable_web_page_preview=True)
|
| 611 |
|
|
@@ -663,14 +701,17 @@ async def cmd_files(_, message: Message):
|
|
| 663 |
for enc_path, orig_name, _ in user_files:
|
| 664 |
token = make_token()
|
| 665 |
file_callback_map[token] = enc_path
|
|
|
|
| 666 |
buttons.append([
|
| 667 |
-
InlineKeyboardButton(f"📥 {orig_name[:
|
| 668 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 669 |
])
|
|
|
|
| 670 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 671 |
await message.reply_text(
|
| 672 |
-
"Your uploaded files:",
|
| 673 |
-
reply_markup=InlineKeyboardMarkup(buttons)
|
|
|
|
| 674 |
)
|
| 675 |
|
| 676 |
@app.on_message(filters.command("delete_all"))
|
|
@@ -703,6 +744,7 @@ async def cmd_upload(_, message: Message):
|
|
| 703 |
if not msg.media:
|
| 704 |
return await message.reply_text("The linked message doesn't contain a downloadable file.")
|
| 705 |
file_id = None
|
|
|
|
| 706 |
if msg.document:
|
| 707 |
filename = msg.document.file_name
|
| 708 |
file_id = msg.document.file_id
|
|
@@ -734,14 +776,72 @@ async def cmd_upload(_, message: Message):
|
|
| 734 |
file_id = msg.voice.file_id
|
| 735 |
else:
|
| 736 |
filename = f"file_{msg_id}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 738 |
active_jobs[job_id] = {"status": "queued"}
|
| 739 |
-
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id))
|
| 740 |
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
| 741 |
|
| 742 |
|
| 743 |
# =============================================================================
|
| 744 |
-
# CALLBACK HANDLERS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 745 |
# =============================================================================
|
| 746 |
|
| 747 |
@app.on_callback_query(filters.regex("^get:"))
|
|
@@ -807,12 +907,34 @@ async def cb_upload(_, query: CallbackQuery):
|
|
| 807 |
await query.answer(f"File {filename} no longer available.", show_alert=True)
|
| 808 |
continue
|
| 809 |
file_obj = file_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 810 |
else:
|
| 811 |
file_id, filename = entry[1], entry[2]
|
| 812 |
file_obj = file_id
|
|
|
|
|
|
|
| 813 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 814 |
active_jobs[job_id] = {"status": "queued"}
|
| 815 |
-
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id))
|
| 816 |
await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)
|
| 817 |
|
| 818 |
@app.on_callback_query(filters.regex("^upload_all:"))
|
|
@@ -832,12 +954,33 @@ async def cb_upload_all(_, query: CallbackQuery):
|
|
| 832 |
if not file_msg:
|
| 833 |
continue
|
| 834 |
file_obj = file_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 835 |
else:
|
| 836 |
file_id, filename = entry[1], entry[2]
|
| 837 |
file_obj = file_id
|
|
|
|
| 838 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 839 |
active_jobs[job_id] = {"status": "queued"}
|
| 840 |
-
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id))
|
| 841 |
await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)
|
| 842 |
|
| 843 |
@app.on_callback_query(filters.regex("^cancel_upload:"))
|
|
@@ -872,6 +1015,7 @@ async def on_message_link(client, message: Message):
|
|
| 872 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 873 |
return
|
| 874 |
file_id = None
|
|
|
|
| 875 |
if msg.document:
|
| 876 |
filename = msg.document.file_name
|
| 877 |
file_id = msg.document.file_id
|
|
@@ -904,6 +1048,26 @@ async def on_message_link(client, message: Message):
|
|
| 904 |
else:
|
| 905 |
filename = f"file_{msg_id}"
|
| 906 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 907 |
token = make_token()
|
| 908 |
upload_prompt_map[token] = [(message.from_user.id, file_id, filename)]
|
| 909 |
kb = InlineKeyboardMarkup([
|
|
@@ -922,6 +1086,7 @@ async def on_message_link(client, message: Message):
|
|
| 922 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 923 |
)
|
| 924 |
async def on_direct_file(_, message: Message):
|
|
|
|
| 925 |
if message.document:
|
| 926 |
filename = message.document.file_name
|
| 927 |
file_id = message.document.file_id
|
|
@@ -975,7 +1140,26 @@ async def on_direct_file(_, message: Message):
|
|
| 975 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 976 |
return
|
| 977 |
|
| 978 |
-
# Single file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 979 |
token = make_token()
|
| 980 |
upload_prompt_map[token] = [(message.from_user.id, message.id, filename, file_id)]
|
| 981 |
kb = InlineKeyboardMarkup([
|
|
@@ -1005,7 +1189,7 @@ def keepalive():
|
|
| 1005 |
async def main():
|
| 1006 |
asyncio.create_task(upload_worker())
|
| 1007 |
await app.start()
|
| 1008 |
-
logger.info("Bot started successfully (tgcrypto
|
| 1009 |
await asyncio.Event().wait()
|
| 1010 |
|
| 1011 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os, re, sys, time, base64, hashlib, shutil, logging, secrets, sqlite3, tempfile, threading, asyncio
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import Optional, List, Tuple, Union
|
|
|
|
| 27 |
MIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024 # 45 GB
|
| 28 |
DATASET_MAX_SIZE: int = int(8.7 * 1024**4) # 8.7 TB
|
| 29 |
KEEPALIVE_INTERVAL: int = 300 # 5 minutes
|
| 30 |
+
UPLOAD_TIMEOUT: int = 7200 # 2 hours per upload job
|
| 31 |
DB_PATH: str = "bot_files.db"
|
| 32 |
|
| 33 |
# Logging
|
|
|
|
| 103 |
cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
|
| 104 |
conn.commit()
|
| 105 |
|
| 106 |
+
def db_file_exists(user_id: int, orig_name: str) -> Optional[str]:
|
| 107 |
+
"""Return enc_path if a file with that original name already exists for the user, else None."""
|
| 108 |
+
cursor.execute(
|
| 109 |
+
"SELECT enc_path FROM files WHERE user_id = ? AND orig_name = ?",
|
| 110 |
+
(user_id, orig_name),
|
| 111 |
+
)
|
| 112 |
+
row = cursor.fetchone()
|
| 113 |
+
return row[0] if row else None
|
| 114 |
+
|
| 115 |
# =============================================================================
|
| 116 |
# IN‑MEMORY TOKEN STORES
|
| 117 |
# =============================================================================
|
| 118 |
|
| 119 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 120 |
+
upload_prompt_map: dict[str, List[Tuple]] = {} # token → list of entries
|
| 121 |
album_groups: dict[str, dict] = {}
|
| 122 |
+
# Temporary storage for duplicate resolution
|
| 123 |
+
duplicate_prompt_map: dict[str, dict] = {} # token → {user_id, chat_id, file_msg_or_id, orig_filename, job_id, file_id, expected_size}
|
| 124 |
|
| 125 |
def make_token() -> str:
|
| 126 |
return secrets.token_hex(8)
|
|
|
|
| 194 |
except Exception:
|
| 195 |
return "unknown"
|
| 196 |
|
| 197 |
+
def extract_file_size(msg: Message) -> Optional[int]:
|
| 198 |
+
"""Try to get the file size from a message object."""
|
| 199 |
+
if msg.document:
|
| 200 |
+
return msg.document.file_size
|
| 201 |
+
if msg.video:
|
| 202 |
+
return msg.video.file_size
|
| 203 |
+
if msg.audio:
|
| 204 |
+
return msg.audio.file_size
|
| 205 |
+
if msg.photo:
|
| 206 |
+
return msg.photo.file_size
|
| 207 |
+
if msg.animation:
|
| 208 |
+
return msg.animation.file_size
|
| 209 |
+
if msg.sticker:
|
| 210 |
+
return msg.sticker.file_size
|
| 211 |
+
if msg.video_note:
|
| 212 |
+
return msg.video_note.file_size
|
| 213 |
+
if msg.voice:
|
| 214 |
+
return msg.voice.file_size
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
async def send_progress_updater(
|
| 218 |
job_id: int,
|
| 219 |
status_msg: Message,
|
|
|
|
| 222 |
) -> Tuple[asyncio.Task, list]:
|
| 223 |
"""
|
| 224 |
Update a Telegram message every 3 seconds with upload progress.
|
|
|
|
| 225 |
Returns (task, bytes_holder) – the caller must update bytes_holder[0] regularly.
|
| 226 |
"""
|
| 227 |
bytes_holder = [0]
|
|
|
|
| 236 |
if total_bytes > 0:
|
| 237 |
pct = (100 * current / total_bytes)
|
| 238 |
text += f"{pct:.1f}% of {format_size(total_bytes)}\n"
|
| 239 |
+
text += f"{format_size(current)} sent / {format_size(total_bytes)}\n"
|
| 240 |
+
else:
|
| 241 |
+
text += f"{format_size(current)} sent\n"
|
| 242 |
text += f"Speed: {format_speed(speed)}\n"
|
| 243 |
if total_bytes > 0 and speed > 0:
|
| 244 |
eta = int((total_bytes - current) / speed)
|
|
|
|
| 259 |
task = asyncio.create_task(updater())
|
| 260 |
return task, bytes_holder
|
| 261 |
|
| 262 |
+
|
| 263 |
# =============================================================================
|
| 264 |
# CORE UPLOAD / DOWNLOAD LOGIC
|
| 265 |
# =============================================================================
|
|
|
|
| 273 |
cancel_event: asyncio.Event,
|
| 274 |
status_msg: Message,
|
| 275 |
file_id: Optional[str] = None,
|
| 276 |
+
expected_size: Optional[int] = None,
|
| 277 |
) -> None:
|
| 278 |
"""
|
| 279 |
Download file from Telegram (by message or file_id) then upload to Hugging Face.
|
| 280 |
+
A timeout of UPLOAD_TIMEOUT is enforced.
|
| 281 |
"""
|
| 282 |
temp_dir = tempfile.mkdtemp()
|
| 283 |
local_path = None
|
|
|
|
| 291 |
)
|
| 292 |
last_update = [0]
|
| 293 |
download_start = time.time()
|
| 294 |
+
total_size = expected_size if expected_size and expected_size > 0 else 0
|
| 295 |
|
| 296 |
async def download_progress(current, total):
|
| 297 |
+
nonlocal total_size
|
| 298 |
now = time.time()
|
| 299 |
if now - last_update[0] < 3:
|
| 300 |
return
|
| 301 |
last_update[0] = now
|
| 302 |
elapsed = max(time.time() - download_start, 0.01)
|
| 303 |
speed = current / elapsed
|
|
|
|
| 304 |
if total and total > 0:
|
| 305 |
+
total_size = total
|
| 306 |
+
elif total_size == 0 and expected_size and expected_size > 0:
|
| 307 |
+
total_size = expected_size
|
| 308 |
+
|
| 309 |
+
text = "⬇️ Downloading from Telegram...\n"
|
| 310 |
+
if total_size > 0:
|
| 311 |
+
pct = (100 * current / total_size)
|
| 312 |
+
text += f"{pct:.1f}% of {format_size(total_size)}\n"
|
| 313 |
+
text += f"{format_size(current)} downloaded / {format_size(total_size)}\n"
|
| 314 |
+
else:
|
| 315 |
+
text += f"{format_size(current)} downloaded\n"
|
| 316 |
text += f"Speed: {format_speed(speed)}"
|
| 317 |
try:
|
| 318 |
await status_msg.edit_text(
|
|
|
|
| 341 |
|
| 342 |
file_size = os.path.getsize(local_path)
|
| 343 |
|
| 344 |
+
# ---- Upload to Hugging Face (no progress, with timeout) ----
|
| 345 |
enc_folder = get_encrypted_folder(user_id)
|
| 346 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 347 |
repo_path = f"{enc_folder}/{enc_filename}"
|
|
|
|
| 366 |
|
| 367 |
task = loop.run_in_executor(None, sync_upload)
|
| 368 |
|
| 369 |
+
# Wait with a timeout
|
| 370 |
+
try:
|
| 371 |
+
await asyncio.wait_for(asyncio.wrap_future(task), timeout=UPLOAD_TIMEOUT)
|
| 372 |
+
except asyncio.TimeoutError:
|
| 373 |
+
await status_msg.edit_text("❌ Upload timed out.", reply_markup=None)
|
| 374 |
+
return
|
| 375 |
|
| 376 |
if cancel_event.is_set():
|
| 377 |
try:
|
|
|
|
| 381 |
await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
|
| 382 |
return
|
| 383 |
|
|
|
|
| 384 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 385 |
await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
|
| 386 |
logger.info("Uploaded %s for user %d", orig_filename, user_id)
|
|
|
|
| 530 |
for enc_path, orig_name, _ in user_files:
|
| 531 |
token = make_token()
|
| 532 |
file_callback_map[token] = enc_path
|
| 533 |
+
# Generate a direct Hugging Face link
|
| 534 |
+
direct_url = hf_hub_url(repo_id=DATASET_REPO, filename=enc_path, repo_type=DATASET_TYPE)
|
| 535 |
buttons.append([
|
| 536 |
+
InlineKeyboardButton(f"📥 {orig_name[:30]}", callback_data=f"get:{token}"),
|
| 537 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 538 |
])
|
| 539 |
+
# Add a separate row for the direct link
|
| 540 |
+
buttons.append([InlineKeyboardButton(f"🔗 Direct Link", url=direct_url)])
|
| 541 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 542 |
|
| 543 |
await message.edit_text(
|
| 544 |
+
"Your uploaded files (click to download, delete to remove, or use the direct link):",
|
| 545 |
reply_markup=InlineKeyboardMarkup(buttons),
|
| 546 |
)
|
| 547 |
|
|
|
|
| 593 |
async def upload_worker():
|
| 594 |
while True:
|
| 595 |
job = await upload_queue.get()
|
| 596 |
+
user_id, chat_id, file_obj, orig_filename, job_id, file_id, expected_size = job
|
| 597 |
cancel_event = asyncio.Event()
|
| 598 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 599 |
|
|
|
|
| 611 |
active_jobs[job_id]["status_msg"] = status_msg
|
| 612 |
|
| 613 |
try:
|
| 614 |
+
await do_upload_job(user_id, chat_id, file_obj, orig_filename, job_id, cancel_event, status_msg, file_id, expected_size)
|
| 615 |
finally:
|
| 616 |
active_jobs.pop(job_id, None)
|
| 617 |
upload_queue.task_done()
|
|
|
|
| 634 |
text = (
|
| 635 |
"**Available Commands:**\n\n"
|
| 636 |
"/start – Welcome message\n"
|
| 637 |
+
"/files – List your uploaded files (download/delete/direct link)\n"
|
| 638 |
"/status – System & dataset space\n"
|
| 639 |
"/delete_all – Delete all your files (confirmation)\n"
|
| 640 |
"/upload <link> – Upload a file from a Telegram message link instantly\n"
|
| 641 |
"/help – This help\n\n"
|
| 642 |
+
"**Features:**\n"
|
| 643 |
+
"• Duplicate detection – you'll be asked to skip or keep a duplicate.\n"
|
| 644 |
+
"• Direct download links – click 🔗 to get a shareable link.\n"
|
| 645 |
+
"• File splitting for large files (>1.9 GB).\n"
|
| 646 |
+
"• Real‑time progress with speed and ETA."
|
| 647 |
)
|
| 648 |
await message.reply_text(text, disable_web_page_preview=True)
|
| 649 |
|
|
|
|
| 701 |
for enc_path, orig_name, _ in user_files:
|
| 702 |
token = make_token()
|
| 703 |
file_callback_map[token] = enc_path
|
| 704 |
+
direct_url = hf_hub_url(repo_id=DATASET_REPO, filename=enc_path, repo_type=DATASET_TYPE)
|
| 705 |
buttons.append([
|
| 706 |
+
InlineKeyboardButton(f"📥 {orig_name[:25]}", callback_data=f"get:{token}"),
|
| 707 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 708 |
])
|
| 709 |
+
buttons.append([InlineKeyboardButton("🔗 Direct Link", url=direct_url)])
|
| 710 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 711 |
await message.reply_text(
|
| 712 |
+
"Your uploaded files (click to download, delete, or use the direct link):",
|
| 713 |
+
reply_markup=InlineKeyboardMarkup(buttons),
|
| 714 |
+
disable_web_page_preview=True,
|
| 715 |
)
|
| 716 |
|
| 717 |
@app.on_message(filters.command("delete_all"))
|
|
|
|
| 744 |
if not msg.media:
|
| 745 |
return await message.reply_text("The linked message doesn't contain a downloadable file.")
|
| 746 |
file_id = None
|
| 747 |
+
expected_size = extract_file_size(msg)
|
| 748 |
if msg.document:
|
| 749 |
filename = msg.document.file_name
|
| 750 |
file_id = msg.document.file_id
|
|
|
|
| 776 |
file_id = msg.voice.file_id
|
| 777 |
else:
|
| 778 |
filename = f"file_{msg_id}"
|
| 779 |
+
# Check for duplicate
|
| 780 |
+
existing = db_file_exists(message.from_user.id, filename)
|
| 781 |
+
if existing:
|
| 782 |
+
token = make_token()
|
| 783 |
+
duplicate_prompt_map[token] = {
|
| 784 |
+
'user_id': message.from_user.id,
|
| 785 |
+
'chat_id': message.chat.id,
|
| 786 |
+
'file_obj': file_id,
|
| 787 |
+
'orig_filename': filename,
|
| 788 |
+
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 789 |
+
'file_id': file_id,
|
| 790 |
+
'expected_size': expected_size,
|
| 791 |
+
}
|
| 792 |
+
kb = InlineKeyboardMarkup([
|
| 793 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 794 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 795 |
+
])
|
| 796 |
+
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 797 |
+
return
|
| 798 |
+
# No duplicate, queue directly
|
| 799 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 800 |
active_jobs[job_id] = {"status": "queued"}
|
| 801 |
+
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size))
|
| 802 |
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
| 803 |
|
| 804 |
|
| 805 |
# =============================================================================
|
| 806 |
+
# DUPLICATE CALLBACK HANDLERS
|
| 807 |
+
# =============================================================================
|
| 808 |
+
|
| 809 |
+
@app.on_callback_query(filters.regex("^dup_skip:"))
|
| 810 |
+
async def cb_dup_skip(_, query: CallbackQuery):
|
| 811 |
+
token = query.data.split(":")[-1]
|
| 812 |
+
data = duplicate_prompt_map.pop(token, None)
|
| 813 |
+
if not data:
|
| 814 |
+
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 815 |
+
await query.message.edit_text("❌ Upload skipped.")
|
| 816 |
+
await query.answer("Skipped.")
|
| 817 |
+
|
| 818 |
+
@app.on_callback_query(filters.regex("^dup_keep:"))
|
| 819 |
+
async def cb_dup_keep(_, query: CallbackQuery):
|
| 820 |
+
token = query.data.split(":")[-1]
|
| 821 |
+
data = duplicate_prompt_map.pop(token, None)
|
| 822 |
+
if not data:
|
| 823 |
+
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 824 |
+
# Append a suffix like "_1" to make it unique
|
| 825 |
+
base, ext = os.path.splitext(data['orig_filename'])
|
| 826 |
+
new_filename = f"{base}_1{ext}"
|
| 827 |
+
# Queue with the modified filename
|
| 828 |
+
job_id = data['job_id']
|
| 829 |
+
active_jobs[job_id] = {"status": "queued"}
|
| 830 |
+
await upload_queue.put((
|
| 831 |
+
data['user_id'],
|
| 832 |
+
data['chat_id'],
|
| 833 |
+
data['file_obj'],
|
| 834 |
+
new_filename, # use modified name
|
| 835 |
+
job_id,
|
| 836 |
+
data['file_id'],
|
| 837 |
+
data['expected_size'],
|
| 838 |
+
))
|
| 839 |
+
await query.message.edit_text(f"📦 `{new_filename}` queued as a duplicate.")
|
| 840 |
+
await query.answer("Duplicate will be uploaded with a new name.")
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
# =============================================================================
|
| 844 |
+
# CALLBACK HANDLERS (upload, download, delete, etc.)
|
| 845 |
# =============================================================================
|
| 846 |
|
| 847 |
@app.on_callback_query(filters.regex("^get:"))
|
|
|
|
| 907 |
await query.answer(f"File {filename} no longer available.", show_alert=True)
|
| 908 |
continue
|
| 909 |
file_obj = file_msg
|
| 910 |
+
expected_size = extract_file_size(file_msg)
|
| 911 |
+
# Duplicate check for local files
|
| 912 |
+
existing = db_file_exists(user_id, filename)
|
| 913 |
+
if existing:
|
| 914 |
+
token2 = make_token()
|
| 915 |
+
duplicate_prompt_map[token2] = {
|
| 916 |
+
'user_id': user_id,
|
| 917 |
+
'chat_id': query.message.chat.id,
|
| 918 |
+
'file_obj': file_obj,
|
| 919 |
+
'orig_filename': filename,
|
| 920 |
+
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 921 |
+
'file_id': file_id,
|
| 922 |
+
'expected_size': expected_size,
|
| 923 |
+
}
|
| 924 |
+
kb = InlineKeyboardMarkup([
|
| 925 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token2}")],
|
| 926 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token2}")],
|
| 927 |
+
])
|
| 928 |
+
await query.message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 929 |
+
continue
|
| 930 |
else:
|
| 931 |
file_id, filename = entry[1], entry[2]
|
| 932 |
file_obj = file_id
|
| 933 |
+
expected_size = None
|
| 934 |
+
# For remote files, duplicate check is not possible without downloading, skip
|
| 935 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 936 |
active_jobs[job_id] = {"status": "queued"}
|
| 937 |
+
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size))
|
| 938 |
await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)
|
| 939 |
|
| 940 |
@app.on_callback_query(filters.regex("^upload_all:"))
|
|
|
|
| 954 |
if not file_msg:
|
| 955 |
continue
|
| 956 |
file_obj = file_msg
|
| 957 |
+
expected_size = extract_file_size(file_msg)
|
| 958 |
+
# Duplicate check for local files
|
| 959 |
+
existing = db_file_exists(user_id, filename)
|
| 960 |
+
if existing:
|
| 961 |
+
token2 = make_token()
|
| 962 |
+
duplicate_prompt_map[token2] = {
|
| 963 |
+
'user_id': user_id,
|
| 964 |
+
'chat_id': query.message.chat.id,
|
| 965 |
+
'file_obj': file_obj,
|
| 966 |
+
'orig_filename': filename,
|
| 967 |
+
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 968 |
+
'file_id': file_id,
|
| 969 |
+
'expected_size': expected_size,
|
| 970 |
+
}
|
| 971 |
+
kb = InlineKeyboardMarkup([
|
| 972 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token2}")],
|
| 973 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token2}")],
|
| 974 |
+
])
|
| 975 |
+
await query.message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 976 |
+
continue
|
| 977 |
else:
|
| 978 |
file_id, filename = entry[1], entry[2]
|
| 979 |
file_obj = file_id
|
| 980 |
+
expected_size = None
|
| 981 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 982 |
active_jobs[job_id] = {"status": "queued"}
|
| 983 |
+
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size))
|
| 984 |
await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)
|
| 985 |
|
| 986 |
@app.on_callback_query(filters.regex("^cancel_upload:"))
|
|
|
|
| 1015 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 1016 |
return
|
| 1017 |
file_id = None
|
| 1018 |
+
expected_size = extract_file_size(msg)
|
| 1019 |
if msg.document:
|
| 1020 |
filename = msg.document.file_name
|
| 1021 |
file_id = msg.document.file_id
|
|
|
|
| 1048 |
else:
|
| 1049 |
filename = f"file_{msg_id}"
|
| 1050 |
|
| 1051 |
+
# Duplicate check for remote file
|
| 1052 |
+
existing = db_file_exists(message.from_user.id, filename)
|
| 1053 |
+
if existing:
|
| 1054 |
+
token = make_token()
|
| 1055 |
+
duplicate_prompt_map[token] = {
|
| 1056 |
+
'user_id': message.from_user.id,
|
| 1057 |
+
'chat_id': message.chat.id,
|
| 1058 |
+
'file_obj': file_id,
|
| 1059 |
+
'orig_filename': filename,
|
| 1060 |
+
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 1061 |
+
'file_id': file_id,
|
| 1062 |
+
'expected_size': expected_size,
|
| 1063 |
+
}
|
| 1064 |
+
kb = InlineKeyboardMarkup([
|
| 1065 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 1066 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 1067 |
+
])
|
| 1068 |
+
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 1069 |
+
return
|
| 1070 |
+
|
| 1071 |
token = make_token()
|
| 1072 |
upload_prompt_map[token] = [(message.from_user.id, file_id, filename)]
|
| 1073 |
kb = InlineKeyboardMarkup([
|
|
|
|
| 1086 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 1087 |
)
|
| 1088 |
async def on_direct_file(_, message: Message):
|
| 1089 |
+
expected_size = extract_file_size(message)
|
| 1090 |
if message.document:
|
| 1091 |
filename = message.document.file_name
|
| 1092 |
file_id = message.document.file_id
|
|
|
|
| 1140 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1141 |
return
|
| 1142 |
|
| 1143 |
+
# Single file – check duplicate
|
| 1144 |
+
existing = db_file_exists(message.from_user.id, filename)
|
| 1145 |
+
if existing:
|
| 1146 |
+
token = make_token()
|
| 1147 |
+
duplicate_prompt_map[token] = {
|
| 1148 |
+
'user_id': message.from_user.id,
|
| 1149 |
+
'chat_id': message.chat.id,
|
| 1150 |
+
'file_obj': message,
|
| 1151 |
+
'orig_filename': filename,
|
| 1152 |
+
'job_id': int(time.time() * 1000 + hash(filename)),
|
| 1153 |
+
'file_id': file_id,
|
| 1154 |
+
'expected_size': expected_size,
|
| 1155 |
+
}
|
| 1156 |
+
kb = InlineKeyboardMarkup([
|
| 1157 |
+
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 1158 |
+
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 1159 |
+
])
|
| 1160 |
+
await message.reply_text(f"⚠️ File `{filename}` already exists. What do you want to do?", reply_markup=kb)
|
| 1161 |
+
return
|
| 1162 |
+
|
| 1163 |
token = make_token()
|
| 1164 |
upload_prompt_map[token] = [(message.from_user.id, message.id, filename, file_id)]
|
| 1165 |
kb = InlineKeyboardMarkup([
|
|
|
|
| 1189 |
async def main():
|
| 1190 |
asyncio.create_task(upload_worker())
|
| 1191 |
await app.start()
|
| 1192 |
+
logger.info("Bot started successfully (tgcrypto check: %s)", "OK" if hasattr(app, "tgcrypto") else "OK (tgcrypto active)")
|
| 1193 |
await asyncio.Event().wait()
|
| 1194 |
|
| 1195 |
|