Cxops commited on
Commit
595e5cb
·
verified ·
1 Parent(s): dda777d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -55
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import sys
3
  import time
4
  import base64
5
  import hashlib
@@ -8,15 +7,14 @@ import threading
8
  import asyncio
9
  import sqlite3
10
  import tempfile
11
- from pathlib import Path
12
- from typing import Optional, Tuple
13
 
14
  import requests
15
  from flask import Flask
16
  from pyrogram import Client, filters
17
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
18
  from huggingface_hub import HfApi, hf_hub_download, get_hf_file_metadata
19
- from cryptography.fernet import Fernet
20
 
21
  # --------------- CONFIG ---------------
22
  API_ID = int(os.environ["API_ID"])
@@ -26,25 +24,28 @@ HF_TOKEN = os.environ["HF_TOKEN"]
26
  OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
27
 
28
  DATASET_REPO = "Cxops/Bzxv"
29
- MAX_FILE_SIZE_TG = 1900 * 1024 * 1024 # 1900 MB per part
30
- MIN_FREE_DISK = 45 * 1024 * 1024 * 1024 # 45 GB
31
- KEEPALIVE_INTERVAL = 300 # 5 minutes
32
  DB_PATH = "bot_files.db"
33
 
34
- # --------------- ENCRYPTION SETUP ---------------
35
- fernet_key = base64.urlsafe_b64encode(hashlib.sha256(OBFUSCATION_KEY.encode()).digest())
36
- fernet = Fernet(fernet_key)
 
37
 
38
  def encrypt_text(plain: str) -> str:
39
- token = fernet.encrypt(plain.encode())
 
40
  return base64.urlsafe_b64encode(token).decode().rstrip("=")
41
 
42
  def decrypt_text(encoded: str) -> str:
 
43
  padding = 4 - len(encoded) % 4
44
  if padding != 4:
45
  encoded += "=" * padding
46
  token = base64.urlsafe_b64decode(encoded.encode())
47
- return fernet.decrypt(token).decode()
48
 
49
  def get_encrypted_folder(user_id: int) -> str:
50
  return encrypt_text(str(user_id))
@@ -52,7 +53,7 @@ def get_encrypted_folder(user_id: int) -> str:
52
  def get_encrypted_filename(original: str) -> str:
53
  return encrypt_text(original)
54
 
55
- # --------------- DATABASE ---------------
56
  conn = sqlite3.connect(DB_PATH, check_same_thread=False)
57
  cursor = conn.cursor()
