Spaces:
Running
Running
Z User commited on
Commit ·
93094bf
1
Parent(s): 426e8e9
v4: JSON-only API, fixed VixSrc, removed AllMovieLand, clean JSON docs
Browse files1234567891011121314151617181920212223242526279 unmodified lines373839404142434445463 unmodified lines50515253545556575859606162638 unmodified lines7273747576777879808182837 unmodified lines91929394959697989910010110210310421 unmodified lines1261271281291301311324 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611624 unmodified lines1671681691701711721731741751 unmodified line1771781791801811821832 unmodified lines1861871881891901911921931 unmodified line19519619719819920020120220320420520620720811 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792803 unmodified lines2842852862872882892902912922932942956 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323334 unmodified lines33833934034134234334416 unmodified lines36136236336436536636736836937037146 unmodified lines41841942042142242342442542642742842943043143243343443543643743843944044112 unmodified lines45445545645745845946028 unmodified lines48949049149249349449549649749849950050150250350450550650750850951051151210 unmodified lines5235245255265275285295303 unmodified lines5345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297304 unmodified lines7357367377387397407417427437447457467477487497507517527539 unmodified lines7637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259265 unmodified lines9329339349359369379389399409419429439449459469479489499509512 unmodified lines95495595695795895996096196296396496596614 unmodified lines9819829839849859869871 unmodified line989990991992993994995"""StreamForge API v3 - Multi-Language Stream ScraperBased on CloudStream extensions + CinePro core providersScrapes direct m3u8 URLs via API endpoints (no browser automation needed)"""from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponsefrom pydantic import BaseModelfrom typing import Optionalimport httpximport jsonimport reimport hashlibimport base64import timeimport asynciofrom bs4 import BeautifulSoupapp = FastAPI(title="StreamForge API",description="Multi-language stream scraper - Hindi, Tamil, Telugu, English, Italian, French & more",version="3.0.0",)app.add_middleware(9 unmodified linesHEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Accept": "application/json","Accept-Language": "en-US,en;q=0.5",}# ===== Models =====class ScrapeRequest(BaseModel):3 unmodified linesepisode: Optional[int] = Nonesources: Optional[list[str]] = Noneclass StreamResult(BaseModel):source: strtitle: strquality: strlanguage: strurl: strtype: str# ===== Helpers =====8 unmodified linesreturn {"imdb_id": data.get("external_ids", {}).get("imdb_id"),"title": data.get("title") or data.get("name"),"overview": data.get("overview"),"poster_path": data.get("poster_path"),"original_title": data.get("original_title") or data.get("original_name"),"year": (data.get("release_date") or data.get("first_air_date") or "")[:4],}def detect_language(label: str) -> str:lower = label.lower()if "hindi" in lower or "hin" in lower: return "Hindi"7 unmodified linesif "french" in lower or "fra" in lower or "vf" in lower: return "French"if "german" in lower or "deu" in lower or "ger" in lower: return "German"if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish"if "vietnamese" in lower or "vie" in lower: return "Vietnamese"if "arabic" in lower or "ara" in lower: return "Arabic"if "multi" in lower: return "Multi"return "English" # Default for API-based providers# ===== CineSu Scraper (Direct m3u8 API - English, some multi-language) =====# Flow: Construct URL → HEAD verify → return m3u8async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []21 unmodified lineserrors.append(f"CineSu: HTTP {resp.status_code}")return results, errors# Parse M3U8 playlistcontent = resp.textif "#EXT-X-STREAM-INF" in content:lines = content.split("\n")4 unmodified linesquality = resolution.group(1) if resolution else "Auto"label = name.group(1) if name else qualityif i + 1 < len(lines) and lines[i + 1].startswith("http"):results.append(StreamResult(source="CineSu",title=label,quality=quality,language="English",url=lines[i + 1].strip(),type="m3u8",))elif ".m3u8" in content:# Direct m3u8 URLm3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content)if m3u8_match:results.append(StreamResult(source="CineSu",title="English Stream",quality="Auto",language="English",url=m3u8_match.group(0),type="m3u8",))if not results:errors.append("CineSu: No streams found")4 unmodified linesreturn results, errors# ===== VixSrc Scraper (Token-based m3u8 - Multi-language audio) =====# Flow: API → embed HTML → extract token → master m3u8 with multi-audio# Note: The src_path token expires VERY fast (~2s), so we must fetch immediatelyasync def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []1 unmodified linetry:async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:# Step 1: Get embed path (contains short-lived token)if media_type == "movie":api_url = f"https://vixsrc.to/api/movie/{tmdb_id}"else:2 unmodified linesapi_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}"api_resp = await client.get(api_url)# VixSrc sometimes returns HTML instead of JSON (Cloudflare)try:api_data = api_resp.json()except:1 unmodified linereturn results, errorssrc_path = api_data.get("src", "")if not src_path:errors.append("VixSrc: No embed path returned")return results, errors# Step 2: IMMEDIATELY fetch embed HTML (token expires fast)embed_resp = await client.get(f"https://vixsrc.to{src_path}")if embed_resp.status_code == 410:# Token expired, retry onceapi_resp2 = await client.get(api_url)11 unmodified lineshtml = embed_resp.text# Step 3: Extract token, expires, playlist URL# Try multiple regex patterns since the HTML format can varytoken = Noneexpires = Noneplaylist = None# Pattern 1: key:"value" formattoken_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html)expires_match = re.search(r'expires["\']\s*:\s*["\']([^"\']+)', html)url_match = re.search(r'url\s*:\s*["\']([^"\']+)', html)if token_match:token = token_match.group(1)if expires_match:expires = expires_match.group(1)if url_match:playlist = url_match.group(1)# Pattern 2: JavaScript variable formatif not token:token_match2 = re.search(r'var\s+token\s*=\s*["\']([^"\']+)', html)if token_match2:token = token_match2.group(1)if not expires:expires_match2 = re.search(r'var\s+expires\s*=\s*["\']([^"\']+)', html)if expires_match2:expires = expires_match2.group(1)if not playlist:playlist_match2 = re.search(r'(?:playlist|file|src)\s*[:=]\s*["\']([^"\']+/playlist[^"\']*)', html)if playlist_match2:playlist = playlist_match2.group(1)# Pattern 3: JSON object in script tagif not token:json_match = re.search(r'\{[^}]*token[^}]*\}', html)if json_match:try:j = json.loads(json_match.group(0))token = j.get("token")expires = j.get("expires")playlist = j.get("url") or j.get("playlist") or j.get("file")except:passif not (token and playlist):errors.append("VixSrc: Could not extract stream parameters from embed")return results, errors# Step 4: Build master URLif not expires:expires = str(int(time.time()) + 86400)sep = "&" if "?" in playlist else "?"master_url = f"{playlist}{sep}token={token}&expires={expires}&h=1"# Step 5: Fetch master playlistpl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"})pl_content = pl_resp.text3 unmodified lineslines = pl_content.split("\n")for line in lines:if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"):lang_match = re.search(r'LANGUAGE="([^"]+)"', line)name_match = re.search(r'NAME="([^"]+)"', line)uri_match = re.search(r'URI="([^"]+)"', line)if lang_match and uri_match:audio_tracks.append({"language": name_match.group(1) if name_match else lang_match.group(1),"uri": uri_match.group(1),})6 unmodified linesvideo_url = lines[i + 1].strip()if audio_tracks:for track in audio_tracks:results.append(StreamResult(source="VixSrc",title=f"{track['language']} Audio",quality=quality,language=detect_language(track["language"]),url=video_url,type="m3u8",))else:results.append(StreamResult(source="VixSrc",title="English Stream",quality=quality,language="English",url=video_url,type="m3u8",))else:results.append(StreamResult(source="VixSrc",title="Stream",quality="Auto",language="English",url=master_url,type="m3u8",))if not results:errors.append("VixSrc: No streams found in playlist")4 unmodified linesreturn results, errors# ===== VidNest Scraper (Custom base64 - Multi-language including French) =====VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="16 unmodified linesresult.append((((c2 & 0x03) << 6) | c3) & 0xff)return bytes(result).decode("utf-8", errors="ignore")async def scrape_vidnest(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []# VidNest servers and their languagesservers = {"purstream": "French","klikxxi": "English",46 unmodified linessource_name = source.get("name", source.get("label", ""))stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"# Detect language from source name or serverlang = detect_language(source_name) if source_name else languageserver_results.append(StreamResult(source=f"VidNest/{server_name}",title=source_name or title,quality=quality,language=lang,url=stream_url,type=stream_type,))except Exception as e:return server_results, f"{server_name}: {str(e)}"return server_results, None# Fetch all servers in paralleltasks = [fetch_server(name, lang) for name, lang in servers.items()]task_results = await asyncio.gather(*tasks, return_exceptions=True)12 unmodified linesreturn results, errors# ===== Popr Scraper (Aggregator API - Multi-language including Hindi) =====async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []28 unmodified linesis_m3u8 = stream.get("isM3U8", False)stream_type = "m3u8" if is_m3u8 else "direct"# Detect language from quality labellang = detect_language(quality)server_results.append(StreamResult(source=f"Popr/{server}",title=quality,quality=quality,language=lang,url=stream_url,type=stream_type,))except Exception as e:return server_results, f"{server}: {str(e)}"return server_results, None# Fetch servers in paralleltasks = [fetch_server(s) for s in servers]task_results = await asyncio.gather(*tasks, return_exceptions=True)10 unmodified linesseen_urls = set()unique_results = []for r in results:if r.url not in seen_urls:seen_urls.add(r.url)unique_results.append(r)results = unique_results3 unmodified linesreturn results, errors# ===== AllMovieLand Scraper (Hindi, Tamil, Telugu, Bengali - CSRF-based) =====async def scrape_allmovieland(imdb_id: str, media_type: str, season: int = None, episode: int = None):results = []errors = []try:async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:known_domains = ["piexe411qok.com"]# Discover player domaintry:resp = await client.get("https://allmovieland.one/")html = resp.textdomains = set(re.findall(r'https?://([a-z0-9]+\.com)', html))skip = {"google.com", "facebook.com", "youtube.com", "allmovielandapp.com","bit.ly", "vk.com", "ok.ru", "googletagmanager.com"}for d in domains:if d not in skip:known_domains.insert(0, d)except:pass# Get PHPSESSIDresp0 = await client.get("https://allmovieland.one/")aml_sessid = ""for name, value in resp0.cookies.items():if name == "PHPSESSID":aml_sessid = valuebreakif not aml_sessid:errors.append("AllMovieLand: Could not get session")return results, errors# Find working player domain and get embedplayer_domain = Noneembed_html = Nonefor domain in known_domains:try:resp = await client.get(f"https://{domain}/play/{imdb_id}",headers={"Referer": "https://allmovieland.one/"},)if "HDVBPlayer" in resp.text or "let p3" in resp.text:player_domain = domainembed_html = resp.textbreakexcept:continueif not player_domain or not embed_html:errors.append("AllMovieLand: Could not load player page")return results, errorsembed_url = f"https://{player_domain}/play/{imdb_id}"# Parse config and POST for playlist (with CSRF retry)for attempt in range(3):try:# Get fresh embed for CSRF tokenresp1 = await client.get(f"https://{player_domain}/play/{imdb_id}",headers={"Referer": "https://allmovieland.one/"},)html = resp1.textmatch = re.search(r'let\s+p3\s*=\s*(\{[\s\S]*?\})\s*;', html)if not match:match = re.search(r'new\s+HDVBPlayer\((\{[\s\S]*?\})\)', html)if not match:continuetry:config = json.loads(match.group(1))except:config = json.loads(match.group(1).replace("\\/", "/"))key = config.get("key", "")file_url = config.get("file", "").replace("\\/", "/")# POST immediately with proper headersresp2 = await client.post(file_url,headers={"X-CSRF-TOKEN": key,"Referer": embed_url,"Cookie": f"PHPSESSID={aml_sessid}","Content-Type": "application/x-www-form-urlencoded","Origin": f"https://{player_domain}",})content = resp2.text.strip()if content in ("7", "10", "11"):continue # CSRF expired, retryplaylist = json.loads(content)# Get m3u8 for each languagefor item in playlist:lang = item.get("title", "Unknown")file_id = item.get("file", "")playlist_url = f"https://{player_domain}/playlist/{file_id}.txt"resp3 = await client.post(playlist_url,headers={"X-CSRF-TOKEN": key,"Referer": embed_url,"Cookie": f"PHPSESSID={aml_sessid}","Content-Type": "application/x-www-form-urlencoded","Origin": f"https://{player_domain}",})m3u8 = resp3.text.strip()if m3u8 in ("7", "10", "11"):continueif m3u8.startswith("#EXTM3U"):lines = m3u8.split("\n")for i, line in enumerate(lines):if line.startswith("#EXT-X-STREAM-INF:"):quality = re.search(r'RESOLUTION=(\d+x\d+)', line)quality_str = quality.group(1) if quality else "Auto"if i + 1 < len(lines) and lines[i + 1].startswith("http"):results.append(StreamResult(source="AllMovieLand",title=lang,quality=quality_str,language=detect_language(lang),url=lines[i + 1].strip(),type="m3u8",))elif m3u8.startswith("http"):url = m3u8.split("\n")[0].strip()stream_type = "m3u8" if ".m3u8" in url else "direct"results.append(StreamResult(source="AllMovieLand",title=lang,quality="Auto",language=detect_language(lang),url=url,type=stream_type,))elif ".m3u8" in m3u8:m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', m3u8)if m3u8_match:results.append(StreamResult(source="AllMovieLand",title=lang,quality="Auto",language=detect_language(lang),url=m3u8_match.group(0),type="m3u8",))break # Success, stop retryingexcept:continueif not results:errors.append("AllMovieLand: No streams found")except Exception as e:errors.append(f"AllMovieLand: {str(e)}")return 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 = []4 unmodified linesif 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)9 unmodified linesreturn {"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):5 unmodified linesdata = 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():2 unmodified lines@app.get("/api/sources")async def list_sources():return {"sources": [{"name": "CineSu", "language": "English", "langCode": "en", "type": "both", "method": "direct_api"},{"name": "VixSrc", "language": "Multi", "langCode": "multi", "type": "both", "method": "token_api"},{"name": "VidNest", "language": "Multi", "langCode": "multi", "type": "both", "method": "custom_b64_api"},{"name": "Popr", "language": "Multi", "langCode": "multi", "type": "both", "method": "aggregator_api"},{"name": "AllMovieLand", "language": "Hindi", "langCode": "hi", "type": "both", "method": "csrf_scrape"},]}@app.get("/api/search")14 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]1 unmodified line@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()))123456789101112131415161718192021229 unmodified lines32333435363738394041423 unmodified lines4647484950518 unmodified lines606162636465666768697 unmodified lines777879808182838485868721 unmodified lines1091101111121131144 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421434 unmodified lines1481491501511521531541 unmodified line1561571581591601611622 unmodified lines1651661671681691701711 unmodified line17317417517617717817918018118218318418511 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402413 unmodified lines2452462472482492502512522532542552562576 unmodified lines2642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962974 unmodified lines30230330430530630730816 unmodified lines32532632732832933033133233333433546 unmodified lines38238338438538638738838939039139239339439539639739839940040140240312 unmodified lines41641741841942042142228 unmodified lines45145245345445545645745845946046146246346446546646746846947047147210 unmodified lines4834844854864874884894903 unmodified lines4944954964974984995005015025035045055065075085095105115125135145155165175185195205214 unmodified lines5265275285295305315325335345355365379 unmodified lines5475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296305 unmodified lines6366376386396406416426436446456466476486496506516526536546556566576586596606616626632 unmodified lines66666766866967067167267367414 unmodified lines6896906916926936941 unmodified line696697698699700701"""StreamForge API v4 - Multi-Language Stream ScraperScrapes direct m3u8 URLs from multiple sources"""from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optionalimport httpximport jsonimport reimport timeimport asyncioapp = FastAPI(title="StreamForge API",description="Multi-language m3u8 stream scraper",version="4.0.0",)app.add_middleware(9 unmodified linesHEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36","Accept": "application/json, text/html, */*","Accept-Language": "en-US,en;q=0.5",}# ===== Models =====class ScrapeRequest(BaseModel):3 unmodified linesepisode: Optional[int] = Nonesources: Optional[list[str]] = None# ===== Helpers =====8 unmodified linesreturn {"imdb_id": data.get("external_ids", {}).get("imdb_id"),"title": data.get("title") or data.get("name"),"year": (data.get("release_date") or data.get("first_air_date") or "")[:4],}def detect_language(label: str) -> str:lower = label.lower()if "hindi" in lower or "hin" in lower: return "Hindi"7 unmodified linesif "french" in lower or "fra" in lower or "vf" in lower: return "French"if "german" in lower or "deu" in lower or "ger" in lower: return "German"if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish"if "multi" in lower: return "Multi"return "English"# ===== CineSu Scraper =====async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []21 unmodified lineserrors.append(f"CineSu: HTTP {resp.status_code}")return results, errorscontent = resp.textif "#EXT-X-STREAM-INF" in content:lines = content.split("\n")4 unmodified linesquality = resolution.group(1) if resolution else "Auto"label = name.group(1) if name else qualityif i + 1 < len(lines) and lines[i + 1].startswith("http"):results.append({"source": "CineSu","title": label,"quality": quality,"language": "English","url": lines[i + 1].strip(),"type": "m3u8",})elif ".m3u8" in content:m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content)if m3u8_match:results.append({"source": "CineSu","title": "English Stream","quality": "Auto","language": "English","url": m3u8_match.group(0),"type": "m3u8",})if not results:errors.append("CineSu: No streams found")4 unmodified linesreturn results, errors# ===== VixSrc Scraper (Fixed: uses window.masterPlaylist) =====async def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []1 unmodified linetry:async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:# Step 1: Get embed pathif media_type == "movie":api_url = f"https://vixsrc.to/api/movie/{tmdb_id}"else:2 unmodified linesapi_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}"api_resp = await client.get(api_url)try:api_data = api_resp.json()except:1 unmodified linereturn results, errorssrc_path = api_data.get("src", "")if not src_path:errors.append("VixSrc: No embed path returned")return results, errors# Step 2: Fetch embed HTMLembed_resp = await client.get(f"https://vixsrc.to{src_path}")if embed_resp.status_code == 410:# Token expired, retry onceapi_resp2 = await client.get(api_url)11 unmodified lineshtml = embed_resp.text# Step 3: Extract from window.masterPlaylisttoken = Noneexpires = Noneplaylist_url = Nonemp_match = re.search(r'window\.masterPlaylist\s*=\s*(\{[\s\S]*?\})\s*\n', html)if mp_match:mp_text = mp_match.group(1)token_m = re.search(r"'token'\s*:\s*'([^']+)'", mp_text)expires_m = re.search(r"'expires'\s*:\s*'([^']+)'", mp_text)url_m = re.search(r"url\s*:\s*'([^']+)'", mp_text)if token_m:token = token_m.group(1)if expires_m:expires = expires_m.group(1)if url_m:playlist_url = url_m.group(1)# Fallback: try old patternsif not token:token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html)if token_match:token = token_match.group(1)if not playlist_url:url_match = re.search(r'url\s*:\s*["\']([^"\']+playlist[^"\']*)', html)if url_match:playlist_url = url_match.group(1)if not (token and playlist_url):errors.append("VixSrc: Could not extract stream parameters from embed")return results, errors# Step 4: Build master URL and fetchif not expires:expires = str(int(time.time()) + 86400)sep = "&" if "?" in playlist_url else "?"master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1"pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"})pl_content = pl_resp.text3 unmodified lineslines = pl_content.split("\n")for line in lines:if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"):name_match = re.search(r'NAME="([^"]+)"', line)lang_match = re.search(r'LANGUAGE="([^"]+)"', line)uri_match = re.search(r'URI="([^"]+)"', line)if name_match and uri_match:audio_tracks.append({"language": name_match.group(1),"lang_code": lang_match.group(1) if lang_match else name_match.group(1),"uri": uri_match.group(1),})6 unmodified linesvideo_url = lines[i + 1].strip()if audio_tracks:for track in audio_tracks:results.append({"source": "VixSrc","title": f"{track['language']} Audio","quality": quality,"language": detect_language(track["language"]),"url": video_url,"audio_url": track["uri"],"type": "m3u8",})else:results.append({"source": "VixSrc","title": "English Stream","quality": quality,"language": "English","url": video_url,"type": "m3u8",})else:# Return master URL as-is if we can't parseresults.append({"source": "VixSrc","title": "Stream","quality": "Auto","language": "Multi","url": master_url,"type": "m3u8",})if not results:errors.append("VixSrc: No streams found in playlist")4 unmodified linesreturn results, errors# ===== VidNest Scraper =====VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="16 unmodified linesresult.append((((c2 & 0x03) << 6) | c3) & 0xff)return bytes(result).decode("utf-8", errors="ignore")async def scrape_vidnest(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []errors = []servers = {"purstream": "French","klikxxi": "English",46 unmodified linessource_name = source.get("name", source.get("label", ""))stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"lang = detect_language(source_name) if source_name else languageserver_results.append({"source": f"VidNest/{server_name}","title": source_name or title,"quality": quality,"language": lang,"url": stream_url,"type": stream_type,})except Exception as e:return server_results, f"{server_name}: {str(e)}"return server_results, Nonetasks = [fetch_server(name, lang) for name, lang in servers.items()]task_results = await asyncio.gather(*tasks, return_exceptions=True)12 unmodified linesreturn results, errors# ===== Popr Scraper (Improved dedup) =====async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None):results = []28 unmodified linesis_m3u8 = stream.get("isM3U8", False)stream_type = "m3u8" if is_m3u8 else "direct"lang = detect_language(quality)server_results.append({"source": f"Popr/{server}","title": quality,"quality": quality,"language": lang,"url": stream_url,"type": stream_type,})except Exception as e:return server_results, f"{server}: {str(e)}"return server_results, Nonetasks = [fetch_server(s) for s in servers]task_results = await asyncio.gather(*tasks, return_exceptions=True)10 unmodified linesseen_urls = set()unique_results = []for r in results:if r["url"] not in seen_urls:seen_urls.add(r["url"])unique_results.append(r)results = unique_results3 unmodified linesreturn results, errors# ===== Source Map =====SOURCE_MAP = {"cinesu": {"name": "CineSu", "fn": lambda tid, mt, s, e: scrape_cinesu(tid, mt, s, e),"languages": ["English"], "reliability": "high"},"vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e),"languages": ["English", "Italian", "Multi"], "reliability": "high"},"vidnest": {"name": "VidNest", "fn": lambda tid, mt, s, e: scrape_vidnest(tid, mt, s, e),"languages": ["French", "English", "Multi"], "reliability": "medium"},"popr": {"name": "Popr", "fn": lambda tid, mt, s, e: scrape_popr(tid, mt, s, e),"languages": ["Hindi", "Tamil", "Telugu", "English", "French"], "reliability": "high"},}DEFAULT_SOURCES = ["cinesu", "vixsrc", "popr"]# ===== Helper: Run scrapers =====async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: int = None, source_keys: list = None):info = await get_tmdb_info(tmdb_id, media_type)title = info.get("title")imdb_id = info.get("imdb_id")all_results = []all_errors = []4 unmodified linesif not src:return [], [f"{key}: Unknown source"]try:r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=30)return r, eexcept asyncio.TimeoutError:return [], [f"{src['name']}: Timeout (30s)"]except Exception as ex:return [], [f"{src['name']}: {str(ex)}"]tasks = [run_one(k) for k in keys]task_results = await asyncio.gather(*tasks, return_exceptions=True)9 unmodified linesreturn {"success": len(all_results) > 0,"tmdb_id": tmdb_id,"imdb_id": imdb_id,"title": title,"year": info.get("year"),"results": all_results,"errors": all_errors if all_errors else None,}# ===== Root: JSON documentation =====@app.get("/")async def root():return {"api": "StreamForge","version": "4.0.0","description": "Multi-language m3u8 stream scraper","endpoints": {"movie": {"all_sources": "/movie/{tmdb_id}","single_source": "/movie/{tmdb_id}/{source}","example": "/movie/912649","example_source": "/movie/912649/popr",},"tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}","single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}","example": "/tv/1396/1/1","example_source": "/tv/1396/1/1/cinesu",},"search": {"path": "/search/{query}","example": "/search/Venom",},"api_endpoints": {"health": "GET /api/health","sources": "GET /api/sources","search": "GET /api/search?q={query}","scrape": "POST /api/scrape","scrape_all": "POST /api/scrape/all",},},"sources": {key: {"name": src["name"], "languages": src["languages"], "reliability": src["reliability"]}for key, src in SOURCE_MAP.items()},"default_sources": DEFAULT_SOURCES,"tips": ["No source = all default sources (cinesu, vixsrc, popr)","Best for Hindi: /movie/ID/popr","Best for English: /movie/ID/cinesu","Best for French: /movie/ID/vidnest","Best for Italian: /movie/ID/vixsrc","m3u8 links work in VLC, mpv, or any HLS player",],}# ===== Simple GET endpoints =====@app.get("/movie/{tmdb_id}")async def movie_all(tmdb_id: int):return await run_scrape(tmdb_id, "movie")@app.get("/movie/{tmdb_id}/{source}")async def movie_source(tmdb_id: int, source: str):source = source.lower()if source not in SOURCE_MAP:raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})return await run_scrape(tmdb_id, "movie", source_keys=[source])@app.get("/tv/{tmdb_id}/{season}/{episode}")async def tv_all(tmdb_id: int, season: int, episode: int):return await run_scrape(tmdb_id, "tv", season=season, episode=episode)@app.get("/tv/{tmdb_id}/{season}/{episode}/{source}")async def tv_source(tmdb_id: int, season: int, episode: int, source: str):source = source.lower()if source not in SOURCE_MAP:raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})return await run_scrape(tmdb_id, "tv", season=season, episode=episode, source_keys=[source])@app.get("/search/{query}")async def search_simple(query: str, page: int = 1):5 unmodified linesdata = resp.json()filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]results = []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]results.append({"id": mid,"type": "TV" if mt == "tv" else "Movie","title": t,"year": year,"url": f"/{mt}/{mid}" if mt == "movie" else f"/tv/{mid}/1/1",})return {"query": query,"count": len(results),"results": results,}# ===== JSON API endpoints =====@app.get("/api/health")async def health():2 unmodified lines@app.get("/api/sources")async def list_sources():return {"sources": {key: {"name": src["name"], "languages": src["languages"], "reliability": src["reliability"]}for key, src in SOURCE_MAP.items()},"default": DEFAULT_SOURCES,}@app.get("/api/search")14 unmodified lines@app.post("/api/scrape")async def scrape(request: ScrapeRequest):source_keys = Noneif request.sources:source_keys = [s.lower() for s in request.sources]1 unmodified line@app.post("/api/scrape/all")async def scrape_all(request: ScrapeRequest):return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, list(SOURCE_MAP.keys()))
main.py+202-496