diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..12e00ed --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: fmainz diff --git a/README-de.md b/README-de.md index a9de650..1c81847 100644 --- a/README-de.md +++ b/README-de.md @@ -1,4 +1,4 @@ -[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://github.com/hacs/integration) +[![marketplace_badge](https://img.shields.io/badge/Marketplace-Custom-41BDF5.svg)](https://www.home-assistant.io/integrations/marketplace) [![GitHub release](https://img.shields.io/github/release/fmainz/ha-ipfire?include_prereleases=&sort=semver&color=blue)](https://github.com/fmainz/ha-ipfire/releases/) ![last commit](https://img.shields.io/github/last-commit/fmainz/ha-ipfire) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) @@ -41,6 +41,14 @@ Diese Dokumentation ist auch in 🇬🇧 [englischer Sprache](README.md) verfüg ## Neues in dieser Version +### v0.3.7 + +* Datenschutzbewussten Diagnosebericht mit Integrations- und Verbindungsstatus, Verfügbarkeit der API-Daten, Update-Status, Entitätsanzahlen, UTC-Zeitangaben und bereinigten Fehlerinformationen hinzugefügt. Der normale Zustand `unknown` von Button-Entitäten wird bei der Anzahl nicht verfügbarer oder unbekannter Entitäten nicht mitgezählt. Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden im Bericht nicht ausgegeben. Die API-Revision erscheint, wenn IPFire-API v0.2.1 oder neuer sie bereitstellt. +* Netzwerkhersteller (`mac_vendor`) zu den DHCP-Lease-Attributen hinzugefügt. Die Zuordnung erfolgt lokal anhand der MAC-Adresse des Lease. +* Native Home-Assistant-Update-Entität hinzugefügt, die verfügbare IPFire-Core- und Paket-Updates anzeigt und das vollständige Pakfire-Upgrade starten kann. +* Statusmeldung für den Update-Vorgang sowie eine native Home-Assistant-Update-Aktion zum Starten eines erforderlichen IPFire-Neustarts hinzugefügt. Die Update- und Neustartfunktionen benötigen eine kompatible `api.cgi`; für den Neustart ist IPFire-API v0.2.5 oder neuer erforderlich. +* Versionsanforderung für `aiooui` angepasst, sodass kompatible Versionen ab 0.1.9 verwendet werden können. + ### v0.3.6 * DHCP-Lease-Anzahl und Clientdaten als Sensorattribute hinzugefügt (benötigt api.cgi). @@ -87,6 +95,9 @@ HA-IPFire bietet folgende Funktionen: * DHCP-Lease-Sensor mit Clientdaten¹ * Trafficzähler für einzelne Netzwerkzonen¹ * Neustartstatus und Gesamtzahl verfügbarer Updates¹ +* Verfügbare IPFire-Updates anzeigen und das vollständige Pakfire-Upgrade in Home Assistant installieren¹ +* Einen erforderlichen IPFire-Neustart über die native HA-Update-Ansicht bestätigen und starten¹ +* Einen datensparsamen Diagnosebericht in den HA-Benachrichtigungen erstellen ¹Benötigt api.cgi aus [IPFire-API](https://github.com/FMainz/IPFire-API) @@ -181,12 +192,15 @@ Sensoren werden nur für interne Schnittstellen angelegt, die auf der IPFire-Fir ### DHCP-Leases -* **Aktive DHCP-Leases** – Anzahl aktiver DHCP-Leases. Das Attribut `leases` enthält die von IPFire gemeldeten Clientdaten mit IP-Adresse, MAC-Adresse, Hostname, Ablaufzeit und Status. Du findest sie in Home Assistant in der Detailansicht des Sensors unter den Attributen. +* **Aktive DHCP-Leases** – Anzahl aktiver DHCP-Leases. Das Attribut `leases` enthält die von IPFire gemeldeten Clientdaten mit IP-Adresse, MAC-Adresse, Hostname, Ablaufzeit und Status. HA-IPFire ergänzt außerdem `mac_vendor`, ermittelt anhand des MAC-Adresspräfixes aus einer lokalen Zuordnungstabelle. Bei privaten oder nicht registrierten MAC-Adressen kann der Wert fehlen oder unzutreffend sein. Die Lease-Details findest du in Home Assistant in der Detailansicht des Sensors unter den Attributen. ### Systemstatus * **Neustart erforderlich** – zeigt an, wenn IPFire nach einem Update einen Neustart verlangt. Benötigt eine aktuelle Version von `api.cgi`; bei älteren Versionen bleibt der Sensor unbekannt. -* **Updates verfügbar** – Gesamtzahl der verfügbaren Updates, einschließlich Core- und Paket-Updates. +* **Updates verfügbar** – Gesamtzahl der verfügbaren Updates, einschließlich Core- und Paket-Updates. Das Attribut `updates` listet die einzelnen Core- und Paket-Updates mit ihren Versionen auf. +* **IPFire-Systemupdates** – native Home-Assistant-Update-Entität. Sie erscheint im Update-Bereich von Home Assistant, wenn Updates verfügbar sind; die Release-Zusammenfassung listet Core- und Paket-Updates auf. Mit „Installieren“ wird das vollständige Pakfire-Upgrade gestartet, da IPFire keine Auswahl einzelner Updates unterstützt. +* **Update-Vorgang** – zeigt an, ob ein über die API gestartetes Update inaktiv ist, läuft, abgeschlossen ist oder fehlgeschlagen ist. +* **Router neu starten** – erscheint als native Home-Assistant-Update-Aktion, wenn `api.cgi` ab Revision 0.2.5 einen erforderlichen Neustart meldet. Über die Update-Ansicht kannst du den Router-Neustart nach Bestätigung starten. ### Internetverbindung @@ -396,10 +410,16 @@ Die aktuellen Übertragungsraten werden aus den Trafficzählern berechnet und al ## Support -Wenn du einen Fehler findest oder einen Verbesserungsvorschlag hast, kannst du ein Issue im GitHub-Repository erstellen: +Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, der Anzahl aktivierter Entitäten mit dem Status `unavailable` oder `unknown` (der normale `unknown`-Status von Buttons wird ausgelassen), UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers (sekundengenau), einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. + +Du kannst auch ein Issue erstellen oder einen Verbesserungsvorschlag im GitHub-Repository einreichen: https://github.com/FMainz/HA-IPFire/issues +Wenn dir HA-IPFire weiterhilft, kannst du die Weiterentwicklung auf Ko-fi unterstützen: + +[![FMainz auf Ko-fi unterstützen](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/fmainz) + ## Repository https://github.com/FMainz/HA-IPFire diff --git a/README.md b/README.md index e95b4c0..6712f01 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://github.com/hacs/integration) +[![marketplace_badge](https://img.shields.io/badge/Marketplace-Custom-41BDF5.svg)](https://www.home-assistant.io/integrations/marketplace) [![GitHub release](https://img.shields.io/github/release/fmainz/ha-ipfire?include_prereleases=&sort=semver&color=blue)](https://github.com/fmainz/ha-ipfire/releases/) ![last commit](https://img.shields.io/github/last-commit/fmainz/ha-ipfire) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) @@ -41,6 +41,14 @@ This documentation is also available in 🇩🇪 [German](README-de.md). ## What’s New in This Version +### v0.3.7 + +* Added a privacy-conscious diagnostic report with integration and connection status, API data availability, update status, entity counts, UTC timestamps and sanitized error details. Button entities in their normal `unknown` state are excluded from the unavailable/unknown count; the report omits credentials, IP addresses, hostnames and DHCP client details. API revision is included when supported by IPFire-API v0.2.1 or later. +* Added the network-card vendor (`mac_vendor`) to DHCP lease attributes, looked up locally from the lease MAC address. +* Added a native Home Assistant update entity that shows available IPFire core and package updates and can start the full Pakfire upgrade. +* Added update-operation status reporting and a native Home Assistant update action for starting a required IPFire reboot. These update and reboot features require a compatible `api.cgi`; reboot requires IPFire-API v0.2.5 or later. +* Updated the `aiooui` dependency requirement to accept compatible versions from 0.1.9 onward. + ### v0.3.6 * Added DHCP lease count and client details as sensor attributes (requires `api.cgi`). @@ -87,6 +95,9 @@ HA-IPFire provides the following features: * DHCP lease sensor with client details¹ * Traffic counters for individual network zones¹ * Reboot-required status and total available update count¹ +* Review available IPFire updates and install the full Pakfire upgrade from Home Assistant¹ +* Confirm and start a required IPFire reboot through Home Assistant's native Updates interface¹ +* Generate a privacy-conscious diagnostic report in Home Assistant notifications ¹Requires `api.cgi` from [IPFire-API](https://github.com/FMainz/IPFire-API). @@ -183,12 +194,15 @@ Sensors are created only for internal interfaces configured on the IPFire firewa ### DHCP leases -* **Active DHCP Leases** – number of active DHCP leases. The `leases` attribute contains the client records reported by IPFire, including IP address, MAC address, hostname, expiry, and status. To view them, open the sensor's more-info panel in Home Assistant and inspect its attributes. +* **Active DHCP Leases** – number of active DHCP leases. The `leases` attribute contains the client records reported by IPFire, including IP address, MAC address, hostname, expiry, and status. HA-IPFire also adds `mac_vendor`, looked up locally from the MAC address prefix. This may be unavailable or inaccurate for private or unregistered MAC addresses. To view the lease details, open the sensor's more-info panel in Home Assistant and inspect its attributes. ### System status * **Reboot Required** – indicates when IPFire requires a reboot after an update. Requires a current version of `api.cgi`; older versions leave the sensor unknown. -* **Updates Available** – total number of available updates, including core and package updates. +* **Updates Available** – total number of available updates, including core and package updates. Its `updates` attribute lists the exact core/package updates and versions. +* **IPFire System Updates** – native Home Assistant update entity. It appears in Home Assistant's Updates section when updates are available; its release summary lists the included core and package updates. Installing it starts the full Pakfire upgrade, because IPFire does not support selecting individual updates. +* **Update Operation** – reports whether an API-started update is idle, running, completed, or failed. +* **Restart router** – appears as a native Home Assistant update action when `api.cgi` revision 0.2.5 or newer reports that a reboot is required. Start the router reboot from the Updates interface after confirmation. ### Internet connection @@ -393,10 +407,16 @@ Current transfer rates are calculated from the traffic counters and are provided ## Support -If you encounter a problem or have a suggestion, please open an issue in the GitHub repository: +If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, counts of enabled entities in `unavailable` or `unknown` state (the normal `unknown` state of buttons is excluded), UTC timestamps for the last successful update and last error (to the second), a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. + +You can also open an issue or suggest an improvement in the GitHub repository: https://github.com/FMainz/HA-IPFire/issues +If you find HA-IPFire useful, you can support its ongoing development on Ko-fi: + +[![Support FMainz on Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/fmainz) + ## Repository https://github.com/FMainz/HA-IPFire diff --git a/custom_components/ipfire/__init__.py b/custom_components/ipfire/__init__.py index 5aed5f4..809f242 100644 --- a/custom_components/ipfire/__init__.py +++ b/custom_components/ipfire/__init__.py @@ -3,6 +3,8 @@ from dataclasses import dataclass from datetime import timedelta +import aiooui + from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv @@ -20,7 +22,7 @@ from .coordinator import IPFireCoordinator -PLATFORMS: list[str] = ["binary_sensor", "button", "sensor"] +PLATFORMS: list[str] = ["binary_sensor", "button", "sensor", "update"] CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) @@ -58,6 +60,9 @@ async def async_setup_entry( ) -> bool: """Set up HA-IPFire from a config entry.""" + if not aiooui.is_loaded(): + await aiooui.async_load() + session = async_get_clientsession(hass) scan_interval = entry.options.get( @@ -100,4 +105,4 @@ async def async_unload_entry( return await hass.config_entries.async_unload_platforms( entry, PLATFORMS, - ) \ No newline at end of file + ) diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index 6ccceef..107cf28 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -1,14 +1,29 @@ from __future__ import annotations +import json +import re from dataclasses import dataclass +from datetime import datetime, timezone +from homeassistant.components import persistent_notification from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.config_entries import ConfigEntry +from homeassistant.const import __version__ as HA_VERSION from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.translation import async_get_translations from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.loader import async_get_loaded_integration +from .const import ( + CONF_SCAN_INTERVAL, + CONF_VERIFY_SSL, + DEFAULT_SCAN_INTERVAL, + DOMAIN, +) from .coordinator import IPFireCoordinator @@ -35,6 +50,13 @@ class IPFireButtonDescription(ButtonEntityDescription): icon="mdi:lan-disconnect", action="disconnect", ), + IPFireButtonDescription( + key="diagnostic_report", + translation_key="diagnostic_report", + icon="mdi:bug-outline", + entity_category=EntityCategory.DIAGNOSTIC, + action="diagnostic_report", + ), ) @@ -48,7 +70,7 @@ async def async_setup_entry( coordinator: IPFireCoordinator = entry.runtime_data.coordinator async_add_entities( - IPFireConnectionButton( + IPFireActionButton( coordinator, entry, description, @@ -57,11 +79,11 @@ async def async_setup_entry( ) -class IPFireConnectionButton( +class IPFireActionButton( CoordinatorEntity[IPFireCoordinator], ButtonEntity, ): - """Represent an IPFire connection control button.""" + """Represent an IPFire action button.""" _attr_has_entity_name = True @@ -76,6 +98,7 @@ def __init__( super().__init__(coordinator) self.entity_description = description + self.entry = entry self._attr_unique_id = f"{entry.entry_id}_{description.key}" self._attr_device_info = DeviceInfo( identifiers={("ipfire", entry.entry_id)}, @@ -84,10 +107,276 @@ def __init__( model="Firewall", ) + @property + def available(self) -> bool: + """Keep the diagnostic report available during coordinator errors.""" + if self.entity_description.action == "diagnostic_report": + return True + return super().available + async def async_press(self) -> None: """Handle the button press.""" if self.entity_description.action == "connect": await self.coordinator.async_connect() - else: - await self.coordinator.async_disconnect() \ No newline at end of file + elif self.entity_description.action == "disconnect": + await self.coordinator.async_disconnect() + elif self.entity_description.action == "diagnostic_report": + await self._async_create_diagnostic_report() + + async def _async_create_diagnostic_report(self) -> None: + """Create a privacy-conscious diagnostic report notification.""" + integration = async_get_loaded_integration(self.hass, DOMAIN) + integration_version = integration.manifest.get("version", "unknown") + data = self.coordinator.data + coordinator_status = ( + "successful" if self.coordinator.last_update_success else "failed" + ) + data_status = "available" if data is not None else "unavailable" + last_error = self.coordinator.last_update_error + interval = self.entry.options.get( + CONF_SCAN_INTERVAL, + DEFAULT_SCAN_INTERVAL, + ) + entity_counts = self._entity_counts() + last_error_type, last_error_message = self._safe_error_details(last_error) + + lines = [ + "versions:", + f" ha_ipfire: {self._yaml_scalar(integration_version)}", + f" home_assistant: {self._yaml_scalar(HA_VERSION)}", + "settings:", + f" scan_interval_seconds: {self._yaml_scalar(interval)}", + " verify_ssl_certificate: " + f"{self._yaml_scalar(self.entry.data.get(CONF_VERIFY_SSL))}", + " entities:", + ] + + for domain, counts in entity_counts.items(): + lines.extend( + [ + f" {domain}:", + f" enabled: {counts['enabled']}", + f" disabled: {counts['disabled']}", + f" unavailable: {counts['unavailable']}", + f" unknown: {counts['unknown']}", + ] + ) + + lines.extend( + [ + "connection:", + " coordinator_update: " + f"{self._yaml_scalar(coordinator_status)}", + " last_successful_update_utc: " + f"{self._yaml_scalar(self._format_utc(self.coordinator.last_successful_update_utc))}", + " last_error_utc: " + f"{self._yaml_scalar(self._format_utc(self.coordinator.last_error_utc))}", + f" last_error_type: {self._yaml_scalar(last_error_type)}", + " last_error_message: " + f"{self._yaml_scalar(last_error_message)}", + " ipfire: " + f"{self._yaml_scalar(data.connection_state if data else None)}", + "api_data:", + f" last_data: {self._yaml_scalar(data_status)}", + " api_revision: " + f"{self._yaml_scalar(data.api_revision if data else None)}", + ] + ) + + def unavailable_reason(value: object) -> str | None: + if value is not None: + return None + if data is None: + return "query_failed" if last_error is not None else "not_queried" + return "not_reported_by_api" + + leases = data.dhcp_leases if data is not None else None + updates = data.available_updates if data is not None else None + operation = data.update_operation if data is not None else None + lines.extend( + [ + " dhcp_leases:", + " count: " + f"{self._yaml_scalar(len(leases) if leases is not None else None)}", + " status: " + f"{self._yaml_scalar('available' if leases is not None else 'unavailable')}", + f" reason: {self._yaml_scalar(unavailable_reason(leases))}", + " available_update_list:", + " count: " + f"{self._yaml_scalar(len(updates) if updates is not None else None)}", + " status: " + f"{self._yaml_scalar('available' if updates is not None else 'unavailable')}", + f" reason: {self._yaml_scalar(unavailable_reason(updates))}", + " update_operation:", + " status: " + f"{self._yaml_scalar(self._safe_operation_status(operation))}", + f" reason: {self._yaml_scalar(unavailable_reason(operation))}", + ] + ) + + if data is not None: + lines.extend( + [ + "", + "ipfire:", + f" version: {self._yaml_scalar(data.system.version)}", + " architecture: " + f"{self._yaml_scalar(data.system.architecture)}", + " kernel_version: " + f"{self._yaml_scalar(data.system.kernel_version)}", + " core_update_available: " + f"{self._yaml_scalar(data.system.core_update)}", + " package_updates_available: " + f"{self._yaml_scalar(data.system.package_updates)}", + " reboot_required: " + f"{self._yaml_scalar(data.system.reboot_required)}", + ] + ) + + report = "\n".join(lines) + translations = await async_get_translations( + self.hass, + self.hass.config.language, + "common", + {DOMAIN}, + ) + title = translations.get( + f"component.{DOMAIN}.common.diagnostic_report_title", + "HA-IPFire: Error report", + ) + notice = translations.get( + f"component.{DOMAIN}.common.diagnostic_report_notice", + "Review this report before sharing it. It excludes credentials, " + "IP addresses, hostnames, and DHCP client details.", + ) + message = f"{notice}\n\n```yaml\n{report}\n```" + persistent_notification.async_create( + self.hass, + message, + title=title, + notification_id=f"ipfire_diagnostic_report_{self.entry.entry_id}", + ) + + def _entity_counts(self) -> dict[str, dict[str, int]]: + """Count entity states without including entity IDs.""" + registry = er.async_get(self.hass) + counts: dict[str, dict[str, int]] = {} + for entity in er.async_entries_for_config_entry( + registry, + self.entry.entry_id, + ): + if entity.domain not in { + "sensor", + "binary_sensor", + "button", + "update", + }: + continue + domain_counts = counts.setdefault( + entity.domain, + { + "enabled": 0, + "disabled": 0, + "unavailable": 0, + "unknown": 0, + }, + ) + if entity.disabled_by is not None: + domain_counts["disabled"] += 1 + continue + + domain_counts["enabled"] += 1 + state = self.hass.states.get(entity.entity_id) + if state is None: + continue + if state.state == "unavailable": + domain_counts["unavailable"] += 1 + elif state.state == "unknown" and entity.domain != "button": + domain_counts["unknown"] += 1 + return dict(sorted(counts.items())) + + @staticmethod + def _format_utc(value: object) -> str | None: + """Format a timestamp as an ISO 8601 UTC value.""" + if not isinstance(value, datetime): + return None + return value.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") + + @staticmethod + def _safe_operation_status( + operation: dict[str, object] | None, + ) -> str | None: + """Return only known-safe update operation states.""" + if operation is None: + return None + status = operation.get("status") + if isinstance(status, str) and status in { + "idle", + "running", + "completed", + "failed", + }: + return str(status) + return "unknown" + + def _safe_error_details( + self, + error: BaseException | None, + ) -> tuple[str | None, str | None]: + """Redact addresses, hostnames, credentials, and URLs from errors.""" + if error is None: + return None, None + + message = str(error) or "No error details provided" + for secret in ( + self.coordinator.base_url, + self.coordinator.username, + self.coordinator.password, + ): + if secret: + message = message.replace(secret, "[redacted]") + + message = re.sub( + r"https?://[^\s'\"]+", + "[URL redacted]", + message, + flags=re.IGNORECASE, + ) + message = re.sub( + r"(?i)(host(?:name)?\s+)[^\s,;]+", + r"\1[redacted]", + message, + ) + message = re.sub( + r"(?i)\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}\b", + "[hostname redacted]", + message, + ) + message = re.sub( + r"\b(?:\d{1,3}\.){3}\d{1,3}\b", + "[IP address redacted]", + message, + ) + message = re.sub( + r"\b(?:[0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}\b", + "[MAC address redacted]", + message, + ) + message = re.sub( + r"(? str: + """Return a YAML-safe scalar without exposing arbitrary formatting.""" + if value is None: + return "none" + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, (int, float)): + return str(value) + return json.dumps(str(value), ensure_ascii=False) diff --git a/custom_components/ipfire/coordinator.py b/custom_components/ipfire/coordinator.py index aefa4ef..acc8ebe 100644 --- a/custom_components/ipfire/coordinator.py +++ b/custom_components/ipfire/coordinator.py @@ -4,7 +4,7 @@ import time import xml.etree.ElementTree as ET from dataclasses import dataclass -from datetime import timedelta +from datetime import datetime, timedelta import aiohttp @@ -14,6 +14,7 @@ DataUpdateCoordinator, UpdateFailed, ) +from homeassistant.util import dt as dt_util from .const import DOMAIN, API_PATH _LOGGER = logging.getLogger(__name__) @@ -88,6 +89,7 @@ class IPFireInterfaceData: class IPFireData: """Represent data received from IPFire.""" + api_revision: str | None rxb: int txb: int rx_rate: float @@ -102,6 +104,8 @@ class IPFireData: system: IPFireSystemData network: IPFireNetworkData dhcp_leases: tuple[dict[str, object], ...] | None + available_updates: tuple[dict[str, object], ...] | None + update_operation: dict[str, object] | None services: dict[str, bool] addons: dict[str, dict[str, bool]] @@ -134,12 +138,26 @@ def __init__( self.password = password self.verify_ssl = verify_ssl + self.last_successful_update_utc: datetime | None = None + self.last_error_utc: datetime | None = None + self.last_update_error: BaseException | None = None + self._previous_rx_bytes: int | None = None self._previous_tx_bytes: int | None = None self._previous_timestamp: float | None = None self._previous_cpu_total: int | None = None self._previous_cpu_idle: int | None = None + def _async_refresh_finished(self) -> None: + """Keep UTC timestamps and the last update error for diagnostics.""" + if self.last_update_success: + self.last_successful_update_utc = dt_util.utcnow() + return + + if self.last_exception is not None: + self.last_error_utc = dt_util.utcnow() + self.last_update_error = self.last_exception + @property def api_url(self) -> str: """Return the IPFire API URL.""" @@ -195,7 +213,7 @@ async def _async_update_data(self) -> IPFireData: except ConfigEntryAuthFailed: raise - except (aiohttp.ClientError, ValueError) as err: + except (aiohttp.ClientError, TimeoutError, ValueError) as err: raise UpdateFailed( f"Unable to read data from IPFire: {err}" ) from err @@ -208,6 +226,8 @@ async def _async_update_data(self) -> IPFireData: dhcp = payload.get("dhcp", {}) services = payload.get("services", {}) addons = payload.get("addons", {}) + updates = payload.get("updates", {}) + raw_api_revision = payload.get("api_revision") if not isinstance(connection, dict): raise ValueError("Invalid connection data from IPFire") @@ -229,6 +249,25 @@ async def _async_update_data(self) -> IPFireData: if not isinstance(addons, dict): raise ValueError("Invalid addons data from IPFire") + if not isinstance(updates, dict): + raise ValueError("Invalid update data from IPFire") + + raw_available_updates = updates.get("available") + if raw_available_updates is not None and ( + not isinstance(raw_available_updates, list) + or not all( + isinstance(update, dict) + for update in raw_available_updates + ) + ): + raise ValueError("Invalid available update list from IPFire") + + raw_update_operation = updates.get("operation") + if raw_update_operation is not None and not isinstance( + raw_update_operation, dict + ): + raise ValueError("Invalid update operation data from IPFire") + raw_interfaces = network.get("interfaces", {}) if not isinstance(raw_interfaces, dict): raise ValueError("Invalid network interface data from IPFire") @@ -401,6 +440,12 @@ async def _async_update_data(self) -> IPFireData: self._previous_timestamp = now return IPFireData( + api_revision=( + str(raw_api_revision) + if isinstance(raw_api_revision, (str, int)) + and not isinstance(raw_api_revision, bool) + else None + ), rxb=rx_bytes, txb=tx_bytes, rx_rate=rx_rate, @@ -415,6 +460,16 @@ async def _async_update_data(self) -> IPFireData: system=system_data, network=network_data, dhcp_leases=dhcp_leases, + available_updates=( + tuple(raw_available_updates) + if isinstance(raw_available_updates, list) + else None + ), + update_operation=( + dict(raw_update_operation) + if isinstance(raw_update_operation, dict) + else None + ), services=services, addons=addons, ) @@ -427,6 +482,114 @@ async def async_disconnect(self) -> None: """Disconnect the IPFire Internet connection.""" await self._async_connection_action("disconnect") + async def async_start_upgrade(self) -> None: + """Start installing all updates available on IPFire.""" + try: + async with self.session.post( + self.api_url, + auth=self._auth(), + ssl=self.verify_ssl, + headers={"X-IPFire-API": "1"}, + data={"action": "upgrade"}, + timeout=aiohttp.ClientTimeout(total=15), + ) as response: + if response.status in (401, 403): + raise ConfigEntryAuthFailed( + "Invalid IPFire username or password" + ) + + try: + payload = await response.json(content_type=None) + except (ValueError, TypeError): + payload = {} + + if not isinstance(payload, dict): + raise UpdateFailed( + "IPFire returned an invalid upgrade response" + ) + + if ( + response.status >= 400 + or payload.get("result") != "accepted" + ): + error = payload.get("error", "unknown_error") + raise UpdateFailed( + f"Unable to start IPFire upgrade: {error}" + ) + + except ConfigEntryAuthFailed: + raise + + except (aiohttp.ClientError, ValueError) as err: + raise UpdateFailed( + f"Unable to start IPFire upgrade: {err}" + ) from err + + await self.async_request_refresh() + + @property + def supports_reboot_action(self) -> bool: + """Return whether the installed API supports reboot requests.""" + if self.data is None or self.data.api_revision is None: + return False + try: + revision = tuple( + int(part) for part in self.data.api_revision.split(".") + ) + except ValueError: + return False + return revision >= (0, 2, 5) + + async def async_reboot(self) -> None: + """Start an IPFire reboot when the API reports it is required.""" + if ( + not self.supports_reboot_action + or self.data is None + or self.data.system.reboot_required is not True + ): + raise UpdateFailed("IPFire does not currently require a reboot") + + try: + async with self.session.post( + self.api_url, + auth=self._auth(), + ssl=self.verify_ssl, + headers={"X-IPFire-API": "1"}, + data={"action": "reboot"}, + timeout=aiohttp.ClientTimeout(total=15), + ) as response: + if response.status in (401, 403): + raise ConfigEntryAuthFailed( + "Invalid IPFire username or password" + ) + + try: + payload = await response.json(content_type=None) + except (ValueError, TypeError): + payload = {} + + if not isinstance(payload, dict): + raise UpdateFailed( + "IPFire returned an invalid reboot response" + ) + + if ( + response.status >= 400 + or payload.get("result") != "accepted" + ): + error = payload.get("error", "unknown_error") + raise UpdateFailed( + f"Unable to start IPFire reboot: {error}" + ) + + except ConfigEntryAuthFailed: + raise + + except (aiohttp.ClientError, TimeoutError, ValueError) as err: + raise UpdateFailed( + f"Unable to start IPFire reboot: {err}" + ) from err + async def _async_connection_action(self, action: str) -> None: """Execute a connection action on IPFire.""" if action not in {"connect", "disconnect"}: diff --git a/custom_components/ipfire/icons.json b/custom_components/ipfire/icons.json index 15cbe7c..76f61e0 100644 --- a/custom_components/ipfire/icons.json +++ b/custom_components/ipfire/icons.json @@ -123,6 +123,19 @@ }, "updates_available": { "default": "mdi:package-up" + }, + "update_operation": { + "default": "mdi:progress-clock" + } + }, + "update": { + "system_updates": { + "default": "mdi:package-up" + } + }, + "button": { + "diagnostic_report": { + "default": "mdi:bug-outline" } }, "binary_sensor": { diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 589fe6d..1a9c75d 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -9,6 +9,6 @@ "integration_type": "device", "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", - "requirements": [], - "version": "0.3.6" + "requirements": ["aiooui>=0.1.9"], + "version": "0.3.7" } diff --git a/custom_components/ipfire/sensor.py b/custom_components/ipfire/sensor.py index 13644f2..5d518ca 100644 --- a/custom_components/ipfire/sensor.py +++ b/custom_components/ipfire/sensor.py @@ -2,6 +2,8 @@ from dataclasses import dataclass +import aiooui + from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -348,6 +350,7 @@ async def async_setup_entry( ] entities.append(IPFireDHCPLeasesSensor(coordinator, entry)) + entities.append(IPFireUpdateOperationSensor(coordinator, entry)) # The overall Download/Upload sensors represent the RED (WAN) interface. # Add separate byte counters for the internal GREEN, ORANGE, and BLUE zones. @@ -412,6 +415,76 @@ def native_value(self) -> int | float | str | None: return value + @property + def extra_state_attributes(self) -> dict[str, object] | None: + """Expose update details and operation state on the update count sensor.""" + if ( + self.entity_description.key != "package_updates" + or self.coordinator.data is None + ): + return None + + data = self.coordinator.data + attributes: dict[str, object] = {} + if data.available_updates is not None: + attributes["updates"] = [ + dict(update) for update in data.available_updates + ] + if data.update_operation is not None: + attributes["operation"] = dict(data.update_operation) + return attributes or None + + +class IPFireUpdateOperationSensor( + CoordinatorEntity[IPFireCoordinator], + SensorEntity, +): + """Report the state of an update started through the API.""" + + _attr_has_entity_name = True + _attr_translation_key = "update_operation" + _attr_entity_registry_enabled_default = True + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the update operation sensor.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_update_operation" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def native_value(self) -> str | None: + """Return the Pakfire update operation state.""" + if self.coordinator.data is None: + return None + operation = self.coordinator.data.update_operation + if operation is None: + return None + status = operation.get("status") + return status if isinstance(status, str) else None + + @property + def extra_state_attributes(self) -> dict[str, object] | None: + """Expose operation timestamps and errors for diagnostics.""" + if self.coordinator.data is None: + return None + operation = self.coordinator.data.update_operation + if operation is None: + return None + return { + key: operation[key] + for key in ("started_at", "finished_at", "exit_code", "error") + if key in operation + } + class IPFireDHCPLeasesSensor( CoordinatorEntity[IPFireCoordinator], @@ -457,7 +530,23 @@ def extra_state_attributes(self) -> dict[str, list[dict[str, object]]] | None: leases = self.coordinator.data.dhcp_leases if leases is None: return None - return {"leases": [dict(lease) for lease in leases]} + + lease_attributes: list[dict[str, object]] = [] + for lease in leases: + lease_data = dict(lease) + mac_address = lease_data.get("mac_address") or lease_data.get( + "mac" + ) + if isinstance(mac_address, str) and mac_address: + try: + lease_data["mac_vendor"] = aiooui.get_vendor(mac_address) + except (TypeError, ValueError): + lease_data["mac_vendor"] = None + else: + lease_data["mac_vendor"] = None + lease_attributes.append(lease_data) + + return {"leases": lease_attributes} class IPFireInterfaceTrafficSensor( diff --git a/custom_components/ipfire/translations/de.json b/custom_components/ipfire/translations/de.json index 4cc7775..5f4b09d 100644 --- a/custom_components/ipfire/translations/de.json +++ b/custom_components/ipfire/translations/de.json @@ -63,6 +63,10 @@ } } }, + "common": { + "diagnostic_report_title": "HA-IPFire: Fehlerbericht", + "diagnostic_report_notice": "Prüfe den Bericht vor dem Teilen. Er enthält keine Zugangsdaten, IP-Adressen, Hostnamen oder DHCP-Clientdaten." + }, "entity": { "sensor": { "download": { @@ -187,6 +191,17 @@ "updates_available": { "name": "Updates verfügbar" }, + "update_operation": { + "name": "Update-Vorgang", + "state": { + "idle": "Inaktiv", + "starting": "Startet", + "running": "Läuft", + "completed": "Abgeschlossen", + "failed": "Fehlgeschlagen", + "unknown": "Unbekannt" + } + }, "external_ip": { "name": "Externe IP-Adresse" }, @@ -257,12 +272,23 @@ "name": "D-Bus Daemon" } }, + "update": { + "system_updates": { + "name": "IPFire-Systemupdates" + }, + "reboot": { + "name": "Router neu starten" + } + }, "button": { "connect": { "name": "Verbinden" }, "disconnect": { "name": "Trennen" + }, + "diagnostic_report": { + "name": "Bericht für Fehlermeldungen" } } } diff --git a/custom_components/ipfire/translations/en.json b/custom_components/ipfire/translations/en.json index 85a85bc..7db8e4d 100644 --- a/custom_components/ipfire/translations/en.json +++ b/custom_components/ipfire/translations/en.json @@ -63,6 +63,10 @@ } } }, + "common": { + "diagnostic_report_title": "HA-IPFire: Error report", + "diagnostic_report_notice": "Review this report before sharing it. It excludes credentials, IP addresses, hostnames, and DHCP client details." + }, "entity": { "sensor": { "download": { @@ -187,6 +191,17 @@ "updates_available": { "name": "Updates Available" }, + "update_operation": { + "name": "Update Operation", + "state": { + "idle": "Idle", + "starting": "Starting", + "running": "Running", + "completed": "Completed", + "failed": "Failed", + "unknown": "Unknown" + } + }, "external_ip": { "name": "External IP Address" }, @@ -257,12 +272,23 @@ "name": "D-Bus Daemon" } }, + "update": { + "system_updates": { + "name": "IPFire System Updates" + }, + "reboot": { + "name": "Restart router" + } + }, "button": { "connect": { "name": "Connect" }, "disconnect": { "name": "Disconnect" + }, + "diagnostic_report": { + "name": "Error Report" } } } diff --git a/custom_components/ipfire/update.py b/custom_components/ipfire/update.py new file mode 100644 index 0000000..16887ba --- /dev/null +++ b/custom_components/ipfire/update.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +from typing import Any + +from homeassistant.components.update import ( + UpdateEntity, + UpdateEntityFeature, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .coordinator import IPFireCoordinator + + +PARALLEL_UPDATES = 1 + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up IPFire update entities.""" + coordinator: IPFireCoordinator = entry.runtime_data.coordinator + async_add_entities( + [ + IPFireSystemUpdateEntity(coordinator, entry), + IPFireRebootUpdateEntity(coordinator, entry), + ] + ) + + +class IPFireSystemUpdateEntity( + CoordinatorEntity[IPFireCoordinator], + UpdateEntity, +): + """Represent the complete set of available IPFire updates.""" + + _attr_has_entity_name = True + _attr_translation_key = "system_updates" + _attr_supported_features = ( + UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS + ) + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the system update entity.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_system_updates" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def available(self) -> bool: + """Require the API's detailed update list for this entity.""" + return ( + super().available + and self.coordinator.data is not None + and self.coordinator.data.available_updates is not None + ) + + @property + def has_update(self) -> bool: + """Return whether any core or package updates are pending.""" + updates = self._available_updates + return updates is not None and bool(updates) + + @property + def installed_version(self) -> str | None: + """Return the installed IPFire version.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.system.version + + @property + def latest_version(self) -> str | None: + """Summarize the batch target; Pakfire installs it as one operation.""" + updates = self._available_updates + if not updates: + return None + + core_update = next( + (update for update in updates if update.get("type") == "core"), + None, + ) + package_count = sum( + update.get("type") == "package" for update in updates + ) + + parts = [] + if core_update is not None: + parts.append(f"Core {core_update.get('available_release')}") + if package_count: + parts.append( + f"{package_count} package update" + f"{'s' if package_count != 1 else ''}" + ) + return " + ".join(parts) + + @property + def release_summary(self) -> str | None: + """List the packages and versions included in the update batch.""" + updates = self._available_updates + if updates is None: + return None + + lines = [] + for update in updates: + if update.get("type") == "core": + lines.append( + "Core update: release " + f"{update.get('installed_release')} → " + f"{update.get('available_release')}" + ) + continue + + name = update.get("name", "Unknown package") + installed = update.get("installed_version", "?") + available = update.get("available_version", "?") + lines.append(f"{name}: {installed} → {available}") + + summary = "\n".join(lines) + return summary[:255] + + @property + def in_progress(self) -> bool: + """Report when Pakfire is currently installing the update batch.""" + if self.coordinator.data is None: + return False + operation = self.coordinator.data.update_operation or {} + return operation.get("status") in {"starting", "running"} + + async def async_install( + self, + version: str | None, + backup: bool, + **kwargs: Any, + ) -> None: + """Start Pakfire's all-updates upgrade through the IPFire API.""" + await self.coordinator.async_start_upgrade() + + @property + def _available_updates(self) -> tuple[dict[str, object], ...] | None: + """Return the API-reported update batch, if available.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.available_updates + + +class IPFireRebootUpdateEntity( + CoordinatorEntity[IPFireCoordinator], + UpdateEntity, +): + """Offer a native Home Assistant update action for a required IPFire reboot.""" + + _attr_has_entity_name = True + _attr_translation_key = "reboot" + _attr_icon = "mdi:restart" + _attr_supported_features = UpdateEntityFeature.INSTALL + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the reboot update entity.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_reboot" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def available(self) -> bool: + """Require an API revision that supports reboot requests.""" + return super().available and self.coordinator.supports_reboot_action + + @property + def has_update(self) -> bool: + """Report a reboot action when IPFire requires a restart.""" + return ( + self.coordinator.data is not None + and self.coordinator.data.system.reboot_required is True + ) + + @property + def installed_version(self) -> str | None: + """Return the currently running IPFire version.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.system.version + + @property + def latest_version(self) -> str | None: + """Change the update state while a reboot is required.""" + if self.coordinator.data is None: + return None + version = self.coordinator.data.system.version + if self.has_update: + return f"{version} (reboot required)" + return version + + async def async_install( + self, + version: str | None, + backup: bool, + **kwargs: Any, + ) -> None: + """Start the IPFire reboot after Home Assistant confirmation.""" + await self.coordinator.async_reboot()