#!/usr/bin/env python3 """ Ekeepa Field Dashboard — multi-device sync API. Serves on 0.0.0.0:8097, proxied by ekeepa-dashboard-nginx at /field/api/. Storage: JSON state file + SQLite audit log. Auth: header X-Field-Pass must equal FIELD_PASS. Reads are open (the state is only meaningful to the team and the page itself is public anyway), writes require the pass. Rotate by editing FIELD_PASS below and restarting. Endpoints GET /health -> {status, time} GET /state?device=X -> {state, savedAt, savedBy, updatedAt} POST /save -> body {state:{...}, device:"..."} + X-Field-Pass persists state, appends audit row GET /audit?limit=50 -> recent writes (who/when/what counts) """ import json import os import sqlite3 import socketserver import http.server from datetime import datetime PORT = 8097 BASE = "/data/dashboards/ekeepa/field" STATE_FILE = os.path.join(BASE, "state.json") DB_FILE = os.path.join(BASE, "sync_audit.db") FIELD_PASS = "ekipa-field-1405" def init_db(): os.makedirs(BASE, exist_ok=True) conn = sqlite3.connect(DB_FILE) conn.execute(""" CREATE TABLE IF NOT EXISTS writes ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT, device TEXT, ip TEXT, leads INTEGER, reports INTEGER, state_bytes INTEGER, note TEXT ) """) conn.commit() conn.close() def load_state(): if not os.path.exists(STATE_FILE): return None try: with open(STATE_FILE, "r", encoding="utf-8") as f: return json.load(f) except Exception: return None def save_state(state, device, ip): tmp = STATE_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(state, f, ensure_ascii=False, indent=2) os.replace(tmp, STATE_FILE) try: conn = sqlite3.connect(DB_FILE) conn.execute( "INSERT INTO writes (ts, device, ip, leads, reports, state_bytes, note) " "VALUES (?,?,?,?,?,?,?)", ( datetime.now().isoformat(timespec="seconds"), device or "?", ip or "?", len(state.get("leads") or []), len(state.get("reports") or []), os.path.getsize(STATE_FILE), "save", ), ) conn.commit() conn.close() except Exception as e: print("audit error:", e) class Handler(http.server.BaseHTTPRequestHandler): server_version = "EkeepaFieldSync/1.0" # ---------- helpers ---------- def _h(self, code=200, ctype="application/json; charset=utf-8"): self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") self.send_header( "Access-Control-Allow-Headers", "Content-Type, X-Field-Pass, Authorization" ) self.send_header("Cache-Control", "no-store") self.end_headers() def _json(self, obj, code=200): self._h(code) self.wfile.write(json.dumps(obj, ensure_ascii=False).encode("utf-8")) def log_message(self, fmt, *args): print("%s - %s" % (self.address_string(), fmt % args)) # ---------- verbs ---------- def do_OPTIONS(self): self._h(204) def do_GET(self): path = self.path.split("?")[0].rstrip("/") or "/" query = {} if "?" in self.path: for kv in self.path.split("?", 1)[1].split("&"): if "=" in kv: k, v = kv.split("=", 1) query[k] = v if path in ("/", "/health", "/ping"): self._json({"status": "ok", "time": datetime.now().isoformat(timespec="seconds")}) return if path in ("/state", "/api/state", "/leads"): st = load_state() if st is None: self._json({"state": None, "savedAt": None, "savedBy": None, "message": "no state yet"}) return self._json({ "state": st, "savedAt": st.get("lastSaved"), "savedBy": st.get("lastDevice"), "updatedAt": datetime.fromtimestamp( os.path.getmtime(STATE_FILE) ).isoformat(timespec="seconds"), }) return if path in ("/audit", "/api/audit"): try: limit = min(int(query.get("limit", 50)), 500) except Exception: limit = 50 try: conn = sqlite3.connect(DB_FILE) rows = conn.execute( "SELECT ts, device, ip, leads, reports, state_bytes " "FROM writes ORDER BY id DESC LIMIT ?", (limit,), ).fetchall() conn.close() self._json({ "count": len(rows), "writes": [ {"ts": r[0], "device": r[1], "ip": r[2], "leads": r[3], "reports": r[4], "bytes": r[5]} for r in rows ], }) except Exception as e: self._json({"error": str(e)}, 500) return self._json({"error": "not found", "path": path}, 404) def do_POST(self): path = self.path.split("?")[0].rstrip("/") or "/" if path not in ("/save", "/api/save", "/update"): self._json({"error": "not found"}, 404) return given = (self.headers.get("X-Field-Pass") or "").strip() if given != FIELD_PASS: self._json({"error": "invalid pass", "code": 401}, 401) return try: n = int(self.headers.get("Content-Length", 0)) except Exception: n = 0 if n <= 0 or n > 8_000_000: self._json({"error": "bad body size"}, 400) return try: payload = json.loads(self.rfile.read(n).decode("utf-8")) except Exception as e: self._json({"error": "bad json: %s" % e}, 400) return st = payload.get("state") if not isinstance(st, dict): self._json({"error": "missing state object"}, 400) return device = payload.get("device") or "?" st["lastDevice"] = device st["serverSavedAt"] = datetime.now().isoformat(timespec="seconds") try: save_state(st, device, self.client_address[0]) except Exception as e: self._json({"error": "write failed: %s" % e}, 500) return self._json({ "success": True, "savedAt": st.get("lastSaved"), "savedBy": device, "leads": len(st.get("leads") or []), "reports": len(st.get("reports") or []), "bytes": os.path.getsize(STATE_FILE), }) class ThreadingServer(socketserver.ThreadingMixIn, http.server.HTTPServer): daemon_threads = True allow_reuse_address = True if __name__ == "__main__": init_db() print("Ekeepa Field sync API on :%d" % PORT) print(" state ->", STATE_FILE) print(" audit ->", DB_FILE) ThreadingServer(("0.0.0.0", PORT), Handler).serve_forever()