Update app.py
Browse files6 unmodified lines789101112131415161718199 unmodified lines29303132333435363738394041424344454635 unmodified lines82838485868743 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551569 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612628 unmodified lines2712722732742752762774 unmodified lines2822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343351 unmodified line33733833934034134234323 unmodified lines36736836937037137237324 unmodified lines39839940040140240340423 unmodified lines4284294304314324334342 unmodified lines43743843944044144244344444544644744844945045145224 unmodified lines47747847948048148248348448548648748825 unmodified lines5145155165175185195205216 unmodified linesimport asyncioimport sqlite3import tempfilefrom typing import Optionalimport requestsfrom flask import Flaskfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom huggingface_hub import HfApi, hf_hub_download, get_hf_file_metadatafrom cryptography.hazmat.primitives.ciphers.aead import AESSIV# --------------- CONFIG ---------------9 unmodified linesKEEPALIVE_INTERVAL = 300 # 5 minutesDB_PATH = "bot_files.db"# --------------- DETERMINISTIC ENCRYPTION (AES-SIV) ---------------# Always produces the same ciphertext for the same key + plaintext.siv_key = hashlib.sha512(OBFUSCATION_KEY.encode()).digest()aes_siv = AESSIV(siv_key)def encrypt_text(plain: str) -> str:"""Return URLβsafe base64 without padding (always the same output for the same input)."""token = aes_siv.encrypt(plain.encode(), None)return base64.urlsafe_b64encode(token).decode().rstrip("=")def decrypt_text(encoded: str) -> str:"""Recover the original string. Accepts base64 with or without padding."""padding = 4 - len(encoded) % 4if padding != 4:encoded += "=" * padding35 unmodified linescursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))conn.commit()# --------------- FLASK HEALTH SERVER ---------------web = Flask(__name__)43 unmodified linesdef format_speed(bytes_per_sec):return f"{format_size(bytes_per_sec)}/s"async def progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,start_bytes: int = 0, total_bytes: Optional[int] = None,is_upload: bool = True):"""Update the status message every 3 seconds with progress (percentage, speed, ETA).Returns a tuple (task, bytes_holder) where bytes_holder is a list with a single elementthat should be updated periodically to reflect the current transferred bytes."""last_bytes = [start_bytes]start_time = time.time()async def updater():while not cancel_event.is_set():elapsed = max(time.time() - start_time, 0.01)current = last_bytes[0]speed = current / elapsedtext = ""if total_bytes and total_bytes > 0:pct = min(100 * current / total_bytes, 100)text += f"{pct:.1f}% of {format_size(total_bytes)}\n"text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"text += f"Speed: {format_speed(speed)}\n"if total_bytes and speed > 0:9 unmodified linesexcept Exception:breakawait asyncio.sleep(3)task = asyncio.create_task(updater())return task, last_bytes# --------------- UPLOAD JOB ---------------async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str,job_id: int, cancel_event: asyncio.Event, status_msg):temp_dir = tempfile.mkdtemp()try:# 1. Download file from Telegramawait status_msg.edit_text("β¬οΈ Downloading from Telegram...",reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("β Cancel", callback_data=f"cancel_job:{job_id}")]]))local_path = await file_msg.download(file_name=os.path.join(temp_dir, orig_filename))if cancel_event.is_set():returnfile_size = os.path.getsize(local_path)# 2. Prepare Hugging Face path (encrypted)enc_folder = get_encrypted_folder(user_id)enc_filename = get_encrypted_filename(orig_filename)repo_path = f"{enc_folder}/{enc_filename}"# 3. Start progress updater for uploadprogress_task, bytes_holder = await progress_updater(job_id, status_msg, cancel_event,start_bytes=0, total_bytes=file_size, is_upload=True)# We'll simulate upload progress because HF API doesn't give real-time bytes.# We'll update bytes_holder based on elapsed time assuming a reasonable speed.async def simulate_progress():start = time.time()while not cancel_event.is_set():elapsed = time.time() - start# Rough estimate: assume ~10 MB/s upload speed (adjust if needed)estimated = min(elapsed * 10_000_000, file_size)bytes_holder[0] = estimatedawait asyncio.sleep(1)bytes_holder[0] = file_size # finaliseprogress_sim = asyncio.create_task(simulate_progress())# 4. Actual upload (in executor)loop = asyncio.get_event_loop()upload_done = loop.create_future()def sync_upload():try:hf.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,repo_id=DATASET_REPO,repo_type="dataset",)return Trueexcept Exception as e:raise etask = loop.run_in_executor(None, sync_upload)# Wait for completion or cancelwhile not task.done():if cancel_event.is_set():breakawait asyncio.sleep(1)if cancel_event.is_set():# Delete the partially uploaded file from HFtry:hf.delete_file(path_in_repo=repo_path,2 unmodified lines)except Exception:passprogress_task.cancel()progress_sim.cancel()await status_msg.edit_text("β Upload cancelled.", reply_markup=None)return# Normal completionawait task # raise exception if anybytes_holder[0] = file_sizeprogress_task.cancel()progress_sim.cancel()# Record in databasedb_add_file(user_id, repo_path, orig_filename, file_size)await status_msg.edit_text(f"β Uploaded: `{orig_filename}`", reply_markup=None)8 unmodified linesjob_id: int, cancel_event: asyncio.Event, status_msg):temp_dir = tempfile.mkdtemp()try:# Get file size from HF metadataloop = asyncio.get_event_loop()metadata = await loop.run_in_executor(None,4 unmodified lines)total_size = metadata.size# Start progress updater for downloadprogress_task, bytes_holder = await progress_updater(job_id, status_msg, cancel_event,start_bytes=0, total_bytes=total_size, is_upload=False)local_file = os.path.join(temp_dir, "downloaded_file")# Download with stream to track progressdownload_done = loop.create_future()def sync_download_with_progress():try:url = hf.get_hf_file_metadata_url(repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset")headers = {"Authorization": f"Bearer {HF_TOKEN}"}resp = requests.get(url, stream=True, headers=headers)resp.raise_for_status()with open(local_file, "wb") as f:downloaded = 0for chunk in resp.iter_content(chunk_size=8192):if cancel_event.is_set():breakf.write(chunk)downloaded += len(chunk)bytes_holder[0] = downloadedreturn Trueexcept Exception as e:raise etask = loop.run_in_executor(None, sync_download_with_progress)# Wait for completion or cancelwhile not task.done():if cancel_event.is_set():breakawait asyncio.sleep(1)if cancel_event.is_set():progress_task.cancel()await status_msg.edit_text("β Download cancelled.", reply_markup=None)returnawait taskprogress_task.cancel()# Send file (split if needed)file_size = os.path.getsize(local_file)if file_size <= MAX_FILE_SIZE_TG:await status_msg.edit_text("π€ Sending file to Telegram...", reply_markup=None)1 unmodified lineawait status_msg.delete()else:part_size = MAX_FILE_SIZE_TGnum_parts = -(-file_size // part_size) # ceil divisionawait status_msg.edit_text(f"π€ Sending in {num_parts} parts...", reply_markup=None)with open(local_file, "rb") as f:for i in range(1, num_parts + 1):23 unmodified linescancel_event = asyncio.Event()active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}# Wait until enough free disk spacewhile get_free_disk() < MIN_FREE_DISK:await asyncio.sleep(10)24 unmodified linesuser_id = message.from_user.iduser_files = db_get_user_files(user_id)# Fallback: if DB is empty, scan HF and rebuild DB entriesif not user_files:enc_folder = get_encrypted_folder(user_id)try:23 unmodified linesbuttons = []for enc_path, orig_name, _ in user_files:buttons.append([InlineKeyboardButton(orig_name[:60], callback_data=f"get:{enc_path}")])await message.reply_text("Your uploaded files:",2 unmodified lines@app.on_callback_query(filters.regex("^get:"))async def get_file_callback(_, query):enc_path = query.data.replace("get:", "")job_id = int(time.time() * 1000)cancel_event = asyncio.Event()active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event, "type": "download"}# Retrieve original file nametry:orig_name = decrypt_text(enc_path.split("/")[-1])except Exception:orig_name = enc_path.split("/")[-1] # fallbackstatus_msg = await query.message.edit_text("β³ Preparing download...",24 unmodified lines@app.on_callback_query(filters.regex("^upload:"))async def upload_callback(_, query):_, user_id_str, msg_id_str, orig_filename = query.data.split(":", 3)user_id = int(user_id_str)chat_id = query.message.chat.idtry:file_msg = await app.get_messages(chat_id, int(msg_id_str))except Exception:return await query.answer("Original message missing.", show_alert=True)25 unmodified lineselse:filename = f"{message.photo.file_unique_id}.jpg"kb = InlineKeyboardMarkup([[InlineKeyboardButton("β¬οΈ Upload File", callback_data=f"upload:{message.from_user.id}:{message.id}:{filename}")],[InlineKeyboardButton("β Cancel", callback_data="cancel_upload:0")]])6 unmodified lines78910111213141516171819209 unmodified lines30313233343536373839404142434435 unmodified lines8081828384858687888990919243 unmodified lines1361371381391401411421431441451461471481491501511521531541551569 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532 unmodified lines2562572582592602612622632642652662672682692702712722732742758 unmodified lines2842852862872882894 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413421 unmodified line34434534634734834935023 unmodified lines37437537637737837924 unmodified lines40440540640740840941023 unmodified lines4344354364374384394404414424432 unmodified lines44644744844945045145245345445545645745845946046146246346424 unmodified lines48949049149249349449549649749849950050150250350425 unmodified lines5305315325335345355365375385395405416 unmodified linesimport asyncioimport sqlite3import tempfileimport secretsfrom typing import Optionalimport requestsfrom flask import Flaskfrom pyrogram import Client, filtersfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom huggingface_hub import HfApi, get_hf_file_metadatafrom cryptography.hazmat.primitives.ciphers.aead import AESSIV# --------------- CONFIG ---------------9 unmodified linesKEEPALIVE_INTERVAL = 300 # 5 minutesDB_PATH = "bot_files.db"# --------------- 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 += "=" * padding35 unmodified linescursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))conn.commit()# --------------- CALLBACK MAPPINGS (avoid long data) ---------------file_callback_map = {} # token -> enc_pathupload_prompt_map = {} # token -> (user_id, message_id, orig_filename)def make_token():return secrets.token_hex(8)# --------------- FLASK HEALTH SERVER ---------------web = Flask(__name__)43 unmodified linesdef format_speed(bytes_per_sec):return f"{format_size(bytes_per_sec)}/s"# --------------- PROGRESS UPDATER ---------------def start_progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,total_bytes: Optional[int] = None, is_upload: bool = True):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 = ""if total_bytes and total_bytes > 0:pct = min(100 * current / total_bytes, 100)text = f"{pct:.1f}% of {format_size(total_bytes)}\n"text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"text += f"Speed: {format_speed(speed)}\n"if total_bytes and speed > 0:9 unmodified linesexcept Exception:breakawait asyncio.sleep(3)try:await status_msg.edit_text("β Cancelled.", reply_markup=None)except Exception:passtask = asyncio.create_task(updater())return {'task': task, 'bytes': bytes_holder}# --------------- UPLOAD JOB ---------------async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str,job_id: int, cancel_event: asyncio.Event, status_msg):temp_dir = tempfile.mkdtemp()local_path = Nonetry:# Download from Telegram with progressdownload_bytes_holder = [0]start_time = time.time()async def download_progress(current, total):download_bytes_holder[0] = currentelapsed = max(time.time() - start_time, 0.01)speed = current / elapsedpct = min(100 * current / total, 100) if total else 0text = f"β¬οΈ Downloading from Telegram...\n{pct:.1f}% of {format_size(total)}\n{format_size(current)} downloaded\nSpeed: {format_speed(speed)}"try:await status_msg.edit_text(text,reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("β Cancel", callback_data=f"cancel_job:{job_id}")]]))except Exception:passlocal_path = await file_msg.download(file_name=os.path.join(temp_dir, orig_filename),progress=download_progress)if cancel_event.is_set():returnfile_size = os.path.getsize(local_path)# Upload to Hugging Faceenc_folder = get_encrypted_folder(user_id)enc_filename = get_encrypted_filename(orig_filename)repo_path = f"{enc_folder}/{enc_filename}"prog = start_progress_updater(job_id, status_msg, cancel_event,total_bytes=file_size, is_upload=True)upload_prog_task = prog['task']upload_bytes_holder = prog['bytes']async def simulate_upload():start = time.time()while not cancel_event.is_set():elapsed = time.time() - startestimated = min(elapsed * 10_000_000, file_size)upload_bytes_holder[0] = estimatedawait asyncio.sleep(1)upload_bytes_holder[0] = file_sizesim_task = asyncio.create_task(simulate_upload())loop = asyncio.get_event_loop()upload_done = loop.create_future()def sync_upload():hf.upload_file(path_or_fileobj=local_path,path_in_repo=repo_path,repo_id=DATASET_REPO,repo_type="dataset",)task = loop.run_in_executor(None, sync_upload)while not task.done():if cancel_event.is_set():breakawait asyncio.sleep(1)if cancel_event.is_set():try:hf.delete_file(path_in_repo=repo_path,2 unmodified lines)except Exception:passupload_prog_task.cancel()sim_task.cancel()try:await status_msg.edit_text("β Upload cancelled.", reply_markup=None)except Exception:passreturnawait taskupload_bytes_holder[0] = file_sizeawait asyncio.sleep(0.5)upload_prog_task.cancel()sim_task.cancel()db_add_file(user_id, repo_path, orig_filename, file_size)await status_msg.edit_text(f"β Uploaded: `{orig_filename}`", reply_markup=None)8 unmodified linesjob_id: int, cancel_event: asyncio.Event, status_msg):temp_dir = tempfile.mkdtemp()try:loop = asyncio.get_event_loop()metadata = await loop.run_in_executor(None,4 unmodified lines)total_size = metadata.sizeprog = start_progress_updater(job_id, status_msg, cancel_event,total_bytes=total_size, is_upload=False)prog_task = prog['task']bytes_holder = prog['bytes']local_file = os.path.join(temp_dir, "downloaded_file")download_done = loop.create_future()def sync_download_with_progress():url = hf.get_hf_file_metadata_url(repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset")headers = {"Authorization": f"Bearer {HF_TOKEN}"}resp = requests.get(url, stream=True, headers=headers)resp.raise_for_status()with open(local_file, "wb") as f:downloaded = 0for chunk in resp.iter_content(chunk_size=8192):if cancel_event.is_set():breakf.write(chunk)downloaded += len(chunk)bytes_holder[0] = downloadedreturn Truetask = loop.run_in_executor(None, sync_download_with_progress)while not task.done():if cancel_event.is_set():breakawait asyncio.sleep(1)if cancel_event.is_set():prog_task.cancel()await status_msg.edit_text("β Download cancelled.", reply_markup=None)returnawait taskbytes_holder[0] = total_sizeawait asyncio.sleep(0.5)prog_task.cancel()file_size = os.path.getsize(local_file)if file_size <= MAX_FILE_SIZE_TG:await status_msg.edit_text("π€ Sending file to Telegram...", reply_markup=None)1 unmodified lineawait status_msg.delete()else:part_size = MAX_FILE_SIZE_TGnum_parts = -(-file_size // part_size)await status_msg.edit_text(f"π€ Sending in {num_parts} parts...", reply_markup=None)with open(local_file, "rb") as f:for i in range(1, num_parts + 1):23 unmodified linescancel_event = asyncio.Event()active_jobs[job_id] = {"status": "running", "cancel_event": cancel_event}while get_free_disk() < MIN_FREE_DISK:await asyncio.sleep(10)24 unmodified linesuser_id = message.from_user.iduser_files = db_get_user_files(user_id)# Fallback scan if DB emptyif not user_files:enc_folder = get_encrypted_folder(user_id)try:23 unmodified linesbuttons = []for enc_path, orig_name, _ in user_files:# Generate a short token instead of passing the whole pathtoken = make_token()file_callback_map[token] = enc_pathbuttons.append([InlineKeyboardButton(orig_name[:60], callback_data=f"get:{token}")])await message.reply_text("Your uploaded files:",2 unmodified lines@app.on_callback_query(filters.regex("^get:"))async def get_file_callback(_, query):token = query.data.replace("get:", "")enc_path = file_callback_map.pop(token, None)if not enc_path:return await query.answer("This file list is no longer valid. Please 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...",24 unmodified lines@app.on_callback_query(filters.regex("^upload:"))async def upload_callback(_, query):token = query.data.replace("upload:", "")data = upload_prompt_map.pop(token, None)if not data:return await query.answer("Upload prompt expired. Please send the file again.", show_alert=True)user_id, msg_id, orig_filename = datachat_id = query.message.chat.idtry:file_msg = await app.get_messages(chat_id, msg_id)except Exception:return await query.answer("Original message missing.", show_alert=True)25 unmodified lineselse:filename = f"{message.photo.file_unique_id}.jpg"# Use short token to avoid long callback datatoken = make_token()upload_prompt_map[token] = (message.from_user.id, message.id, filename)kb = InlineKeyboardMarkup([[InlineKeyboardButton("β¬οΈ Upload File", callback_data=f"upload:{token}")],[InlineKeyboardButton("β Cancel", callback_data="cancel_upload:0")]])
app.py+119-99