1
0
mirror of https://github.com/taigrr/wtf synced 2025-01-18 04:03:14 -08:00

feat: Add new widget for football scores and standings

This commit is contained in:
Cizer Pereira
2019-10-19 16:11:53 +02:00
committed by Cizer Pereira
parent d7b0669796
commit e7e1463181
8 changed files with 359 additions and 2 deletions

View File

@@ -0,0 +1,45 @@
package football
import (
"fmt"
"net/http"
)
var (
footballAPIUrl = "http://api.football-data.org/v2"
)
type leagueInfo struct {
id int
caption string
}
type Client struct {
apiKey string
}
func NewClient(apiKey string) *Client {
client := Client{
apiKey: apiKey,
}
return &client
}
func (client *Client) footballRequest(path string, id int) (*http.Response, error) {
url := fmt.Sprintf("%s/competitions/%d/%s", footballAPIUrl, id, path)
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Auth-Token", client.apiKey)
if err != nil {
return nil, err
}
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}

View File

@@ -0,0 +1,37 @@
package football
import (
"os"
"github.com/olebedev/config"
"github.com/wtfutil/wtf/cfg"
)
const (
defaultFocusable = true
defaultTitle = "football"
)
type Settings struct {
common *cfg.Common
apiKey string `help:"Your Football-data API token."`
league string `help:"Name of the competition. For example PL"`
favTeam string `help:"Teams to follow in mentioned league"`
matchesFrom int `help:"Matches till Today (Today - Number of days), Default: 2"`
matchesTo int `help:"Matches from Today (Today + Number of days), Default: 5"`
standingCount int `help:"Top N number of teams in standings, Default: 5"`
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
apiKey: ymlConfig.UString("apiKey", ymlConfig.UString("apikey", os.Getenv("WTF_FOOTBALL_API_KEY"))),
league: ymlConfig.UString("league", ymlConfig.UString("league", os.Getenv("WTF_FOOTBALL_LEAGUE"))),
favTeam: ymlConfig.UString("favTeam", ymlConfig.UString("favTeam", os.Getenv("WTF_FOOTBALL_TEAM"))),
matchesFrom: ymlConfig.UInt("matchesFrom", 5),
matchesTo: ymlConfig.UInt("matchesTo", 5),
standingCount: ymlConfig.UInt("standingCount", 5),
}
return &settings
}

46
modules/football/types.go Normal file
View File

@@ -0,0 +1,46 @@
package football
type Team struct {
Name string `json:"name"`
}
type LeagueStandings struct {
Standings []struct {
Table []Table `json:"table"`
} `json:"standings"`
}
type Table struct {
Draw int `json:"draw"`
GoalDifference int `json:"goalDifference"`
Lost int `json:"lost"`
Won int `json:"won"`
PlayedGames int `json:"playedGames"`
Points int `json:"points"`
Position int `json:"position"`
Team Team `json:"team"`
}
type LeagueFixtuers struct {
Matches []Matches `json:"matches"`
}
type Matches struct {
AwayTeam Team `json:"awayTeam"`
HomeTeam Team `json:"homeTeam"`
Score Score `json:"score"`
Stage string `json:"stage"`
Status string `json:"status"`
Date string `json:"utcDate"`
}
type Score struct {
FullTime ScoreByTime `json:"fullTime"`
HalfTime ScoreByTime `json:"halfTime"`
Winner string `json:"winner"`
}
type ScoreByTime struct {
AwayTeam int `json:"awayTeam"`
HomeTeam int `json:"homeTeam"`
}

37
modules/football/util.go Normal file
View File

@@ -0,0 +1,37 @@
package football
import (
"bytes"
"fmt"
"strings"
"time"
"github.com/olekukonko/tablewriter"
)
func createTable(header []string, buf *bytes.Buffer) *tablewriter.Table {
table := tablewriter.NewWriter(buf)
if len(header) != 0 {
table.SetHeader(header)
}
table.SetBorder(false)
table.SetCenterSeparator(" ")
table.SetColumnSeparator(" ")
table.SetRowSeparator(" ")
table.SetAlignment(tablewriter.ALIGN_LEFT)
return table
}
func parseDateString(d string) string {
return fmt.Sprintf("🕙 %s", strings.Replace(d, "T", " ", 1))
}
func getDateString(offset int) string {
today := time.Now()
return today.AddDate(0, 0, offset).Format("2006-01-02")
}

181
modules/football/widget.go Normal file
View File

