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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -119
app.py CHANGED
@@ -8,8 +8,7 @@ import shutil
8
  import asyncio
9
  import logging
10
  import tempfile
11
- from pathlib import Path
12
- from typing import Dict, Optional, Tuple
13
 
14
  import aiohttp
15
  from aiohttp import web
@@ -26,8 +25,8 @@ from pyrogram.types import (
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"]
@@ -35,18 +34,22 @@ 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"
41
  HF_BRANCH = "main"
42
 
43
- MIN_FREE_DISK = 45 * 1024**3 # 45 GB
44
- SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024 # slightly under 2 GiB
45
- PROGRESS_INTERVAL = 3 # seconds
46
- KEEPALIVE_INTERVAL = 300 # 5 minutes
47
 
48
  # ------------------- Logging -------------------
49
- logging.basicConfig(level=logging.INFO)
 
 
 
50
  logger = logging.getLogger(__name__)
51
 
52
  # ------------------- Encryption -------------------
@@ -62,20 +65,16 @@ key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
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,7 +82,6 @@ def get_user_folder(user_id: int) -> str:
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,7 +92,6 @@ def hf_read_json(path: str) -> Optional[dict]:
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,7 +102,6 @@ def hf_write_json(path: str, data: dict):
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}")
@@ -113,7 +109,6 @@ def hf_delete_file(path: str):
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,29 +118,22 @@ def hf_file_size(path: str) -> Optional[int]:
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()):
@@ -159,7 +147,6 @@ async def progress_updater():
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,13 +161,12 @@ async def progress_updater():
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,7 +190,6 @@ def format_bytes(size: int) -> str:
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,7 +199,6 @@ async def operation_worker():
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:
@@ -224,14 +208,13 @@ async def operation_worker():
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,7 +222,6 @@ async def handle_upload(op: dict):
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,7 +233,6 @@ async def handle_upload(op: dict):
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,17 +247,15 @@ async def handle_upload(op: dict):
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,18 +278,15 @@ async def handle_upload(op: dict):
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:
@@ -318,7 +294,6 @@ async def handle_upload(op: dict):
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,
@@ -337,11 +312,8 @@ async def handle_upload(op: dict):
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)
@@ -351,31 +323,27 @@ async def handle_upload(op: dict):
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,39 +361,16 @@ async def handle_download(op: dict):
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(
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)
@@ -435,7 +380,6 @@ async def handle_download(op: dict):
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,7 +391,6 @@ async def handle_download(op: dict):
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():
@@ -458,12 +401,9 @@ async def handle_download(op: dict):
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:
@@ -471,7 +411,6 @@ async def handle_download(op: dict):
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(
@@ -500,7 +439,6 @@ def upload_progress(current, total, msg_id):
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:
@@ -554,16 +492,50 @@ async def download_range(url: str, start: int, end: int, dest: str, msg_id: int,
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"
@@ -572,7 +544,6 @@ async def list_files(client: Client, message: Message):
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}")])
@@ -580,13 +551,13 @@ async def list_files(client: Client, message: Message):
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)
@@ -601,12 +572,10 @@ async def download_file_cb(client: Client, query: CallbackQuery):
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,7 +586,6 @@ async def download_file_cb(client: Client, query: CallbackQuery):
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,
@@ -631,7 +599,7 @@ async def download_file_cb(client: Client, query: CallbackQuery):
631
  })
632
 
633
  @app_client.on_callback_query(filters.regex(r"^cancel_op_(\d+)$"))
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:
@@ -640,13 +608,19 @@ async def cancel_operation(client: Client, query: CallbackQuery):
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
@@ -657,14 +631,31 @@ async def media_handler(client: Client, message: Message):
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?",
@@ -682,8 +673,7 @@ async def media_handler(client: Client, message: Message):
682
  }
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,15 +681,12 @@ async def upload_confirm(client: Client, query: CallbackQuery):
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"],
@@ -711,15 +698,14 @@ async def upload_confirm(client: Client, query: CallbackQuery):
711
  })
712
 
713
  @app_client.on_callback_query(filters.regex(r"^cancel_prompt_(\d+)$"))
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()
@@ -728,16 +714,15 @@ async def keep_alive_server():
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)
@@ -746,18 +731,11 @@ async def keep_alive_server():
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__":
 
8
  import asyncio
9
  import logging
10
  import tempfile
