iptv/M3U8/scrapers/streamsgate.py

193 lines
4.5 KiB
Python
Raw Normal View History

2026-03-20 12:52:11 -04:00
import asyncio
import re
2025-12-08 13:21:43 -05:00
from functools import partial
2026-03-20 12:52:11 -04:00
from itertools import chain
from urllib.parse import urljoin
2025-12-08 13:21:43 -05:00
from selectolax.parser import HTMLParser
2025-12-08 13:21:43 -05:00
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
2026-05-02 15:39:02 -04:00
CACHE_FILE = Cache(TAG, exp=19_800)
2025-12-08 13:21:43 -05:00
BASE_URL = "https://streamsgates.io"
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
SPORT_URLS = [
urljoin(BASE_URL, f"data/{sport}.json")
for sport in [
# "cfb",
"mlb",
"nba",
# "nfl",
"nhl",
"soccer",
"ufc",
]
]
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
def get_event(t1: str, t2: str) -> str:
match t1:
case "RED ZONE":
return "NFL RedZone"
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
case "TBD":
return "TBD"
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
case _:
return f"{t1.strip()} vs {t2.strip()}"
2025-12-08 13:21:43 -05:00
async def process_event(url: str, url_num: int) -> tuple[str | None, str | None]:
2026-04-11 19:31:42 -04:00
nones = None, None
if not (event_data := await network.request(url, log=log)):
log.warning(f"URL {url_num}) Failed to load url.")
2026-04-11 19:31:42 -04:00
return nones
soup_1 = HTMLParser(event_data.content)
ifr = soup_1.css_first("iframe")
if not ifr or not (src := ifr.attributes.get("src")):
log.warning(f"URL {url_num}) No iframe element found.")
2026-04-11 19:31:42 -04:00
return nones
ifr_src = f"https:{src}" if src.startswith("//") else src
if not (
ifr_src_data := await network.request(
ifr_src,
headers={"Referer": url},
log=log,
)
):
log.warning(f"URL {url_num}) Failed to load iframe source. (IFR1)")
2026-04-11 19:31:42 -04:00
return nones
2026-04-19 19:31:17 -04:00
valid_m3u8 = re.compile(r"(file|source):\s+(\'|\")([^\"]*)(\'|\")", re.I)
if not (match := valid_m3u8.search(ifr_src_data.text)):
log.warning(f"URL {url_num}) No source found.")
2026-04-11 19:31:42 -04:00
return nones
log.info(f"URL {url_num}) Captured M3U8")
2026-04-19 19:31:17 -04:00
return match[3], ifr_src
async def get_events() -> list[dict[str, str]]:
2026-03-20 12:52:11 -04:00
now = Time.clean(Time.now())
2025-12-08 13:21:43 -05:00
tasks = [network.request(url, log=log) for url in SPORT_URLS]
2025-12-08 13:21:43 -05:00
results = await asyncio.gather(*tasks)
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
events = []
2025-12-18 03:04:11 -05:00
if not (api_data := [*chain.from_iterable(r.json() for r in results if r)]):
return events
2025-12-18 03:04:11 -05:00
2026-03-20 12:52:11 -04:00
for stream_group in api_data:
date = stream_group.get("time")
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
sport = stream_group.get("league")
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
t1, t2 = stream_group.get("away"), stream_group.get("home")
2025-12-08 13:21:43 -05:00
2026-03-20 12:52:11 -04:00
if not (date and sport):
continue
event_dt = Time.from_str(date, timezone="UTC")
if event_dt.date() != now.date():
2026-03-20 12:52:11 -04:00
continue
if not (streams := stream_group.get("streams")) or not (
url := streams[0].get("url")
):
2026-03-20 12:52:11 -04:00
continue
if not (t1 and t2):
2026-03-20 12:52:11 -04:00
continue
event = get_event(t1, t2)
2026-03-20 12:52:11 -04:00
events.append(
{
"sport": sport,
"event": event,
"link": url,
"timestamp": now.timestamp(),
2026-03-20 12:52:11 -04:00
}
)
2025-12-08 13:21:43 -05:00
return events
async def scrape() -> None:
if cached_urls := CACHE_FILE.load():
urls.update({k: v for k, v in cached_urls.items() if v["url"]})
2026-02-28 15:42:50 -05:00
log.info(f"Loaded {len(urls)} event(s) from cache")
2025-12-08 13:21:43 -05:00
return
2025-12-08 13:21:43 -05:00
log.info(f'Scraping from "{BASE_URL}"')
if events := await get_events():
log.info(f"Processing {len(events)} new URL(s)")
for i, ev in enumerate(events, start=1):
handler = partial(
process_event,
url=(link := ev["link"]),
url_num=i,
)
url, iframe = await network.safe_process(
handler,
url_num=i,
semaphore=network.HTTP_S,
log=log,
)
sport, event, ts = (
ev["sport"],
ev["event"],
ev["timestamp"],
)
key = f"[{sport}] {event} ({TAG})"
tvg_id, logo = leagues.get_tvg_info(sport, event)
entry = {
"url": url,
"logo": logo,
"base": iframe,
"timestamp": ts,
"id": tvg_id or "Live.Event.us",
"link": link,
}
cached_urls[key] = entry
if url:
entry["url"] = url.split("?st")[0]
urls[key] = entry
2025-12-08 13:21:43 -05:00
log.info(f"Collected and cached {len(urls)} 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)