Cxops commited on
Commit
dda777d
·
verified ·
1 Parent(s): 95e5c53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +472 -204
app.py CHANGED
@@ -1,278 +1,546 @@
1
  import os
 
2
  import time
3
- import tempfile
 
4
  import shutil
5
  import threading
 
 
 
 
 
6
 
 
7
  from flask import Flask
8
-
9
  from pyrogram import Client, filters
10
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
 
 
11
 
12
- from huggingface_hub import HfApi, hf_hub_download
13
-
14
- # =========================
15
- # CONFIG
16
- # =========================
17
-
18
  API_ID = int(os.environ["API_ID"])
19
  API_HASH = os.environ["API_HASH"]
20
  BOT_TOKEN = os.environ["BOT_TOKEN"]
21
  HF_TOKEN = os.environ["HF_TOKEN"]
 
22
 
23
  DATASET_REPO = "Cxops/Bzxv"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # =========================
26
- # LOGS
27
- # =========================
 
 
 
28
 
29
- def log(msg):
30
- print(f"[LOG] {msg}", flush=True)
 
31
 
32
- # =========================
33
- # FLASK (HF SPACE KEEP ALIVE)
34
- # =========================
35
 
36
- app_web = Flask(__name__)
 
37
 
38
- @app_web.route("/")
39
  def home():
40
- return "OK"
41
 
42
  def run_web():
43
- app_web.run(host="0.0.0.0", port=7860)
44
-
45
- # =========================
46
- # HF CLIENT
47
- # =========================
48
 
 
49
  hf = HfApi(token=HF_TOKEN)
50
 
51
- # =========================
52
- # PYROGRAM
53
- # =========================
54
-
55
  app = Client(
56
- "bot",
57
  api_id=API_ID,
58
  api_hash=API_HASH,
59
  bot_token=BOT_TOKEN
60
  )
61
 
62
- # =========================
63
- # CLEANUP
64
- # =========================
65
 
66
- def cleanup(path):
 
 
67
  try:
68
- shutil.rmtree(path, ignore_errors=True)
69
- except:
 
 
 
70
  pass
71
 
