Add live Dunnellon weather and clean up Roku guide titles
This commit is contained in:
@@ -14,6 +14,7 @@ from fastapi.responses import RedirectResponse, Response, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from .discovery import SERVICE, start_discovery
|
||||
from .weather import NWSWeather
|
||||
|
||||
WEATHER_ID = "weather"
|
||||
HOP_HEADERS = {
|
||||
@@ -49,12 +50,35 @@ def lineup(data):
|
||||
return sorted(channels, key=lambda channel: channel["number"])
|
||||
|
||||
|
||||
def programs(channel_guide):
|
||||
EPISODE_CODE = re.compile(r"\bS(\d{1,2})E(\d{1,3})\b", re.IGNORECASE)
|
||||
RELEASE_SUFFIX = re.compile(
|
||||
r"\b(?:\d{3,4}p|WEB(?:[ ._-]?(?:DL|Rip))?|BluRay|BRRip|HDTV|[xh][ .]?26[45]|HEVC)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def program_title(item, channel_name):
|
||||
program = item.get("program") or {}
|
||||
title = item.get("title") or program.get("title")
|
||||
if not title:
|
||||
return "Off air" if item["type"] == "flex" else "Programming"
|
||||
if program.get("type") != "episode":
|
||||
return title
|
||||
words = re.sub(r"(?<=\w)\.(?=\w)", " ", title)
|
||||
match = EPISODE_CODE.search(words)
|
||||
if not match:
|
||||
return words
|
||||
season, episode = map(int, match.groups())
|
||||
label = f"{channel_name} S{season:02d}E{episode:02d}"
|
||||
detail = RELEASE_SUFFIX.split(words[match.end():], maxsplit=1)[0].strip(" ._-")
|
||||
return f"{label} · {detail}" if detail else label
|
||||
|
||||
|
||||
def programs(channel_guide, channel_name):
|
||||
result = []
|
||||
for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]):
|
||||
title = item.get("title") or (item.get("program") or {}).get("title")
|
||||
result.append({
|
||||
"title": title or ("Off air" if item["type"] == "flex" else "Programming"),
|
||||
"title": program_title(item, channel_name),
|
||||
"start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)),
|
||||
"stop": utc_string(datetime.fromtimestamp(item["stop"] / 1000, UTC)),
|
||||
})
|
||||
@@ -90,6 +114,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
||||
port = int(os.getenv("RETROTV_PORT", "4242"))
|
||||
base_url = f"http://{ip}:{port}"
|
||||
name = os.getenv("RETROTV_NAME", "retroLabs")
|
||||
weather_provider = NWSWeather()
|
||||
upstream = tunarr_url or os.getenv("RETROTV_TUNARR_URL", "http://127.0.0.1:14242")
|
||||
identity = Path(id_file or os.getenv("RETROTV_ID_FILE", "data/server-id"))
|
||||
|
||||
@@ -171,7 +196,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
||||
return {
|
||||
"serverTime": utc_string(now),
|
||||
"channels": [
|
||||
{**channel, "programs": programs(schedules.get(channel["id"], {}))}
|
||||
{**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])}
|
||||
for channel in lineup(channel_data)
|
||||
],
|
||||
}
|
||||
@@ -185,9 +210,10 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
||||
channel_data, schedules = await asyncio.gather(
|
||||
upstream_json("/api/channels"), guide_data(now, 24)
|
||||
)
|
||||
if not any(channel["id"] == channel_id for channel in lineup(channel_data)):
|
||||
channel = next((entry for entry in lineup(channel_data) if entry["id"] == channel_id), None)
|
||||
if channel is None:
|
||||
raise HTTPException(404, "Channel not found")
|
||||
entries = programs(schedules.get(channel_id, {}))
|
||||
entries = programs(schedules.get(channel_id, {}), channel["name"])
|
||||
return {
|
||||
"now": next((p for p in entries if p["start"] <= stamp < p["stop"]), None),
|
||||
"next": next((p for p in entries if p["start"] > stamp), None),
|
||||
@@ -196,7 +222,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
||||
|
||||
@app.get("/api/v1/weather")
|
||||
async def weather():
|
||||
return {"status": "placeholder"}
|
||||
return await weather_provider.read()
|
||||
|
||||
async def proxy(request, path, *, playlist=False, params=None):
|
||||
client = app.state.tunarr
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
fastapi==0.115.14
|
||||
httpx==0.28.1
|
||||
uvicorn==0.34.3
|
||||
astral==3.2
|
||||
|
||||
129
bridge/weather.py
Normal file
129
bridge/weather.py
Normal file
@@ -0,0 +1,129 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
from time import monotonic
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from astral import Observer
|
||||
from astral.sun import sun
|
||||
|
||||
import httpx
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NWSWeather:
|
||||
def __init__(self):
|
||||
self.point = os.getenv("RETROTV_WEATHER_POINT", "").strip()
|
||||
self.location = os.getenv("RETROTV_WEATHER_LOCATION", "Local Weather")
|
||||
self.cache = {}
|
||||
self.retry_at = {}
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
async def _cached(self, client, key, url, ttl, transform):
|
||||
now = monotonic()
|
||||
if now >= self.retry_at.get(key, 0):
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
self.cache[key] = (transform(response.json()), now + ttl)
|
||||
self.retry_at[key] = now + ttl
|
||||
except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as exc:
|
||||
LOG.warning("NWS %s unavailable: %s", key, exc)
|
||||
self.retry_at[key] = now + 60
|
||||
return self.cache.get(key, (None, 0))
|
||||
|
||||
async def read(self):
|
||||
if not self.point:
|
||||
return {"status": "unconfigured", "location": self.location}
|
||||
async with self.lock, httpx.AsyncClient(
|
||||
base_url="https://api.weather.gov", timeout=3,
|
||||
headers={"User-Agent": "retroLabs/0.1", "Accept": "application/geo+json"},
|
||||
) as client:
|
||||
grid, _ = await self._cached(
|
||||
client, "grid", f"/points/{self.point}", 86400,
|
||||
lambda body: body["properties"],
|
||||
)
|
||||
if not grid:
|
||||
return {"status": "unavailable", "location": self.location}
|
||||
|
||||
async def current():
|
||||
stations, _ = await self._cached(
|
||||
client, "stations", grid["observationStations"], 86400,
|
||||
lambda body: [station["properties"]["stationIdentifier"]
|
||||
for station in body["features"][:5]],
|
||||
)
|
||||
candidates = await asyncio.gather(*(
|
||||
self._cached(client, f"observation:{station}",
|
||||
f"/stations/{station}/observations/latest", 300, observation)
|
||||
for station in stations or []
|
||||
))
|
||||
recent = [(value, deadline) for value, deadline in candidates if value]
|
||||
return next(((value, deadline) for value, deadline in recent
|
||||
if deadline > monotonic()), recent[0] if recent else (None, 0))
|
||||
|
||||
parts = await asyncio.gather(
|
||||
current(),
|
||||
self._cached(client, "hourly", grid["forecastHourly"], 600,
|
||||
lambda body: periods(body, 18)),
|
||||
self._cached(client, "forecast", grid["forecast"], 600,
|
||||
lambda body: periods(body, 14)),
|
||||
self._cached(client, "alerts", f"/alerts/active?point={self.point}", 120,
|
||||
lambda body: [alert["properties"] for alert in body["features"]]),
|
||||
)
|
||||
clock = datetime.now(UTC)
|
||||
now = clock.isoformat()
|
||||
local_zone = ZoneInfo(grid["timeZone"])
|
||||
latitude, longitude = map(float, self.point.split(","))
|
||||
daylight = sun(Observer(latitude, longitude),
|
||||
date=clock.astimezone(local_zone).date(), tzinfo=local_zone)
|
||||
observation_data, hourly, forecast, alerts = (value for value, _ in parts)
|
||||
return {
|
||||
"status": "ok", "location": self.location, "source": "National Weather Service",
|
||||
"current": observation_data,
|
||||
"almanac": {key: local_time(daylight[key]) for key in ("sunrise", "sunset")},
|
||||
"hourly": future_periods(hourly, now)[:6],
|
||||
"forecast": future_periods(forecast, now)[:6],
|
||||
"alerts": [
|
||||
{"event": alert["event"], "headline": alert.get("headline")}
|
||||
for alert in alerts or [] if after(alert.get("ends") or alert.get("expires"), now)
|
||||
],
|
||||
"alertsAvailable": parts[3][1] > monotonic(),
|
||||
"stale": any(deadline <= monotonic() for _, deadline in parts[:3]),
|
||||
}
|
||||
|
||||
|
||||
def local_time(value):
|
||||
return value.strftime("%I:%M %p").lstrip("0")
|
||||
|
||||
|
||||
def observation(body):
|
||||
data = body["properties"]
|
||||
celsius = data["temperature"]["value"]
|
||||
if celsius is None:
|
||||
raise ValueError("Observation has no temperature")
|
||||
humidity = data.get("relativeHumidity", {}).get("value")
|
||||
wind = data.get("windSpeed", {}).get("value")
|
||||
return {
|
||||
"temperature": round(celsius * 9 / 5 + 32), "conditions": data["textDescription"],
|
||||
"humidity": None if humidity is None else round(humidity),
|
||||
"windMph": None if wind is None else round(wind * 0.621371),
|
||||
"observedAt": data["timestamp"],
|
||||
}
|
||||
|
||||
|
||||
def periods(body, limit):
|
||||
return [
|
||||
{"name": item["name"] or local_time(datetime.fromisoformat(item["startTime"])), "start": item["startTime"], "end": item["endTime"],
|
||||
"temperature": item["temperature"], "conditions": item["shortForecast"]}
|
||||
for item in body["properties"]["periods"][:limit]
|
||||
]
|
||||
|
||||
|
||||
def after(value, now):
|
||||
return value is not None and datetime.fromisoformat(value) > datetime.fromisoformat(now)
|
||||
|
||||
|
||||
def future_periods(items, now):
|
||||
return [item for item in items or [] if after(item["end"], now)]
|
||||
Reference in New Issue
Block a user