Cxops commited on
Commit
35e8395
·
verified ·
1 Parent(s): 156da6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -1190
app.py CHANGED
@@ -1,186 +1,61 @@
1
- import os, re, sys, time, base64, hashlib, shutil, logging, secrets, sqlite3, tempfile, threading, asyncio
2
- from pathlib import Path
3
- from typing import Optional, List, Tuple, Union, Set
 
4
 
5
- import requests
6
  from flask import Flask
7
- from pyrogram import Client, filters
8
- from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery
9
- from huggingface_hub import HfApi, get_hf_file_metadata, hf_hub_download, hf_hub_url
10
- from cryptography.hazmat.primitives.ciphers.aead import AESSIV
11
-
12
- # Force tgCrypto for maximum Telegram speed
13
- try:
14
- import tgcrypto # noqa: F401
15
- except ImportError:
16
- print("❌ tgCrypto is NOT installed! Install it with: pip install tgCrypto")
17
- sys.exit(1)
18
-
19
- # Optional uvloop
20
- try:
21
- import uvloop
22
- UVLOOP_AVAILABLE = True
23
- except ImportError:
24
- UVLOOP_AVAILABLE = False
25
-
26
- # =============================================================================
27
- # CONFIGURATION
28
- # =============================================================================
29
-
30
- API_ID: int = int(os.environ["API_ID"])
31
- API_HASH: str = os.environ["API_HASH"]
32
- BOT_TOKEN: str = os.environ["BOT_TOKEN"]
33
- HF_TOKEN: str = os.environ["HF_TOKEN"]
34
- OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
35
-
36
- SPACE_HOST: str = "https://Cxops-Push.hf.space"
37
- DATASET_REPO: str = "Cxops/Bzxv"
38
- DATASET_TYPE: str = "dataset"
39
- MAX_FILE_SIZE_TG: int = 1900 * 1024 * 1024 # 1900 MB
40
- MAX_SINGLE_FILE_SIZE: int = 45 * 1024**3 # 45 GB
41
- MIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024 # 45 GB
42
- DATASET_MAX_SIZE: int = int(8.7 * 1024**4) # 8.7 TB
43
- KEEPALIVE_INTERVAL: int = 300 # 5 minutes
44
- UPLOAD_TIMEOUT: int = 7200 # 2 hours
45
- DB_PATH: str = "bot_files.db"
46
-
47
- logging.basicConfig(
48
- level=logging.INFO,
49
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
50
- handlers=[logging.StreamHandler(sys.stdout)],
51
- )
52
- logger = logging.getLogger("StorageBot")
53
-
54
- # =============================================================================
55
- # DETERMINISTIC ENCRYPTION (AES‑SIV)
56
- # =============================================================================
57
-
58
- _siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
59
- _aes_siv = AESSIV(_siv_key)
60
-
61
- def encrypt_text(plain: str) -> str:
62
- token = _aes_siv.encrypt(plain.encode(), None)
63
- return base64.urlsafe_b64encode(token).decode().rstrip("=")
64
-
65
- def decrypt_text(encoded: str) -> str:
66
- padding = 4 - len(encoded) % 4
67
- if padding != 4:
68
- encoded += "=" * padding
69
- token = base64.urlsafe_b64decode(encoded.encode())
70
- return _aes_siv.decrypt(token, None).decode()
71
-
72
- def get_encrypted_folder(user_id: int) -> str:
73
- return encrypt_text(str(user_id))
74
-
75
- def get_encrypted_filename(original: str) -> str:
76
- return encrypt_text(original)
77
 
78
- # =============================================================================
79
- # DATABASE
80
- # =============================================================================
81
-
82
- conn = sqlite3.connect(DB_PATH, check_same_thread=False)
83
- conn.row_factory = sqlite3.Row
84
- conn.execute("PRAGMA journal_mode=WAL")
85
- cursor = conn.cursor()
86
- cursor.execute("""
87
- CREATE TABLE IF NOT EXISTS files (
88
- user_id INTEGER,
89
- enc_path TEXT UNIQUE,
90
- orig_name TEXT,
91
- size INTEGER,
92
- timestamp REAL
93
- )
94
- """)
95
- conn.commit()
96
-
97
- def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:
98
- cursor.execute(
99
- "INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",
100
- (user_id, enc_path, orig_name, size, time.time()),
101
- )
102
- conn.commit()
103
-
104
- def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:
105
- cursor.execute(
106
- "SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC",
107
- (user_id,),
108
- )
109
- return [(row[0], row[1], row[2]) for row in cursor.fetchall()]
110
-
111
- def db_remove_file(enc_path: str) -> None:
112
- cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
113
- conn.commit()
114
-
115
- def db_remove_all_user_files(user_id: int) -> None:
116
- cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
117
- conn.commit()
118
 
119
- def db_file_exists(user_id: int, orig_name: str, size: Optional[int] = None) -> Optional[Tuple[str, int]]:
120
- if size is not None:
121
- cursor.execute(
122
- "SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ? AND size = ?",
123
- (user_id, orig_name, size),
124
- )
125
- else:
126
- cursor.execute(
127
- "SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ?",
128
- (user_id, orig_name),
129
- )
130
- row = cursor.fetchone()
131
- return (row[0], row[1]) if row else None
132
 
133
- # =============================================================================
134
- # IN‑MEMORY STORES
135
- # =============================================================================
136
 
137
- file_callback_map: dict[str, str] = {}
138
- upload_prompt_map: dict[str, List[Tuple]] = {}
139
- album_groups: dict[str, dict] = {}
140
- duplicate_prompt_map: dict[str, dict] = {}
141
 
142
- def make_token() -> str:
143
- return secrets.token_hex(8)
144
 
145
- # =============================================================================
146
- # FLASK HEALTH CHECK
147
- # =============================================================================
148
 
149
  web = Flask(__name__)
150
 
151
  @web.route("/")
152
  def home():
153
- return "Status: OK - Bot Running"
154
 
155
  def run_web():
156
  web.run(host="0.0.0.0", port=7860)
157
 
158
- # =============================================================================
159
- # HUGGING FACE & PYROGRAM
160
- # =============================================================================
161
 
162
  hf = HfApi(token=HF_TOKEN)
163
 
 
 
 
 
164
  app = Client(
165
  "storage_bot",
166
  api_id=API_ID,
167
  api_hash=API_HASH,
168
- bot_token=BOT_TOKEN,
169
  )
170
 
171
- # =============================================================================
172
- # GLOBAL STATE
173
- # =============================================================================
174
-
175
- upload_queue: asyncio.Queue = asyncio.Queue()
176
- active_jobs: dict[int, dict] = {}
177
- bot_start_time = time.time()
178
 
179
- # =============================================================================
180
- # UTILITY HELPERS
181
- # =============================================================================
182
-
183
- def cleanup(path: str) -> None:
184
  try:
185
  if os.path.isdir(path):
186
  shutil.rmtree(path, ignore_errors=True)
@@ -189,1094 +64,187 @@ def cleanup(path: str) -> None:
189
  except Exception:
