updated api for tag support
This commit is contained in:
1 parent
4f78e42699
commit
baada590c5
10 files changed
+95
-69
No files matched your search
@@ -2,7 +2,7 @@ from typing import Generic, List, TypeVar
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from pydantic.fields import Field
|
from pydantic.fields import Field
|
||||||
from pydantic.generics import GenericModel
|
from pydantic.generics import GenericModel
|
||||||
from src.automations.types import AutomationData
|
from src.automations.types import ExtenededAutomationData
|
||||||
|
|
||||||
DataT = TypeVar("DataT")
|
DataT = TypeVar("DataT")
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ class ListData(GenericModel, Generic[DataT]):
|
|||||||
|
|
||||||
class UpdateAutoRequest(BaseModel):
|
class UpdateAutoRequest(BaseModel):
|
||||||
index: int = Field(description="Index of the automation to update")
|
index: int = Field(description="Index of the automation to update")
|
||||||
data: AutomationData
|
data: ExtenededAutomationData
|
||||||
|
|
||||||
|
|
||||||
class DeleteAutoRequest(BaseModel):
|
class DeleteAutoRequest(BaseModel):
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
from itertools import chain
|
from itertools import chain
|
||||||
from typing import Iterable, Iterator
|
from typing import Iterable, Iterator
|
||||||
from pydantic.error_wrappers import ValidationError
|
from pydantic.error_wrappers import ValidationError
|
||||||
|
from src.automations.tags import TagManager
|
||||||
from src.json_serializer import normalize_obj
|
from src.json_serializer import normalize_obj
|
||||||
from .types import AutomationData, AutomationMetdata
|
from .types import AutomationData, AutomationMetdata, ExtenededAutomationData
|
||||||
from .parsers import _parse_actions
|
from .parsers import _parse_actions
|
||||||
from .errors import InvalidAutomationFile
|
from .errors import InvalidAutomationFile
|
||||||
|
|
||||||
# Single loader
|
# Single loader
|
||||||
def load_automation(
|
def load_automation(
|
||||||
automations_raw_data: Iterable[dict],
|
auto_raw: dict,
|
||||||
) -> Iterator[AutomationData]:
|
tags: dict,
|
||||||
|
) -> Iterator[ExtenededAutomationData]:
|
||||||
"""Converts an automation dictionary loaded directly from the config into
|
"""Converts an automation dictionary loaded directly from the config into
|
||||||
several python typed objects
|
several python typed objects
|
||||||
|
|
||||||
@@ -17,22 +19,22 @@ def load_automation(
|
|||||||
automations_raw_data (Iterable[dict])
|
automations_raw_data (Iterable[dict])
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Iterator[AutomationData]
|
Iterator[ExtenededAutomationData]
|
||||||
|
|
||||||
"""
|
"""
|
||||||
for auto_raw in automations_raw_data:
|
try:
|
||||||
try:
|
yield ExtenededAutomationData(
|
||||||
yield AutomationData(
|
metadata=AutomationMetdata.parse_obj(auto_raw),
|
||||||
metadata=AutomationMetdata.parse_obj(auto_raw),
|
sequence=list(
|
||||||
sequence=list(
|
_parse_actions(
|
||||||
_parse_actions(
|
chain(
|
||||||
chain(
|
auto_raw.get("condition", []),
|
||||||
auto_raw.get("condition", []),
|
auto_raw.get("action", []),
|
||||||
auto_raw.get("action", []),
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
),
|
)
|
||||||
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
|
),
|
||||||
)
|
trigger=[normalize_obj(obj) for obj in auto_raw.get("trigger", [])],
|
||||||
except ValidationError as err:
|
tags=tags,
|
||||||
raise InvalidAutomationFile from err
|
)
|
||||||
|
except ValidationError as err:
|
||||||
|
raise InvalidAutomationFile from err
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from typing import Iterator, List, Optional
|
from typing import Iterator, List, Optional
|
||||||
from src.automations.errors import FailedDeletion
|
from src.automations.errors import FailedDeletion
|
||||||
from src.automations.types import AutomationData
|
from src.automations.types import AutomationData, ExtenededAutomationData
|
||||||
from src.hass_config.loader import HassConfig
|
from src.hass_config.loader import HassConfig
|
||||||
from .loader import load_automation
|
from .loader import load_automation
|
||||||
|
|
||||||
@@ -14,21 +14,24 @@ class AutomationManager:
|
|||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
limit: int = 10,
|
limit: int = 10,
|
||||||
) -> Iterator[AutomationData]:
|
) -> Iterator[AutomationData]:
|
||||||
|
tags = self.hass_config.automation_tags
|
||||||
for i, auto in enumerate(self.hass_config.automations):
|
for i, auto in enumerate(self.hass_config.automations):
|
||||||
if i < offset:
|
if i < offset:
|
||||||
continue
|
continue
|
||||||
if i >= offset + limit:
|
if i >= offset + limit:
|
||||||
break
|
break
|
||||||
yield from load_automation([auto])
|
yield from load_automation(auto, tags.get(i, {}))
|
||||||
|
|
||||||
def get(self, index: int) -> Optional[AutomationData]:
|
def get(self, index: int) -> Optional[AutomationData]:
|
||||||
|
tags = self.hass_config.automation_tags
|
||||||
if index >= 0:
|
if index >= 0:
|
||||||
for i, auto in enumerate(self.hass_config.automations):
|
for i, auto in enumerate(self.hass_config.automations):
|
||||||
if i == index:
|
if i == index:
|
||||||
return next(load_automation(([auto])))
|
return next(load_automation(auto, tags.get(i, {})))
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def update(self, index: int, automation: AutomationData):
|
def update(self, index: int, automation: ExtenededAutomationData):
|
||||||
|
tags = self.hass_config.automation_tags
|
||||||
automations: List[dict] = []
|
automations: List[dict] = []
|
||||||
updated = False
|
updated = False
|
||||||
for i, orig_auto in enumerate(self.hass_config.automations):
|
for i, orig_auto in enumerate(self.hass_config.automations):
|
||||||
@@ -39,8 +42,10 @@ class AutomationManager:
|
|||||||
automations.append(orig_auto)
|
automations.append(orig_auto)
|
||||||
if not updated:
|
if not updated:
|
||||||
automations.append(automation.to_primitive())
|
automations.append(automation.to_primitive())
|
||||||
|
tags[index] = automation.tags
|
||||||
self.hass_config.save_automations(automations)
|
self.hass_config.save_automations(automations)
|
||||||
|
self.hass_config.save_tags(tags)
|
||||||
|
|
||||||
def delete(self, index: int):
|
def delete(self, index: int):
|
||||||
automations: List[dict] = []
|
automations: List[dict] = []
|
||||||
deleted = False
|
deleted = False
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
|
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List
|
from typing import Dict
|
||||||
from src.yaml_serializer import dump_yaml, load_yaml
|
from src.yaml_serializer import dump_yaml, load_yaml
|
||||||
|
|
||||||
class TagManager(Dict[str, List[str]]):
|
class TagManager(Dict[int, Dict[str, str]]):
|
||||||
def save(self, path: Path):
|
def save(self, path: Path):
|
||||||
path.write_text(dump_yaml(self))
|
path.write_text(dump_yaml(dict(self)))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def load(cls, path: Path):
|
def load(cls, path: Path):
|
||||||
|
|||||||
@@ -44,3 +44,6 @@ class AutomationData(BaseModel):
|
|||||||
"condition": [],
|
"condition": [],
|
||||||
"action": [action.to_primitive() for action in self.sequence],
|
"action": [action.to_primitive() for action in self.sequence],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class ExtenededAutomationData(AutomationData):
|
||||||
|
tags: Dict[str, str] = Field(default_factory=dict)
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
from src.automations.tags import TagManager
|
||||||
|
|
||||||
from src.yaml_serializer import load_yaml, dump_yaml
|
from src.yaml_serializer import load_yaml, dump_yaml
|
||||||
from src.yaml_serializer.types import IncludedYaml
|
from src.yaml_serializer.types import IncludedYaml
|
||||||
@@ -24,6 +25,18 @@ class HassConfig:
|
|||||||
except FileNotFoundError as err:
|
except FileNotFoundError as err:
|
||||||
raise MissingFile("automations.yaml") from err
|
raise MissingFile("automations.yaml") from err
|
||||||
return self.configurations["automation"]
|
return self.configurations["automation"]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def automation_tags(self) -> TagManager:
|
||||||
|
tag_path = self.get_automation_tags_path()
|
||||||
|
if not tag_path.exists():
|
||||||
|
return TagManager()
|
||||||
|
else:
|
||||||
|
return TagManager.load(tag_path)
|
||||||
|
|
||||||
|
|
||||||
|
def get_automation_tags_path(self) -> Path:
|
||||||
|
return self.root_path / "_shortu_automation_tags.yaml"
|
||||||
|
|
||||||
def get_configuration_path(self) -> Path:
|
def get_configuration_path(self) -> Path:
|
||||||
return self.root_path / "configuration.yaml"
|
return self.root_path / "configuration.yaml"
|
||||||
@@ -50,3 +63,6 @@ class HassConfig:
|
|||||||
self.get_configuration_path().write_text(
|
self.get_configuration_path().write_text(
|
||||||
dump_yaml({**self.configurations, "automation": automations})
|
dump_yaml({**self.configurations, "automation": automations})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def save_tags(self, tags: TagManager):
|
||||||
|
tags.save(self.get_automation_tags_path())
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
from unittest import TestCase
|
from unittest import TestCase
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from src.api.app import make_app
|
from src.api.app import make_app
|
||||||
from src.automations.types import AutomationData, AutomationMetdata
|
from src.automations.types import AutomationData, AutomationMetdata, ExtenededAutomationData
|
||||||
from tests.utils import get_example_automation_loader
|
from tests.utils import get_example_automation_loader
|
||||||
|
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ class automation_update_tests(BaseTestCase):
|
|||||||
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20})
|
resp = self.client.post("/automations/list", json={"limit": 1, "offset": 20})
|
||||||
new_auto = resp.json()["data"][0]
|
new_auto = resp.json()["data"][0]
|
||||||
self.assertNotEqual(original_auto, new_auto)
|
self.assertNotEqual(original_auto, new_auto)
|
||||||
self.assertEqual(AutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto)
|
self.assertEqual(ExtenededAutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto)
|
||||||
|
|
||||||
|
|
||||||
class automation_delete_tests(BaseTestCase):
|
class automation_delete_tests(BaseTestCase):
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ from unittest import TestCase
|
|||||||
from src.automations.types import (
|
from src.automations.types import (
|
||||||
AutomationActionNode,
|
AutomationActionNode,
|
||||||
AutomationConditionNode,
|
AutomationConditionNode,
|
||||||
AutomationData,
|
|
||||||
AutomationMetdata,
|
AutomationMetdata,
|
||||||
|
ExtenededAutomationData,
|
||||||
)
|
)
|
||||||
from src.automations.loader import load_automation
|
from src.automations.loader import load_automation
|
||||||
from src.yaml_serializer.types import (
|
from src.yaml_serializer.types import (
|
||||||
@@ -16,30 +16,29 @@ class loader_tests(TestCase):
|
|||||||
def test_load_automation_runs(self):
|
def test_load_automation_runs(self):
|
||||||
auto = list(
|
auto = list(
|
||||||
load_automation(
|
load_automation(
|
||||||
[
|
{
|
||||||
{
|
"id": "1616887975473",
|
||||||
"id": "1616887975473",
|
"alias": "Home Assistant Off",
|
||||||
"alias": "Home Assistant Off",
|
"description": "",
|
||||||
"description": "",
|
"trigger": [{"platform": "homeassistant", "event": "shutdown"}],
|
||||||
"trigger": [{"platform": "homeassistant", "event": "shutdown"}],
|
"condition": ["states(time.time) >= '10:00:00'"],
|
||||||
"condition": ["states(time.time) >= '10:00:00'"],
|
"action": [
|
||||||
"action": [
|
{
|
||||||
{
|
"device_id": SecretValue("my_mobile_phone", "..."),
|
||||||
"device_id": SecretValue("my_mobile_phone", "..."),
|
"domain": "mobile_app",
|
||||||
"domain": "mobile_app",
|
"type": "notify",
|
||||||
"type": "notify",
|
"title": "Hassio Status",
|
||||||
"title": "Hassio Status",
|
"message": "Hassio Is turning off...",
|
||||||
"message": "Hassio Is turning off...",
|
}
|
||||||
}
|
],
|
||||||
],
|
"mode": "single",
|
||||||
"mode": "single",
|
},
|
||||||
}
|
{}
|
||||||
]
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
auto[0],
|
auto[0],
|
||||||
AutomationData(
|
ExtenededAutomationData(
|
||||||
metadata=AutomationMetdata(
|
metadata=AutomationMetdata(
|
||||||
id="1616887975473",
|
id="1616887975473",
|
||||||
alias="Home Assistant Off",
|
alias="Home Assistant Off",
|
||||||
@@ -63,5 +62,6 @@ class loader_tests(TestCase):
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
tags={}
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from unittest import TestCase
|
from unittest import TestCase
|
||||||
from src.automations.errors import FailedDeletion, InvalidAutomationFile
|
from src.automations.errors import FailedDeletion, InvalidAutomationFile
|
||||||
from src.automations.types import AutomationData, AutomationMetdata
|
from src.automations.types import AutomationMetdata, ExtenededAutomationData
|
||||||
from tests.utils import (
|
from tests.utils import (
|
||||||
get_dummy_automation_loader,
|
get_dummy_automation_loader,
|
||||||
get_example_automation_loader,
|
get_example_automation_loader,
|
||||||
@@ -43,7 +43,7 @@ class manager_tests(TestCase):
|
|||||||
[],
|
[],
|
||||||
automation_in_conifguration_mode="none",
|
automation_in_conifguration_mode="none",
|
||||||
)
|
)
|
||||||
manager.update(1, AutomationData(metadata=AutomationMetdata(id="test1")))
|
manager.update(1, ExtenededAutomationData(metadata=AutomationMetdata(id="test1")))
|
||||||
auto = manager.get(0)
|
auto = manager.get(0)
|
||||||
self.assertIsNotNone(auto)
|
self.assertIsNotNone(auto)
|
||||||
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
||||||
@@ -51,7 +51,7 @@ class manager_tests(TestCase):
|
|||||||
def test_create_automation_with_example_folder(self):
|
def test_create_automation_with_example_folder(self):
|
||||||
_, _, manager = get_example_automation_loader()
|
_, _, manager = get_example_automation_loader()
|
||||||
self.assertEqual(manager.get_total_items(), 28)
|
self.assertEqual(manager.get_total_items(), 28)
|
||||||
manager.update(32, AutomationData(metadata=AutomationMetdata(id="test1")))
|
manager.update(32, ExtenededAutomationData(metadata=AutomationMetdata(id="test1")))
|
||||||
auto = manager.get(28)
|
auto = manager.get(28)
|
||||||
self.assertIsNotNone(auto)
|
self.assertIsNotNone(auto)
|
||||||
self.assertEqual(manager.get_total_items(), 29)
|
self.assertEqual(manager.get_total_items(), 29)
|
||||||
@@ -60,24 +60,24 @@ class manager_tests(TestCase):
|
|||||||
def test_update_automation(self):
|
def test_update_automation(self):
|
||||||
_, _, manager = get_dummy_automation_loader(
|
_, _, manager = get_dummy_automation_loader(
|
||||||
[
|
[
|
||||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||||
],
|
],
|
||||||
automation_in_conifguration_mode="none",
|
automation_in_conifguration_mode="none",
|
||||||
)
|
)
|
||||||
auto = manager.get(0)
|
auto = manager.get(0)
|
||||||
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
self.assertEqual(auto.metadata.id, "test1") # type: ignore
|
||||||
manager.update(0, AutomationData(metadata=AutomationMetdata(id="toaster-7")))
|
manager.update(0, ExtenededAutomationData(metadata=AutomationMetdata(id="toaster-7")))
|
||||||
auto = manager.get(0)
|
auto = manager.get(0)
|
||||||
self.assertEqual(auto.metadata.id, "toaster-7") # type: ignore
|
self.assertEqual(auto.metadata.id, "toaster-7") # type: ignore
|
||||||
|
|
||||||
def test_delete_automation(self):
|
def test_delete_automation(self):
|
||||||
_, _, manager = get_dummy_automation_loader(
|
_, _, manager = get_dummy_automation_loader(
|
||||||
[
|
[
|
||||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||||
],
|
],
|
||||||
automation_in_conifguration_mode="none",
|
automation_in_conifguration_mode="none",
|
||||||
)
|
)
|
||||||
@@ -90,9 +90,9 @@ class manager_tests(TestCase):
|
|||||||
def test_failed_deletion_automation(self):
|
def test_failed_deletion_automation(self):
|
||||||
_, _, manager = get_dummy_automation_loader(
|
_, _, manager = get_dummy_automation_loader(
|
||||||
[
|
[
|
||||||
AutomationData(metadata=AutomationMetdata(id="test1")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test2")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
|
||||||
AutomationData(metadata=AutomationMetdata(id="test3")),
|
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
|
||||||
],
|
],
|
||||||
automation_in_conifguration_mode="none",
|
automation_in_conifguration_mode="none",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
|
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import mkdtemp
|
from tempfile import mktemp
|
||||||
from unittest import TestCase
|
from unittest import TestCase
|
||||||
from src.automations.tags import TagManager
|
from src.automations.tags import TagManager
|
||||||
|
|
||||||
class tag_tests(TestCase):
|
class tag_tests(TestCase):
|
||||||
|
|
||||||
def test_load_and_save(self):
|
def test_load_and_save(self):
|
||||||
tmp_file = Path(mkdtemp())
|
tmp_file = Path(mktemp()).with_suffix('.yml')
|
||||||
tags = TagManager()
|
tags = TagManager()
|
||||||
tags['id#1'] = ['home things', 'barns', 'kitchen']
|
tags[0] = {'Room': "Kitchen", "Type": 'Lights'}
|
||||||
tags['id#2'] = ['kitchen']
|
tags[1] = {}
|
||||||
|
|
||||||
tags.save(tmp_file)
|
tags.save(tmp_file)
|
||||||
loaded_tags = TagManager.load(tmp_file)
|
loaded_tags = TagManager.load(tmp_file)
|
||||||
|
|||||||
Reference in new issue
Block a user