Filesharing / app.py
ttnikal's picture
torrent
a6dbd9e
Raw History Blame Contribute Delete
20.5 kB
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 = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');
:root { --primary: #6366f1; --bg: #030712; --card: #0f172a; --text: #f8fafc; --text-dim: #94a3b8; --border: #334155; }
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: var(--bg);
background-image: radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.15) 0px, transparent 50%);
color: var(--text);
margin: 0; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem;
}
.container { width: 100%; max-width: 800px; animation: fadeIn 0.6s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.card { background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(12px); padding: 40px; border-radius: 28px; box-shadow: 0 20px 50px rgba(0,0,0,0.5); border: 1px solid var(--border); }
h2 { font-size: 2rem; font-weight: 800; text-align: center; margin-bottom: 0.5rem; letter-spacing: -1px; }
p.subtitle { text-align: center; color: var(--text-dim); margin-bottom: 2.5rem; font-weight: 500; }
.file-list { display: grid; gap: 12px; }
.file-item {
background: rgba(30, 41, 59, 0.5); padding: 16px; border-radius: 20px; border: 1px solid var(--border);
display: flex; justify-content: space-between; align-items: center; transition: 0.3s;
}
.file-item:hover { border-color: var(--primary); background: rgba(99, 102, 241, 0.05); transform: translateX(5px); }
.file-icon {
width: 48px; height: 48px; background: var(--bg); border-radius: 14px;
display: flex; align-items: center; justify-content: center; font-size: 0.8rem; font-weight: 800; color: var(--primary);
}
.file-details { flex: 1; margin-left: 15px; overflow: hidden; }
.file-name { font-weight: 700; color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-meta { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
.actions { display: flex; gap: 8px; }
.btn-sm { padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: 700; text-decoration: none; transition: 0.2s; }
.btn-get { background: var(--primary); color: #fff; }
.btn-watch { background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); }
.password-form { text-align: center; }
input[type="password"] {
background: var(--bg); border: 2px solid var(--border); color: #fff;
padding: 16px; border-radius: 16px; width: 100%; max-width: 320px; outline: none; transition: 0.3s; font-size: 1rem; margin-bottom: 20px;
}
input[type="password"]:focus { border-color: var(--primary); }
.btn-main {
background: var(--primary); color: white; border: none; padding: 16px 40px; border-radius: 16px;
cursor: pointer; font-weight: 800; font-size: 1rem; transition: 0.3s; box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
}
@media (max-width: 600px) {
.file-item { flex-direction: column; align-items: flex-start; gap: 15px; }
.actions { width: 100%; }
.btn-sm { flex: 1; text-align: center; }
}
</style>
"""
def get_password_wall(target_name: str, error: bool = False):
return f"""
<html><head><meta name="viewport" content="width=device-width, initial-scale=1">{UI_STYLE}</head>
<body><div class="container"><div class="card password-form">
<h2>🔐 Restricted Access</h2>
<p class="subtitle">'{target_name}' is protected by a secure access code.</p>
<form method="get">
<input type="password" name="password" placeholder="Enter Access Code" autofocus required>
{f'<p style="color:#ff5252;font-size:14px;margin-top:-10px;margin-bottom:15px;">Incorrect password. Please try again.</p>' if error else ''}
<div><button type="submit" class="btn-main">Unlock Content</button></div>
</form>
</div></div></body></html>
"""
@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"""
<div class="file-item">
<div class="file-icon">{ext[:4]}</div>
<div class="file-details">
<div class="file-name">{f['name']}</div>
<div class="file-meta">{f['size']} MB • {ext}</div>
</div>
<div class="actions">
{f'<a href="{f["stream"]}" class="btn-sm btn-watch">Watch</a>' if f['stream'] else ''}
<a href="{f['url']}" class="btn-sm btn-get">Download</a>
</div>
</div>"""
return HTMLResponse(f"""
<html><head><title>NexusShare - File Viewer</title><meta name="viewport" content="width=device-width, initial-scale=1">{UI_STYLE}</head>
<body><div class="container"><div class="card">
<h2>📦 Archive Contents</h2>
<p class="subtitle">Viewing {len(files_data)} items from batch <b>{batch_id}</b></p>
<div class="file-list">{items_html}</div>
<div style="text-align:center;margin-top:30px;color:#444;font-size:12px;">Powered by NexusShare Professional</div>
</div></div></body></html>
""")
@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"""
<html><head><title>NexusShare Player</title><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{{margin:0;background:#000;display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;}}
.player-container {{ width:100%; max-width:1000px; height: auto; aspect-ratio: 16/9; position: relative; }}
video {{ width:100%; height:100%; border-radius: 12px; box-shadow: 0 0 50px rgba(0,0,0,0.8); }}
.header {{ position:absolute; top:20px; left:20px; z-index:10; background:rgba(0,0,0,0.5); padding:10px 20px; border-radius:30px; backdrop-filter:blur(10px); color:white; font-size:14px; }}
</style>
</head><body>
<div class="player-container">
<div class="header">🎬 Playing: {"_".join(fname.split("_")[1:])}</div>
<video controls autoplay>
<source src="/download/{filepath}?password={password or ''}" type="video/mp4">
</video>
</div>
</body></html>
""")
@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)