Spaces:
Sleeping

fireflix-api / app.py
EpicCoderGG's picture
Upload app.py with huggingface_hub
fc70423 verified
Raw History Blame Contribute Delete
23.2 kB
"""
FireFlix AllMovieLand API β€” Deployed on HuggingFace Spaces
Returns playable m3u8 URLs from AllMovieLand using TMDB/IMDB IDs.
"""
from fastapi import FastAPI, Query, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import httpx
import re
import json
import time
from typing import Optional
from 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.0
MOVIELAND_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.
Also discovers the href (CDN) domain which is used for playlist/m3u8 URLs."""
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 _get_embed_via_allorigins(client: httpx.AsyncClient, embed_url: str) -> tuple:
"""Try loading the embed page through allorigins proxy when direct access is blocked (e.g. on cloud hosts)."""
from urllib.parse import quote
proxy_url = f"https://api.allorigins.win/raw?url={quote(embed_url, safe='')}"
try:
r = await client.get(proxy_url, headers={"User-Agent": UA}, timeout=15.0)
if r.status_code == 200 and "let p3" in r.text:
return r.text, None
return None, f"proxy status {r.status_code}"
except Exception as e:
return None, f"proxy error: {str(e)[:50]}"
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 (try direct, then proxy fallback)
embed_url = f"{player_domain}/play/{imdb_id}"
r1 = await client.get(embed_url, headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"}, cookies=cookies)
embed_html = r1.text
if r1.status_code == 404 or r1.status_code == 403:
# Player domain blocked (common on cloud hosts) β€” try allorigins proxy
proxy_html, proxy_err = await _get_embed_via_allorigins(client, embed_url)
if proxy_html:
embed_html = proxy_html
else:
# Last resort: try the movie page on allmovieland directly
# to find an alternative player domain
new_domain = await _discover_player_domain(client)
if new_domain and new_domain != player_domain:
embed_url = f"{new_domain}/play/{imdb_id}"
r1b = await client.get(embed_url, headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"}, cookies=cookies)
if r1b.status_code == 200 and "let p3" in r1b.text:
embed_html = r1b.text
player_domain = new_domain
else:
return None, f"embed blocked (direct {r1.status_code}, proxy {proxy_err})"
else:
return None, f"embed blocked (status {r1.status_code}, proxy {proxy_err})"
if r1.status_code != 200 and "let p3" not in embed_html:
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>', embed_html, 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("/debug")
async def debug_connectivity():
"""Debug endpoint to check what HF can reach."""
results = {}
async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
# Test allmovieland homepage
try:
r = await client.get(f"{MOVIELAND_BASE}/", headers={"User-Agent": UA})
results["allmovieland_home"] = {"status": r.status_code, "len": len(r.text), "has_PHPSSESSID": "PHPSESSID" in str(r.cookies)}
except Exception as e:
results["allmovieland_home"] = {"error": str(e)[:80]}
# Test films page
try:
r = await client.get(f"{MOVIELAND_BASE}/films/", headers={"User-Agent": UA})
results["allmovieland_films"] = {"status": r.status_code, "len": len(r.text)}
except Exception as e:
results["allmovieland_films"] = {"error": str(e)[:80]}
# Discover player domain
player_domain = await _discover_player_domain(client)
results["player_domain"] = player_domain or "NOT FOUND"
# Test player domain embed directly
if player_domain:
try:
r = await client.get(f"{player_domain}/play/tt16366836", headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"})
results["embed_test"] = {"status": r.status_code, "len": len(r.text), "has_p3": "let p3" in r.text}
except Exception as e:
results["embed_test"] = {"error": str(e)[:80]}
# Test allorigins proxy for the embed
if r.status_code != 200 or "let p3" not in r.text:
proxy_html, proxy_err = await _get_embed_via_allorigins(client, f"{player_domain}/play/tt16366836")
results["allorigins_proxy"] = {"success": proxy_html is not None, "error": proxy_err, "has_p3": proxy_html and "let p3" in proxy_html if proxy_html else False}
# Test CDN/playlist domain
try:
r = await client.get("https://kayel415jek.com/", headers={"User-Agent": UA}, timeout=5.0)
results["cdn_kayel"] = {"status": r.status_code}
except Exception as e:
results["cdn_kayel"] = {"error": str(e)[:80]}
if not player_domain:
# Try hardcoded fallback
try:
r = await client.get("https://piexe411qok.com/play/tt16366836", headers={"User-Agent": UA, "Referer": f"{MOVIELAND_BASE}/"})
results["embed_fallback"] = {"status": r.status_code, "len": len(r.text), "has_p3": "let p3" in r.text}
except Exception as e:
results["embed_fallback"] = {"error": str(e)[:80]}
return results
@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)",
"/debug": "Check connectivity to AllMovieLand from this server",
}
}