190
  pass
191
 
192
- def get_free_disk() -> int:
193
- return shutil.disk_usage("/").free
194
-
195
- def format_size(bytes_val: int) -> str:
196
- for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
197
- if bytes_val < 1024.0:
198
- return f"{bytes_val:.1f} {unit}"
199
- bytes_val /= 1024.0
200
- return f"{bytes_val:.1f} PB"
201
-
202
- def format_speed(bytes_per_sec: float) -> str:
203
- return f"{format_size(bytes_per_sec)}/s"
204
-
205
- def get_total_memory() -> int:
206
- try:
207
- with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
208
- limit = int(f.read().strip())
209
- if limit < 9_223_372_036_854_771_200:
210
- return limit
211
- except Exception:
212
- pass
213
- try:
214
- with open("/proc/meminfo") as f:
215
- for line in f:
216
- if line.startswith("MemTotal:"):
217
- return int(line.split()[1]) * 1024
218
- except Exception:
219
- pass
220
- return 0
221
-
222
- def extract_file_size(msg: Message) -> Optional[int]:
223
- if msg.document:
224
- return msg.document.file_size
225
- if msg.video:
226
- return msg.video.file_size
227
- if msg.audio:
228
- return msg.audio.file_size
229
- if msg.photo:
230
- return msg.photo.file_size
231
- if msg.animation:
232
- return msg.animation.file_size
233
- if msg.sticker:
234
- return msg.sticker.file_size
235
- if msg.video_note:
236
- return msg.video_note.file_size
237
- if msg.voice:
238
- return msg.voice.file_size
239
- return None
240
-
241
- def check_file_size_limit(filename: str, size: Optional[int]) -> Optional[str]:
242
- if size is not None and size > MAX_SINGLE_FILE_SIZE:
243
- return f"❌ File `{filename}` is too large ({format_size(size)}). Maximum allowed is {format_size(MAX_SINGLE_FILE_SIZE)}."
244
- return None
245
-
246
- async def send_progress_updater(
247
- job_id: int,
248
- status_msg: Message,
249
- cancel_event: asyncio.Event,
250
- total_bytes: int,
251
- ) -> Tuple[asyncio.Task, list]:
252
- bytes_holder = [0]
253
- start_time = time.time()
254
 
255
- async def updater():
256
- while not cancel_event.is_set():
257
- elapsed = max(time.time() - start_time, 0.01)
258
- current = bytes_holder[0]
259
- speed = current / elapsed
260
- text = "📤 Sending to Telegram...\n"
261
- if total_bytes > 0:
262
- pct = (100 * current / total_bytes)
263
- text += f"{pct:.1f}% of {format_size(total_bytes)}\n"
264
- text += f"{format_size(current)} sent / {format_size(total_bytes)}\n"
265
- else:
266
- text += f"{format_size(current)} sent\n"
267
- text += f"Speed: {format_speed(speed)}\n"
268
- if total_bytes > 0 and speed > 0:
269
- eta = int((total_bytes - current) / speed)
270
- text += f"ETA: {eta}s"
271
- else:
272
- text += "ETA: ..."
273
- try:
274
- await status_msg.edit_text(
275
- text,
276
- reply_markup=InlineKeyboardMarkup(
277
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
278
- ),
279
- )
280
- except Exception:
281
- break
282
- await asyncio.sleep(3)
283
-
284
- task = asyncio.create_task(updater())
285
- return task, bytes_holder
286
 
287
- # =============================================================================
288
- # CORE UPLOAD / DOWNLOAD LOGIC (FIXED – NO PROGRESS CALLBACK DURING DOWNLOAD)
289
- # =============================================================================
290
 
291
- async def do_upload_job(
292
- user_id: int,
293
- chat_id: int,
294
- file_msg_or_id: Union[Message, str],
295
- orig_filename: str,
296
- job_id: int,
297
- cancel_event: asyncio.Event,
298
- status_msg: Message,
299
- file_id: Optional[str] = None,
300
- expected_size: Optional[int] = None,
301
- ) -> None:
302
- temp_dir = tempfile.mkdtemp()
303
- active_jobs[job_id]["temp_dir"] = temp_dir
304
- local_path = None
305
- orig_filename = os.path.basename(orig_filename)
306
  try:
307
- await status_msg.edit_text(
308
- "⬇️ Downloading from Telegram...",
309
- reply_markup=InlineKeyboardMarkup(
310
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
311
- ),
312
  )
313
 
314
- # ✅ Download without progress callback – prevents thread‑safety errors
315
- local_path = await app.download_media(
316
- file_msg_or_id,
317
- file_name=os.path.join(temp_dir, orig_filename),
318
- )
319
 
320
- if cancel_event.is_set():
321
- await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
322
- return
323
-
324
- file_size = os.path.getsize(local_path)
325
-
326
- enc_folder = get_encrypted_folder(user_id)
327
- enc_filename = get_encrypted_filename(orig_filename)
328
- repo_path = f"{enc_folder}/{enc_filename}"
329
-
330
- await status_msg.edit_text(
331
- "⬆️ Uploading to Hugging Face...",
332
- reply_markup=InlineKeyboardMarkup(
333
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
334
- ),
335
- )
336
-
337
- loop = asyncio.get_event_loop()
338
- def sync_upload():
339
- hf.upload_file(
340
- path_or_fileobj=local_path,
341
- path_in_repo=repo_path,
342
- repo_id=DATASET_REPO,
343
- repo_type=DATASET_TYPE,
344
  )
345
 
346
- task = loop.run_in_executor(None, sync_upload)
347
- try:
348
- await asyncio.wait_for(asyncio.wrap_future(task), timeout=UPLOAD_TIMEOUT)
349
- except asyncio.TimeoutError:
350
- await status_msg.edit_text("❌ Upload timed out.", reply_markup=None)
351
- return
352
-
353
- if cancel_event.is_set():
354
- try:
355
- hf.delete_file(path_in_repo=repo_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
356
- except Exception:
357
- pass
358
- await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
359
- return
360
-
361
- db_add_file(user_id, repo_path, orig_filename, file_size)
362
- await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)
363
- logger.info("Uploaded %s for user %d", orig_filename, user_id)
364
-
365
- except Exception as e:
366
- logger.exception("Upload failed for %s", orig_filename)
367
- await status_msg.edit_text(f"❌ Upload failed: {e}", reply_markup=None)
368
- finally:
369
- cleanup(temp_dir)
370
-
371
-
372
- async def do_download_job(
373
- chat_id: int,
374
- enc_path: str,
375
- orig_name: str,
376
- job_id: int,
377
- cancel_event: asyncio.Event,
378
- status_msg: Message,
379
- ) -> None:
380
- temp_dir = tempfile.mkdtemp()
381
- active_jobs[job_id]["temp_dir"] = temp_dir
382
- try:
383
- loop = asyncio.get_event_loop()
384
-
385
- await status_msg.edit_text(
386
- "⬇️ Downloading from dataset...",
387
- reply_markup=InlineKeyboardMarkup(
388
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
389
- ),
390
- )
391
-
392
- download_future = loop.run_in_executor(
393
- None,
394
- lambda: hf_hub_download(
395
- repo_id=DATASET_REPO,
396
- filename=enc_path,
397
- repo_type=DATASET_TYPE,
398
- token=HF_TOKEN,
399
- local_dir=temp_dir,
400
- resume_download=True,
401
- ),
402
- )
403
 
