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