Files
hass-to-be-good/custom_components/strike/config_flow.py
2025-10-26 14:46:43 +01:00

165 lines
5.2 KiB
Python

"""Config flow for Strike Bitcoin integration."""
from __future__ import annotations
import logging
from typing import Any
import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from .const import (
API_BASE_URL,
API_TIMEOUT,
CONF_API_KEY,
CONF_CURRENCY_PAIR,
DEFAULT_CURRENCY_PAIR,
DEFAULT_NAME,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
TICKER_ENDPOINT,
)
_LOGGER = logging.getLogger(__name__)
async def validate_api_key(hass: HomeAssistant, api_key: str, currency_pair: str) -> dict[str, Any]:
"""Validate the API key by making a test request."""
session = async_get_clientsession(hass)
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {api_key}",
}
try:
async with session.get(
f"{API_BASE_URL}{TICKER_ENDPOINT}",
headers=headers,
params={"sourceCurrency": currency_pair[:3], "targetCurrency": currency_pair[3:]},
timeout=aiohttp.ClientTimeout(total=API_TIMEOUT),
) as response:
if response.status == 401:
raise InvalidAuth
if response.status == 403:
raise InvalidAuth
if response.status != 200:
_LOGGER.error("API request failed with status %s", response.status)
raise CannotConnect
data = await response.json()
_LOGGER.debug("API validation successful: %s", data)
return {"title": f"{DEFAULT_NAME} ({currency_pair})"}
except aiohttp.ClientError as err:
_LOGGER.error("Error connecting to Strike API: %s", err)
raise CannotConnect from err
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Unexpected error validating API key: %s", err)
raise CannotConnect from err
class StrikeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Strike Bitcoin."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
try:
info = await validate_api_key(
self.hass,
user_input[CONF_API_KEY],
user_input.get(CONF_CURRENCY_PAIR, DEFAULT_CURRENCY_PAIR),
)
await self.async_set_unique_id(
f"{user_input.get(CONF_CURRENCY_PAIR, DEFAULT_CURRENCY_PAIR)}"
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=info["title"],
data=user_input,
)
except InvalidAuth:
errors["base"] = "invalid_auth"
except CannotConnect:
errors["base"] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
data_schema = vol.Schema(
{
vol.Required(CONF_API_KEY): str,
vol.Optional(
CONF_CURRENCY_PAIR, default=DEFAULT_CURRENCY_PAIR
): str,
vol.Optional(
CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
): cv.positive_int,
}
)
return self.async_show_form(
step_id="user",
data_schema=data_schema,
errors=errors,
)
@staticmethod
@callback
def async_get_options_flow(
config_entry: config_entries.ConfigEntry,
) -> StrikeOptionsFlowHandler:
"""Get the options flow for this handler."""
return StrikeOptionsFlowHandler(config_entry)
class StrikeOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle Strike options."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional(
CONF_SCAN_INTERVAL,
default=self.config_entry.data.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
),
): cv.positive_int,
}
),
)
class CannotConnect(Exception):
"""Error to indicate we cannot connect."""
class InvalidAuth(Exception):
"""Error to indicate there is invalid auth."""