#!/usr/bin/env python3 """THB server, CGI edition (lighttpd + mod_cgi). The Android app talks to the same /api/... routes as thb_server.py; this script only adapts them to the CGI environment. State lives in ../keys/tags.json and writes are serialised with an flock (several CGI processes can run at once). """ import fcntl import json import os import re import sys from pathlib import Path from urllib.parse import parse_qs, urlparse BASE = Path(__file__).resolve().parent.parent # /opt/thb sys.path.insert(0, str(BASE / "server")) import thb_server as srv # noqa: E402 import qr as qrmod # noqa: E402 (pure-python QR encoder, server/qr.py) LOCK_PATH = BASE / "keys" / ".lock" # When the local box has no os-findmy environment (Debian ARM), the FindMy fetch # is forwarded to the PC that does (thb_server.py on :8787). UPSTREAM = os.environ.get("THB_UPSTREAM", "").rstrip("/") REASONS = { 200: "OK", 201: "Created", 204: "No Content", 400: "Bad Request", 401: "Unauthorized", 404: "Not Found", 500: "Internal Server Error", } def _send(code, body, ctype="application/json; charset=utf-8"): if isinstance(body, str): body = body.encode("utf-8") out = sys.stdout.buffer out.write(("Status: %d %s\r\n" % (code, REASONS.get(code, "OK"))).encode()) out.write(("Content-Type: %s\r\n" % ctype).encode()) out.write(b"Access-Control-Allow-Origin: *\r\n") out.write(b"Access-Control-Allow-Methods: GET,POST,DELETE,OPTIONS\r\n") out.write(b"Access-Control-Allow-Headers: Content-Type,X-Auth\r\n") out.write(b"Cache-Control: no-store\r\n") out.write(("Content-Length: %d\r\n\r\n" % len(body)).encode()) out.write(body) def send_json(code, obj): _send(code, json.dumps(obj, ensure_ascii=False)) def read_json_body(): n = int(os.environ.get("CONTENT_LENGTH") or 0) if n <= 0: return {} raw = sys.stdin.buffer.read(n) try: return json.loads(raw.decode("utf-8")) except Exception: # noqa: BLE001 - bad body is the client's problem return {} def locked(fn): """Run fn() with an exclusive lock on the tag database.""" LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) with open(LOCK_PATH, "w") as fh: fcntl.flock(fh, fcntl.LOCK_EX) try: return fn() finally: fcntl.flock(fh, fcntl.LOCK_UN) def fetch_locked(fn): """One Apple fetch at a time. The emulated Mac keeps its ADI state in a single file under /opt/findmy/state, and two emulators writing it at once would corrupt it. """ path = LOCK_PATH.parent / ".fetch.lock" path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w") as fh: fcntl.flock(fh, fcntl.LOCK_EX) try: return fn() finally: fcntl.flock(fh, fcntl.LOCK_UN) def authorized(): if not srv.TOKEN: return True return os.environ.get("HTTP_X_AUTH", "") == srv.TOKEN def serve_static(rel): site = srv.SITE.resolve() target = (site / rel).resolve() if not str(target).startswith(str(site)) or not target.is_file(): return send_json(404, {"error": "not found"}) ctype = { ".html": "text/html; charset=utf-8", ".json": "application/json; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".png": "image/png", ".svg": "image/svg+xml", }.get(target.suffix, "application/octet-stream") _send(200, target.read_bytes(), ctype) def do_get(path, q): parts = [p for p in path.split("/") if p] if path == "/api/health": return send_json(200, { "ok": True, "server": "THB", "cgi": True, "osf": bool(srv.OSF_PY and srv.OSF_PY.exists()), "session": bool(srv.SESSION_FILE and srv.SESSION_FILE.exists()), "time": srv.datetime.now(srv.timezone.utc).isoformat(), }) if not authorized(): return send_json(401, {"error": "unauthorized"}) if path == "/api/qr": # PNG of the same QR that 設定 → QR 表示 makes, so the phone can scan the # server settings instead of typing them. url = (q.get("u", [""])[0] or os.environ.get("THB_PUBLIC_URL", "")).strip() if not url: url = "https://%s/thb" % (os.environ.get("HTTP_HOST") or "dangofactory.net") text = qrmod.config_text(url, srv.TOKEN) try: scale = max(1, min(20, int(q.get("scale", ["8"])[0]))) margin = max(0, min(16, int(q.get("margin", ["4"])[0]))) except ValueError: return send_json(400, {"error": "bad scale/margin"}) return _send(200, qrmod.png_bytes(qrmod.encode(text), scale, margin), "image/png") if path in ("/api/tags", "/api/tags/"): return send_json(200, {"tags": [srv.public_tag(t) for t in srv.load_tags()["tags"]]}) if len(parts) == 3 and parts[:2] == ["api", "tags"]: t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None) return send_json(200, srv.public_tag(t)) if t else send_json(404, {"error": "not found"}) if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "locations": days = int(q.get("days", ["7"])[0]) t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None) if not t: return send_json(404, {"error": "not found"}) return send_json(200, {"id": t["id"], "points": t.get("points", []), "days": days}) if path.startswith("/site/"): return serve_static(path[len("/site/"):]) if path in ("/", "", "/index.html"): return serve_static("index.html") return send_json(404, {"error": "not found"}) def do_post(path, q): parts = [p for p in path.split("/") if p] if path != "/api/health" and not authorized(): return send_json(401, {"error": "unauthorized"}) if path in ("/api/self/points", "/api/self/points/"): body = read_json_body() pts = body.get("points") or [] name = str(body.get("name") or "").strip()[:60] or "この端末" if not isinstance(pts, list): return send_json(400, {"error": "points must be a list"}) def add_self(): db = srv.load_tags() t = next((x for x in db["tags"] if x["id"] == "self"), None) if t is None: t = { "id": "self", "name": name, "created": srv.datetime.now(srv.timezone.utc).isoformat(), "updated": None, "points": [], **srv.new_keypair(), } db["tags"].append(t) before = len(t.get("points", [])) t["points"] = srv.merge_points(t.get("points", []), pts) t["updated"] = srv.datetime.now(srv.timezone.utc).isoformat() srv.save_tags(db) return t, before t, before = locked(add_self) return send_json(200, { "id": "self", "added": len(t["points"]) - before, "total": len(t["points"]), "last": t["points"][-1] if t["points"] else None, }) if path in ("/api/tags", "/api/tags/"): body = read_json_body() name = str(body.get("name") or "").strip()[:60] or "THB" tag = { "id": srv.uuid.uuid4().hex[:12], "name": name, "created": srv.datetime.now(srv.timezone.utc).isoformat(), "updated": None, "points": [], **srv.new_keypair(), } def add_tag(): db = srv.load_tags() db["tags"].append(tag) srv.save_tags(db) locked(add_tag) return send_json(201, srv.public_tag(tag)) if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "name": body = read_json_body() name = str(body.get("name") or "").strip()[:60] if not name: return send_json(400, {"error": "name is empty"}) def rename(): db = srv.load_tags() t2 = next((x for x in db["tags"] if x["id"] == parts[2]), None) if t2 is not None: t2["name"] = name srv.save_tags(db) return t2 t2 = locked(rename) if t2 is None: return send_json(404, {"error": "not found"}) return send_json(200, srv.public_tag(t2)) if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "refresh": days = int(q.get("days", ["7"])[0]) t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None) if not t: return send_json(404, {"error": "not found"}) # No local os-findmy environment: forward the fetch to the PC. if not srv.OSF_PY and UPSTREAM: import urllib.error import urllib.request url = "%s/api/tags/%s/refresh?days=%d" % (UPSTREAM, parts[2], days) req = urllib.request.Request(url, data=b"{}", method="POST") req.add_header("Content-Type", "application/json") if srv.TOKEN: req.add_header("X-Auth", srv.TOKEN) try: with urllib.request.urlopen(req, timeout=180) as r: result = json.loads(r.read().decode("utf-8")) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace") try: return send_json(e.code, json.loads(body)) except ValueError: return send_json(e.code, {"error": body[:200]}) except Exception as e: # noqa: BLE001 return send_json(502, {"error": "upstream %s: %s" % (UPSTREAM, e)}) # Pull the points the PC just collected into the local copy too. try: with urllib.request.urlopen( "%s/api/tags/%s" % (UPSTREAM, parts[2]), timeout=30) as r: remote = json.loads(r.read().decode("utf-8")) def merge_remote(): db = srv.load_tags() t2 = next((x for x in db["tags"] if x["id"] == parts[2]), None) if t2 is not None: t2["points"] = srv.merge_points( t2.get("points", []), remote.get("points", [])) t2["updated"] = srv.datetime.now(srv.timezone.utc).isoformat() srv.save_tags(db) locked(merge_remote) except Exception: # noqa: BLE001 - the refresh itself succeeded pass return send_json(200, result) try: res = fetch_locked(lambda: srv.fetch_for_tag(t, days)) except Exception as e: # noqa: BLE001 - report the reason to the phone return send_json(500, {"error": str(e)}) def merge_refresh(): db = srv.load_tags() t2 = next((x for x in db["tags"] if x["id"] == parts[2]), t) before = len(t2.get("points", [])) t2["points"] = srv.merge_points(t2.get("points", []), res.get("points", [])) t2["updated"] = srv.datetime.now(srv.timezone.utc).isoformat() srv.save_tags(db) return t2, before t, before = locked(merge_refresh) return send_json(200, { "id": t["id"], "encrypted": res.get("encrypted", 0), "added": len(t["points"]) - before, "total": len(t["points"]), "last": t["points"][-1] if t["points"] else None, }) if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "points": body = read_json_body() pts = body.get("points") or [] if not isinstance(pts, list): return send_json(400, {"error": "points must be a list"}) def merge_points(): db = srv.load_tags() t = next((x for x in db["tags"] if x["id"] == parts[2]), None) if not t: return None, 0 before = len(t.get("points", [])) t["points"] = srv.merge_points(t.get("points", []), pts) t["updated"] = srv.datetime.now(srv.timezone.utc).isoformat() srv.save_tags(db) return t, before t, before = locked(merge_points) if t is None: return send_json(404, {"error": "not found"}) return send_json(200, { "id": t["id"], "added": len(t["points"]) - before, "total": len(t["points"]), "last": t["points"][-1] if t["points"] else None, }) return send_json(404, {"error": "not found"}) def do_delete(path): if not authorized(): return send_json(401, {"error": "unauthorized"}) m = re.fullmatch(r"/api/tags/([0-9a-zA-Z]+)/?", path) if not m: return send_json(404, {"error": "not found"}) tag_id = m.group(1) def delete(): db = srv.load_tags() t = next((x for x in db["tags"] if x["id"] == tag_id), None) if t is None: return None if tag_id == "self" or t.get("protected"): return "protected" before = len(db["tags"]) db["tags"] = [x for x in db["tags"] if x["id"] != tag_id] srv.save_tags(db) return before - len(db["tags"]) res = locked(delete) if res is None: return send_json(404, {"error": "not found"}) if res == "protected": return send_json(403, {"error": "この端末の記録は削除できません"}) return send_json(200, {"deleted": res}) def main(): srv.TOKEN = os.environ.get("THB_TOKEN", "") method = os.environ.get("REQUEST_METHOD", "GET").upper() path = os.environ.get("PATH_INFO") or "" if not path or path == "/": path = urlparse(os.environ.get("REQUEST_URI", "/")).path # strip the mount point (/thb) if path.startswith("/thb/"): path = path[len("/thb"):] elif path == "/thb": path = "/" q = parse_qs(os.environ.get("QUERY_STRING", "")) try: if method == "OPTIONS": _send(204, b"") elif method == "GET": do_get(path, q) elif method == "POST": do_post(path, q) elif method == "DELETE": do_delete(path) else: send_json(405, {"error": "method not allowed"}) except Exception as e: # noqa: BLE001 - never let a CGI crash silently import traceback traceback.print_exc(file=sys.stderr) send_json(500, {"error": "%s: %s" % (type(e).__name__, e)}) if __name__ == "__main__": main()