404
- while not download_future.done():
405
- if cancel_event.is_set():
406
- await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)
407
- return
408
- await asyncio.sleep(1)
409
 
410
- local_file = download_future.result()
411
- total_size = os.path.getsize(local_file)
412
-
413
- if total_size <= MAX_FILE_SIZE_TG:
414
- prog_task, bytes_holder = await send_progress_updater(
415
- job_id, status_msg, cancel_event, total_size
416
- )
417
-
418
- def send_progress(current, total):
419
- bytes_holder[0] = current
420
-
421
- await app.send_document(
422
- chat_id,
423
- document=local_file,
424
- file_name=orig_name,
425
- caption=orig_name,
426
- progress=send_progress,
427
- )
428
- prog_task.cancel()
429
- if cancel_event.is_set():
430
- await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)
431
- else:
432
- await status_msg.delete()
433
- else:
434
- part_size = MAX_FILE_SIZE_TG
435
- num_parts = -(-total_size // part_size)
436
- with open(local_file, "rb") as f:
437
- for i in range(1, num_parts + 1):
438
- if cancel_event.is_set():
439
- await status_msg.edit_text("❌ Cancelled during send.", reply_markup=None)
440
- break
441
- await status_msg.edit_text(
442
- f"📤 Sending part {i}/{num_parts}...",
443
- reply_markup=InlineKeyboardMarkup(
444
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
445
- ),
446
- )
447
- part_name = f"{orig_name}.part{i}of{num_parts}"
448
- part_path = os.path.join(temp_dir, part_name)
449
- with open(part_path, "wb") as p:
450
- bytes_written = 0
451
- while bytes_written < part_size:
452
- buf = f.read(min(1024 * 1024, part_size - bytes_written))
453
- if not buf:
454
- break
455
- p.write(buf)
456
- bytes_written += len(buf)
457
- await app.send_document(
458
- chat_id,
459
- document=part_path,
460
- file_name=part_name,
461
- caption=f"{orig_name} – Part {i}/{num_parts}",
462
  )
463
- os.remove(part_path)
464
- if not cancel_event.is_set():
465
- await status_msg.delete()
466
- logger.info("Downloaded %s for chat %d", orig_name, chat_id)
467
-
468
- except Exception as e:
469
- logger.exception("Download failed for %s", orig_name)
470
- await status_msg.edit_text(f"❌ Download failed: {e}")
471
- finally:
472
- cleanup(temp_dir)
473
-
474
 
475
- # =============================================================================
476
- # DELETION HELPERS
477
- # =============================================================================
 
478
 
479
- async def delete_user_file(chat_id, user_id, enc_path, token, query: CallbackQuery):
480
- try:
481
- hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
482
- db_remove_file(enc_path)
483
- file_callback_map.pop(token, None)
484
- await query.answer("File deleted.", show_alert=True)
485
- await refresh_file_list(chat_id, user_id, query.message)
486
  except Exception as e:
487
- await query.answer(f"Error: {e}", show_alert=True)
488
-
489
-
490
- async def delete_all_user_files(chat_id, user_id, query: CallbackQuery):
491
- user_files = db_get_user_files(user_id)
492
- if not user_files:
493
- await query.answer("No files to delete.", show_alert=True)
494
- return
495
-
496
- for enc_path, _, _ in user_files:
497
- try:
498
- hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
499
- except Exception:
500
- pass
501
-
502
- db_remove_all_user_files(user_id)
503
- tokens_to_delete = [tok for tok, path in file_callback_map.items() if path.startswith(get_encrypted_folder(user_id))]
504
- for tok in tokens_to_delete:
505
- file_callback_map.pop(tok, None)
506
-
507
- await query.answer(f"Deleted {len(user_files)} file(s).", show_alert=True)
508
- await refresh_file_list(chat_id, user_id, query.message)
509
-
510
-
511
- async def refresh_file_list(chat_id: int, user_id: int, message: Message):
512
- user_files = db_get_user_files(user_id)
513
- if not user_files:
514
- return await message.edit_text("You have no uploaded files.", reply_markup=None)
515
-
516
- buttons = []
517
- for enc_path, orig_name, size in user_files:
518
- token = make_token()
519
- file_callback_map[token] = enc_path
520
- display = f"{orig_name[:25]} ({format_size(size)})" if size else orig_name[:25]
521
- buttons.append([
522
- InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),
523
- InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
524
- ])
525
- buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
526
-
527
- await message.edit_text(
528
- "Your uploaded files (click to download, delete to remove):",
529
- reply_markup=InlineKeyboardMarkup(buttons),
530
- )
531
 
 
 
 
532
 
533
- # =============================================================================
534
- # DUPLICATE DETECTION & HANDLING
535
- # =============================================================================
536
 
537
- def check_duplicate(user_id: int, orig_name: str) -> Optional[int]:
538
- # Check local DB first
539
- row = db_file_exists(user_id, orig_name)
540
- if row:
541
- return row[1] # size
542
 
543
- # Check HF dataset
544
- enc_folder = get_encrypted_folder(user_id)
545
- enc_filename = get_encrypted_filename(orig_name)
546
- enc_path = f"{enc_folder}/{enc_filename}"
547
  try:
