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,150 @@
1
+ """Client for the Nextcloud Shopping List app (``shopping_list``).
2
+
3
+ Covers the lists and items surface of the app's OCS API. Shop areas, tags,
4
+ shares and the public-link API are deliberately not wrapped yet — nothing asks
5
+ for them, and the item payload carries ``shopAreaId`` through untouched, so the
6
+ app's own area auto-detection keeps working.
7
+
8
+ See https://github.com/otherworld-dev/Shopping-List.
9
+ """
10
+
11
+ import logging
12
+ from typing import Any
13
+
14
+ from .base import BaseNextcloudClient
15
+ from .ocs import OCS_REQUEST_HEADERS
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ShoppingListClient(BaseNextcloudClient):
21
+ """Client for Nextcloud Shopping List app operations."""
22
+
23
+ app_name = "shopping_list"
24
+
25
+ API_BASE = "/ocs/v2.php/apps/shopping_list/api/v1"
26
+
27
+ # Own copy -- see the note in GroupsClient.
28
+ _OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
29
+
30
+ async def _ocs(self, method: str, path: str, **kwargs: Any) -> Any:
31
+ """Issue an OCS request and hand back ``ocs.data``.
32
+
33
+ Every route in this app answers with the same envelope, and
34
+ ``/ocs/v2.php`` mirrors the OCS code onto the HTTP status, which
35
+ ``_make_request`` already raises on — so unwrapping is all that is left
36
+ to do. The delete/clear routes answer 204 with an empty body, hence the
37
+ guard.
38
+ """
39
+ response = await self._make_request(
40
+ method, f"{self.API_BASE}{path}", headers=self._OCS_HEADERS, **kwargs
41
+ )
42
+ if not response.content:
43
+ return None
44
+ return response.json()["ocs"]["data"]
45
+
46
+ # --- Lists ---
47
+
48
+ async def get_lists(self) -> list[dict[str, Any]]:
49
+ """Get every list the user owns or has had shared with them."""
50
+ return await self._ocs("GET", "/lists")
51
+
52
+ async def get_list(self, list_id: int) -> dict[str, Any]:
53
+ """Get a single list.
54
+
55
+ Raises:
56
+ HTTPStatusError: 404 if the list does not exist or is not shared
57
+ with the user.
58
+ """
59
+ return await self._ocs("GET", f"/lists/{list_id}")
60
+
61
+ async def create_list(self, title: str) -> dict[str, Any]:
62
+ """Create a new list owned by the user."""
63
+ return await self._ocs("POST", "/lists", json={"title": title})
64
+
65
+ async def update_list(self, list_id: int, title: str) -> dict[str, Any]:
66
+ """Rename a list.
67
+
68
+ Raises:
69
+ HTTPStatusError: 404 if not found, 403 without write access.
70
+ """
71
+ return await self._ocs("PUT", f"/lists/{list_id}", json={"title": title})
72
+
73
+ async def delete_list(self, list_id: int) -> None:
74
+ """Delete a list and everything on it.
75
+
76
+ Raises:
77
+ HTTPStatusError: 404 if not found, 403 if the user is not the owner.
78
+ """
79
+ await self._ocs("DELETE", f"/lists/{list_id}")
80
+
81
+ # --- Items ---
82
+
83
+ async def get_items(self, list_id: int) -> list[dict[str, Any]]:
84
+ """Get every item on a list, checked ones included."""
85
+ return await self._ocs("GET", f"/lists/{list_id}/items")
86
+
87
+ async def add_item(
88
+ self,
89
+ list_id: int,
90
+ name: str,
91
+ quantity: str | None = None,
92
+ unit: str | None = None,
93
+ shop_area_id: int | None = None,
94
+ checked: bool = False,
95
+ ) -> dict[str, Any]:
96
+ """Add an item to a list.
97
+
98
+ Args:
99
+ list_id: List to add to.
100
+ name: Item name, e.g. "flour".
101
+ quantity: Free-text amount, e.g. "2". Defaults to "1" server-side.
102
+ unit: Free-text unit, e.g. "cups".
103
+ shop_area_id: Shop area to file the item under. Left unset, the app
104
+ assigns one from its keyword mappings.
105
+ checked: Add the item already ticked off.
106
+
107
+ Raises:
108
+ HTTPStatusError: 404 if the list is missing, 403 without write
109
+ access.
110
+ """
111
+ payload: dict[str, Any] = {"name": name, "checked": checked}
112
+ if quantity is not None:
113
+ payload["quantity"] = quantity
114
+ if unit is not None:
115
+ payload["unit"] = unit
116
+ if shop_area_id is not None:
117
+ payload["shopAreaId"] = shop_area_id
118
+ return await self._ocs("POST", f"/lists/{list_id}/items", json=payload)
119
+
120
+ async def update_item(
121
+ self, list_id: int, item_id: int, fields: dict[str, Any]
122
+ ) -> dict[str, Any]:
123
+ """Update an item's fields.
124
+
125
+ Args:
126
+ fields: Only the keys present are changed — the app reads the
127
+ request params rather than a full entity, so an omitted field
128
+ keeps its value while an explicit ``None`` clears it.
129
+ """
130
+ return await self._ocs("PUT", f"/lists/{list_id}/items/{item_id}", json=fields)
131
+
132
+ async def check_item(
133
+ self, list_id: int, item_id: int, checked: bool
134
+ ) -> dict[str, Any]:
135
+ """Tick an item off, or put it back on the list."""
136
+ return await self._ocs(
137
+ "PUT", f"/lists/{list_id}/items/{item_id}/check", json={"checked": checked}
138
+ )
139
+
140
+ async def delete_item(self, list_id: int, item_id: int) -> None:
141
+ """Delete a single item."""
142
+ await self._ocs("DELETE", f"/lists/{list_id}/items/{item_id}")
143
+
144
+ async def clear_checked_items(self, list_id: int) -> None:
145
+ """Delete every ticked-off item on a list."""
146
+ await self._ocs("DELETE", f"/lists/{list_id}/items/checked")
147
+
148
+ async def uncheck_all_items(self, list_id: int) -> None:
149
+ """Put every ticked-off item on a list back into the open section."""
150
+ await self._ocs("POST", f"/lists/{list_id}/items/uncheck-all")
@@ -0,0 +1,146 @@
1
+ """Client for Nextcloud Tables app operations."""
2
+
3
+ import logging
4
+ from typing import Any, Dict, List
5
+
6
+ from .base import BaseNextcloudClient
7
+ from .ocs import OCS_REQUEST_HEADERS
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class TablesClient(BaseNextcloudClient):
13
+ """Client for Nextcloud Tables app operations."""
14
+
15
+ app_name = "tables"
16
+
17
+ # Own copy -- see the note in GroupsClient.
18
+ _OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
19
+
20
+ async def list_tables(self) -> List[Dict[str, Any]]:
21
+ """List all tables available to the user."""
22
+ response = await self._make_request(
23
+ "GET",
24
+ "/ocs/v2.php/apps/tables/api/2/tables",
25
+ headers=self._OCS_HEADERS,
26
+ )
27
+ result = response.json()
28
+ return result["ocs"]["data"]
29
+
30
+ async def get_table_schema(self, table_id: int) -> Dict[str, Any]:
31
+ """Get the schema/structure of a specific table including columns and views."""
32
+ # Using v1 API as v2 schema endpoint had issues during testing
33
+ response = await self._make_request(
34
+ "GET", f"/apps/tables/api/1/tables/{table_id}/scheme"
35
+ )
36
+ return response.json()
37
+
38
+ async def get_table_rows(
39
+ self, table_id: int, limit: int | None = None, offset: int | None = None
40
+ ) -> list[dict[str, Any]]:
41
+ """Read rows from a table with optional pagination."""
42
+ return await self._get_rows(
43
+ f"/apps/tables/api/1/tables/{table_id}/rows", limit, offset
44
+ )
45
+
46
+ async def get_view_rows(
47
+ self, view_id: int, limit: int | None = None, offset: int | None = None
48
+ ) -> list[dict[str, Any]]:
49
+ """Read rows of a view, with the view's filters and sorting applied."""
50
+ return await self._get_rows(
51
+ f"/apps/tables/api/1/views/{view_id}/rows", limit, offset
52
+ )
53
+
54
+ async def _get_rows(
55
+ self, path: str, limit: int | None, offset: int | None
56
+ ) -> list[dict[str, Any]]:
57
+ params = {
58
+ k: v for k, v in (("limit", limit), ("offset", offset)) if v is not None
59
+ }
60
+ response = await self._make_request("GET", path, params=params)
61
+ return response.json()
62
+
63
+ async def get_row(self, row_id: int) -> dict[str, Any]:
64
+ """Get a single row by ID."""
65
+ response = await self._make_request("GET", f"/apps/tables/api/1/rows/{row_id}")
66
+ return response.json()
67
+
68
+ async def create_row(self, table_id: int, data: Dict[str, Any]) -> Dict[str, Any]:
69
+ """Insert a new row into a table.
70
+
71
+ Args:
72
+ table_id: ID of the table to insert into
73
+ data: Dictionary mapping column IDs to values, e.g. {1: "text", 2: 42}
74
+ """
75
+ # Transform data to API format: {"data": {"1": "text", "2": 42}}
76
+ api_data = {str(k): v for k, v in data.items()}
77
+
78
+ response = await self._make_request(
79
+ "POST",
80
+ f"/ocs/v2.php/apps/tables/api/2/tables/{table_id}/rows",
81
+ headers=self._OCS_HEADERS,
82
+ json={"data": api_data},
83
+ )
84
+ result = response.json()
85
+ return result["ocs"]["data"]
86
+
87
+ async def update_row(self, row_id: int, data: Dict[str, Any]) -> Dict[str, Any]:
88
+ """Update an existing row in a table.
89
+
90
+ Args:
91
+ row_id: ID of the row to update
92
+ data: Dictionary mapping column IDs to new values, e.g. {1: "new text", 2: 99}
93
+ """
94
+ # Transform data to API format for v1 endpoint
95
+ api_data = {str(k): v for k, v in data.items()}
96
+
97
+ response = await self._make_request(
98
+ "PUT",
99
+ f"/apps/tables/api/1/rows/{row_id}",
100
+ json={"data": api_data},
101
+ )
102
+ return response.json()
103
+
104
+ async def delete_row(self, row_id: int) -> Dict[str, Any]:
105
+ """Delete a row from a table."""
106
+ response = await self._make_request(
107
+ "DELETE", f"/apps/tables/api/1/rows/{row_id}"
108
+ )
109
+ return response.json()
110
+
111
+ def transform_row_data(
112
+ self, rows: List[Dict[str, Any]], columns: List[Dict[str, Any]]
113
+ ) -> List[Dict[str, Any]]:
114
+ """Transform raw row data into more readable format using column names.
115
+
116
+ Args:
117
+ rows: Raw row data from the API
118
+ columns: Column definitions from table schema
119
+
120
+ Returns:
121
+ List of rows with column names as keys instead of column IDs
122
+ """
123
+ # Create mapping from column ID to column title
124
+ column_map = {col["id"]: col["title"] for col in columns}
125
+
126
+ transformed_rows = []
127
+ for row in rows:
128
+ transformed_row = {
129
+ "id": row["id"],
130
+ "tableId": row["tableId"],
131
+ "createdBy": row["createdBy"],
132
+ "createdAt": row["createdAt"],
133
+ "lastEditBy": row["lastEditBy"],
134
+ "lastEditAt": row["lastEditAt"],
135
+ "data": {},
136
+ }
137
+
138
+ # Transform data array to column_name: value mapping
139
+ for item in row["data"]:
140
+ column_id = item["columnId"]
141
+ column_name = column_map.get(column_id, f"column_{column_id}")
142
+ transformed_row["data"][column_name] = item["value"]
143
+
144
+ transformed_rows.append(transformed_row)
145
+
146
+ return transformed_rows