10 Commits

Author SHA1 Message Date
95d0fa07b8 Home assistant now have 100% test coverage
All checks were successful
Run short tests / run-tests (push) Successful in 1m2s
2024-10-24 16:17:34 +02:00
234323c766 Add more tests for ha
All checks were successful
Run short tests / run-tests (push) Successful in 1m1s
2024-10-23 13:53:29 +02:00
2a1a40f75f Rename ticktickutil, add interface for di 2024-10-22 16:40:19 +02:00
f295779566 Add test structure 2024-10-22 14:09:51 +02:00
269cedd70b rename .github workflow 2024-10-21 11:14:48 +02:00
6ded11a22f Fix action 2024-10-18 17:15:31 +02:00
ad6b7cdbc1 Starts adding tests and github workflow 2024-10-18 17:14:10 +02:00
Tianyu Liu
7827ec794d Create tests.yml 2024-10-18 17:13:16 +02:00
7a4b28fe01 Learn action file 2024-10-18 12:12:03 +02:00
7d96a3e292 try action on this repo 2024-10-18 12:10:49 +02:00
8 changed files with 450 additions and 96 deletions

20
.github/workflows/short-tests.yml vendored Normal file
View 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
View File

@@ -33,3 +33,5 @@ __pycache__/
config.yaml
bin/
*.db
cover.html

View File

