Cxops commited on
Commit
15e94d2
·
verified ·
1 Parent(s): 954c1aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -61
app.py CHANGED
@@ -26,16 +26,15 @@ from pyrogram.types import (
26
  InlineKeyboardButton,
27
  )
28
  from pyrogram.errors import MessageNotModified
29
- from huggingface_hub import HfApi, upload_file, hf_hub_url
30
  from huggingface_hub.utils import RepositoryNotFoundError, EntryNotFoundError
31
 
32
  # ------------------- Configuration -------------------
33
- # Using .get() to prevent hard crashes if auth/API keys are missing
34
- BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
35
- API_ID = int(os.environ.get("API_ID", 0) or 0)
36
- API_HASH = os.environ.get("API_HASH", "")
37
- HF_TOKEN = os.environ.get("HF_TOKEN")
38
- SECRET_KEY = os.environ.get("SECRET_KEY", "default_secret_key_for_testing")
39
 
40
  HF_REPO_ID = "Cxops/Bzxv"
41
  HF_REPO_TYPE = "dataset"
@@ -63,18 +62,20 @@ key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
63
  fernet = Fernet(key)
64
 
65
  def encrypt(data: str) -> str:
66
- """Encrypt string to URL-safe base64."""
67
  token = fernet.encrypt(data.encode())
68
  return base64.urlsafe_b64encode(token).decode().rstrip("=")
69
 
70
  def decrypt(token: str) -> str:
71
- """Decrypt URL-safe base64 token back to string."""
 
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
  def get_user_folder(user_id: int) -> str:
79
  return encrypt(str(user_id))
80
 
@@ -82,6 +83,7 @@ def get_user_folder(user_id: int) -> str:
82
  hf_api = HfApi(token=HF_TOKEN)
83
 
84
  def hf_read_json(path: str) -> Optional[dict]:
 
85
  try:
86
  content = hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
87
  return json.loads(content)
@@ -92,6 +94,7 @@ def hf_read_json(path: str) -> Optional[dict]:
92
  return None
93
 
94
  def hf_write_json(path: str, data: dict):
 
95
  content = json.dumps(data, indent=2).encode("utf-8")
96
  hf_api.upload_file(
97
  path_or_fileobj=content,
@@ -102,12 +105,15 @@ def hf_write_json(path: str, data: dict):
102
  )
103
 
104
  def hf_delete_file(path: str):
 
105
  try:
106
- hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, commit_message=f"delete {path}")
 
107
  except Exception as e:
108
  logger.error(f"Failed to delete {path}: {e}")
109
 
110
  def hf_file_size(path: str) -> Optional[int]:
 
111
  try:
112
  info = hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
113
  return info.size
@@ -117,36 +123,29 @@ def hf_file_size(path: str) -> Optional[int]:
117
  logger.error(f"hf_file_size error for {path}: {e}")
118
  return None
119
 
120
- # Async wrappers for blocking IO bounds
121
- async def async_hf_read_json(path: str) -> Optional[dict]:
122
- return await asyncio.to_thread(hf_read_json, path)
123
-
124
- async def async_hf_write_json(path: str, data: dict):
125
- await asyncio.to_thread(hf_write_json, path, data)
126
-
127
- async def async_hf_delete_file(path: str):
128
- await asyncio.to_thread(hf_delete_file, path)
129
-
130
- async def async_hf_file_size(path: str) -> Optional[int]:
131
- return await asyncio.to_thread(hf_file_size, path)
132
-
133
  # ------------------- Disk space -------------------
134
  def free_disk_gb() -> float:
135
  return shutil.disk_usage("/").free / (1024**3)
136
 
137
  def enough_disk(needed: int = 0) -> bool:
 
138
  return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
139
 
140
  # ------------------- Bot initialisation -------------------
141
  app_client = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
142
 
143
  # ------------------- Global state -------------------
 
144
  active_progress: Dict[int, dict] = {}
 
145
  op_queue = asyncio.Queue()
 
 
146
  pending_uploads: Dict[int, dict] = {}
147
 
148
  # ------------------- Progress updater -------------------
