Cxops commited on
Commit
73e6eb4
·
verified ·
1 Parent(s): 7cc78d2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +767 -0
app.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import math
5
+ import time
6
+ import base64
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
16
+ from cryptography.fernet import Fernet
17
+ from cryptography.hazmat.primitives import hashes
18
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
19
+ from cryptography.hazmat.backends import default_backend
20
+
21
+ from pyrogram import Client, filters
22
+ from pyrogram.types import (
23
+ Message,
24
+ CallbackQuery,
25
+ InlineKeyboardMarkup,
26
+ InlineKeyboardButton,
27
+ )
28
+ from pyrogram.errors import MessageNotModified
29
+ from huggingface_hub import HfApi, login, upload_file, hf_hub_url
30
+ from huggingface_hub.utils import RepositoryNotFoundError, EntryNotFoundError
31
+
32
+ # ------------------- 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"
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 -------------------
53
+ SALT = b"huggingbot_salt_2025"
54
+ kdf = PBKDF2HMAC(
55
+ algorithm=hashes.SHA256(),
56
+ length=32,
57
+ salt=SALT,
58
+ iterations=100_000,
59
+ backend=default_backend(),
60
+ )
61
+ 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
+
82
+ # ------------------- Hugging Face API -------------------
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)
90
+ except EntryNotFoundError:
91
+ return None
92
+ except Exception as e:
93
+ logger.error(f"hf_read_json error for {path}: {e}")
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,
101
+ path_in_repo=path,
102
+ repo_id=HF_REPO_ID,
103
+ repo_type=HF_REPO_TYPE,
104
+ commit_message=f"update {path}",
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
120
+ except EntryNotFoundError:
121
+ return None
122
+ except Exception as e:
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()):
152
+ try:
153
+ chat_id = info["chat_id"]
154
+ state = info["state"]
155
+ filename = info["filename"]
156
+ current = info.get("current", 0)
157
+ total = info.get("total", 0)
158
+ start_time = info.get("start_time", time.time())
159
+ cancel_event = info.get("cancel_event", None)
160
+ op_type = info.get("op_type", "")
161
+
162
+ # Calculate speed and percentage
163
+ elapsed = max(time.time() - start_time, 1)
164
+ speed = current / elapsed if current > 0 else 0
165
+ if total > 0:
166
+ percent = (current / total) * 100
167
+ progress_bar = make_progress_bar(percent)
168
+ text = (
169
+ f"**{op_type}** `{filename}`\n"
170
+ f"{progress_bar} {percent:.1f}%\n"
171
+ f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
172
+ f"⚡ {format_bytes(speed)}/s"
173
+ )
174
+ else:
175
+ text = f"**{op_type}** `{filename}`\n⏳ Processing..."
176
+
177
+ # Inline keyboard with Cancel button (only if operation can be cancelled)
178
+ keyboard = None
179
+ if state in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
180
+ keyboard = InlineKeyboardMarkup([
181
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")]
182
+ ])
183
+ # For 'uploading_to_hf' no cancel button to keep things simple.
184
+ await app_client.edit_message_text(
185
+ chat_id, msg_id, text, reply_markup=keyboard
186
+ )
187
+ except MessageNotModified:
188
+ pass
189
+ except Exception as e:
190
+ logger.error(f"Updater error for msg {msg_id}: {e}")
191
+
192
+ def make_progress_bar(percent: float, width: int = 10) -> str:
193
+ filled = int(width * percent / 100)
194
+ return "█" * filled + "░" * (width - filled)
195
+
196
+ def format_bytes(size: int) -> str:
197
+ if size == 0:
198
+ return "0 B"
199
+ units = ["B", "KB", "MB", "GB", "TB"]
200
+ i = int(math.floor(math.log(size, 1024)))
201
+ p = math.pow(1024, i)
202
+ s = round(size / p, 1)
203
+ return f"{s} {units[i]}"
204
+
205
+ # ------------------- Operation worker -------------------
206
+ async def operation_worker():
207
+ """Process one operation at a time from the queue."""
208
+ while True:
209
+ op = await op_queue.get()
210
+ try:
211
+ if op["type"] == "upload":
212
+ await handle_upload(op)
213
+ elif op["type"] == "download":
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"]
238
+ file_name = op["file_name"]
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",
246
+ "filename": file_name,
247
+ "current": 0,
248
+ "total": 0,
249
+ "start_time": time.time(),
250
+ "cancel_event": cancel_event,
251
+ "op_type": "Upload",
252
+ }
253
+
254
+ # Wait for disk space
255
+ while not enough_disk():
256
+ try:
257
+ await app_client.edit_message_text(
258
+ chat_id, msg_id,
259
+ f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)",
260
+ )
261
+ except:
262
+ pass
263
+ await asyncio.sleep(10)
264
+ if cancel_event.is_set():
265
+ await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
266
+ del active_progress[msg_id]
267
+ return
268
+
269
+ # Download file from Telegram
270
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
271
+ os.close(tmp_fd)
272
+ try:
273
+ # Progress callback for Pyrogram download
274
+ def tg_progress(current, total, msg_id):
275
+ info = active_progress.get(msg_id)
276
+ if info:
277
+ info["current"] = current
278
+ info["total"] = total
279
+ info["start_time"] = time.time() # keep updating start to get recent speed
280
+
281
+ await app_client.download_media(
282
+ file_id,
283
+ file_name=tmp_path,
284
+ progress=tg_progress,
285
+ progress_args=(msg_id,),
286
+ )
287
+ except Exception as e:
288
+ logger.error(f"Download failed: {e}")
289
+ if os.path.exists(tmp_path):
290
+ os.unlink(tmp_path)
291
+ await app_client.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
292
+ del active_progress[msg_id]
293
+ return
294
+
295
+ if cancel_event.is_set():
296
+ if os.path.exists(tmp_path):
297
+ os.unlink(tmp_path)
298
+ await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
299
+ del active_progress[msg_id]
300
+ return
301
+
302
+ # 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}")
334
+ if os.path.exists(tmp_path):
335
+ os.unlink(tmp_path)
336
+ await app_client.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
337
+ del active_progress[msg_id]
338
+ return
339
+
340
+ # 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"]
382
+ msg_id = op["status_msg_id"]
383
+ cancel_event = op["cancel_event"]
384
+
385
+ active_progress[msg_id] = {
386
+ "chat_id": chat_id,
387
+ "state": "downloading_from_hf",
388
+ "filename": orig_name,
389
+ "current": 0,
390
+ "total": file_size if file_size else 0,
391
+ "start_time": time.time(),
392
+ "cancel_event": cancel_event,
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)
432
+ await app_client.send_document(
433
+ chat_id, tmp_path,
434
+ caption=orig_name,
435
+ progress=upload_progress,
436
+ progress_args=(msg_id,),
437
+ )
438
+ # Check cancel
439
+ if cancel_event.is_set():
440
+ await app_client.stop_transmission()
441
+ await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
442
+ del active_progress[msg_id]
443
+ return
444
+ await app_client.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
445
+ finally:
446
+ if os.path.exists(tmp_path):
447
+ os.unlink(tmp_path)
448
+ del active_progress[msg_id]
449
+ else:
450
+ # Split into parts
451
+ total_parts = math.ceil(file_size / SPLIT_SIZE)
452
+ for part_idx in range(total_parts):
453
+ if cancel_event.is_set():
454
+ await app_client.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
455
+ del active_progress[msg_id]
456
+ return
457
+ start = part_idx * SPLIT_SIZE
458
+ end = min(start + SPLIT_SIZE - 1, file_size - 1)
459
+ part_size = end - start + 1
460
+ part_name = f"{orig_name}.part{part_idx+1:03d}"
461
+
462
+ # update progress for this part
463
+ active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
464
+ active_progress[msg_id]["current"] = 0
465
+ active_progress[msg_id]["total"] = part_size
466
+
467
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
468
+ os.close(tmp_fd)
469
+ try:
470
+ success = await download_range(url, start, end, tmp_path, msg_id,
471
+ cancel_event, part_size, part_name)
472
+ if not success:
473
+ return
474
+ # Upload part
475
+ active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
476
+ active_progress[msg_id]["total"] = part_size
477
+ await app_client.send_document(
478
+ chat_id, tmp_path,
479
+ caption=f"{orig_name} - Part {part_idx+1}/{total_parts}",
480
+ progress=upload_progress,
481
+ progress_args=(msg_id,),
482
+ )
483
+ if cancel_event.is_set():
484
+ await app_client.stop_transmission()
485
+ await app_client.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
486
+ del active_progress[msg_id]
487
+ return
488
+ finally:
489
+ if os.path.exists(tmp_path):
490
+ os.unlink(tmp_path)
491
+ await app_client.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
492
+ del active_progress[msg_id]
493
+
494
+ def upload_progress(current, total, msg_id):
495
+ info = active_progress.get(msg_id)
496
+ if info:
497
+ info["current"] = current
498
+ info["total"] = total
499
+ info["start_time"] = time.time()
500
+
501
+ async def download_from_url(url: str, dest: str, msg_id: int, cancel_event: asyncio.Event,
502
+ total_size: Optional[int], name: str) -> bool:
503
+ """Download a whole file with progress, returns True on success."""
504
+ try:
505
+ async with aiohttp.ClientSession() as session:
506
+ async with session.get(url) as resp:
507
+ if resp.status != 200:
508
+ raise Exception(f"HTTP {resp.status}")
509
+ total = total_size or int(resp.headers.get("Content-Length", 0))
510
+ info = active_progress.get(msg_id)
511
+ if info:
512
+ info["total"] = total
513
+ downloaded = 0
514
+ with open(dest, "wb") as f:
515
+ async for chunk in resp.content.iter_chunked(64*1024):
516
+ if cancel_event.is_set():
517
+ return False
518
+ f.write(chunk)
519
+ downloaded += len(chunk)
520
+ if info:
521
+ info["current"] = downloaded
522
+ info["start_time"] = time.time()
523
+ return True
524
+ except Exception as e:
525
+ logger.error(f"Download error: {e}")
526
+ await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
527
+ return False
528
+
529
+ async def download_range(url: str, start: int, end: int, dest: str, msg_id: int,
530
+ cancel_event: asyncio.Event, size: int, name: str) -> bool:
531
+ headers = {"Range": f"bytes={start}-{end}"}
532
+ try:
533
+ async with aiohttp.ClientSession() as session:
534
+ async with session.get(url, headers=headers) as resp:
535
+ if resp.status not in (200, 206):
536
+ raise Exception(f"HTTP {resp.status}")
537
+ total = size
538
+ info = active_progress.get(msg_id)
539
+ if info:
540
+ info["total"] = total
541
+ downloaded = 0
542
+ with open(dest, "wb") as f:
543
+ async for chunk in resp.content.iter_chunked(64*1024):
544
+ if cancel_event.is_set():
545
+ return False
546
+ f.write(chunk)
547
+ downloaded += len(chunk)
548
+ if info:
549
+ info["current"] = downloaded
550
+ info["start_time"] = time.time()
551
+ return True
552
+ except Exception as e:
553
+ logger.error(f"Range download error: {e}")
554
+ await app_client.edit_message_text(msg_id, f"❌ Download error: {e}")
555
+ return False
556
+
557
+ # ------------------- Telegram Handlers -------------------
558
+ @app_client.on_message(filters.command("start"))
559
+ async def start_cmd(client: Client, message: Message):
560
+ await message.reply(
561
+ "👋 Hello! Send me any file to upload it to the cloud.\n"
562
+ "Use /files to see your uploaded files.",
563
+ )
564
+
565
+ @app_client.on_message(filters.command("files"))
566
+ async def list_files(client: Client, message: Message):
567
+ user_id = message.from_user.id
568
+ folder = get_user_folder(user_id)
569
+ meta_path = f"{folder}/meta.json"
570
+ meta = hf_read_json(meta_path)
571
+ if not meta or len(meta) == 0:
572
+ await message.reply("📭 You haven't uploaded any files yet.")
573
+ return
574
+
575
+ # 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}")])
579
+ keyboard.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
580
+ await message.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
581
+
582
+ @app_client.on_callback_query(filters.regex(r"^files_refresh$"))
583
+ async def refresh_files(client: Client, query: CallbackQuery):
584
+ await query.answer("Refreshing…")
585
+ await list_files(client, query.message)
586
+ await query.message.delete()
587
+
588
+ @app_client.on_callback_query(filters.regex(r"^dl_(.+)"))
589
+ async def download_file_cb(client: Client, query: CallbackQuery):
590
+ enc_fname = query.data.split("_", 1)[1]
591
+ user_id = query.from_user.id
592
+ folder = get_user_folder(user_id)
593
+ meta = hf_read_json(f"{folder}/meta.json")
594
+ if not meta or enc_fname not in meta:
595
+ await query.answer("File not found!", show_alert=True)
596
+ return
597
+ orig_name = meta[enc_fname]
598
+ file_size = hf_file_size(f"{folder}/{enc_fname}")
599
+ if file_size is None:
600
+ await query.answer("Cannot read file size.", show_alert=True)
601
+ return
602
+
603
+ await query.answer("Starting download…")
604
+ # Create a progress message
605
+ status_msg = await client.send_message(
606
+ query.message.chat.id, f"⏳ Preparing download: `{orig_name}`…"
607
+ )
608
+ cancel_event = asyncio.Event()
609
+ # Add cancel button callback
610
+ active_progress[status_msg.id] = {
611
+ "chat_id": status_msg.chat.id,
612
+ "state": "starting",
613
+ "filename": orig_name,
614
+ "current": 0,
615
+ "total": 0,
616
+ "start_time": time.time(),
617
+ "cancel_event": cancel_event,
618
+ "op_type": "Download",
619
+ }
620
+ # Enqueue the operation
621
+ await op_queue.put({
622
+ "type": "download",
623
+ "user_id": user_id,
624
+ "chat_id": status_msg.chat.id,
625
+ "folder": folder,
626
+ "enc_fname": enc_fname,
627
+ "orig_name": orig_name,
628
+ "file_size": file_size,
629
+ "status_msg_id": status_msg.id,
630
+ "cancel_event": cancel_event,
631
+ })
632
+
633
+ @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:
638
+ info["cancel_event"].set()
639
+ await query.answer("Cancelling…")
640
+ else:
641
+ await query.answer("Nothing to cancel.", show_alert=True)
642
+
643
+ @app_client.on_message(filters.media & filters.private)
644
+ async def media_handler(client: Client, message: Message):
645
+ user_id = message.from_user.id
646
+ # Extract file info
647
+ if message.document:
648
+ file_id = message.document.file_id
649
+ file_name = message.document.file_name or "file"
650
+ file_size = message.document.file_size
651
+ elif message.video:
652
+ file_id = message.video.file_id
653
+ file_name = message.video.file_name or "video.mp4"
654
+ file_size = message.video.file_size
655
+ elif message.audio:
656
+ file_id = message.audio.file_id
657
+ file_name = message.audio.file_name or "audio.mp3"
658
+ file_size = message.audio.file_size
659
+ elif message.photo:
660
+ # Use largest photo
661
+ file_id = message.photo.file_id
662
+ file_name = f"photo_{message.photo.file_unique_id}.jpg"
663
+ file_size = message.photo.file_size # may be 0
664
+ else:
665
+ return
666
+
667
+ # 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?",
671
+ reply_markup=InlineKeyboardMarkup([
672
+ [InlineKeyboardButton("✅ Upload", callback_data=f"upload_{message.id}")],
673
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{message.id}")],
674
+ ]),
675
+ quote=True,
676
+ )
677
+ pending_uploads[prompt.id] = {
678
+ "file_id": file_id,
679
+ "file_name": file_name,
680
+ "file_size": file_size,
681
+ "user_id": user_id,
682
+ }
683
+
684
+ @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:
690
+ await query.answer("Session expired, please send the file again.", show_alert=True)
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"],
706
+ "chat_id": prompt_msg.chat.id,
707
+ "file_id": info["file_id"],
708
+ "file_name": info["file_name"],
709
+ "status_msg_id": status_msg.id,
710
+ "cancel_event": cancel_event,
711
+ })
712
+
713
+ @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()
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__":
764
+ try:
765
+ asyncio.run(main())
766
+ except KeyboardInterrupt:
767
+ logger.info("Bot stopped.")