548
- if hf.file_exists(repo_id=DATASET_REPO, filename=enc_path, repo_type=DATASET_TYPE):
549
- # Add to DB with placeholder size (will be updated on next /files)
550
- db_add_file(user_id, enc_path, orig_name, 0)
551
- return 0
552
- except Exception as e:
553
- logger.warning("HF duplicate check failed: %s", e)
554
- return None
555
-
556
-
557
- def generate_unique_filename(user_id: int, base: str, ext: str, reserved: Optional[Set[str]] = None) -> str:
558
- counter = 1
559
- while True:
560
- candidate = f"{base}_{counter}{ext}"
561
- if reserved and candidate in reserved:
562
- counter += 1
563
- continue
564
- if not db_file_exists(user_id, candidate):
565
- return candidate
566
- counter += 1
567
-
568
-
569
- async def handle_duplicate(
570
- user_id: int,
571
- chat_id: int,
572
- file_obj: Union[Message, str],
573
- orig_filename: str,
574
- expected_size: Optional[int],
575
- existing_size: int,
576
- file_id: Optional[str] = None,
577
- msg_id: Optional[int] = None,
578
- reserved_names: Optional[Set[str]] = None,
579
- ):
580
- if expected_size is not None and existing_size != expected_size:
581
- # Different size → auto‑rename
582
- base, ext = os.path.splitext(orig_filename)
583
- new_name = generate_unique_filename(user_id, base, ext, reserved_names)
584
- if reserved_names is not None:
585
- reserved_names.add(new_name)
586
- job_id = int(time.time() * 1000 + hash(new_name))
587
- cancel_event = asyncio.Event()
588
- active_jobs[job_id] = {"status": "queued", "cancel_event": cancel_event}
589
- await upload_queue.put((user_id, chat_id, file_obj, new_name, job_id, file_id, expected_size, cancel_event))
590
- await app.send_message(
591
- chat_id,
592
- f"ℹ️ File `{orig_filename}` already exists with a different size. "
593
- f"Uploading as `{new_name}`."
594
- )
595
- else:
596
- # Same size → prompt user
597
- token = secrets.token_hex(8)
598
- duplicate_prompt_map[token] = {
599
- 'user_id': user_id,
600
- 'chat_id': chat_id,
601
- 'file_obj': file_obj,
602
- 'orig_filename': orig_filename,
603
- 'job_id': int(time.time() * 1000 + hash(orig_filename)),
604
- 'file_id': file_id,
605
- 'expected_size': expected_size,
606
- 'existing_size': existing_size,
607
- 'msg_id': msg_id,
608
- }
609
- size_note = f" ({format_size(expected_size)})" if expected_size else ""
610
- kb = InlineKeyboardMarkup([
611
- [InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
612
- [InlineKeyboardButton("📤 Upload (rename)", callback_data=f"dup_keep:{token}")],
613
- ])
614
- await app.send_message(
615
- chat_id,
616
- f"⚠️ File `{orig_filename}` already exists{size_note}.\nWhat do you want to do?",
617
- reply_markup=kb,
618
  )
619
 
620
-
621
- # =============================================================================
622
- # ALBUM GROUPING
623
- # =============================================================================
624
-
625
- async def process_album_group(media_group_id: str):
626
- group_data = album_groups.pop(media_group_id, None)
627
- if not group_data:
628
- return
629
- chat_id = group_data['chat_id']
630
- user_id = group_data['user_id']
631
- messages = group_data['messages']
632
-
633
- valid_files = []
634
- skipped_names = []
635
- for msg_id, filename, file_id, size in messages:
636
- limit_msg = check_file_size_limit(filename, size)
637
- if limit_msg:
638
- skipped_names.append(filename)
639
- else:
640
- valid_files.append((msg_id, filename, file_id, size))
641
-
642
- if not valid_files:
643
- if skipped_names:
644
- skip_text = "\n".join(f"• `{f}`" for f in skipped_names)
645
- await app.send_message(chat_id,
646
- f"❌ All files exceed the {format_size(MAX_SINGLE_FILE_SIZE)} limit and were skipped:\n{skip_text}")
647
- return
648
-
649
- reserved_names: Set[str] = set()
650
- non_dup = []
651
-
652
- for msg_id, filename, file_id, size in valid_files:
653
- existing_size = check_duplicate(user_id, filename)
654
- if existing_size is not None:
655
- try:
656
- file_msg = await app.get_messages(chat_id, msg_id)
657
- except Exception:
658
- file_msg = None
659
- await handle_duplicate(
660
- user_id, chat_id,
661
- file_obj=file_msg if file_msg else file_id,
662
- orig_filename=filename,
663
- expected_size=size,
664
- existing_size=existing_size,
665
- file_id=file_id,
666
- msg_id=msg_id,
667
- reserved_names=reserved_names,
668
- )
669
- else:
670
- non_dup.append((msg_id, filename, file_id, size))
671
-
672
- if non_dup:
673
- if len(non_dup) == 1:
674
- msg_id, filename, file_id, _ = non_dup[0]
675
- token = make_token()
676
- upload_prompt_map[token] = [(user_id, msg_id, filename, file_id)]
677
- kb = InlineKeyboardMarkup([
678
- [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
679
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
680
- ])
681
- await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
682
- else:
683
- files_list = "\n".join(f"• {fname} ({format_size(fsize)})" for _, fname, _, fsize in non_dup)
684
- token = make_token()
685
- upload_prompt_map[token] = [(user_id, msg_id, fname, fid) for msg_id, fname, fid, _ in non_dup]
686
-
687
- button_rows = [
688
- [InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")]
689
- ]
690
- for msg_id, fname, fid, _ in non_dup:
691
- individual_token = make_token()
692
- upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]
693
- button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
694
- button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])
695
-
696
- prompt_text = f"Received {len(non_dup)} non‑duplicate files.\n{files_list}\n\nChoose:"
697
- if skipped_names:
698
- prompt_text += f"\n⚠️ Skipped (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names)
699
- await app.send_message(chat_id, prompt_text, reply_markup=InlineKeyboardMarkup(button_rows))
700
-
701
- if skipped_names and not non_dup:
702
- await app.send_message(chat_id, f"⚠️ Skipped {len(skipped_names)} file(s) (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names))
703
-
704
-
705
- # =============================================================================
706
- # UPLOAD QUEUE WORKER
707
- # =============================================================================
708
-
709
- async def upload_worker():
710
- while True:
711
- user_id, chat_id, file_obj, orig_filename, job_id, file_id, expected_size, cancel_event = await upload_queue.get()
712
- if cancel_event.is_set():
713
- upload_queue.task_done()
714
- continue
715
-
716
- active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}
717
-
718
- while get_free_disk() < MIN_FREE_DISK:
719
- logger.warning("Low disk space – pausing uploads")
720
- await asyncio.sleep(10)
721
-
722
- status_msg = await app.send_message(
723
- chat_id,
724
- "⏳ Starting upload...",
725
- reply_markup=InlineKeyboardMarkup(
726
- [[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]
727
- ),
728
  )
729
- active_jobs[job_id]["status_msg"] = status_msg
730
-
731
- try:
732
- await do_upload_job(user_id, chat_id, file_obj, orig_filename, job_id, cancel_event, status_msg, file_id, expected_size)
733
- finally:
734
- active_jobs.pop(job_id, None)
735
- upload_queue.task_done()
736
-
737
-
738
- # =============================================================================
739
- # BOT COMMAND HANDLERS
740
- # =============================================================================
741
-
742
- @app.on_message(filters.command("start"))
743
- async def cmd_start(_, message: Message):
744
- await message.reply_text(
745
- "👋 **Welcome to the Storage Bot!**\n\n"
746
- "Send me any file or a Telegram message link to upload it to our cloud dataset.\n"
747
- "Use /help for a full command list.\n\n"
748
- "Type /cancelall to stop all running uploads instantly."
749
- )
750
-
751
- @app.on_message(filters.command("help"))
752
- async def cmd_help(_, message: Message):
753
- text = (
754
- "**Available Commands:**\n\n"
755
- "/start – Welcome message\n"
756
- "/files – List your uploaded files (download/delete)\n"
757
- "/status – System & dataset space\n"
758
- "/delete_all – Delete all your files (confirmation)\n"
759
- "/upload <link> – Upload a file from a Telegram message link instantly\n"
760
- "/cancelall – Cancel every active upload / download job\n"
761
- "/help – This help\n\n"
762
- "**Duplicate handling:**\n"
763
- "• Same name, different size → automatically renamed with _1, _2 ... and uploaded.\n"
764
- "• Same name, same size → you get a Skip / Upload (rename) choice.\n"
765
- "**Speed:** tgCrypto enforced, maximum possible throughput."
766
- )
767
- await message.reply_text(text, disable_web_page_preview=True)
768
 
769
- @app.on_message(filters.command("status"))
770
- async def cmd_status(_, message: Message):
771
- free = get_free_disk()
772
- disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"
773
-
774
- try:
775
- info = hf.dataset_info(repo_id=DATASET_REPO)
776
- used = info.used_storage or 0
777
- except Exception as e:
778
- logger.warning("Failed to fetch dataset info: %s", e)
779
- used = 0
780
- dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"
781
-
782
- uptime_sec = int(time.time() - bot_start_time)
783
- uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"
784
-
785
- mem_text = f"🧠 Memory: {format_size(get_total_memory())}"
786
- cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"
787
-
788
- status_msg = f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}\n{cpu_text}"
789
- await message.reply_text(status_msg)
790
-
791
- @app.on_message(filters.command("files"))
792
- async def cmd_files(_, message: Message):
793
- user_id = message.from_user.id
794
- user_files = db_get_user_files(user_id)
795
- if not user_files:
796
- enc_folder = get_encrypted_folder(user_id)
797
- try:
798
- all_hf = hf.list_repo_files(repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
799
- hf_user_files = [f for f in all_hf if f.startswith(enc_folder + "/")]
800
- for path in hf_user_files:
801
- _, enc_name = path.split("/", 1)
802
- try:
803
- orig_name = decrypt_text(enc_name)
804
- except Exception:
805
- orig_name = enc_name
806
- try:
807
- file_url = hf_hub_url(repo_id=DATASET_REPO, filename=path, repo_type=DATASET_TYPE)
808
- meta = get_hf_file_metadata(url=file_url, token=HF_TOKEN)
809
- size = meta.size
810
- except Exception:
811
- size = 0
812
- db_add_file(user_id, path, orig_name, size)
813
- user_files = db_get_user_files(user_id)
814
- except Exception as e:
815
- logger.warning("Fallback scan failed: %s", e)
816
- if not user_files:
817
- return await message.reply_text("You have no uploaded files.")
818
- buttons = []
819
- for enc_path, orig_name, size in user_files:
820
- token = make_token()
821
- file_callback_map[token] = enc_path
822
- display = f"{orig_name[:20]} ({format_size(size)})" if size else orig_name[:20]
823
- buttons.append([
824
- InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),
825
- InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),
826
- ])
827
- buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
828
- await message.reply_text(
829
- "Your uploaded files (click to download, delete to remove):",
830
- reply_markup=InlineKeyboardMarkup(buttons),
831
- disable_web_page_preview=True,
832
- )
833
-
834
- @app.on_message(filters.command("delete_all"))
835
- async def cmd_delete_all(_, message: Message):
836
- user_id = message.from_user.id
837
- kb = InlineKeyboardMarkup([
838
- [InlineKeyboardButton("Yes, delete all my files", callback_data=f"delete_all:{user_id}")],
839
- [InlineKeyboardButton("Cancel", callback_data="cancel_upload:0")],
840
- ])
841
- await message.reply_text("⚠️ Permanently delete **all** your files? This cannot be undone.", reply_markup=kb)
842
 
