Skip to content

Commit 3a01c16

Browse files
authored
Clean-up/Refactoring of old code (#177)
_Because initially the project was written for a different AppAPI authentication, where all transmitted data was signed - there was a lot of unnecessary code left._ This pull request will cover it all, total refactoring and simplification of the code. **After this, it will be possible to make public methods for communicating with Nextcloud, which would make it easier to connect third-party packages.** **It is also necessary to clean up the code before adding asynchronous methods.** Changes proposed in this pull request: * set `AUTHORIZATION-APP-API` header with help of `event_hook` * set default `timeout` during `httpx.adapter` creation * set `base_url` during `httpx.adapter` creation * download_directory_as_zip: directly call `session.adapter.stream` (removed `_session.get_stream`) * all DAV methods now directly call `_session.adapter_dav.XXX` (removed `_session.dav` / `_session.dav_stream`) * removed `_session.request` and `_sessions.request_json` - instead directly call `session.adapter` * `response_headers` are now set with help of `httpx.event_hooks` * other internal code refactoring --------- Signed-off-by: Alexander Piskun <bigcat88@icloud.com>
1 parent 695b5a5 commit 3a01c16

25 files changed

+317
-472
lines changed

nc_py_api/_exceptions.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Exceptions for the Nextcloud API."""
22

3-
from httpx import codes
3+
from httpx import Response, codes
44

55

66
class NextcloudException(Exception):
@@ -42,21 +42,24 @@ def __init__(self, reason="Missing capability", info: str = ""):
4242
super().__init__(412, reason=reason, info=info)
4343

4444

45-
def check_error(code: int, info: str = ""):
45+
def check_error(response: Response, info: str = ""):
4646
"""Checks HTTP code from Nextcloud, and raises exception in case of error.
4747
4848
For the OCS and DAV `code` be code returned by HTTP and not the status from ``ocs_meta``.
4949
"""
50-
if 996 <= code <= 999:
51-
if code == 996:
50+
status_code = response.status_code
51+
if not info:
52+
info = f"request: {response.request.method} {response.request.url}"
53+
if 996 <= status_code <= 999:
54+
if status_code == 996:
5255
phrase = "Server error"
53-
elif code == 997:
56+
elif status_code == 997:
5457
phrase = "Unauthorised"
55-
elif code == 998:
58+
elif status_code == 998:
5659
phrase = "Not found"
5760
else:
5861
phrase = "Unknown error"
59-
raise NextcloudException(code, reason=phrase, info=info)
60-
if not codes.is_error(code):
62+
raise NextcloudException(status_code, reason=phrase, info=info)
63+
if not codes.is_error(status_code):
6164
return
62-
raise NextcloudException(code, reason=codes(code).phrase, info=info)
65+
raise NextcloudException(status_code, reason=codes(status_code).phrase, info=info)

nc_py_api/_preferences.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ def available(self) -> bool:
2020
def set_value(self, app_name: str, key: str, value: str) -> None:
2121
"""Sets the value for the key for the specific application."""
2222
require_capabilities("provisioning_api", self._session.capabilities)
23-
self._session.ocs(method="POST", path=f"{self._ep_base}/{app_name}/{key}", params={"configValue": value})
23+
self._session.ocs("POST", f"{self._ep_base}/{app_name}/{key}", params={"configValue": value})
2424

2525
def delete(self, app_name: str, key: str) -> None:
2626
"""Removes a key and its value for a specific application."""
2727
require_capabilities("provisioning_api", self._session.capabilities)
28-
self._session.ocs(method="DELETE", path=f"{self._ep_base}/{app_name}/{key}")
28+
self._session.ocs("DELETE", f"{self._ep_base}/{app_name}/{key}")

nc_py_api/_preferences_ex.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ def get_values(self, keys: list[str]) -> list[CfgRecord]:
4444
raise ValueError("`key` parameter can not be empty")
4545
require_capabilities("app_api", self._session.capabilities)
4646
data = {"configKeys": keys}
47-
results = self._session.ocs(
48-
method="POST", path=f"{self._session.ae_url}/{self._url_suffix}/get-values", json=data
49-
)
47+
results = self._session.ocs("POST", f"{self._session.ae_url}/{self._url_suffix}/get-values", json=data)
5048
return [CfgRecord(i) for i in results]
5149

5250
def delete(self, keys: typing.Union[str, list[str]], not_fail=True) -> None:
@@ -59,9 +57,7 @@ def delete(self, keys: typing.Union[str, list[str]], not_fail=True) -> None:
5957
raise ValueError("`key` parameter can not be empty")
6058
require_capabilities("app_api", self._session.capabilities)
6159
try:
62-
self._session.ocs(
63-
method="DELETE", path=f"{self._session.ae_url}/{self._url_suffix}", json={"configKeys": keys}
64-
)
60+
self._session.ocs("DELETE", f"{self._session.ae_url}/{self._url_suffix}", json={"configKeys": keys})
6561
except NextcloudExceptionNotFound as e:
6662
if not not_fail:
6763
raise e from None
@@ -78,7 +74,7 @@ def set_value(self, key: str, value: str) -> None:
7874
raise ValueError("`key` parameter can not be empty")
7975
require_capabilities("app_api", self._session.capabilities)
8076
params = {"configKey": key, "configValue": value}
81-
self._session.ocs(method="POST", path=f"{self._session.ae_url}/{self._url_suffix}", json=params)
77+
self._session.ocs("POST", f"{self._session.ae_url}/{self._url_suffix}", json=params)
8278

8379

8480
class AppConfigExAPI(_BasicAppCfgPref):
@@ -99,4 +95,4 @@ def set_value(self, key: str, value: str, sensitive: typing.Optional[bool] = Non
9995
params: dict = {"configKey": key, "configValue": value}
10096
if sensitive is not None:
10197
params["sensitive"] = sensitive
102-
self._session.ocs(method="POST", path=f"{self._session.ae_url}/{self._url_suffix}", json=params)
98+
self._session.ocs("POST", f"{self._session.ae_url}/{self._url_suffix}", json=params)

0 commit comments

Comments
 (0)