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,3046 @@
1
+ """WebDAV client for Nextcloud file operations."""
2
+
3
+ import logging
4
+ import mimetypes
5
+ import xml.etree.ElementTree as ET
6
+ from email.utils import parsedate_to_datetime
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+ from urllib.parse import quote, unquote
10
+ from xml.sax.saxutils import escape as xml_escape
11
+
12
+ import anyio
13
+ from httpx2 import HTTPStatusError, RemoteProtocolError, Response
14
+
15
+ from . import instrumentation
16
+ from .base import BaseNextcloudClient
17
+ from .dav_urls import encode_dav_path
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # ``OCS-APIRequest`` is not spelled anywhere in this module: the shared httpx2
22
+ # client sends it on every request (``nextcloud_client.http.NEXTCLOUD_DEFAULT_HEADERS``). DAV
23
+ # requests here pass only their request-specific ``Depth`` / ``Content-Type`` /
24
+ # ``Destination`` headers, and deliberately not ``ocs.OCS_REQUEST_HEADERS`` --
25
+ # Sabre answers in XML, so its ``Accept: application/json`` would be a lie.
26
+ _XML_CONTENT_TYPE = "text/xml"
27
+
28
+
29
+ class OversizeDownload(Exception):
30
+ """A streamed download exceeded its byte budget and was aborted.
31
+
32
+ Distinct from the pre-flight size gate: that acts on the size the server
33
+ advertised at scan time, this acts on what actually arrives, so it still
34
+ holds when ``Content-Length`` is absent or untrue.
35
+ """
36
+
37
+
38
+ def _read_complete_body(response: Response, label: str) -> bytes:
39
+ """Return the response body, raising on a short read vs ``Content-Length``.
40
+
41
+ A truncated/desynced response on a pooled keep-alive connection can hand
42
+ back an empty/short body that the document parser then reads as ``0 chars``
43
+ and the vector-sync processor permanently dead-letters (#965). Compare the
44
+ received byte count against the declared ``Content-Length`` and raise a
45
+ retryable :class:`httpx2.RemoteProtocolError` on a mismatch: the processor
46
+ retries/re-queues a raised transport error instead of dead-lettering the
47
+ document, so a healthy file recovers on the next scan. (httpx2 already
48
+ raises on most genuine truncations during the read; this is the
49
+ belt-and-suspenders guard for the cases it returns intact. The robust
50
+ mitigation for connection poisoning is ``NEXTCLOUD_HTTP_KEEPALIVE=false``.)
51
+ A missing or malformed header (e.g. ``Transfer-Encoding: chunked``) skips
52
+ the check so legitimately header-less responses never raise.
53
+
54
+ ``Content-Length`` on a compressed response describes the compressed
55
+ size on the wire, not the decompressed ``response.content`` httpx2 hands
56
+ back — comparing the two would misfire on every compressible file
57
+ Nextcloud happens to gzip, so the check only applies to identity-encoded
58
+ responses (see #1099).
59
+ """
60
+ content = response.content
61
+ _verify_content_length(response, len(content), label)
62
+ return content
63
+
64
+
65
+ def _expected_content_length(response: Response) -> int | None:
66
+ """The comparable ``Content-Length``, or ``None`` when the check can't apply.
67
+
68
+ Returns ``None`` for a compressed response (the header describes the
69
+ compressed size on the wire, not the decompressed bytes httpx2 hands back --
70
+ see #1099), a missing header (e.g. ``Transfer-Encoding: chunked``), a
71
+ malformed one, or a degenerate negative length.
72
+ """
73
+ content_encoding = response.headers.get("content-encoding")
74
+ if content_encoding is not None and content_encoding.lower() != "identity":
75
+ return None
76
+ declared = response.headers.get("content-length")
77
+ if declared is None:
78
+ return None
79
+ try:
80
+ expected = int(declared)
81
+ except ValueError:
82
+ # Malformed header — nothing reliable to compare against, so don't
83
+ # raise spuriously; let the (possibly fine) body through.
84
+ return None
85
+ if expected < 0:
86
+ # Degenerate header (negative length) — can't be a real short-read
87
+ # signal and would always trip the check below; ignore it.
88
+ return None
89
+ return expected
90
+
91
+
92
+ def _verify_content_length(response: Response, received: int, label: str) -> None:
93
+ """Raise :class:`RemoteProtocolError` when ``received`` is a short read.
94
+
95
+ Shared by the buffered (:func:`_read_complete_body`) and streaming
96
+ (``WebDavClient.stream_to_file``) download paths so the #965 truncation
97
+ guard and the #1099 content-encoding carve-out cannot drift apart between
98
+ them.
99
+ """
100
+ expected = _expected_content_length(response)
101
+ if expected is None or received == expected:
102
+ return
103
+ instrumentation.hooks.on_download_truncated()
104
+ # Log here, not just in the message: callers funnel this through a
105
+ # generic ``except Exception`` that would otherwise report it as an
106
+ # opaque "Unexpected error reading file".
107
+ logger.warning(
108
+ "Truncated download for %r: expected %d bytes, got %d "
109
+ "(poisoned keep-alive connection? set NEXTCLOUD_HTTP_KEEPALIVE=false "
110
+ "— see #965)",
111
+ label,
112
+ expected,
113
+ received,
114
+ )
115
+ raise RemoteProtocolError(
116
+ f"Truncated download for {label!r}: expected {expected} bytes, "
117
+ f"got {received} (poisoned keep-alive connection? see #965)",
118
+ request=response.request,
119
+ )
120
+
121
+
122
+ # Paging defaults for WebDAV SEARCH. Nextcloud's SEARCH returns a server-default
123
+ # page (~100 results) when no ``<d:nresults>`` is sent, silently truncating large
124
+ # folders. ``search_files_all`` pages explicitly to fetch the complete result set.
125
+ # Small enough that one page returns well inside the client read timeout even on a
126
+ # slow instance: a single 50k-row SEARCH over a ~10k-file folder exceeded 30 s and
127
+ # the resulting truncated discovery purged the index (Deck #1373).
128
+ WEBDAV_SEARCH_PAGE_SIZE = 1000
129
+ # Nextcloud's SEARCH (icewind/searchdav) reads the offset from its *own* XML
130
+ # namespace, not ``DAV:`` -- a ``<d:firstresult>`` is silently ignored.
131
+ SEARCHDAV_NS = "https://github.com/icewind1991/SearchDAV/ns"
132
+ # Hard ceiling so a pathologically large folder can't drive an unbounded crawl.
133
+ # Crossing it is logged as a truncation warning (and surfaced via a metric) so the
134
+ # cap can never again silently hide files.
135
+ WEBDAV_SEARCH_MAX_RESULTS = 50000
136
+ # ids OR-ed into one ``find_files_by_ids`` SEARCH. A search page verifies at most
137
+ # a few hundred files, so this is usually a single request.
138
+ FILE_ID_BATCH = 100
139
+
140
+
141
+ def _reject_path_traversal(path: str) -> str:
142
+ """Reject a DAV path that walks out of the user's home, returning it as-is.
143
+
144
+ Every WebDAV request path is built by ``WebDAVClient._webdav_path``, which
145
+ concatenates caller input onto ``/remote.php/dav/files/<principal>``. MCP
146
+ tool arguments reach that unmodified, so a path containing ``..`` segments
147
+ is normalised away by the URL layer *before* the request leaves us and can
148
+ address another user's home or the DAV root
149
+ (pythonsecurity:S2083). There is no legitimate use of ``..`` in a path
150
+ relative to one's own home, so this fails closed rather than normalising:
151
+ silently rewriting the path would turn a caller's mistake into a
152
+ successful operation on a file they did not name.
153
+
154
+ Backslashes are folded to ``/`` first — Nextcloud treats ``\\`` as a literal
155
+ filename character, but the URL layer does not, so ``..\\..`` must not slip
156
+ past a ``/``-only split.
157
+ """
158
+ if any(segment == ".." for segment in path.replace("\\", "/").split("/")):
159
+ raise ValueError(
160
+ f"Path may not contain '..' segments; it must stay within the "
161
+ f"user's files: {path!r}"
162
+ )
163
+ return path
164
+
165
+
166
+ def normalize_etag(raw: Optional[str]) -> Optional[str]:
167
+ """Strip the quotes an ETag is transported in, so callers can pass it back.
168
+
169
+ Every etag this client surfaces goes through here — ``read_file``,
170
+ ``list_directory``, the search parser and now ``write_file`` — so the
171
+ representation cannot drift between the value we hand out and the value
172
+ ``_write_precondition_header`` expects to re-quote.
173
+
174
+ Two shapes need repairing beyond the quotes:
175
+
176
+ *Weak validators.* ``W/"abc"`` used to come out as ``W/"abc`` because
177
+ ``strip`` only removes characters from the *ends* and the leading ``W``
178
+ protected the opening quote — usable as neither an etag nor an ``If-Match``
179
+ value (RFC 9110 requires strong comparison there anyway). The prefix is now
180
+ removed first.
181
+
182
+ *Content-coding suffixes.* Apache's ``mod_deflate`` appends ``-gzip`` (and
183
+ front ends that compress with zstd append ``-zstd``) to the
184
+ ETag of every compressed response unless ``DeflateAlterETag NoChange`` is
185
+ set; ``AddSuffix`` is the default and the directive did not exist before
186
+ Apache 2.4.15, so many deployments never set it. The etag a caller reads
187
+ back is then not the etag the origin stored, and handing it to ``If-Match``
188
+ makes Nextcloud reject the write — so every overwrite of an existing file
189
+ fails behind such a proxy, with an error that reads like a real conflict.
190
+ """
191
+ if raw is None:
192
+ return None
193
+ # Repeat until nothing changes, so the result is a fixed point: normalising
194
+ # a normalised etag must be a no-op, or the value handed out drifts from the
195
+ # one ``_write_precondition_header`` re-normalises. One pass was not enough
196
+ # for whitespace inside the quotes (``'"\r0'``) or a stacked suffix.
197
+ cleaned = raw
198
+ while True:
199
+ previous = cleaned
200
+ cleaned = cleaned.strip().removeprefix("W/").strip('"')
201
+ for suffix in ("-gzip", "-br", "-deflate", "-zstd"):
202
+ cleaned = cleaned.removesuffix(suffix)
203
+ if cleaned == previous:
204
+ return cleaned
205
+
206
+
207
+ #: Collection holding one file's comments, addressed by file id.
208
+ _COMMENTS_PATH = "/remote.php/dav/comments/files"
209
+
210
+
211
+ def _dav_props_ok(response_elem: ET.Element) -> dict[str, str]:
212
+ """Return a multistatus response's ``200 OK`` properties, keyed by local name.
213
+
214
+ A response carries one ``propstat`` block per status: the 200 one holds the
215
+ values, while a 404 one lists the properties the server does *not* have.
216
+ Folding those in would fabricate empty values for them.
217
+ """
218
+ props: dict[str, str] = {}
219
+ for propstat in response_elem.findall("{DAV:}propstat"):
220
+ # "HTTP/1.1 200 OK" -> the code is the second token. Matching the token
221
+ # rather than a " 200 " substring keeps a reason-phrase-less status line
222
+ # (legal per RFC 9110) working.
223
+ status = (propstat.findtext("{DAV:}status") or "").split()
224
+ if len(status) < 2 or status[1] != "200":
225
+ continue
226
+ prop = propstat.find("{DAV:}prop")
227
+ if prop is None:
228
+ continue
229
+ for child in prop:
230
+ props[str(child.tag).rsplit("}", 1)[-1]] = (child.text or "").strip()
231
+ return props
232
+
233
+
234
+ def _parse_comment_props(props: dict[str, str]) -> dict[str, Any] | None:
235
+ """Shape one comment's DAV properties into the dict ``FileComment`` consumes.
236
+
237
+ Returns None for a row without a usable id — one malformed comment should
238
+ cost the caller that comment, not the whole thread.
239
+ """
240
+ try:
241
+ comment_id = int(props["id"])
242
+ except (KeyError, ValueError):
243
+ logger.warning("Skipping comment with unusable id %r", props.get("id"))
244
+ return None
245
+ return {
246
+ "id": comment_id,
247
+ "message": props.get("message", ""),
248
+ "actor_id": props.get("actorId", ""),
249
+ "actor_type": props.get("actorType", ""),
250
+ "actor_display_name": props.get("actorDisplayName") or None,
251
+ # Raw DAV date (RFC 1123), like every other timestamp this client
252
+ # surfaces -- see FileInfo.last_modified.
253
+ "creation_datetime": props.get("creationDateTime") or None,
254
+ "verb": props.get("verb", ""),
255
+ "is_unread": props.get("isUnread", "").lower() == "true",
256
+ }
257
+
258
+
259
+ def _destination_precondition_header(
260
+ destination_webdav_path: str, if_destination_match: str
261
+ ) -> dict[str, str]:
262
+ """Build the tagged-list ``If:`` header that conditions the *destination*.
263
+
264
+ ``If-Match`` is the obvious choice here and it is **wrong**: per RFC 9110 it
265
+ applies to the request-URI, which for MOVE/COPY is the *source*. Conditioning
266
+ the destination needs RFC 4918 §10.4's tagged-list form, where the resource
267
+ the condition applies to is named explicitly::
268
+
269
+ If: <destination-uri> (["etag"])
270
+
271
+ Three details are load-bearing, all dictated by sabre/dav's parser
272
+ (``Server::getIfConditions``)::
273
+
274
+ /(?:\\<(?P<uri>.*?)\\>\\s)?\\((?P<not>Not\\s)?...(?:\\[(?P<etag>[^\\]]*)\\])?\\)/im
275
+
276
+ * the **space after ``>``** is required by the regex — without it the URI is
277
+ not captured and the condition silently applies to the request-URI instead,
278
+ i.e. it guards the wrong resource;
279
+ * the etag **keeps its quotes inside the brackets**, because the comparison is
280
+ ``$node->getETag() == $token['etag']`` and Nextcloud's ``Node::getETag()``
281
+ returns a quoted value;
282
+ * the URI is resolved with ``calculateUri()``, so it must be the same
283
+ percent-encoded absolute DAV path used in ``Destination``.
284
+ """
285
+ return {"If": f'<{destination_webdav_path}> (["{if_destination_match}"])'}
286
+
287
+
288
+ def _validate_destination_precondition(
289
+ if_destination_match: Optional[str], overwrite: bool
290
+ ) -> None:
291
+ """Reject combinations the WebDAV ``If:`` grammar cannot express.
292
+
293
+ Raised at the client boundary rather than silently reinterpreted, so a
294
+ caller never believes a guard is in force when it is not.
295
+ """
296
+ if if_destination_match is None:
297
+ return
298
+ if if_destination_match == "*":
299
+ raise ValueError(
300
+ "if_destination_match='*' is not expressible: RFC 4918's tagged-list "
301
+ "If: grammar has no wildcard, and 'the destination must exist' cannot "
302
+ "be asserted this way — an If: condition naming a missing URI returns "
303
+ "404, not 412. Use overwrite=True without a destination etag."
304
+ )
305
+ if not overwrite:
306
+ raise ValueError(
307
+ "if_destination_match with overwrite=False is contradictory: the etag "
308
+ "asserts which version of the destination to replace, while "
309
+ "overwrite=False refuses to replace it at all. Pass overwrite=True to "
310
+ "replace exactly that version."
311
+ )
312
+
313
+
314
+ def like_predicate(prop_element: str, value: str) -> str:
315
+ """Build a ``<d:like>`` SEARCH predicate with *value* XML-escaped.
316
+
317
+ Every caller-supplied literal in a SEARCH body goes through here. A value
318
+ containing ``&``, ``<`` or ``>`` -- "Costs & Revenue%" is the everyday case
319
+ -- otherwise produces malformed XML that Sabre/DAV rejects with 400, and
320
+ the search fails rather than returning nothing.
321
+
322
+ It exists as a shared builder rather than an escaping call each site
323
+ remembers to make: the same predicate was being assembled in five places,
324
+ two of which had no escaping at all. Routing construction through one
325
+ function makes the escaping structural instead of a convention.
326
+
327
+ Args:
328
+ prop_element: Namespaced property element, e.g. ``"d:displayname"`` or
329
+ ``"oc:tags"``. Not caller-supplied -- callers pass a literal.
330
+ value: The match value, including any ``%`` wildcards. Escaped here.
331
+ """
332
+ return (
333
+ "<d:like>"
334
+ f"<d:prop><{prop_element}/></d:prop>"
335
+ f"<d:literal>{xml_escape(value)}</d:literal>"
336
+ "</d:like>"
337
+ )
338
+
339
+
340
+ def _write_precondition_header(if_match: Optional[str]) -> dict[str, str]:
341
+ """Pick the single conditional header for a fail-closed PUT.
342
+
343
+ A write always carries a precondition so it can never silently clobber an
344
+ existing file (the server evaluates it atomically before the PUT):
345
+
346
+ - ``None`` -> ``If-None-Match: *`` (create-only)
347
+ - ``"*"`` -> ``If-Match: *`` (force-overwrite an existing file)
348
+ - an etag -> ``If-Match: "<etag>"`` (overwrite iff unchanged)
349
+ """
350
+ if if_match is None:
351
+ return {"If-None-Match": "*"}
352
+ if if_match == "*":
353
+ return {"If-Match": "*"}
354
+ return {"If-Match": f'"{normalize_etag(if_match)}"'}
355
+
356
+
357
+ def _write_conflict_result(
358
+ if_match: Optional[str], status_code: int, path: str
359
+ ) -> Optional[Dict[str, Any]]:
360
+ """Map a known write-conflict status to a structured result, else ``None``.
361
+
362
+ 412 and 423 are conditions a caller must react to (not transport failures),
363
+ so :meth:`WebDAVClient.write_file` returns them rather than raising, matching
364
+ ``move_resource``/``copy_resource``. Which 412 message applies depends on
365
+ which precondition we sent -- the client knows, so it gives a cause-specific,
366
+ actionable message instead of parsing the server's response body. Any other
367
+ status returns ``None`` so the caller re-raises.
368
+ """
369
+ if status_code == 412:
370
+ if if_match is None:
371
+ logger.debug(
372
+ "Precondition failed writing '%s': file already exists "
373
+ "(create-only If-None-Match)",
374
+ path,
375
+ )
376
+ return {
377
+ "status_code": 412,
378
+ "message": "File already exists — read it first to get its etag "
379
+ "and pass if_match to overwrite safely, or pass if_match='*' to "
380
+ "overwrite deliberately",
381
+ }
382
+ if if_match == "*":
383
+ logger.debug(
384
+ "Precondition failed writing '%s': file does not exist "
385
+ "(force-overwrite If-Match: *)",
386
+ path,
387
+ )
388
+ return {
389
+ "status_code": 412,
390
+ "message": "File does not exist — cannot force-overwrite a missing "
391
+ "file; omit if_match to create it",
392
+ }
393
+ logger.debug(
394
+ "Precondition failed writing '%s': file changed since if_match etag "
395
+ "was read",
396
+ path,
397
+ )
398
+ return {
399
+ "status_code": 412,
400
+ "message": "File was modified since the given etag was read "
401
+ "(concurrent edit) — re-read before writing",
402
+ }
403
+ if status_code == 423:
404
+ logger.debug("Resource locked writing '%s'", path)
405
+ return {
406
+ "status_code": 423,
407
+ "message": "File is locked by another client (e.g. open in the "
408
+ "Nextcloud web editor) — not retried automatically",
409
+ }
410
+ return None
411
+
412
+
413
+ class WebDAVClient(BaseNextcloudClient):
414
+ """Client for Nextcloud WebDAV operations."""
415
+
416
+ app_name = "webdav"
417
+
418
+ def _webdav_path(self, path: str) -> str:
419
+ """Build the request path for ``path`` under the user's DAV root.
420
+
421
+ Percent-encodes the caller-supplied portion (see ``encode_dav_path``)
422
+ so names with ``#``, commas, or spaces don't truncate/404; the base
423
+ ``/remote.php/dav/files/<principal>`` segment is left as-is.
424
+
425
+ Precondition: ``path`` is a **decoded** path (the convention everywhere
426
+ in this client — PROPFIND/REPORT hrefs are ``unquote``d before storage,
427
+ and MCP-tool inputs are raw). It is encoded exactly once, so passing an
428
+ already-encoded path would double-encode it (``%20`` → ``%2520``).
429
+
430
+ Raises ``ValueError`` for a path containing ``..``. This is the single
431
+ chokepoint every WebDAV request path goes through, so guarding here
432
+ covers read/write/delete/move/copy/list at once rather than per caller.
433
+ """
434
+ safe_path = _reject_path_traversal(path)
435
+ return (
436
+ f"{self._get_webdav_base_path()}/{encode_dav_path(safe_path.lstrip('/'))}"
437
+ )
438
+
439
+ async def delete_resource(self, path: str) -> Dict[str, Any]:
440
+ """Delete a resource (file or directory) via WebDAV DELETE."""
441
+ await self._ensure_principal_id()
442
+ # Ensure path ends with a slash if it's a directory
443
+ if not path.endswith("/"):
444
+ path_with_slash = f"{path}/"
445
+ else:
446
+ path_with_slash = path
447
+
448
+ webdav_path = self._webdav_path(path_with_slash)
449
+ logger.debug("Deleting WebDAV resource: %s", webdav_path)
450
+
451
+ try:
452
+ # First try a PROPFIND to verify resource exists
453
+ propfind_headers = {"Depth": "0"}
454
+ try:
455
+ propfind_resp = await self._make_request(
456
+ "PROPFIND", webdav_path, headers=propfind_headers
457
+ )
458
+ logger.debug(
459
+ "Resource exists check status: %s", propfind_resp.status_code
460
+ )
461
+ except HTTPStatusError as e:
462
+ if e.response.status_code == 404:
463
+ logger.debug(
464
+ "Resource '%s' doesn't exist, no deletion needed", path
465
+ )
466
+ return {"status_code": 404}
467
+ # For other errors, continue with deletion attempt
468
+
469
+ # Proceed with deletion
470
+ response = await self._make_request("DELETE", webdav_path)
471
+ logger.debug("Successfully deleted WebDAV resource '%s'", path)
472
+ return {"status_code": response.status_code}
473
+
474
+ except HTTPStatusError as e:
475
+ if e.response.status_code == 404:
476
+ logger.debug("Resource '%s' not found, no deletion needed", path)
477
+ return {"status_code": 404}
478
+ else:
479
+ logger.error("HTTP error deleting WebDAV resource '%s': %s", path, e)
480
+ raise e
481
+ except Exception as e:
482
+ logger.error("Unexpected error deleting WebDAV resource '%s': %s", path, e)
483
+ raise e
484
+
485
+ async def cleanup_old_attachment_directory(
486
+ self, note_id: int, old_category: str
487
+ ) -> Dict[str, Any]:
488
+ """Remove the husk left at a note's old category after a category change.
489
+
490
+ Only removes the directory if it is EMPTY. The Notes app relocates
491
+ ``.attachments.<note_id>`` to the new category itself as part of the
492
+ category change, so by the time this runs the old path is normally
493
+ already gone. Anything still *in* it is live attachment data the server
494
+ has not moved yet — deleting that would destroy the user's attachments
495
+ rather than tidy up after them, and the directory the caller wants gone
496
+ would take the files with it.
497
+ """
498
+ old_category_path_part = f"{old_category}/" if old_category else ""
499
+ old_attachment_dir_path = (
500
+ f"Notes/{old_category_path_part}.attachments.{note_id}/"
501
+ )
502
+
503
+ logger.debug(
504
+ "Cleaning up old attachment directory: %s", old_attachment_dir_path
505
+ )
506
+ try:
507
+ try:
508
+ remaining = await self.list_directory(old_attachment_dir_path)
509
+ except HTTPStatusError as e:
510
+ if e.response.status_code != 404:
511
+ raise
512
+ # Already gone (the normal case — the server moved it). Fall
513
+ # through to the DELETE, which no-ops on 404.
514
+ remaining = []
515
+
516
+ if remaining:
517
+ logger.warning(
518
+ "Refusing to delete old attachment directory %s for note %s: "
519
+ "it still holds %d item(s), so the server has not relocated "
520
+ "them to the new category yet. Leaving it in place — deleting "
521
+ "it here would destroy those attachments.",
522
+ old_attachment_dir_path,
523
+ note_id,
524
+ len(remaining),
525
+ )
526
+ # 412: we refused because the "directory is empty" precondition
527
+ # did not hold. Keeps the {"status_code": int} shape callers see.
528
+ return {"status_code": 412, "deleted": False}
529
+
530
+ # ponytail: probe-then-delete, not an atomic conditional delete —
531
+ # a write into this old path between the two calls would still be
532
+ # removed. WebDAV has no "delete only if empty" (DELETE on a
533
+ # collection is always infinite-depth), so closing it means an
534
+ # If-Match on the collection etag. Not worth it for a window that
535
+ # needs someone writing into the *previous* category of a note that
536
+ # just moved; upgrade if that ever shows up in practice.
537
+ delete_result = await self.delete_resource(path=old_attachment_dir_path)
538
+ logger.debug("Cleanup result: %s", delete_result)
539
+ return delete_result
540
+ except Exception as e:
541
+ logger.error("Error during cleanup of old attachment directory: %s", e)
542
+ raise e
543
+
544
+ async def cleanup_note_attachments(
545
+ self, note_id: int, category: str
546
+ ) -> Dict[str, Any]:
547
+ """Clean up attachment directory for a specific note and category."""
548
+ cat_path_part = f"{category}/" if category else ""
549
+ attachment_dir_path = f"Notes/{cat_path_part}.attachments.{note_id}/"
550
+
551
+ logger.debug(
552
+ "Cleaning up attachments for note %s in category '%s'", note_id, category
553
+ )
554
+ try:
555
+ delete_result = await self.delete_resource(path=attachment_dir_path)
556
+ logger.debug("Cleanup result for note %s: %s", note_id, delete_result)
557
+ return delete_result
558
+ except Exception as e:
559
+ logger.error("Failed cleaning up attachments for note %s: %s", note_id, e)
560
+ raise e
561
+
562
+ async def add_note_attachment(
563
+ self,
564
+ note_id: int,
565
+ filename: str,
566
+ content: bytes,
567
+ category: Optional[str] = None,
568
+ mime_type: Optional[str] = None,
569
+ ) -> Dict[str, Any]:
570
+ """Add/Update an attachment to a note via WebDAV PUT."""
571
+ await self._ensure_principal_id()
572
+ # Construct paths based on provided category. Encode via _webdav_path so
573
+ # categories/filenames with '#', commas or spaces don't truncate/404.
574
+ category_path_part = f"{category}/" if category else ""
575
+ attachment_dir_segment = f".attachments.{note_id}"
576
+ parent_dir_webdav_rel_path = (
577
+ f"Notes/{category_path_part}{attachment_dir_segment}"
578
+ )
579
+ parent_dir_path = self._webdav_path(parent_dir_webdav_rel_path)
580
+ attachment_path = self._webdav_path(f"{parent_dir_webdav_rel_path}/{filename}")
581
+
582
+ logger.debug("Uploading attachment '%s' for note %s", filename, note_id)
583
+
584
+ if not mime_type:
585
+ mime_type, _ = mimetypes.guess_type(filename)
586
+ if not mime_type:
587
+ mime_type = "application/octet-stream"
588
+
589
+ headers = {"Content-Type": mime_type}
590
+ try:
591
+ # First check if we can access WebDAV at all
592
+ notes_dir_path = self._webdav_path("Notes")
593
+ propfind_headers = {"Depth": "0"}
594
+ notes_dir_response = await self._make_request(
595
+ "PROPFIND", notes_dir_path, headers=propfind_headers
596
+ )
597
+
598
+ if notes_dir_response.status_code == 401:
599
+ logger.error("WebDAV authentication failed for Notes directory")
600
+ raise HTTPStatusError(
601
+ f"Authentication error accessing WebDAV Notes directory: {notes_dir_response.status_code}",
602
+ request=notes_dir_response.request,
603
+ response=notes_dir_response,
604
+ )
605
+ elif notes_dir_response.status_code >= 400:
606
+ logger.error(
607
+ "Error accessing WebDAV Notes directory: %s",
608
+ notes_dir_response.status_code,
609
+ )
610
+ notes_dir_response.raise_for_status()
611
+
612
+ # Ensure the parent directory exists using MKCOL
613
+ mkcol_response = await self._make_request("MKCOL", parent_dir_path)
614
+
615
+ # MKCOL should return 201 Created or 405 Method Not Allowed (if directory already exists)
616
+ if mkcol_response.status_code not in [201, 405]:
617
+ logger.error(
618
+ "Unexpected status code %s when creating attachments directory",
619
+ mkcol_response.status_code,
620
+ )
621
+ mkcol_response.raise_for_status()
622
+
623
+ # Proceed with the PUT request
624
+ response = await self._make_request(
625
+ "PUT", attachment_path, content=content, headers=headers
626
+ )
627
+ response.raise_for_status()
628
+ logger.debug(
629
+ "Successfully uploaded attachment '%s' to note %s", filename, note_id
630
+ )
631
+ return {"status_code": response.status_code}
632
+
633
+ except HTTPStatusError as e:
634
+ logger.error(
635
+ "HTTP error uploading attachment '%s' to note %s: %s",
636
+ filename,
637
+ note_id,
638
+ e,
639
+ )
640
+ raise e
641
+ except Exception as e:
642
+ logger.error(
643
+ "Unexpected error uploading attachment '%s' to note %s: %s",
644
+ filename,
645
+ note_id,
646
+ e,
647
+ )
648
+ raise e
649
+
650
+ async def get_note_attachment(
651
+ self, note_id: int, filename: str, category: Optional[str] = None
652
+ ) -> Tuple[bytes, str]:
653
+ """Fetch a specific attachment from a note via WebDAV GET."""
654
+ await self._ensure_principal_id()
655
+ category_path_part = f"{category}/" if category else ""
656
+ attachment_dir_segment = f".attachments.{note_id}"
657
+ attachment_path = self._webdav_path(
658
+ f"Notes/{category_path_part}{attachment_dir_segment}/{filename}"
659
+ )
660
+
661
+ logger.debug("Fetching attachment '%s' for note %s", filename, note_id)
662
+
663
+ try:
664
+ response = await self._make_request("GET", attachment_path)
665
+ response.raise_for_status()
666
+
667
+ content = _read_complete_body(response, filename)
668
+ mime_type = response.headers.get("content-type", "application/octet-stream")
669
+
670
+ logger.debug(
671
+ "Successfully fetched attachment '%s' (%s bytes)",
672
+ filename,
673
+ len(content),
674
+ )
675
+ return content, mime_type
676
+
677
+ except HTTPStatusError as e:
678
+ if e.response.status_code == 404:
679
+ logger.debug("Attachment '%s' not found for note %s", filename, note_id)
680
+ else:
681
+ logger.error(
682
+ "HTTP error fetching attachment '%s' for note %s: %s",
683
+ filename,
684
+ note_id,
685
+ e,
686
+ )
687
+ raise e
688
+ except Exception as e:
689
+ logger.error(
690
+ "Unexpected error fetching attachment '%s' for note %s: %s",
691
+ filename,
692
+ note_id,
693
+ e,
694
+ )
695
+ raise e
696
+
697
+ async def list_directory(self, path: str = "") -> List[Dict[str, Any]]:
698
+ """List files and directories in the specified path via WebDAV PROPFIND."""
699
+ await self._ensure_principal_id()
700
+ webdav_path = self._webdav_path(path)
701
+ if not webdav_path.endswith("/"):
702
+ webdav_path += "/"
703
+
704
+ logger.debug("Listing directory: %s", path)
705
+
706
+ # oc:fileid is requested alongside the DAV properties because it is the
707
+ # only stable identity a browser link can use (/index.php/f/<id>); paths
708
+ # move and rename. The search PROPFINDs below already ask for it.
709
+ propfind_body = """<?xml version="1.0"?>
710
+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
711
+ <d:prop>
712
+ <d:displayname/>
713
+ <d:getcontentlength/>
714
+ <d:getcontenttype/>
715
+ <d:getlastmodified/>
716
+ <d:getetag/>
717
+ <d:resourcetype/>
718
+ <oc:fileid/>
719
+ </d:prop>
720
+ </d:propfind>"""
721
+
722
+ headers = {"Depth": "1", "Content-Type": _XML_CONTENT_TYPE}
723
+
724
+ try:
725
+ response = await self._make_request(
726
+ "PROPFIND", webdav_path, content=propfind_body, headers=headers
727
+ )
728
+ response.raise_for_status()
729
+
730
+ # Parse the XML response
731
+ root = ET.fromstring(response.content)
732
+ items = []
733
+
734
+ # Skip the first response (the directory itself)
735
+ responses = root.findall(".//{DAV:}response")[1:]
736
+
737
+ for response_elem in responses:
738
+ href = response_elem.find(".//{DAV:}href")
739
+ if href is None:
740
+ continue
741
+
742
+ # Extract file/directory name from href. <d:href> is required by
743
+ # RFC 3986 to be percent-encoded, so non-ASCII names arrive
744
+ # encoded — decode before exposing to callers (issue #776).
745
+ href_text = href.text or ""
746
+ name = unquote(href_text.rstrip("/").split("/")[-1])
747
+ if not name:
748
+ continue
749
+
750
+ # Get properties
751
+ propstat = response_elem.find(".//{DAV:}propstat")
752
+ if propstat is None:
753
+ continue
754
+
755
+ prop = propstat.find(".//{DAV:}prop")
756
+ if prop is None:
757
+ continue
758
+
759
+ # Determine if it's a directory
760
+ resourcetype = prop.find(".//{DAV:}resourcetype")
761
+ is_directory = (
762
+ resourcetype is not None
763
+ and resourcetype.find(".//{DAV:}collection") is not None
764
+ )
765
+
766
+ # Get other properties
767
+ size_elem = prop.find(".//{DAV:}getcontentlength")
768
+ size = (
769
+ int(size_elem.text)
770
+ if size_elem is not None and size_elem.text
771
+ else 0
772
+ )
773
+
774
+ content_type_elem = prop.find(".//{DAV:}getcontenttype")
775
+ content_type = (
776
+ content_type_elem.text if content_type_elem is not None else None
777
+ )
778
+
779
+ modified_elem = prop.find(".//{DAV:}getlastmodified")
780
+ modified = modified_elem.text if modified_elem is not None else None
781
+
782
+ # Strip surrounding quotes to match every other etag path in
783
+ # this client (a caller feeds this straight into write_file's
784
+ # if_match, which re-adds the quotes for the If-Match header).
785
+ etag_elem = prop.find(".//{DAV:}getetag")
786
+ etag = (
787
+ normalize_etag(etag_elem.text)
788
+ if etag_elem is not None and etag_elem.text
789
+ else None
790
+ )
791
+
792
+ # Parsed defensively, unlike the sizes above: file_id only feeds
793
+ # the deep link, so a server that ever returns a non-numeric one
794
+ # should cost the caller that link, not the whole listing.
795
+ fileid_elem = prop.find(".//{http://owncloud.org/ns}fileid")
796
+ file_id = None
797
+ if fileid_elem is not None and fileid_elem.text:
798
+ try:
799
+ file_id = int(fileid_elem.text)
800
+ except ValueError:
801
+ logger.warning(
802
+ "Ignoring non-numeric oc:fileid %r for %s",
803
+ fileid_elem.text,
804
+ name,
805
+ )
806
+
807
+ items.append(
808
+ {
809
+ "name": name,
810
+ "path": f"{path.rstrip('/')}/{name}" if path else name,
811
+ "is_directory": is_directory,
812
+ "size": size if not is_directory else None,
813
+ "content_type": content_type,
814
+ "last_modified": modified,
815
+ "etag": etag,
816
+ "file_id": file_id,
817
+ }
818
+ )
819
+
820
+ logger.debug("Found %s items in directory: %s", len(items), path)
821
+ return items
822
+
823
+ except HTTPStatusError as e:
824
+ # A missing directory is an expected outcome for callers that probe
825
+ # before acting (see cleanup_old_attachment_directory), not a fault.
826
+ if e.response.status_code == 404:
827
+ logger.debug("Directory '%s' not found", webdav_path)
828
+ else:
829
+ logger.error("HTTP error listing directory '%s': %s", webdav_path, e)
830
+ raise e
831
+ except Exception as e:
832
+ logger.error("Unexpected error listing directory '%s': %s", webdav_path, e)
833
+ raise e
834
+
835
+ async def stream_to_file(
836
+ self, path: str, dest: Path, *, max_bytes: int | None = None
837
+ ) -> Tuple[int, str, Optional[str]]:
838
+ """Stream a WebDAV GET straight to ``dest``, never holding the whole body.
839
+
840
+ :meth:`read_file` buffers the entire response (``response.content``), so
841
+ peak memory scales with file size -- a 531 MB PDF OOMKilled an ingest
842
+ worker mid-download. Streaming keeps resident memory at one chunk
843
+ regardless of how large the document is.
844
+
845
+ ``max_bytes`` aborts the transfer as soon as the limit is exceeded and
846
+ removes the partial file. This is the guard that survives an absent or
847
+ untrue ``Content-Length``: the pre-flight size gate can only act on what
848
+ the server advertised at scan time, whereas this acts on what actually
849
+ arrives.
850
+
851
+ Returns ``(bytes_written, content_type, etag)`` -- the same triple
852
+ :meth:`read_file` returns, so a caller that streams a document can still
853
+ hand the etag back as ``write_file``'s ``if_match`` (or report it) without
854
+ a second request. The etag is ``None`` if the server sent no ``ETag``.
855
+ Raises :class:`OversizeDownload` if ``max_bytes`` is exceeded, or
856
+ :class:`httpx2.RemoteProtocolError` on a short read (#965).
857
+ """
858
+ await self._ensure_principal_id()
859
+ webdav_path = self._webdav_path(path)
860
+
861
+ logger.debug("Streaming file to %s: %s", dest, path)
862
+
863
+ written = 0
864
+ try:
865
+ async with self._stream_request("GET", webdav_path) as response:
866
+ content_type = response.headers.get(
867
+ "content-type", "application/octet-stream"
868
+ )
869
+ etag = normalize_etag(response.headers.get("etag"))
870
+ # anyio's async file wrapper, not pathlib.Path.open: the writes
871
+ # run on a worker thread, so streaming a multi-hundred-MB
872
+ # document does not block the event loop (and with it every other
873
+ # in-flight job on this worker) for the duration of the download.
874
+ async with await anyio.open_file(dest, "wb") as fh:
875
+ async for chunk in response.aiter_bytes():
876
+ written += len(chunk)
877
+ if max_bytes is not None and written > max_bytes:
878
+ raise OversizeDownload(
879
+ f"Download of {path!r} exceeded {max_bytes} bytes "
880
+ f"(aborted after {written})"
881
+ )
882
+ await fh.write(chunk)
883
+ # Same short-read guard as the buffered path, against bytes
884
+ # written rather than bytes held in memory.
885
+ _verify_content_length(response, written, path)
886
+ except BaseException:
887
+ # Never leave a partial or over-cap file behind for the parser to
888
+ # read as a valid (truncated) document.
889
+ dest.unlink(missing_ok=True)
890
+ raise
891
+
892
+ logger.debug("Streamed '%s' to %s (%s bytes)", path, dest, written)
893
+ return written, content_type, etag
894
+
895
+ async def read_file(self, path: str) -> Tuple[bytes, str, Optional[str]]:
896
+ """Read a file's content via WebDAV GET.
897
+
898
+ Returns the ``ETag`` alongside the content so a caller that intends to
899
+ write the file back can pass it as ``write_file``'s ``if_match`` and
900
+ detect a concurrent edit (made e.g. directly in the Nextcloud web UI)
901
+ instead of silently overwriting it -- there was previously no way for
902
+ a caller to even notice that race. The etag is ``None`` if the server
903
+ did not return an ``ETag`` header.
904
+ """
905
+ await self._ensure_principal_id()
906
+ webdav_path = self._webdav_path(path)
907
+
908
+ logger.debug("Reading file: %s", path)
909
+
910
+ try:
911
+ response = await self._make_request("GET", webdav_path)
912
+ response.raise_for_status()
913
+
914
+ content = _read_complete_body(response, path)
915
+ content_type = response.headers.get(
916
+ "content-type", "application/octet-stream"
917
+ )
918
+ etag = normalize_etag(response.headers.get("etag"))
919
+
920
+ logger.debug("Successfully read file '%s' (%s bytes)", path, len(content))
921
+ return content, content_type, etag
922
+
923
+ except HTTPStatusError as e:
924
+ logger.error("HTTP error reading file '%s': %s", path, e)
925
+ raise e
926
+ except Exception as e:
927
+ logger.error("Unexpected error reading file '%s': %s", path, e)
928
+ raise e
929
+
930
+ async def get_preview(self, path: str, size: int) -> tuple[bytes, str]:
931
+ """Fetch Nextcloud's preview of a file, scaled to fit ``size`` x ``size``.
932
+
933
+ Uses ``GET /index.php/core/preview.png?file=<path>``, the route the
934
+ Files app loads thumbnails from. Despite the name it answers with what
935
+ the preview provider produces: JPEG for photos, PNG for images with
936
+ transparency. Nextcloud keeps the aspect ratio (``a=1``), applies the
937
+ EXIF orientation, never upscales, and only renders a few sizes,
938
+ rounding the request up to the next one (256, 1024, or the largest
939
+ preview the server allows).
940
+
941
+ ``forceIcon=0`` and ``mimeFallback=false`` make a file without a
942
+ preview provider answer 404 instead of a generic file-type icon.
943
+
944
+ Args:
945
+ path: File path relative to the user's files root.
946
+ size: Requested bounding box edge, in pixels.
947
+
948
+ Returns:
949
+ ``(content, content_type)`` of the preview image.
950
+
951
+ Raises:
952
+ HTTPStatusError: 404 when the file does not exist or Nextcloud
953
+ cannot render a preview for it.
954
+ """
955
+ response = await self._make_request(
956
+ "GET",
957
+ "/core/preview.png",
958
+ params={
959
+ "file": "/" + path.lstrip("/"),
960
+ "x": size,
961
+ "y": size,
962
+ "a": 1,
963
+ "forceIcon": 0,
964
+ "mimeFallback": "false",
965
+ },
966
+ )
967
+ content = _read_complete_body(response, path)
968
+ content_type = response.headers.get("content-type", "application/octet-stream")
969
+ return content, content_type
970
+
971
+ async def write_file(
972
+ self,
973
+ path: str,
974
+ content: bytes,
975
+ content_type: Optional[str] = None,
976
+ if_match: Optional[str] = None,
977
+ ) -> Dict[str, Any]:
978
+ """Write content to a file via WebDAV PUT.
979
+
980
+ Every PUT is conditional: the write is fail-closed so an existing file
981
+ is never silently overwritten. Exactly one precondition header is sent,
982
+ chosen by ``if_match``:
983
+
984
+ ================= ==================== ======================================
985
+ ``if_match`` Header sent Behaviour (412 = precondition failed)
986
+ ================= ==================== ======================================
987
+ ``None`` (default) ``If-None-Match: *`` Create-only. 412 if the path already
988
+ exists -- read it first to get an etag.
989
+ an etag, e.g. abc ``If-Match: "abc"`` Conditional overwrite. 412 if the file
990
+ changed since that etag (or is gone).
991
+ ``"*"`` ``If-Match: *`` Force-overwrite an existing file. 412 if
992
+ it does not exist.
993
+ ================= ==================== ======================================
994
+
995
+ Args:
996
+ path: Destination path.
997
+ content: Raw bytes to write.
998
+ content_type: MIME type (guessed from ``path`` if omitted).
999
+ if_match: ``None`` to create a new file (fails if it exists); an
1000
+ etag from :meth:`read_file` to overwrite only if unchanged; or
1001
+ the literal ``"*"`` to force-overwrite an existing file.
1002
+
1003
+ Returns:
1004
+ ``{"status_code": ...}`` on success. On a 412 (a precondition above
1005
+ failed) or a 423 (WebDAV lock held by another client, e.g. the file
1006
+ is open in the Nextcloud web editor), returns ``{"status_code": ...,
1007
+ "message": ...}`` instead of raising, matching ``move_resource``/
1008
+ ``copy_resource``'s handling of their own known conflict statuses
1009
+ -- both are conditions a caller should react to, not a transport
1010
+ failure. Any other error status still raises ``HTTPStatusError``.
1011
+ """
1012
+ await self._ensure_principal_id()
1013
+ webdav_path = self._webdav_path(path)
1014
+
1015
+ logger.debug("Writing file: %s", path)
1016
+
1017
+ if not content_type:
1018
+ content_type, _ = mimetypes.guess_type(path)
1019
+ if not content_type:
1020
+ content_type = "application/octet-stream"
1021
+
1022
+ headers = {"Content-Type": content_type}
1023
+ # Always send a precondition so a write can never silently clobber an
1024
+ # existing file. The server (Sabre checkPreconditions) evaluates it
1025
+ # atomically before the PUT, so this is race-free.
1026
+ headers.update(_write_precondition_header(if_match))
1027
+
1028
+ try:
1029
+ response = await self._make_request(
1030
+ "PUT", webdav_path, content=content, headers=headers
1031
+ )
1032
+ response.raise_for_status()
1033
+
1034
+ logger.debug("Successfully wrote file '%s'", path)
1035
+ # Surface the new etag so a read-modify-write loop can chain writes
1036
+ # without a re-GET. Nextcloud also sends OC-ETag; prefer the standard
1037
+ # header and fall back. May be None if a proxy stripped both, in
1038
+ # which case the caller must re-read before its next conditional
1039
+ # write.
1040
+ return {
1041
+ "status_code": response.status_code,
1042
+ "etag": normalize_etag(
1043
+ response.headers.get("etag") or response.headers.get("oc-etag")
1044
+ ),
1045
+ }
1046
+
1047
+ except HTTPStatusError as e:
1048
+ # 412/423 are actionable conflicts the caller must handle -> return
1049
+ # a structured result. Anything else is a genuine transport error.
1050
+ conflict = _write_conflict_result(if_match, e.response.status_code, path)
1051
+ if conflict is not None:
1052
+ return conflict
1053
+ logger.error("HTTP error writing file '%s': %s", path, e)
1054
+ raise e
1055
+ except Exception as e:
1056
+ logger.error("Unexpected error writing file '%s': %s", path, e)
1057
+ raise e
1058
+
1059
+ async def create_directory(
1060
+ self, path: str, recursive: bool = False
1061
+ ) -> Dict[str, Any]:
1062
+ """Create a directory via WebDAV MKCOL."""
1063
+ await self._ensure_principal_id()
1064
+ webdav_path = self._webdav_path(path)
1065
+ if not webdav_path.endswith("/"):
1066
+ webdav_path += "/"
1067
+
1068
+ logger.debug("Creating directory: %s", path)
1069
+
1070
+ try:
1071
+ response = await self._make_request("MKCOL", webdav_path)
1072
+ response.raise_for_status()
1073
+
1074
+ logger.debug("Successfully created directory '%s'", path)
1075
+ return {"status_code": response.status_code}
1076
+
1077
+ except HTTPStatusError as e:
1078
+ # Method Not Allowed - directory already exists
1079
+ if e.response.status_code == 405:
1080
+ logger.debug("Directory '%s' already exists", path)
1081
+ return {"status_code": 405, "message": "Directory already exists"}
1082
+
1083
+ # File Conflict - parent directory does not exist
1084
+ if e.response.status_code == 409 and recursive:
1085
+ # Extract parent directory path
1086
+ path_parts = path.strip("/").split("/")
1087
+ if len(path_parts) > 1:
1088
+ parent_dir = "/".join(path_parts[:-1])
1089
+ logger.debug(
1090
+ "Parent directory '%s' doesn't exist, creating recursively",
1091
+ parent_dir,
1092
+ )
1093
+ await self.create_directory(parent_dir, recursive)
1094
+ # Now try to create the original directory again
1095
+ return await self.create_directory(path, recursive)
1096
+ else:
1097
+ # This shouldn't happen for single-level directories under root
1098
+ logger.error("409 conflict for single-level directory '%s'", path)
1099
+ raise e
1100
+
1101
+ logger.error("HTTP error creating directory '%s': %s", path, e)
1102
+ raise e
1103
+ except Exception as e:
1104
+ logger.error("Unexpected error creating directory '%s': %s", path, e)
1105
+ raise e
1106
+
1107
+ @staticmethod
1108
+ def _transfer_conflict_result(
1109
+ status_code: int,
1110
+ if_destination_match: Optional[str],
1111
+ ) -> Optional[Dict[str, Any]]:
1112
+ """Map a known MOVE/COPY conflict status to a structured result, else None.
1113
+
1114
+ Mirrors ``_write_conflict_result``. ``None`` means "not a conflict we
1115
+ model" — the caller re-raises.
1116
+
1117
+ 404 and 412 mean different things depending on whether a destination etag
1118
+ was sent, because sabre resolves the tagged ``If:`` URI with
1119
+ ``getNodeForPath``: a missing destination raises NotFound and surfaces as
1120
+ 404, not 412.
1121
+ """
1122
+ if status_code == 404:
1123
+ if if_destination_match is not None:
1124
+ return {
1125
+ "status_code": 404,
1126
+ "message": (
1127
+ "Source not found, or the destination whose etag was "
1128
+ "asserted does not exist (an If: condition naming a "
1129
+ "missing URI yields 404, not 412)."
1130
+ ),
1131
+ }
1132
+ return {"status_code": 404, "message": "Source resource not found"}
1133
+ if status_code == 412:
1134
+ if if_destination_match is not None:
1135
+ return {
1136
+ "status_code": 412,
1137
+ "message": (
1138
+ "Destination changed since that etag was read — re-read "
1139
+ "it before retrying. Note the etag condition applies to "
1140
+ "files only: a directory destination always fails this "
1141
+ "check."
1142
+ ),
1143
+ }
1144
+ return {
1145
+ "status_code": 412,
1146
+ "message": "Destination already exists and overwrite is false",
1147
+ }
1148
+ if status_code == 409:
1149
+ return {
1150
+ "status_code": 409,
1151
+ "message": "Parent directory of destination doesn't exist",
1152
+ }
1153
+ return None
1154
+
1155
+ async def _transfer_resource(
1156
+ self,
1157
+ method: str,
1158
+ source_path: str,
1159
+ destination_path: str,
1160
+ overwrite: bool = False,
1161
+ *,
1162
+ if_destination_match: Optional[str] = None,
1163
+ ) -> Dict[str, Any]:
1164
+ """Shared implementation of WebDAV MOVE and COPY.
1165
+
1166
+ The two verbs differ only in the HTTP method and log wording — path
1167
+ normalisation, header construction, the destination precondition and the
1168
+ conflict mapping are identical, so they live here rather than being
1169
+ maintained (and drifting) in two places.
1170
+ """
1171
+ await self._ensure_principal_id()
1172
+ source_webdav_path = self._webdav_path(source_path)
1173
+ destination_webdav_path = self._webdav_path(destination_path)
1174
+
1175
+ # Ensure paths have consistent trailing slashes for directories
1176
+ if source_path.endswith("/") and not destination_path.endswith("/"):
1177
+ destination_webdav_path += "/"
1178
+ elif not source_path.endswith("/") and destination_path.endswith("/"):
1179
+ source_webdav_path += "/"
1180
+
1181
+ logger.debug(
1182
+ "%s resource from '%s' to '%s'", method, source_path, destination_path
1183
+ )
1184
+
1185
+ _validate_destination_precondition(if_destination_match, overwrite)
1186
+
1187
+ headers = {
1188
+ "Destination": destination_webdav_path,
1189
+ "Overwrite": "T" if overwrite else "F",
1190
+ }
1191
+ if if_destination_match is not None:
1192
+ headers.update(
1193
+ _destination_precondition_header(
1194
+ destination_webdav_path, if_destination_match
1195
+ )
1196
+ )
1197
+
1198
+ try:
1199
+ response = await self._make_request(
1200
+ method, source_webdav_path, headers=headers
1201
+ )
1202
+ response.raise_for_status()
1203
+ logger.debug(
1204
+ "%s succeeded from '%s' to '%s'", method, source_path, destination_path
1205
+ )
1206
+ return {"status_code": response.status_code}
1207
+
1208
+ except HTTPStatusError as e:
1209
+ conflict = self._transfer_conflict_result(
1210
+ e.response.status_code, if_destination_match
1211
+ )
1212
+ if conflict is not None:
1213
+ logger.debug(
1214
+ "%s conflict (%s) from '%s' to '%s'",
1215
+ method,
1216
+ e.response.status_code,
1217
+ source_path,
1218
+ destination_path,
1219
+ )
1220
+ return conflict
1221
+ logger.error(
1222
+ "HTTP error on %s from '%s' to '%s': %s",
1223
+ method,
1224
+ source_path,
1225
+ destination_path,
1226
+ e,
1227
+ )
1228
+ raise e
1229
+ except Exception as e:
1230
+ logger.error(
1231
+ "Unexpected error on %s from '%s' to '%s': %s",
1232
+ method,
1233
+ source_path,
1234
+ destination_path,
1235
+ e,
1236
+ )
1237
+ raise e
1238
+
1239
+ async def move_resource(
1240
+ self,
1241
+ source_path: str,
1242
+ destination_path: str,
1243
+ overwrite: bool = False,
1244
+ *,
1245
+ if_destination_match: Optional[str] = None,
1246
+ ) -> Dict[str, Any]:
1247
+ """Move or rename a resource (file or directory) via WebDAV MOVE.
1248
+
1249
+ Args:
1250
+ source_path: The path of the file or directory to move
1251
+ destination_path: The new path for the file or directory
1252
+ overwrite: Whether to overwrite the destination if it exists
1253
+ if_destination_match: Optional ETag of the destination. When given,
1254
+ the move replaces the destination only if it is still that exact
1255
+ version, closing the window where ``overwrite=True`` clobbers a
1256
+ file someone else changed in the meantime.
1257
+
1258
+ Requires ``overwrite=True`` (the two are contradictory otherwise)
1259
+ and does not accept ``"*"``; both raise ``ValueError``.
1260
+
1261
+ Two limitations, both from sabre/dav and neither hideable: the
1262
+ etag condition is evaluated only for files
1263
+ (``$node instanceof IFile``), so a **directory** destination
1264
+ always fails it with 412; and an ``If:`` condition naming a URI
1265
+ that does not exist yields **404, not 412**.
1266
+
1267
+ Returns:
1268
+ Dict with status_code and optional message
1269
+ """
1270
+ return await self._transfer_resource(
1271
+ "MOVE",
1272
+ source_path,
1273
+ destination_path,
1274
+ overwrite,
1275
+ if_destination_match=if_destination_match,
1276
+ )
1277
+
1278
+ async def copy_resource(
1279
+ self,
1280
+ source_path: str,
1281
+ destination_path: str,
1282
+ overwrite: bool = False,
1283
+ *,
1284
+ if_destination_match: Optional[str] = None,
1285
+ ) -> Dict[str, Any]:
1286
+ """Copy a resource (file or directory) via WebDAV COPY.
1287
+
1288
+ Args:
1289
+ source_path: The path of the file or directory to copy
1290
+ destination_path: The destination path for the copy
1291
+ overwrite: Whether to overwrite the destination if it exists
1292
+ if_destination_match: Optional ETag of the destination. When given,
1293
+ the copy replaces the destination only if it is still that exact
1294
+ version, closing the window where ``overwrite=True`` clobbers a
1295
+ file someone else changed in the meantime.
1296
+
1297
+ Requires ``overwrite=True`` (the two are contradictory otherwise)
1298
+ and does not accept ``"*"``; both raise ``ValueError``.
1299
+
1300
+ Two limitations, both from sabre/dav and neither hideable: the
1301
+ etag condition is evaluated only for files
1302
+ (``$node instanceof IFile``), so a **directory** destination
1303
+ always fails it with 412; and an ``If:`` condition naming a URI
1304
+ that does not exist yields **404, not 412**.
1305
+
1306
+ Returns:
1307
+ Dict with status_code and optional message
1308
+ """
1309
+ return await self._transfer_resource(
1310
+ "COPY",
1311
+ source_path,
1312
+ destination_path,
1313
+ overwrite,
1314
+ if_destination_match=if_destination_match,
1315
+ )
1316
+
1317
+ async def search_files(
1318
+ self,
1319
+ scope: str = "",
1320
+ where_conditions: Optional[str] = None,
1321
+ properties: Optional[List[str]] = None,
1322
+ order_by: Optional[List[Tuple[str, str]]] = None,
1323
+ limit: Optional[int] = None,
1324
+ offset: Optional[int] = None,
1325
+ ) -> List[Dict[str, Any]]:
1326
+ """Search for files using WebDAV SEARCH method (RFC 5323).
1327
+
1328
+ Args:
1329
+ scope: Directory path to search in (empty string for user root)
1330
+ where_conditions: XML string for where clause conditions
1331
+ properties: List of property names to retrieve (defaults to basic set)
1332
+ order_by: List of (property, direction) tuples for sorting, e.g. [("getlastmodified", "descending")]
1333
+ limit: Maximum number of results to return
1334
+ offset: Number of leading results to skip (``<sd:firstresult>``). Note
1335
+ that not every Nextcloud release honours offset paging; callers
1336
+ that need guaranteed completeness should use ``search_files_all``,
1337
+ which detects an ignored offset and falls back.
1338
+
1339
+ Returns:
1340
+ List of file/directory dictionaries with requested properties
1341
+ """
1342
+ await self._ensure_principal_id()
1343
+ # Default properties if not specified
1344
+ if properties is None:
1345
+ properties = [
1346
+ "displayname",
1347
+ "getcontentlength",
1348
+ "getcontenttype",
1349
+ "getlastmodified",
1350
+ "resourcetype",
1351
+ "getetag",
1352
+ ]
1353
+
1354
+ # Build the SEARCH request XML
1355
+ search_body = self._build_search_xml(
1356
+ scope=scope,
1357
+ where_conditions=where_conditions,
1358
+ properties=properties,
1359
+ order_by=order_by,
1360
+ limit=limit,
1361
+ offset=offset,
1362
+ )
1363
+
1364
+ # The SEARCH endpoint is at the dav root
1365
+ search_path = "/remote.php/dav/"
1366
+
1367
+ headers = {"Content-Type": _XML_CONTENT_TYPE}
1368
+
1369
+ logger.debug("Searching files in scope: %s", scope)
1370
+
1371
+ try:
1372
+ response = await self._make_request(
1373
+ "SEARCH", search_path, content=search_body, headers=headers
1374
+ )
1375
+ response.raise_for_status()
1376
+
1377
+ # Parse the XML response
1378
+ results = self._parse_search_response(response.content, scope)
1379
+
1380
+ logger.debug("Search returned %s results", len(results))
1381
+ return results
1382
+
1383
+ except HTTPStatusError as e:
1384
+ # Surface the server's actual reason: Nextcloud/Sabre returns an XML
1385
+ # error body (e.g. "<s:message>...</s:message>") that pinpoints the
1386
+ # cause — far more actionable than the generic httpx2
1387
+ # "Client error '400 Bad Request' for url '.../dav/'" string. A 400
1388
+ # here almost always means a malformed SEARCH body (commonly an
1389
+ # un-escaped character in the scope path).
1390
+ detail = (e.response.text or "").strip().replace("\n", " ")
1391
+ logger.error(
1392
+ "WebDAV SEARCH failed: HTTP %s for scope %r — %s",
1393
+ e.response.status_code,
1394
+ scope or "<user root>",
1395
+ detail[:500] or "(empty response body)",
1396
+ )
1397
+ raise e
1398
+ except Exception as e:
1399
+ logger.error(
1400
+ "Unexpected error during WebDAV SEARCH (scope %r): %s", scope, e
1401
+ )
1402
+ raise e
1403
+
1404
+ async def search_files_all(
1405
+ self,
1406
+ scope: str = "",
1407
+ where_conditions: Optional[str] = None,
1408
+ properties: Optional[List[str]] = None,
1409
+ order_by: Optional[List[Tuple[str, str]]] = None,
1410
+ page_size: int = WEBDAV_SEARCH_PAGE_SIZE,
1411
+ max_results: int = WEBDAV_SEARCH_MAX_RESULTS,
1412
+ ) -> List[Dict[str, Any]]:
1413
+ """Fetch the *complete* SEARCH result set, paging past the server default.
1414
+
1415
+ A plain ``search_files`` with no ``limit`` returns only Nextcloud's default
1416
+ page (~100), silently dropping the rest of a large folder. This method pages
1417
+ with ``<sd:firstresult>`` until a short page signals the end. If the server
1418
+ ignores the offset (a page repeats results already seen), it falls back to a
1419
+ single fetch with an explicit large ``nresults`` so completeness never depends
1420
+ on offset support.
1421
+
1422
+ Args:
1423
+ scope: Directory path to search in (empty string for user root)
1424
+ where_conditions: XML where-clause conditions
1425
+ properties: Properties to retrieve (must include ``fileid`` for dedup)
1426
+ order_by: Optional sort order
1427
+ page_size: Results requested per page
1428
+ max_results: Hard ceiling; crossing it logs a truncation warning and
1429
+ increments ``webdav_search_truncated_total``
1430
+
1431
+ Returns:
1432
+ All matching file/directory dicts, de-duplicated by file id / path.
1433
+ """
1434
+ paged = await self._search_offset_paged(
1435
+ scope, where_conditions, properties, order_by, page_size, max_results
1436
+ )
1437
+ # ``None`` signals the server ignored the offset (or an offset page
1438
+ # failed) -- fetch everything in one bounded request instead.
1439
+ if paged is None:
1440
+ return await self._single_fetch_fallback(
1441
+ scope, where_conditions, properties, order_by, max_results
1442
+ )
1443
+ self._warn_if_truncated(len(paged), scope, max_results)
1444
+ return paged[:max_results]
1445
+
1446
+ async def _search_offset_paged(
1447
+ self,
1448
+ scope: str,
1449
+ where_conditions: Optional[str],
1450
+ properties: Optional[List[str]],
1451
+ order_by: Optional[List[Tuple[str, str]]],
1452
+ page_size: int,
1453
+ max_results: int,
1454
+ ) -> Optional[List[Dict[str, Any]]]:
1455
+ """Page the SEARCH with ``<sd:firstresult>`` until exhausted.
1456
+
1457
+ Returns the accumulated rows, or ``None`` when the server ignores the
1458
+ offset (a page repeats already-seen rows, or an offset page errors) and
1459
+ the caller should fall back to a single bounded fetch.
1460
+ """
1461
+
1462
+ def _key(item: Dict[str, Any]) -> Any:
1463
+ # file_id is globally unique; path is the stable fallback when a
1464
+ # producer omits fileid. ``id(item)`` is a last resort so an item
1465
+ # missing both never collapses into another under a shared ``None``
1466
+ # key (which would silently drop rows from the result set).
1467
+ # ``is not None`` rather than truthiness so a (hypothetical)
1468
+ # file_id of 0 isn't treated as absent.
1469
+ file_id = item.get("file_id")
1470
+ if file_id is not None:
1471
+ return file_id
1472
+ return item.get("path") or id(item)
1473
+
1474
+ results: List[Dict[str, Any]] = []
1475
+ seen: set[Any] = set()
1476
+ offset = 0
1477
+
1478
+ while len(results) < max_results:
1479
+ try:
1480
+ page = await self.search_files(
1481
+ scope=scope,
1482
+ where_conditions=where_conditions,
1483
+ properties=properties,
1484
+ order_by=order_by,
1485
+ limit=page_size,
1486
+ offset=offset,
1487
+ )
1488
+ except Exception:
1489
+ # A failure on the very first page is a real error, not a
1490
+ # paging quirk -- surface it. A later page failing means offset
1491
+ # paging is unusable; signal a fallback rather than lose the tail.
1492
+ if offset == 0:
1493
+ raise
1494
+ logger.warning(
1495
+ "WebDAV SEARCH offset page failed for scope %r; "
1496
+ "falling back to single fetch",
1497
+ scope,
1498
+ exc_info=True,
1499
+ )
1500
+ return None
1501
+
1502
+ if not page:
1503
+ break
1504
+
1505
+ fresh = [item for item in page if _key(item) not in seen]
1506
+
1507
+ # Server ignored the offset (returned an already-seen page); signal
1508
+ # the caller to re-fetch in one bounded request. The accumulated
1509
+ # ``results`` are intentionally discarded -- the single fetch is
1510
+ # authoritative and re-returns them, so nothing is lost.
1511
+ if offset > 0 and not fresh:
1512
+ logger.warning(
1513
+ "WebDAV SEARCH ignored offset for scope %r; "
1514
+ "falling back to single fetch (limit=%d)",
1515
+ scope,
1516
+ max_results,
1517
+ )
1518
+ return None
1519
+
1520
+ for item in fresh:
1521
+ seen.add(_key(item))
1522
+ results.append(item)
1523
+
1524
+ # A short page means we've reached the end of the result set.
1525
+ if len(page) < page_size:
1526
+ break
1527
+
1528
+ offset += page_size
1529
+
1530
+ return results
1531
+
1532
+ async def _single_fetch_fallback(
1533
+ self,
1534
+ scope: str,
1535
+ where_conditions: Optional[str],
1536
+ properties: Optional[List[str]],
1537
+ order_by: Optional[List[Tuple[str, str]]],
1538
+ max_results: int,
1539
+ ) -> List[Dict[str, Any]]:
1540
+ """Single SEARCH with a large explicit ``nresults`` (offset-free fallback)."""
1541
+ results = await self.search_files(
1542
+ scope=scope,
1543
+ where_conditions=where_conditions,
1544
+ properties=properties,
1545
+ order_by=order_by,
1546
+ limit=max_results,
1547
+ )
1548
+ self._warn_if_truncated(len(results), scope, max_results)
1549
+ return results
1550
+
1551
+ @staticmethod
1552
+ def _warn_if_truncated(count: int, scope: str, max_results: int) -> None:
1553
+ """Warn + count when a SEARCH hit the ceiling, so a cap is never silent."""
1554
+ if count >= max_results:
1555
+ instrumentation.hooks.on_scan_truncated()
1556
+ logger.warning(
1557
+ "WebDAV SEARCH reached max_results=%d for scope %r; "
1558
+ "results may be truncated -- raise WEBDAV_SEARCH_MAX_RESULTS",
1559
+ max_results,
1560
+ scope,
1561
+ )
1562
+
1563
+ def _build_search_xml(
1564
+ self,
1565
+ scope: str,
1566
+ where_conditions: Optional[str],
1567
+ properties: List[str],
1568
+ order_by: Optional[List[Tuple[str, str]]],
1569
+ limit: Optional[int],
1570
+ offset: Optional[int] = None,
1571
+ ) -> str:
1572
+ """Build the XML body for a SEARCH request."""
1573
+ # Construct the scope path
1574
+ principal = self._principal_or_username()
1575
+ scope_path = f"/files/{principal}"
1576
+ if scope:
1577
+ scope_path = f"{scope_path}/{scope.lstrip('/')}"
1578
+ # XML-escape before embedding in <d:href>: a folder whose name contains
1579
+ # '&', '<' or '>' (e.g. "Reports & Plans") otherwise produces a malformed
1580
+ # SEARCH body that Nextcloud's Sabre/DAV parser rejects with 400 Bad
1581
+ # Request — silently skipping that folder and all of its descendants
1582
+ # during the tag-based indexing walk. Escaping keeps the path literal
1583
+ # (Sabre unescapes it back), matching how folders without special
1584
+ # characters already resolve.
1585
+ scope_href = xml_escape(scope_path)
1586
+
1587
+ # Build property list
1588
+ prop_xml = "\n".join([self._property_to_xml(prop) for prop in properties])
1589
+
1590
+ # Build where clause. An *empty* ``<d:where>`` is not a match-all:
1591
+ # Nextcloud answers it with ``500`` and a Sabre ``TypeError`` document
1592
+ # (verified against 32.0.14). So an unfiltered search -- "everything
1593
+ # under this folder", the most obvious call an MCP client can make --
1594
+ # needs an explicit predicate that holds for every row instead.
1595
+ # ``displayname LIKE '%'`` is that predicate, and reuses the operator
1596
+ # the filtered callers already build.
1597
+ where_xml = (where_conditions or "").strip() or (
1598
+ "<d:like><d:prop><d:displayname/></d:prop><d:literal>%</d:literal></d:like>"
1599
+ )
1600
+
1601
+ # Build order by clause
1602
+ orderby_xml = ""
1603
+ if order_by:
1604
+ order_elements = []
1605
+ for prop, direction in order_by:
1606
+ prop_element = self._property_to_xml(prop)
1607
+ dir_element = (
1608
+ "<d:ascending/>"
1609
+ if direction.lower() == "ascending"
1610
+ else "<d:descending/>"
1611
+ )
1612
+ order_elements.append(f"<d:order>{prop_element}{dir_element}</d:order>")
1613
+ orderby_xml = "\n".join(order_elements)
1614
+ else:
1615
+ orderby_xml = ""
1616
+
1617
+ # Build limit clause. ``<d:nresults>`` caps the page size; ``<sd:firstresult>``
1618
+ # is the paging offset, in the searchdav namespace (see ``SEARCHDAV_NS``).
1619
+ # A server that still ignores it returns the first page again rather than
1620
+ # erroring -- ``search_files_all`` detects that non-progress and falls back
1621
+ # to a single bounded fetch.
1622
+ limit_parts = []
1623
+ if limit:
1624
+ limit_parts.append(f"<d:nresults>{limit}</d:nresults>")
1625
+ # ``is not None`` (not truthiness) so a future explicit offset=0 is
1626
+ # emitted rather than silently dropped.
1627
+ if offset is not None:
1628
+ limit_parts.append(f"<sd:firstresult>{offset}</sd:firstresult>")
1629
+ limit_xml = f"<d:limit>{''.join(limit_parts)}</d:limit>" if limit_parts else ""
1630
+
1631
+ # Construct the full SEARCH XML
1632
+ search_xml = f"""<?xml version="1.0" encoding="UTF-8"?>
1633
+ <d:searchrequest xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns" xmlns:sd="{SEARCHDAV_NS}">
1634
+ <d:basicsearch>
1635
+ <d:select>
1636
+ <d:prop>
1637
+ {prop_xml}
1638
+ </d:prop>
1639
+ </d:select>
1640
+ <d:from>
1641
+ <d:scope>
1642
+ <d:href>{scope_href}</d:href>
1643
+ <d:depth>infinity</d:depth>
1644
+ </d:scope>
1645
+ </d:from>
1646
+ <d:where>
1647
+ {where_xml}
1648
+ </d:where>
1649
+ <d:orderby>
1650
+ {orderby_xml}
1651
+ </d:orderby>
1652
+ {limit_xml}
1653
+ </d:basicsearch>
1654
+ </d:searchrequest>"""
1655
+
1656
+ return search_xml
1657
+
1658
+ def _property_to_xml(self, prop: str) -> str:
1659
+ """Convert a property name to its XML element."""
1660
+ # Handle properties with namespace prefixes
1661
+ if prop.startswith("{"):
1662
+ # Already a full namespace
1663
+ namespace_end = prop.index("}")
1664
+ namespace = prop[1:namespace_end]
1665
+ local_name = prop[namespace_end + 1 :]
1666
+
1667
+ # Map namespace URIs to prefixes
1668
+ ns_map = {
1669
+ "DAV:": "d",
1670
+ "http://owncloud.org/ns": "oc",
1671
+ "http://nextcloud.org/ns": "nc",
1672
+ }
1673
+
1674
+ prefix = ns_map.get(namespace, "d")
1675
+ return f"<{prefix}:{local_name}/>"
1676
+ else:
1677
+ # Guess namespace based on common properties
1678
+ if prop in [
1679
+ "displayname",
1680
+ "getcontentlength",
1681
+ "getcontenttype",
1682
+ "getlastmodified",
1683
+ "resourcetype",
1684
+ "getetag",
1685
+ "quota-available-bytes",
1686
+ "quota-used-bytes",
1687
+ ]:
1688
+ return f"<d:{prop}/>"
1689
+ elif prop in [
1690
+ "fileid",
1691
+ "size",
1692
+ "permissions",
1693
+ "favorite",
1694
+ "tags",
1695
+ "owner-id",
1696
+ "owner-display-name",
1697
+ "share-types",
1698
+ "checksums",
1699
+ "comments-count",
1700
+ "comments-unread",
1701
+ ]:
1702
+ return f"<oc:{prop}/>"
1703
+ else:
1704
+ # Assume nc namespace for newer properties
1705
+ return f"<nc:{prop}/>"
1706
+
1707
+ def _parse_search_response(
1708
+ self, xml_content: bytes, scope: str
1709
+ ) -> List[Dict[str, Any]]:
1710
+ """Parse the XML response from a SEARCH request."""
1711
+ root = ET.fromstring(xml_content)
1712
+ items = []
1713
+
1714
+ # Process each response element
1715
+ responses = root.findall(".//{DAV:}response")
1716
+
1717
+ for response_elem in responses:
1718
+ href = response_elem.find(".//{DAV:}href")
1719
+ if href is None:
1720
+ continue
1721
+
1722
+ # Extract file/directory path from href. <d:href> is required by
1723
+ # RFC 3986 to be percent-encoded, so non-ASCII paths arrive
1724
+ # encoded — decode before exposing to callers (issue #776).
1725
+ href_text = unquote(href.text or "")
1726
+ # Remove the /remote.php/dav/files/<principal>/ prefix to get relative path.
1727
+ path_parts = href_text.split("/files/")
1728
+ if len(path_parts) > 1:
1729
+ # Get the path after the principal segment.
1730
+ path_after_user = "/".join(path_parts[1].split("/")[1:])
1731
+ relative_path = path_after_user.rstrip("/")
1732
+ else:
1733
+ relative_path = href_text.rstrip("/").split("/")[-1]
1734
+
1735
+ # Get properties
1736
+ propstat = response_elem.find(".//{DAV:}propstat")
1737
+ if propstat is None:
1738
+ continue
1739
+
1740
+ prop = propstat.find(".//{DAV:}prop")
1741
+ if prop is None:
1742
+ continue
1743
+
1744
+ # Build item dictionary
1745
+ item = {"path": relative_path, "href": href_text}
1746
+
1747
+ # Extract all properties
1748
+ for child in prop:
1749
+ tag = child.tag
1750
+ value = child.text
1751
+
1752
+ # Remove namespace from tag
1753
+ if "}" in tag:
1754
+ tag = tag.split("}", 1)[1]
1755
+
1756
+ # Handle special properties
1757
+ if tag == "resourcetype":
1758
+ item["is_directory"] = child.find(".//{DAV:}collection") is not None
1759
+ elif tag == "getcontentlength":
1760
+ item["size"] = int(value) if value else 0
1761
+ elif tag == "displayname":
1762
+ item["name"] = value
1763
+ elif tag == "getcontenttype":
1764
+ item["content_type"] = value
1765
+ elif tag == "getlastmodified":
1766
+ item["last_modified"] = value
1767
+ elif tag == "getetag":
1768
+ item["etag"] = normalize_etag(value) if value else None
1769
+ elif tag == "fileid":
1770
+ item["file_id"] = int(value) if value else None
1771
+ elif tag == "favorite":
1772
+ item["is_favorite"] = value == "1"
1773
+ elif tag == "tags":
1774
+ # Tags can be comma-separated or have multiple child elements
1775
+ if value:
1776
+ # Handle comma-separated tags
1777
+ item["tags"] = [
1778
+ t.strip() for t in value.split(",") if t.strip()
1779
+ ]
1780
+ else:
1781
+ # Check for child tag elements (alternative format)
1782
+ tag_elements = child.findall(".//{http://owncloud.org/ns}tag")
1783
+ if tag_elements:
1784
+ item["tags"] = [t.text for t in tag_elements if t.text]
1785
+ else:
1786
+ item["tags"] = []
1787
+ elif tag == "permissions":
1788
+ item["permissions"] = value
1789
+ elif tag == "size":
1790
+ # oc:size includes folder sizes
1791
+ item["total_size"] = int(value) if value else 0
1792
+ else:
1793
+ # Store other properties as-is
1794
+ item[tag] = value
1795
+
1796
+ items.append(item)
1797
+
1798
+ return items
1799
+
1800
+ async def find_by_name(
1801
+ self, pattern: str, scope: str = "", limit: Optional[int] = None
1802
+ ) -> List[Dict[str, Any]]:
1803
+ """Find files by name pattern using LIKE matching.
1804
+
1805
+ Args:
1806
+ pattern: Name pattern to search for (supports % wildcard)
1807
+ scope: Directory path to search in (empty string for user root)
1808
+ limit: Maximum number of results to return
1809
+
1810
+ Returns:
1811
+ List of matching files/directories
1812
+
1813
+ Examples:
1814
+ # Find all .txt files
1815
+ results = await find_by_name("%.txt")
1816
+
1817
+ # Find files starting with "report"
1818
+ results = await find_by_name("report%")
1819
+ """
1820
+ where_conditions = like_predicate("d:displayname", pattern)
1821
+
1822
+ return await self.search_files(
1823
+ scope=scope, where_conditions=where_conditions, limit=limit
1824
+ )
1825
+
1826
+ async def find_by_type(
1827
+ self, mime_type: str, scope: str = "", limit: Optional[int] = None
1828
+ ) -> List[Dict[str, Any]]:
1829
+ """Find files by MIME type.
1830
+
1831
+ Args:
1832
+ mime_type: MIME type to search for (supports % wildcard, e.g., "image/%")
1833
+ scope: Directory path to search in (empty string for user root)
1834
+ limit: Maximum number of results to return
1835
+
1836
+ Returns:
1837
+ List of matching files
1838
+
1839
+ Examples:
1840
+ # Find all images
1841
+ results = await find_by_type("image/%")
1842
+
1843
+ # Find all PDFs
1844
+ results = await find_by_type("application/pdf")
1845
+
1846
+ Note:
1847
+ With ``limit=None`` this returns only Nextcloud's default SEARCH page
1848
+ (~100 results), so it truncates large folders. Use ``find_all_by_type``
1849
+ when complete coverage matters (e.g. building an indexing work-list).
1850
+ """
1851
+ where_conditions, properties = self._type_search_args(mime_type)
1852
+ return await self.search_files(
1853
+ scope=scope,
1854
+ where_conditions=where_conditions,
1855
+ properties=properties,
1856
+ limit=limit,
1857
+ )
1858
+
1859
+ async def find_all_by_type(
1860
+ self, mime_type: str, scope: str = ""
1861
+ ) -> List[Dict[str, Any]]:
1862
+ """Find *all* files of a MIME type, paging past the SEARCH default page.
1863
+
1864
+ Unlike ``find_by_type`` (single default-capped page), this pages the SEARCH
1865
+ to completion so a large tagged folder is fully discovered. Used by the
1866
+ vector-sync scanner's tagged-folder expansion, where a missed file means a
1867
+ document that is never indexed.
1868
+
1869
+ Args:
1870
+ mime_type: MIME type to search for (supports % wildcard)
1871
+ scope: Directory path to search in (empty string for user root)
1872
+
1873
+ Returns:
1874
+ All matching files (bounded by ``WEBDAV_SEARCH_MAX_RESULTS``).
1875
+ """
1876
+ where_conditions, properties = self._type_search_args(mime_type)
1877
+ return await self.search_files_all(
1878
+ scope=scope,
1879
+ where_conditions=where_conditions,
1880
+ properties=properties,
1881
+ )
1882
+
1883
+ @staticmethod
1884
+ def _type_search_args(mime_type: str) -> Tuple[str, List[str]]:
1885
+ """Build the where-clause + property list for a MIME-type SEARCH."""
1886
+ # Escape so a caller-supplied MIME type can't break the SEARCH XML or
1887
+ # inject elements. All current callers pass literal strings, but this
1888
+ # keeps the boundary safe for any future user-supplied value.
1889
+ where_conditions = like_predicate("d:getcontenttype", mime_type)
1890
+
1891
+ # fileid is required by callers like NextcloudClient.find_files_by_tag
1892
+ # that dedupe results by id; the default property set in search_files
1893
+ # omits it.
1894
+ properties = [
1895
+ "displayname",
1896
+ "getcontentlength",
1897
+ "getcontenttype",
1898
+ "getlastmodified",
1899
+ "resourcetype",
1900
+ "getetag",
1901
+ "fileid",
1902
+ ]
1903
+ return where_conditions, properties
1904
+
1905
+ async def list_favorites(
1906
+ self, scope: str = "", limit: Optional[int] = None
1907
+ ) -> List[Dict[str, Any]]:
1908
+ """List all favorite files.
1909
+
1910
+ Args:
1911
+ scope: Directory path to search in (empty string for user root)
1912
+ limit: Maximum number of results to return
1913
+
1914
+ Returns:
1915
+ List of favorite files/directories
1916
+
1917
+ Examples:
1918
+ # List all favorites
1919
+ results = await list_favorites()
1920
+
1921
+ # List favorites in a specific folder
1922
+ results = await list_favorites(scope="Documents")
1923
+ """
1924
+ # Use REPORT method for favorites as it's more efficient
1925
+ # But we can also use SEARCH as fallback
1926
+ where_conditions = """
1927
+ <d:eq>
1928
+ <d:prop>
1929
+ <oc:favorite/>
1930
+ </d:prop>
1931
+ <d:literal>1</d:literal>
1932
+ </d:eq>
1933
+ """
1934
+
1935
+ # Request favorite property
1936
+ properties = [
1937
+ "displayname",
1938
+ "getcontentlength",
1939
+ "getcontenttype",
1940
+ "getlastmodified",
1941
+ "resourcetype",
1942
+ "getetag",
1943
+ "fileid",
1944
+ "favorite",
1945
+ ]
1946
+
1947
+ return await self.search_files(
1948
+ scope=scope,
1949
+ where_conditions=where_conditions,
1950
+ properties=properties,
1951
+ limit=limit,
1952
+ )
1953
+
1954
+ async def find_by_tag(
1955
+ self, tag_name: str, scope: str = "", limit: Optional[int] = None
1956
+ ) -> List[Dict[str, Any]]:
1957
+ """Find files by tag name.
1958
+
1959
+ DEPRECATED: Use NextcloudClient.find_files_by_tag() instead, which uses
1960
+ the proper OCS Tags API rather than WebDAV SEARCH.
1961
+
1962
+ Args:
1963
+ tag_name: Tag to filter by (e.g., "vector-index")
1964
+ scope: Directory path to search in (empty string for user root)
1965
+ limit: Maximum number of results to return
1966
+
1967
+ Returns:
1968
+ List of files/directories with the specified tag
1969
+
1970
+ Examples:
1971
+ # Find all files tagged with "vector-index"
1972
+ results = await find_by_tag("vector-index")
1973
+
1974
+ # Find tagged files in a specific folder
1975
+ results = await find_by_tag("vector-index", scope="Documents")
1976
+ """
1977
+ # Use LIKE for tag matching since tags can be comma-separated
1978
+ where_conditions = like_predicate("oc:tags", f"%{tag_name}%")
1979
+
1980
+ # Request tag property along with standard properties
1981
+ properties = [
1982
+ "displayname",
1983
+ "getcontentlength",
1984
+ "getcontenttype",
1985
+ "getlastmodified",
1986
+ "resourcetype",
1987
+ "getetag",
1988
+ "fileid",
1989
+ "tags",
1990
+ ]
1991
+
1992
+ return await self.search_files(
1993
+ scope=scope,
1994
+ where_conditions=where_conditions,
1995
+ properties=properties,
1996
+ limit=limit,
1997
+ )
1998
+
1999
+ async def file_accessible_by_id(self, file_id: int) -> bool:
2000
+ """ACL-aware access check for a file by its global Nextcloud file ID.
2001
+
2002
+ Used by verify-on-read (ADR-019). Searches the authenticated user's
2003
+ whole files tree — which *includes mounted shares* — via WebDAV SEARCH
2004
+ (RFC 5323) filtered on ``oc:fileid``, returning True iff the user can
2005
+ currently access the file.
2006
+
2007
+ This is the only check that resolves shared files correctly:
2008
+
2009
+ - :meth:`get_file_info` resolves a path under the caller's *own* root,
2010
+ so it 404s on a file shared into the caller's account (Nextcloud
2011
+ mounts received shares at the recipient's root by basename, a
2012
+ different path than the owner indexed).
2013
+ - The ``/remote.php/dav/meta/{id}/`` endpoint resolves only the user's
2014
+ *own* storage, so it 404s on shared files too.
2015
+
2016
+ SEARCH-by-fileid handles all cases: owned files, directly-shared files,
2017
+ and files reachable via a shared parent folder (verified empirically).
2018
+
2019
+ Args:
2020
+ file_id: Nextcloud internal (global) file ID.
2021
+
2022
+ Returns:
2023
+ True if the user can access the file, False if it is not present
2024
+ in their tree (not owned and not shared with them).
2025
+
2026
+ Raises:
2027
+ HTTPStatusError: On transport/server errors — callers treat these
2028
+ as transient (keep the result), not as a definitive denial.
2029
+ """
2030
+ where = (
2031
+ "<d:eq><d:prop><oc:fileid/></d:prop>"
2032
+ f"<d:literal>{int(file_id)}</d:literal></d:eq>"
2033
+ )
2034
+ results = await self.search_files(
2035
+ scope="", # user's whole files tree, incl. mounted shares
2036
+ where_conditions=where,
2037
+ properties=["fileid"],
2038
+ limit=1,
2039
+ )
2040
+ return len(results) > 0
2041
+
2042
+ async def find_files_by_ids(self, file_ids: list[int]) -> list[dict[str, Any]]:
2043
+ """The files among ``file_ids`` the user can currently reach.
2044
+
2045
+ Batched form of :meth:`file_accessible_by_id`: one SEARCH over the
2046
+ user's whole files tree (incl. mounted shares) per ``FILE_ID_BATCH``
2047
+ ids, OR-ing an ``oc:fileid`` match per id. Each row carries ``file_id``,
2048
+ the user-relative ``path`` and ``content_type``; an id absent from the
2049
+ result is not in the user's tree. Raises on transport/server errors,
2050
+ like ``file_accessible_by_id``.
2051
+ """
2052
+ found: list[dict[str, Any]] = []
2053
+ for start in range(0, len(file_ids), FILE_ID_BATCH):
2054
+ batch = file_ids[start : start + FILE_ID_BATCH]
2055
+ matches = "".join(
2056
+ "<d:eq><d:prop><oc:fileid/></d:prop>"
2057
+ f"<d:literal>{int(file_id)}</d:literal></d:eq>"
2058
+ for file_id in batch
2059
+ )
2060
+ # Headroom over len(batch): a file mounted at two paths (shared to
2061
+ # the user twice) returns one row per path.
2062
+ limit = 2 * len(batch)
2063
+ page = await self.search_files(
2064
+ scope="",
2065
+ where_conditions=matches
2066
+ if len(batch) == 1
2067
+ else f"<d:or>{matches}</d:or>",
2068
+ properties=["fileid", "getcontenttype"],
2069
+ limit=limit,
2070
+ )
2071
+ if len(page) >= limit:
2072
+ # A full page may be truncated, and a missing row reads as
2073
+ # "inaccessible", which evicts a live file. Raise instead so
2074
+ # the caller fails open.
2075
+ raise RuntimeError(
2076
+ f"SEARCH-by-fileid returned a full page ({limit} rows) "
2077
+ f"for {len(batch)} ids; result may be truncated"
2078
+ )
2079
+ found += page
2080
+ return found
2081
+
2082
+ async def get_fileid(self, path: str) -> str | None:
2083
+ """Return the Nextcloud fileid of a file/folder path, or None if absent.
2084
+
2085
+ A Depth-0 ``PROPFIND`` for ``oc:fileid`` on the principal-scoped path.
2086
+ Used by the folder-ancestor resolver (ADR-033 Phase 3) to map an ancestor
2087
+ folder path to its canonical fileid — stable across every user who mounts
2088
+ a shared folder, which is what makes the folder-scope search filter
2089
+ user-agnostic. A 404 (path gone/inaccessible) returns None so callers
2090
+ degrade gracefully rather than aborting an index.
2091
+ """
2092
+ await self._ensure_principal_id()
2093
+ webdav_path = self._webdav_path(path)
2094
+ propfind_body = (
2095
+ '<?xml version="1.0"?>'
2096
+ '<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">'
2097
+ "<d:prop><oc:fileid/></d:prop></d:propfind>"
2098
+ )
2099
+ headers = {"Depth": "0", "Content-Type": _XML_CONTENT_TYPE}
2100
+ try:
2101
+ response = await self._make_request(
2102
+ "PROPFIND", webdav_path, content=propfind_body, headers=headers
2103
+ )
2104
+ response.raise_for_status()
2105
+ except HTTPStatusError as e:
2106
+ if e.response.status_code == 404:
2107
+ return None
2108
+ raise
2109
+ root = ET.fromstring(response.content)
2110
+ # Match oc:fileid by local name (namespace-agnostic) rather than a
2111
+ # namespace map, so the owncloud namespace URL is not embedded as a
2112
+ # standalone string literal (it stays only inside the request-body XML).
2113
+ for elem in root.iter():
2114
+ if isinstance(elem.tag, str) and elem.tag.rsplit("}", 1)[-1] == "fileid":
2115
+ text = (elem.text or "").strip()
2116
+ if text:
2117
+ return text
2118
+ return None
2119
+
2120
+ async def list_comments(
2121
+ self, file_id: int, *, limit: int = 20, offset: int = 0
2122
+ ) -> list[dict[str, Any]]:
2123
+ """Return comments on a file, newest first.
2124
+
2125
+ A ``REPORT`` carrying ``oc:filter-comments`` rather than a ``PROPFIND``:
2126
+ the report is the only form that takes ``limit``/``offset``, and a
2127
+ Depth-1 PROPFIND on the collection would return the entire thread.
2128
+
2129
+ Args:
2130
+ file_id: Nextcloud file ID (see :meth:`get_fileid`).
2131
+ limit: Maximum comments to return.
2132
+ offset: How many of the newest comments to skip.
2133
+
2134
+ Returns:
2135
+ One dict per comment, in the shape ``FileComment`` expects.
2136
+ """
2137
+ # The owncloud namespace stays inside the request body, never a
2138
+ # standalone string constant -- same reason as get_fileid, which matches
2139
+ # oc properties by local name rather than naming the URL (see
2140
+ # _dav_props_ok). A bare URL literal also trips Sonar's python:S5332.
2141
+ body = (
2142
+ '<?xml version="1.0" encoding="utf-8"?>'
2143
+ '<oc:filter-comments xmlns:oc="http://owncloud.org/ns">'
2144
+ f"<oc:limit>{int(limit)}</oc:limit>"
2145
+ f"<oc:offset>{int(offset)}</oc:offset>"
2146
+ "</oc:filter-comments>"
2147
+ )
2148
+ response = await self._make_request(
2149
+ "REPORT",
2150
+ f"{_COMMENTS_PATH}/{int(file_id)}",
2151
+ content=body,
2152
+ headers={
2153
+ "Depth": "0",
2154
+ "Content-Type": _XML_CONTENT_TYPE,
2155
+ },
2156
+ )
2157
+
2158
+ root = ET.fromstring(response.content)
2159
+ comments = []
2160
+ for response_elem in root.findall("{DAV:}response"):
2161
+ props = _dav_props_ok(response_elem)
2162
+ if not props:
2163
+ continue
2164
+ comment = _parse_comment_props(props)
2165
+ if comment is not None:
2166
+ comments.append(comment)
2167
+
2168
+ logger.debug("Found %s comment(s) on file %s", len(comments), file_id)
2169
+ return comments
2170
+
2171
+ async def create_comment(self, file_id: int, message: str) -> int | None:
2172
+ """Post a comment on a file and return the new comment's ID.
2173
+
2174
+ Nextcloud answers ``201`` with an **empty body**, naming the new comment
2175
+ only in the ``Content-Location`` header — so the ID is read from there
2176
+ rather than by fetching the comment back.
2177
+
2178
+ Mentions are the server's business: it parses ``@"username"`` out of the
2179
+ message when storing it and sends the notification itself.
2180
+
2181
+ Args:
2182
+ file_id: Nextcloud file ID (see :meth:`get_fileid`).
2183
+ message: Comment text. The caller is expected to have checked it
2184
+ against Nextcloud's 1000-character limit.
2185
+
2186
+ Returns:
2187
+ The new comment's ID, or None if the server named no location.
2188
+ """
2189
+ response = await self._make_request(
2190
+ "POST",
2191
+ f"{_COMMENTS_PATH}/{int(file_id)}",
2192
+ json={"actorType": "users", "verb": "comment", "message": message},
2193
+ )
2194
+
2195
+ location = response.headers.get("Content-Location", "")
2196
+ comment_id = location.rstrip("/").rsplit("/", 1)[-1]
2197
+ try:
2198
+ return int(comment_id)
2199
+ except ValueError:
2200
+ logger.warning(
2201
+ "Comment created on file %s but Content-Location %r carries no id",
2202
+ file_id,
2203
+ location,
2204
+ )
2205
+ return None
2206
+
2207
+ async def _get_file_info_by_id(self, file_id: int) -> Dict[str, Any]:
2208
+ """Get file information by Nextcloud file ID using WebDAV.
2209
+
2210
+ Args:
2211
+ file_id: Nextcloud internal file ID
2212
+
2213
+ Returns:
2214
+ File information dictionary with path, size, content_type, etc.
2215
+
2216
+ Raises:
2217
+ HTTPStatusError: If file not found or request fails
2218
+ """
2219
+ # Nextcloud allows accessing files by ID via special meta endpoint
2220
+ meta_path = f"/remote.php/dav/meta/{file_id}/"
2221
+
2222
+ propfind_body = """<?xml version="1.0"?>
2223
+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
2224
+ <d:prop>
2225
+ <d:displayname/>
2226
+ <d:getcontentlength/>
2227
+ <d:getcontenttype/>
2228
+ <d:getlastmodified/>
2229
+ <d:resourcetype/>
2230
+ <d:getetag/>
2231
+ <oc:fileid/>
2232
+ </d:prop>
2233
+ </d:propfind>"""
2234
+
2235
+ headers = {"Depth": "0", "Content-Type": _XML_CONTENT_TYPE}
2236
+
2237
+ response = await self._make_request(
2238
+ "PROPFIND", meta_path, content=propfind_body, headers=headers
2239
+ )
2240
+ response.raise_for_status()
2241
+
2242
+ # Parse the XML response
2243
+ root = ET.fromstring(response.content)
2244
+ responses = root.findall(".//{DAV:}response")
2245
+
2246
+ if not responses:
2247
+ raise RuntimeError(f"File ID {file_id} not found")
2248
+
2249
+ response_elem = responses[0]
2250
+ href = response_elem.find(".//{DAV:}href")
2251
+ if href is None:
2252
+ raise RuntimeError(f"No href in response for file ID {file_id}")
2253
+
2254
+ propstat = response_elem.find(".//{DAV:}propstat")
2255
+ if propstat is None:
2256
+ raise RuntimeError(f"No propstat for file ID {file_id}")
2257
+
2258
+ prop = propstat.find(".//{DAV:}prop")
2259
+ if prop is None:
2260
+ raise RuntimeError(f"No prop for file ID {file_id}")
2261
+
2262
+ # Extract file path from displayname or construct from file ID
2263
+ displayname_elem = prop.find(".//{DAV:}displayname")
2264
+ name = (
2265
+ displayname_elem.text if displayname_elem is not None else f"file_{file_id}"
2266
+ )
2267
+
2268
+ # Get file properties
2269
+ size_elem = prop.find(".//{DAV:}getcontentlength")
2270
+ size = int(size_elem.text) if size_elem is not None and size_elem.text else 0
2271
+
2272
+ content_type_elem = prop.find(".//{DAV:}getcontenttype")
2273
+ content_type = content_type_elem.text if content_type_elem is not None else None
2274
+
2275
+ modified_elem = prop.find(".//{DAV:}getlastmodified")
2276
+ modified = modified_elem.text if modified_elem is not None else None
2277
+
2278
+ etag_elem = prop.find(".//{DAV:}getetag")
2279
+ etag = (
2280
+ normalize_etag(etag_elem.text)
2281
+ if etag_elem is not None and etag_elem.text
2282
+ else None
2283
+ )
2284
+
2285
+ # Check if it's a directory
2286
+ resourcetype = prop.find(".//{DAV:}resourcetype")
2287
+ is_directory = (
2288
+ resourcetype is not None
2289
+ and resourcetype.find(".//{DAV:}collection") is not None
2290
+ )
2291
+
2292
+ # Try to get actual file path - meta endpoint doesn't give us the real path
2293
+ # so we'll construct a reasonable path from the name
2294
+ # The calling code in NextcloudClient will have the context to determine the actual path
2295
+ file_info = {
2296
+ "name": name,
2297
+ "path": f"/{name}", # Placeholder - caller should use WebDAV to get real path if needed
2298
+ "size": size,
2299
+ "content_type": content_type,
2300
+ "last_modified": modified,
2301
+ "etag": etag,
2302
+ "is_directory": is_directory,
2303
+ "file_id": file_id,
2304
+ }
2305
+
2306
+ logger.debug("Retrieved file info for ID %s: %s", file_id, name)
2307
+ return file_info
2308
+
2309
+ async def get_tag_by_name(self, tag_name: str) -> dict[str, Any] | None:
2310
+ """Get a system tag by its name via WebDAV.
2311
+
2312
+ Args:
2313
+ tag_name: Name of the tag to find (case-sensitive)
2314
+
2315
+ Returns:
2316
+ Tag dictionary if found, None otherwise
2317
+ """
2318
+ # Use WebDAV PROPFIND to list all systemtags
2319
+ propfind_body = """<?xml version="1.0"?>
2320
+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
2321
+ <d:prop>
2322
+ <oc:id/>
2323
+ <oc:display-name/>
2324
+ <oc:user-visible/>
2325
+ <oc:user-assignable/>
2326
+ </d:prop>
2327
+ </d:propfind>"""
2328
+
2329
+ response = await self._make_request(
2330
+ "PROPFIND",
2331
+ "/remote.php/dav/systemtags/",
2332
+ headers={
2333
+ "Depth": "1",
2334
+ "Content-Type": _XML_CONTENT_TYPE,
2335
+ },
2336
+ content=propfind_body,
2337
+ )
2338
+ # Redundant after _make_request (which raises on non-2xx) but
2339
+ # makes the contract explicit at the call site so a future
2340
+ # refactor of _make_request cannot silently feed an error body
2341
+ # into ET.fromstring below.
2342
+ response.raise_for_status()
2343
+
2344
+ # Parse XML response
2345
+ root = ET.fromstring(response.content)
2346
+ ns = {
2347
+ "d": "DAV:",
2348
+ "oc": "http://owncloud.org/ns",
2349
+ }
2350
+
2351
+ for response_elem in root.findall("d:response", ns):
2352
+ href = response_elem.find("d:href", ns)
2353
+ if href is None or href.text == "/remote.php/dav/systemtags/":
2354
+ # Skip the collection itself
2355
+ continue
2356
+
2357
+ propstat = response_elem.find("d:propstat", ns)
2358
+ if propstat is None:
2359
+ continue
2360
+
2361
+ prop = propstat.find("d:prop", ns)
2362
+ if prop is None:
2363
+ continue
2364
+
2365
+ # Extract tag properties
2366
+ tag_id_elem = prop.find("oc:id", ns)
2367
+ display_name_elem = prop.find("oc:display-name", ns)
2368
+ user_visible_elem = prop.find("oc:user-visible", ns)
2369
+ user_assignable_elem = prop.find("oc:user-assignable", ns)
2370
+
2371
+ if display_name_elem is not None and display_name_elem.text == tag_name:
2372
+ tag_info = {
2373
+ "id": int(tag_id_elem.text)
2374
+ if tag_id_elem is not None and tag_id_elem.text is not None
2375
+ else None,
2376
+ "name": display_name_elem.text,
2377
+ "userVisible": user_visible_elem.text.lower() == "true"
2378
+ if user_visible_elem is not None
2379
+ and user_visible_elem.text is not None
2380
+ else True,
2381
+ "userAssignable": user_assignable_elem.text.lower() == "true"
2382
+ if user_assignable_elem is not None
2383
+ and user_assignable_elem.text is not None
2384
+ else True,
2385
+ }
2386
+ logger.debug("Found tag %r with ID %s", tag_name, tag_info["id"])
2387
+ return tag_info
2388
+
2389
+ logger.debug("Tag %r not found", tag_name)
2390
+ return None
2391
+
2392
+ async def get_files_by_tag(self, tag_id: int) -> list[dict[str, Any]]:
2393
+ """Get all files tagged with a specific system tag via WebDAV REPORT.
2394
+
2395
+ Args:
2396
+ tag_id: Numeric ID of the tag
2397
+
2398
+ Returns:
2399
+ List of file info dictionaries with path, size, content_type, etc.
2400
+ """
2401
+ await self._ensure_principal_id()
2402
+ # Use WebDAV REPORT method with systemtag filter. resourcetype is
2403
+ # included so callers can distinguish folders from files (needed for
2404
+ # recursive exclusion of tagged directories — see issue #710).
2405
+ report_body = f"""<?xml version="1.0"?>
2406
+ <oc:filter-files xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
2407
+ <d:prop>
2408
+ <oc:fileid/>
2409
+ <d:displayname/>
2410
+ <d:getcontentlength/>
2411
+ <d:getcontenttype/>
2412
+ <d:getlastmodified/>
2413
+ <d:getetag/>
2414
+ <d:resourcetype/>
2415
+ </d:prop>
2416
+ <oc:filter-rules>
2417
+ <oc:systemtag>{tag_id}</oc:systemtag>
2418
+ </oc:filter-rules>
2419
+ </oc:filter-files>"""
2420
+
2421
+ response = await self._make_request(
2422
+ "REPORT",
2423
+ f"{self._get_webdav_base_path()}/",
2424
+ headers={"Content-Type": _XML_CONTENT_TYPE},
2425
+ content=report_body,
2426
+ )
2427
+ # Redundant after _make_request (which raises on non-2xx) but
2428
+ # makes the contract explicit at the call site — see the same
2429
+ # rationale in get_tag_by_name.
2430
+ response.raise_for_status()
2431
+
2432
+ # Parse XML response
2433
+ root = ET.fromstring(response.content)
2434
+ ns = {
2435
+ "d": "DAV:",
2436
+ "oc": "http://owncloud.org/ns",
2437
+ }
2438
+
2439
+ files = []
2440
+ for response_elem in root.findall("d:response", ns):
2441
+ # Extract href (file path)
2442
+ href_elem = response_elem.find("d:href", ns)
2443
+ if href_elem is None or not href_elem.text:
2444
+ continue
2445
+
2446
+ propstat = response_elem.find("d:propstat", ns)
2447
+ if propstat is None:
2448
+ continue
2449
+
2450
+ prop = propstat.find("d:prop", ns)
2451
+ if prop is None:
2452
+ continue
2453
+
2454
+ # Extract all properties
2455
+ fileid_elem = prop.find("oc:fileid", ns)
2456
+ displayname_elem = prop.find("d:displayname", ns)
2457
+ contentlength_elem = prop.find("d:getcontentlength", ns)
2458
+ contenttype_elem = prop.find("d:getcontenttype", ns)
2459
+ lastmodified_elem = prop.find("d:getlastmodified", ns)
2460
+ etag_elem = prop.find("d:getetag", ns)
2461
+ resourcetype_elem = prop.find("d:resourcetype", ns)
2462
+
2463
+ if fileid_elem is None or not fileid_elem.text:
2464
+ continue
2465
+
2466
+ # A resourcetype with a <d:collection/> child indicates a folder.
2467
+ is_directory = (
2468
+ resourcetype_elem is not None
2469
+ and resourcetype_elem.find("d:collection", ns) is not None
2470
+ )
2471
+
2472
+ # Decode href path and extract the user-relative file path.
2473
+ # str.replace() would strip every occurrence of the prefix,
2474
+ # so an adversarially-named directory could collide; strip
2475
+ # only the leading occurrence via startswith + slice.
2476
+ href_path = unquote(href_elem.text)
2477
+ webdav_prefix = f"/remote.php/dav/files/{self._principal_or_username()}/"
2478
+ if href_path.startswith(webdav_prefix):
2479
+ file_path = "/" + href_path[len(webdav_prefix) :]
2480
+ else:
2481
+ file_path = href_path
2482
+
2483
+ # Parse last modified timestamp
2484
+ last_modified_timestamp = None
2485
+ if lastmodified_elem is not None and lastmodified_elem.text:
2486
+ try:
2487
+ dt = parsedate_to_datetime(lastmodified_elem.text)
2488
+ last_modified_timestamp = int(dt.timestamp())
2489
+ except (TypeError, ValueError):
2490
+ logger.debug(
2491
+ "Unparseable getlastmodified %r", lastmodified_elem.text
2492
+ )
2493
+
2494
+ file_info = {
2495
+ "id": int(fileid_elem.text),
2496
+ "path": file_path,
2497
+ "name": displayname_elem.text
2498
+ if displayname_elem is not None
2499
+ else file_path.split("/")[-1],
2500
+ "size": int(contentlength_elem.text)
2501
+ if contentlength_elem is not None and contentlength_elem.text
2502
+ else 0,
2503
+ "content_type": contenttype_elem.text
2504
+ if contenttype_elem is not None
2505
+ else "",
2506
+ "last_modified": lastmodified_elem.text
2507
+ if lastmodified_elem is not None
2508
+ else None,
2509
+ "last_modified_timestamp": last_modified_timestamp,
2510
+ "etag": etag_elem.text if etag_elem is not None else None,
2511
+ "is_directory": is_directory,
2512
+ }
2513
+ files.append(file_info)
2514
+
2515
+ logger.debug("Found %d files with tag ID %s", len(files), tag_id)
2516
+ return files
2517
+
2518
+ async def get_file_info(self, path: str) -> dict[str, Any] | None:
2519
+ """Get file info including file ID via WebDAV PROPFIND.
2520
+
2521
+ .. note::
2522
+ **Behavior change (ADR-019):** previously this method returned
2523
+ ``None`` for HTTP 404. It now raises ``HTTPStatusError`` for any
2524
+ non-2xx status, including 404. ``None`` is reserved for the
2525
+ ambiguous *malformed PROPFIND* case (server returned 2xx with a
2526
+ response body missing required XML elements). External callers
2527
+ updating from the old contract must catch ``HTTPStatusError``
2528
+ and inspect ``e.response.status_code`` to handle 404 explicitly.
2529
+
2530
+ Args:
2531
+ path: Path to the file (relative to user's files directory)
2532
+
2533
+ Returns:
2534
+ File info dictionary with id, name, size, content_type, etc.
2535
+ Returns ``None`` ONLY when the server returned a malformed
2536
+ PROPFIND response (missing ``<d:response>`` /
2537
+ ``<d:propstat>`` / ``<d:prop>`` elements) — an ambiguous
2538
+ state where we cannot tell whether the file exists.
2539
+
2540
+ Raises:
2541
+ HTTPStatusError: For any non-2xx HTTP status, including 404
2542
+ ("not found"). Callers that want to treat 404 as
2543
+ "absent" should catch ``HTTPStatusError`` and check
2544
+ ``e.response.status_code``. This matches the convention
2545
+ of the rest of this client and lets verify-on-read
2546
+ distinguish a definitive absence (HTTP 404) from a
2547
+ brittle response (None).
2548
+ """
2549
+ await self._ensure_principal_id()
2550
+ webdav_path = self._webdav_path(path)
2551
+
2552
+ propfind_body = """<?xml version="1.0"?>
2553
+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
2554
+ <d:prop>
2555
+ <oc:fileid/>
2556
+ <d:displayname/>
2557
+ <d:getcontentlength/>
2558
+ <d:getcontenttype/>
2559
+ <d:getlastmodified/>
2560
+ <d:getetag/>
2561
+ <d:resourcetype/>
2562
+ </d:prop>
2563
+ </d:propfind>"""
2564
+
2565
+ response = await self._client.request(
2566
+ "PROPFIND",
2567
+ webdav_path,
2568
+ headers={"Depth": "0"},
2569
+ content=propfind_body,
2570
+ )
2571
+ response.raise_for_status()
2572
+
2573
+ # Parse XML response
2574
+ root = ET.fromstring(response.content)
2575
+ ns = {
2576
+ "d": "DAV:",
2577
+ "oc": "http://owncloud.org/ns",
2578
+ }
2579
+
2580
+ response_elem = root.find("d:response", ns)
2581
+ if response_elem is None:
2582
+ return None
2583
+
2584
+ propstat = response_elem.find("d:propstat", ns)
2585
+ if propstat is None:
2586
+ return None
2587
+
2588
+ prop = propstat.find("d:prop", ns)
2589
+ if prop is None:
2590
+ return None
2591
+
2592
+ # Extract properties
2593
+ fileid_elem = prop.find("oc:fileid", ns)
2594
+ displayname_elem = prop.find("d:displayname", ns)
2595
+ contentlength_elem = prop.find("d:getcontentlength", ns)
2596
+ contenttype_elem = prop.find("d:getcontenttype", ns)
2597
+ lastmodified_elem = prop.find("d:getlastmodified", ns)
2598
+ etag_elem = prop.find("d:getetag", ns)
2599
+ resourcetype_elem = prop.find("d:resourcetype", ns)
2600
+
2601
+ is_directory = (
2602
+ resourcetype_elem is not None
2603
+ and resourcetype_elem.find("d:collection", ns) is not None
2604
+ )
2605
+
2606
+ file_info = {
2607
+ "id": int(fileid_elem.text)
2608
+ if fileid_elem is not None and fileid_elem.text is not None
2609
+ else None,
2610
+ "path": path,
2611
+ "name": displayname_elem.text
2612
+ if displayname_elem is not None
2613
+ else path.split("/")[-1],
2614
+ "size": int(contentlength_elem.text)
2615
+ if contentlength_elem is not None and contentlength_elem.text
2616
+ else 0,
2617
+ "content_type": contenttype_elem.text
2618
+ if contenttype_elem is not None
2619
+ else "",
2620
+ "last_modified": lastmodified_elem.text
2621
+ if lastmodified_elem is not None
2622
+ else None,
2623
+ "etag": normalize_etag(etag_elem.text)
2624
+ if etag_elem is not None and etag_elem.text
2625
+ else None,
2626
+ "is_directory": is_directory,
2627
+ }
2628
+
2629
+ logger.debug("Got file info for '%s': id=%s", path, file_info["id"])
2630
+ return file_info
2631
+
2632
+ async def create_tag(
2633
+ self,
2634
+ name: str,
2635
+ user_visible: bool = True,
2636
+ user_assignable: bool = True,
2637
+ ) -> dict[str, Any]:
2638
+ """Create a system tag via WebDAV.
2639
+
2640
+ Args:
2641
+ name: Name of the tag to create
2642
+ user_visible: Whether the tag is visible to users
2643
+ user_assignable: Whether users can assign this tag
2644
+
2645
+ Returns:
2646
+ Tag dictionary with id, name, userVisible, userAssignable
2647
+
2648
+ Raises:
2649
+ HTTPStatusError: If tag creation fails (409 if already exists)
2650
+ """
2651
+ # Use WebDAV POST with JSON body to create tag
2652
+ response = await self._client.post(
2653
+ "/remote.php/dav/systemtags/",
2654
+ headers={"Content-Type": "application/json"},
2655
+ json={
2656
+ "name": name,
2657
+ "userVisible": user_visible,
2658
+ "userAssignable": user_assignable,
2659
+ },
2660
+ )
2661
+ response.raise_for_status()
2662
+
2663
+ # Extract tag ID from Content-Location header (e.g., /remote.php/dav/systemtags/42)
2664
+ content_location = response.headers.get("Content-Location", "")
2665
+ tag_id = None
2666
+ if content_location:
2667
+ # Extract the numeric ID from the path
2668
+ try:
2669
+ tag_id = int(content_location.rstrip("/").split("/")[-1])
2670
+ except (ValueError, IndexError):
2671
+ logger.debug("No tag id in Content-Location %r", content_location)
2672
+
2673
+ tag_info = {
2674
+ "id": tag_id,
2675
+ "name": name,
2676
+ "userVisible": user_visible,
2677
+ "userAssignable": user_assignable,
2678
+ }
2679
+
2680
+ logger.info("Created tag '%s' with ID %s", name, tag_info["id"])
2681
+ return tag_info
2682
+
2683
+ async def get_or_create_tag(
2684
+ self,
2685
+ name: str,
2686
+ user_visible: bool = True,
2687
+ user_assignable: bool = True,
2688
+ ) -> dict[str, Any]:
2689
+ """Get a tag by name, creating it if it doesn't exist.
2690
+
2691
+ Args:
2692
+ name: Name of the tag
2693
+ user_visible: Whether the tag is visible to users (for creation)
2694
+ user_assignable: Whether users can assign this tag (for creation)
2695
+
2696
+ Returns:
2697
+ Tag dictionary with id, name, userVisible, userAssignable
2698
+ """
2699
+ # First try to get existing tag
2700
+ existing_tag = await self.get_tag_by_name(name)
2701
+ if existing_tag:
2702
+ logger.debug("Tag '%s' already exists with ID %s", name, existing_tag["id"])
2703
+ return existing_tag
2704
+
2705
+ # Create new tag
2706
+ try:
2707
+ return await self.create_tag(name, user_visible, user_assignable)
2708
+ except HTTPStatusError as e:
2709
+ if e.response.status_code == 409:
2710
+ # Tag was created between our check and creation, fetch it
2711
+ existing_tag = await self.get_tag_by_name(name)
2712
+ if existing_tag:
2713
+ return existing_tag
2714
+ raise
2715
+
2716
+ async def assign_tag_to_file(self, file_id: int, tag_id: int) -> bool:
2717
+ """Assign a system tag to a file.
2718
+
2719
+ Args:
2720
+ file_id: Numeric file ID
2721
+ tag_id: Numeric tag ID
2722
+
2723
+ Returns:
2724
+ True if tag was assigned successfully (or already assigned)
2725
+
2726
+ Raises:
2727
+ HTTPStatusError: If tag assignment fails
2728
+ """
2729
+ response = await self._client.request(
2730
+ "PUT",
2731
+ f"/remote.php/dav/systemtags-relations/files/{file_id}/{tag_id}",
2732
+ headers={"Content-Length": "0"},
2733
+ content=b"",
2734
+ )
2735
+
2736
+ # 201 = Created (new assignment), 409 = Conflict (already assigned)
2737
+ if response.status_code in (201, 409):
2738
+ logger.info("Tagged file %s with tag %s", file_id, tag_id)
2739
+ return True
2740
+
2741
+ response.raise_for_status()
2742
+ return True
2743
+
2744
+ async def remove_tag_from_file(self, file_id: int, tag_id: int) -> bool:
2745
+ """Remove a system tag from a file.
2746
+
2747
+ Args:
2748
+ file_id: Numeric file ID
2749
+ tag_id: Numeric tag ID
2750
+
2751
+ Returns:
2752
+ True if tag was removed successfully (or wasn't assigned)
2753
+
2754
+ Raises:
2755
+ HTTPStatusError: If tag removal fails
2756
+ """
2757
+ response = await self._client.request(
2758
+ "DELETE",
2759
+ f"/remote.php/dav/systemtags-relations/files/{file_id}/{tag_id}",
2760
+ )
2761
+
2762
+ # 204 = No Content (removed), 404 = Not Found (wasn't assigned)
2763
+ if response.status_code in (204, 404):
2764
+ logger.info("Removed tag %s from file %s", tag_id, file_id)
2765
+ return True
2766
+
2767
+ response.raise_for_status()
2768
+ return True
2769
+
2770
+ # -- Trash bin and file versions ----------------------------------------
2771
+ #
2772
+ # Nextcloud serves both from dedicated DAV endpoints rather than the files
2773
+ # endpoint:
2774
+ # /remote.php/dav/trashbin/<principal>/trash
2775
+ # /remote.php/dav/versions/<principal>/versions/<fileid>
2776
+ # Restoring is a MOVE into a "restore" collection in both cases -- that is
2777
+ # the interface Nextcloud provides, not a workaround.
2778
+
2779
+ _TRASH_PROPS = (
2780
+ ("trashbin_filename", "{http://nextcloud.org/ns}trashbin-filename"),
2781
+ ("original_location", "{http://nextcloud.org/ns}trashbin-original-location"),
2782
+ ("deleted_at", "{http://nextcloud.org/ns}trashbin-deletion-time"),
2783
+ ("size", "{DAV:}getcontentlength"),
2784
+ )
2785
+
2786
+ _VERSION_PROPS = (
2787
+ ("size", "{DAV:}getcontentlength"),
2788
+ ("modified", "{DAV:}getlastmodified"),
2789
+ ("label", "{http://nextcloud.org/ns}version-label"),
2790
+ )
2791
+
2792
+ def _trashbin_base(self) -> str:
2793
+ return f"/remote.php/dav/trashbin/{self._principal_or_username()}"
2794
+
2795
+ def _versions_base(self) -> str:
2796
+ return f"/remote.php/dav/versions/{self._principal_or_username()}"
2797
+
2798
+ @staticmethod
2799
+ def _propfind_body(props: tuple[tuple[str, str], ...]) -> str:
2800
+ lines = []
2801
+ for _, qualified in props:
2802
+ namespace, _, local = qualified.partition("}")
2803
+ namespace = namespace.lstrip("{")
2804
+ prefix = "d" if namespace == "DAV:" else "nc"
2805
+ lines.append(f"<{prefix}:{local} />")
2806
+ inner = "".join(lines)
2807
+ return (
2808
+ '<?xml version="1.0" encoding="utf-8"?>'
2809
+ '<d:propfind xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns">'
2810
+ f"<d:prop>{inner}</d:prop>"
2811
+ "</d:propfind>"
2812
+ )
2813
+
2814
+ @staticmethod
2815
+ def _read_props(
2816
+ response_elem: "ET.Element", props: tuple[tuple[str, str], ...]
2817
+ ) -> Dict[str, Any]:
2818
+ """Read the requested properties out of a multistatus response.
2819
+
2820
+ Only the ``200 OK`` propstat block is consulted. A response carries one
2821
+ block per status, and the 404 one lists the properties the server does
2822
+ *not* have -- folding those in would fabricate values for them.
2823
+ """
2824
+ # _dav_props_ok keys by local name; the tables here carry the fully
2825
+ # qualified name, so strip the namespace before the lookup.
2826
+ available = _dav_props_ok(response_elem)
2827
+ return {
2828
+ key: available.get(qualified.rpartition("}")[2]) for key, qualified in props
2829
+ }
2830
+
2831
+ async def list_trash(self) -> List[Dict[str, Any]]:
2832
+ """List the files currently in the trash bin."""
2833
+ await self._ensure_principal_id()
2834
+ response = await self._make_request(
2835
+ "PROPFIND",
2836
+ f"{self._trashbin_base()}/trash",
2837
+ content=self._propfind_body(self._TRASH_PROPS),
2838
+ headers={
2839
+ "Depth": "1",
2840
+ "Content-Type": "application/xml",
2841
+ },
2842
+ )
2843
+
2844
+ root = ET.fromstring(response.content)
2845
+ items: List[Dict[str, Any]] = []
2846
+ for response_elem in root.findall(".//{DAV:}response"):
2847
+ href_elem = response_elem.find("{DAV:}href")
2848
+ if href_elem is None or not href_elem.text:
2849
+ continue
2850
+ href = href_elem.text
2851
+ entry_id = unquote(href.rstrip("/").split("/")[-1])
2852
+ # The 'trash' collection itself is not an entry.
2853
+ if not entry_id or entry_id == "trash":
2854
+ continue
2855
+ entry = self._read_props(response_elem, self._TRASH_PROPS)
2856
+ entry["id"] = entry_id
2857
+ entry["href"] = href
2858
+ items.append(entry)
2859
+ return items
2860
+
2861
+ async def restore_from_trash(self, entry_id: str) -> Dict[str, Any]:
2862
+ """Restore a trashed entry to the location it was deleted from."""
2863
+ await self._ensure_principal_id()
2864
+ source = f"{self._trashbin_base()}/trash/{quote(entry_id, safe='')}"
2865
+ destination = f"{self._trashbin_base()}/restore/{quote(entry_id, safe='')}"
2866
+ # No Overwrite header: "restore" is a virtual collection, and with
2867
+ # "Overwrite: F" Sabre reports HTTP 412 "destination node already
2868
+ # exists" even when nothing sits at the original location. Nextcloud's
2869
+ # own web UI does not send the header either.
2870
+ await self._make_request(
2871
+ "MOVE",
2872
+ source,
2873
+ headers={
2874
+ "Destination": self._resolve_url(destination),
2875
+ },
2876
+ )
2877
+ return {"restored": entry_id}
2878
+
2879
+ async def list_versions(
2880
+ self, path: str, *, file_id: Optional[str | int] = None
2881
+ ) -> Dict[str, Any]:
2882
+ """List the stored previous versions of a file.
2883
+
2884
+ ``file_id`` lets a caller that already resolved the path (e.g. the
2885
+ MCP tool layer, which does so for the excluded-tag guard) skip a
2886
+ second ``get_fileid`` round-trip. Resolved internally when omitted,
2887
+ so the method still works standalone.
2888
+ """
2889
+ await self._ensure_principal_id()
2890
+ if file_id is None:
2891
+ file_id = await self.get_fileid(path)
2892
+ if not file_id:
2893
+ raise ValueError(f"No file id for path: {path}")
2894
+
2895
+ response = await self._make_request(
2896
+ "PROPFIND",
2897
+ f"{self._versions_base()}/versions/{file_id}",
2898
+ content=self._propfind_body(self._VERSION_PROPS),
2899
+ headers={
2900
+ "Depth": "1",
2901
+ "Content-Type": "application/xml",
2902
+ },
2903
+ )
2904
+
2905
+ root = ET.fromstring(response.content)
2906
+ versions: List[Dict[str, Any]] = []
2907
+ for response_elem in root.findall(".//{DAV:}response"):
2908
+ href_elem = response_elem.find("{DAV:}href")
2909
+ if href_elem is None or not href_elem.text:
2910
+ continue
2911
+ version_id = unquote(href_elem.text.rstrip("/").split("/")[-1])
2912
+ # The collection itself is named after the file id.
2913
+ if not version_id or version_id == str(file_id):
2914
+ continue
2915
+ entry = self._read_props(response_elem, self._VERSION_PROPS)
2916
+ entry["version_id"] = version_id
2917
+ versions.append(entry)
2918
+ return {"path": path, "file_id": file_id, "versions": versions}
2919
+
2920
+ async def restore_version(
2921
+ self, path: str, version_id: str, *, file_id: Optional[str | int] = None
2922
+ ) -> Dict[str, Any]:
2923
+ """Roll a file back to an earlier version.
2924
+
2925
+ The current content is not lost: Nextcloud stores it as a version in
2926
+ turn, so the rollback itself can be undone.
2927
+
2928
+ ``file_id``: see :meth:`list_versions`.
2929
+ """
2930
+ await self._ensure_principal_id()
2931
+ if file_id is None:
2932
+ file_id = await self.get_fileid(path)
2933
+ if not file_id:
2934
+ raise ValueError(f"No file id for path: {path}")
2935
+
2936
+ source = (
2937
+ f"{self._versions_base()}/versions/{file_id}/{quote(version_id, safe='')}"
2938
+ )
2939
+ destination = f"{self._versions_base()}/restore/target"
2940
+ await self._make_request(
2941
+ "MOVE",
2942
+ source,
2943
+ headers={
2944
+ "Destination": self._resolve_url(destination),
2945
+ },
2946
+ )
2947
+ return {"path": path, "restored_version": version_id}
2948
+
2949
+ # -- File tags (systemtags) ---------------------------------------------
2950
+ #
2951
+ # The client already covered tags (create/assign/remove/search); only two
2952
+ # read paths were missing: list every tag, and list the tags of one file.
2953
+
2954
+ _TAG_PROPFIND = """<?xml version="1.0"?>
2955
+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
2956
+ <d:prop>
2957
+ <oc:id/>
2958
+ <oc:display-name/>
2959
+ <oc:user-visible/>
2960
+ <oc:user-assignable/>
2961
+ </d:prop>
2962
+ </d:propfind>"""
2963
+
2964
+ async def list_tags(self) -> List[Dict[str, Any]]:
2965
+ """Every system tag defined on this instance."""
2966
+ response = await self._make_request(
2967
+ "PROPFIND",
2968
+ "/remote.php/dav/systemtags/",
2969
+ headers={
2970
+ "Depth": "1",
2971
+ "Content-Type": _XML_CONTENT_TYPE,
2972
+ },
2973
+ content=self._TAG_PROPFIND,
2974
+ )
2975
+
2976
+ return self._tags_from_multistatus(ET.fromstring(response.content))
2977
+
2978
+ @staticmethod
2979
+ def _tags_from_multistatus(root: Any) -> List[Dict[str, Any]]:
2980
+ """Extract tags from a systemtags PROPFIND response.
2981
+
2982
+ The collection itself comes back as a response element and is skipped.
2983
+ An entry without an id or display name cannot be used for anything, so
2984
+ it is dropped rather than surfaced with placeholder values.
2985
+ """
2986
+ tags: List[Dict[str, Any]] = []
2987
+ for response_elem in root.findall("{DAV:}response"):
2988
+ href = response_elem.find("{DAV:}href")
2989
+ if href is None or href.text == "/remote.php/dav/systemtags/":
2990
+ continue
2991
+ name_elem = response_elem.find(".//{http://owncloud.org/ns}display-name")
2992
+ id_elem = response_elem.find(".//{http://owncloud.org/ns}id")
2993
+ # An entry without a usable id or name cannot be acted on, and an
2994
+ # empty display name would also make the sort key ambiguous.
2995
+ if id_elem is None or not id_elem.text:
2996
+ continue
2997
+ if name_elem is None or not (name_elem.text or "").strip():
2998
+ continue
2999
+ assignable = response_elem.find(
3000
+ ".//{http://owncloud.org/ns}user-assignable"
3001
+ )
3002
+ tags.append(
3003
+ {
3004
+ "id": int(id_elem.text),
3005
+ "name": name_elem.text or "",
3006
+ "assignable": (assignable is None or assignable.text != "false"),
3007
+ }
3008
+ )
3009
+ return sorted(tags, key=lambda t: t["name"].lower())
3010
+
3011
+ async def get_file_tags(self, path: str) -> Dict[str, Any]:
3012
+ """The tags assigned to one file.
3013
+
3014
+ Nextcloud only reports tag *ids* on the file, so the names are looked
3015
+ up from the full list. That is one extra call, but ids alone are of
3016
+ little use to the caller -- and unguessable for a language model.
3017
+ """
3018
+ file_id = await self.get_fileid(path)
3019
+ if not file_id:
3020
+ raise ValueError(f"No file id for path: {path}")
3021
+
3022
+ response = await self._make_request(
3023
+ "PROPFIND",
3024
+ f"/remote.php/dav/systemtags-relations/files/{file_id}",
3025
+ headers={
3026
+ "Depth": "1",
3027
+ "Content-Type": _XML_CONTENT_TYPE,
3028
+ },
3029
+ content=self._TAG_PROPFIND,
3030
+ )
3031
+
3032
+ root = ET.fromstring(response.content)
3033
+ ids: List[int] = []
3034
+ for id_elem in root.findall(".//{http://owncloud.org/ns}id"):
3035
+ if id_elem.text and id_elem.text.isdigit():
3036
+ ids.append(int(id_elem.text))
3037
+
3038
+ names = {t["id"]: t["name"] for t in await self.list_tags()}
3039
+ return {
3040
+ "path": path,
3041
+ "file_id": file_id,
3042
+ "tags": [
3043
+ {"id": i, "name": names.get(i, f"(unknown tag {i})")}
3044
+ for i in sorted(set(ids))
3045
+ ],
3046
+ }