#!/usr/bin/env python3 """Simple web server: one button to turn off all kids' devices.""" import json from http.server import HTTPServer, BaseHTTPRequestHandler from devices import shutdown_all, status_all, _set_budget, _get_budget, BUDGET_SECONDS, TICK_INTERVAL class Handler(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/" or self.path == "/index.html": self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.end_headers() self.wfile.write(HTML.encode()) elif self.path == "/status": self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps(status_all()).encode()) else: self.send_error(404) def do_POST(self): content_length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(content_length).decode() if content_length > 0 else "" if self.path == "/run": try: actions = shutdown_all() status = "ok" except Exception as e: actions = [{"icon": "❌", "title": "Error", "detail": str(e)}] status = "error" self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps({"status": status, "actions": actions}).encode()) elif self.path == "/budget": try: data = json.loads(body) if body else {} dev_id = data.get("device", "") delta = int(data.get("delta", 0)) current = _get_budget(dev_id) new_budget = max(0, min(BUDGET_SECONDS, current + delta)) _set_budget(dev_id, new_budget) self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps({"status": "ok"}).encode()) except Exception as e: self.send_response(400) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps({"status": "error", "detail": str(e)}).encode()) else: self.send_error(404) def log_message(self, format, *args): pass HTML = """\
TV + Gabi's computer + Gaja's computer