iptv/M3U8/scrapers/streamsgate.py

192 lines
4.6 KiB
Python
Raw Normal View History

2025-12-08 13:21:43 -05:00
import asyncio
from functools import partial
from itertools import chain
from typing import Any
from urllib.parse import urljoin
from playwright.async_api import async_playwright
from .utils import Cache, Time, get_logger, leagues, network
log = get_logger(__name__)
urls: dict[str, dict[str, str | float]] = {}
2025-12-15 21:59:13 -05:00
TAG = "STRMSGATE"
2025-12-13 16:57:14 -05:00
2025-12-16 02:30:44 -05:00
CACHE_FILE = Cache(f"{TAG.lower()}.json", exp=10_800)
2025-12-08 13:21:43 -05:00
2025-12-16 02:30:44 -05:00
API_FILE = Cache(f"{TAG.lower()}-api.json", exp=28_800)
2025-12-08 13:21:43 -05:00
BASE_URL = "https://streamingon.org"
SPORT_ENDPOINTS = [
"soccer",
"nfl",
"nba",
"cfb",
"mlb",
"nhl",
"ufc",
"boxing",
"f1",
]
def get_event(t1: str, t2: str) -> str:
match t1:
case "RED ZONE":
return "NFL RedZone"
case "TBD":
return "TBD"
case _:
return f"{t1.strip()} vs {t2.strip()}"
2025-12-18 03:04:11 -05:00
async def refresh_api_cache(now_ts: float) -> list[dict[str, Any]]:
2025-12-08 13:21:43 -05:00
log.info("Refreshing API cache")
tasks = [
2025-12-18 03:04:11 -05:00
network.request(
urljoin(BASE_URL, f"data/{sport}.json"),
log=log,
)
2025-12-08 13:21:43 -05:00
for sport in SPORT_ENDPOINTS
]
results = await asyncio.gather(*tasks)
2025-12-18 12:51:16 -05:00
if not (data := [*chain.from_iterable(r.json() for r in results if r)]):
return [{"timestamp": now_ts}]
2025-12-08 13:21:43 -05:00
for ev in data:
ev["ts"] = ev.pop("timestamp")
2025-12-12 10:46:56 -05:00
data[-1]["timestamp"] = now_ts
2025-12-08 13:21:43 -05:00
return data
2025-12-18 03:04:11 -05:00
async def get_events(cached_keys: list[str]) -> list[dict[str, str]]:
2025-12-08 13:21:43 -05:00
now = Time.clean(Time.now())
if not (api_data := API_FILE.load(per_entry=False, index=-1)):
2025-12-18 03:04:11 -05:00
api_data = await refresh_api_cache(now.timestamp())
2025-12-08 13:21:43 -05:00
API_FILE.write(api_data)
events = []
2025-12-16 20:39:52 -05:00
start_dt = now.delta(hours=-1)
2025-12-16 14:27:05 -05:00
end_dt = now.delta(minutes=5)
2025-12-08 13:21:43 -05:00
for stream_group in api_data:
2025-12-22 17:08:41 -05:00
date = stream_group.get("time")
2025-12-08 13:21:43 -05:00
sport = stream_group.get("league")
t1, t2 = stream_group.get("away"), stream_group.get("home")
2025-12-18 03:04:11 -05:00
event = get_event(t1, t2)
2025-12-22 17:08:41 -05:00
if not (date and sport):
2025-12-18 03:04:11 -05:00
continue
2025-12-18 12:51:16 -05:00
if f"[{sport}] {event} ({TAG})" in cached_keys:
2025-12-18 03:04:11 -05:00
continue
2025-12-22 17:08:41 -05:00
event_dt = Time.from_str(date, timezone="UTC")
2025-12-08 13:21:43 -05:00
2025-12-16 14:27:05 -05:00
if not start_dt <= event_dt <= end_dt:
2025-12-08 13:21:43 -05:00
continue
if not (streams := stream_group.get("streams")):
continue
if not (url := streams[0].get("url")):
continue
events.append(
{
"sport": sport,
"event": event,
"link": url,
"timestamp": event_dt.timestamp(),
}
)
return events
2025-12-18 03:04:11 -05:00
async def scrape() -> None:
2025-12-08 13:21:43 -05:00
cached_urls = CACHE_FILE.load()
2025-12-18 04:14:54 -05:00
2025-12-16 20:39:52 -05:00
cached_count = len(cached_urls)
2025-12-18 04:14:54 -05:00
2025-12-16 20:39:52 -05:00
urls.update(cached_urls)
2025-12-08 13:21:43 -05:00
log.info(f"Loaded {cached_count} event(s) from cache")
log.info(f'Scraping from "{BASE_URL}"')
2025-12-18 03:04:11 -05:00
events = await get_events(cached_urls.keys())
2025-12-08 13:21:43 -05:00
log.info(f"Processing {len(events)} new URL(s)")
if events:
async with async_playwright() as p:
2025-12-19 17:58:37 -05:00
browser, context = await network.browser(p, browser="external")
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
try:
for i, ev in enumerate(events, start=1):
handler = partial(
network.process_event,
url=ev["link"],
url_num=i,
context=context,
log=log,
2025-12-16 20:39:52 -05:00
)
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
url = await network.safe_process(
handler,
url_num=i,
semaphore=network.PW_S,
log=log,
)
if url:
sport, event, ts, link = (
ev["sport"],
ev["event"],
ev["timestamp"],
ev["link"],
)
key = f"[{sport}] {event} ({TAG})"
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
tvg_id, logo = leagues.get_tvg_info(sport, event)
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
entry = {
"url": url,
"logo": logo,
"base": BASE_URL,
"timestamp": ts,
"id": tvg_id or "Live.Event.us",
"link": link,
}
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
urls[key] = cached_urls[key] = entry
2025-12-08 13:21:43 -05:00
2025-12-23 13:28:56 -05:00
finally:
await browser.close()
2025-12-08 13:21:43 -05:00
2025-12-16 20:39:52 -05:00
if new_count := len(cached_urls) - cached_count:
2025-12-08 13:21:43 -05:00
log.info(f"Collected and cached {new_count} new event(s)")
2025-12-18 04:14:54 -05:00
2025-12-08 13:21:43 -05:00
else:
log.info("No new events found")
CACHE_FILE.write(cached_urls)