iptv/M3U8/scrape/ppv.py

219 lines
5.7 KiB
Python
Raw Normal View History

2025-09-03 15:00:17 -04:00
#!/usr/bin/env python3
import asyncio
import json
import re
2025-09-04 11:50:29 -04:00
from datetime import datetime, timedelta
2025-09-04 19:53:27 -04:00
from functools import partial
2025-09-03 15:00:17 -04:00
from pathlib import Path
from urllib.parse import urljoin
import httpx
2025-09-04 19:53:27 -04:00
from playwright.async_api import async_playwright
from .utils import (
TZ,
capture_req,
get_base,
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-03 15:00:17 -04:00
log = get_logger(__name__)
2025-09-04 14:50:52 -04:00
urls: dict[str, dict[str, str | float]] = {}
2025-09-03 15:00:17 -04:00
API_FILE = Path(__file__).parent / "caches" / "ppv_api.json"
CACHE_FILE = Path(__file__).parent / "caches" / "ppv.json"
2025-09-04 19:53:27 -04:00
MIRRORS = [
"https://ppvs.su",
"https://ppv.to",
"https://ppv.wtf",
"https://ppv.land",
"https://freeppv.fun",
]
2025-09-03 15:00:17 -04:00
async def refresh_api_cache(client: httpx.AsyncClient, url: str) -> dict:
log.info("Refreshing API cache")
try:
r = await client.get(url)
r.raise_for_status()
except Exception as e:
log.error(f'Failed to fetch "{url}"\n{e}')
return {}
return r.json()
def load_api_cache() -> dict[str, dict[str, str | str]]:
try:
data: dict = json.loads(API_FILE.read_text(encoding="utf-8"))
2025-09-04 09:59:19 -04:00
age: float = now.timestamp() - data.get("timestamp", 0)
2025-09-03 15:00:17 -04:00
return data if age < 86400 else {} # 24 hours
except (FileNotFoundError, json.JSONDecodeError):
return {}
async def process_event(url: str, url_num: int) -> str | None:
async with async_playwright() as p:
browser = await p.firefox.launch(headless=True)
context = await browser.new_context()
page = await context.new_page()
captured: list[str] = []
got_one = asyncio.Event()
2025-09-04 19:53:27 -04:00
handler = partial(capture_req, captured=captured, got_one=got_one)
2025-09-03 15:00:17 -04:00
2025-09-04 19:53:27 -04:00
page.on("request", handler)
2025-09-03 15:00:17 -04:00
try:
2025-09-04 09:59:19 -04:00
await page.goto(url, wait_until="domcontentloaded", timeout=15_000)
2025-09-03 15:00:17 -04:00
wait_task = asyncio.create_task(got_one.wait())
try:
await asyncio.wait_for(wait_task, timeout=10)
except asyncio.TimeoutError:
2025-09-04 19:53:27 -04:00
log.warning(f"URL {url_num}) Timed out waiting for M3U8.")
return
2025-09-03 15:00:17 -04:00
finally:
if not wait_task.done():
wait_task.cancel()
try:
await wait_task
except asyncio.CancelledError:
pass
if captured:
log.info(f"URL {url_num}) Captured M3U8")
return captured[-1]
2025-09-04 19:53:27 -04:00
log.warning(f"URL {url_num}) No M3U8 captured after waiting.")
return
2025-09-03 15:00:17 -04:00
except Exception as e:
log.warning(f"URL {url_num}) Exception while processing: {e}")
2025-09-04 19:53:27 -04:00
return
2025-09-03 15:00:17 -04:00
finally:
2025-09-04 19:53:27 -04:00
page.remove_listener("request", handler)
2025-09-03 15:00:17 -04:00
await page.close()
await browser.close()
async def get_events(
client: httpx.AsyncClient,
api_url: str,
2025-09-03 18:41:07 -04:00
cached_keys: set[str],
2025-09-04 19:53:27 -04:00
) -> list[dict[str, str]]:
2025-09-03 18:41:07 -04:00
events: list[dict[str, str]] = []
2025-09-03 15:00:17 -04:00
base_url = re.match(r"(https?://.+?)/", api_url)[1]
if not (api_data := load_api_cache()):
api_data = await refresh_api_cache(client, api_url)
API_FILE.write_text(json.dumps(api_data, indent=2), encoding="utf-8")
for stream_group in api_data["streams"]:
sport = stream_group["category"]
if sport == "24/7 Streams":
continue
for event in stream_group["streams"]:
name, start_ts, end_ts, logo, uri_name = (
event["name"],
event["starts_at"],
event["ends_at"],
event.get(
"poster",
"https://i.gyazo.com/ec27417a9644ae517196494afa72d2b9.png",
),
event["uri_name"],
)
key = f"[{sport}] {name}"
if key in cached_keys:
continue
2025-09-04 11:50:29 -04:00
start_dt = datetime.fromtimestamp(start_ts, tz=TZ) - timedelta(minutes=30)
2025-09-03 15:00:17 -04:00
2025-09-04 11:50:29 -04:00
end_dt = datetime.fromtimestamp(end_ts, tz=TZ) + timedelta(minutes=30)
2025-09-03 15:00:17 -04:00
2025-09-03 18:41:07 -04:00
if not start_dt <= now < end_dt:
2025-09-03 15:00:17 -04:00
continue
events.append(
{
"sport": sport,
"event": name,
"link": urljoin(base_url, f"/live/{uri_name}"),
"logo": logo,
}
)
return events
async def main(client: httpx.AsyncClient) -> None:
if not (base_url := await get_base(client, MIRRORS)):
log.warning("No working PPV mirrors")
return
log.info(f'Scraping from "{base_url}"')
2025-09-05 10:37:22 -04:00
cached_urls = load_cache(CACHE_FILE, exp=14400)
2025-09-03 15:00:17 -04:00
cached_count = len(cached_urls)
2025-09-04 14:50:52 -04:00
log.info(f"Collected {cached_count} event(s) from cache")
2025-09-03 15:00:17 -04:00
events = await get_events(
client,
urljoin(base_url, "/api/streams"),
set(cached_urls.keys()),
)
2025-09-04 14:50:52 -04:00
log.info(f"Processing {len(events)} new URLs")
2025-09-03 15:00:17 -04:00
2025-09-03 18:41:07 -04:00
for i, ev in enumerate(events, start=1):
2025-09-03 15:00:17 -04:00
url = await safe_process_event(
2025-09-03 18:41:07 -04:00
lambda: process_event(ev["link"], url_num=i),
url_num=i,
2025-09-03 15:00:17 -04:00
log=log,
)
if url:
entry = {
"url": url,
"logo": ev["logo"],
2025-09-04 09:59:19 -04:00
"timestamp": now.timestamp(),
2025-09-03 15:00:17 -04:00
}
key = f"[{ev['sport']}] {ev['event']}"
urls[key] = cached_urls[key] = entry
CACHE_FILE.write_text(json.dumps(cached_urls, indent=2), encoding="utf-8")
2025-09-04 14:50:52 -04:00
log.info(f"Collected {len(cached_urls) - cached_count} new event(s)")
2025-09-03 15:00:17 -04:00
# works if no cloudflare bot detection