Add homeassistant to ticktick

This commit is contained in:
2024-09-19 15:10:33 +02:00
parent 271368bf52
commit 9c414d28ad
3 changed files with 333 additions and 1 deletions

View File

@@ -9,6 +9,7 @@ import (
"time"
"github.com/spf13/viper"
"github.com/t-liu93/home-automation-backend/util/ticktick"
)
type haMessage struct {
@@ -17,6 +18,11 @@ type haMessage struct {
Content string `json:"content"`
}
type actionTask struct {
Action string `json:"action"`
DueHour int `json:"due_hour"`
}
func HandleHaMessage(w http.ResponseWriter, r *http.Request) {
var message haMessage
decoder := json.NewDecoder(r.Body)
@@ -33,6 +39,8 @@ func HandleHaMessage(w http.ResponseWriter, r *http.Request) {
handlePooRecorderMsg(message)
case "location_recorder":
handleLocationRecorderMsg(message)
case "ticktick":
handleTicktickMsg(message)
}
}
@@ -66,6 +74,13 @@ func handleLocationRecorderMsg(message haMessage) {
}
}
func handleTicktickMsg(message haMessage) {
switch message.Action {
case "create_action_task":
createActionTask(message)
}
}
func handleGetLatestPoo() {
client := &http.Client{
Timeout: time.Second * 1,
@@ -76,3 +91,31 @@ func handleGetLatestPoo() {
slog.Warn(fmt.Sprintln("handleGetLatestPoo Error sending request to poo recorder", err))
}
}
func createActionTask(message haMessage) {
if !viper.InConfig("homeassistant.actionTaskProjectId") {
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file")
return
}
projectId := viper.GetString("homeassistant.actionTaskProjectId")
detail := strings.ReplaceAll(message.Content, "'", "\"")
var task actionTask
err := json.Unmarshal([]byte(detail), &task)
if err != nil {
slog.Warn(fmt.Sprintln("Homeassistant.createActionTask Error unmarshalling", err))
return
}
dueHour := task.DueHour
due := time.Now().Add(time.Hour * time.Duration(dueHour))
dueNextMidnight := time.Date(due.Year(), due.Month(), due.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, 1)
dueTicktick := dueNextMidnight.UTC().Format(ticktick.DateTimeLayout)
ticktickTask := ticktick.Task{
ProjectId: projectId,
Title: task.Action,
DueDate: dueTicktick,
}
err = ticktick.CreateTask(ticktickTask)
if err != nil {
slog.Warn(fmt.Sprintf("Homeassistant.createActionTask Error creating task %s", err))
}
}