Cxops commited on
Commit
e67347b
·
verified ·
1 Parent(s): ad73479

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -804
app.py CHANGED
@@ -1,17 +1,11 @@
1
  #!/usr/bin/env python3
2
  """
3
- Production‑grade Telegram ↔ Hugging Face Storage Bot.
4
- - AES‑SIV deterministic encryption per user.
5
- - Async SQLite via aiosqlite (no blocking I/O).
6
- - Full media support, albums, message links.
7
- - Persistent job queue, multi‑worker, true cancellation.
8
- - Quota accounting, atomic operations, startup reconciliation.
9
- - All handlers fully implemented, FloodWait safe.
10
  """
11
 
12
  import asyncio, base64, hashlib, json, logging, os, re, secrets, shutil, signal, sys, tempfile, threading, time, unicodedata
13
  from pathlib import Path
14
- from typing import Optional, Tuple, Union
15
 
16
  import aiosqlite
17
  import requests
@@ -21,6 +15,19 @@ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message,
21
  from huggingface_hub import HfApi, hf_hub_download, hf_hub_url, utils as hf_utils
22
  from cryptography.hazmat.primitives.ciphers.aead import AESSIV
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  # ---------------------------------------------------------------------------
25
  # Config
26
  # ---------------------------------------------------------------------------
@@ -33,27 +40,21 @@ API_ID = int(os.environ["API_ID"])
33
  API_HASH = os.environ["API_HASH"]
34
  BOT_TOKEN = os.environ["BOT_TOKEN"]
35
  HF_TOKEN = os.environ["HF_TOKEN"]
36
- OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")
37
  SPACE_HOST = os.environ.get("SPACE_HOST", "http://localhost:7860")
38
 
39
  DATASET_REPO = "Cxops/Bzxv"
40
  DATASET_TYPE = "dataset"
 
41
  MAX_SINGLE_FILE = 45 * 1024**3
42
  MIN_FREE_DISK = 45 * 1024**3
43
  DATASET_MAX = int(8.7 * 1024**4)
44
  QUOTA_PER_USER = 500 * 1024**3
45
  KEEPALIVE_INTERVAL = 300
46
- UPLOAD_TIMEOUT = 7200
47
- MAX_WORKERS = 3
48
- RATE_LIMIT_UPLOADS = 5
49
- RATE_LIMIT_WINDOW = 600
50
  DB_PATH = "bot.db"
 
51
 
52
- logging.basicConfig(
53
- level=logging.INFO,
54
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
55
- handlers=[logging.StreamHandler(sys.stdout)],
56
- )
57
  logger = logging.getLogger("StorageBot")
58
 
59
  # ---------------------------------------------------------------------------
@@ -62,188 +63,131 @@ logger = logging.getLogger("StorageBot")
62
  _siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
63
  _aes_siv = AESSIV(_siv_key)
64
 
65
- def encrypt_text(plain: str) -> str:
66
- token = _aes_siv.encrypt(plain.encode(), None)
67
- return base64.urlsafe_b64encode(token).decode().rstrip("=")
68
 
69
- def decrypt_text(encoded: str) -> str:
70
- pad = 4 - len(encoded) % 4
71
  if pad != 4:
72
- encoded += "=" * pad
73
- try:
74
- token = base64.urlsafe_b64decode(encoded.encode())
75
- return _aes_siv.decrypt(token, None).decode()
76
- except Exception:
77
- raise ValueError("Invalid encrypted data")
78
 
79
  def enc_folder(uid: int) -> str:
80
  return encrypt_text(str(uid))
81
 
82
- def enc_filename(orig: str) -> str:
83
- return encrypt_text(orig)
84
 
85
  # ---------------------------------------------------------------------------
86
- # Async Database (aiosqlite)
87
  # ---------------------------------------------------------------------------
88
  _db_conn: Optional[aiosqlite.Connection] = None
89
 
90
- async def get_db() -> aiosqlite.Connection:
91
  global _db_conn
92
  if _db_conn is None:
93
- _db_conn = await aiosqlite.connect(DB_PATH)
94
  _db_conn.row_factory = aiosqlite.Row
95
  await _db_conn.execute("PRAGMA journal_mode=WAL")
96
- await _db_conn.execute("PRAGMA foreign_keys=ON")
97
  await _db_conn.execute("PRAGMA busy_timeout=5000")
98
  await _migrate(_db_conn)
99
  return _db_conn
100
 
101
- async def _migrate(db: aiosqlite.Connection):
102
- cur = await db.execute("PRAGMA user_version")
103
- ver = (await cur.fetchone())[0]
104
- if ver < 1:
105
- await db.executescript("""
106
- CREATE TABLE IF NOT EXISTS files (
107
- user_id INTEGER NOT NULL,
108
- enc_path TEXT UNIQUE NOT NULL,
109
- orig_name TEXT NOT NULL,
110
- size INTEGER NOT NULL CHECK(size >= 0),
111
- timestamp REAL NOT NULL DEFAULT (strftime('%s','now'))
112
- );
113
- CREATE INDEX IF NOT EXISTS idx_files_user ON files(user_id);
114
- CREATE INDEX IF NOT EXISTS idx_files_name ON files(orig_name);
115
-
116
- CREATE TABLE IF NOT EXISTS job_queue (
117
- job_id TEXT PRIMARY KEY NOT NULL,
118
- user_id INTEGER NOT NULL,
119
- chat_id INTEGER NOT NULL,
120
- file_id TEXT NOT NULL,
121
- orig_filename TEXT NOT NULL,
122
- expected_size INTEGER,
123
- status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','processing','completed','failed','cancelled')),
124
- created REAL NOT NULL DEFAULT (strftime('%s','now')),
125
- updated REAL NOT NULL DEFAULT (strftime('%s','now'))
126
- );
127
- CREATE INDEX IF NOT EXISTS idx_jobs_status ON job_queue(status);
128
-
129
- CREATE TABLE IF NOT EXISTS callback_tokens (
130
- token TEXT PRIMARY KEY NOT NULL,
131
- type TEXT NOT NULL,
132
- data TEXT NOT NULL,
133
- created REAL NOT NULL DEFAULT (strftime('%s','now'))
134
- );
135
-
136
- CREATE TABLE IF NOT EXISTS user_quota (
137
- user_id INTEGER PRIMARY KEY NOT NULL,
138
- used_bytes INTEGER NOT NULL DEFAULT 0 CHECK(used_bytes >= 0)
139
- );
140
- PRAGMA user_version = 1;
141
- """)
142
- await db.commit()
143
 
144
- # ---------------------------------------------------------------------------
145
- # DB helpers (all async via aiosqlite)
146
- # ---------------------------------------------------------------------------
147
- async def db_execute(sql: str, params: tuple = ()) -> None:
148
  db = await get_db()
