55 Commits

Author SHA1 Message Date
959bd79d1a see if i get token correctly to config
All checks were successful
Run nightly tests / build (push) Successful in 34s
Run nightly tests / nightly-tests-play (push) Successful in 15s
Run short tests / run-tests (push) Successful in 1m17s
2025-05-24 13:50:28 +02:00
1290bdb0fa token not printed yet
All checks were successful
Run nightly tests / build (push) Successful in 37s
Run nightly tests / nightly-tests-play (push) Successful in 37s
Run short tests / run-tests (push) Successful in 1m19s
2025-05-24 13:06:35 +02:00
23df98f586 try if token is readable
All checks were successful
Run nightly tests / build (push) Successful in 1m25s
Run nightly tests / nightly-tests-play (push) Successful in 17s
Run short tests / run-tests (push) Successful in 1m57s
2025-05-24 13:04:02 +02:00
6d4ad23abb Use tee
Some checks failed
Run nightly tests / build (push) Successful in 1m13s
Run short tests / run-tests (push) Successful in 1m41s
Run nightly tests / nightly-tests-play (push) Failing after 34s
2025-05-23 12:30:03 +02:00
8205232db3 I dont understand why hosts not take effect
Some checks failed
Run nightly tests / build (push) Successful in 1m16s
Run short tests / run-tests (push) Successful in 1m40s
Run nightly tests / nightly-tests-play (push) Failing after 33s
2025-05-23 12:27:47 +02:00
c1d56f8ee0 echo needs -e to pass linefeed
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m15s
Run nightly tests / nightly-tests-play (push) Failing after 45s
2025-05-23 12:24:54 +02:00
cf5a47ed4a try if host format is correct or not
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m16s
Run nightly tests / nightly-tests-play (push) Failing after 46s
2025-05-23 12:21:35 +02:00
63cec9b9d8 host not found either, install it and try
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m17s
Run nightly tests / nightly-tests-play (push) Failing after 33s
2025-05-23 12:14:58 +02:00
909b45b51e ping not permitted, use host instead
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m41s
Run nightly tests / nightly-tests-play (push) Failing after 26s
2025-05-23 12:12:20 +02:00
2d529b1f1c doesnt have ping yet, needs to install
Some checks failed
Run short tests / run-tests (push) Successful in 1m17s
Run nightly tests / build (push) Successful in 1m40s
Run nightly tests / nightly-tests-play (push) Failing after 31s
2025-05-23 12:08:21 +02:00
f3dfae6e12 let's check the ip returned by new hosts
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m38s
Run nightly tests / nightly-tests-play (push) Failing after 41s
2025-05-23 12:05:43 +02:00
6900be6904 while loop hangs the flow, will use background
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m37s
Run nightly tests / nightly-tests-play (push) Failing after 41s
2025-05-23 12:02:39 +02:00
ab0be6ea45 workflow run hangs, modify version
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Has been cancelled
2025-05-23 11:59:21 +02:00
daaf79e721 Looks like need to use netcat-openbsd
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m17s
Run nightly tests / nightly-tests-play (push) Has been cancelled
2025-05-23 11:55:25 +02:00
482f23912c nc not there, install first
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m15s
Run nightly tests / nightly-tests-play (push) Failing after 38s
2025-05-23 11:52:02 +02:00
a8ac1e359d See if modifying host is working
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Failing after 15s
2025-05-23 11:49:21 +02:00
8438944f8a Needs to +x permission of executable
All checks were successful
Run nightly tests / build (push) Successful in 1m14s
Run short tests / run-tests (push) Successful in 1m36s
Run nightly tests / nightly-tests-play (push) Successful in 17s
Run nightly tests / nightly-tests (push) Successful in 37s
2025-05-23 11:43:01 +02:00
175e3e36a7 Upload with use a nother version of github workspace
Some checks failed
Run short tests / run-tests (push) Successful in 1m18s
Run nightly tests / build (push) Successful in 1m16s
Run nightly tests / nightly-tests-play (push) Failing after 32s
Run nightly tests / nightly-tests (push) Successful in 34s
2025-05-23 11:40:23 +02:00
05381bde3a Test with help message
Some checks failed
Run nightly tests / build (push) Successful in 1m10s
Run short tests / run-tests (push) Successful in 1m39s
Run nightly tests / nightly-tests-play (push) Failing after 16s
Run nightly tests / nightly-tests (push) Failing after 36s
2025-05-23 11:38:31 +02:00
ab53a7dc71 Check workspace location
All checks were successful
Run short tests / run-tests (push) Successful in 1m19s
Run nightly tests / build (push) Successful in 1m19s
Run nightly tests / nightly-tests-play (push) Successful in 18s
Run nightly tests / nightly-tests (push) Successful in 34s
2025-05-23 11:35:49 +02:00
d9264885ab Change location
Some checks failed
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / build (push) Successful in 1m37s
Run nightly tests / nightly-tests-play (push) Failing after 37s
Run nightly tests / nightly-tests (push) Successful in 25s
2025-05-23 11:33:04 +02:00
cb3f1ee9fd Test download artifacts and print message
Some checks failed
Run nightly tests / build (push) Successful in 1m41s
Run short tests / run-tests (push) Successful in 1m33s
Run nightly tests / nightly-tests-play (push) Failing after 36s
Run nightly tests / nightly-tests (push) Successful in 40s
2025-05-23 11:29:44 +02:00
6c4be53f4b Add second step
All checks were successful
Run short tests / run-tests (push) Successful in 1m11s
Run nightly tests / build (push) Successful in 1m45s
Run nightly tests / nightly-tests (push) Successful in 42s
2025-05-21 20:30:55 +02:00
85e4863f12 try another one
All checks were successful
Run short tests / run-tests (push) Successful in 1m16s
Run nightly tests / build (push) Successful in 1m39s
2025-05-21 20:28:03 +02:00
a0c5a92bb9 looks like path is not correct
All checks were successful
Run short tests / run-tests (push) Successful in 1m22s
Run nightly tests / build (push) Successful in 1m41s
2025-05-21 20:12:53 +02:00
439f7e64bd paths should be path
All checks were successful
Run short tests / run-tests (push) Successful in 1m23s
Run nightly tests / build (push) Successful in 1m34s
2025-05-21 20:09:15 +02:00
61a544ca29 Lets see if we can upload artifacts
Some checks failed
Run short tests / run-tests (push) Successful in 1m21s
Run nightly tests / build (push) Failing after 1m48s
2025-05-21 20:07:09 +02:00
5348d2a8f4 Add ls lr to see where is the artifactory
All checks were successful
Run short tests / run-tests (push) Successful in 1m23s
Run nightly tests / build (push) Successful in 1m27s
2025-05-21 20:04:17 +02:00
14e589f2ee add working directory should work
All checks were successful
Run short tests / run-tests (push) Successful in 1m21s
Run nightly tests / build (push) Successful in 1m30s
2025-05-21 20:01:40 +02:00
e1a9f24d2b pwd
Some checks failed
Run nightly tests / build (push) Successful in 35s
Run short tests / run-tests (push) Has been cancelled
2025-05-21 20:01:05 +02:00
69c6d2fd3f try build
Some checks failed
Run nightly tests / build (push) Failing after 35s
Run short tests / run-tests (push) Successful in 1m23s
2025-05-21 19:59:11 +02:00
f288b32092 will try
Some checks failed
Run nightly tests / nightly-tests (push) Failing after 38s
Run short tests / run-tests (push) Successful in 1m22s
2025-05-21 19:57:33 +02:00
06606ca06c try build
Some checks failed
Run short tests / run-tests (push) Has been cancelled
2025-05-21 19:56:54 +02:00
8df89d3478 schedule looks good now, run at 20 utc, so 21 cest.
All checks were successful
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / nightly-tests (push) Successful in 1m50s
2025-05-21 14:51:24 +02:00
f97841b079 print working see with checkout
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / nightly-tests (push) Successful in 1m40s
2025-05-21 14:41:44 +02:00
17d2f4d1f5 test cron
All checks were successful
Run short tests / run-tests (push) Successful in 1m15s
Run nightly tests / test-cron-job (push) Successful in 30s
2025-05-21 14:38:05 +02:00
1aa6c7dac4 test cron at 1430
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / run-tests (push) Successful in 1m41s
2025-05-21 14:24:22 +02:00
da5bf43197 add push to main
All checks were successful
Run short tests / run-tests (push) Successful in 1m14s
Run nightly tests / run-tests (push) Successful in 1m40s
2025-05-21 10:52:29 +02:00
0d803f4b23 add nightly cron at 0am
All checks were successful
Run short tests / run-tests (push) Successful in 1m38s
2025-05-20 15:22:30 +02:00
fc4e0217b2 check if lable works
All checks were successful
Run short tests / run-tests (push) Successful in 1m13s
Run nightly tests / run-tests (push) Successful in 1m36s
2025-05-20 15:20:07 +02:00
d4db20be16 add nightly test template
Some checks failed
Run nightly tests / run-tests (push) Failing after 13s
Run short tests / run-tests (push) Has been cancelled
2025-05-20 15:19:16 +02:00
1041016210 Revert "change runner to linux"
Some checks failed
Run short tests / run-tests (push) Has been cancelled
This reverts commit 99ed529600.
2025-05-20 15:18:18 +02:00
99ed529600 change runner to linux
Some checks failed
Run short tests / run-tests (push) Failing after 12s
2025-05-20 15:16:58 +02:00
f02bb1e6fb Merge pull request 'feature/refactoring' (#1) from feature/refactoring into master
All checks were successful
Run short tests / run-tests (push) Successful in 1m58s
Reviewed-on: https://code.jamesvillage.dev/tliu93/home-automation-backend/pulls/1
2025-05-19 22:28:40 +02:00
ccb70e3165 Use struct, idomatic go way to write homeassistant component and make it 100 test covered
All checks were successful
Run short tests / run-tests (push) Successful in 1m2s
Run short tests / run-tests (pull_request) Successful in 1m2s
2025-05-19 22:20:05 +02:00
0a76c5feca wip 2025-05-19 20:25:53 +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
9 changed files with 527 additions and 100 deletions

70
.github/workflows/nightly.yml vendored Normal file
View File

@@ -0,0 +1,70 @@
name: Run nightly tests
on:
workflow_dispatch:
schedule:
- cron: '0 20 * * *' # Every day at 20:00 UTC
push:
jobs:
build:
runs-on: [ubuntu-latest, cloud]
steps:
- uses: actions/checkout@v4
# - name: Set up Go
# uses: actions/setup-go@v4
# with:
# go-version: '1.23'
# - name: build
# working-directory: ./src
# run: |
# go build
# - name: Upload artifacts
# uses: actions/upload-artifact@v3
# with:
# path: ${{ github.workspace }}/src/home-automation-backend
# name: home-automation-backend_build_${{ github.run_number }}
# retention-days: 1
nightly-tests-play:
runs-on: [ubuntu-latest, cloud]
needs: build
steps:
- name: Put token into config file
run: |
cat <<EOF > ${GITHUB_WORKSPACE}/config.json
{
"token": "${{ secrets.TEST_TOKEN }}"
}
EOF
- name: print config file
run: cat ${GITHUB_WORKSPACE}/config.json
# - name: Download artifacts
# uses: actions/download-artifact@v3
# with:
# name: home-automation-backend_build_${{ github.run_number }}
# - name: Print helping message
# run: |
# chmod +x ${GITHUB_WORKSPACE}/home-automation-backend
# ${GITHUB_WORKSPACE}/home-automation-backend help
# nightly-tests:
# runs-on: [ubuntu-latest, cloud]
# needs: build
# steps:
# - uses: actions/checkout@v4
# - name: Download artifacts
# uses: actions/download-artifact@v3
# with:
# name: home-automation-backend_build_${{ github.run_number }}
# - name: Check files
# run: ls -lR
# - name: Set up Go
# uses: actions/setup-go@v4
# with:
# go-version: '1.23'
# - name: build
# run: go build
# - name: Run nightly tests
# working-directory: ./tests
# run: go test -v --short ./...

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 config.yaml
bin/ bin/
*.db *.db
cover.html

View File

@@ -21,11 +21,15 @@ 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.TicktickUtil
ha *homeassistant.HomeAssistant
)
// serveCmd represents the serve command // serveCmd represents the serve command
var serveCmd = &cobra.Command{ var serveCmd = &cobra.Command{
@@ -43,7 +47,7 @@ func initUtil() {
os.Exit(1) os.Exit(1)
} }
// init ticktick // init ticktick
ticktick.Init() ticktick = ticktickutil.Init()
} }
func initComponent() { func initComponent() {
@@ -51,6 +55,8 @@ func initComponent() {
pooRecorder.Init(&scheduler) pooRecorder.Init(&scheduler)
// init location recorder // init location recorder
locationRecorder.Init() locationRecorder.Init()
// init homeassistant
ha = homeassistant.NewHomeAssistant(ticktick)
} }
func serve(cmd *cobra.Command, args []string) { func serve(cmd *cobra.Command, args []string) {
@@ -103,8 +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", ha.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")

View File

@@ -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 {
@@ -18,104 +18,135 @@ 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"`
} }
func HandleHaMessage(w http.ResponseWriter, r *http.Request) { func NewHomeAssistant(ticktick ticktickutil.TicktickUtil) *HomeAssistant {
return &HomeAssistant{
ticktickUtil: ticktick,
}
}
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":
handlePooRecorderMsg(message) res := ha.handlePooRecorderMsg(message)
case "location_recorder": if !res {
handleLocationRecorderMsg(message) slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling poo recorder message"))
case "ticktick": http.Error(w, "", http.StatusInternalServerError)
handleTicktickMsg(message) }
case "location_recorder":
res := ha.handleLocationRecorderMsg(message)
if !res {
slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling location recorder message"))
http.Error(w, "", http.StatusInternalServerError)
}
case "ticktick":
res := ha.handleTicktickMsg(message)
if !res {
slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Error handling ticktick message"))
http.Error(w, "", http.StatusInternalServerError)
}
default:
slog.Warn(fmt.Sprintln("homeassistant.HandleHaMessage: Unknown target", message.Target))
http.Error(w, "", http.StatusInternalServerError)
} }
} }
func handlePooRecorderMsg(message haMessage) { func (ha *HomeAssistant) handlePooRecorderMsg(message haMessage) bool {
switch message.Action { switch message.Action {
case "get_latest": case "get_latest":
handleGetLatestPoo() return ha.handleGetLatestPoo()
default:
slog.Warn(fmt.Sprintln("homeassistant.handlePooRecorderMsg: Unknown action", message.Action))
return false
} }
} }
func handleLocationRecorderMsg(message haMessage) { func (ha *HomeAssistant) 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("homeassistant.handleLocationRecorderMsg: Error sending request to location recorder", err))
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 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() { 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 true
} }
func createActionTask(message haMessage) { func (ha *HomeAssistant) 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 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))
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 = 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