11
+ from typing import Dict, Optional
 
12
 
13
  import aiohttp
14
  from aiohttp import web
 
25
  InlineKeyboardButton,
26
  )
27
  from pyrogram.errors import MessageNotModified
28
+ from huggingface_hub import HfApi, upload_file, hf_hub_url
29
+ from huggingface_hub.utils import EntryNotFoundError
30
 
31
  # ------------------- Configuration -------------------
32
  BOT_TOKEN = os.environ["BOT_TOKEN"]
 
34
  API_HASH = os.environ["API_HASH"]
35
  HF_TOKEN = os.environ["HF_TOKEN"]
36
  SECRET_KEY = os.environ["SECRET_KEY"]
37
+ SPACE_URL = os.environ.get("SPACE_URL", "http://localhost:7860") # <-- use public URL
38
 
39
  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*1024
45
+ PROGRESS_INTERVAL = 3
46
+ KEEPALIVE_INTERVAL = 300
47
 
48
  # ------------------- Logging -------------------
49
+ logging.basicConfig(
50
+ level=logging.INFO,
51
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
52
+ )
53
  logger = logging.getLogger(__name__)
54
 
55
  # ------------------- Encryption -------------------
 
65
  fernet = Fernet(key)
66
 
67
  def encrypt(data: str) -> str:
 
68
  token = fernet.encrypt(data.encode())
69
  return base64.urlsafe_b64encode(token).decode().rstrip("=")
70
 
71
  def decrypt(token: str) -> str:
 
 
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
  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
  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
  )
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,
107
  commit_message=f"delete {path}")
 
109
  logger.error(f"Failed to delete {path}: {e}")
110
 
111
  def hf_file_size(path: str) -> Optional[int]:
 
112
  try:
113
  info = hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
114
  return info.size
 
118
  logger.error(f"hf_file_size error for {path}: {e}")
119
  return None
120
 
 
121
  def free_disk_gb() -> float:
122
  return shutil.disk_usage("/").free / (1024**3)
123
 
124
  def enough_disk(needed: int = 0) -> bool:
 
125
  return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
126
 
127
  # ------------------- Bot initialisation -------------------
128
  app_client = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
129
 
130
  # ------------------- Global state -------------------
 
131
  active_progress: Dict[int, dict] = {}
 
132
  op_queue = asyncio.Queue()
 
 
133
  pending_uploads: Dict[int, dict] = {}
134
 
135
  # ------------------- Progress updater -------------------
136
  async def progress_updater():
 
137
  while True:
138
  await asyncio.sleep(PROGRESS_INTERVAL)
139
  for msg_id, info in list(active_progress.items()):
 
147
  cancel_event = info.get("cancel_event", None)
148
  op_type = info.get("op_type", "")
149
 
 
150
  elapsed = max(time.time() - start_time, 1)
151
  speed = current / elapsed if current > 0 else 0
152
  if total > 0:
 
161
  else:
162
  text = f"**{op_type}** `{filename}`\n⏳ Processing..."
163
 
 
164
  keyboard = None
165
  if state in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
166
  keyboard = InlineKeyboardMarkup([
167
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")]
168
  ])
169
+
170
  await app_client.edit_message_text(
171
  chat_id, msg_id, text, reply_markup=keyboard
172
  )
 
190
 
191
  # ------------------- Operation worker -------------------
192
  async def operation_worker():
 
193
  while True:
194
  op = await op_queue.get()
195
  try:
 
199
  await handle_download(op)
200
  except Exception as e:
201
  logger.exception(f"Worker error: {e}")
 
202
  msg_id = op.get("status_msg_id")
203
  chat_id = op.get("chat_id")
204
  if msg_id and chat_id:
 
208
  )
209
  except:
210
  pass
 
211
  if msg_id in active_progress:
212
  del active_progress[msg_id]
213
  finally:
214
  op_queue.task_done()
215
 
216
+ # ------------------- Upload / Download handlers (unchanged) -------------------
217
  async def handle_upload(op: dict):
 
218
  user_id = op["user_id"]
219
  chat_id = op["chat_id"]
220
  file_id = op["file_id"]
 
222
  msg_id = op["status_msg_id"]
223
  cancel_event = op["cancel_event"]
224
 
 
225
  active_progress[msg_id] = {
226
  "chat_id": chat_id,
227
  "state": "downloading_from_tg",
 
233
  "op_type": "Upload",
234
  }
