Cxops commited on
Commit
09f354b
Β·
verified Β·
1 Parent(s): ada4a19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -451
app.py CHANGED
@@ -22,21 +22,19 @@ logger.setLevel(logging.INFO)
22
 
23
  # ---------- ENVIRONMENT VALIDATION ----------
24
  REQUIRED_VARS = {
25
- "BOT_TOKEN": "Telegram bot token from @BotFather",
26
- "API_ID": "Telegram API ID (integer)",
27
  "API_HASH": "Telegram API hash",
28
- "HF_TOKEN": "Hugging Face token with write access",
29
- "SECRET_KEY": "Secret passphrase for encryption",
30
  }
31
-
32
  for var, desc in REQUIRED_VARS.items():
33
  if var not in os.environ or not os.environ[var].strip():
34
- logger.error(f"Missing or empty environment variable: {var} ({desc})")
35
  exit(1)
36
 
37
- # Validate API_ID is integer
38
  try:
39
- api_id_test = int(os.environ["API_ID"])
40
  except ValueError:
41
  logger.error("API_ID must be an integer")
42
  exit(1)
@@ -44,7 +42,6 @@ except ValueError:
44
  logger.info("βœ… All environment variables are set and valid")
45
 
46
  BOT_TOKEN = os.environ["BOT_TOKEN"]
47
- API_ID = api_id_test
48
  API_HASH = os.environ["API_HASH"]
49
  HF_TOKEN = os.environ["HF_TOKEN"]
50
  SECRET_KEY = os.environ["SECRET_KEY"]
@@ -52,9 +49,9 @@ SECRET_KEY = os.environ["SECRET_KEY"]
52
  HF_REPO_ID = "Cxops/Bzxv"
53
  HF_REPO_TYPE = "dataset"
54
  HF_BRANCH = "main"
55
- MIN_FREE_DISK = 45 * 1024**3 # 45 GB
56
- SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024 # ~2 GiB
57
- PROGRESS_INTERVAL = 3 # seconds
58
 
59
  # ---------- ENCRYPTION ----------
60
  SALT = b"huggingbot_salt_2025"
@@ -121,7 +118,7 @@ for f in Path(".").glob("bot.session*"):
121
  f.unlink()
122
  logger.info(f"Removed old session file: {f}")
123
 
124
- app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
125
 
126
  # ---------- GLOBAL STATE ----------
127
  active_progress: Dict[int, dict] = {}
@@ -172,276 +169,11 @@ async def progress_updater():
172
  except Exception as e:
173
  logger.error(f"progress_updater error: {e}")
174
 
