Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,23 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
import threading
|
| 13 |
-
import asyncio
|
| 14 |
from pathlib import Path
|
| 15 |
from typing import Optional, List, Tuple, Union
|
| 16 |
|
| 17 |
import requests
|
| 18 |
from flask import Flask
|
| 19 |
from pyrogram import Client, filters
|
| 20 |
-
from pyrogram.types import
|
| 21 |
-
|
| 22 |
-
InlineKeyboardButton,
|
| 23 |
-
Message,
|
| 24 |
-
CallbackQuery,
|
| 25 |
-
)
|
| 26 |
-
from huggingface_hub import (
|
| 27 |
-
HfApi,
|
| 28 |
-
get_hf_file_metadata,
|
| 29 |
-
hf_hub_download,
|
| 30 |
-
hf_hub_url,
|
| 31 |
-
)
|
| 32 |
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
|
| 33 |
|
| 34 |
# =============================================================================
|
|
@@ -41,15 +30,14 @@ BOT_TOKEN: str = os.environ["BOT_TOKEN"]
|
|
| 41 |
HF_TOKEN: str = os.environ["HF_TOKEN"]
|
| 42 |
OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
|
| 43 |
|
| 44 |
-
|
| 45 |
-
SPACE_HOST: str = "https://cxops-push.hf.space"
|
| 46 |
|
| 47 |
DATASET_REPO: str = "Cxops/Bzxv"
|
| 48 |
DATASET_TYPE: str = "dataset"
|
| 49 |
-
MAX_FILE_SIZE_TG: int = 1900 * 1024 * 1024
|
| 50 |
-
MIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024
|
| 51 |
-
DATASET_MAX_SIZE: int = int(8.7 * 1024**4)
|
| 52 |
-
KEEPALIVE_INTERVAL: int = 300
|
| 53 |
DB_PATH: str = "bot_files.db"
|
| 54 |
|
| 55 |
# Logging
|
|
@@ -67,40 +55,32 @@ logger = logging.getLogger("StorageBot")
|
|
| 67 |
_siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
|
| 68 |
_aes_siv = AESSIV(_siv_key)
|
| 69 |
|
| 70 |
-
|
| 71 |
def encrypt_text(plain: str) -> str:
|
| 72 |
-
"""Return URL‑safe base64 (no padding) deterministic ciphertext."""
|
| 73 |
token = _aes_siv.encrypt(plain.encode(), None)
|
| 74 |
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 75 |
|
| 76 |
-
|
| 77 |
def decrypt_text(encoded: str) -> str:
|
| 78 |
-
"""Recover original string from URL‑safe base64 (with or without padding)."""
|
| 79 |
padding = 4 - len(encoded) % 4
|
| 80 |
if padding != 4:
|
| 81 |
encoded += "=" * padding
|
| 82 |
token = base64.urlsafe_b64decode(encoded.encode())
|
| 83 |
return _aes_siv.decrypt(token, None).decode()
|
| 84 |
|
| 85 |
-
|
| 86 |
def get_encrypted_folder(user_id: int) -> str:
|
| 87 |
return encrypt_text(str(user_id))
|
| 88 |
|
| 89 |
-
|
| 90 |
def get_encrypted_filename(original: str) -> str:
|
| 91 |
return encrypt_text(original)
|
| 92 |
|
| 93 |
-
|
| 94 |
# =============================================================================
|
| 95 |
-
# DATABASE
|
| 96 |
# =============================================================================
|
| 97 |
|
| 98 |
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 99 |
conn.row_factory = sqlite3.Row
|
| 100 |
conn.execute("PRAGMA journal_mode=WAL")
|
| 101 |
cursor = conn.cursor()
|
| 102 |
-
cursor.execute(
|
| 103 |
-
"""
|
| 104 |
CREATE TABLE IF NOT EXISTS files (
|
| 105 |
user_id INTEGER,
|
| 106 |
enc_path TEXT UNIQUE,
|
|
@@ -108,11 +88,9 @@ cursor.execute(
|
|
| 108 |
size INTEGER,
|
| 109 |
timestamp REAL
|
| 110 |
)
|
| 111 |
-
|
| 112 |
-
)
|
| 113 |
conn.commit()
|
| 114 |
|
| 115 |
-
|
| 116 |
def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
|
| 117 |
cursor.execute(
|
| 118 |
"INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",
|
|
@@ -120,7 +98,6 @@ def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
|
|
| 120 |
)
|
| 121 |
conn.commit()
|
| 122 |
|
| 123 |
-
|
| 124 |
def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
|
| 125 |
cursor.execute(
|
| 126 |
"SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC",
|
|
@@ -128,53 +105,40 @@ def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
|
|
| 128 |
)
|
| 129 |
return [(row[0], row[1], row[2]) for row in cursor.fetchall()]
|
| 130 |
|
| 131 |
-
|
| 132 |
def db_remove_file(enc_path: str) -> None:
|
| 133 |
cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
|
| 134 |
conn.commit()
|
| 135 |
|
| 136 |
-
|
| 137 |
def db_remove_all_user_files(user_id: int) -> None:
|
| 138 |
cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
|
| 139 |
conn.commit()
|
| 140 |
|
| 141 |
-
|
| 142 |
# =============================================================================
|
| 143 |
-
#
|
| 144 |
# =============================================================================
|
| 145 |
|
| 146 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 147 |
-
#
|
| 148 |
-
# Local: (user_id, msg_id, filename, file_id)
|
| 149 |
-
# Remote: (user_id, file_id, filename)
|
| 150 |
-
upload_prompt_map: dict[str, List[Tuple]] = {}
|
| 151 |
-
|
| 152 |
-
# Album grouping
|
| 153 |
album_groups: dict[str, dict] = {}
|
| 154 |
|
| 155 |
-
|
| 156 |
def make_token() -> str:
|
| 157 |
return secrets.token_hex(8)
|
| 158 |
|
| 159 |
-
|
| 160 |
# =============================================================================
|
| 161 |
-
# FLASK HEALTH
|
| 162 |
# =============================================================================
|
| 163 |
|
| 164 |
web = Flask(__name__)
|
| 165 |
|
| 166 |
-
|
| 167 |
@web.route("/")
|
| 168 |
def home():
|
| 169 |
return "Status: OK - Bot Running"
|
| 170 |
|
| 171 |
-
|
| 172 |
def run_web():
|
| 173 |
web.run(host="0.0.0.0", port=7860)
|
| 174 |
|
| 175 |
-
|
| 176 |
# =============================================================================
|
| 177 |
-
# HUGGING FACE
|
| 178 |
# =============================================================================
|
| 179 |
|
| 180 |
hf = HfApi(token=HF_TOKEN)
|
|
@@ -187,16 +151,15 @@ app = Client(
|
|
| 187 |
)
|
| 188 |
|
| 189 |
# =============================================================================
|
| 190 |
-
#
|
| 191 |
# =============================================================================
|
| 192 |
|
| 193 |
upload_queue: asyncio.Queue = asyncio.Queue()
|
| 194 |
active_jobs: dict[int, dict] = {}
|
| 195 |
bot_start_time = time.time()
|
| 196 |
|
| 197 |
-
|
| 198 |
# =============================================================================
|
| 199 |
-
# UTILITY
|
| 200 |
# =============================================================================
|
| 201 |
|
| 202 |
def cleanup(path: str) -> None:
|
|
@@ -208,11 +171,9 @@ def cleanup(path: str) -> None:
|
|
| 208 |
except Exception:
|
| 209 |
pass
|
| 210 |
|
| 211 |
-
|
| 212 |
def get_free_disk() -> int:
|
| 213 |
return shutil.disk_usage("/").free
|
| 214 |
|
| 215 |
-
|
| 216 |
def format_size(bytes_val: int) -> str:
|
| 217 |
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
|
| 218 |
if bytes_val < 1024.0:
|
|
@@ -220,11 +181,9 @@ def format_size(bytes_val: int) -> str:
|
|
| 220 |
bytes_val /= 1024.0
|
| 221 |
return f"{bytes_val:.1f} PB"
|
| 222 |
|
| 223 |
-
|
| 224 |
def format_speed(bytes_per_sec: float) -> str:
|
| 225 |
return f"{format_size(bytes_per_sec)}/s"
|
| 226 |
|
| 227 |
-
|
| 228 |
def get_memory_usage() -> str:
|
| 229 |
try:
|
| 230 |
with open("/proc/self/status") as f:
|
|
@@ -234,13 +193,17 @@ def get_memory_usage() -> str:
|
|
| 234 |
except Exception:
|
| 235 |
return "unknown"
|
| 236 |
|
| 237 |
-
|
| 238 |
async def send_progress_updater(
|
| 239 |
job_id: int,
|
| 240 |
status_msg: Message,
|
| 241 |
cancel_event: asyncio.Event,
|
| 242 |
total_bytes: int,
|
| 243 |
) -> Tuple[asyncio.Task, list]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
bytes_holder = [0]
|
| 245 |
start_time = time.time()
|
| 246 |
|
|
@@ -249,15 +212,17 @@ async def send_progress_updater(
|
|
| 249 |
elapsed = max(time.time() - start_time, 0.01)
|
| 250 |
current = bytes_holder[0]
|
| 251 |
speed = current / elapsed
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
f"
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
| 261 |
try:
|
| 262 |
await status_msg.edit_text(
|
| 263 |
text,
|
|
@@ -272,9 +237,8 @@ async def send_progress_updater(
|
|
| 272 |
task = asyncio.create_task(updater())
|
| 273 |
return task, bytes_holder
|
| 274 |
|
| 275 |
-
|
| 276 |
# =============================================================================
|
| 277 |
-
# UPLOAD / DOWNLOAD
|
| 278 |
# =============================================================================
|
| 279 |
|
| 280 |
async def do_upload_job(
|
|
@@ -287,10 +251,14 @@ async def do_upload_job(
|
|
| 287 |
status_msg: Message,
|
| 288 |
file_id: Optional[str] = None,
|
| 289 |
) -> None:
|
| 290 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 291 |
temp_dir = tempfile.mkdtemp()
|
| 292 |
local_path = None
|
| 293 |
try:
|
|
|
|
| 294 |
await status_msg.edit_text(
|
| 295 |
"⬇️ Downloading from Telegram...",
|
| 296 |
reply_markup=InlineKeyboardMarkup(
|
|
@@ -298,6 +266,7 @@ async def do_upload_job(
|
|
| 298 |
),
|
| 299 |
)
|
| 300 |
last_update = [0]
|
|
|
|
| 301 |
|
| 302 |
async def download_progress(current, total):
|
| 303 |
now = time.time()
|
|
@@ -306,13 +275,12 @@ async def do_upload_job(
|
|
| 306 |
last_update[0] = now
|
| 307 |
elapsed = max(time.time() - download_start, 0.01)
|
| 308 |
speed = current / elapsed
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
f"{pct:.1f}% of {format_size(total)}\n"
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
)
|
| 316 |
try:
|
| 317 |
await status_msg.edit_text(
|
| 318 |
text,
|
|
@@ -323,15 +291,12 @@ async def do_upload_job(
|
|
| 323 |
except Exception:
|
| 324 |
pass
|
| 325 |
|
| 326 |
-
download_start = time.time()
|
| 327 |
-
|
| 328 |
if isinstance(file_msg_or_id, Message):
|
| 329 |
local_path = await file_msg_or_id.download(
|
| 330 |
file_name=os.path.join(temp_dir, orig_filename),
|
| 331 |
progress=download_progress,
|
| 332 |
)
|
| 333 |
else:
|
| 334 |
-
# Download by file_id
|
| 335 |
local_path = await app.download_media(
|
| 336 |
file_msg_or_id,
|
| 337 |
file_name=os.path.join(temp_dir, orig_filename),
|
|
@@ -343,6 +308,7 @@ async def do_upload_job(
|
|
| 343 |
|
| 344 |
file_size = os.path.getsize(local_path)
|
| 345 |
|
|
|
|
| 346 |
enc_folder = get_encrypted_folder(user_id)
|
| 347 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 348 |
repo_path = f"{enc_folder}/{enc_filename}"
|
|
@@ -374,11 +340,7 @@ async def do_upload_job(
|
|
| 374 |
|
| 375 |
if cancel_event.is_set():
|
| 376 |
try:
|
| 377 |
-
hf.delete_file(
|
| 378 |
-
path_in_repo=repo_path,
|
| 379 |
-
repo_id=DATASET_REPO,
|
| 380 |
-
repo_type=DATASET_TYPE,
|
| 381 |
-
)
|
| 382 |
except Exception:
|
| 383 |
pass
|
| 384 |
await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
|
|
@@ -404,6 +366,7 @@ async def do_download_job(
|
|
| 404 |
cancel_event: asyncio.Event,
|
| 405 |
status_msg: Message,
|
| 406 |
) -> None:
|
|
|
|
| 407 |
temp_dir = tempfile.mkdtemp()
|
| 408 |
try:
|
| 409 |
loop = asyncio.get_event_loop()
|
|
@@ -489,16 +452,12 @@ async def do_download_job(
|
|
| 489 |
|
| 490 |
|
| 491 |
# =============================================================================
|
| 492 |
-
#
|
| 493 |
# =============================================================================
|
| 494 |
|
| 495 |
async def delete_user_file(chat_id, user_id, enc_path, token, query: CallbackQuery):
|
| 496 |
try:
|
| 497 |
-
hf.delete_file(
|
| 498 |
-
path_in_repo=enc_path,
|
| 499 |
-
repo_id=DATASET_REPO,
|
| 500 |
-
repo_type=DATASET_TYPE,
|
| 501 |
-
)
|
| 502 |
db_remove_file(enc_path)
|
| 503 |
file_callback_map.pop(token, None)
|
| 504 |
await query.answer("File deleted.", show_alert=True)
|
|
@@ -515,20 +474,12 @@ async def delete_all_user_files(chat_id, user_id, query: CallbackQuery):
|
|
| 515 |
|
| 516 |
for enc_path, _, _ in user_files:
|
| 517 |
try:
|
| 518 |
-
hf.delete_file(
|
| 519 |
-
path_in_repo=enc_path,
|
| 520 |
-
repo_id=DATASET_REPO,
|
| 521 |
-
repo_type=DATASET_TYPE,
|
| 522 |
-
)
|
| 523 |
except Exception:
|
| 524 |
pass
|
| 525 |
|
| 526 |
db_remove_all_user_files(user_id)
|
| 527 |
-
|
| 528 |
-
tokens_to_delete = [
|
| 529 |
-
tok for tok, path in file_callback_map.items()
|
| 530 |
-
if path.startswith(get_encrypted_folder(user_id))
|
| 531 |
-
]
|
| 532 |
for tok in tokens_to_delete:
|
| 533 |
file_callback_map.pop(tok, None)
|
| 534 |
|
|
@@ -549,7 +500,6 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 549 |
InlineKeyboardButton(f"📥 {orig_name[:40]}", callback_data=f"get:{token}"),
|
| 550 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 551 |
])
|
| 552 |
-
|
| 553 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 554 |
|
| 555 |
await message.edit_text(
|
|
@@ -566,10 +516,9 @@ async def process_album_group(media_group_id: str):
|
|
| 566 |
group_data = album_groups.pop(media_group_id, None)
|
| 567 |
if not group_data:
|
| 568 |
return
|
| 569 |
-
|
| 570 |
chat_id = group_data['chat_id']
|
| 571 |
user_id = group_data['user_id']
|
| 572 |
-
messages = group_data['messages'] #
|
| 573 |
|
| 574 |
if len(messages) == 1:
|
| 575 |
msg_id, filename, file_id = messages[0]
|
|
@@ -591,16 +540,12 @@ async def process_album_group(media_group_id: str):
|
|
| 591 |
for msg_id, fname, fid in messages:
|
| 592 |
individual_token = make_token()
|
| 593 |
upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]
|
| 594 |
-
button_rows.append(
|
| 595 |
-
[InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")]
|
| 596 |
-
)
|
| 597 |
button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])
|
| 598 |
|
| 599 |
-
await app.send_message(
|
| 600 |
-
chat_id,
|
| 601 |
f"Received {len(messages)} files.\n{files_list}\n\nChoose:",
|
| 602 |
-
reply_markup=InlineKeyboardMarkup(button_rows)
|
| 603 |
-
)
|
| 604 |
|
| 605 |
|
| 606 |
# =============================================================================
|
|
@@ -628,9 +573,7 @@ async def upload_worker():
|
|
| 628 |
active_jobs[job_id]["status_msg"] = status_msg
|
| 629 |
|
| 630 |
try:
|
| 631 |
-
await do_upload_job(
|
| 632 |
-
user_id, chat_id, file_obj, orig_filename, job_id, cancel_event, status_msg, file_id
|
| 633 |
-
)
|
| 634 |
finally:
|
| 635 |
active_jobs.pop(job_id, None)
|
| 636 |
upload_queue.task_done()
|
|
@@ -648,61 +591,51 @@ async def cmd_start(_, message: Message):
|
|
| 648 |
"Use /help for a full command list."
|
| 649 |
)
|
| 650 |
|
| 651 |
-
|
| 652 |
@app.on_message(filters.command("help"))
|
| 653 |
async def cmd_help(_, message: Message):
|
| 654 |
text = (
|
| 655 |
"**Available Commands:**\n\n"
|
| 656 |
-
"/start –
|
| 657 |
-
"/files – List your uploaded files (
|
| 658 |
-
"/status –
|
| 659 |
-
"/delete_all – Delete all your files (confirmation
|
| 660 |
-
"/upload <link> –
|
| 661 |
-
"/help – This help
|
| 662 |
-
"**
|
| 663 |
-
"• Send any file
|
| 664 |
-
"•
|
| 665 |
-
"•
|
| 666 |
-
"•
|
| 667 |
-
"• In /files list, click a file to download it back, or use the Delete button."
|
| 668 |
)
|
| 669 |
await message.reply_text(text, disable_web_page_preview=True)
|
| 670 |
|
| 671 |
-
|
| 672 |
@app.on_message(filters.command("status"))
|
| 673 |
async def cmd_status(_, message: Message):
|
| 674 |
free = get_free_disk()
|
| 675 |
disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
|
| 676 |
-
|
| 677 |
try:
|
| 678 |
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 679 |
used = info.used_storage or 0
|
| 680 |
except Exception:
|
| 681 |
used = 0
|
| 682 |
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
| 683 |
-
|
| 684 |
uptime_sec = int(time.time() - bot_start_time)
|
| 685 |
uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
|
| 686 |
mem_text = f"🧠 Memory: {get_memory_usage()}"
|
| 687 |
cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
|
| 688 |
-
|
| 689 |
try:
|
| 690 |
r = requests.head("https://huggingface.co", timeout=5)
|
| 691 |
hf_ping = "OK" if r.status_code < 400 else f"HTTP {r.status_code}"
|
| 692 |
except Exception:
|
| 693 |
hf_ping = "unreachable"
|
| 694 |
-
|
| 695 |
await message.reply_text(
|
| 696 |
-
f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}\n{cpu_text}\n"
|
| 697 |
-
f"🌐 Hugging Face: {hf_ping}"
|
| 698 |
)
|
| 699 |
|
| 700 |
-
|
| 701 |
@app.on_message(filters.command("files"))
|
| 702 |
async def cmd_files(_, message: Message):
|
| 703 |
user_id = message.from_user.id
|
| 704 |
user_files = db_get_user_files(user_id)
|
| 705 |
-
|
| 706 |
if not user_files:
|
| 707 |
enc_folder = get_encrypted_folder(user_id)
|
| 708 |
try:
|
|
@@ -723,11 +656,9 @@ async def cmd_files(_, message: Message):
|
|
| 723 |
db_add_file(user_id, path, orig_name, size)
|
| 724 |
user_files = db_get_user_files(user_id)
|
| 725 |
except Exception as e:
|
| 726 |
-
logger.warning("Fallback scan failed
|
| 727 |
-
|
| 728 |
if not user_files:
|
| 729 |
return await message.reply_text("You have no uploaded files.")
|
| 730 |
-
|
| 731 |
buttons = []
|
| 732 |
for enc_path, orig_name, _ in user_files:
|
| 733 |
token = make_token()
|
|
@@ -736,15 +667,12 @@ async def cmd_files(_, message: Message):
|
|
| 736 |
InlineKeyboardButton(f"📥 {orig_name[:40]}", callback_data=f"get:{token}"),
|
| 737 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 738 |
])
|
| 739 |
-
|
| 740 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 741 |
-
|
| 742 |
await message.reply_text(
|
| 743 |
-
"Your uploaded files
|
| 744 |
-
reply_markup=InlineKeyboardMarkup(buttons)
|
| 745 |
)
|
| 746 |
|
| 747 |
-
|
| 748 |
@app.on_message(filters.command("delete_all"))
|
| 749 |
async def cmd_delete_all(_, message: Message):
|
| 750 |
user_id = message.from_user.id
|
|
@@ -752,23 +680,17 @@ async def cmd_delete_all(_, message: Message):
|
|
| 752 |
[InlineKeyboardButton("Yes, delete all my files", callback_data=f"delete_all:{user_id}")],
|
| 753 |
[InlineKeyboardButton("Cancel", callback_data="cancel_upload:0")],
|
| 754 |
])
|
| 755 |
-
await message.reply_text(
|
| 756 |
-
"⚠️ This will permanently delete **all** your files from the dataset. Are you sure?",
|
| 757 |
-
reply_markup=kb,
|
| 758 |
-
)
|
| 759 |
-
|
| 760 |
|
| 761 |
@app.on_message(filters.command("upload"))
|
| 762 |
async def cmd_upload(_, message: Message):
|
| 763 |
args = message.text.split(maxsplit=1)
|
| 764 |
if len(args) < 2:
|
| 765 |
return await message.reply_text("Usage: /upload <link>")
|
| 766 |
-
|
| 767 |
link = args[1].strip()
|
| 768 |
match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)
|
| 769 |
if not match:
|
| 770 |
return await message.reply_text("Invalid Telegram message link.")
|
| 771 |
-
|
| 772 |
chat_str, msg_id = match.group(2), int(match.group(3))
|
| 773 |
try:
|
| 774 |
if chat_str.startswith("c/"):
|
|
@@ -778,11 +700,8 @@ async def cmd_upload(_, message: Message):
|
|
| 778 |
msg = await app.get_messages(chat_id, msg_id)
|
| 779 |
except Exception as e:
|
| 780 |
return await message.reply_text(f"❌ Could not fetch the message: {e}")
|
| 781 |
-
|
| 782 |
if not msg.media:
|
| 783 |
-
return await message.reply_text("The linked message doesn't contain
|
| 784 |
-
|
| 785 |
-
# Extract file_id and filename
|
| 786 |
file_id = None
|
| 787 |
if msg.document:
|
| 788 |
filename = msg.document.file_name
|
|
@@ -815,7 +734,6 @@ async def cmd_upload(_, message: Message):
|
|
| 815 |
file_id = msg.voice.file_id
|
| 816 |
else:
|
| 817 |
filename = f"file_{msg_id}"
|
| 818 |
-
|
| 819 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 820 |
active_jobs[job_id] = {"status": "queued"}
|
| 821 |
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id))
|
|
@@ -832,27 +750,20 @@ async def cb_get_file(_, query: CallbackQuery):
|
|
| 832 |
enc_path = file_callback_map.get(token)
|
| 833 |
if not enc_path:
|
| 834 |
return await query.answer("Invalid or expired link. Use /files again.", show_alert=True)
|
| 835 |
-
|
| 836 |
job_id = int(time.time() * 1000)
|
| 837 |
cancel_event = asyncio.Event()
|
| 838 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
|
| 839 |
-
|
| 840 |
try:
|
| 841 |
orig_name = decrypt_text(enc_path.split("/")[-1])
|
| 842 |
except Exception:
|
| 843 |
orig_name = enc_path.split("/")[-1]
|
| 844 |
-
|
| 845 |
status_msg = await query.message.edit_text(
|
| 846 |
"⏳ Preparing download...",
|
| 847 |
-
reply_markup=InlineKeyboardMarkup(
|
| 848 |
-
[[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
|
| 849 |
-
),
|
| 850 |
)
|
| 851 |
active_jobs[job_id]["status_msg"] = status_msg
|
| 852 |
-
|
| 853 |
asyncio.create_task(do_download_job(query.message.chat.id, enc_path, orig_name, job_id, cancel_event, status_msg))
|
| 854 |
|
| 855 |
-
|
| 856 |
@app.on_callback_query(filters.regex("^delete:"))
|
| 857 |
async def cb_delete_file(_, query: CallbackQuery):
|
| 858 |
token = query.data.replace("delete:", "")
|
|
@@ -862,13 +773,11 @@ async def cb_delete_file(_, query: CallbackQuery):
|
|
| 862 |
user_id = query.from_user.id
|
| 863 |
await delete_user_file(query.message.chat.id, user_id, enc_path, token, query)
|
| 864 |
|
| 865 |
-
|
| 866 |
@app.on_callback_query(filters.regex("^delete_all:"))
|
| 867 |
async def cb_delete_all(_, query: CallbackQuery):
|
| 868 |
user_id = int(query.data.split(":")[-1])
|
| 869 |
await delete_all_user_files(query.message.chat.id, user_id, query)
|
| 870 |
|
| 871 |
-
|
| 872 |
@app.on_callback_query(filters.regex("^cancel_job:"))
|
| 873 |
async def cb_cancel_job(_, query: CallbackQuery):
|
| 874 |
_, job_id_str = query.data.split(":")
|
|
@@ -879,21 +788,16 @@ async def cb_cancel_job(_, query: CallbackQuery):
|
|
| 879 |
else:
|
| 880 |
await query.answer("Job not found.")
|
| 881 |
|
| 882 |
-
|
| 883 |
@app.on_callback_query(filters.regex("^upload:"))
|
| 884 |
async def cb_upload(_, query: CallbackQuery):
|
| 885 |
token = query.data.replace("upload:", "")
|
| 886 |
entries = upload_prompt_map.pop(token, None)
|
| 887 |
if not entries:
|
| 888 |
return await query.answer("Prompt expired.", show_alert=True)
|
| 889 |
-
|
| 890 |
for entry in entries:
|
| 891 |
user_id = entry[0]
|
| 892 |
if len(entry) == 4:
|
| 893 |
-
|
| 894 |
-
msg_id = entry[1]
|
| 895 |
-
filename = entry[2]
|
| 896 |
-
file_id = entry[3]
|
| 897 |
try:
|
| 898 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 899 |
except Exception:
|
|
@@ -904,31 +808,23 @@ async def cb_upload(_, query: CallbackQuery):
|
|
| 904 |
continue
|
| 905 |
file_obj = file_msg
|
| 906 |
else:
|
| 907 |
-
|
| 908 |
-
file_id = entry[1]
|
| 909 |
-
filename = entry[2]
|
| 910 |
file_obj = file_id
|
| 911 |
-
|
| 912 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 913 |
active_jobs[job_id] = {"status": "queued"}
|
| 914 |
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id))
|
| 915 |
-
|
| 916 |
await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)
|
| 917 |
|
| 918 |
-
|
| 919 |
@app.on_callback_query(filters.regex("^upload_all:"))
|
| 920 |
async def cb_upload_all(_, query: CallbackQuery):
|
| 921 |
token = query.data.replace("upload_all:", "")
|
| 922 |
entries = upload_prompt_map.pop(token, None)
|
| 923 |
if not entries:
|
| 924 |
return await query.answer("Prompt expired.", show_alert=True)
|
| 925 |
-
|
| 926 |
for entry in entries:
|
| 927 |
user_id = entry[0]
|
| 928 |
if len(entry) == 4:
|
| 929 |
-
msg_id = entry[1]
|
| 930 |
-
filename = entry[2]
|
| 931 |
-
file_id = entry[3]
|
| 932 |
try:
|
| 933 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 934 |
except Exception:
|
|
@@ -937,24 +833,20 @@ async def cb_upload_all(_, query: CallbackQuery):
|
|
| 937 |
continue
|
| 938 |
file_obj = file_msg
|
| 939 |
else:
|
| 940 |
-
file_id = entry[1]
|
| 941 |
-
filename = entry[2]
|
| 942 |
file_obj = file_id
|
| 943 |
-
|
| 944 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 945 |
active_jobs[job_id] = {"status": "queued"}
|
| 946 |
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id))
|
| 947 |
-
|
| 948 |
await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)
|
| 949 |
|
| 950 |
-
|
| 951 |
@app.on_callback_query(filters.regex("^cancel_upload:"))
|
| 952 |
async def cb_cancel_upload_prompt(_, query: CallbackQuery):
|
| 953 |
await query.message.delete()
|
| 954 |
|
| 955 |
|
| 956 |
# =============================================================================
|
| 957 |
-
# MESSAGE LINK
|
| 958 |
# =============================================================================
|
| 959 |
|
| 960 |
@app.on_message(
|
|
@@ -966,7 +858,6 @@ async def on_message_link(client, message: Message):
|
|
| 966 |
links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)
|
| 967 |
if not links:
|
| 968 |
return
|
| 969 |
-
|
| 970 |
chat_str, msg_id = links[0][1], int(links[0][2])
|
| 971 |
try:
|
| 972 |
if chat_str.startswith("c/"):
|
|
@@ -977,12 +868,9 @@ async def on_message_link(client, message: Message):
|
|
| 977 |
except Exception as e:
|
| 978 |
await message.reply_text(f"❌ Could not access the message: {e}")
|
| 979 |
return
|
| 980 |
-
|
| 981 |
if not msg.media:
|
| 982 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 983 |
return
|
| 984 |
-
|
| 985 |
-
# Extract filename and file_id
|
| 986 |
file_id = None
|
| 987 |
if msg.document:
|
| 988 |
filename = msg.document.file_name
|
|
@@ -1016,22 +904,17 @@ async def on_message_link(client, message: Message):
|
|
| 1016 |
else:
|
| 1017 |
filename = f"file_{msg_id}"
|
| 1018 |
|
| 1019 |
-
# Remote entry: (user_id, file_id, filename)
|
| 1020 |
token = make_token()
|
| 1021 |
upload_prompt_map[token] = [(message.from_user.id, file_id, filename)]
|
| 1022 |
-
|
| 1023 |
kb = InlineKeyboardMarkup([
|
| 1024 |
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 1025 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1026 |
])
|
| 1027 |
-
await message.reply_text(
|
| 1028 |
-
f"Found file `{filename}` in the linked message. Do you want to upload it?",
|
| 1029 |
-
reply_markup=kb,
|
| 1030 |
-
)
|
| 1031 |
|
| 1032 |
|
| 1033 |
# =============================================================================
|
| 1034 |
-
# DIRECT FILE RECEIVER (any
|
| 1035 |
# =============================================================================
|
| 1036 |
|
| 1037 |
@app.on_message(
|
|
@@ -1082,7 +965,6 @@ async def on_direct_file(_, message: Message):
|
|
| 1082 |
'timer': None,
|
| 1083 |
}
|
| 1084 |
album_groups[group_id]['messages'].append((message.id, filename, file_id))
|
| 1085 |
-
|
| 1086 |
if album_groups[group_id]['timer']:
|
| 1087 |
album_groups[group_id]['timer'].cancel()
|
| 1088 |
|
|
@@ -1093,10 +975,9 @@ async def on_direct_file(_, message: Message):
|
|
| 1093 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1094 |
return
|
| 1095 |
|
| 1096 |
-
# Single file
|
| 1097 |
token = make_token()
|
| 1098 |
upload_prompt_map[token] = [(message.from_user.id, message.id, filename, file_id)]
|
| 1099 |
-
|
| 1100 |
kb = InlineKeyboardMarkup([
|
| 1101 |
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 1102 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
|
@@ -1118,13 +999,13 @@ def keepalive():
|
|
| 1118 |
|
| 1119 |
|
| 1120 |
# =============================================================================
|
| 1121 |
-
# MAIN
|
| 1122 |
# =============================================================================
|
| 1123 |
|
| 1124 |
async def main():
|
| 1125 |
asyncio.create_task(upload_worker())
|
| 1126 |
await app.start()
|
| 1127 |
-
logger.info("Bot started successfully")
|
| 1128 |
await asyncio.Event().wait()
|
| 1129 |
|
| 1130 |
|
|
|
|
| 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
|
| 15 |
|
| 16 |
import requests
|
| 17 |
from flask import Flask
|
| 18 |
from pyrogram import Client, filters
|
| 19 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery
|
| 20 |
+
from huggingface_hub import HfApi, get_hf_file_metadata, hf_hub_download, hf_hub_url
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
|
| 22 |
|
| 23 |
# =============================================================================
|
|
|
|
| 30 |
HF_TOKEN: str = os.environ["HF_TOKEN"]
|
| 31 |
OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
|
| 32 |
|
| 33 |
+
SPACE_HOST: str = "https://cxops-push.hf.space" # Keep‑alive URL
|
|
|
|
| 34 |
|
| 35 |
DATASET_REPO: str = "Cxops/Bzxv"
|
| 36 |
DATASET_TYPE: str = "dataset"
|
| 37 |
+
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
|
|
|
|
| 55 |
_siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
|
| 56 |
_aes_siv = AESSIV(_siv_key)
|
| 57 |
|
|
|
|
| 58 |
def encrypt_text(plain: str) -> str:
|
|
|
|
| 59 |
token = _aes_siv.encrypt(plain.encode(), None)
|
| 60 |
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 61 |
|
|
|
|
| 62 |
def decrypt_text(encoded: str) -> str:
|
|
|
|
| 63 |
padding = 4 - len(encoded) % 4
|
| 64 |
if padding != 4:
|
| 65 |
encoded += "=" * padding
|
| 66 |
token = base64.urlsafe_b64decode(encoded.encode())
|
| 67 |
return _aes_siv.decrypt(token, None).decode()
|
| 68 |
|
|
|
|
| 69 |
def get_encrypted_folder(user_id: int) -> str:
|
| 70 |
return encrypt_text(str(user_id))
|
| 71 |
|
|
|
|
| 72 |
def get_encrypted_filename(original: str) -> str:
|
| 73 |
return encrypt_text(original)
|
| 74 |
|
|
|
|
| 75 |
# =============================================================================
|
| 76 |
+
# DATABASE (WAL mode for concurrency)
|
| 77 |
# =============================================================================
|
| 78 |
|
| 79 |
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 80 |
conn.row_factory = sqlite3.Row
|
| 81 |
conn.execute("PRAGMA journal_mode=WAL")
|
| 82 |
cursor = conn.cursor()
|
| 83 |
+
cursor.execute("""
|
|
|
|
| 84 |
CREATE TABLE IF NOT EXISTS files (
|
| 85 |
user_id INTEGER,
|
| 86 |
enc_path TEXT UNIQUE,
|
|
|
|
| 88 |
size INTEGER,
|
| 89 |
timestamp REAL
|
| 90 |
)
|
| 91 |
+
""")
|
|
|
|
| 92 |
conn.commit()
|
| 93 |
|
|
|
|
| 94 |
def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
|
| 95 |
cursor.execute(
|
| 96 |
"INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",
|
|
|
|
| 98 |
)
|
| 99 |
conn.commit()
|
| 100 |
|
|
|
|
| 101 |
def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
|
| 102 |
cursor.execute(
|
| 103 |
"SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC",
|
|
|
|
| 105 |
)
|
| 106 |
return [(row[0], row[1], row[2]) for row in cursor.fetchall()]
|
| 107 |
|
|
|
|
| 108 |
def db_remove_file(enc_path: str) -> None:
|
| 109 |
cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
|
| 110 |
conn.commit()
|
| 111 |
|
|
|
|
| 112 |
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 tuples (local or remote)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
album_groups: dict[str, dict] = {}
|
| 123 |
|
|
|
|
| 124 |
def make_token() -> str:
|
| 125 |
return secrets.token_hex(8)
|
| 126 |
|
|
|
|
| 127 |
# =============================================================================
|
| 128 |
+
# FLASK HEALTH CHECK
|
| 129 |
# =============================================================================
|
| 130 |
|
| 131 |
web = Flask(__name__)
|
| 132 |
|
|
|
|
| 133 |
@web.route("/")
|
| 134 |
def home():
|
| 135 |
return "Status: OK - Bot Running"
|
| 136 |
|
|
|
|
| 137 |
def run_web():
|
| 138 |
web.run(host="0.0.0.0", port=7860)
|
| 139 |
|
|
|
|
| 140 |
# =============================================================================
|
| 141 |
+
# HUGGING FACE API & PYROGRAM CLIENT
|
| 142 |
# =============================================================================
|
| 143 |
|
| 144 |
hf = HfApi(token=HF_TOKEN)
|
|
|
|
| 151 |
)
|
| 152 |
|
| 153 |
# =============================================================================
|
| 154 |
+
# GLOBAL STATE
|
| 155 |
# =============================================================================
|
| 156 |
|
| 157 |
upload_queue: asyncio.Queue = asyncio.Queue()
|
| 158 |
active_jobs: dict[int, dict] = {}
|
| 159 |
bot_start_time = time.time()
|
| 160 |
|
|
|
|
| 161 |
# =============================================================================
|
| 162 |
+
# UTILITY HELPERS
|
| 163 |
# =============================================================================
|
| 164 |
|
| 165 |
def cleanup(path: str) -> None:
|
|
|
|
| 171 |
except Exception:
|
| 172 |
pass
|
| 173 |
|
|
|
|
| 174 |
def get_free_disk() -> int:
|
| 175 |
return shutil.disk_usage("/").free
|
| 176 |
|
|
|
|
| 177 |
def format_size(bytes_val: int) -> str:
|
| 178 |
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
|
| 179 |
if bytes_val < 1024.0:
|
|
|
|
| 181 |
bytes_val /= 1024.0
|
| 182 |
return f"{bytes_val:.1f} PB"
|
| 183 |
|
|
|
|
| 184 |
def format_speed(bytes_per_sec: float) -> str:
|
| 185 |
return f"{format_size(bytes_per_sec)}/s"
|
| 186 |
|
|
|
|
| 187 |
def get_memory_usage() -> str:
|
| 188 |
try:
|
| 189 |
with open("/proc/self/status") as f:
|
|
|
|
| 193 |
except Exception:
|
| 194 |
return "unknown"
|
| 195 |
|
|
|
|
| 196 |
async def send_progress_updater(
|
| 197 |
job_id: int,
|
| 198 |
status_msg: Message,
|
| 199 |
cancel_event: asyncio.Event,
|
| 200 |
total_bytes: int,
|
| 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]
|
| 208 |
start_time = time.time()
|
| 209 |
|
|
|
|
| 212 |
elapsed = max(time.time() - start_time, 0.01)
|
| 213 |
current = bytes_holder[0]
|
| 214 |
speed = current / elapsed
|
| 215 |
+
text = "📤 Sending to Telegram...\n"
|
| 216 |
+
if total_bytes > 0:
|
| 217 |
+
pct = (100 * current / total_bytes)
|
| 218 |
+
text += f"{pct:.1f}% of {format_size(total_bytes)}\n"
|
| 219 |
+
text += f"{format_size(current)} sent\n"
|
| 220 |
+
text += f"Speed: {format_speed(speed)}\n"
|
| 221 |
+
if total_bytes > 0 and speed > 0:
|
| 222 |
+
eta = int((total_bytes - current) / speed)
|
| 223 |
+
text += f"ETA: {eta}s"
|
| 224 |
+
else:
|
| 225 |
+
text += "ETA: ..."
|
| 226 |
try:
|
| 227 |
await status_msg.edit_text(
|
| 228 |
text,
|
|
|
|
| 237 |
task = asyncio.create_task(updater())
|
| 238 |
return task, bytes_holder
|
| 239 |
|
|
|
|
| 240 |
# =============================================================================
|
| 241 |
+
# CORE UPLOAD / DOWNLOAD LOGIC
|
| 242 |
# =============================================================================
|
| 243 |
|
| 244 |
async def do_upload_job(
|
|
|
|
| 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 |
+
Progress shows speed & downloaded amount; percentage only when total is known.
|
| 257 |
+
"""
|
| 258 |
temp_dir = tempfile.mkdtemp()
|
| 259 |
local_path = None
|
| 260 |
try:
|
| 261 |
+
# ---- Download from Telegram (progress shown) ----
|
| 262 |
await status_msg.edit_text(
|
| 263 |
"⬇️ Downloading from Telegram...",
|
| 264 |
reply_markup=InlineKeyboardMarkup(
|
|
|
|
| 266 |
),
|
| 267 |
)
|
| 268 |
last_update = [0]
|
| 269 |
+
download_start = time.time()
|
| 270 |
|
| 271 |
async def download_progress(current, total):
|
| 272 |
now = time.time()
|
|
|
|
| 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 |
+
pct = (100 * current / total)
|
| 281 |
+
text += f"{pct:.1f}% of {format_size(total)}\n"
|
| 282 |
+
text += f"{format_size(current)} downloaded\n"
|
| 283 |
+
text += f"Speed: {format_speed(speed)}"
|
|
|
|
| 284 |
try:
|
| 285 |
await status_msg.edit_text(
|
| 286 |
text,
|
|
|
|
| 291 |
except Exception:
|
| 292 |
pass
|
| 293 |
|
|
|
|
|
|
|
| 294 |
if isinstance(file_msg_or_id, Message):
|
| 295 |
local_path = await file_msg_or_id.download(
|
| 296 |
file_name=os.path.join(temp_dir, orig_filename),
|
| 297 |
progress=download_progress,
|
| 298 |
)
|
| 299 |
else:
|
|
|
|
| 300 |
local_path = await app.download_media(
|
| 301 |
file_msg_or_id,
|
| 302 |
file_name=os.path.join(temp_dir, orig_filename),
|
|
|
|
| 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}"
|
|
|
|
| 340 |
|
| 341 |
if cancel_event.is_set():
|
| 342 |
try:
|
| 343 |
+
hf.delete_file(path_in_repo=repo_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
except Exception:
|
| 345 |
pass
|
| 346 |
await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
|
|
|
|
| 366 |
cancel_event: asyncio.Event,
|
| 367 |
status_msg: Message,
|
| 368 |
) -> None:
|
| 369 |
+
"""Download file from Hugging Face dataset and send back to Telegram."""
|
| 370 |
temp_dir = tempfile.mkdtemp()
|
| 371 |
try:
|
| 372 |
loop = asyncio.get_event_loop()
|
|
|
|
| 452 |
|
| 453 |
|
| 454 |
# =============================================================================
|
| 455 |
+
# DELETION HELPERS
|
| 456 |
# =============================================================================
|
| 457 |
|
| 458 |
async def delete_user_file(chat_id, user_id, enc_path, token, query: CallbackQuery):
|
| 459 |
try:
|
| 460 |
+
hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
db_remove_file(enc_path)
|
| 462 |
file_callback_map.pop(token, None)
|
| 463 |
await query.answer("File deleted.", show_alert=True)
|
|
|
|
| 474 |
|
| 475 |
for enc_path, _, _ in user_files:
|
| 476 |
try:
|
| 477 |
+
hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
except Exception:
|
| 479 |
pass
|
| 480 |
|
| 481 |
db_remove_all_user_files(user_id)
|
| 482 |
+
tokens_to_delete = [tok for tok, path in file_callback_map.items() if path.startswith(get_encrypted_folder(user_id))]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
for tok in tokens_to_delete:
|
| 484 |
file_callback_map.pop(tok, None)
|
| 485 |
|
|
|
|
| 500 |
InlineKeyboardButton(f"📥 {orig_name[:40]}", callback_data=f"get:{token}"),
|
| 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(
|
|
|
|
| 516 |
group_data = album_groups.pop(media_group_id, None)
|
| 517 |
if not group_data:
|
| 518 |
return
|
|
|
|
| 519 |
chat_id = group_data['chat_id']
|
| 520 |
user_id = group_data['user_id']
|
| 521 |
+
messages = group_data['messages'] # (message_id, filename, file_id)
|
| 522 |
|
| 523 |
if len(messages) == 1:
|
| 524 |
msg_id, filename, file_id = messages[0]
|
|
|
|
| 540 |
for msg_id, fname, fid in messages:
|
| 541 |
individual_token = make_token()
|
| 542 |
upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]
|
| 543 |
+
button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
|
|
|
|
|
|
|
| 544 |
button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])
|
| 545 |
|
| 546 |
+
await app.send_message(chat_id,
|
|
|
|
| 547 |
f"Received {len(messages)} files.\n{files_list}\n\nChoose:",
|
| 548 |
+
reply_markup=InlineKeyboardMarkup(button_rows))
|
|
|
|
| 549 |
|
| 550 |
|
| 551 |
# =============================================================================
|
|
|
|
| 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()
|
|
|
|
| 591 |
"Use /help for a full command list."
|
| 592 |
)
|
| 593 |
|
|
|
|
| 594 |
@app.on_message(filters.command("help"))
|
| 595 |
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 buttons)\n"
|
| 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 |
+
"**Usage:**\n"
|
| 605 |
+
"• Send any file → prompt to upload.\n"
|
| 606 |
+
"• Album → 'Upload All' + individual buttons.\n"
|
| 607 |
+
"• Message link → fetches file & asks.\n"
|
| 608 |
+
"• /upload <link> → direct upload (no prompt)."
|
|
|
|
| 609 |
)
|
| 610 |
await message.reply_text(text, disable_web_page_preview=True)
|
| 611 |
|
|
|
|
| 612 |
@app.on_message(filters.command("status"))
|
| 613 |
async def cmd_status(_, message: Message):
|
| 614 |
free = get_free_disk()
|
| 615 |
disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
|
|
|
|
| 616 |
try:
|
| 617 |
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 618 |
used = info.used_storage or 0
|
| 619 |
except Exception:
|
| 620 |
used = 0
|
| 621 |
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
|
|
|
| 622 |
uptime_sec = int(time.time() - bot_start_time)
|
| 623 |
uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
|
| 624 |
mem_text = f"🧠 Memory: {get_memory_usage()}"
|
| 625 |
cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
|
|
|
|
| 626 |
try:
|
| 627 |
r = requests.head("https://huggingface.co", timeout=5)
|
| 628 |
hf_ping = "OK" if r.status_code < 400 else f"HTTP {r.status_code}"
|
| 629 |
except Exception:
|
| 630 |
hf_ping = "unreachable"
|
|
|
|
| 631 |
await message.reply_text(
|
| 632 |
+
f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}\n{cpu_text}\n🌐 Hugging Face: {hf_ping}"
|
|
|
|
| 633 |
)
|
| 634 |
|
|
|
|
| 635 |
@app.on_message(filters.command("files"))
|
| 636 |
async def cmd_files(_, message: Message):
|
| 637 |
user_id = message.from_user.id
|
| 638 |
user_files = db_get_user_files(user_id)
|
|
|
|
| 639 |
if not user_files:
|
| 640 |
enc_folder = get_encrypted_folder(user_id)
|
| 641 |
try:
|
|
|
|
| 656 |
db_add_file(user_id, path, orig_name, size)
|
| 657 |
user_files = db_get_user_files(user_id)
|
| 658 |
except Exception as e:
|
| 659 |
+
logger.warning("Fallback scan failed: %s", e)
|
|
|
|
| 660 |
if not user_files:
|
| 661 |
return await message.reply_text("You have no uploaded files.")
|
|
|
|
| 662 |
buttons = []
|
| 663 |
for enc_path, orig_name, _ in user_files:
|
| 664 |
token = make_token()
|
|
|
|
| 667 |
InlineKeyboardButton(f"📥 {orig_name[:40]}", callback_data=f"get:{token}"),
|
| 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"))
|
| 677 |
async def cmd_delete_all(_, message: Message):
|
| 678 |
user_id = message.from_user.id
|
|
|
|
| 680 |
[InlineKeyboardButton("Yes, delete all my files", callback_data=f"delete_all:{user_id}")],
|
| 681 |
[InlineKeyboardButton("Cancel", callback_data="cancel_upload:0")],
|
| 682 |
])
|
| 683 |
+
await message.reply_text("⚠️ Permanently delete **all** your files? This cannot be undone.", reply_markup=kb)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
|
| 685 |
@app.on_message(filters.command("upload"))
|
| 686 |
async def cmd_upload(_, message: Message):
|
| 687 |
args = message.text.split(maxsplit=1)
|
| 688 |
if len(args) < 2:
|
| 689 |
return await message.reply_text("Usage: /upload <link>")
|
|
|
|
| 690 |
link = args[1].strip()
|
| 691 |
match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)
|
| 692 |
if not match:
|
| 693 |
return await message.reply_text("Invalid Telegram message link.")
|
|
|
|
| 694 |
chat_str, msg_id = match.group(2), int(match.group(3))
|
| 695 |
try:
|
| 696 |
if chat_str.startswith("c/"):
|
|
|
|
| 700 |
msg = await app.get_messages(chat_id, msg_id)
|
| 701 |
except Exception as e:
|
| 702 |
return await message.reply_text(f"❌ Could not fetch the message: {e}")
|
|
|
|
| 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
|
|
|
|
| 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))
|
|
|
|
| 750 |
enc_path = file_callback_map.get(token)
|
| 751 |
if not enc_path:
|
| 752 |
return await query.answer("Invalid or expired link. Use /files again.", show_alert=True)
|
|
|
|
| 753 |
job_id = int(time.time() * 1000)
|
| 754 |
cancel_event = asyncio.Event()
|
| 755 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
|
|
|
|
| 756 |
try:
|
| 757 |
orig_name = decrypt_text(enc_path.split("/")[-1])
|
| 758 |
except Exception:
|
| 759 |
orig_name = enc_path.split("/")[-1]
|
|
|
|
| 760 |
status_msg = await query.message.edit_text(
|
| 761 |
"⏳ Preparing download...",
|
| 762 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),
|
|
|
|
|
|
|
| 763 |
)
|
| 764 |
active_jobs[job_id]["status_msg"] = status_msg
|
|
|
|
| 765 |
asyncio.create_task(do_download_job(query.message.chat.id, enc_path, orig_name, job_id, cancel_event, status_msg))
|
| 766 |
|
|
|
|
| 767 |
@app.on_callback_query(filters.regex("^delete:"))
|
| 768 |
async def cb_delete_file(_, query: CallbackQuery):
|
| 769 |
token = query.data.replace("delete:", "")
|
|
|
|
| 773 |
user_id = query.from_user.id
|
| 774 |
await delete_user_file(query.message.chat.id, user_id, enc_path, token, query)
|
| 775 |
|
|
|
|
| 776 |
@app.on_callback_query(filters.regex("^delete_all:"))
|
| 777 |
async def cb_delete_all(_, query: CallbackQuery):
|
| 778 |
user_id = int(query.data.split(":")[-1])
|
| 779 |
await delete_all_user_files(query.message.chat.id, user_id, query)
|
| 780 |
|
|
|
|
| 781 |
@app.on_callback_query(filters.regex("^cancel_job:"))
|
| 782 |
async def cb_cancel_job(_, query: CallbackQuery):
|
| 783 |
_, job_id_str = query.data.split(":")
|
|
|
|
| 788 |
else:
|
| 789 |
await query.answer("Job not found.")
|
| 790 |
|
|
|
|
| 791 |
@app.on_callback_query(filters.regex("^upload:"))
|
| 792 |
async def cb_upload(_, query: CallbackQuery):
|
| 793 |
token = query.data.replace("upload:", "")
|
| 794 |
entries = upload_prompt_map.pop(token, None)
|
| 795 |
if not entries:
|
| 796 |
return await query.answer("Prompt expired.", show_alert=True)
|
|
|
|
| 797 |
for entry in entries:
|
| 798 |
user_id = entry[0]
|
| 799 |
if len(entry) == 4:
|
| 800 |
+
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
|
|
|
|
|
|
|
|
|
| 801 |
try:
|
| 802 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 803 |
except Exception:
|
|
|
|
| 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:"))
|
| 819 |
async def cb_upload_all(_, query: CallbackQuery):
|
| 820 |
token = query.data.replace("upload_all:", "")
|
| 821 |
entries = upload_prompt_map.pop(token, None)
|
| 822 |
if not entries:
|
| 823 |
return await query.answer("Prompt expired.", show_alert=True)
|
|
|
|
| 824 |
for entry in entries:
|
| 825 |
user_id = entry[0]
|
| 826 |
if len(entry) == 4:
|
| 827 |
+
msg_id, filename, file_id = entry[1], entry[2], entry[3]
|
|
|
|
|
|
|
| 828 |
try:
|
| 829 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 830 |
except Exception:
|
|
|
|
| 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:"))
|
| 844 |
async def cb_cancel_upload_prompt(_, query: CallbackQuery):
|
| 845 |
await query.message.delete()
|
| 846 |
|
| 847 |
|
| 848 |
# =============================================================================
|
| 849 |
+
# MESSAGE LINK INTERACTIVE PROMPT
|
| 850 |
# =============================================================================
|
| 851 |
|
| 852 |
@app.on_message(
|
|
|
|
| 858 |
links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)
|
| 859 |
if not links:
|
| 860 |
return
|
|
|
|
| 861 |
chat_str, msg_id = links[0][1], int(links[0][2])
|
| 862 |
try:
|
| 863 |
if chat_str.startswith("c/"):
|
|
|
|
| 868 |
except Exception as e:
|
| 869 |
await message.reply_text(f"❌ Could not access the message: {e}")
|
| 870 |
return
|
|
|
|
| 871 |
if not msg.media:
|
| 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
|
|
|
|
| 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([
|
| 910 |
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 911 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 912 |
])
|
| 913 |
+
await message.reply_text(f"Found file `{filename}` in the linked message. Do you want to upload it?", reply_markup=kb)
|
|
|
|
|
|
|
|
|
|
| 914 |
|
| 915 |
|
| 916 |
# =============================================================================
|
| 917 |
+
# DIRECT FILE RECEIVER (any media type)
|
| 918 |
# =============================================================================
|
| 919 |
|
| 920 |
@app.on_message(
|
|
|
|
| 965 |
'timer': None,
|
| 966 |
}
|
| 967 |
album_groups[group_id]['messages'].append((message.id, filename, file_id))
|
|
|
|
| 968 |
if album_groups[group_id]['timer']:
|
| 969 |
album_groups[group_id]['timer'].cancel()
|
| 970 |
|
|
|
|
| 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([
|
| 982 |
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 983 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
|
|
|
| 999 |
|
| 1000 |
|
| 1001 |
# =============================================================================
|
| 1002 |
+
# MAIN
|
| 1003 |
# =============================================================================
|
| 1004 |
|
| 1005 |
async def main():
|
| 1006 |
asyncio.create_task(upload_worker())
|
| 1007 |
await app.start()
|
| 1008 |
+
logger.info("Bot started successfully (tgcrypto active: %s)", app.tgcrypto)
|
| 1009 |
await asyncio.Event().wait()
|
| 1010 |
|
| 1011 |
|