From 94ba8329327c87ef0cf0061bb216230a6d98ea4c Mon Sep 17 00:00:00 2001 From: Tianyu Liu Date: Mon, 19 Aug 2024 12:05:46 +0200 Subject: [PATCH] Add action task --- src/cloud_util/homeassistant.py | 24 +++++++++++++++++++++--- src/cloud_util/ticktick.py | 3 ++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/cloud_util/homeassistant.py b/src/cloud_util/homeassistant.py index 261f03b..9e4b49b 100644 --- a/src/cloud_util/homeassistant.py +++ b/src/cloud_util/homeassistant.py @@ -1,3 +1,8 @@ +from __future__ import annotations + +import ast +from datetime import datetime, timedelta, timezone + from pydantic import BaseModel from src.cloud_util.ticktick import TickTick @@ -21,11 +26,24 @@ class HomeAssistant: def _process_ticktick_message(self, message: PublishMessage) -> dict[str, str]: if message.action == "create_shopping_list": - return self._create_shopping_list(item=message.content) + return self._create_shopping_list(content=message.content) + if message.action == "create_action_task": + return self._create_action_task(content=message.content) return {"Status": "Unknown action"} - def _create_shopping_list(self, item: str) -> dict[str, str]: + def _create_shopping_list(self, content: str) -> dict[str, str]: project_id = Config.get_env("TICKTICK_SHOPPING_LIST") - task = TickTick.Task(projectId=project_id, title=item) + 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)) return self._ticktick.create_task(task=task) diff --git a/src/cloud_util/ticktick.py b/src/cloud_util/ticktick.py index b2fa321..f471b83 100644 --- a/src/cloud_util/ticktick.py +++ b/src/cloud_util/ticktick.py @@ -75,5 +75,6 @@ class TickTick: requests.post(ticktick_task_creation_url, headers=header, json=asdict(task), timeout=10) return {"title": task.title} - def datetime_to_ticktick_format(self, datetime: datetime) -> str: + @staticmethod + def datetime_to_ticktick_format(datetime: datetime) -> str: return datetime.strftime("%Y-%m-%dT%H:%M:%S") + "+0000"