Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Google Cloud integration."""
2 
3 from __future__ import annotations
4 
5 import json
6 import logging
7 from typing import TYPE_CHECKING, Any, cast
8 
9 from google.cloud import texttospeech
10 import voluptuous as vol
11 
12 from homeassistant.components.file_upload import process_uploaded_file
13 from homeassistant.components.tts import CONF_LANG
14 from homeassistant.config_entries import (
15  ConfigEntry,
16  ConfigFlow,
17  ConfigFlowResult,
18  OptionsFlow,
19 )
20 from homeassistant.core import callback
22  FileSelector,
23  FileSelectorConfig,
24  SelectSelector,
25  SelectSelectorConfig,
26  SelectSelectorMode,
27 )
28 
29 from .const import (
30  CONF_KEY_FILE,
31  CONF_SERVICE_ACCOUNT_INFO,
32  CONF_STT_MODEL,
33  DEFAULT_LANG,
34  DEFAULT_STT_MODEL,
35  DOMAIN,
36  SUPPORTED_STT_MODELS,
37  TITLE,
38 )
39 from .helpers import (
40  async_tts_voices,
41  tts_options_schema,
42  tts_platform_schema,
43  validate_service_account_info,
44 )
45 
46 _LOGGER = logging.getLogger(__name__)
47 
48 UPLOADED_KEY_FILE = "uploaded_key_file"
49 
50 STEP_USER_DATA_SCHEMA = vol.Schema(
51  {
52  vol.Required(UPLOADED_KEY_FILE): FileSelector(
53  FileSelectorConfig(accept=".json,application/json")
54  )
55  }
56 )
57 
58 
59 class GoogleCloudConfigFlow(ConfigFlow, domain=DOMAIN):
60  """Handle a config flow for Google Cloud integration."""
61 
62  VERSION = 1
63 
64  _name: str | None = None
65  entry: ConfigEntry | None = None
66  abort_reason: str | None = None
67 
68  def _parse_uploaded_file(self, uploaded_file_id: str) -> dict[str, Any]:
69  """Read and parse an uploaded JSON file."""
70  with process_uploaded_file(self.hass, uploaded_file_id) as file_path:
71  contents = file_path.read_text()
72  return cast(dict[str, Any], json.loads(contents))
73 
74  async def async_step_user(
75  self, user_input: dict[str, Any] | None = None
76  ) -> ConfigFlowResult:
77  """Handle the initial step."""
78  errors: dict[str, Any] = {}
79  if user_input is not None:
80  try:
81  service_account_info = await self.hass.async_add_executor_job(
82  self._parse_uploaded_file_parse_uploaded_file, user_input[UPLOADED_KEY_FILE]
83  )
84  validate_service_account_info(service_account_info)
85  except ValueError:
86  _LOGGER.exception("Reading uploaded JSON file failed")
87  errors["base"] = "invalid_file"
88  else:
89  data = {CONF_SERVICE_ACCOUNT_INFO: service_account_info}
90  if self.entry:
91  if TYPE_CHECKING:
92  assert self.abort_reason
93  return self.async_update_reload_and_abortasync_update_reload_and_abort(
94  self.entry, data=data, reason=self.abort_reason
95  )
96  return self.async_create_entryasync_create_entryasync_create_entry(title=TITLE, data=data)
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="user",
99  data_schema=STEP_USER_DATA_SCHEMA,
100  errors=errors,
101  description_placeholders={
102  "url": "https://console.cloud.google.com/apis/credentials/serviceaccountkey"
103  },
104  )
105 
106  async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
107  """Import Google Cloud configuration from YAML."""
108 
109  def _read_key_file() -> dict[str, Any]:
110  with open(
111  self.hass.config.path(import_data[CONF_KEY_FILE]), encoding="utf8"
112  ) as f:
113  return cast(dict[str, Any], json.load(f))
114 
115  service_account_info = await self.hass.async_add_executor_job(_read_key_file)
116  try:
117  validate_service_account_info(service_account_info)
118  except ValueError:
119  _LOGGER.exception("Reading credentials JSON file failed")
120  return self.async_abortasync_abortasync_abort(reason="invalid_file")
121  options = {
122  k: v for k, v in import_data.items() if k in tts_platform_schema().schema
123  }
124  options.pop(CONF_KEY_FILE)
125  _LOGGER.debug("Creating imported config entry with options: %s", options)
126  return self.async_create_entryasync_create_entryasync_create_entry(
127  title=TITLE,
128  data={CONF_SERVICE_ACCOUNT_INFO: service_account_info},
129  options=options,
130  )
131 
132  @staticmethod
133  @callback
135  config_entry: ConfigEntry,
136  ) -> GoogleCloudOptionsFlowHandler:
137  """Create the options flow."""
139 
140 
142  """Google Cloud options flow."""
143 
144  async def async_step_init(
145  self, user_input: dict[str, Any] | None = None
146  ) -> ConfigFlowResult:
147  """Manage the options."""
148  if user_input is not None:
149  return self.async_create_entryasync_create_entry(data=user_input)
150 
151  service_account_info = self.config_entryconfig_entryconfig_entry.data[CONF_SERVICE_ACCOUNT_INFO]
152  client: texttospeech.TextToSpeechAsyncClient = (
153  texttospeech.TextToSpeechAsyncClient.from_service_account_info(
154  service_account_info
155  )
156  )
157  voices = await async_tts_voices(client)
158  return self.async_show_formasync_show_form(
159  step_id="init",
160  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
161  vol.Schema(
162  {
163  vol.Optional(
164  CONF_LANG,
165  default=DEFAULT_LANG,
166  ): SelectSelector(
168  mode=SelectSelectorMode.DROPDOWN, options=list(voices)
169  )
170  ),
172  self.config_entryconfig_entryconfig_entry.options, voices, from_config_flow=True
173  ).schema,
174  vol.Optional(
175  CONF_STT_MODEL,
176  default=DEFAULT_STT_MODEL,
177  ): SelectSelector(
179  mode=SelectSelectorMode.DROPDOWN,
180  options=SUPPORTED_STT_MODELS,
181  )
182  ),
183  }
184  ),
185  self.config_entryconfig_entryconfig_entry.options,
186  ),
187  )
dict[str, Any] _parse_uploaded_file(self, str uploaded_file_id)
Definition: config_flow.py:68
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:76
ConfigFlowResult async_step_import(self, dict[str, Any] import_data)
Definition: config_flow.py:106
GoogleCloudOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:136
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:146
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_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
None config_entry(self, ConfigEntry value)
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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
Iterator[Path] process_uploaded_file(HomeAssistant hass, str file_id)
Definition: __init__.py:36
dict[str, list[str]] async_tts_voices(texttospeech.TextToSpeechAsyncClient client)
Definition: helpers.py:42
vol.Schema tts_options_schema(Mapping[str, Any] config_options, dict[str, list[str]] voices, bool from_config_flow=False)
Definition: helpers.py:58
None validate_service_account_info(Mapping[str, str] info)
Definition: helpers.py:170
None open(self, **Any kwargs)
Definition: lock.py:86