Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,12 @@ turn it off, set `MCP_DASHBOARD=off`.
To put it on a site of its own behind a reverse proxy, map the site's root to `/dashboard/` (it answers there too), e.g. with nginx
`location / { proxy_pass http://deb1:8765/dashboard/; }`. The live updates need nothing more: they tell nginx not to buffer them.

A link to the page shared in a chat app previews with its sun icon, "Weather Dashboard" and a line about it (the page's Open Graph
tags), behind a proxy too, with nothing to set: the preview's picture is the icon as this repository publishes it on GitHub
(`raw.githubusercontent.com`), since WhatsApp and Messenger want a full https address and ecobot-mcp can't know its own. Only the
chat app fetches it; your browser loads the page's icon from ecobot-mcp (`/dashboard/icon.png`). Serve the site over https
(Signal shows no preview for plain http). A chat app keeps a preview it has made: to see a new one, share the link with `?v=2` on the end.

## Upgrading

Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept; settings with an old name still work
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o
| `MCP_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-mcp`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses |
| `MCP_CHART_BASE_URL` | none | Where people's browsers reach the chart links' pictures (`?charts=link`, below): the URL a reverse proxy serves `/charts` at, e.g. `https://api.example.org/ecobot-charts` with nginx's `location /ecobot-charts/ { proxy_pass http://127.0.0.1:8765/charts/; }`. Unset: the address the MCP request came to (`X-Forwarded-Proto` and `X-Forwarded-Host` when a proxy sends them) with `/charts` |
| `MCP_CHART_LINK_HOURS` | `24` | How long a chart link's picture answers (1 to 720 hours). They are kept in memory (at most 500, 64 MB in all, the oldest dropped first): a restart forgets them, and an old link answers 404 |
| `MCP_DASHBOARD` | `on` | The gauges' live web page at `/dashboard` beside `/mcp` (`http://deb1:8765/dashboard`): read-only, so it needs no token and answers any `Host` (open it by the machine's name or address from the LAN); `/mcp` keeps both checks. `off`: `/dashboard`, `/dashboard/data` and `/dashboard/events` answer 404 |
| `MCP_DASHBOARD` | `on` | The gauges' live web page at `/dashboard` beside `/mcp` (`http://deb1:8765/dashboard`): read-only, so it needs no token and answers any `Host` (open it by the machine's name or address from the LAN); `/mcp` keeps both checks. `off`: `/dashboard`, `/dashboard/`, `/dashboard/icon.png`, `/dashboard/data` and `/dashboard/events` answer 404 |

