-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
437 lines (350 loc) · 10.1 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// This file is licensed under the Creative Commons Attribution 4.0 International License.
// To view a copy of this license, visit https://creativecommons.org/licenses/by/4.0/
// Original work by serstuk93.
package main
import (
"errors"
"fmt"
"image/color"
"net/url"
"os"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"github.com/sirupsen/logrus"
)
var urls = []string{
"https://monitory.heureka.sk/f:1676:34-;p:1/",
"https://another-url.com/path",
"https://monitory.heureka.sk/",
}
func main() {
startTime := time.Now()
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
ForceColors: true,
})
logrus.Infof("Starting app")
log := logrus.New()
// Open or create the log file for appending
file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Warnf("Failed opening log file: %s", err.Error())
}
defer file.Close()
// Set the log output to the file
log.SetOutput(file)
log.Infof("NewWithID loaded time: %s", time.Since(startTime))
a := app.NewWithID("com.serstuk93.heurwatchdog")
w := a.NewWindow("WatchDog")
r, err := fyne.LoadResourceFromPath("icon.png")
if err != nil {
log.Warnf("Failed opening log file: %s", err.Error())
} else {
w.SetIcon(r)
}
log.Infof("window loaded time: %s", time.Since(startTime))
w.Resize(fyne.NewSize(300, 400))
urlEntry := widget.NewEntry()
urlEntry.SetPlaceHolder("Enter a URL here")
log.Infof("new url Entry loaded time: %s", time.Since(startTime))
urlList := widget.NewList(
func() int {
return len(urls)
},
func() fyne.CanvasObject {
return widget.NewLabel("template")
},
func(id widget.ListItemID, obj fyne.CanvasObject) {
label := obj.(*widget.Label)
label.SetText(urls[id])
},
)
var width float32 = 500
var height float32 = 10
minSize := fyne.NewSize(width, height)
spacer := canvas.NewRectangle(color.Black)
spacer.SetMinSize(minSize)
mainContainer := container.NewVBox(
spacer,
urlEntry,
)
listContainer := container.NewVBox()
// To store the references to the checkboxes and their corresponding containers
var checkboxes []*widget.Check
var itemContainers []*fyne.Container
productTracker := NewProductTracker()
contentContainer := container.NewVBox(
spacer,
)
// Add the new URL as a label to the container
for _, ul := range urls {
lbl := canvas.NewText(ul, theme.ForegroundColor())
checkbox := widget.NewCheck("", func(checked bool) {
})
hBox := container.NewHBox(checkbox, lbl) // Horizontal box with a checkbox and a label
listContainer.Add(hBox)
// Store the references
checkboxes = append(checkboxes, checkbox)
itemContainers = append(itemContainers, hBox)
}
delIndex := make(map[int]string)
deleteButton := widget.NewButton("Delete URL", nil)
deleteButton = widget.NewButton("Delete URL", func() {
for i, checkbox := range checkboxes {
if checkbox.Checked {
listContainer.Remove(itemContainers[i])
var label *canvas.Text
var ok bool
if label, ok = itemContainers[i].Objects[1].(*canvas.Text); ok {
urls = removeItem(urls, label.Text)
}
for num, co := range contentContainer.Objects {
switch co.(type) {
case *fyne.Container:
z, ok := co.(*fyne.Container)
if !ok {
continue
}
for _, i := range z.Objects {
y, ok := i.(*widget.Label)
if !ok {
continue
}
if y.Text == "" {
break
}
if y.Text == label.Text {
fmt.Println(y.Text)
delIndex[num] = ""
break
}
}
}
}
}
}
fmt.Println(delIndex)
for i := range delIndex {
contentContainer.Objects[i] = nil
}
if len(urls) == 0 {
deleteButton.Disable()
} else {
deleteButton.Enable()
}
var newObjects []fyne.CanvasObject
for i, obj := range contentContainer.Objects {
_, ok := delIndex[i]
if !ok {
newObjects = append(newObjects, obj)
}
}
// Clear the map
delIndex = make(map[int]string)
contentContainer.Objects = newObjects
contentContainer.Refresh()
deleteButton.Refresh()
})
addButton := widget.NewButton("Add URL", func() {
logrus.Info("Add URL button clicked")
if urlEntry.Text != "" {
urls = append(urls, urlEntry.Text)
urlList.Resize(fyne.NewSize(urlList.Size().Width, calculateListHeight(len(urls), 50))) // assuming each item's height is 50
urlList.Refresh()
logrus.Info("listed urls are", urls)
// Add the new URL as a label to the container
label := canvas.NewText(urlEntry.Text, color.Black)
fmt.Println("Adding label:", label, urlEntry.Text)
checkbox := widget.NewCheck("", func(checked bool) {
// Handle the check change if you need
})
hBox := container.NewHBox(checkbox, label) // Horizontal box with a checkbox and a label
listContainer.Add(hBox)
a, _ := getTextFromHBox(hBox)
fmt.Println(a)
// Store the references
checkboxes = append(checkboxes, checkbox)
itemContainers = append(itemContainers, hBox)
if len(urls) > 0 {
deleteButton.Enable()
}
listContainer.Refresh()
urlEntry.SetText("")
}
})
refreshButton := widget.NewButton("Refresh", func() {
contentContainer.Objects = nil
log.Debug("refresh button clicked")
displayProducts(contentContainer, productTracker)
w.Canvas().Refresh(contentContainer)
})
mainContainer.Add(addButton)
mainContainer.Add(deleteButton)
mainContainer.Add(refreshButton)
mainContainer.Add(contentContainer)
mainContainer.Add(urlList)
mainContainer.Add(listContainer)
log.Infof("buttons loaded time: %s", time.Since(startTime))
go func() {
displayProducts(contentContainer, productTracker)
startAutoRefresh(contentContainer, productTracker)
}()
log.Infof("goroutines time: %s", time.Since(startTime))
scrollContainer := container.NewScroll(mainContainer)
scrollContainer.SetMinSize(fyne.NewSize(400, 300))
w.SetContent(scrollContainer)
elapsedTime := time.Since(startTime)
log.Infof("Elapsed time: %s", elapsedTime)
w.SetFullScreen(false)
w.SetTitle("WatchDog")
w.ShowAndRun()
logrus.Infof("Exiting")
}
func displayProducts(content *fyne.Container, productTracker *ProductTracker) {
productsMap, err := CheckUrls(urls)
if err != nil {
logrus.Error("Error: ", err)
}
if len(productsMap) == 0 {
logrus.Warn("No products found")
return
}
headerColor := color.RGBA{R: 255, G: 0, B: 0, A: 255}
headerFont := &fyne.TextStyle{
Bold: true,
Italic: false,
Monospace: false,
}
// Create a divider
divider := canvas.NewLine(color.Gray{0x99})
divider.StrokeWidth = 2
for header, products := range productsMap {
logrus.Info("Header: ", header)
headerLabel := canvas.NewText(header.Header, headerColor)
headerLabel.TextSize = 20 // Adjust as needed
headerLabel.TextStyle = *headerFont
// Create a divider
divider := canvas.NewLine(color.Gray{0x99})
divider.StrokeWidth = 2
productsContainer := container.NewVBox(container.NewStack(headerLabel), divider) // Add the header and divider to the vertical container
for _, product := range products {
logrus.Infof("Title: %s, Price: %s, URL: %s\n", product.Title, product.Price, product.URL)
productString := fmt.Sprintf("%s, Price: %s ", product.Title, product.Price)
productLabel := widget.NewLabel(productString)
link, err := url.Parse(product.URL)
if err != nil {
fmt.Println("Error:", err)
return
}
hyperlink := widget.NewHyperlink("Product Link", link)
row := container.NewHBox(productLabel, layout.NewSpacer(), hyperlink)
productsContainer.Add(row)
l1 := &widget.Label{}
l1.Text = header.URL
productsContainer.Add(l1)
l1.Hide()
}
content.Add(productsContainer)
}
productTracker.CheckAndNotifyNewProducts(productsMap)
}
type HeaderURL struct {
Header string
URL string
}
func CheckUrls(rawUrlList []string) (map[HeaderURL][]Product, error) {
logrus.Infof("starting CheckUrls for %s", rawUrlList)
urlProductMap := make(map[HeaderURL][]Product)
var errorUrl error
for _, rawUrl := range rawUrlList {
srchUrl, header, products, err := checkHeureka(rawUrl)
headerStr := HeaderURL{
Header: header,
URL: srchUrl,
}
if err != nil {
errorUrl = errors.Join(errorUrl, err)
continue
}
if len(products) > 5 {
products = products[:5]
}
urlProductMap[headerStr] = products
}
if len(urlProductMap) < 1 {
return nil, errorUrl
}
return urlProductMap, errorUrl
}
func startAutoRefresh(content *fyne.Container, productTracker *ProductTracker) {
go func() {
for {
content.Objects = nil
displayProducts(content, productTracker)
content.Refresh()
time.Sleep(1 * time.Hour)
}
}()
}
type ProductTracker struct {
lastProductsMap map[HeaderURL][]Product
}
func NewProductTracker() *ProductTracker {
return &ProductTracker{
lastProductsMap: make(map[HeaderURL][]Product),
}
}
func (pt *ProductTracker) CheckAndNotifyNewProducts(productsMap map[HeaderURL][]Product) {
for header, products := range productsMap {
lastProducts, exists := pt.lastProductsMap[header]
if !exists {
sendNotification(NewProducts + header.Header)
} else {
for _, product := range products {
if !productExistsInList(product, lastProducts) {
sendNotification(FoundProduct + product.Title)
}
}
}
}
pt.lastProductsMap = productsMap
}
func productExistsInList(product Product, productList []Product) bool {
for _, p := range productList {
if p.Title == product.Title {
return true
}
}
return false
}
func sendNotification(message string) {
notif := fyne.NewNotification(ProductAlert, message)
fyne.CurrentApp().SendNotification(notif)
}
func calculateListHeight(itemCount int, itemHeight float32) float32 {
return float32(itemCount) * itemHeight
}
func removeItem(slice []string, item string) []string {
for i, v := range slice {
if v == item {
return append(slice[:i], slice[i+1:]...)
}
}
return slice
}
func getTextFromHBox(hBox *fyne.Container) (string, bool) {
if len(hBox.Objects) < 2 {
return "", false
}
// Trying to type assert the second object to a label
if label, ok := hBox.Objects[1].(*canvas.Text); ok {
return label.Text, true
}
return "", false
}