Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Epic Games Store integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from epicstore_api import EpicGamesStoreAPI
9 import voluptuous as vol
10 
11 from homeassistant import config_entries
12 from homeassistant.config_entries import ConfigFlowResult
13 from homeassistant.const import CONF_COUNTRY, CONF_LANGUAGE
14 from homeassistant.core import HomeAssistant
16  CountrySelector,
17  LanguageSelector,
18  LanguageSelectorConfig,
19 )
20 
21 from .const import DOMAIN, SUPPORTED_LANGUAGES
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 STEP_USER_DATA_SCHEMA = vol.Schema(
26  {
27  vol.Required(CONF_LANGUAGE): LanguageSelector(
28  LanguageSelectorConfig(languages=SUPPORTED_LANGUAGES)
29  ),
30  vol.Required(CONF_COUNTRY): CountrySelector(),
31  }
32 )
33 
34 
35 def get_default_language(hass: HomeAssistant) -> str | None:
36  """Get default language code based on Home Assistant config."""
37  language_code = f"{hass.config.language}-{hass.config.country}"
38  if language_code in SUPPORTED_LANGUAGES:
39  return language_code
40  if hass.config.language in SUPPORTED_LANGUAGES:
41  return hass.config.language
42  return None
43 
44 
45 async def validate_input(hass: HomeAssistant, user_input: dict[str, Any]) -> None:
46  """Validate the user input allows us to connect."""
47  api = EpicGamesStoreAPI(user_input[CONF_LANGUAGE], user_input[CONF_COUNTRY])
48  data = await hass.async_add_executor_job(api.get_free_games)
49 
50  if data.get("errors"):
51  _LOGGER.warning(data["errors"])
52 
53  assert data["data"]["Catalog"]["searchStore"]["elements"]
54 
55 
56 class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
57  """Handle a config flow for Epic Games Store."""
58 
59  VERSION = 1
60 
61  async def async_step_user(
62  self, user_input: dict[str, Any] | None = None
63  ) -> ConfigFlowResult:
64  """Handle the initial step."""
65  data_schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
66  STEP_USER_DATA_SCHEMA,
67  user_input
68  or {
69  CONF_LANGUAGE: get_default_language(self.hass),
70  CONF_COUNTRY: self.hass.config.country,
71  },
72  )
73  if user_input is None:
74  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=data_schema)
75 
76  await self.async_set_unique_idasync_set_unique_id(
77  f"freegames-{user_input[CONF_LANGUAGE]}-{user_input[CONF_COUNTRY]}"
78  )
79  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
80 
81  errors = {}
82 
83  try:
84  await validate_input(self.hass, user_input)
85  except Exception:
86  _LOGGER.exception("Unexpected exception")
87  errors["base"] = "unknown"
88  else:
89  return self.async_create_entryasync_create_entryasync_create_entry(
90  title=f"Epic Games Store - Free Games ({user_input[CONF_LANGUAGE]}-{user_input[CONF_COUNTRY]})",
91  data=user_input,
92  )
93 
94  return self.async_show_formasync_show_formasync_show_form(
95  step_id="user", data_schema=data_schema, errors=errors
96  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:63
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
None validate_input(HomeAssistant hass, dict[str, Any] user_input)
Definition: config_flow.py:45
str|None get_default_language(HomeAssistant hass)
Definition: config_flow.py:35