Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294import asyncio, base64, hashlib, json, logging, os, re, secrets, shutil, signal, sys, tempfile, threading, time, unicodedatafrom pathlib import Pathfrom typing import Optional, Tupleimport aiosqliteimport requestsfrom flask import Flaskfrom pyrogram import Client, filters, errors as pyro_errorsfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQueryfrom huggingface_hub import HfApi, hf_hub_download, hf_hub_url, utils as hf_utilsfrom cryptography.hazmat.primitives.ciphers.aead import AESSIV# ---------------------------------------------------------------------------# DNS FIX (Google DNS)# ---------------------------------------------------------------------------def set_google_dns():try:path = "/etc/resolv.conf"if os.path.exists(path):with open(path, "w") as f:f.write("nameserver 8.8.8.8\n")f.write("nameserver 8.8.4.4\n")except Exception:pass# ---------------------------------------------------------------------------# Config# ---------------------------------------------------------------------------REQUIRED_ENV = ["API_ID", "API_HASH", "BOT_TOKEN", "HF_TOKEN"]for var in REQUIRED_ENV:if var not in os.environ:raise SystemExit(f"Missing environment variable: {var}")API_ID = int(os.environ["API_ID"])API_HASH = os.environ["API_HASH"]BOT_TOKEN = os.environ["BOT_TOKEN"]HF_TOKEN = os.environ["HF_TOKEN"]OBFUSCATION_KEY = os.environ.get("OBFUSCATION_KEY", "change-me")SPACE_HOST = os.environ.get("SPACE_HOST", "http://localhost:7860")DATASET_REPO = "Cxops/Bzxv"DATASET_TYPE = "dataset"MAX_SINGLE_FILE = 45 * 1024**3MIN_FREE_DISK = 45 * 1024**3DATASET_MAX = int(8.7 * 1024**4)QUOTA_PER_USER = 500 * 1024**3KEEPALIVE_INTERVAL = 300DB_PATH = "bot.db"MAX_WORKERS = 3logging.basicConfig(level=logging.INFO)logger = logging.getLogger("StorageBot")# ---------------------------------------------------------------------------# Encryption# ---------------------------------------------------------------------------_siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()_aes_siv = AESSIV(_siv_key)def encrypt_text(t: str) -> str:return base64.urlsafe_b64encode(_aes_siv.encrypt(t.encode(), None)).decode().rstrip("=")def decrypt_text(t: str) -> str:pad = 4 - len(t) % 4if pad != 4:t += "=" * padreturn _aes_siv.decrypt(base64.urlsafe_b64decode(t), None).decode()def enc_folder(uid: int) -> str:return encrypt_text(str(uid))def enc_filename(name: str) -> str:return encrypt_text(name)# ---------------------------------------------------------------------------# DB# ---------------------------------------------------------------------------_db_conn: Optional[aiosqlite.Connection] = Noneasync def get_db():global _db_connif _db_conn is None:_db_conn = await aiosqlite.connect(DB_PATH, isolation_level=None) # FIX_db_conn.row_factory = aiosqlite.Rowawait _db_conn.execute("PRAGMA journal_mode=WAL")await _db_conn.execute("PRAGMA busy_timeout=5000")await _migrate(_db_conn)return _db_connasync def _migrate(db):await db.executescript("""CREATE TABLE IF NOT EXISTS files (user_id INTEGER,enc_path TEXT UNIQUE,orig_name TEXT,size INTEGER,timestamp REAL DEFAULT (strftime('%s','now')));CREATE TABLE IF NOT EXISTS job_queue (job_id TEXT PRIMARY KEY,user_id INTEGER,chat_id INTEGER,file_id TEXT,orig_filename TEXT,expected_size INTEGER,status TEXT DEFAULT 'pending',created REAL DEFAULT (strftime('%s','now')));CREATE TABLE IF NOT EXISTS user_quota (user_id INTEGER PRIMARY KEY,used_bytes INTEGER DEFAULT 0);""")await db.commit()async def db_execute(sql, params=()):db = await get_db()await db.execute(sql, params)await db.commit()async def db_fetchone(sql, params=()):db = await get_db()cur = await db.execute(sql, params)return await cur.fetchone()async def db_fetchall(sql, params=()):db = await get_db()cur = await db.execute(sql, params)return await cur.fetchall()# ---------------------------------------------------------------------------# SAFE ATOMIC QUEUE (FIXED CRASH)# ---------------------------------------------------------------------------async def dequeue_job():db = await get_db()async with db.execute("""UPDATE job_queueSET status='processing'WHERE job_id = (SELECT job_id FROM job_queueWHERE status='pending'ORDER BY createdLIMIT 1)RETURNING job_id, user_id, chat_id, file_id, orig_filename, expected_size""") as cur:row = await cur.fetchone()await db.commit()return row# ---------------------------------------------------------------------------# Worker# ---------------------------------------------------------------------------active_uploads = {}async def upload_worker(i: int):while True:try:job = await dequeue_job()if not job:await asyncio.sleep(3)continuejob_id, user_id, chat_id, file_id, name, size = joblogger.info(f"Worker {i} -> {name}")task = asyncio.create_task(process_upload(job_id, user_id, chat_id, file_id, name, size))active_uploads[job_id] = tasktry:await taskfinally:active_uploads.pop(job_id, None)except Exception as e:logger.error(f"Worker error: {e}")await asyncio.sleep(2)# ---------------------------------------------------------------------------# Flask# ---------------------------------------------------------------------------web = Flask(__name__)@web.route("/")def home():return "OK"def run_web():web.run(host="0.0.0.0", port=7860)# ---------------------------------------------------------------------------# HF API# ---------------------------------------------------------------------------hf = HfApi(token=HF_TOKEN)async def hf_upload(local, path):return await asyncio.to_thread(hf.upload_file,path_or_fileobj=local,path_in_repo=path,repo_id=DATASET_REPO,repo_type=DATASET_TYPE,)async def hf_delete(path):return await asyncio.to_thread(hf.delete_file,path_in_repo=path,repo_id=DATASET_REPO,repo_type=DATASET_TYPE,)# ---------------------------------------------------------------------------# Telegram bot# ---------------------------------------------------------------------------app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)@app.on_message(filters.command("start"))async def start(_, m):await m.reply("Bot running")# ---------------------------------------------------------------------------# Upload queue entry# ---------------------------------------------------------------------------async def enqueue(job):job_id = secrets.token_hex(8)await db_execute("""INSERT INTO job_queue VALUES (?,?,?,?,?,?, 'pending', strftime('%s','now'))""", job)return job_id# ---------------------------------------------------------------------------# PROCESS UPLOAD (simplified safe core)# ---------------------------------------------------------------------------async def process_upload(job_id, user_id, chat_id, file_id, name, size):try:tmp = tempfile.mkdtemp()path = os.path.join(tmp, name)msg = await app.send_message(chat_id, "Downloading...")local = await app.download_media(file_id, file_name=path)repo_path = f"{enc_folder(user_id)}/{enc_filename(name)}"await msg.edit("Uploading...")await hf_upload(local, repo_path)await db_execute("INSERT OR REPLACE INTO files VALUES (?,?,?,?)",(user_id, repo_path, name, size))await msg.edit("Done")except Exception as e:await app.send_message(chat_id, f"Failed: {e}")# ---------------------------------------------------------------------------# MAIN# ---------------------------------------------------------------------------bot_start_time = time.time()async def main():for i in range(MAX_WORKERS):asyncio.create_task(upload_worker(i))await app.start()logger.info("Bot started")while True:await asyncio.sleep(3600)if __name__ == "__main__":set_google_dns()loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)threading.Thread(target=run_web, daemon=True).start()try:loop.run_until_complete(main())except KeyboardInterrupt:pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243import os, re, sys, time, base64, hashlib, shutil, logging, secrets, sqlite3, tempfile, threading, asynciofrom pathlib import Pathfrom typing import Optional, List, Tuple, Unionimport requestsfrom flask import Flaskfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQueryfrom huggingface_hub import HfApi, get_hf_file_metadata, hf_hub_download, hf_hub_urlfrom cryptography.hazmat.primitives.ciphers.aead import AESSIV# =============================================================================# CONFIGURATION# =============================================================================API_ID: int = int(os.environ["API_ID"])API_HASH: str = os.environ["API_HASH"]BOT_TOKEN: str = os.environ["BOT_TOKEN"]HF_TOKEN: str = os.environ["HF_TOKEN"]OBFUSCATION_KEY: str = os.environ.get("OBFUSCATION_KEY", "change-me-to-a-secret-string")SPACE_HOST: str = "https://cxops-push.hf.space" # Keep‑alive URLDATASET_REPO: str = "Cxops/Bzxv"DATASET_TYPE: str = "dataset"MAX_FILE_SIZE_TG: int = 1900 * 1024 * 1024 # 1900 MB per Telegram part (splitting)MAX_SINGLE_FILE_SIZE: int = 45 * 1024**3 # 45 GB – refuse larger uploadsMIN_FREE_DISK: int = 45 * 1024 * 1024 * 1024 # 45 GBDATASET_MAX_SIZE: int = int(8.7 * 1024**4) # 8.7 TBKEEPALIVE_INTERVAL: int = 300 # 5 minutesUPLOAD_TIMEOUT: int = 7200 # 2 hours per upload jobDB_PATH: str = "bot_files.db"# Optimisation: larger block size for faster Telegram downloads (1 MB)DOWNLOAD_BLOCK_SIZE: int = 1024 * 1024 # 1 MB# Logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",handlers=[logging.StreamHandler(sys.stdout)],)logger = logging.getLogger("StorageBot")# =============================================================================# DETERMINISTIC ENCRYPTION (AES‑SIV)# =============================================================================_siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()_aes_siv = AESSIV(_siv_key)def encrypt_text(plain: str) -> str:token = _aes_siv.encrypt(plain.encode(), None)return base64.urlsafe_b64encode(token).decode().rstrip("=")def decrypt_text(encoded: str) -> str:padding = 4 - len(encoded) % 4if padding != 4:encoded += "=" * paddingtoken = base64.urlsafe_b64decode(encoded.encode())return _aes_siv.decrypt(token, None).decode()def get_encrypted_folder(user_id: int) -> str:return encrypt_text(str(user_id))def get_encrypted_filename(original: str) -> str:return encrypt_text(original)# =============================================================================# DATABASE (WAL mode for concurrency)# =============================================================================conn = sqlite3.connect(DB_PATH, check_same_thread=False)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA journal_mode=WAL")cursor = conn.cursor()cursor.execute("""CREATE TABLE IF NOT EXISTS files (user_id INTEGER,enc_path TEXT UNIQUE,orig_name TEXT,size INTEGER,timestamp REAL)""")conn.commit()def db_add_file(user_id: int, enc_path: str, orig_name: str, size: int) -> None:cursor.execute("INSERT OR REPLACE INTO files (user_id, enc_path, orig_name, size, timestamp) VALUES (?, ?, ?, ?, ?)",(user_id, enc_path, orig_name, size, time.time()),)conn.commit()def db_get_user_files(user_id: int) -> List[Tuple[str, str, int]]:cursor.execute("SELECT enc_path, orig_name, size FROM files WHERE user_id = ? ORDER BY timestamp DESC",(user_id,),)return [(row[0], row[1], row[2]) for row in cursor.fetchall()]def db_remove_file(enc_path: str) -> None:cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))conn.commit()def db_remove_all_user_files(user_id: int) -> None:cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))conn.commit()def db_file_exists(user_id: int, orig_name: str, size: Optional[int] = None) -> Optional[Tuple[str, int]]:"""Check if a file with given name (and optionally exact size) exists.Returns (enc_path, size) if found, else None."""if size is not None:cursor.execute("SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ? AND size = ?",(user_id, orig_name, size),)else:cursor.execute("SELECT enc_path, size FROM files WHERE user_id = ? AND orig_name = ?",(user_id, orig_name),)row = cursor.fetchone()return (row[0], row[1]) if row else None# =============================================================================# IN‑MEMORY TOKEN STORES# =============================================================================file_callback_map: dict[str, str] = {} # token → enc_pathupload_prompt_map: dict[str, List[Tuple]] = {} # token → list of entriesalbum_groups: dict[str, dict] = {}duplicate_prompt_map: dict[str, dict] = {} # token → duplicate infodef make_token() -> str:return secrets.token_hex(8)# =============================================================================# FLASK HEALTH CHECK# =============================================================================web = Flask(__name__)@web.route("/")def home():return "Status: OK - Bot Running"def run_web():web.run(host="0.0.0.0", port=7860)# =============================================================================# HUGGING FACE API & PYROGRAM CLIENT# =============================================================================hf = HfApi(token=HF_TOKEN)app = Client("storage_bot",api_id=API_ID,api_hash=API_HASH,bot_token=BOT_TOKEN,)# =============================================================================# GLOBAL STATE# =============================================================================upload_queue: asyncio.Queue = asyncio.Queue()active_jobs: dict[int, dict] = {}bot_start_time = time.time()# =============================================================================# UTILITY HELPERS# =============================================================================def cleanup(path: str) -> None:try:if os.path.isdir(path):shutil.rmtree(path, ignore_errors=True)elif os.path.isfile(path):os.remove(path)except Exception:passdef get_free_disk() -> int:return shutil.disk_usage("/").freedef format_size(bytes_val: int) -> str:for unit in ['B', 'KB', 'MB', 'GB', 'TB']:if bytes_val < 1024.0:return f"{bytes_val:.1f} {unit}"bytes_val /= 1024.0return f"{bytes_val:.1f} PB"def format_speed(bytes_per_sec: float) -> str:return f"{format_size(bytes_per_sec)}/s"def get_total_memory() -> int:"""Returns the total memory available to the container (in bytes).Tries cgroup v1 limit first, then falls back to /proc/meminfo MemTotal."""try:with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:limit = int(f.read().strip())if limit < 9_223_372_036_854_771_200: # less than practically infinitereturn limitexcept Exception:passtry:with open("/proc/meminfo") as f:for line in f:if line.startswith("MemTotal:"):return int(line.split()[1]) * 1024 # kB → bytesexcept Exception:passreturn 0def extract_file_size(msg: Message) -> Optional[int]:if msg.document:return msg.document.file_sizeif msg.video:return msg.video.file_sizeif msg.audio:return msg.audio.file_sizeif msg.photo:return msg.photo.file_sizeif msg.animation:return msg.animation.file_sizeif msg.sticker:return msg.sticker.file_sizeif msg.video_note:return msg.video_note.file_sizeif msg.voice:return msg.voice.file_sizereturn Nonedef check_file_size_limit(filename: str, size: Optional[int]) -> Optional[str]:if size is not None and size > MAX_SINGLE_FILE_SIZE:return f"❌ File `{filename}` is too large ({format_size(size)}). Maximum allowed is {format_size(MAX_SINGLE_FILE_SIZE)}."return Noneasync def send_progress_updater(job_id: int,status_msg: Message,cancel_event: asyncio.Event,total_bytes: int,) -> Tuple[asyncio.Task, list]:bytes_holder = [0]start_time = time.time()async def updater():while not cancel_event.is_set():elapsed = max(time.time() - start_time, 0.01)current = bytes_holder[0]speed = current / elapsedtext = "📤 Sending to Telegram...\n"if total_bytes > 0:pct = (100 * current / total_bytes)text += f"{pct:.1f}% of {format_size(total_bytes)}\n"text += f"{format_size(current)} sent / {format_size(total_bytes)}\n"else:text += f"{format_size(current)} sent\n"text += f"Speed: {format_speed(speed)}\n"if total_bytes > 0 and speed > 0:eta = int((total_bytes - current) / speed)text += f"ETA: {eta}s"else:text += "ETA: ..."try:await status_msg.edit_text(text,reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)except Exception:breakawait asyncio.sleep(3)task = asyncio.create_task(updater())return task, bytes_holder# =============================================================================# CORE UPLOAD / DOWNLOAD LOGIC# =============================================================================async def do_upload_job(user_id: int,chat_id: int,file_msg_or_id: Union[Message, str],orig_filename: str,job_id: int,cancel_event: asyncio.Event,status_msg: Message,file_id: Optional[str] = None,expected_size: Optional[int] = None,) -> None:temp_dir = tempfile.mkdtemp()local_path = Nonetry:await status_msg.edit_text("⬇️ Downloading from Telegram...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)last_update = [0]download_start = time.time()total_size = expected_size if expected_size and expected_size > 0 else 0async def download_progress(current, total):nonlocal total_sizenow = time.time()if now - last_update[0] < 3:returnlast_update[0] = nowelapsed = max(time.time() - download_start, 0.01)speed = current / elapsedif total and total > 0:total_size = totalelif total_size == 0 and expected_size and expected_size > 0:total_size = expected_sizetext = "⬇️ Downloading from Telegram...\n"if total_size > 0:pct = (100 * current / total_size)text += f"{pct:.1f}% of {format_size(total_size)}\n"text += f"{format_size(current)} downloaded / {format_size(total_size)}\n"else:text += f"{format_size(current)} downloaded\n"text += f"Speed: {format_speed(speed)}"try:await status_msg.edit_text(text,reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)except Exception:passif isinstance(file_msg_or_id, Message):local_path = await file_msg_or_id.download(file_name=os.path.join(temp_dir, orig_filename),block_size=DOWNLOAD_BLOCK_SIZE,progress=download_progress,)else:local_path = await app.download_media(file_msg_or_id,file_name=os.path.join(temp_dir, orig_filename),block_size=DOWNLOAD_BLOCK_SIZE,progress=download_progress,)if cancel_event.is_set():returnfile_size = os.path.getsize(local_path)enc_folder = get_encrypted_folder(user_id)enc_filename = get_encrypted_filename(orig_filename)repo_path = f"{enc_folder}/{enc_filename}"await status_msg.edit_text("⬆️ Uploading to Hugging Face...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)loop = asyncio.get_event_loop()def sync_upload():hf.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,repo_id=DATASET_REPO,repo_type=DATASET_TYPE,)task = loop.run_in_executor(None, sync_upload)try:await asyncio.wait_for(asyncio.wrap_future(task), timeout=UPLOAD_TIMEOUT)except asyncio.TimeoutError:await status_msg.edit_text("❌ Upload timed out.", reply_markup=None)returnif cancel_event.is_set():try:hf.delete_file(path_in_repo=repo_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)except Exception:passawait status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)returndb_add_file(user_id, repo_path, orig_filename, file_size)await status_msg.edit_text(f"✅ Uploaded: `{orig_filename}`", reply_markup=None)logger.info("Uploaded %s for user %d", orig_filename, user_id)except Exception as e:logger.exception("Upload failed for %s", orig_filename)await status_msg.edit_text(f"❌ Upload failed: {e}", reply_markup=None)finally:cleanup(temp_dir)async def do_download_job(chat_id: int,enc_path: str,orig_name: str,job_id: int,cancel_event: asyncio.Event,status_msg: Message,) -> None:temp_dir = tempfile.mkdtemp()try:loop = asyncio.get_event_loop()await status_msg.edit_text("⬇️ Downloading from dataset...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)download_future = loop.run_in_executor(None,lambda: hf_hub_download(repo_id=DATASET_REPO,filename=enc_path,repo_type=DATASET_TYPE,token=HF_TOKEN,local_dir=temp_dir,),)while not download_future.done():if cancel_event.is_set():await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)returnawait asyncio.sleep(1)local_file = download_future.result()total_size = os.path.getsize(local_file)if total_size <= MAX_FILE_SIZE_TG:prog_task, bytes_holder = await send_progress_updater(job_id, status_msg, cancel_event, total_size)async def send_progress(current, total):bytes_holder[0] = currentawait app.send_document(chat_id,document=local_file,file_name=orig_name,caption=orig_name,progress=send_progress,)prog_task.cancel()await status_msg.delete()else:part_size = MAX_FILE_SIZE_TGnum_parts = -(-total_size // part_size)with open(local_file, "rb") as f:for i in range(1, num_parts + 1):if cancel_event.is_set():await status_msg.edit_text("❌ Cancelled during send.")returnawait status_msg.edit_text(f"📤 Sending part {i}/{num_parts}...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)chunk = f.read(part_size)part_name = f"{orig_name}.part{i}of{num_parts}"part_path = os.path.join(temp_dir, part_name)with open(part_path, "wb") as p:p.write(chunk)await app.send_document(chat_id,document=part_path,file_name=part_name,caption=f"{orig_name} – Part {i}/{num_parts}",)os.remove(part_path)await status_msg.delete()logger.info("Downloaded %s for chat %d", orig_name, chat_id)except Exception as e:logger.exception("Download failed for %s", orig_name)await status_msg.edit_text(f"❌ Download failed: {e}")finally:cleanup(temp_dir)# =============================================================================# DELETION HELPERS# =============================================================================async def delete_user_file(chat_id, user_id, enc_path, token, query: CallbackQuery):try:hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)db_remove_file(enc_path)file_callback_map.pop(token, None)await query.answer("File deleted.", show_alert=True)await refresh_file_list(chat_id, user_id, query.message)except Exception as e:await query.answer(f"Error: {e}", show_alert=True)async def delete_all_user_files(chat_id, user_id, query: CallbackQuery):user_files = db_get_user_files(user_id)if not user_files:await query.answer("No files to delete.", show_alert=True)returnfor enc_path, _, _ in user_files:try:hf.delete_file(path_in_repo=enc_path, repo_id=DATASET_REPO, repo_type=DATASET_TYPE)except Exception:passdb_remove_all_user_files(user_id)tokens_to_delete = [tok for tok, path in file_callback_map.items() if path.startswith(get_encrypted_folder(user_id))]for tok in tokens_to_delete:file_callback_map.pop(tok, None)await query.answer(f"Deleted {len(user_files)} file(s).", show_alert=True)await refresh_file_list(chat_id, user_id, query.message)async def refresh_file_list(chat_id: int, user_id: int, message: Message):user_files = db_get_user_files(user_id)if not user_files:return await message.edit_text("You have no uploaded files.", reply_markup=None)buttons = []for enc_path, orig_name, size in user_files:token = make_token()file_callback_map[token] = enc_pathdisplay = f"{orig_name[:25]} ({format_size(size)})" if size else orig_name[:25]buttons.append([InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),])buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])await message.edit_text("Your uploaded files (click to download, delete to remove):",reply_markup=InlineKeyboardMarkup(buttons),)# =============================================================================# DUPLICATE DETECTION & RENAMING# =============================================================================def build_duplicate_prompt(user_id: int,chat_id: int,file_obj: Union[Message, str],orig_filename: str,expected_size: Optional[int],file_id: Optional[str] = None,msg_id: Optional[int] = None,) -> Tuple[Optional[str], Optional[dict]]:"""Returns token and prompt data if the file already exists, else (None, None)."""existing = db_file_exists(user_id, orig_filename, expected_size)if not existing:existing = db_file_exists(user_id, orig_filename) # any sizeif not existing:return None, None_, existing_size = existingtoken = make_token()duplicate_prompt_map[token] = {'user_id': user_id,'chat_id': chat_id,'file_obj': file_obj,'orig_filename': orig_filename,'job_id': int(time.time() * 1000 + hash(orig_filename)),'file_id': file_id,'expected_size': expected_size,'existing_size': existing_size,'msg_id': msg_id, # for album duplicate retrieval}return token, duplicate_prompt_map[token]async def send_duplicate_prompt(chat_id, token, orig_filename, expected_size, existing_size):if expected_size is not None and existing_size is not None and expected_size == existing_size:size_note = f" (same size: {format_size(expected_size)})"else:size_note = f" (existing size: {format_size(existing_size or 0)})" if existing_size else ""kb = InlineKeyboardMarkup([[InlineKeyboardButton("⏭️ Skip", callback_data=f"dup_skip:{token}")],[InlineKeyboardButton("➕ Keep Duplicate", callback_data=f"dup_keep:{token}")],])await app.send_message(chat_id,f"⚠️ File `{orig_filename}` already exists{size_note}.\nWhat do you want to do?",reply_markup=kb,)def generate_unique_filename(user_id: int, base: str, ext: str) -> str:"""Creates a filename like base_1.ext that doesn't exist for this user yet."""counter = 1while True:candidate = f"{base}_{counter}{ext}"if not db_file_exists(user_id, candidate):return candidatecounter += 1# =============================================================================# ALBUM GROUPING# =============================================================================async def process_album_group(media_group_id: str):group_data = album_groups.pop(media_group_id, None)if not group_data:returnchat_id = group_data['chat_id']user_id = group_data['user_id']messages = group_data['messages'] # list of (message_id, filename, file_id, size)valid_files = []skipped_names = []for msg_id, filename, file_id, size in messages:limit_msg = check_file_size_limit(filename, size)if limit_msg:skipped_names.append(filename)else:valid_files.append((msg_id, filename, file_id, size))if not valid_files:if skipped_names:skip_text = "\n".join(f"• `{f}`" for f in skipped_names)await app.send_message(chat_id,f"❌ All files exceed the {format_size(MAX_SINGLE_FILE_SIZE)} limit and were skipped:\n{skip_text}")return# Single pass: separate duplicates and clean filesnon_dup = []dup_entries = []for msg_id, filename, file_id, size in valid_files:token, data = build_duplicate_prompt(user_id, chat_id, None, filename, size, file_id, msg_id)if token:dup_entries.append((token, data))else:non_dup.append((msg_id, filename, file_id, size))# Send duplicate prompts individuallyfor token, data in dup_entries:await send_duplicate_prompt(chat_id, token, data['orig_filename'],data['expected_size'], data['existing_size'])if non_dup:if len(non_dup) == 1:msg_id, filename, file_id, _ = non_dup[0]token = make_token()upload_prompt_map[token] = [(user_id, msg_id, filename, file_id)]kb = InlineKeyboardMarkup([[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],])await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)else:files_list = "\n".join(f"• {fname} ({format_size(fsize)})" for _, fname, _, fsize in non_dup)token = make_token()upload_prompt_map[token] = [(user_id, msg_id, fname, fid) for msg_id, fname, fid, _ in non_dup]button_rows = [[InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")]]for msg_id, fname, fid, _ in non_dup:individual_token = make_token()upload_prompt_map[individual_token] = [(user_id, msg_id, fname, fid)]button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])button_rows.append([InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")])prompt_text = f"Received {len(non_dup)} non‑duplicate files.\n{files_list}\n\nChoose:"if skipped_names:prompt_text += f"\n⚠️ Skipped (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names)await app.send_message(chat_id, prompt_text, reply_markup=InlineKeyboardMarkup(button_rows))# Notify about skipped files regardlessif skipped_names:skip_msg = f"⚠️ Skipped {len(skipped_names)} file(s) (exceed {format_size(MAX_SINGLE_FILE_SIZE)}): " + ", ".join(f"`{f}`" for f in skipped_names)if not non_dup: # only skipped message was not sent aboveawait app.send_message(chat_id, skip_msg)else:# Already appended to prompt, but we can send a separate one if needed; however it's included in prompt.pass# =============================================================================# UPLOAD QUEUE WORKER# =============================================================================async def upload_worker():while True:job = await upload_queue.get()user_id, chat_id, file_obj, orig_filename, job_id, file_id, expected_size = jobcancel_event = asyncio.Event()active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}while get_free_disk() < MIN_FREE_DISK:logger.warning("Low disk space – pausing uploads")await asyncio.sleep(10)status_msg = await app.send_message(chat_id,"⏳ Starting upload...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)active_jobs[job_id]["status_msg"] = status_msgtry:await do_upload_job(user_id, chat_id, file_obj, orig_filename, job_id, cancel_event, status_msg, file_id, expected_size)finally:active_jobs.pop(job_id, None)upload_queue.task_done()# =============================================================================# BOT COMMAND HANDLERS# =============================================================================@app.on_message(filters.command("start"))async def cmd_start(_, message: Message):await message.reply_text("👋 **Welcome to the Storage Bot!**\n\n""Send me any file or a Telegram message link to upload it to our cloud dataset.\n""Use /help for a full command list.")@app.on_message(filters.command("help"))async def cmd_help(_, message: Message):text = ("**Available Commands:**\n\n""/start – Welcome message\n""/files – List your uploaded files (download/delete)\n""/status – System & dataset space\n""/delete_all – Delete all your files (confirmation)\n""/upload <link> – Upload a file from a Telegram message link instantly\n""/help – This help\n\n""**Features:**\n""• Maximum file size: 45 GB – larger uploads are rejected.\n""• Duplicate detection (name + size) – you'll be asked to skip or keep.\n""• Smart renaming for duplicates (unique suffix).\n""• Optimised download speed (1 MB block size).\n""• File splitting for large downloads (>1.9 GB).\n""• Real‑time progress with speed and ETA.")await message.reply_text(text, disable_web_page_preview=True)@app.on_message(filters.command("status"))async def cmd_status(_, message: Message):free = get_free_disk()disk_text = f"💾 Local disk: {format_size(free)} free (min {format_size(MIN_FREE_DISK)})"try:info = hf.dataset_info(repo_id=DATASET_REPO)used = info.used_storage or 0except Exception as e:logger.warning("Failed to fetch dataset info: %s", e)used = 0dataset_text = f"📦 Dataset: {format_size(used)} used of {format_size(DATASET_MAX_SIZE)}"uptime_sec = int(time.time() - bot_start_time)uptime_text = f"⏱️ Uptime: {uptime_sec//3600}h {(uptime_sec%3600)//60}m {uptime_sec%60}s"mem_text = f"🧠 Memory: {format_size(get_total_memory())}"cpu_text = f"🖥️ CPU cores: {os.cpu_count()}"status_msg = f"{disk_text}\n{dataset_text}\n{uptime_text}\n{mem_text}\n{cpu_text}"await message.reply_text(status_msg)@app.on_message(filters.command("files"))async def cmd_files(_, message: Message):user_id = message.from_user.iduser_files = db_get_user_files(user_id)if not user_files:enc_folder = get_encrypted_folder(user_id)try:all_hf = hf.list_repo_files(repo_id=DATASET_REPO, repo_type=DATASET_TYPE)hf_user_files = [f for f in all_hf if f.startswith(enc_folder + "/")]for path in hf_user_files:_, enc_name = path.split("/", 1)try:orig_name = decrypt_text(enc_name)except Exception:orig_name = enc_nametry:file_url = hf_hub_url(repo_id=DATASET_REPO, filename=path, repo_type=DATASET_TYPE)meta = get_hf_file_metadata(url=file_url, token=HF_TOKEN)size = meta.sizeexcept Exception:size = 0db_add_file(user_id, path, orig_name, size)user_files = db_get_user_files(user_id)except Exception as e:logger.warning("Fallback scan failed: %s", e)if not user_files:return await message.reply_text("You have no uploaded files.")buttons = []for enc_path, orig_name, size in user_files:token = make_token()file_callback_map[token] = enc_pathdisplay = f"{orig_name[:20]} ({format_size(size)})" if size else orig_name[:20]buttons.append([InlineKeyboardButton(f"📥 {display}", callback_data=f"get:{token}"),InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}"),])buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])await message.reply_text("Your uploaded files (click to download, delete to remove):",reply_markup=InlineKeyboardMarkup(buttons),disable_web_page_preview=True,)@app.on_message(filters.command("delete_all"))async def cmd_delete_all(_, message: Message):user_id = message.from_user.idkb = InlineKeyboardMarkup([[InlineKeyboardButton("Yes, delete all my files", callback_data=f"delete_all:{user_id}")],[InlineKeyboardButton("Cancel", callback_data="cancel_upload:0")],])await message.reply_text("⚠️ Permanently delete **all** your files? This cannot be undone.", reply_markup=kb)@app.on_message(filters.command("upload"))async def cmd_upload(_, message: Message):args = message.text.split(maxsplit=1)if len(args) < 2:return await message.reply_text("Usage: /upload <link>")link = args[1].strip()match = re.search(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', link)if not match:return await message.reply_text("Invalid Telegram message link.")chat_str, msg_id = match.group(2), int(match.group(3))try:if chat_str.startswith("c/"):chat_id = int("-100" + chat_str[2:])else:chat_id = chat_strmsg = await app.get_messages(chat_id, msg_id)except Exception as e:return await message.reply_text(f"❌ Could not fetch the message: {e}")if not msg.media:return await message.reply_text("The linked message doesn't contain a downloadable file.")file_id, expected_size, filename = _extract_file_info(msg)if not filename:return await message.reply_text("Could not determine file name.")limit_err = check_file_size_limit(filename, expected_size)if limit_err:return await message.reply_text(limit_err)token, data = build_duplicate_prompt(message.from_user.id, message.chat.id, file_id, filename, expected_size, file_id)if token:await send_duplicate_prompt(message.chat.id, token, filename, expected_size, data['existing_size'])returnjob_id = int(time.time() * 1000 + hash(filename))active_jobs[job_id] = {"status": "queued"}await upload_queue.put((message.from_user.id, message.chat.id, file_id, filename, job_id, file_id, expected_size))await message.reply_text(f"📦 `{filename}` queued for upload.")def _extract_file_info(msg: Message) -> Tuple[Optional[str], Optional[int], Optional[str]]:"""Returns (file_id, expected_size, filename) or (None, None, None)."""expected_size = extract_file_size(msg)if msg.document:return msg.document.file_id, expected_size, msg.document.file_nameelif msg.video:return msg.video.file_id, expected_size, msg.video.file_name or f"{msg.video.file_unique_id}.mp4"elif msg.audio:return msg.audio.file_id, expected_size, msg.audio.file_name or f"{msg.audio.file_unique_id}.mp3"elif msg.photo:return msg.photo.file_id, expected_size, f"{msg.photo.file_unique_id}.jpg"elif msg.animation:return msg.animation.file_id, expected_size, msg.animation.file_name or f"{msg.animation.file_unique_id}.mp4"elif msg.sticker:if msg.sticker.is_animated:fn = f"{msg.sticker.file_unique_id}.tgs"elif msg.sticker.is_video:fn = f"{msg.sticker.file_unique_id}.webm"else:fn = f"{msg.sticker.file_unique_id}.webp"return msg.sticker.file_id, expected_size, fnelif msg.video_note:return msg.video_note.file_id, expected_size, f"{msg.video_note.file_unique_id}.mp4"elif msg.voice:return msg.voice.file_id, expected_size, f"{msg.voice.file_unique_id}.ogg"return None, None, None# =============================================================================# DUPLICATE CALLBACK HANDLERS# =============================================================================@app.on_callback_query(filters.regex("^dup_skip:"))async def cb_dup_skip(_, query: CallbackQuery):token = query.data.split(":")[-1]data = duplicate_prompt_map.pop(token, None)if not data:return await query.answer("This prompt is no longer valid.", show_alert=True)await query.message.edit_text("❌ Upload skipped.")await query.answer("Skipped.")@app.on_callback_query(filters.regex("^dup_keep:"))async def cb_dup_keep(_, query: CallbackQuery):token = query.data.split(":")[-1]data = duplicate_prompt_map.pop(token, None)if not data:return await query.answer("This prompt is no longer valid.", show_alert=True)# Retrieve the actual file object if we only have a message id (from album)file_obj = data.get('file_obj')if file_obj is None:try:file_obj = await app.get_messages(data['chat_id'], data['msg_id'])except Exception:return await query.answer("Original message no longer available.", show_alert=True)base, ext = os.path.splitext(data['orig_filename'])new_filename = generate_unique_filename(data['user_id'], base, ext)job_id = data['job_id']active_jobs[job_id] = {"status": "queued"}await upload_queue.put((data['user_id'],data['chat_id'],file_obj,new_filename,job_id,data['file_id'],data['expected_size'],))await query.message.edit_text(f"📦 `{new_filename}` queued as a duplicate.")await query.answer("Duplicate will be uploaded with a new name.")# =============================================================================# CALLBACK HANDLERS (upload, download, delete, etc.)# =============================================================================@app.on_callback_query(filters.regex("^get:"))async def cb_get_file(_, query: CallbackQuery):token = query.data.replace("get:", "")enc_path = file_callback_map.get(token)if not enc_path:return await query.answer("Invalid or expired link. Use /files again.", show_alert=True)job_id = int(time.time() * 1000)cancel_event = asyncio.Event()active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}try:orig_name = decrypt_text(enc_path.split("/")[-1])except Exception:orig_name = enc_path.split("/")[-1]status_msg = await query.message.edit_text("⏳ Preparing download...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]]),)active_jobs[job_id]["status_msg"] = status_msgasyncio.create_task(do_download_job(query.message.chat.id, enc_path, orig_name, job_id, cancel_event, status_msg))@app.on_callback_query(filters.regex("^delete:"))async def cb_delete_file(_, query: CallbackQuery):token = query.data.replace("delete:", "")enc_path = file_callback_map.pop(token, None)if not enc_path:return await query.answer("File not found or already deleted.", show_alert=True)user_id = query.from_user.idawait delete_user_file(query.message.chat.id, user_id, enc_path, token, query)@app.on_callback_query(filters.regex("^delete_all:"))async def cb_delete_all(_, query: CallbackQuery):user_id = int(query.data.split(":")[-1])await delete_all_user_files(query.message.chat.id, user_id, query)@app.on_callback_query(filters.regex("^cancel_job:"))async def cb_cancel_job(_, query: CallbackQuery):_, job_id_str = query.data.split(":")job_id = int(job_id_str)if job_id in active_jobs:active_jobs[job_id]["cancel_event"].set()await query.answer("Cancelling...")else:await query.answer("Job not found.")@app.on_callback_query(filters.regex("^upload:"))async def cb_upload(_, query: CallbackQuery):token = query.data.replace("upload:", "")entries = upload_prompt_map.pop(token, None)if not entries:return await query.answer("Prompt expired.", show_alert=True)for entry in entries:user_id = entry[0]if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:# local file: (user_id, msg_id, filename, file_id)msg_id, filename, file_id = entry[1], entry[2], entry[3]try:file_msg = await app.get_messages(query.message.chat.id, msg_id)except Exception:await query.answer(f"Message for {filename} missing.", show_alert=True)continueif not file_msg:await query.answer(f"File {filename} no longer available.", show_alert=True)continuefile_obj = file_msgexpected_size = extract_file_size(file_msg)limit_err = check_file_size_limit(filename, expected_size)if limit_err:await query.message.reply_text(limit_err)continuetoken2, data = build_duplicate_prompt(user_id, query.message.chat.id, file_obj, filename, expected_size, file_id)if token2:await send_duplicate_prompt(query.message.chat.id, token2, filename, expected_size, data['existing_size'])continueelse:# remote file: (user_id, file_id, filename, expected_size)file_id, filename = entry[1], entry[2]expected_size = entry[3] if len(entry) == 4 else Nonelimit_err = check_file_size_limit(filename, expected_size)if limit_err:await query.message.reply_text(limit_err)continuefile_obj = file_idjob_id = int(time.time() * 1000 + hash(filename))active_jobs[job_id] = {"status": "queued"}await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size))await query.message.edit_text(f"📦 {len(entries)} file(s) added to queue.", reply_markup=None)@app.on_callback_query(filters.regex("^upload_all:"))async def cb_upload_all(_, query: CallbackQuery):token = query.data.replace("upload_all:", "")entries = upload_prompt_map.pop(token, None)if not entries:return await query.answer("Prompt expired.", show_alert=True)for entry in entries:user_id = entry[0]if len(entry) == 4 and isinstance(entry[1], int) and entry[1] > 0:msg_id, filename, file_id = entry[1], entry[2], entry[3]try:file_msg = await app.get_messages(query.message.chat.id, msg_id)except Exception:continueif not file_msg:continuefile_obj = file_msgexpected_size = extract_file_size(file_msg)limit_err = check_file_size_limit(filename, expected_size)if limit_err:await query.message.reply_text(limit_err)continuetoken2, data = build_duplicate_prompt(user_id, query.message.chat.id, file_obj, filename, expected_size, file_id)if token2:await send_duplicate_prompt(query.message.chat.id, token2, filename, expected_size, data['existing_size'])continueelse:file_id, filename = entry[1], entry[2]expected_size = entry[3] if len(entry) == 4 else Nonelimit_err = check_file_size_limit(filename, expected_size)if limit_err:await query.message.reply_text(limit_err)continuefile_obj = file_idjob_id = int(time.time() * 1000 + hash(filename))active_jobs[job_id] = {"status": "queued"}await upload_queue.put((user_id, query.message.chat.id, file_obj, filename, job_id, file_id, expected_size))await query.message.edit_text(f"📦 All {len(entries)} files added to queue.", reply_markup=None)@app.on_callback_query(filters.regex("^cancel_upload:"))async def cb_cancel_upload_prompt(_, query: CallbackQuery):await query.message.delete()# =============================================================================# MESSAGE LINK INTERACTIVE PROMPT# =============================================================================@app.on_message(filters.text& ~filters.command(["start", "help", "status", "files", "delete_all", "upload"])& filters.regex(r'https?://t\.me/'))async def on_message_link(client, message: Message):links = re.findall(r'(https?://t\.me/((?:c/)?[\w\d_]+)/(\d+))', message.text)if not links:returnchat_str, msg_id = links[0][1], int(links[0][2])try:if chat_str.startswith("c/"):chat_id = int("-100" + chat_str[2:])else:chat_id = chat_strmsg = await app.get_messages(chat_id, msg_id)except Exception as e:await message.reply_text(f"❌ Could not access the message: {e}")returnif not msg.media:await message.reply_text("The linked message does not contain any downloadable file.")returnfile_id, expected_size, filename = _extract_file_info(msg)if not filename:return await message.reply_text("Could not determine file name.")limit_err = check_file_size_limit(filename, expected_size)if limit_err:return await message.reply_text(limit_err)token, data = build_duplicate_prompt(message.from_user.id, message.chat.id, file_id, filename, expected_size, file_id)if token:await send_duplicate_prompt(message.chat.id, token, filename, expected_size, data['existing_size'])returnupload_token = make_token()upload_prompt_map[upload_token] = [(message.from_user.id, file_id, filename, expected_size)]kb = InlineKeyboardMarkup([[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],])await message.reply_text(f"Found file `{filename}`. Do you want to upload it?", reply_markup=kb)# =============================================================================# DIRECT FILE RECEIVER# =============================================================================@app.on_message(filters.document | filters.video | filters.audio | filters.photo| filters.animation | filters.sticker | filters.video_note | filters.voice)async def on_direct_file(_, message: Message):file_id, expected_size, filename = _extract_file_info(message)if not filename:returnif message.media_group_id and (message.photo or message.video or message.document):group_id = str(message.media_group_id)if group_id not in album_groups:album_groups[group_id] = {'chat_id': message.chat.id,'user_id': message.from_user.id,'messages': [],'timer': None,}album_groups[group_id]['messages'].append((message.id, filename, file_id, expected_size))if album_groups[group_id]['timer']:album_groups[group_id]['timer'].cancel()async def timer_callback(gid=group_id):await asyncio.sleep(2)await process_album_group(gid)album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())returnlimit_err = check_file_size_limit(filename, expected_size)if limit_err:return await message.reply_text(limit_err)token, data = build_duplicate_prompt(message.from_user.id, message.chat.id, message, filename, expected_size, file_id)if token:await send_duplicate_prompt(message.chat.id, token, filename, expected_size, data['existing_size'])returnupload_token = make_token()upload_prompt_map[upload_token] = [(message.from_user.id, message.id, filename, file_id)]kb = InlineKeyboardMarkup([[InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{upload_token}")],[InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")],])await message.reply_text(f"Do you want to upload `{filename}`?", reply_markup=kb)# =============================================================================# KEEP‑ALIVE PING# =============================================================================def keepalive():while True:try:requests.get(SPACE_HOST, timeout=10)except Exception as e:logger.warning("Keep‑alive ping failed: %s", e)time.sleep(KEEPALIVE_INTERVAL)# =============================================================================# MAIN# =============================================================================async def main():asyncio.create_task(upload_worker())await app.start()logger.info("Bot started successfully (tgcrypto: %s)", "available" if hasattr(app, "tgcrypto") else "missing")await asyncio.Event().wait()if __name__ == "__main__":threading.Thread(target=run_web, daemon=True).start()threading.Thread(target=keepalive, daemon=True).start()app.run(main())
app.py+1183-234