Cxops commited on
Commit
cf57358
·
verified ·
1 Parent(s): aaa6e44

Update app.py

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