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 files12342345679891011121516131419151617232418192021229 unmodified lines3233344035363738394041423 unmodified lines46474853545556575859604950518 unmodified lines606162757677636465666768697 unmodified lines777879949580978182831001018485868721 unmodified lines1091101111291121131144 unmodified lines1191201211401411421431441451461471221231241251261271281291301491311321521531541551561571581591331341351361371381391401411421434 unmodified lines1481491501701711721511521531541 unmodified line1561571581801591601611622 unmodified lines1651661671891901681691701711 unmodified line17317417519817617717817920318018120518218318418511 unmodified lines1971981992232242002012022272282292302312322332342352362372382392402412422432442452462472482492502512522532542552032042052062072082092102112122132142152162172182192202572582592602612622632642652662672212222232242252262272282292302312322712332342352742752362372382772392402413 unmodified lines2452462472872482492502902512522922532542552562576 unmodified lines2642652663053063073083093103113122672682692702712722732742752763143153163173183193203212772782792802812822832842853233243253263273283293302862872882892902912922932942952962974 unmodified lines30230330434130530630730816 unmodified lines32532632732832933033133236833333433546 unmodified lines38238338442138538642442542642742842943043138738838939039139239339439539639739839940043840140240312 unmodified lines41641741845741942042142228 unmodified lines45145245349245445549549649749849950050150245645745845946046146246346446546646746846950947047147210 unmodified lines4834844855265274864874884894903 unmodified lines4944954965375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067074974984997117127137147155005015025035045055065075085097185105115127215135145157245167265175185195205214 unmodified lines5265275287387397407417427437447455295305317485325337505345355365379 unmodified lines5475485497665507687695515525535545555565577737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158165585595605618208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888895625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066078928938948958966086096106118996126136149029039049059066156166176189099109119129136196206216229166236246259199209219229236266276286296305 unmodified lines6366376389359366396406416426436449429439449456456466476486496506516526536546556566576586599486606616626632 unmodified lines66666766895795895996096196296366967067167267367414 unmodified lines6896906919846926936941 unmodified line696697698992699700701"""StreamForge API v3 - Multi-Language Stream ScraperBased on CloudStream extensions + CinePro core providersScrapes direct m3u8 URLs via API endpoints (no browser automation needed)StreamForge API v4 - Multi-Language Stream ScraperScrapes direct m3u8 URLs from multiple sources"""
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 BeautifulSoup
app = FastAPI( title="StreamForge API", description="Multi-language stream scraper - Hindi, Tamil, Telugu, English, Italian, French & more", version="3.0.0", description="Multi-language m3u8 stream scraper", version="4.0.0",)
app.add_middleware(9 unmodified lines
HEADERS = { "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": "application/json, text/html, */*", "Accept-Language": "en-US,en;q=0.5",}
# ===== Models =====
class ScrapeRequest(BaseModel):3 unmodified lines episode: Optional[int] = None sources: Optional[list[str]] = None
class StreamResult(BaseModel): source: str title: str quality: str language: str url: str type: str
# ===== Helpers =====
8 unmodified lines return { "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 lines if "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 return "English"
# ===== CineSu Scraper (Direct m3u8 API - English, some multi-language) =====# Flow: Construct URL → HEAD verify → return m3u8# ===== CineSu Scraper =====
async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = []21 unmodified lines errors.append(f"CineSu: HTTP {resp.status_code}") return results, errors
# Parse M3U8 playlist content = resp.text if "#EXT-X-STREAM-INF" in content: lines = content.split("\n")4 unmodified lines quality = resolution.group(1) if resolution else "Auto" label = name.group(1) if name else quality if 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", )) results.append({ "source": "CineSu", "title": label, "quality": quality, "language": "English", "url": lines[i + 1].strip(), "type": "m3u8", }) elif ".m3u8" in content: # Direct m3u8 URL m3u8_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", )) 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 lines return 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 immediately# ===== 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 line
try: async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: # Step 1: Get embed path (contains short-lived token) # Step 1: Get embed path if media_type == "movie": api_url = f"https://vixsrc.to/api/movie/{tmdb_id}" else:2 unmodified lines api_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 line return results, errors
src_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) # Step 2: Fetch embed HTML embed_resp = await client.get(f"https://vixsrc.to{src_path}")
if embed_resp.status_code == 410: # Token expired, retry once api_resp2 = await client.get(api_url)11 unmodified lines
html = embed_resp.text
# Step 3: Extract token, expires, playlist URL # Try multiple regex patterns since the HTML format can vary # Step 3: Extract from window.masterPlaylist token = None expires = None playlist = None
# Pattern 1: key:"value" format token_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 format if 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 tag playlist_url = None
mp_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 patterns if 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: pass
if not (token and playlist): 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 # Step 4: Build master URL and fetch if not expires: expires = str(int(time.time()) + 86400) sep = "&" if "?" in playlist else "?" master_url = f"{playlist}{sep}token={token}&expires={expires}&h=1" sep = "&" if "?" in playlist_url else "?" master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1"
# Step 5: Fetch master playlist pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"}) pl_content = pl_resp.text
3 unmodified lines lines = 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) lang_match = re.search(r'LANGUAGE="([^"]+)"', line) uri_match = re.search(r'URI="([^"]+)"', line) if lang_match and uri_match: if name_match and uri_match: audio_tracks.append({ "language": name_match.group(1) if name_match else lang_match.group(1), "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 lines video_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", )) 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(StreamResult( source="VixSrc", title="English Stream", quality=quality, language="English", url=video_url, type="m3u8", )) results.append({ "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", )) # Return master URL as-is if we can't parse results.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 lines return results, errors
# ===== VidNest Scraper (Custom base64 - Multi-language including French) =====# ===== VidNest Scraper =====
VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="
16 unmodified lines result.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 languages servers = { "purstream": "French", "klikxxi": "English",46 unmodified lines source_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 server lang = detect_language(source_name) if source_name else language
server_results.append(StreamResult( source=f"VidNest/{server_name}", title=source_name or title, quality=quality, language=lang, url=stream_url, type=stream_type, )) server_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, None
# Fetch all servers in parallel tasks = [fetch_server(name, lang) for name, lang in servers.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
12 unmodified lines return results, errors
# ===== Popr Scraper (Aggregator API - Multi-language including Hindi) =====# ===== Popr Scraper (Improved dedup) =====
async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = []28 unmodified lines is_m3u8 = stream.get("isM3U8", False) stream_type = "m3u8" if is_m3u8 else "direct"
# Detect language from quality label lang = detect_language(quality)
server_results.append(StreamResult( source=f"Popr/{server}", title=quality, quality=quality, language=lang, url=stream_url, type=stream_type, )) 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, None
# Fetch servers in parallel tasks = [fetch_server(s) for s in servers] task_results = await asyncio.gather(*tasks, return_exceptions=True)
10 unmodified lines seen_urls = set() unique_results = [] for r in results: if r.url not in seen_urls: seen_urls.add(r.url) if r["url"] not in seen_urls: seen_urls.add(r["url"]) unique_results.append(r) results = unique_results
3 unmodified lines return 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 domain try: resp = await client.get("https://allmovieland.one/") html = resp.text domains = 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 PHPSESSID resp0 = await client.get("https://allmovieland.one/") aml_sessid = "" for name, value in resp0.cookies.items(): if name == "PHPSESSID": aml_sessid = value break
if not aml_sessid: errors.append("AllMovieLand: Could not get session") return results, errors
# Find working player domain and get embed player_domain = None embed_html = None for 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 = domain embed_html = resp.text break except: continue
if not player_domain or not embed_html: errors.append("AllMovieLand: Could not load player page") return results, errors
embed_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 token resp1 = await client.get( f"https://{player_domain}/play/{imdb_id}", headers={"Referer": "https://allmovieland.one/"}, ) html = resp1.text match = 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: continue
try: 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 headers resp2 = 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, retry
playlist = json.loads(content)
# Get m3u8 for each language for 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"): continue
if 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 retrying
except: continue
if 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}, "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", "allmovieland"]DEFAULT_SOURCES = ["cinesu", "vixsrc", "popr"]
# ===== Helper: Run scrapers and return results =====# ===== Helper: Run scrapers =====
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") imdb_id = info.get("imdb_id")
all_results = [] all_errors = []4 unmodified lines 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) r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=30) return r, e except asyncio.TimeoutError: return [], [f"{src.get('name', key)}: Timeout (30s)"] return [], [f"{src['name']}: Timeout (30s)"] except Exception as ex: return [], [f"{src.get('name', key)}: {str(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 lines 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, "title": title, "year": info.get("year"), "results": all_results, "errors": all_errors if all_errors else None, }
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 = src lang = 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 =====# ===== Root: JSON documentation =====
@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) ===== 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, json: Optional[str] = Query(None)): data = await run_scrape(tmdb_id, "movie") if json is not None: return data return HTMLResponse(content=results_to_html(data))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, json: Optional[str] = Query(None)):async def movie_source(tmdb_id: int, source: str): 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 data return HTMLResponse(content=results_to_html(data)) 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, json: Optional[str] = Query(None)): data = await run_scrape(tmdb_id, "tv", season=season, episode=episode) if json is not None: return data return HTMLResponse(content=results_to_html(data))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, json: Optional[str] = Query(None)):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, 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 data return HTMLResponse(content=results_to_html(data)) 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 lines 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") 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] 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)) 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 (for apps/scripts) =====# ===== JSON API endpoints =====
@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"}, ] "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): # Normalize source names to lowercase keys source_keys = None if 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()))
main.py+202-496