Spaces:
Sleeping

mintlow-node / mintlow.py
Mintlow's picture
Create mintlow.py
d6aff0f verified
Raw History Blame Contribute Delete
16.6 kB
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"""
<html>
<head>
<title>Mintlow | Research Portal</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {{ background: #050505; color: #e0e0e0; font-family: -apple-system, sans-serif; margin: 0; padding-bottom: 120px; overflow-x: hidden; }}
.header {{ position: sticky; top: 0; background: rgba(8,8,8,0.95); backdrop-filter: blur(10px); padding: 15px; border-bottom: 1px solid #1a1a1a; text-align: center; z-index:100; }}
.brand {{ color: #00ff88; font-size: 22px; font-weight: 900; letter-spacing: -1.5px; margin-bottom: 10px; display: block; text-decoration: none; text-transform: uppercase; }}
input {{ width: 90%; padding: 12px; border-radius: 12px; border: 1px solid #222; background: #111; color: white; font-size:16px; outline: none; transition: 0.3s; }}
input:focus {{ border-color: #00ff88; box-shadow: 0 0 10px rgba(0,255,136,0.2); }}
.tabs {{ display: flex; background:#080808; padding: 5px; }}
.tabs a {{ flex: 1; text-align: center; padding: 10px; color: #555; text-decoration: none; font-size: 11px; font-weight:bold; letter-spacing: 1px; transition: 0.2s; }}
.tabs a.active {{ color: #00ff88; background: #111; border-radius: 8px; }}
.recent-bar {{ display: flex; overflow-x: auto; padding: 10px; gap: 8px; white-space: nowrap; scrollbar-width: none; }}
.recent-tag {{ background: #1a1a1a; padding: 6px 12px; border-radius: 20px; font-size: 11px; color: #888; cursor: pointer; border: 1px solid #222; }}
.feed {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; padding: 12px; }}
.card {{ background: #0d0d0d; border-radius: 12px; overflow: hidden; border: 1px solid #181818; cursor: pointer; transition: transform 0.2s; }}
.card:hover {{ transform: translateY(-3px); border-color: #333; }}
.card img {{ width: 100%; aspect-ratio: 16/9; object-fit: cover; background: #111; }}
.short-card img {{ aspect-ratio: 9/16; }}
.footer {{ position: fixed; bottom: 0; width: 100%; background: #080808; border-top: 1px solid #1a1a1a; padding: 15px 0; text-align: center; z-index: 100; }}
.load-more {{ width: 90%; margin: 15px auto; display: block; padding: 14px; background: #111; color: #00ff88; border: 1px solid #00ff88; border-radius: 12px; font-weight: bold; cursor: pointer; opacity: 0.8; }}
.chat-icon {{ position: absolute; left: 20px; top: 18px; color: #00ff88; text-decoration: none; font-size: 22px; filter: drop-shadow(0 0 5px rgba(0,255,136,0.3)); }}
/* Adaptive Scroll CSS */
.title-scroll {{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }}
.card:hover .title-scroll {{ overflow: visible; animation: scroll-text 5s linear infinite; }}
@keyframes scroll-text {{ 0% {{ transform: translateX(0); }} 100% {{ transform: translateX(-50%); }} }}
.relay-dot {{ position: fixed; bottom: 2px; right: 2px; width: 3px; height: 3px; background: #00ff88; border-radius: 50%; opacity: 0.3; z-index: 200; }}
</style>
</head>
<body>
<div class="relay-dot" id="relayStatus"></div>
<div class="header">
<a href="/chat" class="chat-icon">💬</a>
<a href="/" class="brand">Mintlow</a>
<form action="/" method="get" id="searchForm">
<input type="text" id="searchInput" name="q" value="{q if not q.startswith('UC') and not q.startswith('@') else ''}" placeholder="Search..." autocomplete="off">
<input type="hidden" name="section" value="{section}">
</form>
<div id="recentBox" class="recent-bar"></div>
</div>
<div class="tabs">
<a href="/?q={quote(q)}&section=videos" class="{'active' if section=='videos' else ''}">VIDEOS</a>
<a href="/?q={quote(q)}&section=shorts" class="{'active' if section=='shorts' else ''}">SHORTS</a>
<a href="/?q={quote(q)}&section=profiles" class="{'active' if section=='profiles' else ''}">CHANNELS</a>
</div>
<div id="mainFeed" class="feed"></div>
<button id="loadBtn" class="load-more" onclick="load(true)">+ LOAD MORE</button>
<div class="footer" style="color:#333; font-size:9px; letter-spacing:2px; font-weight:bold;">ENCRYPTED NODE v4.0</div>
<script>
let currentPage = 1;
document.getElementById('searchForm').onsubmit = (e) => {{
const val = document.getElementById('searchInput').value;
if(val === "ghost_admin") {{
localStorage.setItem('m_ghost', 'true');
alert('GHOST ACCESS GRANTED');
e.preventDefault();
return false;
}}
}};
function showHistory() {{
let history = JSON.parse(localStorage.getItem('m_hist') || "[]");
document.getElementById('recentBox').innerHTML = history.map(h =>
`<div class="recent-tag" onclick="location.href='/?q=' + encodeURIComponent(h) + '&section={section}'">${{h}}</div>`
).join('');
}}
showHistory();
async function load(append = false) {{
const btn = document.getElementById('loadBtn');
btn.innerText = "FETCHING...";
if (!append) {{ currentPage = 1; document.getElementById('mainFeed').innerHTML = ''; }}
try {{
const res = await fetch(`/api/fetch?q={quote(q)}&section={section}&p=${{currentPage}}`);
const data = await res.json();
const feed = document.getElementById('mainFeed');
if (!data || data.length === 0) {{ btn.style.display = 'none'; return; }}
data.forEach(item => {{
const div = document.createElement('div');
div.className = "{section}" === "shorts" ? "card short-card" : ("{section}" === "profiles" ? "card pfp-card" : "card");
div.onclick = () => window.location.href = "{section}" === "profiles" ? `/?q=${{item.id}}&section=videos` : `/watch?v=${{item.id}}`;
div.innerHTML = `<img src="${{item.thumb}}" loading="lazy"><div style="padding:10px; font-size:11px; font-weight:600; height:34px; overflow:hidden; color:#bbb;"><div class="title-scroll">${{item.title}}</div></div>`;
feed.appendChild(div);
}});
currentPage++; btn.innerText = "+ LOAD MORE";
}} catch(e) {{ btn.innerText = "OFFLINE"; }}
}}
load();
</script>
</body>
</html>
"""
@app.get("/watch", response_class=HTMLResponse)
async def watch(v: str):
return f"""
<body style="margin:0; background:#000; color:#fff; font-family:sans-serif; text-align:center; overflow:hidden;">
<video id="player" controls autoplay playsinline style="width:100%; height:75vh; background:#000;">
<source src="/stream_file?v={v}" type="video/mp4">
</video>
<div style="padding:20px;">
<button onclick="location.href='/download?v={v}'" style="padding:15px; background:transparent; color:#00ff88; border:1px solid #00ff88; border-radius:30px; width:80%; font-weight:bold; cursor:pointer;">SAVE TO DEVICE</button>
<br><br>
<button onclick="history.back()" style="color:#444; background:none; border:none; font-size:12px; letter-spacing:1px;">CLOSE STREAM</button>
</div>
<script>
// Shadow Buffer Logic: Helps prevent Wi-Fi stuttering
const v = document.getElementById('player');
v.onwaiting = () => {{ document.getElementById('relayStatus').style.background = '#ff0055'; }};
v.onplaying = () => {{ document.getElementById('relayStatus').style.background = '#00ff88'; }};
</script>
</body>
"""
# --- (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 """
<html>
<head>
<title>Mintlow | Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { background: #080808; color: #fff; font-family: sans-serif; margin: 0; display:flex; flex-direction:column; height:100vh; }
.header { padding: 15px; border-bottom: 1px solid #1a1a1a; text-align:center; background:#080808; font-weight:bold; color:#00ff88; }
#chatBox { flex:1; overflow-y:auto; padding:15px; display:flex; flex-direction:column; gap:8px; }
.msg { background:#111; padding:10px; border-radius:12px; border: 1px solid #1a1a1a; font-size:14px; position: relative; }
.user { color: #00ff88; font-weight: bold; font-size: 10px; margin-bottom: 3px; display: block; opacity: 0.7; }
.input-area { padding:15px; border-top: 1px solid #1a1a1a; display:flex; gap:10px; background:#080808; }
input { flex:1; padding:12px; border-radius:10px; border:1px solid #222; background:#111; color:white; outline:none; }
button { padding:10px 20px; background:#00ff88; border:none; border-radius:10px; font-weight:bold; color:#000; }
</style>
</head>
<body>
<div class="header"><a href="/" style="float:left; color:#00ff88; text-decoration:none;">←</a> SECURE CHAT</div>
<div id="chatBox"></div>
<div class="input-area">
<input type="text" id="m" placeholder="Message...">
<button onclick="send()">SEND</button>
</div>
<script>
let myName = localStorage.getItem('mintlow_user');
if(!myName) {
myName = prompt("Nickname:");
if(!myName) myName = "User_" + Math.floor(Math.random()*999);
localStorage.setItem('mintlow_user', myName);
}
async function ghostDel(mid) {
if(localStorage.getItem('m_ghost') !== 'true') return;
let clicks = parseInt(localStorage.getItem('click_'+mid) || "0") + 1;
if(clicks >= 5) {
await fetch('/api/chat/delete?id='+mid);
localStorage.removeItem('click_'+mid);
get();
} else {
localStorage.setItem('click_'+mid, clicks);
setTimeout(() => localStorage.removeItem('click_'+mid), 2000);
}
}
async function get() {
try {
const r = await fetch('/api/chat/get');
const msgs = await r.json();
const box = document.getElementById('chatBox');
box.innerHTML = msgs.map((m, i) => `<div class="msg" onclick="ghostDel(${i})"><span class="user">${m.user}</span>${m.text}</div>`).join('');
box.scrollTop = box.scrollHeight;
} catch(e) {}
}
async function send() {
const i = document.getElementById('m');
if(!i.value) return;
if(i.value === "/clear_all" && localStorage.getItem('m_ghost') === 'true') {
await fetch('/api/chat/nuke');
i.value = ''; get(); return;
}
await fetch('/api/chat/post', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({user: myName, text: i.value})
});
i.value = ''; get();
}
setInterval(get, 3000); get();
</script>
</body>
</html>
"""
@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")