1
0
mirror of https://github.com/taigrr/wtf synced 2025-01-18 04:03:14 -08:00
wtf/prettyweather/widget.go
Patrick José Pereira 5130af7e1c prettyweather: Add view configuration
From `curl wttr.in/:help`:
```
View options:

    ?0                      # only current weather
    ?1                      # current weather + 1 day
    ?2                      # current weather + 2 days
    ?n                      # narrow version (only day and night)
    ?q                      # quiet version (no "Weather report" text)
    ?Q                      # superquiet version (no "Weather report", no city name)
    ?T                      # switch terminal sequences off (no colors)
```

Signed-off-by: Patrick José Pereira <patrickelectric@gmail.com>
2018-06-04 20:01:59 -03:00

69 lines
1.5 KiB
Go

package prettyweather
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/olebedev/config"
"github.com/senorprogrammer/wtf/wtf"
)
// Config is a pointer to the global config object
var Config *config.Config
type Widget struct {
wtf.TextWidget
result string
unit string
city string
view string
}
func NewWidget() *Widget {
widget := Widget{
TextWidget: wtf.NewTextWidget(" Pretty Weather ", "prettyweather", false),
}
return &widget
}
func (widget *Widget) Refresh() {
if widget.Disabled() {
return
}
widget.UpdateRefreshedAt()
widget.prettyWeather()
widget.View.SetText(fmt.Sprintf("%s", widget.result))
}
//this method reads the config and calls wttr.in for pretty weather
func (widget *Widget) prettyWeather() {
client := &http.Client{}
widget.unit = Config.UString("wtf.mods.prettyweather.unit", "m")
widget.city = Config.UString("wtf.mods.prettyweather.city", "")
widget.view = Config.UString("wtf.mods.prettyweather.view", "0")
req, err := http.NewRequest("GET", "https://wttr.in/"+widget.city+"?"+widget.view+"?"+widget.unit, nil)
if err != nil {
widget.result = fmt.Sprintf("%s", err.Error())
return
}
req.Header.Set("User-Agent", "curl")
response, err := client.Do(req)
if err != nil {
widget.result = fmt.Sprintf("%s", err.Error())
return
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
widget.result = fmt.Sprintf("%s", err.Error())
return
}
widget.result = fmt.Sprintf("%s", strings.TrimSpace(string(contents)))
}