Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,7 @@ from cryptography.fernet import Fernet
|
|
| 7 |
from cryptography.hazmat.primitives import hashes
|
| 8 |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
| 9 |
from cryptography.hazmat.backends import default_backend
|
| 10 |
-
from pyrogram import Client, filters
|
| 11 |
from pyrogram.types import (
|
| 12 |
Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
|
| 13 |
)
|
|
@@ -109,298 +109,13 @@ active_progress: Dict[int, dict] = {}
|
|
| 109 |
op_queue = asyncio.Queue()
|
| 110 |
pending_uploads: Dict[int, dict] = {}
|
| 111 |
|
| 112 |
-
# ----------
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
return "0 B"
|
| 120 |
-
units = ["B", "KB", "MB", "GB", "TB"]
|
| 121 |
-
i = int(math.floor(math.log(size, 1024)))
|
| 122 |
-
return f"{round(size / (1024**i), 1)} {units[i]}"
|
| 123 |
-
|
| 124 |
-
async def progress_updater():
|
| 125 |
-
while True:
|
| 126 |
-
await asyncio.sleep(PROGRESS_INTERVAL)
|
| 127 |
-
for msg_id, info in list(active_progress.items()):
|
| 128 |
-
try:
|
| 129 |
-
chat_id = info["chat_id"]
|
| 130 |
-
filename = info["filename"]
|
| 131 |
-
current = info.get("current", 0)
|
| 132 |
-
total = info.get("total", 0)
|
| 133 |
-
start_time = info.get("start_time", time.time())
|
| 134 |
-
op_type = info.get("op_type", "")
|
| 135 |
-
elapsed = max(time.time() - start_time, 1)
|
| 136 |
-
speed = current / elapsed if current > 0 else 0
|
| 137 |
-
if total > 0:
|
| 138 |
-
percent = (current / total) * 100
|
| 139 |
-
text = (
|
| 140 |
-
f"**{op_type}** `{filename}`\n"
|
| 141 |
-
f"{make_progress_bar(percent)} {percent:.1f}%\n"
|
| 142 |
-
f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
|
| 143 |
-
f"⚡ {format_bytes(speed)}/s"
|
| 144 |
-
)
|
| 145 |
-
else:
|
| 146 |
-
text = f"**{op_type}** `{filename}`\n⏳ Processing..."
|
| 147 |
-
keyboard = None
|
| 148 |
-
if info["state"] in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
|
| 149 |
-
keyboard = InlineKeyboardMarkup([[
|
| 150 |
-
InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")
|
| 151 |
-
]])
|
| 152 |
-
await app.edit_message_text(chat_id, msg_id, text, reply_markup=keyboard)
|
| 153 |
-
except MessageNotModified:
|
| 154 |
-
pass
|
| 155 |
-
except Exception as e:
|
| 156 |
-
logger.error(f"progress_updater error: {e}")
|
| 157 |
-
|
| 158 |
-
# ---------- UPLOAD / DOWNLOAD OPERATIONS ----------
|
| 159 |
-
async def handle_upload(op: dict):
|
| 160 |
-
user_id = op["user_id"]
|
| 161 |
-
chat_id = op["chat_id"]
|
| 162 |
-
file_id = op["file_id"]
|
| 163 |
-
file_name = op["file_name"]
|
| 164 |
-
msg_id = op["status_msg_id"]
|
| 165 |
-
cancel_event = op["cancel_event"]
|
| 166 |
-
|
| 167 |
-
active_progress[msg_id] = {
|
| 168 |
-
"chat_id": chat_id, "state": "downloading_from_tg",
|
| 169 |
-
"filename": file_name, "current": 0, "total": 0,
|
| 170 |
-
"start_time": time.time(), "cancel_event": cancel_event,
|
| 171 |
-
"op_type": "Upload",
|
| 172 |
-
}
|
| 173 |
-
|
| 174 |
-
while not enough_disk():
|
| 175 |
-
try:
|
| 176 |
-
await app.edit_message_text(chat_id, msg_id,
|
| 177 |
-
f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)")
|
| 178 |
-
except:
|
| 179 |
-
pass
|
| 180 |
-
await asyncio.sleep(10)
|
| 181 |
-
if cancel_event.is_set():
|
| 182 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
|
| 183 |
-
del active_progress[msg_id]
|
| 184 |
-
return
|
| 185 |
-
|
| 186 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
|
| 187 |
-
os.close(tmp_fd)
|
| 188 |
-
try:
|
| 189 |
-
def tg_progress(current, total, mid):
|
| 190 |
-
info = active_progress.get(mid)
|
| 191 |
-
if info:
|
| 192 |
-
info["current"] = current
|
| 193 |
-
info["total"] = total
|
| 194 |
-
info["start_time"] = time.time()
|
| 195 |
-
|
| 196 |
-
await app.download_media(file_id, file_name=tmp_path,
|
| 197 |
-
progress=tg_progress, progress_args=(msg_id,))
|
| 198 |
-
except Exception as e:
|
| 199 |
-
logger.error(f"TG download error: {e}")
|
| 200 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 201 |
-
await app.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
|
| 202 |
-
del active_progress[msg_id]
|
| 203 |
-
return
|
| 204 |
-
|
| 205 |
-
if cancel_event.is_set():
|
| 206 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 207 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
|
| 208 |
-
del active_progress[msg_id]
|
| 209 |
-
return
|
| 210 |
-
|
| 211 |
-
active_progress[msg_id]["state"] = "uploading_to_hf"
|
| 212 |
-
active_progress[msg_id]["current"] = 0
|
| 213 |
-
active_progress[msg_id]["total"] = 0
|
| 214 |
-
|
| 215 |
-
folder = get_user_folder(user_id)
|
| 216 |
-
enc_fname = encrypt(file_name)
|
| 217 |
-
hf_path = f"{folder}/{enc_fname}"
|
| 218 |
-
meta_path = f"{folder}/meta.json"
|
| 219 |
-
|
| 220 |
-
def hf_progress(current, total, mid):
|
| 221 |
-
info = active_progress.get(mid)
|
| 222 |
-
if info:
|
| 223 |
-
info["current"] = current
|
| 224 |
-
info["total"] = total
|
| 225 |
-
info["start_time"] = time.time()
|
| 226 |
-
|
| 227 |
-
try:
|
| 228 |
-
upload_file(path_or_fileobj=tmp_path, path_in_repo=hf_path,
|
| 229 |
-
repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
|
| 230 |
-
token=HF_TOKEN,
|
| 231 |
-
progress_callback=hf_progress,
|
| 232 |
-
progress_callback_msg_id=msg_id)
|
| 233 |
-
except Exception as e:
|
| 234 |
-
logger.error(f"HF upload error: {e}")
|
| 235 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 236 |
-
await app.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
|
| 237 |
-
del active_progress[msg_id]
|
| 238 |
-
return
|
| 239 |
-
|
| 240 |
-
if cancel_event.is_set():
|
| 241 |
-
hf_delete_file(hf_path)
|
| 242 |
-
meta = hf_read_json(meta_path) or {}
|
| 243 |
-
meta.pop(enc_fname, None)
|
| 244 |
-
hf_write_json(meta_path, meta)
|
| 245 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 246 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
|
| 247 |
-
del active_progress[msg_id]
|
| 248 |
-
return
|
| 249 |
-
|
| 250 |
-
meta = hf_read_json(meta_path) or {}
|
| 251 |
-
meta[enc_fname] = file_name
|
| 252 |
-
try:
|
| 253 |
-
hf_write_json(meta_path, meta)
|
| 254 |
-
except Exception as e:
|
| 255 |
-
logger.error(f"Meta update error: {e}")
|
| 256 |
-
await app.edit_message_text(chat_id, msg_id, f"✅ Uploaded, but meta update failed: {e}")
|
| 257 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 258 |
-
del active_progress[msg_id]
|
| 259 |
-
return
|
| 260 |
-
|
| 261 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 262 |
-
await app.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
|
| 263 |
-
del active_progress[msg_id]
|
| 264 |
-
|
| 265 |
-
async def handle_download(op: dict):
|
| 266 |
-
user_id = op["user_id"]
|
| 267 |
-
chat_id = op["chat_id"]
|
| 268 |
-
folder = op["folder"]
|
| 269 |
-
enc_fname = op["enc_fname"]
|
| 270 |
-
orig_name = op["orig_name"]
|
| 271 |
-
file_size = op["file_size"]
|
| 272 |
-
msg_id = op["status_msg_id"]
|
| 273 |
-
cancel_event = op["cancel_event"]
|
| 274 |
-
|
| 275 |
-
active_progress[msg_id] = {
|
| 276 |
-
"chat_id": chat_id, "state": "downloading_from_hf",
|
| 277 |
-
"filename": orig_name, "current": 0,
|
| 278 |
-
"total": file_size if file_size else 0,
|
| 279 |
-
"start_time": time.time(), "cancel_event": cancel_event,
|
| 280 |
-
"op_type": "Download",
|
| 281 |
-
}
|
| 282 |
-
|
| 283 |
-
url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}",
|
| 284 |
-
repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
|
| 285 |
-
|
| 286 |
-
async def send_file(path: str, caption: str):
|
| 287 |
-
active_progress[msg_id]["state"] = "sending_to_tg"
|
| 288 |
-
active_progress[msg_id]["total"] = os.path.getsize(path)
|
| 289 |
-
await app.send_document(chat_id, path, caption=caption,
|
| 290 |
-
progress=lambda c, t: upload_progress(c, t, msg_id))
|
| 291 |
-
if cancel_event.is_set():
|
| 292 |
-
await app.stop_transmission()
|
| 293 |
-
|
| 294 |
-
def upload_progress(current, total, mid):
|
| 295 |
-
info = active_progress.get(mid)
|
| 296 |
-
if info:
|
| 297 |
-
info["current"] = current
|
| 298 |
-
info["total"] = total
|
| 299 |
-
info["start_time"] = time.time()
|
| 300 |
-
|
| 301 |
-
if file_size is None or file_size <= SPLIT_SIZE:
|
| 302 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
|
| 303 |
-
os.close(tmp_fd)
|
| 304 |
-
try:
|
| 305 |
-
success = await download_from_url(url, tmp_path, msg_id, cancel_event, file_size)
|
| 306 |
-
if not success:
|
| 307 |
-
return
|
| 308 |
-
await send_file(tmp_path, orig_name)
|
| 309 |
-
if cancel_event.is_set():
|
| 310 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
|
| 311 |
-
del active_progress[msg_id]
|
| 312 |
-
return
|
| 313 |
-
await app.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
|
| 314 |
-
finally:
|
| 315 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 316 |
-
del active_progress[msg_id]
|
| 317 |
-
else:
|
| 318 |
-
total_parts = math.ceil(file_size / SPLIT_SIZE)
|
| 319 |
-
for part_idx in range(total_parts):
|
| 320 |
-
if cancel_event.is_set():
|
| 321 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
|
| 322 |
-
del active_progress[msg_id]
|
| 323 |
-
return
|
| 324 |
-
start = part_idx * SPLIT_SIZE
|
| 325 |
-
end = min(start + SPLIT_SIZE - 1, file_size - 1)
|
| 326 |
-
part_size = end - start + 1
|
| 327 |
-
part_name = f"{orig_name}.part{part_idx+1:03d}"
|
| 328 |
-
active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
|
| 329 |
-
active_progress[msg_id]["current"] = 0
|
| 330 |
-
active_progress[msg_id]["total"] = part_size
|
| 331 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
|
| 332 |
-
os.close(tmp_fd)
|
| 333 |
-
try:
|
| 334 |
-
success = await download_range(url, start, end, tmp_path, msg_id, cancel_event, part_size)
|
| 335 |
-
if not success:
|
| 336 |
-
return
|
| 337 |
-
active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
|
| 338 |
-
await send_file(tmp_path, f"{orig_name} - Part {part_idx+1}/{total_parts}")
|
| 339 |
-
if cancel_event.is_set():
|
| 340 |
-
await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
|
| 341 |
-
del active_progress[msg_id]
|
| 342 |
-
return
|
| 343 |
-
finally:
|
| 344 |
-
if os.path.exists(tmp_path): os.unlink(tmp_path)
|
| 345 |
-
await app.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
|
| 346 |
-
del active_progress[msg_id]
|
| 347 |
-
|
| 348 |
-
async def download_from_url(url: str, dest: str, msg_id: int,
|
| 349 |
-
cancel_event: asyncio.Event,
|
| 350 |
-
total_size: Optional[int]) -> bool:
|
| 351 |
-
try:
|
| 352 |
-
async with aiohttp.ClientSession() as session:
|
| 353 |
-
async with session.get(url) as resp:
|
| 354 |
-
if resp.status != 200:
|
| 355 |
-
raise Exception(f"HTTP {resp.status}")
|
| 356 |
-
total = total_size or int(resp.headers.get("Content-Length", 0))
|
| 357 |
-
info = active_progress.get(msg_id)
|
| 358 |
-
if info: info["total"] = total
|
| 359 |
-
downloaded = 0
|
| 360 |
-
with open(dest, "wb") as f:
|
| 361 |
-
async for chunk in resp.content.iter_chunked(64*1024):
|
| 362 |
-
if cancel_event.is_set():
|
| 363 |
-
return False
|
| 364 |
-
f.write(chunk)
|
| 365 |
-
downloaded += len(chunk)
|
| 366 |
-
if info:
|
| 367 |
-
info["current"] = downloaded
|
| 368 |
-
info["start_time"] = time.time()
|
| 369 |
-
return True
|
| 370 |
-
except Exception as e:
|
| 371 |
-
logger.error(f"download_from_url error: {e}")
|
| 372 |
-
await app.edit_message_text(msg_id, f"❌ Download error: {e}")
|
| 373 |
-
return False
|
| 374 |
-
|
| 375 |
-
async def download_range(url: str, start: int, end: int, dest: str,
|
| 376 |
-
msg_id: int, cancel_event: asyncio.Event,
|
| 377 |
-
size: int) -> bool:
|
| 378 |
-
headers = {"Range": f"bytes={start}-{end}"}
|
| 379 |
-
try:
|
| 380 |
-
async with aiohttp.ClientSession() as session:
|
| 381 |
-
async with session.get(url, headers=headers) as resp:
|
| 382 |
-
if resp.status not in (200, 206):
|
| 383 |
-
raise Exception(f"HTTP {resp.status}")
|
| 384 |
-
info = active_progress.get(msg_id)
|
| 385 |
-
if info: info["total"] = size
|
| 386 |
-
downloaded = 0
|
| 387 |
-
with open(dest, "wb") as f:
|
| 388 |
-
async for chunk in resp.content.iter_chunked(64*1024):
|
| 389 |
-
if cancel_event.is_set():
|
| 390 |
-
return False
|
| 391 |
-
f.write(chunk)
|
| 392 |
-
downloaded += len(chunk)
|
| 393 |
-
if info:
|
| 394 |
-
info["current"] = downloaded
|
| 395 |
-
info["start_time"] = time.time()
|
| 396 |
-
return True
|
| 397 |
-
except Exception as e:
|
| 398 |
-
logger.error(f"download_range error: {e}")
|
| 399 |
-
await app.edit_message_text(msg_id, f"❌ Download error: {e}")
|
| 400 |
-
return False
|
| 401 |
-
|
| 402 |
-
# ---------- CATCH-ALL DEBUG LOG (proves messages arrive) ----------
|
| 403 |
-
@app.on_message()
|
| 404 |
async def debug_all(client, msg: Message):
|
| 405 |
logger.info(f"MSG from {msg.from_user.id}: {msg.text or msg.caption or '<no text>'} (chat={msg.chat.id})")
|
| 406 |
|
|
@@ -408,16 +123,11 @@ async def debug_all(client, msg: Message):
|
|
| 408 |
@app.on_message(filters.command("start"))
|
| 409 |
async def start_cmd(_, msg: Message):
|
| 410 |
logger.info(f"/start from {msg.from_user.id}")
|
| 411 |
-
await msg.reply("👋
|
| 412 |
|
| 413 |
@app.on_message(filters.command("help"))
|
| 414 |
async def help_cmd(_, msg: Message):
|
| 415 |
-
await msg.reply(
|
| 416 |
-
"**Commands:**\n/start, /files, /help\n\n"
|
| 417 |
-
"**How to use:**\n1. Send any file.\n"
|
| 418 |
-
"2. Click **Upload** to store it.\n"
|
| 419 |
-
"3. Use /files to download."
|
| 420 |
-
)
|
| 421 |
|
| 422 |
@app.on_message(filters.command("files"))
|
| 423 |
async def list_files(_, msg: Message):
|
|
@@ -430,109 +140,7 @@ async def list_files(_, msg: Message):
|
|
| 430 |
kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
|
| 431 |
await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
|
| 432 |
|
| 433 |
-
|
| 434 |
-
async def refresh_files(_, query: CallbackQuery):
|
| 435 |
-
await query.answer("Refreshing…")
|
| 436 |
-
await list_files(_, query.message)
|
| 437 |
-
await query.message.delete()
|
| 438 |
-
|
| 439 |
-
@app.on_callback_query(filters.regex("^dl_(.+)"))
|
| 440 |
-
async def download_file_cb(_, query: CallbackQuery):
|
| 441 |
-
enc = query.data.split("_", 1)[1]
|
| 442 |
-
user_id = query.from_user.id
|
| 443 |
-
folder = get_user_folder(user_id)
|
| 444 |
-
meta = hf_read_json(f"{folder}/meta.json")
|
| 445 |
-
if not meta or enc not in meta:
|
| 446 |
-
await query.answer("File not found", show_alert=True); return
|
| 447 |
-
orig_name = meta[enc]
|
| 448 |
-
size = hf_file_size(f"{folder}/{enc}")
|
| 449 |
-
await query.answer("Starting download…")
|
| 450 |
-
st = await query.message.reply(f"⏳ Preparing download: `{orig_name}`…")
|
| 451 |
-
cancel_ev = asyncio.Event()
|
| 452 |
-
active_progress[st.id] = {
|
| 453 |
-
"chat_id": st.chat.id, "filename": orig_name,
|
| 454 |
-
"current": 0, "total": 0, "start_time": time.time(),
|
| 455 |
-
"cancel_event": cancel_ev, "op_type": "Download", "state": "starting"
|
| 456 |
-
}
|
| 457 |
-
await op_queue.put({
|
| 458 |
-
"type": "download", "user_id": user_id, "chat_id": st.chat.id,
|
| 459 |
-
"folder": folder, "enc_fname": enc, "orig_name": orig_name,
|
| 460 |
-
"file_size": size, "status_msg_id": st.id, "cancel_event": cancel_ev
|
| 461 |
-
})
|
| 462 |
-
|
| 463 |
-
@app.on_callback_query(filters.regex("^cancel_op_(\\d+)$"))
|
| 464 |
-
async def cancel_op(_, query: CallbackQuery):
|
| 465 |
-
msg_id = int(query.data.split("_")[2])
|
| 466 |
-
info = active_progress.get(msg_id)
|
| 467 |
-
if info and "cancel_event" in info:
|
| 468 |
-
info["cancel_event"].set()
|
| 469 |
-
await query.answer("Cancelling…")
|
| 470 |
-
else:
|
| 471 |
-
await query.answer("Nothing to cancel", show_alert=True)
|
| 472 |
-
|
| 473 |
-
# ---------- MEDIA HANDLER ----------
|
| 474 |
-
@app.on_message(filters.media)
|
| 475 |
-
async def media_handler(_, msg: Message):
|
| 476 |
-
logger.info(f"Media from {msg.from_user.id}")
|
| 477 |
-
file_id = None
|
| 478 |
-
file_name = "file"
|
| 479 |
-
file_size = 0
|
| 480 |
-
|
| 481 |
-
if msg.document:
|
| 482 |
-
file_id = msg.document.file_id; file_name = msg.document.file_name or "doc"; file_size = msg.document.file_size
|
| 483 |
-
elif msg.video:
|
| 484 |
-
file_id = msg.video.file_id; file_name = msg.video.file_name or "video.mp4"; file_size = msg.video.file_size
|
| 485 |
-
elif msg.audio:
|
| 486 |
-
file_id = msg.audio.file_id; file_name = msg.audio.file_name or "audio.mp3"; file_size = msg.audio.file_size
|
| 487 |
-
elif msg.photo:
|
| 488 |
-
file_id = msg.photo.file_id; file_name = f"photo_{msg.photo.file_unique_id}.jpg"; file_size = msg.photo.file_size or 0
|
| 489 |
-
elif msg.voice:
|
| 490 |
-
file_id = msg.voice.file_id; file_name = f"voice_{msg.voice.file_unique_id}.ogg"; file_size = msg.voice.file_size
|
| 491 |
-
elif msg.video_note:
|
| 492 |
-
file_id = msg.video_note.file_id; file_name = f"vn_{msg.video_note.file_unique_id}.mp4"; file_size = msg.video_note.file_size
|
| 493 |
-
elif msg.sticker:
|
| 494 |
-
file_id = msg.sticker.file_id; file_name = f"sticker_{msg.sticker.file_unique_id}.webp"; file_size = msg.sticker.file_size
|
| 495 |
-
else:
|
| 496 |
-
return
|
| 497 |
-
|
| 498 |
-
if not file_id:
|
| 499 |
-
return
|
| 500 |
-
|
| 501 |
-
prompt = await msg.reply(
|
| 502 |
-
f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\nDo you want to upload?",
|
| 503 |
-
reply_markup=InlineKeyboardMarkup([[
|
| 504 |
-
InlineKeyboardButton("✅ Upload", callback_data=f"upload_{msg.id}"),
|
| 505 |
-
InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
|
| 506 |
-
]]),
|
| 507 |
-
quote=True,
|
| 508 |
-
)
|
| 509 |
-
pending_uploads[prompt.id] = {
|
| 510 |
-
"file_id": file_id, "file_name": file_name,
|
| 511 |
-
"file_size": file_size, "user_id": msg.from_user.id,
|
| 512 |
-
}
|
| 513 |
-
|
| 514 |
-
@app.on_callback_query(filters.regex("^upload_(\\d+)$"))
|
| 515 |
-
async def confirm_upload(_, query: CallbackQuery):
|
| 516 |
-
info = pending_uploads.pop(query.message.id, None)
|
| 517 |
-
if not info:
|
| 518 |
-
await query.answer("Expired", show_alert=True); return
|
| 519 |
-
await query.answer()
|
| 520 |
-
await query.message.delete()
|
| 521 |
-
st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
|
| 522 |
-
cancel_ev = asyncio.Event()
|
| 523 |
-
await op_queue.put({
|
| 524 |
-
"type": "upload", "user_id": info["user_id"], "chat_id": query.message.chat.id,
|
| 525 |
-
"file_id": info["file_id"], "file_name": info["file_name"],
|
| 526 |
-
"status_msg_id": st.id, "cancel_event": cancel_ev,
|
| 527 |
-
})
|
| 528 |
-
|
| 529 |
-
@app.on_callback_query(filters.regex("^cancel_prompt_(\\d+)$"))
|
| 530 |
-
async def cancel_prompt(_, query: CallbackQuery):
|
| 531 |
-
pending_uploads.pop(query.message.id, None)
|
| 532 |
-
await query.answer("Cancelled.")
|
| 533 |
-
await query.message.delete()
|
| 534 |
-
|
| 535 |
-
# ---------- KEEP-ALIVE ----------
|
| 536 |
async def keep_alive():
|
| 537 |
async def handler(request):
|
| 538 |
return web.Response(text="Alive")
|
|
@@ -555,27 +163,10 @@ async def keep_alive():
|
|
| 555 |
await asyncio.sleep(KEEPALIVE_INTERVAL)
|
| 556 |
asyncio.create_task(pinger())
|
| 557 |
|
| 558 |
-
# ---------- WORKER ----------
|
| 559 |
-
async def worker():
|
| 560 |
-
while True:
|
| 561 |
-
op = await op_queue.get()
|
| 562 |
-
try:
|
| 563 |
-
if op["type"] == "upload":
|
| 564 |
-
await handle_upload(op)
|
| 565 |
-
else:
|
| 566 |
-
await handle_download(op)
|
| 567 |
-
except Exception as e:
|
| 568 |
-
logger.exception(f"Worker error: {e}")
|
| 569 |
-
finally:
|
| 570 |
-
op_queue.task_done()
|
| 571 |
-
|
| 572 |
# ---------- MAIN ----------
|
| 573 |
async def main():
|
| 574 |
logger.info("Verifying environment... OK")
|
| 575 |
-
logger.info(f"Repo: {HF_REPO_ID}, Disk limit: {MIN_FREE_DISK//(1024**3)} GB")
|
| 576 |
await keep_alive()
|
| 577 |
-
asyncio.create_task(worker())
|
| 578 |
-
asyncio.create_task(progress_updater())
|
| 579 |
|
| 580 |
while True:
|
| 581 |
try:
|
|
@@ -590,6 +181,7 @@ async def main():
|
|
| 590 |
logger.exception(f"Start error: {e}")
|
| 591 |
await asyncio.sleep(30)
|
| 592 |
|
|
|
|
| 593 |
await asyncio.Event().wait()
|
| 594 |
|
| 595 |
if __name__ == "__main__":
|
|
|
|
| 7 |
from cryptography.hazmat.primitives import hashes
|
| 8 |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
| 9 |
from cryptography.hazmat.backends import default_backend
|
| 10 |
+
from pyrogram import Client, filters, raw
|
| 11 |
from pyrogram.types import (
|
| 12 |
Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
|
| 13 |
)
|
|
|
|
| 109 |
op_queue = asyncio.Queue()
|
| 110 |
pending_uploads: Dict[int, dict] = {}
|
| 111 |
|
| 112 |
+
# ---------- RAW UPDATE LOGGER ----------
|
| 113 |
+
@app.on_raw_update()
|
| 114 |
+
async def raw_logger(client, update, users, chats):
|
| 115 |
+
logger.info(f"RAW UPDATE: {update}")
|
| 116 |
|
| 117 |
+
# ---------- DIAGNOSTIC CATCH-ALL (non-blocking) ----------
|
| 118 |
+
@app.on_message(group=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
async def debug_all(client, msg: Message):
|
| 120 |
logger.info(f"MSG from {msg.from_user.id}: {msg.text or msg.caption or '<no text>'} (chat={msg.chat.id})")
|
| 121 |
|
|
|
|
| 123 |
@app.on_message(filters.command("start"))
|
| 124 |
async def start_cmd(_, msg: Message):
|
| 125 |
logger.info(f"/start from {msg.from_user.id}")
|
| 126 |
+
await msg.reply("👋 Welcome! Send any file to upload.")
|
| 127 |
|
| 128 |
@app.on_message(filters.command("help"))
|
| 129 |
async def help_cmd(_, msg: Message):
|
| 130 |
+
await msg.reply("/start, /files, /help")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
@app.on_message(filters.command("files"))
|
| 133 |
async def list_files(_, msg: Message):
|
|
|
|
| 140 |
kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
|
| 141 |
await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
|
| 142 |
|
| 143 |
+
# ---------- KEEP‑ALIVE ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
async def keep_alive():
|
| 145 |
async def handler(request):
|
| 146 |
return web.Response(text="Alive")
|
|
|
|
| 163 |
await asyncio.sleep(KEEPALIVE_INTERVAL)
|
| 164 |
asyncio.create_task(pinger())
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
# ---------- MAIN ----------
|
| 167 |
async def main():
|
| 168 |
logger.info("Verifying environment... OK")
|
|
|
|
| 169 |
await keep_alive()
|
|
|
|
|
|
|
| 170 |
|
| 171 |
while True:
|
| 172 |
try:
|
|
|
|
| 181 |
logger.exception(f"Start error: {e}")
|
| 182 |
await asyncio.sleep(30)
|
| 183 |
|
| 184 |
+
# idle forever
|
| 185 |
await asyncio.Event().wait()
|
| 186 |
|
| 187 |
if __name__ == "__main__":
|