Skip to content

Commit

Permalink
hotfixs and code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Amateur-God committed Nov 3, 2024
1 parent b3fb58e commit 2e653ad
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 44 deletions.
13 changes: 4 additions & 9 deletions custom_components/technitiumdns/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

_LOGGER = logging.getLogger(__name__)


class TechnitiumDNSApi:
"""Class to interact with the TechnitiumDNS API."""

Expand Down Expand Up @@ -37,11 +36,9 @@ async def fetch_data(self, endpoint, params=None):
return data
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
_LOGGER.error("Attempt %d: Error fetching data from %s: %s", attempt + 1, endpoint, err)

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (108/100) Warning

Line too long (108/100)

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (108/100) Warning

Line too long (108/100)
if attempt == retries - 1: # Raise the exception if final attempt fails
raise Exception(
f"Error fetching data from {endpoint} after {retries} attempts: {err}"
) from err
await asyncio.sleep(5) # Wait 5 seconds before retrying
if attempt == retries - 1:
raise Exception(f"Error fetching data from {endpoint} after {retries} attempts: {err}") from err

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (120/100) Warning

Line too long (120/100)

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (120/100) Warning

Line too long (120/100)
await asyncio.sleep(5)
except Exception as e:

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Variable name "e" doesn't conform to snake_case naming style Warning

Variable name "e" doesn't conform to snake_case naming style

Check warning

Code scanning / Pylint (reported by Codacy)

Variable name "e" doesn't conform to snake_case naming style Warning

Variable name "e" doesn't conform to snake_case naming style
_LOGGER.error("An error occurred: %s", e)
raise Exception(f"An error occurred: {e}") from e
Expand Down Expand Up @@ -105,9 +102,7 @@ async def set_ad_blocking(self, enable):
data = await response.json()
_LOGGER.debug("Response: %s", data)
if data.get("status") != "ok":
raise Exception(
f"Error setting ad blocking: {data.get('errorMessage')}"
)
raise Exception(f"Error setting ad blocking: {data.get('errorMessage')}")

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (101/100) Warning

Line too long (101/100)

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (101/100) Warning

Line too long (101/100)
return data
except aiohttp.ClientError as err:
_LOGGER.error("Error setting ad blocking: %s", err)
Expand Down
71 changes: 36 additions & 35 deletions custom_components/technitiumdns/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,39 +65,42 @@ async def _async_update_data(self):