235
 
 
236
  while not enough_disk():
237
  try:
238
  await app_client.edit_message_text(
 
247
  del active_progress[msg_id]
248
  return
249
 
 
250
  tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
251
  os.close(tmp_fd)
252
  try:
 
253
  def tg_progress(current, total, msg_id):
254
  info = active_progress.get(msg_id)
255
  if info:
256
  info["current"] = current
257
  info["total"] = total
258
+ info["start_time"] = time.time()
259
 
260
  await app_client.download_media(
261
  file_id,
 
278
  del active_progress[msg_id]
279
  return
280
 
 
281
  active_progress[msg_id]["state"] = "uploading_to_hf"
282
  active_progress[msg_id]["current"] = 0
283
  active_progress[msg_id]["total"] = 0
284
 
 
285
  folder = get_user_folder(user_id)
286
  enc_fname = encrypt(file_name)
287
  hf_path = f"{folder}/{enc_fname}"
288
  meta_path = f"{folder}/meta.json"
289
 
 
290
  def hf_progress(current, total, msg_id):
291
  info = active_progress.get(msg_id)
292
  if info:
 
294
  info["total"] = total
295
  info["start_time"] = time.time()
296
 
 
297
  try:
298
  upload_file(
299
  path_or_fileobj=tmp_path,
 
312
  del active_progress[msg_id]
313
  return
314
 
 
315
  if cancel_event.is_set():
 
316
  hf_delete_file(hf_path)
 
317
  meta = hf_read_json(meta_path) or {}
318
  meta.pop(enc_fname, None)
319
  hf_write_json(meta_path, meta)
 
323
  del active_progress[msg_id]
324
  return
325
 
 
326
  meta = hf_read_json(meta_path) or {}
327
  meta[enc_fname] = file_name
328
  try:
329
  hf_write_json(meta_path, meta)
330
  except Exception as e:
331
  logger.error(f"Meta upload failed: {e}")
 
332
  await app_client.edit_message_text(chat_id, msg_id, f"✅ File uploaded, but metadata update failed: {e}")
333
  if os.path.exists(tmp_path):
334
  os.unlink(tmp_path)
335
  del active_progress[msg_id]
336
  return
337
 
 
338
  if os.path.exists(tmp_path):
339
  os.unlink(tmp_path)
340
  await app_client.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
341
  del active_progress[msg_id]
342
 
343
  async def handle_download(op: dict):
 
344
  user_id = op["user_id"]
345
  chat_id = op["chat_id"]
346
+ folder = op["folder"]
347
  enc_fname = op["enc_fname"]
348
  orig_name = op["orig_name"]
349
  file_size = op["file_size"]
 
361
  "op_type": "Download",
362
  }
363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}", repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
365
 
366
  if file_size is None or file_size <= SPLIT_SIZE:
 
367
  tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
368
  os.close(tmp_fd)
369
  try:
370
  success = await download_from_url(url, tmp_path, msg_id, cancel_event,
371
  file_size, orig_name)
372
  if not success:
373
+ return
 
 
374
  active_progress[msg_id]["state"] = "sending_to_tg"
375
  active_progress[msg_id]["current"] = 0
376
  active_progress[msg_id]["total"] = os.path.getsize(tmp_path)
 
380
  progress=upload_progress,
381
  progress_args=(msg_id,),
382
  )
 
383
  if cancel_event.is_set():
384
  await app_client.stop_transmission()
385
  await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
 
391
  os.unlink(tmp_path)
392
  del active_progress[msg_id]
393
  else:
 
394
  total_parts = math.ceil(file_size / SPLIT_SIZE)
395
  for part_idx in range(total_parts):
396
  if cancel_event.is_set():
 
401
  end = min(start + SPLIT_SIZE - 1, file_size - 1)
402
  part_size = end - start + 1
403
  part_name = f"{orig_name}.part{part_idx+1:03d}"
 
 
404
  active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
405
  active_progress[msg_id]["current"] = 0
406
  active_progress[msg_id]["total"] = part_size
 
407
  tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
408
  os.close(tmp_fd)
409
  try:
 
411
  cancel_event, part_size, part_name)
412
  if not success:
413
  return
 
414
  active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
415
  active_progress[msg_id]["total"] = part_size
416
  await app_client.send_document(
 
439
 
440
  async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyncio.Event,
441
  total_size: Optional[int], name: str) -> bool:
 
