/
widget.go
106 lines (79 loc) · 2.09 KB
/
widget.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
package hibp
import (
"fmt"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
)
// Widget is the container for hibp data
type Widget struct {
view.TextWidget
settings *Settings
statuses []*Status
err error
}
// NewWidget creates a new instance of a widget
func NewWidget(tviewApp *tview.Application, redrawChan chan bool, settings *Settings) *Widget {
widget := &Widget{
TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.Common),
settings: settings,
}
return widget
}
/* -------------------- Exported Functions -------------------- */
// Fetch retrieves HIBP data from the HIBP API
func (widget *Widget) Fetch(accounts []string) ([]*Status, error) {
data := []*Status{}
for _, account := range accounts {
stat, err := widget.fetchForAccount(account, widget.settings.since)
if err != nil {
return nil, err
}
data = append(data, stat)
}
return data, nil
}
// Refresh updates the data for this widget and displays it onscreen
func (widget *Widget) Refresh() {
statuses, err := widget.Fetch(widget.settings.accounts)
if err != nil {
widget.err = err
widget.statuses = nil
} else {
widget.err = nil
widget.statuses = statuses
}
widget.Redraw(widget.content)
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) content() (string, string, bool) {
title := widget.CommonSettings().Title
if widget.err != nil {
return title, widget.err.Error(), true
}
title += widget.sinceDateForTitle()
str := ""
for _, status := range widget.statuses {
color := widget.settings.colors.ok
if status.HasBeenCompromised() {
color = widget.settings.colors.pwned
}
if status != nil {
str += fmt.Sprintf(" [%s]%s[white]\n", color, status.Account)
}
}
return title, str, false
}
func (widget *Widget) sinceDateForTitle() string {
dateStr := ""
if widget.settings.HasSince() {
sinceStr := ""
dt, err := widget.settings.SinceDate()
if err != nil {
sinceStr = widget.settings.since
} else {
sinceStr = dt.Format("Jan _2, 2006")
}
dateStr = dateStr + " since " + sinceStr
}
return dateStr
}