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
nextcloud_client/news.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""Client for Nextcloud News app operations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from enum import IntEnum
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .base import BaseNextcloudClient
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NewsItemType(IntEnum):
|
|
13
|
+
"""Type constants for News API item queries."""
|
|
14
|
+
|
|
15
|
+
FEED = 0 # Single feed
|
|
16
|
+
FOLDER = 1 # Folder and its feeds
|
|
17
|
+
STARRED = 2 # All starred items
|
|
18
|
+
ALL = 3 # All items
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class NewsClient(BaseNextcloudClient):
|
|
22
|
+
"""Client for Nextcloud News app operations."""
|
|
23
|
+
|
|
24
|
+
app_name = "news"
|
|
25
|
+
API_BASE = "/apps/news/api/v1-3"
|
|
26
|
+
|
|
27
|
+
# --- Folders ---
|
|
28
|
+
|
|
29
|
+
async def get_folders(self) -> list[dict[str, Any]]:
|
|
30
|
+
"""Get all folders."""
|
|
31
|
+
response = await self._make_request("GET", f"{self.API_BASE}/folders")
|
|
32
|
+
return response.json().get("folders", [])
|
|
33
|
+
|
|
34
|
+
async def create_folder(self, name: str) -> dict[str, Any]:
|
|
35
|
+
"""Create a new folder.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
name: Folder name
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
Created folder data
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
HTTPStatusError: 409 if folder name already exists,
|
|
45
|
+
422 if name is empty
|
|
46
|
+
"""
|
|
47
|
+
response = await self._make_request(
|
|
48
|
+
"POST", f"{self.API_BASE}/folders", json={"name": name}
|
|
49
|
+
)
|
|
50
|
+
folders = response.json().get("folders", [])
|
|
51
|
+
return folders[0] if folders else {}
|
|
52
|
+
|
|
53
|
+
async def rename_folder(self, folder_id: int, name: str) -> None:
|
|
54
|
+
"""Rename a folder.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
folder_id: Folder ID
|
|
58
|
+
name: New folder name
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
HTTPStatusError: 404 if folder not found, 409 if name exists
|
|
62
|
+
"""
|
|
63
|
+
await self._make_request(
|
|
64
|
+
"PUT", f"{self.API_BASE}/folders/{folder_id}", json={"name": name}
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
async def delete_folder(self, folder_id: int) -> None:
|
|
68
|
+
"""Delete a folder and all its feeds/items.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
folder_id: Folder ID
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
HTTPStatusError: 404 if folder not found
|
|
75
|
+
"""
|
|
76
|
+
await self._make_request("DELETE", f"{self.API_BASE}/folders/{folder_id}")
|
|
77
|
+
|
|
78
|
+
async def mark_folder_read(self, folder_id: int, newest_item_id: int) -> None:
|
|
79
|
+
"""Mark all items in a folder as read.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
folder_id: Folder ID
|
|
83
|
+
newest_item_id: ID of newest item to mark read (prevents marking
|
|
84
|
+
items user hasn't seen yet)
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
HTTPStatusError: 404 if folder not found
|
|
88
|
+
"""
|
|
89
|
+
await self._make_request(
|
|
90
|
+
"POST",
|
|
91
|
+
f"{self.API_BASE}/folders/{folder_id}/read",
|
|
92
|
+
json={"newestItemId": newest_item_id},
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# --- Feeds ---
|
|
96
|
+
|
|
97
|
+
async def get_feeds(self) -> dict[str, Any]:
|
|
98
|
+
"""Get all feeds with metadata.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
Dict with keys:
|
|
102
|
+
- feeds: List of feed objects
|
|
103
|
+
- starredCount: Number of starred items
|
|
104
|
+
- newestItemId: ID of newest item (omitted if no items)
|
|
105
|
+
"""
|
|
106
|
+
response = await self._make_request("GET", f"{self.API_BASE}/feeds")
|
|
107
|
+
return response.json()
|
|
108
|
+
|
|
109
|
+
async def create_feed(
|
|
110
|
+
self, url: str, folder_id: int | None = None
|
|
111
|
+
) -> dict[str, Any]:
|
|
112
|
+
"""Subscribe to a new feed.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
url: Feed URL
|
|
116
|
+
folder_id: Optional folder ID (None for root)
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
Created feed data
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
HTTPStatusError: 409 if feed already exists, 422 if URL is invalid
|
|
123
|
+
"""
|
|
124
|
+
body: dict[str, Any] = {"url": url}
|
|
125
|
+
if folder_id is not None:
|
|
126
|
+
body["folderId"] = folder_id
|
|
127
|
+
response = await self._make_request("POST", f"{self.API_BASE}/feeds", json=body)
|
|
128
|
+
data = response.json()
|
|
129
|
+
feeds = data.get("feeds", [])
|
|
130
|
+
return feeds[0] if feeds else {}
|
|
131
|
+
|
|
132
|
+
async def delete_feed(self, feed_id: int) -> None:
|
|
133
|
+
"""Unsubscribe from a feed (deletes all items).
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
feed_id: Feed ID
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
HTTPStatusError: 404 if feed not found
|
|
140
|
+
"""
|
|
141
|
+
await self._make_request("DELETE", f"{self.API_BASE}/feeds/{feed_id}")
|
|
142
|
+
|
|
143
|
+
async def move_feed(self, feed_id: int, folder_id: int | None) -> None:
|
|
144
|
+
"""Move a feed to a different folder.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
feed_id: Feed ID
|
|
148
|
+
folder_id: Target folder ID (None for root)
|
|
149
|
+
|
|
150
|
+
Raises:
|
|
151
|
+
HTTPStatusError: 404 if feed not found
|
|
152
|
+
"""
|
|
153
|
+
await self._make_request(
|
|
154
|
+
"POST",
|
|
155
|
+
f"{self.API_BASE}/feeds/{feed_id}/move",
|
|
156
|
+
json={"folderId": folder_id},
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
async def rename_feed(self, feed_id: int, title: str) -> None:
|
|
160
|
+
"""Rename a feed.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
feed_id: Feed ID
|
|
164
|
+
title: New feed title
|
|
165
|
+
|
|
166
|
+
Raises:
|
|
167
|
+
HTTPStatusError: 404 if feed not found
|
|
168
|
+
"""
|
|
169
|
+
await self._make_request(
|
|
170
|
+
"POST",
|
|
171
|
+
f"{self.API_BASE}/feeds/{feed_id}/rename",
|
|
172
|
+
json={"feedTitle": title},
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def mark_feed_read(self, feed_id: int, newest_item_id: int) -> None:
|
|
176
|
+
"""Mark all items in a feed as read.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
feed_id: Feed ID
|
|
180
|
+
newest_item_id: ID of newest item to mark read
|
|
181
|
+
|
|
182
|
+
Raises:
|
|
183
|
+
HTTPStatusError: 404 if feed not found
|
|
184
|
+
"""
|
|
185
|
+
await self._make_request(
|
|
186
|
+
"POST",
|
|
187
|
+
f"{self.API_BASE}/feeds/{feed_id}/read",
|
|
188
|
+
json={"newestItemId": newest_item_id},
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# --- Items ---
|
|
192
|
+
|
|
193
|
+
async def get_items(
|
|
194
|
+
self,
|
|
195
|
+
batch_size: int = 50,
|
|
196
|
+
offset: int = 0,
|
|
197
|
+
type_: int = NewsItemType.ALL,
|
|
198
|
+
id_: int = 0,
|
|
199
|
+
get_read: bool = True,
|
|
200
|
+
oldest_first: bool = False,
|
|
201
|
+
) -> list[dict[str, Any]]:
|
|
202
|
+
"""Get items (articles) with filtering.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
batch_size: Number of items to return (-1 for all)
|
|
206
|
+
offset: Item ID to start after (for pagination)
|
|
207
|
+
type_: Item type filter (NewsItemType)
|
|
208
|
+
id_: Feed/folder ID (ignored for STARRED/ALL types)
|
|
209
|
+
get_read: Include read items
|
|
210
|
+
oldest_first: Sort oldest first instead of newest
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
List of item objects
|
|
214
|
+
"""
|
|
215
|
+
params: dict[str, Any] = {
|
|
216
|
+
"batchSize": batch_size,
|
|
217
|
+
"offset": offset,
|
|
218
|
+
"type": type_,
|
|
219
|
+
"id": id_,
|
|
220
|
+
"getRead": str(get_read).lower(),
|
|
221
|
+
"oldestFirst": str(oldest_first).lower(),
|
|
222
|
+
}
|
|
223
|
+
response = await self._make_request(
|
|
224
|
+
"GET", f"{self.API_BASE}/items", params=params
|
|
225
|
+
)
|
|
226
|
+
return response.json().get("items", [])
|
|
227
|
+
|
|
228
|
+
async def get_item(self, item_id: int) -> dict[str, Any]:
|
|
229
|
+
"""Get a specific item by ID.
|
|
230
|
+
|
|
231
|
+
Note: The News API doesn't have a direct single-item endpoint,
|
|
232
|
+
so we fetch all items and filter. For efficiency, consider
|
|
233
|
+
caching or using get_items with specific feed if known.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
item_id: Item ID
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
Item data
|
|
240
|
+
|
|
241
|
+
Raises:
|
|
242
|
+
ValueError: If item not found
|
|
243
|
+
"""
|
|
244
|
+
# Fetch all items and find the one we need
|
|
245
|
+
# This is inefficient but the API doesn't provide a direct endpoint
|
|
246
|
+
items = await self.get_items(batch_size=-1, get_read=True)
|
|
247
|
+
for item in items:
|
|
248
|
+
if item.get("id") == item_id:
|
|
249
|
+
return item
|
|
250
|
+
raise ValueError(f"Item {item_id} not found")
|
|
251
|
+
|
|
252
|
+
async def get_updated_items(
|
|
253
|
+
self,
|
|
254
|
+
last_modified: int,
|
|
255
|
+
type_: int = NewsItemType.ALL,
|
|
256
|
+
id_: int = 0,
|
|
257
|
+
) -> list[dict[str, Any]]:
|
|
258
|
+
"""Get items modified since a timestamp (for delta sync).
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
last_modified: Unix timestamp (seconds or microseconds)
|
|
262
|
+
type_: Item type filter
|
|
263
|
+
id_: Feed/folder ID
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
List of modified items (includes deleted items)
|
|
267
|
+
"""
|
|
268
|
+
params: dict[str, Any] = {
|
|
269
|
+
"lastModified": last_modified,
|
|
270
|
+
"type": type_,
|
|
271
|
+
"id": id_,
|
|
272
|
+
}
|
|
273
|
+
response = await self._make_request(
|
|
274
|
+
"GET", f"{self.API_BASE}/items/updated", params=params
|
|
275
|
+
)
|
|
276
|
+
return response.json().get("items", [])
|
|
277
|
+
|
|
278
|
+
async def mark_item_read(self, item_id: int) -> None:
|
|
279
|
+
"""Mark a single item as read.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
item_id: Item ID
|
|
283
|
+
|
|
284
|
+
Raises:
|
|
285
|
+
HTTPStatusError: 404 if item not found
|
|
286
|
+
"""
|
|
287
|
+
await self._make_request("POST", f"{self.API_BASE}/items/{item_id}/read")
|
|
288
|
+
|
|
289
|
+
async def mark_item_unread(self, item_id: int) -> None:
|
|
290
|
+
"""Mark a single item as unread.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
item_id: Item ID
|
|
294
|
+
|
|
295
|
+
Raises:
|
|
296
|
+
HTTPStatusError: 404 if item not found
|
|
297
|
+
"""
|
|
298
|
+
await self._make_request("POST", f"{self.API_BASE}/items/{item_id}/unread")
|
|
299
|
+
|
|
300
|
+
async def star_item(self, item_id: int) -> None:
|
|
301
|
+
"""Star (favorite) a single item.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
item_id: Item ID
|
|
305
|
+
|
|
306
|
+
Raises:
|
|
307
|
+
HTTPStatusError: 404 if item not found
|
|
308
|
+
"""
|
|
309
|
+
await self._make_request("POST", f"{self.API_BASE}/items/{item_id}/star")
|
|
310
|
+
|
|
311
|
+
async def unstar_item(self, item_id: int) -> None:
|
|
312
|
+
"""Unstar a single item.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
item_id: Item ID
|
|
316
|
+
|
|
317
|
+
Raises:
|
|
318
|
+
HTTPStatusError: 404 if item not found
|
|
319
|
+
"""
|
|
320
|
+
await self._make_request("POST", f"{self.API_BASE}/items/{item_id}/unstar")
|
|
321
|
+
|
|
322
|
+
async def mark_items_read(self, item_ids: list[int]) -> None:
|
|
323
|
+
"""Mark multiple items as read.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
item_ids: List of item IDs
|
|
327
|
+
"""
|
|
328
|
+
await self._make_request(
|
|
329
|
+
"POST", f"{self.API_BASE}/items/read/multiple", json={"itemIds": item_ids}
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
async def mark_items_unread(self, item_ids: list[int]) -> None:
|
|
333
|
+
"""Mark multiple items as unread.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
item_ids: List of item IDs
|
|
337
|
+
"""
|
|
338
|
+
await self._make_request(
|
|
339
|
+
"POST",
|
|
340
|
+
f"{self.API_BASE}/items/unread/multiple",
|
|
341
|
+
json={"itemIds": item_ids},
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
async def star_items(self, item_ids: list[int]) -> None:
|
|
345
|
+
"""Star multiple items.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
item_ids: List of item IDs
|
|
349
|
+
"""
|
|
350
|
+
await self._make_request(
|
|
351
|
+
"POST", f"{self.API_BASE}/items/star/multiple", json={"itemIds": item_ids}
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
async def unstar_items(self, item_ids: list[int]) -> None:
|
|
355
|
+
"""Unstar multiple items.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
item_ids: List of item IDs
|
|
359
|
+
"""
|
|
360
|
+
await self._make_request(
|
|
361
|
+
"POST",
|
|
362
|
+
f"{self.API_BASE}/items/unstar/multiple",
|
|
363
|
+
json={"itemIds": item_ids},
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
async def mark_all_read(self, newest_item_id: int) -> None:
|
|
367
|
+
"""Mark all items as read.
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
newest_item_id: ID of newest item to mark read
|
|
371
|
+
"""
|
|
372
|
+
await self._make_request(
|
|
373
|
+
"POST", f"{self.API_BASE}/items/read", json={"newestItemId": newest_item_id}
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
# --- Status ---
|
|
377
|
+
|
|
378
|
+
async def get_status(self) -> dict[str, Any]:
|
|
379
|
+
"""Get News app status and configuration.
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
Dict with version and warnings
|
|
383
|
+
"""
|
|
384
|
+
response = await self._make_request("GET", f"{self.API_BASE}/status")
|
|
385
|
+
return response.json()
|
|
386
|
+
|
|
387
|
+
async def get_version(self) -> str:
|
|
388
|
+
"""Get News app version.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
Version string (e.g., "25.0.0")
|
|
392
|
+
"""
|
|
393
|
+
response = await self._make_request("GET", f"{self.API_BASE}/version")
|
|
394
|
+
return response.json().get("version", "")
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Client for Nextcloud Notes app operations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any, AsyncIterator, Dict, Optional
|
|
5
|
+
|
|
6
|
+
from .base import BaseNextcloudClient
|
|
7
|
+
from .webdav import WebDAVClient
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _expect_note_object(payload: Any, *, operation: str) -> Dict[str, Any]:
|
|
13
|
+
"""Coerce a Notes API single-note response into a dict.
|
|
14
|
+
|
|
15
|
+
Notes v5.0.0 has a catch-all route (``notes_api#fail``) that returns ``[]``
|
|
16
|
+
as JSON for unmatched paths, and a few edge cases where the response is a
|
|
17
|
+
list-wrapped object instead of a bare object — see issue #730. Without this
|
|
18
|
+
guard, callers hit a cryptic Pydantic ``"argument after ** must be a mapping,
|
|
19
|
+
not list"`` from ``Note(**payload)``.
|
|
20
|
+
|
|
21
|
+
Returns the dict unchanged. If the payload is a single-element list, returns
|
|
22
|
+
the inner dict. Anything else (empty list, list of multiple, non-dict) raises
|
|
23
|
+
a clear ``ValueError`` so the failure mode is obvious in logs.
|
|
24
|
+
"""
|
|
25
|
+
if isinstance(payload, dict):
|
|
26
|
+
return payload
|
|
27
|
+
if isinstance(payload, list):
|
|
28
|
+
if len(payload) == 1 and isinstance(payload[0], dict):
|
|
29
|
+
logger.warning(
|
|
30
|
+
"Notes API returned a single-element list for %s; unwrapping. "
|
|
31
|
+
"This is a Notes app v5.0.0 quirk — see #730.",
|
|
32
|
+
operation,
|
|
33
|
+
)
|
|
34
|
+
return payload[0]
|
|
35
|
+
raise ValueError(
|
|
36
|
+
f"{operation}: Notes API returned a list-shaped payload "
|
|
37
|
+
f"({len(payload)} elements) where a single note object was expected. "
|
|
38
|
+
f"This typically means the request was routed to the catch-all "
|
|
39
|
+
f"notes_api#fail handler (e.g. unmatched URL or wrong API version). "
|
|
40
|
+
f"Verify the Notes app version and URL prefix (#732)."
|
|
41
|
+
)
|
|
42
|
+
raise ValueError(
|
|
43
|
+
f"{operation}: Notes API returned an unexpected payload type "
|
|
44
|
+
f"({type(payload).__name__}) where a single note object was expected."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class NotesClient(BaseNextcloudClient):
|
|
49
|
+
"""Client for Nextcloud Notes app operations."""
|
|
50
|
+
|
|
51
|
+
app_name = "notes"
|
|
52
|
+
|
|
53
|
+
async def get_settings(self) -> Dict[str, Any]:
|
|
54
|
+
"""Get Notes app settings."""
|
|
55
|
+
response = await self._make_request("GET", "/apps/notes/api/v1/settings")
|
|
56
|
+
return response.json()
|
|
57
|
+
|
|
58
|
+
async def get_all_notes(
|
|
59
|
+
self, prune_before: Optional[int] = None
|
|
60
|
+
) -> AsyncIterator[Dict[str, Any]]:
|
|
61
|
+
"""Get all notes, yielding them one at a time.
|
|
62
|
+
|
|
63
|
+
The Notes API returns changed notes with full data in chunks, and ALL note IDs
|
|
64
|
+
(with only 'id' field) in the last chunk for deletion detection. This causes
|
|
65
|
+
duplicates which we handle by tracking seen IDs (first occurrence with full
|
|
66
|
+
data is kept, later pruned duplicates are skipped).
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
prune_before: Optional Unix timestamp. Notes unchanged since this time
|
|
70
|
+
are pruned (only 'id' field returned in last chunk).
|
|
71
|
+
Reduces data transfer for large note collections.
|
|
72
|
+
|
|
73
|
+
Yields:
|
|
74
|
+
Note dictionaries with full data (deduplicated).
|
|
75
|
+
"""
|
|
76
|
+
cursor = ""
|
|
77
|
+
seen_ids: set[int] = set()
|
|
78
|
+
|
|
79
|
+
while True:
|
|
80
|
+
params: Dict[str, Any] = {"chunkSize": 100}
|
|
81
|
+
if cursor:
|
|
82
|
+
params["chunkCursor"] = cursor
|
|
83
|
+
if prune_before is not None:
|
|
84
|
+
params["pruneBefore"] = prune_before
|
|
85
|
+
|
|
86
|
+
response = await self._make_request(
|
|
87
|
+
"GET",
|
|
88
|
+
"/apps/notes/api/v1/notes",
|
|
89
|
+
params=params,
|
|
90
|
+
)
|
|
91
|
+
response_data = response.json()
|
|
92
|
+
|
|
93
|
+
for note in response_data:
|
|
94
|
+
note_id = note.get("id")
|
|
95
|
+
if note_id is None:
|
|
96
|
+
logger.warning("Skipping note without ID: %s", note)
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
# Skip duplicates (API returns all IDs in last chunk for deletion detection)
|
|
100
|
+
if note_id in seen_ids:
|
|
101
|
+
logger.debug(
|
|
102
|
+
"Skipping duplicate note %s (pruned version in last chunk)",
|
|
103
|
+
note_id,
|
|
104
|
+
)
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
seen_ids.add(note_id)
|
|
108
|
+
yield note
|
|
109
|
+
|
|
110
|
+
if "X-Notes-Chunk-Cursor" not in response.headers:
|
|
111
|
+
break
|
|
112
|
+
cursor = response.headers["X-Notes-Chunk-Cursor"]
|
|
113
|
+
|
|
114
|
+
async def get_note(self, note_id: int) -> Dict[str, Any]:
|
|
115
|
+
"""Get a specific note by ID."""
|
|
116
|
+
response = await self._make_request(
|
|
117
|
+
"GET", f"/apps/notes/api/v1/notes/{note_id}"
|
|
118
|
+
)
|
|
119
|
+
return _expect_note_object(response.json(), operation="get_note")
|
|
120
|
+
|
|
121
|
+
async def create_note(
|
|
122
|
+
self,
|
|
123
|
+
title: Optional[str] = None,
|
|
124
|
+
content: Optional[str] = None,
|
|
125
|
+
category: Optional[str] = None,
|
|
126
|
+
) -> Dict[str, Any]:
|
|
127
|
+
"""Create a new note."""
|
|
128
|
+
body = {}
|
|
129
|
+
if title:
|
|
130
|
+
body["title"] = title
|
|
131
|
+
if content:
|
|
132
|
+
body["content"] = content
|
|
133
|
+
if category:
|
|
134
|
+
body["category"] = category
|
|
135
|
+
|
|
136
|
+
response = await self._make_request(
|
|
137
|
+
"POST", "/apps/notes/api/v1/notes", json=body
|
|
138
|
+
)
|
|
139
|
+
return _expect_note_object(response.json(), operation="create_note")
|
|
140
|
+
|
|
141
|
+
async def update(
|
|
142
|
+
self,
|
|
143
|
+
note_id: int,
|
|
144
|
+
etag: str,
|
|
145
|
+
title: Optional[str] = None,
|
|
146
|
+
content: Optional[str] = None,
|
|
147
|
+
category: Optional[str] = None,
|
|
148
|
+
) -> Dict[str, Any]:
|
|
149
|
+
"""Update an existing note."""
|
|
150
|
+
# Get current note details to check for category change
|
|
151
|
+
old_note = None
|
|
152
|
+
try:
|
|
153
|
+
if category is not None:
|
|
154
|
+
old_note = await self.get_note(note_id)
|
|
155
|
+
old_category = old_note.get("category", "")
|
|
156
|
+
logger.info("Current category for note %s: '%s'", note_id, old_category)
|
|
157
|
+
except Exception as e:
|
|
158
|
+
logger.warning(
|
|
159
|
+
"Could not fetch current note %s details before update: %s", note_id, e
|
|
160
|
+
)
|
|
161
|
+
old_note = None
|
|
162
|
+
|
|
163
|
+
# Prepare update body
|
|
164
|
+
body = {}
|
|
165
|
+
if title:
|
|
166
|
+
body["title"] = title
|
|
167
|
+
if content:
|
|
168
|
+
body["content"] = content
|
|
169
|
+
if category:
|
|
170
|
+
body["category"] = category
|
|
171
|
+
|
|
172
|
+
logger.info(
|
|
173
|
+
"Attempting to update note %s with etag %s. Body: %s", note_id, etag, body
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
response = await self._make_request(
|
|
177
|
+
"PUT",
|
|
178
|
+
f"/apps/notes/api/v1/notes/{note_id}",
|
|
179
|
+
json=body,
|
|
180
|
+
headers={"If-Match": f'"{etag}"'},
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
logger.info(
|
|
184
|
+
"Update response for note %s: Status %s", note_id, response.status_code
|
|
185
|
+
)
|
|
186
|
+
updated_note = _expect_note_object(response.json(), operation="update_note")
|
|
187
|
+
|
|
188
|
+
# Check for category change and cleanup old attachment directory if needed
|
|
189
|
+
if (
|
|
190
|
+
old_note
|
|
191
|
+
and category is not None
|
|
192
|
+
and old_note.get("category", "") != category
|
|
193
|
+
):
|
|
194
|
+
logger.info(
|
|
195
|
+
"Category changed from '%s' to '%s' - cleaning up old attachment directory",
|
|
196
|
+
old_note.get("category", ""),
|
|
197
|
+
category,
|
|
198
|
+
)
|
|
199
|
+
try:
|
|
200
|
+
webdav_client = WebDAVClient(self._client, self.username)
|
|
201
|
+
await webdav_client.cleanup_old_attachment_directory(
|
|
202
|
+
note_id=note_id, old_category=old_note.get("category", "")
|
|
203
|
+
)
|
|
204
|
+
except Exception as e:
|
|
205
|
+
logger.error(
|
|
206
|
+
"Error cleaning up old attachment directory for note %s: %s",
|
|
207
|
+
note_id,
|
|
208
|
+
e,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return updated_note
|
|
212
|
+
|
|
213
|
+
async def delete_note(self, note_id: int) -> Dict[str, Any]:
|
|
214
|
+
"""Delete a note and its attachments."""
|
|
215
|
+
# Fetch note details first to get category for cleanup
|
|
216
|
+
try:
|
|
217
|
+
note_details = await self.get_note(note_id)
|
|
218
|
+
category = note_details.get("category", "")
|
|
219
|
+
|
|
220
|
+
# Determine potential categories for cleanup
|
|
221
|
+
potential_categories = []
|
|
222
|
+
if category:
|
|
223
|
+
potential_categories.append(category)
|
|
224
|
+
if category != "":
|
|
225
|
+
potential_categories.append("") # Empty category
|
|
226
|
+
|
|
227
|
+
logger.info(
|
|
228
|
+
"Note %s has category: '%s', will check attachment directories in: %s",
|
|
229
|
+
note_id,
|
|
230
|
+
category,
|
|
231
|
+
potential_categories,
|
|
232
|
+
)
|
|
233
|
+
except Exception as e:
|
|
234
|
+
logger.warning(
|
|
235
|
+
"Could not fetch note %s details before deletion: %s", note_id, e
|
|
236
|
+
)
|
|
237
|
+
potential_categories = ["", "Unknown"] # Try common categories
|
|
238
|
+
|
|
239
|
+
# Delete the note via API
|
|
240
|
+
logger.info("Deleting note %s via API", note_id)
|
|
241
|
+
response = await self._make_request(
|
|
242
|
+
"DELETE", f"/apps/notes/api/v1/notes/{note_id}"
|
|
243
|
+
)
|
|
244
|
+
logger.info("Note %s deleted successfully via API", note_id)
|
|
245
|
+
json_response = response.json()
|
|
246
|
+
|
|
247
|
+
# Clean up attachment directories
|
|
248
|
+
try:
|
|
249
|
+
webdav_client = WebDAVClient(self._client, self.username)
|
|
250
|
+
|
|
251
|
+
for cat in potential_categories:
|
|
252
|
+
try:
|
|
253
|
+
await webdav_client.cleanup_note_attachments(note_id, cat)
|
|
254
|
+
except Exception as e:
|
|
255
|
+
logger.warning(
|
|
256
|
+
"Failed to cleanup attachments for category '%s': %s", cat, e
|
|
257
|
+
)
|
|
258
|
+
except Exception as e:
|
|
259
|
+
logger.warning("Error during attachment cleanup: %s", e)
|
|
260
|
+
|
|
261
|
+
return json_response
|
|
262
|
+
|
|
263
|
+
async def append_content(self, note_id: int, content: str) -> Dict[str, Any]:
|
|
264
|
+
"""Append content to an existing note with a separator."""
|
|
265
|
+
logger.info("Appending content to note %s", note_id)
|
|
266
|
+
|
|
267
|
+
# Get current note
|
|
268
|
+
current_note = await self.get_note(note_id)
|
|
269
|
+
|
|
270
|
+
# Use fixed separator for consistency
|
|
271
|
+
separator = "\n---\n"
|
|
272
|
+
|
|
273
|
+
# Combine content
|
|
274
|
+
existing_content = current_note.get("content", "")
|
|
275
|
+
if existing_content:
|
|
276
|
+
new_content = existing_content + separator + content
|
|
277
|
+
else:
|
|
278
|
+
new_content = content # No separator needed for empty notes
|
|
279
|
+
|
|
280
|
+
logger.info(
|
|
281
|
+
"Combining existing content (%s chars) with new content (%s chars)",
|
|
282
|
+
len(existing_content),
|
|
283
|
+
len(content),
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
# Update with combined content
|
|
287
|
+
return await self.update(
|
|
288
|
+
note_id=note_id,
|
|
289
|
+
etag=current_note["etag"],
|
|
290
|
+
content=new_content,
|
|
291
|
+
title=None, # Keep existing title
|
|
292
|
+
category=None, # Keep existing category
|
|
293
|
+
)
|