This commit is contained in:
2025-05-19 20:25:53 +02:00
parent 234323c766
commit 0a76c5feca
4 changed files with 99 additions and 59 deletions

View File

@@ -27,7 +27,8 @@ import (
var ( var (
port string port string
scheduler gocron.Scheduler scheduler gocron.Scheduler
ticktick *ticktickutil.TicktickUtilImpl ticktick ticktickutil.TicktickUtil
ha *homeassistant.HomeAssistant
) )
// serveCmd represents the serve command // serveCmd represents the serve command
@@ -55,7 +56,7 @@ func initComponent() {
// init location recorder // init location recorder
locationRecorder.Init() locationRecorder.Init()
// init homeassistant // init homeassistant
homeassistant.Init(ticktick) ha = homeassistant.NewHomeAssistant(ticktick)
} }
func serve(cmd *cobra.Command, args []string) { func serve(cmd *cobra.Command, args []string) {
@@ -108,7 +109,7 @@ func serve(cmd *cobra.Command, args []string) {
router.HandleFunc("/poo/latest", pooRecorder.HandleNotifyLatestPoo).Methods("GET") router.HandleFunc("/poo/latest", pooRecorder.HandleNotifyLatestPoo).Methods("GET")
router.HandleFunc("/poo/record", pooRecorder.HandleRecordPoo).Methods("POST") router.HandleFunc("/poo/record", pooRecorder.HandleRecordPoo).Methods("POST")
router.HandleFunc("/homeassistant/publish", homeassistant.HandleHaMessage).Methods("POST") router.HandleFunc("/homeassistant/publish", ha.HandleHaMessage).Methods("POST")
router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST") router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST")

View File

@@ -18,60 +18,68 @@ type haMessage struct {
Content string `json:"content"` Content string `json:"content"`
} }
type HomeAssistant struct {
ticktickUtil ticktickutil.TicktickUtil
}
type actionTask struct { type actionTask struct {
Action string `json:"action"` Action string `json:"action"`
DueHour int `json:"due_hour"` DueHour int `json:"due_hour"`
} }
var ( func NewHomeAssistant(ticktick ticktickutil.TicktickUtil) *HomeAssistant {
ticktickUtil ticktickutil.TicktickUtil return &HomeAssistant{
) ticktickUtil: ticktick,
}
func Init(ticktick ticktickutil.TicktickUtil) {
ticktickUtil = ticktick
} }
func HandleHaMessage(w http.ResponseWriter, r *http.Request) { func (ha *HomeAssistant) HandleHaMessage(w http.ResponseWriter, r *http.Request) {
var message haMessage var message haMessage
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields() decoder.DisallowUnknownFields()
err := decoder.Decode(&message) err := decoder.Decode(&message)
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("HandleHaMessage: Error decoding request body", err)) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error decoding request body", err))
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, "", http.StatusInternalServerError)
return return
} }
switch message.Target { switch message.Target {
case "poo_recorder": case "poo_recorder":
res := handlePooRecorderMsg(message) res := ha.handlePooRecorderMsg(message)
if !res { if !res {
http.Error(w, "Error handling poo recorder message", http.StatusInternalServerError) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling poo recorder message"))
http.Error(w, "", http.StatusInternalServerError)
} }
case "location_recorder": case "location_recorder":
res := handleLocationRecorderMsg(message) res := ha.handleLocationRecorderMsg(message)
if !res { if !res {
http.Error(w, "Error handling location recorder message", http.StatusInternalServerError) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling location recorder message"))
http.Error(w, "", http.StatusInternalServerError)
} }
case "ticktick": case "ticktick":
handleTicktickMsg(message) res := ha.handleTicktickMsg(message)
if !res {
slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling ticktick message"))
http.Error(w, "", http.StatusInternalServerError)
}
default: default:
slog.Warn(fmt.Sprintln("HandleHaMessage Unknown target", message.Target)) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Unknown target", message.Target))
http.Error(w, "Unknown target", http.StatusBadRequest) http.Error(w, "", http.StatusInternalServerError)
} }
} }
func handlePooRecorderMsg(message haMessage) bool { func (ha *HomeAssistant) handlePooRecorderMsg(message haMessage) bool {
switch message.Action { switch message.Action {
case "get_latest": case "get_latest":
return handleGetLatestPoo() return ha.handleGetLatestPoo()
default: default:
slog.Warn(fmt.Sprintln("handlePooRecorderMsg: Unknown action", message.Action)) slog.Warn(fmt.Sprintln("homeassistant.handlePooRecorderMsg: Unknown action", message.Action))
return false return false
} }
} }
func handleLocationRecorderMsg(message haMessage) bool { func (ha *HomeAssistant) handleLocationRecorderMsg(message haMessage) bool {
if message.Action == "record" { if message.Action == "record" {
port := viper.GetString("port") port := viper.GetString("port")
client := &http.Client{ client := &http.Client{
@@ -79,49 +87,52 @@ func handleLocationRecorderMsg(message haMessage) bool {
} }
_, err := client.Post("http://localhost:"+port+"/location/record", "application/json", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\""))) _, err := client.Post("http://localhost:"+port+"/location/record", "application/json", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\"")))
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Error sending request to location recorder", err)) slog.Warn(fmt.Sprintln("homeassistant.handleLocationRecorderMsg: Error sending request to location recorder", err))
return false return false
} }
} else { } else {
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Unknown action", message.Action)) slog.Warn(fmt.Sprintln("homeassistant.handleLocationRecorderMsg: Unknown action", message.Action))
return false return false
} }
return true return true
} }
func handleTicktickMsg(message haMessage) { func (ha *HomeAssistant) handleTicktickMsg(message haMessage) bool {
switch message.Action { switch message.Action {
case "create_action_task": case "create_action_task":
createActionTask(message) return ha.createActionTask(message)
default:
slog.Warn(fmt.Sprintln("homeassistant.handleTicktickMsg: Unknown action", message.Action))
return false
} }
} }
func handleGetLatestPoo() bool { func (ha *HomeAssistant) handleGetLatestPoo() bool {
client := &http.Client{ client := &http.Client{
Timeout: time.Second * 1, Timeout: time.Second * 1,
} }
port := viper.GetString("port") port := viper.GetString("port")
_, err := client.Get("http://localhost:" + port + "/poo/latest") _, err := client.Get("http://localhost:" + port + "/poo/latest")
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("handleGetLatestPoo: Error sending request to poo recorder", err)) slog.Warn(fmt.Sprintln("homeassistant.handleGetLatestPoo: Error sending request to poo recorder", err))
return false return false
} }
return true return true
} }
func createActionTask(message haMessage) { func (ha *HomeAssistant) createActionTask(message haMessage) bool {
if !viper.InConfig("homeassistant.actionTaskProjectId") { if !viper.InConfig("homeassistant.actionTaskProjectId") {
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file") slog.Warn("homeassistant.createActionTask: actionTaskProjectId not found in config file")
return return false
} }
projectId := viper.GetString("homeassistant.actionTaskProjectId") projectId := viper.GetString("homeassistant.actionTaskProjectId")
detail := strings.ReplaceAll(message.Content, "'", "\"") detail := strings.ReplaceAll(message.Content, "'", "\"")
var task actionTask var task actionTask
err := json.Unmarshal([]byte(detail), &task) err := json.Unmarshal([]byte(detail), &task)
if err != nil { if err != nil {
slog.Warn(fmt.Sprintln("Homeassistant.createActionTask Error unmarshalling", err)) slog.Warn(fmt.Sprintln("homeassistant.createActionTask: Error unmarshalling", err))
return return false
} }
dueHour := task.DueHour dueHour := task.DueHour
due := time.Now().Add(time.Hour * time.Duration(dueHour)) due := time.Now().Add(time.Hour * time.Duration(dueHour))
@@ -132,8 +143,10 @@ func createActionTask(message haMessage) {
Title: task.Action, Title: task.Action,
DueDate: dueTicktick, DueDate: dueTicktick,
} }
err = ticktickUtil.CreateTask(ticktickTask) err = ha.ticktickUtil.CreateTask(ticktickTask)
if err != nil { if err != nil {
slog.Warn(fmt.Sprintf("Homeassistant.createActionTask Error creating task %s", err)) slog.Warn(fmt.Sprintf("homeassistant.createActionTask: Error creating task %s", err))
return false
} }
return true
} }

