Skip to content

Commit

Permalink
Merge pull request #203 from Snuffy2/Change-notices-functions-to-REST…
Browse files Browse the repository at this point in the history
…-API

Change notices functions to REST API
  • Loading branch information
alexdelprete authored Sep 20, 2024
2 parents a2b2676 + 91ffdfb commit 0228e5f
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 114 deletions.
10 changes: 1 addition & 9 deletions custom_components/opnsense/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,6 @@ async def _get_carp_status(self):
async def _get_dhcp_leases(self):
return await self._client.get_dhcp_leases()

@_log_timing
async def _are_notices_pending(self):
return await self._client.are_notices_pending()

@_log_timing
async def _get_notices(self):
return await self._client.get_notices()
Expand Down Expand Up @@ -147,11 +143,7 @@ async def _async_update_data(self):
# self._state["dhcp_leases"] = await self._client.get_dhcp_leases()
self._state["dhcp_leases"] = []
self._state["dhcp_stats"] = {}
self._state["notices"] = {}
self._state["notices"][
"pending_notices_present"
] = await self._are_notices_pending()
self._state["notices"]["pending_notices"] = await self._get_notices()
self._state["notices"] = await self._get_notices()

lease_stats: Mapping[str, int] = {"total": 0, "online": 0, "offline": 0}
for lease in self._state["dhcp_leases"]:
Expand Down
155 changes: 53 additions & 102 deletions custom_components/opnsense/pyopnsense/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,114 +1418,65 @@ async def _get_telemetry_legacy(self) -> Mapping[str, Any]:
return telemetry

@_log_errors
async def are_notices_pending(self) -> Mapping[str, Any]:
script: str = r"""
if (file_exists('/usr/local/etc/inc/notices.inc')) {
require_once '/usr/local/etc/inc/notices.inc';
$toreturn = [
"data" => are_notices_pending(),
];
} else {
$status = new \OPNsense\System\SystemStatus();
$pending = false;
foreach ($status->getSystemStatus() as $key => $value) {
if ($value["statusCode"] != 2) {
$pending = true;
break;
}
}
$toreturn = [
"data" => $pending,
];
}
"""
response: Mapping[str, Any] = await self._exec_php(script)
if response is None or not isinstance(response, Mapping):
_LOGGER.error("Invalid data returned from are_notices_pending")
return {}
return response.get("data", {})

@_log_errors
async def get_notices(self):
script: str = r"""
if (file_exists('/usr/local/etc/inc/notices.inc')) {
require_once '/usr/local/etc/inc/notices.inc';
$toreturn = [
"data" => get_notices(),
];
} else {
$status = new \OPNsense\System\SystemStatus();
$toreturn = [
"data" => $status->getSystemStatus(),
];
}
"""
response: Mapping[str, Any] = await self._exec_php(script)
if response is None or not isinstance(response, Mapping):
_LOGGER.error("Invalid data returned from get_notices -> getSystemStatus")
return []
value: Mapping[str, Any] = response.get("data", [])
async def get_notices(self) -> list:
notices_info: Mapping[str, Any] | list = await self._get(
"/api/core/system/status"
)
_LOGGER.debug(f"[get_notices] notices_info: {notices_info}")

if isinstance(value, list):
if not isinstance(notices_info, Mapping):
return []

notices: list = []
for key in value.keys():
notice: Mapping[str, Any] = value.get(key)
# 22.7.2+
if "statusCode" in notice.keys():
if notice["statusCode"] != 2:
real_notice = {}
real_notice["notice"] = notice["message"]
real_notice["id"] = key
real_notice["created_at"] = notice["timestamp"]
notices.append(real_notice)
else:
notice["created_at"] = key
notice["id"] = key
notices.append(notice)

pending_notices_present = False
pending_notices: list = []
for key, notice in notices_info.items():
if isinstance(notices_info, Mapping) and notice.get("statusCode", 2) != 2:
pending_notices_present = True
real_notice: Mapping[str, Any] = {}
real_notice["notice"] = notice.get("message", None)
real_notice["id"] = key
real_notice["created_at"] = notice.get("timestamp", None)
pending_notices.append(real_notice)

notices: Mapping[str, Any] = {}
notices["pending_notices_present"] = pending_notices_present
notices["pending_notices"] = pending_notices
_LOGGER.debug(f"[get_notices] notices: {notices}")
return notices

@_log_errors
async def close_notice(self, id) -> None:
async def close_notice(self, id) -> bool:
"""
id = "all" to wipe everything
"""
script: str = (
r"""
$data = json_decode('{}', true);
$id = $data["id"];
if (file_exists('/usr/local/etc/inc/notices.inc')) {{
require_once '/usr/local/etc/inc/notices.inc';
close_notice($id);
$toreturn = [
"data" => true,
];
}} else {{
$status = new \OPNsense\System\SystemStatus();
if (strtolower($id) == "all") {{
foreach ($status->getSystemStatus() as $key => $value) {{
$status->dismissStatus($key);
}}
}} else {{
$status->dismissStatus($id);
}}
$toreturn = [
"data" => true,
];
}}
""".format(
json.dumps(
{
"id": id,
}
)
success = True
if id.lower() == "all":
notices: Mapping[str, Any] | list = await self._get(
"/api/core/system/status"
)
)

await self._exec_php(script)
_LOGGER.debug(f"[close_notice] notices: {notices}")

if not isinstance(notices, Mapping):
return False
for key, notice in notices.items():
if "statusCode" in notice:
dismiss: Mapping[str, Any] | list = await self._post(
"/api/core/system/dismissStatus", payload={"subject": key}
)
_LOGGER.debug(f"[close_notice] id: {key}, dismiss: {dismiss}")
if (
not isinstance(dismiss, Mapping)
or dismiss.get("status", "failed") != "ok"
):
success = False
else:
dismiss: Mapping[str, Any] | list = await self._post(
"/api/core/system/dismissStatus", payload={"subject": id}
)
_LOGGER.debug(f"[close_notice] id: {id}, dismiss: {dismiss}")
if (
not isinstance(dismiss, Mapping)
or dismiss.get("status", "failed") != "ok"
):
success = False
_LOGGER.debug(f"[close_notice] success: {success}")
return success
5 changes: 2 additions & 3 deletions function_method.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@
| Get Carp Status | Yes | Yes | |
| Get Carp Interfaces | Yes | Yes | |
| Delete ARP Entry | Yes | | |
| Are Notices Pending | Yes | Yes | |
| Get Notices | Yes | Yes | |
| Close Notice | Yes | Yes | |

# REST API Functions

Expand All @@ -52,3 +49,5 @@
| Send WOL | /api/wol/wol/set | 2018 | |
| Get ARP Table | /api/diagnostics/interface/search_arp | 2022 | |
| Get System Info | /api/diagnostics/system/systemInformation | 24.7 | Partial: Still using XMLRPC for Getting Device ID |
| Get Notices | /api/core/system/status | 2022 | |
| Close Notice | /api/core/system/status<br>/api/core/system/dismissStatus | 2022 | |

0 comments on commit 0228e5f

Please sign in to comment.