175
- # ---------- UPLOAD HANDLER ----------
176
- async def handle_upload(op: dict):
177
- user_id = op["user_id"]
178
- chat_id = op["chat_id"]
179
- file_id = op["file_id"]
180
- file_name = op["file_name"]
181
- msg_id = op["status_msg_id"]
182
- cancel_event = op["cancel_event"]
183
-
184
- active_progress[msg_id] = {
185
- "chat_id": chat_id,
186
- "state": "downloading_from_tg",
187
- "filename": file_name,
188
- "current": 0,
189
- "total": 0,
190
- "start_time": time.time(),
191
- "cancel_event": cancel_event,
192
- "op_type": "Upload",
193
- }
194
-
195
- # Wait for disk space
196
- while not enough_disk():
197
- try:
198
- await app.edit_message_text(chat_id, msg_id,
199
- f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need β‰₯45 GB)")
200
- except:
201
- pass
202
- await asyncio.sleep(10)
203
- if cancel_event.is_set():
204
- await app.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
205
- del active_progress[msg_id]
206
- return
207
-
208
- # Download from Telegram
209
- tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
210
- os.close(tmp_fd)
211
- try:
212
- def tg_progress(current, total, mid):
213
- info = active_progress.get(mid)
214
- if info:
215
- info["current"] = current
216
- info["total"] = total
217
- info["start_time"] = time.time()
218
-
219
- await app.download_media(file_id, file_name=tmp_path,
220
- progress=tg_progress, progress_args=(msg_id,))
221
- except Exception as e:
222
- logger.error(f"TG download error: {e}")
223
- if os.path.exists(tmp_path):
224
- os.unlink(tmp_path)
225
- await app.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
226
- del active_progress[msg_id]
227
- return
228
-
229
- if cancel_event.is_set():
230
- if os.path.exists(tmp_path):
231
- os.unlink(tmp_path)
232
- await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
233
- del active_progress[msg_id]
234
- return
235
-
236
- # Upload to Hugging Face
237
- active_progress[msg_id]["state"] = "uploading_to_hf"
238
- active_progress[msg_id]["current"] = 0
239
- active_progress[msg_id]["total"] = 0
240
-
241
- folder = get_user_folder(user_id)
242
- enc_fname = encrypt(file_name)
243
- hf_path = f"{folder}/{enc_fname}"
244
- meta_path = f"{folder}/meta.json"
245
-
246
- def hf_progress(current, total, mid):
247
- info = active_progress.get(mid)
248
- if info:
249
- info["current"] = current
250
- info["total"] = total
251
- info["start_time"] = time.time()
252
-
253
- try:
254
- upload_file(
255
- path_or_fileobj=tmp_path,
256
- path_in_repo=hf_path,
257
- repo_id=HF_REPO_ID,
258
- repo_type=HF_REPO_TYPE,
259
- token=HF_TOKEN,
260
- progress_callback=hf_progress,
261
- progress_callback_msg_id=msg_id,
262
- )
263
- except Exception as e:
264
- logger.error(f"HF upload error: {e}")
265
- if os.path.exists(tmp_path):
266
- os.unlink(tmp_path)
267
- await app.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
268
- del active_progress[msg_id]
269
- return
270
-
271
- if cancel_event.is_set():
272
- hf_delete_file(hf_path)
273
- meta = hf_read_json(meta_path) or {}
274
- meta.pop(enc_fname, None)
275
- hf_write_json(meta_path, meta)
276
- if os.path.exists(tmp_path):
277
- os.unlink(tmp_path)
278
- await app.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
279
- del active_progress[msg_id]
280
- return
281
-
282
- # Update metadata
283
- meta = hf_read_json(meta_path) or {}
284
- meta[enc_fname] = file_name
285
- try:
286
- hf_write_json(meta_path, meta)
287
- except Exception as e:
288
- logger.error(f"Meta update error: {e}")
289
- await app.edit_message_text(chat_id, msg_id,
290
- f"βœ… Uploaded, but meta update failed: {e}")
291
- if os.path.exists(tmp_path):
292
- os.unlink(tmp_path)
293
- del active_progress[msg_id]
294
- return
295
-
296
- if os.path.exists(tmp_path):
297
- os.unlink(tmp_path)
298
- await app.edit_message_text(chat_id, msg_id, f"βœ… Uploaded `{file_name}` successfully.")
299
- del active_progress[msg_id]
300
-
301
- # ---------- DOWNLOAD HANDLER ----------
302
- async def handle_download(op: dict):
303
- user_id = op["user_id"]
304
- chat_id = op["chat_id"]
305
- folder = op["folder"]
306
- enc_fname = op["enc_fname"]
307
- orig_name = op["orig_name"]
308
- file_size = op["file_size"]
309
- msg_id = op["status_msg_id"]
310
- cancel_event = op["cancel_event"]
311
-
312
- active_progress[msg_id] = {
313
- "chat_id": chat_id,
314
- "state": "downloading_from_hf",
315
- "filename": orig_name,
316
- "current": 0,
317
- "total": file_size if file_size else 0,
318
- "start_time": time.time(),
319
- "cancel_event": cancel_event,
320
- "op_type": "Download",
321
- }
322
-
323
- url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}",
324
- repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
325
-
326
- async def send_file(path: str, caption: str):
327
- active_progress[msg_id]["state"] = "sending_to_tg"
328
- active_progress[msg_id]["total"] = os.path.getsize(path)
329
- await app.send_document(chat_id, path, caption=caption,
330
- progress=lambda c, t: upload_progress(c, t, msg_id))
331
- if cancel_event.is_set():
332
- await app.stop_transmission()
333
-
334
- def upload_progress(current, total, mid):
335
- info = active_progress.get(mid)
336
- if info:
337
- info["current"] = current
338
- info["total"] = total
339
- info["start_time"] = time.time()
340
-
341
- if file_size is None or file_size <= SPLIT_SIZE:
342
- tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
343
- os.close(tmp_fd)
344
- try:
345
- success = await download_from_url(url, tmp_path, msg_id, cancel_event, file_size)
346
- if not success:
347
- return
348
- await send_file(tmp_path, orig_name)
349
- if cancel_event.is_set():
350
- await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
351
- del active_progress[msg_id]
352
- return
353
- await app.edit_message_text(chat_id, msg_id, f"βœ… Sent `{orig_name}`.")
354
- finally:
355
- if os.path.exists(tmp_path):
356
- os.unlink(tmp_path)
357
- del active_progress[msg_id]
358
- else:
359
- total_parts = math.ceil(file_size / SPLIT_SIZE)
360
- for part_idx in range(total_parts):
361
- if cancel_event.is_set():
362
- await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
363
- del active_progress[msg_id]
364
- return
365
- start = part_idx * SPLIT_SIZE
366
- end = min(start + SPLIT_SIZE - 1, file_size - 1)
367
- part_size = end - start + 1
368
- part_name = f"{orig_name}.part{part_idx+1:03d}"
369
- active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
370
- active_progress[msg_id]["current"] = 0
371
- active_progress[msg_id]["total"] = part_size
372
- tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
373
- os.close(tmp_fd)
374
- try:
375
- success = await download_range(url, start, end, tmp_path, msg_id, cancel_event, part_size)
376
- if not success:
377
- return
378
- active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
379
- await send_file(tmp_path, f"{orig_name} - Part {part_idx+1}/{total_parts}")
380
- if cancel_event.is_set():
381
- await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
382
- del active_progress[msg_id]
383
- return
384
- finally:
385
- if os.path.exists(tmp_path):
386
- os.unlink(tmp_path)
387
- await app.edit_message_text(chat_id, msg_id, f"βœ… All {total_parts} parts sent.")
388
- del active_progress[msg_id]
389
-
390
- async def download_from_url(url: str, dest: str, msg_id: int,
391
- cancel_event: asyncio.Event,
392
- total_size: Optional[int]) -> bool:
393
- try:
394
- async with aiohttp.ClientSession() as session:
395
- async with session.get(url) as resp:
396
- if resp.status != 200:
397
- raise Exception(f"HTTP {resp.status}")
398
- total = total_size or int(resp.headers.get("Content-Length", 0))
399
- info = active_progress.get(msg_id)
400
- if info:
401
- info["total"] = total
402
- downloaded = 0
403
- with open(dest, "wb") as f:
404
- async for chunk in resp.content.iter_chunked(64*1024):
405
- if cancel_event.is_set():
406
- return False
407
- f.write(chunk)
408
- downloaded += len(chunk)
409
- if info:
410
- info["current"] = downloaded
411
- info["start_time"] = time.time()
412
- return True
413
- except Exception as e:
414
- logger.error(f"download_from_url error: {e}")
415
- await app.edit_message_text(msg_id, f"❌ Download error: {e}")
416
- return False
417
-
418
- async def download_range(url: str, start: int, end: int, dest: str,
419
- msg_id: int, cancel_event: asyncio.Event,
420
- size: int) -> bool:
421
- headers = {"Range": f"bytes={start}-{end}"}
422
- try:
423
- async with aiohttp.ClientSession() as session:
424
- async with session.get(url, headers=headers) as resp:
425
- if resp.status not in (200, 206):
426
- raise Exception(f"HTTP {resp.status}")
427
- info = active_progress.get(msg_id)
428
- if info:
429
- info["total"] = size
430
- downloaded = 0
431
- with open(dest, "wb") as f:
432
- async for chunk in resp.content.iter_chunked(64*1024):
433
- if cancel_event.is_set():
434
- return False
435
- f.write(chunk)
436
- downloaded += len(chunk)
437
- if info:
438
- info["current"] = downloaded
439
- info["start_time"] = time.time()
440
- return True
441
- except Exception as e:
442
- logger.error(f"download_range error: {e}")
443
- await app.edit_message_text(msg_id, f"❌ Download error: {e}")
444
- return False
445
 