@@ -0,0 +1,280 @@
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 MockTicktickUtil struct {
mock.Mock
}
func (m *MockTicktickUtil) HandleAuthCode(w http.ResponseWriter, r *http.Request) {
m.Called(w, r)
}
func (m *MockTicktickUtil) GetTasks(projectId string) []ticktickutil.Task {
args := m.Called(projectId)
return args.Get(0).([]ticktickutil.Task)
}
func (m *MockTicktickUtil) HasDuplicateTask(projectId string, taskTitile string) bool {
args := m.Called(projectId, taskTitile)
return args.Bool(0)
}
func (m *MockTicktickUtil) CreateTask(task ticktickutil.Task) error {
args := m.Called(task)
return args.Error(0)
}
func SetupTearDown(t *testing.T) (func(), *HomeAssistant) {
loggertearDown := loggerSetupTeardown()
mockTicktick := &MockTicktickUtil{}
ha := NewHomeAssistant(mockTicktick)
return func() {
loggertearDown()
viper.Reset()
}, ha
}
func loggerSetupTeardown() func() {
logger := slog.New(slog.NewTextHandler(loggerText, nil))
defaultLogger := slog.Default()
slog.SetDefault(logger)
return func() {
slog.SetDefault(defaultLogger)
loggerText.Reset()
}
}
func TestHandleHaMessageJsonDecodeError(t *testing.T) {
teardown, ha := 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()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Error decoding request body")
}
func TestHandlePooRecorderMsgGetLatest(t *testing.T) {
teardown, ha := 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)
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String())
}
func TestHandlePooRecorderMsgUnknownAction(t *testing.T) {
teardown, ha := 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()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.handlePooRecorderMsg: Unknown action")
}
func TestHandlePooRecorderMsgGetLatestError(t *testing.T) {
teardown, ha := 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)
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.handleGetLatestPoo: Error sending request to poo recorder")
}
func TestHandleLocationRecorderMsg(t *testing.T) {
teardown, ha := 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)
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String())
}
func TestHandleLocationRecorderMsgUnknownAction(t *testing.T) {
teardown, ha := 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()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.handleLocationRecorderMsg: Unknown action")
}
func TestHandleLocationRecorderMsgRequestErr(t *testing.T) {
teardown, ha := 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)
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.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()
mockTicktick := &MockTicktickUtil{}
mockTicktick.On("CreateTask", mock.Anything).Return(nil)
ha := NewHomeAssistant(mockTicktick)
viper.Set("homeassistant.actionTaskProjectId", expectedProjectId)
ha.HandleHaMessage(w, req)
expectedTask := ticktickutil.Task{
Title: "test_action",
DueDate: dueTicktick,
ProjectId: expectedProjectId,
}
mockTicktick.AssertCalled(t, "CreateTask", expectedTask)
mockTicktick.AssertNumberOfCalls(t, "CreateTask", 1)
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, loggerText.String())
}
func TestHandleTicktickMsgUnknownAction(t *testing.T) {
teardown, ha := SetupTearDown(t)
defer teardown()
requestBody := `{"target": "ticktick", "action": "unknown_action", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.handleTicktickMsg: Unknown action")
}
func TestHandleTicktickMsgProjectIdUnset(t *testing.T) {
teardown, ha := 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()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.createActionTask: actionTaskProjectId not found in config file")
}
func TestHandleTicktickMsgJsonError(t *testing.T) {
teardown, ha := 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")
ha.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 := &MockTicktickUtil{}
viper.Set("homeassistant.actionTaskProjectId", "some project id")
mockedTicktickUtil.On("CreateTask", mock.Anything).Return(errors.New("some error"))
ha := NewHomeAssistant(mockedTicktickUtil)
ha.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, ha := SetupTearDown(t)
defer teardown()
requestBody := `{"target": "unknown_target", "action": "record", "content": ""}`
req := httptest.NewRequest(http.MethodPost, "/homeassistant/publish", strings.NewReader(requestBody))
w := httptest.NewRecorder()
ha.HandleHaMessage(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, loggerText.String(), "homeassistant.HandleHaMessage: Unknown target")
}

View File

@@ -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.10.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

View File

@@ -72,13 +72,15 @@ 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=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=

View File

@@ -1,4 +1,4 @@
package ticktick package ticktickutil
import ( import (
"bytes" "bytes"
@@ -15,15 +15,25 @@ 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 (
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"` Id string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Color string `json:"color,omitempty"` Color string `json:"color,omitempty"`
@@ -33,16 +43,16 @@ type Project struct {
ViewMode string `json:"viewMode,omitempty"` ViewMode string `json:"viewMode,omitempty"`
Permission string `json:"permission,omitempty"` Permission string `json:"permission,omitempty"`
Kind string `json:"kind,omitempty"` Kind string `json:"kind,omitempty"`
} }
type Column struct { Column struct {
Id string `json:"id"` Id string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
ProjectId string `json:"projectId"` ProjectId string `json:"projectId"`
SortOrder int64 `json:"sortOrder,omitempty"` SortOrder int64 `json:"sortOrder,omitempty"`
} }
type Task struct { Task struct {
Id string `json:"id"` Id string `json:"id"`
ProjectId string `json:"projectId"` ProjectId string `json:"projectId"`
Title string `json:"title"` Title string `json:"title"`
@@ -59,15 +69,17 @@ type Task struct {
StartDate string `json:"startDate,omitempty"` StartDate string `json:"startDate,omitempty"`
Status int32 `json:"status,omitempty"` Status int32 `json:"status,omitempty"`
TimeZone string `json:"timeZone,omitempty"` TimeZone string `json:"timeZone,omitempty"`
} }
type ProjectData struct { ProjectData struct {
Project Project `json:"project"` Project Project `json:"project"`
Tasks []Task `json:"tasks"` Tasks []Task `json:"tasks"`
Columns []Column `json:"columns,omitempty"` Columns []Column `json:"columns,omitempty"`
} }
)
func Init() { func Init() TicktickUtil { // 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()))