This repository has been archived by the owner on Nov 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
284 lines (231 loc) · 7.97 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/input"
"github.com/go-rod/rod/lib/launcher"
"github.com/joho/godotenv"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
type SolarAssistant struct {
url string
user string
pass string
debug bool
browser *rod.Browser
}
func main() {
if err := godotenv.Load(); err != nil {
log.Printf("unable to load .env file: %s", err)
}
path, _ := launcher.LookPath()
log.Printf("browser path: %s", path)
u := launcher.New().Bin(path).MustLaunch()
browser := rod.New().ControlURL(u).MustConnect()
defer browser.MustClose()
solarAssistant := &SolarAssistant{
url: os.Getenv("SOLAR_ASSISTANT_URL"),
user: os.Getenv("SOLAR_ASSISTANT_USER"),
pass: os.Getenv("SOLAR_ASSISTANT_PASS"),
debug: os.Getenv("SOLAR_ASSISTANT_DEBUG") == "1",
browser: browser,
}
r := gin.New()
r.Use(
cors.Default(),
gin.LoggerWithConfig(gin.LoggerConfig{SkipPaths: []string{"/health", "/favicon.ico"}}),
gin.Recovery(),
)
r.GET("/health", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
r.GET("/work-mode-schedule", solarAssistant.updateWorkModeSchedule)
if err := r.Run(":8080"); err != nil {
log.Fatalf("unable to start server: %s", err)
}
}
type WorkModeScheduleUpdate struct {
From string
To string
Priority string
Enabled int
}
type WorkModeSchedule1Update struct {
From string `form:"schedule1[from]"`
To string `form:"schedule1[to]"`
Priority string `form:"schedule1[priority]"`
Enabled int `form:"schedule1[enabled]"`
}
type WorkModeSchedule2Update struct {
From string `form:"schedule2[from]"`
To string `form:"schedule2[to]"`
Priority string `form:"schedule2[priority]"`
Enabled int `form:"schedule2[enabled]"`
}
type WorkModeSchedule3Update struct {
From string `form:"schedule3[from]"`
To string `form:"schedule3[to]"`
Priority string `form:"schedule3[priority]"`
Enabled int `form:"schedule3[enabled]"`
}
type WorkModeSchedule4Update struct {
From string `form:"schedule4[from]"`
To string `form:"schedule4[to]"`
Priority string `form:"schedule4[priority]"`
Enabled int `form:"schedule4[enabled]"`
}
type UpdateScheduleRequest struct {
Schedule1 WorkModeSchedule1Update `form:"schedule1"`
Schedule2 WorkModeSchedule2Update `form:"schedule2"`
Schedule3 WorkModeSchedule3Update `form:"schedule3"`
Schedule4 WorkModeSchedule4Update `form:"schedule4"`
}
func (solarAssistant *SolarAssistant) updateWorkModeSchedule(c *gin.Context) {
log.Println("receiving request to update schedule")
var request UpdateScheduleRequest
if err := c.BindQuery(&request); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"status": "error",
"message": "bad request",
})
return
}
log.Printf("go to power page at (%s)", solarAssistant.url+"/power")
page := solarAssistant.browser.MustPage(solarAssistant.url + "/power").MustWaitStable()
defer page.MustClose()
if strings.Contains(page.MustInfo().URL, "/sign_in") {
log.Println("inputting login")
page.MustElement("input#user_email").MustInput(solarAssistant.user)
page.MustElement("input#user_password").MustInput(solarAssistant.pass).MustType(input.Enter)
page.MustWaitStable()
log.Println("signing in")
page.MustNavigate(solarAssistant.url + "/power").MustWaitStable()
}
log.Println("generating map of schedules")
m := make(map[string]WorkModeScheduleUpdate)
if request.Schedule1.From != "" || request.Schedule1.To != "" || request.Schedule1.Priority != "" || request.Schedule1.Enabled != 0 {
m["1"] = WorkModeScheduleUpdate{From: request.Schedule1.From, To: request.Schedule1.To, Priority: request.Schedule1.Priority, Enabled: request.Schedule1.Enabled}
}
if request.Schedule2.From != "" || request.Schedule2.To != "" || request.Schedule2.Priority != "" || request.Schedule2.Enabled != 0 {
m["2"] = WorkModeScheduleUpdate{From: request.Schedule2.From, To: request.Schedule2.To, Priority: request.Schedule2.Priority, Enabled: request.Schedule2.Enabled}
}
if request.Schedule3.From != "" || request.Schedule3.To != "" || request.Schedule3.Priority != "" || request.Schedule3.Enabled != 0 {
m["3"] = WorkModeScheduleUpdate{From: request.Schedule3.From, To: request.Schedule3.To, Priority: request.Schedule3.Priority, Enabled: request.Schedule3.Enabled}
}
if request.Schedule4.From != "" || request.Schedule4.To != "" || request.Schedule4.Priority != "" || request.Schedule4.Enabled != 0 {
m["4"] = WorkModeScheduleUpdate{From: request.Schedule4.From, To: request.Schedule4.To, Priority: request.Schedule4.Priority, Enabled: request.Schedule4.Enabled}
}
if !solarAssistant.updateWorkSchedule(page, m) {
c.AbortWithStatusJSON(http.StatusInternalServerError, solarAssistant.response(gin.H{
"status": "error",
"message": "unable to find 'work mode schedule'",
}, page))
return
}
log.Printf("waiting to see if form is correctly updated")
// workaround due to bug, possibly in ui
time.Sleep(30 * time.Second)
needUpdate := false
for i := 1; i <= 4; i++ {
row := strconv.Itoa(i)
req := m[row]
if req.Enabled != 0 {
el := page.MustElement("input#work_mode_slot_" + row + "_enabled_check")
currentBool := el.MustProperty("checked").Bool()
needUpdate = (currentBool && req.Enabled == -1) || (!currentBool && req.Enabled == 1)
if needUpdate {
break
}
}
}
if needUpdate {
log.Println("enabled is not set correctly, fixing")
if !solarAssistant.updateWorkSchedule(page, m) {
c.AbortWithStatusJSON(http.StatusInternalServerError, solarAssistant.response(gin.H{
"status": "error",
"message": "unable to find 'work mode schedule'",
}, page))
return
}
}
log.Printf("waiting for apis to finish")
time.Sleep(30 * time.Second)
log.Printf("all should be complete")
c.JSON(http.StatusOK, gin.H{
"status": "success",
})
}
func (solarAssistant *SolarAssistant) updateWorkSchedule(page *rod.Page, m map[string]WorkModeScheduleUpdate) bool {
containerEl := page.MustElement("#schedule")
if !strings.Contains(containerEl.MustElement("h3").MustText(), "Work mode schedule") {
return false
}
log.Println("pressing edit schedule")
page.MustElement("a[phx-click=\"edit_schedule\"]").MustClick().MustWaitStable()
for row, req := range m {
log.Printf("updating schedule %s", row)
if req.From != "" {
startEl := containerEl.MustElement("input#work_mode_slot_" + row + "_start")
startEl.MustInput("")
startEl.MustType(timeInput(req.From)...)
}
if req.To != "" {
endEl := containerEl.MustElement("input#work_mode_slot_" + row + "_end")
endEl.MustInput("")
endEl.MustType(timeInput(req.To)...)
}
if req.Priority != "" {
containerEl.MustElement("select#work_mode_slot_" + row + "_priority").MustSelect(req.Priority)
}
if req.Enabled != 0 {
el := page.MustElement("input#work_mode_slot_" + row + "_enabled_check")
currentBool := el.MustProperty("checked").Bool()
if (currentBool && req.Enabled == -1) || (!currentBool && req.Enabled == 1) {
el.MustClick().MustWaitStable()
}
}
}
containerEl.MustElement("button[type=submit]").MustClick().MustWaitStable()
page.MustScreenshot("test.png")
return true
}
func (solarAssistant *SolarAssistant) response(response gin.H, page *rod.Page) gin.H {
if solarAssistant.debug {
page.MustScreenshot(time.Now().String() + ".png")
}
return response
}
func timeInput(time string) []input.Key {
keys := make([]input.Key, 0)
for _, char := range time {
switch string(char) {
case "0":
keys = append(keys, input.Digit0)
case "1":
keys = append(keys, input.Digit1)
case "2":
keys = append(keys, input.Digit2)
case "3":
keys = append(keys, input.Digit3)
case "4":
keys = append(keys, input.Digit4)
case "5":
keys = append(keys, input.Digit5)
case "6":
keys = append(keys, input.Digit6)
case "7":
keys = append(keys, input.Digit7)
case "8":
keys = append(keys, input.Digit8)
case "9":
keys = append(keys, input.Digit9)
}
}
return keys
}