Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506"""FireFlix AllMovieLand API β Deployed on HuggingFace SpacesReturns playable m3u8 URLs from AllMovieLand using TMDB/IMDB IDs."""
from fastapi import FastAPI, Query, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponseimport httpximport reimport jsonimport timefrom typing import Optionalfrom urllib.parse import quote, urlparse
app = FastAPI(title="FireFlix API", version="2.0.0")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"TIMEOUT = 15.0MOVIELAND_BASE = "https://allmovieland.one"TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973"
def _quality_label(height: int) -> str: if height >= 2160: return f"{height}p (4K)" if height >= 1440: return f"{height}p (2K)" if height >= 1080: return f"{height}p (FHD)" if height >= 720: return f"{height}p (HD)" if height >= 480: return f"{height}p (SD)" return f"{height}p"
# βββ TMDB lookup ββββββββββββββββββββββββββββββββββββββββββββββββββββasync def get_tmdb_info(tmdb_id: str, media_type: str): try: async with httpx.AsyncClient(timeout=8.0) as client: r = await client.get( f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}", params={"api_key": TMDB_API_KEY} ) if r.status_code == 200: data = r.json() return data.get("title") or data.get("name", ""), data.get("imdb_id", "") except: pass return "", ""
# βββ AllMovieLand βββββββββββββββββββββββββββββββββββββββββββββββββββasync def _discover_player_domain(client: httpx.AsyncClient) -> str: """Discover the current AllMovieLand player domain from a film page.""" try: r = await client.get(f"{MOVIELAND_BASE}/films/", headers={"User-Agent": UA}, timeout=8.0) if r.status_code == 200: film_match = re.search(r'href="(https?://allmovieland[^"]*\.html)"', r.text) if film_match: r2 = await client.get(film_match.group(1), headers={"User-Agent": UA}, timeout=8.0) if r2.status_code == 200: dm = re.search(r"AwsIndStreamDomain\s*=\s*'([^']+)'", r2.text) if dm: return dm.group(1).rstrip("/") except: pass try: r = await client.get(f"{MOVIELAND_BASE}/", headers={"User-Agent": UA}, timeout=8.0) dm = re.search(r"AwsIndStreamDomain\s*=\s*'([^']+)'", r.text) if dm: return dm.group(1).rstrip("/") except: pass return ""
async def _ml_single_attempt(client: httpx.AsyncClient, player_domain: str, imdb_id: str, media_type: str, season: Optional[str], episode: Optional[str], phpsessid: str): """Single attempt at scraping AllMovieLand. Returns (result_dict, error_str).""" cookies = {"PHPSESSID": phpsessid} if phpsessid else {}
# Step 1: Load embed page embed_url = f"{player_domain}/play/{imdb_id}" r1 = await client.get(embed_url, headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"}, cookies=cookies)
if r1.status_code == 404: player_domain = await _discover_player_domain(client) if not player_domain: return None, f"embed 404, no player domain found" embed_url = f"{player_domain}/play/{imdb_id}" r1 = await client.get(embed_url, headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"}, cookies=cookies)
if r1.status_code != 200: return None, f"embed status {r1.status_code}"
# Step 2: Parse config from last <script> tag (phisher's approach: first { to last }) scripts = re.findall(r'<script[^>]*>(.*?)</script>', r1.text, re.DOTALL) if not scripts: return None, "no script tags found"
last_script = scripts[-1] start = last_script.find('{') end = last_script.rfind('}') if start == -1 or end <= start: return None, "no JSON config found in script"
try: config = json.loads(last_script[start:end+1]) except json.JSONDecodeError as e: return None, f"JSON parse error: {str(e)[:50]}"
key = config.get('key', '') file_url = config.get('file', '') href = config.get('href', '')
if not key or not file_url: return None, f"missing key={bool(key)} or file={bool(file_url)}"
# Fix file URL if relative if not file_url.startswith('http'): file_url = f"https://{href}{file_url}" if href else f"{player_domain}{file_url}"
# Step 3: POST to file URL β CRITICAL: Referer must be the embed URL r2 = await client.post(file_url, headers={ "User-Agent": UA, "X-CSRF-TOKEN": key, "Referer": embed_url, }, cookies=cookies, timeout=12.0)
if r2.status_code != 200: return None, f"file POST status {r2.status_code}"
response_text = r2.text.strip()
# Error codes: 7 = CSRF expired, 11 = missing/wrong Referer if response_text in ('7', '11'): return None, f"CSRF error {response_text}"
# Parse languages try: cleaned = re.sub(r',\s*\[\]', '', response_text) items = json.loads(cleaned) except: return None, f"invalid JSON response: {response_text[:80]}"
if not isinstance(items, list): return None, f"unexpected response type: {type(items).__name__}"
# Step 4: Detect TV vs Movie structure is_tv_structure = False for item in items: if isinstance(item, dict) and item.get('folder') and isinstance(item['folder'], list): if item['folder'] and isinstance(item['folder'][0], dict) and item['folder'][0].get('episode'): is_tv_structure = True break
streams = [] m3u8_headers = {"Referer": f"https://{href}/", "Origin": f"https://{href}"}
if is_tv_structure: s_num = str(season or "1") e_num = str(episode or "1")
for season_item in items: if not isinstance(season_item, dict): continue s_id = str(season_item.get('id', '')) s_title = str(season_item.get('title', '')) if s_id != s_num and f"Season {s_num}" not in s_title and s_title != s_num: continue
for ep in season_item.get('folder', []): if not isinstance(ep, dict): continue ep_num = str(ep.get('episode', '')) if ep_num != e_num: continue
for lang_file in ep.get('folder', []): if not isinstance(lang_file, dict): continue file_id = lang_file.get('file', '') lang_title = lang_file.get('title', 'Unknown') if not file_id: continue
m3u8_url = await _ml_get_m3u8(client, player_domain, href, key, file_id, cookies) if m3u8_url: best_quality = await _ml_get_quality(client, m3u8_url, href) streams.append({ "url": m3u8_url, "headers": m3u8_headers, "quality": best_quality, "language": lang_title, }) break break
if not streams: for season_item in items: if not isinstance(season_item, dict) or not season_item.get('folder'): continue for ep in season_item['folder'][:1]: if not isinstance(ep, dict): continue for lang_file in ep.get('folder', []): if not isinstance(lang_file, dict): continue file_id = lang_file.get('file', '') lang_title = lang_file.get('title', 'Unknown') if file_id: m3u8_url = await _ml_get_m3u8(client, player_domain, href, key, file_id, cookies) if m3u8_url: best_quality = await _ml_get_quality(client, m3u8_url, href) streams.append({ "url": m3u8_url, "headers": m3u8_headers, "quality": best_quality, "language": lang_title, }) break break else: for item in items: if not isinstance(item, dict): continue lang_title = item.get('title', 'Unknown') file_id = item.get('file', '') if not file_id: continue
m3u8_url = await _ml_get_m3u8(client, player_domain, href, key, file_id, cookies) if m3u8_url: best_quality = await _ml_get_quality(client, m3u8_url, href) streams.append({ "url": m3u8_url, "headers": m3u8_headers, "quality": best_quality, "language": lang_title, })
if not streams: return None, "no playable streams found"
return { "server": "AllMovieLand", "serverId": "movieland", "status": "ok", "streams": streams, "subtitles": [], "responseTime": 0, }, None
async def _ml_get_m3u8(client: httpx.AsyncClient, player_domain: str, href: str, key: str, file_id: str, cookies: dict) -> str: try: playlist_url = f"https://{href}/playlist/{file_id}.txt" r = await client.post(playlist_url, headers={ "User-Agent": UA, "X-CSRF-TOKEN": key, "Referer": f"{MOVIELAND_BASE}/", }, cookies=cookies, timeout=8.0) if r.status_code != 200: return "" text = r.text.strip() if text.startswith('http'): return text.split('\n')[0].strip() if text.startswith('#EXTM3U'): return playlist_url return "" except: return ""
async def _ml_get_quality(client: httpx.AsyncClient, m3u8_url: str, href: str) -> str: try: r = await client.get(m3u8_url, headers={ "User-Agent": UA, "Referer": f"https://{href}/", }, timeout=5.0) if r.status_code == 200 and '#EXTM3U' in r.text[:100]: max_height = 0 for line in r.text.split("\n"): if line.strip().startswith("#EXT-X-STREAM-INF"): res_match = re.search(r'RESOLUTION=(\d+)x(\d+)', line) if res_match: height = int(res_match.group(2)) if height > max_height: max_height = height if max_height > 0: return _quality_label(max_height) except: pass return "HD"
async def scrape_movieland(imdb_id: str, media_type: str, season: Optional[str], episode: Optional[str]): start = time.time() last_error = ""
async with httpx.AsyncClient(timeout=TIMEOUT, follow_redirects=True) as client: player_domain = await _discover_player_domain(client) if not player_domain: return {"server": "AllMovieLand", "serverId": "movieland", "status": "error", "streams": [], "subtitles": [], "error": "could not discover player domain", "responseTime": int((time.time() - start) * 1000)}
for attempt in range(3): try: r0 = await client.get(f"{MOVIELAND_BASE}/", headers={"User-Agent": UA}, timeout=8.0) phpsessid = dict(r0.cookies).get('PHPSESSID', '') except Exception as e: last_error = f"allmovieland unreachable: {str(e)[:50]}" continue
result, err = await _ml_single_attempt( client, player_domain, imdb_id, media_type, season, episode, phpsessid )
if result: result["responseTime"] = int((time.time() - start) * 1000) return result
last_error = err or "unknown error"
return {"server": "AllMovieLand", "serverId": "movieland", "status": "error", "streams": [], "subtitles": [], "error": last_error, "responseTime": int((time.time() - start) * 1000)}
# βββ M3U8 Proxy βββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/proxy")async def proxy_stream( url: str = Query(..., description="M3U8 or segment URL to proxy"), origin: str = Query("", description="Origin header"), referer: str = Query("", description="Referer header"),): try: headers = {"User-Agent": UA, "Accept": "*/*"} if origin: headers["Origin"] = origin if referer: headers["Referer"] = referer
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client: r = await client.get(url, headers=headers)
if r.status_code != 200: return JSONResponse({"error": f"Upstream {r.status_code}"}, status_code=r.status_code)
content_type = r.headers.get("content-type", "") buf = r.content
is_playlist = "mpegurl" in content_type or b"#EXTM3U" in buf[:300] or b"#EXTINF" in buf[:300]
if is_playlist: text = buf.decode("utf-8", errors="replace") base_url = url.rsplit("/", 1)[0] + "/" rewritten = rewrite_m3u8(text, base_url, headers.get("Origin", origin), headers.get("Referer", referer)) return Response( content=rewritten, media_type="application/vnd.apple.mpegurl", headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "no-cache"}, )
out_buf = buf out_ct = "video/mp2t"
if _is_png_wrapped_ts(buf): ts_offset = _find_ts_start(buf) if ts_offset > 0: out_buf = buf[ts_offset:] elif len(buf) > 0 and buf[0] == 0x47: out_ct = "video/mp2t" else: out_ct = content_type or "application/octet-stream"
return Response( content=out_buf, media_type=out_ct, headers={"Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=3600"}, ) except Exception as e: return JSONResponse({"error": str(e)}, status_code=500)
def _is_png_wrapped_ts(buf: bytes) -> bool: if len(buf) < 16 or buf[:8] != b'\x89PNG\r\n\x1a\n': return False iend_pos = buf.find(b'IEND', 0, 500) if iend_pos < 0: return False after = iend_pos + 8 return after < len(buf) and buf[after] == 0x47
def _find_ts_start(buf: bytes) -> int: iend_pos = buf.find(b'IEND', 0, 500) if iend_pos < 0: return 0 after = iend_pos + 8 if after < len(buf) and buf[after] == 0x47: return after for i in range(iend_pos, min(len(buf), iend_pos + 50)): if buf[i] == 0x47: return i return 0
def rewrite_m3u8(content: str, base_url: str, origin: str, referer: str) -> str: lines = content.split("\n") result = [] for line in lines: stripped = line.strip() if not stripped: result.append(line) continue if stripped.startswith("#EXT"): if 'URI="' in stripped: def _replace_uri(m): uri = m.group(1) full = _resolve_url(uri, base_url) p = f'/proxy?url={quote(full, safe="")}&origin={quote(origin, safe="")}&referer={quote(referer, safe="")}' return f'URI="{p}"' line = re.sub(r'URI="([^"]+)"', _replace_uri, line) result.append(line) continue if stripped.startswith("#"): result.append(line) continue full = _resolve_url(stripped, base_url) p = f'/proxy?url={quote(full, safe="")}&origin={quote(origin, safe="")}&referer={quote(referer, safe="")}' result.append(p) return "\n".join(result)
def _resolve_url(uri: str, base_url: str) -> str: if uri.startswith("http://") or uri.startswith("https://"): return uri if uri.startswith("/"): parsed = urlparse(base_url) return f"{parsed.scheme}://{parsed.netloc}{uri}" return base_url + uri
# βββ Main Scrape Endpoint βββββββββββββββββββββββββββββββββββββββββββ@app.get("/scrape")async def scrape( id: str = Query(..., description="TMDB ID or IMDB ID (e.g. tt15398776)"), type: str = Query("movie", description="movie or tv"), season: Optional[str] = Query(None), episode: Optional[str] = Query(None),): start_time = time.time()
imdb_id_direct = "" if id.startswith("tt"): imdb_id_direct = id
title, imdb_id = await get_tmdb_info(id, type)
if not imdb_id and imdb_id_direct: imdb_id = imdb_id_direct
if not imdb_id: return { "success": False, "error": "No IMDB ID found. Provide a TMDB ID or a direct IMDB ID (tt...).", "tmdb_id": id, "type": type, "title": title, "imdb_id": "", "sources": [], "total_sources": 0, "working_sources": 0, "total_streams": 0, "responseTime": int((time.time() - start_time) * 1000), }
result = await scrape_movieland(imdb_id, type, season, episode)
sources = [result] working = 1 if result.get("status") == "ok" else 0 total_streams = len(result.get("streams", []))
return { "success": working > 0, "tmdb_id": id, "type": type, "title": title, "imdb_id": imdb_id, "sources": sources, "total_sources": 1, "working_sources": working, "total_streams": total_streams, "responseTime": int((time.time() - start_time) * 1000), }
@app.get("/")async def root(): return { "service": "FireFlix API", "version": "2.0.0", "endpoints": { "/scrape": "Get streaming links (params: id, type, season, episode)", "/proxy": "Proxy m3u8/segments (params: url, origin, referer)", } }app.pyAdded+506