149
  async def progress_updater():
 
150
  while True:
151
  await asyncio.sleep(PROGRESS_INTERVAL)
152
  for msg_id, info in list(active_progress.items()):
@@ -157,8 +156,10 @@ async def progress_updater():
157
  current = info.get("current", 0)
158
  total = info.get("total", 0)
159
  start_time = info.get("start_time", time.time())
 
160
  op_type = info.get("op_type", "")
161
 
 
162
  elapsed = max(time.time() - start_time, 1)
163
  speed = current / elapsed if current > 0 else 0
164
  if total > 0:
@@ -173,12 +174,13 @@ async def progress_updater():
173
  else:
174
  text = f"**{op_type}** `{filename}`\n⏳ Processing..."
175
 
 
176
  keyboard = None
177
  if state in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
178
  keyboard = InlineKeyboardMarkup([
179
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")]
180
  ])
181
-
182
  await app_client.edit_message_text(
183
  chat_id, msg_id, text, reply_markup=keyboard
184
  )
@@ -202,6 +204,7 @@ def format_bytes(size: int) -> str:
202
 
203
  # ------------------- Operation worker -------------------
204
  async def operation_worker():
 
205
  while True:
206
  op = await op_queue.get()
207
  try:
@@ -211,26 +214,24 @@ async def operation_worker():
211
  await handle_download(op)
212
  except Exception as e:
213
  logger.exception(f"Worker error: {e}")
 
214
  msg_id = op.get("status_msg_id")
215
  chat_id = op.get("chat_id")
216
  if msg_id and chat_id:
217
  try:
218
- await app_client.edit_message_text(chat_id, msg_id, f"❌ Error: {e}")
 
 
219
  except:
220
  pass
 
221
  if msg_id in active_progress:
222
  del active_progress[msg_id]
223
  finally:
224
  op_queue.task_done()
225
 
226
- async def upload_progress(current, total, msg_id):
227
- info = active_progress.get(msg_id)
228
- if info:
229
- info["current"] = current
230
- info["total"] = total
231
- info["start_time"] = time.time()
232
-
233
  async def handle_upload(op: dict):
 
234
  user_id = op["user_id"]
235
  chat_id = op["chat_id"]
236
  file_id = op["file_id"]
@@ -238,6 +239,7 @@ async def handle_upload(op: dict):
238
  msg_id = op["status_msg_id"]
239
  cancel_event = op["cancel_event"]
240
 
 
241
  active_progress[msg_id] = {
242
  "chat_id": chat_id,
243
  "state": "downloading_from_tg",
@@ -249,6 +251,7 @@ async def handle_upload(op: dict):
249
  "op_type": "Upload",
250
  }
251
 
 
252
  while not enough_disk():
253
  try:
