iptv/M3U8/scrapers/streambtw.py

119 lines
2.9 KiB
Python
Raw Normal View History

2025-09-04 19:53:27 -04:00
import re
from pathlib import Path
from urllib.parse import urljoin
import httpx
from selectolax.parser import HTMLParser
2025-10-01 11:57:49 -04:00
from .utils import Cache, Time, get_logger, leagues, network
2025-09-04 19:53:27 -04:00
log = get_logger(__name__)
2025-09-05 10:37:22 -04:00
urls: dict[str, dict[str, str]] = {}
2025-09-04 19:53:27 -04:00
BASE_URL = "https://streambtw.com/"
2025-10-01 11:57:49 -04:00
CACHE_FILE = Cache(Path(__file__).parent / "caches" / "streambtw.json", exp=86_400)
2025-09-04 19:53:27 -04:00
async def process_event(
client: httpx.AsyncClient,
url: str,
url_num: int,
) -> str | None:
try:
r = await client.get(url)
r.raise_for_status()
except Exception as e:
log.error(f'URL {url_num}) Failed to fetch "{url}"\n{e}')
return
valid_m3u8 = re.compile(
r'var\s+randomM3u8\s*=\s*[\'"]([^\'"]+)[\'"]',
re.IGNORECASE,
)
if match := valid_m3u8.search(r.text):
log.info(f"URL {url_num}) Captured M3U8")
return match[1]
log.info(f"URL {url_num}) No M3U8 found")
async def get_events(client: httpx.AsyncClient) -> list[dict[str, str]]:
try:
r = await client.get(BASE_URL)
r.raise_for_status()
except Exception as e:
2025-10-01 11:57:49 -04:00
log.error(f'Failed to fetch "{BASE_URL}": {e}')
2025-09-04 19:53:27 -04:00
return []
soup = HTMLParser(r.text)
events = []
for card in soup.css("div.container div.card"):
sport = card.css_first("h5.card-title").text(strip=True)
name = card.css_first("p.card-text").text(strip=True)
link = card.css_first("a.btn.btn-primary")
2025-10-01 11:57:49 -04:00
if not (href := link.attrs.get("href")):
continue
events.append(
{
"sport": sport,
"event": name,
"link": urljoin(BASE_URL, href),
}
)
2025-09-04 19:53:27 -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
if cached := CACHE_FILE.load():
2025-09-04 19:53:27 -04:00
urls.update(cached)
2025-10-01 11:57:49 -04:00
log.info(f"Loaded {len(urls)} event(s) from cache")
2025-09-04 19:53:27 -04:00
return
log.info(f'Scraping from "{BASE_URL}"')
events = await get_events(client)
2025-09-05 15:56:07 -04:00
log.info(f"Processing {len(events)} new URL(s)")
2025-09-04 19:53:27 -04:00
2025-10-01 18:34:18 -04:00
now = Time.now().timestamp()
2025-09-04 19:53:27 -04:00
for i, ev in enumerate(events, start=1):
2025-10-01 11:57:49 -04:00
url = await network.safe_process(
2025-09-04 19:53:27 -04:00
lambda: process_event(client, url=ev["link"], url_num=i),
url_num=i,
log=log,
2025-10-01 11:57:49 -04:00
timeout=10,
2025-09-04 19:53:27 -04:00
)
if url:
2025-09-19 02:05:40 -04:00
sport, event = ev["sport"], ev["event"]
key = f"[{sport}] {event} (SBTW)"
2025-09-13 04:42:55 -04:00
2025-09-24 12:30:55 -04:00
tvg_id, logo = leagues.info(sport)
2025-09-21 10:28:15 -04:00
2025-09-04 19:53:27 -04:00
entry = {
"url": url,
2025-09-24 16:21:25 -04:00
"logo": logo,
2025-09-13 04:42:55 -04:00
"base": BASE_URL,
2025-10-01 18:34:18 -04:00
"timestamp": now,
2025-10-01 11:57:49 -04:00
"id": tvg_id or "Live.Event.us",
2025-09-04 19:53:27 -04:00
}
2025-09-13 04:42:55 -04:00
urls[key] = entry
2025-09-04 19:53:27 -04:00
log.info(f"Collected {len(urls)} event(s)")
2025-10-01 11:57:49 -04:00
CACHE_FILE.write(urls)