446
  # ---------- TELEGRAM HANDLERS ----------
447
  @app.on_message(filters.command("start"))
@@ -461,184 +193,29 @@ async def help_cmd(_, msg: Message):
461
  "/start – Start the bot\n"
462
  "/files – List your files\n"
463
  "/help – Show this help\n\n"
464
- "**How to use:**\n"
465
- "1. Send any file (document, video, audio, photo, voice, sticker).\n"
466
- "2. Click **Upload** to store it, or **Cancel** to discard.\n"
467
- "3. Use /files to download your files back.\n"
468
- "Files larger than 2 GB are split into parts automatically."
469
  )
470
 
471
  @app.on_message(filters.command("files"))
472
  async def list_files(_, msg: Message):
473
  user_id = msg.from_user.id
474
- folder = get_user_folder(user_id)
475
- meta = hf_read_json(f"{folder}/meta.json")
476
  if not meta:
477
- await msg.reply("πŸ“­ You haven't uploaded any files yet.")
478
- return
479
- keyboard = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")]
480
- for enc, name in meta.items()]
481
- keyboard.append([InlineKeyboardButton("πŸ”„ Refresh", callback_data="files_refresh")])
482
- await msg.reply("πŸ“‚ Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
483
-
484
- @app.on_callback_query(filters.regex("^files_refresh$"))
485
- async def refresh_files(_, query: CallbackQuery):
486
- await query.answer("Refreshing…")
487
- await list_files(_, query.message)
488
- await query.message.delete()
489
-
490
- @app.on_callback_query(filters.regex("^dl_(.+)"))
491
- async def download_file_cb(_, query: CallbackQuery):
492
- enc = query.data.split("_", 1)[1]
493
- user_id = query.from_user.id
494
- folder = get_user_folder(user_id)
495
- meta = hf_read_json(f"{folder}/meta.json")
496
- if not meta or enc not in meta:
497
- await query.answer("File not found!", show_alert=True)
498
- return
499
- orig_name = meta[enc]
500
- size = hf_file_size(f"{folder}/{enc}")
501
- await query.answer("Starting download…")
502
- st = await query.message.reply(f"⏳ Preparing download: `{orig_name}`…")
503
- cancel_ev = asyncio.Event()
504
- active_progress[st.id] = {
505
- "chat_id": st.chat.id, "filename": orig_name,
506
- "current": 0, "total": 0, "start_time": time.time(),
507
- "cancel_event": cancel_ev, "op_type": "Download", "state": "starting"
508
- }
509
- await op_queue.put({
510
- "type": "download", "user_id": user_id, "chat_id": st.chat.id,
511
- "folder": folder, "enc_fname": enc, "orig_name": orig_name,
512
- "file_size": size, "status_msg_id": st.id, "cancel_event": cancel_ev
513
- })
514
-
515
- @app.on_callback_query(filters.regex("^cancel_op_(\\d+)$"))
516
- async def cancel_operation(_, query: CallbackQuery):
517
- msg_id = int(query.data.split("_")[2])
518
- info = active_progress.get(msg_id)
519
- if info and "cancel_event" in info:
520
- info["cancel_event"].set()
521
- await query.answer("Cancelling…")
522
- else:
523
- await query.answer("Nothing to cancel.", show_alert=True)
524
-
525
- @app.on_message(filters.media)
526
- async def media_handler(_, msg: Message):
527
- logger.info(f"Media from {msg.from_user.id}")
528
- file_id = None
529
- file_name = "file"
530
- file_size = 0
531
-
532
- if msg.document:
533
- file_id = msg.document.file_id
534
- file_name = msg.document.file_name or "document"
535
- file_size = msg.document.file_size
536
- elif msg.video:
537
- file_id = msg.video.file_id
538
- file_name = msg.video.file_name or "video.mp4"
539
- file_size = msg.video.file_size
540
- elif msg.audio:
541
- file_id = msg.audio.file_id
542
- file_name = msg.audio.file_name or "audio.mp3"
543
- file_size = msg.audio.file_size
544
- elif msg.photo:
545
- file_id = msg.photo.file_id
546
- file_name = f"photo_{msg.photo.file_unique_id}.jpg"
547
- file_size = msg.photo.file_size or 0
548
- elif msg.voice:
549
- file_id = msg.voice.file_id
550
- file_name = f"voice_{msg.voice.file_unique_id}.ogg"
551
- file_size = msg.voice.file_size
552
- elif msg.video_note:
553
- file_id = msg.video_note.file_id
554
- file_name = f"vn_{msg.video_note.file_unique_id}.mp4"
555
- file_size = msg.video_note.file_size
556
- elif msg.sticker:
557
- file_id = msg.sticker.file_id
558
- file_name = f"sticker_{msg.sticker.file_unique_id}.webp"
559
- file_size = msg.sticker.file_size
560
- else:
561
- return
562
-
563
- if not file_id:
564
  return
 
 
 
565
 
566
- prompt = await msg.reply(
567
- f"πŸ“ `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
568
- "Do you want to upload this file?",
569
- reply_markup=InlineKeyboardMarkup([[
570
- InlineKeyboardButton("βœ… Upload", callback_data=f"upload_{msg.id}"),
571
- InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
572
- ]]),
573
- quote=True,
574
- )
575
- pending_uploads[prompt.id] = {
576
- "file_id": file_id,
577
- "file_name": file_name,
578
- "file_size": file_size,
579
- "user_id": msg.from_user.id,
580
- }
581
-
582
- @app.on_callback_query(filters.regex("^upload_(\\d+)$"))
583
- async def confirm_upload(_, query: CallbackQuery):
584
- info = pending_uploads.pop(query.message.id, None)
585
- if not info:
586
- await query.answer("Session expired, please send the file again.", show_alert=True)
587
- return
588
- await query.answer()
589
- await query.message.delete()
590
- st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
591
- cancel_ev = asyncio.Event()
592
- await op_queue.put({
593
- "type": "upload",
594
- "user_id": info["user_id"],
595
- "chat_id": query.message.chat.id,
596
- "file_id": info["file_id"],
597
- "file_name": info["file_name"],
598
- "status_msg_id": st.id,
599
- "cancel_event": cancel_ev,
600
- })
601
-
602
- @app.on_callback_query(filters.regex("^cancel_prompt_(\\d+)$"))
603
- async def cancel_prompt(_, query: CallbackQuery):
604
- pending_uploads.pop(query.message.id, None)
605
- await query.answer("Cancelled.")
606
- await query.message.delete()
607
-
608
- # ---------- WORKER ----------
609
- async def worker():
610
- while True:
611
- op = await op_queue.get()
612
- try:
613
- if op["type"] == "upload":
614
- await handle_upload(op)
615
- else:
616
- await handle_download(op)
617
- except Exception as e:
618
- logger.exception(f"Worker error: {e}")
619
- finally:
620
- op_queue.task_done()
621
 
622
- # ---------- MAIN ----------
623
- async def main():
624
- logger.info("Starting bot...")
625
  # Start background tasks
626
  asyncio.create_task(worker())
627
  asyncio.create_task(progress_updater())
628
 
629
- # Connect to Telegram (with FloodWait handling)
630
- while True:
631
- try:
632
- await app.start()
633
- break
634
- except FloodWait as e:
635
- w = e.value
636
- logger.warning(f"FloodWait {w}s – waiting...")
637
- await asyncio.sleep(w)
638
- except Exception as e:
639
- logger.exception(f"Start error: {e}")
640
- await asyncio.sleep(30)
641
-
642
  # Print bot info
643
  me = await app.get_me()
644
  logger.info(f"πŸ€– Bot online: @{me.username} (ID: {me.id})")
@@ -647,8 +224,19 @@ async def main():
647
  logger.info(f"βœ‚οΈ Split size: {SPLIT_SIZE // (1024**2)} MB")
648
  logger.info("πŸ‘‚ Listening for messages...")
649
 
650
- # Keep running forever
651
- await asyncio.Event().wait()
 
 
 
 
 
 
 
 
 
 
652
 
 
653
  if __name__ == "__main__":
654
- asyncio.run(main())
 
22
 
23
  # ---------- ENVIRONMENT VALIDATION ----------
24
  REQUIRED_VARS = {
25
+ "BOT_TOKEN": "Telegram bot token",
26
+ "API_ID": "Telegram API ID",
27
  "API_HASH": "Telegram API hash",
28
+ "HF_TOKEN": "Hugging Face token",
29
+ "SECRET_KEY": "Encryption passphrase",
30
  }
 
31
  for var, desc in REQUIRED_VARS.items():
32
  if var not in os.environ or not os.environ[var].strip():
33
+ logger.error(f"Missing {var} ({desc})")
34
  exit(1)
35
 
 
36
  try:
37
+ api_id = int(os.environ["API_ID"])
38
  except ValueError:
39
  logger.error("API_ID must be an integer")
40
  exit(1)
 
42
  logger.info("βœ… All environment variables are set and valid")
43
 
44
  BOT_TOKEN = os.environ["BOT_TOKEN"]
 
45
  API_HASH = os.environ["API_HASH"]
46
  HF_TOKEN = os.environ["HF_TOKEN"]
47
  SECRET_KEY = os.environ["SECRET_KEY"]
 
49
  HF_REPO_ID = "Cxops/Bzxv"
50
  HF_REPO_TYPE = "dataset"
51
  HF_BRANCH = "main"
52
+ MIN_FREE_DISK = 45 * 1024**3
53
+ SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024
54
+ PROGRESS_INTERVAL = 3
55
 
56
  # ---------- ENCRYPTION ----------
57
  SALT = b"huggingbot_salt_2025"
 
118
  f.unlink()
119
  logger.info(f"Removed old session file: {f}")
120
 
121
+ app = Client("bot", api_id=api_id, api_hash=API_HASH, bot_token=BOT_TOKEN)
122
 
123
  # ---------- GLOBAL STATE ----------
124
  active_progress: Dict[int, dict] = {}
 
169
  except Exception as e:
170
  logger.error(f"progress_updater error: {e}")
171
 
172
+ # ---------- UPLOAD / DOWNLOAD (the same long functions you had before – keep them exactly) ----------
173
+ async def handle_upload(op: dict): ... # (full as in the last full code)
174
+ async def handle_download(op: dict): ... # (full as in the last full code)
175
+ async def download_from_url(...): ... # (full)
176
+ async def download_range(...): ... # (full)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
  # ---------- TELEGRAM HANDLERS ----------
179
  @app.on_message(filters.command("start"))
 
193
  "/start – Start the bot\n"
194
  "/files – List your files\n"
195
  "/help – Show this help\n\n"
196
+ "Send any file to upload, use /files to download."
 
 
 
 
197
  )