View File

@@ -10,18 +10,44 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
) )
var ( var (
loggerText = new(bytes.Buffer) loggerText = new(bytes.Buffer)
) )
func SetupTearDown(t *testing.T) func() { type MockTicktickUtil struct {
// Mock methods for testing
}
func (m *MockTicktickUtil) HandleAuthCode(w http.ResponseWriter, r *http.Request) {
// Mock implementation
}
func (m *MockTicktickUtil) GetTasks(projectId string) []ticktickutil.Task {
// Mock implementation
return []ticktickutil.Task{}
}
func (m *MockTicktickUtil) HasDuplicateTask(projectId string, taskTitle string) bool {
// Mock implementation
return false
}
func (m *MockTicktickUtil) CreateTask(task ticktickutil.Task) error {
// Mock implementation
return nil
}
func SetupTearDown(t *testing.T) (func(), *HomeAssistant) {
loggertearDown := loggerSetupTeardown() loggertearDown := loggerSetupTeardown()
mockTicktick := &MockTicktickUtil{}
ha := NewHomeAssistant(mockTicktick)
return func() { return func() {
loggertearDown() loggertearDown()
} }, ha
} }
func loggerSetupTeardown() func() { func loggerSetupTeardown() func() {
@@ -36,20 +62,20 @@ func loggerSetupTeardown() func() {
} }
func TestHandleHaMessageJsonDecodeError(t *testing.T) { func TestHandleHaMessageJsonDecodeError(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }` invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "HandleHaMessage: Error decoding request body") assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Error decoding request body")
} }
func TestHandlePooRecorderMsgGetLatest(t *testing.T) { func TestHandlePooRecorderMsgGetLatest(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
@@ -62,26 +88,26 @@ func TestHandlePooRecorderMsgGetLatest(t *testing.T) {
port := strings.Split(server.URL, ":")[2] port := strings.Split(server.URL, ":")[2]
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String()) assert.Empty(t, loggerText.String())
} }
func TestHandlePooRecorderMsgUnknownAction(t *testing.T) { func TestHandlePooRecorderMsgUnknownAction(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "handlePooRecorderMsg: Unknown action") assert.Contains(t, loggerText.String(), "homeassistant.handlePooRecorderMsg: Unknown action")
} }
func TestHandlePooRecorderMsgGetLatestError(t *testing.T) { func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}` requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
@@ -91,13 +117,13 @@ func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
port := "invalid port" port := "invalid port"
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "handleGetLatestPoo: Error sending request to poo recorder") assert.Contains(t, loggerText.String(), "homeassistant.handleGetLatestPoo: Error sending request to poo recorder")
} }
func TestHandleLocationRecorderMsg(t *testing.T) { func TestHandleLocationRecorderMsg(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}`
@@ -113,26 +139,26 @@ func TestHandleLocationRecorderMsg(t *testing.T) {
port := strings.Split(server.URL, ":")[2] port := strings.Split(server.URL, ":")[2]
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String()) assert.Empty(t, loggerText.String())
} }
func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) { func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}` requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody)) req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder() w := httptest.NewRecorder()
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Unknown action") assert.Contains(t, loggerText.String(), "homeassistant.handleLocationRecorderMsg: Unknown action")
} }
func TestHandleLocationRecorderMsgRequestErr(t *testing.T) { func TestHandleLocationRecorderMsgRequestErr(t *testing.T) {
teardown := SetupTearDown(t) teardown, ha := SetupTearDown(t)
defer teardown() defer teardown()
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}` requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}`
@@ -142,7 +168,7 @@ func TestHandleLocationRecorderMsgRequestErr(t *testing.T) {
port := "invalid port" port := "invalid port"
viper.Set("port", port) viper.Set("port", port)
HandleHaMessage(w, req) ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Error sending request to location recorder") assert.Contains(t, loggerText.String(), "homeassistant.handleLocationRecorderMsg: Error sending request to location recorder")
} }

View File

@@ -78,7 +78,7 @@ type (
} }
) )
func Init() *TicktickUtilImpl { // TODO: Will modify Init to a proper behavior func Init() TicktickUtil { // TODO: Will modify Init to a proper behavior
ticktickUtilImpl := &TicktickUtilImpl{} ticktickUtilImpl := &TicktickUtilImpl{}
if !viper.InConfig("ticktick.clientId") { if !viper.InConfig("ticktick.clientId") {
slog.Error("TickTick clientId not found in config file, exiting..") slog.Error("TickTick clientId not found in config file, exiting..")