Skip to content

Commit

Permalink
chore!: rewrite it all
Browse files Browse the repository at this point in the history
  • Loading branch information
wolffshots committed May 24, 2024
1 parent 70861da commit e49e32a
Show file tree
Hide file tree
Showing 19 changed files with 308 additions and 1,541 deletions.
186 changes: 23 additions & 163 deletions custom_components/audiobookshelf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,172 +1,32 @@
"""Init for audiobookshelf integration"""

import asyncio
"""Custom component for Audiobookshelf."""
import logging
from homeassistant.helpers import discovery
# from .sensor import async_refresh_libraries

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from requests import HTTPError, Timeout

from custom_components.audiobookshelf.api import AudiobookshelfApiClient

from .const import (
CONF_ACCESS_TOKEN,
CONF_HOST,
DOMAIN,
ISSUE_URL,
PLATFORMS,
SCAN_INTERVAL,
VERSION,
)

_LOGGER: logging.Logger = logging.getLogger(__package__)


class AudiobookshelfDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(
self,
hass: HomeAssistant,
client: AudiobookshelfApiClient,
) -> None:
"""Initialize."""
self.api = client
self.platforms = []

super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)

async def _async_update_data(self) -> dict[str, None]:
"""Update data via library."""
update = {"connectivity": None, "users": None, "sessions": None}
try:
connectivity_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/ping",
)
_LOGGER.debug(
"""async_update connectivity_update: %s""",
connectivity_update,
)
update["connectivity"] = connectivity_update
except ConnectionError:
update["connectivity"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["connectivity"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["connectivity"] = f"HTTPError: Generic HTTP Error happened {http_error}"
try:
users_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/api/users",
)
num_users = self.api.count_active_users(users_update)
_LOGGER.debug("""async_update num_users: %s""", num_users)
update["users"] = num_users
except ConnectionError:
update["users"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["users"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["users"] = f"HTTPError: Generic HTTP Error happened {http_error}"
try:
online_users_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/api/users/online",
)
open_sessions = self.api.count_open_sessions(online_users_update)
_LOGGER.debug("""async_update open_sessions: %s""", open_sessions)
update["sessions"] = open_sessions
except ConnectionError:
update["sessions"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["sessions"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["sessions"] = f"HTTPError: Generic HTTP Error happened {http_error}"
try:
library_stats_update = await self.api.api_wrapper(
method="get",
url=self.api.get_host() + "/api/libraries",
)
update["libraries"] = library_stats_update
except ConnectionError:
update["libraries"] = "ConnectionError: Unable to connect."
except (TimeoutError, Timeout):
update["libraries"] = "TimeoutError: Request timed out."
except HTTPError as http_error:
update["libraries"] = f"HTTPError: Generic HTTP Error happened {http_error}"
return update

async def async_setup(hass: HomeAssistant, config: Config) -> bool:
"""Setting up this integration using YAML is not supported."""
return True

async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
) -> bool:
"""Set up this integration using UI."""
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})
_LOGGER.info(
"""
-------------------------------------------------------------------
Audiobookshelf
Version: %s
This is a custom integration!
If you have any issues with this you need to open an issue here:
%s
-------------------------------------------------------------------
""",
VERSION,
ISSUE_URL,
)

host = entry.data.get(CONF_HOST)
access_token = entry.data.get(CONF_ACCESS_TOKEN)

session = async_get_clientsession(hass)
client = AudiobookshelfApiClient(host, access_token, session)

coordinator = AudiobookshelfDataUpdateCoordinator(hass=hass, client=client)
await coordinator.async_refresh()
DOMAIN = "audiobookshelf"

if not coordinator.last_update_success:
raise ConfigEntryNotReady
_LOGGER = logging.getLogger(__name__)

hass.data[DOMAIN][entry.entry_id] = coordinator
# async def async_setup(hass, config):
# """Set up the Audiobookshelf component."""
# # Schedule the setup of sensor platform
# hass.async_create_task(discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config))
# hass.async_create_task(async_refresh_libraries(hass))

for platform in PLATFORMS:
if entry.options.get(platform, True):
coordinator.platforms.append(platform)
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform),
)
entry.add_update_listener(async_reload_entry)
return True
# return True

async def async_setup(hass, config):
"""Set up the Audiobookshelf component."""
# Schedule the setup of sensor platform
hass.async_create_task(discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config))

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Handle removal of an entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
unloaded = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in PLATFORMS
if platform in coordinator.platforms
],
),
)
if unloaded:
hass.data[DOMAIN].pop(entry.entry_id)
# Use a helper to get the async_add_entities function from the sensor platform setup
# async def platform_setup():
# """Wait for platform to be set up and then start refreshing libraries."""
# platform = hass.data.get('sensor_platform')
# if platform:
# await async_refresh_libraries(hass, platform.async_add_entities)

return unloaded
# hass.async_create_task(platform_setup())

async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
return True
107 changes: 0 additions & 107 deletions custom_components/audiobookshelf/api.py

This file was deleted.

51 changes: 0 additions & 51 deletions custom_components/audiobookshelf/binary_sensor.py

This file was deleted.

Loading

0 comments on commit e49e32a

Please sign in to comment.