Update app.py
Browse files
app.py
CHANGED
|
@@ -7,13 +7,14 @@ import threading
|
|
| 7 |
import asyncio
|
| 8 |
import sqlite3
|
| 9 |
import tempfile
|
|
|
|
| 10 |
from typing import Optional
|
| 11 |
|
| 12 |
import requests
|
| 13 |
from flask import Flask
|
| 14 |
from pyrogram import Client, filters
|
| 15 |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 16 |
-
from huggingface_hub import HfApi,
|
| 17 |
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
|
| 18 |
|
| 19 |
# --------------- CONFIG ---------------
|
|
@@ -29,18 +30,15 @@ MIN_FREE_DISK = 45 * 1024 * 1024 * 1024 # 45 GB
|
|
| 29 |
KEEPALIVE_INTERVAL = 300 # 5 minutes
|
| 30 |
DB_PATH = "bot_files.db"
|
| 31 |
|
| 32 |
-
# --------------- DETERMINISTIC ENCRYPTION (AES
|
| 33 |
-
# Always produces the same ciphertext for the same key + plaintext.
|
| 34 |
siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
|
| 35 |
aes_siv = AESSIV(siv_key)
|
| 36 |
|
| 37 |
def encrypt_text(plain: str) -> str:
|
| 38 |
-
"""Return URLβsafe base64 without padding (always the same output for the same input)."""
|
| 39 |
token = aes_siv.encrypt(plain.encode(), None)
|
| 40 |
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 41 |
|
| 42 |
def decrypt_text(encoded: str) -> str:
|
| 43 |
-
"""Recover the original string. Accepts base64 with or without padding."""
|
| 44 |
padding = 4 - len(encoded) % 4
|
| 45 |
if padding != 4:
|
| 46 |
encoded += "=" * padding
|
|
@@ -82,6 +80,13 @@ def db_remove_file(enc_path):
|
|
| 82 |
cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
|
| 83 |
conn.commit()
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
# --------------- FLASK HEALTH SERVER ---------------
|
| 86 |
web = Flask(__name__)
|
| 87 |
|
|
@@ -131,26 +136,21 @@ def format_size(bytes_val):
|
|
| 131 |
def format_speed(bytes_per_sec):
|
| 132 |
return f"{format_size(bytes_per_sec)}/s"
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
is_upload: bool = True):
|
| 137 |
-
|
| 138 |
-
Update the status message every 3 seconds with progress (percentage, speed, ETA).
|
| 139 |
-
Returns a tuple (task, bytes_holder) where bytes_holder is a list with a single element
|
| 140 |
-
that should be updated periodically to reflect the current transferred bytes.
|
| 141 |
-
"""
|
| 142 |
-
last_bytes = [start_bytes]
|
| 143 |
start_time = time.time()
|
| 144 |
|
| 145 |
async def updater():
|
| 146 |
while not cancel_event.is_set():
|
| 147 |
elapsed = max(time.time() - start_time, 0.01)
|
| 148 |
-
current =
|
| 149 |
speed = current / elapsed
|
| 150 |
text = ""
|
| 151 |
if total_bytes and total_bytes > 0:
|
| 152 |
pct = min(100 * current / total_bytes, 100)
|
| 153 |
-
text
|
| 154 |
text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"
|
| 155 |
text += f"Speed: {format_speed(speed)}\n"
|
| 156 |
if total_bytes and speed > 0:
|
|
@@ -166,77 +166,88 @@ async def progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
|
|
| 166 |
except Exception:
|
| 167 |
break
|
| 168 |
await asyncio.sleep(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
task = asyncio.create_task(updater())
|
| 171 |
-
return task,
|
| 172 |
|
| 173 |
# --------------- UPLOAD JOB ---------------
|
| 174 |
async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str,
|
| 175 |
job_id: int, cancel_event: asyncio.Event, status_msg):
|
| 176 |
temp_dir = tempfile.mkdtemp()
|
|
|
|
| 177 |
try:
|
| 178 |
-
#
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
if cancel_event.is_set():
|
| 185 |
return
|
| 186 |
-
|
| 187 |
file_size = os.path.getsize(local_path)
|
| 188 |
|
| 189 |
-
#
|
| 190 |
enc_folder = get_encrypted_folder(user_id)
|
| 191 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 192 |
repo_path = f"{enc_folder}/{enc_filename}"
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
)
|
| 199 |
|
| 200 |
-
|
| 201 |
-
# We'll update bytes_holder based on elapsed time assuming a reasonable speed.
|
| 202 |
-
async def simulate_progress():
|
| 203 |
start = time.time()
|
| 204 |
while not cancel_event.is_set():
|
| 205 |
elapsed = time.time() - start
|
| 206 |
-
# Rough estimate: assume ~10 MB/s upload speed (adjust if needed)
|
| 207 |
estimated = min(elapsed * 10_000_000, file_size)
|
| 208 |
-
|
| 209 |
await asyncio.sleep(1)
|
| 210 |
-
|
| 211 |
|
| 212 |
-
|
| 213 |
|
| 214 |
-
# 4. Actual upload (in executor)
|
| 215 |
loop = asyncio.get_event_loop()
|
| 216 |
upload_done = loop.create_future()
|
| 217 |
|
| 218 |
def sync_upload():
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
)
|
| 226 |
-
return True
|
| 227 |
-
except Exception as e:
|
| 228 |
-
raise e
|
| 229 |
|
| 230 |
task = loop.run_in_executor(None, sync_upload)
|
| 231 |
|
| 232 |
-
# Wait for completion or cancel
|
| 233 |
while not task.done():
|
| 234 |
if cancel_event.is_set():
|
| 235 |
break
|
| 236 |
await asyncio.sleep(1)
|
| 237 |
|
| 238 |
if cancel_event.is_set():
|
| 239 |
-
# Delete the partially uploaded file from HF
|
| 240 |
try:
|
| 241 |
hf.delete_file(
|
| 242 |
path_in_repo=repo_path,
|
|
@@ -245,18 +256,20 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
|
|
| 245 |
)
|
| 246 |
except Exception:
|
| 247 |
pass
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
return
|
| 252 |
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
|
| 259 |
-
# Record in database
|
| 260 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 261 |
|
| 262 |
await status_msg.edit_text(f"β
Uploaded: `{orig_filename}`", reply_markup=None)
|
|
@@ -271,7 +284,6 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
|
|
| 271 |
job_id: int, cancel_event: asyncio.Event, status_msg):
|
| 272 |
temp_dir = tempfile.mkdtemp()
|
| 273 |
try:
|
| 274 |
-
# Get file size from HF metadata
|
| 275 |
loop = asyncio.get_event_loop()
|
| 276 |
metadata = await loop.run_in_executor(
|
| 277 |
None,
|
|
@@ -282,54 +294,49 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
|
|
| 282 |
)
|
| 283 |
total_size = metadata.size
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
)
|
| 290 |
|
| 291 |
local_file = os.path.join(temp_dir, "downloaded_file")
|
| 292 |
|
| 293 |
-
# Download with stream to track progress
|
| 294 |
download_done = loop.create_future()
|
| 295 |
|
| 296 |
def sync_download_with_progress():
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
return True
|
| 313 |
-
except Exception as e:
|
| 314 |
-
raise e
|
| 315 |
|
| 316 |
task = loop.run_in_executor(None, sync_download_with_progress)
|
| 317 |
|
| 318 |
-
# Wait for completion or cancel
|
| 319 |
while not task.done():
|
| 320 |
if cancel_event.is_set():
|
| 321 |
break
|
| 322 |
await asyncio.sleep(1)
|
| 323 |
|
| 324 |
if cancel_event.is_set():
|
| 325 |
-
|
| 326 |
await status_msg.edit_text("β Download cancelled.", reply_markup=None)
|
| 327 |
return
|
| 328 |
|
| 329 |
await task
|
| 330 |
-
|
|
|
|
|
|
|
| 331 |
|
| 332 |
-
# Send file (split if needed)
|
| 333 |
file_size = os.path.getsize(local_file)
|
| 334 |
if file_size <= MAX_FILE_SIZE_TG:
|
| 335 |
await status_msg.edit_text("π€ Sending file to Telegram...", reply_markup=None)
|
|
@@ -337,7 +344,7 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
|
|
| 337 |
await status_msg.delete()
|
| 338 |
else:
|
| 339 |
part_size = MAX_FILE_SIZE_TG
|
| 340 |
-
num_parts = -(-file_size // part_size)
|
| 341 |
await status_msg.edit_text(f"π€ Sending in {num_parts} parts...", reply_markup=None)
|
| 342 |
with open(local_file, "rb") as f:
|
| 343 |
for i in range(1, num_parts + 1):
|
|
@@ -367,7 +374,6 @@ async def upload_worker():
|
|
| 367 |
cancel_event = asyncio.Event()
|
| 368 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 369 |
|
| 370 |
-
# Wait until enough free disk space
|
| 371 |
while get_free_disk() < MIN_FREE_DISK:
|
| 372 |
await asyncio.sleep(10)
|
| 373 |
|
|
@@ -398,7 +404,7 @@ async def list_files(_, message):
|
|
| 398 |
user_id = message.from_user.id
|
| 399 |
user_files = db_get_user_files(user_id)
|
| 400 |
|
| 401 |
-
# Fallback
|
| 402 |
if not user_files:
|
| 403 |
enc_folder = get_encrypted_folder(user_id)
|
| 404 |
try:
|
|
@@ -428,7 +434,10 @@ async def list_files(_, message):
|
|
| 428 |
|
| 429 |
buttons = []
|
| 430 |
for enc_path, orig_name, _ in user_files:
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
| 432 |
|
| 433 |
await message.reply_text(
|
| 434 |
"Your uploaded files:",
|
|
@@ -437,16 +446,19 @@ async def list_files(_, message):
|
|
| 437 |
|
| 438 |
@app.on_callback_query(filters.regex("^get:"))
|
| 439 |
async def get_file_callback(_, query):
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
job_id = int(time.time() * 1000)
|
| 442 |
cancel_event = asyncio.Event()
|
| 443 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
|
| 444 |
|
| 445 |
-
# Retrieve original file name
|
| 446 |
try:
|
| 447 |
orig_name = decrypt_text(enc_path.split("/")[-1])
|
| 448 |
except Exception:
|
| 449 |
-
orig_name = enc_path.split("/")[-1]
|
| 450 |
|
| 451 |
status_msg = await query.message.edit_text(
|
| 452 |
"β³ Preparing download...",
|
|
@@ -477,12 +489,16 @@ async def cancel_job_callback(_, query):
|
|
| 477 |
|
| 478 |
@app.on_callback_query(filters.regex("^upload:"))
|
| 479 |
async def upload_callback(_, query):
|
| 480 |
-
|
| 481 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
chat_id = query.message.chat.id
|
| 483 |
|
| 484 |
try:
|
| 485 |
-
file_msg = await app.get_messages(chat_id,
|
| 486 |
except Exception:
|
| 487 |
return await query.answer("Original message missing.", show_alert=True)
|
| 488 |
|
|
@@ -514,8 +530,12 @@ async def on_file(_, message):
|
|
| 514 |
else:
|
| 515 |
filename = f"{message.photo.file_unique_id}.jpg"
|
| 516 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
kb = InlineKeyboardMarkup([
|
| 518 |
-
[InlineKeyboardButton("β¬οΈ Upload File", callback_data=f"upload:{
|
| 519 |
[InlineKeyboardButton("β Cancel", callback_data="cancel_upload:0")]
|
| 520 |
])
|
| 521 |
|
|
|
|
| 7 |
import asyncio
|
| 8 |
import sqlite3
|
| 9 |
import tempfile
|
| 10 |
+
import secrets
|
| 11 |
from typing import Optional
|
| 12 |
|
| 13 |
import requests
|
| 14 |
from flask import Flask
|
| 15 |
from pyrogram import Client, filters
|
| 16 |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 17 |
+
from huggingface_hub import HfApi, get_hf_file_metadata
|
| 18 |
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
|
| 19 |
|
| 20 |
# --------------- CONFIG ---------------
|
|
|
|
| 30 |
KEEPALIVE_INTERVAL = 300 # 5 minutes
|
| 31 |
DB_PATH = "bot_files.db"
|
| 32 |
|
| 33 |
+
# --------------- DETERMINISTIC ENCRYPTION (AESβSIV) ---------------
|
|
|
|
| 34 |
siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
|
| 35 |
aes_siv = AESSIV(siv_key)
|
| 36 |
|
| 37 |
def encrypt_text(plain: str) -> str:
|
|
|
|
| 38 |
token = aes_siv.encrypt(plain.encode(), None)
|
| 39 |
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 40 |
|
| 41 |
def decrypt_text(encoded: str) -> str:
|
|
|
|
| 42 |
padding = 4 - len(encoded) % 4
|
| 43 |
if padding != 4:
|
| 44 |
encoded += "=" * padding
|
|
|
|
| 80 |
cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
|
| 81 |
conn.commit()
|
| 82 |
|
| 83 |
+
# --------------- CALLBACK MAPPINGS (avoid long data) ---------------
|
| 84 |
+
file_callback_map = {} # token -> enc_path
|
| 85 |
+
upload_prompt_map = {} # token -> (user_id, message_id, orig_filename)
|
| 86 |
+
|
| 87 |
+
def make_token():
|
| 88 |
+
return secrets.token_hex(8)
|
| 89 |
+
|
| 90 |
# --------------- FLASK HEALTH SERVER ---------------
|
| 91 |
web = Flask(__name__)
|
| 92 |
|
|
|
|
| 136 |
def format_speed(bytes_per_sec):
|
| 137 |
return f"{format_size(bytes_per_sec)}/s"
|
| 138 |
|
| 139 |
+
# --------------- PROGRESS UPDATER ---------------
|
| 140 |
+
def start_progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
|
| 141 |
+
total_bytes: Optional[int] = None, is_upload: bool = True):
|
| 142 |
+
bytes_holder = [0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
start_time = time.time()
|
| 144 |
|
| 145 |
async def updater():
|
| 146 |
while not cancel_event.is_set():
|
| 147 |
elapsed = max(time.time() - start_time, 0.01)
|
| 148 |
+
current = bytes_holder[0]
|
| 149 |
speed = current / elapsed
|
| 150 |
text = ""
|
| 151 |
if total_bytes and total_bytes > 0:
|
| 152 |
pct = min(100 * current / total_bytes, 100)
|
| 153 |
+
text = f"{pct:.1f}% of {format_size(total_bytes)}\n"
|
| 154 |
text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"
|
| 155 |
text += f"Speed: {format_speed(speed)}\n"
|
| 156 |
if total_bytes and speed > 0:
|
|
|
|
| 166 |
except Exception:
|
| 167 |
break
|
| 168 |
await asyncio.sleep(3)
|
| 169 |
+
try:
|
| 170 |
+
await status_msg.edit_text("β Cancelled.", reply_markup=None)
|
| 171 |
+
except Exception:
|
| 172 |
+
pass
|
| 173 |
|
| 174 |
task = asyncio.create_task(updater())
|
| 175 |
+
return {'task': task, 'bytes': bytes_holder}
|
| 176 |
|
| 177 |
# --------------- UPLOAD JOB ---------------
|
| 178 |
async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str,
|
| 179 |
job_id: int, cancel_event: asyncio.Event, status_msg):
|
| 180 |
temp_dir = tempfile.mkdtemp()
|
| 181 |
+
local_path = None
|
| 182 |
try:
|
| 183 |
+
# Download from Telegram with progress
|
| 184 |
+
download_bytes_holder = [0]
|
| 185 |
+
start_time = time.time()
|
| 186 |
+
|
| 187 |
+
async def download_progress(current, total):
|
| 188 |
+
download_bytes_holder[0] = current
|
| 189 |
+
elapsed = max(time.time() - start_time, 0.01)
|
| 190 |
+
speed = current / elapsed
|
| 191 |
+
pct = min(100 * current / total, 100) if total else 0
|
| 192 |
+
text = f"β¬οΈ Downloading from Telegram...\n{pct:.1f}% of {format_size(total)}\n{format_size(current)} downloaded\nSpeed: {format_speed(speed)}"
|
| 193 |
+
try:
|
| 194 |
+
await status_msg.edit_text(
|
| 195 |
+
text,
|
| 196 |
+
reply_markup=InlineKeyboardMarkup([
|
| 197 |
+
[InlineKeyboardButton("β Cancel", callback_data=f"cancel_job:{job_id}")]
|
| 198 |
+
])
|
| 199 |
+
)
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
local_path = await file_msg.download(
|
| 204 |
+
file_name=os.path.join(temp_dir, orig_filename),
|
| 205 |
+
progress=download_progress
|
| 206 |
+
)
|
| 207 |
if cancel_event.is_set():
|
| 208 |
return
|
|
|
|
| 209 |
file_size = os.path.getsize(local_path)
|
| 210 |
|
| 211 |
+
# Upload to Hugging Face
|
| 212 |
enc_folder = get_encrypted_folder(user_id)
|
| 213 |
enc_filename = get_encrypted_filename(orig_filename)
|
| 214 |
repo_path = f"{enc_folder}/{enc_filename}"
|
| 215 |
|
| 216 |
+
prog = start_progress_updater(job_id, status_msg, cancel_event,
|
| 217 |
+
total_bytes=file_size, is_upload=True)
|
| 218 |
+
upload_prog_task = prog['task']
|
| 219 |
+
upload_bytes_holder = prog['bytes']
|
|
|
|
| 220 |
|
| 221 |
+
async def simulate_upload():
|
|
|
|
|
|
|
| 222 |
start = time.time()
|
| 223 |
while not cancel_event.is_set():
|
| 224 |
elapsed = time.time() - start
|
|
|
|
| 225 |
estimated = min(elapsed * 10_000_000, file_size)
|
| 226 |
+
upload_bytes_holder[0] = estimated
|
| 227 |
await asyncio.sleep(1)
|
| 228 |
+
upload_bytes_holder[0] = file_size
|
| 229 |
|
| 230 |
+
sim_task = asyncio.create_task(simulate_upload())
|
| 231 |
|
|
|
|
| 232 |
loop = asyncio.get_event_loop()
|
| 233 |
upload_done = loop.create_future()
|
| 234 |
|
| 235 |
def sync_upload():
|
| 236 |
+
hf.upload_file(
|
| 237 |
+
path_or_fileobj=local_path,
|
| 238 |
+
path_in_repo=repo_path,
|
| 239 |
+
repo_id=DATASET_REPO,
|
| 240 |
+
repo_type="dataset",
|
| 241 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
task = loop.run_in_executor(None, sync_upload)
|
| 244 |
|
|
|
|
| 245 |
while not task.done():
|
| 246 |
if cancel_event.is_set():
|
| 247 |
break
|
| 248 |
await asyncio.sleep(1)
|
| 249 |
|
| 250 |
if cancel_event.is_set():
|
|
|
|
| 251 |
try:
|
| 252 |
hf.delete_file(
|
| 253 |
path_in_repo=repo_path,
|
|
|
|
| 256 |
)
|
| 257 |
except Exception:
|
| 258 |
pass
|
| 259 |
+
upload_prog_task.cancel()
|
| 260 |
+
sim_task.cancel()
|
| 261 |
+
try:
|
| 262 |
+
await status_msg.edit_text("β Upload cancelled.", reply_markup=None)
|
| 263 |
+
except Exception:
|
| 264 |
+
pass
|
| 265 |
return
|
| 266 |
|
| 267 |
+
await task
|
| 268 |
+
upload_bytes_holder[0] = file_size
|
| 269 |
+
await asyncio.sleep(0.5)
|
| 270 |
+
upload_prog_task.cancel()
|
| 271 |
+
sim_task.cancel()
|
| 272 |
|
|
|
|
| 273 |
db_add_file(user_id, repo_path, orig_filename, file_size)
|
| 274 |
|
| 275 |
await status_msg.edit_text(f"β
Uploaded: `{orig_filename}`", reply_markup=None)
|
|
|
|
| 284 |
job_id: int, cancel_event: asyncio.Event, status_msg):
|
| 285 |
temp_dir = tempfile.mkdtemp()
|
| 286 |
try:
|
|
|
|
| 287 |
loop = asyncio.get_event_loop()
|
| 288 |
metadata = await loop.run_in_executor(
|
| 289 |
None,
|
|
|
|
| 294 |
)
|
| 295 |
total_size = metadata.size
|
| 296 |
|
| 297 |
+
prog = start_progress_updater(job_id, status_msg, cancel_event,
|
| 298 |
+
total_bytes=total_size, is_upload=False)
|
| 299 |
+
prog_task = prog['task']
|
| 300 |
+
bytes_holder = prog['bytes']
|
|
|
|
| 301 |
|
| 302 |
local_file = os.path.join(temp_dir, "downloaded_file")
|
| 303 |
|
|
|
|
| 304 |
download_done = loop.create_future()
|
| 305 |
|
| 306 |
def sync_download_with_progress():
|
| 307 |
+
url = hf.get_hf_file_metadata_url(
|
| 308 |
+
repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset"
|
| 309 |
+
)
|
| 310 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 311 |
+
resp = requests.get(url, stream=True, headers=headers)
|
| 312 |
+
resp.raise_for_status()
|
| 313 |
+
with open(local_file, "wb") as f:
|
| 314 |
+
downloaded = 0
|
| 315 |
+
for chunk in resp.iter_content(chunk_size=8192):
|
| 316 |
+
if cancel_event.is_set():
|
| 317 |
+
break
|
| 318 |
+
f.write(chunk)
|
| 319 |
+
downloaded += len(chunk)
|
| 320 |
+
bytes_holder[0] = downloaded
|
| 321 |
+
return True
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
task = loop.run_in_executor(None, sync_download_with_progress)
|
| 324 |
|
|
|
|
| 325 |
while not task.done():
|
| 326 |
if cancel_event.is_set():
|
| 327 |
break
|
| 328 |
await asyncio.sleep(1)
|
| 329 |
|
| 330 |
if cancel_event.is_set():
|
| 331 |
+
prog_task.cancel()
|
| 332 |
await status_msg.edit_text("β Download cancelled.", reply_markup=None)
|
| 333 |
return
|
| 334 |
|
| 335 |
await task
|
| 336 |
+
bytes_holder[0] = total_size
|
| 337 |
+
await asyncio.sleep(0.5)
|
| 338 |
+
prog_task.cancel()
|
| 339 |
|
|
|
|
| 340 |
file_size = os.path.getsize(local_file)
|
| 341 |
if file_size <= MAX_FILE_SIZE_TG:
|
| 342 |
await status_msg.edit_text("π€ Sending file to Telegram...", reply_markup=None)
|
|
|
|
| 344 |
await status_msg.delete()
|
| 345 |
else:
|
| 346 |
part_size = MAX_FILE_SIZE_TG
|
| 347 |
+
num_parts = -(-file_size // part_size)
|
| 348 |
await status_msg.edit_text(f"π€ Sending in {num_parts} parts...", reply_markup=None)
|
| 349 |
with open(local_file, "rb") as f:
|
| 350 |
for i in range(1, num_parts + 1):
|
|
|
|
| 374 |
cancel_event = asyncio.Event()
|
| 375 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
|
| 376 |
|
|
|
|
| 377 |
while get_free_disk() < MIN_FREE_DISK:
|
| 378 |
await asyncio.sleep(10)
|
| 379 |
|
|
|
|
| 404 |
user_id = message.from_user.id
|
| 405 |
user_files = db_get_user_files(user_id)
|
| 406 |
|
| 407 |
+
# Fallback scan if DB empty
|
| 408 |
if not user_files:
|
| 409 |
enc_folder = get_encrypted_folder(user_id)
|
| 410 |
try:
|
|
|
|
| 434 |
|
| 435 |
buttons = []
|
| 436 |
for enc_path, orig_name, _ in user_files:
|
| 437 |
+
# Generate a short token instead of passing the whole path
|
| 438 |
+
token = make_token()
|
| 439 |
+
file_callback_map[token] = enc_path
|
| 440 |
+
buttons.append([InlineKeyboardButton(orig_name[:60], callback_data=f"get:{token}")])
|
| 441 |
|
| 442 |
await message.reply_text(
|
| 443 |
"Your uploaded files:",
|
|
|
|
| 446 |
|
| 447 |
@app.on_callback_query(filters.regex("^get:"))
|
| 448 |
async def get_file_callback(_, query):
|
| 449 |
+
token = query.data.replace("get:", "")
|
| 450 |
+
enc_path = file_callback_map.pop(token, None)
|
| 451 |
+
if not enc_path:
|
| 452 |
+
return await query.answer("This file list is no longer valid. Please use /files again.", show_alert=True)
|
| 453 |
+
|
| 454 |
job_id = int(time.time() * 1000)
|
| 455 |
cancel_event = asyncio.Event()
|
| 456 |
active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
|
| 457 |
|
|
|
|
| 458 |
try:
|
| 459 |
orig_name = decrypt_text(enc_path.split("/")[-1])
|
| 460 |
except Exception:
|
| 461 |
+
orig_name = enc_path.split("/")[-1]
|
| 462 |
|
| 463 |
status_msg = await query.message.edit_text(
|
| 464 |
"β³ Preparing download...",
|
|
|
|
| 489 |
|
| 490 |
@app.on_callback_query(filters.regex("^upload:"))
|
| 491 |
async def upload_callback(_, query):
|
| 492 |
+
token = query.data.replace("upload:", "")
|
| 493 |
+
data = upload_prompt_map.pop(token, None)
|
| 494 |
+
if not data:
|
| 495 |
+
return await query.answer("Upload prompt expired. Please send the file again.", show_alert=True)
|
| 496 |
+
|
| 497 |
+
user_id, msg_id, orig_filename = data
|
| 498 |
chat_id = query.message.chat.id
|
| 499 |
|
| 500 |
try:
|
| 501 |
+
file_msg = await app.get_messages(chat_id, msg_id)
|
| 502 |
except Exception:
|
| 503 |
return await query.answer("Original message missing.", show_alert=True)
|
| 504 |
|
|
|
|
| 530 |
else:
|
| 531 |
filename = f"{message.photo.file_unique_id}.jpg"
|
| 532 |
|
| 533 |
+
# Use short token to avoid long callback data
|
| 534 |
+
token = make_token()
|
| 535 |
+
upload_prompt_map[token] = (message.from_user.id, message.id, filename)
|
| 536 |
+
|
| 537 |
kb = InlineKeyboardMarkup([
|
| 538 |
+
[InlineKeyboardButton("β¬οΈ Upload File", callback_data=f"upload:{token}")],
|
| 539 |
[InlineKeyboardButton("β Cancel", callback_data="cancel_upload:0")]
|
| 540 |
])
|
| 541 |
|