149
  await db.execute(sql, params)
150
  await db.commit()
151
 
152
- async def db_fetchone(sql: str, params: tuple = ()) -> Optional[aiosqlite.Row]:
153
  db = await get_db()
154
- async with db.execute(sql, params) as cursor:
155
- return await cursor.fetchone()
156
 
157
- async def db_fetchall(sql: str, params: tuple = ()) -> list[aiosqlite.Row]:
158
  db = await get_db()
159
- async with db.execute(sql, params) as cursor:
160
- return await cursor.fetchall()
161
-
162
- # ---------------------------------------------------------------------------
163
- # Rate limiter (in‑memory)
164
- # ---------------------------------------------------------------------------
165
- class RateLimiter:
166
- def __init__(self):
167
- self._users: dict[int, list[float]] = {}
168
- self._lock = asyncio.Lock()
169
-
170
- async def is_allowed(self, user_id: int) -> bool:
171
- async with self._lock:
172
- now = time.time()
173
- if user_id not in self._users:
174
- self._users[user_id] = []
175
- timestamps = self._users[user_id]
176
- self._users[user_id] = [t for t in timestamps if now - t < RATE_LIMIT_WINDOW]
177
- if len(self._users[user_id]) >= RATE_LIMIT_UPLOADS:
178
- return False
179
- self._users[user_id].append(now)
180
- return True
181
-
182
- rate_limiter = RateLimiter()
183
 
184
  # ---------------------------------------------------------------------------
185
- # Utilities
186
  # ---------------------------------------------------------------------------
187
- def format_size(b: int) -> str:
188
- for u in ['B','KB','MB','GB','TB']:
189
- if b < 1024: return f"{b:.1f} {u}"
190
- b /= 1024
191
- return f"{b:.1f} PB"
192
 
193
- def get_free_disk() -> int:
194
- return shutil.disk_usage("/").free
 
 
 
 
 
 
 
 
 
 
195
 
196
- def total_memory() -> int:
197
- try:
198
- with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
199
- val = int(f.read().strip())
200
- if val < 9_223_372_036_854_771_200:
201
- return val
202
- except: pass
203
- try:
204
- with open("/sys/fs/cgroup/memory.max") as f:
205
- val = f.read().strip()
206
- if val != "max":
207
- return int(val)
208
- except: pass
209
- try:
210
- with open("/proc/meminfo") as f:
211
- for line in f:
212
- if line.startswith("MemTotal:"):
213
- return int(line.split()[1]) * 1024
214
- except: pass
215
- return 0
216
-
217
- def sanitize_filename(name: str) -> str:
218
- name = unicodedata.normalize('NFC', name)
219
- name = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', name)
220
- name = re.sub(r'[\\/*?:"<>|]', '_', name)
221
- if len(name) > 200:
222
- stem, ext = os.path.splitext(name)
223
- stem = stem[:195 - len(ext)] + "..."
224
- name = stem + ext
225
- return name or "unnamed"
226
 
227
  # ---------------------------------------------------------------------------
228
- # FloodWait retry helper
229
  # ---------------------------------------------------------------------------
230
- async def flood_retry(coro, *args, **kwargs):
231
- """
232
- Retry a Pyrogram method with exponential backoff on FloodWait.
233
- `coro` should be a coroutine function (e.g., app.send_message).
234
- """
235
- for attempt in range(5):
236
  try:
237
- return await coro(*args, **kwargs)
238
- except pyro_errors.FloodWait as e:
239
- wait = e.value + 1
240
- logger.warning(f"FloodWait {wait}s")
241
- await asyncio.sleep(wait)
242
- except pyro_errors.RPCError as e:
243
- if attempt == 4:
244
- raise
245
- await asyncio.sleep(2 ** attempt)
246
- return None
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  # ---------------------------------------------------------------------------
249
  # Flask
@@ -252,700 +196,104 @@ web = Flask(__name__)
252
 
253
  @web.route("/")
254
  def home():
255
- return "Status: OK"
256
-
257
- @web.route("/health")
258
- def health():
259
- return {"status": "healthy"}
260
-
261
- @web.route("/ready")
262
- def ready():
263
- return {"status": "ready"}
264
 
265
  def run_web():
266
- web.run(host="0.0.0.0", port=7860, use_reloader=False)
267
 
268
  # ---------------------------------------------------------------------------
269
- # Hugging Face async wrappers
270
  # ---------------------------------------------------------------------------
271
  hf = HfApi(token=HF_TOKEN)
272
 
273
- async def hf_upload_file(local_path: str, path_in_repo: str):
274
  return await asyncio.to_thread(
275
  hf.upload_file,
276
- path_or_fileobj=local_path,
277
- path_in_repo=path_in_repo,
278
  repo_id=DATASET_REPO,
279
  repo_type=DATASET_TYPE,
280
  )
281
 
282
- async def hf_delete_file(path_in_repo: str):
283
  return await asyncio.to_thread(
284
  hf.delete_file,
285
- path_in_repo=path_in_repo,
286
  repo_id=DATASET_REPO,
287
  repo_type=DATASET_TYPE,
288
  )
289
 
290
- async def hf_get_metadata(filename: str):
291
- url = hf_hub_url(repo_id=DATASET_REPO, filename=filename, repo_type=DATASET_TYPE)
292
- return await asyncio.to_thread(hf.get_hf_file_metadata, url=url, token=HF_TOKEN)
293
-
294
- async def hf_dataset_info():
295
- return await asyncio.to_thread(hf.dataset_info, repo_id=DATASET_REPO)
296
-
297
- async def hf_list_files():
298
- return await asyncio.to_thread(hf.list_repo_files, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)
299
-
300
  # ---------------------------------------------------------------------------
301
- # Quota (atomic with aiosqlite)
302
  # ---------------------------------------------------------------------------
303
- _quota_lock = asyncio.Lock()
304
-
305
- async def reserve_quota(user_id: int, bytes_: int) -> bool:
306
- async with _quota_lock:
307
- row = await db_fetchone("SELECT used_bytes FROM user_quota WHERE user_id=?", (user_id,))
308
- used = row["used_bytes"] if row else 0
309
- if used + bytes_ > QUOTA_PER_USER:
310
- return False
311
- await db_execute(
312
- "INSERT INTO user_quota (user_id, used_bytes) VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET used_bytes = used_bytes + ?",
313
- (user_id, bytes_, bytes_)
314
- )
315
- return True
316
-
317
- async def release_quota(user_id: int, bytes_: int):
318
- async with _quota_lock:
319
- await db_execute(
320
- "UPDATE user_quota SET used_bytes = MAX(0, used_bytes - ?) WHERE user_id=?",
321
- (bytes_, user_id)
322
- )
323
 
