- edit scraping method for streamcenter.py
- misc edits.
This commit is contained in:
doms9 2026-04-09 01:25:23 -04:00
parent 1af71f0610
commit 00000d9dec
3 changed files with 64 additions and 65 deletions

View file

@ -67,7 +67,6 @@ async def main() -> None:
# asyncio.create_task(fsports.scrape(xtrnl_brwsr)), # asyncio.create_task(fsports.scrape(xtrnl_brwsr)),
asyncio.create_task(ppv.scrape(xtrnl_brwsr)), asyncio.create_task(ppv.scrape(xtrnl_brwsr)),
asyncio.create_task(roxie.scrape(hdl_brwsr)), asyncio.create_task(roxie.scrape(hdl_brwsr)),
asyncio.create_task(streamcenter.scrape(hdl_brwsr)),
] ]
httpx_tasks = [ httpx_tasks = [
@ -78,6 +77,7 @@ async def main() -> None:
# asyncio.create_task(ovogoal.scrape()), # asyncio.create_task(ovogoal.scrape()),
asyncio.create_task(pawa.scrape()), asyncio.create_task(pawa.scrape()),
asyncio.create_task(shark.scrape()), asyncio.create_task(shark.scrape()),
asyncio.create_task(streamcenter.scrape()),
# asyncio.create_task(streamhub.scrape()), # asyncio.create_task(streamhub.scrape()),
asyncio.create_task(streamsgate.scrape()), asyncio.create_task(streamsgate.scrape()),
asyncio.create_task(streamtpnew.scrape()), asyncio.create_task(streamtpnew.scrape()),

View file

@ -85,7 +85,7 @@ async def get_events(cached_keys: list[str]) -> list[dict[str, str]]:
event_dt = Time.from_str(event["start"], timezone="UTC") event_dt = Time.from_str(event["start"], timezone="UTC")
if now.date() != event_dt.date(): if event_dt.date() != now.date():
continue continue
if not (channels := event.get("channels")): if not (channels := event.get("channels")):

View file

@ -1,6 +1,6 @@
from functools import partial from functools import partial
from playwright.async_api import Browser from selectolax.parser import HTMLParser
from .utils import Cache, Time, get_logger, leagues, network from .utils import Cache, Time, get_logger, leagues, network
@ -10,9 +10,7 @@ urls: dict[str, dict[str, str | float]] = {}
TAG = "STRMCNTR" TAG = "STRMCNTR"
CACHE_FILE = Cache(TAG, exp=10_800) CACHE_FILE = Cache(TAG, exp=19_800)
API_FILE = Cache(f"{TAG}-api", exp=19_800)
API_URL = "https://backend.streamcenter.live/api/Parties" API_URL = "https://backend.streamcenter.live/api/Parties"
@ -30,30 +28,40 @@ CATEGORIES = {
} }
async def process_event(url: str, url_num: int) -> str | None:
if not (html_data := await network.request(url, log=log)):
log.warning(f"URL {url_num}) Failed to load url.")
return
soup = HTMLParser(html_data.content)
iframe = soup.css_first("iframe")
if not iframe or not (iframe_src := iframe.attributes.get("src")):
log.warning(f"URL {url_num}) No iframe element found.")
return
log.info(f"URL {url_num}) Captured M3U8")
return f"https://mainstreams.pro/hls/{iframe_src.rsplit("=", 1)[-1]}.m3u8"
async def get_events(cached_keys: list[str]) -> list[dict[str, str]]: async def get_events(cached_keys: list[str]) -> list[dict[str, str]]:
now = Time.clean(Time.now()) now = Time.clean(Time.now())
if not (api_data := API_FILE.load(per_entry=False, index=-1)): events = []
log.info("Refreshing API cache")
api_data = [{"timestamp": now.timestamp()}] if not (
r := await network.request(
if r := await network.request(
API_URL, API_URL,
log=log, log=log,
params={"pageNumber": 1, "pageSize": 500}, params={"pageNumber": 1, "pageSize": 500},
)
): ):
return events
api_data: list[dict] = r.json() api_data: list[dict] = r.json()
api_data[-1]["timestamp"] = now.timestamp()
API_FILE.write(api_data)
events = []
start_dt = now.delta(hours=-1)
end_dt = now.delta(minutes=5)
for stream_group in api_data: for stream_group in api_data:
category_id: int = stream_group.get("categoryId") category_id: int = stream_group.get("categoryId")
@ -66,30 +74,29 @@ async def get_events(cached_keys: list[str]) -> list[dict[str, str]]:
if not (name and category_id and iframe and event_time): if not (name and category_id and iframe and event_time):
continue continue
event_dt = Time.from_str(event_time, timezone="CET")
if event_dt.date() != now.date():
continue
if not (sport := CATEGORIES.get(category_id)): if not (sport := CATEGORIES.get(category_id)):
continue continue
if f"[{sport}] {name} ({TAG})" in cached_keys: if f"[{sport}] {name} ({TAG})" in cached_keys:
continue continue
event_dt = Time.from_str(event_time, timezone="CET")
if not start_dt <= event_dt <= end_dt:
continue
events.append( events.append(
{ {
"sport": sport, "sport": sport,
"event": name, "event": name,
"link": iframe.replace("<", "?", count=1), "link": iframe.split("<")[0],
"timestamp": event_dt.timestamp(),
} }
) )
return events return events
async def scrape(browser: Browser) -> None: async def scrape() -> None:
cached_urls = CACHE_FILE.load() cached_urls = CACHE_FILE.load()
valid_urls = {k: v for k, v in cached_urls.items() if v["url"]} valid_urls = {k: v for k, v in cached_urls.items() if v["url"]}
@ -105,15 +112,13 @@ async def scrape(browser: Browser) -> None:
if events := await get_events(cached_urls.keys()): if events := await get_events(cached_urls.keys()):
log.info(f"Processing {len(events)} new URL(s)") log.info(f"Processing {len(events)} new URL(s)")
async with network.event_context(browser) as context: now = Time.clean(Time.now())
for i, ev in enumerate(events, start=1): for i, ev in enumerate(events, start=1):
async with network.event_page(context) as page:
handler = partial( handler = partial(
network.process_event, process_event,
url=(link := ev["link"]), url=(link := ev["link"]),
url_num=i, url_num=i,
page=page,
log=log,
) )
url = await network.safe_process( url = await network.safe_process(
@ -123,11 +128,7 @@ async def scrape(browser: Browser) -> None:
log=log, log=log,
) )
sport, event, ts = ( sport, event = ev["sport"], ev["event"]
ev["sport"],
ev["event"],
ev["timestamp"],
)
key = f"[{sport}] {event} ({TAG})" key = f"[{sport}] {event} ({TAG})"
@ -137,7 +138,7 @@ async def scrape(browser: Browser) -> None:
"url": url, "url": url,
"logo": logo, "logo": logo,
"base": "https://streamcenter.xyz", "base": "https://streamcenter.xyz",
"timestamp": ts, "timestamp": now.timestamp(),
"id": tvg_id or "Live.Event.us", "id": tvg_id or "Live.Event.us",
"link": link, "link": link,
} }
@ -147,8 +148,6 @@ async def scrape(browser: Browser) -> None:
if url: if url:
valid_count += 1 valid_count += 1
entry["url"] = url.split("?")[0]
urls[key] = entry urls[key] = entry
log.info(f"Collected and cached {valid_count - cached_count} new event(s)") log.info(f"Collected and cached {valid_count - cached_count} new event(s)")