843
- @app.on_message(filters.command("cancelall"))
844
- async def cmd_cancel_all(_, message: Message):
845
- cancelled = 0
846
- for job_id, job in list(active_jobs.items()):
847
- if "cancel_event" in job:
848
- job["cancel_event"].set()
849
- cancelled += 1
850
  try:
851
- if "status_msg" in job:
852
- await job["status_msg"].delete()
853
  except Exception:
854
  pass
855
- while not upload_queue.empty():
856
- upload_queue.get_nowait()
857
- upload_queue.task_done()
858
- await message.reply_text(f"❌ Cancelled {cancelled} active job(s) and cleared the queue.")
859
 
860
- @app.on_message(filters.command("upload"))
861
- async def cmd_upload(_, message: Message):
862
- args = message.text.split(maxsplit=1)
863
- if len(args) < 2:
864
- return await message.reply_text("Usage: /upload <link>")
865
- link = args[1].strip()
866
- match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)
867
- if not match:
868
- return await message.reply_text("Invalid Telegram message link.")
869
- chat_str, msg_id = match.group(2), int(match.group(3))
870
- try:
871
- if chat_str.startswith("c/"):
872
- chat_id = int("-100" + chat_str[2:])
873
- else:
874
- chat_id = chat_str
875
- msg = await app.get_messages(chat_id, msg_id)
876
  except Exception as e:
877
- return await message.reply_text(f"❌ Could not fetch the message: {e}")
878
- if not msg.media:
879
- return await message.reply_text("The linked message doesn't contain a downloadable file.")
880
- file_id, expected_size, filename = _extract_file_info(msg)
881
- if not filename:
882
- return await message.reply_text("Could not determine file name.")
883
-
884
- limit_err = check_file_size_limit(filename, expected_size)
885
- if limit_err:
886
- return await message.reply_text(limit_err)
887
-
888
- existing_size = check_duplicate(message.from_user.id, filename)
889
- if existing_size is not None:
890
- await handle_duplicate(
891
- user_id=message.from_user.id,
892
- chat_id=message.chat.id,
893
- file_obj=file_id,
894
- orig_filename=filename,
895
- expected_size=expected_size,
896
- existing_size=existing_size,
897
- file_id=file_id,
898
  )
