From a9197e2b897197e978bb08ef054352733d42d09e Mon Sep 17 00:00:00 2001 From: Stephen Simpson Date: Fri, 4 Dec 2026 08:43:24 -0600 Subject: [PATCH 1/5] Add Nexstar free networks and guides --- app/scrapers/free_networks/__init__.py | 4 +- app/scrapers/free_networks/nexstar.py | 277 +++++++++++++++++++++++++ 2 files changed, 279 insertions(+), 2 deletions(-) create mode 100644 app/scrapers/free_networks/nexstar.py diff --git a/app/scrapers/free_networks/__init__.py b/app/scrapers/free_networks/__init__.py index 85d787b2..ff5af076 100644 --- a/app/scrapers/free_networks/__init__.py +++ b/app/scrapers/free_networks/__init__.py @@ -17,7 +17,7 @@ from . import ( adultswim, aetn, aljazeera, arirang, ballysports, beond, bloomberg, cbn, cbsnews, cgtn, cineverse, cowboyplus, cw, dw, ewtn, freetv, fstv, gameandfish, gizmott, hallmark, heartland, hsn, - i24news, jtv, ksl, mansa, newsmax, newsnation, nhk, nwsl, og_network, olympics, outside, positiv, qvc, redbull, scripps, shift, simple, + i24news, jtv, ksl, mansa, newsmax, newsnation, nexstar, nhk, nwsl, og_network, olympics, outside, positiv, qvc, redbull, scripps, shift, simple, sinclair, shout, sotal_partners, sportstv, tastemade, tbn, triller, trt, vsin, yahoo, ) @@ -26,7 +26,7 @@ NETWORKS = [ sinclair.Sinclair(), dw.DW(), aljazeera.AlJazeera(), i24news.I24News(), trt.TRT(), nhk.NHK(), arirang.Arirang(), bloomberg.Bloomberg(), cbsnews.CBSNews(), scripps.Scripps(), - newsmax.Newsmax(), newsnation.NewsNation(), fstv.FreeSpeechTV(), ewtn.EWTN(), positiv.PosiTV(), tbn.TBN(), + newsmax.Newsmax(), newsnation.NewsNation(), nexstar.Nexstar(), fstv.FreeSpeechTV(), ewtn.EWTN(), positiv.PosiTV(), tbn.TBN(), hsn.HSN(), qvc.QVC(), tastemade.Tastemade(), aetn.AETN(), ksl.KSL(), cbn.CBN(), gameandfish.GameAndFish(), outside.OutsideTV(), cw.CW(), cineverse.Cineverse(), og_network.OGNetwork(), *sotal_partners.NETWORKS, beond.BeOND(), mansa.Mansa(), freetv.FreeTV(), nwsl.NWSL(), triller.Triller(), heartland.Heartland(), shout.Shout(), diff --git a/app/scrapers/free_networks/nexstar.py b/app/scrapers/free_networks/nexstar.py new file mode 100644 index 00000000..31c816c5 --- /dev/null +++ b/app/scrapers/free_networks/nexstar.py @@ -0,0 +1,277 @@ +"""Nexstar-owned local stations with public Anvato/Lura live streams and guides. + +The station pages expose their live-player configuration in WordPress REST +metadata, even when the pages themselves are behind PerimeterX. The player ID +and access key are read at playback time, then Lura returns a fresh signed HLS +URL. Keep only the station key in the channel URL; signed URLs expire. + +The official program-schedule pages embed TitanTV. Its public data API provides +the local broadcast lineup and a seven-day schedule for each station. +""" +from __future__ import annotations + +import html +import json +import re +from datetime import datetime +from urllib.parse import urlsplit +from zoneinfo import ZoneInfo + +from ._common import Network, NetChannel, logger, parse_iso, program + +_LURA_API = 'https://tkx.mp.lura.live/rest/v2/mcp/video/{}' +_TITAN_API = 'https://www.titantvguide.com/data' +_GUIDE_DAYS = 7 +_PLAYER_RE = re.compile(r'data-nexstar-video="([^"]+)"') +_JSONP_RE = re.compile(r'^[^(]*\((.*)\)\s*;?\s*$', re.S) +_ID_RE = re.compile(r'[A-Za-z0-9_-]+') +_KEY_RE = re.compile(r'[A-Za-z0-9]+') + + +_STATIONS = { + 'wgn': { + 'name': 'WGN+', 'host': 'wgntv.com', 'live_slug': 'live-streaming', + 'logo': 'https://wgntv.com/wp-content/uploads/sites/5/2018/11/wgn_splash_1280x720.png?strip=1', + 'titan_site': '77961', 'titan_lineup': 'WGN', 'call_sign': 'WGN-DT1', + 'timezone': ZoneInfo('America/Chicago'), + }, + 'ktla': { + 'name': 'KTLA+', 'host': 'ktla.com', 'live_slug': 'live-streaming', + 'logo': 'https://ktla.com/wp-content/uploads/sites/4/2026/01/KTLA-5-SOCIA-BAN_KTLA-5-SOCIAL-BAN_SET_2056x1440.png?strip=1', + 'titan_site': '77958', 'titan_lineup': 'KTLA', 'call_sign': 'KTLA-DT1', + 'timezone': ZoneInfo('America/Los_Angeles'), + }, + 'wpix': { + 'name': 'PIX11+', 'host': 'pix11.com', 'live_slug': 'live', + 'logo': 'https://pix11.com/wp-content/uploads/sites/25/2023/08/pix11logo.png?strip=1', + 'titan_site': '77726', 'titan_lineup': 'WPIX', 'call_sign': 'WPIX-DT1', + 'timezone': ZoneInfo('America/New_York'), + }, +} + + +def _text(values) -> str | None: + """English text from TitanTV's localized {Text, Lang} list.""" + entries = [entry for entry in values or [] if isinstance(entry, dict)] + english = next((entry for entry in entries if entry.get('Lang') == 'eng'), None) + entry = english or (entries[0] if entries else None) + return entry.get('Text') if entry else None + + +def _anvacks(player: dict) -> list[str]: + streams = (player.get('livestreams') or {}).values() + return list(dict.fromkeys( + stream['anvack'] for stream in streams + if isinstance(stream, dict) and _KEY_RE.fullmatch(stream.get('anvack') or '') + )) + + +def _positive_int(value) -> int | None: + try: + number = int(value) + except (TypeError, ValueError): + return None + return number if number > 0 else None + + +def _air_date(value): + try: + return datetime.strptime(value, '%m/%d/%Y').date() + except (TypeError, ValueError): + return None + + +def _find_player(rendered: str, station_id: str) -> dict | None: + for match in _PLAYER_RE.finditer(rendered): + try: + player = json.loads(html.unescape(match.group(1))) + except (TypeError, ValueError): + continue + if not isinstance(player, dict) or player.get('provider') != 'anvato': + continue + attributes = player.get('attributes') or {} + if attributes.get('type') != 'live': + continue + player_station = attributes.get('station') + if not player_station or str(player_station).lower() == station_id: + return player + return None + + +def _parse_jsonp(body: str) -> dict: + match = _JSONP_RE.search(body.strip()) + try: + data = json.loads(match.group(1) if match else body) + except ValueError as exc: + raise RuntimeError('invalid Lura response') from exc + if not isinstance(data, dict): + raise RuntimeError('unexpected Lura response') + return data + + +class Nexstar(Network): + key = 'nexstar' + name = 'Nexstar (WGN+, KTLA+, PIX11+)' + + def channels(self, s): + return [NetChannel(cid, station['name'], cid, logo=station['logo'], category='News') + for cid, station in _STATIONS.items()] + + def resolve(self, s, ref): + station = _STATIONS.get(ref) + if not station: + raise RuntimeError(f'Nexstar: unknown station {ref!r}') + name, host = station['name'], station['host'] + live_url = f'https://{host}/{station["live_slug"]}/' + + response = s.session.get( + f'https://{host}/wp-json/wp/v2/pages', + params={'slug': station['live_slug']}, timeout=15, + ) + response.raise_for_status() + try: + pages = response.json() + except ValueError as exc: + raise RuntimeError(f'Nexstar: {name} returned invalid WordPress metadata') from exc + if not isinstance(pages, list) or not pages or not isinstance(pages[0], dict): + raise RuntimeError(f'Nexstar: no live-player page found for {name}') + + rendered = (pages[0].get('content') or {}).get('rendered') or '' + player = _find_player(rendered, ref) + if not player: + raise RuntimeError(f'Nexstar: no live Anvato player found for {name}') + attributes = player.get('attributes') or {} + video_id = player.get('id') or attributes.get('id') + if not isinstance(video_id, str) or not _ID_RE.fullmatch(video_id): + raise RuntimeError(f'Nexstar: invalid live-player ID for {name}') + + keys = _anvacks(player) + if not keys: + raise RuntimeError(f'Nexstar: no live-player access key found for {name}') + + last_error = '' + for key in keys: + try: + result = s.session.get( + _LURA_API.format(video_id), params={'anvack': key}, + headers={'Referer': live_url, 'Origin': f'https://{host}'}, + timeout=15, + ) + result.raise_for_status() + data = _parse_jsonp(result.text) + except Exception as exc: + last_error = str(exc) + continue + + exception = data.get('exception') + if isinstance(exception, dict): + last_error = str(exception.get('desc') or exception.get('code') or '') + for published in data.get('published_urls') or []: + if not isinstance(published, dict): + continue + url = published.get('embed_url') or '' + parts = urlsplit(url) + if (parts.scheme == 'https' + and (parts.hostname or '').endswith('.mp.lura.live') + and parts.path.endswith('.m3u8')): + return url + + detail = f': {last_error}' if last_error else '' + raise RuntimeError(f'Nexstar: Lura returned no playable stream for {name}{detail}') + + def programs(self, s, channels): + out = [] + for channel in channels: + station = _STATIONS.get(channel.id) + if not station: + continue + guide = self._station_programs(s, channel.id, station) + if guide is None: + # Keep the stored guide rather than treating a failed fetch as + # an empty schedule. + logger.warning('[free_networks] Nexstar guide unavailable for %s', station['name']) + return None + out.extend(guide) + return out + + def _station_programs(self, s, channel_id, station): + site = station['titan_site'] + lineups = self._titan_json(s, f'lineups/{site}') + if not isinstance(lineups, list): + return None + lineup = next((row for row in lineups + if isinstance(row, dict) and row.get('LineupName') == station['titan_lineup']), None) + lineup_id = lineup.get('LineupId') if lineup else None + if not isinstance(lineup_id, str) or not lineup_id: + return None + + data = self._titan_json(s, f'channels/{site}/{lineup_id}') + lineup_channels = data.get('Channels') if isinstance(data, dict) else None + if not isinstance(lineup_channels, list): + return None + guide_channel = next((row for row in lineup_channels + if isinstance(row, dict) and row.get('CallSign') == station['call_sign']), None) + channel_index = guide_channel.get('ChannelIndex') if guide_channel else None + if not isinstance(channel_index, int): + return None + + today = datetime.now(station['timezone']).replace(hour=0, minute=0, second=0, microsecond=0) + date_arg = today.strftime('%Y%m%d%H%M') + data = self._titan_json( + s, f'events/{site}/{lineup_id}/{date_arg}/1440/{channel_index}/{_GUIDE_DAYS}', + ) + event_channels = data.get('Channels') if isinstance(data, dict) else None + if not isinstance(event_channels, list): + return None + events = next((row for row in event_channels + if isinstance(row, dict) and row.get('ChannelIndex') == channel_index), None) + days = events.get('Days') if events else None + if not isinstance(days, list): + return None + return self._parse_programs(channel_id, days) + + @staticmethod + def _parse_programs(channel_id: str, days: list) -> list: + out, seen = [], set() + for day in days: + if not isinstance(day, dict): + continue + for row in day.get('Shows') or []: + if not isinstance(row, dict): + continue + title = _text(row.get('Title')) + start = parse_iso(row.get('StartTime')) + end = parse_iso(row.get('EndTime')) + event_id = row.get('EventId') + identity = event_id if event_id is not None else (start, end, title) + if identity in seen: + continue + seen.add(identity) + + rating = row.get('Rating') or {} + p = program( + channel_id, title, start, end, + episode_title=_text(row.get('EpisodeTitle')), + description=_text(row.get('Description')), + category='; '.join(filter(None, (_text(item) for item in row.get('Category') or []))), + rating=rating.get('TV') if isinstance(rating, dict) else None, + season=_positive_int(row.get('SeasonNumber')), + episode=_positive_int(row.get('SeasonEpisodeNumber')), + original_air_date=_air_date(row.get('OriginalAirDate')), + ) + if p: + out.append(p) + return out + + @staticmethod + def _titan_json(s, path: str): + response = s.get(f'{_TITAN_API}/{path}') + if not response: + return None + try: + envelope = response.json() + except ValueError: + return None + if not isinstance(envelope, dict) or envelope.get('Status') != 'SUCCESS': + return None + return envelope.get('Json') From b1353b2f8beb90efa925f7b46853de8b38d078dc Mon Sep 17 00:00:00 2001 From: Stephen Simpson Date: Fri, 4 Dec 2026 12:20:27 -0600 Subject: [PATCH 2/5] Use Plus-specific Nexstar program guides --- app/scrapers/free_networks/nexstar.py | 452 ++++++++++++++++++-------- 1 file changed, 309 insertions(+), 143 deletions(-) diff --git a/app/scrapers/free_networks/nexstar.py b/app/scrapers/free_networks/nexstar.py index 31c816c5..92f16e3e 100644 --- a/app/scrapers/free_networks/nexstar.py +++ b/app/scrapers/free_networks/nexstar.py @@ -1,88 +1,98 @@ -"""Nexstar-owned local stations with public Anvato/Lura live streams and guides. +"""Nexstar Plus streams and program guides. -The station pages expose their live-player configuration in WordPress REST -metadata, even when the pages themselves are behind PerimeterX. The player ID -and access key are read at playback time, then Lura returns a fresh signed HLS -URL. Keep only the station key in the channel URL; signed URLs expire. - -The official program-schedule pages embed TitanTV. Its public data API provides -the local broadcast lineup and a seven-day schedule for each station. +The live players come from the stations' public WordPress pages. PIX11+ has a +Lura schedule feed; WGN+ and KTLA+ publish recurring schedules on their sites. """ from __future__ import annotations import html import json import re -from datetime import datetime +from datetime import datetime, time, timedelta from urllib.parse import urlsplit from zoneinfo import ZoneInfo -from ._common import Network, NetChannel, logger, parse_iso, program +import requests + +from ._common import Network, NetChannel, from_epoch, logger, program _LURA_API = 'https://tkx.mp.lura.live/rest/v2/mcp/video/{}' -_TITAN_API = 'https://www.titantvguide.com/data' +_LURA_FEED = 'https://feed.mp.lura.live/v3/feed/{}' +_FEED_PAGE_SIZE = 100 _GUIDE_DAYS = 7 _PLAYER_RE = re.compile(r'data-nexstar-video="([^"]+)"') _JSONP_RE = re.compile(r'^[^(]*\((.*)\)\s*;?\s*$', re.S) _ID_RE = re.compile(r'[A-Za-z0-9_-]+') _KEY_RE = re.compile(r'[A-Za-z0-9]+') - - +_FEED_ID_RE = re.compile(r'\bfeedid=([A-Za-z0-9_-]+)', re.I) +_LI_RE = re.compile(r']*>(.*?)', re.I | re.S) +_TIME_RANGE_RE = re.compile( + r'(?P\d{1,2})(?::(?P\d{2}))?\s*(?P[ap])?\s*[-–]\s*' + r'(?P\d{1,2})(?::(?P\d{2}))?\s*(?P[ap])\b', re.I) +_KTLA_RANGE_RE = re.compile( + r'(?P\d{1,2})(?::(?P\d{2}))?\s*(?PAM|PM)\s*[–-]\s*' + r'(?P\d{1,2})(?::(?P\d{2}))?\s*(?PAM|PM)\b', re.I) +_KTLA_ROW_RE = re.compile( + r']*class=["\'][^"\']*\bktla-flex-row\b[^"\']*["\'][^>]*>\s*' + r']*>(?P