72
- # =========================
73
- # PROGRESS UI
74
- # =========================
75
-
76
- def bar(cur, total, start):
77
- elapsed = time.time() - start
78
- speed = cur / (elapsed + 0.0001)
79
-
80
- percent = (cur * 100 / total) if total else 0
81
-
82
- blocks = int(percent // 10)
83
- return (
84
- "█" * blocks + "░" * (10 - blocks) + "\n"
85
- f"{percent:.2f}%\n"
86
- f"{speed/1024/1024:.2f} MB/s"
87
- )
88
-
89
- # =========================
90
- # START
91
- # =========================
92
-
93
- @app.on_message(filters.command("start"))
94
- async def start(_, m):
95
- await m.reply_text(
96
- "⚡ Bot Ready\n\n"
97
- "Send file → HF storage\n"
98
- "/files → list"
99
- )
100
-
101
- # =========================
102
- # LIST FILES
103
- # =========================
104
-
105
- @app.on_message(filters.command("files"))
106
- async def files(_, m):
107
- uid = str(m.from_user.id)
108
-
109
- all_files = hf.list_repo_files(
110
- repo_id=DATASET_REPO,
111
- repo_type="dataset"
112
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- user_files = [f for f in all_files if f.startswith(uid + "/")]
 
115
 
116
- if not user_files:
117
- return await m.reply_text("No files found")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- buttons = [
120
- [InlineKeyboardButton(os.path.basename(f), callback_data=f"get:{f}")]
121
- for f in user_files[:50]
122
- ]
 
123
 
124
- await m.reply_text(
125
- "Your files:",
126
- reply_markup=InlineKeyboardMarkup(buttons)
127
- )
128
 
129
- # =========================
130
- # HF → TELEGRAM (FIXED PROGRESS)
131
- # =========================
132
 
133
- @app.on_callback_query(filters.regex("^get:"))
134
- async def get_file(_, q):
135
- path = q.data.split(":", 1)[1]
136
- tmp = tempfile.mkdtemp()
137
 
 
 
 
 
138
  try:
139
- await q.message.edit_text("📥 Downloading from HF...")
140
-
141
- start = time.time()
142
- last = [0]
143
-
144
- file_path = hf_hub_download(
145
- repo_id=DATASET_REPO,
146
- repo_type="dataset",
147
- filename=path,
148
- token=HF_TOKEN,
149
- local_dir=tmp
150
  )
 
151
 
152
- await q.message.edit_text("📤 Uploading to Telegram...")
153
-
154
- tg_start = time.time()
155
- tg_last = [0]
156
-
157
- def tg_progress(cur, total):
158
- now = time.time()
159
 
160
- if now - tg_last[0] < 2:
161
- return
162
- tg_last[0] = now
163
 
 
164
  try:
165
- q.message.edit_text(
166
- "📤 Uploading to Telegram...\n\n" +
167
- bar(cur, total, tg_start)
 
 
168
  )
169
- except:
170
- pass
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
- await app.send_document(
173
- chat_id=q.message.chat.id,
174
- document=file_path,
175
- progress=tg_progress
176
- )
177
 
178
- await q.message.delete()
 
 
 
179
 
180
- except Exception as e:
181
- log(f"HF->TG error: {e}")
182
- await q.message.reply_text(str(e))
 
183
 
184
- finally:
185
- cleanup(tmp)
186
 
187
- # =========================
188
- # TELEGRAM → HF (FIXED PROGRESS)
189
- # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
- @app.on_message(
192
- filters.document |
193
- filters.video |
194
- filters.audio |
195
- filters.photo
196
- )
197
- async def upload(_, m):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
- tmp = tempfile.mkdtemp()
 
 
 
 
200
 
201
- try:
202
- status = await m.reply_text("Starting...")
203
-
204
- if m.document:
205
- name = m.document.file_name
206
- elif m.video:
207
- name = m.video.file_name or f"{m.video.file_unique_id}.mp4"
208
- elif m.audio:
209
- name = m.audio.file_name or f"{m.audio.file_unique_id}.mp3"
210
- else:
211
- name = f"{m.photo[-1].file_unique_id}.jpg"
212
 
213
- uid = str(m.from_user.id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
- start = time.time()
216
- last = [0]
217
 
218
- # DOWNLOAD PROGRESS
219
- def dl_progress(cur, total):
220
- now = time.time()
221
 
222
- if now - last[0] < 2:
223
- return
224
- last[0] = now
 
225
 
226
- try:
227
- status.edit_text(
228
- "📥 Downloading from Telegram...\n\n" +
229
- bar(cur, total, start)
230
- )
231
- except:
232
- pass
 
 
 
 
 
 
233
 
234
- local = await m.download(
235
- file_name=f"{tmp}/{name}",
236
- progress=dl_progress
237
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
- await status.edit_text("☁ Uploading to HF...")
 
 
 
240
 
241
- repo_path = f"{uid}/{name}"
 
242
 
243
- # HF upload background
244
- def hf_upload():
245
- try:
246
- hf.upload_file(
247
- path_or_fileobj=local,
248
- path_in_repo=repo_path,
249
- repo_id=DATASET_REPO,
250
- repo_type="dataset",
251
- )
252
- status.edit_text("⚡ Upload Complete")
253
- log("HF upload done")
254
- except Exception as e:
255
- status.edit_text(f"HF Error:\n{e}")
256
- log(f"HF error: {e}")
257
 
258
- threading.Thread(target=hf_upload, daemon=True).start()
259
 
260
- except Exception as e:
261
- await m.reply_text(str(e))
 
 
262
 
263
- finally:
264
- threading.Thread(
265
- target=lambda: (time.sleep(15), cleanup(tmp)),
266
- daemon=True
267
- ).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
- # =========================
270
- # RUN
271
- # =========================
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
  if __name__ == "__main__":
274
- log("Bot starting...")
275
-
276
  threading.Thread(target=run_web, daemon=True).start()
277
-
278
- app.run()
 
1
  import os
2
+ import sys
3
  import time
4
+ import base64
5
+ import hashlib
6
  import shutil
7
  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"])
23
  API_HASH = os.environ["API_HASH"]
24
  BOT_TOKEN = os.environ["BOT_TOKEN"]
25
  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))
51
+
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("""
59
+ CREATE TABLE IF NOT EXISTS files (
60
+ user_id INTEGER,
61
+ enc_path TEXT UNIQUE,
62
+ orig_name TEXT,
63
+ size INTEGER,
64
+ timestamp REAL
65
+ )
66
+ """)
67
+ conn.commit()
68
 
69
+ def db_add_file(user_id, enc_path, orig_name, size):
70
+ cursor.execute(
71
+ "INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",
72
+ (user_id, enc_path, orig_name, size, time.time())
73
+ )
74
+ conn.commit()
75
 
76
+ def db_get_user_files(user_id):
77
+ cursor.execute("SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC", (user_id,))
78
+ return cursor.fetchall()
79
 
80
+ def db_remove_file(enc_path):
81
+ cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
82
+ conn.commit()
83
 
84
+ # --------------- FLASK HEALTH SERVER ---------------
85
+ web = Flask(__name__)
86
 
87
+ @web.route("/")
88
  def home():
89
+ return "Telegram HF Storage Bot Running"
90
 
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 ---------------
 
 
 
98
  app = Client(
99
+ "storage_bot",
100
  api_id=API_ID,
101
  api_hash=API_HASH,
102
  bot_token=BOT_TOKEN
103
  )
104
 
105
+ # --------------- ASYNC QUEUE & STATE ---------------
106
+ upload_queue = asyncio.Queue()
107
+ active_jobs = {}
108
 
109
+ # --------------- HELPERS ---------------
110
+
111
+ def cleanup(path: str):
112
  try:
113
+ if os.path.isdir(path):
114
+ shutil.rmtree(path, ignore_errors=True)
115
+ elif os.path.isfile(path):
116
+ os.remove(path)
117
+ except Exception:
118
  pass
119
 
120
+ def get_free_disk() -> int:
121
+ st = shutil.disk_usage("/")
122
+ return st.free
123
+
124
+ def format_size(bytes_val):
125
+ for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
126
+ if bytes_val < 1024.0:
127
+ return f"{bytes_val:.1f} {unit}"
128
+ bytes_val /= 1024.0
129
+ return f"{bytes_val:.1f} PB"
130
+
131
+ def format_speed(bytes_per_sec):
132
+ return f"{format_size(bytes_per_sec)}/s"
133
+
134
+ 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():
145
+ elapsed = max(time.time() - start_time, 0.01)
146
+ current = last_bytes[0]
147
+ speed = current / elapsed
148
+ text = ""
149
+ if total_bytes and total_bytes > 0:
150
+ pct = min(100 * current / total_bytes, 100)
151
+ text += f"{pct:.1f}% of {format_size(total_bytes)}\n"
152
+ text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"
153
+ text += f"Speed: {format_speed(speed)}\n"
154
+ if total_bytes and speed > 0:
155
+ eta = (total_bytes - current) / speed
156
+ text += f"ETA: {int(eta)}s"
157
+ try:
158
+ await status_msg.edit_text(
159
+ text,
160
+ reply_markup=InlineKeyboardMarkup([
161
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
162
+ ])
163
+ )
164
+ except Exception:
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
+
172
+ # --------------- UPLOAD JOB ---------------
173
+ 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}")]
181
+ ]))
182
+ local_path = await file_msg.download(file_name=os.path.join(temp_dir, orig_filename))
183
+ if cancel_event.is_set():
184
+ return
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
 