442
  try:
443
  async with aiohttp.ClientSession() as session:
444
  async with session.get(url) as resp:
 
492
  await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
493
  return False
494
 
495
+ # ===================== TELEGRAM HANDLERS =====================
496
+
497
+ # 1. Catch‑all debug handler (logs EVERY message)
498
+ @app_client.on_message()
499
+ async def debug_log_all(client, message: Message):
500
+ logger.info(f"RECEIVED MESSAGE from {message.from_user.id}: {message.text or message.caption or '<no text>'} | chat id: {message.chat.id}")
501
+
502
+ # 2. Basic /ping command for connectivity test
503
+ @app_client.on_message(filters.command("ping"))
504
+ async def ping_cmd(client, message: Message):
505
+ logger.info(f"/ping from {message.from_user.id}")
506
+ await message.reply("🏓 Pong!")
507
+
508
+ # 3. /start command
509
  @app_client.on_message(filters.command("start"))
510
+ async def start_cmd(client, message: Message):
511
+ logger.info(f"/start from {message.from_user.id}")
512
+ await message.reply(
513
+ "👋 **Welcome to Cloud Storage Bot!**\n\n"
514
+ "📤 Send any file to upload it.\n"
515
+ "📂 Use /files to see your uploaded files.\n"
516
+ "ℹ️ /help for more info.\n"
517
+ "🏓 /ping to test."
518
+ )
519
+
520
+ # 4. /help command
521
+ @app_client.on_message(filters.command("help"))
522
+ async def help_cmd(client, message: Message):
523
  await message.reply(
524
+ "**Commands:**\n"
525
+ "/start - Start the bot\n"
526
+ "/files - List your files\n"
527
+ "/help - Show this help\n"
528
+ "/ping - Test bot connectivity\n\n"
529
+ "**How to use:**\n"
530
+ "1. Send any file (document, video, audio, photo, voice, sticker…).\n"
531
+ "2. Click **Upload** to store it, or **Cancel** to discard.\n"
532
+ "3. Use /files to browse and download your files back.\n\n"
533
+ "Files > 2GB are split automatically."
534
  )
535
 
536
+ # 5. /files command
537
  @app_client.on_message(filters.command("files"))
538
+ async def list_files(client, message: Message):
539
  user_id = message.from_user.id
540
  folder = get_user_folder(user_id)
541
  meta_path = f"{folder}/meta.json"
 
544
  await message.reply("📭 You haven't uploaded any files yet.")
545
  return
546
 
 
547
  keyboard = []
548
  for enc_name, orig_name in meta.items():
549
  keyboard.append([InlineKeyboardButton(orig_name, callback_data=f"dl_{enc_name}")])
 
551
  await message.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
552
 
553
  @app_client.on_callback_query(filters.regex(r"^files_refresh$"))
554
+ async def refresh_files(client, query: CallbackQuery):
555
  await query.answer("Refreshing…")
556
  await list_files(client, query.message)
557
  await query.message.delete()
558
 
559
  @app_client.on_callback_query(filters.regex(r"^dl_(.+)"))
560
+ async def download_file_cb(client, query: CallbackQuery):
561
  enc_fname = query.data.split("_", 1)[1]
562
  user_id = query.from_user.id
563
  folder = get_user_folder(user_id)
 
572
  return
573
 
574
  await query.answer("Starting download…")
 
575
  status_msg = await client.send_message(
576
  query.message.chat.id, f"⏳ Preparing download: `{orig_name}`…"
577
  )
578
  cancel_event = asyncio.Event()
 
579
  active_progress[status_msg.id] = {
580
  "chat_id": status_msg.chat.id,
581
  "state": "starting",
 
586
  "cancel_event": cancel_event,
587
  "op_type": "Download",
588
  }
 
589
  await op_queue.put({
590
  "type": "download",
591
  "user_id": user_id,
 
599
  })
600
 
601
  @app_client.on_callback_query(filters.regex(r"^cancel_op_(\d+)$"))
602
+ async def cancel_operation(client, query: CallbackQuery):
603
  msg_id = int(query.data.split("_")[2])
604
  info = active_progress.get(msg_id)
605
  if info and "cancel_event" in info:
 
608
  else:
609
  await query.answer("Nothing to cancel.", show_alert=True)
610
 