58
  cursor.execute("""
@@ -91,7 +92,7 @@ def home():
91
  def run_web():
92
  web.run(host="0.0.0.0", port=7860)
93
 
94
- # --------------- HF CLIENT ---------------
95
  hf = HfApi(token=HF_TOKEN)
96
 
97
  # --------------- PYROGRAM BOT ---------------
@@ -107,7 +108,6 @@ upload_queue = asyncio.Queue()
107
  active_jobs = {}
108
 
109
  # --------------- HELPERS ---------------
110
-
111
  def cleanup(path: str):
112
  try:
113
  if os.path.isdir(path):
@@ -135,10 +135,12 @@ async def progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
135
  start_bytes: int = 0, total_bytes: Optional[int] = None,
136
  is_upload: bool = True):
137
  """
138
- Updates the status message every 3 seconds with progress (if total_bytes known)
139
- and speed/ETA. Returns the current uploaded/downloaded bytes (updated via a shared list).
 
140
  """
141
- last_bytes = [start_bytes] # mutable container so inner function can update it
 
142
 
143
  async def updater():
144
  while not cancel_event.is_set():
@@ -165,7 +167,6 @@ async def progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
165
  break
166
  await asyncio.sleep(3)
167
 
168
- start_time = time.time()
169
  task = asyncio.create_task(updater())
170
  return task, last_bytes
171
 
@@ -174,7 +175,7 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
174
  job_id: int, cancel_event: asyncio.Event, status_msg):
175
  temp_dir = tempfile.mkdtemp()
176
  try:
177
- # Download from Telegram
178
  await status_msg.edit_text("⬇️ Downloading from Telegram...",
179
  reply_markup=InlineKeyboardMarkup([
180
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
@@ -185,17 +186,32 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
185
 
186
  file_size = os.path.getsize(local_path)
187
 
188
- # Prepare HF path
189
  enc_folder = get_encrypted_folder(user_id)
190
  enc_filename = get_encrypted_filename(orig_filename)
191
  repo_path = f"{enc_folder}/{enc_filename}"
192
 
193
- # Start progress updater (upload phase)
194
  progress_task, bytes_holder = await progress_updater(
195
  job_id, status_msg, cancel_event,
196
  start_bytes=0, total_bytes=file_size, is_upload=True
197
  )
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  loop = asyncio.get_event_loop()
200
  upload_done = loop.create_future()
201
 
@@ -213,29 +229,14 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
213
 
214
  task = loop.run_in_executor(None, sync_upload)
215
 
216
- # We'll simulate progress by checking the file size (not possible to get real-time bytes from hf api)
217
- # Instead we'll update bytes_holder every 0.5s based on time elapsed (estimated)
218
- # Actually, we can't get real-time; we'll assume linear progress based on time.
219
- async def simulate_upload_progress():
220
- start = time.time()
221
- while not task.done() and not cancel_event.is_set():
222
- elapsed = time.time() - start
223
- # rough estimate: assume upload speed ~10 MB/s (adjustable)
224
- estimated = min(elapsed * 10_000_000, file_size)
225
- bytes_holder[0] = estimated
226
- await asyncio.sleep(1)
227
- bytes_holder[0] = file_size # final
228
-
229
- progress_sim = asyncio.create_task(simulate_upload_progress())
230
-
231
- # Wait for actual upload completion or cancel
232
  while not task.done():
233
  if cancel_event.is_set():
234
  break
235
  await asyncio.sleep(1)
236
 
237
  if cancel_event.is_set():
238
- # Cancel HF upload if possible (we delete afterwards)
239
  try:
240
  hf.delete_file(
241
  path_in_repo=repo_path,
@@ -250,7 +251,7 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
250
  return
251
 
252
  # Normal completion
253
- await task # raise any exception
254
  bytes_holder[0] = file_size
255
  progress_task.cancel()
256
  progress_sim.cancel()
@@ -270,7 +271,7 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
270
  job_id: int, cancel_event: asyncio.Event, status_msg):
271
  temp_dir = tempfile.mkdtemp()
272
  try:
273
- # Get file metadata (size) from HF
274
  loop = asyncio.get_event_loop()
275
  metadata = await loop.run_in_executor(
276
  None,
@@ -281,21 +282,19 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
281
  )
282
  total_size = metadata.size
283
 
284
- # Start progress updater (download phase)
285
  progress_task, bytes_holder = await progress_updater(
286
  job_id, status_msg, cancel_event,
287
  start_bytes=0, total_bytes=total_size, is_upload=False
288
  )
289
 
290
- # Download in chunks to track progress
291
- download_done = loop.create_future()
292
  local_file = os.path.join(temp_dir, "downloaded_file")
293
 
 
 
 
294
  def sync_download_with_progress():
295
  try:
296
- # We'll use hf_hub_download and then check size after; but we want progress while downloading.
297
- # We can use requests to download and update bytes.
298
- import requests
299
  url = hf.get_hf_file_metadata_url(
300
  repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset"
301
  )
@@ -316,6 +315,7 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
316
 
317
  task = loop.run_in_executor(None, sync_download_with_progress)
318
 
 
319
  while not task.done():
320
  if cancel_event.is_set():
321
  break
@@ -329,7 +329,7 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
329
  await task
330
  progress_task.cancel()
331
 
332
- # Split if too large and send
333
  file_size = os.path.getsize(local_file)
334
  if file_size <= MAX_FILE_SIZE_TG:
335
  await status_msg.edit_text("📤 Sending file to Telegram...", reply_markup=None)
@@ -337,7 +337,7 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
337
  await status_msg.delete()
338
  else:
339
  part_size = MAX_FILE_SIZE_TG
340
- num_parts = -(-file_size // part_size)
341
  await status_msg.edit_text(f"📤 Sending in {num_parts} parts...", reply_markup=None)
342
  with open(local_file, "rb") as f:
343
  for i in range(1, num_parts + 1):
@@ -367,6 +367,7 @@ async def upload_worker():
367
  cancel_event = asyncio.Event()
368
  active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
369
 
 
370
  while get_free_disk() < MIN_FREE_DISK:
371
  await asyncio.sleep(10)
372
 
@@ -396,14 +397,14 @@ async def start_cmd(_, message):
396
  async def list_files(_, message):
397
  user_id = message.from_user.id
398
  user_files = db_get_user_files(user_id)
 
 
399
  if not user_files:
400
- # Fallback: check HF directly (maybe DB is empty after restart)
401
  enc_folder = get_encrypted_folder(user_id)
402
  try:
403
  all_hf = hf.list_repo_files(repo_id=DATASET_REPO, repo_type="dataset")
404
  hf_user_files = [f for f in all_hf if f.startswith(enc_folder + "/")]
405
  for path in hf_user_files:
406
- # Rebuild DB entry
407
  _, enc_name = path.split("/", 1)
408
  try:
409
  orig_name = decrypt_text(enc_name)
@@ -441,12 +442,11 @@ async def get_file_callback(_, query):
441
  cancel_event = asyncio.Event()
442
  active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
443
 
444
- # Get original name from DB (or decrypt)
445
- orig_name = enc_path.split("/")[-1] # fallback
446
  try:
447
- orig_name = decrypt_text(orig_name)
448
  except Exception:
449
- pass
450
 
451
  status_msg = await query.message.edit_text(
452
  "⏳ Preparing download...",
 
1
  import os
 
2
  import time
3
  import base64
4
  import hashlib
 
7
  import asyncio
8
  import sqlite3
9
  import tempfile
10
+ from typing import Optional
 
11
 
12
  import requests
13
  from flask import Flask
14
  from pyrogram import Client, filters
15
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
16
  from huggingface_hub import HfApi, hf_hub_download, get_hf_file_metadata
17
+ from cryptography.hazmat.primitives.ciphers.aead import AESSIV
18
 
19
  # --------------- CONFIG ---------------
20
  API_ID = int(os.environ["API_ID"])
 
24
  OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
25
 
26
  DATASET_REPO = "Cxops/Bzxv"
27
+ MAX_FILE_SIZE_TG = 1900 * 1024 * 1024 # 1900 MB per Telegram part
28
+ MIN_FREE_DISK = 45 * 1024 * 1024 * 1024 # 45 GB
29
+ KEEPALIVE_INTERVAL = 300 # 5 minutes
30
  DB_PATH = "bot_files.db"
31
 
32
+ # --------------- DETERMINISTIC ENCRYPTION (AES-SIV) ---------------
33
+ # Always produces the same ciphertext for the same key + plaintext.
34
+ siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
35
+ aes_siv = AESSIV(siv_key)
36
 
37
  def encrypt_text(plain: str) -> str:
38
+ """Return URL‑safe base64 without padding (always the same output for the same input)."""
39
+ token = aes_siv.encrypt(plain.encode(), None)
40
  return base64.urlsafe_b64encode(token).decode().rstrip("=")
41
 
42
  def decrypt_text(encoded: str) -> str:
43
+ """Recover the original string. Accepts base64 with or without padding."""
44
  padding = 4 - len(encoded) % 4
45
  if padding != 4:
46
  encoded += "=" * padding
47
  token = base64.urlsafe_b64decode(encoded.encode())
48
+ return aes_siv.decrypt(token, None).decode()
49
 
50
  def get_encrypted_folder(user_id: int) -> str:
51
  return encrypt_text(str(user_id))
 
53
  def get_encrypted_filename(original: str) -> str:
54
  return encrypt_text(original)
55
 
56
+ # --------------- SQLITE DATABASE ---------------
57
  conn = sqlite3.connect(DB_PATH, check_same_thread=False)
58
  cursor = conn.cursor()
59
  cursor.execute("""
 
92
  def run_web():
93
  web.run(host="0.0.0.0", port=7860)
94
 
95
+ # --------------- HUGGING FACE CLIENT ---------------
96
  hf = HfApi(token=HF_TOKEN)
97
 
98
  # --------------- PYROGRAM BOT ---------------
 
108
  active_jobs = {}
109
 
110
  # --------------- HELPERS ---------------
 
111
  def cleanup(path: str):
112
  try:
113
  if os.path.isdir(path):
 
135
  start_bytes: int = 0, total_bytes: Optional[int] = None,
136
  is_upload: bool = True):
