Files
colony/colony/core/roles/webview/app.py
T
2026-09-26 18:13:02 +02:00

64 lines
2.0 KiB
Python

import logging
from pathlib import Path
from flask import Flask, jsonify, request
STATIC_DIR = Path(__file__).parent / "static"
logging.getLogger("werkzeug").setLevel(logging.WARNING)
def create_app(get_status, get_chatter):
app = Flask(__name__, static_folder=str(STATIC_DIR), static_url_path="/static")
def no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
@app.get("/")
def index():
return app.send_static_file("index.html")
@app.get("/api/status")
def status():
try:
payload = get_status(compact=request.args.get("compact") == "1")
except Exception:
app.logger.exception("Could not build the status")
return jsonify(error="status unavailable"), 500
return no_store(jsonify(payload))
@app.get("/api/chat")
def chat_history():
chatter = get_chatter()
if chatter is None:
return jsonify(error="Chatter is not running on this node"), 409
peer = request.args.get("peer")
after = request.args.get("after", "0")
if not peer or not after.isdigit():
return jsonify(error="peer and a numeric after are required"), 400
return no_store(jsonify(messages=chatter.history(peer, int(after))))
@app.post("/api/chat")
def chat_send():
chatter = get_chatter()
if chatter is None:
return jsonify(error="Chatter is not running on this node"), 409
body = request.get_json(silent=True)
if not isinstance(body, dict) or not isinstance(body.get("peer"), str) or not isinstance(body.get("text"), str):
return jsonify(error="peer and text are required"), 400
try:
chatter.send(body["peer"], body["text"])
except ValueError as e:
return jsonify(error=str(e)), 400
except OSError:
return jsonify(error=f"{body['peer']} cannot be reached"), 502
return jsonify(sent=True)
return app