Home Assistant Unofficial Reference 2024.12.1
keyring.py
Go to the documentation of this file.
1 """KNX Keyring handler."""
2 
3 import logging
4 from pathlib import Path
5 import shutil
6 from typing import Final
7 
8 from xknx.exceptions.exception import InvalidSecureConfiguration
9 from xknx.secure.keyring import Keyring, sync_load_keyring
10 
11 from homeassistant.components.file_upload import process_uploaded_file
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.storage import STORAGE_DIR
14 
15 from ..const import DOMAIN
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
20 DEFAULT_KNX_KEYRING_FILENAME: Final = "keyring.knxkeys"
21 
22 
24  hass: HomeAssistant, uploaded_file_id: str, password: str
25 ) -> Keyring:
26  """Validate the uploaded file and move it to the storage directory.
27 
28  Return a Keyring object.
29  Raises InvalidSecureConfiguration if the file or password is invalid.
30  """
31 
32  def _process_upload() -> Keyring:
33  with process_uploaded_file(hass, uploaded_file_id) as file_path:
34  try:
35  keyring = sync_load_keyring(
36  path=file_path,
37  password=password,
38  )
39  except InvalidSecureConfiguration as err:
40  _LOGGER.debug(err)
41  raise
42  dest_path = Path(hass.config.path(STORAGE_DIR, DOMAIN))
43  dest_path.mkdir(exist_ok=True)
44  dest_file = dest_path / DEFAULT_KNX_KEYRING_FILENAME
45  shutil.move(file_path, dest_file)
46  return keyring
47 
48  return await hass.async_add_executor_job(_process_upload)
Iterator[Path] process_uploaded_file(HomeAssistant hass, str file_id)
Definition: __init__.py:36
Keyring save_uploaded_knxkeys_file(HomeAssistant hass, str uploaded_file_id, str password)
Definition: keyring.py:25