iptv/M3U8/scrapers/streameast.py

219 lines
5.9 KiB
Python
Raw Normal View History

2025-09-11 14:55:53 -04:00
import asyncio
from functools import partial
from pathlib import Path
from urllib.parse import urljoin
import httpx
2025-10-09 20:18:37 -04:00
from playwright.async_api import BrowserContext, async_playwright
2025-09-11 14:55:53 -04:00
from selectolax.parser import HTMLParser
2025-10-01 11:57:49 -04:00
from .utils import Cache, Time, get_logger, leagues, network
2025-09-11 14:55:53 -04:00
log = get_logger(__name__)
urls: dict[str, dict[str, str | float]] = {}
2025-10-01 11:57:49 -04:00
CACHE_FILE = Cache(Path(__file__).parent / "caches" / "streameast.json", exp=10_800)
2025-09-11 14:55:53 -04:00
MIRRORS = [
2025-10-15 19:00:56 -04:00
"https://streameast.sg",
2025-09-11 14:55:53 -04:00
"https://streameast.ga",
"https://streameast.tw",
"https://streameast.ph",
"https://streameast.ch",
"https://streameast.ec",
"https://streameast.fi",
"https://streameast.ms",
"https://streameast.ps",
"https://streameast.cf",
"https://streameast.sk",
"https://thestreameast.co",
"https://thestreameast.fun",
"https://thestreameast.ru",
"https://thestreameast.su",
]
2025-10-09 20:18:37 -04:00
async def process_event(
url: str,
url_num: int,
context: BrowserContext,
) -> str | None:
page = await context.new_page()
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
captured: list[str] = []
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
got_one = asyncio.Event()
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
handler = partial(network.capture_req, captured=captured, got_one=got_one)
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
page.on("request", handler)
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
try:
await page.goto(url, wait_until="domcontentloaded", timeout=15_000)
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
wait_task = asyncio.create_task(got_one.wait())
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
try:
await asyncio.wait_for(wait_task, timeout=10)
except asyncio.TimeoutError:
log.warning(f"URL {url_num}) Timed out waiting for M3U8.")
return
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
finally:
if not wait_task.done():
wait_task.cancel()
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
try:
await wait_task
except asyncio.CancelledError:
pass
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
if captured:
log.info(f"URL {url_num}) Captured M3U8")
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
return captured[-1]
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
log.warning(f"URL {url_num}) No M3U8 captured after waiting.")
return
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
except Exception as e:
log.warning(f"URL {url_num}) Exception while processing: {e}")
return
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
finally:
page.remove_listener("request", handler)
await page.close()
2025-09-11 14:55:53 -04:00
async def get_events(
client: httpx.AsyncClient,
url: str,
2025-09-13 04:42:55 -04:00
cached_keys: set[str],
2025-09-11 14:55:53 -04:00
) -> list[dict[str, str]]:
try:
r = await client.get(url)
r.raise_for_status()
except Exception as e:
2025-10-15 10:53:54 -04:00
log.error(f'Failed to fetch "{url}": {e}')
2025-09-11 14:55:53 -04:00
return []
soup = HTMLParser(r.text)
events = []
2025-10-02 12:57:25 -04:00
now = Time.clean(Time.now())
2025-10-01 11:57:49 -04:00
start_dt = now.delta(minutes=-30)
end_dt = now.delta(minutes=30)
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
for section in soup.css("div.se-sport-section"):
if not (sport := section.attributes.get("data-sport-name", "").strip()):
2025-09-11 14:55:53 -04:00
continue
2025-09-28 11:28:28 -04:00
for a in section.css("a.uefa-card"):
2025-10-13 13:36:09 -04:00
if not (href := a.attributes.get("href")):
continue
link = urljoin(url, href)
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
team_spans = [t.text(strip=True) for t in a.css("span.uefa-name")]
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
if len(team_spans) == 2:
name = f"{team_spans[0]} vs {team_spans[1]}"
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
elif len(team_spans) == 1:
name = team_spans[0]
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
else:
continue
2025-09-11 14:55:53 -04:00
2025-09-28 11:28:28 -04:00
if not (time_span := a.css_first(".uefa-time")):
continue
time_text = time_span.text(strip=True)
2025-09-29 13:42:51 -04:00
2025-10-15 10:53:54 -04:00
timestamp = int(a.attributes.get("data-time", Time.default_8()))
2025-09-28 11:28:28 -04:00
key = f"[{sport}] {name} (SEAST)"
if cached_keys & {key}:
continue
2025-09-11 14:55:53 -04:00
2025-10-01 11:57:49 -04:00
event_dt = Time.from_ts(timestamp)
2025-09-11 14:55:53 -04:00
2025-10-04 15:17:00 -04:00
if time_text == "LIVE" or (start_dt <= event_dt <= end_dt):
2025-09-28 11:28:28 -04:00
events.append(
{
"sport": sport,
"event": name,
2025-10-13 13:36:09 -04:00
"link": link,
2025-10-01 11:57:49 -04:00
"timestamp": timestamp,
2025-09-28 11:28:28 -04:00
}
)
2025-09-11 14:55:53 -04:00
return events
2025-09-20 23:26:18 -04:00
async def scrape(client: httpx.AsyncClient) -> None:
2025-10-01 11:57:49 -04:00
cached_urls = CACHE_FILE.load()
2025-09-11 14:55:53 -04:00
cached_count = len(cached_urls)
urls.update(cached_urls)
2025-10-01 11:57:49 -04:00
log.info(f"Loaded {cached_count} event(s) from cache")
2025-09-11 14:55:53 -04:00
2025-10-01 11:57:49 -04:00
if not (base_url := await network.get_base(MIRRORS)):
2025-09-11 14:55:53 -04:00
log.warning("No working StreamEast mirrors")
2025-10-01 11:57:49 -04:00
CACHE_FILE.write(cached_urls)
2025-09-11 14:55:53 -04:00
return
log.info(f'Scraping from "{base_url}"')
events = await get_events(
client,
base_url,
set(cached_urls.keys()),
)
log.info(f"Processing {len(events)} new URL(s)")
2025-10-09 20:18:37 -04:00
async with async_playwright() as p:
browser, context = await network.browser(p, browser="brave")
for i, ev in enumerate(events, start=1):
2025-10-15 10:53:54 -04:00
handler = partial(process_event, url=ev["link"], url_num=i, context=context)
url = await network.safe_process(handler, url_num=i, log=log)
2025-10-09 20:18:37 -04:00
if url:
sport, event, ts = ev["sport"], ev["event"], ev["timestamp"]
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
tvg_id, logo = leagues.info(sport)
2025-09-19 02:05:40 -04:00
2025-10-09 20:18:37 -04:00
if sport == "NBA" and leagues.is_valid(event, "WNBA"):
sport = "WNBA"
tvg_id, logo = leagues.info("WNBA")
2025-09-24 12:30:55 -04:00
2025-10-09 20:18:37 -04:00
key = f"[{sport}] {event} (SEAST)"
2025-09-13 04:42:55 -04:00
2025-10-09 20:18:37 -04:00
entry = {
"url": url,
"logo": logo,
"base": "https://embedsports.top/",
"timestamp": ts,
"id": tvg_id or "Live.Event.us",
}
2025-09-21 10:28:15 -04:00
2025-10-09 20:18:37 -04:00
urls[key] = cached_urls[key] = entry
2025-09-11 14:55:53 -04:00
2025-10-09 20:18:37 -04:00
await browser.close()
2025-09-11 14:55:53 -04:00
if new_count := len(cached_urls) - cached_count:
log.info(f"Collected and cached {new_count} new event(s)")
else:
log.info("No new events found")
2025-10-01 11:57:49 -04:00
CACHE_FILE.write(cached_urls)
2025-10-10 17:14:32 -04:00
# cloudflare bot protection added