611
+ # ===================== MEDIA HANDLER (no private filter, for testing) =====================
612
+ @app_client.on_message(filters.media)
613
+ async def media_handler(client, message: Message):
614
  user_id = message.from_user.id
615
+ logger.info(f"Media from {user_id}, type={message.media}")
616
+
617
+ file_id = None
618
+ file_name = "file"
619
+ file_size = 0
620
+
621
  if message.document:
622
  file_id = message.document.file_id
623
+ file_name = message.document.file_name or "document"
624
  file_size = message.document.file_size
625
  elif message.video:
626
  file_id = message.video.file_id
 
631
  file_name = message.audio.file_name or "audio.mp3"
632
  file_size = message.audio.file_size
633
  elif message.photo:
 
634
  file_id = message.photo.file_id
635
  file_name = f"photo_{message.photo.file_unique_id}.jpg"
636
+ file_size = message.photo.file_size or 0
637
+ elif message.voice:
638
+ file_id = message.voice.file_id
639
+ file_name = f"voice_{message.voice.file_unique_id}.ogg"
640
+ file_size = message.voice.file_size
641
+ elif message.video_note:
642
+ file_id = message.video_note.file_id
643
+ file_name = f"video_note_{message.video_note.file_unique_id}.mp4"
644
+ file_size = message.video_note.file_size
645
+ elif message.sticker:
646
+ file_id = message.sticker.file_id
647
+ file_name = f"sticker_{message.sticker.file_unique_id}.webp"
648
+ file_size = message.sticker.file_size
649
  else:
650
+ file_id = getattr(message, message.media.value, None)
651
+ if file_id:
652
+ file_name = f"media_{message.id}"
653
+ file_size = 0
654
+
655
+ if not file_id:
656
+ await message.reply("❌ Could not extract file.")
657
  return
658
 
 
659
  prompt = await message.reply(
660
  f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
661
  "Do you want to upload this file?",
 
673
  }
674
 
675
  @app_client.on_callback_query(filters.regex(r"^upload_(\d+)$"))
676
+ async def upload_confirm(client, query: CallbackQuery):
 
677
  prompt_msg = query.message
678
  info = pending_uploads.pop(prompt_msg.id, None)
679
  if not info:
 
681
  return
682
 
683
  await query.answer()
 
684
  await prompt_msg.delete()
685
 
 
686
  status_msg = await client.send_message(
687
  prompt_msg.chat.id, f"⏳ Preparing upload: `{info['file_name']}`…"
688
  )
689
  cancel_event = asyncio.Event()
 
690
  await op_queue.put({
691
  "type": "upload",
692
  "user_id": info["user_id"],
 
698
  })
699
 
700
  @app_client.on_callback_query(filters.regex(r"^cancel_prompt_(\d+)$"))
701
+ async def cancel_prompt(client, query: CallbackQuery):
702
  prompt_msg = query.message
703
  pending_uploads.pop(prompt_msg.id, None)
704
  await query.answer("Cancelled.")
705
  await prompt_msg.delete()
706
 
707
+ # ------------------- Keep‑alive (pings SPACE_URL) -------------------
708
  async def keep_alive_server():
 
709
  async def handle(request):
710
  return web.Response(text="Bot is alive")
711
  app = web.Application()
 
714
  await runner.setup()
715
  site = web.TCPSite(runner, "0.0.0.0", 7860)
716
  await site.start()
717
+ logger.info(f"Keep‑alive server started on port 7860, external pings will go to {SPACE_URL}")
718
 
 
719
  async def self_ping():
720
+ await asyncio.sleep(10)
721
  while True:
722
  try:
723
  async with aiohttp.ClientSession() as session:
724
+ async with session.get(SPACE_URL) as resp:
725
+ logger.info(f"Self‑ping {SPACE_URL}: {resp.status}")
726
  except Exception as e:
727
  logger.error(f"Self‑ping failed: {e}")
728
  await asyncio.sleep(KEEPALIVE_INTERVAL)
 
731
 
732
  # ------------------- Main -------------------
733
  async def main():
 
734
  await keep_alive_server()
 
 
735
  await app_client.start()
736
+ logger.info("Bot started, waiting for messages...")
 
 
737
  asyncio.create_task(operation_worker())
738
  asyncio.create_task(progress_updater())
 
 
739
  await asyncio.Event().wait()
740
 
741
  if __name__ == "__main__":