@@ -21,11 +21,14 @@ import (
"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/util/notion"
"github.com/t-liu93/home-automation-backend/util/ticktick"
"github.com/t-liu93/home-automation-backend/util/ticktickutil"
)
var port string
var scheduler gocron.Scheduler
var (
port string
scheduler gocron.Scheduler
ticktick *ticktickutil.TicktickUtilImpl
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
@@ -43,7 +46,7 @@ func initUtil() {
os.Exit(1)
}
// init ticktick
ticktick.Init()
ticktick = ticktickutil.Init()
}
func initComponent() {
@@ -51,6 +54,8 @@ func initComponent() {
pooRecorder.Init(&scheduler)
// init location recorder
locationRecorder.Init()
// init homeassistant
homeassistant.Init(ticktick)
}
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/record", pooRecorder.HandleRecordPoo).Methods("POST")
router.HandleFunc("/homeassistant/publish", homeassistant.HandleHaMessage).Methods("POST")
router.HandleFunc("/location/record", locationRecorder.HandleRecordLocation).Methods("POST")

View File

@@ -9,7 +9,7 @@ import (
"time"
"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 {
@@ -23,99 +23,125 @@ type actionTask struct {
DueHour int `json:"due_hour"`
}
var (
ticktickUtil ticktickutil.TicktickUtil
)
func Init(ticktick ticktickutil.TicktickUtil) {
ticktickUtil = ticktick
}
func HandleHaMessage(w http.ResponseWriter, r *http.Request) {
var message haMessage
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&message)
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)
return
}
switch message.Target {
case "poo_recorder":
handlePooRecorderMsg(message)
res := handlePooRecorderMsg(message)
if !res {
http.Error(w, "Error handling poo recorder message", http.StatusInternalServerError)
}
case "location_recorder":
handleLocationRecorderMsg(message)
res := handleLocationRecorderMsg(message)
if !res {
http.Error(w, "Error handling location recorder message", http.StatusInternalServerError)
}
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 {
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" {
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{
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 {
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 {
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 {
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{
Timeout: time.Second * 1,
}
port := viper.GetString("port")
_, err := client.Get("http://localhost:" + port + "/poo/latest")
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
}
func createActionTask(message haMessage) {
if !viper.InConfig("homeassistant.actionTaskProjectId") {
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not found in config file")
return
return true
}
func createActionTask(message haMessage) bool {
if !viper.IsSet("homeassistant.actionTaskProjectId") {
slog.Warn("Homeassistant.createActionTask actionTaskProjectId not set")
return false
}
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
slog.Warn(fmt.Sprintln("Homeassistant.createActionTask: Error unmarshalling", err))
return false
}
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{
dueTicktick := dueNextMidnight.UTC().Format(ticktickutil.DateTimeLayout)
ticktickTask := ticktickutil.Task{
ProjectId: projectId,
Title: task.Action,
DueDate: dueTicktick,
}
err = ticktick.CreateTask(ticktickTask)
err = ticktickUtil.CreateTask(ticktickTask)
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

@@ -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")
}

View File

@@ -8,11 +8,13 @@ require (
github.com/jomei/notionapi v1.13.2
github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
golang.org/x/term v0.24.0
modernc.org/sqlite v1.33.1
)
require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.7.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/ncruces/go-strftime v0.1.9 // 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/robfig/cron/v3 v3.0.1 // 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/cast v1.6.0 // 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
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect

View File

@@ -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.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.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=

View File

@@ -1,4 +1,4 @@
package ticktick
package ticktickutil
import (
"bytes"
@@ -15,15 +15,25 @@ import (
"github.com/spf13/viper"
)
var (
authState string
)
const (
DateTimeLayout = "2006-01-02T15:04:05-0700"
)
type Project struct {
type (
TicktickUtil interface {
HandleAuthCode(w http.ResponseWriter, r *http.Request)
GetTasks(projectId string) []Task
HasDuplicateTask(projectId string, taskTitile string) bool
CreateTask(task Task) error
}
TicktickUtilImpl struct {
authState string
}
)
type (
Project struct {
Id string `json:"id"`
Name string `json:"name"`
Color string `json:"color,omitempty"`
@@ -35,14 +45,14 @@ type Project struct {
Kind string `json:"kind,omitempty"`
}
type Column struct {
Column struct {
Id string `json:"id"`
Name string `json:"name"`
ProjectId string `json:"projectId"`
SortOrder int64 `json:"sortOrder,omitempty"`
}
type Task struct {
Task struct {
Id string `json:"id"`
ProjectId string `json:"projectId"`
Title string `json:"title"`
@@ -61,13 +71,15 @@ type Task struct {
TimeZone string `json:"timeZone,omitempty"`
}
type ProjectData struct {
ProjectData struct {
Project Project `json:"project"`
Tasks []Task `json:"tasks"`
Columns []Column `json:"columns,omitempty"`
}
)
func Init() {
func Init() *TicktickUtilImpl { // TODO: Will modify Init to a proper behavior
ticktickUtilImpl := &TicktickUtilImpl{}
if !viper.InConfig("ticktick.clientId") {
slog.Error("TickTick clientId not found in config file, exiting..")
os.Exit(1)
@@ -83,14 +95,15 @@ func Init() {
}
}
} 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")
code := r.URL.Query().Get("code")
if state != authState {
if state != t.authState {
slog.Warn(fmt.Sprintln("HandleAuthCode Invalid state", state))
http.Error(w, "Invalid state", http.StatusBadRequest)
return
@@ -148,7 +161,7 @@ func HandleAuthCode(w http.ResponseWriter, r *http.Request) {
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)
token := viper.GetString("ticktick.token")
req, err := http.NewRequest("GET", getTaskUrl, nil)
@@ -184,8 +197,8 @@ func GetTasks(projectId string) []Task {
return projectData.Tasks
}
func HasDuplicateTask(projectId string, taskTitile string) bool {
tasks := GetTasks(projectId)
func (t *TicktickUtilImpl) HasDuplicateTask(projectId string, taskTitile string) bool {
tasks := t.GetTasks(projectId)
for _, task := range tasks {
if task.Title == taskTitile {
return true
@@ -194,8 +207,8 @@ func HasDuplicateTask(projectId string, taskTitile string) bool {
return false
}
func CreateTask(task Task) error {
if HasDuplicateTask(task.ProjectId, task.Title) {
func (t *TicktickUtilImpl) CreateTask(task Task) error {
if t.HasDuplicateTask(task.ProjectId, task.Title) {
return nil
}
token := viper.GetString("ticktick.token")
@@ -259,7 +272,7 @@ func getProjects() ([]Project, error) {
return projects, nil
}
func beginAuth() {
func (t *TicktickUtilImpl) beginAuth() {
if !viper.InConfig("ticktick.redirectUri") {
slog.Error("TickTick redirectUri not found in config file, exiting..")
os.Exit(1)
@@ -272,12 +285,12 @@ func beginAuth() {
slog.Error(fmt.Sprintln("Error generating auth state", err))
os.Exit(1)
}
authState = hex.EncodeToString(authStateBytes)
t.authState = hex.EncodeToString(authStateBytes)
params := url.Values{}
params.Add("client_id", viper.GetString("ticktick.clientId"))
params.Add("response_type", "code")
params.Add("redirect_uri", viper.GetString("ticktick.redirectUri"))
params.Add("state", authState)
params.Add("state", t.authState)
params.Add("scope", "tasks:read tasks:write")
authUrl.RawQuery = params.Encode()
slog.Info(fmt.Sprintln("Please visit the following URL to authorize TickTick:", authUrl.String()))