""" StreamForge API v13 - Multi-Language Stream Scraper v13 (netmirror+castle rebuild, Nuvio port): - NetMirror REBUILT from All-in-One-Nuvio netmirror.js: the bcdnxw CDN 429s are REFERER-gating, not IP-blocking - the CDN requires Referer "https://videodownloader.site/" (net27.cc referers get 429 from any IP). With it, direct playback AND the Space proxy both return 206 video/mp4 (360p-1080p verified). Movie subtitles proxied (real SRT). NewTV platform fallback is dead upstream - not ported. - Castle REBUILT from All-in-One-Nuvio castle.js: v2.0.1 getVideo2 flow with correct seasons[] "movieId" traversal (fixes WRONG-EPISODE bug), correct movieType matching (2=Movies/1=TV), per-language tracks (Tamil/OST/English) + TV shared-stream fallback, VTT subtitles. img*.com CDNs serve TS segments disguised as image/jpeg - intentional upstream obfuscation, plays fine. - Tested & dead (NOT integrated): vidlink, vidfast, vidsrc.me, kurage, vixsrc, goated, 1shows, showbox, allmovieland, moviebox, vidrock, Nuvio NewTV. - NOT added per policy: Cineby (dead), Videasy (Cineby property - absent). - Vyla (docs.vyla.cc): private GitLab repo + no public hosted API - cannot be self-hosted without repo access (documented, not integrated). - All 6 default sources verified playable end-to-end (m3u8 playlist + segment fetch + real TS/MP4 bytes) from a datacenter IP. v12 (client-playability release): - FIXED: all proxy URLs are now ABSOLUTE (https://space/proxy_range?u=...) - the v11 relative (/proxy_range?...) URLs broke players that don't know the API base (this is why NetMirror/MOON "loaded but wouldn't play") - Proxy engine v2: Range passthrough on BOTH /proxy and /proxy_range, HEAD support, Origin header injection, content-sniffed m3u8 detection, and m3u8 playlists whose every key/variant/segment URI is rewritten to ABSOLUTE proxy URLs (any player works) - PlayBox: m3u8 served through the proxy with Referer+Origin+UA injected - its gateway intermittently gates direct client fetches with a JSON error page (red tests) - Movies4u: every candidate m3u8 is validated at scrape time (acek-cdn sometimes serves PNG block pages / dead tokens) - only verified playlists are returned - Every stream now carries an absolute proxied_url fallback; Castle/Movix direct URLs unchanged (verified playable) - PersianStremio: MKV hosts confirmed Range-capable (206) - direct links kept - NetMirror: bcdnxw CDN 429-blocks ALL datacenter IPs (HF included) - primary stays the direct mp4 + Referer/UA headers (device-IP playback, like the Nuvio app); absolute proxied_url kept as fallback """ from fastapi import FastAPI, HTTPException, Query, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse, Response, JSONResponse from pydantic import BaseModel from typing import Optional import httpx import json import re import base64 import time import asyncio import contextvars import hashlib import html as ihtml from urllib.parse import quote, urljoin, urlparse app = FastAPI( title="StreamForge API", description="Multi-language m3u8/mp4/MKV stream scraper", version="13.0.0", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973" TMDB_BASE = "https://api.themoviedb.org/3" 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, text/html, */*", "Accept-Language": "en-US,en;q=0.5", } # ===== Models ===== class ScrapeRequest(BaseModel): tmdb_id: int media_type: str = "movie" season: Optional[int] = None episode: Optional[int] = None sources: Optional[list[str]] = None # ===== Helpers ===== async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict: async with httpx.AsyncClient(timeout=10) as client: type_path = "tv" if media_type == "tv" else "movie" resp = await client.get( f"{TMDB_BASE}/{type_path}/{tmdb_id}", params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"} ) data = resp.json() return { "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" if "tamil" in lower or "tam" in lower: return "Tamil" if "telugu" in lower or "tel" in lower: return "Telugu" if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali" if "malayalam" in lower or "mal" in lower: return "Malayalam" if "kannada" in lower or "kan" in lower: return "Kannada" if "english" in lower or "eng" in lower or "en" == lower: return "English" if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian" 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 "persian" in lower or "farsi" in lower: return "Persian" if "multi" in lower or "dual" in lower: return "Multi" return "English" def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: int = 16): dtot = b"" d = b"" while len(dtot) < key_len + iv_len: d = hashlib.md5(d + password + salt).digest() dtot += d return dtot[:key_len], dtot[key_len:key_len + iv_len] def normalize_title(title: str) -> str: cleaned = re.sub(r'\[[^\]]*\]', '', title) cleaned = re.sub(r'\((?:Dub|HD|Cam|TS|HDRip|BRRip|DVDRip|WEBRip|WEB-DL)\)', '', cleaned, flags=re.IGNORECASE) cleaned = re.sub(r'\s+', ' ', cleaned).strip() return cleaned def extract_language_from_title(title: str) -> str: bracket_match = re.search(r'\[([^\]]+)\]', title) if bracket_match: lang_text = bracket_match.group(1) detected = detect_language(lang_text) if detected != "English" or lang_text.lower() == "english": return detected return "" _SF_CTRL_ENC = re.compile(r'%(0[0-9a-f]|1[0-9a-f]|7f)', re.IGNORECASE) def _sf_url_has_ctrl(u: str) -> bool: """Detect literal or percent-encoded control characters in a URL.""" if not u: return True if re.search(r'[\x00-\x1f\x7f]', u): return True return bool(_SF_CTRL_ENC.search(u)) def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English", headers: dict = None, subtitles: list = None, direct_url: str = None, proxied_url: str = None) -> dict: # strip control characters some APIs embed in URLs url = re.sub(r'[\x00-\x1f\x7f]', '', url or "") r = { "source": source, "title": title, "quality": quality, "language": detect_language(language) if language else "English", "url": url, "type": "m3u8" if ".m3u8" in url else "direct", } if headers: r["headers"] = headers if subtitles: r["subtitles"] = subtitles if direct_url: r["direct_url"] = direct_url if proxied_url: r["proxied_url"] = proxied_url return r def _sf_norm(s: str) -> str: return re.sub(r"[^a-z0-9]", "", (s or "").lower()) # ===== Proxy engine v2 ===== # Streams that need special headers (Referer/Origin/UA), are IP-bound, or lack CORS # cannot be played directly by clients. They flow through /proxy_range, which does: # * header injection (ref / origin / ua) # * Range passthrough (seek) + HEAD # * content-sniffed m3u8 detection; every key/variant/segment URI inside a playlist # is rewritten to an ABSOLUTE /proxy_range URL so any player (hls.js, ExoPlayer, # VLC, native