899
- return
900
-
901
- job_id = int(time.time() * 1000 + hash(filename))
902
- cancel_event = asyncio.Event()
903
- active_jobs[job_id] = {"status": "queued", "cancel_event": cancel_event}
904
- await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size, cancel_event))
905
- await message.reply_text(f"📦 `{filename}` queued for upload.")
906
-
907
-
908
- def _extract_file_info(msg: Message) -> Tuple[Optional[str], Optional[int], Optional[str]]:
909
- expected_size = extract_file_size(msg)
910
- if msg.document:
911
- return msg.document.file_id, expected_size, msg.document.file_name
912
- elif msg.video:
913
- return msg.video.file_id, expected_size, msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
914
- elif msg.audio:
915
- return msg.audio.file_id, expected_size, msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
916
- elif msg.photo:
917
- return msg.photo.file_id, expected_size, f"{msg.photo.file_unique_id}.jpg"
918
- elif msg.animation:
919
- return msg.animation.file_id, expected_size, msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
920
- elif msg.sticker:
921
- if msg.sticker.is_animated:
922
- fn = f"{msg.sticker.file_unique_id}.tgs"
923
- elif msg.sticker.is_video:
924
- fn = f"{msg.sticker.file_unique_id}.webm"
925
- else:
926
- fn = f"{msg.sticker.file_unique_id}.webp"
927
- return msg.sticker.file_id, expected_size, fn
928
- elif msg.video_note:
929
- return msg.video_note.file_id, expected_size, f"{msg.video_note.file_unique_id}.mp4"
930
- elif msg.voice:
931
- return msg.voice.file_id, expected_size, f"{msg.voice.file_unique_id}.ogg"
932
- return None, None, None
933
-
934
-
935
- # =============================================================================
936
- # DUPLICATE & CALLBACK HANDLERS
937
- # =============================================================================
938
-
939
- @app.on_callback_query(filters.regex("^dup_skip:"))
940
- async def cb_dup_skip(_, query: CallbackQuery):
941
- token = query.data.split(":")[-1]
942
- duplicate_prompt_map.pop(token, None)
943
- await query.message.edit_text("❌ Upload skipped.")
944
- await query.answer("Skipped.")
945
-
946
- @app.on_callback_query(filters.regex("^dup_keep:"))
947
- async def cb_dup_keep(_, query: CallbackQuery):
948
- token = query.data.split(":")[-1]
949
- data = duplicate_prompt_map.pop(token, None)
950
- if not data:
951
- return await query.answer("Prompt expired.", show_alert=True)
952
-
953
- file_obj = data.get('file_obj')
954
- if file_obj is None:
955
- try:
956
- file_obj = await app.get_messages(data['chat_id'], data['msg_id'])
957
- except Exception:
958
- return await query.answer("Original message no longer available.", show_alert=True)
959
-
960
- base, ext = os.path.splitext(data['orig_filename'])
961
- new_filename = generate_unique_filename(data['user_id'], base, ext)
962
-
963
- job_id = data['job_id']
964
- cancel_event = asyncio.Event()
965
- active_jobs[job_id] = {"status": "queued", "cancel_event": cancel_event}
966
- await upload_queue.put((
967
- data['user_id'],
968
- data['chat_id'],
969
- file_obj,
970
- new_filename,
971
- job_id,
972
- data['file_id'],
973
- data['expected_size'],
974
- cancel_event,
975
- ))
976
- await query.message.edit_text(f"📦 `{new_filename}` queued (renamed duplicate).")
977
- await query.answer("Duplicate will be uploaded with a new name.")
978
-
979
- @app.on_callback_query(filters.regex("^get:"))
980
- async def cb_get_file(_, query: CallbackQuery):
981
- token = query.data.replace("get:", "")
982
- enc_path = file_callback_map.get(token)
983
- if not enc_path:
984
- return await query.answer("Invalid or expired link. Use /files again.", show_alert=True)
985
- job_id = int(time.time() * 1000)
986
- cancel_event = asyncio.Event()
987
- active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}
988
- try:
989
- orig_name = decrypt_text(enc_path.split("/")[-1])
990
- except Exception:
991
- orig_name = enc_path.split("/")[-1]
992
- status_msg = await query.message.edit_text(
993
- "⏳ Preparing download...",
994
- reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),
995
- )
996
- active_jobs[job_id]["status_msg"] = status_msg
997
- asyncio.create_task(do_download_job(query.message.chat.id, enc_path, orig_name, job_id, cancel_event, status_msg))
998
-
999
- @app.on_callback_query(filters.regex("^delete:"))
1000
- async def cb_delete_file(_, query: CallbackQuery):
1001
- token = query.data.replace("delete:", "")
1002
- enc_path = file_callback_map.pop(token, None)
1003
- if not enc_path:
1004
- return await query.answer("File not found or already deleted.", show_alert=True)
1005
- user_id = query.from_user.id
1006
- await delete_user_file(query.message.chat.id, user_id, enc_path, token, query)
1007
-
1008
- @app.on_callback_query(filters.regex("^delete_all:"))
1009
- async def cb_delete_all(_, query: CallbackQuery):
1010
- user_id = int(query.data.split(":")[-1])
1011
- await delete_all_user_files(query.message.chat.id, user_id, query)
1012
-
1013
- @app.on_callback_query(filters.regex("^cancel_job:"))
1014
- async def cb_cancel_job(_, query: CallbackQuery):
1015
- _, job_id_str = query.data.split(":")
1016
- job_id = int(job_id_str)
1017
- job = active_jobs.get(job_id)
1018
- if job and "cancel_event" in job:
1019
- job["cancel_event"].set()
1020
- await query.answer("Job cancelled. Cleaning up...")
1021
- try:
1022
- if "status_msg" in job:
1023
- await job["status_msg"].delete()
1024
- except Exception:
1025
- pass
1026
- else:
1027
- await query.answer("Job not found or already finished.")
1028
-
1029
- @app.on_callback_query(filters.regex("^upload:"))
1030
- async def cb_upload(_, query: CallbackQuery):
1031
- token = query.data.replace("upload:", "")
1032
- entries = upload_prompt_map.pop(token, None)
1033
- if not entries:
1034
- return await query.answer("Prompt expired.", show_alert=True)
1035
- for entry in entries:
1036
- user_id = entry[0]
1037
- if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
1038
- msg_id, filename, file_id = entry[1], entry[2], entry[3]
1039
- try:
1040
- file_msg = await app.get_messages(query.message.chat.id, msg_id)
1041
- except Exception:
1042
- continue
1043
- if not file_msg:
1044
- continue
1045
- file_obj = file_msg
1046
- expected_size = extract_file_size(file_msg)
1047
- limit_err = check_file_size_limit(filename, expected_size)
1048
- if limit_err:
1049
- await query.message.reply_text(limit_err)
1050
- continue
1051
-
1052
- existing_size = check_duplicate(user_id, filename)
1053
- if existing_size is not None:
1054
- await handle_duplicate(
1055
- user_id, query.message.chat.id, file_obj,
1056
- orig_filename=filename,
1057
- expected_size=expected_size,
1058
- existing_size=existing_size,
1059
- file_id=file_id,
1060
- msg_id=msg_id,
1061
- )
1062
- continue
1063
- else:
1064
- file_id, filename = entry[1], entry[2]
1065
- expected_size = entry[3] if len(entry) == 4 else None
1066
- limit_err = check_file_size_limit(filename, expected_size)
1067
- if limit_err:
1068
- await query.message.reply_text(limit_err)
1069
- continue
1070
- file_obj = file_id
1071
-
1072
- job_id = int(time.time() * 1000 + hash(filename))
1073
- cancel_event = asyncio.Event()
1074
- active_jobs[job_id] = {"status": "queued", "cancel_event": cancel_event}
1075
- await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size, cancel_event))
1076
- await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)
1077
-
1078
- @app.on_callback_query(filters.regex("^upload_all:"))
1079
- async def cb_upload_all(_, query: CallbackQuery):
1080
- token = query.data.replace("upload_all:", "")
1081
- entries = upload_prompt_map.pop(token, None)
1082
- if not entries:
1083
- return await query.answer("Prompt expired.", show_alert=True)
1084
- for entry in entries:
1085
- user_id = entry[0]
1086
- if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:
1087
- msg_id, filename, file_id = entry[1], entry[2], entry[3]
1088
- try:
1089
- file_msg = await app.get_messages(query.message.chat.id, msg_id)
1090
- except Exception:
1091
- continue
1092
- if not file_msg:
1093
- continue
1094
- file_obj = file_msg
1095
- expected_size = extract_file_size(file_msg)
1096
- limit_err = check_file_size_limit(filename, expected_size)
1097
- if limit_err:
1098
- await query.message.reply_text(limit_err)
1099
- continue
1100
-
1101
- existing_size = check_duplicate(user_id, filename)
1102
- if existing_size is not None:
1103
- await handle_duplicate(
1104
- user_id, query.message.chat.id, file_obj,
1105
- orig_filename=filename,
1106
- expected_size=expected_size,
1107
- existing_size=existing_size,
1108
- file_id=file_id,
1109
- msg_id=msg_id,
1110
- )
1111
- continue
1112
- else:
1113
- file_id, filename = entry[1], entry[2]
1114
- expected_size = entry[3] if len(entry) == 4 else None
1115
- limit_err = check_file_size_limit(filename, expected_size)
1116
- if limit_err:
1117
- await query.message.reply_text(limit_err)
1118
- continue
1119
- file_obj = file_id
1120
-
1121
- job_id = int(time.time() * 1000 + hash(filename))
1122
- cancel_event = asyncio.Event()
1123
- active_jobs[job_id] = {"status": "queued", "cancel_event": cancel_event}
1124
- await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size, cancel_event))
1125
- await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)
1126
-
1127
- @app.on_callback_query(filters.regex("^cancel_upload:"))
1128
- async def cb_cancel_upload_prompt(_, query: CallbackQuery):
1129
- await query.message.delete()
1130
 
 
 
