added auto searching

This commit is contained in:
Ari Sosnovsky committed 2021-11-11 11:12:50 -05:00
1 parent d61085c2f1
commit a05c1b9dca
10 files changed
+112 -24

No files matched your search

+3 -2
View File
@@ -1,7 +1,7 @@
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from ..env import ROOT_FOLDER
from . import ping, search
from src.env import ROOT_FOLDER
from .routes import ping, search, automations
app = FastAPI()
app.mount(
@@ -14,3 +14,4 @@ app.mount(
)
app.include_router(ping.router, prefix="/ping")
app.include_router(search.router, prefix="/search")
app.include_router(automations.router, prefix="/automations")
+12
View File
@@ -0,0 +1,12 @@
from src.env import ROOT_FOLDER
from src.db.connection import HassDatabase
from src.config.AutomationLoader import AutomationLoader
from src.config.HassSafeConstructor import load_hass_config
hass_config = load_hass_config(ROOT_FOLDER / "tests/samples")
db_connection = HassDatabase(
f"sqlite:///{ROOT_FOLDER / 'tests/samples'}/home-assistant_v2.db"
)
automation_loader = AutomationLoader(hass_config)
View File
Whitespace-only changes.
+40
View File
@@ -0,0 +1,40 @@
from typing import Optional
from fastapi import APIRouter, HTTPException
from ..config import automation_loader
router = APIRouter()
@router.get("/list")
def read_ping(
offset: int = 0,
limit: int = 10,
alias: Optional[str] = None,
description: Optional[str] = None,
mode: Optional[str] = None,
):
return list(
automation_loader.find(
offset=offset,
limit=limit,
alias=alias,
description=description,
mode=mode,
)
)
@router.get("/{index}")
def read_ping(index: int):
if auto := automation_loader.get(index):
return auto
else:
raise HTTPException(
status_code=400,
detail={
"index": "out of bounds",
"must_be": f">= 0 or < {len(automation_loader)}",
"specified": index,
},
)
@@ -1,12 +1,12 @@
from fastapi import APIRouter
from datetime import datetime
from ..env import BUILD_VERSION
from src.env import BUILD_VERSION
router = APIRouter()
@router.get("/ping")
@router.get("/")
def read_ping():
return {
"version": BUILD_VERSION,
@@ -1,14 +1,11 @@
from typing import Dict, Optional
from typing import Optional
from fastapi import APIRouter
from pydantic.main import BaseModel
from src.db import entities, connection
from src.db import entities
from ..config import db_connection
router = APIRouter()
db_connection = connection.HassDatabase(
"sqlite:////home/asosnovsky/LinuxProjects/random/Shortumation/api/tests/samples/home-assistant_v2.db"
)
class EntityRequest(BaseModel):
domain: Optional[str] = None
-9
View File
@@ -1,9 +0,0 @@
from typing import Literal
SearchObjects = Literal[
"entity_id",
"device_id",
"domain",
"event_type",
"statistic_id",
]
+33 -2
View File
@@ -1,5 +1,6 @@
from typing import Dict, Iterable, List, Literal, Optional, Tuple, Union
from typing import Dict, Iterable, List, Literal, Optional, Union
from pydantic.fields import Field
from pydantic.error_wrappers import ValidationError
from src.json_serializer import json_dumps, normalize_obj
from src.config.HassSafeConstructor import HassConfig, IncludedYaml, SecretValue
from pydantic import BaseModel
@@ -150,7 +151,7 @@ def _parse_conditions(
# Global Loader
class AutomationLoader:
def __init__(self, loaded_yaml: HassConfig) -> None:
self.automation_ref = loaded_yaml["automation"]
self.automation_ref = loaded_yaml.config["automation"]
if isinstance(self.automation_ref, IncludedYaml):
self.automation_raw_data: list = self.automation_ref.data
@@ -162,3 +163,33 @@ class AutomationLoader:
raise AutomationLoaderException(
f"Invalid automation file, expected it to be a 'list' instead it's a '{type(self.automation_data)}'"
)
self.automations_data = list(load_automation(self.automation_raw_data))
def find(
self,
offset: int = 0,
limit: int = 10,
alias: Optional[str] = None,
description: Optional[str] = None,
mode: Optional[str] = None,
):
for auto in self.automations_data[offset : (offset + limit)]:
if alias is not None:
if auto.metadata.alias.lower().count(alias.lower()) <= 0:
continue
if description is not None:
if auto.metadata.description.lower().count(description.lower()) <= 0:
continue
if mode is not None:
if auto.metadata.mode.lower().count(mode.lower()) <= 0:
continue
yield auto
def get(self, index: int):
if (index < 0) or (len(self.automations_data) <= index):
return None
return self.automations_data[index]
def __len__(self):
return len(self.automations_data)
+1 -1
View File
@@ -2,6 +2,6 @@ from decouple import config
from pathlib import Path
ROOT_FOLDER = Path(__file__).parent.parent
ROOT_FOLDER = Path(__file__).parent.parent.absolute()
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
LOG_LEVEL = config("LOG_LEVEL", "INFO")
+18 -2
View File
@@ -3,13 +3,19 @@ from src.config.AutomationLoader import (
AutomationActionNode,
AutomationConditionNode,
AutomationData,
AutomationLoader,
AutomationMetdata,
load_automation,
_parse_conditions,
_parse_actions,
)
from src.json_serializer import NOT_IMPLEMENTED_SV_MSG
from src.config.HassSafeConstructor import SecretValue, load_hass_config, IncludedYaml
from src.config.HassSafeConstructor import (
HassConfig,
SecretValue,
load_hass_config,
IncludedYaml,
)
from tests.utils import SAMPLE_HA_PATH
@@ -227,7 +233,7 @@ class config_finder_tests(TestCase):
for expected, parsed in zip(expected_process, _parse_actions(raw_conditions)):
self.assertEqual(parsed, expected)
def test_automation_loader(self):
def test_load_automation_runs(self):
auto = list(
load_automation(
[
@@ -283,3 +289,13 @@ class config_finder_tests(TestCase):
],
),
)
def test_finding_with_AutomationLoader(self):
automation_loader = AutomationLoader(load_hass_config(SAMPLE_HA_PATH))
first_auto_with_find = list(automation_loader.find(limit=1))
first_auto_with_get = automation_loader.get(0)
self.assertEqual(first_auto_with_find[0], first_auto_with_get)
kitchen_autos = list(automation_loader.find(alias="kitchen"))
self.assertTrue(len(kitchen_autos), 3)