Spaces:
Running
Running
Z User commited on
Commit ·
426e8e9
1
Parent(s): 8b468c1
Add simple GET URLs: /movie/ID, /tv/ID/s/e, /search/Query, individual sources, simple text docs
Browse files704 unmodified lines705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100329 unmodified lines10331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097704 unmodified linesreturn results, errors# ===== API Endpoints =====@app.get("/")async def root(format: str = Query(None), accept: Optional[str] = None):# Return JSON for API clients or ?format=jsonfrom starlette.requests import Request# Simple check: if format=json requested, return JSONif format == "json":return {"name": "StreamForge API","version": "3.0.0","description": "Multi-language stream scraper - direct m3u8 via API","docs": "Visit this URL in a browser for full documentation with examples","quick_start": {"step1_search": "GET /api/search?q=Jawan","step2_scrape": "POST /api/scrape body: {tmdb_id: 937278, media_type: 'movie'}","step2_tv": "POST /api/scrape body: {tmdb_id: 1396, media_type: 'tv', season: 1, episode: 1}",},"endpoints": {"/api/search": "Search TMDB for movies/TV","/api/scrape": "Scrape streaming links (select sources)","/api/scrape/all": "Scrape ALL sources at once","/api/sources": "List available sources & languages","/api/health": "Health check",}}# Return beautiful HTML docs for browsersreturn HTMLResponse(content="""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>StreamForge API v3.0</title><style>:root { --bg: #0f0f0f; --card: #1a1a2e; --border: #2a2a4a; --accent: #e94560; --accent2: #0f3460; --text: #e0e0e0; --dim: #888; --code-bg: #16213e; --green: #4ecca3; --orange: #ff9f43; }* { margin: 0; padding: 0; box-sizing: border-box; }body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg); color: var(--text); line-height: 1.7; }.container { max-width: 900px; margin: 0 auto; padding: 2rem 1.5rem; }h1 { font-size: 2.2rem; margin-bottom: 0.3rem; }h1 span { color: var(--accent); }.subtitle { color: var(--dim); font-size: 1.05rem; margin-bottom: 2rem; }.badge { display: inline-block; background: var(--accent); color: #fff; padding: 2px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 600; vertical-align: middle; }.badge.green { background: var(--green); color: #000; }.badge.orange { background: var(--orange); color: #000; }.card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 1.5rem; margin-bottom: 1.5rem; }.card h2 { font-size: 1.3rem; margin-bottom: 0.8rem; color: var(--accent); }.card h3 { font-size: 1.05rem; margin: 1rem 0 0.4rem; color: var(--green); }pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 8px; padding: 1rem; overflow-x: auto; font-size: 0.85rem; line-height: 1.5; margin: 0.5rem 0; }code { font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; }.inline { background: var(--code-bg); padding: 2px 6px; border-radius: 4px; font-size: 0.88em; }table { width: 100%; border-collapse: collapse; margin: 0.5rem 0; }th, td { text-align: left; padding: 0.5rem 0.8rem; border-bottom: 1px solid var(--border); font-size: 0.9rem; }th { color: var(--dim); font-weight: 600; }.method { font-weight: 700; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; }.get { background: var(--green); color: #000; }.post { background: var(--accent); color: #fff; }a { color: var(--green); text-decoration: none; }a:hover { text-decoration: underline; }.flow { display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap; margin: 0.5rem 0; }.flow-step { background: var(--code-bg); border: 1px solid var(--border); border-radius: 6px; padding: 4px 12px; font-size: 0.85rem; }.flow-arrow { color: var(--accent); font-weight: bold; }.tip { background: rgba(78, 204, 163, 0.1); border-left: 3px solid var(--green); padding: 0.8rem 1rem; border-radius: 0 8px 8px 0; margin: 0.8rem 0; font-size: 0.9rem; }.warn { background: rgba(233, 69, 96, 0.1); border-left: 3px solid var(--accent); padding: 0.8rem 1rem; border-radius: 0 8px 8px 0; margin: 0.8rem 0; font-size: 0.9rem; }footer { text-align: center; padding: 2rem 0 1rem; color: var(--dim); font-size: 0.8rem; }@media (max-width: 600px) { .container { padding: 1rem; } h1 { font-size: 1.6rem; } pre { font-size: 0.75rem; } }</style></head><body><div class="container"><h1><span>⚡</span> StreamForge API <span>v3.0</span></h1><p class="subtitle">Multi-language stream scraper — direct m3u8 URLs via API, no browser needed <span class="badge">Hindi</span> <span class="badge">Tamil</span> <span class="badge">Telugu</span> <span class="badge">English</span> <span class="badge">French</span> <span class="badge">Italian</span></p><!-- Quick Start --><div class="card"><h2>🚀 Quick Start</h2><p>The typical flow is: <strong>search</strong> for a movie/show → get the <code class="inline">tmdb_id</code> → <strong>scrape</strong> for streams.</p><div class="flow"><span class="flow-step">1. Search TMDB</span><span class="flow-arrow">→</span><span class="flow-step">2. Get tmdb_id</span><span class="flow-arrow">→</span><span class="flow-step">3. Scrape Streams</span><span class="flow-arrow">→</span><span class="flow-step">4. Get m3u8 URLs</span></div><h3>Step 1 — Search for a movie</h3><pre><code>curl "<span id="base"></span>/api/search?q=Jawan"</code></pre><h3>Step 2 — Scrape streams using the tmdb_id</h3><pre><code>curl -X POST "<span id="base2"></span>/api/scrape" \\-H "Content-Type: application/json" \\-d '{"tmdb_id": 937278, "media_type": "movie"}'</code></pre><h3>For TV shows (with season & episode)</h3><pre><code>curl -X POST "<span id="base3"></span>/api/scrape" \\-H "Content-Type: application/json" \\-d '{"tmdb_id": 1396, "media_type": "tv", "season": 1, "episode": 1}'</code></pre><h3>Scrape specific sources only</h3><pre><code>curl -X POST "<span id="base4"></span>/api/scrape" \\-H "Content-Type: application/json" \\-d '{"tmdb_id": 937278, "media_type": "movie", "sources": ["CineSu", "AllMovieLand"]}'</code></pre><h3>Scrape ALL sources at once</h3><pre><code>curl -X POST "<span id="base5"></span>/api/scrape/all" \\-H "Content-Type: application/json" \\-d '{"tmdb_id": 937278, "media_type": "movie"}'</code></pre></div><!-- Endpoints Reference --><div class="card"><h2>📡 Endpoints</h2><table><tr><th>Method</th><th>Path</th><th>Description</th></tr><tr><td><span class="method get">GET</span></td><td><code class="inline">/api/search</code></td><td>Search TMDB for movies & TV shows</td></tr><tr><td><span class="method post">POST</span></td><td><code class="inline">/api/scrape</code></td><td>Scrape streaming links (select sources)</td></tr><tr><td><span class="method post">POST</span></td><td><code class="inline">/api/scrape/all</code></td><td>Scrape ALL sources at once</td></tr><tr><td><span class="method get">GET</span></td><td><code class="inline">/api/sources</code></td><td>List available sources & their languages</td></tr><tr><td><span class="method get">GET</span></td><td><code class="inline">/api/health</code></td><td>Health check</td></tr></table></div><!-- Search Endpoint --><div class="card"><h2>🔍 GET /api/search</h2><p>Proxy search against TMDB. Returns movies & TV shows matching your query.</p><h3>Query Parameters</h3><table><tr><th>Param</th><th>Type</th><th>Required</th><th>Description</th></tr><tr><td><code class="inline">q</code></td><td>string</td><td>✅ Yes</td><td>Search query (movie/show title)</td></tr><tr><td><code class="inline">page</code></td><td>int</td><td>No</td><td>Page number (default: 1)</td></tr></table><h3>Example Response</h3><pre><code>{"page": 1,"total_results": 3,"total_pages": 1,"results": [{"id": 937278, // ← this is your tmdb_id"media_type": "movie","title": "Jawan","overview": "A prison warden...","poster_path": "/jFt1gS4BGHlK8xt76Y3B3tNfKqQ.jpg","release_date": "2023-09-07"}]}</code></pre></div><!-- Scrape Endpoint --><div class="card"><h2>🎬 POST /api/scrape</h2><p>The main endpoint. Takes a TMDB ID and returns direct m3u8 streaming URLs.</p><h3>Request Body</h3><table><tr><th>Field</th><th>Type</th><th>Required</th><th>Description</th></tr><tr><td><code class="inline">tmdb_id</code></td><td>int</td><td>✅ Yes</td><td>TMDB movie/show ID (from /api/search)</td></tr><tr><td><code class="inline">media_type</code></td><td>string</td><td>No</td><td>"movie" (default) or "tv"</td></tr><tr><td><code class="inline">season</code></td><td>int</td><td>No*</td><td>Season number (required for TV)</td></tr><tr><td><code class="inline">episode</code></td><td>int</td><td>No*</td><td>Episode number (required for TV)</td></tr><tr><td><code class="inline">sources</code></td><td>string[]</td><td>No</td><td>Source names to use (default: CineSu, VixSrc, Popr, AllMovieLand)</td></tr></table><h3>Example Response</h3><pre><code>{"success": true,"tmdb_id": 937278,"title": "Jawan","imdb_id": "tt15353838","results": [{"source": "CineSu","title": "English","quality": "1920x1080","language": "English","url": "https://cine.su/v1/stream/....m3u8","type": "m3u8"},{"source": "AllMovieLand","title": "Hindi","quality": "1920x1080","language": "Hindi","url": "https://....m3u8","type": "m3u8"},{"source": "Popr/catflix","title": "Hindi - 1080p","quality": "Hindi - 1080p","language": "Hindi","url": "https://....m3u8","type": "m3u8"}],"errors": ["VixSrc: Token expired"]}</code></pre></div><!-- Sources --><div class="card"><h2>🌐 Sources</h2><table><tr><th>Source</th><th>Languages</th><th>Movies</th><th>TV</th><th>Method</th><th>Reliability</th></tr><tr><td><strong>CineSu</strong></td><td>English</td><td>✅</td><td>✅</td><td>Direct API</td><td><span class="badge green">High</span></td></tr><tr><td><strong>VixSrc</strong></td><td>Multi-audio (Italian, English, etc.)</td><td>✅</td><td>✅</td><td>Token API</td><td><span class="badge orange">Medium</span></td></tr><tr><td><strong>VidNest</strong></td><td>French, English, Multi</td><td>✅</td><td>✅</td><td>Custom Base64 API</td><td><span class="badge orange">Medium</span></td></tr><tr><td><strong>Popr</strong></td><td>Hindi, English, Tamil, Telugu, French</td><td>✅</td><td>✅</td><td>Aggregator API</td><td><span class="badge green">High</span></td></tr><tr><td><strong>AllMovieLand</strong></td><td>Hindi, Tamil, Telugu, Bengali</td><td>✅</td><td>✅</td><td>CSRF Scrape</td><td><span class="badge orange">Medium</span></td></tr></table><div class="tip"><strong>💡 Best for Hindi content:</strong> Use <code class="inline">sources: ["Popr", "AllMovieLand"]</code> — these have the best Hindi coverage.</div><div class="tip"><strong>💡 Best for English:</strong> Use <code class="inline">sources: ["CineSu", "Popr"]</code> — CineSu is the most reliable for English.</div></div><!-- Notes --><div class="card"><h2>⚠️ Notes</h2><ul style="padding-left: 1.2rem; font-size: 0.92rem;"><li>All streams return <strong>direct m3u8 URLs</strong> — use any HLS player (VLC, hls.js, mpv) to play them.</li><li>VixSrc tokens expire in ~2 seconds; the API handles retries automatically but may still fail occasionally.</li><li>AllMovieLand requires a valid IMDB ID (fetched automatically from TMDB). If TMDB has no IMDB link, this source is skipped.</li><li>Each scraper has a <strong>30-second timeout</strong>. Use <code class="inline">sources</code> to limit which scrapers run for faster results.</li><li>The <code class="inline">type</code> field in results is usually <code class="inline">"m3u8"</code>. Rare cases may return <code class="inline">"direct"</code> for non-HLS streams.</li></ul></div><!-- JSON mode --><div class="card"><h2>🤖 Programmatic Access</h2><p>For non-browser clients, add <code class="inline">?format=json</code> to get the original JSON response:</p><pre><code>curl "<span id="base6"></span>/?format=json"</code></pre><p style="margin-top:0.5rem;">Or just set <code class="inline">Accept: application/json</code> header.</p></div><footer>StreamForge API v3.0 • Powered by FastAPI • Deployed on HuggingFace Spaces</footer></div><script>// Fill base URLs dynamicallyvar b = window.location.origin;document.getElementById('base').textContent = b;document.getElementById('base2').textContent = b;document.getElementById('base3').textContent = b;document.getElementById('base4').textContent = b;document.getElementById('base5').textContent = b;document.getElementById('base6').textContent = b;</script></body></html>""")@app.get("/api/health")async def health():29 unmodified lines@app.post("/api/scrape")async def scrape(request: ScrapeRequest):# Get TMDB infotry:info = await get_tmdb_info(request.tmdb_id, request.media_type)except Exception as e:raise HTTPException(status_code=500, detail=f"TMDB lookup failed: {str(e)}")imdb_id = info.get("imdb_id")title = info.get("title")all_results = []all_errors = []# Define all scrapersrequested_sources = request.sources or ["CineSu", "VixSrc", "Popr", "AllMovieLand"]async def run_scraper(name: str, scraper):try:r, e = await asyncio.wait_for(scraper(), timeout=30)return r, eexcept asyncio.TimeoutError:return [], [f"{name}: Timeout (30s)"]except Exception as ex:return [], [f"{name}: {str(ex)}"]scraper_map = {"CineSu": lambda: scrape_cinesu(request.tmdb_id, request.media_type, request.season, request.episode),"VixSrc": lambda: scrape_vixsrc(request.tmdb_id, request.media_type, request.season, request.episode),"VidNest": lambda: scrape_vidnest(request.tmdb_id, request.media_type, request.season, request.episode),"Popr": lambda: scrape_popr(request.tmdb_id, request.media_type, request.season, request.episode),"AllMovieLand": lambda: scrape_allmovieland(imdb_id, request.media_type, request.season, request.episode) if imdb_id else ([], ["AllMovieLand: No IMDB ID"]),}active_scrapers = {k: v for k, v in scraper_map.items() if k in requested_sources}tasks = [run_scraper(name, scraper) for name, scraper in active_scrapers.items()]task_results = await asyncio.gather(*tasks, return_exceptions=True)for result in task_results:if isinstance(result, Exception):all_errors.append(f"Scraper failed: {str(result)}")else:r, e = resultall_results.extend(r)all_errors.extend(e)return {"success": len(all_results) > 0,"tmdb_id": request.tmdb_id,"title": title,"imdb_id": imdb_id,"results": [r.dict() for r in all_results],"errors": all_errors,}@app.post("/api/scrape/all")async def scrape_all(request: ScrapeRequest):"""Scrape from ALL available sources"""request.sources = ["CineSu", "VixSrc", "VidNest", "Popr", "AllMovieLand"]return await scrape(request)if __name__ == "__main__":704 unmodified lines70570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095129 unmodified lines981982983984985986987988989990991992993994995996704 unmodified linesreturn results, errors# ===== Source Map =====SOURCE_MAP = {"cinesu": {"name": "CineSu", "fn": lambda tid, mt, s, e: scrape_cinesu(tid, mt, s, e)},"vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e)},"vidnest": {"name": "VidNest", "fn": lambda tid, mt, s, e: scrape_vidnest(tid, mt, s, e)},"popr": {"name": "Popr", "fn": lambda tid, mt, s, e: scrape_popr(tid, mt, s, e)},"allmovieland": {"name": "AllMovieLand", "fn_amll": True},}DEFAULT_SOURCES = ["cinesu", "vixsrc", "popr", "allmovieland"]# ===== Helper: Run scrapers and return results =====async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: int = None, source_keys: list = None):"""Core scrape logic shared by all endpoints."""info = await get_tmdb_info(tmdb_id, media_type)imdb_id = info.get("imdb_id")title = info.get("title")all_results = []all_errors = []keys = source_keys or DEFAULT_SOURCESasync def run_one(key: str):src = SOURCE_MAP.get(key)if not src:return [], [f"{key}: Unknown source"]try:if src.get("fn_amll"):if not imdb_id:return [], [f"AllMovieLand: No IMDB ID"]r, e = await asyncio.wait_for(scrape_allmovieland(imdb_id, media_type, season, episode), timeout=30)else:r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=30)return r, eexcept asyncio.TimeoutError:return [], [f"{src.get('name', key)}: Timeout (30s)"]except Exception as ex:return [], [f"{src.get('name', key)}: {str(ex)}"]tasks = [run_one(k) for k in keys]task_results = await asyncio.gather(*tasks, return_exceptions=True)for result in task_results:if isinstance(result, Exception):all_errors.append(f"Scraper failed: {str(result)}")else:r, e = resultall_results.extend(r)all_errors.extend(e)return {"success": len(all_results) > 0,"tmdb_id": tmdb_id,"title": title,"imdb_id": imdb_id,"results": [r.dict() for r in all_results],"errors": all_errors,}def results_to_html(data: dict) -> str:"""Convert scrape results to simple phone-friendly HTML with clickable m3u8 links."""title = data.get("title", "Unknown")tmdb_id = data.get("tmdb_id")imdb_id = data.get("imdb_id")results = data.get("results", [])errors = data.get("errors", [])lines = []lines.append("<pre style='font-size:14px;line-height:1.6;white-space:pre-wrap;word-break:break-all;'>")lines.append(f"<b>{title}</b>")if imdb_id:lines.append(f"TMDB: {tmdb_id} | IMDB: {imdb_id}")lines.append("")if not results:lines.append("No streams found.")else:current_source = ""for r in results:src = r.get("source", "")if src != current_source:lines.append(f"<b>{'='*40}</b>")lines.append(f"<b>{src}</b>")current_source = srclang = r.get("language", "")quality = r.get("quality", "")url = r.get("url", "")label_parts = [p for p in [lang, quality] if p and p != "Auto"]label = " | ".join(label_parts) if label_parts else "Stream"lines.append(f" <a href='{url}' target='_blank'>{label}</a>")if errors:lines.append("")lines.append(f"<b>{'='*40}</b>")lines.append("<b>Errors:</b>")for e in errors:lines.append(f" x {e}")lines.append("</pre>")return "\n".join(lines)# ===== API Endpoints =====@app.get("/")async def root():return HTMLResponse(content="""<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>StreamForge API</title><style>body { font-family: monospace; background: #111; color: #ccc; padding: 1rem; max-width: 800px; margin: 0 auto; font-size: 14px; line-height: 1.7; }a { color: #5bf; text-decoration: none; }a:hover { text-decoration: underline; }b { color: #fff; }h1 { color: #e94560; font-size: 1.4rem; margin-bottom: 0.3rem; }h2 { color: #4ecca3; font-size: 1.1rem; margin-top: 1.5rem; }.url { background: #1a1a2e; padding: 4px 8px; border-radius: 4px; display: inline-block; margin: 2px 0; word-break: break-all; }.note { color: #888; font-size: 13px; }hr { border: none; border-top: 1px solid #333; margin: 1.5rem 0; }</style></head><body><h1>StreamForge API v3</h1><p class="note">Multi-language m3u8 stream scraper</p><h2>Quick URLs (just type in browser)</h2><p><b>Movie:</b></p><div class="url">/movie/912649</div><div class="url">/movie/912649/popr</div><p><b>TV Show:</b></p><div class="url">/tv/1396/1/1</div><div class="url">/tv/1396/1/1/cinesu</div><p><b>Search:</b></p><div class="url">/search/Jawan</div><hr><h2>Sources (use in URL)</h2><table style="font-size:13px;border-collapse:collapse;"><tr><td style="padding:2px 12px;color:#4ecca3;">cinesu</td><td>English</td><td style="color:#4ecca3;">high</td></tr><tr><td style="padding:2px 12px;color:#4ecca3;">vixsrc</td><td>Multi-audio</td><td style="color:#ff9f43;">medium</td></tr><tr><td style="padding:2px 12px;color:#4ecca3;">vidnest</td><td>French, English</td><td style="color:#ff9f43;">medium</td></tr><tr><td style="padding:2px 12px;color:#4ecca3;">popr</td><td>Hindi, Tamil, Telugu, English, French</td><td style="color:#4ecca3;">high</td></tr><tr><td style="padding:2px 12px;color:#4ecca3;">allmovieland</td><td>Hindi, Tamil, Telugu, Bengali</td><td style="color:#ff9f43;">medium</td></tr></table><hr><h2>API Endpoints (for apps/scripts)</h2><div class="url">GET /api/search?q=Jawan</div><div class="url">GET /api/sources</div><div class="url">GET /api/health</div><div class="url">POST /api/scrape {"tmdb_id":912649,"media_type":"movie"}</div><div class="url">POST /api/scrape {"tmdb_id":912649,"media_type":"tv","season":1,"episode":1}</div><div class="url">POST /api/scrape {"tmdb_id":912649,"sources":["cinesu","popr"]}</div><div class="url">POST /api/scrape/all {"tmdb_id":912649}</div><hr><h2>Tips</h2><p>- Best for Hindi: <b>/movie/ID/popr</b> or <b>/movie/ID/allmovieland</b></p><p>- Best for English: <b>/movie/ID/cinesu</b></p><p>- No source = all default sources (cinesu, vixsrc, popr, allmovieland)</p><p>- Add <b>?json</b> to any URL for raw JSON instead of HTML</p><p>- m3u8 links can be played in VLC, mpv, or any HLS player</p></body></html>""")# ===== Simple GET endpoints (phone-friendly) =====@app.get("/movie/{tmdb_id}")async def movie_all(tmdb_id: int, json: Optional[str] = Query(None)):data = await run_scrape(tmdb_id, "movie")if json is not None:return datareturn HTMLResponse(content=results_to_html(data))@app.get("/movie/{tmdb_id}/{source}")async def movie_source(tmdb_id: int, source: str, json: Optional[str] = Query(None)):source = source.lower()if source not in SOURCE_MAP:raise HTTPException(400, f"Unknown source '{source}'. Available: {', '.join(SOURCE_MAP.keys())}")data = await run_scrape(tmdb_id, "movie", source_keys=[source])if json is not None:return datareturn HTMLResponse(content=results_to_html(data))@app.get("/tv/{tmdb_id}/{season}/{episode}")async def tv_all(tmdb_id: int, season: int, episode: int, json: Optional[str] = Query(None)):data = await run_scrape(tmdb_id, "tv", season=season, episode=episode)if json is not None:return datareturn HTMLResponse(content=results_to_html(data))@app.get("/tv/{tmdb_id}/{season}/{episode}/{source}")async def tv_source(tmdb_id: int, season: int, episode: int, source: str, json: Optional[str] = Query(None)):source = source.lower()if source not in SOURCE_MAP:raise HTTPException(400, f"Unknown source '{source}'. Available: {', '.join(SOURCE_MAP.keys())}")data = await run_scrape(tmdb_id, "tv", season=season, episode=episode, source_keys=[source])if json is not None:return datareturn HTMLResponse(content=results_to_html(data))@app.get("/search/{query}")async def search_simple(query: str, page: int = 1):async with httpx.AsyncClient(timeout=10) as client:resp = await client.get(f"{TMDB_BASE}/search/multi",params={"api_key": TMDB_API_KEY, "query": query, "page": page, "include_adult": False})data = resp.json()filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]lines = ["<pre style='font-size:14px;line-height:1.7;white-space:pre-wrap;'>"]lines.append(f"<b>Search: {query}</b> ({len(filtered)} results)\n")for r in filtered[:20]:mid = r.get("id")mt = r.get("media_type", "movie")t = r.get("title") or r.get("name", "Unknown")year = (r.get("release_date") or r.get("first_air_date") or "")[:4]type_label = "TV" if mt == "tv" else "Movie"lines.append(f" <a href='/{mt}/{mid}'>{t}</a> ({year}) [{type_label}] id:{mid}")lines.append("</pre>")return HTMLResponse(content="\n".join(lines))# ===== JSON API endpoints (for apps/scripts) =====@app.get("/api/health")async def health():29 unmodified lines@app.post("/api/scrape")async def scrape(request: ScrapeRequest):# Normalize source names to lowercase keyssource_keys = Noneif request.sources:source_keys = [s.lower() for s in request.sources]return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, source_keys)@app.post("/api/scrape/all")async def scrape_all(request: ScrapeRequest):"""Scrape from ALL available sources"""return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, list(SOURCE_MAP.keys()))if __name__ == "__main__":
main.py+237-338