On the Pi a page built in the background at the same time as a visit made the visit several times slower (one Python process). Every real request now holds the warmers off until it has been quiet for 3 s (pluginhost.visited / wait_quiet). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
481 lines
21 KiB
Python
481 lines
21 KiB
Python
"""The dashboard as a web page (Flask + Jinja templates).
|
||
|
||
Runs inside the dashboard process on a background thread (`web_worker`,
|
||
started by `dash.main` when `web.enabled` is set), so it reads the same live
|
||
`Store` the workers fill — no extra calls to Nextcloud / OWM / termix.
|
||
|
||
/ Home: the clock + the plugins' regions (pluginhost.home_parts: weather,
|
||
stations, main temperature, birthdays + cards, Upcoming, day view)
|
||
/m old compact Home -> redirects to / (Home is responsive now)
|
||
/fonts/… DejaVu + Symbola from the Pi, so pictograms match the device
|
||
/settings edit dash_config.json (settings.py); /api/settings POST, /api/restart POST,
|
||
/api/status (worker states), /api/geocode?q= (place search) — admin only
|
||
/login log in (GET form / POST), logged in: who you are + log out; /logout POST
|
||
/api/users… Settings ▸ Users (auth.py): users, the household view — admin only
|
||
/app the phone app's newest build to install (mirrored from the sync server, sync.app_mirror)
|
||
/api/sync/kick POST from the phone app: "sync now" (sync.kick; proven by the data key, not a login)
|
||
the plugins' pages (plugins/<name>/, pluginhost.py): /week, /month, /api/reminders, /api/events …
|
||
(calendar), /weather, /icon/… (weather), /stations, /work, /health, /food …
|
||
|
||
The pages are responsive: a wall layout that fills a landscape screen
|
||
(1080p TV / monitor) without scrolling, a scrolling stacked layout on
|
||
phones, tablets and portrait windows. They re-fetch themselves every minute
|
||
(and when the tab comes back into view); the analog clock ticks in the browser.
|
||
Who's looking (auth.py): admin (everything), a member (their plugins + calendars) or,
|
||
without a login, the household — read only (every write refused here). No accounts yet =
|
||
everyone is admin. Still meant for the LAN (plain HTTP).
|
||
"""
|
||
import base64
|
||
import io
|
||
import ipaddress
|
||
import logging
|
||
import math
|
||
import os
|
||
import socket
|
||
from urllib.parse import urlparse, urlsplit
|
||
|
||
from flask import Flask, abort, g, jsonify, redirect, render_template, request, send_file, url_for
|
||
|
||
import auth
|
||
from config import FONT_DIR, THEME
|
||
from panel import EMOJI_FONTS
|
||
import pluginhost
|
||
import webview
|
||
|
||
FONTS = {
|
||
"dejavu.ttf": os.path.join(FONT_DIR, "DejaVuSans.ttf"),
|
||
"dejavu-bold.ttf": os.path.join(FONT_DIR, "DejaVuSans-Bold.ttf"),
|
||
"emoji.ttf": next((p for p in EMOJI_FONTS if os.path.exists(p)), None),
|
||
}
|
||
STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
|
||
MAX_BODY = 2 * 1024 * 1024 # bytes a request may send (the biggest: a long note)
|
||
|
||
|
||
def build_id():
|
||
"""Changes whenever dash.css / dash.js change on disk (a deploy): pages compare
|
||
it on their minute refresh and reload in full, so they pick up the new files."""
|
||
return "%x" % int(max(os.path.getmtime(os.path.join(STATIC, f)) for f in ("dash.css", "dash.js", "users.js", "system.js")))
|
||
|
||
|
||
def host_ok(store):
|
||
"""Against DNS rebinding: a page on another site can point its own name at this address, and
|
||
its requests then arrive with that name. So answer only to an IP address, localhost, this
|
||
machine's name (+ .local / .lan / .home) and the names in web.hosts (dash_config.json)."""
|
||
try:
|
||
h = (urlsplit("//" + (request.host or "")).hostname or "").rstrip(".").lower()
|
||
except ValueError:
|
||
return False
|
||
try:
|
||
ipaddress.ip_address(h)
|
||
return True
|
||
except ValueError:
|
||
pass
|
||
me = socket.gethostname().lower()
|
||
extra = {str(x).strip().lower() for x in ((store.cfg.get("web") or {}).get("hosts") or [])}
|
||
return h in {"localhost", me, me + ".local", me + ".lan", me + ".home"} | extra
|
||
|
||
|
||
def same_origin():
|
||
"""Writes only from our own pages: JSON bodies (a plain cross-site form can't
|
||
send those without a CORS preflight we never answer) and, when the browser
|
||
sends one, an Origin naming this host."""
|
||
origin = request.headers.get("Origin")
|
||
return request.is_json and (not origin or urlparse(origin).netloc == request.host)
|
||
|
||
|
||
def _calendar_names(store, users, household):
|
||
"""Every calendar name the dashboard knows, for Settings ▸ Users — not only what the last
|
||
sync found (empty right after a restart): Settings ▸ Calendar's names (hidden, cards,
|
||
pictograms, no new events), the Local calendar, and whatever someone is already given."""
|
||
c = store.cfg.get("calendar") or {}
|
||
with store.lock:
|
||
names = {r["name"] for r in store.cal_collections} | {m.get("cal_name") for m, _, _ in store.cal_sources}
|
||
names |= set(c.get("hidden_calendars") or []) | set(c.get("card_calendars") or []) | set(c.get("no_create") or [])
|
||
names |= {k for k in (c.get("icons") or {}) if k != "*"} | {c.get("local_name") or "Local"}
|
||
for v in users + [household]:
|
||
names |= set(v.get("calendars") or [])
|
||
return sorted((n for n in names if n), key=str.lower)
|
||
|
||
|
||
def _set_cookie(resp, token):
|
||
resp.set_cookie(auth.COOKIE, token, max_age=auth.SESSION_DAYS * 86400, httponly=True, samesite="Lax")
|
||
|
||
|
||
def create_app(store):
|
||
app = Flask(__name__)
|
||
app.config["TEMPLATES_AUTO_RELOAD"] = True # a template-only deploy needs no restart
|
||
app.config["MAX_CONTENT_LENGTH"] = MAX_BODY
|
||
app.jinja_env.globals.update(THEME=THEME, cos=math.cos, sin=math.sin, LUNCH_BG=webview.LUNCH_BG,
|
||
build_id=build_id, SCALE=[], # the calendar plugin sets SCALE
|
||
plugin_nav=lambda: pluginhost.nav(store),
|
||
plugin_section=lambda name: pluginhost.section(store, name),
|
||
plugin_host=lambda name: pluginhost.host_of(store, name),
|
||
viewer=auth.viewer, auth_active=auth.active)
|
||
pluginhost.attach(app, store, same_origin) # plugins/<name>/ (pluginhost.py)
|
||
|
||
@app.before_request
|
||
def who():
|
||
"""Who's looking (auth.py); the household can't write anything, only admins reach
|
||
Settings. Only for our own names (host_ok)."""
|
||
if not host_ok(store) and not request.environ.get("dash.internal"):
|
||
print(f"web: refused a request for host {request.host!r} (add it to web.hosts if it's yours)", flush=True)
|
||
abort(400)
|
||
g.viewer = v = auth.from_request()
|
||
if not request.environ.get("dash.internal"):
|
||
pluginhost.visited()
|
||
if request.path in ("/login", "/logout", "/api/sync/kick"): # the kick proves itself (sync.kick)
|
||
return None
|
||
if request.path.startswith(ADMIN_ONLY) and v["kind"] != "admin":
|
||
if request.method == "GET" and request.path == "/settings":
|
||
return redirect("/login?next=/settings")
|
||
abort(403)
|
||
if request.method not in ("GET", "HEAD", "OPTIONS") and v["kind"] == "household":
|
||
abort(403)
|
||
return None
|
||
|
||
@app.route("/login", methods=["GET", "POST"])
|
||
def login():
|
||
nxt = request.values.get("next") or "/"
|
||
nxt = nxt if nxt.startswith("/") and not nxt.startswith("//") else "/"
|
||
err = None
|
||
if request.method == "POST":
|
||
origin = request.headers.get("Origin")
|
||
if origin and urlparse(origin).netloc != request.host:
|
||
abort(403)
|
||
addr = request.remote_addr or "?"
|
||
if auth.locked(addr):
|
||
err = "Too many wrong passwords — wait 10 minutes."
|
||
else:
|
||
tok = auth.login(request.form.get("name"), request.form.get("password"), addr,
|
||
request.headers.get("User-Agent", ""))
|
||
if tok:
|
||
resp = redirect(nxt)
|
||
_set_cookie(resp, tok)
|
||
return resp
|
||
err = "Wrong name or password."
|
||
return render_template("login.html", page="login", error=err, next=nxt,
|
||
name=request.form.get("name", "")), (401 if err else 200)
|
||
|
||
@app.route("/logout", methods=["POST"])
|
||
def logout():
|
||
origin = request.headers.get("Origin")
|
||
if origin and urlparse(origin).netloc != request.host:
|
||
abort(403)
|
||
auth.logout(request.cookies.get(auth.COOKIE))
|
||
resp = redirect("/")
|
||
resp.delete_cookie(auth.COOKIE)
|
||
return resp
|
||
|
||
@app.route("/api/users")
|
||
def api_users():
|
||
users, hh = auth.users(), auth.household()
|
||
return jsonify(users=users, household=hh, plugins=pluginhost.catalog(),
|
||
calendars=_calendar_names(store, users, hh), me=g.viewer["id"], active=auth.active())
|
||
|
||
@app.route("/api/users/<what>", methods=["POST"])
|
||
def api_users_change(what):
|
||
if not same_origin():
|
||
abort(403)
|
||
d = request.get_json(silent=True) or {}
|
||
names = [p["name"] for p in pluginhost.catalog()]
|
||
me, first = g.viewer["id"], not auth.active()
|
||
if what == "save":
|
||
if first: # the first account is the admin, logged in at once
|
||
if not auth.setup_ok(d.get("setup"), request.remote_addr):
|
||
return jsonify(error="Wrong setup code — it's in the dashboard's log (journalctl -u dashboard).",
|
||
field="setup"), 403
|
||
d["role"] = "admin"
|
||
uid, err = auth.save_user(d, names, me_id=me, keep_token=request.cookies.get(auth.COOKIE))
|
||
if err:
|
||
return jsonify(error=err), 400
|
||
resp = jsonify(ok=True, id=uid)
|
||
if first:
|
||
_set_cookie(resp, auth.login(d.get("name"), d.get("password"), request.remote_addr or "?"))
|
||
return resp
|
||
if what == "delete":
|
||
err = auth.delete_user(d.get("id"), me_id=me)
|
||
return (jsonify(error=err), 400) if err else jsonify(ok=True)
|
||
if what == "logout":
|
||
auth.logout_everywhere(d.get("id"))
|
||
return jsonify(ok=True)
|
||
if what == "household":
|
||
auth.save_household(d, names)
|
||
return jsonify(ok=True)
|
||
abort(404)
|
||
|
||
@app.route("/favicon.ico") # browsers ask for it unprompted
|
||
def favicon():
|
||
return redirect(url_for("static", filename="favicon.svg"), 301)
|
||
|
||
@app.route("/")
|
||
def home():
|
||
parts = pluginhost.home_parts(store)
|
||
off = [c for c, gone in (("off-wx", "weather" not in parts), ("off-st", not ({"stations", "main"} & set(parts))),
|
||
("off-cal", "day" not in parts)) if gone]
|
||
return render_template("home.html", parts=parts, off=off, page="home")
|
||
|
||
@app.route("/m")
|
||
def mini(): # old compact Home; / adapts to the window now
|
||
return redirect("/", 301)
|
||
|
||
@app.route("/settings")
|
||
def settings_page():
|
||
import settings
|
||
return render_template("settings.html", v=settings.view(store), page="settings")
|
||
|
||
@app.route("/api/settings", methods=["POST"])
|
||
def api_settings():
|
||
if not same_origin():
|
||
abort(403)
|
||
import settings
|
||
try:
|
||
return jsonify(settings.apply(store, request.get_json(silent=True) or {}))
|
||
except settings.Invalid as e:
|
||
return jsonify(error=str(e), field=e.field), 400
|
||
except OSError as e:
|
||
return jsonify(error=f"Could not write the config ({e.strerror})."), 500
|
||
|
||
@app.route("/api/restart", methods=["POST"])
|
||
def api_restart():
|
||
if not same_origin():
|
||
abort(403)
|
||
import settings
|
||
settings.restart(store)
|
||
return jsonify(ok=True)
|
||
|
||
@app.route("/app")
|
||
def app_page(): # the phone app for the home network (sync.app_mirror)
|
||
import sync
|
||
return render_template("app.html", page="app", info=sync.app_info())
|
||
|
||
@app.route("/app/dash-app.apk")
|
||
def app_apk():
|
||
import sync
|
||
info = sync.app_info()
|
||
if not info:
|
||
abort(404)
|
||
return send_file(info["file"], mimetype="application/vnd.android.package-archive", as_attachment=True,
|
||
download_name=f"dashPi-{info.get('version')}-{info.get('build')}.apk", max_age=0)
|
||
|
||
@app.route("/api/sync/kick", methods=["POST"])
|
||
def api_sync_kick():
|
||
import sync
|
||
code, answer = sync.kick(request.get_data(cache=False))
|
||
return jsonify(answer), code
|
||
|
||
# ---- Settings ▸ General ▸ Sync (sync.py): set up / join from the browser, devices, the phone's QR code — admin only
|
||
def sync_answer(fn):
|
||
if not same_origin():
|
||
abort(403)
|
||
try:
|
||
return jsonify(fn(request.get_json(silent=True) or {}) or {"ok": True})
|
||
except (ValueError, RuntimeError, OSError) as e:
|
||
return jsonify(error=str(e)), 400
|
||
|
||
@app.route("/api/sync")
|
||
def api_sync():
|
||
import sync
|
||
v = sync.view()
|
||
v["primary"] = (store.cfg.get("sync") or {}).get("primary", True)
|
||
v["devices"], v["manager"], v["devices_error"] = [], False, None
|
||
if v["configured"]:
|
||
try:
|
||
v["devices"], v["manager"] = sync.devices()
|
||
except Exception as e:
|
||
v["devices_error"] = str(e)
|
||
return jsonify(v)
|
||
|
||
@app.route("/api/sync/<what>", methods=["POST"])
|
||
def api_sync_do(what):
|
||
import sync
|
||
import threading
|
||
import settings
|
||
|
||
def connect(d):
|
||
res = sync.connect(str(d.get("server") or ""), str(d.get("token") or ""),
|
||
d.get("passphrase") or None, d.get("recovery") or None)
|
||
threading.Thread(target=_quietly, args=(sync.sync_now,), daemon=True, name="sync-first").start()
|
||
return res
|
||
|
||
def add(d):
|
||
res = sync.add_device(str(d.get("name") or "").strip())
|
||
res["link"] = sync.pair_link(res["server"], res["token"])
|
||
png = sync.qr_png(res["link"])
|
||
res["qr"] = None if png is None else "data:image/png;base64," + base64.b64encode(png).decode()
|
||
return res
|
||
|
||
steps = {
|
||
"probe": lambda d: sync.probe(str(d.get("server") or ""), str(d.get("token") or "")),
|
||
"connect": connect,
|
||
"now": lambda d: sync.sync_now(),
|
||
"passphrase": lambda d: sync.new_passphrase(d.get("new"), old=d.get("old") or None,
|
||
recovery=d.get("recovery") or None),
|
||
"disconnect": lambda d: sync.disconnect(),
|
||
"add": add,
|
||
"revoke": lambda d: sync.revoke_device(str(d.get("name") or "")),
|
||
"primary": lambda d: settings.save_part(store, "sync", dict(store.cfg.get("sync") or {},
|
||
primary=bool(d.get("on")))),
|
||
}
|
||
if what == "kick" or what not in steps:
|
||
abort(404)
|
||
return sync_answer(steps[what])
|
||
|
||
# ---- the 3.5" screen as a picture (?n = which screen, 0 = Home) — what the Pi shows, or would — admin only
|
||
@app.route("/api/screen.png")
|
||
def api_screen():
|
||
import screens
|
||
from panel import Panel
|
||
if "panel" not in _preview:
|
||
_preview["panel"] = Panel(None)
|
||
names = [s["label"] for s in screens.screen_list(store)]
|
||
n = request.args.get("n", "0")
|
||
n = names.index(n) if n in names else int(n) if n.isdigit() and int(n) < len(names) else 0
|
||
img = screens.render(_preview["panel"], _OwnScreen(store, n))
|
||
buf = io.BytesIO()
|
||
img.save(buf, "PNG")
|
||
resp = app.response_class(buf.getvalue(), mimetype="image/png")
|
||
resp.headers["X-Screens"] = ", ".join(names)
|
||
return resp
|
||
|
||
# ---- Settings ▸ General (system.py): web address, touch calibration, backup / restore — admin only
|
||
@app.route("/api/system")
|
||
def api_system():
|
||
import system
|
||
return jsonify(system.view(store, getattr(store, "headless", False)))
|
||
|
||
@app.route("/api/system/backup")
|
||
def api_backup():
|
||
import system
|
||
data, name = system.backup()
|
||
return send_file(io.BytesIO(data), mimetype="application/zip", as_attachment=True, download_name=name, max_age=0)
|
||
|
||
@app.route("/api/system/restore", methods=["POST"])
|
||
def api_restore():
|
||
"""The backup as the raw body (not a form: it's bigger than MAX_BODY, read straight to disk)."""
|
||
import system
|
||
origin = request.headers.get("Origin")
|
||
if origin and urlparse(origin).netloc != request.host:
|
||
abort(403)
|
||
if request.headers.get("Content-Type") != "application/zip":
|
||
return jsonify(error="Send the backup .zip."), 400
|
||
try:
|
||
info = system.receive(request.environ["wsgi.input"], request.content_length or 0)
|
||
except system.Invalid as e:
|
||
return jsonify(error=str(e)), 400
|
||
return jsonify(ok=True, backup=info)
|
||
|
||
@app.route("/api/system/<what>", methods=["POST"])
|
||
def api_system_do(what):
|
||
import settings
|
||
import system
|
||
if not same_origin():
|
||
abort(403)
|
||
d = request.get_json(silent=True) or {}
|
||
try:
|
||
if what == "web":
|
||
new, restart = system.web_settings(store, d)
|
||
settings.save_part(store, "web", new)
|
||
if restart:
|
||
store.restart_needed = True
|
||
return jsonify(ok=True, restart=restart)
|
||
if what == "screen":
|
||
settings.save_part(store, "screen", system.screen_settings(store, d))
|
||
store.restart_needed = True
|
||
return jsonify(ok=True, restart=True)
|
||
if what == "calibrate":
|
||
system.recalibrate()
|
||
settings.restart(store)
|
||
return jsonify(ok=True)
|
||
if what == "cancel-restore":
|
||
system.cancel()
|
||
return jsonify(ok=True)
|
||
if what == "apply-restore":
|
||
settings.restart(store)
|
||
return jsonify(ok=True)
|
||
except system.Invalid as e:
|
||
return jsonify(error=str(e)), 400
|
||
abort(404)
|
||
|
||
@app.route("/api/status")
|
||
def api_status():
|
||
import settings
|
||
return jsonify({**settings.status(store), "restart": store.restart_needed})
|
||
|
||
@app.route("/api/geocode")
|
||
def api_geocode():
|
||
import settings
|
||
q = (request.args.get("q") or "").strip()[:80]
|
||
if len(q) < 2:
|
||
return jsonify([])
|
||
try:
|
||
return jsonify(settings.geocode(q))
|
||
except Exception as e:
|
||
return jsonify(error=type(e).__name__), 502
|
||
|
||
@app.route("/fonts/<name>")
|
||
def fonts(name):
|
||
path = FONTS.get(name)
|
||
if not path or not os.path.exists(path):
|
||
abort(404)
|
||
return send_file(path, mimetype="font/ttf", max_age=7 * 86400)
|
||
|
||
return app
|
||
|
||
|
||
ADMIN_ONLY = ("/settings", "/api/settings", "/api/restart", "/api/status", "/api/geocode", "/api/users",
|
||
"/api/sync", "/api/system", "/api/screen")
|
||
_preview = {} # the off-screen panel of /api/screen.png, made on first use
|
||
|
||
|
||
class _OwnScreen:
|
||
"""The store as a preview sees it: the same data, its own screen index (and taps, sub-tabs) — the real
|
||
panel's stay as they are."""
|
||
def __init__(self, store, n):
|
||
object.__setattr__(self, "_store", store)
|
||
self.screen, self.hits, self.temp_tab, self.cal_page = n, [], -1, 0
|
||
|
||
def __getattr__(self, k):
|
||
return getattr(self._store, k) # (/api/sync/kick is let through before this: it proves itself)
|
||
WARM = ("/", "/settings") # the plugins keep their own pages warm
|
||
|
||
|
||
def _quietly(fn):
|
||
try:
|
||
fn()
|
||
except Exception as e:
|
||
print(f"web: {fn.__name__}: {e}", flush=True)
|
||
|
||
|
||
def _warm(app):
|
||
"""Open the core pages once after start-up, so the first real visit doesn't pay for
|
||
compiling the templates (≈ 0.5–1 s each on the Pi 3). Plugins keep their own pages
|
||
warm (pluginhost.warm)."""
|
||
import time
|
||
time.sleep(15) # the workers' first fetches come first
|
||
client = app.test_client()
|
||
for path in WARM:
|
||
for v in auth.warm_viewers(): # as each admin account (auth.from_request)
|
||
pluginhost.wait_quiet()
|
||
try:
|
||
client.get(path, environ_base={"dash.internal": True, "dash.viewer": v})
|
||
except Exception as e:
|
||
print(f"web: warm {path}: {type(e).__name__}: {e}", flush=True)
|
||
|
||
|
||
def web_worker(store):
|
||
"""Serve the web view on web.host:web.port (default 0.0.0.0:8080)."""
|
||
from werkzeug.serving import make_server
|
||
wc = store.cfg.get("web") or {}
|
||
logging.getLogger("werkzeug").setLevel(logging.WARNING) # no per-request log lines
|
||
import threading
|
||
app = create_app(store)
|
||
try:
|
||
srv = make_server(wc.get("host", "0.0.0.0"), int(wc.get("port", 8080)), app, threaded=True)
|
||
except OSError as e:
|
||
print("web: cannot start:", e, flush=True)
|
||
return
|
||
print(f"web: serving on http://{srv.host}:{srv.port}/", flush=True)
|
||
if not auth.active():
|
||
print(f"web: no admin account yet — Settings ▸ Users asks for this setup code: {auth.setup_code()}", flush=True)
|
||
threading.Thread(target=_warm, args=(app,), daemon=True, name="web-warm").start()
|
||
srv.serve_forever()
|