Cxops commited on
Commit
fe2e76e
·
verified ·
1 Parent(s): 47294fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +659 -12
app.py CHANGED
@@ -1,22 +1,669 @@
1
- import os
2
- import logging
 
 
 
 
 
 
 
3
  from pyrogram import Client, filters
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # Suppress Pyrogram’s own spammy logs
6
- logging.basicConfig(level=logging.WARNING)
7
- log = logging.getLogger(__name__)
 
 
 
8
 
9
  BOT_TOKEN = os.environ["BOT_TOKEN"]
10
  API_ID = int(os.environ["API_ID"])
11
  API_HASH = os.environ["API_HASH"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- app = Client("echo_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
 
14
 
15
- @app.on_message()
16
- async def echo(client, msg):
17
- log.warning(f"Message from {msg.from_user.id}: {msg.text}")
18
- await msg.reply(f"Echo: {msg.text}")
19
 
20
  if __name__ == "__main__":
21
- log.warning("Starting echo bot...")
22
- app.run()
 
1
+ import os, json, math, time, base64, shutil, asyncio, logging, tempfile
2
+ from typing import Dict, Optional
3
+
4
+ import aiohttp
5
+ from aiohttp import web
6
+ from cryptography.fernet import Fernet
7
+ from cryptography.hazmat.primitives import hashes
8
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
9
+ from cryptography.hazmat.backends import default_backend
10
  from pyrogram import Client, filters
11
+ from pyrogram.types import (
12
+ Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
13
+ )
14
+ from pyrogram.errors import MessageNotModified
15
+ from huggingface_hub import HfApi, upload_file, hf_hub_url
16
+ from huggingface_hub.utils import EntryNotFoundError
17
+
18
+ # ---------- LOGGING (clean, only our messages) ----------
19
+ logging.basicConfig(level=logging.WARNING, format="%(asctime)s [%(levelname)s] %(message)s")
20
+ logger = logging.getLogger("bot")
21
+ logger.setLevel(logging.INFO)
22
 
23
+ # ---------- CONFIGURATION ----------
24
+ REQUIRED_ENV = ["BOT_TOKEN", "API_ID", "API_HASH", "HF_TOKEN", "SECRET_KEY"]
25
+ for var in REQUIRED_ENV:
26
+ if var not in os.environ:
27
+ logger.error(f"Missing environment variable: {var}")
28
+ exit(1)
29
 
30
  BOT_TOKEN = os.environ["BOT_TOKEN"]
31
  API_ID = int(os.environ["API_ID"])
32
  API_HASH = os.environ["API_HASH"]
33
+ HF_TOKEN = os.environ["HF_TOKEN"]
34
+ SECRET_KEY = os.environ["SECRET_KEY"]
35
+
36
+ # Your Hugging Face Space public URL (no secret needed)
37
+ SPACE_URL = "https://cxops-push.hf.space"
38
+
39
+ HF_REPO_ID = "Cxops/Bzxv"
40
+ HF_REPO_TYPE = "dataset"
41
+ HF_BRANCH = "main"
42
+ MIN_FREE_DISK = 45 * 1024**3 # 45 GB
43
+ SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024 # just under 2 GiB
44
+ PROGRESS_INTERVAL = 3 # seconds
45
+ KEEPALIVE_INTERVAL = 300 # 5 minutes
46
+
47
+ # ---------- ENCRYPTION ----------
48
+ SALT = b"huggingbot_salt_2025"
49
+ kdf = PBKDF2HMAC(
50
+ algorithm=hashes.SHA256(), length=32, salt=SALT,
51
+ iterations=100_000, backend=default_backend()
52
+ )
53
+ key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
54
+ fernet = Fernet(key)
55
+
56
+ def encrypt(data: str) -> str:
57
+ return base64.urlsafe_b64encode(fernet.encrypt(data.encode())).decode().rstrip("=")
58
+
59
+ def decrypt(token: str) -> str:
60
+ pad = 4 - len(token) % 4
61
+ if pad != 4:
62
+ token += "=" * pad
63
+ return fernet.decrypt(base64.urlsafe_b64decode(token)).decode()
64
+
65
+ def get_user_folder(user_id: int) -> str:
66
+ return encrypt(str(user_id))
67
+
68
+ # ---------- HUGGING FACE API ----------
69
+ hf_api = HfApi(token=HF_TOKEN)
70
+
71
+ def hf_read_json(path: str) -> Optional[dict]:
72
+ try:
73
+ return json.loads(hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH))
74
+ except EntryNotFoundError:
75
+ return None
76
+ except Exception as e:
77
+ logger.error(f"hf_read_json error: {e}")
78
+ return None
79
+
80
+ def hf_write_json(path: str, data: dict):
81
+ hf_api.upload_file(
82
+ path_or_fileobj=json.dumps(data, indent=2).encode(),
83
+ path_in_repo=path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
84
+ commit_message=f"update {path}"
85
+ )
86
+
87
+ def hf_delete_file(path: str):
88
+ try:
89
+ hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
90
+ commit_message=f"delete {path}")
91
+ except Exception as e:
92
+ logger.error(f"hf_delete_file error: {e}")
93
+
94
+ def hf_file_size(path: str) -> Optional[int]:
95
+ try:
96
+ return hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE).size
97
+ except EntryNotFoundError:
98
+ return None
99
+ except Exception as e:
100
+ logger.error(f"hf_file_size error: {e}")
101
+ return None
102
+
103
+ def free_disk_gb() -> float:
104
+ return shutil.disk_usage("/").free / (1024**3)
105
+
106
+ def enough_disk(needed: int = 0) -> bool:
107
+ return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
108
+
109
+ # ---------- BOT CLIENT ----------
110
+ app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
111
+
112
+ # ---------- GLOBAL STATE ----------
113
+ active_progress: Dict[int, dict] = {}
114
+ op_queue = asyncio.Queue()
115
+ pending_uploads: Dict[int, dict] = {}
116
+
117
+ # ---------- HELPER FUNCTIONS ----------
118
+ def make_progress_bar(percent: float, width: int = 10) -> str:
119
+ filled = int(width * percent / 100)
120
+ return "█" * filled + "░" * (width - filled)
121
+
122
+ def format_bytes(size: int) -> str:
123
+ if size == 0:
124
+ return "0 B"
125
+ units = ["B", "KB", "MB", "GB", "TB"]
126
+ i = int(math.floor(math.log(size, 1024)))
127
+ return f"{round(size / (1024**i), 1)} {units[i]}"
128
+
129
+ async def progress_updater():
130
+ """Updates active progress messages every PROGRESS_INTERVAL seconds."""
131
+ while True:
132
+ await asyncio.sleep(PROGRESS_INTERVAL)
133
+ for msg_id, info in list(active_progress.items()):
134
+ try:
135
+ chat_id = info["chat_id"]
136
+ filename = info["filename"]
137
+ current = info.get("current", 0)
138
+ total = info.get("total", 0)
139
+ start_time = info.get("start_time", time.time())
140
+ op_type = info.get("op_type", "")
141
+ elapsed = max(time.time() - start_time, 1)
142
+ speed = current / elapsed if current > 0 else 0
143
+
144
+ if total > 0:
145
+ percent = (current / total) * 100
146
+ text = (
147
+ f"**{op_type}** `{filename}`\n"
148
+ f"{make_progress_bar(percent)} {percent:.1f}%\n"
149
+ f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
150
+ f"⚡ {format_bytes(speed)}/s"
151
+ )
152
+ else:
153
+ text = f"**{op_type}** `{filename}`\n⏳ Processing..."
154
+
155
+ keyboard = None
156
+ if info["state"] in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
157
+ keyboard = InlineKeyboardMarkup([[
158
+ InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")
159
+ ]])
160
+
161
+ await app.edit_message_text(chat_id, msg_id, text, reply_markup=keyboard)
162
+ except MessageNotModified:
163
+ pass
164
+ except Exception as e:
165
+ logger.error(f"progress_updater error: {e}")
166
+
167
+ # ---------- UPLOAD / DOWNLOAD HANDLERS ----------
168
+
169
+ async def handle_upload(op: dict):
170
+ user_id = op["user_id"]
171
+ chat_id = op["chat_id"]
172
+ file_id = op["file_id"]
173
+ file_name = op["file_name"]
174
+ msg_id = op["status_msg_id"]
175
+ cancel_event = op["cancel_event"]
176
+
177
+ active_progress[msg_id] = {
178
+ "chat_id": chat_id,
179
+ "state": "downloading_from_tg",
180
+ "filename": file_name,
181
+ "current": 0,
182
+ "total": 0,
183
+ "start_time": time.time(),
184
+ "cancel_event": cancel_event,
185
+ "op_type": "Upload",
186
+ }
187
+
188
+ # Wait for disk space
189
+ while not enough_disk():
190
+ try:
191
+ await app.edit_message_text(
192
+ chat_id, msg_id,
193
+ f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)",
194
+ )
195
+ except:
196
+ pass
197
+ await asyncio.sleep(10)
198
+ if cancel_event.is_set():
199
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
200
+ del active_progress[msg_id]
201
+ return
202
+
203
+ # Download from Telegram
204
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
205
+ os.close(tmp_fd)
206
+ try:
207
+ def tg_progress(current, total, msg_id):
208
+ info = active_progress.get(msg_id)
209
+ if info:
210
+ info["current"] = current
211
+ info["total"] = total
212
+ info["start_time"] = time.time()
213
+
214
+ await app.download_media(file_id, file_name=tmp_path,
215
+ progress=tg_progress, progress_args=(msg_id,))
216
+ except Exception as e:
217
+ logger.error(f"TG download error: {e}")
218
+ if os.path.exists(tmp_path):
219
+ os.unlink(tmp_path)
220
+ await app.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
221
+ del active_progress[msg_id]
222
+ return
223
+
224
+ if cancel_event.is_set():
225
+ if os.path.exists(tmp_path):
226
+ os.unlink(tmp_path)
227
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
228
+ del active_progress[msg_id]
229
+ return
230
+
231
+ # Upload to Hugging Face
232
+ active_progress[msg_id]["state"] = "uploading_to_hf"
233
+ active_progress[msg_id]["current"] = 0
234
+ active_progress[msg_id]["total"] = 0
235
+
236
+ folder = get_user_folder(user_id)
237
+ enc_fname = encrypt(file_name)
238
+ hf_path = f"{folder}/{enc_fname}"
239
+ meta_path = f"{folder}/meta.json"
240
+
241
+ def hf_progress(current, total, msg_id):
242
+ info = active_progress.get(msg_id)
243
+ if info:
244
+ info["current"] = current
245
+ info["total"] = total
246
+ info["start_time"] = time.time()
247
+
248
+ try:
249
+ upload_file(
250
+ path_or_fileobj=tmp_path,
251
+ path_in_repo=hf_path,
252
+ repo_id=HF_REPO_ID,
253
+ repo_type=HF_REPO_TYPE,
254
+ token=HF_TOKEN,
255
+ progress_callback=hf_progress,
256
+ progress_callback_msg_id=msg_id,
257
+ )
258
+ except Exception as e:
259
+ logger.error(f"HF upload error: {e}")
260
+ if os.path.exists(tmp_path):
261
+ os.unlink(tmp_path)
262
+ await app.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
263
+ del active_progress[msg_id]
264
+ return
265
+
266
+ if cancel_event.is_set():
267
+ hf_delete_file(hf_path)
268
+ meta = hf_read_json(meta_path) or {}
269
+ meta.pop(enc_fname, None)
270
+ hf_write_json(meta_path, meta)
271
+ if os.path.exists(tmp_path):
272
+ os.unlink(tmp_path)
273
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
274
+ del active_progress[msg_id]
275
+ return
276
+
277
+ # Update metadata
278
+ meta = hf_read_json(meta_path) or {}
279
+ meta[enc_fname] = file_name
280
+ try:
281
+ hf_write_json(meta_path, meta)
282
+ except Exception as e:
283
+ logger.error(f"Meta update error: {e}")
284
+ await app.edit_message_text(chat_id, msg_id,
285
+ f"✅ Uploaded, but meta update failed: {e}")
286
+ if os.path.exists(tmp_path):
287
+ os.unlink(tmp_path)
288
+ del active_progress[msg_id]
289
+ return
290
+
291
+ if os.path.exists(tmp_path):
292
+ os.unlink(tmp_path)
293
+ await app.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
294
+ del active_progress[msg_id]
295
+
296
+ async def handle_download(op: dict):
297
+ user_id = op["user_id"]
298
+ chat_id = op["chat_id"]
299
+ folder = op["folder"]
300
+ enc_fname = op["enc_fname"]
301
+ orig_name = op["orig_name"]
302
+ file_size = op["file_size"]
303
+ msg_id = op["status_msg_id"]
304
+ cancel_event = op["cancel_event"]
305
+
306
+ active_progress[msg_id] = {
307
+ "chat_id": chat_id,
308
+ "state": "downloading_from_hf",
309
+ "filename": orig_name,
310
+ "current": 0,
311
+ "total": file_size if file_size else 0,
312
+ "start_time": time.time(),
313
+ "cancel_event": cancel_event,
314
+ "op_type": "Download",
315
+ }
316
+
317
+ url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}",
318
+ repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
319
+
320
+ # Helper to send a file from disk with progress
321
+ async def send_file(path: str, caption: str):
322
+ active_progress[msg_id]["state"] = "sending_to_tg"
323
+ active_progress[msg_id]["total"] = os.path.getsize(path)
324
+ await app.send_document(
325
+ chat_id, path, caption=caption,
326
+ progress=lambda c, t: upload_progress(c, t, msg_id)
327
+ )
328
+ if cancel_event.is_set():
329
+ await app.stop_transmission()
330
+
331
+ def upload_progress(current, total, msg_id):
332
+ info = active_progress.get(msg_id)
333
+ if info:
334
+ info["current"] = current
335
+ info["total"] = total
336
+ info["start_time"] = time.time()
337
+
338
+ if file_size is None or file_size <= SPLIT_SIZE:
339
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
340
+ os.close(tmp_fd)
341
+ try:
342
+ success = await download_from_url(url, tmp_path, msg_id, cancel_event, file_size)
343
+ if not success:
344
+ return
345
+ await send_file(tmp_path, orig_name)
346
+ if cancel_event.is_set():
347
+ await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
348
+ del active_progress[msg_id]
349
+ return
350
+ await app.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
351
+ finally:
352
+ if os.path.exists(tmp_path):
353
+ os.unlink(tmp_path)
354
+ del active_progress[msg_id]
355
+ else:
356
+ total_parts = math.ceil(file_size / SPLIT_SIZE)
357
+ for part_idx in range(total_parts):
358
+ if cancel_event.is_set():
359
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
360
+ del active_progress[msg_id]
361
+ return
362
+ start = part_idx * SPLIT_SIZE
363
+ end = min(start + SPLIT_SIZE - 1, file_size - 1)
364
+ part_size = end - start + 1
365
+ part_name = f"{orig_name}.part{part_idx+1:03d}"
366
+ active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
367
+ active_progress[msg_id]["current"] = 0
368
+ active_progress[msg_id]["total"] = part_size
369
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
370
+ os.close(tmp_fd)
371
+ try:
372
+ success = await download_range(url, start, end, tmp_path,
373
+ msg_id, cancel_event, part_size)
374
+ if not success:
375
+ return
376
+ active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
377
+ await send_file(tmp_path, f"{orig_name} - Part {part_idx+1}/{total_parts}")
378
+ if cancel_event.is_set():
379
+ await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
380
+ del active_progress[msg_id]
381
+ return
382
+ finally:
383
+ if os.path.exists(tmp_path):
384
+ os.unlink(tmp_path)
385
+ await app.edit_message_text(chat_id, msg_id,
386
+ f"✅ All {total_parts} parts sent.")
387
+ del active_progress[msg_id]
388
+
389
+ async def download_from_url(url: str, dest: str, msg_id: int,
390
+ cancel_event: asyncio.Event,
391
+ total_size: Optional[int]) -> bool:
392
+ try:
393
+ async with aiohttp.ClientSession() as session:
394
+ async with session.get(url) as resp:
395
+ if resp.status != 200:
396
+ raise Exception(f"HTTP {resp.status}")
397
+ total = total_size or int(resp.headers.get("Content-Length", 0))
398
+ info = active_progress.get(msg_id)
399
+ if info:
400
+ info["total"] = total
401
+ downloaded = 0
402
+ with open(dest, "wb") as f:
403
+ async for chunk in resp.content.iter_chunked(64*1024):
404
+ if cancel_event.is_set():
405
+ return False
406
+ f.write(chunk)
407
+ downloaded += len(chunk)
408
+ if info:
409
+ info["current"] = downloaded
410
+ info["start_time"] = time.time()
411
+ return True
412
+ except Exception as e:
413
+ logger.error(f"download_from_url error: {e}")
414
+ await app.edit_message_text(msg_id, f"❌ Download error: {e}")
415
+ return False
416
+
417
+ async def download_range(url: str, start: int, end: int, dest: str,
418
+ msg_id: int, cancel_event: asyncio.Event,
419
+ size: int) -> bool:
420
+ headers = {"Range": f"bytes={start}-{end}"}
421
+ try:
422
+ async with aiohttp.ClientSession() as session:
423
+ async with session.get(url, headers=headers) as resp:
424
+ if resp.status not in (200, 206):
425
+ raise Exception(f"HTTP {resp.status}")
426
+ info = active_progress.get(msg_id)
427
+ if info:
428
+ info["total"] = size
429
+ downloaded = 0
430
+ with open(dest, "wb") as f:
431
+ async for chunk in resp.content.iter_chunked(64*1024):
432
+ if cancel_event.is_set():
433
+ return False
434
+ f.write(chunk)
435
+ downloaded += len(chunk)
436
+ if info:
437
+ info["current"] = downloaded
438
+ info["start_time"] = time.time()
439
+ return True
440
+ except Exception as e:
441
+ logger.error(f"download_range error: {e}")
442
+ await app.edit_message_text(msg_id, f"❌ Download error: {e}")
443
+ return False
444
+
445
+ # ---------- TELEGRAM COMMAND HANDLERS ----------
446
+
447
+ @app.on_message(filters.command("start"))
448
+ async def start_cmd(_, msg: Message):
449
+ logger.info(f"/start from {msg.from_user.id}")
450
+ await msg.reply(
451
+ "👋 **Welcome to Cloud Storage Bot!**\n\n"
452
+ "Send any file to upload it to the cloud.\n"
453
+ "Use /files to see your uploaded files.\n"
454
+ "Help: /help"
455
+ )
456
+
457
+ @app.on_message(filters.command("help"))
458
+ async def help_cmd(_, msg: Message):
459
+ await msg.reply(
460
+ "**Commands:**\n"
461
+ "/start – Start the bot\n"
462
+ "/files – List your files\n"
463
+ "/help – Show this help\n\n"
464
+ "**How to use:**\n"
465
+ "1. Send any file (document, video, audio, photo, voice, sticker).\n"
466
+ "2. Click **Upload** to store it, or **Cancel** to discard.\n"
467
+ "3. Use /files to download your files back.\n"
468
+ "Files larger than 2 GB are split into parts automatically."
469
+ )
470
+
471
+ @app.on_message(filters.command("files"))
472
+ async def list_files(_, msg: Message):
473
+ user_id = msg.from_user.id
474
+ folder = get_user_folder(user_id)
475
+ meta = hf_read_json(f"{folder}/meta.json")
476
+ if not meta:
477
+ await msg.reply("📭 You haven't uploaded any files yet.")
478
+ return
479
+
480
+ keyboard = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")]
481
+ for enc, name in meta.items()]
482
+ keyboard.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
483
+ await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(keyboard))
484
+
485
+ @app.on_callback_query(filters.regex(r"^files_refresh$"))
486
+ async def refresh_files(_, query: CallbackQuery):
487
+ await query.answer("Refreshing…")
488
+ await list_files(_, query.message)
489
+ await query.message.delete()
490
+
491
+ @app.on_callback_query(filters.regex(r"^dl_(.+)"))
492
+ async def download_file_cb(_, query: CallbackQuery):
493
+ enc = query.data.split("_", 1)[1]
494
+ user_id = query.from_user.id
495
+ folder = get_user_folder(user_id)
496
+ meta = hf_read_json(f"{folder}/meta.json")
497
+ if not meta or enc not in meta:
498
+ await query.answer("File not found!", show_alert=True)
499
+ return
500
+ orig_name = meta[enc]
501
+ size = hf_file_size(f"{folder}/{enc}")
502
+ await query.answer("Starting download…")
503
+ st = await query.message.reply(f"⏳ Preparing download: `{orig_name}`…")
504
+ cancel_ev = asyncio.Event()
505
+ active_progress[st.id] = {
506
+ "chat_id": st.chat.id, "filename": orig_name,
507
+ "current": 0, "total": 0, "start_time": time.time(),
508
+ "cancel_event": cancel_ev, "op_type": "Download", "state": "starting"
509
+ }
510
+ await op_queue.put({
511
+ "type": "download", "user_id": user_id, "chat_id": st.chat.id,
512
+ "folder": folder, "enc_fname": enc, "orig_name": orig_name,
513
+ "file_size": size, "status_msg_id": st.id, "cancel_event": cancel_ev
514
+ })
515
+
516
+ @app.on_callback_query(filters.regex(r"^cancel_op_(\d+)$"))
517
+ async def cancel_operation(_, query: CallbackQuery):
518
+ msg_id = int(query.data.split("_")[2])
519
+ info = active_progress.get(msg_id)
520
+ if info and "cancel_event" in info:
521
+ info["cancel_event"].set()
522
+ await query.answer("Cancelling…")
523
+ else:
524
+ await query.answer("Nothing to cancel.", show_alert=True)
525
+
526
+ # ---------- MEDIA HANDLER ----------
527
+
528
+ @app.on_message(filters.media)
529
+ async def media_handler(_, msg: Message):
530
+ logger.info(f"Media from {msg.from_user.id}")
531
+ file_id = None
532
+ file_name = "file"
533
+ file_size = 0
534
+
535
+ if msg.document:
536
+ file_id = msg.document.file_id
537
+ file_name = msg.document.file_name or "document"
538
+ file_size = msg.document.file_size
539
+ elif msg.video:
540
+ file_id = msg.video.file_id
541
+ file_name = msg.video.file_name or "video.mp4"
542
+ file_size = msg.video.file_size
543
+ elif msg.audio:
544
+ file_id = msg.audio.file_id
545
+ file_name = msg.audio.file_name or "audio.mp3"
546
+ file_size = msg.audio.file_size
547
+ elif msg.photo:
548
+ file_id = msg.photo.file_id
549
+ file_name = f"photo_{msg.photo.file_unique_id}.jpg"
550
+ file_size = msg.photo.file_size or 0
551
+ elif msg.voice:
552
+ file_id = msg.voice.file_id
553
+ file_name = f"voice_{msg.voice.file_unique_id}.ogg"
554
+ file_size = msg.voice.file_size
555
+ elif msg.video_note:
556
+ file_id = msg.video_note.file_id
557
+ file_name = f"vn_{msg.video_note.file_unique_id}.mp4"
558
+ file_size = msg.video_note.file_size
559
+ elif msg.sticker:
560
+ file_id = msg.sticker.file_id
561
+ file_name = f"sticker_{msg.sticker.file_unique_id}.webp"
562
+ file_size = msg.sticker.file_size
563
+ else:
564
+ return
565
+
566
+ if not file_id:
567
+ return
568
+
569
+ prompt = await msg.reply(
570
+ f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
571
+ "Do you want to upload this file?",
572
+ reply_markup=InlineKeyboardMarkup([[
573
+ InlineKeyboardButton("✅ Upload", callback_data=f"upload_{msg.id}"),
574
+ InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
575
+ ]]),
576
+ quote=True,
577
+ )
578
+ pending_uploads[prompt.id] = {
579
+ "file_id": file_id,
580
+ "file_name": file_name,
581
+ "file_size": file_size,
582
+ "user_id": msg.from_user.id,
583
+ }
584
+
585
+ @app.on_callback_query(filters.regex(r"^upload_(\d+)$"))
586
+ async def confirm_upload(_, query: CallbackQuery):
587
+ info = pending_uploads.pop(query.message.id, None)
588
+ if not info:
589
+ await query.answer("Session expired, please send the file again.", show_alert=True)
590
+ return
591
+ await query.answer()
592
+ await query.message.delete()
593
+ st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
594
+ cancel_ev = asyncio.Event()
595
+ await op_queue.put({
596
+ "type": "upload",
597
+ "user_id": info["user_id"],
598
+ "chat_id": query.message.chat.id,
599
+ "file_id": info["file_id"],
600
+ "file_name": info["file_name"],
601
+ "status_msg_id": st.id,
602
+ "cancel_event": cancel_ev,
603
+ })
604
+
605
+ @app.on_callback_query(filters.regex(r"^cancel_prompt_(\d+)$"))
606
+ async def cancel_prompt(_, query: CallbackQuery):
607
+ pending_uploads.pop(query.message.id, None)
608
+ await query.answer("Cancelled.")
609
+ await query.message.delete()
610
+
611
+ # ---------- KEEP‑ALIVE SERVER ----------
612
+ async def keep_alive():
613
+ async def handler(request):
614
+ return web.Response(text="Alive")
615
+ web_app = web.Application()
616
+ web_app.router.add_get("/", handler)
617
+ runner = web.AppRunner(web_app)
618
+ await runner.setup()
619
+ await web.TCPSite(runner, "0.0.0.0", 7860).start()
620
+ logger.info(f"Keep‑alive server started on port 7860 (pings {SPACE_URL})")
621
+
622
+ async def pinger():
623
+ await asyncio.sleep(10)
624
+ while True:
625
+ try:
626
+ async with aiohttp.ClientSession() as session:
627
+ async with session.get(SPACE_URL) as resp:
628
+ logger.info(f"Self‑ping {SPACE_URL} → {resp.status}")
629
+ except Exception as e:
630
+ logger.error(f"Self‑ping failed: {e}")
631
+ await asyncio.sleep(KEEPALIVE_INTERVAL)
632
+
633
+ asyncio.create_task(pinger())
634
+
635
+ # ---------- OPERATION WORKER ----------
636
+ async def worker():
637
+ while True:
638
+ op = await op_queue.get()
639
+ try:
640
+ if op["type"] == "upload":
641
+ await handle_upload(op)
642
+ else:
643
+ await handle_download(op)
644
+ except Exception as e:
645
+ logger.exception(f"Worker error: {e}")
646
+ finally:
647
+ op_queue.task_done()
648
+
649
+ # ---------- MAIN ----------
650
+ async def main():
651
+ # Verify all variables are set
652
+ logger.info("Environment check: all required variables present.")
653
+ logger.info(f"HF repo: {HF_REPO_ID}")
654
+ logger.info(f"Space URL: {SPACE_URL}")
655
+ logger.info(f"Disk limit: {MIN_FREE_DISK // (1024**3)} GB free required")
656
+ logger.info(f"Split size: {SPLIT_SIZE // (1024**2)} MB")
657
+
658
+ await keep_alive()
659
+ await app.start()
660
+ logger.info("Bot started – listening for messages...")
661
 
662
+ asyncio.create_task(worker())
663
+ asyncio.create_task(progress_updater())
664
 
665
+ # Keep running forever
666
+ await asyncio.Event().wait()
 
 
667
 
668
  if __name__ == "__main__":
669
+ asyncio.run(main())