Cxops commited on
Commit
b8ce7d6
·
verified ·
1 Parent(s): bf0265d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +616 -194
app.py CHANGED
@@ -1,221 +1,643 @@
1
- import os
2
- import asyncio
3
- import hashlib
4
- import shutil
5
- import logging
6
- import aiohttp
7
-
8
- from fastapi import FastAPI
9
- import uvicorn
10
-
11
- from pyrogram import Client, filters, idle
12
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
13
- from huggingface_hub import HfApi
14
-
15
- # ================= LOGGING =================
16
-
17
- logging.basicConfig(level=logging.INFO)
18
- log = logging.getLogger("bot")
19
-
20
- # ================= CONFIG =================
21
-
22
- BOT_TOKEN = os.getenv("BOT_TOKEN")
23
- API_ID = int(os.getenv("API_ID"))
24
- API_HASH = os.getenv("API_HASH")
25
- HF_TOKEN = os.getenv("HF_TOKEN")
26
-
27
- DATASET_REPO = "Cxops/Bzxv"
28
- SPACE_URL = "https://cxops-push.hf.space"
29
-
30
- BASE_DIR = "/data/files"
31
- os.makedirs(BASE_DIR, exist_ok=True)
32
-
33
- DISK_LIMIT_GB = 45
34
 
35
- # ================= FASTAPI (7860) =================
36
-
37
- web = FastAPI()
38
-
39
- @web.get("/")
40
- def home():
41
- return {"status": "running"}
42
-
43
- @web.get("/health")
44
- def health():
45
- free = shutil.disk_usage("/data").free
46
- return {"free_gb": round(free / (1024**3), 2)}
47
-
48
- # ================= BOT =================
49
-
50
- app = Client(
51
- "hf_bot",
52
- api_id=API_ID,
53
- api_hash=API_HASH,
54
- bot_token=BOT_TOKEN
55
  )
