Skip to content

Commit e5eeb21

Browse files
committed
feat: Add API endpoint error handling
- Enhance error handling and add region endpoint in config flow. - Add new error messages for DTEK and Yasno API connection issues. - Proper no_accounts_found error usage
1 parent e197e3c commit e5eeb21

File tree

3 files changed

+38
-8
lines changed

3 files changed

+38
-8
lines changed

custom_components/svitlo_yeah/config_flow.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
from .api.dtek.json import DtekAPIJson
2020
from .api.e_svitlo import ESvitloClient
21-
from .api.yasno import YasnoApi
21+
from .api.yasno import YASNO_REGIONS_ENDPOINT, YasnoApi
2222
from .const import (
2323
CONF_ACCOUNT_ID,
2424
CONF_ADDRESS_STR,
@@ -41,6 +41,8 @@
4141
)
4242

4343
if TYPE_CHECKING:
44+
from collections.abc import Mapping
45+
4446
from .models import YasnoRegion
4547

4648

@@ -157,6 +159,8 @@ async def async_step_group(
157159
provider_type = self.data[CONF_PROVIDER_TYPE]
158160

159161
groups = []
162+
errors: dict[str, str] | None = None
163+
description_placeholders: Mapping[str, str] | None = None
160164
if provider_type == PROVIDER_TYPE_YASNO:
161165
if region_id and provider_id:
162166
temp_api = YasnoApi(
@@ -165,12 +169,29 @@ async def async_step_group(
165169
)
166170
await temp_api.fetch_planned_outage_data()
167171
groups = temp_api.get_yasno_groups()
172+
if not groups:
173+
description_placeholders = {"url": YASNO_REGIONS_ENDPOINT}
174+
# noinspection PyTypeChecker
175+
return self.async_abort(
176+
reason="yasno_connection_error",
177+
description_placeholders=description_placeholders,
178+
)
179+
168180
elif provider_type == PROVIDER_TYPE_DTEK_JSON and provider_id:
169181
urls = DTEK_PROVIDER_URLS.get(provider_id, [])
170182
if urls:
171183
temp_api = DtekAPIJson(urls=urls, group=None)
172184
await temp_api.fetch_data()
173185
groups = temp_api.get_dtek_region_groups()
186+
if not groups:
187+
description_placeholders = {
188+
"urls": urls[0] if len(urls) == 1 else urls
189+
} # ty:ignore[invalid-assignment]
190+
# noinspection PyTypeChecker
191+
return self.async_abort(
192+
reason="dtek_json_empty_data",
193+
description_placeholders=description_placeholders,
194+
)
174195

175196
data_schema = vol.Schema(
176197
{
@@ -186,7 +207,12 @@ async def async_step_group(
186207
},
187208
)
188209
# noinspection PyTypeChecker
189-
return self.async_show_form(step_id="group", data_schema=data_schema)
210+
return self.async_show_form(
211+
step_id="group",
212+
data_schema=data_schema,
213+
errors=errors,
214+
description_placeholders=description_placeholders,
215+
)
190216

191217
async def async_step_esvitlo_auth(
192218
self, user_input: dict | None = None

custom_components/svitlo_yeah/translations/en.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
"title": "Svitlo Yeah!",
33
"config": {
44
"abort": {
5-
"dtek_scraping_fail": "Error accessing the DTEK website\nIf you are sure the site is working, the reason is the site's protection against data collection (anti-bot system Incapsula Imperva).\nCollecting data on DTEK outages is a complex process because the site uses an anti-bot system.\nI can try to bypass the anti-bot system only through third-party specialized services.\nSuch a service costs about 2.5 EUR for 1000 requests (for example https://hypersolutions.co/pricing).\nIf the page on my cache server updates every 30 minutes, the maximum cost will be about ~2.5 EUR for ~20 days.\nOne obtained cookie can possibly be used multiple times, so the real cost may be lower (or significantly lower).\nIf someone is interested in this, I could implement everything myself, I just need the API key of the appropriate service.\nTelegram @ALERTua"
5+
"no_accounts_found": "No accounts found",
6+
"dtek_scraping_fail": "Error accessing the DTEK website\nIf you are sure the site is working, the reason is the site's protection against data collection (anti-bot system Incapsula Imperva).\nCollecting data on DTEK outages is a complex process because the site uses an anti-bot system.\nI can try to bypass the anti-bot system only through third-party specialized services.\nSuch a service costs about 2.5 EUR for 1000 requests (for example https://hypersolutions.co/pricing).\nIf the page on my cache server updates every 30 minutes, the maximum cost will be about ~2.5 EUR for ~20 days.\nOne obtained cookie can possibly be used multiple times, so the real cost may be lower (or significantly lower).\nIf someone is interested in this, I could implement everything myself, I just need the API key of the appropriate service.\nTelegram @ALERTua",
7+
"yasno_connection_error": "Failed to fetch Yasno groups.\nPlease check your connection to Yasno API.\n{url}",
8+
"dtek_json_empty_data": "Failed to fetch groups.\nPlease check your connection to the data source.\n`fact.data` field should exist and not be empty.\nThis can happen if there are no scheduled outages for today.\nPlease try to add the integration configuration later when the source contains the schedule data.\n{urls}"
69
},
710
"step": {
811
"user": {
@@ -41,8 +44,7 @@
4144
}
4245
},
4346
"error": {
44-
"invalid_auth": "Invalid username or password",
45-
"no_accounts_found": "No accounts found"
47+
"invalid_auth": "Invalid username or password"
4648
}
4749
},
4850
"device": {

custom_components/svitlo_yeah/translations/uk.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
"title": "Svitlo Yeah!",
33
"config": {
44
"abort": {
5-
"dtek_scraping_fail": "Помилка запиту на сайт ДТЕК\nЯкщо ви певні, що сайт працює, то причина в захисті сайту від збору даних (анти-бот система Incapsula Imperva).\nЗбір даних про відключення ДТЕК є складним процесом, оскільки сайт використовує антибот систему.\nЯ можу спробувати обійти антибот систему лише за допомогою сторонніх спеціалізованих сервісів.\nТакий сервіс коштує близько 2.5 EUR за 1000 запитів (наприклад https://hypersolutions.co/pricing).\nЯкщо сторінка на моєму кешу-сервері оновлюватиметься кожні 30 хвилин, максимальна вартість становитиме ~2.5 EUR за ~20 днів.\nОдин отриманий cookie можливо можна буде використовувати кілька разів, тому реальна вартість може бути нижчою (або значно нижчою).\nЯкщо хтось зацікавлений у цьому, я міг би реалізувати все це самостійно, мені потрібен лише API ключ відповідного сервісу.\nТелеграм @ALERTua"
5+
"no_accounts_found": "Не знайдено особових рахунків",
6+
"dtek_scraping_fail": "Помилка запиту на сайт ДТЕК\nЯкщо ви певні, що сайт працює, то причина в захисті сайту від збору даних (анти-бот система Incapsula Imperva).\nЗбір даних про відключення ДТЕК є складним процесом, оскільки сайт використовує антибот систему.\nЯ можу спробувати обійти антибот систему лише за допомогою сторонніх спеціалізованих сервісів.\nТакий сервіс коштує близько 2.5 EUR за 1000 запитів (наприклад https://hypersolutions.co/pricing).\nЯкщо сторінка на моєму кешу-сервері оновлюватиметься кожні 30 хвилин, максимальна вартість становитиме ~2.5 EUR за ~20 днів.\nОдин отриманий cookie можливо можна буде використовувати кілька разів, тому реальна вартість може бути нижчою (або значно нижчою).\nЯкщо хтось зацікавлений у цьому, я міг би реалізувати все це самостійно, мені потрібен лише API ключ відповідного сервісу.\nТелеграм @ALERTua",
7+
"yasno_connection_error": "Не вдалося отримати групи Yasno.\nПеревірте з'єднання з API Yasno.\n{url}",
8+
"dtek_json_empty_data": "Не вдалося отримати групи.\nПеревірте з'єднання з джерелом даних.\nПоле `fact.data` повинно існувати та не бути порожнім.\nЦе може статися, якщо на сьогодні графіку відключень ще немає.\nСпробуйте додати конфігурацію інтеграції пізніше, коли джерело міститиме графік відключень.\n{urls}"
69
},
710
"step": {
811
"user": {
@@ -41,8 +44,7 @@
4144
}
4245
},
4346
"error": {
44-
"invalid_auth": "Неправильне ім'я користувача або пароль",
45-
"no_accounts_found": "Не знайдено особових рахунків"
47+
"invalid_auth": "Неправильне ім'я користувача або пароль"
4648
}
4749
},
4850
"device": {

0 commit comments

Comments
 (0)