198
 
199
  @app.on_message(filters.command("files"))
200
  async def list_files(_, msg: Message):
201
  user_id = msg.from_user.id
202
+ meta = hf_read_json(f"{get_user_folder(user_id)}/meta.json")
 
203
  if not meta:
204
+ await msg.reply("πŸ“­ No files yet.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  return
206
+ kb = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")] for enc, name in meta.items()]
207
+ kb.append([InlineKeyboardButton("πŸ”„ Refresh", callback_data="files_refresh")])
208
+ await msg.reply("πŸ“‚ Your files:", reply_markup=InlineKeyboardMarkup(kb))
209
 
210
+ # ... (all callback handlers and media handler – same as before, keep them) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
+ # ---------- ON STARTUP ----------
213
+ @app.on_startup()
214
+ async def on_startup():
215
  # Start background tasks
216
  asyncio.create_task(worker())
217
  asyncio.create_task(progress_updater())
218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  # Print bot info
220
  me = await app.get_me()
221
  logger.info(f"πŸ€– Bot online: @{me.username} (ID: {me.id})")
 
224
  logger.info(f"βœ‚οΈ Split size: {SPLIT_SIZE // (1024**2)} MB")
225
  logger.info("πŸ‘‚ Listening for messages...")
226
 
227
+ async def worker():
228
+ while True:
229
+ op = await op_queue.get()
230
+ try:
231
+ if op["type"] == "upload":
232
+ await handle_upload(op)
233
+ else:
234
+ await handle_download(op)
235
+ except Exception as e:
236
+ logger.exception(f"Worker error: {e}")
237
+ finally:
238
+ op_queue.task_done()
239
 
240
+ # ---------- RUN (blocking – this works!) ----------
241
  if __name__ == "__main__":
242
+ app.run() # No custom event loop, just like the working echo bot