Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,34 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import Optional, List, Tuple, Union
|
| 4 |
|
| 5 |
import requests
|
| 6 |
from flask import Flask
|
| 7 |
from pyrogram import Client, filters
|
| 8 |
-
from pyrogram.types import
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
|
| 11 |
|
| 12 |
# =============================================================================
|
|
@@ -19,21 +41,17 @@ BOT_TOKEN: str = os.environ["BOT_TOKEN"]
|
|
| 19 |
HF_TOKEN: str = os.environ["HF_TOKEN"]
|
| 20 |
OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
DATASET_REPO: str = "Cxops/Bzxv"
|
| 25 |
DATASET_TYPE: str = "dataset"
|
| 26 |
-
MAX_FILE_SIZE_TG: int = 1900 * 1024 * 1024
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
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 |
-
# 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,
|
|
@@ -49,32 +67,40 @@ logger = logging.getLogger("StorageBot")
|
|
| 49 |
_siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
|
| 50 |
_aes_siv = AESSIV(_siv_key)
|
| 51 |
|
|
|
|
| 52 |
def encrypt_text(plain: str) -> str:
|
|
|
|
| 53 |
token = _aes_siv.encrypt(plain.encode(), None)
|
| 54 |
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 55 |
|
|
|
|
| 56 |
def decrypt_text(encoded: str) -> str:
|
|
|
|
| 57 |
padding = 4 - len(encoded) % 4
|
| 58 |
if padding != 4:
|
| 59 |
encoded += "=" * padding
|
| 60 |
token = base64.urlsafe_b64decode(encoded.encode())
|
| 61 |
return _aes_siv.decrypt(token, None).decode()
|
| 62 |
|
|
|
|
| 63 |
def get_encrypted_folder(user_id: int) -> str:
|
| 64 |
return encrypt_text(str(user_id))
|
| 65 |
|
|
|
|
| 66 |
def get_encrypted_filename(original: str) -> str:
|
| 67 |
return encrypt_text(original)
|
| 68 |
|
|
|
|
| 69 |
# =============================================================================
|
| 70 |
-
# DATABASE
|
| 71 |
# =============================================================================
|
| 72 |
|
| 73 |
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 74 |
conn.row_factory = sqlite3.Row
|
| 75 |
conn.execute("PRAGMA journal_mode=WAL")
|
| 76 |
cursor = conn.cursor()
|
| 77 |
-
cursor.execute(
|
|
|
|
| 78 |
CREATE TABLE IF NOT EXISTS files (
|
| 79 |
user_id INTEGER,
|
| 80 |
enc_path TEXT UNIQUE,
|
|
@@ -82,9 +108,11 @@ cursor.execute("""
|
|
| 82 |
size INTEGER,
|
| 83 |
timestamp REAL
|
| 84 |
)
|
| 85 |
-
"""
|
|
|
|
| 86 |
conn.commit()
|
| 87 |
|
|
|
|
| 88 |
def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
|
| 89 |
cursor.execute(
|
| 90 |
"INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",
|
|
@@ -92,6 +120,7 @@ def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
|
|
| 92 |
)
|
| 93 |
conn.commit()
|
| 94 |
|
|
|
|
| 95 |
def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
|
| 96 |
cursor.execute(
|
| 97 |
"SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC",
|
|
@@ -99,59 +128,53 @@ def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
|
|
| 99 |
)
|
| 100 |
return [(row[0], row[1], row[2]) for row in cursor.fetchall()]
|
| 101 |
|
|
|
|
| 102 |
def db_remove_file(enc_path: str) -> None:
|
| 103 |
cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
|
| 104 |
conn.commit()
|
| 105 |
|
|
|
|
| 106 |
def db_remove_all_user_files(user_id: int) -> None:
|
| 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 |
-
"""
|
| 115 |
-
if size is not None:
|
| 116 |
-
cursor.execute(
|
| 117 |
-
"SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ? AND size = ?",
|
| 118 |
-
(user_id, orig_name, size),
|
| 119 |
-
)
|
| 120 |
-
else:
|
| 121 |
-
cursor.execute(
|
| 122 |
-
"SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ?",
|
| 123 |
-
(user_id, orig_name),
|
| 124 |
-
)
|
| 125 |
-
row = cursor.fetchone()
|
| 126 |
-
return (row[0], row[1]) if row else None
|
| 127 |
|
| 128 |
# =============================================================================
|
| 129 |
-
#
|
| 130 |
# =============================================================================
|
| 131 |
|
| 132 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
album_groups: dict[str, dict] = {}
|
| 135 |
-
|
| 136 |
|
| 137 |
def make_token() -> str:
|
| 138 |
return secrets.token_hex(8)
|
| 139 |
|
|
|
|
| 140 |
# =============================================================================
|
| 141 |
-
# FLASK HEALTH
|
| 142 |
# =============================================================================
|
| 143 |
|
| 144 |
web = Flask(__name__)
|
| 145 |
|
|
|
|
| 146 |
@web.route("/")
|
| 147 |
def home():
|
| 148 |
return "Status: OK - Bot Running"
|
| 149 |
|
|
|
|
| 150 |
def run_web():
|
| 151 |
web.run(host="0.0.0.0", port=7860)
|
| 152 |
|
|
|
|
| 153 |
# =============================================================================
|
| 154 |
-
# HUGGING FACE
|
| 155 |
# =============================================================================
|
| 156 |
|
| 157 |
hf = HfApi(token=HF_TOKEN)
|
|
@@ -164,15 +187,16 @@ app = Client(
|
|
| 164 |
)
|
| 165 |
|
| 166 |
# =============================================================================
|
| 167 |
-
#
|
| 168 |
# =============================================================================
|
| 169 |
|
| 170 |
upload_queue: asyncio.Queue = asyncio.Queue()
|
| 171 |
active_jobs: dict[int, dict] = {}
|
| 172 |
bot_start_time = time.time()
|
| 173 |
|
|
|
|
| 174 |
# =============================================================================
|
| 175 |
-
# UTILITY
|
| 176 |
# =============================================================================
|
| 177 |
|
| 178 |
def cleanup(path: str) -> None:
|
|
@@ -184,9 +208,11 @@ def cleanup(path: str) -> None:
|
|
| 184 |
except Exception:
|
| 185 |
pass
|
| 186 |
|
|
|
|
| 187 |
def get_free_disk() -> int:
|
| 188 |
return shutil.disk_usage("/").free
|
| 189 |
|
|
|
|
| 190 |
def format_size(bytes_val: int) -> str:
|
| 191 |
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
|
| 192 |
if bytes_val < 1024.0:
|
|
@@ -194,53 +220,20 @@ def format_size(bytes_val: int) -> str:
|
|
| 194 |
bytes_val /= 1024.0
|
| 195 |
return f"{bytes_val:.1f} PB"
|
| 196 |
|
|
|
|
| 197 |
def format_speed(bytes_per_sec: float) -> str:
|
| 198 |
return f"{format_size(bytes_per_sec)}/s"
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
Returns the total memory available to the container (in bytes).
|
| 203 |
-
Tries cgroup v1 limit first, then falls back to /proc/meminfo MemTotal.
|
| 204 |
-
"""
|
| 205 |
-
try:
|
| 206 |
-
with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
|
| 207 |
-
limit = int(f.read().strip())
|
| 208 |
-
if limit < 9_223_372_036_854_771_200: # less than practically infinite
|
| 209 |
-
return limit
|
| 210 |
-
except Exception:
|
| 211 |
-
pass
|
| 212 |
try:
|
| 213 |
-
with open("/proc/
|
| 214 |
for line in f:
|
| 215 |
-
if line.startswith("
|
| 216 |
-
return int(line.split()[1]) * 1024
|
| 217 |
except Exception:
|
| 218 |
-
|
| 219 |
-
return 0
|
| 220 |
|
| 221 |
-
def extract_file_size(msg: Message) -> Optional[int]:
|
| 222 |
-
if msg.document:
|
| 223 |
-
return msg.document.file_size
|
| 224 |
-
if msg.video:
|
| 225 |
-
return msg.video.file_size
|
| 226 |
-
if msg.audio:
|
| 227 |
-
return msg.audio.file_size
|
| 228 |
-
if msg.photo:
|
| 229 |
-
return msg.photo.file_size
|
| 230 |
-
if msg.animation:
|
| 231 |
-
return msg.animation.file_size
|
| 232 |
-
if msg.sticker:
|
| 233 |
-
return msg.sticker.file_size
|
| 234 |
-
if msg.video_note:
|
| 235 |
-
return msg.video_note.file_size
|
| 236 |
-
if msg.voice:
|
| 237 |
-
return msg.voice.file_size
|
| 238 |
-
return None
|
| 239 |
-
|
| 240 |
-
def check_file_size_limit(filename: str, size: Optional[int]) -> Optional[str]:
|
| 241 |
-
if size is not None and size > MAX_SINGLE_FILE_SIZE:
|
| 242 |
-
return f"❌ File `{filename}` is too large ({format_size(size)}). Maximum allowed is {format_size(MAX_SINGLE_FILE_SIZE)}."
|
| 243 |
-
return None
|
| 244 |
|
| 245 |
async def send_progress_updater(
|
| 246 |
job_id: int,
|
|
@@ -256,19 +249,15 @@ async def send_progress_updater(
|
|
| 256 |
elapsed = max(time.time() - start_time, 0.01)
|
| 257 |
current = bytes_holder[0]
|
| 258 |
speed = current / elapsed
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
eta = int((total_bytes - current) / speed)
|
| 269 |
-
text += f"ETA: {eta}s"
|
| 270 |
-
else:
|
| 271 |
-
text += "ETA: ..."
|
| 272 |
try:
|
| 273 |
await status_msg.edit_text(
|
| 274 |
text,
|
|
@@ -285,7 +274,7 @@ async def send_progress_updater(
|
|
| 285 |
|
| 286 |
|
| 287 |
# =============================================================================
|
| 288 |
-
#
|
| 289 |
# =============================================================================
|
| 290 |
|
| 291 |
async def do_upload_job(
|
|
@@ -297,8 +286,8 @@ async def do_upload_job(
|
|
| 297 |
cancel_event: asyncio.Event,
|
| 298 |
status_msg: Message,
|
| 299 |
file_id: Optional[str] = None,
|
| 300 |
-
expected_size: Optional[int] = None,
|
| 301 |
) -> None:
|
|
|
|
| 302 |
temp_dir = tempfile.mkdtemp()
|
| 303 |
local_path = None
|
| 304 |
try:
|
|
@@ -309,30 +298,21 @@ async def do_upload_job(
|
|
| 309 |
),
|
| 310 |
)
|
| 311 |
last_update = [0]
|
| 312 |
-
download_start = time.time()
|
| 313 |
-
total_size = expected_size if expected_size and expected_size > 0 else 0
|
| 314 |
|
| 315 |
async def download_progress(current, total):
|
| 316 |
-
nonlocal total_size
|
| 317 |
now = time.time()
|
| 318 |
if now - last_update[0] < 3:
|
| 319 |
return
|
| 320 |
last_update[0] = now
|
| 321 |
elapsed = max(time.time() - download_start, 0.01)
|
| 322 |
speed = current / elapsed
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
pct = (100 * current / total_size)
|
| 331 |
-
text += f"{pct:.1f}% of {format_size(total_size)}\n"
|
| 332 |
-
text += f"{format_size(current)} downloaded / {format_size(total_size)}\n"
|
| 333 |
-
else:
|
| 334 |
-
text += f"{format_size(current)} downloaded\n"
|
| 335 |
-
text += f"Speed: {format_speed(speed)}"
|
| 336 |
try:
|
| 337 |
await status_msg.edit_text(
|
| 338 |
text,
|
|
@@ -343,17 +323,18 @@ async def do_upload_job(
|
|
| 343 |
except Exception:
|
| 344 |
pass
|
| 345 |
|
|
|
|
|
|
|
| 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 |
|
|
@@ -374,6 +355,8 @@ async def do_upload_job(
|
|
| 374 |
)
|
| 375 |
|
| 376 |
loop = asyncio.get_event_loop()
|
|
|
|
|
|
|
| 377 |
def sync_upload():
|
| 378 |
hf.upload_file(
|
| 379 |
path_or_fileobj=local_path,
|
|
@@ -383,20 +366,25 @@ async def do_upload_job(
|
|
| 383 |
)
|
| 384 |
|
| 385 |
task = loop.run_in_executor(None, sync_upload)
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
|
| 392 |
if cancel_event.is_set():
|
| 393 |
try:
|
| 394 |
-
hf.delete_file(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
except Exception:
|
| 396 |
pass
|
| 397 |
await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
|
| 398 |
return
|
| 399 |
|
|
|
|
| 400 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 401 |
await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
|
| 402 |
logger.info("Uploaded %s for user %d", orig_filename, user_id)
|
|
@@ -501,12 +489,16 @@ async def do_download_job(
|
|
| 501 |
|
| 502 |
|
| 503 |
# =============================================================================
|
| 504 |
-
#
|
| 505 |
# =============================================================================
|
| 506 |
|
| 507 |
async def delete_user_file(chat_id, user_id, enc_path, token, query: CallbackQuery):
|
| 508 |
try:
|
| 509 |
-
hf.delete_file(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
db_remove_file(enc_path)
|
| 511 |
file_callback_map.pop(token, None)
|
| 512 |
await query.answer("File deleted.", show_alert=True)
|
|
@@ -523,12 +515,20 @@ async def delete_all_user_files(chat_id, user_id, query: CallbackQuery):
|
|
| 523 |
|
| 524 |
for enc_path, _, _ in user_files:
|
| 525 |
try:
|
| 526 |
-
hf.delete_file(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 527 |
except Exception:
|
| 528 |
pass
|
| 529 |
|
| 530 |
db_remove_all_user_files(user_id)
|
| 531 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
for tok in tokens_to_delete:
|
| 533 |
file_callback_map.pop(tok, None)
|
| 534 |
|
|
@@ -542,14 +542,14 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 542 |
return await message.edit_text("You have no uploaded files.", reply_markup=None)
|
| 543 |
|
| 544 |
buttons = []
|
| 545 |
-
for enc_path, orig_name,
|
| 546 |
token = make_token()
|
| 547 |
file_callback_map[token] = enc_path
|
| 548 |
-
display = f"{orig_name[:25]} ({format_size(size)})" if size else orig_name[:25]
|
| 549 |
buttons.append([
|
| 550 |
-
InlineKeyboardButton(f"📥 {
|
| 551 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 552 |
])
|
|
|
|
| 553 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
| 554 |
|
| 555 |
await message.edit_text(
|
|
@@ -558,68 +558,6 @@ async def refresh_file_list(chat_id: int, user_id: int, message: Message):
|
|
| 558 |
)
|
| 559 |
|
| 560 |
|
| 561 |
-
# =============================================================================
|
| 562 |
-
# DUPLICATE DETECTION & RENAMING
|
| 563 |
-
# =============================================================================
|
| 564 |
-
|
| 565 |
-
def build_duplicate_prompt(
|
| 566 |
-
user_id: int,
|
| 567 |
-
chat_id: int,
|
| 568 |
-
file_obj: Union[Message, str],
|
| 569 |
-
orig_filename: str,
|
| 570 |
-
expected_size: Optional[int],
|
| 571 |
-
file_id: Optional[str] = None,
|
| 572 |
-
msg_id: Optional[int] = None,
|
| 573 |
-
) -> Tuple[Optional[str], Optional[dict]]:
|
| 574 |
-
"""Returns token and prompt data if the file already exists, else (None, None)."""
|
| 575 |
-
existing = db_file_exists(user_id, orig_filename, expected_size)
|
| 576 |
-
if not existing:
|
| 577 |
-
existing = db_file_exists(user_id, orig_filename) # any size
|
| 578 |
-
if not existing:
|
| 579 |
-
return None, None
|
| 580 |
-
_, existing_size = existing
|
| 581 |
-
|
| 582 |
-
token = make_token()
|
| 583 |
-
duplicate_prompt_map[token] = {
|
| 584 |
-
'user_id': user_id,
|
| 585 |
-
'chat_id': chat_id,
|
| 586 |
-
'file_obj': file_obj,
|
| 587 |
-
'orig_filename': orig_filename,
|
| 588 |
-
'job_id': int(time.time() * 1000 + hash(orig_filename)),
|
| 589 |
-
'file_id': file_id,
|
| 590 |
-
'expected_size': expected_size,
|
| 591 |
-
'existing_size': existing_size,
|
| 592 |
-
'msg_id': msg_id, # for album duplicate retrieval
|
| 593 |
-
}
|
| 594 |
-
return token, duplicate_prompt_map[token]
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
async def send_duplicate_prompt(chat_id, token, orig_filename, expected_size, existing_size):
|
| 598 |
-
if expected_size is not None and existing_size is not None and expected_size == existing_size:
|
| 599 |
-
size_note = f" (same size: {format_size(expected_size)})"
|
| 600 |
-
else:
|
| 601 |
-
size_note = f" (existing size: {format_size(existing_size or 0)})" if existing_size else ""
|
| 602 |
-
kb = InlineKeyboardMarkup([
|
| 603 |
-
[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
|
| 604 |
-
[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],
|
| 605 |
-
])
|
| 606 |
-
await app.send_message(
|
| 607 |
-
chat_id,
|
| 608 |
-
f"⚠️ File `{orig_filename}` already exists{size_note}.\nWhat do you want to do?",
|
| 609 |
-
reply_markup=kb,
|
| 610 |
-
)
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
def generate_unique_filename(user_id: int, base: str, ext: str) -> str:
|
| 614 |
-
"""Creates a filename like base_1.ext that doesn't exist for this user yet."""
|
| 615 |
-
counter = 1
|
| 616 |
-
while True:
|
| 617 |
-
candidate = f"{base}_{counter}{ext}"
|
| 618 |
-
if not db_file_exists(user_id, candidate):
|
| 619 |
-
return candidate
|
| 620 |
-
counter += 1
|
| 621 |
-
|
| 622 |
-
|
| 623 |
# =============================================================================
|
| 624 |
# ALBUM GROUPING
|
| 625 |
# =============================================================================
|
|
@@ -628,83 +566,42 @@ async def process_album_group(media_group_id: str):
|
|
| 628 |
group_data = album_groups.pop(media_group_id, None)
|
| 629 |
if not group_data:
|
| 630 |
return
|
|
|
|
| 631 |
chat_id = group_data['chat_id']
|
| 632 |
user_id = group_data['user_id']
|
| 633 |
-
messages = group_data['messages'] # list of (message_id, filename, file_id
|
| 634 |
-
|
| 635 |
-
valid_files = []
|
| 636 |
-
skipped_names = []
|
| 637 |
-
for msg_id, filename, file_id, size in messages:
|
| 638 |
-
limit_msg = check_file_size_limit(filename, size)
|
| 639 |
-
if limit_msg:
|
| 640 |
-
skipped_names.append(filename)
|
| 641 |
-
else:
|
| 642 |
-
valid_files.append((msg_id, filename, file_id, size))
|
| 643 |
|
| 644 |
-
if
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
token
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
data['expected_size'], data['existing_size']
|
| 668 |
)
|
| 669 |
|
| 670 |
-
if non_dup:
|
| 671 |
-
if len(non_dup) == 1:
|
| 672 |
-
msg_id, filename, file_id, _ = non_dup[0]
|
| 673 |
-
token = make_token()
|
| 674 |
-
upload_prompt_map[token] = [(user_id, msg_id, filename, file_id)]
|
| 675 |
-
kb = InlineKeyboardMarkup([
|
| 676 |
-
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 677 |
-
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 678 |
-
])
|
| 679 |
-
await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
|
| 680 |
-
else:
|
| 681 |
-
files_list = "\n".join(f"• {fname} ({format_size(fsize)})" for _, fname, _, fsize in non_dup)
|
| 682 |
-
token = make_token()
|
| 683 |
-
upload_prompt_map[token] = [(user_id, msg_id, fname, fid) for msg_id, fname, fid, _ in non_dup]
|
| 684 |
-
|
| 685 |
-
button_rows = [
|
| 686 |
-
[InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")]
|
| 687 |
-
]
|
| 688 |
-
for msg_id, fname, fid, _ in non_dup:
|
| 689 |
-
individual_token = make_token()
|
| 690 |
-
upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]
|
| 691 |
-
button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
|
| 692 |
-
button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])
|
| 693 |
-
|
| 694 |
-
prompt_text = f"Received {len(non_dup)} non‑duplicate files.\n{files_list}\n\nChoose:"
|
| 695 |
-
if skipped_names:
|
| 696 |
-
prompt_text += f"\n⚠️ Skipped (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names)
|
| 697 |
-
await app.send_message(chat_id, prompt_text, reply_markup=InlineKeyboardMarkup(button_rows))
|
| 698 |
-
|
| 699 |
-
# Notify about skipped files regardless
|
| 700 |
-
if skipped_names:
|
| 701 |
-
skip_msg = f"⚠️ Skipped {len(skipped_names)} file(s) (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names)
|
| 702 |
-
if not non_dup: # only skipped message was not sent above
|
| 703 |
-
await app.send_message(chat_id, skip_msg)
|
| 704 |
-
else:
|
| 705 |
-
# Already appended to prompt, but we can send a separate one if needed; however it's included in prompt.
|
| 706 |
-
pass
|
| 707 |
-
|
| 708 |
|
| 709 |
# =============================================================================
|
| 710 |
# UPLOAD QUEUE WORKER
|
|
@@ -713,7 +610,7 @@ async def process_album_group(media_group_id: str):
|
|
| 713 |
async def upload_worker():
|
| 714 |
while True:
|
| 715 |
job = await upload_queue.get()
|
| 716 |
-
user_id, chat_id, file_obj, orig_filename, job_id, file_id
|
| 717 |
cancel_event = asyncio.Event()
|
| 718 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 719 |
|
|
@@ -731,7 +628,9 @@ async def upload_worker():
|
|
| 731 |
active_jobs[job_id]["status_msg"] = status_msg
|
| 732 |
|
| 733 |
try:
|
| 734 |
-
await do_upload_job(
|
|
|
|
|
|
|
| 735 |
finally:
|
| 736 |
active_jobs.pop(job_id, None)
|
| 737 |
upload_queue.task_done()
|
|
@@ -749,26 +648,27 @@ async def cmd_start(_, message: Message):
|
|
| 749 |
"Use /help for a full command list."
|
| 750 |
)
|
| 751 |
|
|
|
|
| 752 |
@app.on_message(filters.command("help"))
|
| 753 |
async def cmd_help(_, message: Message):
|
| 754 |
text = (
|
| 755 |
"**Available Commands:**\n\n"
|
| 756 |
-
"/start –
|
| 757 |
-
"/files – List your uploaded files (download/delete)\n"
|
| 758 |
-
"/status –
|
| 759 |
-
"/delete_all – Delete all your files (confirmation)\n"
|
| 760 |
-
"/upload <link> –
|
| 761 |
-
"/help – This help\n\n"
|
| 762 |
-
"**
|
| 763 |
-
"•
|
| 764 |
-
"•
|
| 765 |
-
"•
|
| 766 |
-
"•
|
| 767 |
-
"•
|
| 768 |
-
"• Real‑time progress with speed and ETA."
|
| 769 |
)
|
| 770 |
await message.reply_text(text, disable_web_page_preview=True)
|
| 771 |
|
|
|
|
| 772 |
@app.on_message(filters.command("status"))
|
| 773 |
async def cmd_status(_, message: Message):
|
| 774 |
free = get_free_disk()
|
|
@@ -777,24 +677,32 @@ async def cmd_status(_, message: Message):
|
|
| 777 |
try:
|
| 778 |
info = hf.dataset_info(repo_id=DATASET_REPO)
|
| 779 |
used = info.used_storage or 0
|
| 780 |
-
except Exception
|
| 781 |
-
logger.warning("Failed to fetch dataset info: %s", e)
|
| 782 |
used = 0
|
| 783 |
dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
|
| 784 |
|
| 785 |
uptime_sec = int(time.time() - bot_start_time)
|
| 786 |
uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
|
| 787 |
-
|
| 788 |
-
mem_text = f"🧠 Memory: {format_size(get_total_memory())}"
|
| 789 |
cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
|
| 790 |
|
| 791 |
-
|
| 792 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 793 |
|
| 794 |
@app.on_message(filters.command("files"))
|
| 795 |
async def cmd_files(_, message: Message):
|
| 796 |
user_id = message.from_user.id
|
| 797 |
user_files = db_get_user_files(user_id)
|
|
|
|
| 798 |
if not user_files:
|
| 799 |
enc_folder = get_encrypted_folder(user_id)
|
| 800 |
try:
|
|
@@ -815,25 +723,28 @@ async def cmd_files(_, message: Message):
|
|
| 815 |
db_add_file(user_id, path, orig_name, size)
|
| 816 |
user_files = db_get_user_files(user_id)
|
| 817 |
except Exception as e:
|
| 818 |
-
logger.warning("Fallback scan failed: %s", e)
|
|
|
|
| 819 |
if not user_files:
|
| 820 |
return await message.reply_text("You have no uploaded files.")
|
|
|
|
| 821 |
buttons = []
|
| 822 |
-
for enc_path, orig_name,
|
| 823 |
token = make_token()
|
| 824 |
file_callback_map[token] = enc_path
|
| 825 |
-
display = f"{orig_name[:20]} ({format_size(size)})" if size else orig_name[:20]
|
| 826 |
buttons.append([
|
| 827 |
-
InlineKeyboardButton(f"📥 {
|
| 828 |
InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
|
| 829 |
])
|
|
|
|
| 830 |
buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
|
|
|
|
| 831 |
await message.reply_text(
|
| 832 |
"Your uploaded files (click to download, delete to remove):",
|
| 833 |
reply_markup=InlineKeyboardMarkup(buttons),
|
| 834 |
-
disable_web_page_preview=True,
|
| 835 |
)
|
| 836 |
|
|
|
|
| 837 |
@app.on_message(filters.command("delete_all"))
|
| 838 |
async def cmd_delete_all(_, message: Message):
|
| 839 |
user_id = message.from_user.id
|
|
@@ -841,17 +752,23 @@ async def cmd_delete_all(_, message: Message):
|
|
| 841 |
[InlineKeyboardButton("Yes, delete all my files", callback_data=f"delete_all:{user_id}")],
|
| 842 |
[InlineKeyboardButton("Cancel", callback_data="cancel_upload:0")],
|
| 843 |
])
|
| 844 |
-
await message.reply_text(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
|
| 846 |
@app.on_message(filters.command("upload"))
|
| 847 |
async def cmd_upload(_, message: Message):
|
| 848 |
args = message.text.split(maxsplit=1)
|
| 849 |
if len(args) < 2:
|
| 850 |
return await message.reply_text("Usage: /upload <link>")
|
|
|
|
| 851 |
link = args[1].strip()
|
| 852 |
match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)
|
| 853 |
if not match:
|
| 854 |
return await message.reply_text("Invalid Telegram message link.")
|
|
|
|
| 855 |
chat_str, msg_id = match.group(2), int(match.group(3))
|
| 856 |
try:
|
| 857 |
if chat_str.startswith("c/"):
|
|
@@ -861,107 +778,52 @@ async def cmd_upload(_, message: Message):
|
|
| 861 |
msg = await app.get_messages(chat_id, msg_id)
|
| 862 |
except Exception as e:
|
| 863 |
return await message.reply_text(f"❌ Could not fetch the message: {e}")
|
| 864 |
-
if not msg.media:
|
| 865 |
-
return await message.reply_text("The linked message doesn't contain a downloadable file.")
|
| 866 |
-
file_id, expected_size, filename = _extract_file_info(msg)
|
| 867 |
-
if not filename:
|
| 868 |
-
return await message.reply_text("Could not determine file name.")
|
| 869 |
-
|
| 870 |
-
limit_err = check_file_size_limit(filename, expected_size)
|
| 871 |
-
if limit_err:
|
| 872 |
-
return await message.reply_text(limit_err)
|
| 873 |
-
|
| 874 |
-
token, data = build_duplicate_prompt(
|
| 875 |
-
message.from_user.id, message.chat.id, file_id, filename, expected_size, file_id
|
| 876 |
-
)
|
| 877 |
-
if token:
|
| 878 |
-
await send_duplicate_prompt(
|
| 879 |
-
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 880 |
-
)
|
| 881 |
-
return
|
| 882 |
-
|
| 883 |
-
job_id = int(time.time() * 1000 + hash(filename))
|
| 884 |
-
active_jobs[job_id] = {"status": "queued"}
|
| 885 |
-
await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size))
|
| 886 |
-
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
| 887 |
|
|
|
|
|
|
|
| 888 |
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
expected_size = extract_file_size(msg)
|
| 892 |
if msg.document:
|
| 893 |
-
|
|
|
|
| 894 |
elif msg.video:
|
| 895 |
-
|
|
|
|
| 896 |
elif msg.audio:
|
| 897 |
-
|
|
|
|
| 898 |
elif msg.photo:
|
| 899 |
-
|
|
|
|
| 900 |
elif msg.animation:
|
| 901 |
-
|
|
|
|
| 902 |
elif msg.sticker:
|
| 903 |
if msg.sticker.is_animated:
|
| 904 |
-
|
| 905 |
elif msg.sticker.is_video:
|
| 906 |
-
|
| 907 |
else:
|
| 908 |
-
|
| 909 |
-
|
| 910 |
elif msg.video_note:
|
| 911 |
-
|
|
|
|
| 912 |
elif msg.voice:
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
# =============================================================================
|
| 918 |
-
# DUPLICATE CALLBACK HANDLERS
|
| 919 |
-
# =============================================================================
|
| 920 |
-
|
| 921 |
-
@app.on_callback_query(filters.regex("^dup_skip:"))
|
| 922 |
-
async def cb_dup_skip(_, query: CallbackQuery):
|
| 923 |
-
token = query.data.split(":")[-1]
|
| 924 |
-
data = duplicate_prompt_map.pop(token, None)
|
| 925 |
-
if not data:
|
| 926 |
-
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 927 |
-
await query.message.edit_text("❌ Upload skipped.")
|
| 928 |
-
await query.answer("Skipped.")
|
| 929 |
-
|
| 930 |
-
@app.on_callback_query(filters.regex("^dup_keep:"))
|
| 931 |
-
async def cb_dup_keep(_, query: CallbackQuery):
|
| 932 |
-
token = query.data.split(":")[-1]
|
| 933 |
-
data = duplicate_prompt_map.pop(token, None)
|
| 934 |
-
if not data:
|
| 935 |
-
return await query.answer("This prompt is no longer valid.", show_alert=True)
|
| 936 |
-
|
| 937 |
-
# Retrieve the actual file object if we only have a message id (from album)
|
| 938 |
-
file_obj = data.get('file_obj')
|
| 939 |
-
if file_obj is None:
|
| 940 |
-
try:
|
| 941 |
-
file_obj = await app.get_messages(data['chat_id'], data['msg_id'])
|
| 942 |
-
except Exception:
|
| 943 |
-
return await query.answer("Original message no longer available.", show_alert=True)
|
| 944 |
-
|
| 945 |
-
base, ext = os.path.splitext(data['orig_filename'])
|
| 946 |
-
new_filename = generate_unique_filename(data['user_id'], base, ext)
|
| 947 |
|
| 948 |
-
job_id =
|
| 949 |
active_jobs[job_id] = {"status": "queued"}
|
| 950 |
-
await upload_queue.put((
|
| 951 |
-
|
| 952 |
-
data['chat_id'],
|
| 953 |
-
file_obj,
|
| 954 |
-
new_filename,
|
| 955 |
-
job_id,
|
| 956 |
-
data['file_id'],
|
| 957 |
-
data['expected_size'],
|
| 958 |
-
))
|
| 959 |
-
await query.message.edit_text(f"📦 `{new_filename}` queued as a duplicate.")
|
| 960 |
-
await query.answer("Duplicate will be uploaded with a new name.")
|
| 961 |
|
| 962 |
|
| 963 |
# =============================================================================
|
| 964 |
-
# CALLBACK HANDLERS
|
| 965 |
# =============================================================================
|
| 966 |
|
| 967 |
@app.on_callback_query(filters.regex("^get:"))
|
|
@@ -970,20 +832,27 @@ async def cb_get_file(_, query: CallbackQuery):
|
|
| 970 |
enc_path = file_callback_map.get(token)
|
| 971 |
if not enc_path:
|
| 972 |
return await query.answer("Invalid or expired link. Use /files again.", show_alert=True)
|
|
|
|
| 973 |
job_id = int(time.time() * 1000)
|
| 974 |
cancel_event = asyncio.Event()
|
| 975 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
|
|
|
|
| 976 |
try:
|
| 977 |
orig_name = decrypt_text(enc_path.split("/")[-1])
|
| 978 |
except Exception:
|
| 979 |
orig_name = enc_path.split("/")[-1]
|
|
|
|
| 980 |
status_msg = await query.message.edit_text(
|
| 981 |
"⏳ Preparing download...",
|
| 982 |
-
reply_markup=InlineKeyboardMarkup(
|
|
|
|
|
|
|
| 983 |
)
|
| 984 |
active_jobs[job_id]["status_msg"] = status_msg
|
|
|
|
| 985 |
asyncio.create_task(do_download_job(query.message.chat.id, enc_path, orig_name, job_id, cancel_event, status_msg))
|
| 986 |
|
|
|
|
| 987 |
@app.on_callback_query(filters.regex("^delete:"))
|
| 988 |
async def cb_delete_file(_, query: CallbackQuery):
|
| 989 |
token = query.data.replace("delete:", "")
|
|
@@ -993,11 +862,13 @@ async def cb_delete_file(_, query: CallbackQuery):
|
|
| 993 |
user_id = query.from_user.id
|
| 994 |
await delete_user_file(query.message.chat.id, user_id, enc_path, token, query)
|
| 995 |
|
|
|
|
| 996 |
@app.on_callback_query(filters.regex("^delete_all:"))
|
| 997 |
async def cb_delete_all(_, query: CallbackQuery):
|
| 998 |
user_id = int(query.data.split(":")[-1])
|
| 999 |
await delete_all_user_files(query.message.chat.id, user_id, query)
|
| 1000 |
|
|
|
|
| 1001 |
@app.on_callback_query(filters.regex("^cancel_job:"))
|
| 1002 |
async def cb_cancel_job(_, query: CallbackQuery):
|
| 1003 |
_, job_id_str = query.data.split(":")
|
|
@@ -1008,17 +879,21 @@ async def cb_cancel_job(_, query: CallbackQuery):
|
|
| 1008 |
else:
|
| 1009 |
await query.answer("Job not found.")
|
| 1010 |
|
|
|
|
| 1011 |
@app.on_callback_query(filters.regex("^upload:"))
|
| 1012 |
async def cb_upload(_, query: CallbackQuery):
|
| 1013 |
token = query.data.replace("upload:", "")
|
| 1014 |
entries = upload_prompt_map.pop(token, None)
|
| 1015 |
if not entries:
|
| 1016 |
return await query.answer("Prompt expired.", show_alert=True)
|
|
|
|
| 1017 |
for entry in entries:
|
| 1018 |
user_id = entry[0]
|
| 1019 |
-
if len(entry) == 4
|
| 1020 |
-
#
|
| 1021 |
-
msg_id
|
|
|
|
|
|
|
| 1022 |
try:
|
| 1023 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 1024 |
except Exception:
|
|
@@ -1028,44 +903,32 @@ async def cb_upload(_, query: CallbackQuery):
|
|
| 1028 |
await query.answer(f"File {filename} no longer available.", show_alert=True)
|
| 1029 |
continue
|
| 1030 |
file_obj = file_msg
|
| 1031 |
-
expected_size = extract_file_size(file_msg)
|
| 1032 |
-
limit_err = check_file_size_limit(filename, expected_size)
|
| 1033 |
-
if limit_err:
|
| 1034 |
-
await query.message.reply_text(limit_err)
|
| 1035 |
-
continue
|
| 1036 |
-
token2, data = build_duplicate_prompt(
|
| 1037 |
-
user_id, query.message.chat.id, file_obj, filename, expected_size, file_id
|
| 1038 |
-
)
|
| 1039 |
-
if token2:
|
| 1040 |
-
await send_duplicate_prompt(
|
| 1041 |
-
query.message.chat.id, token2, filename, expected_size, data['existing_size']
|
| 1042 |
-
)
|
| 1043 |
-
continue
|
| 1044 |
else:
|
| 1045 |
-
#
|
| 1046 |
-
file_id
|
| 1047 |
-
|
| 1048 |
-
limit_err = check_file_size_limit(filename, expected_size)
|
| 1049 |
-
if limit_err:
|
| 1050 |
-
await query.message.reply_text(limit_err)
|
| 1051 |
-
continue
|
| 1052 |
file_obj = file_id
|
| 1053 |
|
| 1054 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 1055 |
active_jobs[job_id] = {"status": "queued"}
|
| 1056 |
-
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id
|
|
|
|
| 1057 |
await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)
|
| 1058 |
|
|
|
|
| 1059 |
@app.on_callback_query(filters.regex("^upload_all:"))
|
| 1060 |
async def cb_upload_all(_, query: CallbackQuery):
|
| 1061 |
token = query.data.replace("upload_all:", "")
|
| 1062 |
entries = upload_prompt_map.pop(token, None)
|
| 1063 |
if not entries:
|
| 1064 |
return await query.answer("Prompt expired.", show_alert=True)
|
|
|
|
| 1065 |
for entry in entries:
|
| 1066 |
user_id = entry[0]
|
| 1067 |
-
if len(entry) == 4
|
| 1068 |
-
msg_id
|
|
|
|
|
|
|
| 1069 |
try:
|
| 1070 |
file_msg = await app.get_messages(query.message.chat.id, msg_id)
|
| 1071 |
except Exception:
|
|
@@ -1073,40 +936,25 @@ async def cb_upload_all(_, query: CallbackQuery):
|
|
| 1073 |
if not file_msg:
|
| 1074 |
continue
|
| 1075 |
file_obj = file_msg
|
| 1076 |
-
expected_size = extract_file_size(file_msg)
|
| 1077 |
-
limit_err = check_file_size_limit(filename, expected_size)
|
| 1078 |
-
if limit_err:
|
| 1079 |
-
await query.message.reply_text(limit_err)
|
| 1080 |
-
continue
|
| 1081 |
-
token2, data = build_duplicate_prompt(
|
| 1082 |
-
user_id, query.message.chat.id, file_obj, filename, expected_size, file_id
|
| 1083 |
-
)
|
| 1084 |
-
if token2:
|
| 1085 |
-
await send_duplicate_prompt(
|
| 1086 |
-
query.message.chat.id, token2, filename, expected_size, data['existing_size']
|
| 1087 |
-
)
|
| 1088 |
-
continue
|
| 1089 |
else:
|
| 1090 |
-
file_id
|
| 1091 |
-
|
| 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 |
file_obj = file_id
|
| 1097 |
|
| 1098 |
job_id = int(time.time() * 1000 + hash(filename))
|
| 1099 |
active_jobs[job_id] = {"status": "queued"}
|
| 1100 |
-
await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id
|
|
|
|
| 1101 |
await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)
|
| 1102 |
|
|
|
|
| 1103 |
@app.on_callback_query(filters.regex("^cancel_upload:"))
|
| 1104 |
async def cb_cancel_upload_prompt(_, query: CallbackQuery):
|
| 1105 |
await query.message.delete()
|
| 1106 |
|
| 1107 |
|
| 1108 |
# =============================================================================
|
| 1109 |
-
# MESSAGE LINK
|
| 1110 |
# =============================================================================
|
| 1111 |
|
| 1112 |
@app.on_message(
|
|
@@ -1118,6 +966,7 @@ async def on_message_link(client, message: Message):
|
|
| 1118 |
links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)
|
| 1119 |
if not links:
|
| 1120 |
return
|
|
|
|
| 1121 |
chat_str, msg_id = links[0][1], int(links[0][2])
|
| 1122 |
try:
|
| 1123 |
if chat_str.startswith("c/"):
|
|
@@ -1128,38 +977,61 @@ async def on_message_link(client, message: Message):
|
|
| 1128 |
except Exception as e:
|
| 1129 |
await message.reply_text(f"❌ Could not access the message: {e}")
|
| 1130 |
return
|
|
|
|
| 1131 |
if not msg.media:
|
| 1132 |
await message.reply_text("The linked message does not contain any downloadable file.")
|
| 1133 |
return
|
| 1134 |
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
|
| 1140 |
-
|
| 1141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1142 |
|
| 1143 |
-
|
| 1144 |
-
|
| 1145 |
-
)
|
| 1146 |
-
if token:
|
| 1147 |
-
await send_duplicate_prompt(
|
| 1148 |
-
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 1149 |
-
)
|
| 1150 |
-
return
|
| 1151 |
|
| 1152 |
-
upload_token = make_token()
|
| 1153 |
-
upload_prompt_map[upload_token] = [(message.from_user.id, file_id, filename, expected_size)]
|
| 1154 |
kb = InlineKeyboardMarkup([
|
| 1155 |
-
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{
|
| 1156 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1157 |
])
|
| 1158 |
-
await message.reply_text(
|
|
|
|
|
|
|
|
|
|
| 1159 |
|
| 1160 |
|
| 1161 |
# =============================================================================
|
| 1162 |
-
# DIRECT FILE RECEIVER
|
| 1163 |
# =============================================================================
|
| 1164 |
|
| 1165 |
@app.on_message(
|
|
@@ -1167,10 +1039,39 @@ async def on_message_link(client, message: Message):
|
|
| 1167 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 1168 |
)
|
| 1169 |
async def on_direct_file(_, message: Message):
|
| 1170 |
-
|
| 1171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1172 |
return
|
| 1173 |
|
|
|
|
| 1174 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 1175 |
group_id = str(message.media_group_id)
|
| 1176 |
if group_id not in album_groups:
|
|
@@ -1180,7 +1081,8 @@ async def on_direct_file(_, message: Message):
|
|
| 1180 |
'messages': [],
|
| 1181 |
'timer': None,
|
| 1182 |
}
|
| 1183 |
-
album_groups[group_id]['messages'].append((message.id, filename, file_id
|
|
|
|
| 1184 |
if album_groups[group_id]['timer']:
|
| 1185 |
album_groups[group_id]['timer'].cancel()
|
| 1186 |
|
|
@@ -1191,23 +1093,12 @@ async def on_direct_file(_, message: Message):
|
|
| 1191 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1192 |
return
|
| 1193 |
|
| 1194 |
-
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
token, data = build_duplicate_prompt(
|
| 1199 |
-
message.from_user.id, message.chat.id, message, filename, expected_size, file_id
|
| 1200 |
-
)
|
| 1201 |
-
if token:
|
| 1202 |
-
await send_duplicate_prompt(
|
| 1203 |
-
message.chat.id, token, filename, expected_size, data['existing_size']
|
| 1204 |
-
)
|
| 1205 |
-
return
|
| 1206 |
|
| 1207 |
-
upload_token = make_token()
|
| 1208 |
-
upload_prompt_map[upload_token] = [(message.from_user.id, message.id, filename, file_id)]
|
| 1209 |
kb = InlineKeyboardMarkup([
|
| 1210 |
-
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{
|
| 1211 |
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 1212 |
])
|
| 1213 |
await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)
|
|
@@ -1227,13 +1118,13 @@ def keepalive():
|
|
| 1227 |
|
| 1228 |
|
| 1229 |
# =============================================================================
|
| 1230 |
-
# MAIN
|
| 1231 |
# =============================================================================
|
| 1232 |
|
| 1233 |
async def main():
|
| 1234 |
asyncio.create_task(upload_worker())
|
| 1235 |
await app.start()
|
| 1236 |
-
logger.info("Bot started successfully
|
| 1237 |
await asyncio.Event().wait()
|
| 1238 |
|
| 1239 |
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import base64
|
| 6 |
+
import hashlib
|
| 7 |
+
import shutil
|
| 8 |
+
import logging
|
| 9 |
+
import secrets
|
| 10 |
+
import sqlite3
|
| 11 |
+
import tempfile
|
| 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 |
+
InlineKeyboardMarkup,
|
| 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 |
HF_TOKEN: str = os.environ["HF_TOKEN"]
|
| 42 |
OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
|
| 43 |
|
| 44 |
+
# Hard‑coded Space URL for keep‑alive pings
|
| 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 # 1900 MB per part
|
| 50 |
+
MIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024 # 45 GB
|
| 51 |
+
DATASET_MAX_SIZE: int = int(8.7 * 1024**4) # 8.7 TB
|
| 52 |
+
KEEPALIVE_INTERVAL: int = 300 # 5 minutes
|
|
|
|
|
|
|
| 53 |
DB_PATH: str = "bot_files.db"
|
| 54 |
|
|
|
|
|
|
|
|
|
|
| 55 |
# Logging
|
| 56 |
logging.basicConfig(
|
| 57 |
level=logging.INFO,
|
|
|
|
| 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 |
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 |
)
|
| 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 |
)
|
| 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 |
+
# CALLBACK TOKEN MAPS
|
| 144 |
# =============================================================================
|
| 145 |
|
| 146 |
file_callback_map: dict[str, str] = {} # token → enc_path
|
| 147 |
+
# Each entry: tuple with 3 or 4 elements.
|
| 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 SERVER
|
| 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 CLIENT & PYROGRAM BOT
|
| 178 |
# =============================================================================
|
| 179 |
|
| 180 |
hf = HfApi(token=HF_TOKEN)
|
|
|
|
| 187 |
)
|
| 188 |
|
| 189 |
# =============================================================================
|
| 190 |
+
# ASYNC QUEUE & STATE
|
| 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 FUNCTIONS
|
| 200 |
# =============================================================================
|
| 201 |
|
| 202 |
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 |
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:
|
| 231 |
for line in f:
|
| 232 |
+
if line.startswith("VmRSS:"):
|
| 233 |
+
return format_size(int(line.split()[1]) * 1024)
|
| 234 |
except Exception:
|
| 235 |
+
return "unknown"
|
|
|
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
async def send_progress_updater(
|
| 239 |
job_id: int,
|
|
|
|
| 249 |
elapsed = max(time.time() - start_time, 0.01)
|
| 250 |
current = bytes_holder[0]
|
| 251 |
speed = current / elapsed
|
| 252 |
+
pct = (100 * current / total_bytes) if total_bytes else 0
|
| 253 |
+
eta = int((total_bytes - current) / speed) if speed > 0 else -1
|
| 254 |
+
text = (
|
| 255 |
+
f"📤 Sending to Telegram...\n"
|
| 256 |
+
f"{pct:.1f}% of {format_size(total_bytes)}\n"
|
| 257 |
+
f"{format_size(current)} sent\n"
|
| 258 |
+
f"Speed: {format_speed(speed)}\n"
|
| 259 |
+
f"ETA: {eta}s" if eta >= 0 else "ETA: ..."
|
| 260 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
try:
|
| 262 |
await status_msg.edit_text(
|
| 263 |
text,
|
|
|
|
| 274 |
|
| 275 |
|
| 276 |
# =============================================================================
|
| 277 |
+
# UPLOAD / DOWNLOAD JOBS
|
| 278 |
# =============================================================================
|
| 279 |
|
| 280 |
async def do_upload_job(
|
|
|
|
| 286 |
cancel_event: asyncio.Event,
|
| 287 |
status_msg: Message,
|
| 288 |
file_id: Optional[str] = None,
|
|
|
|
| 289 |
) -> None:
|
| 290 |
+
"""Download file from Telegram (by message or file_id) and upload to HF."""
|
| 291 |
temp_dir = tempfile.mkdtemp()
|
| 292 |
local_path = None
|
| 293 |
try:
|
|
|
|
| 298 |
),
|
| 299 |
)
|
| 300 |
last_update = [0]
|
|
|
|
|
|
|
| 301 |
|
| 302 |
async def download_progress(current, total):
|
|
|
|
| 303 |
now = time.time()
|
| 304 |
if now - last_update[0] < 3:
|
| 305 |
return
|
| 306 |
last_update[0] = now
|
| 307 |
elapsed = max(time.time() - download_start, 0.01)
|
| 308 |
speed = current / elapsed
|
| 309 |
+
pct = (100 * current / total) if total else 0
|
| 310 |
+
text = (
|
| 311 |
+
f"⬇️ Downloading from Telegram...\n"
|
| 312 |
+
f"{pct:.1f}% of {format_size(total)}\n"
|
| 313 |
+
f"{format_size(current)} downloaded\n"
|
| 314 |
+
f"Speed: {format_speed(speed)}"
|
| 315 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
try:
|
| 317 |
await status_msg.edit_text(
|
| 318 |
text,
|
|
|
|
| 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),
|
|
|
|
| 338 |
progress=download_progress,
|
| 339 |
)
|
| 340 |
|
|
|
|
| 355 |
)
|
| 356 |
|
| 357 |
loop = asyncio.get_event_loop()
|
| 358 |
+
upload_done = loop.create_future()
|
| 359 |
+
|
| 360 |
def sync_upload():
|
| 361 |
hf.upload_file(
|
| 362 |
path_or_fileobj=local_path,
|
|
|
|
| 366 |
)
|
| 367 |
|
| 368 |
task = loop.run_in_executor(None, sync_upload)
|
| 369 |
+
|
| 370 |
+
while not task.done():
|
| 371 |
+
if cancel_event.is_set():
|
| 372 |
+
break
|
| 373 |
+
await asyncio.sleep(1)
|
| 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)
|
| 385 |
return
|
| 386 |
|
| 387 |
+
await task
|
| 388 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 389 |
await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
|
| 390 |
logger.info("Uploaded %s for user %d", orig_filename, user_id)
|
|
|
|
| 489 |
|
| 490 |
|
| 491 |
# =============================================================================
|
| 492 |
+
# DELETE FUNCTIONS
|
| 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 |
|
| 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 |
|
|
|
|
| 542 |
return await message.edit_text("You have no uploaded files.", reply_markup=None)
|
| 543 |
|
| 544 |
buttons = []
|
| 545 |
+
for enc_path, orig_name, _ in user_files:
|
| 546 |
token = make_token()
|
| 547 |
file_callback_map[token] = enc_path
|
|
|
|
| 548 |
buttons.append([
|
| 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(
|
|
|
|
| 558 |
)
|
| 559 |
|
| 560 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
# =============================================================================
|
| 562 |
# ALBUM GROUPING
|
| 563 |
# =============================================================================
|
|
|
|
| 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'] # list of (message_id, filename, file_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
|
| 574 |
+
if len(messages) == 1:
|
| 575 |
+
msg_id, filename, file_id = messages[0]
|
| 576 |
+
token = make_token()
|
| 577 |
+
upload_prompt_map[token] = [(user_id, msg_id, filename, file_id)]
|
| 578 |
+
kb = InlineKeyboardMarkup([
|
| 579 |
+
[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
|
| 580 |
+
[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
|
| 581 |
+
])
|
| 582 |
+
await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
|
| 583 |
+
else:
|
| 584 |
+
files_list = "\n".join(f"• {fname}" for _, fname, _ in messages)
|
| 585 |
+
token = make_token()
|
| 586 |
+
upload_prompt_map[token] = [(user_id, msg_id, fname, fid) for msg_id, fname, fid in messages]
|
| 587 |
+
|
| 588 |
+
button_rows = [
|
| 589 |
+
[InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")]
|
| 590 |
+
]
|
| 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 |
# =============================================================================
|
| 607 |
# UPLOAD QUEUE WORKER
|
|
|
|
| 610 |
async def upload_worker():
|
| 611 |
while True:
|
| 612 |
job = await upload_queue.get()
|
| 613 |
+
user_id, chat_id, file_obj, orig_filename, job_id, file_id = job
|
| 614 |
cancel_event = asyncio.Event()
|
| 615 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 616 |
|
|
|
|
| 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 |
"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 – Show welcome message\n"
|
| 657 |
+
"/files – List your uploaded files (with download/delete buttons)\n"
|
| 658 |
+
"/status – Show system & dataset space\n"
|
| 659 |
+
"/delete_all – Delete all your files (confirmation button)\n"
|
| 660 |
+
"/upload <link> – Directly upload a file from a Telegram message link\n"
|
| 661 |
+
"/help – This help text\n\n"
|
| 662 |
+
"**How to use:**\n"
|
| 663 |
+
"• Send any file (document, video, audio, photo, sticker, voice, etc.) → bot asks to upload.\n"
|
| 664 |
+
"• Send multiple files as an album → bot shows one message with 'Upload All' + individual buttons.\n"
|
| 665 |
+
"• Send a message link (like https://t.me/.../123) → bot fetches the file and asks to upload.\n"
|
| 666 |
+
"• Use /upload <link> to skip the prompt and upload instantly.\n"
|
| 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()
|
|
|
|
| 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 |
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 for user %d: %s", user_id, e)
|
| 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()
|
| 734 |
file_callback_map[token] = enc_path
|
|
|
|
| 735 |
buttons.append([
|
| 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 (click to download, delete to remove):",
|
| 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 |
[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 |
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 any downloadable file.")
|
| 784 |
|
| 785 |
+
# Extract file_id and filename
|
| 786 |
+
file_id = None
|
|
|
|
| 787 |
if msg.document:
|
| 788 |
+
filename = msg.document.file_name
|
| 789 |
+
file_id = msg.document.file_id
|
| 790 |
elif msg.video:
|
| 791 |
+
filename = msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
|
| 792 |
+
file_id = msg.video.file_id
|
| 793 |
elif msg.audio:
|
| 794 |
+
filename = msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
|
| 795 |
+
file_id = msg.audio.file_id
|
| 796 |
elif msg.photo:
|
| 797 |
+
filename = f"{msg.photo.file_unique_id}.jpg"
|
| 798 |
+
file_id = msg.photo.file_id
|
| 799 |
elif msg.animation:
|
| 800 |
+
filename = msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
|
| 801 |
+
file_id = msg.animation.file_id
|
| 802 |
elif msg.sticker:
|
| 803 |
if msg.sticker.is_animated:
|
| 804 |
+
filename = f"{msg.sticker.file_unique_id}.tgs"
|
| 805 |
elif msg.sticker.is_video:
|
| 806 |
+
filename = f"{msg.sticker.file_unique_id}.webm"
|
| 807 |
else:
|
| 808 |
+
filename = f"{msg.sticker.file_unique_id}.webp"
|
| 809 |
+
file_id = msg.sticker.file_id
|
| 810 |
elif msg.video_note:
|
| 811 |
+
filename = f"{msg.video_note.file_unique_id}.mp4"
|
| 812 |
+
file_id = msg.video_note.file_id
|
| 813 |
elif msg.voice:
|
| 814 |
+
filename = f"{msg.voice.file_unique_id}.ogg"
|
| 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))
|
| 822 |
+
await message.reply_text(f"📦 `{filename}` queued for upload.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
|
| 824 |
|
| 825 |
# =============================================================================
|
| 826 |
+
# CALLBACK HANDLERS
|
| 827 |
# =============================================================================
|
| 828 |
|
| 829 |
@app.on_callback_query(filters.regex("^get:"))
|
|
|
|
| 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 |
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 |
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 |
+
# Local: (user_id, msg_id, filename, file_id)
|
| 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:
|
|
|
|
| 903 |
await query.answer(f"File {filename} no longer available.", show_alert=True)
|
| 904 |
continue
|
| 905 |
file_obj = file_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 906 |
else:
|
| 907 |
+
# Remote: (user_id, file_id, filename)
|
| 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:
|
|
|
|
| 936 |
if not file_msg:
|
| 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 HANDLER (interactive prompt)
|
| 958 |
# =============================================================================
|
| 959 |
|
| 960 |
@app.on_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 |
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
|
| 989 |
+
file_id = msg.document.file_id
|
| 990 |
+
elif msg.video:
|
| 991 |
+
filename = msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
|
| 992 |
+
file_id = msg.video.file_id
|
| 993 |
+
elif msg.audio:
|
| 994 |
+
filename = msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
|
| 995 |
+
file_id = msg.audio.file_id
|
| 996 |
+
elif msg.photo:
|
| 997 |
+
filename = f"{msg.photo.file_unique_id}.jpg"
|
| 998 |
+
file_id = msg.photo.file_id
|
| 999 |
+
elif msg.animation:
|
| 1000 |
+
filename = msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
|
| 1001 |
+
file_id = msg.animation.file_id
|
| 1002 |
+
elif msg.sticker:
|
| 1003 |
+
if msg.sticker.is_animated:
|
| 1004 |
+
filename = f"{msg.sticker.file_unique_id}.tgs"
|
| 1005 |
+
elif msg.sticker.is_video:
|
| 1006 |
+
filename = f"{msg.sticker.file_unique_id}.webm"
|
| 1007 |
+
else:
|
| 1008 |
+
filename = f"{msg.sticker.file_unique_id}.webp"
|
| 1009 |
+
file_id = msg.sticker.file_id
|
| 1010 |
+
elif msg.video_note:
|
| 1011 |
+
filename = f"{msg.video_note.file_unique_id}.mp4"
|
| 1012 |
+
file_id = msg.video_note.file_id
|
| 1013 |
+
elif msg.voice:
|
| 1014 |
+
filename = f"{msg.voice.file_unique_id}.ogg"
|
| 1015 |
+
file_id = msg.voice.file_id
|
| 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 supported media)
|
| 1035 |
# =============================================================================
|
| 1036 |
|
| 1037 |
@app.on_message(
|
|
|
|
| 1039 |
| filters.animation | filters.sticker | filters.video_note | filters.voice
|
| 1040 |
)
|
| 1041 |
async def on_direct_file(_, message: Message):
|
| 1042 |
+
if message.document:
|
| 1043 |
+
filename = message.document.file_name
|
| 1044 |
+
file_id = message.document.file_id
|
| 1045 |
+
elif message.video:
|
| 1046 |
+
filename = message.video.file_name or f"{message.video.file_unique_id}.mp4"
|
| 1047 |
+
file_id = message.video.file_id
|
| 1048 |
+
elif message.audio:
|
| 1049 |
+
filename = message.audio.file_name or f"{message.audio.file_unique_id}.mp3"
|
| 1050 |
+
file_id = message.audio.file_id
|
| 1051 |
+
elif message.photo:
|
| 1052 |
+
filename = f"{message.photo.file_unique_id}.jpg"
|
| 1053 |
+
file_id = message.photo.file_id
|
| 1054 |
+
elif message.animation:
|
| 1055 |
+
filename = message.animation.file_name or f"{message.animation.file_unique_id}.mp4"
|
| 1056 |
+
file_id = message.animation.file_id
|
| 1057 |
+
elif message.sticker:
|
| 1058 |
+
if message.sticker.is_animated:
|
| 1059 |
+
filename = f"{message.sticker.file_unique_id}.tgs"
|
| 1060 |
+
elif message.sticker.is_video:
|
| 1061 |
+
filename = f"{message.sticker.file_unique_id}.webm"
|
| 1062 |
+
else:
|
| 1063 |
+
filename = f"{message.sticker.file_unique_id}.webp"
|
| 1064 |
+
file_id = message.sticker.file_id
|
| 1065 |
+
elif message.video_note:
|
| 1066 |
+
filename = f"{message.video_note.file_unique_id}.mp4"
|
| 1067 |
+
file_id = message.video_note.file_id
|
| 1068 |
+
elif message.voice:
|
| 1069 |
+
filename = f"{message.voice.file_unique_id}.ogg"
|
| 1070 |
+
file_id = message.voice.file_id
|
| 1071 |
+
else:
|
| 1072 |
return
|
| 1073 |
|
| 1074 |
+
# Album grouping
|
| 1075 |
if message.media_group_id and (message.photo or message.video or message.document):
|
| 1076 |
group_id = str(message.media_group_id)
|
| 1077 |
if group_id not in album_groups:
|
|
|
|
| 1081 |
'messages': [],
|
| 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 |
album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
|
| 1094 |
return
|
| 1095 |
|
| 1096 |
+
# Single file – local entry: (user_id, msg_id, filename, file_id)
|
| 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")],
|
| 1103 |
])
|
| 1104 |
await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)
|
|
|
|
| 1118 |
|
| 1119 |
|
| 1120 |
# =============================================================================
|
| 1121 |
+
# MAIN ENTRY POINT
|
| 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 |
|