iptv/M3U8/scrapers/strmd.py

261 lines
6.6 KiB
Python
Raw Normal View History

2025-11-06 19:15:48 -05:00
import asyncio
2025-10-11 13:59:24 -04:00
import re
from functools import partial
from typing import Any
from urllib.parse import urljoin
import httpx
2025-11-06 19:15:48 -05:00
from playwright.async_api import BrowserContext, async_playwright
2025-10-11 13:59:24 -04:00
from .utils import Cache, Time, get_logger, leagues, network
log = get_logger(__name__)
urls: dict[str, dict[str, str | float]] = {}
2025-11-13 12:43:55 -05:00
CACHE_FILE = Cache("strmd.json", exp=10_800)
2025-10-11 13:59:24 -04:00
2025-11-13 12:43:55 -05:00
API_FILE = Cache("strmd-api.json", exp=28_800)
2025-10-11 13:59:24 -04:00
MIRRORS = ["https://streamed.pk", "https://streami.su", "https://streamed.st"]
2025-11-15 02:05:52 -05:00
def fix_sport(s: str) -> str:
2025-10-11 13:59:24 -04:00
if "-" in s:
return " ".join(i.capitalize() for i in s.split("-"))
elif s == "fight":
return "Fight (UFC/Boxing)"
2025-10-17 21:01:05 -04:00
return s.capitalize() if len(s) >= 4 else s.upper()
2025-10-11 13:59:24 -04:00
async def refresh_api_cache(
client: httpx.AsyncClient, url: str
) -> list[dict[str, Any]]:
log.info("Refreshing API cache")
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-11-13 12:43:55 -05:00
2025-10-11 13:59:24 -04:00
return {}
data = r.json()
2025-10-15 10:53:54 -04:00
data[-1]["timestamp"] = Time.now().timestamp()
2025-10-11 13:59:24 -04:00
return data
2025-11-06 19:15:48 -05:00
async def process_event(
url: str,
url_num: int,
context: BrowserContext,
timeout: int | float = 10,
) -> str | None:
page = await context.new_page()
captured: list[str] = []
got_one = asyncio.Event()
handler = partial(
network.capture_req,
captured=captured,
got_one=got_one,
)
page.on("request", handler)
try:
await page.goto(
url,
wait_until="domcontentloaded",
timeout=15_000,
)
wait_task = asyncio.create_task(got_one.wait())
try:
await page.click(".jw-icon-display")
await asyncio.wait_for(wait_task, timeout=timeout)
except asyncio.TimeoutError:
log.warning(f"URL {url_num}) Timed out waiting for M3U8.")
return
finally:
if not wait_task.done():
wait_task.cancel()
try:
await wait_task
except asyncio.CancelledError:
pass
if captured:
log.info(f"URL {url_num}) Captured M3U8")
return captured[0]
log.warning(f"URL {url_num}) No M3U8 captured after waiting.")
return
except Exception as e:
log.warning(f"URL {url_num}) Exception while processing: {e}")
return
finally:
page.remove_listener("request", handler)
await page.close()
2025-10-11 13:59:24 -04:00
async def get_events(
client: httpx.AsyncClient,
base_url: str,
cached_keys: set[str],
) -> list[dict[str, str]]:
2025-10-11 18:43:57 -04:00
2025-10-15 10:53:54 -04:00
if not (api_data := API_FILE.load(per_entry=False, index=-1)):
2025-10-11 13:59:24 -04:00
api_data = await refresh_api_cache(
client,
urljoin(
base_url,
"api/matches/all-today",
),
)
API_FILE.write(api_data)
2025-11-13 12:43:55 -05:00
events = []
2025-10-11 13:59:24 -04:00
now = Time.clean(Time.now())
start_dt = now.delta(minutes=-30)
end_dt = now.delta(minutes=30)
pattern = re.compile(r"[\n\r]+|\s{2,}")
for event in api_data:
2025-11-15 02:05:52 -05:00
if (category := event.get("category")) == "other":
2025-10-11 13:59:24 -04:00
continue
if not (ts := event["date"]):
continue
start_ts = int(str(ts)[:-3])
event_dt = Time.from_ts(start_ts)
if not start_dt <= event_dt <= end_dt:
continue
2025-11-15 02:05:52 -05:00
sport = fix_sport(category)
2025-10-11 13:59:24 -04:00
parts = pattern.split(event["title"].strip())
name = " | ".join(p.strip() for p in parts if p.strip())
logo = urljoin(base_url, poster) if (poster := event.get("poster")) else None
key = f"[{sport}] {name} (STRMD)"
if cached_keys & {key}:
continue
sources: list[dict[str, str]] = event["sources"]
if not sources:
continue
2025-10-19 11:38:06 -04:00
source = sources[1] if len(sources) > 1 else sources[0]
2025-10-11 13:59:24 -04:00
source_type = source.get("source")
stream_id = source.get("id")
if not (source_type and stream_id):
continue
events.append(
{
"sport": sport,
"event": name,
"link": f"https://embedsports.top/embed/{source_type}/{stream_id}/1",
"logo": logo,
"timestamp": event_dt.timestamp(),
}
)
return events
async def scrape(client: httpx.AsyncClient) -> None:
cached_urls = CACHE_FILE.load()
cached_count = len(cached_urls)
urls.update(cached_urls)
log.info(f"Loaded {cached_count} event(s) from cache")
if not (base_url := await network.get_base(MIRRORS)):
2025-11-15 02:05:52 -05:00
log.warning("No working STRMD mirrors")
2025-10-11 13:59:24 -04:00
CACHE_FILE.write(cached_urls)
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-29 03:21:18 -04:00
if events:
async with async_playwright() as p:
2025-10-30 19:54:06 -04:00
browser, context = await network.browser(p, browser="brave")
2025-10-29 03:21:18 -04:00
for i, ev in enumerate(events, start=1):
handler = partial(
2025-11-06 19:15:48 -05:00
process_event,
2025-10-29 03:21:18 -04:00
url=ev["link"],
url_num=i,
context=context,
)
2025-10-11 13:59:24 -04:00
2025-10-29 03:21:18 -04:00
url = await network.safe_process(
handler,
url_num=i,
log=log,
2025-10-11 13:59:24 -04:00
)
2025-10-29 03:21:18 -04:00
if url:
sport, event, logo, ts = (
ev["sport"],
ev["event"],
ev["logo"],
ev["timestamp"],
)
key = f"[{sport}] {event} (STRMD)"
2025-10-11 13:59:24 -04:00
2025-10-29 03:21:18 -04:00
tvg_id, pic = leagues.get_tvg_info(sport, event)
2025-10-11 13:59:24 -04:00
2025-10-29 03:21:18 -04:00
entry = {
"url": url,
"logo": logo or pic,
"base": "https://embedsports.top/",
"timestamp": ts,
"id": tvg_id or "Live.Event.us",
}
2025-10-11 13:59:24 -04:00
2025-10-29 03:21:18 -04:00
urls[key] = cached_urls[key] = entry
2025-10-11 13:59:24 -04:00
2025-10-29 03:21:18 -04:00
await browser.close()
2025-10-11 13:59:24 -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")
CACHE_FILE.write(cached_urls)