Implement code review for nzbget (#39425)

* implement code review for nzbget

* Update strings.json

* Update sensor.py

* Update config_flow.py

* Update sensor.py

* Update config_flow.py

* Update config_flow.py

* Update config_flow.py
This commit is contained in:
Chris Talkington 2020-08-30 13:59:15 -05:00 committed by GitHub
parent 65a9e18b27
commit 863c7414bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 23 deletions

View File

@ -78,26 +78,27 @@ class NZBGetConfigFlow(ConfigFlow, domain=DOMAIN):
if self._async_current_entries(): if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed") return self.async_abort(reason="single_instance_allowed")
if user_input is None: errors = {}
return self._show_setup_form()
if CONF_VERIFY_SSL not in user_input: if user_input is not None:
user_input[CONF_VERIFY_SSL] = DEFAULT_VERIFY_SSL if CONF_VERIFY_SSL not in user_input:
user_input[CONF_VERIFY_SSL] = DEFAULT_VERIFY_SSL
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
validate_input, self.hass, user_input validate_input, self.hass, user_input
) )
except NZBGetAPIException: except NZBGetAPIException:
return self._show_setup_form({"base": "cannot_connect"}) errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")
return self.async_abort(reason="unknown") return self.async_abort(reason="unknown")
else:
return self.async_create_entry(
title=user_input[CONF_HOST],
data=user_input,
)
return self.async_create_entry(title=user_input[CONF_HOST], data=user_input)
def _show_setup_form(self, errors: Optional[Dict] = None) -> Dict[str, Any]:
"""Show the setup form to the user."""
data_schema = { data_schema = {
vol.Required(CONF_HOST): str, vol.Required(CONF_HOST): str,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): str, vol.Optional(CONF_NAME, default=DEFAULT_NAME): str,

View File

@ -1,4 +1,5 @@
"""Monitor the NZBGet API.""" """Monitor the NZBGet API."""
from datetime import timedelta
import logging import logging
from typing import Callable, List, Optional from typing import Callable, List, Optional
@ -7,10 +8,11 @@ from homeassistant.const import (
CONF_NAME, CONF_NAME,
DATA_MEGABYTES, DATA_MEGABYTES,
DATA_RATE_MEGABYTES_PER_SECOND, DATA_RATE_MEGABYTES_PER_SECOND,
TIME_MINUTES, DEVICE_CLASS_TIMESTAMP,
) )
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util.dt import utcnow
from . import NZBGetEntity from . import NZBGetEntity
from .const import DATA_COORDINATOR, DOMAIN from .const import DATA_COORDINATOR, DOMAIN
@ -32,7 +34,7 @@ SENSOR_TYPES = {
"post_job_count": ["PostJobCount", "Post Processing Jobs", "Jobs"], "post_job_count": ["PostJobCount", "Post Processing Jobs", "Jobs"],
"post_paused": ["PostPaused", "Post Processing Paused", None], "post_paused": ["PostPaused", "Post Processing Paused", None],
"remaining_size": ["RemainingSizeMB", "Queue Size", DATA_MEGABYTES], "remaining_size": ["RemainingSizeMB", "Queue Size", DATA_MEGABYTES],
"uptime": ["UpTimeSec", "Uptime", TIME_MINUTES], "uptime": ["UpTimeSec", "Uptime", None],
} }
@ -85,6 +87,14 @@ class NZBGetSensor(NZBGetEntity, Entity):
name=f"{entry_name} {sensor_name}", name=f"{entry_name} {sensor_name}",
) )
@property
def device_class(self):
"""Return the device class."""
if "UpTimeSec" in self._sensor_type:
return DEVICE_CLASS_TIMESTAMP
return None
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return the unique ID of the sensor.""" """Return the unique ID of the sensor."""
@ -109,7 +119,7 @@ class NZBGetSensor(NZBGetEntity, Entity):
return round(value / 2 ** 20, 2) return round(value / 2 ** 20, 2)
if "UpTimeSec" in self._sensor_type and value > 0: if "UpTimeSec" in self._sensor_type and value > 0:
# Convert uptime from seconds to minutes uptime = utcnow() - timedelta(seconds=value)
return round(value / 60, 2) return uptime.replace(microsecond=0).isoformat()
return value return value

View File

@ -16,8 +16,7 @@
} }
}, },
"error": { "error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]"
}, },
"abort": { "abort": {
"single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]", "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]",