1131
 
1132
- # =============================================================================
1133
- # MESSAGE LINK INTERACTIVE PROMPT
1134
- # =============================================================================
1135
 
1136
  @app.on_message(
1137
- filters.text
1138
- & ~filters.command(["start", "help", "status", "files", "delete_all", "upload", "cancelall"])
1139
- & filters.regex(r'https?://t\.me/')
 
1140
  )
1141
- async def on_message_link(client, message: Message):
1142
- links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)
1143
- if not links:
1144
- return
1145
- chat_str, msg_id = links[0][1], int(links[0][2])
1146
- try:
1147
- if chat_str.startswith("c/"):
1148
- chat_id = int("-100" + chat_str[2:])
1149
- else:
1150
- chat_id = chat_str
1151
- msg = await app.get_messages(chat_id, msg_id)
1152
- except Exception as e:
1153
- await message.reply_text(f"❌ Could not access the message: {e}")
1154
- return
1155
- if not msg.media:
1156
- await message.reply_text("The linked message does not contain any downloadable file.")
1157
- return
1158
-
1159
- file_id, expected_size, filename = _extract_file_info(msg)
1160
- if not filename:
1161
- return await message.reply_text("Could not determine file name.")
1162
 
1163
- limit_err = check_file_size_limit(filename, expected_size)
1164
- if limit_err:
1165
- return await message.reply_text(limit_err)
1166
 
1167
- existing_size = check_duplicate(message.from_user.id, filename)
1168
- if existing_size is not None:
1169
- await handle_duplicate(
1170
- user_id=message.from_user.id,
1171
- chat_id=message.chat.id,
1172
- file_obj=file_id,
1173
- orig_filename=filename,
1174
- expected_size=expected_size,
1175
- existing_size=existing_size,
1176
- file_id=file_id,
1177
  )
1178
- return
1179
-
1180
- upload_token = make_token()
1181
- upload_prompt_map[upload_token] = [(message.from_user.id, file_id, filename, expected_size)]
1182
- kb = InlineKeyboardMarkup([
1183
- [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],
1184
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
1185
- ])
1186
- await message.reply_text(f"Found file `{filename}`. Do you want to upload it?", reply_markup=kb)
1187
 
 
 
 
1188
 
1189
- # =============================================================================
1190
- # DIRECT FILE RECEIVER
1191
- # =============================================================================
1192
-
1193
- @app.on_message(
1194
- filters.document | filters.video | filters.audio | filters.photo
1195
- | filters.animation | filters.sticker | filters.video_note | filters.voice
1196
- )
1197
- async def on_direct_file(_, message: Message):
1198
- file_id, expected_size, filename = _extract_file_info(message)
1199
- if not filename:
1200
- return
1201
-
1202
- if message.media_group_id and (message.photo or message.video or message.document):
1203
- group_id = str(message.media_group_id)
1204
- if group_id not in album_groups:
1205
- album_groups[group_id] = {
1206
- 'chat_id': message.chat.id,
1207
- 'user_id': message.from_user.id,
1208
- 'messages': [],
1209
- 'timer': None,
1210
- }
1211
- album_groups[group_id]['messages'].append((message.id, filename, file_id, expected_size))
1212
- if album_groups[group_id]['timer']:
1213
- album_groups[group_id]['timer'].cancel()
1214
 
1215
- async def timer_callback(gid=group_id):
1216
- await asyncio.sleep(2)
1217
- await process_album_group(gid)
 
 
 
1218
 
1219
- album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
1220
- return
 
1221
 
1222
- limit_err = check_file_size_limit(filename, expected_size)
1223
- if limit_err:
1224
- return await message.reply_text(limit_err)
 
 
 
1225
 
1226
- existing_size = check_duplicate(message.from_user.id, filename)
1227
- if existing_size is not None:
1228
- await handle_duplicate(
1229
- user_id=message.from_user.id,
1230
- chat_id=message.chat.id,
1231
- file_obj=message,
1232
- orig_filename=filename,
1233
- expected_size=expected_size,
1234
- existing_size=existing_size,
1235
- file_id=file_id,
1236
- msg_id=message.id,
1237
  )
1238
- return
1239
 
1240
- upload_token = make_token()
1241
- upload_prompt_map[upload_token] = [(message.from_user.id, message.id, filename, file_id)]
1242
- kb = InlineKeyboardMarkup([
1243
- [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],
1244
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],
1245
- ])
1246
- await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)
1247
 
 
 
 
 
 
 
1248
 
1249
- # =============================================================================
1250
- # KEEP‑ALIVE PING
1251
- # =============================================================================
1252
 
1253
- def keepalive():
1254
- while True:
1255
- try:
1256
- requests.get(SPACE_HOST, timeout=10)
1257
- except Exception as e:
1258
- logger.warning("Keep‑alive ping failed: %s", e)
1259
- time.sleep(KEEPALIVE_INTERVAL)
1260
 
 
 
1261
 
1262
- # =============================================================================
1263
  # MAIN
1264
- # =============================================================================
1265
 
1266
- async def main():
1267
- if UVLOOP_AVAILABLE:
1268
- uvloop.install()
1269
- logger.info("✅ uvloop installed – faster asyncio event loop.")
1270
- else:
1271
- logger.info("ℹ️ uvloop not installed – install it with: pip install uvloop")
1272
 
1273
- asyncio.create_task(upload_worker())
1274
- await app.start()
1275
- logger.info("Bot started successfully (tgcrypto: %s)", "available" if hasattr(app, "tgcrypto") else "missing")
1276
- await asyncio.Event().wait()
1277
 
 
1278
 
