-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
267 lines (225 loc) · 5.36 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
//go:build js && wasm
package main
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"net/url"
"time"
"github.com/glasslabs/client-go"
)
const (
api = "https://api.openweathermap.org/data/2.5/"
apiCurrentPath = "weather"
apiForecastPath = "forecast/daily"
)
var (
//go:embed assets/style.css
css []byte
//go:embed assets/wu-icons-style.css
icons []byte
//go:embed assets/index.html
html []byte
)
// Config is the module configuration.
type Config struct {
LocationID string `yaml:"locationId"`
AppID string `yaml:"appId"`
Units string `yaml:"units"`
Interval time.Duration `yaml:"interval"`
}
// NewConfig returns a Config with default values set.
func NewConfig() Config {
return Config{
Interval: 30 * time.Minute,
}
}
func main() {
log := client.NewLogger()
mod, err := client.NewModule()
if err != nil {
log.Error("Could not create module", "error", err.Error())
return
}
cfg := NewConfig()
if err = mod.ParseConfig(&cfg); err != nil {
log.Error("Could not parse config", "error", err.Error())
return
}
log.Info("Loading Module", "module", mod.Name())
m := &Module{
mod: mod,
cfg: cfg,
log: log,
}
if err = m.setup(); err != nil {
log.Error("Could not setup module", "error", err.Error())
return
}
tick := time.NewTicker(cfg.Interval)
defer tick.Stop()
for {
m.update()
<-tick.C
}
}
// Module runs the module.
type Module struct {
mod *client.Module
cfg Config
tmpl *template.Template
log *client.Logger
}
func (m *Module) setup() error {
tmpl, err := template.New("html").Parse(string(html))
if err != nil {
return fmt.Errorf("paring template: %w", err)
}
m.tmpl = tmpl
if err = m.mod.LoadCSS(string(css), string(icons)); err != nil {
return fmt.Errorf("loading css: %w", err)
}
if err = m.render(data{}); err != nil {
m.log.Error("Could not render weather data", "error", err.Error())
}
return nil
}
func (m *Module) update() {
d := data{}
if err := m.request(apiCurrentPath, url.Values{}, &d.Current); err != nil {
m.log.Error("Could not get current weather data", "error", err.Error())
}
if err := m.request(apiForecastPath, url.Values{"cnt": []string{"4"}}, &d.Forecast); err != nil {
m.log.Error("Could not get current weather data", "error", err.Error())
}
if len(d.Forecast.List) > 1 {
d.Current.Day = d.Forecast.List[0]
d.Forecast.List = d.Forecast.List[1:]
}
d.Current.Icon = d.Current.Weather.Icon()
for i := range d.Forecast.List {
dy := d.Forecast.List[i]
t := time.Unix(dy.Unix, 0)
dy.Day = t.Format("Monday")
dy.Icon = dy.Weather.Icon()
d.Forecast.List[i] = dy
}
if err := m.render(d); err != nil {
m.log.Error("Could not render weather data", "error", err.Error())
}
}
func (m *Module) render(d data) error {
var buf bytes.Buffer
if err := m.tmpl.Execute(&buf, d); err != nil {
return fmt.Errorf("rendering html: %w", err)
}
m.mod.Element().SetInnerHTML(buf.String())
return nil
}
func (m *Module) request(p string, qry url.Values, v interface{}) error {
u, err := url.Parse(api + p)
if err != nil {
return fmt.Errorf("could not parse url: %w", err)
}
q := url.Values{}
q.Set("id", m.cfg.LocationID)
q.Set("appid", m.cfg.AppID)
q.Set("units", m.cfg.Units)
for k, val := range qry {
q[k] = val
}
u.RawQuery = q.Encode()
//nolint:noctx
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return fmt.Errorf("could create request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("could not request url: %w", err)
}
defer func() {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
de := dataError{}
if err = json.NewDecoder(resp.Body).Decode(&de); err != nil {
return fmt.Errorf("could not parse error: %w", err)
}
return fmt.Errorf("could not fetch data: %s", de.Message)
}
if err = json.NewDecoder(resp.Body).Decode(v); err != nil {
return fmt.Errorf("could not parse data: %w", err)
}
return nil
}
type dataError struct {
Code int `json:"cod"`
Message string `json:"message"`
}
type data struct {
Current current
Forecast forecast
}
type current struct {
Main struct {
Temp float64 `json:"temp"`
} `json:"main"`
Day day
Weather weather `json:"weather"`
Icon string
}
type forecast struct {
List []day `json:"list"`
}
type day struct {
Unix int64 `json:"dt"`
Day string
Temp struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
} `json:"temp"`
Weather weather `json:"weather"`
Icon string
Rain float64 `json:"rain"`
}
const unknownIcon = "wu-unknown"
var iconTable = map[string]string{
"01d": "wu-clear",
"02d": "wu-partlycloudy",
"03d": "wu-cloudy",
"04d": "wu-cloudy",
"09d": "wu-flurries",
"10d": "wu-rain",
"11d": "wu-tstorms",
"13d": "wu-snow",
"50d": "wu-fog",
"01n": "wu-clear wu-night",
"02n": "wu-partlycloudy wu-night",
"03n": "wu-cloudy wu-night",
"04n": "wu-cloudy wu-night",
"09n": "wu-flurries wu-night",
"10n": "wu-rain wu-night",
"11n": "wu-tstorms wu-night",
"13n": "wu-snow wu-night",
"50n": "wu-fog wu-night",
}
type weather []struct {
IconCode string `json:"icon"`
}
// Icon returns the weather icon or the unknown icon.
func (w weather) Icon() string {
if len(w) == 0 {
return unknownIcon
}
icn, ok := iconTable[w[0].IconCode]
if !ok {
return unknownIcon
}
return icn
}