|
| 1 | +"""DataUpdateCoordinator for battery notes library.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from datetime import datetime, timedelta |
| 5 | +import logging |
| 6 | +import json |
| 7 | +import os |
| 8 | + |
| 9 | +from homeassistant.core import HomeAssistant |
| 10 | +from homeassistant.exceptions import ConfigEntryNotReady |
| 11 | +from homeassistant.helpers.update_coordinator import ( |
| 12 | + DataUpdateCoordinator, |
| 13 | + UpdateFailed, |
| 14 | +) |
| 15 | + |
| 16 | +from .library_updater import ( |
| 17 | + LibraryUpdaterClient, |
| 18 | + LibraryUpdaterClientError, |
| 19 | +) |
| 20 | + |
| 21 | +from .const import ( |
| 22 | + DOMAIN, |
| 23 | + LOGGER, |
| 24 | + DATA_LIBRARY_LAST_UPDATE, |
| 25 | +) |
| 26 | + |
| 27 | +_LOGGER = logging.getLogger(__name__) |
| 28 | + |
| 29 | +BUILT_IN_DATA_DIRECTORY = os.path.join(os.path.dirname(__file__), "data") |
| 30 | + |
| 31 | + |
| 32 | +class BatteryNotesLibraryUpdateCoordinator(DataUpdateCoordinator): |
| 33 | + """Class to manage fetching the library from GitHub.""" |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + hass: HomeAssistant, |
| 38 | + client: LibraryUpdaterClient, |
| 39 | + ) -> None: |
| 40 | + """Initialize.""" |
| 41 | + self.client = client |
| 42 | + super().__init__( |
| 43 | + hass=hass, |
| 44 | + logger=LOGGER, |
| 45 | + name=DOMAIN, |
| 46 | + update_interval=timedelta(hours=24), |
| 47 | + ) |
| 48 | + |
| 49 | + async def _async_update_data(self): |
| 50 | + """Update data via library.""" |
| 51 | + |
| 52 | + if await self.time_to_update_library() is False: |
| 53 | + return |
| 54 | + |
| 55 | + try: |
| 56 | + _LOGGER.debug("Getting library updates") |
| 57 | + |
| 58 | + content = await self.client.async_get_data() |
| 59 | + |
| 60 | + if validate_json(content): |
| 61 | + json_path = os.path.join( |
| 62 | + BUILT_IN_DATA_DIRECTORY, |
| 63 | + "library.json", |
| 64 | + ) |
| 65 | + |
| 66 | + f = open(json_path, mode="w", encoding="utf-8") |
| 67 | + f.write(content) |
| 68 | + |
| 69 | + self.hass.data[DOMAIN][DATA_LIBRARY_LAST_UPDATE] = datetime.now() |
| 70 | + |
| 71 | + _LOGGER.debug("Updated library") |
| 72 | + else: |
| 73 | + _LOGGER.error("Library file is invalid, not updated") |
| 74 | + |
| 75 | + except LibraryUpdaterClientError as exception: |
| 76 | + raise UpdateFailed(exception) from exception |
| 77 | + |
| 78 | + async def time_to_update_library(self) -> bool: |
| 79 | + """Check when last updated and if OK to do a new library update.""" |
| 80 | + try: |
| 81 | + if DATA_LIBRARY_LAST_UPDATE in self.hass.data[DOMAIN]: |
| 82 | + time_since_last_update = ( |
| 83 | + datetime.now() - self.hass.data[DOMAIN][DATA_LIBRARY_LAST_UPDATE] |
| 84 | + ) |
| 85 | + |
| 86 | + time_difference_in_hours = time_since_last_update / timedelta(hours=1) |
| 87 | + |
| 88 | + if time_difference_in_hours < 23: |
| 89 | + _LOGGER.debug("Skipping library updates") |
| 90 | + return False |
| 91 | + return True |
| 92 | + except ConfigEntryNotReady: |
| 93 | + # Ignore as we are initial load |
| 94 | + return True |
| 95 | + |
| 96 | + |
| 97 | +def validate_json(content: str) -> bool: |
| 98 | + """Check if content is valid json.""" |
| 99 | + try: |
| 100 | + library = json.loads(content) |
| 101 | + |
| 102 | + if "version" not in library: |
| 103 | + return False |
| 104 | + |
| 105 | + if library["version"] > 1: |
| 106 | + return False |
| 107 | + except ValueError: |
| 108 | + return False |
| 109 | + return True |
0 commit comments