137
  """
138
+ Update the status message every 3 seconds with progress (percentage, speed, ETA).
139
+ Returns a tuple (task, bytes_holder) where bytes_holder is a list with a single element
140
+ that should be updated periodically to reflect the current transferred bytes.
141
  """
142
+ last_bytes = [start_bytes]
143
+ start_time = time.time()
144
 
145
  async def updater():
146
  while not cancel_event.is_set():
 
167
  break
168
  await asyncio.sleep(3)
169
 
 
170
  task = asyncio.create_task(updater())
171
  return task, last_bytes
172
 
 
175
  job_id: int, cancel_event: asyncio.Event, status_msg):
176
  temp_dir = tempfile.mkdtemp()
177
  try:
178
+ # 1. Download file from Telegram
179
  await status_msg.edit_text("⬇️ Downloading from Telegram...",
180
  reply_markup=InlineKeyboardMarkup([
181
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
 
186
 
187
  file_size = os.path.getsize(local_path)
188
 
189
+ # 2. Prepare Hugging Face path (encrypted)
190
  enc_folder = get_encrypted_folder(user_id)
191
  enc_filename = get_encrypted_filename(orig_filename)
192
  repo_path = f"{enc_folder}/{enc_filename}"
193
 
194
+ # 3. Start progress updater for upload
195
  progress_task, bytes_holder = await progress_updater(
196
  job_id, status_msg, cancel_event,
197
  start_bytes=0, total_bytes=file_size, is_upload=True
198
  )
199
 
200
+ # We'll simulate upload progress because HF API doesn't give real-time bytes.
201
+ # We'll update bytes_holder based on elapsed time assuming a reasonable speed.
202
+ async def simulate_progress():
203
+ start = time.time()
204
+ while not cancel_event.is_set():
205
+ elapsed = time.time() - start
206
+ # Rough estimate: assume ~10 MB/s upload speed (adjust if needed)
207
+ estimated = min(elapsed * 10_000_000, file_size)
208
+ bytes_holder[0] = estimated
209
+ await asyncio.sleep(1)
210
+ bytes_holder[0] = file_size # finalise
211
+
212
+ progress_sim = asyncio.create_task(simulate_progress())
213
+
214
+ # 4. Actual upload (in executor)
215
  loop = asyncio.get_event_loop()
216
  upload_done = loop.create_future()
217
 
 
229
 
230
  task = loop.run_in_executor(None, sync_upload)
231
 
232
+ # Wait for completion or cancel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  while not task.done():
234
  if cancel_event.is_set():
235
  break
236
  await asyncio.sleep(1)
237
 
238
  if cancel_event.is_set():
239
+ # Delete the partially uploaded file from HF
240
  try:
241
  hf.delete_file(
242
  path_in_repo=repo_path,
 
251
  return
252
 
253
  # Normal completion
254
+ await task # raise exception if any
255
  bytes_holder[0] = file_size
256
  progress_task.cancel()
257
  progress_sim.cancel()
 
271
  job_id: int, cancel_event: asyncio.Event, status_msg):
272
  temp_dir = tempfile.mkdtemp()
273
  try:
274
+ # Get file size from HF metadata
275
  loop = asyncio.get_event_loop()
276
  metadata = await loop.run_in_executor(
277
  None,
 
282
  )
283
  total_size = metadata.size
284
 
285
+ # Start progress updater for download
286
  progress_task, bytes_holder = await progress_updater(
287
  job_id, status_msg, cancel_event,
288
  start_bytes=0, total_bytes=total_size, is_upload=False
289
  )
290
 
 
 
291
  local_file = os.path.join(temp_dir, "downloaded_file")
292
 
293
+ # Download with stream to track progress
294
+ download_done = loop.create_future()
295
+
296
  def sync_download_with_progress():
297
  try:
 
 
 
298
  url = hf.get_hf_file_metadata_url(
299
  repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset"
300
  )
 
315
 
316
  task = loop.run_in_executor(None, sync_download_with_progress)
317
 
318
+ # Wait for completion or cancel
319
  while not task.done():
320
  if cancel_event.is_set():
321
  break
 
329
  await task
330
  progress_task.cancel()
331
 
332
+ # Send file (split if needed)
333
  file_size = os.path.getsize(local_file)
334
  if file_size <= MAX_FILE_SIZE_TG:
335
  await status_msg.edit_text("📤 Sending file to Telegram...", reply_markup=None)
 
337
  await status_msg.delete()
338
  else:
339
  part_size = MAX_FILE_SIZE_TG
340
+ num_parts = -(-file_size // part_size) # ceil division
341
  await status_msg.edit_text(f"📤 Sending in {num_parts} parts...", reply_markup=None)
342
  with open(local_file, "rb") as f:
343
  for i in range(1, num_parts + 1):
 
367
  cancel_event = asyncio.Event()
368
  active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
369
 
370
+ # Wait until enough free disk space
371
  while get_free_disk() < MIN_FREE_DISK:
372
  await asyncio.sleep(10)
373
 
 
397
  async def list_files(_, message):
398
  user_id = message.from_user.id
399
  user_files = db_get_user_files(user_id)
400
+
401
+ # Fallback: if DB is empty, scan HF and rebuild DB entries
402
  if not user_files:
 
403
  enc_folder = get_encrypted_folder(user_id)
404
  try:
405
  all_hf = hf.list_repo_files(repo_id=DATASET_REPO, repo_type="dataset")
406
  hf_user_files = [f for f in all_hf if f.startswith(enc_folder + "/")]
407
  for path in hf_user_files:
 
408
  _, enc_name = path.split("/", 1)
409
  try:
410
  orig_name = decrypt_text(enc_name)
 
442
  cancel_event = asyncio.Event()
443
  active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
444
 
445
+ # Retrieve original file name
 
446
  try:
447
+ orig_name = decrypt_text(enc_path.split("/")[-1])
448
  except Exception:
449
+ orig_name = enc_path.split("/")[-1] # fallback
450
 
451
  status_msg = await query.message.edit_text(
452
  "⏳ Preparing download...",