1279
- if __name__ == "__main__":
1280
- threading.Thread(target=run_web, daemon=True).start()
1281
- threading.Thread(target=keepalive, daemon=True).start()
1282
- app.run(main())
 
1
+ import os
2
+ import tempfile
3
+ import shutil
4
+ import threading
5
 
 
6
  from flask import Flask
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ from pyrogram import Client, filters
9
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ from huggingface_hub import HfApi, hf_hub_download
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # =========================
14
+ # CONFIG
15
+ # =========================
16
 
17
+ API_ID = int(os.environ["API_ID"])
18
+ API_HASH = os.environ["API_HASH"]
19
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
20
+ HF_TOKEN = os.environ["HF_TOKEN"]
21
 
22
+ DATASET_REPO = "Cxops/Bzxv"
 
23
 
24
+ # =========================
25
+ # FLASK HEALTH SERVER
26
+ # =========================
27
 
28
  web = Flask(__name__)
29
 
30
  @web.route("/")
31
  def home():
32
+ return "Telegram HF Storage Bot Running"
33
 
34
  def run_web():
35
  web.run(host="0.0.0.0", port=7860)
36
 
37
+ # =========================
38
+ # HUGGINGFACE
39
+ # =========================
40
 
41
  hf = HfApi(token=HF_TOKEN)
42
 
43
+ # =========================
44
+ # PYROGRAM
45
+ # =========================
46
+
47
  app = Client(
48
  "storage_bot",
49
  api_id=API_ID,
50
  api_hash=API_HASH,
51
+ bot_token=BOT_TOKEN
52
  )
53
 
54
+ # =========================
55
+ # HELPERS
56
+ # =========================
 
 
 
 
57
 
58
+ def cleanup(path):
 
 
 
 
59
  try:
60
  if os.path.isdir(path):
61
  shutil.rmtree(path, ignore_errors=True)
 
64
  except Exception:
65
  pass
66
 
67
+ # =========================
68
+ # COMMANDS
69
+ # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ @app.on_message(filters.command("start"))
72
+ async def start(_, message):
73
+ await message.reply_text(
74
+ "Send me a file.\n\n"
75
+ "/files - List uploaded files"
76
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ @app.on_message(filters.command("files"))
79
+ async def files(_, message):
80
+ user_id = str(message.from_user.id)
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  try:
83
+ repo_files = hf.list_repo_files(
84
+ repo_id=DATASET_REPO,
85
+ repo_type="dataset"
 
 
86
  )
87
 
88
+ user_files = [
89
+ f for f in repo_files
90
+ if f.startswith(f"{user_id}/")
91
+ ]
 
92
 
93
+ if not user_files:
94
+ return await message.reply_text(
95
+ "You have no uploaded files."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  )
97
 
98
+ buttons = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ for path in user_files:
101
+ filename = os.path.basename(path)
 
 
 
102
 
103
+ buttons.append(
104
+ [
105
+ InlineKeyboardButton(
106
+ filename[:60],
107
+ callback_data=f"get:{path}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  )
109
+ ]
110
+ )
 
 
 
 
 
 
 
 
 
111
 
112
+ await message.reply_text(
113
+ "Your uploaded files:",
114
+ reply_markup=InlineKeyboardMarkup(buttons)
115
+ )
116
 
 
 
 
 
 
 
 
117
  except Exception as e:
118
+ await message.reply_text(f"Error:\n{e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ # =========================
121
+ # DOWNLOAD FROM HF
122
+ # =========================
123
 
124
+ @app.on_callback_query(filters.regex("^get:"))
125
+ async def get_file(_, query):
126
+ path = query.data.replace("get:", "")
127
 
128
+ temp_dir = tempfile.mkdtemp()
 
 
 
 
129
 
 
 
 
 
130
  try:
131
+ await query.message.edit_text(
132
+ "Downloading from dataset..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  )
134
 
135
+ local_file = hf_hub_download(
136
+ repo_id=DATASET_REPO,
137
+ repo_type="dataset",
138
+ filename=path,
139
+ token=HF_TOKEN,
140
+ local_dir=temp_dir
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
+ await query.message.reply_document(
144
+ local_file,
145
+ caption=os.path.basename(path)
146
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
 
 
 
 
 
 
 
148
  try:
149
+ await query.message.delete()
 
150
  except Exception:
151
  pass
 
 
 
 
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  except Exception as e:
154
+ await query.message.reply_text(
155
+ f"Error:\n{e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
+ finally:
159
+ cleanup(temp_dir)
160
 
161
+ # =========================
162
+ # RECEIVE FILES
163
+ # =========================
164
 
165
  @app.on_message(
166
+ filters.document |
167
+ filters.video |
168
+ filters.audio |
169
+ filters.photo
170
  )
171
+ async def upload_file(_, message):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
+ temp_dir = tempfile.mkdtemp()
 
 
174
 
175
+ try:
176
+ status = await message.reply_text(
177
+ "Downloading file..."
 
 
 
 
 
 
 
178
  )
 
 
 
 
 
 
 
 
 
179
 
180
+ if message.document:
181
+ media = message.document
182
+ filename = media.file_name
183
 
184
+ elif message.video:
185
+ media = message.video
186
+ filename = (
187
+ media.file_name
188
+ or f"{media.file_unique_id}.mp4"
189
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
+ elif message.audio:
192
+ media = message.audio
193
+ filename = (
194
+ media.file_name
195
+ or f"{media.file_unique_id}.mp3"
196
+ )
197
 
198
+ else:
199
+ media = message.photo[-1]
200
+ filename = f"{media.file_unique_id}.jpg"
201
 
202
+ local_path = await message.download(
203
+ file_name=os.path.join(
204
+ temp_dir,
205
+ filename
206
+ )
207
+ )
208
 
209
+ await status.edit_text(
210
+ "Uploading to Hugging Face..."
 
 
 
 
 
 
 
 
 
211
  )
 
212
 
213
+ repo_path = (
214
+ f"{message.from_user.id}/{filename}"
215
+ )
 
 
 
 
216
 
217
+ hf.upload_file(
218
+ path_or_fileobj=local_path,
219
+ path_in_repo=repo_path,
220
+ repo_id=DATASET_REPO,
221
+ repo_type="dataset"
222
+ )
223
 
224
+ await status.edit_text(
225
+ f"Uploaded successfully.\n\n{filename}"
226
+ )
227
 
228
+ except Exception as e:
229
+ await message.reply_text(
230
+ f"Upload failed:\n{e}"
231
+ )
 
 
 
232
 
233
+ finally:
234
+ cleanup(temp_dir)
235
 
236
+ # =========================
237
  # MAIN
238
+ # =========================
239
 
240
+ if __name__ == "__main__":
241
+ print("Starting Flask health server...")
 
 
 
 
242
 
243
+ threading.Thread(
244
+ target=run_web,
245
+ daemon=True
246
+ ).start()
247
 
248
+ print("Starting Telegram bot...")
249
 
250
+ app.run()