254
  await app_client.edit_message_text(
@@ -263,15 +266,17 @@ async def handle_upload(op: dict):
263
  del active_progress[msg_id]
264
  return
265
 
 
266
  tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
267
  os.close(tmp_fd)
268
  try:
269
- async def tg_progress(current, total, msg_id):
 
270
  info = active_progress.get(msg_id)
271
  if info:
272
  info["current"] = current
273
  info["total"] = total
274
- info["start_time"] = time.time()
275
 
276
  await app_client.download_media(
277
  file_id,
@@ -294,23 +299,35 @@ async def handle_upload(op: dict):
294
  del active_progress[msg_id]
295
  return
296
 
 
297
  active_progress[msg_id]["state"] = "uploading_to_hf"
298
  active_progress[msg_id]["current"] = 0
299
  active_progress[msg_id]["total"] = 0
300
 
 
301
  folder = get_user_folder(user_id)
302
  enc_fname = encrypt(file_name)
303
  hf_path = f"{folder}/{enc_fname}"
304
  meta_path = f"{folder}/meta.json"
305
 
 
 
 
 
 
 
 
 
 
306
  try:
307
- await asyncio.to_thread(
308
- upload_file,
309
  path_or_fileobj=tmp_path,
310
  path_in_repo=hf_path,
311
  repo_id=HF_REPO_ID,
312
  repo_type=HF_REPO_TYPE,
313
  token=HF_TOKEN,
 
 
314
  )
315
  except Exception as e:
316
  logger.error(f"HF upload failed: {e}")
@@ -320,38 +337,45 @@ async def handle_upload(op: dict):
320
  del active_progress[msg_id]
321
  return
322
 
 
323
  if cancel_event.is_set():
324
- await async_hf_delete_file(hf_path)
325
- meta = await async_hf_read_json(meta_path) or {}
 
 
326
  meta.pop(enc_fname, None)
327
- await async_hf_write_json(meta_path, meta)
328
  if os.path.exists(tmp_path):
329
  os.unlink(tmp_path)
330
  await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
331
  del active_progress[msg_id]
332
  return
333
 
334
- meta = await async_hf_read_json(meta_path) or {}
 
335
  meta[enc_fname] = file_name
336
  try:
337
- await async_hf_write_json(meta_path, meta)
338
  except Exception as e:
339
  logger.error(f"Meta upload failed: {e}")
 
340
  await app_client.edit_message_text(chat_id, msg_id, f"✅ File uploaded, but metadata update failed: {e}")
341
  if os.path.exists(tmp_path):
342
  os.unlink(tmp_path)
343
  del active_progress[msg_id]
344
  return
345
 
 
346
  if os.path.exists(tmp_path):
347
  os.unlink(tmp_path)
348
  await app_client.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
349
  del active_progress[msg_id]
350
 
351
  async def handle_download(op: dict):
 
352
  user_id = op["user_id"]
353
  chat_id = op["chat_id"]
354
- folder = op["folder"]
355
  enc_fname = op["enc_fname"]
356
  orig_name = op["orig_name"]
357
  file_size = op["file_size"]
@@ -369,11 +393,12 @@ async def handle_download(op: dict):
369
  "op_type": "Download",
370
  }
371
 
 
372
  if file_size and file_size > SPLIT_SIZE:
 
373
  needed = SPLIT_SIZE
374
  else:
375
  needed = file_size or 0
376
-
377
  while not enough_disk(needed):
378
  try:
379
  await app_client.edit_message_text(
@@ -391,13 +416,16 @@ async def handle_download(op: dict):
391
  url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}", repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
392
 
393
  if file_size is None or file_size <= SPLIT_SIZE:
 
394
  tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
395
  os.close(tmp_fd)
396
  try:
397
- success = await download_from_url(url, tmp_path, msg_id, cancel_event, file_size, orig_name)
 
398
  if not success:
399
- return
400
 
 
401
  active_progress[msg_id]["state"] = "sending_to_tg"
402
  active_progress[msg_id]["current"] = 0
403
  active_progress[msg_id]["total"] = os.path.getsize(tmp_path)
@@ -407,6 +435,7 @@ async def handle_download(op: dict):
407
  progress=upload_progress,
408
  progress_args=(msg_id,),
409
  )
 
410
  if cancel_event.is_set():
411
  await app_client.stop_transmission()
412
  await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
@@ -418,18 +447,19 @@ async def handle_download(op: dict):
418
  os.unlink(tmp_path)
419
  del active_progress[msg_id]
420
  else:
 
421
  total_parts = math.ceil(file_size / SPLIT_SIZE)
422
  for part_idx in range(total_parts):
423
  if cancel_event.is_set():
424
  await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
425
  del active_progress[msg_id]
426
  return
427
-
428
  start = part_idx * SPLIT_SIZE
429
  end = min(start + SPLIT_SIZE - 1, file_size - 1)
430
  part_size = end - start + 1
431
  part_name = f"{orig_name}.part{part_idx+1:03d}"
432
 
 
433
  active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
434
  active_progress[msg_id]["current"] = 0
435
  active_progress[msg_id]["total"] = part_size
@@ -437,10 +467,11 @@ async def handle_download(op: dict):
437
  tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
438
  os.close(tmp_fd)
439
  try:
440
- success = await download_range(url, start, end, tmp_path, msg_id, cancel_event, part_size, part_name)
 
