nextcloud-client 0.211.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nextcloud_client/__init__.py +477 -0
- nextcloud_client/auth.py +34 -0
- nextcloud_client/availability.py +290 -0
- nextcloud_client/base.py +443 -0
- nextcloud_client/calendar.py +3430 -0
- nextcloud_client/collectives.py +325 -0
- nextcloud_client/contacts.py +1321 -0
- nextcloud_client/cookbook.py +244 -0
- nextcloud_client/dav_errors.py +187 -0
- nextcloud_client/dav_urls.py +61 -0
- nextcloud_client/deck.py +930 -0
- nextcloud_client/groups.py +164 -0
- nextcloud_client/http.py +69 -0
- nextcloud_client/instrumentation.py +50 -0
- nextcloud_client/mail.py +825 -0
- nextcloud_client/models/__init__.py +1 -0
- nextcloud_client/models/deck.py +302 -0
- nextcloud_client/models/sharing.py +24 -0
- nextcloud_client/models/talk.py +136 -0
- nextcloud_client/models/users.py +41 -0
- nextcloud_client/news.py +394 -0
- nextcloud_client/notes.py +293 -0
- nextcloud_client/notes_search.py +113 -0
- nextcloud_client/ocs.py +140 -0
- nextcloud_client/py.typed +0 -0
- nextcloud_client/sharing.py +364 -0
- nextcloud_client/shopping_list.py +150 -0
- nextcloud_client/tables.py +146 -0
- nextcloud_client/talk.py +487 -0
- nextcloud_client/users.py +239 -0
- nextcloud_client/webdav.py +3046 -0
- nextcloud_client-0.211.0.dist-info/METADATA +102 -0
- nextcloud_client-0.211.0.dist-info/RECORD +34 -0
- nextcloud_client-0.211.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Controller for notes search functionality."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, AsyncIterable, Dict, List
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class NotesSearchController:
|
|
7
|
+
"""Handles notes search logic and scoring."""
|
|
8
|
+
|
|
9
|
+
async def search_notes(
|
|
10
|
+
self, notes: AsyncIterable[Dict[str, Any]], query: str
|
|
11
|
+
) -> List[Dict[str, Any]]:
|
|
12
|
+
"""
|
|
13
|
+
Search notes using token-based matching with relevance ranking.
|
|
14
|
+
Returns notes sorted by relevance score.
|
|
15
|
+
If query is empty, returns all notes.
|
|
16
|
+
"""
|
|
17
|
+
search_results: List[Dict[str, Any]] = []
|
|
18
|
+
query_tokens = self._process_query(query)
|
|
19
|
+
|
|
20
|
+
# If empty query after processing, return all notes
|
|
21
|
+
if not query_tokens:
|
|
22
|
+
async for note in notes:
|
|
23
|
+
search_results.append(
|
|
24
|
+
{
|
|
25
|
+
"id": note.get("id"),
|
|
26
|
+
"title": note.get("title"),
|
|
27
|
+
"category": note.get("category"),
|
|
28
|
+
"modified": note.get("modified"),
|
|
29
|
+
"_score": None, # No score for unfiltered results
|
|
30
|
+
}
|
|
31
|
+
)
|
|
32
|
+
return search_results
|
|
33
|
+
|
|
34
|
+
# Process and score each note
|
|
35
|
+
async for note in notes:
|
|
36
|
+
title_tokens, content_tokens = self._process_note_content(note)
|
|
37
|
+
score = self._calculate_score(query_tokens, title_tokens, content_tokens)
|
|
38
|
+
|
|
39
|
+
# Only include notes with a non-zero score
|
|
40
|
+
if score >= 0.5:
|
|
41
|
+
search_results.append(
|
|
42
|
+
{
|
|
43
|
+
"id": note.get("id"),
|
|
44
|
+
"title": note.get("title"),
|
|
45
|
+
"category": note.get("category"),
|
|
46
|
+
"modified": note.get("modified"),
|
|
47
|
+
"_score": score, # Include score for sorting
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Sort by score in descending order
|
|
52
|
+
search_results.sort(key=lambda x: x["_score"], reverse=True)
|
|
53
|
+
|
|
54
|
+
return search_results
|
|
55
|
+
|
|
56
|
+
def _process_query(self, query: str) -> List[str]:
|
|
57
|
+
"""
|
|
58
|
+
Tokenize and normalize the search query.
|
|
59
|
+
"""
|
|
60
|
+
# Convert to lowercase and split into tokens
|
|
61
|
+
tokens = query.lower().split()
|
|
62
|
+
# Filter out very short tokens
|
|
63
|
+
tokens = [token for token in tokens if len(token) > 1]
|
|
64
|
+
return tokens
|
|
65
|
+
|
|
66
|
+
def _process_note_content(
|
|
67
|
+
self, note: Dict[str, Any]
|
|
68
|
+
) -> tuple[List[str], List[str]]:
|
|
69
|
+
"""
|
|
70
|
+
Tokenize and normalize note title and content.
|
|
71
|
+
"""
|
|
72
|
+
# Process title
|
|
73
|
+
title = note.get("title", "").lower()
|
|
74
|
+
title_tokens = title.split()
|
|
75
|
+
|
|
76
|
+
# Process content
|
|
77
|
+
content = note.get("content", "").lower()
|
|
78
|
+
content_tokens = content.split()
|
|
79
|
+
|
|
80
|
+
return title_tokens, content_tokens
|
|
81
|
+
|
|
82
|
+
def _calculate_score(
|
|
83
|
+
self,
|
|
84
|
+
query_tokens: List[str],
|
|
85
|
+
title_tokens: List[str],
|
|
86
|
+
content_tokens: List[str],
|
|
87
|
+
) -> float:
|
|
88
|
+
"""
|
|
89
|
+
Calculate a relevance score for a note based on query tokens.
|
|
90
|
+
"""
|
|
91
|
+
# Constants for weighting
|
|
92
|
+
TITLE_WEIGHT = 3.0
|
|
93
|
+
CONTENT_WEIGHT = 1.0
|
|
94
|
+
|
|
95
|
+
score = 0.0
|
|
96
|
+
|
|
97
|
+
# Count matches in title
|
|
98
|
+
title_matches = sum(1 for qt in query_tokens if qt in title_tokens)
|
|
99
|
+
if query_tokens: # Avoid division by zero
|
|
100
|
+
title_match_ratio = title_matches / len(query_tokens)
|
|
101
|
+
score += TITLE_WEIGHT * title_match_ratio
|
|
102
|
+
|
|
103
|
+
# Count matches in content
|
|
104
|
+
content_matches = sum(1 for qt in query_tokens if qt in content_tokens)
|
|
105
|
+
if query_tokens: # Avoid division by zero
|
|
106
|
+
content_match_ratio = content_matches / len(query_tokens)
|
|
107
|
+
score += CONTENT_WEIGHT * content_match_ratio
|
|
108
|
+
|
|
109
|
+
# If no tokens matched at all, return zero
|
|
110
|
+
if title_matches == 0 and content_matches == 0:
|
|
111
|
+
return 0.0
|
|
112
|
+
|
|
113
|
+
return score
|
nextcloud_client/ocs.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Shared handling for Nextcloud's OCS response envelope.
|
|
2
|
+
|
|
3
|
+
Every OCS endpoint wraps its payload the same way::
|
|
4
|
+
|
|
5
|
+
{"ocs": {"meta": {"status": "ok", "statuscode": 200, "message": "OK"},
|
|
6
|
+
"data": {...}}}
|
|
7
|
+
|
|
8
|
+
Two properties of that envelope bite callers who only check the HTTP status:
|
|
9
|
+
|
|
10
|
+
* **The v1 trap.** ``/ocs/v1.php`` answers *every* request with HTTP 200 and
|
|
11
|
+
puts the real outcome in ``meta.statuscode``, where success is ``100``.
|
|
12
|
+
``/ocs/v2.php`` mirrors the OCS code onto the HTTP status and uses ``200``.
|
|
13
|
+
Both codes therefore mean success, depending only on which route was called.
|
|
14
|
+
|
|
15
|
+
* **997 is not a server error.** Nextcloud returns it when the request was
|
|
16
|
+
unauthenticated *or* when it omitted the mandatory ``OCS-APIRequest: true``
|
|
17
|
+
header that its CSRF check requires on every OCS call. Reported as a generic
|
|
18
|
+
failure it sends the reader hunting for a server fault that is not there, so
|
|
19
|
+
it gets named explicitly here.
|
|
20
|
+
|
|
21
|
+
This module deliberately does **not** raise. Three clients parse this envelope
|
|
22
|
+
and each raises a different type that its callers already catch --
|
|
23
|
+
``OCSError`` (collectives, caught in a dozen places in ``server/collectives``),
|
|
24
|
+
``HTTPStatusError`` (mail), and ``RuntimeError`` (sharing). Centralising the
|
|
25
|
+
*parsing* and the *wording* is safe; centralising the raising would change
|
|
26
|
+
three caller contracts at once.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from collections.abc import Mapping
|
|
30
|
+
from types import MappingProxyType
|
|
31
|
+
from typing import Any, NamedTuple
|
|
32
|
+
|
|
33
|
+
#: Extra headers a JSON-returning ``/ocs/v2.php`` call sends: OCS answers in XML
|
|
34
|
+
#: unless asked for JSON.
|
|
35
|
+
#:
|
|
36
|
+
#: ``OCS-APIRequest: true`` is deliberately *not* here. Every Nextcloud-bound
|
|
37
|
+
#: httpx2 client sends it as a client default (``nextcloud_client.http.NEXTCLOUD_DEFAULT_HEADERS``
|
|
38
|
+
#: via ``nextcloud_httpx_client``), so no call site can forget it -- a
|
|
39
|
+
#: per-client opt-in is how the Tables v1 routes went without it (GH #1664).
|
|
40
|
+
#: ``tests/unit/test_ocs_headers_are_shared`` fails if any module spells it.
|
|
41
|
+
#:
|
|
42
|
+
#: Read-only on purpose: several clients share this one object, so an in-place
|
|
43
|
+
#: edit would be a cross-client bug; ``MappingProxyType`` makes that a
|
|
44
|
+
#: ``TypeError`` at the point of the mistake. Consumers take a ``dict(...)`` or
|
|
45
|
+
#: ``{**...}`` copy.
|
|
46
|
+
#:
|
|
47
|
+
#: Header sets that do not want JSON keep their own ``Accept`` (or none):
|
|
48
|
+
#: WebDAV (Sabre answers in XML), ``MailClient.get_attachment`` (binary bytes),
|
|
49
|
+
#: Deck's REST API (sends ``Content-Type``), and ``api/passwords.py`` (asks for
|
|
50
|
+
#: JSON with ``format=json``, which OCS honours in place of the header).
|
|
51
|
+
OCS_REQUEST_HEADERS: Mapping[str, str] = MappingProxyType(
|
|
52
|
+
{
|
|
53
|
+
"Accept": "application/json",
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
#: Success codes: ``100`` from OCS v1, ``200`` from v2.
|
|
58
|
+
OCS_SUCCESS_STATUS_CODES = frozenset({100, 200})
|
|
59
|
+
|
|
60
|
+
#: "Unauthorised" in OCS's vocabulary -- bad credentials *or* a missing
|
|
61
|
+
#: ``OCS-APIRequest`` header.
|
|
62
|
+
OCS_STATUS_UNAUTHENTICATED = 997
|
|
63
|
+
|
|
64
|
+
_UNAUTHENTICATED_HINT = (
|
|
65
|
+
"unauthenticated — either the credentials were rejected, or the request "
|
|
66
|
+
"omitted the 'OCS-APIRequest: true' header that Nextcloud's CSRF check "
|
|
67
|
+
"requires on OCS routes"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class OCSEnvelope(NamedTuple):
|
|
72
|
+
"""The parts of an OCS envelope callers act on."""
|
|
73
|
+
|
|
74
|
+
status_code: int
|
|
75
|
+
message: str
|
|
76
|
+
data: Any
|
|
77
|
+
has_data: bool
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def is_success(self) -> bool:
|
|
81
|
+
"""True when the OCS code is a documented success (100 or 200).
|
|
82
|
+
|
|
83
|
+
This is stricter than the ``< 400`` test the collectives and mail
|
|
84
|
+
clients apply. They keep their own comparison for now rather than being
|
|
85
|
+
silently retightened by a refactor -- converging on one rule needs
|
|
86
|
+
evidence about which sub-400 codes real endpoints return.
|
|
87
|
+
"""
|
|
88
|
+
return self.status_code in OCS_SUCCESS_STATUS_CODES
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_ocs_envelope(payload: Any) -> OCSEnvelope:
|
|
92
|
+
"""Pull ``(statuscode, message, data)`` out of an OCS response body.
|
|
93
|
+
|
|
94
|
+
Tolerates every malformed shape seen in practice -- a non-dict body, a
|
|
95
|
+
missing or non-dict ``ocs`` / ``meta``, a non-numeric statuscode -- by
|
|
96
|
+
reporting ``500`` with a description, rather than raising a ``KeyError`` or
|
|
97
|
+
``TypeError`` that tells the caller nothing about what the server said.
|
|
98
|
+
"""
|
|
99
|
+
if not isinstance(payload, dict):
|
|
100
|
+
return OCSEnvelope(
|
|
101
|
+
500, f"Response is not a JSON object: {type(payload).__name__}", None, False
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
ocs = payload.get("ocs")
|
|
105
|
+
if not isinstance(ocs, dict):
|
|
106
|
+
return OCSEnvelope(500, "Response is not an OCS envelope", None, False)
|
|
107
|
+
|
|
108
|
+
meta = ocs.get("meta")
|
|
109
|
+
if not isinstance(meta, dict):
|
|
110
|
+
meta = {}
|
|
111
|
+
|
|
112
|
+
# ``or 200`` covers falsy-but-present values (``0``, ``""``, ``None``) the
|
|
113
|
+
# same way the mail client did before this module existed. Without it an
|
|
114
|
+
# empty statuscode parses to 500, which crosses mail's ``>= 400`` gate and
|
|
115
|
+
# turns a response that used to succeed into a raised error. A genuinely
|
|
116
|
+
# non-numeric value still falls through to 500 -- an unreadable status is
|
|
117
|
+
# not something to report as success.
|
|
118
|
+
raw_status = meta.get("statuscode") or 200
|
|
119
|
+
try:
|
|
120
|
+
status_code = int(raw_status)
|
|
121
|
+
except (TypeError, ValueError, OverflowError):
|
|
122
|
+
# OverflowError: ``json.loads`` accepts ``Infinity``, and int(inf) raises.
|
|
123
|
+
status_code = 500
|
|
124
|
+
|
|
125
|
+
# One fallback string for all three clients. They previously differed --
|
|
126
|
+
# sharing "Unknown error", collectives "OCS error", mail "Unknown OCS
|
|
127
|
+
# error" -- and consolidating is deliberate rather than incidental: this is
|
|
128
|
+
# the text shown only when the server sent no message at all, so a
|
|
129
|
+
# per-client variant conveys nothing a caller can act on. Called out
|
|
130
|
+
# explicitly because the statuscode default next to it was preserved
|
|
131
|
+
# exactly, and the difference in treatment should not look accidental.
|
|
132
|
+
message = meta.get("message") or "Unknown error"
|
|
133
|
+
return OCSEnvelope(status_code, str(message), ocs.get("data"), "data" in ocs)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def describe_ocs_failure(status_code: int, message: str) -> str:
|
|
137
|
+
"""Render an OCS failure, naming 997's two causes rather than guessing."""
|
|
138
|
+
if status_code == OCS_STATUS_UNAUTHENTICATED:
|
|
139
|
+
return f"OCS API error (code {status_code}): {_UNAUTHENTICATED_HINT}"
|
|
140
|
+
return f"OCS API error (code {status_code}): {message}"
|
|
File without changes
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Nextcloud OCS Sharing API client for file/folder sharing operations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .base import BaseNextcloudClient
|
|
7
|
+
from .models.sharing import ShareType
|
|
8
|
+
from .ocs import OCS_REQUEST_HEADERS, describe_ocs_failure, parse_ocs_envelope
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PublicLinkRecipientError(ValueError):
|
|
14
|
+
"""A public-link share was given a recipient it cannot address.
|
|
15
|
+
|
|
16
|
+
Its own type, rather than a plain ``ValueError``, so callers can attach a
|
|
17
|
+
redirect that only fits this case without matching on message text.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_share_with(share_type: int, share_with: str | None) -> None:
|
|
22
|
+
"""Check the ``shareType``/``shareWith`` pairing before it reaches the wire.
|
|
23
|
+
|
|
24
|
+
The case worth guarding is a public link that carries a recipient.
|
|
25
|
+
Nextcloud does not reject it: it ignores ``shareWith`` and returns a
|
|
26
|
+
perfectly valid anonymous link. The caller is then told the share
|
|
27
|
+
succeeded and reasonably believes the file went to the named person, when
|
|
28
|
+
it was actually published to anyone holding the URL. A silent success with
|
|
29
|
+
the wrong audience is worse than an error, which is why this is checked
|
|
30
|
+
client-side rather than left to the server.
|
|
31
|
+
|
|
32
|
+
The inverse — a recipient-typed share with no ``shareWith`` — does fail
|
|
33
|
+
server-side, but as a generic OCS 400 that names neither the field nor what
|
|
34
|
+
belongs in it.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
share_type: OCS ``shareType`` value (see :class:`ShareType`).
|
|
38
|
+
share_with: Recipient identifier, if any.
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
PublicLinkRecipientError: If a public link carries a recipient.
|
|
42
|
+
ValueError: If a recipient-typed share is missing one.
|
|
43
|
+
"""
|
|
44
|
+
has_recipient = bool(share_with and share_with.strip())
|
|
45
|
+
|
|
46
|
+
if share_type == ShareType.PUBLIC_LINK:
|
|
47
|
+
if has_recipient:
|
|
48
|
+
# Deliberately names no alternative *call* here. This message is
|
|
49
|
+
# shared between direct client callers and the MCP tool, which
|
|
50
|
+
# surfaces it verbatim, and the two layers have different names for
|
|
51
|
+
# the same operation -- pointing an agent at a callable that does
|
|
52
|
+
# not exist on its side is worse than not suggesting one. The tool
|
|
53
|
+
# appends its own suggestion when it translates this.
|
|
54
|
+
raise PublicLinkRecipientError(
|
|
55
|
+
f"shareType {ShareType.PUBLIC_LINK} (public link) must not carry "
|
|
56
|
+
f"shareWith: Nextcloud ignores the recipient and publishes the "
|
|
57
|
+
f"file to anyone holding the URL, so it would NOT be shared with "
|
|
58
|
+
f"{share_with!r}. Use shareType {ShareType.USER} (user) or "
|
|
59
|
+
f"{ShareType.GROUP} (group) to share with a recipient, or omit "
|
|
60
|
+
f"shareWith to create an anonymous public link."
|
|
61
|
+
)
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
# Everything that is not a public link addresses someone. Unknown types are
|
|
65
|
+
# treated as recipient-typed rather than rejected outright -- Nextcloud may
|
|
66
|
+
# add share types we do not know about, and refusing them here would break
|
|
67
|
+
# a caller that is otherwise correct.
|
|
68
|
+
if not has_recipient:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
f"shareType {share_type} requires a non-empty shareWith recipient "
|
|
71
|
+
"(user id, group id, email address, federated user@remote, circle "
|
|
72
|
+
"id, Talk conversation token or Deck card id, depending on the type)"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _ocs_data(payload: Any) -> Any:
|
|
77
|
+
"""Validate an OCS envelope and return its ``data``.
|
|
78
|
+
|
|
79
|
+
Raises ``RuntimeError`` -- the type this client has always raised and the
|
|
80
|
+
one its tests assert on. The envelope parsing and the failure wording come
|
|
81
|
+
from :mod:`.ocs` so every OCS client says the same thing about a given
|
|
82
|
+
status code, 997 in particular.
|
|
83
|
+
"""
|
|
84
|
+
envelope = parse_ocs_envelope(payload)
|
|
85
|
+
if not envelope.is_success:
|
|
86
|
+
raise RuntimeError(describe_ocs_failure(envelope.status_code, envelope.message))
|
|
87
|
+
return envelope.data
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class SharingClient(BaseNextcloudClient):
|
|
91
|
+
"""Client for Nextcloud OCS Sharing API operations.
|
|
92
|
+
|
|
93
|
+
Requests go through :meth:`BaseNextcloudClient._make_request`, matching
|
|
94
|
+
every other app client: that is what feeds the tracing spans and the
|
|
95
|
+
``mcp_nextcloud_api_requests_total`` metric, and it raises for status on
|
|
96
|
+
the caller's behalf. It is also already decorated with ``@retry_on_429``,
|
|
97
|
+
which is why these methods no longer carry their own copy: a second,
|
|
98
|
+
outer copy is dead weight. It cannot extend the budget -- the inner loop
|
|
99
|
+
signals exhaustion with ``RuntimeError``, which ``retry_on_429`` does not
|
|
100
|
+
catch -- so it would only read as protection that is not there.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
app_name = "sharing"
|
|
104
|
+
|
|
105
|
+
# Own copy, matching collectives and mail: the module-level dict is shared
|
|
106
|
+
# by all three clients, so passing it straight through would make any
|
|
107
|
+
# future in-place edit a cross-client bug.
|
|
108
|
+
_OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
|
|
109
|
+
|
|
110
|
+
async def create_share(
|
|
111
|
+
self,
|
|
112
|
+
path: str,
|
|
113
|
+
share_with: str | None = None,
|
|
114
|
+
share_type: int = 0,
|
|
115
|
+
permissions: int = 1,
|
|
116
|
+
) -> dict[str, Any]:
|
|
117
|
+
"""Create a share for a file or folder.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
path: Path to file/folder to share (relative to user's files)
|
|
121
|
+
share_with: Recipient identifier — user id, group id, email address,
|
|
122
|
+
federated ``user@remote``, circle id, Talk conversation token or
|
|
123
|
+
Deck card id, depending on ``share_type``. Omit it only for a
|
|
124
|
+
public link (``share_type=3``), which addresses nobody.
|
|
125
|
+
share_type: OCS share type — see :class:`ShareType`. 0=user
|
|
126
|
+
(default), 1=group, 3=public link, 4=email, 6=federated,
|
|
127
|
+
7=circle, 10=Talk conversation, 12=Deck card
|
|
128
|
+
permissions: Share permissions:
|
|
129
|
+
- 1 = read
|
|
130
|
+
- 2 = update
|
|
131
|
+
- 4 = create
|
|
132
|
+
- 8 = delete
|
|
133
|
+
- 16 = share
|
|
134
|
+
- 31 = all permissions
|
|
135
|
+
Common combinations: 1 (read-only), 3 (read+update), 15 (read+update+create+delete)
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
Share data including share ID
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
PublicLinkRecipientError: If a public link carries a recipient. A
|
|
142
|
+
``ValueError`` subclass, so existing ``except ValueError``
|
|
143
|
+
handlers keep working; catch it specifically to react to just
|
|
144
|
+
that case.
|
|
145
|
+
ValueError: If a recipient-typed share is missing its recipient.
|
|
146
|
+
HTTPStatusError: If the request fails
|
|
147
|
+
"""
|
|
148
|
+
validate_share_with(share_type, share_with)
|
|
149
|
+
|
|
150
|
+
payload: dict[str, Any] = {
|
|
151
|
+
"path": path,
|
|
152
|
+
"shareType": share_type,
|
|
153
|
+
"permissions": permissions,
|
|
154
|
+
}
|
|
155
|
+
# Omit shareWith entirely for a public link rather than sending an empty
|
|
156
|
+
# value: validate_share_with has already established there is no
|
|
157
|
+
# recipient, and OCS treats a present-but-empty field inconsistently.
|
|
158
|
+
# Send it trimmed, matching the value validation just accepted -- an
|
|
159
|
+
# untrimmed " alice " would otherwise reach OCS as a different recipient
|
|
160
|
+
# id than the one that was checked.
|
|
161
|
+
if share_with and share_with.strip():
|
|
162
|
+
payload["shareWith"] = share_with.strip()
|
|
163
|
+
|
|
164
|
+
response = await self._make_request(
|
|
165
|
+
"POST",
|
|
166
|
+
"/ocs/v2.php/apps/files_sharing/api/v1/shares",
|
|
167
|
+
headers=self._OCS_HEADERS,
|
|
168
|
+
data=payload,
|
|
169
|
+
)
|
|
170
|
+
data = response.json()
|
|
171
|
+
|
|
172
|
+
share_data = _ocs_data(data)
|
|
173
|
+
|
|
174
|
+
# An OK status with no data still means the share was not created.
|
|
175
|
+
if not share_data:
|
|
176
|
+
envelope = parse_ocs_envelope(data)
|
|
177
|
+
raise RuntimeError(
|
|
178
|
+
f"Share creation failed: {envelope.message} "
|
|
179
|
+
f"(status {envelope.status_code})"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
logger.info(
|
|
183
|
+
"Created share %s: %s -> %s (type=%s, permissions=%s)",
|
|
184
|
+
share_data["id"],
|
|
185
|
+
path,
|
|
186
|
+
share_with,
|
|
187
|
+
share_type,
|
|
188
|
+
permissions,
|
|
189
|
+
)
|
|
190
|
+
return share_data
|
|
191
|
+
|
|
192
|
+
async def create_public_link(
|
|
193
|
+
self,
|
|
194
|
+
path: str,
|
|
195
|
+
permissions: int = 1,
|
|
196
|
+
expire_date: str | None = None,
|
|
197
|
+
) -> dict[str, Any]:
|
|
198
|
+
"""Create a public link share (``shareType=3``) for a file or folder.
|
|
199
|
+
|
|
200
|
+
Unlike :meth:`create_share`, this targets anonymous public access, so no
|
|
201
|
+
``shareWith`` recipient is sent. The returned data carries the public
|
|
202
|
+
``url`` and ``token`` for the link.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
path: Path to file/folder to share (relative to the user's files)
|
|
206
|
+
permissions: Share permissions (default: 1 = read-only). See
|
|
207
|
+
:meth:`create_share` for the bit values.
|
|
208
|
+
expire_date: Optional expiry as ``YYYY-MM-DD``. Nextcloud enforces
|
|
209
|
+
public-link expiry at date granularity — the link expires at
|
|
210
|
+
midnight (start of this date) in the owner's timezone.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Share data including the public ``url`` and ``token``
|
|
214
|
+
|
|
215
|
+
Raises:
|
|
216
|
+
HTTPStatusError: If the request fails
|
|
217
|
+
RuntimeError: If the OCS API reports an error
|
|
218
|
+
"""
|
|
219
|
+
data: dict[str, Any] = {
|
|
220
|
+
"path": path,
|
|
221
|
+
"shareType": ShareType.PUBLIC_LINK,
|
|
222
|
+
"permissions": permissions,
|
|
223
|
+
}
|
|
224
|
+
if expire_date is not None:
|
|
225
|
+
data["expireDate"] = expire_date
|
|
226
|
+
|
|
227
|
+
response = await self._make_request(
|
|
228
|
+
"POST",
|
|
229
|
+
"/ocs/v2.php/apps/files_sharing/api/v1/shares",
|
|
230
|
+
headers=self._OCS_HEADERS,
|
|
231
|
+
data=data,
|
|
232
|
+
)
|
|
233
|
+
result = response.json()
|
|
234
|
+
|
|
235
|
+
share_data = _ocs_data(result)
|
|
236
|
+
|
|
237
|
+
# An OK status with no data still means the link was not created.
|
|
238
|
+
if not share_data:
|
|
239
|
+
envelope = parse_ocs_envelope(result)
|
|
240
|
+
raise RuntimeError(
|
|
241
|
+
f"Public link creation failed: {envelope.message} "
|
|
242
|
+
f"(status {envelope.status_code})"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
logger.info(
|
|
246
|
+
"Created public link %s: %s (permissions=%s, expire_date=%s)",
|
|
247
|
+
share_data["id"],
|
|
248
|
+
path,
|
|
249
|
+
permissions,
|
|
250
|
+
expire_date,
|
|
251
|
+
)
|
|
252
|
+
return share_data
|
|
253
|
+
|
|
254
|
+
async def delete_share(self, share_id: int) -> None:
|
|
255
|
+
"""Delete a share by its ID.
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
share_id: The share ID to delete
|
|
259
|
+
|
|
260
|
+
Raises:
|
|
261
|
+
HTTPStatusError: If the request fails
|
|
262
|
+
"""
|
|
263
|
+
response = await self._make_request(
|
|
264
|
+
"DELETE",
|
|
265
|
+
f"/ocs/v2.php/apps/files_sharing/api/v1/shares/{share_id}",
|
|
266
|
+
headers=self._OCS_HEADERS,
|
|
267
|
+
)
|
|
268
|
+
data = response.json()
|
|
269
|
+
|
|
270
|
+
_ocs_data(data)
|
|
271
|
+
|
|
272
|
+
logger.info("Deleted share %s", share_id)
|
|
273
|
+
|
|
274
|
+
async def get_share(self, share_id: int) -> dict[str, Any]:
|
|
275
|
+
"""Get information about a specific share.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
share_id: The share ID
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
Share data
|
|
282
|
+
|
|
283
|
+
Raises:
|
|
284
|
+
HTTPStatusError: If the request fails
|
|
285
|
+
"""
|
|
286
|
+
response = await self._make_request(
|
|
287
|
+
"GET",
|
|
288
|
+
f"/ocs/v2.php/apps/files_sharing/api/v1/shares/{share_id}",
|
|
289
|
+
headers=self._OCS_HEADERS,
|
|
290
|
+
)
|
|
291
|
+
data = response.json()
|
|
292
|
+
|
|
293
|
+
share_data = _ocs_data(data)
|
|
294
|
+
# The API returns a list with a single share, extract the first element
|
|
295
|
+
if isinstance(share_data, list) and len(share_data) > 0:
|
|
296
|
+
return share_data[0]
|
|
297
|
+
return share_data
|
|
298
|
+
|
|
299
|
+
async def list_shares(
|
|
300
|
+
self, path: str | None = None, shared_with_me: bool = False
|
|
301
|
+
) -> list[dict[str, Any]]:
|
|
302
|
+
"""List shares.
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
path: Optional path to filter shares for a specific file/folder
|
|
306
|
+
shared_with_me: If True, list shares shared with the current user
|
|
307
|
+
|
|
308
|
+
Returns:
|
|
309
|
+
List of share data
|
|
310
|
+
|
|
311
|
+
Raises:
|
|
312
|
+
HTTPStatusError: If the request fails
|
|
313
|
+
"""
|
|
314
|
+
params = {}
|
|
315
|
+
if path:
|
|
316
|
+
params["path"] = path
|
|
317
|
+
if shared_with_me:
|
|
318
|
+
params["shared_with_me"] = "true"
|
|
319
|
+
|
|
320
|
+
response = await self._make_request(
|
|
321
|
+
"GET",
|
|
322
|
+
"/ocs/v2.php/apps/files_sharing/api/v1/shares",
|
|
323
|
+
params=params,
|
|
324
|
+
headers=self._OCS_HEADERS,
|
|
325
|
+
)
|
|
326
|
+
data = response.json()
|
|
327
|
+
|
|
328
|
+
# Handle both single share and list of shares
|
|
329
|
+
shares_data = _ocs_data(data)
|
|
330
|
+
if isinstance(shares_data, dict):
|
|
331
|
+
return [shares_data]
|
|
332
|
+
return shares_data if shares_data else []
|
|
333
|
+
|
|
334
|
+
async def update_share(
|
|
335
|
+
self, share_id: int, permissions: int | None = None
|
|
336
|
+
) -> dict[str, Any]:
|
|
337
|
+
"""Update a share's permissions.
|
|
338
|
+
|
|
339
|
+
Args:
|
|
340
|
+
share_id: The share ID to update
|
|
341
|
+
permissions: New permissions value (see create_share for values)
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
Updated share data
|
|
345
|
+
|
|
346
|
+
Raises:
|
|
347
|
+
HTTPStatusError: If the request fails
|
|
348
|
+
"""
|
|
349
|
+
data = {}
|
|
350
|
+
if permissions is not None:
|
|
351
|
+
data["permissions"] = permissions
|
|
352
|
+
|
|
353
|
+
response = await self._make_request(
|
|
354
|
+
"PUT",
|
|
355
|
+
f"/ocs/v2.php/apps/files_sharing/api/v1/shares/{share_id}",
|
|
356
|
+
headers=self._OCS_HEADERS,
|
|
357
|
+
data=data,
|
|
358
|
+
)
|
|
359
|
+
result = response.json()
|
|
360
|
+
|
|
361
|
+
share_data = _ocs_data(result)
|
|
362
|
+
|
|
363
|
+
logger.info("Updated share %s", share_id)
|
|
364
|
+
return share_data
|