import os, yt_dlp, uvicorn, requests, time, threading
from fastapi import FastAPI, Request, Response, Header
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
from urllib.parse import quote
app = FastAPI()
chat_messages = []
def heartbeat():
while True:
time.sleep(300)
threading.Thread(target=heartbeat, daemon=True).start()
@app.get("/", response_class=HTMLResponse)
async def home(q: str = "trending", section: str = "videos"):
return f"""
Mintlow | Research Portal
"""
@app.get("/watch", response_class=HTMLResponse)
async def watch(v: str):
return f"""
"""
# --- (DOWNLOAD, CHAT, API LOGIC REMAINS UNTOUCHED FOR STABILITY) ---
@app.get("/download")
async def download_video(v: str):
ydl_opts = {'format': '18', 'quiet': True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
try:
info = ydl.extract_info(f"https://www.youtube.com/watch?v={v}", download=False)
url = info['url']
title = info.get('title', 'video').replace(' ', '_')
except: return Response(status_code=404)
r = requests.get(url, stream=True, timeout=15)
headers = {"Content-Disposition": f"attachment; filename={title}.mp4", "X-Content-Type-Options": "nosniff"}
return StreamingResponse(r.iter_content(chunk_size=1024*1024), media_type="application/octet-stream", headers=headers)
@app.get("/chat", response_class=HTMLResponse)
async def chat_page():
return """
Mintlow | Chat
"""
@app.get("/api/chat/get")
async def get_chat():
return JSONResponse(content=chat_messages[-50:])
@app.get("/api/chat/delete")
async def delete_chat(id: int):
global chat_messages
if 0 <= id < len(chat_messages): chat_messages.pop(id)
return {"ok": True}
@app.get("/api/chat/nuke")
async def nuke_chat():
global chat_messages
chat_messages = []
return {"ok": True}
@app.post("/api/chat/post")
async def post_chat(request: Request):
try:
data = await request.json()
chat_messages.append({"user": data.get("user", "Unknown"), "text": data.get("text", "")})
return JSONResponse(content={"status": "ok"})
except: return JSONResponse(content={"status": "error"}, status_code=400)
@app.get("/stream_file")
async def stream_file(v: str, request: Request):
range_header = request.headers.get('range')
headers = {"User-Agent": "Mozilla/5.0", "Accept-Ranges": "bytes"}
if range_header: headers["Range"] = range_header
ydl_opts = {'format': '18', 'quiet': True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
try:
info = ydl.extract_info(f"https://www.youtube.com/watch?v={v}", download=False)
url = info['url']
except: return Response(status_code=404)
r = requests.get(url, headers=headers, stream=True, timeout=15)
proxy_headers = {
"Accept-Ranges": "bytes", "Content-Length": r.headers.get("Content-Length"),
"Content-Range": r.headers.get("Content-Range"), "X-Content-Type-Options": "nosniff",
"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"
}
return StreamingResponse(r.iter_content(chunk_size=1024*512), status_code=r.status_code, media_type="application/octet-stream", headers={k: v for k, v in proxy_headers.items() if v})
@app.get("/api/fetch")
async def api_fetch(q: str, section: str, p: int = 1):
start, end = (p - 1) * 15 + 1, p * 15
is_direct = q.startswith('@') or q.startswith('UC')
if is_direct:
channel_base = f"https://www.youtube.com/{q}" if q.startswith('@') else f"https://www.youtube.com/channel/{q}"
search_query = f"{channel_base}/{section}" if section in ["shorts", "videos"] else f"{channel_base}/videos"
else:
if section == "profiles": search_query = f"https://www.youtube.com/results?search_query={quote(q)}&sp=EgIQAg%3D%3D"
elif section == "shorts": search_query = f"ytsearch50:{q} shorts"
else: search_query = f"ytsearch50:{q}"
ydl_opts = {'quiet': True, 'extract_flat': True, 'playlist_items': f"{start}-{end}", 'ignoreerrors': True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
try:
info = ydl.extract_info(search_query, download=False)
entries = info.get('entries', [])
parsed = []
for v in entries:
if not v: continue
v_id = v.get('id') or v.get('url','').split('/')[-1]
v_title = v.get('title') or v.get('description', 'Video')[:40]
thumbs = v.get('thumbnails', [])
v_thumb = thumbs[-1].get('url') if thumbs else f"https://i.ytimg.com/vi/{v_id}/hqdefault.jpg"
parsed.append({"id": v_id, "title": v_title[:45], "thumb": v_thumb})
return JSONResponse(content=parsed)
except: return JSONResponse(content=[])
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="critical")