Run the retroLabs backend and add the Roku tuner
This commit is contained in:
7
.dockerignore
Normal file
7
.dockerignore
Normal file
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
.env
|
||||
data
|
||||
.venv
|
||||
**/__pycache__
|
||||
roku
|
||||
tests
|
||||
6
.env.example
Normal file
6
.env.example
Normal file
@@ -0,0 +1,6 @@
|
||||
RETROTV_PORT=4242
|
||||
# Use the LAN IPv4 address of this machine.
|
||||
RETROTV_LAN_IP=192.168.0.203
|
||||
RETROTV_NAME=retroLabs
|
||||
RETROTV_MEDIA_DIR=./data/media
|
||||
TUNARR_LOOPBACK_PORT=14242
|
||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
.env
|
||||
/data/
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
*.zip
|
||||
222
HANDOFF.md
Normal file
222
HANDOFF.md
Normal file
@@ -0,0 +1,222 @@
|
||||
# retroLabs Project Handoff
|
||||
|
||||
Updated: 2026-11-13
|
||||
|
||||
## Status
|
||||
|
||||
The initial bridge, Compose stack, and Roku client are implemented. The backend runs on the current machine at `192.168.0.203:4242`. See [README.md](README.md) to set up programming and build the Roku package. Tunarr programming and physical Roku acceptance remain open. The `visionLabs` reference checkout was unavailable on this machine.
|
||||
|
||||
## Product goal
|
||||
|
||||
Build a Roku app that behaves like an old cable television system while using the owner's personal media library:
|
||||
|
||||
- Automatically find its backend on the local network.
|
||||
- Tune channels with up/down controls and join programs already in progress.
|
||||
- Provide configurable channels, weekly schedules, sequential episodes, marathons, commercials, bumpers, and filler.
|
||||
- Provide a classic program guide and retro channel banner/static transitions.
|
||||
- Include an original WeatherSTAR-inspired channel with live current conditions, forecasts, and alerts.
|
||||
- Keep normal playback local to the LAN; internet access is only needed for live weather and optional metadata.
|
||||
- Run the backend on the current machine.
|
||||
|
||||
The user clarified that **REA means “reverse engineer anything.”** For this project, use that as permission to study behavior, protocols, and permissively licensed open-source implementations. Preserve license notices, build original branding/assets, and do not bypass DRM or copy protected branding.
|
||||
|
||||
## Agreed technical direction
|
||||
|
||||
Use **Tunarr as the scheduling and streaming core**, with a small custom **RetroTV Bridge** and a custom Roku SceneGraph app.
|
||||
|
||||
Do not make FieldStation42's local player the primary runtime. FieldStation42 is a valuable design/configuration reference and may get an importer later, but its player renders locally through MPV and its WeatherStar integration is a web channel. A Roku client needs network HLS and cannot directly embed that browser experience.
|
||||
|
||||
Tunarr was selected because it already supplies:
|
||||
|
||||
- Local-folder, Plex, Jellyfin, and Emby media sources.
|
||||
- Channel creation and EPG data.
|
||||
- Time-slot, sequential, cyclic, and randomized scheduling.
|
||||
- Filler, bumpers, commercials, and mid-roll breaks.
|
||||
- FFmpeg-backed HLS suitable for Roku.
|
||||
- Docker and Linux ARM64 support.
|
||||
|
||||
The RetroTV Bridge owns the Roku-specific integration and keeps Tunarr replaceable.
|
||||
|
||||
## Target architecture
|
||||
|
||||
```text
|
||||
Roku SceneGraph app
|
||||
|
|
||||
| SSDP discovery (UDP 1900)
|
||||
| Roku JSON API + HLS (HTTP, externally exposed port 4242)
|
||||
v
|
||||
RetroTV Bridge / reverse proxy on the current machine
|
||||
|-- stable server identity and health endpoint
|
||||
|-- device pairing/token management
|
||||
|-- Roku-friendly channel and guide API
|
||||
|-- live weather provider/cache
|
||||
|-- special-channel injection (weather initially)
|
||||
|-- proxy/rewrite Tunarr HLS and admin traffic
|
||||
v
|
||||
Tunarr (internal-only port, expected 8000)
|
||||
|-- catalog and schedule database
|
||||
|-- FFmpeg/HLS channel workers
|
||||
`-- read-only media mounts
|
||||
```
|
||||
|
||||
Only one configurable HTTP port should need to be exposed to the LAN. Use `4242` by default because it is memorable and matches FieldStation42's convention. Internal container ports do not count as externally exposed service ports.
|
||||
|
||||
## Discovery behavior
|
||||
|
||||
Do not start with a blind scan of every LAN address.
|
||||
|
||||
1. Try the last saved server URL and verify its stable server ID.
|
||||
2. Send an SSDP `M-SEARCH` request with a retroLabs-specific service type.
|
||||
3. The bridge responds with its identity and `LOCATION`, including its configured HTTP port.
|
||||
4. If multiple servers respond, show a server picker.
|
||||
5. Remember the selected server in the Roku registry.
|
||||
6. Provide manual IP/port entry when multicast is blocked by a guest network, VLAN, or AP isolation.
|
||||
7. A bounded fixed-port `/24` probe may be added later as an optional fallback, not the primary method.
|
||||
|
||||
Proposed discovery identity:
|
||||
|
||||
```text
|
||||
ST: urn:retrolabs:service:retrotv:1
|
||||
LOCATION: http://<server-ip>:4242/api/v1/device.xml
|
||||
USN: uuid:<stable-server-uuid>::urn:retrolabs:service:retrotv:1
|
||||
```
|
||||
|
||||
## Initial bridge API contract
|
||||
|
||||
Keep this versioned and small:
|
||||
|
||||
```text
|
||||
GET /api/v1/health
|
||||
GET /api/v1/server
|
||||
POST /api/v1/pair/start
|
||||
POST /api/v1/pair/complete
|
||||
GET /api/v1/channels
|
||||
GET /api/v1/channels/{channelId}/now
|
||||
GET /api/v1/guide?from=<iso>&hours=<n>
|
||||
GET /api/v1/weather
|
||||
GET /stream/{channelId}/master.m3u8
|
||||
GET /admin/...
|
||||
```
|
||||
|
||||
The bridge should normalize Tunarr responses into compact JSON rather than making BrightScript parse M3U/XMLTV or depend on Tunarr's internal API shapes.
|
||||
|
||||
## Roku app behavior
|
||||
|
||||
Use classic BrightScript and SceneGraph for broad device compatibility.
|
||||
|
||||
Core screens/components:
|
||||
|
||||
- Discovery/pairing screen.
|
||||
- Full-screen tuner using a SceneGraph `Video` node and HLS.
|
||||
- Channel banner with number, name, now/next, progress, and clock.
|
||||
- Program guide.
|
||||
- Native weather channel.
|
||||
- Settings/server diagnostics.
|
||||
|
||||
Remote behavior for the first milestone:
|
||||
|
||||
- Up/down: previous/next channel.
|
||||
- OK: show or extend the channel banner.
|
||||
- Star: open the guide/settings menu.
|
||||
- Replay or left: previous channel, if reliable across the target devices.
|
||||
- Back: leave the guide first, then exit playback/app.
|
||||
|
||||
The server clock is authoritative. Tuning a linear channel must join the current program at the correct wall-clock point rather than restarting it. Two Roku devices tuning the same channel should see approximately the same moment.
|
||||
|
||||
## Weather channel
|
||||
|
||||
Implement weather natively in SceneGraph rather than attempting to embed a web page.
|
||||
|
||||
Initial rotation:
|
||||
|
||||
- Current conditions.
|
||||
- Hourly forecast.
|
||||
- Extended forecast.
|
||||
- Sunrise/sunset and basic almanac values.
|
||||
- Active alerts with an interrupting crawl/banner.
|
||||
|
||||
Use a provider adapter. Start with the US National Weather Service when the configured location is in the United States, cache responses on the bridge, and retain the last good observation during temporary outages. Add an international provider later. Radar animation is a later milestone because it adds tile-provider, attribution, and performance decisions.
|
||||
|
||||
The visual treatment should evoke late-1980s/1990s cable weather systems while using an original name, layout, graphics, and licensed/user-supplied music.
|
||||
|
||||
## FieldStation42 compatibility, later
|
||||
|
||||
An optional importer can map FieldStation42 concepts without running its player:
|
||||
|
||||
- `standard` and `loop` stations -> Tunarr channels.
|
||||
- `content_dir` -> local media sources/playlists.
|
||||
- `commercial_dir` and `bump_dir` -> filler lists.
|
||||
- Hourly/day rules -> Tunarr time slots.
|
||||
- Streaming stations -> remote-stream channels.
|
||||
- Guide/weather/web stations -> native Roku special channels or a clear unsupported warning.
|
||||
|
||||
Do not block the first milestone on this importer.
|
||||
|
||||
## Planned project layout
|
||||
|
||||
The new project may adjust names, but start near this shape:
|
||||
|
||||
```text
|
||||
retroLabs/
|
||||
roku/ # manifest, source/, components/, images/
|
||||
bridge/ # discovery, normalized API, weather, proxy
|
||||
deploy/ # Compose/service configuration
|
||||
tests/ # API/contract tests and fixtures
|
||||
docs/
|
||||
README.md
|
||||
HANDOFF.md
|
||||
```
|
||||
|
||||
Recommended bridge implementation: Python 3.12+ with FastAPI/uvicorn because the existing Roku workspace already uses Python bridges and it keeps SSDP, weather caching, and API work straightforward. Keep the reverse proxy/HLS path streaming; never buffer entire video segments into memory.
|
||||
|
||||
## First vertical slice
|
||||
|
||||
The first milestone is complete only when all of the following work on a real Roku and the current machine:
|
||||
|
||||
1. A Compose stack starts Tunarr and the RetroTV Bridge.
|
||||
2. The bridge exposes `GET /api/v1/health` on LAN port `4242`.
|
||||
3. The Roku discovers the bridge automatically on the same subnet and remembers it.
|
||||
4. Tunarr indexes one small read-only test-media folder.
|
||||
5. Two channels appear in the Roku lineup.
|
||||
6. Both channels play through the Roku `Video` node as HLS.
|
||||
7. Up/down changes channels and shows a basic channel banner.
|
||||
8. Tuning joins the program in progress based on server time.
|
||||
9. A basic guide lists now/next programming.
|
||||
10. A placeholder native weather channel appears in the lineup and can later be wired to live data.
|
||||
11. Rebooting the Roku or backend recovers without reconfiguration.
|
||||
|
||||
Defer polished CRT effects, advanced guide styling, radar, a FieldStation importer, and Roku Store distribution until this slice is stable.
|
||||
|
||||
## Current deployment
|
||||
|
||||
The current machine runs Linux x86-64 and Docker Compose. The bridge listens on LAN TCP port 4242, with Tunarr reached internally through host loopback port 14242. Compose mounts the configured media path read-only and persists application state in named volumes. The default media directory is `data/media/`. Use a compatible H.264/AAC sample first and verify playback before enabling hardware transcoding.
|
||||
|
||||
## Existing local reference
|
||||
|
||||
The sibling project `../visionLabs` already demonstrates:
|
||||
|
||||
- Roku BrightScript/SceneGraph packaging.
|
||||
- LAN HLS playback through a Python/FFmpeg bridge.
|
||||
- A simple ZIP build script.
|
||||
- Real-device behavior when direct upstream streams are not Roku-compatible.
|
||||
|
||||
Study it as a reference, especially its HLS playback and packaging, but do not couple retroLabs to it or change its files.
|
||||
|
||||
Roku permits only one sideloaded development app at a time. Testing retroLabs will temporarily replace the installed development build of visionLabs on the device, but both source trees and ZIP artifacts remain independent. Move to a Roku beta/public package later if both apps need to remain installed concurrently.
|
||||
|
||||
## Remaining setup and acceptance
|
||||
|
||||
Add a media source and program two channels in Tunarr, then sideload the Roku ZIP and run the first vertical slice checks. Set the weather location when connecting the live provider.
|
||||
|
||||
## Primary references
|
||||
|
||||
- FieldStation42: https://fieldstation42.com/docs/
|
||||
- FieldStation42 channel recipes: https://fieldstation42.com/docs/guides/channel-recipes/
|
||||
- Tunarr: https://tunarr.com/
|
||||
- Tunarr local media: https://tunarr.com/configure/media_sources/local/
|
||||
- Tunarr scheduling: https://tunarr.com/configure/scheduling/
|
||||
- Tunarr HLS/transcoding: https://tunarr.com/configure/channels/transcoding/
|
||||
- Roku UDP sockets: https://developer.roku.com/dev/docs/rodatagramsocket
|
||||
- Roku streaming formats: https://developer.roku.com/dev/docs/media
|
||||
- National Weather Service API: https://www.weather.gov/documentation/services-web-api
|
||||
- MIT-licensed Roku reference, Nostalgex: https://github.com/chadMueller/Nostalgex/tree/main/roku
|
||||
43
README.md
43
README.md
@@ -0,0 +1,43 @@
|
||||
# retroLabs
|
||||
|
||||
retroLabs runs a private cable-style TV lineup from your media library. Tunarr handles programming and linear HLS. The RetroTV Bridge serves the Roku app and forwards Tunarr's web UI over the same LAN port.
|
||||
|
||||
## Set up programming
|
||||
|
||||
The stack on this machine uses [Tunarr at 192.168.0.203:4242](http://192.168.0.203:4242/web/).
|
||||
|
||||
1. Put a few compatible test videos in `data/media/`, or set `RETROTV_MEDIA_DIR` in `.env` to an existing library and run `docker compose up -d`. The directory is mounted read-only at `/media` inside Tunarr.
|
||||
2. In Tunarr's media sources, add a Local source and a library under `/media`. Start a scan. You can also connect an existing Plex, Jellyfin, or Emby source.
|
||||
3. Create two channels with different numbers. Use HLS as the channel's stream mode for the initial Roku test. Add programming to each channel, save, and use Tunarr's Guide and Watch actions to verify the schedule and playback.
|
||||
4. Open the [Roku channel lineup](http://192.168.0.203:4242/api/v1/channels) to check that both channels and the native weather placeholder are present.
|
||||
|
||||
See the [Tunarr setup walkthrough](https://tunarr.com/getting-started/setup/) and [scheduling documentation](https://tunarr.com/configure/scheduling/) for time slots, sequential programming, and filler.
|
||||
|
||||
## Start the stack on another checkout
|
||||
|
||||
Requires Linux, Docker with Compose, and an available LAN IPv4 address.
|
||||
|
||||
```sh
|
||||
mkdir -p data/media
|
||||
cp .env.example .env
|
||||
# Set RETROTV_LAN_IP in .env to this machine's LAN IPv4.
|
||||
docker compose up -d --build
|
||||
docker compose ps
|
||||
docker compose logs -f bridge tunarr
|
||||
```
|
||||
|
||||
Use `http://<LAN-IP>:4242/web/` for the programming UI and `/api/v1/health` for the bridge health check. Tunarr's internal port 8000 is published only on host loopback port 14242. The bridge uses host networking for SSDP on UDP 1900 and binds HTTP to the configured LAN IP. Admin and device access currently share the trusted LAN with no bridge-level authentication. Compose persists Tunarr's configuration and the bridge's UUID in named volumes.
|
||||
|
||||
## Roku
|
||||
|
||||
Run `./roku/build.sh` to produce `roku/dist/retroLabs.zip`. See [Roku setup and controls](roku/README.md) for sideloading and manual server entry.
|
||||
|
||||
## Backend contract tests
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -r bridge/requirements.txt
|
||||
.venv/bin/python -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
The tests exercise lineup and guide normalization, server ID persistence, Tunarr admin writes, and HLS manifest/segment forwarding. Physical Roku discovery, playback, live tuning, and reboot recovery are the remaining device acceptance checks. Pairing and live weather are deferred.
|
||||
|
||||
282
bridge/app.py
Normal file
282
bridge/app.py
Normal file
@@ -0,0 +1,282 @@
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from urllib.parse import urljoin, urlsplit
|
||||
from uuid import UUID, uuid4
|
||||
from xml.etree import ElementTree as XML
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
from fastapi.responses import RedirectResponse, Response, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from .discovery import SERVICE, start_discovery
|
||||
|
||||
WEATHER_ID = "weather"
|
||||
HOP_HEADERS = {
|
||||
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
||||
"te", "trailer", "transfer-encoding", "upgrade",
|
||||
}
|
||||
URI_ATTRIBUTE = re.compile(r'\bURI="([^"]+)"')
|
||||
|
||||
|
||||
def utc_string(value: datetime):
|
||||
return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def lineup(data):
|
||||
channels = [
|
||||
{
|
||||
"id": channel["id"],
|
||||
"number": channel["number"],
|
||||
"name": channel["name"],
|
||||
"type": "linear",
|
||||
"streamUrl": f'/stream/{channel["id"]}/master.m3u8',
|
||||
}
|
||||
for channel in data if not channel.get("stealth")
|
||||
]
|
||||
used = {channel["number"] for channel in channels}
|
||||
number = 99
|
||||
while number in used:
|
||||
number += 1
|
||||
channels.append({
|
||||
"id": WEATHER_ID, "number": number, "name": "retroLabs Weather",
|
||||
"type": "weather", "streamUrl": None,
|
||||
})
|
||||
return sorted(channels, key=lambda channel: channel["number"])
|
||||
|
||||
|
||||
def programs(channel_guide):
|
||||
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"),
|
||||
"start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)),
|
||||
"stop": utc_string(datetime.fromtimestamp(item["stop"] / 1000, UTC)),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def rewrite_playlist(body, upstream_url):
|
||||
def rewrite(uri):
|
||||
target = urlsplit(urljoin(str(upstream_url), uri))
|
||||
if target.netloc != urlsplit(str(upstream_url)).netloc:
|
||||
return uri
|
||||
return target.path + (f"?{target.query}" if target.query else "")
|
||||
|
||||
lines = []
|
||||
for line in body.splitlines():
|
||||
if line.startswith("#"):
|
||||
line = URI_ATTRIBUTE.sub(lambda match: f'URI="{rewrite(match[1])}"', line)
|
||||
elif line.strip():
|
||||
line = rewrite(line.strip())
|
||||
lines.append(line)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def forwarded_headers(headers, excluded):
|
||||
connection = set(headers.get("connection", "").lower().replace(" ", "").split(","))
|
||||
blocked = HOP_HEADERS | excluded | connection
|
||||
return [(key.decode("latin-1"), value.decode("latin-1"))
|
||||
for key, value in headers.raw if key.decode("latin-1").lower() not in blocked]
|
||||
|
||||
|
||||
def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
||||
ip = os.getenv("RETROTV_LAN_IP", "127.0.0.1")
|
||||
port = int(os.getenv("RETROTV_PORT", "4242"))
|
||||
base_url = f"http://{ip}:{port}"
|
||||
name = os.getenv("RETROTV_NAME", "retroLabs")
|
||||
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"))
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
identity.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not identity.exists():
|
||||
temporary = identity.with_suffix(".tmp")
|
||||
temporary.write_text(f"{uuid4()}\n")
|
||||
temporary.replace(identity)
|
||||
app.state.server_id = str(UUID(identity.read_text().strip()))
|
||||
ssdp = await start_discovery(ip, app.state.server_id, base_url) if discover else None
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=upstream, transport=transport, trust_env=False,
|
||||
timeout=httpx.Timeout(120, connect=5),
|
||||
) as client:
|
||||
app.state.tunarr = client
|
||||
yield
|
||||
finally:
|
||||
if ssdp:
|
||||
ssdp.close()
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
async def upstream_json(path, **params):
|
||||
try:
|
||||
response = await app.state.tunarr.get(path, params=params, timeout=10)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
raise HTTPException(502, "Tunarr did not return usable data") from exc
|
||||
|
||||
async def guide_data(start, hours):
|
||||
return await upstream_json(
|
||||
"/api/guide/channels", dateFrom=utc_string(start),
|
||||
dateTo=utc_string(start + timedelta(hours=hours)),
|
||||
)
|
||||
|
||||
@app.get("/api/v1/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api/v1/server")
|
||||
async def server():
|
||||
return {"id": app.state.server_id, "name": name, "baseUrl": base_url}
|
||||
|
||||
@app.get("/api/v1/device.xml")
|
||||
async def device():
|
||||
root = XML.Element("root", xmlns="urn:schemas-upnp-org:device-1-0")
|
||||
spec = XML.SubElement(root, "specVersion")
|
||||
XML.SubElement(spec, "major").text = "1"
|
||||
XML.SubElement(spec, "minor").text = "0"
|
||||
node = XML.SubElement(root, "device")
|
||||
XML.SubElement(node, "deviceType").text = "urn:retrolabs:device:retrotv:1"
|
||||
XML.SubElement(node, "friendlyName").text = name
|
||||
XML.SubElement(node, "UDN").text = f"uuid:{app.state.server_id}"
|
||||
services = XML.SubElement(node, "serviceList")
|
||||
service = XML.SubElement(services, "service")
|
||||
XML.SubElement(service, "serviceType").text = SERVICE
|
||||
return Response(XML.tostring(root, encoding="utf-8", xml_declaration=True),
|
||||
media_type="application/xml")
|
||||
|
||||
@app.get("/api/v1/channels")
|
||||
async def channels():
|
||||
return {"channels": lineup(await upstream_json("/api/channels"))}
|
||||
|
||||
@app.get("/api/v1/guide")
|
||||
async def guide(
|
||||
start: datetime | None = Query(None, alias="from"),
|
||||
hours: int = Query(3, ge=1, le=24),
|
||||
):
|
||||
now = datetime.now(UTC)
|
||||
if start is not None and start.utcoffset() is None:
|
||||
raise HTTPException(422, "Guide start must include a timezone")
|
||||
channel_data, schedules = await asyncio.gather(
|
||||
upstream_json("/api/channels"), guide_data(start or now, hours)
|
||||
)
|
||||
return {
|
||||
"serverTime": utc_string(now),
|
||||
"channels": [
|
||||
{**channel, "programs": programs(schedules.get(channel["id"], {}))}
|
||||
for channel in lineup(channel_data)
|
||||
],
|
||||
}
|
||||
|
||||
@app.get("/api/v1/channels/{channel_id}/now")
|
||||
async def now_next(channel_id: str):
|
||||
now = datetime.now(UTC)
|
||||
stamp = utc_string(now)
|
||||
if channel_id == WEATHER_ID:
|
||||
return {"now": None, "next": None, "serverTime": stamp}
|
||||
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)):
|
||||
raise HTTPException(404, "Channel not found")
|
||||
entries = programs(schedules.get(channel_id, {}))
|
||||
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),
|
||||
"serverTime": stamp,
|
||||
}
|
||||
|
||||
@app.get("/api/v1/weather")
|
||||
async def weather():
|
||||
return {"status": "placeholder"}
|
||||
|
||||
async def proxy(request, path, *, playlist=False, params=None):
|
||||
client = app.state.tunarr
|
||||
headers = forwarded_headers(
|
||||
request.headers, {"host", "content-length", "x-forwarded-for",
|
||||
"x-forwarded-host", "x-forwarded-proto"}
|
||||
)
|
||||
if request.client:
|
||||
headers.append(("x-forwarded-for", request.client.host))
|
||||
headers.extend([
|
||||
("x-forwarded-host", request.url.netloc),
|
||||
("x-forwarded-proto", request.url.scheme),
|
||||
])
|
||||
has_body = "content-length" in request.headers or "transfer-encoding" in request.headers
|
||||
raw_path = request.scope["raw_path"] if path == request.url.path else path.encode("ascii")
|
||||
target = httpx.Request(
|
||||
request.method, client.base_url.copy_with(raw_path=raw_path),
|
||||
params=params if params is not None else request.url.query,
|
||||
headers=headers, content=request.stream() if has_body else None,
|
||||
)
|
||||
try:
|
||||
response = await client.send(target, stream=True)
|
||||
client.cookies.clear()
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(502, "Tunarr is unavailable") from exc
|
||||
is_playlist = playlist and request.method == "GET" and response.is_success
|
||||
excluded = {"date", "server"}
|
||||
if is_playlist:
|
||||
excluded.update({"content-length", "content-encoding", "etag"})
|
||||
response_headers = forwarded_headers(response.headers, excluded)
|
||||
if is_playlist:
|
||||
try:
|
||||
await response.aread()
|
||||
body = rewrite_playlist(response.text, response.url)
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(502, "Tunarr playlist could not be read") from exc
|
||||
finally:
|
||||
await response.aclose()
|
||||
result = Response(body.encode("utf-8"), status_code=response.status_code)
|
||||
response_headers = [(k, v) for k, v in response_headers if k.lower() != "content-type"]
|
||||
response_headers.append(("content-type", "application/vnd.apple.mpegurl"))
|
||||
else:
|
||||
async def body_stream():
|
||||
try:
|
||||
async for chunk in response.aiter_raw():
|
||||
yield chunk
|
||||
finally:
|
||||
await response.aclose()
|
||||
|
||||
result = StreamingResponse(body_stream(), status_code=response.status_code,
|
||||
background=BackgroundTask(response.aclose))
|
||||
for key, value in response_headers:
|
||||
if key.lower() == "location":
|
||||
location = urlsplit(value)
|
||||
if location.netloc == client.base_url.netloc.decode():
|
||||
value = location.path or "/"
|
||||
if location.query:
|
||||
value += "?" + location.query
|
||||
if location.fragment:
|
||||
value += "#" + location.fragment
|
||||
result.raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
|
||||
return result
|
||||
|
||||
@app.api_route("/stream/{channel_id}/master.m3u8", methods=["GET", "HEAD"])
|
||||
async def tune(request: Request, channel_id: UUID):
|
||||
return await proxy(request, f"/stream/channels/{channel_id}.m3u8", playlist=True)
|
||||
|
||||
@app.get("/admin", include_in_schema=False)
|
||||
@app.get("/admin/", include_in_schema=False)
|
||||
async def admin():
|
||||
return RedirectResponse("/")
|
||||
|
||||
@app.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
|
||||
async def tunarr_admin_and_assets(request: Request, path: str):
|
||||
if path == "api/v1" or path.startswith("api/v1/"):
|
||||
raise HTTPException(404, "Unknown retroLabs endpoint")
|
||||
return await proxy(request, f"/{path}",
|
||||
playlist=path.startswith("stream/") and path.endswith(".m3u8"))
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
55
bridge/discovery.py
Normal file
55
bridge/discovery.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
|
||||
SERVICE = "urn:retrolabs:service:retrotv:1"
|
||||
GROUP = "239.255.255.250"
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Discovery(asyncio.DatagramProtocol):
|
||||
def __init__(self, server_id: str, base_url: str):
|
||||
self.transport = None
|
||||
self.reply = (
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"CACHE-CONTROL: max-age=120\r\n"
|
||||
"EXT:\r\n"
|
||||
f"LOCATION: {base_url}/api/v1/device.xml\r\n"
|
||||
"SERVER: Linux UPnP/1.1 retroLabs/0.1\r\n"
|
||||
f"ST: {SERVICE}\r\n"
|
||||
f"USN: uuid:{server_id}::{SERVICE}\r\n\r\n"
|
||||
).encode("ascii")
|
||||
|
||||
def connection_made(self, transport):
|
||||
self.transport = transport
|
||||
|
||||
def datagram_received(self, data, addr):
|
||||
lines = data.decode("ascii", errors="ignore").splitlines()
|
||||
if not lines or lines[0].strip().upper() != "M-SEARCH * HTTP/1.1":
|
||||
return
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
name, _, value = line.partition(":")
|
||||
headers[name.strip().lower()] = value.strip().lower()
|
||||
if headers.get("man") == '"ssdp:discover"' and headers.get("st") == SERVICE:
|
||||
self.transport.sendto(self.reply, addr)
|
||||
|
||||
|
||||
async def start_discovery(ip: str, server_id: str, base_url: str):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("", 1900))
|
||||
sock.setsockopt(
|
||||
socket.IPPROTO_IP,
|
||||
socket.IP_ADD_MEMBERSHIP,
|
||||
socket.inet_aton(GROUP) + socket.inet_aton(ip),
|
||||
)
|
||||
transport, _ = await asyncio.get_running_loop().create_datagram_endpoint(
|
||||
lambda: Discovery(server_id, base_url), sock=sock
|
||||
)
|
||||
return transport
|
||||
except OSError:
|
||||
sock.close()
|
||||
LOG.exception("SSDP unavailable. The Roku can connect using manual server entry.")
|
||||
return None
|
||||
3
bridge/requirements.txt
Normal file
3
bridge/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
fastapi==0.115.14
|
||||
httpx==0.28.1
|
||||
uvicorn==0.34.3
|
||||
37
compose.yaml
Normal file
37
compose.yaml
Normal file
@@ -0,0 +1,37 @@
|
||||
services:
|
||||
tunarr:
|
||||
image: ghcr.io/chrisbenincasa/tunarr:2026.11.2@sha256:50919e89db8c60f7fe9f3561f84ef77fb5710ccaac5db5599e9b9993c519dea9
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
TZ: America/New_York
|
||||
TUNARR_SERVER_TRUST_PROXY: "true"
|
||||
ports:
|
||||
- "127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242}:8000"
|
||||
volumes:
|
||||
- tunarr-data:/config/tunarr
|
||||
- type: bind
|
||||
source: ${RETROTV_MEDIA_DIR:-./data/media}
|
||||
target: /media
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
bridge:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: deploy/bridge.Dockerfile
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
depends_on:
|
||||
- tunarr
|
||||
environment:
|
||||
RETROTV_LAN_IP: ${RETROTV_LAN_IP:?Set RETROTV_LAN_IP in .env}
|
||||
RETROTV_PORT: ${RETROTV_PORT:-4242}
|
||||
RETROTV_NAME: ${RETROTV_NAME:-retroLabs}
|
||||
RETROTV_TUNARR_URL: http://127.0.0.1:${TUNARR_LOOPBACK_PORT:-14242}
|
||||
RETROTV_ID_FILE: /state/server-id
|
||||
volumes:
|
||||
- bridge-data:/state
|
||||
|
||||
volumes:
|
||||
tunarr-data:
|
||||
bridge-data:
|
||||
7
deploy/bridge.Dockerfile
Normal file
7
deploy/bridge.Dockerfile
Normal file
@@ -0,0 +1,7 @@
|
||||
FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
COPY bridge/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY bridge ./bridge
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
CMD ["sh", "-c", "exec uvicorn bridge.app:app --host \"$RETROTV_LAN_IP\" --port \"$RETROTV_PORT\" --no-proxy-headers"]
|
||||
1
roku/.gitignore
vendored
Normal file
1
roku/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/dist/
|
||||
28
roku/README.md
Normal file
28
roku/README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# retroLabs on Roku
|
||||
|
||||
Build the sideload ZIP from the project root.
|
||||
|
||||
```sh
|
||||
./roku/build.sh
|
||||
unzip -t roku/dist/retroLabs.zip
|
||||
```
|
||||
|
||||
With the bridge running, put the Roku and this server on the same network.
|
||||
Enable Roku Developer Mode and open the Development Application Installer at
|
||||
`http://<roku-ip>` in a browser. Sign in as `rokudev` with the password you set
|
||||
when enabling Developer Mode, then upload and install `roku/dist/retroLabs.zip`.
|
||||
Installing a development ZIP replaces the current sideloaded app.
|
||||
|
||||
On first launch, the app searches for the bridge. If multicast discovery is
|
||||
unavailable, select **Enter server address** and enter the bridge host's LAN
|
||||
IP or hostname. Use `IP:port` if the bridge uses a port other than `4242`.
|
||||
|
||||
- **Up / Down** tunes the previous or next channel.
|
||||
- **OK** shows the banner or retries a failed channel.
|
||||
- **Left / Replay** returns to the last channel.
|
||||
- **Star** opens the program guide, channel refresh, and server selection.
|
||||
- **Back** closes the guide or menu, then exits from the tuner.
|
||||
|
||||
The guide shows current and upcoming titles. The weather channel is a native
|
||||
placeholder. Playback starts from the live HLS playlist supplied by the bridge.
|
||||
SSDP discovery, playback, and live timing require validation on Roku hardware.
|
||||
13
roku/build.sh
Executable file
13
roku/build.sh
Executable file
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
app_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
dist_dir="$app_dir/dist"
|
||||
mkdir -p "$dist_dir"
|
||||
archive_dir="$(mktemp -d "$dist_dir/.build.XXXXXX")"
|
||||
trap 'rm -rf -- "$archive_dir"' EXIT
|
||||
|
||||
cd -- "$app_dir"
|
||||
zip -q -r "$archive_dir/retroLabs.zip" manifest source components
|
||||
mv -f -- "$archive_dir/retroLabs.zip" "$dist_dir/retroLabs.zip"
|
||||
printf '%s\n' "$dist_dir/retroLabs.zip"
|
||||
132
roku/components/BridgeTask.brs
Normal file
132
roku/components/BridgeTask.brs
Normal file
@@ -0,0 +1,132 @@
|
||||
sub init()
|
||||
m.top.functionName = "runRequest"
|
||||
end sub
|
||||
|
||||
sub runRequest()
|
||||
request = m.top.request
|
||||
if request.kind = "discover"
|
||||
registry = CreateObject("roRegistrySection", "server")
|
||||
baseUrl = request.baseUrl
|
||||
serverId = request.serverId
|
||||
if request.useSaved
|
||||
baseUrl = registry.Read("url")
|
||||
serverId = registry.Read("id")
|
||||
end if
|
||||
servers = []
|
||||
if baseUrl <> ""
|
||||
saved = readServer(baseUrl)
|
||||
if saved <> invalid and (serverId = "" or saved.id = serverId)
|
||||
servers.Push(saved)
|
||||
end if
|
||||
end if
|
||||
|
||||
if servers.Count() = 0 and request.manual = false
|
||||
for each baseUrl in discoverUrls()
|
||||
server = readServer(baseUrl)
|
||||
if server <> invalid
|
||||
if server.id = serverId
|
||||
servers = [server]
|
||||
exit for
|
||||
end if
|
||||
duplicate = false
|
||||
for each existing in servers
|
||||
if existing.id = server.id then duplicate = true
|
||||
end for
|
||||
if not duplicate then servers.Push(server)
|
||||
end if
|
||||
end for
|
||||
end if
|
||||
m.top.result = {servers: servers}
|
||||
else if request.kind = "connect"
|
||||
registry = CreateObject("roRegistrySection", "server")
|
||||
registry.Write("url", request.server.baseUrl)
|
||||
registry.Write("id", request.server.id)
|
||||
registry.Flush()
|
||||
m.top.result = {data: readJson(request.server.baseUrl + "/api/v1/channels")}
|
||||
else
|
||||
m.top.result = {data: readJson(request.url)}
|
||||
end if
|
||||
end sub
|
||||
|
||||
function readServer(baseUrl as string) as dynamic
|
||||
data = readJson(baseUrl + "/api/v1/server")
|
||||
if data = invalid or GetInterface(data.id, "ifString") = invalid or data.id = "" then return invalid
|
||||
if GetInterface(data.name, "ifString") = invalid then return invalid
|
||||
return {id: data.id, name: data.name, baseUrl: baseUrl}
|
||||
end function
|
||||
|
||||
function readJson(url as string) as dynamic
|
||||
port = CreateObject("roMessagePort")
|
||||
transfer = CreateObject("roUrlTransfer")
|
||||
transfer.SetMessagePort(port)
|
||||
transfer.SetUrl(url)
|
||||
transfer.AddHeader("Accept", "application/json")
|
||||
if not transfer.AsyncGetToString() then return invalid
|
||||
event = Wait(3500, port)
|
||||
if Type(event) = "roUrlEvent" and event.GetResponseCode() = 200
|
||||
data = ParseJson(event.GetString())
|
||||
if GetInterface(data, "ifAssociativeArray") <> invalid then return data
|
||||
end if
|
||||
transfer.AsyncCancel()
|
||||
return invalid
|
||||
end function
|
||||
|
||||
function discoverUrls() as object
|
||||
urls = []
|
||||
socket = CreateObject("roDatagramSocket")
|
||||
port = CreateObject("roMessagePort")
|
||||
socket.SetMessagePort(port)
|
||||
localAddress = CreateObject("roSocketAddress")
|
||||
if not localAddress.SetAddress("0.0.0.0:0") then return urls
|
||||
if not socket.SetAddress(localAddress) then return urls
|
||||
|
||||
multicast = CreateObject("roSocketAddress")
|
||||
if not multicast.SetAddress("239.255.255.250:1900") then return urls
|
||||
if not socket.SetSendToAddress(multicast) then return urls
|
||||
socket.NotifyReadable(true)
|
||||
|
||||
serviceType = "urn:retrolabs:service:retrotv:1"
|
||||
newline = Chr(13) + Chr(10)
|
||||
request = "M-SEARCH * HTTP/1.1" + newline
|
||||
request += "HOST: 239.255.255.250:1900" + newline
|
||||
request += "MAN: " + Chr(34) + "ssdp:discover" + Chr(34) + newline
|
||||
request += "MX: 1" + newline
|
||||
request += "ST: " + serviceType + newline + newline
|
||||
socket.SendStr(request)
|
||||
|
||||
timer = CreateObject("roTimespan")
|
||||
timer.Mark()
|
||||
while timer.TotalMilliseconds() < 1800 and urls.Count() < 5
|
||||
event = Wait(1800 - timer.TotalMilliseconds() + 1, port)
|
||||
if Type(event) = "roSocketEvent" and socket.IsReadable()
|
||||
baseUrl = responseUrl(socket.ReceiveStr(2048), serviceType)
|
||||
if baseUrl <> ""
|
||||
duplicate = false
|
||||
for each existing in urls
|
||||
if existing = baseUrl then duplicate = true
|
||||
end for
|
||||
if not duplicate then urls.Push(baseUrl)
|
||||
end if
|
||||
end if
|
||||
end while
|
||||
socket.Close()
|
||||
return urls
|
||||
end function
|
||||
|
||||
function responseUrl(response as string, serviceType as string) as string
|
||||
lines = response.Split(Chr(10))
|
||||
if lines.Count() = 0 or Left(lines[0], 12) <> "HTTP/1.1 200" then return ""
|
||||
headers = {}
|
||||
for each line in lines
|
||||
separator = Instr(1, line, ":")
|
||||
if separator > 1
|
||||
key = LCase(Left(line, separator - 1).Trim())
|
||||
headers[key] = Mid(line, separator + 1).Replace(Chr(13), "").Trim()
|
||||
end if
|
||||
end for
|
||||
if headers.st <> serviceType or headers.location = invalid then return ""
|
||||
pattern = CreateObject("roRegex", "^(http://[A-Za-z0-9.-]+:[0-9]{1,5})/api/v1/device[.]xml$", "i")
|
||||
match = pattern.Match(headers.location)
|
||||
if match.Count() = 2 then return match[1]
|
||||
return ""
|
||||
end function
|
||||
8
roku/components/BridgeTask.xml
Normal file
8
roku/components/BridgeTask.xml
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<component name="BridgeTask" extends="Task">
|
||||
<interface>
|
||||
<field id="request" type="assocarray" />
|
||||
<field id="result" type="assocarray" />
|
||||
</interface>
|
||||
<script type="text/brightscript" uri="pkg:/components/BridgeTask.brs" />
|
||||
</component>
|
||||
105
roku/components/Guide.brs
Normal file
105
roku/components/Guide.brs
Normal file
@@ -0,0 +1,105 @@
|
||||
sub showPanel(mode as string, title as string, status as string, titles as object)
|
||||
m.panelMode = mode
|
||||
m.panelTitle.text = title
|
||||
m.panelStatus.text = status
|
||||
content = CreateObject("roSGNode", "ContentNode")
|
||||
for each labelText in titles
|
||||
item = content.CreateChild("ContentNode")
|
||||
item.title = labelText
|
||||
end for
|
||||
m.menu.content = content
|
||||
m.menu.jumpToItem = 0
|
||||
m.panel.visible = true
|
||||
if titles.Count() = 0
|
||||
m.top.SetFocus(true)
|
||||
else
|
||||
m.menu.SetFocus(true)
|
||||
end if
|
||||
end sub
|
||||
|
||||
sub closePanel()
|
||||
m.panelMode = ""
|
||||
m.panel.visible = false
|
||||
m.top.SetFocus(true)
|
||||
end sub
|
||||
|
||||
sub onMenuSelect(event as object)
|
||||
index = event.GetData()
|
||||
if m.panelMode = "servers"
|
||||
if index < m.servers.Count()
|
||||
connectServer(m.servers[index])
|
||||
else if index = m.servers.Count()
|
||||
openAddressDialog()
|
||||
else
|
||||
findServer("", false)
|
||||
end if
|
||||
else if m.panelMode = "lineup"
|
||||
if index = 0
|
||||
loadLineup()
|
||||
else
|
||||
findServer("", false)
|
||||
end if
|
||||
else if m.panelMode = "options"
|
||||
if index = 0
|
||||
openGuide()
|
||||
else if index = 1
|
||||
m.channelIndex = -1
|
||||
m.video.control = "stop"
|
||||
m.retryTimer.control = "stop"
|
||||
loadLineup()
|
||||
else
|
||||
findServer("", false)
|
||||
end if
|
||||
else if m.panelMode = "guide"
|
||||
id = m.guideIds[index]
|
||||
for i = 0 to m.channels.Count() - 1
|
||||
if m.channels[i].id = id
|
||||
closePanel()
|
||||
tune(i)
|
||||
exit for
|
||||
end if
|
||||
end for
|
||||
else if m.panelMode = "guideError"
|
||||
openGuide()
|
||||
end if
|
||||
end sub
|
||||
|
||||
sub openGuide()
|
||||
if m.guideRequest <> invalid
|
||||
m.guideRequest.UnobserveFieldScoped("result")
|
||||
m.guideRequest.control = "stop"
|
||||
end if
|
||||
showPanel("guideLoading", "Program guide", "Loading the schedule…", [])
|
||||
m.guideRequest = startRequest({url: m.server.baseUrl + "/api/v1/guide?hours=3"}, "onGuide")
|
||||
end sub
|
||||
|
||||
sub onGuide(event as object)
|
||||
m.guideRequest = invalid
|
||||
if m.panelMode <> "guideLoading" then return
|
||||
data = event.GetData().data
|
||||
if data = invalid or GetInterface(data.channels, "ifArray") = invalid
|
||||
showPanel("guideError", "Program guide", "Could not load the schedule.", ["Retry"])
|
||||
return
|
||||
end if
|
||||
syncClock(data.serverTime)
|
||||
now = currentEpoch()
|
||||
m.guideIds = []
|
||||
titles = []
|
||||
for each channel in data.channels
|
||||
current = invalid
|
||||
upcoming = invalid
|
||||
if GetInterface(channel.programs, "ifArray") <> invalid
|
||||
for each program in channel.programs
|
||||
if parseUtc(program.start) > now
|
||||
upcoming = program
|
||||
exit for
|
||||
else if parseUtc(program.stop) > now
|
||||
current = program
|
||||
end if
|
||||
end for
|
||||
end if
|
||||
titles.Push(channelLabel(channel) + " | " + programTitle(current) + " / " + programTitle(upcoming))
|
||||
m.guideIds.Push(channel.id)
|
||||
end for
|
||||
showPanel("guide", "Program guide", "CHANNEL | NOW / NEXT", titles)
|
||||
end sub
|
||||
330
roku/components/RetroScene.brs
Normal file
330
roku/components/RetroScene.brs
Normal file
@@ -0,0 +1,330 @@
|
||||
sub init()
|
||||
for each id in ["video", "weather", "banner", "channelTitle", "clock", "nowTitle", "nextTitle", "progressTrack", "progress", "playbackStatus", "panel", "panelTitle", "panelStatus", "menu", "bannerTimer", "clockTimer", "retryTimer"]
|
||||
m[id] = m.top.FindNode(id)
|
||||
end for
|
||||
m.channels = []
|
||||
m.channelIndex = -1
|
||||
m.previousIndex = -1
|
||||
m.retryCount = 0
|
||||
m.serverRequest = invalid
|
||||
m.schedule = invalid
|
||||
m.clockReference = CreateObject("roTimespan")
|
||||
|
||||
m.menu.ObserveField("itemSelected", "onMenuSelect")
|
||||
m.video.ObserveField("state", "onVideoState")
|
||||
m.bannerTimer.ObserveField("fire", "hideBanner")
|
||||
m.clockTimer.ObserveField("fire", "refreshClock")
|
||||
m.retryTimer.ObserveField("fire", "retryPlayback")
|
||||
m.clockTimer.control = "start"
|
||||
findServer("", true)
|
||||
end sub
|
||||
|
||||
sub findServer(baseUrl as string, useSaved as boolean)
|
||||
if m.serverRequest <> invalid then return
|
||||
m.banner.visible = false
|
||||
m.weather.visible = false
|
||||
m.video.control = "stop"
|
||||
m.video.visible = false
|
||||
m.playbackStatus.visible = false
|
||||
m.retryTimer.control = "stop"
|
||||
m.channelIndex = -1
|
||||
showPanel("servers", "Connect to retroLabs", "Looking for the bridge…", [])
|
||||
m.serverRequest = startRequest({
|
||||
kind: "discover"
|
||||
baseUrl: baseUrl
|
||||
serverId: ""
|
||||
manual: baseUrl <> ""
|
||||
useSaved: useSaved
|
||||
}, "onServers")
|
||||
end sub
|
||||
|
||||
sub onServers(event as object)
|
||||
m.serverRequest = invalid
|
||||
m.servers = event.GetData().servers
|
||||
if m.servers.Count() = 1
|
||||
connectServer(m.servers[0])
|
||||
return
|
||||
end if
|
||||
|
||||
titles = []
|
||||
for each server in m.servers
|
||||
titles.Push(server.name + " " + server.baseUrl)
|
||||
end for
|
||||
titles.Push("Enter server address")
|
||||
titles.Push("Search again")
|
||||
status = "Select a bridge on your network."
|
||||
if m.servers.Count() = 0 then status = "No bridge found. Check the server or enter its address."
|
||||
showPanel("servers", "Connect to retroLabs", status, titles)
|
||||
end sub
|
||||
|
||||
sub connectServer(server as object)
|
||||
m.server = server
|
||||
loadLineup()
|
||||
end sub
|
||||
|
||||
sub loadLineup()
|
||||
if m.serverRequest <> invalid then return
|
||||
showPanel("lineup", m.server.name, "Loading channels…", [])
|
||||
m.serverRequest = startRequest({kind: "connect", server: m.server}, "onChannels")
|
||||
end sub
|
||||
|
||||
sub onChannels(event as object)
|
||||
m.serverRequest = invalid
|
||||
data = event.GetData().data
|
||||
if data = invalid or GetInterface(data.channels, "ifArray") = invalid
|
||||
showPanel("lineup", m.server.name, "Could not load channels.", ["Retry", "Find another server"])
|
||||
return
|
||||
end if
|
||||
m.channels = data.channels
|
||||
if m.channels.Count() = 0
|
||||
showPanel("lineup", m.server.name, "Set up a channel in Tunarr, then refresh the lineup.", ["Refresh", "Find another server"])
|
||||
return
|
||||
end if
|
||||
|
||||
closePanel()
|
||||
m.previousIndex = -1
|
||||
tune(0)
|
||||
end sub
|
||||
|
||||
function startRequest(request as object, callback as string) as object
|
||||
worker = CreateObject("roSGNode", "BridgeTask")
|
||||
worker.request = request
|
||||
worker.ObserveFieldScoped("result", callback)
|
||||
worker.control = "run"
|
||||
return worker
|
||||
end function
|
||||
|
||||
sub openAddressDialog()
|
||||
dialog = CreateObject("roSGNode", "KeyboardDialog")
|
||||
dialog.title = "Enter server IP or IP:port"
|
||||
dialog.buttons = ["Connect", "Cancel"]
|
||||
if m.server <> invalid then dialog.text = Mid(m.server.baseUrl, 8)
|
||||
dialog.ObserveField("buttonSelected", "onAddressSelected")
|
||||
m.top.dialog = dialog
|
||||
end sub
|
||||
|
||||
sub onAddressSelected(event as object)
|
||||
dialog = m.top.dialog
|
||||
if event.GetData() <> 0
|
||||
dialog.close = true
|
||||
return
|
||||
end if
|
||||
|
||||
address = dialog.text.Trim()
|
||||
if LCase(Left(address, 7)) = "http://" then address = Mid(address, 8)
|
||||
if Right(address, 1) = "/" then address = Left(address, Len(address) - 1)
|
||||
if Instr(1, address, ":") = 0 then address += ":4242"
|
||||
pattern = CreateObject("roRegex", "^([A-Za-z0-9.-]+):([0-9]{1,5})$", "")
|
||||
match = pattern.Match(address)
|
||||
if match.Count() = 0
|
||||
dialog.title = "Enter an IP address or hostname"
|
||||
return
|
||||
end if
|
||||
port = match[2]
|
||||
if Val(port) < 1 or Val(port) > 65535
|
||||
dialog.title = "Enter a port from 1 to 65535"
|
||||
return
|
||||
end if
|
||||
dialog.close = true
|
||||
findServer("http://" + match[1] + ":" + port, false)
|
||||
end sub
|
||||
|
||||
sub tune(index as integer)
|
||||
if index < 0 or index >= m.channels.Count() then return
|
||||
if m.channelIndex <> index
|
||||
m.previousIndex = m.channelIndex
|
||||
m.channelIndex = index
|
||||
end if
|
||||
m.retryTimer.control = "stop"
|
||||
m.retryCount = 0
|
||||
channel = m.channels[index]
|
||||
m.schedule = invalid
|
||||
m.channelTitle.text = channelLabel(channel)
|
||||
m.nowTitle.text = "NOW —"
|
||||
m.nextTitle.text = "NEXT —"
|
||||
m.progressTrack.visible = false
|
||||
m.progress.width = 0
|
||||
startPlayback()
|
||||
showBanner()
|
||||
refreshSchedule()
|
||||
end sub
|
||||
|
||||
sub startPlayback()
|
||||
if m.channelIndex < 0 then return
|
||||
channel = m.channels[m.channelIndex]
|
||||
m.video.control = "stop"
|
||||
m.weather.visible = channel.type = "weather"
|
||||
m.video.visible = not m.weather.visible
|
||||
m.playbackStatus.visible = false
|
||||
if m.weather.visible then return
|
||||
|
||||
streamUrl = channel.streamUrl
|
||||
if GetInterface(streamUrl, "ifString") = invalid or streamUrl = ""
|
||||
setPlaybackStatus("This channel has no stream.")
|
||||
return
|
||||
end if
|
||||
if Left(streamUrl, 1) = "/" then streamUrl = m.server.baseUrl + streamUrl
|
||||
content = CreateObject("roSGNode", "ContentNode")
|
||||
content.url = streamUrl
|
||||
content.streamFormat = "hls"
|
||||
content.live = true
|
||||
content.title = channel.name
|
||||
m.video.content = content
|
||||
setPlaybackStatus("Tuning…")
|
||||
m.video.control = "play"
|
||||
end sub
|
||||
|
||||
sub refreshSchedule()
|
||||
if m.channelIndex < 0 then return
|
||||
if m.scheduleRequest <> invalid
|
||||
m.scheduleRequest.UnobserveFieldScoped("result")
|
||||
m.scheduleRequest.control = "stop"
|
||||
end if
|
||||
channel = m.channels[m.channelIndex]
|
||||
m.scheduleRequestedAt = CreateObject("roTimespan")
|
||||
m.scheduleRequestedAt.Mark()
|
||||
m.scheduleRequest = startRequest({
|
||||
url: m.server.baseUrl + "/api/v1/channels/" + channel.id + "/now"
|
||||
}, "onSchedule")
|
||||
end sub
|
||||
|
||||
sub onSchedule(event as object)
|
||||
if m.scheduleRequest = invalid or not m.scheduleRequest.IsSameNode(event.GetRoSGNode()) then return
|
||||
m.scheduleRequest = invalid
|
||||
if m.channelIndex < 0 then return
|
||||
data = event.GetData().data
|
||||
if data = invalid then return
|
||||
m.schedule = data
|
||||
syncClock(data.serverTime)
|
||||
m.nowTitle.text = "NOW " + programTitle(data.now)
|
||||
m.nextTitle.text = "NEXT " + programTitle(data.next)
|
||||
refreshClock()
|
||||
end sub
|
||||
|
||||
sub showBanner()
|
||||
m.banner.visible = true
|
||||
m.bannerTimer.control = "stop"
|
||||
m.bannerTimer.control = "start"
|
||||
refreshClock()
|
||||
end sub
|
||||
|
||||
sub hideBanner()
|
||||
m.banner.visible = false
|
||||
end sub
|
||||
|
||||
sub syncClock(serverTime as dynamic)
|
||||
epoch = parseUtc(serverTime)
|
||||
if epoch = 0 then return
|
||||
m.serverEpoch = epoch
|
||||
m.clockReference.Mark()
|
||||
end sub
|
||||
|
||||
function parseUtc(value as dynamic) as longinteger
|
||||
if GetInterface(value, "ifString") = invalid or Len(value) < 19 then return 0
|
||||
timestamp = CreateObject("roDateTime")
|
||||
timestamp.FromISO8601String(Left(value, 19))
|
||||
return timestamp.AsSeconds()
|
||||
end function
|
||||
|
||||
function currentEpoch() as longinteger
|
||||
if m.serverEpoch <> invalid then return m.serverEpoch + Int(m.clockReference.TotalMilliseconds() / 1000)
|
||||
return CreateObject("roDateTime").AsSeconds()
|
||||
end function
|
||||
|
||||
sub refreshClock()
|
||||
if not m.banner.visible then return
|
||||
now = currentEpoch()
|
||||
clock = CreateObject("roDateTime")
|
||||
clock.FromSeconds(now)
|
||||
clock.ToLocalTime()
|
||||
hour = clock.GetHours() MOD 12
|
||||
if hour = 0 then hour = 12
|
||||
meridiem = " AM"
|
||||
if clock.GetHours() >= 12 then meridiem = " PM"
|
||||
m.clock.text = hour.ToStr() + ":" + Right("0" + clock.GetMinutes().ToStr(), 2) + meridiem
|
||||
|
||||
if m.schedule = invalid or m.schedule.now = invalid then return
|
||||
starts = parseUtc(m.schedule.now.start)
|
||||
stops = parseUtc(m.schedule.now.stop)
|
||||
if starts = 0 or stops <= starts then return
|
||||
elapsed = now - starts
|
||||
if elapsed < 0 then elapsed = 0
|
||||
if now >= stops
|
||||
elapsed = stops - starts
|
||||
if m.scheduleRequestedAt.TotalMilliseconds() >= 10000 and m.scheduleRequest = invalid then refreshSchedule()
|
||||
end if
|
||||
m.progressTrack.visible = true
|
||||
m.progress.width = 1124.0 * elapsed / (stops - starts)
|
||||
end sub
|
||||
|
||||
function programTitle(program as dynamic) as string
|
||||
if program = invalid or GetInterface(program.title, "ifString") = invalid then return "—"
|
||||
return program.title
|
||||
end function
|
||||
|
||||
function channelLabel(channel as object) as string
|
||||
return channel.number.ToStr() + " " + channel.name
|
||||
end function
|
||||
|
||||
sub setPlaybackStatus(message as string)
|
||||
m.playbackStatus.text = message
|
||||
m.playbackStatus.visible = true
|
||||
end sub
|
||||
|
||||
sub onVideoState()
|
||||
if m.channelIndex < 0 or m.weather.visible then return
|
||||
if m.video.state = "playing"
|
||||
m.playbackStatus.visible = false
|
||||
m.retryCount = 0
|
||||
else if m.video.state = "buffering"
|
||||
setPlaybackStatus("Tuning…")
|
||||
else if m.video.state = "error" or m.video.state = "finished"
|
||||
if m.retryCount < 3
|
||||
m.retryCount++
|
||||
setPlaybackStatus("Reconnecting…")
|
||||
m.retryTimer.control = "start"
|
||||
else
|
||||
setPlaybackStatus("Channel unavailable. Press OK to retry.")
|
||||
end if
|
||||
end if
|
||||
end sub
|
||||
|
||||
sub retryPlayback()
|
||||
startPlayback()
|
||||
end sub
|
||||
|
||||
function onKeyEvent(key as string, press as boolean) as boolean
|
||||
if not press then return false
|
||||
if key = "back" and m.panel.visible and m.channelIndex >= 0
|
||||
closePanel()
|
||||
return true
|
||||
end if
|
||||
if key = "options" and m.channelIndex >= 0
|
||||
if m.panel.visible
|
||||
closePanel()
|
||||
else
|
||||
showPanel("options", "retroLabs", m.server.name + " " + m.server.baseUrl, ["Program guide", "Refresh channels", "Change server"])
|
||||
end if
|
||||
return true
|
||||
end if
|
||||
if m.panel.visible or m.channelIndex < 0 then return false
|
||||
|
||||
if key = "up" or key = "down"
|
||||
direction = 1
|
||||
if key = "up" then direction = -1
|
||||
tune((m.channelIndex + direction + m.channels.Count()) MOD m.channels.Count())
|
||||
return true
|
||||
else if key = "left" or key = "replay"
|
||||
if m.previousIndex >= 0 then tune(m.previousIndex)
|
||||
return true
|
||||
else if LCase(key) = "ok"
|
||||
if m.video.state = "error" or m.video.state = "finished"
|
||||
tune(m.channelIndex)
|
||||
else
|
||||
showBanner()
|
||||
refreshSchedule()
|
||||
end if
|
||||
return true
|
||||
end if
|
||||
return false
|
||||
end function
|
||||
46
roku/components/RetroScene.xml
Normal file
46
roku/components/RetroScene.xml
Normal file
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<component name="RetroScene" extends="Scene">
|
||||
<script type="text/brightscript" uri="pkg:/components/RetroScene.brs" />
|
||||
<script type="text/brightscript" uri="pkg:/components/Guide.brs" />
|
||||
<children>
|
||||
<Video id="video" width="1280" height="720" enableUI="false" />
|
||||
<Group id="weather" visible="false">
|
||||
<Rectangle width="1280" height="720" color="0x122D62FF" />
|
||||
<Rectangle translation="[70,120]" width="1140" height="5" color="0x78E5EBFF" />
|
||||
<Label translation="[70,55]" width="900" height="55" text="retroLabs Weather"
|
||||
font="font:LargeBoldSystemFont" color="0xF8F7EFFF" />
|
||||
<Label translation="[70,195]" width="1100" height="50" text="Live local weather is coming soon."
|
||||
font="font:MediumSystemFont" color="0xF8F7EFFF" />
|
||||
</Group>
|
||||
<Group id="banner" translation="[50,525]" visible="false">
|
||||
<Rectangle width="1180" height="145" color="0x101A32EF" />
|
||||
<Rectangle width="6" height="145" color="0x78E5EBFF" />
|
||||
<Label id="channelTitle" translation="[28,9]" width="950" height="44"
|
||||
font="font:MediumBoldSystemFont" color="0x78E5EBFF" />
|
||||
<Label id="clock" translation="[980,9]" width="170" height="44"
|
||||
horizAlign="right" font="font:MediumSystemFont" />
|
||||
<Label id="nowTitle" translation="[28,57]" width="550" height="44"
|
||||
font="font:SmallSystemFont" />
|
||||
<Label id="nextTitle" translation="[602,57]" width="550" height="44"
|
||||
font="font:SmallSystemFont" />
|
||||
<Rectangle id="progressTrack" translation="[28,120]" width="1124" height="4" color="0x344465FF" />
|
||||
<Rectangle id="progress" translation="[28,120]" width="0" height="4" color="0x78E5EBFF" />
|
||||
</Group>
|
||||
<Label id="playbackStatus" translation="[0,322]" width="1280" height="70"
|
||||
horizAlign="center" font="font:MediumBoldSystemFont" visible="false" />
|
||||
<Group id="panel" visible="false">
|
||||
<Rectangle width="1280" height="720" color="0x101A32FF" />
|
||||
<Rectangle translation="[65,125]" width="1150" height="4" color="0x78E5EBFF" />
|
||||
<Label id="panelTitle" translation="[65,50]" width="1140" height="60"
|
||||
font="font:LargeBoldSystemFont" color="0x78E5EBFF" />
|
||||
<Label id="panelStatus" translation="[65,143]" width="1150" height="54"
|
||||
font="font:SmallSystemFont" />
|
||||
<LabelList id="menu" translation="[65,202]" itemSize="[1150,50]" itemSpacing="[0,4]"
|
||||
numRows="8" color="0xF8F7EFFF" focusedColor="0x101A32FF" font="font:SmallSystemFont"
|
||||
focusedFont="font:SmallBoldSystemFont" focusBitmapBlendColor="0x78E5EBFF" />
|
||||
</Group>
|
||||
<Timer id="bannerTimer" duration="5" />
|
||||
<Timer id="clockTimer" duration="1" repeat="true" />
|
||||
<Timer id="retryTimer" duration="3" />
|
||||
</children>
|
||||
</component>
|
||||
5
roku/manifest
Normal file
5
roku/manifest
Normal file
@@ -0,0 +1,5 @@
|
||||
title=retroLabs
|
||||
major_version=0
|
||||
minor_version=1
|
||||
build_version=1
|
||||
ui_resolutions=hd
|
||||
12
roku/source/main.brs
Normal file
12
roku/source/main.brs
Normal file
@@ -0,0 +1,12 @@
|
||||
sub Main()
|
||||
port = CreateObject("roMessagePort")
|
||||
screen = CreateObject("roSGScreen")
|
||||
screen.SetMessagePort(port)
|
||||
screen.CreateScene("RetroScene")
|
||||
screen.Show()
|
||||
|
||||
while true
|
||||
event = Wait(0, port)
|
||||
if Type(event) = "roSGScreenEvent" and event.IsScreenClosed() then return
|
||||
end while
|
||||
end sub
|
||||
99
tests/test_bridge.py
Normal file
99
tests/test_bridge.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from bridge.app import create_app
|
||||
|
||||
CHANNEL = "4592af97-494e-42d4-9758-10bb26b05343"
|
||||
|
||||
|
||||
class Body(httpx.AsyncByteStream):
|
||||
def __init__(self, content):
|
||||
self.content = content
|
||||
|
||||
async def __aiter__(self):
|
||||
yield self.content
|
||||
|
||||
|
||||
class BridgeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.app = create_app(
|
||||
tunarr_url="http://tunarr:8000", transport=httpx.MockTransport(self.upstream),
|
||||
discover=False, id_file=Path(temporary.name) / "server-id",
|
||||
)
|
||||
self.client = self.enterContext(TestClient(self.app))
|
||||
|
||||
async def upstream(self, request):
|
||||
path = request.url.path
|
||||
if path == "/api/channels":
|
||||
return httpx.Response(200, json=[
|
||||
{"id": CHANNEL, "number": 99, "name": "Test TV"},
|
||||
{"id": "hidden", "number": 100, "name": "Hidden", "stealth": True},
|
||||
])
|
||||
if path == "/api/guide/channels":
|
||||
start = datetime.fromisoformat(request.url.params["dateFrom"])
|
||||
intervals = [
|
||||
("Current show", start - timedelta(minutes=20), start + timedelta(minutes=10)),
|
||||
("Next show", start + timedelta(minutes=10), start + timedelta(minutes=40)),
|
||||
]
|
||||
return httpx.Response(200, json={CHANNEL: {"programs": [
|
||||
{"type": "content", "title": title, "start": int(first.timestamp() * 1000),
|
||||
"stop": int(last.timestamp() * 1000)}
|
||||
for title, first, last in reversed(intervals)
|
||||
]}})
|
||||
if path == f"/stream/channels/{CHANNEL}.m3u8":
|
||||
return httpx.Response(200, text=(
|
||||
'#EXTM3U\n#EXT-X-MEDIA:TYPE=SUBTITLES,URI="subs.m3u8"\n'
|
||||
f'http://tunarr:8000/stream/channels/{CHANNEL}/hls/live.m3u8?a=1\n'
|
||||
))
|
||||
if path.endswith("/hls/live.m3u8"):
|
||||
self.assertEqual(request.url.params["a"], "1")
|
||||
return httpx.Response(200, text="#EXTM3U\nsegment.ts\n")
|
||||
if path.endswith("/hls/segment.ts"):
|
||||
self.assertEqual(request.headers["range"], "bytes=0-6")
|
||||
return httpx.Response(206, stream=Body(b"segment"), headers={"Content-Range": "bytes 0-6/7"})
|
||||
if path == "/api/test-write":
|
||||
self.assertEqual(request.url.params["limit"], "2")
|
||||
return httpx.Response(201, stream=Body(await request.aread()))
|
||||
return httpx.Response(404)
|
||||
|
||||
def test_lineup_and_guide(self):
|
||||
lineup = self.client.get("/api/v1/channels").json()["channels"]
|
||||
self.assertEqual([channel["id"] for channel in lineup], [CHANNEL, "weather"])
|
||||
self.assertEqual(lineup[1]["number"], 100)
|
||||
guide = self.client.get("/api/v1/guide?hours=3").json()
|
||||
self.assertEqual(guide["channels"][0]["programs"][0]["title"], "Current show")
|
||||
current = self.client.get(f"/api/v1/channels/{CHANNEL}/now").json()
|
||||
self.assertEqual(current["now"]["title"], "Current show")
|
||||
self.assertEqual(current["next"]["title"], "Next show")
|
||||
self.assertEqual(self.client.get("/api/v1/channels/hidden/now").status_code, 404)
|
||||
|
||||
def test_stream_proxy_resolves_from_upstream_path(self):
|
||||
result = self.client.get(f"/stream/{CHANNEL}/master.m3u8")
|
||||
self.assertEqual(result.headers["content-type"], "application/vnd.apple.mpegurl")
|
||||
self.assertIn('URI="/stream/channels/subs.m3u8"', result.text)
|
||||
variant_path = result.text.splitlines()[-1]
|
||||
self.assertEqual(variant_path, f"/stream/channels/{CHANNEL}/hls/live.m3u8?a=1")
|
||||
segment_path = self.client.get(variant_path).text.splitlines()[-1]
|
||||
result = self.client.get(segment_path, headers={"Range": "bytes=0-6"})
|
||||
self.assertEqual(result.status_code, 206)
|
||||
self.assertEqual(result.headers["content-range"], "bytes 0-6/7")
|
||||
self.assertEqual(result.content, b"segment")
|
||||
|
||||
def test_admin_proxies_writes(self):
|
||||
self.assertEqual(self.client.get("/admin/", follow_redirects=False).status_code, 307)
|
||||
response = self.client.post("/api/test-write?limit=2", content="test body")
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertEqual(response.text, "test body")
|
||||
|
||||
def test_server_id_is_persisted(self):
|
||||
server_id = self.client.get("/api/v1/server").json()["id"]
|
||||
self.assertIn(server_id, self.client.get("/api/v1/device.xml").text)
|
||||
with TestClient(self.app) as restarted:
|
||||
self.assertEqual(restarted.get("/api/v1/server").json()["id"], server_id)
|
||||
Reference in New Issue
Block a user