56
-
57
- hf = HfApi(token=HF_TOKEN)
58
-
59
- # ================= UTIL =================
60
-
61
- def hash_id(x: str):
62
- return hashlib.sha256(x.encode()).hexdigest()[:16]
63
-
64
- def folder(uid, uname):
65
- return hash_id(f"{uid}:{uname}")
66
-
67
- def user_dir(f):
68
- path = os.path.join(BASE_DIR, f)
69
- os.makedirs(path, exist_ok=True)
70
- return path
71
-
72
- def disk_ok():
73
- free = shutil.disk_usage("/data").free
74
- return free > (DISK_LIMIT_GB * 1024**3)
75
-
76
- # ================= KEEPALIVE =================
77
-
78
- async def keepalive():
79
- while True:
80
- try:
81
- async with aiohttp.ClientSession() as s:
82
- await s.get(SPACE_URL)
83
- except Exception as e:
84
- log.warning(f"keepalive error: {e}")
85
- await asyncio.sleep(300)
86
-
87
- # ================= HF UPLOAD =================
88
-
89
- async def upload_hf(local, remote):
90
- loop = asyncio.get_event_loop()
91
- await loop.run_in_executor(
92
- None,
93
- lambda: hf.upload_file(
94
- path_or_fileobj=local,
95
- path_in_repo=remote,
96
- repo_id=DATASET_REPO,
97
- repo_type="dataset"
98
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  )
100
 
101
- # ================= QUEUE =================
102
-
103
- queue = asyncio.Queue()
104
-
105
- async def worker():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  while True:
107
- job = await queue.get()
108
-
109
- msg = job["msg"]
110
- file_id = job["file_id"]
111
- folder_name = job["folder"]
112
- fake = job["fake"]
113
-
114
- if not disk_ok():
115
- await msg.reply("❌ Disk full. Try later.")
116
- continue
117
-
118
- status = await msg.reply("⬇ Downloading...")
119
-
120
- path = await app.download_media(
121
- file_id,
122
- file_name=os.path.join(user_dir(folder_name), fake)
123
- )
124
-
125
- await status.edit("☁ Uploading to HuggingFace...")
126
-
127
- await upload_hf(path, f"{folder_name}/{fake}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
 
129
  try:
130
- os.remove(path)
 
131
  except:
132
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- await status.edit("✅ Done")
135
-
136
- # ================= HANDLERS (FIXED ORDER) =================
 
 
 
137
 
138
- pending = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- # 🔥 IMPORTANT: START FIRST (private only)
141
- @app.on_message(filters.private & filters.command("start"))
142
- async def start(_, msg):
143
- log.info("START RECEIVED")
144
- await msg.reply("👋 Bot is working. Send files to store them.")
 
 
 
 
 
145
 
146
- # 🔥 FILE HANDLER (private only)
147
- @app.on_message(filters.private & (filters.document | filters.video | filters.audio))
148
- async def receive(_, msg):
149
- user = msg.from_user
150
- if not user:
 
 
 
 
 
 
151
  return
152
 
153
- f = folder(user.id, user.username or str(user.id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- file_id = (
156
- msg.document.file_id if msg.document else
157
- msg.video.file_id if msg.video else
158
- msg.audio.file_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  )
160
 
161
- fake = hash_id(file_id)
 
 
 
 
 
 
 
 
162
 
163
- pending[user.id] = {
164
- "file_id": file_id,
165
- "folder": f,
166
- "fake": fake,
167
- "msg": msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- kb = InlineKeyboardMarkup([
171
- [
172
- InlineKeyboardButton("⬆ Upload", callback_data="up"),
173
- InlineKeyboardButton("❌ Cancel", callback_data="no")
174
- ]
175
- ])
176
-
177
- await msg.reply("File received. Upload?", reply_markup=kb)
178
-
179
- # 🔥 CALLBACKS
180
- @app.on_callback_query()
181
- async def cb(_, q):
182
- uid = q.from_user.id
183
-
184
- if q.data == "no":
185
- pending.pop(uid, None)
186
- return await q.message.edit("Cancelled")
187
-
188
- if q.data == "up":
189
- if uid in pending:
190
- await queue.put(pending[uid])
191
- pending.pop(uid)
192
- await q.message.edit("Queued ✔")
193
-
194
- # ================= STARTUP =================
195
-
196
- async def run_web():
197
- config = uvicorn.Config(web, host="0.0.0.0", port=7860)
198
- server = uvicorn.Server(config)
199
- await server.serve()
200
-
201
- async def start_bot():
202
- log.info("Starting bot...")
203
-
204
- await app.start()
205
 
206
- me = await app.get_me()
207
- log.info(f"Bot running as @{me.username}")
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  asyncio.create_task(worker())
210
- asyncio.create_task(keepalive())
211
-
212
- await idle()
213
 
214
- async def main():
215
- await asyncio.gather(
216
- start_bot(),
217
- run_web()
218
- )
 
 
219
 
 
220
  if __name__ == "__main__":
221
- asyncio.run(main())
 
 
 
 
1
+ import os, json, math, time, base64, shutil, asyncio, logging, tempfile, threading
2
+ from typing import Dict, Optional
3
+ from pathlib import Path
4
+ from http.server import HTTPServer, BaseHTTPRequestHandler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ import aiohttp
7
+ from cryptography.fernet import Fernet
8
+ from cryptography.hazmat.primitives import hashes
9
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
10
+ from cryptography.hazmat.backends import default_backend
11
+ from pyrogram import Client, filters
12
+ from pyrogram.types import (
13
+ Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
 
 
 
 
 
 
 
 
 
 
 
 
14
  )
15
+ from pyrogram.errors import MessageNotModified, FloodWait
16
+ from huggingface_hub import HfApi, upload_file, hf_hub_url
17
+ from huggingface_hub.utils import EntryNotFoundError
18
+
19
+ # ---------- LOGGING ----------
20
+ logging.basicConfig(level=logging.WARNING, format="%(asctime)s [%(levelname)s] %(message)s")
21
+ logger = logging.getLogger("bot")
22
+ logger.setLevel(logging.INFO)
23
+
24
+ # ---------- ENVIRONMENT VALIDATION ----------
25
+ REQUIRED_VARS = {
26
+ "BOT_TOKEN": "Telegram bot token",
27
+ "API_ID": "Telegram API ID (integer)",
28
+ "API_HASH": "Telegram API hash",
29
+ "HF_TOKEN": "Hugging Face token with write access",
30
+ "SECRET_KEY": "Secret passphrase for encryption",
31
+ }
32
+ for var, desc in REQUIRED_VARS.items():
33
+ if var not in os.environ or not os.environ[var].strip():
34
+ logger.error(f"Missing {var} ({desc})")
35
+ exit(1)
36
+ try:
37
+ api_id = int(os.environ["API_ID"])
38
+ except ValueError:
39
+ logger.error("API_ID must be an integer")
40
+ exit(1)
41
+
42
+ logger.info("✅ All environment variables are set and valid")
43
+
44
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
45
+ API_HASH = os.environ["API_HASH"]
46
+ HF_TOKEN = os.environ["HF_TOKEN"]
47
+ SECRET_KEY = os.environ["SECRET_KEY"]
48
+
49
+ HF_REPO_ID = "Cxops/Bzxv"
50
+ HF_REPO_TYPE = "dataset"
51
+ HF_BRANCH = "main"
52
+ MIN_FREE_DISK = 45 * 1024**3
53
+ SPLIT_SIZE = 2 * 1024**3 - 10*1024*1024
54
+ PROGRESS_INTERVAL = 3
55
+
56
+ # ---------- ENCRYPTION ----------
57
+ SALT = b"huggingbot_salt_2025"
58
+ kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=SALT,
59
+ iterations=100_000, backend=default_backend())
60
+ key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
61
+ fernet = Fernet(key)
62
+
63
+ def encrypt(data: str) -> str:
64
+ return base64.urlsafe_b64encode(fernet.encrypt(data.encode())).decode().rstrip("=")
65
+
66
+ def decrypt(token: str) -> str:
67
+ pad = 4 - len(token) % 4
68
+ if pad != 4:
69
+ token += "=" * pad
70
+ return fernet.decrypt(base64.urlsafe_b64decode(token)).decode()
71
+
72
+ def get_user_folder(user_id: int) -> str:
73
+ return encrypt(str(user_id))
74
+
75
+ # ---------- HUGGING FACE ----------
76
+ hf_api = HfApi(token=HF_TOKEN)
77
+
78
+ def hf_read_json(path: str) -> Optional[dict]:
79
+ try:
80
+ return json.loads(hf_api.read_file(HF_REPO_ID, path, repo_type=HF_REPO_TYPE, revision=HF_BRANCH))
81
+ except EntryNotFoundError:
82
+ return None
83
+ except Exception as e:
84
+ logger.error(f"hf_read_json error: {e}")
85
+ return None
86
+
87
+ def hf_write_json(path: str, data: dict):
88
+ hf_api.upload_file(
89
+ path_or_fileobj=json.dumps(data, indent=2).encode(),
90
+ path_in_repo=path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
91
+ commit_message=f"update {path}"
92
  )
93
 
94
+ def hf_delete_file(path: str):
95
+ try:
96
+ hf_api.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE,
97
+ commit_message=f"delete {path}")
98
+ except Exception as e:
99
+ logger.error(f"hf_delete_file error: {e}")
100
+
101
+ def hf_file_size(path: str) -> Optional[int]:
102
+ try:
103
+ return hf_api.get_file_metadata(HF_REPO_ID, path, repo_type=HF_REPO_TYPE).size
104
+ except EntryNotFoundError:
105
+ return None
106
+ except Exception as e:
107
+ logger.error(f"hf_file_size error: {e}")
108
+ return None
109
+
110
+ def free_disk_gb() -> float:
111
+ return shutil.disk_usage("/").free / (1024**3)
112
+
113
+ def enough_disk(needed: int = 0) -> bool:
114
+ return (shutil.disk_usage("/").free - needed) >= MIN_FREE_DISK
115
+
116
+ # ---------- SIMPLE HTTP SERVER (port 7860) ----------
117
+ class HealthHandler(BaseHTTPRequestHandler):
118
+ def do_GET(self):
119
+ self.send_response(200)
120
+ self.end_headers()
121
+ self.wfile.write(b"Alive")
122
+ def log_message(self, format, *args):
123
+ pass
124
+
125
+ def start_http_server():
126
+ server = HTTPServer(("0.0.0.0", 7860), HealthHandler)
127
+ logger.info("🌐 HTTP health server started on port 7860")
128
+ server.serve_forever()
129
+
130
+ # ---------- BOT CLIENT ----------
131
+ for f in Path(".").glob("bot.session*"):
132
+ f.unlink()
133
+ logger.info(f"Removed old session file: {f}")
134
+
135
+ app = Client("bot", api_id=api_id, api_hash=API_HASH, bot_token=BOT_TOKEN)
136
+
137
+ # ---------- GLOBAL STATE ----------
138
+ active_progress: Dict[int, dict] = {}
139
+ op_queue = asyncio.Queue()
140
+ pending_uploads: Dict[int, dict] = {}
141
+
142
+ # ---------- HELPERS ----------
143
+ def make_progress_bar(percent: float, width: int = 10) -> str:
144
+ filled = int(width * percent / 100)
145
+ return "█" * filled + "░" * (width - filled)
146
+
147
+ def format_bytes(size: int) -> str:
148
+ if size == 0:
149
+ return "0 B"
150
+ units = ["B", "KB", "MB", "GB", "TB"]
151
+ i = int(math.floor(math.log(size, 1024)))
152
+ return f"{round(size / (1024**i), 1)} {units[i]}"
153
+
154
+ async def progress_updater():
155
  while True:
156
+ await asyncio.sleep(PROGRESS_INTERVAL)
157
+ for msg_id, info in list(active_progress.items()):
158
+ try:
159
+ chat_id = info["chat_id"]
160
+ filename = info["filename"]
161
+ current = info.get("current", 0)
162
+ total = info.get("total", 0)
163
+ start_time = info.get("start_time", time.time())
164
+ op_type = info.get("op_type", "")
165
+ elapsed = max(time.time() - start_time, 1)
166
+ speed = current / elapsed if current > 0 else 0
167
+ if total > 0:
168
+ percent = (current / total) * 100
169
+ text = (f"**{op_type}** `{filename}`\n"
170
+ f"{make_progress_bar(percent)} {percent:.1f}%\n"
171
+ f"📦 {format_bytes(current)} / {format_bytes(total)}\n"
172
+ f"⚡ {format_bytes(speed)}/s")
173
+ else:
174
+ text = f"**{op_type}** `{filename}`\n⏳ Processing..."
175
+ keyboard = None
176
+ if info["state"] in ("downloading_from_tg", "downloading_from_hf", "sending_to_tg"):
177
+ keyboard = InlineKeyboardMarkup([[
178
+ InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_op_{msg_id}")
179
+ ]])
180
+ await app.edit_message_text(chat_id, msg_id, text, reply_markup=keyboard)
181
+ except MessageNotModified:
182
+ pass
183
+ except Exception as e:
184
+ logger.error(f"progress_updater error: {e}")
185
+
186
+ # ---------- UPLOAD HANDLER ----------
187
+ async def handle_upload(op: dict):
188
+ user_id = op["user_id"]
189
+ chat_id = op["chat_id"]
190
+ file_id = op["file_id"]
191
+ file_name = op["file_name"]
192
+ msg_id = op["status_msg_id"]
193
+ cancel_event = op["cancel_event"]
194
+
195
+ active_progress[msg_id] = {
196
+ "chat_id": chat_id,
197
+ "state": "downloading_from_tg",
198
+ "filename": file_name,
199
+ "current": 0,
200
+ "total": 0,
201
+ "start_time": time.time(),
202
+ "cancel_event": cancel_event,
203
+ "op_type": "Upload",
204
+ }
205
 
206
+ while not enough_disk():
207
  try:
208
+ await app.edit_message_text(chat_id, msg_id,
209
+ f"⏳ Waiting for disk space... (free: {free_disk_gb():.1f} GB, need ≥45 GB)")
210
  except:
211
  pass
212
+ await asyncio.sleep(10)
213
+ if cancel_event.is_set():
214
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled (disk wait).")
215
+ del active_progress[msg_id]
216
+ return
217
+
218
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix="_" + file_name)
219
+ os.close(tmp_fd)
220
+ try:
221
+ def tg_progress(current, total, mid):
222
+ info = active_progress.get(mid)
223
+ if info:
224
+ info["current"] = current
225
+ info["total"] = total
226
+ info["start_time"] = time.time()
227
+
228
+ await app.download_media(file_id, file_name=tmp_path,
229
+ progress=tg_progress, progress_args=(msg_id,))
230
+ except Exception as e:
231
+ logger.error(f"TG download error: {e}")
232
+ if os.path.exists(tmp_path):
233
+ os.unlink(tmp_path)
234
+ await app.edit_message_text(chat_id, msg_id, f"❌ Download error: {e}")
235
+ del active_progress[msg_id]
236
+ return
237
 
238
+ if cancel_event.is_set():
239
+ if os.path.exists(tmp_path):
240
+ os.unlink(tmp_path)
241
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
242
+ del active_progress[msg_id]
243
+ return
244
 
245
+ active_progress[msg_id]["state"] = "uploading_to_hf"
246
+ active_progress[msg_id]["current"] = 0
247
+ active_progress[msg_id]["total"] = 0
248
+
249
+ folder = get_user_folder(user_id)
250
+ enc_fname = encrypt(file_name)
251
+ hf_path = f"{folder}/{enc_fname}"
252
+ meta_path = f"{folder}/meta.json"
253
+
254
+ def hf_progress(current, total, mid):
255
+ info = active_progress.get(mid)
256
+ if info:
257
+ info["current"] = current
258
+ info["total"] = total
259
+ info["start_time"] = time.time()
260
+
261
+ try:
262
+ upload_file(
263
+ path_or_fileobj=tmp_path,
264
+ path_in_repo=hf_path,
265
+ repo_id=HF_REPO_ID,
266
+ repo_type=HF_REPO_TYPE,
267
+ token=HF_TOKEN,
268
+ progress_callback=hf_progress,
269
+ progress_callback_msg_id=msg_id,
270
+ )
271
+ except Exception as e:
272
+ logger.error(f"HF upload error: {e}")
273
+ if os.path.exists(tmp_path):
274
+ os.unlink(tmp_path)
275
+ await app.edit_message_text(chat_id, msg_id, f"❌ Upload error: {e}")
276
+ del active_progress[msg_id]
277
+ return
278
 
279
+ if cancel_event.is_set():
280
+ hf_delete_file(hf_path)
281
+ meta = hf_read_json(meta_path) or {}
282
+ meta.pop(enc_fname, None)
283
+ hf_write_json(meta_path, meta)
284
+ if os.path.exists(tmp_path):
285
+ os.unlink(tmp_path)
286
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled & file removed.")
287
+ del active_progress[msg_id]
288
+ return
289
 
290
+ meta = hf_read_json(meta_path) or {}
291
+ meta[enc_fname] = file_name
292
+ try:
293
+ hf_write_json(meta_path, meta)
294
+ except Exception as e:
295
+ logger.error(f"Meta update error: {e}")
296
+ await app.edit_message_text(chat_id, msg_id,
297
+ f"✅ Uploaded, but meta update failed: {e}")
298
+ if os.path.exists(tmp_path):
299
+ os.unlink(tmp_path)
300
+ del active_progress[msg_id]
301
  return
302
 
303
+ if os.path.exists(tmp_path):
304
+ os.unlink(tmp_path)
305
+ await app.edit_message_text(chat_id, msg_id, f"✅ Uploaded `{file_name}` successfully.")
306
+ del active_progress[msg_id]
307
+
308
+ # ---------- DOWNLOAD HANDLER ----------
309
+ async def handle_download(op: dict):
310
+ user_id = op["user_id"]
311
+ chat_id = op["chat_id"]
312
+ folder = op["folder"]
313
+ enc_fname = op["enc_fname"]
314
+ orig_name = op["orig_name"]
315
+ file_size = op["file_size"]
316
+ msg_id = op["status_msg_id"]
317
+ cancel_event = op["cancel_event"]
318
+
319
+ active_progress[msg_id] = {
320
+ "chat_id": chat_id,
321
+ "state": "downloading_from_hf",
322
+ "filename": orig_name,
323
+ "current": 0,
324
+ "total": file_size if file_size else 0,
325
+ "start_time": time.time(),
326
+ "cancel_event": cancel_event,
327
+ "op_type": "Download",
328
+ }
329
 
330
+ url = hf_hub_url(HF_REPO_ID, f"{folder}/{enc_fname}",
331
+ repo_type=HF_REPO_TYPE, revision=HF_BRANCH)
332
+
333
+ async def send_file(path: str, caption: str):
334
+ active_progress[msg_id]["state"] = "sending_to_tg"
335
+ active_progress[msg_id]["total"] = os.path.getsize(path)
336
+ await app.send_document(chat_id, path, caption=caption,
337
+ progress=lambda c, t: upload_progress(c, t, msg_id))
338
+ if cancel_event.is_set():
339
+ await app.stop_transmission()
340
+
341
+ def upload_progress(current, total, mid):
342
+ info = active_progress.get(mid)
343
+ if info:
344
+ info["current"] = current
345
+ info["total"] = total
346
+ info["start_time"] = time.time()
347
+
348
+ if file_size is None or file_size <= SPLIT_SIZE:
349
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{orig_name}")
350
+ os.close(tmp_fd)
351
+ try:
352
+ success = await download_from_url(url, tmp_path, msg_id, cancel_event, file_size)
353
+ if not success:
354
+ return
355
+ await send_file(tmp_path, orig_name)
356
+ if cancel_event.is_set():
357
+ await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
358
+ del active_progress[msg_id]
359
+ return
360
+ await app.edit_message_text(chat_id, msg_id, f"✅ Sent `{orig_name}`.")
361
+ finally:
362
+ if os.path.exists(tmp_path):
363
+ os.unlink(tmp_path)
364
+ del active_progress[msg_id]
365
+ else:
366
+ total_parts = math.ceil(file_size / SPLIT_SIZE)
367
+ for part_idx in range(total_parts):
368
+ if cancel_event.is_set():
369
+ await app.edit_message_text(chat_id, msg_id, "❌ Cancelled.")
370
+ del active_progress[msg_id]
371
+ return
372
+ start = part_idx * SPLIT_SIZE
373
+ end = min(start + SPLIT_SIZE - 1, file_size - 1)
374
+ part_size = end - start + 1
375
+ part_name = f"{orig_name}.part{part_idx+1:03d}"
376
+ active_progress[msg_id]["state"] = f"downloading part {part_idx+1}/{total_parts}"
377
+ active_progress[msg_id]["current"] = 0
378
+ active_progress[msg_id]["total"] = part_size
379
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=f"_{part_name}")
380
+ os.close(tmp_fd)
381
+ try:
382
+ success = await download_range(url, start, end, tmp_path, msg_id, cancel_event, part_size)
383
+ if not success:
384
+ return
385
+ active_progress[msg_id]["state"] = f"sending part {part_idx+1}/{total_parts}"
386
+ await send_file(tmp_path, f"{orig_name} - Part {part_idx+1}/{total_parts}")
387
+ if cancel_event.is_set():
388
+ await app.edit_message_text(chat_id, msg_id, "❌ Send cancelled.")
389
+ del active_progress[msg_id]
390
+ return
391
+ finally:
392
+ if os.path.exists(tmp_path):
393
+ os.unlink(tmp_path)
394
+ await app.edit_message_text(chat_id, msg_id, f"✅ All {total_parts} parts sent.")
395
+ del active_progress[msg_id]
396
+
397
+ async def download_from_url(url: str, dest: str, msg_id: int,
398
+ cancel_event: asyncio.Event,
399
+ total_size: Optional[int]) -> bool:
400
+ try:
401
+ async with aiohttp.ClientSession() as session:
402
+ async with session.get(url) as resp:
403
+ if resp.status != 200:
404
+ raise Exception(f"HTTP {resp.status}")
405
+ total = total_size or int(resp.headers.get("Content-Length", 0))
406
+ info = active_progress.get(msg_id)
407
+ if info:
408
+ info["total"] = total
409
+ downloaded = 0
410
+ with open(dest, "wb") as f:
411
+ async for chunk in resp.content.iter_chunked(64*1024):
412
+ if cancel_event.is_set():
413
+ return False
414
+ f.write(chunk)
415
+ downloaded += len(chunk)
416
+ if info:
417
+ info["current"] = downloaded
418
+ info["start_time"] = time.time()
419
+ return True
420
+ except Exception as e:
421
+ logger.error(f"download_from_url error: {e}")
422
+ await app.edit_message_text(msg_id, f"❌ Download error: {e}")
423
+ return False
424
+
425
+ async def download_range(url: str, start: int, end: int, dest: str,
426
+ msg_id: int, cancel_event: asyncio.Event,
427
+ size: int) -> bool:
428
+ headers = {"Range": f"bytes={start}-{end}"}
429
+ try:
430
+ async with aiohttp.ClientSession() as session:
431
+ async with session.get(url, headers=headers) as resp:
432
+ if resp.status not in (200, 206):
433
+ raise Exception(f"HTTP {resp.status}")
434
+ info = active_progress.get(msg_id)
435
+ if info:
436
+ info["total"] = size
437
+ downloaded = 0
438
+ with open(dest, "wb") as f:
439
+ async for chunk in resp.content.iter_chunked(64*1024):
440
+ if cancel_event.is_set():
441
+ return False
442
+ f.write(chunk)
443
+ downloaded += len(chunk)
444
+ if info:
445
+ info["current"] = downloaded
446
+ info["start_time"] = time.time()
447
+ return True
448
+ except Exception as e:
449
+ logger.error(f"download_range error: {e}")
450
+ await app.edit_message_text(msg_id, f"❌ Download error: {e}")
451
+ return False
452
+
453
+ # ---------- TELEGRAM HANDLERS ----------
454
+ @app.on_message(filters.command("start"))
455
+ async def start_cmd(_, msg: Message):
456
+ logger.info(f"/start from {msg.from_user.id}")
457
+ await msg.reply(
458
+ "👋 **Welcome to Cloud Storage Bot!**\n\n"
459
+ "Send any file to upload it to the cloud.\n"
460
+ "Use /files to see your uploaded files.\n"
461
+ "Help: /help"
462
  )
463
 
464
+ @app.on_message(filters.command("help"))
465
+ async def help_cmd(_, msg: Message):
466
+ await msg.reply(
467
+ "**Commands:**\n"
468
+ "/start – Start the bot\n"
469
+ "/files – List your files\n"
470
+ "/help – Show this help\n\n"
471
+ "Send any file to upload, use /files to download."
472
+ )
473
 
474
+ @app.on_message(filters.command("files"))
475
+ async def list_files(_, msg: Message):
476
+ user_id = msg.from_user.id
477
+ meta = hf_read_json(f"{get_user_folder(user_id)}/meta.json")
478
+ if not meta:
479
+ await msg.reply("📭 No files yet.")
480
+ return
481
+ kb = [[InlineKeyboardButton(name, callback_data=f"dl_{enc}")] for enc, name in meta.items()]
482
+ kb.append([InlineKeyboardButton("🔄 Refresh", callback_data="files_refresh")])
483
+ await msg.reply("📂 Your files:", reply_markup=InlineKeyboardMarkup(kb))
484
+
485
+ @app.on_callback_query(filters.regex("^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("^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("^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
+ @app.on_message(filters.media)
527
+ async def media_handler(_, msg: Message):
528
+ logger.info(f"Media from {msg.from_user.id}")
529
+ file_id = None
530
+ file_name = "file"
531
+ file_size = 0
532
+
533
+ if msg.document:
534
+ file_id = msg.document.file_id
535
+ file_name = msg.document.file_name or "document"
536
+ file_size = msg.document.file_size
537
+ elif msg.video:
538
+ file_id = msg.video.file_id
539
+ file_name = msg.video.file_name or "video.mp4"
540
+ file_size = msg.video.file_size
541
+ elif msg.audio:
542
+ file_id = msg.audio.file_id
543
+ file_name = msg.audio.file_name or "audio.mp3"
544
+ file_size = msg.audio.file_size
545
+ elif msg.photo:
546
+ file_id = msg.photo.file_id
547
+ file_name = f"photo_{msg.photo.file_unique_id}.jpg"
548
+ file_size = msg.photo.file_size or 0
549
+ elif msg.voice:
550
+ file_id = msg.voice.file_id
551
+ file_name = f"voice_{msg.voice.file_unique_id}.ogg"
552
+ file_size = msg.voice.file_size
553
+ elif msg.video_note:
554
+ file_id = msg.video_note.file_id
555
+ file_name = f"vn_{msg.video_note.file_unique_id}.mp4"
556
+ file_size = msg.video_note.file_size
557
+ elif msg.sticker:
558
+ file_id = msg.sticker.file_id
559
+ file_name = f"sticker_{msg.sticker.file_unique_id}.webp"
560
+ file_size = msg.sticker.file_size
561
+ else:
562
+ return
563
 
564
+ if not file_id:
565
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566
 
567
+ prompt = await msg.reply(
568
+ f"📁 `{file_name}` ({format_bytes(file_size) if file_size else 'unknown size'})\n"
569
+ "Do you want to upload this file?",
570
+ reply_markup=InlineKeyboardMarkup([[
571
+ InlineKeyboardButton("✅ Upload", callback_data=f"upload_{msg.id}"),
572
+ InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_prompt_{msg.id}")
573
+ ]]),
574
+ quote=True,
575
+ )
576
+ pending_uploads[prompt.id] = {
577
+ "file_id": file_id,
578
+ "file_name": file_name,
579
+ "file_size": file_size,
580
+ "user_id": msg.from_user.id,
581
+ }
582
 
583
+ @app.on_callback_query(filters.regex("^upload_(\\d+)$"))
584
+ async def confirm_upload(_, query: CallbackQuery):
585
+ info = pending_uploads.pop(query.message.id, None)
586
+ if not info:
587
+ await query.answer("Session expired, please send the file again.", show_alert=True)
588
+ return
589
+ await query.answer()
590
+ await query.message.delete()
591
+ st = await query.message.reply(f"⏳ Uploading `{info['file_name']}`…")
592
+ cancel_ev = asyncio.Event()
593
+ await op_queue.put({
594
+ "type": "upload",
595
+ "user_id": info["user_id"],
596
+ "chat_id": query.message.chat.id,
597
+ "file_id": info["file_id"],
598
+ "file_name": info["file_name"],
599
+ "status_msg_id": st.id,
600
+ "cancel_event": cancel_ev,
601
+ })
602
+
603
+ @app.on_callback_query(filters.regex("^cancel_prompt_(\\d+)$"))
604
+ async def cancel_prompt(_, query: CallbackQuery):
605
+ pending_uploads.pop(query.message.id, None)
606
+ await query.answer("Cancelled.")
607
+ await query.message.delete()
608
+
609
+ # ---------- WORKER ----------
610
+ async def worker():
611
+ while True:
612
+ op = await op_queue.get()
613
+ try:
614
+ if op["type"] == "upload":
615
+ await handle_upload(op)
616
+ else:
617
+ await handle_download(op)
618
+ except Exception as e:
619
+ logger.exception(f"Worker error: {e}")
620
+ finally:
621
+ op_queue.task_done()
622
+
623
+ # ---------- STARTUP (CORRECTED) ----------
624
+ @app.on_startup()
625
+ async def on_startup():
626
+ # Start background tasks
627
  asyncio.create_task(worker())
628
+ asyncio.create_task(progress_updater())
 
 
629
 
630
+ # Print bot info
631
+ me = await app.get_me()
632
+ logger.info(f"🤖 Bot online: @{me.username} (ID: {me.id})")
633
+ logger.info(f"📦 Repo: {HF_REPO_ID}")
634
+ logger.info(f"💾 Disk limit: {MIN_FREE_DISK // (1024**3)} GB free required")
635
+ logger.info(f"✂️ Split size: {SPLIT_SIZE // (1024**2)} MB")
636
+ logger.info("👂 Listening for messages...")
637
 
638
+ # ---------- MAIN (no more broken add_handler) ----------
639
  if __name__ == "__main__":
640
+ # Start the HTTP health server in a daemon thread
641
+ threading.Thread(target=start_http_server, daemon=True).start()
642
+ # This method works exactly like the echo bot – it blocks and processes updates.
643
+ app.run()