441
  if not success:
442
  return
443
-
444
  active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
445
  active_progress[msg_id]["total"] = part_size
446
  await app_client.send_document(
@@ -460,7 +491,16 @@ async def handle_download(op: dict):
460
  await app_client.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
461
  del active_progress[msg_id]
462
 
463
- async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyncio.Event, total_size: Optional[int], name: str) -> bool:
 
 
 
 
 
 
 
 
 
464
  try:
465
  async with aiohttp.ClientSession() as session:
466
  async with session.get(url) as resp:
@@ -486,7 +526,8 @@ async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyn
486
  await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
487
  return False
488
 
489
- async def download_range(url: str, start: int, end: int, dest: str, msg_id: int, cancel_event: asyncio.Event, size: int, name: str) -> bool:
 
490
  headers = {"Range": f"bytes={start}-{end}"}
491
  try:
492
  async with aiohttp.ClientSession() as session:
@@ -526,11 +567,12 @@ async def list_files(client: Client, message: Message):
526
  user_id = message.from_user.id
527
  folder = get_user_folder(user_id)
528
  meta_path = f"{folder}/meta.json"
529
- meta = await async_hf_read_json(meta_path)
530
  if not meta or len(meta) == 0:
531
  await message.reply("📭 You haven't uploaded any files yet.")
532
  return
533
 
 
534
  keyboard = []
535
  for enc_name, orig_name in meta.items():
536
  keyboard.append([InlineKeyboardButton(orig_name, callback_data=f"dl_{enc_name}")])
@@ -548,22 +590,23 @@ async def download_file_cb(client: Client, query: CallbackQuery):
548
  enc_fname = query.data.split("_", 1)[1]
549
  user_id = query.from_user.id
550
  folder = get_user_folder(user_id)
551
- meta = await async_hf_read_json(f"{folder}/meta.json")
552
  if not meta or enc_fname not in meta:
553
  await query.answer("File not found!", show_alert=True)
554
  return
555
-
556
  orig_name = meta[enc_fname]
557
- file_size = await async_hf_file_size(f"{folder}/{enc_fname}")
558
  if file_size is None:
559
  await query.answer("Cannot read file size.", show_alert=True)
560
  return
561
 
562
  await query.answer("Starting download…")
 
563
  status_msg = await client.send_message(
564
  query.message.chat.id, f"⏳ Preparing download: `{orig_name}`…"
565
  )
566
  cancel_event = asyncio.Event()
 
567
  active_progress[status_msg.id] = {
568
  "chat_id": status_msg.chat.id,
569
  "state": "starting",
@@ -574,6 +617,7 @@ async def download_file_cb(client: Client, query: CallbackQuery):
574
  "cancel_event": cancel_event,
575
  "op_type": "Download",
576
  }
 
