Update app.py
Browse files
app.py
CHANGED
|
@@ -15,16 +15,15 @@ from pyrogram.errors import MessageNotModified, FloodWait
|
|
| 15 |
from huggingface_hub import HfApi, upload_file, hf_hub_url
|
| 16 |
from huggingface_hub.utils import EntryNotFoundError
|
| 17 |
|
| 18 |
-
# ---------- LOGGING
|
| 19 |
logging.basicConfig(level=logging.WARNING, format="%(asctime)s [%(levelname)s] %(message)s")
|
| 20 |
logger = logging.getLogger("bot")
|
| 21 |
logger.setLevel(logging.INFO)
|
| 22 |
|
| 23 |
-
# ----------
|
| 24 |
-
|
| 25 |
-
for var in REQUIRED_ENV:
|
| 26 |
if var not in os.environ:
|
| 27 |
-
logger.error(f"Missing
|
| 28 |
exit(1)
|
| 29 |
|
| 30 |
BOT_TOKEN = os.environ["BOT_TOKEN"]
|
|
@@ -32,8 +31,6 @@ API_ID = int(os.environ["API_ID"])
|
|
| 32 |
API_HASH = os.environ["API_HASH"]
|
| 33 |
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 34 |
SECRET_KEY = os.environ["SECRET_KEY"]
|
| 35 |
-
|
| 36 |
-
# Your Space public URL – no secret needed
|
| 37 |
SPACE_URL = "https://cxops-push.hf.space"
|
| 38 |
|
| 39 |
HF_REPO_ID = "Cxops/Bzxv"
|
|
@@ -46,10 +43,8 @@ KEEPALIVE_INTERVAL = 300
|
|
| 46 |
|
| 47 |
# ---------- ENCRYPTION ----------
|
| 48 |
SALT = b"huggingbot_salt_2025"
|
| 49 |
-
kdf = PBKDF2HMAC(
|
| 50 |
-
|
| 51 |
-
iterations=100_000, backend=default_backend()
|
| 52 |
-
)
|
| 53 |
key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
|
| 54 |
fernet = Fernet(key)
|
| 55 |
|
|
@@ -65,7 +60,7 @@ def decrypt(token: str) -> str:
|
|
| 65 |
def get_user_folder(user_id: int) -> str:
|
| 66 |
return encrypt(str(user_id))
|
| 67 |
|
| 68 |
-
# ---------- HUGGING FACE
|
| 69 |
hf_api = HfApi(token=HF_TOKEN)
|
| 70 |
|
| 71 |
def hf_read_json(path: str) -> Optional[dict]:
|
|
@@ -160,67 +155,295 @@ async def progress_updater():
|
|
| 160 |
except Exception as e:
|
| 161 |
logger.error(f"progress_updater error: {e}")
|
| 162 |
|
| 163 |
-
# ---------- UPLOAD / DOWNLOAD
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
@app.on_message(filters.command("start"))
|
| 173 |
async def start_cmd(_, msg: Message):
|
| 174 |
logger.info(f"/start from {msg.from_user.id}")
|
| 175 |
-
await msg.reply(
|
| 176 |
-
"👋 **Welcome to Cloud Storage Bot!**\n\n"
|
| 177 |
-
"Send any file to upload it to the cloud.\n"
|
| 178 |
-
"Use /files to see your uploaded files.\n"
|
| 179 |
-
"Help: /help"
|
| 180 |
-
)
|
| 181 |
|
| 182 |
@app.on_message(filters.command("help"))
|
| 183 |
async def help_cmd(_, msg: Message):
|
| 184 |
await msg.reply(
|
| 185 |
-
"**Commands:**\n"
|
| 186 |
-
"
|
| 187 |
-
"/files – List your files\n"
|
| 188 |
-
"/help – Show this help\n\n"
|
| 189 |
-
"**How to use:**\n"
|
| 190 |
-
"1. Send any file.\n"
|
| 191 |
"2. Click **Upload** to store it.\n"
|
| 192 |
-
"3. Use /files to download.
|
| 193 |
-
"Files >2GB are split automatically."
|
| 194 |
)
|
| 195 |
|
| 196 |
@app.on_message(filters.command("files"))
|
| 197 |
async def list_files(_, msg: Message):
|
| 198 |
user_id = msg.from_user.id
|
| 199 |
-
|
| 200 |
-
meta = hf_read_json(f"{folder}/meta.json")
|
| 201 |
if not meta:
|
| 202 |
-
await msg.reply("📭
|
| 203 |
return
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
|
| 208 |
|
| 209 |
-
@app.on_callback_query(filters.regex(
|
| 210 |
async def refresh_files(_, query: CallbackQuery):
|
| 211 |
await query.answer("Refreshing…")
|
| 212 |
await list_files(_, query.message)
|
| 213 |
await query.message.delete()
|
| 214 |
|
| 215 |
-
@app.on_callback_query(filters.regex(
|
| 216 |
async def download_file_cb(_, query: CallbackQuery):
|
| 217 |
enc = query.data.split("_", 1)[1]
|
| 218 |
user_id = query.from_user.id
|
| 219 |
folder = get_user_folder(user_id)
|
| 220 |
meta = hf_read_json(f"{folder}/meta.json")
|
| 221 |
if not meta or enc not in meta:
|
| 222 |
-
await query.answer("File not found
|
| 223 |
-
return
|
| 224 |
orig_name = meta[enc]
|
| 225 |
size = hf_file_size(f"{folder}/{enc}")
|
| 226 |
await query.answer("Starting download…")
|
|
@@ -237,16 +460,17 @@ async def download_file_cb(_, query: CallbackQuery):
|
|
| 237 |
"file_size": size, "status_msg_id": st.id, "cancel_event": cancel_ev
|
| 238 |
})
|
| 239 |
|
| 240 |
-
@app.on_callback_query(filters.regex(
|
| 241 |
-
async def
|
| 242 |
msg_id = int(query.data.split("_")[2])
|
| 243 |
info = active_progress.get(msg_id)
|
| 244 |
if info and "cancel_event" in info:
|
| 245 |
info["cancel_event"].set()
|
| 246 |
await query.answer("Cancelling…")
|
| 247 |
else:
|
| 248 |
-
await query.answer("Nothing to cancel
|
| 249 |
|
|
|
|
| 250 |
@app.on_message(filters.media)
|
| 251 |
async def media_handler(_, msg: Message):
|
| 252 |
logger.info(f"Media from {msg.from_user.id}")
|
|
@@ -255,33 +479,19 @@ async def media_handler(_, msg: Message):
|
|
| 255 |
file_size = 0
|
| 256 |
|
| 257 |
if msg.document:
|
| 258 |
-
file_id = msg.document.file_id
|
| 259 |
-
file_name = msg.document.file_name or "document"
|
| 260 |
-
file_size = msg.document.file_size
|
| 261 |
elif msg.video:
|
| 262 |
-
file_id = msg.video.file_id
|
| 263 |
-
file_name = msg.video.file_name or "video.mp4"
|
| 264 |
-
file_size = msg.video.file_size
|
| 265 |
elif msg.audio:
|
| 266 |
-
file_id = msg.audio.file_id
|
| 267 |
-
file_name = msg.audio.file_name or "audio.mp3"
|
| 268 |
-
file_size = msg.audio.file_size
|
| 269 |
elif msg.photo:
|
| 270 |
-
file_id = msg.photo.file_id
|
| 271 |
-
file_name = f"photo_{msg.photo.file_unique_id}.jpg"
|
| 272 |
-
file_size = msg.photo.file_size or 0
|
| 273 |
elif msg.voice:
|
| 274 |
-
file_id = msg.voice.file_id
|
| 275 |
-
file_name = f"voice_{msg.voice.file_unique_id}.ogg"
|
| 276 |
-
file_size = msg.voice.file_size
|
| 277 |
elif msg.video_note:
|
| 278 |
-
file_id = msg.video_note.file_id
|
| 279 |
-
file_name = f"vn_{msg.video_note.file_unique_id}.mp4"
|
| 280 |
-
file_size = msg.video_note.file_size
|
| 281 |
elif msg.sticker:
|
| 282 |
-
file_id = msg.sticker.file_id
|
| 283 |
-
file_name = f"sticker_{msg.sticker.file_unique_id}.webp"
|
| 284 |
-
file_size = msg.sticker.file_size
|
| 285 |
else:
|
| 286 |
return
|
| 287 |
|
|
@@ -289,8 +499,7 @@ async def media_handler(_, msg: Message):
|
|
| 289 |
return
|
| 290 |
|
| 291 |
prompt = await msg.reply(
|
| 292 |
-
f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\
|
| 293 |
-
"Do you want to upload this file?",
|
| 294 |
reply_markup=InlineKeyboardMarkup([[
|
| 295 |
InlineKeyboardButton("✅ Upload", callback_data=f"upload_{msg.id}"),
|
| 296 |
InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
|
|
@@ -298,39 +507,32 @@ async def media_handler(_, msg: Message):
|
|
| 298 |
quote=True,
|
| 299 |
)
|
| 300 |
pending_uploads[prompt.id] = {
|
| 301 |
-
"file_id": file_id,
|
| 302 |
-
"
|
| 303 |
-
"file_size": file_size,
|
| 304 |
-
"user_id": msg.from_user.id,
|
| 305 |
}
|
| 306 |
|
| 307 |
-
@app.on_callback_query(filters.regex(
|
| 308 |
async def confirm_upload(_, query: CallbackQuery):
|
| 309 |
info = pending_uploads.pop(query.message.id, None)
|
| 310 |
if not info:
|
| 311 |
-
await query.answer("
|
| 312 |
-
return
|
| 313 |
await query.answer()
|
| 314 |
await query.message.delete()
|
| 315 |
st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
|
| 316 |
cancel_ev = asyncio.Event()
|
| 317 |
await op_queue.put({
|
| 318 |
-
"type": "upload",
|
| 319 |
-
"
|
| 320 |
-
"
|
| 321 |
-
"file_id": info["file_id"],
|
| 322 |
-
"file_name": info["file_name"],
|
| 323 |
-
"status_msg_id": st.id,
|
| 324 |
-
"cancel_event": cancel_ev,
|
| 325 |
})
|
| 326 |
|
| 327 |
-
@app.on_callback_query(filters.regex(
|
| 328 |
async def cancel_prompt(_, query: CallbackQuery):
|
| 329 |
pending_uploads.pop(query.message.id, None)
|
| 330 |
await query.answer("Cancelled.")
|
| 331 |
await query.message.delete()
|
| 332 |
|
| 333 |
-
# ---------- KEEP
|
| 334 |
async def keep_alive():
|
| 335 |
async def handler(request):
|
| 336 |
return web.Response(text="Alive")
|
|
@@ -339,22 +541,21 @@ async def keep_alive():
|
|
| 339 |
runner = web.AppRunner(web_app)
|
| 340 |
await runner.setup()
|
| 341 |
await web.TCPSite(runner, "0.0.0.0", 7860).start()
|
| 342 |
-
logger.info(f"Keep‑alive
|
| 343 |
|
| 344 |
async def pinger():
|
| 345 |
await asyncio.sleep(10)
|
| 346 |
while True:
|
| 347 |
try:
|
| 348 |
-
async with aiohttp.ClientSession() as
|
| 349 |
-
async with
|
| 350 |
-
logger.info(f"
|
| 351 |
except Exception as e:
|
| 352 |
-
logger.error(f"
|
| 353 |
await asyncio.sleep(KEEPALIVE_INTERVAL)
|
| 354 |
-
|
| 355 |
asyncio.create_task(pinger())
|
| 356 |
|
| 357 |
-
# ----------
|
| 358 |
async def worker():
|
| 359 |
while True:
|
| 360 |
op = await op_queue.get()
|
|
@@ -368,38 +569,27 @@ async def worker():
|
|
| 368 |
finally:
|
| 369 |
op_queue.task_done()
|
| 370 |
|
| 371 |
-
# ---------- MAIN
|
| 372 |
async def main():
|
| 373 |
-
logger.info("
|
| 374 |
-
logger.info(f"
|
| 375 |
-
logger.info(f"Space URL: {SPACE_URL}")
|
| 376 |
-
logger.info(f"Disk limit: {MIN_FREE_DISK // (1024**3)} GB free required")
|
| 377 |
-
logger.info(f"Split size: {SPLIT_SIZE // (1024**2)} MB")
|
| 378 |
-
|
| 379 |
-
# Start keep-alive server immediately (so Space doesn't sleep)
|
| 380 |
await keep_alive()
|
| 381 |
-
|
| 382 |
-
# Start worker and progress updater (they will wait for app to be connected)
|
| 383 |
asyncio.create_task(worker())
|
| 384 |
asyncio.create_task(progress_updater())
|
| 385 |
|
| 386 |
-
# Try to start the bot with FloodWait handling
|
| 387 |
while True:
|
| 388 |
try:
|
| 389 |
await app.start()
|
| 390 |
-
logger.info("Bot
|
| 391 |
-
break
|
| 392 |
except FloodWait as e:
|
| 393 |
-
|
| 394 |
-
logger.warning(f"FloodWait
|
| 395 |
-
|
| 396 |
-
await asyncio.sleep(wait_secs)
|
| 397 |
-
# After waiting, the loop will retry automatically
|
| 398 |
except Exception as e:
|
| 399 |
-
logger.exception(f"
|
| 400 |
-
await asyncio.sleep(30)
|
| 401 |
|
| 402 |
-
# Keep running forever
|
| 403 |
await asyncio.Event().wait()
|
| 404 |
|
| 405 |
if __name__ == "__main__":
|
|
|
|
| 15 |
from huggingface_hub import HfApi, upload_file, hf_hub_url
|
| 16 |
from huggingface_hub.utils import EntryNotFoundError
|
| 17 |
|
| 18 |
+
# ---------- LOGGING ----------
|
| 19 |
logging.basicConfig(level=logging.WARNING, format="%(asctime)s [%(levelname)s] %(message)s")
|
| 20 |
logger = logging.getLogger("bot")
|
| 21 |
logger.setLevel(logging.INFO)
|
| 22 |
|
| 23 |
+
# ---------- CONFIG ----------
|
| 24 |
+
for var in ["BOT_TOKEN", "API_ID", "API_HASH", "HF_TOKEN", "SECRET_KEY"]:
|
|
|
|
| 25 |
if var not in os.environ:
|
| 26 |
+
logger.error(f"Missing {var}")
|
| 27 |
exit(1)
|
| 28 |
|
| 29 |
BOT_TOKEN = os.environ["BOT_TOKEN"]
|
|
|
|
| 31 |
API_HASH = os.environ["API_HASH"]
|
| 32 |
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 33 |
SECRET_KEY = os.environ["SECRET_KEY"]
|
|
|
|
|
|
|
| 34 |
SPACE_URL = "https://cxops-push.hf.space"
|
| 35 |
|
| 36 |
HF_REPO_ID = "Cxops/Bzxv"
|
|
|
|
| 43 |
|
| 44 |
# ---------- ENCRYPTION ----------
|
| 45 |
SALT = b"huggingbot_salt_2025"
|
| 46 |
+
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=SALT,
|
| 47 |
+
iterations=100_000, backend=default_backend())
|
|
|
|
|
|
|
| 48 |
key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
|
| 49 |
fernet = Fernet(key)
|
| 50 |
|
|
|
|
| 60 |
def get_user_folder(user_id: int) -> str:
|
| 61 |
return encrypt(str(user_id))
|
| 62 |
|
| 63 |
+
# ---------- HUGGING FACE ----------
|
| 64 |
hf_api = HfApi(token=HF_TOKEN)
|
| 65 |
|
| 66 |
def hf_read_json(path: str) -> Optional[dict]:
|
|
|
|
| 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 |
+
|
| 407 |
+
# ---------- COMMANDS ----------
|
| 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("👋 **Welcome!**\nSend any file to upload, /files to list, /help for help.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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):
|
| 424 |
user_id = msg.from_user.id
|
| 425 |
+
meta = hf_read_json(f"{get_user_folder(user_id)}/meta.json")
|
|
|
|
| 426 |
if not meta:
|
| 427 |
+
await msg.reply("📭 No files yet.")
|
| 428 |
return
|
| 429 |
+
kb = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")] for enc, name in meta.items()]
|
| 430 |
+
kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
|
| 431 |
+
await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
|
|
|
|
| 432 |
|
| 433 |
+
@app.on_callback_query(filters.regex("^files_refresh$"))
|
| 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…")
|
|
|
|
| 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}")
|
|
|
|
| 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 |
|
|
|
|
| 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}")
|
|
|
|
| 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")
|
|
|
|
| 541 |
runner = web.AppRunner(web_app)
|
| 542 |
await runner.setup()
|
| 543 |
await web.TCPSite(runner, "0.0.0.0", 7860).start()
|
| 544 |
+
logger.info(f"Keep‑alive on :7860, pinging {SPACE_URL}")
|
| 545 |
|
| 546 |
async def pinger():
|
| 547 |
await asyncio.sleep(10)
|
| 548 |
while True:
|
| 549 |
try:
|
| 550 |
+
async with aiohttp.ClientSession() as s:
|
| 551 |
+
async with s.get(SPACE_URL) as resp:
|
| 552 |
+
logger.info(f"Ping {SPACE_URL} → {resp.status}")
|
| 553 |
except Exception as e:
|
| 554 |
+
logger.error(f"Ping failed: {e}")
|
| 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()
|
|
|
|
| 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:
|
| 582 |
await app.start()
|
| 583 |
+
logger.info("Bot online – waiting for messages.")
|
| 584 |
+
break
|
| 585 |
except FloodWait as e:
|
| 586 |
+
w = e.value
|
| 587 |
+
logger.warning(f"FloodWait {w}s – waiting...")
|
| 588 |
+
await asyncio.sleep(w)
|
|
|
|
|
|
|
| 589 |
except Exception as e:
|
| 590 |
+
logger.exception(f"Start error: {e}")
|
| 591 |
+
await asyncio.sleep(30)
|
| 592 |
|
|
|
|
| 593 |
await asyncio.Event().wait()
|
| 594 |
|
| 595 |
if __name__ == "__main__":
|