@@ -0,0 +1,181 @@
package football
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"strings"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
)
var leagueID = map[string]leagueInfo{
"BSA": {2013, "Brazil Série A"},
"PL": {2021, "English Premier League"},
"EC": {2016, "English Championship"},
"EUC": {2018, "European Championship"},
"EL2": {444, "Campeonato Brasileiro da Série A"},
"CL": {2001, "UEFA Champions League"},
"FL1": {2015, "French Ligue 1"},
"GB": {2002, "German Bundesliga"},
"ISA": {2019, "Italy Serie A"},
"NE": {2003, "Netherlands Eredivisie"},
"PPL": {2017, "Portugal Primeira Liga"},
"SPD": {2014, "Spain Primera Division"},
"WC": {2000, "FIFA World Cup"},
}
type Widget struct {
view.TextWidget
*Client
settings *Settings
League leagueInfo
err error
}
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
var widget Widget
leagueId, err := getLeague(settings.league)
if err != nil {
widget = Widget{
err: fmt.Errorf("Unable to get the league id for provided league '%s'", settings.league),
Client: NewClient(settings.apiKey),
settings: settings,
}
return &widget
}
widget = Widget{
TextWidget: view.NewTextWidget(app, settings.common),
Client: NewClient(settings.apiKey),
League: leagueId,
settings: settings,
}
return &widget
}
func (widget *Widget) Refresh() {
widget.Redraw(widget.content)
}
func (widget *Widget) content() (string, string, bool) {
var content string
title := fmt.Sprintf("%s %s", widget.CommonSettings().Title, widget.League.caption)
wrap := false
if widget.err != nil {
return title, widget.err.Error(), true
}
content += widget.GetStandings(widget.League.id)
content += widget.GetMatches(widget.League.id)
return title, content, wrap
}
func getLeague(league string) (leagueInfo, error) {
var l leagueInfo
if val, ok := leagueID[league]; ok {
return val, nil
}
return l, fmt.Errorf("No such league")
}
// GetStandings of particular league
func (widget *Widget) GetStandings(leagueId int) string {
var l LeagueStandings
var content string
content += fmt.Sprintf("Standings:\n\n")
buf := new(bytes.Buffer)
tStandings := createTable([]string{"No.", "Team", "MP", "Won", "Draw", "Lost", "GD", "Points"}, buf)
resp, err := widget.Client.footballRequest("standings", leagueId)
if err != nil {
return fmt.Sprintf("Error fetching standings: %s", err.Error())
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Sprintf("Error fetching standings: %s", err.Error())
}
err = json.Unmarshal(data, &l)
if err != nil {
return fmt.Sprintf("Error fetching standings")
}
if len(l.Standings) > 0 {
for _, i := range l.Standings[0].Table {
if i.Position <= widget.settings.standingCount {
row := []string{strconv.Itoa(i.Position), i.Team.Name, strconv.Itoa(i.PlayedGames), strconv.Itoa(i.Won), strconv.Itoa(i.Draw), strconv.Itoa(i.Lost), strconv.Itoa(i.GoalDifference), strconv.Itoa(i.Points)}
tStandings.Append(row)
}
}
} else {
return fmt.Sprintf("Error fetching standings")
}
tStandings.Render()
content += buf.String()
return content
}
// GetMatches of particular league
func (widget *Widget) GetMatches(leagueId int) string {
var l LeagueFixtuers
var content string
scheduledBuf := new(bytes.Buffer)
playedBuf := new(bytes.Buffer)
tScheduled := createTable([]string{}, scheduledBuf)
tPlayed := createTable([]string{}, playedBuf)
from := getDateString(-widget.settings.matchesFrom)
to := getDateString(widget.settings.matchesTo)
requestPath := fmt.Sprintf("matches?dateFrom=%s&dateTo=%s", from, to)
resp, err := widget.Client.footballRequest(requestPath, leagueId)
if err != nil {
return fmt.Sprintf("Error fetching matches: %s", err.Error())
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Sprintf("Error fetching matches: %s", err.Error())
}
err = json.Unmarshal(data, &l)
if err != nil {
return fmt.Sprintf("Error fetching matches: %s", err.Error())
}
if len(l.Matches) != 0 {
for _, val := range l.Matches {
if strings.Contains(val.AwayTeam.Name, widget.settings.favTeam) || strings.Contains(val.HomeTeam.Name, widget.settings.favTeam) || widget.settings.favTeam == "" {
if val.Status == "SCHEDULED" {
row := []string{"⚽", val.HomeTeam.Name, "🆚", val.AwayTeam.Name, parseDateString(val.Date)}
tScheduled.Append(row)
} else if val.Status == "FINISHED" {
row := []string{"⚽", val.HomeTeam.Name, strconv.Itoa(val.Score.FullTime.HomeTeam), "🆚", val.AwayTeam.Name, strconv.Itoa(val.Score.FullTime.AwayTeam)}
tPlayed.Append(row)
}
}
}
tScheduled.Render()
tPlayed.Render()
if playedBuf.String() != "" {
content += "\nMatches Played:\n\n"
content += playedBuf.String()
}
if scheduledBuf.String() != "" {
content += "\nUpcoming Matches:\n\n"
content += scheduledBuf.String()
}
}
return content
}