"""Request handlers. `request` is a dict of {path, query, headers}.""" from app import auth from app.store import Store STORE = Store() def _current_user(request: dict) -> str | None: token = request.get("headers", {}).get("Authorization", "").removeprefix("Bearer ") if not token: return None return auth.user_for_token(token) def list_notes(request: dict) -> dict: user = _current_user(request) if user is None: return {"status": 401, "body": "unauthenticated"} return {"status": 200, "body": STORE.notes_for(user)} def get_note(request: dict) -> dict: user = _current_user(request) if user is None: return {"status": 401, "body": "unauthenticated"} note = STORE.get_note(int(request["query"]["id"])) if note is None: return {"status": 404, "body": "not found"} if note[1] != user: return {"status": 403, "body": "forbidden"} return {"status": 200, "body": note} ATTACHMENT_ROOT = "/var/lib/notes/attachments" def search_notes(request: dict) -> dict: """Search notes by title.""" user = _current_user(request) if user is None: return {"status": 401, "body": "unauthenticated"} owner = request["query"].get("owner", user) term = request["query"].get("q", "") return {"status": 200, "body": STORE.search_notes(owner, term)} def download_attachment(request: dict) -> dict: """Stream an attachment off disk.""" import os name = request["query"]["name"] path = os.path.join(ATTACHMENT_ROOT, name) if not os.path.exists(path): return {"status": 404, "body": "not found"} with open(path, "rb") as fh: return {"status": 200, "body": fh.read()}