import os import shutil import time import uuid import asyncio from contextlib import asynccontextmanager from typing import List, Optional from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request, Query from fastapi.responses import FileResponse, JSONResponse, HTMLResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from config import UPLOAD_DIR, BASE_URL from db import get_metadata, delete_metadata, set_metadata # Bot status tracking bot_status = {"running": False, "error": None, "started_at": None} # --- CLEANUP TASK --- async def cleanup_old_files(): while True: try: now = time.time() if os.path.exists(UPLOAD_DIR): for root, dirs, files in os.walk(UPLOAD_DIR): for filename in files: file_path = os.path.join(root, filename) try: # Check metadata for custom expiration meta = get_metadata(filename) expire_hours = meta.get("expire_hours", 24) if meta else 24 # If expire_hours is 0, it's 'Never Delete' if expire_hours > 0: if now - os.path.getmtime(file_path) > (expire_hours * 3600): os.remove(file_path) delete_metadata(filename) print(f"🗑️ Cleaned up expired file: {filename} ({expire_hours}h)") except: pass if root != UPLOAD_DIR and not os.listdir(root): try: os.rmdir(root) except: pass except Exception as e: print(f"Cleanup error: {e}") await asyncio.sleep(3600) from pyrogram.types import BotCommand from pyrogram import idle async def start_bot_safe(): try: from bot import bot as telegram_bot if telegram_bot is None: return None await asyncio.wait_for(telegram_bot.start(), timeout=30) try: await telegram_bot.set_bot_commands([ BotCommand("start", "Start the bot"), BotCommand("zip", "Create ZIP"), BotCommand("unzip", "Extract ZIP"), BotCommand("torrent", "Download via magnet/hash/.torrent"), BotCommand("pdf_merge", "Merge PDFs"), BotCommand("vcompress", "Compress Video"), BotCommand("search", "Search your files"), BotCommand("settings", "Bot settings"), BotCommand("files", "My files"), BotCommand("help", "Usage guide") ]) except: pass me = await telegram_bot.get_me() bot_status.update({"running": True, "started_at": time.time()}) print(f"🚀 Bot: @{me.username}") return telegram_bot except Exception as e: bot_status["error"] = str(e) print(f"❌ Bot failed: {e}") return None @asynccontextmanager async def lifespan(app: FastAPI): os.makedirs(UPLOAD_DIR, exist_ok=True) cleanup_task = asyncio.create_task(cleanup_old_files()) telegram_bot = await start_bot_safe() bot_keep_alive_task = None if telegram_bot: async def keep_bot_alive(): while True: try: await asyncio.sleep(10) except asyncio.CancelledError: break bot_keep_alive_task = asyncio.create_task(keep_bot_alive()) yield cleanup_task.cancel() if bot_keep_alive_task: bot_keep_alive_task.cancel() if telegram_bot: await telegram_bot.stop() app = FastAPI(title="NexusShare Pro", lifespan=lifespan) app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/") async def read_index(): return FileResponse("static/index.html") # --- PROFESSIONAL UI TEMPLATES --- UI_STYLE = """ """ def get_password_wall(target_name: str, error: bool = False): return f""" {UI_STYLE}

🔐 Restricted Access

'{target_name}' is protected by a secure access code.