324
- async def reconcile_quota():
325
- async with _quota_lock:
326
- await db_execute("DELETE FROM user_quota")
327
- rows = await db_fetchall("SELECT user_id, COALESCE(SUM(size),0) AS total FROM files GROUP BY user_id")
328
- for row in rows:
329
- await db_execute("INSERT INTO user_quota (user_id, used_bytes) VALUES (?,?)",
330
- (row["user_id"], row["total"]))
331
 
332
  # ---------------------------------------------------------------------------
333
- # Job queue (atomic dequeue)
334
  # ---------------------------------------------------------------------------
335
- async def enqueue_job(user_id, chat_id, file_id, orig_filename, expected_size):
336
- job_id = secrets.token_hex(16)
337
- await db_execute(
338
- "INSERT INTO job_queue (job_id, user_id, chat_id, file_id, orig_filename, expected_size) VALUES (?,?,?,?,?,?)",
339
- (job_id, user_id, chat_id, file_id, orig_filename, expected_size)
340
- )
341
  return job_id
342
 
343
- async def dequeue_job() -> Optional[Tuple[str, int, int, str, str, int]]:
344
- """Atomically claim the next pending job."""
345
- db = await get_db()
346
- async with db.execute("BEGIN IMMEDIATE"):
347
- cursor = await db.execute(
348
- "SELECT job_id, user_id, chat_id, file_id, orig_filename, expected_size FROM job_queue WHERE status='pending' ORDER BY created LIMIT 1"
349
- )
350
- row = await cursor.fetchone()
351
- if row:
352
- await db.execute("UPDATE job_queue SET status='processing', updated=strftime('%s','now') WHERE job_id=?", (row["job_id"],))
353
- await db.commit()
354
- return row
355
-
356
- async def complete_job(job_id: str):
357
- await db_execute("DELETE FROM job_queue WHERE job_id=?", (job_id,))
358
-
359
- async def cancel_job(job_id: str):
360
- await db_execute("UPDATE job_queue SET status='cancelled' WHERE job_id=? AND status IN ('pending','processing')", (job_id,))
361
-
362
- async def reset_processing_jobs():
363
- await db_execute("UPDATE job_queue SET status='pending' WHERE status='processing'")
364
-
365
  # ---------------------------------------------------------------------------
366
- # Callback tokens
367
  # ---------------------------------------------------------------------------
368
- async def store_token(token: str, type_: str, data: dict):
369
- await db_execute("INSERT OR REPLACE INTO callback_tokens (token, type, data, created) VALUES (?,?,?,?)",
370
- (token, type_, json.dumps(data), time.time()))
 
371
 
372
- async def get_token_data(token: str) -> Optional[dict]:
373
- row = await db_fetchone("SELECT data FROM callback_tokens WHERE token=? AND created > ?",
374
- (token, time.time() - 3600))
375
- if row:
376
- return json.loads(row["data"])
377
- return None
378
 
379
- async def delete_token(token: str):
380
- await db_execute("DELETE FROM callback_tokens WHERE token=?", (token,))
381
 
382
- # ---------------------------------------------------------------------------
383
- # File listing helper (pagination)
384
- # ---------------------------------------------------------------------------
385
- async def build_file_list_message(user_id: int, page: int = 0, per_page: int = 10) -> Tuple[str, Optional[InlineKeyboardMarkup]]:
386
- rows = await db_fetchall(
387
- "SELECT enc_path, orig_name, size FROM files WHERE user_id=? ORDER BY timestamp DESC LIMIT ? OFFSET ?",
388
- (user_id, per_page + 1, page * per_page)
389
- )
390
- has_more = len(rows) > per_page
391
- if has_more:
392
- rows = rows[:per_page]
393
- if not rows and page == 0:
394
- return "You have no uploaded files.", None
395
-
396
- buttons = []
397
- for r in rows:
398
- token = secrets.token_hex(8)
399
- await store_token(token, "file", {"enc_path": r["enc_path"], "user_id": user_id})
400
- buttons.append([
401
- InlineKeyboardButton(f"📥 {r['orig_name'][:30]} ({format_size(r['size'])})", callback_data=f"get:{token}"),
402
- InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}")
403
- ])
404
-
405
- nav = []
406
- if page > 0:
407
- nav.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"files_page:{page-1}"))
408
- if has_more:
409
- nav.append(InlineKeyboardButton("Next ➡️", callback_data=f"files_page:{page+1}"))
410
- if nav:
411
- buttons.append(nav)
412
-
413
- buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data="delete_all_confirm")])
414
- return "Your uploaded files:", InlineKeyboardMarkup(buttons)
415
 
416
- # ---------------------------------------------------------------------------
417
- # Upload worker
418
- # ---------------------------------------------------------------------------
419
- active_uploads: dict[str, asyncio.Task] = {}
420
 
421
- async def process_upload(job_id: str, user_id: int, chat_id: int, file_id: str, orig_filename: str, expected_size: int):
422
- needed = (expected_size or 0) + MIN_FREE_DISK
423
- while get_free_disk() < needed:
424
- logger.warning("Low disk, waiting...")
425
- await asyncio.sleep(30)
426
 