202
+ def sync_upload():
203
+ try:
204
+ hf.upload_file(
205
+ path_or_fileobj=local_path,
206
+ path_in_repo=repo_path,
207
+ repo_id=DATASET_REPO,
208
+ repo_type="dataset",
209
+ )
210
+ return True
211
+ except Exception as e:
212
+ raise e
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,
242
+ repo_id=DATASET_REPO,
243
+ repo_type="dataset",
244
+ )
245
+ except Exception:
246
+ pass
247
+ progress_task.cancel()
248
+ progress_sim.cancel()
249
+ await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
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()
257
 
258
+ # Record in database
259
+ db_add_file(user_id, repo_path, orig_filename, file_size)
 
 
260
 
261
+ await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
 
 
262
 
263
+ except Exception as e:
264
+ await status_msg.edit_text(f"❌ Upload failed: {e}", reply_markup=None)
265
+ finally:
266
+ cleanup(temp_dir)
267
 
268
+ # --------------- DOWNLOAD JOB ---------------
269
+ 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,
277
+ lambda: get_hf_file_metadata(
278
+ url=hf.get_hf_file_metadata_url(repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset"),
279
+ token=HF_TOKEN
280
+ )
 
 
 
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
  )
302
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
303
+ resp = requests.get(url, stream=True, headers=headers)
304
+ resp.raise_for_status()
305
+ with open(local_file, "wb") as f:
306
+ downloaded = 0
307
+ for chunk in resp.iter_content(chunk_size=8192):
308
+ if cancel_event.is_set():
309
+ break
310
+ f.write(chunk)
311
+ downloaded += len(chunk)
312
+ bytes_holder[0] = downloaded
313
+ return True
314
+ except Exception as e:
315
+ raise e
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
322
+ await asyncio.sleep(1)
323
 
