Spaces:
Sleeping
Sleeping
File size: 23,225 Bytes
ff68a11 969a9cd ff68a11 969a9cd ff68a11 969a9cd ff68a11 969a9cd ff68a11 969a9cd ff68a11 7738bb0 969a9cd fc70423 7738bb0 ff68a11 7738bb0 ff68a11 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | """
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",
}
}
|