Every request to `/mcp` needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a client whose URL ends `?charts=link` gets each chart as a link to its PNG (`/charts/<id>.png`, served with no token and any `Host`, so anyone with the link can open it until it expires; `MCP_CHART_BASE_URL`, `MCP_CHART_LINK_HOURS`) and the model is asked to put it in its reply as a markdown image, for a chat app that shows those but not a tool's image (LibreChat); a call's request `_meta` `chart_image` (`"png"`, `"link"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once.

Expand Down
3 changes: 1 addition & 2 deletions lib/web_dashboard.html

Large diffs are not rendered by default.

46 changes: 42 additions & 4 deletions lib/web_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
- GET /dashboard (and /dashboard/, the same page): one self-contained HTML5 page (web_dashboard.html: no framework, nothing fetched from elsewhere) whose script draws
the gauges as inline SVG, with HTML titles and tables, in lib/gauge_look.py's colours and sizes, as the Status picture's PNG
(lib/gauges.py) draws its three, without the tables; its tiles laid out to fill the window, portrait or landscape;
- GET /dashboard/icon.png: the page's sun (its original, at ICON_SIZE px: lib/web_dashboard_icon.png) as a file, the page's own
icon (favicon and apple-touch-icon), named relative to the path the page was asked for (/dashboard: "dashboard/icon.png",
/dashboard/: "icon.png"), so it is right whatever path a proxy serves the page at. A file, not a data: URI in the page, because a
link preview can't fetch one: some apps (Signal, iMessage) take the page's icon as the preview's picture.
The page's Open Graph tags (og:title, og:image...) name the same file as this repository publishes it on GitHub (ICON_URL): WhatsApp
and Messenger want og:image as a full https address and take no page icon, and ecobot-mcp can't know its own public address
(nginx's `location / { proxy_pass http://deb1:8765/dashboard/; }` sends ecobot-mcp's own Host and /dashboard/), so nothing is set
for it. Only link previews fetch og:image: a browser opening the page fetches nothing from elsewhere;
- GET /dashboard/data: the tiles as JSON: the gauges' sheet (lib/gauge_sheet.py) from the service's `current` with context, answered
from what is held (fetch off: a request never asks the station; the keep-warm keeps the live reading), as the Status picture's, each
tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`) and the look;
Expand All @@ -12,16 +20,17 @@
comment every HEARTBEAT_SECONDS keeps a proxy from closing it.

No token is asked for (it is the weather and air readings only) and the Host isn't checked: a browser opens it by the machine's name. The MCP
endpoint keeps both. MCP_DASHBOARD off: none of the three routes is served (404). `close()` ends the open streams, so uvicorn's
endpoint keeps both. MCP_DASHBOARD off: none of the four routes is served (404). `close()` ends the open streams, so uvicorn's
graceful shutdown doesn't wait on them (ecobot_mcp's Uvicorn calls it once it stops accepting connections)."""

import asyncio
import html
import json
import logging
from pathlib import Path

from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, StreamingResponse
from starlette.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
from starlette.routing import Route

from . import gauge_sheet
Expand All @@ -33,6 +42,12 @@
log = logging.getLogger(__name__)

PAGE = Path(__file__).with_name("web_dashboard.html")
ICON = Path(__file__).with_name("web_dashboard_icon.png") # the page's sun, drawn large (its original, 534 px, at 512): WhatsApp asks 300 px, Facebook 200
ICON_NAME, ICON_SIZE = "icon.png", 512
ICON_URL = "https://raw.githubusercontent.com/robdevops/ecobot/main/lib/web_dashboard_icon.png" # og:image: ICON as GitHub serves it (https, image/png)
PREVIEW = "<!--link preview-->" # where the page's Open Graph tags go: first in its head, before its icons (Slack reads 32 KB of it)
TITLE = "Weather Dashboard"
DESCRIPTION = "The weather station's and the air sensor's gauges, live."
HEARTBEAT_SECONDS = 25.0 # a comment on an idle stream this often
RETRY_MS = 5000 # how soon a browser connects again after its stream ends
QUEUED = 4 # events waiting on a stream that isn't read: more are dropped (one says it all: fetch again)
Expand Down Expand Up @@ -122,9 +137,32 @@ async def _stream(self, queue: asyncio.Queue):
finally:
self._streams.discard(queue)

# ---------- the link preview ----------
def icon_url(self, path: str) -> str:
"""Where the icon is for a page asked for at `path`, relative to it (/dashboard: "dashboard/icon.png", /dashboard/: "icon.png"),
which a browser or a link preview resolves against the URL it was given."""
return ICON_NAME if path.endswith("/") else f"{path.rsplit('/', 1)[-1]}/{ICON_NAME}"

def preview(self, path: str) -> str:
"""The Open Graph tags (and Twitter's card, read by Slack and Discord: "summary", a small square picture) and the page's icon links
for a page asked for at `path`."""
tags = [("og:type", "website"), ("og:title", TITLE), ("og:description", DESCRIPTION),
("og:image", ICON_URL), ("og:image:type", "image/png"), ("og:image:width", str(ICON_SIZE)),
("og:image:height", str(ICON_SIZE)), ("og:image:alt", "A sun")]
icon = html.escape(self.icon_url(path))
return "\n".join([*(f'<meta property="{k}" content="{html.escape(v)}">' for k, v in tags),
'<meta name="twitter:card" content="summary">',
# the page's own icon, the same picture: what a browser shows, and what some link previews take (Signal, iMessage)
# (Signal, iMessage): a data: URI can't be fetched by one, a file beside the page needs no public URL
f'<link rel="icon" type="image/png" href="{icon}">', f'<link rel="apple-touch-icon" href="{icon}">'])

# ---------- the routes ----------
async def page(self, request: Request):
return HTMLResponse(PAGE.read_text(encoding="utf-8"), headers={"Cache-Control": "no-cache"})
page = PAGE.read_text(encoding="utf-8").replace(PREVIEW, self.preview(request.url.path), 1)
return HTMLResponse(page, headers={"Cache-Control": "no-cache"})

async def icon(self, request: Request):
return Response(ICON.read_bytes(), media_type="image/png", headers={"Cache-Control": "public, max-age=86400"})

async def data_route(self, request: Request):
return JSONResponse(await self.data(), headers={"Cache-Control": "no-store"})
Expand All @@ -142,7 +180,7 @@ def routes(self, path: str = "/dashboard") -> list[Route]:
# The page at `path/` too, not a redirect to `path`: a redirect is built from the Host the request came with, so behind a proxy
# that maps a site's root to `path/` it would send the browser to ecobot-mcp's own LAN address (the page finds its data either way)
return [Route(path, self.page, methods=["GET"]), Route(f"{path}/", self.page, methods=["GET"]),
Route(f"{path}/data", self.data_route, methods=["GET"]),
Route(f"{path}/{ICON_NAME}", self.icon, methods=["GET"]), Route(f"{path}/data", self.data_route, methods=["GET"]),
Route(f"{path}/events", self.events, methods=["GET"])]


Expand Down
Binary file added lib/web_dashboard_icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 63 additions & 5 deletions tests/test_web_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
console error. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder."""

import asyncio
import base64
import html
import io
import json
import re
import os
Expand All @@ -24,7 +27,7 @@
from lib.mcp_server import AIR_URI, EcobotServer, WEATHER_URI, http_app
from lib.service.context import Context
from lib.service.names import Catalogue
from lib.web_dashboard import air_readings_of, readings_of
from lib.web_dashboard import DESCRIPTION, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, readings_of
from tests.chart_samples import _air, _station
from tests.fakes import TZ, StandInService, gauges_result
from tests.test_mcp_listen import Serving, free_port, until
Expand Down Expand Up @@ -100,8 +103,11 @@ async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_
assert page.status_code == 200 and page.headers["content-type"].startswith("text/html")
html = page.text
assert html.startswith("<!DOCTYPE html>") and "<script>" in html and "EventSource" in html
links = re.findall(r'<link[^>]*href="([^"]*)"', html) # (the icon, carried in the page)
assert "https://" not in html and " src=" not in html and links and all(h.startswith("data:image/png;base64,") for h in links)
links = re.findall(r'<link[^>]*href="([^"]*)"', html) # (its icons: the file beside it, as the
assert preview_of(html)["og:image"] == ICON_URL # (the link preview's, on GitHub: only
# a preview fetches it, not the browser)
urls = [u for u in re.findall(r"https?://[^\s\"'<>]+", html) if u != "http://www.w3.org/2000/svg"] # (the SVG namespace: a name)
assert urls == [ICON_URL] and " src=" not in html and "data:" not in html and links == ["dashboard/icon.png"] * 2
assert "<title>Weather Dashboard</title>" in html # nothing fetched from elsewhere
assert data.status_code == 200
got = data.json()
Expand Down Expand Up @@ -131,12 +137,63 @@ async def test_the_page_answers_at_dashboard_slash_too_so_a_proxy_mapping_a_site
slash = await http.get(f"{base}/dashboard/", headers={"Host": "192.168.1.208:8765"})
plain = await http.get(f"{base}/dashboard")
data = await http.get(f"{base}/dashboard/" + "data") # the page at the site's root asks for /data: the proxy's /dashboard/data
assert slash.status_code == 200 and "location" not in slash.headers and slash.text == plain.text
assert slash.status_code == 200 and "location" not in slash.headers
assert preview_of(slash.text)["og:image"] == preview_of(plain.text)["og:image"] == ICON_URL
same = lambda page: re.sub(r'="(?:dashboard/)?icon\.png"', '="ICON"', page) # (the icon links)
assert same(slash.text) == same(plain.text) # the same page but for its picture, beside it as it was asked for
assert data.status_code == 200 and "tiles" in data.json()
script = slash.text
assert 'location.pathname.replace(/\\/+$/, "")' in script and 'BASE + "/data"' in script and 'BASE + "/events"' in script


PREVIEW_TAG = r'<meta (?:property|name)="((?:og|twitter):[^"]+)" content="([^"]*)">'


def preview_of(page: str) -> dict:
"""The page's Open Graph tags and Twitter card ({property or name: content})."""
return {k: html.unescape(v) for k, v in re.findall(PREVIEW_TAG, page)}


async def test_the_link_preview_names_the_sun_icon_beside_the_page_as_it_was_asked_for(server):
# A chat app's link preview reads the page's Open Graph tags; its picture can't be the page's icon, a data: URI: so the icon is a
# file beside the page, named relative to the path the page was asked for, which is right behind any proxy: the site's root mapped
# to /dashboard/ (public https://site/ -> "icon.png" -> https://site/icon.png -> /dashboard/icon.png), or /dashboard passed as it is
port = free_port()
base = f"http://127.0.0.1:{port}"
async with Serving(http_app(server, tokens=(TOKEN,)), port):
async with httpx.AsyncClient() as http:
plain = await http.get(f"{base}/dashboard", headers={"Host": "deb1:8765"})
slash = await http.get(f"{base}/dashboard/", headers={"Host": "192.168.1.208:8765"})
icon = await http.get(f"{base}/dashboard/icon.png", headers={"Host": "deb1:8765"}) # no token, any Host
head = await http.head(f"{base}/dashboard/icon.png")
ranged = await http.get(f"{base}/dashboard/icon.png", headers={"Range": "bytes=0-32767"}) # (as Slack asks): all of it
for page, image in ((plain, "dashboard/icon.png"), (slash, "icon.png")):
tags = preview_of(page.text)
assert tags == {"og:type": "website", "og:title": "Weather Dashboard", "og:description": DESCRIPTION, "og:image": ICON_URL,
"og:image:type": "image/png", "og:image:width": "512", "og:image:height": "512", "og:image:alt": "A sun",
"twitter:card": "summary"} # no og:url: the page's public URL isn't known
head_start = page.text.index("<head>")
assert page.text.index('property="og:type"') - head_start < 100 # first in the head: Slack reads 32 KB
assert page.text.index('name="twitter:card"') < page.text.index('rel="icon"') < 32_768 # (all of them before the icons)
assert "<!--link preview-->" not in page.text
icons = dict(re.findall(r'<link rel="([\w-]+)"[^>]*href="([^"]*)"', page.text))
assert icons == {"icon": image, "apple-touch-icon": image} # the page's own icon is the same file: Signal and iMessage take it
assert icon.status_code == 200 and icon.headers["content-type"] == "image/png"
assert icon.content == ICON.read_bytes() and int(icon.headers["content-length"]) == len(icon.content) < 300_000 # WhatsApp: < 300 KB
assert "max-age=" in icon.headers["cache-control"] and "public" in icon.headers["cache-control"]
assert head.status_code == 200 and head.headers["content-type"] == "image/png"
assert ranged.status_code == 200 and ranged.content == icon.content


def test_the_icon_is_the_pages_own_sun_at_512_px():
from PIL import Image
big = Image.open(io.BytesIO(ICON.read_bytes()))
assert big.format == "PNG" and big.size == (512, 512) # Facebook asks 200 px, WhatsApp 300
assert big.mode == "RGBA" and big.getpixel((0, 0))[3] == 0 and big.getpixel((256, 256))[3] == 255 # the sun on a clear ground
assert "data:" not in PAGE.read_text() # the page carries no icon of its own: it links this one
assert ICON_URL.endswith("/main/" + ICON.relative_to(Path(__file__).resolve().parent.parent).as_posix()) # og:image: this file on GitHub


async def test_the_data_says_so_when_the_station_gives_nothing(server):
server._service = StandInService(current={"sensors": {}, "unavailable": {"station": "The weather station isn't answering right now."}})
port = free_port()
Expand Down Expand Up @@ -228,7 +285,8 @@ async def test_with_mcp_dashboard_off_there_is_no_page_and_mcp_is_as_it_was(serv
port = free_port()
base = f"http://127.0.0.1:{port}"
async with Serving(http_app(server, tokens=(TOKEN,), dashboard=False), port):
assert [(await get(f"{base}{path}")).status_code for path in ("/dashboard", "/dashboard/data", "/dashboard/events")] == [404] * 3
paths = ("/dashboard", "/dashboard/", "/dashboard/icon.png", "/dashboard/data", "/dashboard/events")
assert [(await get(f"{base}{path}")).status_code for path in paths] == [404] * 5
assert (await get(f"{base}/mcp", Accept="text/event-stream")).status_code == 401
lines = [r.getMessage() for r in caplog.records if r.name == "lib.mcp_server.requests"]
assert any("refused: GET /dashboard/data -> 404" in line for line in lines), lines
Expand Down
Loading