324
+ if cancel_event.is_set():
325
+ progress_task.cancel()
326
+ await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)
327
+ return
328
 
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)
336
+ await app.send_document(chat_id, document=local_file, file_name=orig_name, caption=orig_name)
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):
344
+ if cancel_event.is_set():
345
+ await status_msg.edit_text("❌ Cancelled during send.")
346
+ return
347
+ chunk = f.read(part_size)
348
+ part_name = f"{orig_name}.part{i}of{num_parts}"
349
+ part_path = os.path.join(temp_dir, part_name)
350
+ with open(part_path, "wb") as p:
351
+ p.write(chunk)
352
+ await app.send_document(chat_id, document=part_path, file_name=part_name,
353
+ caption=f"{orig_name} – Part {i}/{num_parts}")
354
+ os.remove(part_path)
355
+ await status_msg.delete()
356
 
357
+ except Exception as e:
358
+ await status_msg.edit_text(f"❌ Download failed: {e}")
359
+ finally:
360
+ cleanup(temp_dir)
361
+
362
+ # --------------- QUEUE WORKER ---------------
363
+ async def upload_worker():
364
+ while True:
365
+ job = await upload_queue.get()
366
+ user_id, chat_id, file_msg, orig_filename, job_id = job
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
+
373
+ status_msg = await app.send_message(
374
+ chat_id, "⏳ Starting upload...",
375
+ reply_markup=InlineKeyboardMarkup([
376
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
377
+ ])
378
+ )
379
+ active_jobs[job_id]["status_msg"] = status_msg
380
 
381
+ try:
382
+ await do_upload_job(user_id, chat_id, file_msg, orig_filename, job_id, cancel_event, status_msg)
383
+ finally:
384
+ active_jobs.pop(job_id, None)
385
+ upload_queue.task_done()
386
 
387
+ # --------------- BOT HANDLERS ---------------
388
+ @app.on_message(filters.command("start"))
389
+ async def start_cmd(_, message):
390
+ await message.reply_text(
391
+ "Send me a file to upload it to the dataset.\n"
392
+ "/files – list your uploaded files"
393
+ )
 
 
 
 
394
 
395
+ @app.on_message(filters.command("files"))
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)
410
+ except Exception:
411
+ orig_name = enc_name
412
+ try:
413
+ meta = get_hf_file_metadata(
414
+ url=hf.get_hf_file_metadata_url(repo_id=DATASET_REPO, filename=path, repo_type="dataset"),
415
+ token=HF_TOKEN
416
+ )
417
+ size = meta.size
418
+ except Exception:
419
+ size = 0
420
+ db_add_file(user_id, path, orig_name, size)
421
+ user_files = db_get_user_files(user_id)
422
+ except Exception:
423
+ pass
424
 
425
+ if not user_files:
426
+ return await message.reply_text("You have no uploaded files.")
427
 
428
+ buttons = []
429
+ for enc_path, orig_name, _ in user_files:
430
+ buttons.append([InlineKeyboardButton(orig_name[:60], callback_data=f"get:{enc_path}")])
431
 
