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.
- nextcloud_client/__init__.py +477 -0
- nextcloud_client/auth.py +34 -0
- nextcloud_client/availability.py +290 -0
- nextcloud_client/base.py +443 -0
- nextcloud_client/calendar.py +3430 -0
- nextcloud_client/collectives.py +325 -0
- nextcloud_client/contacts.py +1321 -0
- nextcloud_client/cookbook.py +244 -0
- nextcloud_client/dav_errors.py +187 -0
- nextcloud_client/dav_urls.py +61 -0
- nextcloud_client/deck.py +930 -0
- nextcloud_client/groups.py +164 -0
- nextcloud_client/http.py +69 -0
- nextcloud_client/instrumentation.py +50 -0
- nextcloud_client/mail.py +825 -0
- nextcloud_client/models/__init__.py +1 -0
- nextcloud_client/models/deck.py +302 -0
- nextcloud_client/models/sharing.py +24 -0
- nextcloud_client/models/talk.py +136 -0
- nextcloud_client/models/users.py +41 -0
- nextcloud_client/news.py +394 -0
- nextcloud_client/notes.py +293 -0
- nextcloud_client/notes_search.py +113 -0
- nextcloud_client/ocs.py +140 -0
- nextcloud_client/py.typed +0 -0
- nextcloud_client/sharing.py +364 -0
- nextcloud_client/shopping_list.py +150 -0
- nextcloud_client/tables.py +146 -0
- nextcloud_client/talk.py +487 -0
- nextcloud_client/users.py +239 -0
- nextcloud_client/webdav.py +3046 -0
- nextcloud_client-0.211.0.dist-info/METADATA +102 -0
- nextcloud_client-0.211.0.dist-info/RECORD +34 -0
- nextcloud_client-0.211.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Client for Nextcloud Cookbook app operations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any, Dict, List
|
|
5
|
+
from urllib.parse import quote
|
|
6
|
+
|
|
7
|
+
from httpx2 import Timeout
|
|
8
|
+
|
|
9
|
+
from .base import BaseNextcloudClient
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CookbookClient(BaseNextcloudClient):
|
|
15
|
+
"""Client for Nextcloud Cookbook app operations."""
|
|
16
|
+
|
|
17
|
+
app_name = "cookbook"
|
|
18
|
+
|
|
19
|
+
async def get_version(self) -> Dict[str, Any]:
|
|
20
|
+
"""Get Cookbook app and API version."""
|
|
21
|
+
response = await self._make_request("GET", "/apps/cookbook/api/version")
|
|
22
|
+
return response.json()
|
|
23
|
+
|
|
24
|
+
async def get_config(self) -> Dict[str, Any]:
|
|
25
|
+
"""Get current Cookbook app configuration."""
|
|
26
|
+
response = await self._make_request("GET", "/apps/cookbook/api/v1/config")
|
|
27
|
+
return response.json()
|
|
28
|
+
|
|
29
|
+
async def set_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
30
|
+
"""Set Cookbook app configuration.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
config: Configuration dictionary with fields like:
|
|
34
|
+
- folder: Recipe folder path
|
|
35
|
+
- update_interval: Auto-rescan interval in minutes
|
|
36
|
+
- print_image: Whether to print images with recipes
|
|
37
|
+
- visibleInfoBlocks: Visible info blocks configuration
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Response with status message
|
|
41
|
+
"""
|
|
42
|
+
response = await self._make_request(
|
|
43
|
+
"POST", "/apps/cookbook/api/v1/config", json=config
|
|
44
|
+
)
|
|
45
|
+
return response.json()
|
|
46
|
+
|
|
47
|
+
async def reindex(self) -> str:
|
|
48
|
+
"""Trigger a rescan of all recipes into the caching database.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Success message
|
|
52
|
+
"""
|
|
53
|
+
response = await self._make_request("POST", "/apps/cookbook/api/v1/reindex")
|
|
54
|
+
return response.json()
|
|
55
|
+
|
|
56
|
+
async def list_recipes(self) -> List[Dict[str, Any]]:
|
|
57
|
+
"""Get all recipes in the database.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
List of recipe stubs with basic information
|
|
61
|
+
"""
|
|
62
|
+
response = await self._make_request("GET", "/apps/cookbook/api/v1/recipes")
|
|
63
|
+
return response.json()
|
|
64
|
+
|
|
65
|
+
async def get_recipe(self, recipe_id: int) -> Dict[str, Any]:
|
|
66
|
+
"""Get a single recipe by ID.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
recipe_id: The recipe ID
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
Full recipe data
|
|
73
|
+
"""
|
|
74
|
+
response = await self._make_request(
|
|
75
|
+
"GET", f"/apps/cookbook/api/v1/recipes/{recipe_id}"
|
|
76
|
+
)
|
|
77
|
+
return response.json()
|
|
78
|
+
|
|
79
|
+
async def create_recipe(self, recipe_data: Dict[str, Any]) -> int:
|
|
80
|
+
"""Create a new recipe.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
recipe_data: Recipe data following schema.org/Recipe format.
|
|
84
|
+
Required: name
|
|
85
|
+
Optional: description, ingredients, instructions, etc.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
ID of the newly created recipe
|
|
89
|
+
"""
|
|
90
|
+
response = await self._make_request(
|
|
91
|
+
"POST", "/apps/cookbook/api/v1/recipes", json=recipe_data
|
|
92
|
+
)
|
|
93
|
+
return response.json()
|
|
94
|
+
|
|
95
|
+
async def update_recipe(self, recipe_id: int, recipe_data: Dict[str, Any]) -> int:
|
|
96
|
+
"""Update an existing recipe.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
recipe_id: The recipe ID to update
|
|
100
|
+
recipe_data: Updated recipe data
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
ID of the updated recipe
|
|
104
|
+
"""
|
|
105
|
+
response = await self._make_request(
|
|
106
|
+
"PUT", f"/apps/cookbook/api/v1/recipes/{recipe_id}", json=recipe_data
|
|
107
|
+
)
|
|
108
|
+
return response.json()
|
|
109
|
+
|
|
110
|
+
async def delete_recipe(self, recipe_id: int) -> str:
|
|
111
|
+
"""Delete a recipe.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
recipe_id: The recipe ID to delete
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
Success message
|
|
118
|
+
"""
|
|
119
|
+
response = await self._make_request(
|
|
120
|
+
"DELETE", f"/apps/cookbook/api/v1/recipes/{recipe_id}"
|
|
121
|
+
)
|
|
122
|
+
return response.json()
|
|
123
|
+
|
|
124
|
+
async def import_recipe(self, url: str) -> Dict[str, Any]:
|
|
125
|
+
"""Import a recipe from a URL using schema.org metadata.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
url: URL of the recipe to import
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Full imported recipe data
|
|
132
|
+
"""
|
|
133
|
+
logger.info("Importing recipe from URL: %s", url)
|
|
134
|
+
response = await self._make_request(
|
|
135
|
+
"POST",
|
|
136
|
+
"/apps/cookbook/api/v1/import",
|
|
137
|
+
json={"url": url},
|
|
138
|
+
timeout=Timeout(300.0),
|
|
139
|
+
)
|
|
140
|
+
return response.json()
|
|
141
|
+
|
|
142
|
+
async def get_recipe_image(self, recipe_id: int, size: str = "full") -> bytes:
|
|
143
|
+
"""Get the main image of a recipe.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
recipe_id: The recipe ID
|
|
147
|
+
size: Image size - "full", "thumb" (250px), or "thumb16" (16px)
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Image bytes
|
|
151
|
+
"""
|
|
152
|
+
response = await self._make_request(
|
|
153
|
+
"GET",
|
|
154
|
+
f"/apps/cookbook/api/v1/recipes/{recipe_id}/image",
|
|
155
|
+
params={"size": size},
|
|
156
|
+
)
|
|
157
|
+
return response.content
|
|
158
|
+
|
|
159
|
+
async def search_recipes(self, query: str) -> List[Dict[str, Any]]:
|
|
160
|
+
"""Search for recipes by keywords, tags, and categories.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
query: Search string (URL-encoded, space/comma separated)
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
List of matching recipe stubs
|
|
167
|
+
"""
|
|
168
|
+
encoded_query = quote(query)
|
|
169
|
+
response = await self._make_request(
|
|
170
|
+
"GET", f"/apps/cookbook/api/v1/search/{encoded_query}"
|
|
171
|
+
)
|
|
172
|
+
return response.json()
|
|
173
|
+
|
|
174
|
+
async def list_categories(self) -> List[Dict[str, Any]]:
|
|
175
|
+
"""Get all known categories.
|
|
176
|
+
|
|
177
|
+
Note: A category name of '*' indicates recipes with no category.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
List of categories with recipe counts
|
|
181
|
+
"""
|
|
182
|
+
response = await self._make_request("GET", "/apps/cookbook/api/v1/categories")
|
|
183
|
+
return response.json()
|
|
184
|
+
|
|
185
|
+
async def get_recipes_in_category(self, category: str) -> List[Dict[str, Any]]:
|
|
186
|
+
"""Get all recipes in a specific category.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
category: Category name (use "_" for recipes with no category)
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
List of recipe stubs in the category
|
|
193
|
+
"""
|
|
194
|
+
encoded_category = quote(category)
|
|
195
|
+
response = await self._make_request(
|
|
196
|
+
"GET", f"/apps/cookbook/api/v1/category/{encoded_category}"
|
|
197
|
+
)
|
|
198
|
+
return response.json()
|
|
199
|
+
|
|
200
|
+
async def rename_category(self, old_name: str, new_name: str) -> str:
|
|
201
|
+
"""Rename a category.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
old_name: Current category name
|
|
205
|
+
new_name: New category name
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
New category name
|
|
209
|
+
"""
|
|
210
|
+
encoded_old_name = quote(old_name)
|
|
211
|
+
response = await self._make_request(
|
|
212
|
+
"PUT",
|
|
213
|
+
f"/apps/cookbook/api/v1/category/{encoded_old_name}",
|
|
214
|
+
json={"name": new_name},
|
|
215
|
+
)
|
|
216
|
+
return response.json()
|
|
217
|
+
|
|
218
|
+
async def list_keywords(self) -> List[Dict[str, Any]]:
|
|
219
|
+
"""Get all known keywords/tags.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
List of keywords with recipe counts
|
|
223
|
+
"""
|
|
224
|
+
response = await self._make_request("GET", "/apps/cookbook/api/v1/keywords")
|
|
225
|
+
return response.json()
|
|
226
|
+
|
|
227
|
+
async def get_recipes_with_keywords(
|
|
228
|
+
self, keywords: List[str]
|
|
229
|
+
) -> List[Dict[str, Any]]:
|
|
230
|
+
"""Get all recipes associated with certain keywords.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
keywords: List of keywords to filter by
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
List of recipe stubs matching the keywords
|
|
237
|
+
"""
|
|
238
|
+
# Join keywords with commas
|
|
239
|
+
keywords_str = ",".join(keywords)
|
|
240
|
+
encoded_keywords = quote(keywords_str)
|
|
241
|
+
response = await self._make_request(
|
|
242
|
+
"GET", f"/apps/cookbook/api/v1/tags/{encoded_keywords}"
|
|
243
|
+
)
|
|
244
|
+
return response.json()
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Surface the explanation Nextcloud's DAV layer already sends on a failure.
|
|
2
|
+
|
|
3
|
+
Sabre/DAV answers a failed request with a document naming the concrete cause::
|
|
4
|
+
|
|
5
|
+
<?xml version="1.0" encoding="utf-8"?>
|
|
6
|
+
<d:error xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns">
|
|
7
|
+
<s:exception>Sabre\\DAV\\Exception\\Locked</s:exception>
|
|
8
|
+
<s:message>File is currently write locked</s:message>
|
|
9
|
+
</d:error>
|
|
10
|
+
|
|
11
|
+
The status alone under-specifies the cause: a bare ``412`` says nothing about
|
|
12
|
+
*which* precondition failed, and a ``403`` can be a share permission, a blocked
|
|
13
|
+
filename, or a quota rule. Discarding that body is the difference between an
|
|
14
|
+
actionable error and a shrug -- an unfiltered WebDAV SEARCH returning ``500``
|
|
15
|
+
took far longer to diagnose than it should have, because the server was saying
|
|
16
|
+
``TypeError`` in a body nobody read.
|
|
17
|
+
|
|
18
|
+
Three statuses get their own type because callers branch on them:
|
|
19
|
+
|
|
20
|
+
=== ============================== =======================================
|
|
21
|
+
412 :class:`DavPreconditionFailed` ``If-Match`` ETag no longer current
|
|
22
|
+
423 :class:`DavLocked` resource write-locked by another client
|
|
23
|
+
507 :class:`DavInsufficientStorage` quota exhausted
|
|
24
|
+
=== ============================== =======================================
|
|
25
|
+
|
|
26
|
+
Everything here derives from :class:`httpx2.HTTPStatusError`, so handlers that
|
|
27
|
+
predate this module keep catching these unchanged.
|
|
28
|
+
|
|
29
|
+
Both of ``BaseNextcloudClient``'s request paths are wired to this: the buffered
|
|
30
|
+
``_make_request`` and the streaming ``_stream_request``. The streaming one
|
|
31
|
+
raises before its body is read, so it gets the status-based type without the
|
|
32
|
+
server's wording -- a 507 download is still a
|
|
33
|
+
:class:`DavInsufficientStorage`.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import xml.etree.ElementTree as ET
|
|
37
|
+
|
|
38
|
+
from httpx2 import HTTPStatusError, Request, Response, ResponseNotRead
|
|
39
|
+
|
|
40
|
+
# An XML namespace URI, not an address anything is fetched from. Namespaces are
|
|
41
|
+
# matched as exact strings, so "upgrading" this to https would stop every Sabre
|
|
42
|
+
# error document from being recognised. The same literal appears inline in
|
|
43
|
+
# webdav.py's PROPFIND bodies.
|
|
44
|
+
SABREDAV_NAMESPACE = "http://sabredav.org/ns" # NOSONAR(S5332)
|
|
45
|
+
|
|
46
|
+
# DAV error documents run to a few hundred bytes. Anything larger is not one,
|
|
47
|
+
# and handing it to the XML parser would turn a failed request into an
|
|
48
|
+
# unbounded amount of work on a path that is already failing.
|
|
49
|
+
MAX_ERROR_BODY_BYTES = 64 * 1024
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class DavError(HTTPStatusError):
|
|
53
|
+
"""A failed DAV request, carrying the server's own explanation."""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
message: str,
|
|
58
|
+
*,
|
|
59
|
+
request: Request,
|
|
60
|
+
response: Response,
|
|
61
|
+
dav_exception: str | None = None,
|
|
62
|
+
dav_message: str | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
super().__init__(message, request=request, response=response)
|
|
65
|
+
self.dav_exception = dav_exception
|
|
66
|
+
self.dav_message = dav_message
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DavPreconditionFailed(DavError):
|
|
70
|
+
"""412 -- a precondition failed, typically a stale ``If-Match`` ETag."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class DavLocked(DavError):
|
|
74
|
+
"""423 -- the resource is write-locked by another client."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class DavInsufficientStorage(DavError):
|
|
78
|
+
"""507 -- the write would exceed the available quota."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_STATUS_TYPES: dict[int, type[DavError]] = {
|
|
82
|
+
412: DavPreconditionFailed,
|
|
83
|
+
423: DavLocked,
|
|
84
|
+
507: DavInsufficientStorage,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def parse_dav_error_body(response: Response) -> tuple[str | None, str | None]:
|
|
89
|
+
"""Extract ``(s:exception, s:message)`` from a DAV error response.
|
|
90
|
+
|
|
91
|
+
Returns ``(None, None)`` for anything that is not a readable Sabre error
|
|
92
|
+
document -- an unread streaming response, a JSON body, an oversized body,
|
|
93
|
+
or malformed XML. This runs while another error is already being raised, so
|
|
94
|
+
it must never raise one of its own.
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
body = response.content
|
|
98
|
+
except ResponseNotRead:
|
|
99
|
+
# Streaming responses raise before the body is read. Nothing to add.
|
|
100
|
+
return None, None
|
|
101
|
+
|
|
102
|
+
# Anything that is not a real byte body -- a test double, a stub response
|
|
103
|
+
# from a caller that fakes the httpx2 surface -- is not a DAV error document.
|
|
104
|
+
# This runs while another exception is already propagating, so degrading to
|
|
105
|
+
# "no detail" is the only acceptable outcome. Raising here would replace the
|
|
106
|
+
# caller's real failure with a TypeError from the error handler itself.
|
|
107
|
+
if not isinstance(body, (bytes, bytearray)):
|
|
108
|
+
return None, None
|
|
109
|
+
|
|
110
|
+
if not body or len(body) > MAX_ERROR_BODY_BYTES:
|
|
111
|
+
return None, None
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
root = ET.fromstring(body)
|
|
115
|
+
except (ET.ParseError, LookupError, ValueError):
|
|
116
|
+
# Not XML (an OCS JSON body, an HTML error page from a proxy) or
|
|
117
|
+
# truncated. Both are ordinary here, not worth a log line. LookupError:
|
|
118
|
+
# an XML declaration naming an unknown ``encoding=`` gets past the parser.
|
|
119
|
+
return None, None
|
|
120
|
+
|
|
121
|
+
exception = root.find(f".//{{{SABREDAV_NAMESPACE}}}exception")
|
|
122
|
+
message = root.find(f".//{{{SABREDAV_NAMESPACE}}}message")
|
|
123
|
+
return (
|
|
124
|
+
exception.text if exception is not None else None,
|
|
125
|
+
message.text if message is not None else None,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def dav_error_from_response(
|
|
130
|
+
status: int, *, method: str, url: str, body: bytes | str = b""
|
|
131
|
+
) -> HTTPStatusError:
|
|
132
|
+
"""Build the typed error for a DAV failure observed outside httpx2.
|
|
133
|
+
|
|
134
|
+
The CalDAV client talks through the ``caldav`` library rather than
|
|
135
|
+
``BaseNextcloudClient._make_request`` (an intentional exception -- it has
|
|
136
|
+
its own DAV session), and ``caldav``'s ``put`` *returns* a 412 rather than
|
|
137
|
+
raising. So that path has a status, a URL and a body but no
|
|
138
|
+
``HTTPStatusError`` to enrich. This wraps them into the same vocabulary, so
|
|
139
|
+
a stale-ETag CalDAV write raises the same
|
|
140
|
+
:class:`DavPreconditionFailed` a WebDAV one would.
|
|
141
|
+
"""
|
|
142
|
+
if isinstance(body, str):
|
|
143
|
+
body = body.encode("utf-8", errors="replace")
|
|
144
|
+
|
|
145
|
+
request = Request(method, url)
|
|
146
|
+
response = Response(status, content=body, request=request)
|
|
147
|
+
return enrich_dav_error(
|
|
148
|
+
HTTPStatusError(
|
|
149
|
+
f"{status} error for {method} {url}", request=request, response=response
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def enrich_dav_error(exc: HTTPStatusError) -> HTTPStatusError:
|
|
155
|
+
"""Return *exc* re-expressed with the server's explanation attached.
|
|
156
|
+
|
|
157
|
+
Returns the original exception untouched when there is nothing to add, so
|
|
158
|
+
non-DAV callers (OCS, the app APIs) are unaffected on every status *except*
|
|
159
|
+
412/423/507. Those three are typed off the status code alone, whatever the
|
|
160
|
+
body: the type says "the server answered 412", not "a Sabre document was
|
|
161
|
+
found". A 412 with no parseable body still becomes a
|
|
162
|
+
:class:`DavPreconditionFailed`, just without the ``Server said:`` suffix.
|
|
163
|
+
That is deliberate -- callers branch on those statuses, and a type that
|
|
164
|
+
appeared only when the body happened to parse would be useless to branch on.
|
|
165
|
+
Nothing downstream is affected either way, since every catch site tests
|
|
166
|
+
``isinstance`` or ``.response.status_code`` rather than an exact type.
|
|
167
|
+
"""
|
|
168
|
+
dav_exception, dav_message = parse_dav_error_body(exc.response)
|
|
169
|
+
status = exc.response.status_code
|
|
170
|
+
error_type = _STATUS_TYPES.get(status)
|
|
171
|
+
|
|
172
|
+
if dav_exception is None and dav_message is None and error_type is None:
|
|
173
|
+
return exc
|
|
174
|
+
|
|
175
|
+
detail = ": ".join(part for part in (dav_exception, dav_message) if part)
|
|
176
|
+
# Single line on purpose: callers log this with "%s" (webdav.py does), and a
|
|
177
|
+
# newline here would split one failure across two log records -- which line-
|
|
178
|
+
# oriented log shipping then indexes as two unrelated events.
|
|
179
|
+
message = f"{exc} -- Server said: {detail}" if detail else str(exc)
|
|
180
|
+
|
|
181
|
+
return (error_type or DavError)(
|
|
182
|
+
message,
|
|
183
|
+
request=exc.request,
|
|
184
|
+
response=exc.response,
|
|
185
|
+
dav_exception=dav_exception,
|
|
186
|
+
dav_message=dav_message,
|
|
187
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Percent-encode DAV paths and URLs by one rule, for every DAV client.
|
|
2
|
+
|
|
3
|
+
Paths flow through these clients already URL-decoded -- ``unquote`` on the
|
|
4
|
+
``<d:href>`` of a PROPFIND/REPORT response, the principal id discovered by
|
|
5
|
+
``BaseNextcloudClient._ensure_principal_id``, or raw user-supplied paths from
|
|
6
|
+
MCP tools -- so characters like ``#``, ``,`` and spaces reach the transport
|
|
7
|
+
verbatim unless something encodes them.
|
|
8
|
+
|
|
9
|
+
Two transports, two different ways that hurts:
|
|
10
|
+
|
|
11
|
+
* **httpx2** (Notes, WebDAV, Contacts) parses an unencoded ``#`` as a URL
|
|
12
|
+
fragment and silently truncates the request path -> spurious 404 on an
|
|
13
|
+
otherwise-valid file (PR #891, e.g. filenames with ``#``, commas, or
|
|
14
|
+
double/trailing spaces).
|
|
15
|
+
* **caldav** (Calendar) never gets that far: ``DAVObject.__init__`` rejects any
|
|
16
|
+
URL containing a space outright, so every calendar and task operation fails
|
|
17
|
+
before a request is sent (issue #1449).
|
|
18
|
+
|
|
19
|
+
The convention is therefore: **store decoded, encode exactly once at the point
|
|
20
|
+
of use.** Because the input is decoded, a literal ``%`` encodes to ``%25``
|
|
21
|
+
rather than being mistaken for an existing escape, and the round trip is
|
|
22
|
+
lossless -- including for a path that literally contains the text ``%20``.
|
|
23
|
+
|
|
24
|
+
These live here rather than beside one client so the two cannot drift: they did
|
|
25
|
+
once already, when the calendar copy reached for ``urlsplit`` and reintroduced
|
|
26
|
+
the very ``#`` truncation the WebDAV one exists to prevent.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from urllib.parse import quote
|
|
30
|
+
|
|
31
|
+
__all__ = ["encode_dav_path", "encode_dav_url"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def encode_dav_path(path: str) -> str:
|
|
35
|
+
"""Percent-encode a *decoded* DAV path for use in a request URL or header.
|
|
36
|
+
|
|
37
|
+
``quote`` with ``safe="/"`` encodes the unsafe characters while preserving
|
|
38
|
+
the path separators; an ASCII-only path is unchanged. Everything else --
|
|
39
|
+
``#`` and ``?`` included -- is a literal character in a DAV path, not a
|
|
40
|
+
delimiter, so it is encoded rather than treated as a fragment/query marker.
|
|
41
|
+
"""
|
|
42
|
+
return quote(path, safe="/")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def encode_dav_url(url: str) -> str:
|
|
46
|
+
"""Percent-encode the path of a *decoded* DAV path or absolute URL.
|
|
47
|
+
|
|
48
|
+
Same rule as :func:`encode_dav_path`; only the authority is split off
|
|
49
|
+
first, so an absolute URL's scheme, host and port survive.
|
|
50
|
+
``CalendarClient`` stores absolute URLs where ``WebDAVClient`` stores paths.
|
|
51
|
+
|
|
52
|
+
The split is deliberately ``partition`` and not ``urlsplit``: everything
|
|
53
|
+
after the authority is a DAV *path*. ``urlsplit`` would read a ``#`` or
|
|
54
|
+
``?`` in it as a fragment/query delimiter and drop the remainder, silently
|
|
55
|
+
truncating the URL.
|
|
56
|
+
"""
|
|
57
|
+
scheme, sep, rest = url.partition("://")
|
|
58
|
+
if not sep:
|
|
59
|
+
return encode_dav_path(url)
|
|
60
|
+
netloc, slash, path = rest.partition("/")
|
|
61
|
+
return f"{scheme}://{netloc}{slash}{encode_dav_path(path)}"
|