427
- if not await rate_limiter.is_allowed(user_id):
428
- await flood_retry(app.send_message, chat_id, "⚠️ Too many uploads, try later.")
429
- return
430
-
431
- try:
432
- info = await hf_dataset_info()
433
- current_used = info.used_storage or 0
434
- if current_used + (expected_size or 0) > DATASET_MAX:
435
- await flood_retry(app.send_message, chat_id, "❌ Dataset is full.")
436
- return
437
- except Exception as e:
438
- logger.warning(f"Could not fetch dataset info: {e}")
439
-
440
- temp_dir = tempfile.mkdtemp()
441
- local_path = None
442
- try:
443
- msg = await flood_retry(app.send_message, chat_id, f"⬇️ Downloading `{orig_filename}`...")
444
- local_path = await app.download_media(file_id, file_name=os.path.join(temp_dir, orig_filename),
445
- block_size=1024*1024,
446
- progress=lambda c, t: None)
447
- if not local_path or not os.path.exists(local_path):
448
- raise RuntimeError("Download failed")
449
- file_size = os.path.getsize(local_path)
450
-
451
- if file_size > MAX_SINGLE_FILE:
452
- await msg.edit(f"❌ File too large ({format_size(file_size)}).")
453
- return
454
-
455
- if not await reserve_quota(user_id, file_size):
456
- await msg.edit(f"❌ Quota exceeded ({format_size(QUOTA_PER_USER)}).")
457
- return
458
-
459
- safe_name = sanitize_filename(orig_filename)
460
- repo_path = f"{enc_folder(user_id)}/{enc_filename(safe_name)}"
461
- await msg.edit(f"⬆️ Uploading `{safe_name}` to Hugging Face...")
462
-
463
- for attempt in range(3):
464
- try:
465
- await hf_upload_file(local_path, repo_path)
466
- break
467
- except hf_utils.HfHubHTTPError as e:
468
- if attempt == 2:
469
- raise
470
- await asyncio.sleep(2 ** attempt)
471
-
472
- meta = await hf_get_metadata(repo_path)
473
- if meta.size != file_size:
474
- await hf_delete_file(repo_path)
475
- raise RuntimeError("Upload verification failed")
476
-
477
- await db_execute("INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size) VALUES (?,?,?,?)",
478
- (user_id, repo_path, orig_filename, file_size))
479
- await msg.edit(f"✅ Uploaded: `{orig_filename}` ({format_size(file_size)})")
480
- logger.info(f"Uploaded {orig_filename} for user {user_id}")
481
-
482
- except asyncio.CancelledError:
483
- logger.info(f"Job {job_id} cancelled")
484
- if local_path and os.path.exists(local_path):
485
- os.remove(local_path)
486
- if 'repo_path' in locals():
487
- try:
488
- await hf_delete_file(repo_path)
489
- except: pass
490
- await release_quota(user_id, file_size if 'file_size' in locals() else expected_size or 0)
491
- except Exception as e:
492
- logger.exception("Upload failed")
493
- await release_quota(user_id, file_size if 'file_size' in locals() else expected_size or 0)
494
- await flood_retry(app.send_message, chat_id, f"❌ Upload failed: {e}")
495
- finally:
496
- if local_path and os.path.exists(local_path):
497
- os.remove(local_path)
498
- shutil.rmtree(temp_dir, ignore_errors=True)
499
-
500
- async def upload_worker(worker_id: int):
501
- while True:
502
- job = await dequeue_job()
503
- if not job:
504
- await asyncio.sleep(5)
505
- continue
506
- job_id, user_id, chat_id, file_id, orig_filename, expected_size = job
507
- logger.info(f"Worker {worker_id} processing {orig_filename}")
508
- task = asyncio.create_task(process_upload(job_id, user_id, chat_id, file_id, orig_filename, expected_size))
509
- active_uploads[job_id] = task
510
- try:
511
- await task
512
- except Exception:
513
- pass
514
- finally:
515
- active_uploads.pop(job_id, None)
516
- await complete_job(job_id)
517
-
518
- # ---------------------------------------------------------------------------
519
- # Download helper
520
- # ---------------------------------------------------------------------------
521
- async def do_download(chat_id: int, enc_path: str, orig_name: str):
522
- temp_dir = tempfile.mkdtemp()
523
- local_file = None
524
- try:
525
- msg = await flood_retry(app.send_message, chat_id, f"⬇️ Downloading `{orig_name}`...")
526
- local_file = await asyncio.to_thread(
527
- hf_hub_download,
528
- repo_id=DATASET_REPO, filename=enc_path, repo_type=DATASET_TYPE,
529
- token=HF_TOKEN, local_dir=temp_dir
530
  )
531
- total = os.path.getsize(local_file)
532
- if total <= 1900 * 1024 * 1024:
533
- await flood_retry(app.send_document, chat_id, document=local_file, file_name=orig_name,
534
- progress=lambda c, t: None)
535
- await msg.delete()
536
- else:
537
- parts = -(-total // (1900*1024*1024))
538
- with open(local_file, 'rb') as f:
539
- for i in range(1, parts+1):
540
- chunk = f.read(1900*1024*1024)
541
- part_name = f"{orig_name}.part{i}of{parts}"
542
- part_path = os.path.join(temp_dir, part_name)
543
- with open(part_path, 'wb') as pf:
544
- pf.write(chunk)
545
- await flood_retry(app.send_document, chat_id, document=part_path, file_name=part_name,
546
- caption=f"Part {i}/{parts}")
547
- os.remove(part_path)
548
- await msg.delete()
549
- except Exception as e:
550
- await flood_retry(app.send_message, chat_id, f"❌ Download failed: {e}")
551
- finally:
552
- shutil.rmtree(temp_dir, ignore_errors=True)
553
-
554
- # ---------------------------------------------------------------------------
555
- # Bot Handlers
556
- # ---------------------------------------------------------------------------
557
- app = Client("storage_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
558
-
559
- @app.on_message(filters.command("start"))
560
- async def start_cmd(_, msg: Message):
561
- await msg.reply("👋 Welcome! Send a file or t.me link.\n/files – list\n/status – stats")
562
 
563
- @app.on_message(filters.command("help"))
564
- async def help_cmd(_, msg: Message):
565
- await msg.reply("/files – list\n/status – system stats\n/delete_all – delete all\n/upload <link>")
566
 
567
- @app.on_message(filters.command("status"))
568
- async def status_cmd(_, msg: Message):
569
- free = get_free_disk()
570
- try:
571
- info = await hf_dataset_info()
572
- used = info.used_storage or 0
573
- except Exception:
574
- used = 0
575
- uptime = int(time.time() - bot_start_time)
576
- queue_len = len(await db_fetchall("SELECT 1 FROM job_queue WHERE status IN ('pending','processing')"))
577
- text = (
578
- f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})\n"
579
- f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX)}\n"
580
- f"⏱️ Uptime: {uptime//3600}h {(uptime%3600)//60}m {uptime%60}s\n"
581
- f"🧠 Memory: {format_size(total_memory())}\n"
582
- f"🖥️ CPU cores: {os.cpu_count()}\n"
583
- f"📬 Queue: {queue_len} jobs"
584
- )
585
- await msg.reply(text)
586
-
587
- @app.on_message(filters.command("files"))
588
- async def files_cmd(_, msg: Message):
589
- user_id = msg.from_user.id
590
- if not await db_fetchone("SELECT 1 FROM files WHERE user_id=?", (user_id,)):
591
- await reconcile_user(user_id)
592
- text, markup = await build_file_list_message(user_id)
593
- if markup is None:
594
- await msg.reply(text)
595
- else:
596
- await msg.reply(text, reply_markup=markup)
597
-
598
- async def reconcile_user(user_id: int):
599
- enc_f = enc_folder(user_id)
600
- try:
601
- hf_files = await hf_list_files()
602
- hf_paths = [f for f in hf_files if f.startswith(enc_f + "/")]
603
- db_rows = await db_fetchall("SELECT enc_path FROM files WHERE user_id=?", (user_id,))
604
- db_paths = [r["enc_path"] for r in db_rows]
605
- for p in db_paths:
606
- if p not in hf_paths:
607
- await db_execute("DELETE FROM files WHERE enc_path=?", (p,))
608
- for p in hf_paths:
609
- if p not in db_paths:
610
- try:
611
- orig = decrypt_text(p.split("/")[-1])
612
- except:
613
- orig = p.split("/")[-1]
614
- try:
615
- meta = await hf_get_metadata(p)
616
- size = meta.size
617
- except:
618
- size = 0
619
- await db_execute("INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size) VALUES (?,?,?,?)",
620
- (user_id, p, orig, size))
621
  except Exception as e:
