From 5b456afb49bfa6ff1567510bc1d9362377d32216 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Sun, 4 Oct 2020 22:58:03 +0200 Subject: New config format and new features We're now using json as a config format instead of our weird own format. The weather icon is now optional, simply don't define WeatherPlace in your config. You can now specify which subreddit to get background images from. The default is still /r/EarthPorn. --- weather/weather.go | 59 ++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 15 deletions(-) (limited to 'weather') diff --git a/weather/weather.go b/weather/weather.go index 87b7a83..2a1d23f 100644 --- a/weather/weather.go +++ b/weather/weather.go @@ -3,7 +3,9 @@ package weather import ( "encoding/xml" - "net/http" + "github.com/silvasur/startpage/http_getter" + "github.com/silvasur/startpage/interval" + "log" "time" ) @@ -35,33 +37,60 @@ type weatherdata struct { Forecast []*Weather `xml:"forecast>tabular>time"` } -func CurrentWeather(place string) (Weather, error) { +func CurrentWeather(place string) (*Weather, error) { url := "http://www.yr.no/place/" + place + "/forecast_hour_by_hour.xml" - client := &http.Client{} - - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return Weather{}, err - } - - req.Header.Add("User-Agent", "github.com/slivasur/startpage/weather") - - resp, err := client.Do(req) + resp, err := http_getter.Get(url) if err != nil { - return Weather{}, err + return nil, err } defer resp.Body.Close() var wd weatherdata dec := xml.NewDecoder(resp.Body) if err := dec.Decode(&wd); err != nil { - return Weather{}, err + return nil, err } w := wd.Forecast[0] w.URL = "http://www.yr.no/place/" + place w.prepIcon() - return *w, nil + return w, nil +} + +type WeatherProvider struct { + place string + intervalRunner *interval.IntervalRunner + weather *Weather + err error +} + +const ( + UPDATE_INTERVAL = 30 * time.Minute + RETRY_INTERVAL = 1 * time.Minute +) + +func NewWeatherProvider(place string) *WeatherProvider { + return &WeatherProvider{ + place: place, + intervalRunner: interval.NewIntervalRunner(UPDATE_INTERVAL, RETRY_INTERVAL), + } +} + +func (wp *WeatherProvider) CurrentWeather() (*Weather, error) { + wp.intervalRunner.Run(func() bool { + log.Printf("Getting new weather data") + wp.weather, wp.err = CurrentWeather(wp.place) + + if wp.err == nil { + log.Printf("Successfully loaded weather data") + } else { + log.Printf("Failed loading weather data: %s", wp.err) + } + + return wp.err == nil + }) + + return wp.weather, wp.err } -- cgit v1.2.3-70-g09d2