nextcloud-client 0.211.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,164 @@
1
+ """Nextcloud Groups API client."""
2
+
3
+ import logging
4
+ from typing import List
5
+
6
+ from .base import BaseNextcloudClient, retry_on_429
7
+ from .ocs import OCS_REQUEST_HEADERS
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class GroupsClient(BaseNextcloudClient):
13
+ """Client for Nextcloud Groups API operations."""
14
+
15
+ app_name = "groups"
16
+
17
+ # Own copy: the module-level dict is shared by every OCS client, so passing
18
+ # it straight through would make any future in-place edit a cross-client bug.
19
+ #
20
+ # It is still ONE object per class, not per instance or per call. Nothing
21
+ # mutates it today, and httpx2 does not touch the dict it is handed. But a
22
+ # future `additional_headers` parameter reaching for
23
+ # `self._OCS_HEADERS.update(...)` would leak into every instance and every
24
+ # later call -- build `{**self._OCS_HEADERS, ...}` instead.
25
+ _OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
26
+
27
+ @retry_on_429
28
+ async def search_groups(
29
+ self,
30
+ search: str | None = None,
31
+ limit: int | None = None,
32
+ offset: int | None = None,
33
+ ) -> List[str]:
34
+ """
35
+ Search for groups on the Nextcloud server.
36
+
37
+ Args:
38
+ search: Optional search string to filter groups
39
+ limit: Optional limit for number of results
40
+ offset: Optional offset for pagination
41
+
42
+ Returns:
43
+ List of group IDs matching the search criteria
44
+ """
45
+ params = {}
46
+ if search is not None:
47
+ params["search"] = search
48
+ if limit is not None:
49
+ params["limit"] = limit
50
+ if offset is not None:
51
+ params["offset"] = offset
52
+
53
+ response = await self._client.get(
54
+ "/ocs/v2.php/cloud/groups",
55
+ params=params,
56
+ headers=self._OCS_HEADERS,
57
+ )
58
+ response.raise_for_status()
59
+ data = response.json()
60
+
61
+ groups = data["ocs"]["data"].get("groups", [])
62
+ return groups
63
+
64
+ @retry_on_429
65
+ async def create_group(self, groupid: str) -> None:
66
+ """
67
+ Create a new group.
68
+
69
+ Args:
70
+ groupid: The group ID to create
71
+
72
+ Raises:
73
+ HTTPStatusError: If the request fails (e.g., group already exists)
74
+ """
75
+ response = await self._client.post(
76
+ "/ocs/v2.php/cloud/groups",
77
+ data={"groupid": groupid},
78
+ headers=self._OCS_HEADERS,
79
+ )
80
+ response.raise_for_status()
81
+ logger.info("Created group: %s", groupid)
82
+
83
+ @retry_on_429
84
+ async def delete_group(self, groupid: str) -> None:
85
+ """
86
+ Delete a group.
87
+
88
+ Args:
89
+ groupid: The group ID to delete
90
+
91
+ Raises:
92
+ HTTPStatusError: If the request fails (e.g., group doesn't exist)
93
+ """
94
+ response = await self._client.delete(
95
+ f"/ocs/v2.php/cloud/groups/{groupid}",
96
+ headers=self._OCS_HEADERS,
97
+ )
98
+ response.raise_for_status()
99
+ logger.info("Deleted group: %s", groupid)
100
+
101
+ @retry_on_429
102
+ async def get_group_members(self, groupid: str) -> List[str]:
103
+ """
104
+ Get members of a group.
105
+
106
+ Args:
107
+ groupid: The group ID
108
+
109
+ Returns:
110
+ List of usernames in the group
111
+ """
112
+ response = await self._client.get(
113
+ f"/ocs/v2.php/cloud/groups/{groupid}",
114
+ headers=self._OCS_HEADERS,
115
+ )
116
+ response.raise_for_status()
117
+ data = response.json()
118
+
119
+ users = data["ocs"]["data"].get("users", [])
120
+ return users
121
+
122
+ @retry_on_429
123
+ async def get_group_subadmins(self, groupid: str) -> List[str]:
124
+ """
125
+ Get subadmins of a group.
126
+
127
+ Args:
128
+ groupid: The group ID
129
+
130
+ Returns:
131
+ List of usernames who are subadmins of the group
132
+ """
133
+ response = await self._client.get(
134
+ f"/ocs/v2.php/cloud/groups/{groupid}/subadmins",
135
+ headers=self._OCS_HEADERS,
136
+ )
137
+ response.raise_for_status()
138
+ data = response.json()
139
+
140
+ # The API returns data as a list or dict depending on results
141
+ subadmins_data = data["ocs"]["data"]
142
+ if isinstance(subadmins_data, list):
143
+ return subadmins_data
144
+ return []
145
+
146
+ @retry_on_429
147
+ async def update_group_displayname(self, groupid: str, displayname: str) -> None:
148
+ """
149
+ Update a group's display name.
150
+
151
+ Args:
152
+ groupid: The group ID
153
+ displayname: The new display name
154
+
155
+ Raises:
156
+ HTTPStatusError: If the request fails
157
+ """
158
+ response = await self._client.put(
159
+ f"/ocs/v2.php/cloud/groups/{groupid}",
160
+ data={"key": "displayname", "value": displayname},
161
+ headers=self._OCS_HEADERS,
162
+ )
163
+ response.raise_for_status()
164
+ logger.info("Updated group %s displayname to: %s", groupid, displayname)
@@ -0,0 +1,69 @@
1
+ """httpx2 client and transport factories for Nextcloud connections.
2
+
3
+ TLS verification and keep-alive are explicit arguments here. The MCP server
4
+ fills them from its configuration (``NEXTCLOUD_VERIFY_SSL``,
5
+ ``NEXTCLOUD_CA_BUNDLE``, ``NEXTCLOUD_HTTP_KEEPALIVE``) in
6
+ ``nextcloud_mcp_server.http``.
7
+ """
8
+
9
+ from collections.abc import Mapping
10
+ from types import MappingProxyType
11
+ from typing import Any
12
+
13
+ import httpx2
14
+
15
+ #: Sent on every request to Nextcloud. A non-browser client identifies itself
16
+ #: with ``OCS-APIRequest: true``. OCS routes refuse requests without it
17
+ #: (``meta.statuscode: 997``). It also exempts app routes from the CSRF check.
18
+ #: On ``#[CORS]`` app routes it stops ``CORSMiddleware`` from logging the
19
+ #: session out and re-authenticating, which is the path that 404s Tables v1 on
20
+ #: Nextcloud 33 (GH #1664). This is the only place the header is spelled, and
21
+ #: per-request headers merge over it. The mapping is read-only for the same
22
+ #: reason as ``ocs.OCS_REQUEST_HEADERS``: every client shares this one object.
23
+ NEXTCLOUD_DEFAULT_HEADERS: Mapping[str, str] = MappingProxyType(
24
+ {"OCS-APIRequest": "true"}
25
+ )
26
+
27
+
28
+ def nextcloud_httpx_client(**kwargs: Any) -> httpx2.AsyncClient:
29
+ """Create an httpx2.AsyncClient that sends ``NEXTCLOUD_DEFAULT_HEADERS``.
30
+
31
+ The default headers are client defaults, and caller-supplied ``headers``
32
+ are merged over them.
33
+
34
+ This factory is Nextcloud-specific. Build clients for other services
35
+ (Qdrant, the embedding gateway, document processors, ...) with
36
+ ``httpx2.AsyncClient`` directly. The configured OIDC provider is the one
37
+ sanctioned exception: it shares Nextcloud's TLS settings and ignores the
38
+ extra header.
39
+
40
+ Args:
41
+ **kwargs: Forwarded to ``httpx2.AsyncClient()``.
42
+ """
43
+ # httpx2.Headers: case-insensitive override, and accepts every header shape
44
+ # httpx2 does (mapping, Headers, list of tuples).
45
+ headers = httpx2.Headers(NEXTCLOUD_DEFAULT_HEADERS)
46
+ headers.update(kwargs.get("headers") or {})
47
+ kwargs["headers"] = headers
48
+ return httpx2.AsyncClient(**kwargs)
49
+
50
+
51
+ def nextcloud_httpx_transport(
52
+ *, keepalive: bool = True, **kwargs: Any
53
+ ) -> httpx2.AsyncHTTPTransport:
54
+ """Create an httpx2.AsyncHTTPTransport for Nextcloud.
55
+
56
+ With ``keepalive=False`` the transport is built with
57
+ ``Limits(max_keepalive_connections=0)``, so every request opens a fresh
58
+ connection instead of reusing a pooled keep-alive one. This stops a
59
+ truncated or desynced response from poisoning a pooled connection and
60
+ silently returning empty bytes on later reads (see #965). A
61
+ caller-supplied ``limits`` kwarg takes precedence.
62
+
63
+ Args:
64
+ keepalive: Whether pooled connections may be reused.
65
+ **kwargs: Forwarded to ``httpx2.AsyncHTTPTransport()``.
66
+ """
67
+ if not keepalive:
68
+ kwargs.setdefault("limits", httpx2.Limits(max_keepalive_connections=0))
69
+ return httpx2.AsyncHTTPTransport(**kwargs)
@@ -0,0 +1,50 @@
1
+ """Instrumentation hooks for the Nextcloud clients. They do nothing by default.
2
+
3
+ The clients do not depend on prometheus or OpenTelemetry. An application that
4
+ wants metrics or traces subclasses :class:`Instrumentation` and installs an
5
+ instance at startup. The MCP server does so in
6
+ ``nextcloud_mcp_server.observability.metrics``::
7
+
8
+ from nextcloud_client import instrumentation
9
+
10
+ class MyHooks(instrumentation.Instrumentation):
11
+ def on_api_call(self, app, method, status_code, duration): ...
12
+
13
+ instrumentation.hooks = MyHooks()
14
+
15
+ Call sites read ``instrumentation.hooks`` at call time, never at import time,
16
+ so the installed object takes effect for clients that already exist.
17
+ """
18
+
19
+ from contextlib import AbstractContextManager, nullcontext
20
+
21
+
22
+ class Instrumentation:
23
+ """No-op hooks. Override the ones you need.
24
+
25
+ Hooks run inline in the request path and must not raise. Calls are not
26
+ wrapped, so an exception from a hook fails the API call it observes.
27
+ """
28
+
29
+ def on_api_call(
30
+ self, app: str, method: str, status_code: int, duration: float
31
+ ) -> None:
32
+ """One finished request to Nextcloud; ``status_code`` is 0 if none arrived."""
33
+
34
+ def on_api_retry(self, app: str, reason: str) -> None:
35
+ """A request about to be retried (``reason`` is e.g. "429" or "423")."""
36
+
37
+ def on_download_truncated(self) -> None:
38
+ """A WebDAV GET returned fewer bytes than expected."""
39
+
40
+ def on_scan_truncated(self) -> None:
41
+ """A folder-expansion SEARCH hit its result ceiling."""
42
+
43
+ def trace_api_call(
44
+ self, app: str, method: str, path: str | None = None
45
+ ) -> AbstractContextManager[object]:
46
+ """Context manager wrapping one request to Nextcloud, e.g. a trace span."""
47
+ return nullcontext()
48
+
49
+
50
+ hooks: Instrumentation = Instrumentation()