diff --git a/homeassistant/components/filesize/__init__.py b/homeassistant/components/filesize/__init__.py index 90d2af5d52a..f74efefbcad 100644 --- a/homeassistant/components/filesize/__init__.py +++ b/homeassistant/components/filesize/__init__.py @@ -2,18 +2,39 @@ from __future__ import annotations +import pathlib + from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_FILE_PATH from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryNotReady from .const import PLATFORMS from .coordinator import FileSizeCoordinator +FileSizeConfigEntry = ConfigEntry[FileSizeCoordinator] -async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + +def _get_full_path(hass: HomeAssistant, path: str) -> pathlib.Path: + """Check if path is valid, allowed and return full path.""" + get_path = pathlib.Path(path) + if not hass.config.is_allowed_path(path): + raise ConfigEntryNotReady(f"Filepath {path} is not valid or allowed") + + if not get_path.exists() or not get_path.is_file(): + raise ConfigEntryNotReady(f"Can not access file {path}") + + return get_path.absolute() + + +async def async_setup_entry(hass: HomeAssistant, entry: FileSizeConfigEntry) -> bool: """Set up from a config entry.""" - coordinator = FileSizeCoordinator(hass, entry.data[CONF_FILE_PATH]) + path = await hass.async_add_executor_job( + _get_full_path, hass, entry.data[CONF_FILE_PATH] + ) + coordinator = FileSizeCoordinator(hass, path) await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True diff --git a/homeassistant/components/filesize/coordinator.py b/homeassistant/components/filesize/coordinator.py index 2e59e922801..dcb7486209b 100644 --- a/homeassistant/components/filesize/coordinator.py +++ b/homeassistant/components/filesize/coordinator.py @@ -19,7 +19,7 @@ _LOGGER = logging.getLogger(__name__) class FileSizeCoordinator(DataUpdateCoordinator[dict[str, int | float | datetime]]): """Filesize coordinator.""" - def __init__(self, hass: HomeAssistant, unresolved_path: str) -> None: + def __init__(self, hass: HomeAssistant, path: pathlib.Path) -> None: """Initialize filesize coordinator.""" super().__init__( hass, @@ -28,28 +28,12 @@ class FileSizeCoordinator(DataUpdateCoordinator[dict[str, int | float | datetime update_interval=timedelta(seconds=60), always_update=False, ) - self._unresolved_path = unresolved_path - self._path: pathlib.Path | None = None - - def _get_full_path(self) -> pathlib.Path: - """Check if path is valid, allowed and return full path.""" - path = self._unresolved_path - get_path = pathlib.Path(path) - if not self.hass.config.is_allowed_path(path): - raise UpdateFailed(f"Filepath {path} is not valid or allowed") - - if not get_path.exists() or not get_path.is_file(): - raise UpdateFailed(f"Can not access file {path}") - - return get_path.absolute() + self.path: pathlib.Path = path def _update(self) -> os.stat_result: """Fetch file information.""" - if not self._path: - self._path = self._get_full_path() - try: - return self._path.stat() + return self.path.stat() except OSError as error: raise UpdateFailed(f"Can not retrieve file statistics {error}") from error diff --git a/homeassistant/components/filesize/sensor.py b/homeassistant/components/filesize/sensor.py index 761513b1f48..71a4e50edfe 100644 --- a/homeassistant/components/filesize/sensor.py +++ b/homeassistant/components/filesize/sensor.py @@ -4,7 +4,6 @@ from __future__ import annotations from datetime import datetime import logging -import pathlib from homeassistant.components.sensor import ( SensorDeviceClass, @@ -12,13 +11,13 @@ from homeassistant.components.sensor import ( SensorEntityDescription, SensorStateClass, ) -from homeassistant.config_entries import ConfigEntry -from homeassistant.const import CONF_FILE_PATH, EntityCategory, UnitOfInformation +from homeassistant.const import EntityCategory, UnitOfInformation from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity +from . import FileSizeConfigEntry from .const import DOMAIN from .coordinator import FileSizeCoordinator @@ -53,20 +52,12 @@ SENSOR_TYPES = ( async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: FileSizeConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the platform from config entry.""" - - path = entry.data[CONF_FILE_PATH] - get_path = await hass.async_add_executor_job(pathlib.Path, path) - fullpath = str(get_path.absolute()) - - coordinator = FileSizeCoordinator(hass, fullpath) - await coordinator.async_config_entry_first_refresh() - async_add_entities( - FilesizeEntity(description, fullpath, entry.entry_id, coordinator) + FilesizeEntity(description, entry.entry_id, entry.runtime_data) for description in SENSOR_TYPES ) @@ -79,13 +70,12 @@ class FilesizeEntity(CoordinatorEntity[FileSizeCoordinator], SensorEntity): def __init__( self, description: SensorEntityDescription, - path: str, entry_id: str, coordinator: FileSizeCoordinator, ) -> None: """Initialize the Filesize sensor.""" super().__init__(coordinator) - base_name = path.split("/")[-1] + base_name = str(coordinator.path.absolute()).rsplit("/", maxsplit=1)[-1] self._attr_unique_id = ( entry_id if description.key == "file" else f"{entry_id}-{description.key}" )