|
| 1 | +"""Adds config flow for Trafikverket Train integration.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from pytrafikverket import TrafikverketTrain |
| 7 | +import voluptuous as vol |
| 8 | + |
| 9 | +from homeassistant import config_entries |
| 10 | +from homeassistant.const import CONF_API_KEY, CONF_NAME, CONF_WEEKDAY, WEEKDAYS |
| 11 | +from homeassistant.data_entry_flow import FlowResult |
| 12 | +from homeassistant.helpers.aiohttp_client import async_get_clientsession |
| 13 | +import homeassistant.helpers.config_validation as cv |
| 14 | +import homeassistant.util.dt as dt_util |
| 15 | + |
| 16 | +from .const import CONF_FROM, CONF_TIME, CONF_TO, DOMAIN |
| 17 | +from .util import create_unique_id |
| 18 | + |
| 19 | +ERROR_INVALID_AUTH = "Source: Security, message: Invalid authentication" |
| 20 | +ERROR_INVALID_STATION = "Could not find a station with the specified name" |
| 21 | +ERROR_MULTIPLE_STATION = "Found multiple stations with the specified name" |
| 22 | + |
| 23 | +DATA_SCHEMA = vol.Schema( |
| 24 | + { |
| 25 | + vol.Required(CONF_API_KEY): cv.string, |
| 26 | + vol.Required(CONF_FROM): cv.string, |
| 27 | + vol.Required(CONF_TO): cv.string, |
| 28 | + vol.Optional(CONF_TIME): cv.string, |
| 29 | + vol.Required(CONF_WEEKDAY, default=WEEKDAYS): cv.multi_select( |
| 30 | + {day: day for day in WEEKDAYS} |
| 31 | + ), |
| 32 | + } |
| 33 | +) |
| 34 | +DATA_SCHEMA_REAUTH = vol.Schema( |
| 35 | + { |
| 36 | + vol.Required(CONF_API_KEY): cv.string, |
| 37 | + } |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +class TVTrainConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): |
| 42 | + """Handle a config flow for Trafikverket Train integration.""" |
| 43 | + |
| 44 | + VERSION = 1 |
| 45 | + |
| 46 | + entry: config_entries.ConfigEntry | None |
| 47 | + |
| 48 | + async def validate_input( |
| 49 | + self, api_key: str, train_from: str, train_to: str |
| 50 | + ) -> None: |
| 51 | + """Validate input from user input.""" |
| 52 | + web_session = async_get_clientsession(self.hass) |
| 53 | + train_api = TrafikverketTrain(web_session, api_key) |
| 54 | + await train_api.async_get_train_station(train_from) |
| 55 | + await train_api.async_get_train_station(train_to) |
| 56 | + |
| 57 | + async def async_step_reauth( |
| 58 | + self, user_input: dict[str, Any] | None = None |
| 59 | + ) -> FlowResult: |
| 60 | + """Handle re-authentication with Trafikverket.""" |
| 61 | + |
| 62 | + self.entry = self.hass.config_entries.async_get_entry(self.context["entry_id"]) |
| 63 | + return await self.async_step_reauth_confirm() |
| 64 | + |
| 65 | + async def async_step_reauth_confirm( |
| 66 | + self, user_input: dict[str, Any] | None = None |
| 67 | + ) -> FlowResult: |
| 68 | + """Confirm re-authentication with Trafikverket.""" |
| 69 | + errors: dict[str, str] = {} |
| 70 | + |
| 71 | + if user_input: |
| 72 | + api_key = user_input[CONF_API_KEY] |
| 73 | + |
| 74 | + assert self.entry is not None |
| 75 | + try: |
| 76 | + await self.validate_input( |
| 77 | + api_key, self.entry.data[CONF_FROM], self.entry.data[CONF_TO] |
| 78 | + ) |
| 79 | + except ValueError as err: |
| 80 | + if str(err) == ERROR_INVALID_AUTH: |
| 81 | + errors["base"] = "invalid_auth" |
| 82 | + elif str(err) == ERROR_INVALID_STATION: |
| 83 | + errors["base"] = "invalid_station" |
| 84 | + elif str(err) == ERROR_MULTIPLE_STATION: |
| 85 | + errors["base"] = "more_stations" |
| 86 | + else: |
| 87 | + errors["base"] = "cannot_connect" |
| 88 | + else: |
| 89 | + self.hass.config_entries.async_update_entry( |
| 90 | + self.entry, |
| 91 | + data={ |
| 92 | + **self.entry.data, |
| 93 | + CONF_API_KEY: api_key, |
| 94 | + }, |
| 95 | + ) |
| 96 | + await self.hass.config_entries.async_reload(self.entry.entry_id) |
| 97 | + return self.async_abort(reason="reauth_successful") |
| 98 | + |
| 99 | + return self.async_show_form( |
| 100 | + step_id="reauth_confirm", |
| 101 | + data_schema=DATA_SCHEMA_REAUTH, |
| 102 | + errors=errors, |
| 103 | + ) |
| 104 | + |
| 105 | + async def async_step_import(self, config: dict[str, Any] | None) -> FlowResult: |
| 106 | + """Import a configuration from config.yaml.""" |
| 107 | + |
| 108 | + return await self.async_step_user(user_input=config) |
| 109 | + |
| 110 | + async def async_step_user( |
| 111 | + self, user_input: dict[str, Any] | None = None |
| 112 | + ) -> FlowResult: |
| 113 | + """Handle the user step.""" |
| 114 | + errors: dict[str, str] = {} |
| 115 | + |
| 116 | + if user_input is not None: |
| 117 | + api_key: str = user_input[CONF_API_KEY] |
| 118 | + train_from: str = user_input[CONF_FROM] |
| 119 | + train_to: str = user_input[CONF_TO] |
| 120 | + train_time: str | None = user_input.get(CONF_TIME) |
| 121 | + train_days: list = user_input[CONF_WEEKDAY] |
| 122 | + |
| 123 | + name = f"{train_from} to {train_to}" |
| 124 | + if train_time: |
| 125 | + name = f"{train_from} to {train_to} at {train_time}" |
| 126 | + |
| 127 | + try: |
| 128 | + await self.validate_input(api_key, train_from, train_to) |
| 129 | + except ValueError as err: |
| 130 | + if str(err) == ERROR_INVALID_AUTH: |
| 131 | + errors["base"] = "invalid_auth" |
| 132 | + elif str(err) == ERROR_INVALID_STATION: |
| 133 | + errors["base"] = "invalid_station" |
| 134 | + elif str(err) == ERROR_MULTIPLE_STATION: |
| 135 | + errors["base"] = "more_stations" |
| 136 | + else: |
| 137 | + errors["base"] = "cannot_connect" |
| 138 | + else: |
| 139 | + if train_time: |
| 140 | + if bool(dt_util.parse_time(train_time) is None): |
| 141 | + errors["base"] = "invalid_time" |
| 142 | + if not errors: |
| 143 | + unique_id = create_unique_id( |
| 144 | + train_from, train_to, train_time, train_days |
| 145 | + ) |
| 146 | + await self.async_set_unique_id(unique_id) |
| 147 | + self._abort_if_unique_id_configured() |
| 148 | + return self.async_create_entry( |
| 149 | + title=name, |
| 150 | + data={ |
| 151 | + CONF_API_KEY: api_key, |
| 152 | + CONF_NAME: name, |
| 153 | + CONF_FROM: train_from, |
| 154 | + CONF_TO: train_to, |
| 155 | + CONF_TIME: train_time, |
| 156 | + CONF_WEEKDAY: train_days, |
| 157 | + }, |
| 158 | + ) |
| 159 | + |
| 160 | + return self.async_show_form( |
| 161 | + step_id="user", |
| 162 | + data_schema=DATA_SCHEMA, |
| 163 | + errors=errors, |
| 164 | + ) |
0 commit comments