432
+ await message.reply_text(
433
+ "Your uploaded files:",
434
+ reply_markup=InlineKeyboardMarkup(buttons)
435
+ )
436
 
437
+ @app.on_callback_query(filters.regex("^get:"))
438
+ async def get_file_callback(_, query):
439
+ enc_path = query.data.replace("get:", "")
440
+ job_id = int(time.time() * 1000)
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...",
453
+ reply_markup=InlineKeyboardMarkup([
454
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
455
+ ])
456
+ )
457
+ active_jobs[job_id]["status_msg"] = status_msg
458
+
459
+ asyncio.create_task(do_download_job(
460
+ query.message.chat.id,
461
+ enc_path,
462
+ orig_name,
463
+ job_id,
464
+ cancel_event,
465
+ status_msg
466
+ ))
467
+
468
+ @app.on_callback_query(filters.regex("^cancel_job:"))
469
+ async def cancel_job_callback(_, query):
470
+ _, job_id_str = query.data.split(":")
471
+ job_id = int(job_id_str)
472
+ if job_id in active_jobs:
473
+ active_jobs[job_id]["cancel_event"].set()
474
+ await query.answer("Cancelling...")
475
+ else:
476
+ await query.answer("Job not found.")
477
+
478
+ @app.on_callback_query(filters.regex("^upload:"))
479
+ async def upload_callback(_, query):
480
+ _, user_id_str, msg_id_str, orig_filename = query.data.split(":", 3)
481
+ user_id = int(user_id_str)
482
+ chat_id = query.message.chat.id
483
 
484
+ try:
485
+ file_msg = await app.get_messages(chat_id, int(msg_id_str))
486
+ except Exception:
487
+ return await query.answer("Original message missing.", show_alert=True)
488
 
489
+ if not file_msg:
490
+ return await query.answer("File no longer available.", show_alert=True)
491
 
492
+ job_id = int(time.time() * 1000)
493
+ active_jobs[job_id] = {"status": "queued"}
 
 
 
 
 
 
 
 
 
 
 
 
494
 
495
+ await upload_queue.put((user_id, chat_id, file_msg, orig_filename, job_id))
496
 
497
+ await query.message.edit_text(
498
+ f"📦 `{orig_filename}` added to upload queue.\nYou'll be notified when it starts.",
499
+ reply_markup=None
500
+ )
501
 
502
+ @app.on_callback_query(filters.regex("^cancel_upload:"))
503
+ async def cancel_upload_prompt(_, query):
504
+ await query.message.delete()
505
+
506
+ @app.on_message(filters.document | filters.video | filters.audio | filters.photo)
507
+ async def on_file(_, message):
508
+ if message.document:
509
+ filename = message.document.file_name
510
+ elif message.video:
511
+ filename = message.video.file_name or f"{message.video.file_unique_id}.mp4"
512
+ elif message.audio:
513
+ filename = message.audio.file_name or f"{message.audio.file_unique_id}.mp3"
514
+ else:
515
+ filename = f"{message.photo.file_unique_id}.jpg"
516
+
517
+ kb = InlineKeyboardMarkup([
518
+ [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{message.from_user.id}:{message.id}:{filename}")],
519
+ [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")]
520
+ ])
521
+
522
+ await message.reply_text(
523
+ f"Do you want to upload `{filename}`?",
524
+ reply_markup=kb
525
+ )
526
 
527
+ # --------------- KEEPALIVE ---------------
528
+ def keepalive():
529
+ while True:
530
+ try:
531
+ requests.get("http://localhost:7860/", timeout=10)
532
+ except Exception:
533
+ pass
534
+ time.sleep(KEEPALIVE_INTERVAL)
535
+
536
+ # --------------- MAIN ---------------
537
+ async def main():
538
+ asyncio.create_task(upload_worker())
539
+ await app.start()
540
+ print("Bot started")
541
+ await asyncio.Event().wait()
542
 
543
  if __name__ == "__main__":
 
 
544
  threading.Thread(target=run_web, daemon=True).start()
545
+ threading.Thread(target=keepalive, daemon=True).start()
546
+ app.run(main())