Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import os
|
| 2 |
-
import sys
|
| 3 |
import json
|
| 4 |
import math
|
| 5 |
import time
|
|
@@ -8,11 +7,11 @@ import shutil
|
|
| 8 |
import asyncio
|
| 9 |
import logging
|
| 10 |
import tempfile
|
| 11 |
-
from
|
| 12 |
-
from typing import Dict, Optional, Tuple
|
| 13 |
|
| 14 |
import aiohttp
|
| 15 |
from aiohttp import web
|
|
|
|
| 16 |
from cryptography.fernet import Fernet
|
| 17 |
from cryptography.hazmat.primitives import hashes
|
| 18 |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
|
@@ -25,11 +24,10 @@ from pyrogram.types import (
|
|
| 25 |
InlineKeyboardMarkup,
|
| 26 |
InlineKeyboardButton,
|
| 27 |
)
|
| 28 |
-
from pyrogram.errors import MessageNotModified
|
| 29 |
-
from huggingface_hub import HfApi, login, upload_file, hf_hub_url
|
| 30 |
-
from huggingface_hub.utils import RepositoryNotFoundError, EntryNotFoundError
|
| 31 |
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
BOT_TOKEN = os.environ["BOT_TOKEN"]
|
| 34 |
API_ID = int(os.environ["API_ID"])
|
| 35 |
API_HASH = os.environ["API_HASH"]
|
|
@@ -40,728 +38,228 @@ HF_REPO_ID = "Cxops/Bzxv"
|
|
| 40 |
HF_REPO_TYPE = "dataset"
|
| 41 |
HF_BRANCH = "main"
|
| 42 |
|
| 43 |
-
MIN_FREE_DISK = 45 * 1024**3
|
| 44 |
-
SPLIT_SIZE = 2 * 1024**3 - 10*1024*
|
| 45 |
-
PROGRESS_INTERVAL = 3 # seconds
|
| 46 |
-
KEEPALIVE_INTERVAL = 300 # 5 minutes
|
| 47 |
|
| 48 |
-
# ------------------- Logging -------------------
|
| 49 |
logging.basicConfig(level=logging.INFO)
|
| 50 |
-
|
| 51 |
|
| 52 |
-
# ----------------
|
| 53 |
-
SALT = b"
|
| 54 |
kdf = PBKDF2HMAC(
|
| 55 |
algorithm=hashes.SHA256(),
|
| 56 |
length=32,
|
| 57 |
salt=SALT,
|
| 58 |
-
iterations=
|
| 59 |
backend=default_backend(),
|
| 60 |
)
|
| 61 |
key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
|
| 62 |
fernet = Fernet(key)
|
| 63 |
|
| 64 |
-
def encrypt(
|
| 65 |
-
|
| 66 |
-
token = fernet.encrypt(data.encode())
|
| 67 |
-
return base64.urlsafe_b64encode(token).decode().rstrip("=")
|
| 68 |
-
|
| 69 |
-
def decrypt(token: str) -> str:
|
| 70 |
-
"""Decrypt URL‑safe base64 token back to string."""
|
| 71 |
-
# add padding
|
| 72 |
-
pad = 4 - len(token) % 4
|
| 73 |
-
if pad != 4:
|
| 74 |
-
token += "=" * pad
|
| 75 |
-
raw = base64.urlsafe_b64decode(token)
|
| 76 |
-
return fernet.decrypt(raw).decode()
|
| 77 |
-
|
| 78 |
-
# Folder name = encrypt(str(user_id))
|
| 79 |
-
def get_user_folder(user_id: int) -> str:
|
| 80 |
-
return encrypt(str(user_id))
|
| 81 |
-
|
| 82 |
-
# ------------------- Hugging Face API -------------------
|
| 83 |
-
hf_api = HfApi(token=HF_TOKEN)
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
""
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
return None
|
| 95 |
|
| 96 |
def hf_write_json(path: str, data: dict):
|
| 97 |
-
""
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
path_in_repo=path,
|
| 102 |
repo_id=HF_REPO_ID,
|
| 103 |
repo_type=HF_REPO_TYPE,
|
| 104 |
-
|
| 105 |
)
|
|
|
|
| 106 |
|
| 107 |
-
def
|
| 108 |
-
"""Delete a file from the HF repo."""
|
| 109 |
try:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def hf_file_size(path: str) -> Optional[int]:
|
| 116 |
-
"""Return file size in bytes (LFS or normal)."""
|
| 117 |
try:
|
| 118 |
-
info = hf_api.
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
except Exception as e:
|
| 123 |
-
|
| 124 |
-
return None
|
| 125 |
|
| 126 |
-
# ----------------
|
| 127 |
-
|
| 128 |
-
return shutil.disk_usage("/").free / (1024**3)
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
|
| 134 |
-
# ----------------
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
active_progress: Dict[int, dict] = {}
|
| 140 |
-
# Queue for operations (serialised worker)
|
| 141 |
-
op_queue = asyncio.Queue()
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
|
| 146 |
-
# ----------------
|
| 147 |
-
async def
|
| 148 |
-
"""Periodically edit all active progress messages."""
|
| 149 |
-
while True:
|
| 150 |
-
await asyncio.sleep(PROGRESS_INTERVAL)
|
| 151 |
-
for msg_id, info in list(active_progress.items()):
|
| 152 |
-
try:
|
| 153 |
-
chat_id = info["chat_id"]
|
| 154 |
-
state = info["state"]
|
| 155 |
-
filename = info["filename"]
|
| 156 |
-
current = info.get("current", 0)
|
| 157 |
-
total = info.get("total", 0)
|
| 158 |
-
start_time = info.get("start_time", time.time())
|
| 159 |
-
cancel_event = info.get("cancel_event", None)
|
| 160 |
-
op_type = info.get("op_type", "")
|
| 161 |
-
|
| 162 |
-
# Calculate speed and percentage
|
| 163 |
-
elapsed = max(time.time() - start_time, 1)
|
| 164 |
-
speed = current / elapsed if current > 0 else 0
|
| 165 |
-
if total > 0:
|
| 166 |
-
percent = (current / total) * 100
|
| 167 |
-
progress_bar = make_progress_bar(percent)
|
| 168 |
-
text = (
|
| 169 |
-
f"**{op_type}** `{filename}`\n"
|
| 170 |
-
f"{progress_bar} {percent:.1f}%\n"
|
| 171 |
-
f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
|
| 172 |
-
f"⚡ {format_bytes(speed)}/s"
|
| 173 |
-
)
|
| 174 |
-
else:
|
| 175 |
-
text = f"**{op_type}** `{filename}`\n⏳ Processing..."
|
| 176 |
-
|
| 177 |
-
# Inline keyboard with Cancel button (only if operation can be cancelled)
|
| 178 |
-
keyboard = None
|
| 179 |
-
if state in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
|
| 180 |
-
keyboard = InlineKeyboardMarkup([
|
| 181 |
-
[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")]
|
| 182 |
-
])
|
| 183 |
-
# For 'uploading_to_hf' no cancel button to keep things simple.
|
| 184 |
-
await app_client.edit_message_text(
|
| 185 |
-
chat_id, msg_id, text, reply_markup=keyboard
|
| 186 |
-
)
|
| 187 |
-
except MessageNotModified:
|
| 188 |
-
pass
|
| 189 |
-
except Exception as e:
|
| 190 |
-
logger.error(f"Updater error for msg {msg_id}: {e}")
|
| 191 |
-
|
| 192 |
-
def make_progress_bar(percent: float, width: int = 10) -> str:
|
| 193 |
-
filled = int(width * percent / 100)
|
| 194 |
-
return "█" * filled + "░" * (width - filled)
|
| 195 |
-
|
| 196 |
-
def format_bytes(size: int) -> str:
|
| 197 |
-
if size == 0:
|
| 198 |
-
return "0 B"
|
| 199 |
-
units = ["B", "KB", "MB", "GB", "TB"]
|
| 200 |
-
i = int(math.floor(math.log(size, 1024)))
|
| 201 |
-
p = math.pow(1024, i)
|
| 202 |
-
s = round(size / p, 1)
|
| 203 |
-
return f"{s} {units[i]}"
|
| 204 |
-
|
| 205 |
-
# ------------------- Operation worker -------------------
|
| 206 |
-
async def operation_worker():
|
| 207 |
-
"""Process one operation at a time from the queue."""
|
| 208 |
while True:
|
| 209 |
-
op = await
|
| 210 |
try:
|
| 211 |
if op["type"] == "upload":
|
| 212 |
-
await
|
| 213 |
-
|
| 214 |
-
await
|
| 215 |
except Exception as e:
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
await app_client.edit_message_text(
|
| 223 |
-
chat_id, msg_id, f"❌ Error: {e}"
|
| 224 |
-
)
|
| 225 |
-
except:
|
| 226 |
-
pass
|
| 227 |
-
# Clean up progress entry
|
| 228 |
-
if msg_id in active_progress:
|
| 229 |
-
del active_progress[msg_id]
|
| 230 |
-
finally:
|
| 231 |
-
op_queue.task_done()
|
| 232 |
-
|
| 233 |
-
async def handle_upload(op: dict):
|
| 234 |
-
"""Process a single upload: download from Telegram → upload to HF."""
|
| 235 |
-
user_id = op["user_id"]
|
| 236 |
-
chat_id = op["chat_id"]
|
| 237 |
file_id = op["file_id"]
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
# Initialise progress
|
| 243 |
-
active_progress[msg_id] = {
|
| 244 |
-
"chat_id": chat_id,
|
| 245 |
-
"state": "downloading_from_tg",
|
| 246 |
-
"filename": file_name,
|
| 247 |
-
"current": 0,
|
| 248 |
-
"total": 0,
|
| 249 |
-
"start_time": time.time(),
|
| 250 |
-
"cancel_event": cancel_event,
|
| 251 |
-
"op_type": "Upload",
|
| 252 |
-
}
|
| 253 |
|
| 254 |
-
|
| 255 |
-
while not enough_disk():
|
| 256 |
-
try:
|
| 257 |
-
await app_client.edit_message_text(
|
| 258 |
-
chat_id, msg_id,
|
| 259 |
-
f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)",
|
| 260 |
-
)
|
| 261 |
-
except:
|
| 262 |
-
pass
|
| 263 |
-
await asyncio.sleep(10)
|
| 264 |
-
if cancel_event.is_set():
|
| 265 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
|
| 266 |
-
del active_progress[msg_id]
|
| 267 |
-
return
|
| 268 |
-
|
| 269 |
-
# Download file from Telegram
|
| 270 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
|
| 271 |
-
os.close(tmp_fd)
|
| 272 |
-
try:
|
| 273 |
-
# Progress callback for Pyrogram download
|
| 274 |
-
def tg_progress(current, total, msg_id):
|
| 275 |
-
info = active_progress.get(msg_id)
|
| 276 |
-
if info:
|
| 277 |
-
info["current"] = current
|
| 278 |
-
info["total"] = total
|
| 279 |
-
info["start_time"] = time.time() # keep updating start to get recent speed
|
| 280 |
-
|
| 281 |
-
await app_client.download_media(
|
| 282 |
-
file_id,
|
| 283 |
-
file_name=tmp_path,
|
| 284 |
-
progress=tg_progress,
|
| 285 |
-
progress_args=(msg_id,),
|
| 286 |
-
)
|
| 287 |
-
except Exception as e:
|
| 288 |
-
logger.error(f"Download failed: {e}")
|
| 289 |
-
if os.path.exists(tmp_path):
|
| 290 |
-
os.unlink(tmp_path)
|
| 291 |
-
await app_client.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
|
| 292 |
-
del active_progress[msg_id]
|
| 293 |
-
return
|
| 294 |
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
os.unlink(tmp_path)
|
| 298 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
|
| 299 |
-
del active_progress[msg_id]
|
| 300 |
-
return
|
| 301 |
|
| 302 |
-
|
| 303 |
-
active_progress[msg_id]["state"] = "uploading_to_hf"
|
| 304 |
-
active_progress[msg_id]["current"] = 0
|
| 305 |
-
active_progress[msg_id]["total"] = 0
|
| 306 |
-
|
| 307 |
-
# Prepare HF paths
|
| 308 |
-
folder = get_user_folder(user_id)
|
| 309 |
-
enc_fname = encrypt(file_name)
|
| 310 |
-
hf_path = f"{folder}/{enc_fname}"
|
| 311 |
-
meta_path = f"{folder}/meta.json"
|
| 312 |
-
|
| 313 |
-
# Upload to HF with progress callback
|
| 314 |
-
def hf_progress(current, total, msg_id):
|
| 315 |
-
info = active_progress.get(msg_id)
|
| 316 |
-
if info:
|
| 317 |
-
info["current"] = current
|
| 318 |
-
info["total"] = total
|
| 319 |
-
info["start_time"] = time.time()
|
| 320 |
-
|
| 321 |
-
# Upload the file
|
| 322 |
-
try:
|
| 323 |
-
upload_file(
|
| 324 |
-
path_or_fileobj=tmp_path,
|
| 325 |
-
path_in_repo=hf_path,
|
| 326 |
-
repo_id=HF_REPO_ID,
|
| 327 |
-
repo_type=HF_REPO_TYPE,
|
| 328 |
-
token=HF_TOKEN,
|
| 329 |
-
progress_callback=hf_progress,
|
| 330 |
-
progress_callback_msg_id=msg_id,
|
| 331 |
-
)
|
| 332 |
-
except Exception as e:
|
| 333 |
-
logger.error(f"HF upload failed: {e}")
|
| 334 |
-
if os.path.exists(tmp_path):
|
| 335 |
-
os.unlink(tmp_path)
|
| 336 |
-
await app_client.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
|
| 337 |
-
del active_progress[msg_id]
|
| 338 |
-
return
|
| 339 |
|
| 340 |
-
|
| 341 |
-
if cancel_event.is_set():
|
| 342 |
-
# Rollback: delete file and meta entry
|
| 343 |
-
hf_delete_file(hf_path)
|
| 344 |
-
# update meta to remove entry
|
| 345 |
-
meta = hf_read_json(meta_path) or {}
|
| 346 |
-
meta.pop(enc_fname, None)
|
| 347 |
-
hf_write_json(meta_path, meta)
|
| 348 |
-
if os.path.exists(tmp_path):
|
| 349 |
-
os.unlink(tmp_path)
|
| 350 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
|
| 351 |
-
del active_progress[msg_id]
|
| 352 |
-
return
|
| 353 |
|
| 354 |
-
|
| 355 |
-
meta = hf_read_json(meta_path) or {}
|
| 356 |
-
meta[enc_fname] = file_name
|
| 357 |
-
try:
|
| 358 |
-
hf_write_json(meta_path, meta)
|
| 359 |
-
except Exception as e:
|
| 360 |
-
logger.error(f"Meta upload failed: {e}")
|
| 361 |
-
# File already uploaded, inform user
|
| 362 |
-
await app_client.edit_message_text(chat_id, msg_id, f"✅ File uploaded, but metadata update failed: {e}")
|
| 363 |
-
if os.path.exists(tmp_path):
|
| 364 |
-
os.unlink(tmp_path)
|
| 365 |
-
del active_progress[msg_id]
|
| 366 |
return
|
| 367 |
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
else:
|
| 401 |
-
needed = file_size or 0
|
| 402 |
-
while not enough_disk(needed):
|
| 403 |
-
try:
|
| 404 |
-
await app_client.edit_message_text(
|
| 405 |
-
chat_id, msg_id,
|
| 406 |
-
f"⏳ Waiting for disk space to download `{orig_name}`…",
|
| 407 |
-
)
|
| 408 |
-
except:
|
| 409 |
-
pass
|
| 410 |
-
await asyncio.sleep(10)
|
| 411 |
-
if cancel_event.is_set():
|
| 412 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
|
| 413 |
-
del active_progress[msg_id]
|
| 414 |
-
return
|
| 415 |
-
|
| 416 |
-
url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}", repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
|
| 417 |
-
|
| 418 |
-
if file_size is None or file_size <= SPLIT_SIZE:
|
| 419 |
-
# Single file download
|
| 420 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
|
| 421 |
-
os.close(tmp_fd)
|
| 422 |
-
try:
|
| 423 |
-
success = await download_from_url(url, tmp_path, msg_id, cancel_event,
|
| 424 |
-
file_size, orig_name)
|
| 425 |
-
if not success:
|
| 426 |
-
return # cancelled or error handled inside
|
| 427 |
-
|
| 428 |
-
# Upload to Telegram
|
| 429 |
-
active_progress[msg_id]["state"] = "sending_to_tg"
|
| 430 |
-
active_progress[msg_id]["current"] = 0
|
| 431 |
-
active_progress[msg_id]["total"] = os.path.getsize(tmp_path)
|
| 432 |
-
await app_client.send_document(
|
| 433 |
-
chat_id, tmp_path,
|
| 434 |
-
caption=orig_name,
|
| 435 |
-
progress=upload_progress,
|
| 436 |
-
progress_args=(msg_id,),
|
| 437 |
-
)
|
| 438 |
-
# Check cancel
|
| 439 |
-
if cancel_event.is_set():
|
| 440 |
-
await app_client.stop_transmission()
|
| 441 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
|
| 442 |
-
del active_progress[msg_id]
|
| 443 |
-
return
|
| 444 |
-
await app_client.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
|
| 445 |
-
finally:
|
| 446 |
-
if os.path.exists(tmp_path):
|
| 447 |
-
os.unlink(tmp_path)
|
| 448 |
-
del active_progress[msg_id]
|
| 449 |
-
else:
|
| 450 |
-
# Split into parts
|
| 451 |
-
total_parts = math.ceil(file_size / SPLIT_SIZE)
|
| 452 |
-
for part_idx in range(total_parts):
|
| 453 |
-
if cancel_event.is_set():
|
| 454 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
|
| 455 |
-
del active_progress[msg_id]
|
| 456 |
-
return
|
| 457 |
-
start = part_idx * SPLIT_SIZE
|
| 458 |
-
end = min(start + SPLIT_SIZE - 1, file_size - 1)
|
| 459 |
-
part_size = end - start + 1
|
| 460 |
-
part_name = f"{orig_name}.part{part_idx+1:03d}"
|
| 461 |
-
|
| 462 |
-
# update progress for this part
|
| 463 |
-
active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
|
| 464 |
-
active_progress[msg_id]["current"] = 0
|
| 465 |
-
active_progress[msg_id]["total"] = part_size
|
| 466 |
-
|
| 467 |
-
tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
|
| 468 |
-
os.close(tmp_fd)
|
| 469 |
-
try:
|
| 470 |
-
success = await download_range(url, start, end, tmp_path, msg_id,
|
| 471 |
-
cancel_event, part_size, part_name)
|
| 472 |
-
if not success:
|
| 473 |
-
return
|
| 474 |
-
# Upload part
|
| 475 |
-
active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
|
| 476 |
-
active_progress[msg_id]["total"] = part_size
|
| 477 |
-
await app_client.send_document(
|
| 478 |
-
chat_id, tmp_path,
|
| 479 |
-
caption=f"{orig_name} - Part {part_idx+1}/{total_parts}",
|
| 480 |
-
progress=upload_progress,
|
| 481 |
-
progress_args=(msg_id,),
|
| 482 |
-
)
|
| 483 |
-
if cancel_event.is_set():
|
| 484 |
-
await app_client.stop_transmission()
|
| 485 |
-
await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
|
| 486 |
-
del active_progress[msg_id]
|
| 487 |
-
return
|
| 488 |
-
finally:
|
| 489 |
-
if os.path.exists(tmp_path):
|
| 490 |
-
os.unlink(tmp_path)
|
| 491 |
-
await app_client.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
|
| 492 |
-
del active_progress[msg_id]
|
| 493 |
-
|
| 494 |
-
def upload_progress(current, total, msg_id):
|
| 495 |
-
info = active_progress.get(msg_id)
|
| 496 |
-
if info:
|
| 497 |
-
info["current"] = current
|
| 498 |
-
info["total"] = total
|
| 499 |
-
info["start_time"] = time.time()
|
| 500 |
-
|
| 501 |
-
async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyncio.Event,
|
| 502 |
-
total_size: Optional[int], name: str) -> bool:
|
| 503 |
-
"""Download a whole file with progress, returns True on success."""
|
| 504 |
-
try:
|
| 505 |
-
async with aiohttp.ClientSession() as session:
|
| 506 |
-
async with session.get(url) as resp:
|
| 507 |
-
if resp.status != 200:
|
| 508 |
-
raise Exception(f"HTTP {resp.status}")
|
| 509 |
-
total = total_size or int(resp.headers.get("Content-Length", 0))
|
| 510 |
-
info = active_progress.get(msg_id)
|
| 511 |
-
if info:
|
| 512 |
-
info["total"] = total
|
| 513 |
-
downloaded = 0
|
| 514 |
-
with open(dest, "wb") as f:
|
| 515 |
-
async for chunk in resp.content.iter_chunked(64*1024):
|
| 516 |
-
if cancel_event.is_set():
|
| 517 |
-
return False
|
| 518 |
-
f.write(chunk)
|
| 519 |
-
downloaded += len(chunk)
|
| 520 |
-
if info:
|
| 521 |
-
info["current"] = downloaded
|
| 522 |
-
info["start_time"] = time.time()
|
| 523 |
-
return True
|
| 524 |
-
except Exception as e:
|
| 525 |
-
logger.error(f"Download error: {e}")
|
| 526 |
-
await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
|
| 527 |
-
return False
|
| 528 |
-
|
| 529 |
-
async def download_range(url: str, start: int, end: int, dest: str, msg_id: int,
|
| 530 |
-
cancel_event: asyncio.Event, size: int, name: str) -> bool:
|
| 531 |
-
headers = {"Range": f"bytes={start}-{end}"}
|
| 532 |
-
try:
|
| 533 |
-
async with aiohttp.ClientSession() as session:
|
| 534 |
-
async with session.get(url, headers=headers) as resp:
|
| 535 |
-
if resp.status not in (200, 206):
|
| 536 |
-
raise Exception(f"HTTP {resp.status}")
|
| 537 |
-
total = size
|
| 538 |
-
info = active_progress.get(msg_id)
|
| 539 |
-
if info:
|
| 540 |
-
info["total"] = total
|
| 541 |
-
downloaded = 0
|
| 542 |
-
with open(dest, "wb") as f:
|
| 543 |
-
async for chunk in resp.content.iter_chunked(64*1024):
|
| 544 |
-
if cancel_event.is_set():
|
| 545 |
-
return False
|
| 546 |
-
f.write(chunk)
|
| 547 |
-
downloaded += len(chunk)
|
| 548 |
-
if info:
|
| 549 |
-
info["current"] = downloaded
|
| 550 |
-
info["start_time"] = time.time()
|
| 551 |
-
return True
|
| 552 |
-
except Exception as e:
|
| 553 |
-
logger.error(f"Range download error: {e}")
|
| 554 |
-
await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
|
| 555 |
-
return False
|
| 556 |
-
|
| 557 |
-
# ------------------- Telegram Handlers -------------------
|
| 558 |
-
@app_client.on_message(filters.command("start"))
|
| 559 |
-
async def start_cmd(client: Client, message: Message):
|
| 560 |
-
await message.reply(
|
| 561 |
-
"👋 Hello! Send me any file to upload it to the cloud.\n"
|
| 562 |
-
"Use /files to see your uploaded files.",
|
| 563 |
-
)
|
| 564 |
-
|
| 565 |
-
@app_client.on_message(filters.command("files"))
|
| 566 |
-
async def list_files(client: Client, message: Message):
|
| 567 |
-
user_id = message.from_user.id
|
| 568 |
-
folder = get_user_folder(user_id)
|
| 569 |
-
meta_path = f"{folder}/meta.json"
|
| 570 |
-
meta = hf_read_json(meta_path)
|
| 571 |
-
if not meta or len(meta) == 0:
|
| 572 |
-
await message.reply("📭 You haven't uploaded any files yet.")
|
| 573 |
return
|
| 574 |
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
keyboard.append([InlineKeyboardButton(orig_name, callback_data=f"dl_{enc_name}")])
|
| 579 |
-
keyboard.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
|
| 580 |
-
await message.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
|
| 581 |
-
|
| 582 |
-
@app_client.on_callback_query(filters.regex(r"^files_refresh$"))
|
| 583 |
-
async def refresh_files(client: Client, query: CallbackQuery):
|
| 584 |
-
await query.answer("Refreshing…")
|
| 585 |
-
await list_files(client, query.message)
|
| 586 |
-
await query.message.delete()
|
| 587 |
-
|
| 588 |
-
@app_client.on_callback_query(filters.regex(r"^dl_(.+)"))
|
| 589 |
-
async def download_file_cb(client: Client, query: CallbackQuery):
|
| 590 |
-
enc_fname = query.data.split("_", 1)[1]
|
| 591 |
-
user_id = query.from_user.id
|
| 592 |
-
folder = get_user_folder(user_id)
|
| 593 |
-
meta = hf_read_json(f"{folder}/meta.json")
|
| 594 |
-
if not meta or enc_fname not in meta:
|
| 595 |
-
await query.answer("File not found!", show_alert=True)
|
| 596 |
-
return
|
| 597 |
-
orig_name = meta[enc_fname]
|
| 598 |
-
file_size = hf_file_size(f"{folder}/{enc_fname}")
|
| 599 |
-
if file_size is None:
|
| 600 |
-
await query.answer("Cannot read file size.", show_alert=True)
|
| 601 |
-
return
|
| 602 |
-
|
| 603 |
-
await query.answer("Starting download…")
|
| 604 |
-
# Create a progress message
|
| 605 |
-
status_msg = await client.send_message(
|
| 606 |
-
query.message.chat.id, f"⏳ Preparing download: `{orig_name}`…"
|
| 607 |
-
)
|
| 608 |
-
cancel_event = asyncio.Event()
|
| 609 |
-
# Add cancel button callback
|
| 610 |
-
active_progress[status_msg.id] = {
|
| 611 |
-
"chat_id": status_msg.chat.id,
|
| 612 |
-
"state": "starting",
|
| 613 |
-
"filename": orig_name,
|
| 614 |
-
"current": 0,
|
| 615 |
-
"total": 0,
|
| 616 |
-
"start_time": time.time(),
|
| 617 |
-
"cancel_event": cancel_event,
|
| 618 |
-
"op_type": "Download",
|
| 619 |
-
}
|
| 620 |
-
# Enqueue the operation
|
| 621 |
-
await op_queue.put({
|
| 622 |
-
"type": "download",
|
| 623 |
-
"user_id": user_id,
|
| 624 |
-
"chat_id": status_msg.chat.id,
|
| 625 |
-
"folder": folder,
|
| 626 |
-
"enc_fname": enc_fname,
|
| 627 |
-
"orig_name": orig_name,
|
| 628 |
-
"file_size": file_size,
|
| 629 |
-
"status_msg_id": status_msg.id,
|
| 630 |
-
"cancel_event": cancel_event,
|
| 631 |
-
})
|
| 632 |
|
| 633 |
-
|
| 634 |
-
async def cancel_operation(client: Client, query: CallbackQuery):
|
| 635 |
-
msg_id = int(query.data.split("_")[2])
|
| 636 |
-
info = active_progress.get(msg_id)
|
| 637 |
-
if info and "cancel_event" in info:
|
| 638 |
-
info["cancel_event"].set()
|
| 639 |
-
await query.answer("Cancelling…")
|
| 640 |
-
else:
|
| 641 |
-
await query.answer("Nothing to cancel.", show_alert=True)
|
| 642 |
-
|
| 643 |
-
@app_client.on_message(filters.media & filters.private)
|
| 644 |
-
async def media_handler(client: Client, message: Message):
|
| 645 |
-
user_id = message.from_user.id
|
| 646 |
-
# Extract file info
|
| 647 |
-
if message.document:
|
| 648 |
-
file_id = message.document.file_id
|
| 649 |
-
file_name = message.document.file_name or "file"
|
| 650 |
-
file_size = message.document.file_size
|
| 651 |
-
elif message.video:
|
| 652 |
-
file_id = message.video.file_id
|
| 653 |
-
file_name = message.video.file_name or "video.mp4"
|
| 654 |
-
file_size = message.video.file_size
|
| 655 |
-
elif message.audio:
|
| 656 |
-
file_id = message.audio.file_id
|
| 657 |
-
file_name = message.audio.file_name or "audio.mp3"
|
| 658 |
-
file_size = message.audio.file_size
|
| 659 |
-
elif message.photo:
|
| 660 |
-
# Use largest photo
|
| 661 |
-
file_id = message.photo.file_id
|
| 662 |
-
file_name = f"photo_{message.photo.file_unique_id}.jpg"
|
| 663 |
-
file_size = message.photo.file_size # may be 0
|
| 664 |
-
else:
|
| 665 |
-
return
|
| 666 |
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
"
|
| 671 |
-
|
| 672 |
-
[InlineKeyboardButton("✅ Upload", callback_data=f"upload_{message.id}")],
|
| 673 |
-
[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{message.id}")],
|
| 674 |
-
]),
|
| 675 |
-
quote=True,
|
| 676 |
-
)
|
| 677 |
-
pending_uploads[prompt.id] = {
|
| 678 |
-
"file_id": file_id,
|
| 679 |
-
"file_name": file_name,
|
| 680 |
-
"file_size": file_size,
|
| 681 |
-
"user_id": user_id,
|
| 682 |
}
|
| 683 |
|
| 684 |
-
@
|
| 685 |
-
async def
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
await
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
cancel_event = asyncio.Event()
|
| 702 |
-
# Enqueue
|
| 703 |
-
await op_queue.put({
|
| 704 |
-
"type": "upload",
|
| 705 |
-
"user_id": info["user_id"],
|
| 706 |
-
"chat_id": prompt_msg.chat.id,
|
| 707 |
-
"file_id": info["file_id"],
|
| 708 |
-
"file_name": info["file_name"],
|
| 709 |
-
"status_msg_id": status_msg.id,
|
| 710 |
-
"cancel_event": cancel_event,
|
| 711 |
})
|
| 712 |
|
| 713 |
-
|
| 714 |
-
async def cancel_prompt(client: Client, query: CallbackQuery):
|
| 715 |
-
prompt_msg = query.message
|
| 716 |
-
pending_uploads.pop(prompt_msg.id, None)
|
| 717 |
-
await query.answer("Cancelled.")
|
| 718 |
-
await prompt_msg.delete()
|
| 719 |
-
|
| 720 |
-
# ------------------- Keep-alive HTTP server -------------------
|
| 721 |
-
async def keep_alive_server():
|
| 722 |
-
"""Simple HTTP server that responds to pings to prevent space from sleeping."""
|
| 723 |
-
async def handle(request):
|
| 724 |
-
return web.Response(text="Bot is alive")
|
| 725 |
-
app = web.Application()
|
| 726 |
-
app.router.add_get("/", handle)
|
| 727 |
-
runner = web.AppRunner(app)
|
| 728 |
-
await runner.setup()
|
| 729 |
-
site = web.TCPSite(runner, "0.0.0.0", 7860)
|
| 730 |
-
await site.start()
|
| 731 |
-
logger.info("Keep‑alive server started on port 7860")
|
| 732 |
-
|
| 733 |
-
# Ping itself every 5 minutes
|
| 734 |
-
async def self_ping():
|
| 735 |
-
await asyncio.sleep(10) # wait for server to start
|
| 736 |
-
while True:
|
| 737 |
-
try:
|
| 738 |
-
async with aiohttp.ClientSession() as session:
|
| 739 |
-
async with session.get("http://localhost:7860/") as resp:
|
| 740 |
-
logger.info(f"Self‑ping: {resp.status}")
|
| 741 |
-
except Exception as e:
|
| 742 |
-
logger.error(f"Self‑ping failed: {e}")
|
| 743 |
-
await asyncio.sleep(KEEPALIVE_INTERVAL)
|
| 744 |
-
|
| 745 |
-
asyncio.create_task(self_ping())
|
| 746 |
-
|
| 747 |
-
# ------------------- Main -------------------
|
| 748 |
-
async def main():
|
| 749 |
-
# Start keep‑alive
|
| 750 |
-
await keep_alive_server()
|
| 751 |
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
# Start worker and progress updater
|
| 757 |
-
asyncio.create_task(operation_worker())
|
| 758 |
-
asyncio.create_task(progress_updater())
|
| 759 |
-
|
| 760 |
-
# Idle
|
| 761 |
await asyncio.Event().wait()
|
| 762 |
|
| 763 |
if __name__ == "__main__":
|
| 764 |
-
|
| 765 |
-
asyncio.run(main())
|
| 766 |
-
except KeyboardInterrupt:
|
| 767 |
-
logger.info("Bot stopped.")
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import json
|
| 3 |
import math
|
| 4 |
import time
|
|
|
|
| 7 |
import asyncio
|
| 8 |
import logging
|
| 9 |
import tempfile
|
| 10 |
+
from typing import Dict, Optional
|
|
|
|
| 11 |
|
| 12 |
import aiohttp
|
| 13 |
from aiohttp import web
|
| 14 |
+
|
| 15 |
from cryptography.fernet import Fernet
|
| 16 |
from cryptography.hazmat.primitives import hashes
|
| 17 |
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
|
|
|
| 24 |
InlineKeyboardMarkup,
|
| 25 |
InlineKeyboardButton,
|
| 26 |
)
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
from huggingface_hub import HfApi, hf_hub_download, upload_file
|
| 29 |
+
|
| 30 |
+
# ---------------- CONFIG ----------------
|
| 31 |
BOT_TOKEN = os.environ["BOT_TOKEN"]
|
| 32 |
API_ID = int(os.environ["API_ID"])
|
| 33 |
API_HASH = os.environ["API_HASH"]
|
|
|
|
| 38 |
HF_REPO_TYPE = "dataset"
|
| 39 |
HF_BRANCH = "main"
|
| 40 |
|
| 41 |
+
MIN_FREE_DISK = 45 * 1024**3
|
| 42 |
+
SPLIT_SIZE = 2 * 1024**3 - 10 * 1024 * 1024
|
|
|
|
|
|
|
| 43 |
|
|
|
|
| 44 |
logging.basicConfig(level=logging.INFO)
|
| 45 |
+
log = logging.getLogger(__name__)
|
| 46 |
|
| 47 |
+
# ---------------- ENCRYPTION ----------------
|
| 48 |
+
SALT = b"hf_bot_salt_2025"
|
| 49 |
kdf = PBKDF2HMAC(
|
| 50 |
algorithm=hashes.SHA256(),
|
| 51 |
length=32,
|
| 52 |
salt=SALT,
|
| 53 |
+
iterations=100000,
|
| 54 |
backend=default_backend(),
|
| 55 |
)
|
| 56 |
key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
|
| 57 |
fernet = Fernet(key)
|
| 58 |
|
| 59 |
+
def encrypt(x: str) -> str:
|
| 60 |
+
return base64.urlsafe_b64encode(fernet.encrypt(x.encode())).decode().rstrip("=")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
def decrypt(x: str) -> str:
|
| 63 |
+
pad = "=" * (-len(x) % 4)
|
| 64 |
+
return fernet.decrypt(base64.urlsafe_b64decode(x + pad)).decode()
|
| 65 |
+
|
| 66 |
+
def user_folder(uid: int) -> str:
|
| 67 |
+
return encrypt(str(uid))
|
| 68 |
+
|
| 69 |
+
# ---------------- HF ----------------
|
| 70 |
+
hf_api = HfApi(token=HF_TOKEN)
|
|
|
|
| 71 |
|
| 72 |
def hf_write_json(path: str, data: dict):
|
| 73 |
+
with tempfile.NamedTemporaryFile("w", delete=False) as f:
|
| 74 |
+
json.dump(data, f)
|
| 75 |
+
tmp = f.name
|
| 76 |
+
|
| 77 |
+
upload_file(
|
| 78 |
+
path_or_fileobj=tmp,
|
| 79 |
path_in_repo=path,
|
| 80 |
repo_id=HF_REPO_ID,
|
| 81 |
repo_type=HF_REPO_TYPE,
|
| 82 |
+
token=HF_TOKEN,
|
| 83 |
)
|
| 84 |
+
os.remove(tmp)
|
| 85 |
|
| 86 |
+
def hf_read_json(path: str) -> Optional[dict]:
|
|
|
|
| 87 |
try:
|
| 88 |
+
tmp = hf_hub_download(
|
| 89 |
+
repo_id=HF_REPO_ID,
|
| 90 |
+
repo_type=HF_REPO_TYPE,
|
| 91 |
+
filename=path,
|
| 92 |
+
revision=HF_BRANCH,
|
| 93 |
+
)
|
| 94 |
+
with open(tmp, "r") as f:
|
| 95 |
+
return json.load(f)
|
| 96 |
+
except Exception:
|
| 97 |
+
return None
|
| 98 |
|
| 99 |
def hf_file_size(path: str) -> Optional[int]:
|
|
|
|
| 100 |
try:
|
| 101 |
+
info = hf_api.get_paths_info(
|
| 102 |
+
repo_id=HF_REPO_ID,
|
| 103 |
+
repo_type=HF_REPO_TYPE,
|
| 104 |
+
paths=[path],
|
| 105 |
+
)
|
| 106 |
+
return info[0].size
|
| 107 |
+
except Exception:
|
| 108 |
return None
|
| 109 |
+
|
| 110 |
+
def hf_delete(path: str):
|
| 111 |
+
try:
|
| 112 |
+
hf_api.delete_file(
|
| 113 |
+
path,
|
| 114 |
+
repo_id=HF_REPO_ID,
|
| 115 |
+
repo_type=HF_REPO_TYPE,
|
| 116 |
+
commit_message="delete",
|
| 117 |
+
)
|
| 118 |
except Exception as e:
|
| 119 |
+
log.error(e)
|
|
|
|
| 120 |
|
| 121 |
+
# ---------------- BOT ----------------
|
| 122 |
+
app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
|
|
|
|
| 123 |
|
| 124 |
+
active: Dict[int, dict] = {}
|
| 125 |
+
queue = asyncio.Queue()
|
| 126 |
+
pending = {}
|
| 127 |
|
| 128 |
+
# ---------------- HELPERS ----------------
|
| 129 |
+
def fmt(n):
|
| 130 |
+
if not n:
|
| 131 |
+
return "0 B"
|
| 132 |
+
u = ["B","KB","MB","GB"]
|
| 133 |
+
i = int(math.log(n,1024)) if n > 0 else 0
|
| 134 |
+
return f"{n/1024**i:.1f} {u[i]}"
|
| 135 |
|
| 136 |
+
def bar(p):
|
| 137 |
+
return "█"*int(p/10) + "░"*(10-int(p/10))
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
def free_ok(n=0):
|
| 140 |
+
return (shutil.disk_usage("/").free - n) > MIN_FREE_DISK
|
| 141 |
|
| 142 |
+
# ---------------- WORKER ----------------
|
| 143 |
+
async def worker():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
while True:
|
| 145 |
+
op = await queue.get()
|
| 146 |
try:
|
| 147 |
if op["type"] == "upload":
|
| 148 |
+
await upload_job(op)
|
| 149 |
+
else:
|
| 150 |
+
await download_job(op)
|
| 151 |
except Exception as e:
|
| 152 |
+
log.exception(e)
|
| 153 |
+
queue.task_done()
|
| 154 |
+
|
| 155 |
+
# ---------------- UPLOAD ----------------
|
| 156 |
+
async def upload_job(op):
|
| 157 |
+
msg = op["msg"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
file_id = op["file_id"]
|
| 159 |
+
name = op["name"]
|
| 160 |
+
uid = op["uid"]
|
| 161 |
+
cancel = op["cancel"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
+
active[msg] = {"chat": op["chat"], "file": name, "cur":0, "tot":0, "cancel": cancel}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
while not free_ok():
|
| 166 |
+
await asyncio.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
tmp = tempfile.mktemp()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
await app.download_media(file_id, file_name=tmp)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
if cancel.is_set():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
return
|
| 174 |
|
| 175 |
+
path = f"{user_folder(uid)}/{encrypt(name)}"
|
| 176 |
+
upload_file(tmp, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, path_in_repo=path, token=HF_TOKEN)
|
| 177 |
+
|
| 178 |
+
os.remove(tmp)
|
| 179 |
+
await app.send_message(op["chat"], f"✅ Uploaded {name}")
|
| 180 |
+
|
| 181 |
+
# ---------------- DOWNLOAD ----------------
|
| 182 |
+
async def download_job(op):
|
| 183 |
+
chat = op["chat"]
|
| 184 |
+
msg = op["msg"]
|
| 185 |
+
path = op["path"]
|
| 186 |
+
name = op["name"]
|
| 187 |
+
size = op["size"]
|
| 188 |
+
cancel = op["cancel"]
|
| 189 |
+
|
| 190 |
+
url = hf_api.hf_hub_url(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
|
| 191 |
+
|
| 192 |
+
tmp = tempfile.mktemp()
|
| 193 |
+
|
| 194 |
+
async with aiohttp.ClientSession() as s:
|
| 195 |
+
async with s.get(url) as r:
|
| 196 |
+
with open(tmp,"wb") as f:
|
| 197 |
+
async for c in r.content.iter_chunked(1024*64):
|
| 198 |
+
if cancel.is_set():
|
| 199 |
+
return
|
| 200 |
+
f.write(c)
|
| 201 |
+
|
| 202 |
+
await app.send_document(chat, tmp, caption=name)
|
| 203 |
+
os.remove(tmp)
|
| 204 |
+
|
| 205 |
+
# ---------------- HANDLERS ----------------
|
| 206 |
+
@app.on_message(filters.command("start"))
|
| 207 |
+
async def start(_, m):
|
| 208 |
+
await m.reply("Send files to upload.")
|
| 209 |
+
|
| 210 |
+
@app.on_message(filters.media & filters.private)
|
| 211 |
+
async def media(_, m):
|
| 212 |
+
if m.document:
|
| 213 |
+
fid = m.document.file_id
|
| 214 |
+
name = m.document.file_name
|
| 215 |
+
elif m.video:
|
| 216 |
+
fid = m.video.file_id
|
| 217 |
+
name = m.video.file_name
|
| 218 |
+
elif m.audio:
|
| 219 |
+
fid = m.audio.file_id
|
| 220 |
+
name = m.audio.file_name
|
| 221 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
return
|
| 223 |
|
| 224 |
+
btn = InlineKeyboardMarkup([
|
| 225 |
+
[InlineKeyboardButton("Upload", callback_data=f"up|{m.id}")]
|
| 226 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
+
msg = await m.reply(f"Upload {name}?", reply_markup=btn)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
+
pending[msg.id] = {
|
| 231 |
+
"file_id": fid,
|
| 232 |
+
"name": name,
|
| 233 |
+
"uid": m.from_user.id,
|
| 234 |
+
"chat": m.chat.id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
}
|
| 236 |
|
| 237 |
+
@app.on_callback_query(filters.regex("^up\\|"))
|
| 238 |
+
async def up(_, q):
|
| 239 |
+
mid = int(q.data.split("|")[1])
|
| 240 |
+
data = pending.pop(q.message.id, None)
|
| 241 |
+
if not data:
|
| 242 |
+
return await q.answer("Expired", show_alert=True)
|
| 243 |
+
|
| 244 |
+
cancel = asyncio.Event()
|
| 245 |
+
|
| 246 |
+
await queue.put({
|
| 247 |
+
"type":"upload",
|
| 248 |
+
"file_id": data["file_id"],
|
| 249 |
+
"name": data["name"],
|
| 250 |
+
"uid": data["uid"],
|
| 251 |
+
"chat": data["chat"],
|
| 252 |
+
"msg": q.message.id,
|
| 253 |
+
"cancel": cancel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
})
|
| 255 |
|
| 256 |
+
await q.message.edit("Uploading started...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
# ---------------- MAIN ----------------
|
| 259 |
+
async def main():
|
| 260 |
+
await app.start()
|
| 261 |
+
asyncio.create_task(worker())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
await asyncio.Event().wait()
|
| 263 |
|
| 264 |
if __name__ == "__main__":
|
| 265 |
+
asyncio.run(main())
|
|
|
|
|
|
|
|
|