Spaces:
Sleeping

File size: 16,595 Bytes
d6aff0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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")