iptv/M3U8/scrapers/livetvsx.py

312 lines
9 KiB
Python
Raw Normal View History

2025-09-01 19:12:49 -04:00
import asyncio
2025-09-02 18:06:35 -04:00
import io
2025-09-03 00:00:22 -04:00
import json
2025-09-02 18:06:35 -04:00
import ssl
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
2025-09-04 19:53:27 -04:00
from functools import partial
2025-09-02 18:06:35 -04:00
from pathlib import Path
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
import httpx
2025-09-04 19:53:27 -04:00
from playwright.async_api import async_playwright
from .utils import (
LOGOS,
TZ,
capture_req,
get_logger,
2025-09-05 10:37:22 -04:00
load_cache,
2025-09-04 19:53:27 -04:00
now,
safe_process_event,
)
2025-09-01 19:12:49 -04:00
log = get_logger(__name__)
2025-09-04 14:50:52 -04:00
urls: dict[str, dict[str, str | float]] = {}
2025-09-02 18:06:35 -04:00
BASE_URL = "https://cdn.livetv861.me/rss/upcoming_en.xml"
CERT_BUNDL_URLS = [
"https://curl.se/ca/cacert.pem",
"https://ssl.com/repo/certs/Cloudflare-TLS-I-E1.pem",
"https://ssl.com/repo/certs/SSL.com-TLS-T-ECC-R2.pem",
"https://ssl.com/repo/certs/Sectigo-AAA-Root.pem",
]
2025-09-03 03:14:52 -04:00
CERT_FILE = Path(__file__).parent / "utils" / "cached-ca.pem"
2025-09-01 19:12:49 -04:00
2025-09-03 03:14:52 -04:00
CACHE_FILE = Path(__file__).parent / "caches" / "livetvsx.json"
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
async def write_to_cert(client: httpx.AsyncClient, url: str, cert: Path) -> None:
try:
r = await client.get(url)
r.raise_for_status()
except Exception:
log.error(f"Failed to write fetch: {url} returned {r.status_code}")
with cert.open("a", encoding="utf-8") as f:
f.write(f"{r.text}\n")
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
async def refresh_cert_cache(client: httpx.AsyncClient) -> ssl.SSLContext:
CERT_FILE.unlink(missing_ok=True)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
tasks = [write_to_cert(client, url, CERT_FILE) for url in CERT_BUNDL_URLS]
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
await asyncio.gather(*tasks)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
async def get_cert(client: httpx.AsyncClient) -> ssl.SSLContext:
if CERT_FILE.is_file():
2025-09-04 10:10:28 -04:00
mtime = datetime.fromtimestamp(CERT_FILE.stat().st_mtime, TZ)
2025-09-02 18:06:35 -04:00
2025-09-04 09:59:19 -04:00
if now - mtime < timedelta(days=30):
2025-09-02 18:06:35 -04:00
return ssl.create_default_context(cafile=CERT_FILE)
log.info("Refreshing cached certificate")
await refresh_cert_cache(client)
return ssl.create_default_context(cafile=CERT_FILE)
2025-09-05 10:42:42 -04:00
async def fetch_xml_stream(url: str, ssl_ctx: ssl.SSLContext) -> io.BytesIO | None:
2025-09-02 18:06:35 -04:00
buffer = io.BytesIO()
2025-09-01 19:12:49 -04:00
try:
2025-09-02 18:06:35 -04:00
async with httpx.AsyncClient(timeout=10, verify=ssl_ctx) as client:
async with client.stream("GET", url) as r:
r.raise_for_status()
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
async for chunk in r.aiter_bytes(8192):
buffer.write(chunk)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
buffer.seek(0)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
return buffer
except Exception as e:
log.error(f"Failed to fetch {url}: {e}")
2025-09-05 10:42:42 -04:00
return
2025-09-01 19:12:49 -04:00
2025-09-03 00:39:49 -04:00
async def process_event(url: str, url_num: int) -> str | None:
2025-09-02 18:06:35 -04:00
async with async_playwright() as p:
browser = await p.firefox.launch(headless=True)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
context = await browser.new_context(
ignore_https_errors=True # website doesn't send valid certs
)
2025-09-04 19:53:27 -04:00
page = await context.new_page()
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
captured: list[str] = []
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
got_one = asyncio.Event()
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
handler = partial(capture_req, captured=captured, got_one=got_one)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
popup = None
2025-09-01 19:12:49 -04:00
try:
2025-09-04 19:53:27 -04:00
await page.goto(
2025-09-02 18:06:35 -04:00
url,
wait_until="domcontentloaded",
2025-09-03 00:39:49 -04:00
timeout=10_000,
2025-09-02 18:06:35 -04:00
)
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
btn = await page.query_selector(".lnkhdr > tbody > tr > td:nth-child(2)")
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
if btn:
try:
await btn.click()
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
await page.wait_for_timeout(500)
2025-09-02 18:06:35 -04:00
except Exception as e:
2025-09-03 00:00:22 -04:00
log.debug(f"URL {url_num}) Failed to click Browser Links tab: {e}")
return
2025-09-02 18:06:35 -04:00
else:
2025-09-03 00:00:22 -04:00
log.warning(f"URL {url_num}) Browser Links tab not found")
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
link_img = await page.query_selector(
2025-09-02 18:06:35 -04:00
"tr:nth-child(2) > td:nth-child(1) td:nth-child(6) img"
)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
if not link_img:
2025-09-03 00:00:22 -04:00
log.warning(f"URL {url_num}) No browser link to click.")
return
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
page.on("request", handler)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
try:
2025-09-04 19:53:27 -04:00
async with page.expect_popup(timeout=5_000) as popup_info:
2025-09-02 18:06:35 -04:00
try:
await link_img.click()
except Exception as e:
log.debug(
2025-09-03 00:00:22 -04:00
f"URL {url_num}) Click failed (popup might have already been opened): {e}"
2025-09-02 18:06:35 -04:00
)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
popup = await popup_info.value
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
popup.on("request", handler)
2025-09-02 18:06:35 -04:00
except Exception:
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
try:
await link_img.click()
except Exception as e:
2025-09-03 00:00:22 -04:00
log.debug(f"URL {url_num}) Fallback click failed: {e}")
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
wait_task = asyncio.create_task(got_one.wait())
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
try:
2025-09-03 00:39:49 -04:00
await asyncio.wait_for(wait_task, timeout=1.5e1)
2025-09-02 18:06:35 -04:00
except asyncio.TimeoutError:
2025-09-04 19:53:27 -04:00
log.warning(f"URL {url_num}) Timed out waiting for M3U8.")
2025-09-03 00:00:22 -04:00
return
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
finally:
if not wait_task.done():
wait_task.cancel()
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
try:
await wait_task
except asyncio.CancelledError:
pass
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
page.remove_listener("request", handler)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
if popup:
2025-09-04 19:53:27 -04:00
popup.remove_listener("request", handler)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
await popup.close()
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
await page.close()
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
if captured:
2025-09-03 00:00:22 -04:00
log.info(f"URL {url_num}) Captured M3U8")
2025-09-01 19:12:49 -04:00
2025-09-03 00:00:22 -04:00
return captured[-1]
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
log.warning(f"URL {url_num}) No M3U8 captured in popup or inline playback.")
2025-09-03 00:00:22 -04:00
return
2025-09-03 15:00:17 -04:00
except Exception:
2025-09-02 18:06:35 -04:00
try:
2025-09-04 19:53:27 -04:00
page.remove_listener("request", handler)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
if popup:
2025-09-04 19:53:27 -04:00
popup.remove_listener("request", handler)
2025-09-01 19:12:49 -04:00
2025-09-02 18:06:35 -04:00
await popup.close()
2025-09-01 19:12:49 -04:00
2025-09-04 19:53:27 -04:00
await page.close()
2025-09-02 18:06:35 -04:00
except Exception:
pass
2025-09-01 19:12:49 -04:00
await browser.close()
2025-09-02 18:06:35 -04:00
2025-09-03 18:41:07 -04:00
async def get_events(
url: str,
ssl_ctx: ssl.SSLContext,
cached_keys: set[str],
) -> list[dict[str, str]]:
events: list[dict[str, str]] = []
2025-09-04 10:46:49 -04:00
window_start, window_end = now - timedelta(hours=1), now + timedelta(minutes=30)
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
if buffer := await fetch_xml_stream(url, ssl_ctx):
2025-09-05 12:00:23 -04:00
pub_date_format = "%a, %d %b %Y %H:%M:%S %z"
2025-09-05 10:42:42 -04:00
for _, elem in ET.iterparse(buffer, events=("end",)):
if elem.tag == "item":
title = elem.findtext("title")
desc = elem.findtext("description")
pub_date = elem.findtext("pubDate")
link = elem.findtext("link")
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
try:
dt = datetime.strptime(pub_date, pub_date_format)
dt = dt.astimezone(TZ)
except Exception:
elem.clear()
continue
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
if window_start <= dt <= window_end:
sport, event = (
(
desc.split(".")[0].strip(),
" ".join(p.strip() for p in desc.split(".")[1:]),
)
if desc
else ("", "")
2025-09-03 18:41:07 -04:00
)
2025-09-05 10:42:42 -04:00
key = f"[{sport}: {event}] {title}"
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
if key in cached_keys:
elem.clear()
continue
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
events.append(
{
"sport": sport,
"event": event,
"title": title,
"link": link,
}
)
2025-09-03 18:41:07 -04:00
2025-09-05 10:42:42 -04:00
elem.clear()
2025-09-03 18:41:07 -04:00
return events
2025-09-02 18:06:35 -04:00
async def main(client: httpx.AsyncClient) -> None:
log.info(f'Scraping from "{BASE_URL}"')
cert = await get_cert(client)
2025-09-05 10:37:22 -04:00
cached_urls = load_cache(CACHE_FILE, exp=14400)
2025-09-03 00:00:22 -04:00
cached_count = len(cached_urls)
2025-09-05 15:56:07 -04:00
urls.update(cached_urls)
2025-09-03 00:00:22 -04:00
2025-09-04 14:50:52 -04:00
log.info(f"Collected {cached_count} event(s) from cache")
2025-09-03 18:41:07 -04:00
events = await get_events(BASE_URL, cert, set(cached_urls.keys()))
2025-09-03 00:00:22 -04:00
2025-09-05 15:56:07 -04:00
log.info(f"Processing {len(events)} new URL(s)")
2025-09-02 18:06:35 -04:00
2025-09-03 18:41:07 -04:00
for i, ev in enumerate(events, start=1):
2025-09-03 00:00:22 -04:00
sport = ev["sport"]
event = ev["event"]
title = ev["title"]
link = ev["link"]
2025-09-02 18:06:35 -04:00
2025-09-03 00:00:22 -04:00
key = f"[{sport}: {event}] {title}"
url = await safe_process_event(
2025-09-03 18:41:07 -04:00
lambda: process_event(link, url_num=i),
url_num=i,
2025-09-03 15:00:17 -04:00
log=log,
2025-09-03 00:00:22 -04:00
)
2025-09-02 18:06:35 -04:00
if url:
2025-09-03 00:00:22 -04:00
entry = {
2025-09-02 18:06:35 -04:00
"url": url,
2025-09-03 15:00:17 -04:00
"logo": LOGOS.get(
2025-09-02 18:06:35 -04:00
sport,
"https://i.gyazo.com/ec27417a9644ae517196494afa72d2b9.png",
),
2025-09-04 09:59:19 -04:00
"timestamp": now.timestamp(),
2025-09-02 18:06:35 -04:00
}
2025-09-03 00:00:22 -04:00
urls[key] = cached_urls[key] = entry
2025-09-05 15:56:07 -04:00
if (new_count := len(cached_urls) - cached_count) > 0:
CACHE_FILE.write_text(json.dumps(cached_urls, indent=2), encoding="utf-8")
2025-09-03 00:00:22 -04:00
2025-09-05 15:56:07 -04:00
log.info(f"Collected and cached {new_count} new event(s)")
else:
log.info("No new events found")