Cxops commited on
Commit
954c1aa
·
verified ·
1 Parent(s): 806ea3a

Update app.py

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