github.com/wtfutil/wtf@v0.43.0/modules/weatherservices/prettyweather/widget.go (about)

     1  package prettyweather
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/rivo/tview"
     9  	"github.com/wtfutil/wtf/view"
    10  	"github.com/wtfutil/wtf/wtf"
    11  )
    12  
    13  type Widget struct {
    14  	view.TextWidget
    15  
    16  	result   string
    17  	settings *Settings
    18  }
    19  
    20  func NewWidget(tviewApp *tview.Application, redrawChan chan bool, settings *Settings) *Widget {
    21  	widget := Widget{
    22  		TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.Common),
    23  
    24  		settings: settings,
    25  	}
    26  
    27  	return &widget
    28  }
    29  
    30  func (widget *Widget) Refresh() {
    31  	widget.prettyWeather()
    32  
    33  	widget.Redraw(func() (string, string, bool) { return widget.CommonSettings().Title, widget.result, false })
    34  }
    35  
    36  // this method reads the config and calls wttr.in for pretty weather
    37  func (widget *Widget) prettyWeather() {
    38  	client := &http.Client{}
    39  
    40  	city := widget.settings.city
    41  	unit := widget.settings.unit
    42  	view := widget.settings.view
    43  
    44  	req, err := http.NewRequest("GET", "https://wttr.in/"+city+"?"+view+"?"+unit, http.NoBody)
    45  	if err != nil {
    46  		widget.result = err.Error()
    47  		return
    48  	}
    49  
    50  	req.Header.Set("Accept-Language", widget.settings.language)
    51  	req.Header.Set("User-Agent", "curl")
    52  	response, err := client.Do(req)
    53  	if err != nil {
    54  		widget.result = err.Error()
    55  		return
    56  
    57  	}
    58  	defer func() { _ = response.Body.Close() }()
    59  
    60  	contents, err := io.ReadAll(response.Body)
    61  	if err != nil {
    62  		widget.result = err.Error()
    63  		return
    64  	}
    65  
    66  	widget.result = strings.TrimSpace(wtf.ASCIItoTviewColors(string(contents)))
    67  }