Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Folder watcher."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import os
7 from typing import Any
8 
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlowResult
12 from homeassistant.core import callback
14  SchemaCommonFlowHandler,
15  SchemaConfigFlowHandler,
16  SchemaFlowError,
17  SchemaFlowFormStep,
18 )
20  SelectSelector,
21  SelectSelectorConfig,
22  SelectSelectorMode,
23  TextSelector,
24 )
25 
26 from .const import CONF_FOLDER, CONF_PATTERNS, DEFAULT_PATTERN, DOMAIN
27 
28 
29 async def validate_setup(
30  handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
31 ) -> dict[str, Any]:
32  """Check path is a folder."""
33  value: str = user_input[CONF_FOLDER]
34  dir_in = os.path.expanduser(str(value))
35  handler.parent_handler._async_abort_entries_match({CONF_FOLDER: value}) # noqa: SLF001
36 
37  if not os.path.isdir(dir_in):
38  raise SchemaFlowError("not_dir")
39  if not os.access(dir_in, os.R_OK):
40  raise SchemaFlowError("not_readable_dir")
41  if not handler.parent_handler.hass.config.is_allowed_path(value):
42  raise SchemaFlowError("not_allowed_dir")
43 
44  return user_input
45 
46 
47 OPTIONS_SCHEMA = vol.Schema(
48  {
49  vol.Optional(CONF_PATTERNS, default=[DEFAULT_PATTERN]): SelectSelector(
51  options=[DEFAULT_PATTERN],
52  multiple=True,
53  custom_value=True,
54  mode=SelectSelectorMode.DROPDOWN,
55  )
56  ),
57  }
58 )
59 DATA_SCHEMA = vol.Schema(
60  {
61  vol.Required(CONF_FOLDER): TextSelector(),
62  }
63 ).extend(OPTIONS_SCHEMA.schema)
64 
65 CONFIG_FLOW = {
66  "user": SchemaFlowFormStep(schema=DATA_SCHEMA, validate_user_input=validate_setup),
67 }
68 OPTIONS_FLOW = {
69  "init": SchemaFlowFormStep(schema=OPTIONS_SCHEMA),
70 }
71 
72 
74  """Handle a config flow for Folder Watcher."""
75 
76  config_flow = CONFIG_FLOW
77  options_flow = OPTIONS_FLOW
78 
79  def async_config_entry_title(self, options: Mapping[str, Any]) -> str:
80  """Return config entry title."""
81  return f"Folder Watcher {options[CONF_FOLDER]}"
82 
83  @callback
85  self, data: Mapping[str, Any], **kwargs: Any
86  ) -> ConfigFlowResult:
87  """Finish config flow and create a config entry."""
88  self._async_abort_entries_match_async_abort_entries_match({CONF_FOLDER: data[CONF_FOLDER]})
89  return super().async_create_entry(data, **kwargs)
ConfigFlowResult async_create_entry(self, Mapping[str, Any] data, **Any kwargs)
Definition: config_flow.py:86
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=None)
dict[str, Any] validate_setup(SchemaCommonFlowHandler handler, dict[str, Any] user_input)
Definition: config_flow.py:31