{f'

Incorrect password. Please try again.

' if error else ''}
""" @app.get("/view/{user_id}/{batch_id}") async def view_batch(user_id: str, batch_id: str, password: Optional[str] = Query(None)): user_dir = os.path.join(UPLOAD_DIR, user_id) if not os.path.exists(user_dir): raise HTTPException(404, "User directory not found") meta = get_metadata(batch_id) if meta and meta.get("password") and meta.get("password") != password: return HTMLResponse(get_password_wall(f"Archive: {batch_id}", error=password is not None)) files_data = [] # Search for files belonging to this batch for f in os.listdir(user_dir): if f.startswith(f"{batch_id}_"): if f.endswith(".zip") or f.endswith(".pdf"): continue fpath = os.path.join(user_dir, f) files_data.append({ "name": "_".join(f.split("_")[2:]) if len(f.split("_")) > 2 else "_".join(f.split("_")[1:]), "url": f"/download/{user_id}/{f}?password={password or ''}", "stream": f"/player/{user_id}/{f}?password={password or ''}" if f.lower().endswith(('.mp4', '.mkv', '.webm')) else None, "size": round(os.path.getsize(fpath)/1024/1024, 2), "raw": f }) # Fallback: If no batch files found, maybe batch_id is a single filename if not files_data: target_file = None for f in os.listdir(user_dir): if f.startswith(batch_id): target_file = f break if target_file: fpath = os.path.join(user_dir, target_file) files_data.append({ "name": "_".join(target_file.split("_")[1:]), "url": f"/download/{user_id}/{target_file}?password={password or ''}", "stream": f"/player/{user_id}/{target_file}?password={password or ''}" if target_file.lower().endswith(('.mp4', '.mkv', '.webm')) else None, "size": round(os.path.getsize(fpath)/1024/1024, 2), "raw": target_file }) if not files_data: raise HTTPException(404, "No files found for this batch") files_data.sort(key=lambda x: x["raw"]) items_html = "" for f in files_data: ext = f['name'].split('.')[-1].upper() if '.' in f['name'] else 'FILE' items_html += f"""
{ext[:4]}
{f['name']}
{f['size']} MB • {ext}
{f'Watch' if f['stream'] else ''} Download
""" return HTMLResponse(f""" NexusShare - File Viewer{UI_STYLE}

📦 Archive Contents

Viewing {len(files_data)} items from batch {batch_id}

{items_html}
Powered by NexusShare Professional
""") @app.get("/player/{filepath:path}") async def video_player(filepath: str, password: Optional[str] = Query(None)): safe_path = os.path.normpath(filepath).lstrip(os.sep) path = os.path.join(UPLOAD_DIR, safe_path) if not os.path.exists(path): raise HTTPException(404) fname = os.path.basename(path) meta = get_metadata(fname) or get_metadata(fname.split('_')[0]) if meta and meta.get("password") and meta.get("password") != password: return HTMLResponse(get_password_wall(fname, error=password is not None)) return HTMLResponse(f""" NexusShare Player
🎬 Playing: {"_".join(fname.split("_")[1:])}
""") @app.get("/download/{filepath:path}") async def download_file(filepath: str, request: Request, password: Optional[str] = Query(None)): safe_path = os.path.normpath(filepath).lstrip(os.sep) path = os.path.join(UPLOAD_DIR, safe_path) if not os.path.exists(path): raise HTTPException(404) fname = os.path.basename(path) meta = get_metadata(fname) or get_metadata(fname.split('_')[0]) if meta and meta.get("password") and meta.get("password") != password: accept = request.headers.get("accept", "") if "text/html" in accept: return HTMLResponse(get_password_wall(fname, error=password is not None)) raise HTTPException(403, "Password required.") resp = FileResponse(path, filename="_".join(fname.split("_")[1:])) if meta and meta.get("self_destruct"): async def delete_after(): await asyncio.sleep(10) # Safety delay try: os.remove(path) delete_metadata(fname) except: pass asyncio.create_task(delete_after()) return resp @app.get("/files") async def list_files(x_user_id: str = Header(None)): if not x_user_id: return [] user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}") if not os.path.exists(user_dir): return [] files = [] for f in os.listdir(user_dir): path = os.path.join(user_dir, f) if os.path.isfile(path): files.append({ "name": f"user_{x_user_id}/{f}", "display_name": "_".join(f.split("_")[1:]) if "_" in f else f, "size": os.path.getsize(path), "mtime": os.path.getmtime(path) }) files.sort(key=lambda x: x["mtime"], reverse=True) return files @app.api_route("/upload/{filename}", methods=["PUT", "POST"]) @app.api_route("/upload", methods=["PUT", "POST"]) async def upload_files( filename: Optional[str] = None, files: Optional[List[UploadFile]] = File(None), file: Optional[UploadFile] = File(None), x_user_id: str = Header(None), x_password: str = Header(None), request: Request = None ): user_id = x_user_id or "cli-anonymous" user_dir = os.path.join(UPLOAD_DIR, f"user_{user_id}") os.makedirs(user_dir, exist_ok=True) # Binary Upload (curl -T style) if request.method == "PUT" or (not files and not file and request.headers.get("content-type") != "application/x-www-form-urlencoded"): content = await request.body() if not content: raise HTTPException(status_code=400, detail="Empty file body.") fname = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}" fname = os.path.basename(fname) safe_name = f"{str(uuid.uuid4())[:8]}_{fname}" with open(os.path.join(user_dir, safe_name), "wb") as b: b.write(content) if x_password: set_metadata(safe_name, {"password": x_password}) # Return plain text for terminal, JSON for web if "curl" in request.headers.get("user-agent", "").lower(): return f"{BASE_URL}/download/user_{user_id}/{safe_name}\n" return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"} # Multipart Upload target = (files or []) + ([file] if file else []) if not target: # Check if it was meant to be a binary upload but failed content-type check content = await request.body() if content: fname = filename or f"upload_{int(time.time())}" safe_name = f"{str(uuid.uuid4())[:8]}_{fname}" with open(os.path.join(user_dir, safe_name), "wb") as b: b.write(content) return {"url": f"{BASE_URL}/download/user_{user_id}/{safe_name}"} raise HTTPException(status_code=400, detail="No files provided.") urls = [] for f in target: fname = os.path.basename(f.filename or f"file_{int(time.time())}") name = f"{str(uuid.uuid4())[:8]}_{fname}" dest = os.path.join(user_dir, name) with open(dest, "wb") as b: shutil.copyfileobj(f.file, b) if x_password: set_metadata(name, {"password": x_password}) urls.append(f"{BASE_URL}/download/user_{user_id}/{name}") return {"urls": urls} if len(urls) > 1 or x_user_id else urls[0] @app.post("/api/zip") async def api_zip_files(request: Request, x_user_id: str = Header(None)): if not x_user_id: raise HTTPException(401, "Missing user id") body = await request.json() names = body.get("files") or [] archive_name = (body.get("name") or "").strip() if not names: raise HTTPException(400, "No files selected") user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}") safe_files = [] for n in names: n = os.path.basename(n) fpath = os.path.join(user_dir, n) if os.path.isfile(fpath): safe_files.append(n) if not safe_files: raise HTTPException(404, "No valid files found") archive_name = "".join(c for c in archive_name if c.isalnum() or c in "._-") or f"archive_{int(time.time())}" oname = f"{str(uuid.uuid4())[:8]}_{archive_name}.zip" opath = os.path.join(user_dir, oname) cmd = ["7z", "a", "-mx=5", "-mmt=on", opath] + safe_files p = await asyncio.create_subprocess_exec(*cmd, cwd=user_dir, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) await p.communicate() if p.returncode != 0 or not os.path.exists(opath): raise HTTPException(500, "Zip creation failed") return {"url": f"{BASE_URL}/download/user_{x_user_id}/{oname}", "name": oname} @app.post("/api/unzip") async def api_unzip_file(request: Request, x_user_id: str = Header(None)): if not x_user_id: raise HTTPException(401, "Missing user id") body = await request.json() name = os.path.basename(body.get("file") or "") if not name: raise HTTPException(400, "No file specified") user_dir = os.path.join(UPLOAD_DIR, f"user_{x_user_id}") fpath = os.path.join(user_dir, name) if not os.path.exists(fpath): raise HTTPException(404, "File not found") bid = str(uuid.uuid4())[:8] extract_dir = os.path.join(user_dir, f"unzip_{bid}") os.makedirs(extract_dir, exist_ok=True) cmd = ["7z", "x", fpath, f"-o{extract_dir}", "-y"] p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) await p.communicate() count = 0 new_files = [] for root, dirs, files in os.walk(extract_dir): for f in files: count += 1 new_name = f"{bid}_{count:03d}_{f.replace(' ', '_')}" os.rename(os.path.join(root, f), os.path.join(user_dir, new_name)) new_files.append(new_name) try: shutil.rmtree(extract_dir) except Exception: pass if count == 0: raise HTTPException(500, "No files extracted (not a valid archive?)") return {"view_url": f"{BASE_URL}/view/user_{x_user_id}/{bid}", "files": new_files, "count": count} @app.delete("/delete/{filename}") async def delete_file(filename: str, x_user_id: str = Header(None)): if not x_user_id: raise HTTPException(401) p = os.path.join(UPLOAD_DIR, f"user_{x_user_id}", filename) if os.path.exists(p): os.remove(p) delete_metadata(filename) return {"status": "ok"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)