Technitiumdns_stats = Technitiumdns_statistics.get("response", {}).get("stats", {})
data = {
"queries": Technitiumdns_stats.get("totalQueries"),
"blocked_queries": Technitiumdns_stats.get("totalBlocked"),
"clients": Technitiumdns_stats.get("totalClients"),
"update_available": Technitiumdns_update_info.get("response", {}).get("updateAvailable"),
"no_error": Technitiumdns_stats.get("totalNoError"),
"server_failure": Technitiumdns_stats.get("totalServerFailure"),
"nx_domain": Technitiumdns_stats.get("totalNxDomain"),
"refused": Technitiumdns_stats.get("totalRefused"),
"authoritative": Technitiumdns_stats.get("totalAuthoritative"),
"recursive": Technitiumdns_stats.get("totalRecursive"),
"cached": Technitiumdns_stats.get("totalCached"),
"dropped": Technitiumdns_stats.get("totalDropped"),
"zones": Technitiumdns_stats.get("zones"),
"cached_entries": Technitiumdns_stats.get("cachedEntries"),
"allowed_zones": Technitiumdns_stats.get("allowedZones"),
"blocked_zones": Technitiumdns_stats.get("blockedZones"),
"allow_list_zones": Technitiumdns_stats.get("allowListZones"),
"block_list_zones": Technitiumdns_stats.get("blockListZones"),
"top_clients": "\n".join(
[f"{client['name']} ({client['hits']})" for client in Technitiumdns_top_clients.get("response", {}).get("topClients", [])[:5]]
),
"top_domains": "\n".join(
[f"{domain['name']} ({domain['hits']})" for domain in Technitiumdns_top_domains.get("response", {}).get("topDomains", [])[:5]]
),
"top_blocked_domains": "\n".join(
[f"{domain['name']} ({domain['hits']})" for domain in Technitiumdns_top_blocked_domains.get("response", {}).get("topBlockedDomains", [])[:5]]
),
"queries": Technitiumdns_stats.get("totalQueries", 0),
"blocked_queries": Technitiumdns_stats.get("totalBlocked", 0),
"clients": Technitiumdns_stats.get("totalClients", 0),
"update_available": Technitiumdns_update_info.get("response", {}).get("updateAvailable", False),

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (112/100) Warning

Line too long (112/100)

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (112/100) Warning

Line too long (112/100)
"no_error": Technitiumdns_stats.get("totalNoError", 0),
"server_failure": Technitiumdns_stats.get("totalServerFailure", 0),
"nx_domain": Technitiumdns_stats.get("totalNxDomain", 0),
"refused": Technitiumdns_stats.get("totalRefused", 0),
"authoritative": Technitiumdns_stats.get("totalAuthoritative", 0),
"recursive": Technitiumdns_stats.get("totalRecursive", 0),
"cached": Technitiumdns_stats.get("totalCached", 0),
"dropped": Technitiumdns_stats.get("totalDropped", 0),
"zones": Technitiumdns_stats.get("zones", 0),
"cached_entries": Technitiumdns_stats.get("cachedEntries", 0),
"allowed_zones": Technitiumdns_stats.get("allowedZones", 0),
"blocked_zones": Technitiumdns_stats.get("blockedZones", 0),
"allow_list_zones": Technitiumdns_stats.get("allowListZones", 0),
"block_list_zones": Technitiumdns_stats.get("blockListZones", 0),
"top_clients": [
{"name": client.get("name", "Unknown"), "hits": client.get("hits", 0)}
for client in Technitiumdns_top_clients.get("response", {}).get("topClients", [])[:5]

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (105/100) Warning

Line too long (105/100)

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (105/100) Warning

Line too long (105/100)
],
"top_domains": [
{"name": domain.get("name", "Unknown"), "hits": domain.get("hits", 0)}
for domain in Technitiumdns_top_domains.get("response", {}).get("topDomains", [])[:5]

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (105/100) Warning

Line too long (105/100)

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (105/100) Warning

Line too long (105/100)
],
"top_blocked_domains": [
{"name": domain.get("name", "Unknown"), "hits": domain.get("hits", 0)}
for domain in Technitiumdns_top_blocked_domains.get("response", {}).get("topBlockedDomains", [])[:5]

Check warning

Code scanning / Pylint (reported by Codacy)

Line too long (120/100) Warning

Line too long (120/100)

Check warning

Code scanning / Pylintpython3 (reported by Codacy)

Line too long (120/100) Warning

Line too long (120/100)
],
}
_LOGGER.debug("Data combined: %s", data)
return data
except Exception as err:
_LOGGER.error("Error fetching data: %s", err)
raise UpdateFailed(f"Error fetching data: {err}")
raise UpdateFailed(f"Error fetching data: {err}") from err

class TechnitiumDNSSensor(CoordinatorEntity, SensorEntity):
"""Representation of a TechnitiumDNS sensor."""
Expand Down Expand Up @@ -133,22 +136,20 @@ def state(self):
return state_value[:255]

if isinstance(state_value, (list, dict)):
# Convert complex types to string representation and ensure it is within the limit
state_value = len(state_value)
state_value = len(state_value) # Return length if complex

return state_value

@property
def extra_state_attributes(self):
"""Return additional attributes in a table-friendly format based on sensor type."""
attributes = {
"queries": self.coordinator.data.get("queries"),
"blocked_queries": self.coordinator.data.get("blocked_queries"),
"clients": self.coordinator.data.get("clients"),
"update_available": self.coordinator.data.get("update_available"),
"queries": self.coordinator.data.get("queries", 0),
"blocked_queries": self.coordinator.data.get("blocked_queries", 0),
"clients": self.coordinator.data.get("clients", 0),
"update_available": self.coordinator.data.get("update_available", False),
}

# Add structured table data based on the sensor type
if self._sensor_type == 'top_clients':
attributes["top_clients_table"] = [
{"Client": client.get('name', 'Unknown'), "Hits": client.get('hits', 0)}
Expand Down

0 comments on commit 2e653ad

Please sign in to comment.