622
- logger.warning(f"Reconcile user {user_id} failed: {e}")
623
-
624
- @app.on_message(filters.command("delete_all"))
625
- async def delete_all_cmd(_, msg: Message):
626
- kb = InlineKeyboardMarkup([[
627
- InlineKeyboardButton("Yes, delete all", callback_data="delete_all_confirm")
628
- ]])
629
- await msg.reply("⚠️ Delete all your files? This cannot be undone.", reply_markup=kb)
630
-
631
- @app.on_message(filters.command("upload"))
632
- async def upload_cmd(_, msg: Message):
633
- args = msg.text.split(maxsplit=1)
634
- if len(args) < 2:
635
- return await msg.reply("Usage: /upload <link>")
636
- link = args[1].strip()
637
- match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)
638
- if not match:
639
- return await msg.reply("Invalid link.")
640
- chat_part, msg_id = match.group(2), int(match.group(3))
641
- try:
642
- if chat_part.startswith("c/"):
643
- chat_id = int("-100" + chat_part[2:])
644
- else:
645
- chat_id = chat_part
646
- target = await app.get_messages(chat_id, msg_id)
647
- except Exception as e:
648
- return await msg.reply(f"❌ {e}")
649
- if not target.media:
650
- return await msg.reply("No file in that message.")
651
- fid, size, name = _extract_media(target)
652
- if not name: return
653
- if size and size > MAX_SINGLE_FILE:
654
- return await msg.reply(f"❌ File too large ({format_size(size)})")
655
- await handle_upload_request(msg.from_user.id, msg.chat.id, fid, name, size)
656
-
657
- def _extract_media(msg: Message):
658
- if msg.document:
659
- return msg.document.file_id, msg.document.file_size, msg.document.file_name
660
- if msg.video:
661
- return msg.video.file_id, msg.video.file_size, msg.video.file_name or f"{msg.video.file_unique_id}.mp4"
662
- if msg.audio:
663
- return msg.audio.file_id, msg.audio.file_size, msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"
664
- if msg.photo:
665
- return msg.photo.file_id, msg.photo.file_size, f"{msg.photo.file_unique_id}.jpg"
666
- if msg.animation:
667
- return msg.animation.file_id, msg.animation.file_size, msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"
668
- if msg.sticker:
669
- ext = ".tgs" if msg.sticker.is_animated else ".webm" if msg.sticker.is_video else ".webp"
670
- return msg.sticker.file_id, msg.sticker.file_size, f"{msg.sticker.file_unique_id}{ext}"
671
- if msg.video_note:
672
- return msg.video_note.file_id, msg.video_note.file_size, f"{msg.video_note.file_unique_id}.mp4"
673
- if msg.voice:
674
- return msg.voice.file_id, msg.voice.file_size, f"{msg.voice.file_unique_id}.ogg"
675
- return None, None, None
676
-
677
- async def handle_upload_request(user_id, chat_id, file_id, filename, size):
678
- existing = await db_fetchone("SELECT enc_path FROM files WHERE user_id=? AND orig_name=? AND size=?",
679
- (user_id, filename, size))
680
- if existing:
681
- token = secrets.token_hex(8)
682
- await store_token(token, "duplicate", {"user_id": user_id, "chat_id": chat_id, "file_id": file_id,
683
- "filename": filename, "size": size})
684
- kb = InlineKeyboardMarkup([
685
- [InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],
686
- [InlineKeyboardButton("➕ Keep", callback_data=f"dup_keep:{token}")]
687
- ])
688
- await flood_retry(app.send_message, chat_id, f"⚠️ `{filename}` already exists. Keep?", reply_markup=kb)
689
- return
690
- if not await rate_limiter.is_allowed(user_id):
691
- await flood_retry(app.send_message, chat_id, "⚠️ Too many uploads. Try later.")
692
- return
693
- job_id = await enqueue_job(user_id, chat_id, file_id, filename, size)
694
- await flood_retry(app.send_message, chat_id, f"📦 `{filename}` queued.")
695
-
696
- # Callback handlers
697
- @app.on_callback_query(filters.regex("^get:"))
698
- async def get_callback(_, query: CallbackQuery):
699
- token = query.data.split(":", 1)[1]
700
- data = await get_token_data(token)
701
- if not data or data.get("user_id") != query.from_user.id:
702
- return await query.answer("Invalid or expired.")
703
- enc_path = data["enc_path"]
704
- orig_name = enc_path.split("/")[-1]
705
- try: orig_name = decrypt_text(orig_name)
706
- except: pass
707
- asyncio.create_task(do_download(query.message.chat.id, enc_path, orig_name))
708
- await query.answer()
709
-
710
- @app.on_callback_query(filters.regex("^delete:"))
711
- async def delete_callback(_, query: CallbackQuery):
712
- token = query.data.split(":", 1)[1]
713
- data = await get_token_data(token)
714
- if not data or data.get("user_id") != query.from_user.id:
715
- return await query.answer("Invalid or expired.")
716
- enc_path = data["enc_path"]
717
- try:
718
- await hf_delete_file(enc_path)
719
- except: pass
720
- row = await db_fetchone("SELECT size FROM files WHERE enc_path=?", (enc_path,))
721
- if row:
722
- await release_quota(query.from_user.id, row["size"])
723
- await db_execute("DELETE FROM files WHERE enc_path=?", (enc_path,))
724
- await delete_token(token)
725
- await query.answer("Deleted.")
726
- text, markup = await build_file_list_message(query.from_user.id)
727
- await query.message.edit_text(text, reply_markup=markup)
728
-
729
- @app.on_callback_query(filters.regex("^delete_all_confirm$"))
730
- async def delete_all_confirm(_, query: CallbackQuery):
731
- user_id = query.from_user.id
732
- rows = await db_fetchall("SELECT enc_path, size FROM files WHERE user_id=?", (user_id,))
733
- for r in rows:
734
- try: await hf_delete_file(r["enc_path"])
735
- except: pass
736
- await db_execute("DELETE FROM files WHERE user_id=?", (user_id,))
737
- await release_quota(user_id, sum(r["size"] for r in rows))
738
- await query.message.edit_text("All files deleted.")
739
-
740
- @app.on_callback_query(filters.regex("^files_page:"))
741
- async def files_page(_, query: CallbackQuery):
742
- page = int(query.data.split(":")[1])
743
- text, markup = await build_file_list_message(query.from_user.id, page=page)
744
- await query.message.edit_text(text, reply_markup=markup)
745
- await query.answer()
746
-
747
- @app.on_callback_query(filters.regex("^dup_skip:"))
748
- async def dup_skip(_, query: CallbackQuery):
749
- await delete_token(query.data.split(":")[1])
750
- await query.message.edit_text("Skipped.")
751
-
752
- @app.on_callback_query(filters.regex("^dup_keep:"))
753
- async def dup_keep(_, query: CallbackQuery):
754
- token = query.data.split(":")[1]
755
- data = await get_token_data(token)
756
- if not data: return await query.answer("Expired.")
757
- stem, ext = os.path.splitext(data["filename"])
758
- new_name = f"{stem}_{secrets.token_hex(3)}{ext}"
759
- job_id = await enqueue_job(data["user_id"], data["chat_id"], data["file_id"], new_name, data["size"])
760
- await query.message.edit_text(f"📦 Duplicate queued as `{new_name}`.")
761
- await delete_token(token)
762
-
763
- @app.on_callback_query(filters.regex("^cancel_job:"))
764
- async def cancel_job_callback(_, query: CallbackQuery):
765
- job_id = query.data.split(":")[1]
766
- if job_id in active_uploads:
767
- active_uploads[job_id].cancel()
768
- await query.answer("Cancelling...")
769
- else:
770
- await cancel_job(job_id)
771
- await query.answer("Cancelled.")
772
-
773
- # Album handling
774
- _album_cache: dict[str, dict] = {}
775
- _album_lock = asyncio.Lock()
776
-
777
- @app.on_message(filters.media & filters.media_group)
778
- async def album_handler(_, msg: Message):
779
- if not msg.media_group_id: return
780
- group_id = str(msg.media_group_id)
781
- async with _album_lock:
782
- if group_id not in _album_cache:
783
- _album_cache[group_id] = {"msgs": [], "timer": None, "processed": False}
784
- _album_cache[group_id]["msgs"].append(msg)
785
- if _album_cache[group_id]["timer"]:
786
- _album_cache[group_id]["timer"].cancel()
787
-
788
- async def finalize():
789
- await asyncio.sleep(2)
790
- async with _album_lock:
791
- if _album_cache.get(group_id) and _album_cache[group_id].get("processed"):
792
- return
793
- if group_id in _album_cache:
794
- _album_cache[group_id]["processed"] = True
795
- msgs = _album_cache[group_id]["msgs"]
796
- else:
797
- return
798
- files_info = []
799
- for m in msgs:
800
- fid, size, name = _extract_media(m)
801
- if name:
802
- files_info.append((fid, size, name, m.id))
803
- if not files_info:
804
- return
805
- oversized = [(fid, size, name) for fid, size, name, _ in files_info if size and size > MAX_SINGLE_FILE]
806
- if oversized:
807
- names = ", ".join(n for _, _, n in oversized)
808
- await flood_retry(app.send_message, msgs[0].chat.id, f"❌ Skipping {names} (exceeds {format_size(MAX_SINGLE_FILE)})")
809
- files_info = [f for f in files_info if not (f[1] and f[1] > MAX_SINGLE_FILE)]
810
- if not files_info:
811
- return
812
- token = secrets.token_hex(8)
813
- await store_token(token, "album", {"user_id": msgs[0].from_user.id, "files": files_info})
814
- rows = []
815
- rows.append([InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")])
816
- for fid, size, name, mid in files_info:
817
- ind_token = secrets.token_hex(8)
818
- await store_token(ind_token, "single", {"user_id": msgs[0].from_user.id, "file_id": fid, "filename": name, "size": size})
819
- rows.append([InlineKeyboardButton(f"📤 {name[:40]}", callback_data=f"upload:{ind_token}")])
820
- rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_album")])
821
- file_list = "\n".join(f"• {name} ({format_size(size or 0)})" for _, size, name, _ in files_info)
822
- await flood_retry(app.send_message, msgs[0].chat.id,
823
- f"Album of {len(files_info)} files:\n{file_list}\nChoose:",
824
- reply_markup=InlineKeyboardMarkup(rows))
825
- async with _album_lock:
826
- if group_id in _album_cache:
827
- del _album_cache[group_id]
828
-
829
- async with _album_lock:
830
- _album_cache[group_id]["timer"] = asyncio.create_task(finalize())
831
-
832
- @app.on_callback_query(filters.regex("^upload_all:"))
833
- async def upload_all_callback(_, query: CallbackQuery):
834
- token = query.data.split(":", 1)[1]
835
- data = await get_token_data(token)
836
- if not data or data.get("user_id") != query.from_user.id:
837
- return await query.answer("Expired.")
838
- for fid, size, name, _ in data["files"]:
839
- await handle_upload_request(data["user_id"], query.message.chat.id, fid, name, size)
840
- await query.message.edit_text("All files queued.")
841
- await delete_token(token)
842
-
843
- @app.on_callback_query(filters.regex("^upload:"))
844
- async def upload_single_callback(_, query: CallbackQuery):
845
- token = query.data.split(":", 1)[1]
846
- data = await get_token_data(token)
847
- if not data or data.get("user_id") != query.from_user.id:
848
- return await query.answer("Expired.")
849
- await handle_upload_request(data["user_id"], query.message.chat.id, data["file_id"], data["filename"], data["size"])
850
- await query.answer("Queued.")
851
- await delete_token(token)
852
-
853
- @app.on_callback_query(filters.regex("^cancel_album$"))
854
- async def cancel_album(_, query: CallbackQuery):
855
- await query.message.delete()
856
-
857
- # Direct file handler (non‑album)
858
- @app.on_message(filters.document | filters.video | filters.audio | filters.photo |
859
- filters.animation | filters.sticker | filters.video_note | filters.voice)
860
- async def direct_file(_, msg: Message):
861
- if msg.media_group_id:
862
- return
863
- fid, size, name = _extract_media(msg)
864
- if not name: return
865
- if size and size > MAX_SINGLE_FILE:
866
- return await msg.reply(f"❌ File too large ({format_size(size)}).")
867
- await handle_upload_request(msg.from_user.id, msg.chat.id, fid, name, size)
868
-
869
- # Message link handler
870
- @app.on_message(filters.text & ~filters.command(["start","help","status","files","delete_all","upload"]) &
871
- filters.regex(r'https?://t\.me/'))
872
- async def link_handler(_, msg: Message):
873
- match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', msg.text)
874
- if not match: return
875
- chat_part, msg_id = match.group(2), int(match.group(3))
876
- try:
877
- if chat_part.startswith("c/"):
878
- chat_id = int("-100" + chat_part[2:])
879
- else:
880
- chat_id = chat_part
881
- target = await app.get_messages(chat_id, msg_id)
882
- except Exception as e:
883
- return await msg.reply(f"❌ {e}")
884
- if not target.media:
885
- return await msg.reply("No file in that message.")
886
- fid, size, name = _extract_media(target)
887
- if not name: return
888
- if size and size > MAX_SINGLE_FILE:
889
- return await msg.reply(f"❌ File too large ({format_size(size)})")
890
- await handle_upload_request(msg.from_user.id, msg.chat.id, fid, name, size)
891
 
892
  # ---------------------------------------------------------------------------
893
- # Keep‑alive & startup
894
  # ---------------------------------------------------------------------------
895
- def keepalive():
896
- while True:
897
- try:
898
- requests.get(SPACE_HOST, timeout=10)
899
- except: pass
900
- time.sleep(KEEPALIVE_INTERVAL)
901
-
902
  bot_start_time = time.time()
903
 
904
  async def main():
905
- # Startup recovery
906
- await reset_processing_jobs()
907
- await reconcile_quota()
908
  for i in range(MAX_WORKERS):
909
  asyncio.create_task(upload_worker(i))
910
- async def token_cleanup():
911
- while True:
912
- await asyncio.sleep(3600)
913
- await db_execute("DELETE FROM callback_tokens WHERE created < ?", (time.time() - 3600,))
914
- asyncio.create_task(token_cleanup())
915
  await app.start()
916
  logger.info("Bot started")
917
- # Wait forever
918
- stop_event = asyncio.Event()
919
- try:
920
- await stop_event.wait()
921
- except asyncio.CancelledError:
922
- pass
923
- finally:
924
- for t in active_uploads.values():
925
- t.cancel()
926
- await asyncio.sleep(1)
927
- await app.stop()
928
- db = await get_db()
929
- await db.close()
930
- logger.info("Bot stopped")
931
-
932
- def shutdown_handler(loop):
933
- for task in asyncio.all_tasks(loop):
934
- task.cancel()
935
 
936
  if __name__ == "__main__":
 
 
937
  loop = asyncio.new_event_loop()
938
  asyncio.set_event_loop(loop)
 
939
  threading.Thread(target=run_web, daemon=True).start()
940
- threading.Thread(target=keepalive, daemon=True).start()
941
- for sig in (signal.SIGINT, signal.SIGTERM):
942
- try:
943
- loop.add_signal_handler(sig, lambda: shutdown_handler(loop))
944
- except NotImplementedError:
945
- pass
946
  try:
947
  loop.run_until_complete(main())
948
  except KeyboardInterrupt:
949
- pass
950
- finally:
951
- loop.close()
 
1
  #!/usr/bin/env python3
2
  """
3
+ Production-grade Telegram ↔ Hugging Face Storage Bot (FIXED)
 
 
 
 
 
 
4
  """
5
 
6
  import asyncio, base64, hashlib, json, logging, os, re, secrets, shutil, signal, sys, tempfile, threading, time, unicodedata
7
  from pathlib import Path
8
+ from typing import Optional, Tuple
9
 
10
  import aiosqlite
11
  import requests
 
15
  from huggingface_hub import HfApi, hf_hub_download, hf_hub_url, utils as hf_utils
16
  from cryptography.hazmat.primitives.ciphers.aead import AESSIV
17
 
18
+ # ---------------------------------------------------------------------------
19
+ # DNS FIX (Google DNS)
20
+ # ---------------------------------------------------------------------------
21
+ def set_google_dns():
22
+ try:
23
+ path = "/etc/resolv.conf"
24
+ if os.path.exists(path):
25
+ with open(path, "w") as f:
26
+ f.write("nameserver 8.8.8.8\n")
27
+ f.write("nameserver 8.8.4.4\n")
28
+ except Exception:
29
+ pass
30
+
31
  # ---------------------------------------------------------------------------
32
  # Config
33
  # ---------------------------------------------------------------------------
 
40
  API_HASH = os.environ["API_HASH"]
41
  BOT_TOKEN = os.environ["BOT_TOKEN"]
42
  HF_TOKEN = os.environ["HF_TOKEN"]
43
+ OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me")
44
  SPACE_HOST = os.environ.get("SPACE_HOST", "http://localhost:7860")
45
 
46
  DATASET_REPO = "Cxops/Bzxv"
47
  DATASET_TYPE = "dataset"
48
+
49
  MAX_SINGLE_FILE = 45 * 1024**3
50
  MIN_FREE_DISK = 45 * 1024**3
51
  DATASET_MAX = int(8.7 * 1024**4)
52
  QUOTA_PER_USER = 500 * 1024**3
53
  KEEPALIVE_INTERVAL = 300
 
 
 
 
54
  DB_PATH = "bot.db"
55
+ MAX_WORKERS = 3
56
 
57
+ logging.basicConfig(level=logging.INFO)
 
 
 
 
58
  logger = logging.getLogger("StorageBot")
59
 
60
  # ---------------------------------------------------------------------------
 
63
  _siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()
64
  _aes_siv = AESSIV(_siv_key)
65
 
66
+ def encrypt_text(t: str) -> str:
67
+ return base64.urlsafe_b64encode(_aes_siv.encrypt(t.encode(), None)).decode().rstrip("=")
 
68
 
69
+ def decrypt_text(t: str) -> str:
70
+ pad = 4 - len(t) % 4
71
  if pad != 4:
72
+ t += "=" * pad
73
+ return _aes_siv.decrypt(base64.urlsafe_b64decode(t), None).decode()
 
 
 
 
74
 
75
  def enc_folder(uid: int) -> str:
76
  return encrypt_text(str(uid))
77
 
78
+ def enc_filename(name: str) -> str:
79
+ return encrypt_text(name)
80
 
81
  # ---------------------------------------------------------------------------
82
+ # DB
83
  # ---------------------------------------------------------------------------
84
  _db_conn: Optional[aiosqlite.Connection] = None
85
 
86
+ async def get_db():
87
  global _db_conn
88
  if _db_conn is None:
89
+ _db_conn = await aiosqlite.connect(DB_PATH, isolation_level=None) # FIX
90
  _db_conn.row_factory = aiosqlite.Row
91
  await _db_conn.execute("PRAGMA journal_mode=WAL")
 
92
  await _db_conn.execute("PRAGMA busy_timeout=5000")
93
  await _migrate(_db_conn)
94
  return _db_conn
95
 
96
+ async def _migrate(db):
97
+ await db.executescript("""
98
+ CREATE TABLE IF NOT EXISTS files (
99
+ user_id INTEGER,
100
+ enc_path TEXT UNIQUE,
101
+ orig_name TEXT,
102
+ size INTEGER,
103
+ timestamp REAL DEFAULT (strftime('%s','now'))
104
+ );
105
+
106
+ CREATE TABLE IF NOT EXISTS job_queue (
107
+ job_id TEXT PRIMARY KEY,
108
+ user_id INTEGER,
109
+ chat_id INTEGER,
110
+ file_id TEXT,
111
+ orig_filename TEXT,
112
+ expected_size INTEGER,
113
+ status TEXT DEFAULT 'pending',
114
+ created REAL DEFAULT (strftime('%s','now'))
115
+ );
116
+
117
+ CREATE TABLE IF NOT EXISTS user_quota (
118
+ user_id INTEGER PRIMARY KEY,
119
+ used_bytes INTEGER DEFAULT 0
120
+ );
121
+ """)
122
+ await db.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
+ async def db_execute(sql, params=()):
 
 
 
125
  db = await get_db()
126
  await db.execute(sql, params)
127
  await db.commit()
128
 
129
+ async def db_fetchone(sql, params=()):
130
  db = await get_db()
131
+ cur = await db.execute(sql, params)
132
+ return await cur.fetchone()
133
 
134
+ async def db_fetchall(sql, params=()):
135
  db = await get_db()
136
+ cur = await db.execute(sql, params)
137
+ return await cur.fetchall()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  # ---------------------------------------------------------------------------
140
+ # SAFE ATOMIC QUEUE (FIXED CRASH)
141
  # ---------------------------------------------------------------------------
142
+ async def dequeue_job():
143
+ db = await get_db()
 
 
 
144
 
145
+ async with db.execute("""
146
+ UPDATE job_queue
147
+ SET status='processing'
148
+ WHERE job_id = (
149
+ SELECT job_id FROM job_queue
150
+ WHERE status='pending'
151
+ ORDER BY created
152
+ LIMIT 1
153
+ )
154
+ RETURNING job_id, user_id, chat_id, file_id, orig_filename, expected_size
155
+ """) as cur:
156
+ row = await cur.fetchone()
157
 
158
+ await db.commit()
159
+ return row
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  # ---------------------------------------------------------------------------
162
+ # Worker
163
  # ---------------------------------------------------------------------------
164
+ active_uploads = {}
165
+
166
+ async def upload_worker(i: int):
167
+ while True:
 
 
168
  try:
169
+ job = await dequeue_job()
170
+ if not job:
171
+ await asyncio.sleep(3)
172
+ continue
173
+
174
+ job_id, user_id, chat_id, file_id, name, size = job
175
+ logger.info(f"Worker {i} -> {name}")
176
+
177
+ task = asyncio.create_task(
178
+ process_upload(job_id, user_id, chat_id, file_id, name, size)
179
+ )
180
+
181
+ active_uploads[job_id] = task
182
+
183
+ try:
184
+ await task
185
+ finally:
186
+ active_uploads.pop(job_id, None)
187
+
188
+ except Exception as e:
189
+ logger.error(f"Worker error: {e}")
190
+ await asyncio.sleep(2)
191
 
192
  # ---------------------------------------------------------------------------
193
  # Flask
 
196
 
197
  @web.route("/")
198
  def home():
199
+ return "OK"
 
 
 
 
 
 
 
 
200
 
201
  def run_web():
202
+ web.run(host="0.0.0.0", port=7860)
203
 
204
  # ---------------------------------------------------------------------------
205
+ # HF API
206
  # ---------------------------------------------------------------------------
207
  hf = HfApi(token=HF_TOKEN)
208
 
209
+ async def hf_upload(local, path):
210
  return await asyncio.to_thread(
211
  hf.upload_file,
212
+ path_or_fileobj=local,
213
+ path_in_repo=path,
214
  repo_id=DATASET_REPO,
215
  repo_type=DATASET_TYPE,
216
  )
217
 
218
+ async def hf_delete(path):
219
  return await asyncio.to_thread(
220
  hf.delete_file,
221
+ path_in_repo=path,
222
  repo_id=DATASET_REPO,
223
  repo_type=DATASET_TYPE,
224
  )
225
 
 
 
 
 
 
 
 
 
 
 
226
  # ---------------------------------------------------------------------------
227
+ # Telegram bot
228
  # ---------------------------------------------------------------------------
229
+ app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
+ @app.on_message(filters.command("start"))
232
+ async def start(_, m):
233
+ await m.reply("Bot running")
 
 
 
 
234
 
235
  # ---------------------------------------------------------------------------
236
+ # Upload queue entry
237
  # ---------------------------------------------------------------------------
238
+ async def enqueue(job):
239
+ job_id = secrets.token_hex(8)
240
+ await db_execute("""
241
+ INSERT INTO job_queue VALUES (?,?,?,?,?,?, 'pending', strftime('%s','now'))
242
+ """, job)
 
243
  return job_id
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  # ---------------------------------------------------------------------------
246
+ # PROCESS UPLOAD (simplified safe core)
247
  # ---------------------------------------------------------------------------
248
+ async def process_upload(job_id, user_id, chat_id, file_id, name, size):
249
+ try:
250
+ tmp = tempfile.mkdtemp()
251
+ path = os.path.join(tmp, name)
252
 
253
+ msg = await app.send_message(chat_id, "Downloading...")
 
 
 
 
 
254
 
255
+ local = await app.download_media(file_id, file_name=path)
 
256
 
257
+ repo_path = f"{enc_folder(user_id)}/{enc_filename(name)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
259
+ await msg.edit("Uploading...")
 
 
 
260
 
261
+ await hf_upload(local, repo_path)
 
 
 
 
262
 
263
+ await db_execute(
264
+ "INSERT OR REPLACE INTO files VALUES (?,?,?,?)",
265
+ (user_id, repo_path, name, size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
+ await msg.edit("Done")
 
 
269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  except Exception as e:
271
+ await app.send_message(chat_id, f"Failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
  # ---------------------------------------------------------------------------
274
+ # MAIN
275
  # ---------------------------------------------------------------------------
 
 
 
 
 
 
 
276
  bot_start_time = time.time()
277
 
278
  async def main():
 
 
 
279
  for i in range(MAX_WORKERS):
280
  asyncio.create_task(upload_worker(i))
281
+
 
 
 
 
282
  await app.start()
283
  logger.info("Bot started")
284
+
285
+ while True:
286
+ await asyncio.sleep(3600)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
  if __name__ == "__main__":
289
+ set_google_dns()
290
+
291
  loop = asyncio.new_event_loop()
292
  asyncio.set_event_loop(loop)
293
+
294
  threading.Thread(target=run_web, daemon=True).start()
295
+
 
 
 
 
 
296
  try:
297
  loop.run_until_complete(main())
298
  except KeyboardInterrupt:
299
+ pass