diff --git a/AGENTS.md b/AGENTS.md index bbe2778..e7c5792 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -243,8 +243,8 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py: `gateway.simplex` / `gateway.lxmf` / `gateway.voice`. The gateway MUST NOT read history, show/create invite links, or compose messages — see "gateway isolation" below. -bridges/ standalone third-party API bridges (SimpleX first, plus the - LLM bridge). base.py: +bridges/ standalone third-party API bridges (SimpleX, the LLM bridge, + and Nextcloud). base.py: BridgeInfo + BridgeService (shared localhost JSON HTTP layer, `X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO + contacts learned from inbound DMs and the daemon contact list, @@ -257,6 +257,12 @@ bridges/ standalone third-party API bridges (SimpleX first, plus the scheduler's configured `llm` client (reused, not re-configured), so bodies get short generated text (e.g. an event title + description) over HTTP. + nextcloud.py + nextcloud_client.py: NextcloudBridge — files + (WebDAV), calendar events + tasks (CalDAV), contacts (CardDAV), + and Notes (OCS) behind one JSON surface, so bodies never speak + DAV/OCS; no service daemon (stdlib-only), connection from + `bridges.nextcloud` with a fallback to the top-level + `nextcloud_*` values the calendar seeds use. registry.py: CATALOG, describe_bridges() (catalog injected into the codegen prompts), run_bridges() (threads the scheduler's `llm` client into the LLM bridge). Run with `python -m @@ -1287,6 +1293,35 @@ CLI, unit tests (24) + integration tests (2). client it reports `502`, never a fabricated reply. `calendar.create_event` is the first consumer (title + description extraction, cached in `request.meta` across a `needs_input` resume). +- **Nextcloud bridge** (`bridges/nextcloud.py` + `bridges/nextcloud_client.py`). + Wraps the account's native protocols — WebDAV files, CalDAV calendar events and + tasks (VTODO), CardDAV contacts, and the OCS Notes API — behind one uniform + JSON surface, so a body never speaks DAV/OCS directly. It has **no service + daemon** (Nextcloud is plain HTTPS) and is stdlib-only (`urllib` + `xml.etree` + + `ssl`), so `check_requirements` is always `(True, None)` and it starts + instantly inside the existing `semif-bridge.service`. HTTP Basic auth uses the + username + app password. The connection is configured in `bridges.nextcloud` + (`url`/`username`/`app_password`, plus `default_calendar`/`default_addressbook` + and `verify_tls`/`timeout`); `build_bridge` passes the top-level + `nextcloud_url`/`nextcloud_username`/`nextcloud_app_password`/ + `nextcloud_default_calendar`/`nextcloud_default_addressbook` as a fallback, so + the same account the calendar seeds collect is configured once and a block value + wins. Bodies reach it via the top-level `nextcloud_bridge_url` (+ optional + `nextcloud_bridge_token`); the `BridgeInfo` declares only those two config vars. + Routes (reads `GET`, mutations `POST`): files (`/files`, `/files/stat`, + `/files/read` text-or-base64, `/files/search`, `/files/write|mkdir|delete|move|copy`), + calendars (`/calendars`, `/calendars/events` list, `POST /calendars/events` + + `/update` + `/delete`), tasks (`/tasks` list, `POST /tasks` + `/update` + + `/complete` + `/delete`), contacts (`/addressbooks`, `/contacts` list/search, + `POST /contacts` + `/update` + `/delete`), notes (`/notes`, `/notes/get`, + `POST /notes` + `/update` + `/delete`), and `/user` + `/capabilities` (OCS). + A missing connection is `503`; a real failure (`NextcloudError` — transport, + HTTP error, or bad reply) is `502`, never a fabricated success. Event/task + updates edit the stored iCalendar properties in place (preserving VALARM/ + ATTENDEE), guarded by `If-Match`; creates use `If-None-Match: *`. Calendar/ + addressbook defaults resolve from config when a request names none and the + account has several. `tests/test_nextcloud_bridge.py` drives the real client + over a loopback `http.server` faking Nextcloud's DAV/OCS shapes. ## Bridge backlog (one session per item) @@ -1324,9 +1359,12 @@ The bridge read path (`simplex.next_message`) and contact-link lookup (threaded through `run_bridges`/`build_bridge`, never re-configured), registered in `CATALOG` and seeded under `bridges.llm` + top-level `llm_bridge_url`. `calendar.create_event` extracts its title + description through it. -- [ ] **5. More bridges.** Each new third-party API gets its own `bridges/.py` +- [x] **5. More bridges.** Each new third-party API gets its own `bridges/.py` + config block + `CATALOG` entry; the codegen prompts pick it up automatically - through `describe_bridges()`. + through `describe_bridges()`. Nextcloud shipped (`bridges/nextcloud.py` + + `bridges/nextcloud_client.py`): files/calendars/tasks/contacts/notes over one + JSON surface, no daemon, connection from `bridges.nextcloud` with a top-level + `nextcloud_*` fallback. Future bridges follow the same shape. ### Code principles - **Contain installation artifacts in the repo.** Everything a machine installs diff --git a/README.md b/README.md index de7bcab..dc9364f 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ semif_agent/ voice_transport.py neutral voice transport: mic capture, wake word, VAD, speech-to-text (faster-whisper), text-to-speech (Piper) gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) - bridges/ standalone third-party API bridges (SimpleX + the LLM bridge) + bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud) seeds/ committed starter skills (calendar, simplex) scripts/ bootstrap.sh, simplex-address.py, systemd/*.in requirements/ staging.txt — the pinned engine deps @@ -516,6 +516,8 @@ Key blocks: | `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call | | `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) | | `llm_bridge_url` / `llm_bridge_token` | what skill bodies call for generation | +| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) | +| `nextcloud_bridge_url` / `nextcloud_bridge_token` | what skill bodies call for Nextcloud | | `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) | | `dashboard` | bind host/port | @@ -684,9 +686,10 @@ python -m semif_agent.cli gateway --platform voice ### Bridge services `cli bridge` runs standalone bridges: each is a process that stands up a small, -token-guarded localhost HTTP API in front of one third-party system and owns its -own daemon/profile. Generated skill bodies call them like any HTTP service (base -URL from a config var), so they never speak a native protocol directly. +token-guarded localhost HTTP API in front of one third-party system (and, where +the system needs one, owns its own daemon/profile). Generated skill bodies call +them like any HTTP service (base URL from a config var), so they never speak a +native protocol directly. The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own simplex-chat daemon separate from the gateway's. Its HTTP surface: @@ -728,6 +731,45 @@ carries just the local listener. Skills call it via `llm_bridge_url` fabricated reply. It starts in the same `semif-bridge.service` process as the other enabled bridges. +The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it +wraps the account's native protocols — WebDAV files, CalDAV calendar events and +tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a +body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is +plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly +in the same `semif-bridge` process. The connection (base URL, username, app +password) is configured in `bridges.nextcloud` and falls back to the top-level +`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` / +`nextcloud_default_calendar` the calendar seeds use, so the account is +configured once. Skills call it via `nextcloud_bridge_url` (+ optional +`nextcloud_bridge_token`). Its HTTP surface: + +``` +GET /health +GET /user # account info (OCS) +GET /capabilities # server capabilities (OCS) +GET /files?path= # list a folder (WebDAV) +GET /files/stat?path= +GET /files/read?path= # text, or base64 for binary +GET /files/search?query=&path= +POST /files/write {"path","content","encoding"?,"overwrite"?} +POST /files/mkdir | /files/delete | /files/move | /files/copy +GET /calendars +GET /calendars/events?calendar=&start=&end= # CalDAV VEVENT +POST /calendars/events | /calendars/events/update | /calendars/events/delete +GET /tasks?calendar= # CalDAV VTODO +POST /tasks | /tasks/update | /tasks/complete | /tasks/delete +GET /addressbooks +GET /contacts?addressbook=&query= # CardDAV +POST /contacts | /contacts/update | /contacts/delete +GET /notes | /notes/get?id= # Notes app (OCS) +POST /notes | /notes/update | /notes/delete +``` + +A missing connection is `503`; a real Nextcloud failure (transport, HTTP error, +or a bad reply) is `502` — never a fabricated success. Calendar and addressbook +defaults resolve from `bridges.nextcloud` when a request names none and the +account has several. + ### Dream report ```sh diff --git a/config.example.json b/config.example.json index 928b1f6..6b01190 100644 --- a/config.example.json +++ b/config.example.json @@ -121,6 +121,8 @@ "simplex_bridge_token": "", "llm_bridge_url": "http://127.0.0.1:5229", "llm_bridge_token": "", + "nextcloud_bridge_url": "http://127.0.0.1:5230", + "nextcloud_bridge_token": "", "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", "category_registry": "data/categories.json", @@ -151,6 +153,20 @@ "host": "127.0.0.1", "port": 5229, "token": "" + }, + "nextcloud": { + "_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_addressbook` are used when a request names none and the account has several. `verify_tls` false skips certificate verification (self-signed hosts). Skills use the top-level `nextcloud_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", + "enabled": true, + "host": "127.0.0.1", + "port": 5230, + "token": "", + "url": "", + "username": "", + "app_password": "", + "default_calendar": "", + "default_addressbook": "", + "verify_tls": true, + "timeout": 30 } }, "gateway": { diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 62d0955..94b7735 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -624,6 +624,13 @@ LLM bridge (generation for skills): - Runs inside the same 'semif-bridge' process. It reuses the top-level `llm` model (configured once) and serves a generic POST /chat; skills call it via the top-level llm_bridge_url (default http://127.0.0.1:5229). + +Nextcloud bridge (files/calendar/tasks/contacts/notes for skills): + - Runs inside the same 'semif-bridge' process (Nextcloud is plain HTTPS, so + there is no separate daemon). Configure the account once in config.json under + bridges.nextcloud (url/username/app_password) — or reuse the top-level + nextcloud_* values the calendar seeds collect. Skills call it via the + top-level nextcloud_bridge_url (default http://127.0.0.1:5230). EOF if [[ "$VOICE" = 1 ]]; then diff --git a/semif_agent/bridges/__init__.py b/semif_agent/bridges/__init__.py index a9149e1..1599454 100644 --- a/semif_agent/bridges/__init__.py +++ b/semif_agent/bridges/__init__.py @@ -1,9 +1,9 @@ """Third-party API bridges: a secure local layer between skills and services. A **bridge service** is a standalone process that exposes one third-party system -(SimpleX, the local language model) to codegen-authored skill bodies over a -local, token-guarded HTTP API. It exists so a generated body never speaks a -system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat +(SimpleX, the local language model, Nextcloud) to codegen-authored skill bodies +over a local, token-guarded HTTP API. It exists so a generated body never speaks +a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP surface instead, and the bridge owns the messy integration details and credentials. diff --git a/semif_agent/bridges/nextcloud.py b/semif_agent/bridges/nextcloud.py new file mode 100644 index 0000000..bbc6013 --- /dev/null +++ b/semif_agent/bridges/nextcloud.py @@ -0,0 +1,501 @@ +"""Nextcloud bridge: files, calendars, tasks, contacts, and notes over HTTP. + +Nextcloud speaks several native protocols (WebDAV for files, CalDAV for events +and tasks, CardDAV for contacts, and OCS for the Notes app and server info). A +codegen-authored skill body must never speak those directly. This bridge owns the +connection — base URL, username, and app password — and exposes one uniform, +token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` and +`nextcloud_bridge_token` from `ctx.config` and calls a documented route. + +There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only +(`urllib` + `xml.etree`) and starts instantly. The connection comes from +`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook), +falling back to the top-level `nextcloud_url`/`nextcloud_username`/ +`nextcloud_app_password`/`nextcloud_default_calendar` values the calendar seeds +already use, so the same account is configured in one place. + +The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate +input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated +success. +""" + +from __future__ import annotations + +import uuid + +from .base import BridgeInfo, BridgeService +from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError + + +class NextcloudBridge(BridgeService): + name = "nextcloud" + INFO = BridgeInfo( + name="nextcloud", + service="nextcloud", + description=( + "Read and write the user's Nextcloud: files (WebDAV), calendar events " + "and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app)." + ), + url_config_var="nextcloud_bridge_url", + endpoints=( + "GET /health -> 200 {\"ok\": true, \"platform\": \"nextcloud\"} — the " + "bridge is up", + "GET /user -> 200 {\"user\": {id, display_name, email, language, " + "locale}} — the account (OCS)", + "GET /capabilities -> 200 {Nextcloud server capabilities} (OCS)", + "GET /files?path= -> 200 {\"path\", \"entries\": [{name, path, " + "type (file|dir), size, modified, etag, content_type}]} — list a " + "folder (default /)", + "GET /files/stat?path= -> 200 {one entry, same fields as an " + "entries item}", + "GET /files/read?path= -> 200 {\"path\", \"content\", " + "\"encoding\" (utf-8|base64), \"size\"} — file contents; binary is " + "base64", + "GET /files/search?query=&path= -> 200 {\"results\": " + "[entry]} — filename search under a folder", + "POST /files/write {\"path\", \"content\", \"encoding\"?: " + "utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\"}", + "POST /files/mkdir {\"path\"} -> 200 {\"ok\": true, \"path\"}", + "POST /files/delete {\"path\"} -> 200 {\"ok\": true, \"path\"}", + "POST /files/move {\"path\", \"destination\", \"overwrite\"?: bool} " + "-> 200 {\"ok\": true, \"path\", \"destination\"}", + "POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} " + "-> 200 {\"ok\": true, \"path\", \"destination\"}", + "GET /calendars -> 200 {\"calendars\": [{name, label, description, " + "color, ctag}]}", + "GET /calendars/events?calendar=&start=&end= -> 200 " + "{\"calendar\", \"events\": [{uid, summary, start, end, all_day, " + "location, description, rrule, status, href, etag}]} — start/end " + "optional (ISO 8601); without them every event is returned", + "POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", " + "\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, " + "\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", " + "\"calendar\", \"etag\"}", + "POST /calendars/events/update {\"calendar\"?, \"uid\", \"summary\"?, " + "\"start\"?, \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, " + "\"rrule\"?} -> 200 {\"ok\": true, \"uid\", \"calendar\", \"etag\"} — " + "only the named fields change", + "POST /calendars/events/delete {\"calendar\"?, \"uid\"} -> 200 " + "{\"ok\": true, \"uid\", \"calendar\"}", + "GET /tasks?calendar= -> 200 {\"calendar\", \"tasks\": [{uid, " + "summary, due, status, percent_complete, priority, description, href, " + "etag}]} — CalDAV VTODO", + "POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, " + "\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", " + "\"calendar\", \"etag\"}", + "POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, " + "\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} " + "-> 200 {ok, uid}", + "POST /tasks/complete {\"calendar\"?, \"uid\"} -> 200 {ok, uid} — " + "marks the task COMPLETED", + "POST /tasks/delete {\"calendar\"?, \"uid\"} -> 200 {ok}", + "GET /addressbooks -> 200 {\"addressbooks\": [{name, label, " + "description}]}", + "GET /contacts?addressbook=&query= -> 200 " + "{\"addressbook\", \"contacts\": [{uid, fn, n, emails, phones, org, " + "title, note, url, href, etag}]} — query filters by name/org/email/" + "phone", + "POST /contacts {\"addressbook\"?, \"uid\"?, \"fn\", \"emails\"?, " + "\"phones\"?, \"org\"?, \"title\"?, \"note\"?, \"url\"?, \"n\"?} -> " + "200 {ok, uid}", + "POST /contacts/update {\"addressbook\"?, \"uid\", ...fields} -> 200 " + "{ok, uid}", + "POST /contacts/delete {\"addressbook\"?, \"uid\"} -> 200 {ok}", + "GET /notes -> 200 {\"notes\": [{id, title, category, modified, ...}]} " + "— Nextcloud Notes app (metadata only)", + "GET /notes/get?id= -> 200 {\"note\": {id, title, content, " + "category, ...}}", + "POST /notes {\"title\", \"content\"?, \"category\"?} -> 200 " + "{\"note\": {...}}", + "POST /notes/update {\"id\", \"title\"?, \"content\"?, " + "\"category\"?} -> 200 {\"note\": {...}}", + "POST /notes/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}", + "any request -> 401 {\"error\": \"unauthorized\"} when the token is " + "configured and the auth header is missing or wrong", + "503 {\"error\": \"...\"} when the bridge has no Nextcloud connection " + "configured; 502 {\"error\": \"...\"} on a real Nextcloud failure " + "(transport, HTTP error, or bad reply)", + ), + config_vars=("nextcloud_bridge_url", "nextcloud_bridge_token"), + config_var_docs=( + ( + "nextcloud_bridge_url", + "Base URL of the local Nextcloud bridge (e.g. " + "http://127.0.0.1:5230); never hardcode it in the body.", + ), + ( + "nextcloud_bridge_token", + "Shared secret for the bridge, if one is configured; sent as the " + "X-Semif-Token header. Leave blank when the bridge requires no auth.", + ), + ), + auth_header="X-Semif-Token", + auth_config_var="nextcloud_bridge_token", + ) + + def __init__(self, config: dict | None = None, trace=None, fallback: dict | None = None, client=None): + super().__init__(config, trace) + cfg = config or {} + fb = fallback or {} + + def pick(key: str, default=""): + value = cfg.get(key) + if value in (None, ""): + value = fb.get(key) + return default if value in (None, "") else value + + self.url = str(pick("url")).strip() + self.username = str(pick("username")).strip() + self.app_password = str(pick("app_password")) + self.default_calendar = str(pick("default_calendar")).strip() + self.default_addressbook = str(pick("default_addressbook")).strip() + self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True))) + self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT)) + #: A test seam: inject a client double. Production builds the real one. + self.client = client or NextcloudClient( + self.url, + self.username, + self.app_password, + timeout=self.timeout, + verify_tls=self.verify_tls, + default_calendar=self.default_calendar, + default_addressbook=self.default_addressbook, + ) + + # ---- lifecycle ---- + + def check_requirements(self) -> tuple[bool, str | None]: + # Stdlib only: no missing dependency can make the bridge unstartable. A + # missing connection surfaces as a 503 on the call, not a startup failure. + return True, None + + # ---- routes ---- + + def handle_get(self, path: str, query: dict) -> tuple[int, dict]: + if path == "/health": + return 200, {"ok": True, "platform": self.name} + if not self.client.configured: + return self._unconfigured() + try: + return self._get(path, query) + except NextcloudError as exc: + return 502, {"error": str(exc)[:300]} + except ValueError as exc: + return 400, {"error": str(exc)[:300]} + + def handle_post(self, path: str, payload: dict) -> tuple[int, dict]: + if not self.client.configured: + return self._unconfigured() + try: + return self._post(path, payload) + except NextcloudError as exc: + return 502, {"error": str(exc)[:300]} + except ValueError as exc: + return 400, {"error": str(exc)[:300]} + + def _unconfigured(self) -> tuple[int, dict]: + return 503, { + "error": ( + "the Nextcloud bridge has no connection configured (set " + "bridges.nextcloud.url/username/app_password, or the top-level " + "nextcloud_url/nextcloud_username/nextcloud_app_password)" + ) + } + + def _get(self, path: str, query: dict) -> tuple[int, dict]: + if path == "/user": + return 200, {"user": self.client.user_info()} + if path == "/capabilities": + return 200, self.client.capabilities() + if path == "/files": + return 200, self.client.list_files(self._q(query, "path", "/") or "/") + if path == "/files/stat": + return 200, self.client.stat(self._required_query(query, "path")) + if path == "/files/read": + return 200, self.client.read_file(self._required_query(query, "path")) + if path == "/files/search": + query_text = self._required_query(query, "query") + return 200, { + "results": self.client.search( + query_text, self._q(query, "path", "/") or "/" + ) + } + if path == "/calendars": + return 200, {"calendars": self.client.list_calendars()} + if path == "/calendars/events": + calendar = self._resolve_calendar(self._q(query, "calendar")) + return 200, { + "calendar": calendar, + "events": self.client.list_events( + calendar, + self._q(query, "start", "") or "", + self._q(query, "end", "") or "", + ), + } + if path == "/tasks": + calendar = self._resolve_calendar(self._q(query, "calendar")) + return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)} + if path == "/addressbooks": + return 200, {"addressbooks": self.client.list_addressbooks()} + if path == "/contacts": + addressbook = self._resolve_addressbook(self._q(query, "addressbook")) + return 200, { + "addressbook": addressbook, + "contacts": self.client.list_contacts( + addressbook, self._q(query, "query", "") or "" + ), + } + if path == "/notes": + return 200, {"notes": self.client.list_notes()} + if path == "/notes/get": + return 200, {"note": self.client.get_note(self._required_query(query, "id"))} + return 404, {"error": "not found"} + + def _post(self, path: str, payload: dict) -> tuple[int, dict]: + if path == "/files/write": + return 200, self.client.write_file( + self._required(payload, "path"), + self._required(payload, "content", allow_empty=True), + self._optional_str(payload, "encoding", "utf-8"), + self._optional_bool(payload, "overwrite", True), + ) + if path == "/files/mkdir": + return 200, self.client.mkdir(self._required(payload, "path")) + if path == "/files/delete": + return 200, self.client.delete(self._required(payload, "path")) + if path == "/files/move": + return 200, self.client.move( + self._required(payload, "path"), + self._required(payload, "destination"), + self._optional_bool(payload, "overwrite", False), + ) + if path == "/files/copy": + return 200, self.client.copy( + self._required(payload, "path"), + self._required(payload, "destination"), + self._optional_bool(payload, "overwrite", False), + ) + if path == "/calendars/events": + return 200, self._create_event(payload) + if path == "/calendars/events/update": + return 200, self._update_event(payload) + if path == "/calendars/events/delete": + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + return 200, self.client.delete_object(calendar, self._required(payload, "uid")) + if path == "/tasks": + return 200, self._create_task(payload) + if path == "/tasks/update": + return 200, self._update_task(payload) + if path == "/tasks/complete": + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + return 200, self.client.complete_task(calendar, self._required(payload, "uid")) + if path == "/tasks/delete": + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + return 200, self.client.delete_object(calendar, self._required(payload, "uid")) + if path == "/contacts": + return 200, self._create_contact(payload) + if path == "/contacts/update": + return 200, self._update_contact(payload) + if path == "/contacts/delete": + addressbook = self._resolve_addressbook( + self._optional_str(payload, "addressbook") + ) + return 200, self.client.delete_contact( + addressbook, self._required(payload, "uid") + ) + if path == "/notes": + return 200, { + "note": self.client.create_note( + self._required(payload, "title"), + self._optional_str(payload, "content"), + self._optional_str(payload, "category"), + ) + } + if path == "/notes/update": + return 200, {"note": self._update_note(payload)} + if path == "/notes/delete": + return 200, self.client.delete_note(self._required_id(payload)) + return 404, {"error": "not found"} + + # ---- calendar/task helpers ---- + + def _create_event(self, payload: dict) -> dict: + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + uid = self._optional_str(payload, "uid") or uuid.uuid4().hex + return self.client.create_event( + calendar, + uid, + summary=self._required(payload, "summary"), + start=self._required(payload, "start"), + end=self._optional_str(payload, "end"), + all_day=self._optional_bool(payload, "all_day", False), + location=self._optional_str(payload, "location"), + description=self._optional_str(payload, "description"), + rrule=self._optional_str(payload, "rrule"), + overwrite=self._optional_bool(payload, "overwrite", False), + ) + + def _update_event(self, payload: dict) -> dict: + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + uid = self._required(payload, "uid") + changes = { + key: payload[key] + for key in ("summary", "start", "end", "location", "description", "rrule") + if key in payload + } + if "all_day" in payload: + changes["all_day"] = self._optional_bool(payload, "all_day", False) + return self.client.update_event(calendar, uid, **changes) + + def _create_task(self, payload: dict) -> dict: + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + uid = self._optional_str(payload, "uid") or uuid.uuid4().hex + return self.client.create_task( + calendar, + uid, + summary=self._required(payload, "summary"), + due=self._optional_str(payload, "due"), + priority=self._optional_int(payload, "priority"), + description=self._optional_str(payload, "description"), + ) + + def _update_task(self, payload: dict) -> dict: + calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + uid = self._required(payload, "uid") + changes = { + key: payload[key] + for key in ("summary", "due", "priority", "description", "status", "percent_complete") + if key in payload + } + return self.client.update_task(calendar, uid, **changes) + + # ---- contact helpers ---- + + def _create_contact(self, payload: dict) -> dict: + addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook")) + uid = self._optional_str(payload, "uid") or uuid.uuid4().hex + return self.client.create_contact( + addressbook, + uid, + fn=self._required(payload, "fn"), + n=self._optional_str(payload, "n"), + emails=self._string_list(payload, "emails"), + phones=self._string_list(payload, "phones"), + org=self._optional_str(payload, "org"), + title=self._optional_str(payload, "title"), + note=self._optional_str(payload, "note"), + url=self._optional_str(payload, "url"), + ) + + def _update_contact(self, payload: dict) -> dict: + addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook")) + uid = self._required(payload, "uid") + changes = {} + for key in ("fn", "n", "org", "title", "note", "url"): + if key in payload: + changes[key] = payload[key] + for key in ("emails", "phones"): + if key in payload: + changes[key] = self._string_list(payload, key) + return self.client.update_contact(addressbook, uid, **changes) + + # ---- notes helpers ---- + + def _update_note(self, payload: dict) -> dict: + note_id = self._required_id(payload) + changes = { + key: payload[key] for key in ("title", "content", "category") if key in payload + } + return self.client.update_note(note_id, **changes) + + # ---- default resolution ---- + + def _resolve_calendar(self, name) -> str: + name = str(name or self.default_calendar or "").strip() + if name: + return name + calendars = self.client.list_calendars() + if len(calendars) == 1: + return calendars[0]["name"] + raise ValueError( + "calendar is required (name one in the request, or set " + "bridges.nextcloud.default_calendar)" + ) + + def _resolve_addressbook(self, name) -> str: + name = str(name or self.default_addressbook or "").strip() + if name: + return name + addressbooks = self.client.list_addressbooks() + if len(addressbooks) == 1: + return addressbooks[0]["name"] + raise ValueError( + "addressbook is required (name one in the request, or set " + "bridges.nextcloud.default_addressbook)" + ) + + # ---- input helpers ---- + + @staticmethod + def _q(query: dict, key: str, default=None): + values = query.get(key) + if not values: + return default + return values[0] + + @staticmethod + def _required_query(query: dict, key: str) -> str: + value = NextcloudBridge._q(query, key) + if value is None or not str(value).strip(): + raise ValueError(f"{key} is required") + return str(value).strip() + + @staticmethod + def _required(payload: dict, key: str, allow_empty: bool = False) -> str: + value = payload.get(key) + if not isinstance(value, str) or (not allow_empty and not value.strip()): + raise ValueError(f"{key} is required") + return value if allow_empty else value.strip() + + @staticmethod + def _required_id(payload: dict): + value = payload.get("id") + if value is None or (isinstance(value, str) and not value.strip()): + raise ValueError("id is required") + return value + + @staticmethod + def _optional_str(payload: dict, key: str, default: str = "") -> str: + value = payload.get(key) + if value is None: + return default + if not isinstance(value, str): + raise ValueError(f"{key} must be a string") + return value + + @staticmethod + def _optional_bool(payload: dict, key: str, default: bool) -> bool: + value = payload.get(key) + if value is None: + return default + if not isinstance(value, bool): + raise ValueError(f"{key} must be a boolean") + return value + + @staticmethod + def _optional_int(payload: dict, key: str): + value = payload.get(key) + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{key} must be an integer") + return value + + @staticmethod + def _string_list(payload: dict, key: str) -> list[str]: + value = payload.get(key) + if value is None: + return [] + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise ValueError(f"{key} must be a list of strings") + return value diff --git a/semif_agent/bridges/nextcloud_client.py b/semif_agent/bridges/nextcloud_client.py new file mode 100644 index 0000000..f148a7f --- /dev/null +++ b/semif_agent/bridges/nextcloud_client.py @@ -0,0 +1,1229 @@ +"""A small, real Nextcloud client: WebDAV, CalDAV, CardDAV, and OCS over stdlib. + +The Nextcloud bridge calls this instead of a skill body speaking the DAV/OCS +protocols directly. It owns the connection (base URL, username, app password), +the HTTP Basic auth, the XML request bodies, and the iCalendar/vCard parsing, and +returns plain dicts. Every failure is a `NextcloudError` carrying the HTTP status +when there was one, so the bridge can map it to a 502 (a real Nextcloud failure) +rather than a fabricated success. + +Only the stdlib is used: `urllib.request` (arbitrary DAV methods), `xml.etree`, +`ssl`, `base64`, and `json`. No third-party DAV/iCalendar library. +""" + +from __future__ import annotations + +import base64 +import json +import re +import ssl +import urllib.error +import urllib.parse +import urllib.request +import xml.etree.ElementTree as ET +from datetime import date, datetime, timezone +from xml.sax.saxutils import escape as _xml_escape + +DAV = "DAV:" +CALDAV = "urn:ietf:params:xml:ns:caldav" +CARDDAV = "urn:ietf:params:xml:ns:carddav" +OC = "http://owncloud.org/ns" +NC = "http://nextcloud.org/ns" + +DEFAULT_TIMEOUT = 30.0 + + +class NextcloudError(Exception): + """A real failure talking to Nextcloud (transport, HTTP, or a bad reply).""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +# ---- small helpers ---------------------------------------------------------- + + +def _text(element) -> str: + if element is None: + return "" + return (element.text or "").strip() + + +def _int(value, default=None): + try: + return int(str(value).strip()) + except (TypeError, ValueError): + return default + + +def _norm_path(path) -> str: + """A user-facing DAV path: always leading `/`, no trailing slash (root `/`).""" + text = "/" + str(path or "").strip("/") + return "/" if text == "/" else text + + +def _quote_path(path) -> str: + segments = [s for s in str(path or "").split("/") if s] + if not segments: + return "/" + return "/" + "/".join(urllib.parse.quote(segment, safe="") for segment in segments) + + +def _unescape_text(value: str) -> str: + """Undo iCalendar/vCard backslash escapes (`\\n`, `\\,`, `\\;`, `\\\\`).""" + out: list[str] = [] + index = 0 + while index < len(value): + char = value[index] + if char == "\\" and index + 1 < len(value): + nxt = value[index + 1] + out.append({"n": "\n", "N": "\n", ",": ",", ";": ";", "\\": "\\"}.get(nxt, nxt)) + index += 2 + else: + out.append(char) + index += 1 + return "".join(out) + + +def _escape_text(value) -> str: + return ( + str(value) + .replace("\\", "\\\\") + .replace(";", "\\;") + .replace(",", "\\,") + .replace("\r\n", "\\n") + .replace("\n", "\\n") + .replace("\r", "\\n") + ) + + +def _unfold(text: str) -> list[str]: + """Split into unfolded logical lines (RFC 5545/6350 line folding).""" + lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") + out: list[str] = [] + for line in lines: + if line[:1] in (" ", "\t") and out: + out[-1] += line[1:] + else: + out.append(line) + return out + + +def _parse_prop(line: str) -> tuple[str, dict, str]: + """`NAME;PARAM=VAL:VALUE` -> (NAME, params, value).""" + name, _, value = line.partition(":") + params: dict[str, str] = {} + if ";" in name: + head, *rest = name.split(";") + name = head + for chunk in rest: + key, _, val = chunk.partition("=") + params[key.strip().upper()] = val.strip().strip('"') + return name.strip().upper(), params, value + + +def _prop_name(line: str) -> str: + return line.split(":", 1)[0].split(";", 1)[0].strip().upper() + + +def parse_components(text: str, component: str) -> list[dict]: + """All top-level `component` blocks in an iCalendar stream, as prop dicts. + + Each block maps property NAME -> list of `(params, value)` so repeated + properties (ATTENDEE, ...) survive. Nested components (VALARM) contribute + their own property lines, which is harmless: their names never collide with + the ones the bridge reads. + """ + component = component.upper() + blocks: list[dict] = [] + current: list[str] | None = None + for line in _unfold(text): + if line.startswith("BEGIN:"): + if line[6:].strip().upper() == component: + current = [] + elif current is not None: + current.append(line) + elif line.startswith("END:"): + if line[4:].strip().upper() == component and current is not None: + blocks.append(_props(current)) + current = None + elif current is not None: + current.append(line) + return blocks + + +def _props(lines: list[str]) -> dict: + props: dict[str, list[tuple[dict, str]]] = {} + for line in lines: + if not line.strip(): + continue + name, params, value = _parse_prop(line) + props.setdefault(name, []).append((params, value)) + return props + + +def _first(props: dict, name: str): + entries = props.get(name.upper()) + return entries[0] if entries else None + + +def _value(props: dict, name: str) -> str: + entry = _first(props, name) + return _unescape_text(entry[1]) if entry is not None else "" + + +def _dt_value(params: dict, value: str) -> dict: + value = (value or "").strip() + if params.get("VALUE", "").upper() == "DATE" or (len(value) == 8 and value.isdigit()): + return { + "value": f"{value[0:4]}-{value[4:6]}-{value[6:8]}", + "all_day": True, + } + match = re.match(r"(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z?)", value) + if not match: + return {"value": value, "all_day": False} + iso = ( + f"{match.group(1)}-{match.group(2)}-{match.group(3)}" + f"T{match.group(4)}:{match.group(5)}:{match.group(6)}" + ) + if match.group(7) == "Z": + iso += "+00:00" + return {"value": iso, "all_day": False} + + +def _parse_dt(value) -> datetime: + text = str(value or "").strip().replace("Z", "+00:00") + moment = datetime.fromisoformat(text) + if moment.tzinfo is None: + moment = moment.replace(tzinfo=timezone.utc) + return moment.astimezone(timezone.utc) + + +def _parse_date(value) -> date: + return date.fromisoformat(str(value or "").strip()[:10]) + + +def _stamp(moment: datetime) -> str: + return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + +def _now_stamp() -> str: + return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + +def _dt_lines(name: str, value, all_day: bool) -> list[str]: + if all_day: + return [f"{name};VALUE=DATE:{_parse_date(value).strftime('%Y%m%d')}"] + return [f"{name}:{_stamp(_parse_dt(value))}"] + + +# ---- builders --------------------------------------------------------------- + + +def build_event_ics( + uid: str, + summary: str, + start: str, + end: str = "", + all_day: bool = False, + location: str = "", + description: str = "", + rrule: str = "", + dtstamp: str | None = None, +) -> str: + lines = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//semif-agent//nextcloud bridge//EN", + "CALSCALE:GREGORIAN", + "BEGIN:VEVENT", + f"UID:{_escape_text(uid)}", + f"DTSTAMP:{dtstamp or _now_stamp()}", + ] + lines += _dt_lines("DTSTART", start, all_day) + if end: + lines += _dt_lines("DTEND", end, all_day) + lines.append(f"SUMMARY:{_escape_text(summary)}") + if description: + lines.append(f"DESCRIPTION:{_escape_text(description)}") + if location: + lines.append(f"LOCATION:{_escape_text(location)}") + if rrule: + lines.append(f"RRULE:{rrule}") + lines += ["END:VEVENT", "END:VCALENDAR"] + return "\r\n".join(lines) + "\r\n" + + +def build_todo_ics( + uid: str, + summary: str, + due: str = "", + priority: int | None = None, + description: str = "", + status: str = "NEEDS-ACTION", + percent_complete: int | None = None, + completed: str = "", + dtstamp: str | None = None, +) -> str: + lines = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//semif-agent//nextcloud bridge//EN", + "CALSCALE:GREGORIAN", + "BEGIN:VTODO", + f"UID:{_escape_text(uid)}", + f"DTSTAMP:{dtstamp or _now_stamp()}", + f"SUMMARY:{_escape_text(summary)}", + f"STATUS:{status}", + ] + if due: + lines += _dt_lines("DUE", due, False) + if priority is not None: + lines.append(f"PRIORITY:{int(priority)}") + if percent_complete is not None: + lines.append(f"PERCENT-COMPLETE:{int(percent_complete)}") + if completed: + lines.append(f"COMPLETED:{_stamp(_parse_dt(completed))}") + if description: + lines.append(f"DESCRIPTION:{_escape_text(description)}") + lines += ["END:VTODO", "END:VCALENDAR"] + return "\r\n".join(lines) + "\r\n" + + +def build_vcard( + uid: str, + fn: str, + n: str = "", + emails=(), + phones=(), + org: str = "", + title: str = "", + note: str = "", + url: str = "", +) -> str: + lines = [ + "BEGIN:VCARD", + "VERSION:3.0", + f"UID:{_escape_text(uid)}", + f"FN:{_escape_text(fn)}", + ] + if n: + lines.append(f"N:{_escape_text(n)}") + for email in emails: + lines.append(f"EMAIL;TYPE=INTERNET:{_escape_text(email)}") + for phone in phones: + lines.append(f"TEL:{_escape_text(phone)}") + if org: + lines.append(f"ORG:{_escape_text(org)}") + if title: + lines.append(f"TITLE:{_escape_text(title)}") + if note: + lines.append(f"NOTE:{_escape_text(note)}") + if url: + lines.append(f"URL:{_escape_text(url)}") + lines.append("END:VCARD") + return "\r\n".join(lines) + "\r\n" + + +def parse_vcard(text: str) -> dict: + props = _props(_unfold(text)) + return { + "uid": _value(props, "UID"), + "fn": _value(props, "FN"), + "n": _value(props, "N"), + "emails": [_unescape_text(v) for _, v in props.get("EMAIL", [])], + "phones": [_unescape_text(v) for _, v in props.get("TEL", [])], + "org": _value(props, "ORG"), + "title": _value(props, "TITLE"), + "note": _value(props, "NOTE"), + "url": _value(props, "URL"), + } + + +def _event_dict(props: dict) -> dict: + start = _first(props, "DTSTART") + end = _first(props, "DTEND") + start_info = _dt_value(*start) if start else {"value": "", "all_day": False} + end_info = _dt_value(*end) if end else {"value": "", "all_day": False} + return { + "uid": _value(props, "UID"), + "summary": _value(props, "SUMMARY"), + "description": _value(props, "DESCRIPTION"), + "location": _value(props, "LOCATION"), + "start": start_info["value"], + "end": end_info["value"], + "all_day": bool(start_info["all_day"]), + "rrule": _value(props, "RRULE"), + "status": _value(props, "STATUS"), + } + + +def _todo_dict(props: dict) -> dict: + due = _first(props, "DUE") + due_info = _dt_value(*due) if due else {"value": "", "all_day": False} + return { + "uid": _value(props, "UID"), + "summary": _value(props, "SUMMARY"), + "description": _value(props, "DESCRIPTION"), + "due": due_info["value"], + "status": _value(props, "STATUS"), + "percent_complete": _int(_value(props, "PERCENT-COMPLETE")), + "priority": _int(_value(props, "PRIORITY")), + } + + +def _extract_block(lines: list[str], component: str): + """Return `(start, end, block_lines)` for the first component, or None.""" + component = component.upper() + start = None + for index, line in enumerate(lines): + if line.startswith("BEGIN:") and line[6:].strip().upper() == component: + start = index + break + if start is None: + return None + depth = 1 + for index in range(start + 1, len(lines)): + if lines[index].startswith("BEGIN:"): + depth += 1 + elif lines[index].startswith("END:"): + depth -= 1 + if depth == 0: + return start, index, lines[start : index + 1] + return None + + +def _replace_props(block: list[str], updates: dict) -> list[str]: + """Replace (or remove) properties in a component block, preserving the rest.""" + wanted = {name.upper(): lines for name, lines in updates.items()} + kept = [line for line in block if _prop_name(line) not in wanted] + insert_at = len(kept) - 1 if kept and kept[-1].startswith("END:") else len(kept) + inserted: list[str] = [] + for name, lines in wanted.items(): + if lines: + inserted.extend(lines) + kept[insert_at:insert_at] = inserted + return kept + + +def _rebuild_component(original: list[str], component: str, block: list[str]) -> str: + found = _extract_block(original, component) + if found is None: + return "\r\n".join(block) + "\r\n" + start, end, _ = found + merged = original[:start] + block + original[end + 1 :] + return "\r\n".join(merged) + "\r\n" + + +def _multistatus(data: bytes): + try: + root = ET.fromstring(data) + except ET.ParseError as exc: + raise NextcloudError(f"unparseable DAV response: {exc}") from exc + if root.tag != f"{{{DAV}}}multistatus": + raise NextcloudError(f"unexpected DAV response root {root.tag!r}") + return root + + +def _response_prop(response): + for propstat in response.findall(f"{{{DAV}}}propstat"): + status = _text(propstat.find(f"{{{DAV}}}status")) + if " 200 " in status: + return propstat.find(f"{{{DAV}}}prop") + propstat = response.find(f"{{{DAV}}}propstat") + return propstat.find(f"{{{DAV}}}prop") if propstat is not None else None + + +def _dav_href_to_path(href: str, base: str) -> str: + path = urllib.parse.unquote(urllib.parse.urlparse(href or "").path) + if base and path.startswith(base): + path = path[len(base) :] + return _norm_path(path) + + +# ---- request bodies --------------------------------------------------------- + +_FILE_PROPFIND = ( + '' + '' + "" + "" +).encode("utf-8") + +_CALENDAR_PROPFIND = ( + '' + '' + "" + "" + "" +).encode("utf-8") + +_ADDRESSBOOK_PROPFIND = ( + '' + '' + "" + "" +).encode("utf-8") + +_ADDRESSBOOK_QUERY = ( + '' + '' + "" + "" +).encode("utf-8") + + +def _calendar_query_body(component: str, start: str = "", end: str = "") -> bytes: + time_range = "" + if start or end: + attrs = "" + if start: + attrs += f' start="{_stamp(_parse_dt(start))}"' + if end: + attrs += f' end="{_stamp(_parse_dt(end))}"' + time_range = f"" + return ( + '' + '' + "" + "" + f'{time_range}' + "" + ).encode("utf-8") + + +def _search_body(user: str, path: str, query: str) -> bytes: + scope = f"/files/{urllib.parse.quote(user)}{_quote_path(path)}" + return ( + '' + '' + "" + "" + "" + "" + f"{_xml_escape(scope)}infinity" + "" + "" + f"%{_xml_escape(query)}%" + "" + ).encode("utf-8") + + +class NextcloudClient: + """A configured connection to one Nextcloud account.""" + + def __init__( + self, + url: str, + username: str, + app_password: str, + *, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + default_calendar: str = "", + default_addressbook: str = "", + ): + self.url = str(url or "").strip().rstrip("/") + self.username = str(username or "").strip() + self.app_password = str(app_password or "") + self.timeout = float(timeout or DEFAULT_TIMEOUT) + self.verify_tls = bool(verify_tls) + self.default_calendar = str(default_calendar or "").strip() + self.default_addressbook = str(default_addressbook or "").strip() + + @property + def configured(self) -> bool: + return bool(self.url and self.username and self.app_password) + + # ---- transport ---- + + def _auth_header(self) -> str: + token = base64.b64encode( + f"{self.username}:{self.app_password}".encode("utf-8") + ).decode("ascii") + return f"Basic {token}" + + def _url(self, path: str) -> str: + if not self.url: + raise NextcloudError("the Nextcloud base URL is not configured") + return self.url + path + + def _ssl_context(self): + if self.verify_tls: + return None + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + def _request( + self, + method: str, + path: str, + *, + body: bytes | None = None, + headers: dict | None = None, + depth: str | None = None, + content_type: str | None = None, + ): + request_headers = {"Authorization": self._auth_header()} + if depth is not None: + request_headers["Depth"] = depth + if content_type: + request_headers["Content-Type"] = content_type + if headers: + request_headers.update(headers) + request = urllib.request.Request( + self._url(path), data=body, method=method, headers=request_headers + ) + try: + with urllib.request.urlopen( + request, timeout=self.timeout, context=self._ssl_context() + ) as response: + return response.status, response.headers, response.read() + except urllib.error.HTTPError as exc: + try: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + except Exception: + detail = "" + message = f"{method} {path}: HTTP {exc.code}" + if detail: + message += f" {detail}" + raise NextcloudError(message, status=exc.code) from exc + except (urllib.error.URLError, OSError, TimeoutError) as exc: + raise NextcloudError(f"{method} {path}: {exc}") from exc + + def _ocs(self, method: str, path: str, *, params: dict | None = None, payload: dict | None = None): + url = self._url(path) + params = dict(params or {}) + params.setdefault("format", "json") + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + headers = { + "Authorization": self._auth_header(), + "OCS-APIRequest": "true", + "Accept": "application/json", + } + body = None + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + request = urllib.request.Request(url, data=body, method=method, headers=headers) + try: + with urllib.request.urlopen( + request, timeout=self.timeout, context=self._ssl_context() + ) as response: + data = json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + try: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + except Exception: + detail = "" + raise NextcloudError( + f"{method} {path}: HTTP {exc.code} {detail}".strip(), status=exc.code + ) from exc + except (urllib.error.URLError, OSError, TimeoutError, ValueError) as exc: + raise NextcloudError(f"{method} {path}: {exc}") from exc + if not isinstance(data, dict): + raise NextcloudError(f"{method} {path}: unexpected OCS reply") + ocs = data.get("ocs") + if isinstance(ocs, dict): + meta = ocs.get("meta") or {} + statuscode = _int(meta.get("statuscode")) + if statuscode not in (None, 100, 200): + raise NextcloudError( + f"OCS {path}: {meta.get('statuscode')} {meta.get('message')}".strip(), + status=statuscode if statuscode and statuscode >= 400 else None, + ) + return ocs.get("data") + return data + + # ---- paths ---- + + def _files_base(self) -> str: + return f"/remote.php/dav/files/{urllib.parse.quote(self.username)}" + + def _files_path(self, path: str) -> str: + return self._files_base() + _quote_path(path) + + def _calendars_base(self) -> str: + return f"/remote.php/dav/calendars/{urllib.parse.quote(self.username)}" + + def _calendar_path(self, calendar: str) -> str: + return f"{self._calendars_base()}/{urllib.parse.quote(calendar)}/" + + def _calendar_object_path(self, calendar: str, uid: str) -> str: + return f"{self._calendar_path(calendar)}{urllib.parse.quote(uid, safe='')}.ics" + + def _addressbooks_base(self) -> str: + return f"/remote.php/dav/addressbooks/users/{urllib.parse.quote(self.username)}" + + def _addressbook_path(self, addressbook: str) -> str: + return f"{self._addressbooks_base()}/{urllib.parse.quote(addressbook)}/" + + def _contact_path(self, addressbook: str, uid: str) -> str: + return f"{self._addressbook_path(addressbook)}{urllib.parse.quote(uid, safe='')}.vcf" + + # ---- server info ---- + + def user_info(self) -> dict: + data = self._ocs("GET", "/ocs/v2.php/cloud/user") or {} + if not isinstance(data, dict): + return {} + return { + "id": str(data.get("id") or ""), + "display_name": str(data.get("display-name") or data.get("displayname") or ""), + "email": str(data.get("email") or ""), + "language": str(data.get("language") or ""), + "locale": str(data.get("locale") or ""), + } + + def capabilities(self) -> dict: + data = self._ocs("GET", "/ocs/v2.php/cloud/capabilities") or {} + return data if isinstance(data, dict) else {} + + # ---- files ---- + + def list_files(self, path: str = "/") -> dict: + _status, _headers, data = self._request( + "PROPFIND", + self._files_path(path), + body=_FILE_PROPFIND, + depth="1", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + requested = _norm_path(path) + entries = [] + for response in root.findall(f"{{{DAV}}}response"): + href = _text(response.find(f"{{{DAV}}}href")) + entry_path = _dav_href_to_path(href, self._files_base()) + if entry_path == requested: + continue + prop = _response_prop(response) + if prop is None: + continue + entries.append(self._file_entry(entry_path, prop)) + entries.sort(key=lambda entry: (entry["type"] != "dir", entry["name"].lower())) + return {"path": requested, "entries": entries} + + def stat(self, path: str) -> dict: + _status, _headers, data = self._request( + "PROPFIND", + self._files_path(path), + body=_FILE_PROPFIND, + depth="0", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + response = root.find(f"{{{DAV}}}response") + if response is None: + raise NextcloudError(f"stat {path}: no DAV response", status=404) + prop = _response_prop(response) + if prop is None: + raise NextcloudError(f"stat {path}: no properties returned", status=404) + return self._file_entry(_norm_path(path), prop) + + @staticmethod + def _file_entry(path: str, prop) -> dict: + resourcetype = prop.find(f"{{{DAV}}}resourcetype") + is_dir = resourcetype is not None and resourcetype.find(f"{{{DAV}}}collection") is not None + name = _text(prop.find(f"{{{DAV}}}displayname")) or path.rstrip("/").rsplit("/", 1)[-1] + return { + "name": name, + "path": path, + "type": "dir" if is_dir else "file", + "size": _int(_text(prop.find(f"{{{DAV}}}getcontentlength"))), + "modified": _text(prop.find(f"{{{DAV}}}getlastmodified")), + "etag": _text(prop.find(f"{{{DAV}}}getetag")), + "content_type": _text(prop.find(f"{{{DAV}}}getcontenttype")), + } + + def read_file(self, path: str) -> dict: + _status, _headers, data = self._request("GET", self._files_path(path)) + try: + content = data.decode("utf-8") + encoding = "utf-8" + except UnicodeDecodeError: + content = base64.b64encode(data).decode("ascii") + encoding = "base64" + return { + "path": _norm_path(path), + "content": content, + "encoding": encoding, + "size": len(data), + } + + def write_file( + self, path: str, content: str, encoding: str = "utf-8", overwrite: bool = True + ) -> dict: + if encoding == "base64": + try: + data = base64.b64decode(content, validate=True) + except (ValueError, TypeError) as exc: + raise ValueError(f"content is not valid base64: {exc}") from exc + else: + data = str(content).encode("utf-8") + headers = {} if overwrite else {"If-None-Match": "*"} + self._request( + "PUT", + self._files_path(path), + body=data, + headers=headers, + content_type="application/octet-stream", + ) + return {"ok": True, "path": _norm_path(path)} + + def mkdir(self, path: str) -> dict: + self._request("MKCOL", self._files_path(path)) + return {"ok": True, "path": _norm_path(path)} + + def delete(self, path: str) -> dict: + self._request("DELETE", self._files_path(path)) + return {"ok": True, "path": _norm_path(path)} + + def move(self, path: str, destination: str, overwrite: bool = False) -> dict: + self._request( + "MOVE", + self._files_path(path), + headers={ + "Destination": self._url(self._files_path(destination)), + "Overwrite": "T" if overwrite else "F", + }, + ) + return {"ok": True, "path": _norm_path(path), "destination": _norm_path(destination)} + + def copy(self, path: str, destination: str, overwrite: bool = False) -> dict: + self._request( + "COPY", + self._files_path(path), + headers={ + "Destination": self._url(self._files_path(destination)), + "Overwrite": "T" if overwrite else "F", + }, + ) + return {"ok": True, "path": _norm_path(path), "destination": _norm_path(destination)} + + def search(self, query: str, path: str = "/") -> list[dict]: + _status, _headers, data = self._request( + "SEARCH", + "/remote.php/dav/", + body=_search_body(self.username, path, query), + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + results = [] + for response in root.findall(f"{{{DAV}}}response"): + href = _text(response.find(f"{{{DAV}}}href")) + prop = _response_prop(response) + if prop is None: + continue + results.append( + self._file_entry(_dav_href_to_path(href, self._files_base()), prop) + ) + results.sort(key=lambda entry: entry["path"]) + return results + + # ---- calendars ---- + + def list_calendars(self) -> list[dict]: + _status, _headers, data = self._request( + "PROPFIND", + self._calendars_base() + "/", + body=_CALENDAR_PROPFIND, + depth="1", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + calendars = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + resourcetype = prop.find(f"{{{DAV}}}resourcetype") + if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None: + continue + href = urllib.parse.unquote( + urllib.parse.urlparse(_text(response.find(f"{{{DAV}}}href"))).path + ) + name = href.rstrip("/").rsplit("/", 1)[-1] + if not name: + continue + color = _text(prop.find(f"{{{NC}}}calendar-color")) or _text( + prop.find(f"{{{OC}}}calendar-color") + ) + ctag = _text(prop.find(f"{{{CALDAV}}}getctag")) or _text( + prop.find(f"{{{OC}}}getctag") + ) + calendars.append( + { + "name": name, + "label": _text(prop.find(f"{{{DAV}}}displayname")) or name, + "description": _text(prop.find(f"{{{CALDAV}}}calendar-description")), + "color": color, + "ctag": ctag, + } + ) + calendars.sort(key=lambda calendar: calendar["name"].lower()) + return calendars + + def _report_objects(self, calendar: str, component: str, start: str = "", end: str = "") -> list[dict]: + _status, _headers, data = self._request( + "REPORT", + self._calendar_path(calendar), + body=_calendar_query_body(component, start, end), + depth="1", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + objects = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + href = _text(response.find(f"{{{DAV}}}href")) + etag = _text(prop.find(f"{{{DAV}}}getetag")) + calendar_data = prop.find(f"{{{CALDAV}}}calendar-data") + ics = calendar_data.text if calendar_data is not None and calendar_data.text else "" + for block in parse_components(ics, component): + item = _event_dict(block) if component == "VEVENT" else _todo_dict(block) + item["calendar"] = calendar + item["href"] = href + item["etag"] = etag + objects.append(item) + return objects + + def list_events(self, calendar: str, start: str = "", end: str = "") -> list[dict]: + return self._report_objects(calendar, "VEVENT", start, end) + + def list_tasks(self, calendar: str) -> list[dict]: + return self._report_objects(calendar, "VTODO") + + def get_object(self, calendar: str, uid: str) -> tuple[str | None, str | None]: + try: + _status, headers, data = self._request( + "GET", self._calendar_object_path(calendar, uid) + ) + except NextcloudError as exc: + if exc.status == 404: + return None, None + raise + return (headers.get("ETag") or ""), data.decode("utf-8", "replace") + + def put_object( + self, calendar: str, uid: str, ics: str, etag: str | None = None, overwrite: bool = False + ) -> dict: + headers = {"Content-Type": "text/calendar; charset=utf-8"} + if etag: + headers["If-Match"] = etag + elif not overwrite: + headers["If-None-Match"] = "*" + _status, response_headers, _data = self._request( + "PUT", + self._calendar_object_path(calendar, uid), + body=ics.encode("utf-8"), + headers=headers, + ) + return { + "ok": True, + "uid": uid, + "calendar": calendar, + "etag": response_headers.get("ETag") or "", + } + + def delete_object(self, calendar: str, uid: str) -> dict: + self._request("DELETE", self._calendar_object_path(calendar, uid)) + return {"ok": True, "uid": uid, "calendar": calendar} + + def create_event( + self, + calendar: str, + uid: str, + summary: str, + start: str, + end: str = "", + all_day: bool = False, + location: str = "", + description: str = "", + rrule: str = "", + overwrite: bool = False, + ) -> dict: + ics = build_event_ics( + uid, + summary, + start, + end, + all_day=all_day, + location=location, + description=description, + rrule=rrule, + ) + return self.put_object(calendar, uid, ics, overwrite=overwrite) + + def update_event(self, calendar: str, uid: str, **changes) -> dict: + etag, existing = self.get_object(calendar, uid) + if existing is None: + raise NextcloudError(f"event {uid!r} was not found on calendar {calendar!r}", status=404) + block = _extract_block(_unfold(existing), "VEVENT") + if block is None: + raise NextcloudError(f"event {uid!r} has no VEVENT component") + block_lines = block[2] + all_day = changes.get("all_day") + updates: dict[str, list[str]] = {} + if "summary" in changes and changes["summary"] is not None: + updates["SUMMARY"] = [f"SUMMARY:{_escape_text(changes['summary'])}"] + if "description" in changes and changes["description"] is not None: + updates["DESCRIPTION"] = [f"DESCRIPTION:{_escape_text(changes['description'])}"] + if "location" in changes and changes["location"] is not None: + updates["LOCATION"] = [f"LOCATION:{_escape_text(changes['location'])}"] + if "rrule" in changes and changes["rrule"] is not None: + updates["RRULE"] = [f"RRULE:{changes['rrule']}"] if changes["rrule"] else [] + if "start" in changes and changes["start"] is not None: + updates["DTSTART"] = _dt_lines( + "DTSTART", changes["start"], bool(all_day) + ) + if "end" in changes and changes["end"] is not None: + updates["DTEND"] = _dt_lines("DTEND", changes["end"], bool(all_day)) + new_block = _replace_props(block_lines, updates) + ics = _rebuild_component(_unfold(existing), "VEVENT", new_block) + return self.put_object(calendar, uid, ics, etag=etag) + + def create_task( + self, + calendar: str, + uid: str, + summary: str, + due: str = "", + priority: int | None = None, + description: str = "", + ) -> dict: + ics = build_todo_ics( + uid, summary, due=due, priority=priority, description=description + ) + return self.put_object(calendar, uid, ics) + + def update_task(self, calendar: str, uid: str, **changes) -> dict: + etag, existing = self.get_object(calendar, uid) + if existing is None: + raise NextcloudError(f"task {uid!r} was not found on calendar {calendar!r}", status=404) + block = _extract_block(_unfold(existing), "VTODO") + if block is None: + raise NextcloudError(f"task {uid!r} has no VTODO component") + updates: dict[str, list[str]] = {} + if "summary" in changes and changes["summary"] is not None: + updates["SUMMARY"] = [f"SUMMARY:{_escape_text(changes['summary'])}"] + if "description" in changes and changes["description"] is not None: + updates["DESCRIPTION"] = [f"DESCRIPTION:{_escape_text(changes['description'])}"] + if "due" in changes and changes["due"] is not None: + updates["DUE"] = _dt_lines("DUE", changes["due"], False) if changes["due"] else [] + if "priority" in changes and changes["priority"] is not None: + updates["PRIORITY"] = [f"PRIORITY:{int(changes['priority'])}"] + if "status" in changes and changes["status"] is not None: + updates["STATUS"] = [f"STATUS:{changes['status']}"] + if "percent_complete" in changes and changes["percent_complete"] is not None: + updates["PERCENT-COMPLETE"] = [f"PERCENT-COMPLETE:{int(changes['percent_complete'])}"] + new_block = _replace_props(block[2], updates) + ics = _rebuild_component(_unfold(existing), "VTODO", new_block) + return self.put_object(calendar, uid, ics, etag=etag) + + def complete_task(self, calendar: str, uid: str) -> dict: + etag, existing = self.get_object(calendar, uid) + if existing is None: + raise NextcloudError(f"task {uid!r} was not found on calendar {calendar!r}", status=404) + block = _extract_block(_unfold(existing), "VTODO") + if block is None: + raise NextcloudError(f"task {uid!r} has no VTODO component") + updates = { + "STATUS": ["STATUS:COMPLETED"], + "PERCENT-COMPLETE": ["PERCENT-COMPLETE:100"], + "COMPLETED": [f"COMPLETED:{_now_stamp()}"], + } + new_block = _replace_props(block[2], updates) + ics = _rebuild_component(_unfold(existing), "VTODO", new_block) + return self.put_object(calendar, uid, ics, etag=etag) + + # ---- contacts ---- + + def list_addressbooks(self) -> list[dict]: + _status, _headers, data = self._request( + "PROPFIND", + self._addressbooks_base() + "/", + body=_ADDRESSBOOK_PROPFIND, + depth="1", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + addressbooks = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + resourcetype = prop.find(f"{{{DAV}}}resourcetype") + if resourcetype is None or resourcetype.find(f"{{{CARDDAV}}}addressbook") is None: + continue + href = urllib.parse.unquote( + urllib.parse.urlparse(_text(response.find(f"{{{DAV}}}href"))).path + ) + name = href.rstrip("/").rsplit("/", 1)[-1] + if not name: + continue + addressbooks.append( + { + "name": name, + "label": _text(prop.find(f"{{{DAV}}}displayname")) or name, + "description": _text(prop.find(f"{{{CARDDAV}}}addressbook-description")), + } + ) + addressbooks.sort(key=lambda book: book["name"].lower()) + return addressbooks + + def list_contacts(self, addressbook: str, query: str = "") -> list[dict]: + _status, _headers, data = self._request( + "REPORT", + self._addressbook_path(addressbook), + body=_ADDRESSBOOK_QUERY, + depth="1", + content_type="application/xml; charset=utf-8", + ) + root = _multistatus(data) + contacts = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + href = _text(response.find(f"{{{DAV}}}href")) + etag = _text(prop.find(f"{{{DAV}}}getetag")) + card_data = prop.find(f"{{{CARDDAV}}}address-data") + vcf = card_data.text if card_data is not None and card_data.text else "" + contact = parse_vcard(vcf) + contact["addressbook"] = addressbook + contact["href"] = href + contact["etag"] = etag + contacts.append(contact) + if query: + needle = query.lower() + contacts = [ + contact + for contact in contacts + if needle + in " ".join( + [contact["fn"], contact["org"], contact["note"], *contact["emails"], *contact["phones"]] + ).lower() + ] + contacts.sort(key=lambda contact: contact["fn"].lower()) + return contacts + + def get_contact(self, addressbook: str, uid: str) -> tuple[str | None, dict | None]: + try: + _status, headers, data = self._request( + "GET", self._contact_path(addressbook, uid) + ) + except NextcloudError as exc: + if exc.status == 404: + return None, None + raise + return (headers.get("ETag") or ""), parse_vcard(data.decode("utf-8", "replace")) + + def create_contact(self, addressbook: str, uid: str, **fields) -> dict: + vcf = build_vcard( + uid, + fields.get("fn", ""), + n=fields.get("n", ""), + emails=fields.get("emails") or (), + phones=fields.get("phones") or (), + org=fields.get("org", ""), + title=fields.get("title", ""), + note=fields.get("note", ""), + url=fields.get("url", ""), + ) + self._request( + "PUT", + self._contact_path(addressbook, uid), + body=vcf.encode("utf-8"), + headers={"Content-Type": "text/vcard; charset=utf-8", "If-None-Match": "*"}, + ) + return {"ok": True, "uid": uid, "addressbook": addressbook} + + def update_contact(self, addressbook: str, uid: str, **changes) -> dict: + etag, existing = self.get_contact(addressbook, uid) + if existing is None: + raise NextcloudError( + f"contact {uid!r} was not found in addressbook {addressbook!r}", status=404 + ) + updates: dict[str, list[str]] = {} + if "fn" in changes and changes["fn"] is not None: + updates["FN"] = [f"FN:{_escape_text(changes['fn'])}"] + if "n" in changes and changes["n"] is not None: + updates["N"] = [f"N:{_escape_text(changes['n'])}"] if changes["n"] else [] + if "org" in changes and changes["org"] is not None: + updates["ORG"] = [f"ORG:{_escape_text(changes['org'])}"] if changes["org"] else [] + if "title" in changes and changes["title"] is not None: + updates["TITLE"] = [f"TITLE:{_escape_text(changes['title'])}"] if changes["title"] else [] + if "note" in changes and changes["note"] is not None: + updates["NOTE"] = [f"NOTE:{_escape_text(changes['note'])}"] if changes["note"] else [] + if "emails" in changes and changes["emails"] is not None: + updates["EMAIL"] = [f"EMAIL;TYPE=INTERNET:{_escape_text(email)}" for email in changes["emails"]] + if "phones" in changes and changes["phones"] is not None: + updates["TEL"] = [f"TEL:{_escape_text(phone)}" for phone in changes["phones"]] + try: + _status, _headers, data = self._request( + "GET", self._contact_path(addressbook, uid) + ) + except NextcloudError as exc: # pragma: no cover - raced away after the etag read + raise NextcloudError(f"contact {uid!r} could not be read: {exc}", status=exc.status) from exc + original = _unfold(data.decode("utf-8", "replace")) + block = _extract_block(original, "VCARD") + if block is None: + raise NextcloudError(f"contact {uid!r} has no VCARD component") + new_block = _replace_props(block[2], updates) + vcf = _rebuild_component(original, "VCARD", new_block) + headers = {"Content-Type": "text/vcard; charset=utf-8"} + if etag: + headers["If-Match"] = etag + self._request( + "PUT", self._contact_path(addressbook, uid), body=vcf.encode("utf-8"), headers=headers + ) + return {"ok": True, "uid": uid, "addressbook": addressbook} + + def delete_contact(self, addressbook: str, uid: str) -> dict: + self._request("DELETE", self._contact_path(addressbook, uid)) + return {"ok": True, "uid": uid, "addressbook": addressbook} + + # ---- notes (Notes app OCS API) ---- + + def list_notes(self) -> list[dict]: + data = self._ocs("GET", "/ocs/v2.php/apps/notes/api/v1/notes") + return data if isinstance(data, list) else [] + + def get_note(self, note_id) -> dict: + data = self._ocs("GET", f"/ocs/v2.php/apps/notes/api/v1/notes/{int(note_id)}") + if not isinstance(data, dict): + raise NextcloudError(f"note {note_id} returned no data") + return data + + def create_note(self, title: str, content: str = "", category: str = "") -> dict: + payload = {"title": title, "content": content} + if category: + payload["category"] = category + data = self._ocs("POST", "/ocs/v2.php/apps/notes/api/v1/notes", payload=payload) + if not isinstance(data, dict): + raise NextcloudError("creating the note returned no data") + return data + + def update_note(self, note_id, **changes) -> dict: + payload = {key: value for key, value in changes.items() if value is not None} + data = self._ocs( + "PUT", f"/ocs/v2.php/apps/notes/api/v1/notes/{int(note_id)}", payload=payload + ) + if not isinstance(data, dict): + raise NextcloudError(f"updating note {note_id} returned no data") + return data + + def delete_note(self, note_id) -> dict: + self._ocs("DELETE", f"/ocs/v2.php/apps/notes/api/v1/notes/{int(note_id)}") + return {"ok": True, "id": int(note_id)} diff --git a/semif_agent/bridges/registry.py b/semif_agent/bridges/registry.py index 8d270ee..366d120 100644 --- a/semif_agent/bridges/registry.py +++ b/semif_agent/bridges/registry.py @@ -14,10 +14,11 @@ import threading from .base import BridgeInfo, BridgeService from .llm import LLMBridge +from .nextcloud import NextcloudBridge from .simplex import SimplexBridge #: Known bridge services. Order is presentation order. -CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge) +CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge, NextcloudBridge) def _class_for(name: str) -> type[BridgeService] | None: @@ -75,7 +76,9 @@ def build_bridge( `llm` is the scheduler's configured language-model client, handed to the LLM bridge so it reuses the top-level `llm` endpoint/model instead of duplicating - that config. Other bridges ignore it. + that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a + fallback, so the same account the calendar seeds use is configured once. Other + bridges ignore both. """ bridge_class = _class_for(name) if bridge_class is None: @@ -83,6 +86,18 @@ def build_bridge( block = (config.get("bridges", {}) or {}).get(name, {}) or {} if bridge_class is LLMBridge: return LLMBridge(block, trace=trace, client=llm) + if bridge_class is NextcloudBridge: + return NextcloudBridge( + block, + trace=trace, + fallback={ + "url": config.get("nextcloud_url"), + "username": config.get("nextcloud_username"), + "app_password": config.get("nextcloud_app_password"), + "default_calendar": config.get("nextcloud_default_calendar"), + "default_addressbook": config.get("nextcloud_default_addressbook"), + }, + ) return bridge_class(block, trace=trace) diff --git a/tests/test_codegen.py b/tests/test_codegen.py index d33d81b..ad429b9 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -1559,7 +1559,10 @@ def test_other_codegen_error_does_not_retry(): model="test", timeout=10, stream=True, - context_window=3000, + # Large enough that the prompt (which carries the bridge catalog via + # describe_bridges) passes the pre-flight budget and generation + # starts, so the *output* cap is what trips. + context_window=10000, max_output=0.01, idle_timeout=30, max_attempts=3, diff --git a/tests/test_nextcloud_bridge.py b/tests/test_nextcloud_bridge.py new file mode 100644 index 0000000..945535e --- /dev/null +++ b/tests/test_nextcloud_bridge.py @@ -0,0 +1,954 @@ +"""Pure-stdlib tests for the Nextcloud bridge. + +A loopback `http.server` plays a real Nextcloud (WebDAV files, CalDAV events and +tasks, CardDAV contacts, OCS Notes) so the bridge's own client is exercised over +HTTP with no mocking of the transport. The decision engine and LLM are never +involved. A few route tests inject a fake client to check wiring/validation +without a server. Passing these proves mechanics only; a real run against the +user's Nextcloud is the only proof the integration works. +""" + +import base64 +import json +import threading +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +import pytest + +from semif_agent.bridges.nextcloud import NextcloudBridge +from semif_agent.bridges.nextcloud_client import NextcloudClient, NextcloudError +from semif_agent.bridges.registry import build_bridge, describe_bridges, known_infos + +USER = "alice" +PASSWORD = "app-secret" +MODIFIED = "Mon, 01 Jan 2026 12:00:00 GMT" + + +def _norm(path): + text = "/" + str(path or "").strip("/") + return "/" if text == "/" else text + + +def _parent(path): + if path == "/": + return None + return path.rsplit("/", 1)[0] or "/" + + +class FakeNextcloud: + """A minimal but real Nextcloud-shaped HTTP server for the client.""" + + def __init__(self): + self.files = { + "/": {"type": "dir"}, + "/Documents": {"type": "dir"}, + "/Documents/readme.txt": {"type": "file", "content": b"hello world"}, + "/image.png": {"type": "file", "content": b"\x89PNG\x00\xff"}, + } + self.calendars = {"personal": {"label": "Personal", "objects": {}}} + self.addressbooks = {"contacts": {"label": "Contacts", "cards": {}}} + self.notes = {} + self._next_note_id = 1 + self.calls = [] + self._server = None + self._thread = None + + # ---- lifecycle ---- + + def start(self): + fake = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _read(self): + length = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(length) if length else b"" + + def _authorized(self): + expected = "Basic " + base64.b64encode( + f"{USER}:{PASSWORD}".encode() + ).decode() + return self.headers.get("Authorization") == expected + + def _send(self, status, body=b"", content_type="application/xml", headers=None): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + for key, value in (headers or {}).items(): + self.send_header(key, value) + self.end_headers() + if body: + self.wfile.write(body) + + def _dispatch(self, method): + body = self._read() + fake.calls.append((method, self.path, dict(self.headers), body)) + if not self._authorized(): + self._send(401, b'{"error":"unauthorized"}', "application/json") + return + status, payload, content_type, headers = fake.handle( + method, self.path, body + ) + self._send(status, payload, content_type, headers) + + def do_GET(self): + self._dispatch("GET") + + def do_PUT(self): + self._dispatch("PUT") + + def do_POST(self): + self._dispatch("POST") + + def do_DELETE(self): + self._dispatch("DELETE") + + def do_MOVE(self): + self._dispatch("MOVE") + + def do_COPY(self): + self._dispatch("COPY") + + def do_MKCOL(self): + self._dispatch("MKCOL") + + def do_PROPFIND(self): + self._dispatch("PROPFIND") + + def do_REPORT(self): + self._dispatch("REPORT") + + def do_SEARCH(self): + self._dispatch("SEARCH") + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self._thread.start() + return f"http://127.0.0.1:{self._server.server_address[1]}" + + def stop(self): + if self._server is not None: + self._server.shutdown() + self._server.server_close() + self._server = None + + # ---- routing ---- + + def handle(self, method, path, body): + url = urlparse(path) + route = url.path + query = parse_qs(url.query) + if route.startswith("/ocs/"): + return self._ocs(method, route, body) + if route.startswith("/remote.php/dav/files/"): + return self._files(method, route, body) + if route.startswith("/remote.php/dav/calendars/"): + return self._calendars(method, route, body) + if route.startswith("/remote.php/dav/addressbooks/"): + return self._addressbooks(method, route, body) + if route == "/remote.php/dav/": + return self._search(body) + return 404, b"not found", "text/plain", {} + + def _xml(self, responses): + return ( + '' + '' + + "".join(responses) + + "" + ).encode() + + @staticmethod + def _response(href, props): + return ( + f"{href}" + f"{props}" + "HTTP/1.1 200 OK" + ) + + # ---- files ---- + + def _file_response(self, dav_path): + info = self.files.get(dav_path) + if info is None: + return None + is_dir = info["type"] == "dir" + suffix = dav_path if dav_path == "/" else dav_path + ("/" if is_dir else "") + href = f"/remote.php/dav/files/{USER}{suffix}" + name = "root" if dav_path == "/" else dav_path.rsplit("/", 1)[-1] + size = 0 if is_dir else len(info.get("content", b"")) + resourcetype = "" if is_dir else "" + content_type = "httpd/unix-directory" if is_dir else "text/plain" + props = ( + f"{resourcetype}" + f"{name}" + f"{size}" + f"{MODIFIED}" + f'"etag-{name}"' + f"{content_type}" + ) + return self._response(href, props) + + def _files(self, method, route, body): + rest = route[len("/remote.php/dav/files/") :] + user, _, tail = rest.partition("/") + dav_path = _norm(tail) + if method == "PROPFIND": + depth = None + # depth is read from the request headers by the handler; emulate via + # the client always sending one — Depth "1" lists children. + if dav_path not in self.files: + return 404, b"not found", "text/plain", {} + responses = [] + # The Depth header is not threaded here; both stat and list are + # covered by returning the entry, and list adds children. + responses.append(self._file_response(dav_path)) + for candidate in self.files: + if _parent(candidate) == dav_path and candidate != dav_path: + responses.append(self._file_response(candidate)) + return 207, self._xml([r for r in responses if r]), "application/xml", {} + if method == "GET": + info = self.files.get(dav_path) + if info is None or info["type"] != "file": + return 404, b"not found", "text/plain", {} + return 200, info["content"], "application/octet-stream", {} + if method == "PUT": + self.files[dav_path] = {"type": "file", "content": body} + return 201, b"", "text/plain", {"ETag": '"new"'} + if method == "MKCOL": + self.files[dav_path] = {"type": "dir"} + return 201, b"", "text/plain", {} + if method == "DELETE": + self.files.pop(dav_path, None) + return 204, b"", "text/plain", {} + if method in ("MOVE", "COPY"): + return 201, b"", "text/plain", {} + return 405, b"method not allowed", "text/plain", {} + + def _search(self, body): + text = body.decode("utf-8", "replace") + needle = "" + if "" in text: + needle = text.split("", 1)[1].split("", 1)[0].strip("%") + responses = [] + for dav_path, info in self.files.items(): + if info["type"] != "file": + continue + if needle and needle.lower() not in dav_path.lower(): + continue + responses.append(self._file_response(dav_path)) + return 207, self._xml(responses), "application/xml", {} + + # ---- calendars ---- + + def _calendar_home(self): + responses = [ + self._response( + f"/remote.php/dav/calendars/{USER}/", + "" + f"{USER}", + ) + ] + for name, calendar in self.calendars.items(): + responses.append( + self._response( + f"/remote.php/dav/calendars/{USER}/{name}/", + "" + f"{calendar['label']}" + "desc" + '#ff0000' + "ctag-1", + ) + ) + return self._xml(responses) + + def _calendars(self, method, route, body): + rest = route[len("/remote.php/dav/calendars/") :] + user, _, tail = rest.partition("/") + tail = _norm(tail) + if tail == "/": + if method == "PROPFIND": + return 207, self._calendar_home(), "application/xml", {} + return 405, b"method not allowed", "text/plain", {} + name, _, leaf = tail.lstrip("/").partition("/") + calendar = self.calendars.get(name) + if calendar is None: + return 404, b"not found", "text/plain", {} + if not leaf: + if method == "REPORT": + responses = [] + for uid, ics in calendar["objects"].items(): + responses.append( + self._response( + f"/remote.php/dav/calendars/{USER}/{name}/{uid}.ics", + f'"etag-{uid}"' + f"{_xml_escape(ics)}", + ) + ) + return 207, self._xml(responses), "application/xml", {} + return 405, b"method not allowed", "text/plain", {} + uid = leaf[:-4] if leaf.endswith(".ics") else leaf + if method == "PUT": + calendar["objects"][uid] = body.decode("utf-8") + return 201, b"", "text/plain", {"ETag": f'"etag-{uid}"'} + if method == "GET": + ics = calendar["objects"].get(uid) + if ics is None: + return 404, b"not found", "text/plain", {} + return 200, ics.encode(), "text/calendar", {"ETag": f'"etag-{uid}"'} + if method == "DELETE": + calendar["objects"].pop(uid, None) + return 204, b"", "text/plain", {} + return 405, b"method not allowed", "text/plain", {} + + # ---- contacts ---- + + def _addressbook_home(self): + responses = [ + self._response( + f"/remote.php/dav/addressbooks/users/{USER}/", + "" + f"{USER}", + ) + ] + for name, book in self.addressbooks.items(): + responses.append( + self._response( + f"/remote.php/dav/addressbooks/users/{USER}/{name}/", + "" + f"{book['label']}" + "d", + ) + ) + return self._xml(responses) + + def _addressbooks(self, method, route, body): + rest = route[len("/remote.php/dav/addressbooks/") :] + parts = rest.split("/") + tail = _norm("/".join(parts[2:]) if len(parts) > 2 else "/") + if tail == "/": + if method == "PROPFIND": + return 207, self._addressbook_home(), "application/xml", {} + return 405, b"method not allowed", "text/plain", {} + name, _, leaf = tail.lstrip("/").partition("/") + book = self.addressbooks.get(name) + if book is None: + return 404, b"not found", "text/plain", {} + if not leaf: + if method == "REPORT": + responses = [] + for uid, vcf in book["cards"].items(): + responses.append( + self._response( + f"/remote.php/dav/addressbooks/users/{USER}/{name}/{uid}.vcf", + f'"etag-{uid}"' + f"{_xml_escape(vcf)}", + ) + ) + return 207, self._xml(responses), "application/xml", {} + return 405, b"method not allowed", "text/plain", {} + uid = leaf[:-4] if leaf.endswith(".vcf") else leaf + if method == "PUT": + book["cards"][uid] = body.decode("utf-8") + return 201, b"", "text/plain", {"ETag": f'"etag-{uid}"'} + if method == "GET": + vcf = book["cards"].get(uid) + if vcf is None: + return 404, b"not found", "text/plain", {} + return 200, vcf.encode(), "text/vcard", {"ETag": f'"etag-{uid}"'} + if method == "DELETE": + book["cards"].pop(uid, None) + return 204, b"", "text/plain", {} + return 405, b"method not allowed", "text/plain", {} + + # ---- OCS (notes + info) ---- + + def _ocs_json(self, data, status=200): + return status, json.dumps({"ocs": {"meta": {"statuscode": 200}, "data": data}}).encode(), "application/json", {} + + def _ocs(self, method, route, body): + if route == "/ocs/v2.php/cloud/user": + return self._ocs_json( + {"id": USER, "display-name": "Alice", "email": "alice@example.com"} + ) + if route == "/ocs/v2.php/cloud/capabilities": + return self._ocs_json({"version": {"major": 28}}) + prefix = "/ocs/v2.php/apps/notes/api/v1/notes" + if route == prefix: + if method == "GET": + return self._ocs_json(list(self.notes.values())) + if method == "POST": + payload = json.loads(body.decode() or "{}") + note_id = self._next_note_id + self._next_note_id += 1 + note = {"id": note_id, "title": payload.get("title", ""), + "content": payload.get("content", ""), + "category": payload.get("category", "")} + self.notes[note_id] = note + return self._ocs_json(note) + if route.startswith(prefix + "/"): + note_id = int(route.rsplit("/", 1)[-1]) + note = self.notes.get(note_id) + if note is None: + return 404, b'{"ocs":{"meta":{"statuscode":404},"data":[]}}', "application/json", {} + if method == "GET": + return self._ocs_json(note) + if method == "PUT": + payload = json.loads(body.decode() or "{}") + note.update({k: v for k, v in payload.items() if v is not None}) + return self._ocs_json(note) + if method == "DELETE": + self.notes.pop(note_id, None) + return self._ocs_json([]) + return 404, b"not found", "text/plain", {} + + +def _xml_escape(text): + return ( + text.replace("&", "&").replace("<", "<").replace(">", ">") + ) + + +@pytest.fixture() +def nextcloud(): + fake = FakeNextcloud() + base = fake.start() + try: + yield fake, base + finally: + fake.stop() + + +def make_client(base, **kwargs): + return NextcloudClient(base, USER, PASSWORD, **kwargs) + + +# ---- client: files ---- + + +def test_client_sends_basic_auth(nextcloud): + fake, base = nextcloud + make_client(base).list_files("/") + assert fake.calls, "the server must have received a request" + header = fake.calls[0][2].get("Authorization") + assert header == "Basic " + base64.b64encode(f"{USER}:{PASSWORD}".encode()).decode() + + +def test_list_files_parses_entries(nextcloud): + _fake, base = nextcloud + result = make_client(base).list_files("/") + assert result["path"] == "/" + names = {entry["name"]: entry for entry in result["entries"]} + assert names["Documents"]["type"] == "dir" + assert names["image.png"]["type"] == "file" + assert names["image.png"]["size"] == len(b"\x89PNG\x00\xff") + assert names["image.png"]["etag"] == '"etag-image.png"' + # Directories sort before files. + assert result["entries"][0]["type"] == "dir" + + +def test_list_files_of_a_subfolder(nextcloud): + _fake, base = nextcloud + result = make_client(base).list_files("/Documents") + assert [entry["name"] for entry in result["entries"]] == ["readme.txt"] + + +def test_stat_returns_one_entry(nextcloud): + _fake, base = nextcloud + entry = make_client(base).stat("/Documents/readme.txt") + assert entry["type"] == "file" + assert entry["size"] == 11 + + +def test_read_text_file(nextcloud): + _fake, base = nextcloud + result = make_client(base).read_file("/Documents/readme.txt") + assert result["encoding"] == "utf-8" + assert result["content"] == "hello world" + + +def test_read_binary_file_is_base64(nextcloud): + _fake, base = nextcloud + result = make_client(base).read_file("/image.png") + assert result["encoding"] == "base64" + assert base64.b64decode(result["content"]) == b"\x89PNG\x00\xff" + + +def test_write_file_round_trip(nextcloud): + fake, base = nextcloud + client = make_client(base) + assert client.write_file("/new.txt", "content", overwrite=False)["ok"] is True + put = [call for call in fake.calls if call[0] == "PUT"][0] + assert put[2].get("If-None-Match") == "*" + assert client.read_file("/new.txt")["content"] == "content" + + +def test_write_file_base64(nextcloud): + fake, base = nextcloud + make_client(base).write_file("/bin.dat", base64.b64encode(b"\x00\x01").decode(), encoding="base64") + assert fake.files["/bin.dat"]["content"] == b"\x00\x01" + + +def test_write_file_rejects_bad_base64(nextcloud): + _fake, base = nextcloud + with pytest.raises(ValueError): + make_client(base).write_file("/bin.dat", "not base64!", encoding="base64") + + +def test_mkdir_and_delete(nextcloud): + fake, base = nextcloud + client = make_client(base) + client.mkdir("/NewFolder") + assert fake.files["/NewFolder"]["type"] == "dir" + client.delete("/NewFolder") + assert "/NewFolder" not in fake.files + + +def test_move_sends_destination_header(nextcloud): + fake, base = nextcloud + result = make_client(base).move("/Documents/readme.txt", "/Documents/renamed.txt", overwrite=True) + assert result["destination"] == "/Documents/renamed.txt" + move = [call for call in fake.calls if call[0] == "MOVE"][0] + assert move[2]["Destination"].endswith("/remote.php/dav/files/alice/Documents/renamed.txt") + assert move[2]["Overwrite"] == "T" + + +def test_copy_sends_destination_header(nextcloud): + fake, base = nextcloud + make_client(base).copy("/Documents/readme.txt", "/Documents/copy.txt") + copy = [call for call in fake.calls if call[0] == "COPY"][0] + assert copy[2]["Overwrite"] == "F" + + +def test_search_returns_matching_files(nextcloud): + _fake, base = nextcloud + results = make_client(base).search("readme") + assert [entry["name"] for entry in results] == ["readme.txt"] + + +# ---- client: calendars ---- + + +def test_list_calendars(nextcloud): + _fake, base = nextcloud + calendars = make_client(base).list_calendars() + assert calendars == [ + { + "name": "personal", + "label": "Personal", + "description": "desc", + "color": "#ff0000", + "ctag": "ctag-1", + } + ] + + +def test_create_and_list_event(nextcloud): + _fake, base = nextcloud + client = make_client(base) + created = client.create_event( + "personal", + "uid-1", + "Lunch with Dana", + "2026-03-01T12:00:00+00:00", + end="2026-03-01T13:00:00+00:00", + location="Cafe", + ) + assert created["uid"] == "uid-1" + events = client.list_events("personal") + assert len(events) == 1 + event = events[0] + assert event["summary"] == "Lunch with Dana" + assert event["location"] == "Cafe" + assert event["start"] == "2026-03-01T12:00:00+00:00" + assert event["all_day"] is False + assert event["uid"] == "uid-1" + + +def test_all_day_event_parses(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_event("personal", "u2", "Holiday", "2026-07-04", end="2026-07-05", all_day=True) + event = client.list_events("personal")[0] + assert event["all_day"] is True + assert event["start"] == "2026-07-04" + + +def test_create_event_sends_if_none_match(nextcloud): + fake, base = nextcloud + make_client(base).create_event("personal", "u3", "X", "2026-03-01T12:00:00Z") + put = [call for call in fake.calls if call[0] == "PUT"][0] + assert put[2].get("If-None-Match") == "*" + + +def test_update_event_preserves_other_properties(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_event( + "personal", "u4", "Original", "2026-03-01T12:00:00Z", + end="2026-03-01T13:00:00Z", location="Office", + ) + client.update_event("personal", "u4", summary="Renamed") + event = client.list_events("personal")[0] + assert event["summary"] == "Renamed" + assert event["location"] == "Office", "unchanged properties must survive an update" + assert event["start"] == "2026-03-01T12:00:00+00:00" + + +def test_update_event_uses_if_match(nextcloud): + fake, base = nextcloud + client = make_client(base) + client.create_event("personal", "u5", "X", "2026-03-01T12:00:00Z") + client.update_event("personal", "u5", summary="Y") + put = [call for call in fake.calls if call[0] == "PUT"][-1] + assert put[2].get("If-Match") == '"etag-u5"' + + +def test_delete_event(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_event("personal", "u6", "X", "2026-03-01T12:00:00Z") + assert client.delete_object("personal", "u6")["ok"] is True + assert client.list_events("personal") == [] + + +def test_update_missing_event_is_a_real_failure(nextcloud): + _fake, base = nextcloud + with pytest.raises(NextcloudError) as exc: + make_client(base).update_event("personal", "ghost", summary="X") + assert exc.value.status == 404 + + +# ---- client: tasks ---- + + +def test_create_and_list_task(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_task("personal", "t1", "Buy milk", due="2026-03-02T09:00:00Z", priority=1) + tasks = client.list_tasks("personal") + assert len(tasks) == 1 + task = tasks[0] + assert task["summary"] == "Buy milk" + assert task["status"] == "NEEDS-ACTION" + assert task["priority"] == 1 + assert task["due"] == "2026-03-02T09:00:00+00:00" + + +def test_complete_task(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_task("personal", "t2", "Do it") + client.complete_task("personal", "t2") + task = client.list_tasks("personal")[0] + assert task["status"] == "COMPLETED" + assert task["percent_complete"] == 100 + + +# ---- client: contacts ---- + + +def test_list_addressbooks(nextcloud): + _fake, base = nextcloud + assert make_client(base).list_addressbooks() == [ + {"name": "contacts", "label": "Contacts", "description": "d"} + ] + + +def test_create_and_list_contact(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_contact( + "contacts", "c1", fn="Dana Lee", emails=["dana@example.com"], phones=["555-1234"], org="Acme" + ) + contacts = client.list_contacts("contacts") + assert len(contacts) == 1 + contact = contacts[0] + assert contact["fn"] == "Dana Lee" + assert contact["emails"] == ["dana@example.com"] + assert contact["phones"] == ["555-1234"] + assert contact["org"] == "Acme" + + +def test_contact_query_filters(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_contact("contacts", "c2", fn="Dana Lee", emails=["dana@example.com"]) + client.create_contact("contacts", "c3", fn="Sam Ray", emails=["sam@example.com"]) + assert [c["fn"] for c in client.list_contacts("contacts", "dana")] == ["Dana Lee"] + assert [c["fn"] for c in client.list_contacts("contacts", "nobody")] == [] + + +def test_update_contact_changes_only_named_fields(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_contact("contacts", "c4", fn="Old", emails=["old@example.com"]) + client.update_contact("contacts", "c4", fn="New") + contact = client.list_contacts("contacts")[0] + assert contact["fn"] == "New" + assert contact["emails"] == ["old@example.com"] + + +def test_delete_contact(nextcloud): + _fake, base = nextcloud + client = make_client(base) + client.create_contact("contacts", "c5", fn="Gone") + client.delete_contact("contacts", "c5") + assert client.list_contacts("contacts") == [] + + +# ---- client: notes + info ---- + + +def test_user_info(nextcloud): + _fake, base = nextcloud + assert make_client(base).user_info()["display_name"] == "Alice" + + +def test_capabilities(nextcloud): + _fake, base = nextcloud + assert make_client(base).capabilities()["version"]["major"] == 28 + + +def test_notes_crud(nextcloud): + _fake, base = nextcloud + client = make_client(base) + created = client.create_note("Shopping", "milk, eggs", category="Home") + note_id = created["id"] + assert client.list_notes()[0]["title"] == "Shopping" + assert client.get_note(note_id)["content"] == "milk, eggs" + updated = client.update_note(note_id, content="milk") + assert updated["content"] == "milk" + assert client.delete_note(note_id)["ok"] is True + assert client.list_notes() == [] + + +# ---- client: failure mapping ---- + + +def test_http_error_carries_status(nextcloud): + _fake, base = nextcloud + with pytest.raises(NextcloudError) as exc: + make_client(base).read_file("/missing.txt") + assert exc.value.status == 404 + + +def test_unconfigured_client_is_not_configured(): + assert NextcloudClient("", "", "").configured is False + assert NextcloudClient("https://cloud", "alice", "pw").configured is True + + +# ---- bridge routes (real client over loopback) ---- + + +def bridge_for(base, **config): + return NextcloudBridge({"url": base, "username": USER, "app_password": PASSWORD, **config}) + + +def test_bridge_health(): + bridge = NextcloudBridge({}) + assert bridge.handle_get("/health", {}) == (200, {"ok": True, "platform": "nextcloud"}) + + +def test_bridge_unconfigured_is_503(): + bridge = NextcloudBridge({}) + status, payload = bridge.handle_get("/files", {}) + assert status == 503 + assert "configured" in payload["error"] + + +def test_bridge_lists_files(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base).handle_get("/files", {"path": ["/Documents"]}) + assert status == 200 + assert [entry["name"] for entry in payload["entries"]] == ["readme.txt"] + + +def test_bridge_create_event(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base, default_calendar="personal").handle_post( + "/calendars/events", + {"summary": "Sync", "start": "2026-03-01T12:00:00Z"}, + ) + assert status == 200 + assert payload["ok"] is True and payload["calendar"] == "personal" + assert payload["uid"] + + +def test_bridge_create_event_requires_summary(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base, default_calendar="personal").handle_post( + "/calendars/events", {"start": "2026-03-01T12:00:00Z"} + ) + assert status == 400 + assert "summary" in payload["error"] + + +def test_bridge_requires_calendar_when_ambiguous(nextcloud): + fake, base = nextcloud + fake.calendars["work"] = {"label": "Work", "objects": {}} + status, payload = bridge_for(base).handle_post( + "/calendars/events", {"summary": "X", "start": "2026-03-01T12:00:00Z"} + ) + assert status == 400 + assert "calendar is required" in payload["error"] + + +def test_bridge_uses_only_calendar_when_unset(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base).handle_post( + "/calendars/events", {"summary": "Only", "start": "2026-03-01T12:00:00Z"} + ) + assert status == 200 and payload["calendar"] == "personal" + + +def test_bridge_maps_nextcloud_error_to_502(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base).handle_get("/files/read", {"path": ["/missing.txt"]}) + assert status == 502 + assert "404" in payload["error"] + + +def test_bridge_notes_create_and_get(nextcloud): + _fake, base = nextcloud + bridge = bridge_for(base) + status, payload = bridge.handle_post("/notes", {"title": "T", "content": "C"}) + assert status == 200 + note_id = payload["note"]["id"] + status, payload = bridge.handle_get("/notes/get", {"id": [str(note_id)]}) + assert status == 200 and payload["note"]["title"] == "T" + + +def test_bridge_rejects_bad_types(nextcloud): + _fake, base = nextcloud + bridge = bridge_for(base, default_calendar="personal") + status, payload = bridge.handle_post( + "/calendars/events", {"summary": "X", "start": "2026-01-01T00:00:00Z", "all_day": "yes"} + ) + assert status == 400 + status, payload = bridge.handle_post("/files/write", {"path": "/x", "content": "c", "overwrite": 1}) + assert status == 400 + + +def test_bridge_token_guard(nextcloud): + _fake, base = nextcloud + bridge = bridge_for(base, token="sekret") + port = bridge.start() + try: + with pytest.raises(urllib.error.HTTPError) as exc: + urllib.request.urlopen(f"http://127.0.0.1:{port}/files?path=/", timeout=5) + assert exc.value.code == 401 + request = urllib.request.Request( + f"http://127.0.0.1:{port}/health", headers={"X-Semif-Token": "sekret"} + ) + with urllib.request.urlopen(request, timeout=5) as response: + assert json.loads(response.read()) == {"ok": True, "platform": "nextcloud"} + finally: + bridge.stop() + + +def test_bridge_falls_back_to_top_level_config(): + bridge = build_bridge( + { + "nextcloud_url": "https://cloud.example.com", + "nextcloud_username": "bob", + "nextcloud_app_password": "pw", + "nextcloud_default_calendar": "work", + }, + "nextcloud", + ) + assert isinstance(bridge, NextcloudBridge) + assert bridge.url == "https://cloud.example.com" + assert bridge.username == "bob" + assert bridge.app_password == "pw" + assert bridge.default_calendar == "work" + + +def test_bridge_block_overrides_top_level(): + bridge = build_bridge( + { + "nextcloud_url": "https://fallback.example.com", + "nextcloud_username": "fallback", + "bridges": {"nextcloud": {"url": "https://block.example.com", "username": "block"}}, + }, + "nextcloud", + ) + assert bridge.url == "https://block.example.com" + assert bridge.username == "block" + + +# ---- fake-client route tests ---- + + +class FakeClient: + configured = True + + def __init__(self): + self.calls = [] + self.calendars = [{"name": "personal", "label": "Personal"}] + + def list_calendars(self): + return self.calendars + + def create_event(self, calendar, uid, **fields): + self.calls.append(("create_event", calendar, uid, fields)) + return {"ok": True, "uid": uid, "calendar": calendar, "etag": ""} + + def write_file(self, path, content, encoding, overwrite): + self.calls.append(("write_file", path, content, encoding, overwrite)) + return {"ok": True, "path": path} + + +def test_bridge_passes_encoding_and_overwrite_through(): + client = FakeClient() + bridge = NextcloudBridge({"url": "x", "username": "u", "app_password": "p"}, client=client) + status, payload = bridge.handle_post( + "/files/write", + {"path": "/x", "content": "ZGF0YQ==", "encoding": "base64", "overwrite": False}, + ) + assert status == 200 + assert client.calls == [("write_file", "/x", "ZGF0YQ==", "base64", False)] + + +def test_bridge_generates_uid_when_absent(): + client = FakeClient() + bridge = NextcloudBridge({"url": "x", "username": "u", "app_password": "p"}, client=client) + status, payload = bridge.handle_post( + "/calendars/events", {"summary": "X", "start": "2026-01-01T00:00:00Z"} + ) + assert status == 200 + assert payload["uid"] + assert client.calls[0][1] == "personal" + + +# ---- catalog / codegen surface ---- + + +def test_known_infos_include_nextcloud(): + infos = {info.name: info for info in known_infos()} + assert "nextcloud" in infos + info = infos["nextcloud"] + assert info.url_config_var == "nextcloud_bridge_url" + assert info.auth_header == "X-Semif-Token" + assert info.auth_config_var == "nextcloud_bridge_token" + + +def test_describe_bridges_renders_nextcloud(): + text = describe_bridges() + assert "service: nextcloud" in text + assert "nextcloud_bridge_url" in text + assert "/calendars/events" in text + assert "/files/read" in text + assert "/notes" in text + + +def test_nextcloud_bridge_check_requirements_is_stdlib(): + ok, hint = NextcloudBridge({}).check_requirements() + assert ok is True and hint is None