Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions homeassistant/components/ukraine_alarm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@

import aiohttp
from aiohttp import ClientSession
from ukrainealarm.client import Client
from uasiren.client import Client

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_REGION
from homeassistant.const import CONF_REGION
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
Expand All @@ -24,14 +24,11 @@

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ukraine Alarm as config entry."""
api_key = entry.data[CONF_API_KEY]
region_id = entry.data[CONF_REGION]

websession = async_get_clientsession(hass)

coordinator = UkraineAlarmDataUpdateCoordinator(
hass, websession, api_key, region_id
)
coordinator = UkraineAlarmDataUpdateCoordinator(hass, websession, region_id)
await coordinator.async_config_entry_first_refresh()

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
Expand All @@ -56,19 +53,18 @@ def __init__(
self,
hass: HomeAssistant,
session: ClientSession,
api_key: str,
region_id: str,
) -> None:
"""Initialize."""
self.region_id = region_id
self.ukrainealarm = Client(session, api_key)
self.uasiren = Client(session)

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

async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
res = await self.ukrainealarm.get_alerts(self.region_id)
res = await self.uasiren.get_alerts(self.region_id)
except aiohttp.ClientError as error:
raise UpdateFailed(f"Error fetching alerts from API: {error}") from error

Expand Down
67 changes: 31 additions & 36 deletions homeassistant/components/ukraine_alarm/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@
from __future__ import annotations

import asyncio
import logging

import aiohttp
from ukrainealarm.client import Client
from uasiren.client import Client
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_REGION
from homeassistant.const import CONF_NAME, CONF_REGION
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)


class UkraineAlarmConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for Ukraine Alarm."""
Expand All @@ -21,54 +24,47 @@ class UkraineAlarmConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

def __init__(self):
"""Initialize a new UkraineAlarmConfigFlow."""
self.api_key = None
self.states = None
self.selected_region = None

async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}

if user_input is not None:
if len(self._async_current_entries()) == 5:
return self.async_abort(reason="max_regions")

if not self.states:
websession = async_get_clientsession(self.hass)
reason = None
unknown_err_msg = None
try:
regions = await Client(
websession, user_input[CONF_API_KEY]
).get_regions()
regions = await Client(websession).get_regions()
except aiohttp.ClientResponseError as ex:
errors["base"] = "invalid_api_key" if ex.status == 401 else "unknown"
if ex.status == 429:
reason = "rate_limit"
else:
reason = "unknown"
unknown_err_msg = str(ex)
except aiohttp.ClientConnectionError:
errors["base"] = "cannot_connect"
except aiohttp.ClientError:
errors["base"] = "unknown"
reason = "cannot_connect"
except aiohttp.ClientError as ex:
reason = "unknown"
unknown_err_msg = str(ex)
except asyncio.TimeoutError:
errors["base"] = "timeout"
reason = "timeout"

if not errors and not regions:
errors["base"] = "unknown"
if not reason and not regions:
reason = "unknown"
unknown_err_msg = "no regions returned"

if not errors:
self.api_key = user_input[CONF_API_KEY]
self.states = regions["states"]
return await self.async_step_state()

schema = vol.Schema(
{
vol.Required(CONF_API_KEY): str,
}
)
if unknown_err_msg:
_LOGGER.error("Failed to connect to the service: %s", unknown_err_msg)

return self.async_show_form(
step_id="user",
data_schema=schema,
description_placeholders={"api_url": "https://api.ukrainealarm.com/"},
errors=errors,
last_step=False,
)
if reason:
return self.async_abort(reason=reason)
self.states = regions["states"]

async def async_step_state(self, user_input=None):
"""Handle user-chosen state."""
return await self._handle_pick_region("state", "district", user_input)
return await self._handle_pick_region("user", "district", user_input)

async def async_step_district(self, user_input=None):
"""Handle user-chosen district."""
Expand Down Expand Up @@ -126,7 +122,6 @@ async def _async_finish_flow(self):
return self.async_create_entry(
title=self.selected_region["regionName"],
data={
CONF_API_KEY: self.api_key,
CONF_REGION: self.selected_region["regionId"],
CONF_NAME: self.selected_region["regionName"],
},
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ukraine_alarm/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "Ukraine Alarm",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/ukraine_alarm",
"requirements": ["ukrainealarm==0.0.1"],
"requirements": ["uasiren==0.0.1"],
"codeowners": ["@PaulAnnekov"],
"iot_class": "cloud_polling"
}
17 changes: 5 additions & 12 deletions homeassistant/components/ukraine_alarm/strings.json
Original file line number Diff line number Diff line change
@@ -1,36 +1,29 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_location%]"
},
"error": {
"invalid_api_key": "[%key:common::config_flow::error::invalid_api_key%]",
"max_regions": "Max 5 regions can be configured",
"already_configured": "[%key:common::config_flow::abort::already_configured_location%]",
"rate_limit": "Too much requests",
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"unknown": "[%key:common::config_flow::error::unknown%]",
"timeout": "[%key:common::config_flow::error::timeout_connect%]"
},
"step": {
"user": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
},
"description": "Set up the Ukraine Alarm integration. To generate an API key go to {api_url}"
},
"state": {
"data": {
"region": "Region"
},
"description": "Choose state to monitor"
},
"district": {
"data": {
"region": "[%key:component::ukraine_alarm::config::step::state::data::region%]"
"region": "[%key:component::ukraine_alarm::config::step::user::data::region%]"
},
"description": "If you want to monitor not only state, choose its specific district"
},
"community": {
"data": {
"region": "[%key:component::ukraine_alarm::config::step::state::data::region%]"
"region": "[%key:component::ukraine_alarm::config::step::user::data::region%]"
},
"description": "If you want to monitor not only state and district, choose its specific community"
}
Expand Down
15 changes: 4 additions & 11 deletions homeassistant/components/ukraine_alarm/translations/en.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
{
"config": {
"abort": {
"already_configured": "Location is already configured"
},
"error": {
"already_configured": "Location is already configured",
"cannot_connect": "Failed to connect",
"invalid_api_key": "Invalid API key",
"max_regions": "Max 5 regions can be configured",
"rate_limit": "Too much requests",
"timeout": "Timeout establishing connection",
"unknown": "Unexpected error"
},
Expand All @@ -22,17 +21,11 @@
},
"description": "If you want to monitor not only state, choose its specific district"
},
"state": {
"user": {
"data": {
"region": "Region"
},
"description": "Choose state to monitor"
},
"user": {
"data": {
"api_key": "API Key"
},
"description": "Set up the Ukraine Alarm integration. To generate an API key go to {api_url}"
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2346,7 +2346,7 @@ twitchAPI==2.5.2
uEagle==0.0.2

# homeassistant.components.ukraine_alarm
ukrainealarm==0.0.1
uasiren==0.0.1

# homeassistant.components.unifiprotect
unifi-discovery==1.1.2
Expand Down
2 changes: 1 addition & 1 deletion requirements_test_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1528,7 +1528,7 @@ twitchAPI==2.5.2
uEagle==0.0.2

# homeassistant.components.ukraine_alarm
ukrainealarm==0.0.1
uasiren==0.0.1

# homeassistant.components.unifiprotect
unifi-discovery==1.1.2
Expand Down
Loading