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,325 @@
1
+ """Client for Nextcloud Collectives app API (OCS)."""
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ from .base import BaseNextcloudClient
7
+ from .ocs import (
8
+ OCS_REQUEST_HEADERS,
9
+ describe_ocs_failure,
10
+ parse_ocs_envelope,
11
+ )
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ API_BASE = "/ocs/v2.php/apps/collectives/api/v1.0"
16
+
17
+ _UNSET = object()
18
+ """Sentinel to distinguish 'not provided' from an explicit None."""
19
+
20
+
21
+ class OCSError(Exception):
22
+ """Error returned in the OCS response envelope."""
23
+
24
+ def __init__(self, status_code: int, message: str):
25
+ self.status_code = status_code
26
+ self.message = message
27
+ # No status prefix here: server-side failures arrive already described
28
+ # by ``describe_ocs_failure``, which names the code (and, for 997, what
29
+ # it actually means). Re-prefixing produced "OCS error 404: OCS API
30
+ # error (code 404): ..." in logs and tracebacks. ``status_code`` stays
31
+ # available for the internally-raised cases that carry a bare message.
32
+ super().__init__(message)
33
+
34
+
35
+ class CollectivesClient(BaseNextcloudClient):
36
+ """Client for Nextcloud Collectives app operations."""
37
+
38
+ app_name = "collectives"
39
+
40
+ # Sourced from the shared OCS module so a new call site cannot pick up a
41
+ # drifted copy of the header set -- omitting OCS-APIRequest is what makes
42
+ # Nextcloud answer 997, the failure this module exists to make legible.
43
+ _OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
44
+
45
+ _OCS_HEADERS_JSON: dict[str, str] = {
46
+ **OCS_REQUEST_HEADERS,
47
+ "Content-Type": "application/json",
48
+ }
49
+
50
+ def _unwrap_ocs(self, response_json: dict[str, Any]) -> Any:
51
+ """Unwrap OCS envelope, validating the status before returning data.
52
+
53
+ Raises ``OCSError``, which ``server/collectives`` catches in a dozen
54
+ places. Parsing and failure wording come from :mod:`.ocs`; the
55
+ ``>= 400`` rule stays local because it is looser than the documented
56
+ 100/200 success codes and retightening it here would be a behaviour
57
+ change smuggled into a refactor.
58
+ """
59
+ envelope = parse_ocs_envelope(response_json)
60
+ if envelope.status_code >= 400:
61
+ raise OCSError(
62
+ envelope.status_code,
63
+ describe_ocs_failure(envelope.status_code, envelope.message),
64
+ )
65
+ if not envelope.has_data:
66
+ raise OCSError(500, "OCS response missing 'data' field")
67
+ return envelope.data
68
+
69
+ # Collectives
70
+
71
+ async def get_collectives(self) -> list[dict[str, Any]]:
72
+ """List all collectives the user has access to."""
73
+ response = await self._make_request(
74
+ "GET", f"{API_BASE}/collectives", headers=self._OCS_HEADERS
75
+ )
76
+ data = self._unwrap_ocs(response.json())
77
+ return data["collectives"]
78
+
79
+ async def create_collective(
80
+ self, name: str, emoji: str | None = None
81
+ ) -> dict[str, Any]:
82
+ """Create a new collective."""
83
+ json_data: dict[str, Any] = {"name": name}
84
+ if emoji is not None:
85
+ json_data["emoji"] = emoji
86
+ response = await self._make_request(
87
+ "POST",
88
+ f"{API_BASE}/collectives",
89
+ json=json_data,
90
+ headers=self._OCS_HEADERS_JSON,
91
+ )
92
+ data = self._unwrap_ocs(response.json())
93
+ return data["collective"]
94
+
95
+ async def update_collective(
96
+ self, collective_id: int, emoji: str | None | object = _UNSET
97
+ ) -> dict[str, Any]:
98
+ """Update a collective (emoji).
99
+
100
+ Pass emoji=None to clear the emoji. Omit emoji entirely to leave
101
+ it unchanged.
102
+
103
+ Raises:
104
+ ValueError: If no fields are provided to update.
105
+ """
106
+ json_data: dict[str, Any] = {}
107
+ if emoji is not _UNSET:
108
+ json_data["emoji"] = emoji
109
+ if not json_data:
110
+ raise ValueError("At least one field must be provided to update")
111
+ response = await self._make_request(
112
+ "PUT",
113
+ f"{API_BASE}/collectives/{collective_id}",
114
+ json=json_data,
115
+ headers=self._OCS_HEADERS_JSON,
116
+ )
117
+ data = self._unwrap_ocs(response.json())
118
+ return data["collective"]
119
+
120
+ async def trash_collective(self, collective_id: int) -> None:
121
+ """Move a collective to trash (soft delete)."""
122
+ response = await self._make_request(
123
+ "DELETE",
124
+ f"{API_BASE}/collectives/{collective_id}",
125
+ headers=self._OCS_HEADERS,
126
+ )
127
+ self._unwrap_ocs(response.json())
128
+
129
+ async def delete_collective(self, collective_id: int) -> None:
130
+ """Permanently delete a collective (must be trashed first).
131
+
132
+ This is irreversible. The collective must be in the trash before
133
+ calling this method.
134
+ """
135
+ response = await self._make_request(
136
+ "DELETE",
137
+ f"{API_BASE}/collectives/trash/{collective_id}",
138
+ headers=self._OCS_HEADERS,
139
+ )
140
+ self._unwrap_ocs(response.json())
141
+
142
+ # Trash (collectives)
143
+
144
+ async def get_trashed_collectives(self) -> list[dict[str, Any]]:
145
+ """List trashed collectives."""
146
+ response = await self._make_request(
147
+ "GET", f"{API_BASE}/collectives/trash", headers=self._OCS_HEADERS
148
+ )
149
+ data = self._unwrap_ocs(response.json())
150
+ return data["collectives"]
151
+
152
+ async def restore_collective(self, collective_id: int) -> dict[str, Any]:
153
+ """Restore a collective from trash."""
154
+ response = await self._make_request(
155
+ "PATCH",
156
+ f"{API_BASE}/collectives/trash/{collective_id}",
157
+ headers=self._OCS_HEADERS,
158
+ )
159
+ data = self._unwrap_ocs(response.json())
160
+ return data["collective"]
161
+
162
+ # Pages
163
+
164
+ async def get_pages(self, collective_id: int) -> list[dict[str, Any]]:
165
+ """List all pages in a collective."""
166
+ response = await self._make_request(
167
+ "GET",
168
+ f"{API_BASE}/collectives/{collective_id}/pages",
169
+ headers=self._OCS_HEADERS,
170
+ )
171
+ data = self._unwrap_ocs(response.json())
172
+ return data["pages"]
173
+
174
+ async def get_page(self, collective_id: int, page_id: int) -> dict[str, Any]:
175
+ """Get a single page's metadata."""
176
+ response = await self._make_request(
177
+ "GET",
178
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}",
179
+ headers=self._OCS_HEADERS,
180
+ )
181
+ data = self._unwrap_ocs(response.json())
182
+ return data["page"]
183
+
184
+ async def create_page(
185
+ self, collective_id: int, parent_id: int, title: str
186
+ ) -> dict[str, Any]:
187
+ """Create a new page under a parent page."""
188
+ json_data = {"title": title}
189
+ response = await self._make_request(
190
+ "POST",
191
+ f"{API_BASE}/collectives/{collective_id}/pages/{parent_id}",
192
+ json=json_data,
193
+ headers=self._OCS_HEADERS_JSON,
194
+ )
195
+ data = self._unwrap_ocs(response.json())
196
+ return data["page"]
197
+
198
+ async def move_page(
199
+ self,
200
+ collective_id: int,
201
+ page_id: int,
202
+ parent_id: int | None = None,
203
+ title: str | None = None,
204
+ index: int = 0,
205
+ copy: bool = False,
206
+ ) -> dict[str, Any]:
207
+ """Move or copy a page within a collective."""
208
+ json_data: dict[str, Any] = {"index": index, "copy": copy}
209
+ if parent_id is not None:
210
+ json_data["parentId"] = parent_id
211
+ if title is not None:
212
+ json_data["title"] = title
213
+ response = await self._make_request(
214
+ "PUT",
215
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}",
216
+ json=json_data,
217
+ headers=self._OCS_HEADERS_JSON,
218
+ )
219
+ data = self._unwrap_ocs(response.json())
220
+ return data["page"]
221
+
222
+ async def trash_page(self, collective_id: int, page_id: int) -> None:
223
+ """Move a page to trash (soft delete)."""
224
+ response = await self._make_request(
225
+ "DELETE",
226
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}",
227
+ headers=self._OCS_HEADERS,
228
+ )
229
+ self._unwrap_ocs(response.json())
230
+
231
+ async def set_page_emoji(
232
+ self, collective_id: int, page_id: int, emoji: str | None
233
+ ) -> dict[str, Any]:
234
+ """Set or clear the emoji on a page."""
235
+ # Sending {"emoji": null} intentionally clears the emoji on the server
236
+ json_data = {"emoji": emoji}
237
+ response = await self._make_request(
238
+ "PUT",
239
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}/emoji",
240
+ json=json_data,
241
+ headers=self._OCS_HEADERS_JSON,
242
+ )
243
+ data = self._unwrap_ocs(response.json())
244
+ return data["page"]
245
+
246
+ # Search
247
+
248
+ async def search_pages(
249
+ self, collective_id: int, query: str
250
+ ) -> list[dict[str, Any]]:
251
+ """Full-text search within a collective."""
252
+ response = await self._make_request(
253
+ "GET",
254
+ f"{API_BASE}/collectives/{collective_id}/search",
255
+ params={"searchString": query},
256
+ headers=self._OCS_HEADERS,
257
+ )
258
+ data = self._unwrap_ocs(response.json())
259
+ return data["pages"]
260
+
261
+ # Tags
262
+
263
+ async def get_tags(self, collective_id: int) -> list[dict[str, Any]]:
264
+ """List all tags in a collective."""
265
+ response = await self._make_request(
266
+ "GET",
267
+ f"{API_BASE}/collectives/{collective_id}/tags",
268
+ headers=self._OCS_HEADERS,
269
+ )
270
+ data = self._unwrap_ocs(response.json())
271
+ return data["tags"]
272
+
273
+ async def create_tag(
274
+ self, collective_id: int, name: str, color: str
275
+ ) -> dict[str, Any]:
276
+ """Create a new tag in a collective."""
277
+ json_data = {"name": name, "color": color}
278
+ response = await self._make_request(
279
+ "POST",
280
+ f"{API_BASE}/collectives/{collective_id}/tags",
281
+ json=json_data,
282
+ headers=self._OCS_HEADERS_JSON,
283
+ )
284
+ data = self._unwrap_ocs(response.json())
285
+ return data["tag"]
286
+
287
+ async def assign_tag(self, collective_id: int, page_id: int, tag_id: int) -> None:
288
+ """Assign a tag to a page."""
289
+ response = await self._make_request(
290
+ "PUT",
291
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}/tags/{tag_id}",
292
+ headers=self._OCS_HEADERS,
293
+ )
294
+ self._unwrap_ocs(response.json())
295
+
296
+ async def remove_tag(self, collective_id: int, page_id: int, tag_id: int) -> None:
297
+ """Remove a tag from a page."""
298
+ response = await self._make_request(
299
+ "DELETE",
300
+ f"{API_BASE}/collectives/{collective_id}/pages/{page_id}/tags/{tag_id}",
301
+ headers=self._OCS_HEADERS,
302
+ )
303
+ self._unwrap_ocs(response.json())
304
+
305
+ # Trash
306
+
307
+ async def get_trashed_pages(self, collective_id: int) -> list[dict[str, Any]]:
308
+ """List trashed pages in a collective."""
309
+ response = await self._make_request(
310
+ "GET",
311
+ f"{API_BASE}/collectives/{collective_id}/pages/trash",
312
+ headers=self._OCS_HEADERS,
313
+ )
314
+ data = self._unwrap_ocs(response.json())
315
+ return data["pages"]
316
+
317
+ async def restore_page(self, collective_id: int, page_id: int) -> dict[str, Any]:
318
+ """Restore a page from trash."""
319
+ response = await self._make_request(
320
+ "PATCH",
321
+ f"{API_BASE}/collectives/{collective_id}/pages/trash/{page_id}",
322
+ headers=self._OCS_HEADERS,
323
+ )
324
+ data = self._unwrap_ocs(response.json())
325
+ return data["page"]