577
  await op_queue.put({
578
  "type": "download",
579
  "user_id": user_id,
@@ -599,6 +643,7 @@ async def cancel_operation(client: Client, query: CallbackQuery):
599
  @app_client.on_message(filters.media & filters.private)
600
  async def media_handler(client: Client, message: Message):
601
  user_id = message.from_user.id
 
602
  if message.document:
603
  file_id = message.document.file_id
604
  file_name = message.document.file_name or "file"
@@ -612,12 +657,14 @@ async def media_handler(client: Client, message: Message):
612
  file_name = message.audio.file_name or "audio.mp3"
613
  file_size = message.audio.file_size
614
  elif message.photo:
 
615
  file_id = message.photo.file_id
616
  file_name = f"photo_{message.photo.file_unique_id}.jpg"
617
- file_size = message.photo.file_size
618
  else:
619
  return
620
 
 
621
  prompt = await message.reply(
622
  f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
623
  "Do you want to upload this file?",
@@ -636,6 +683,7 @@ async def media_handler(client: Client, message: Message):
636
 
637
  @app_client.on_callback_query(filters.regex(r"^upload_(\d+)$"))
638
  async def upload_confirm(client: Client, query: CallbackQuery):
 
639
  prompt_msg = query.message
640
  info = pending_uploads.pop(prompt_msg.id, None)
641
  if not info:
@@ -643,13 +691,15 @@ async def upload_confirm(client: Client, query: CallbackQuery):
643
  return
644
 
645
  await query.answer()
 
646
  await prompt_msg.delete()
647
 
 
648
  status_msg = await client.send_message(
649
  prompt_msg.chat.id, f"⏳ Preparing upload: `{info['file_name']}`…"
650
  )
651
  cancel_event = asyncio.Event()
652
-
653
  await op_queue.put({
654
  "type": "upload",
655
  "user_id": info["user_id"],
@@ -669,39 +719,45 @@ async def cancel_prompt(client: Client, query: CallbackQuery):
669
 
670
  # ------------------- Keep-alive HTTP server -------------------
671
  async def keep_alive_server():
 
672
  async def handle(request):
673
  return web.Response(text="Bot is alive")
674
-
675
  app = web.Application()
676
  app.router.add_get("/", handle)
677
  runner = web.AppRunner(app)
678
  await runner.setup()
679
  site = web.TCPSite(runner, "0.0.0.0", 7860)
680
  await site.start()
681
- logger.info("Keep-alive server started on port 7860")
682
 
 
683
  async def self_ping():
684
- await asyncio.sleep(10)
685
  while True:
686
  try:
687
  async with aiohttp.ClientSession() as session:
688
  async with session.get("http://localhost:7860/") as resp:
689
- logger.info(f"Self-ping: {resp.status}")
690
  except Exception as e:
691
- logger.error(f"Self-ping failed: {e}")
692
  await asyncio.sleep(KEEPALIVE_INTERVAL)
693
 
694
  asyncio.create_task(self_ping())
695
 
696
  # ------------------- Main -------------------
697
  async def main():
 
698
  await keep_alive_server()
 
 
699
  await app_client.start()
700
  logger.info("Bot started")
701
 
 
702
  asyncio.create_task(operation_worker())
703
  asyncio.create_task(progress_updater())
704
 
 
705
  await asyncio.Event().wait()
706
 
707
  if __name__ == "__main__":
 
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
  # ------------------- Configuration -------------------
33
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
34
+ API_ID = int(os.environ["API_ID"])
35
+ API_HASH = os.environ["API_HASH"]
36
+ HF_TOKEN = os.environ["HF_TOKEN"]
37
+ SECRET_KEY = os.environ["SECRET_KEY"]
 
38
 
39
  HF_REPO_ID = "Cxops/Bzxv"
40
  HF_REPO_TYPE = "dataset"
 
62
  fernet = Fernet(key)
63
 
64
  def encrypt(data: str) -> str:
65
+ """Encrypt string to URL‑safe base64."""
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
 
 
83
  hf_api = HfApi(token=HF_TOKEN)
84
 
85
  def hf_read_json(path: str) -> Optional[dict]:
86
+ """Read and parse a JSON file from the HF repo."""
87
  try:
88
  content = hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
89
  return json.loads(content)
 
94
  return None
95
 
96
  def hf_write_json(path: str, data: dict):
97
+ """Write JSON data to the HF repo (creates/overwrites the file)."""
98
  content = json.dumps(data, indent=2).encode("utf-8")
99
  hf_api.upload_file(
100
  path_or_fileobj=content,
 
105
  )
106
 
107
  def hf_delete_file(path: str):
108
+ """Delete a file from the HF repo."""
109
  try:
110
+ hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
111
+ commit_message=f"delete {path}")
112
  except Exception as e:
113
  logger.error(f"Failed to delete {path}: {e}")
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.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
119
  return info.size
 
123
  logger.error(f"hf_file_size error for {path}: {e}")
124
  return None
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  # ------------------- Disk space -------------------
127
  def free_disk_gb() -> float:
128
  return shutil.disk_usage("/").free / (1024**3)
129
 
130
  def enough_disk(needed: int = 0) -> bool:
131
+ """Check if after allocating `needed` bytes, free space still >= 45 GB."""
132
  return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
133
 
134
  # ------------------- Bot initialisation -------------------
135
  app_client = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
136
 
137
  # ------------------- Global state -------------------
138
+ # active_progress stores info about ongoing operations per message_id
139
  active_progress: Dict[int, dict] = {}
140
+ # Queue for operations (serialised worker)
141
  op_queue = asyncio.Queue()
142
+
143
+ # Temporary storage for pending uploads: message_id -> file details
144
  pending_uploads: Dict[int, dict] = {}
145
 
146
  # ------------------- Progress updater -------------------
147
  async def progress_updater():
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()):
 
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:
 
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
  )
 
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 op_queue.get()
210
  try:
 
214
  await handle_download(op)
215
  except Exception as e:
216
  logger.exception(f"Worker error: {e}")
217
+ # Notify user via message if possible
218
  msg_id = op.get("status_msg_id")
219
  chat_id = op.get("chat_id")
220
  if msg_id and chat_id:
221
  try:
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"]
 
239
  msg_id = op["status_msg_id"]
240
  cancel_event = op["cancel_event"]
241
 
242
+ # Initialise progress
243
  active_progress[msg_id] = {
244
  "chat_id": chat_id,
245
  "state": "downloading_from_tg",
 
251
  "op_type": "Upload",
252
  }
253
 
254
+ # Wait for disk space
255
  while not enough_disk():
256
  try:
257
  await app_client.edit_message_text(
 
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,
 
299
  del active_progress[msg_id]
300
  return
301
 
302
+ # Update progress state: uploading to HF (no cancel button)
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}")
 
337
  del active_progress[msg_id]
338
  return
339
 
340
+ # If cancelled after upload (unlikely, but just in case)
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
+ # Update metadata
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
+ # Cleanup
369
  if os.path.exists(tmp_path):
370
  os.unlink(tmp_path)
371
  await app_client.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
372
  del active_progress[msg_id]
373
 
374
  async def handle_download(op: dict):
375
+ """Process a file download from HF and send to Telegram."""
376
  user_id = op["user_id"]
377
  chat_id = op["chat_id"]
378
+ folder = op["folder"] # already encrypted
379
  enc_fname = op["enc_fname"]
380
  orig_name = op["orig_name"]
381
  file_size = op["file_size"]
 
393
  "op_type": "Download",
394
  }
395
 
396
+ # Wait for disk (if file is small and we need space for temp parts)
397
  if file_size and file_size > SPLIT_SIZE:
398
+ # For split mode we only need temp space for one part
399
  needed = SPLIT_SIZE
400
  else:
401
  needed = file_size or 0
 
402
  while not enough_disk(needed):
403
  try:
404
  await app_client.edit_message_text(
 
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)
 
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.")
 
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
 
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(
 
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:
 
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:
 
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
+ # Build inline keyboard (max 10 per page? simple: all in one message)
576
  keyboard = []
577
  for enc_name, orig_name in meta.items():
578
  keyboard.append([InlineKeyboardButton(orig_name, callback_data=f"dl_{enc_name}")])
 
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",
 
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,
 
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"
 
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
+ # Store pending upload details
668
  prompt = await message.reply(
669
  f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
670
  "Do you want to upload this file?",
 
683
 
684
  @app_client.on_callback_query(filters.regex(r"^upload_(\d+)$"))
685
  async def upload_confirm(client: Client, query: CallbackQuery):
686
+ original_msg_id = int(query.data.split("_")[1])
687
  prompt_msg = query.message
688
  info = pending_uploads.pop(prompt_msg.id, None)
689
  if not info:
 
691
  return
692
 
693
  await query.answer()
694
+ # Delete the prompt message
695
  await prompt_msg.delete()
696
 
697
+ # Create new progress message
698
  status_msg = await client.send_message(
699
  prompt_msg.chat.id, f"⏳ Preparing upload: `{info['file_name']}`…"
700
  )
701
  cancel_event = asyncio.Event()
702
+ # Enqueue
703
  await op_queue.put({
704
  "type": "upload",
705
  "user_id": info["user_id"],
 
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
+ # Start bot
753
  await app_client.start()
754
  logger.info("Bot started")
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__":