Files
home-automation-backend/src/cloud_util/homeassistant.py

57 lines
2.3 KiB
Python
Raw Normal View History

2024-08-19 12:05:46 +02:00
from __future__ import annotations
import ast
from datetime import datetime, timedelta, timezone
import httpx
2024-08-16 23:29:59 +02:00
from pydantic import BaseModel
from src.cloud_util.ticktick import TickTick
from src.config import Config
class HomeAssistant:
2024-08-21 16:30:43 +02:00
class Message(BaseModel):
2024-08-16 23:29:59 +02:00
target: str
action: str
content: str
def __init__(self, ticktick: TickTick) -> None:
self._ticktick = ticktick
2024-08-21 16:30:43 +02:00
def process_message(self, message: Message) -> dict[str, str]:
2024-08-16 23:29:59 +02:00
if message.target == "ticktick":
return self._process_ticktick_message(message=message)
return {"Status": "Unknown target"}
async def trigger_webhook(self, payload: dict[str, str], webhook_id: str) -> None:
token: str = Config.get_env("HOMEASSISTANT_TOKEN")
webhook_url: str = Config.get_env("HOMEASSISTANT_URL") + "/api/webhook/" + webhook_id
headers: dict[str, str] = {"Authorization": f"Bearer {token}"}
await httpx.AsyncClient().post(webhook_url, json=payload, headers=headers)
2024-08-21 16:30:43 +02:00
def _process_ticktick_message(self, message: Message) -> dict[str, str]:
2024-08-16 23:29:59 +02:00
if message.action == "create_shopping_list":
2024-08-19 12:05:46 +02:00
return self._create_shopping_list(content=message.content)
if message.action == "create_action_task":
return self._create_action_task(content=message.content)
2024-08-16 23:29:59 +02:00
return {"Status": "Unknown action"}
2024-08-19 12:05:46 +02:00
def _create_shopping_list(self, content: str) -> dict[str, str]:
2024-08-16 23:29:59 +02:00
project_id = Config.get_env("TICKTICK_SHOPPING_LIST")
2024-08-19 12:05:46 +02:00
item: dict[str, str] = ast.literal_eval(content)
task = TickTick.Task(projectId=project_id, title=item["item"])
return self._ticktick.create_task(task=task)
def _create_action_task(self, content: str) -> dict[str, str]:
detail: dict[str, str] = ast.literal_eval(content)
project_id = Config.get_env("TICKTICK_HOME_TASK_LIST")
due_hour = detail["due_hour"]
due = datetime.now(tz=datetime.now().astimezone().tzinfo) + timedelta(hours=due_hour)
due = (due + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
due = due.astimezone(timezone.utc)
task = TickTick.Task(projectId=project_id, title=detail["action"], dueDate=TickTick.datetime_to_ticktick_format(due))
2024-08-16 23:29:59 +02:00
return self._ticktick.create_task(task=task)