Compare commits
10 Commits
9c414d28ad
...
95d0fa07b8
| Author | SHA1 | Date | |
|---|---|---|---|
| 95d0fa07b8 | |||
| 234323c766 | |||
| 2a1a40f75f | |||
| f295779566 | |||
| 269cedd70b | |||
| 6ded11a22f | |||
| ad6b7cdbc1 | |||
|
|
7827ec794d | ||
| 7a4b28fe01 | |||
| 7d96a3e292 |
20
.github/workflows/short-tests.yml
vendored
Normal file
20
.github/workflows/short-tests.yml
vendored
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
name: Run short tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
run-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: '1.23'
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
working-directory: ./src
|
||||||
|
run: go test -v --short ./...
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -33,3 +33,5 @@ __pycache__/
|
|||||||
config.yaml
|
config.yaml
|
||||||
bin/
|
bin/
|
||||||
*.db
|
*.db
|
||||||
|
|
||||||
|
cover.html
|
||||||
@@ -21,11 +21,14 @@ import (
|
|||||||
"github.com/t-liu93/home-automation-backend/components/locationRecorder"
|
"github.com/t-liu93/home-automation-backend/components/locationRecorder"
|
||||||
"github.com/t-liu93/home-automation-backend/components/pooRecorder"
|
"github.com/t-liu93/home-automation-backend/components/pooRecorder"
|
||||||
"github.com/t-liu93/home-automation-backend/util/notion"
|
"github.com/t-liu93/home-automation-backend/util/notion"
|
||||||
"github.com/t-liu93/home-automation-backend/util/ticktick"
|
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
var port string
|
var (
|
||||||
var scheduler gocron.Scheduler
|
port string
|
||||||
|
scheduler gocron.Scheduler
|
||||||
|
ticktick *ticktickutil.TicktickUtilImpl
|
||||||
|
)
|
||||||
|
|
||||||
// serveCmd represents the serve command
|
// serveCmd represents the serve command
|
||||||
var serveCmd = &cobra.Command{
|
var serveCmd = &cobra.Command{
|
||||||
@@ -43,7 +46,7 @@ func initUtil() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
// init ticktick
|
// init ticktick
|
||||||
ticktick.Init()
|
ticktick = ticktickutil.Init()
|
||||||
}
|
}
|
||||||
|
|
||||||
func initComponent() {
|
func initComponent() {
|
||||||
@@ -51,6 +54,8 @@ func initComponent() {
|
|||||||
pooRecorder.Init(&scheduler)
|
pooRecorder.Init(&scheduler)
|
||||||
// init location recorder
|
// init location recorder
|
||||||
locationRecorder.Init()
|
locationRecorder.Init()
|
||||||
|
// init homeassistant
|
||||||
|
homeassistant.Init(ticktick)
|
||||||
}
|
}
|
||||||
|
|
||||||
func serve(cmd *cobra.Command, args []string) {
|
func serve(cmd *cobra.Command, args []string) {
|
||||||
@@ -103,7 +108,6 @@ 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", homeassistant.HandleHaMessage).Methods("POST")
|
||||||
|
|
||||||
router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST")
|
router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST")
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
"github.com/t-liu93/home-automation-backend/util/ticktick"
|
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
type haMessage struct {
|
type haMessage struct {
|
||||||
@@ -23,99 +23,125 @@ type actionTask struct {
|
|||||||
DueHour int `json:"due_hour"`
|
DueHour int `json:"due_hour"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ticktickUtil ticktickutil.TicktickUtil
|
||||||
|
)
|
||||||
|
|
||||||
|
func Init(ticktick ticktickutil.TicktickUtil) {
|
||||||
|
ticktickUtil = ticktick
|
||||||
|
}
|
||||||
|
|
||||||
func HandleHaMessage(w http.ResponseWriter, r *http.Request) {
|
func 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("HandleHaMessage: Error decoding request body", err))
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
switch message.Target {
|
switch message.Target {
|
||||||
case "poo_recorder":
|
case "poo_recorder":
|
||||||
handlePooRecorderMsg(message)
|
res := handlePooRecorderMsg(message)
|
||||||
|
if !res {
|
||||||
|
http.Error(w, "Error handling poo recorder message", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
case "location_recorder":
|
case "location_recorder":
|
||||||
handleLocationRecorderMsg(message)
|
res := handleLocationRecorderMsg(message)
|
||||||
|
if !res {
|
||||||
|
http.Error(w, "Error handling location recorder message", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
case "ticktick":
|
case "ticktick":
|
||||||
handleTicktickMsg(message)
|
res := handleTicktickMsg(message)
|
||||||
|
if !res {
|
||||||
|
http.Error(w, "Error handling ticktick message", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
slog.Warn(fmt.Sprintln("HandleHaMessage: Unknown target", message.Target))
|
||||||
|
http.Error(w, "Unknown target", http.StatusBadRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handlePooRecorderMsg(message haMessage) {
|
func handlePooRecorderMsg(message haMessage) bool {
|
||||||
switch message.Action {
|
switch message.Action {
|
||||||
case "get_latest":
|
case "get_latest":
|
||||||
handleGetLatestPoo()
|
return handleGetLatestPoo()
|
||||||
|
default:
|
||||||
|
slog.Warn(fmt.Sprintln("handlePooRecorderMsg: Unknown action", message.Action))
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleLocationRecorderMsg(message haMessage) {
|
func handleLocationRecorderMsg(message haMessage) bool {
|
||||||
if message.Action == "record" {
|
if message.Action == "record" {
|
||||||
port := viper.GetString("port")
|
port := viper.GetString("port")
|
||||||
req, err := http.NewRequest("POST", "http://localhost:"+port+"/location/record", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\"")))
|
|
||||||
if err != nil {
|
|
||||||
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg Error creating request to location recorder", err))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: time.Second * 1,
|
Timeout: time.Second * 1,
|
||||||
}
|
}
|
||||||
_, err = client.Do(req)
|
_, 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("handleLocationRecorderMsg: Error sending request to location recorder", err))
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
} else {
|
} else {
|
||||||
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg Unknown action", message.Action))
|
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg: Unknown action", message.Action))
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleTicktickMsg(message haMessage) {
|
func handleTicktickMsg(message haMessage) bool {
|
||||||
switch message.Action {
|
switch message.Action {
|
||||||
case "create_action_task":
|
case "create_action_task":
|
||||||
createActionTask(message)
|
return createActionTask(message)
|
||||||
|
default:
|
||||||
|
slog.Warn(fmt.Sprintln("handleTicktickMsg: Unknown action", message.Action))
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleGetLatestPoo() {
|
func 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("handleGetLatestPoo: Error sending request to poo recorder", err))
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func createActionTask(message haMessage) {
|
func createActionTask(message haMessage) bool {
|
||||||
if !viper.InConfig("homeassistant.actionTaskProjectId") {
|
if !viper.IsSet("homeassistant.actionTaskProjectId") {
|
||||||
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file")
|
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not set")
|
||||||
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))
|
||||||
dueNextMidnight := time.Date(due.Year(), due.Month(), due.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, 1)
|
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)
|
dueTicktick := dueNextMidnight.UTC().Format(ticktickutil.DateTimeLayout)
|
||||||
ticktickTask := ticktick.Task{
|
ticktickTask := ticktickutil.Task{
|
||||||
ProjectId: projectId,
|
ProjectId: projectId,
|
||||||
Title: task.Action,
|
Title: task.Action,
|
||||||
DueDate: dueTicktick,
|
DueDate: dueTicktick,
|
||||||
}
|
}
|
||||||
err = ticktick.CreateTask(ticktickTask)
|
err = 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
|
||||||
}
|
}
|
||||||
|
|||||||
284
src/components/homeassistant/homeassistant_test.go
Normal file
284
src/components/homeassistant/homeassistant_test.go
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
package homeassistant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/spf13/viper"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
loggerText = new(bytes.Buffer)
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
MockedTicktickUtil struct {
|
||||||
|
mock.Mock
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetupTearDown(t *testing.T) func() {
|
||||||
|
loggertearDown := loggerSetupTeardown()
|
||||||
|
|
||||||
|
return func() {
|
||||||
|
loggertearDown()
|
||||||
|
viper.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loggerSetupTeardown() func() {
|
||||||
|
logger := slog.New(slog.NewTextHandler(loggerText, nil))
|
||||||
|
defaultLogger := slog.Default()
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
return func() {
|
||||||
|
slog.SetDefault(defaultLogger)
|
||||||
|
loggerText.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockedTicktickUtil) HandleAuthCode(w http.ResponseWriter, r *http.Request) {
|
||||||
|
m.Called(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockedTicktickUtil) GetTasks(projectId string) []ticktickutil.Task {
|
||||||
|
args := m.Called(projectId)
|
||||||
|
return args.Get(0).([]ticktickutil.Task)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockedTicktickUtil) HasDuplicateTask(projectId string, taskTitile string) bool {
|
||||||
|
args := m.Called(projectId, taskTitile)
|
||||||
|
return args.Bool(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockedTicktickUtil) CreateTask(task ticktickutil.Task) error {
|
||||||
|
args := m.Called(task)
|
||||||
|
return args.Error(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleHaMessageJsonDecodeError(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
invalidRequestBody := ` { "target": "poo_recorder", "action": "get_latest", "content": " }`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "HandleHaMessage: Error decoding request body")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandlePooRecorderMsgGetLatest(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assert.Equal(t, http.MethodGet, r.Method)
|
||||||
|
assert.Equal(t, "/poo/latest", r.URL.Path)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
port := strings.Split(server.URL, ":")[2]
|
||||||
|
viper.Set("port", port)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Empty(t, loggerText.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandlePooRecorderMsgUnknownAction(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "poo_recorder", "action": "unknown_action", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "handlePooRecorderMsg: Unknown action")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "poo_recorder", "action": "get_latest", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
port := "invalid port"
|
||||||
|
viper.Set("port", port)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "handleGetLatestPoo: Error sending request to poo recorder")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLocationRecorderMsg(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
assert.Equal(t, http.MethodPost, r.Method)
|
||||||
|
assert.Equal(t, "/location/record", r.URL.Path)
|
||||||
|
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
port := strings.Split(server.URL, ":")[2]
|
||||||
|
viper.Set("port", port)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Empty(t, loggerText.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "location_recorder", "action": "unknown_action", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Unknown action")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleLocationRecorderMsgRequestErr(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "location_recorder", "action": "record", "content": "{'person': 'test', 'latitude': '1.0', 'longitude': '2.0', 'altitude': '3.0'}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
port := "invalid port"
|
||||||
|
viper.Set("port", port)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "handleLocationRecorderMsg: Error sending request to location recorder")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTicktickMsgCreateActionTask(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
const expectedProjectId = "test_project_id"
|
||||||
|
const dueHour = 12
|
||||||
|
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(ticktickutil.DateTimeLayout)
|
||||||
|
|
||||||
|
requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mockedTicktickUtil := new(MockedTicktickUtil)
|
||||||
|
viper.Set("homeassistant.actionTaskProjectId", expectedProjectId)
|
||||||
|
|
||||||
|
mockedTicktickUtil.On("CreateTask", mock.Anything).Return(nil)
|
||||||
|
|
||||||
|
Init(mockedTicktickUtil)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
|
||||||
|
expectedTask := ticktickutil.Task{
|
||||||
|
Title: "test_action",
|
||||||
|
ProjectId: expectedProjectId,
|
||||||
|
DueDate: dueTicktick,
|
||||||
|
}
|
||||||
|
|
||||||
|
mockedTicktickUtil.AssertCalled(t, "CreateTask", expectedTask)
|
||||||
|
mockedTicktickUtil.AssertNumberOfCalls(t, "CreateTask", 1)
|
||||||
|
assert.Equal(t, http.StatusOK, w.Code)
|
||||||
|
assert.Empty(t, loggerText.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTicktickMsgUnknownAction(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "ticktick", "action": "unknown_action", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "handleTicktickMsg: Unknown action")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTicktickMsgProjectIdUnset(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "Homeassistant.createActionTask actionTaskProjectId not set")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTicktickMsgJsonError(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
invalidRequestBody := ` { "target": "ticktick", "action": "create_action_task", "content": "{'title': 'tes, 'action': 'test_action', 'due_hour': 12}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(invalidRequestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
viper.Set("homeassistant.actionTaskProjectId", "some project id")
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "Homeassistant.createActionTask: Error unmarshalling")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTicktickMsgTicktickUtilErr(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "ticktick", "action": "create_action_task", "content": "{'title': 'test', 'action': 'test_action', 'due_hour': 12}"}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
mockedTicktickUtil := new(MockedTicktickUtil)
|
||||||
|
viper.Set("homeassistant.actionTaskProjectId", "some project id")
|
||||||
|
|
||||||
|
mockedTicktickUtil.On("CreateTask", mock.Anything).Return(errors.New("some error"))
|
||||||
|
|
||||||
|
Init(mockedTicktickUtil)
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
|
||||||
|
mockedTicktickUtil.AssertCalled(t, "CreateTask", mock.Anything)
|
||||||
|
assert.Equal(t, http.StatusInternalServerError, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "Homeassistant.createActionTask: Error creating task")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleHaMessageUnknownTarget(t *testing.T) {
|
||||||
|
teardown := SetupTearDown(t)
|
||||||
|
defer teardown()
|
||||||
|
|
||||||
|
requestBody := `{"target": "unknown_target", "action": "record", "content": ""}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
HandleHaMessage(w, req)
|
||||||
|
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||||
|
assert.Contains(t, loggerText.String(), "HandleHaMessage: Unknown target")
|
||||||
|
}
|
||||||
@@ -8,11 +8,13 @@ require (
|
|||||||
github.com/jomei/notionapi v1.13.2
|
github.com/jomei/notionapi v1.13.2
|
||||||
github.com/spf13/cobra v1.8.1
|
github.com/spf13/cobra v1.8.1
|
||||||
github.com/spf13/viper v1.19.0
|
github.com/spf13/viper v1.19.0
|
||||||
|
github.com/stretchr/testify v1.9.0
|
||||||
golang.org/x/term v0.24.0
|
golang.org/x/term v0.24.0
|
||||||
modernc.org/sqlite v1.33.1
|
modernc.org/sqlite v1.33.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
@@ -25,6 +27,7 @@ require (
|
|||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||||
@@ -33,6 +36,7 @@ require (
|
|||||||
github.com/spf13/afero v1.11.0 // indirect
|
github.com/spf13/afero v1.11.0 // indirect
|
||||||
github.com/spf13/cast v1.6.0 // indirect
|
github.com/spf13/cast v1.6.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
github.com/stretchr/objx v0.5.2 // indirect
|
||||||
github.com/subosito/gotenv v1.6.0 // indirect
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
go.uber.org/atomic v1.9.0 // indirect
|
go.uber.org/atomic v1.9.0 // indirect
|
||||||
go.uber.org/multierr v1.9.0 // indirect
|
go.uber.org/multierr v1.9.0 // indirect
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package ticktick
|
package ticktickutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -15,59 +15,71 @@ import (
|
|||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
authState string
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
DateTimeLayout = "2006-01-02T15:04:05-0700"
|
DateTimeLayout = "2006-01-02T15:04:05-0700"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Project struct {
|
type (
|
||||||
Id string `json:"id"`
|
TicktickUtil interface {
|
||||||
Name string `json:"name"`
|
HandleAuthCode(w http.ResponseWriter, r *http.Request)
|
||||||
Color string `json:"color,omitempty"`
|
GetTasks(projectId string) []Task
|
||||||
SortOrder int64 `json:"sortOrder,omitempty"`
|
HasDuplicateTask(projectId string, taskTitile string) bool
|
||||||
Closed bool `json:"closed,omitempty"`
|
CreateTask(task Task) error
|
||||||
GroupId string `json:"groupId,omitempty"`
|
}
|
||||||
ViewMode string `json:"viewMode,omitempty"`
|
|
||||||
Permission string `json:"permission,omitempty"`
|
|
||||||
Kind string `json:"kind,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Column struct {
|
TicktickUtilImpl struct {
|
||||||
Id string `json:"id"`
|
authState string
|
||||||
Name string `json:"name"`
|
}
|
||||||
ProjectId string `json:"projectId"`
|
)
|
||||||
SortOrder int64 `json:"sortOrder,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Task struct {
|
type (
|
||||||
Id string `json:"id"`
|
Project struct {
|
||||||
ProjectId string `json:"projectId"`
|
Id string `json:"id"`
|
||||||
Title string `json:"title"`
|
Name string `json:"name"`
|
||||||
IsAllDay bool `json:"isAllDay,omitempty"`
|
Color string `json:"color,omitempty"`
|
||||||
CompletedTime string `json:"completedTime,omitempty"`
|
SortOrder int64 `json:"sortOrder,omitempty"`
|
||||||
Content string `json:"content,omitempty"`
|
Closed bool `json:"closed,omitempty"`
|
||||||
Desc string `json:"desc,omitempty"`
|
GroupId string `json:"groupId,omitempty"`
|
||||||
DueDate string `json:"dueDate,omitempty"`
|
ViewMode string `json:"viewMode,omitempty"`
|
||||||
Items []interface{} `json:"items,omitempty"`
|
Permission string `json:"permission,omitempty"`
|
||||||
Priority int `json:"priority,omitempty"`
|
Kind string `json:"kind,omitempty"`
|
||||||
Reminders []string `json:"reminders,omitempty"`
|
}
|
||||||
RepeatFlag string `json:"repeatFlag,omitempty"`
|
|
||||||
SortOrder int64 `json:"sortOrder,omitempty"`
|
|
||||||
StartDate string `json:"startDate,omitempty"`
|
|
||||||
Status int32 `json:"status,omitempty"`
|
|
||||||
TimeZone string `json:"timeZone,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProjectData struct {
|
Column struct {
|
||||||
Project Project `json:"project"`
|
Id string `json:"id"`
|
||||||
Tasks []Task `json:"tasks"`
|
Name string `json:"name"`
|
||||||
Columns []Column `json:"columns,omitempty"`
|
ProjectId string `json:"projectId"`
|
||||||
}
|
SortOrder int64 `json:"sortOrder,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
func Init() {
|
Task struct {
|
||||||
|
Id string `json:"id"`
|
||||||
|
ProjectId string `json:"projectId"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
IsAllDay bool `json:"isAllDay,omitempty"`
|
||||||
|
CompletedTime string `json:"completedTime,omitempty"`
|
||||||
|
Content string `json:"content,omitempty"`
|
||||||
|
Desc string `json:"desc,omitempty"`
|
||||||
|
DueDate string `json:"dueDate,omitempty"`
|
||||||
|
Items []interface{} `json:"items,omitempty"`
|
||||||
|
Priority int `json:"priority,omitempty"`
|
||||||
|
Reminders []string `json:"reminders,omitempty"`
|
||||||
|
RepeatFlag string `json:"repeatFlag,omitempty"`
|
||||||
|
SortOrder int64 `json:"sortOrder,omitempty"`
|
||||||
|
StartDate string `json:"startDate,omitempty"`
|
||||||
|
Status int32 `json:"status,omitempty"`
|
||||||
|
TimeZone string `json:"timeZone,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
ProjectData struct {
|
||||||
|
Project Project `json:"project"`
|
||||||
|
Tasks []Task `json:"tasks"`
|
||||||
|
Columns []Column `json:"columns,omitempty"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func Init() *TicktickUtilImpl { // TODO: Will modify Init to a proper behavior
|
||||||
|
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..")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -83,14 +95,15 @@ func Init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
beginAuth()
|
ticktickUtilImpl.beginAuth()
|
||||||
}
|
}
|
||||||
|
return ticktickUtilImpl
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleAuthCode(w http.ResponseWriter, r *http.Request) {
|
func (t *TicktickUtilImpl) HandleAuthCode(w http.ResponseWriter, r *http.Request) {
|
||||||
state := r.URL.Query().Get("state")
|
state := r.URL.Query().Get("state")
|
||||||
code := r.URL.Query().Get("code")
|
code := r.URL.Query().Get("code")
|
||||||
if state != authState {
|
if state != t.authState {
|
||||||
slog.Warn(fmt.Sprintln("HandleAuthCode Invalid state", state))
|
slog.Warn(fmt.Sprintln("HandleAuthCode Invalid state", state))
|
||||||
http.Error(w, "Invalid state", http.StatusBadRequest)
|
http.Error(w, "Invalid state", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
@@ -148,7 +161,7 @@ func HandleAuthCode(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Write([]byte("Authorization successful"))
|
w.Write([]byte("Authorization successful"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetTasks(projectId string) []Task {
|
func (t *TicktickUtilImpl) GetTasks(projectId string) []Task {
|
||||||
getTaskUrl := fmt.Sprintf("https://api.ticktick.com/open/v1/project/%s/data", projectId)
|
getTaskUrl := fmt.Sprintf("https://api.ticktick.com/open/v1/project/%s/data", projectId)
|
||||||
token := viper.GetString("ticktick.token")
|
token := viper.GetString("ticktick.token")
|
||||||
req, err := http.NewRequest("GET", getTaskUrl, nil)
|
req, err := http.NewRequest("GET", getTaskUrl, nil)
|
||||||
@@ -184,8 +197,8 @@ func GetTasks(projectId string) []Task {
|
|||||||
return projectData.Tasks
|
return projectData.Tasks
|
||||||
}
|
}
|
||||||
|
|
||||||
func HasDuplicateTask(projectId string, taskTitile string) bool {
|
func (t *TicktickUtilImpl) HasDuplicateTask(projectId string, taskTitile string) bool {
|
||||||
tasks := GetTasks(projectId)
|
tasks := t.GetTasks(projectId)
|
||||||
for _, task := range tasks {
|
for _, task := range tasks {
|
||||||
if task.Title == taskTitile {
|
if task.Title == taskTitile {
|
||||||
return true
|
return true
|
||||||
@@ -194,8 +207,8 @@ func HasDuplicateTask(projectId string, taskTitile string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateTask(task Task) error {
|
func (t *TicktickUtilImpl) CreateTask(task Task) error {
|
||||||
if HasDuplicateTask(task.ProjectId, task.Title) {
|
if t.HasDuplicateTask(task.ProjectId, task.Title) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
token := viper.GetString("ticktick.token")
|
token := viper.GetString("ticktick.token")
|
||||||
@@ -259,7 +272,7 @@ func getProjects() ([]Project, error) {
|
|||||||
return projects, nil
|
return projects, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func beginAuth() {
|
func (t *TicktickUtilImpl) beginAuth() {
|
||||||
if !viper.InConfig("ticktick.redirectUri") {
|
if !viper.InConfig("ticktick.redirectUri") {
|
||||||
slog.Error("TickTick redirectUri not found in config file, exiting..")
|
slog.Error("TickTick redirectUri not found in config file, exiting..")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -272,12 +285,12 @@ func beginAuth() {
|
|||||||
slog.Error(fmt.Sprintln("Error generating auth state", err))
|
slog.Error(fmt.Sprintln("Error generating auth state", err))
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
authState = hex.EncodeToString(authStateBytes)
|
t.authState = hex.EncodeToString(authStateBytes)
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", viper.GetString("ticktick.clientId"))
|
params.Add("client_id", viper.GetString("ticktick.clientId"))
|
||||||
params.Add("response_type", "code")
|
params.Add("response_type", "code")
|
||||||
params.Add("redirect_uri", viper.GetString("ticktick.redirectUri"))
|
params.Add("redirect_uri", viper.GetString("ticktick.redirectUri"))
|
||||||
params.Add("state", authState)
|
params.Add("state", t.authState)
|
||||||
params.Add("scope", "tasks:read tasks:write")
|
params.Add("scope", "tasks:read tasks:write")
|
||||||
authUrl.RawQuery = params.Encode()
|
authUrl.RawQuery = params.Encode()
|
||||||
slog.Info(fmt.Sprintln("Please visit the following URL to authorize TickTick:", authUrl.String()))
|
slog.Info(fmt.Sprintln("Please visit the following URL to authorize TickTick:", authUrl.String()))
|
||||||
Reference in New Issue
Block a user