goff

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2021 License: BSD-3-Clause Imports: 11 Imported by: 0

README

goff GoDoc Build Status Coverage Status

goff is a library for communicating with the Yahoo Fantasy Sports APIs.

This application is written using the Go programming language and is licensed under the New BSD license.

Building

$ go get https://github.com/Forestmb/goff
$ cd $GOPATH/src/github.com/Forestmb/goff
$ ./build.sh

To make sure this build runs before every commit, use:

$ ln -s "$(pwd)/build.sh" .git/hooks/pre-commit

Debug

The goff/debug package can be used to help with developing goff. It uses the OAuth 2.0 configuraiton provided by goff to make arbitrary GET request to the Yahoo Fantasy Sports APIs and outputs the string XML response. To run:

$ cd $GOPATH/src/github.com/Forestmb/goff
$ go run debug/debug.go --clientKey=<key> --clientSecret=<secret> --redirectURL=<redirect-url>

The values key and secret can be obtained after registering your own applicaiton: http://developer.yahoo.com/fantasysports/guide/GettingStarted.html

The redirect-url must match the callback domain given when registering the application with Yahoo. For development, using 127.0.0.1 for the domain and http://127.0.0.1 as the redirect URL should suffice.

Documentation

Overview

Package goff provides a basic Yahoo Fantasy Sports API client.

This package is designed to facilitate communication with the Yahoo Fantasy Sports API. It is recommended, but not required, to use the golang.org/x/oauth2 package to generate a HTTP client to make authenticated API request. The steps required to get a new client up and running with this package are as follows:

  1. Obtain an API key for your application. See https://developer.apps.yahoo.com/dashboard/createKey.html
  2. Call goff.GetOAuth2Config(clientId, clientSecret, redirectURL) using your client's information.
  3. Use oath2.Config to obtain an oauth2.Token. See https://godoc.org/golang.org/x/oauth2#example-Config
  4. Call oauth2Config.Client(ctx, token) with the config and access token.
  5. Pass the returned http.Client into goff.NewClient.
  6. Use the returned goff.Client to make direct API requests with GetFantasyContent(url) or through one of the convenience methods. See http://developer.yahoo.com/fantasysports/guide/ for the type requests that can be made.

To use OAuth 1.0 for authentication, use:

  1. Obtain an API key for your application. See https://developer.apps.yahoo.com/dashboard/createKey.html
  2. Call goff.GetConsumer(clientID, clientSecret) using your client's information.
  3. Use oauth.Consumer to obtain an oauth.AccessToken. See https://godoc.org/github.com/mrjones/oauth
  4. Call oauthConsumer.MakeHttpClient(accessToken) with the consumer and access token.
  5. Pass the returned http.Client into goff.NewClient.
  6. Use the returned goff.Client to make direct API requests with GetFantasyContent(url) or through one of the convenience methods. See http://developer.yahoo.com/fantasysports/guide/ for the type requests that can be made.

The goff client is currently in early stage development and the API is subject to change at any moment.

Index

Constants

View Source
const (
	// NflGameKey represents the current year's Yahoo fantasy football game
	NflGameKey = "nfl"

	// YahooBaseURL is the base URL for all calls to Yahoo's fantasy sports API
	YahooBaseURL = "https://fantasysports.yahooapis.com/fantasy/v2"

	// YahooRequestTokenURL is used to create OAuth request tokens
	YahooRequestTokenURL = "https://api.login.yahoo.com/oauth/v2/get_request_token"

	// YahooAuthTokenURL is used to create OAuth authorization tokens
	YahooAuthTokenURL = "https://api.login.yahoo.com/oauth/v2/request_auth"

	// YahooGetTokenURL is used to get the OAuth access token used when making
	// calls to the fantasy sports API.
	YahooGetTokenURL = "https://api.login.yahoo.com/oauth/v2/get_token"

	// YahooOauth2AuthURL is uesd to start the OAuth 2 login process.
	YahooOauth2AuthURL = "https://api.login.yahoo.com/oauth2/request_auth"

	// YahooOauth2TokenURL is used to create OAuth 2 access tokens used when
	// making calls to the fantasy sports API.
	YahooOauth2TokenURL = "https://api.login.yahoo.com/oauth2/get_token"
)

Variables

View Source
var ErrAccessDenied = errors.New(
	"user does not have permission to access the requested resource")

ErrAccessDenied is returned when the user does not have permision to access the requested resource.

View Source
var YearKeys = map[string]string{
	"nfl":  NflGameKey,
	"2021": "406",
	"2020": "399",
	"2019": "390",
	"2018": "380",
	"2017": "371",
	"2016": "359",
	"2015": "348",
	"2014": "331",
	"2013": "314",
	"2012": "273",
	"2011": "257",
	"2010": "242",
	"2009": "222",
	"2008": "199",
	"2007": "175",
	"2006": "153",
	"2005": "124",
	"2004": "101",
	"2003": "79",
	"2002": "49",
	"2001": "57",
}

YearKeys is map of a string year to the string Yahoo uses to identify the fantasy football game for that year.

Functions

func GetConsumer

func GetConsumer(clientID string, clientSecret string) *oauth.Consumer

GetConsumer generates an OAuth Consumer for the Yahoo fantasy sports API

func GetOAuth2Config added in v0.4.0

func GetOAuth2Config(clientID string, clientSecret string, redirectURL string) *oauth2.Config

GetOAuth2Config generates an OAuth 2 configuration for the Yahoo fantasy sports API

Types

type Cache added in v0.2.0

type Cache interface {
	// Sets the content retrieved for the URL at the given time
	Set(url string, time time.Time, content *FantasyContent)

	// Gets the content for the URL given a time for which the content should
	// be valid
	Get(url string, time time.Time) (content *FantasyContent, ok bool)
}

Cache sets and retrieves fantasy content for request URLs based on the time for which the content was valid

type Client

type Client struct {
	// Provides fantasy content for this application.
	Provider ContentProvider
}

Client is an application authorized to use the Yahoo fantasy sports API.

func NewCachedClient added in v0.4.0

func NewCachedClient(cache Cache, client HTTPClient) *Client

NewCachedClient creates a new fantasy client that checks and updates the given Cache when retrieving fantasy content.

See NewLRUCache

func NewClient added in v0.4.0

func NewClient(c HTTPClient) *Client

NewClient creates a Client that to communicate with the Yahoo fantasy sports API. See the package level documentation for one way to create a http.Client that can authenticate with Yahoo's APIs which can be passed in here.

func (*Client) GetAllTeamStats

func (c *Client) GetAllTeamStats(leagueKey string, week int) ([]Team, error)

GetAllTeamStats gets teams stats for a given week.

func (*Client) GetAllTeams

func (c *Client) GetAllTeams(leagueKey string) ([]Team, error)

GetAllTeams returns all teams playing in the given league.

func (*Client) GetFantasyContent

func (c *Client) GetFantasyContent(url string) (*FantasyContent, error)

GetFantasyContent directly access Yahoo fantasy resources.

See http://developer.yahoo.com/fantasysports/guide/ for more information

func (*Client) GetLeagueMetadata

func (c *Client) GetLeagueMetadata(leagueKey string) (*League, error)

GetLeagueMetadata returns the metadata associated with the given league.

func (*Client) GetLeagueStandings added in v0.3.0

func (c *Client) GetLeagueStandings(leagueKey string) (*League, error)

GetLeagueStandings gets a league containing the current standings.

func (*Client) GetMatchupsForWeekRange added in v0.4.0

func (c *Client) GetMatchupsForWeekRange(leagueKey string, startWeek, endWeek int) (map[int][]Matchup, error)

GetMatchupsForWeekRange returns a list of matchups for each week in the requested range.

func (*Client) GetPlayersStats

func (c *Client) GetPlayersStats(leagueKey string, week int, players []Player) ([]Player, error)

GetPlayersStats returns a list of Players containing their stats for the given week in the given year.

func (*Client) GetTeam

func (c *Client) GetTeam(teamKey string) (*Team, error)

GetTeam returns all available information about the given team.

func (*Client) GetTeamRoster

func (c *Client) GetTeamRoster(teamKey string, week int) ([]Player, error)

GetTeamRoster returns a team's roster for the given week.

func (*Client) GetUserLeagues

func (c *Client) GetUserLeagues(year string) ([]League, error)

GetUserLeagues returns a list of the current user's leagues for the given year.

func (*Client) RequestCount

func (c *Client) RequestCount() int

RequestCount returns the amount of requests made to the Yahoo API on behalf of the application represented by this Client.

type ContentProvider

type ContentProvider interface {
	Get(url string) (content *FantasyContent, err error)
	// The amount of requests made to the Yahoo API on behalf of the application
	// represented by this Client.
	RequestCount() int
}

ContentProvider returns the data from an API request.

type FantasyContent

type FantasyContent struct {
	XMLName xml.Name `xml:"fantasy_content"`
	League  League   `xml:"league"`
	Team    Team     `xml:"team"`
	Users   []User   `xml:"users>user"`
}

FantasyContent is the root level response containing the data from a request to the fantasy sports API.

type Game

type Game struct {
	Leagues []League `xml:"leagues>league"`
}

Game represents a single year in the Yahoo fantasy football ecosystem. It consists of zero or more leagues.

type HTTPClient added in v0.4.0

type HTTPClient interface {
	// Makes a HTTP GET request
	Get(url string) (response *http.Response, err error)
}

HTTPClient defines methods needed to communicated with a service over HTTP

type LRUCache added in v0.3.0

type LRUCache struct {
	ClientID        string
	Duration        time.Duration
	DurationSeconds int64
	Cache           *lru.LRUCache
}

LRUCache implements Cache utilizing a LRU cache and unique keys to cache content for up to a maximum duration.

func NewLRUCache added in v0.2.0

func NewLRUCache(
	clientID string,
	duration time.Duration,
	cache *lru.LRUCache) *LRUCache

NewLRUCache creates a new Cache that caches content for the given client for up to the maximum duration.

See NewCachedClient

func (*LRUCache) Get added in v0.3.0

func (l *LRUCache) Get(url string, time time.Time) (content *FantasyContent, ok bool)

Get the content for the given URL at the given time.

func (*LRUCache) Set added in v0.3.0

func (l *LRUCache) Set(url string, time time.Time, content *FantasyContent)

Set specifies that the given content was retrieved for the given URL at the given time. The content for that URL will be available by LRUCache.Get from the given 'time' up to 'time + l.Duration'

type LRUCacheValue added in v0.3.0

type LRUCacheValue struct {
	// contains filtered or unexported fields
}

LRUCacheValue implements lru.Value to be able to store fantasy content in a LRUCache

func (*LRUCacheValue) Size added in v0.3.0

func (v *LRUCacheValue) Size() int

Size always returns '1'. All LRU cache values have the same size, meaning the backing lru.LRUCache will prune strictly based on number of cached content and not the total size in memory.

type League

type League struct {
	LeagueKey   string     `xml:"league_key"`
	LeagueID    uint64     `xml:"league_id"`
	Name        string     `xml:"name"`
	URL         string     `xml:"url"`
	Players     []Player   `xml:"players>player"`
	Teams       []Team     `xml:"teams>team"`
	DraftStatus string     `xml:"draft_status"`
	CurrentWeek int        `xml:"current_week"`
	StartWeek   int        `xml:"start_week"`
	EndWeek     int        `xml:"end_week"`
	IsFinished  bool       `xml:"is_finished"`
	Standings   []Team     `xml:"standings>teams>team"`
	Scoreboard  Scoreboard `xml:"scoreboard"`
	Settings    Settings   `xml:"settings"`
}

A League is a uniquely identifiable group of players and teams. The scoring system, roster details, and other metadata can differ between leagues.

type Manager

type Manager struct {
	ManagerID      uint64 `xml:"manager_id"`
	Nickname       string `xml:"nickname"`
	GUID           string `xml:"guid"`
	IsCurrentLogin bool   `xml:"is_current_login"`
}

A Manager is a user in change of a given team.

type Matchup

type Matchup struct {
	Week  int    `xml:"week"`
	Teams []Team `xml:"teams>team"`
}

A Matchup is a collection of teams paired against one another for a given week.

type Name

type Name struct {
	Full  string `xml:"full"`
	First string `xml:"first"`
	Last  string `xml:"last"`
}

Name is a name of a player.

type Player

type Player struct {
	PlayerKey          string           `xml:"player_key"`
	PlayerID           uint64           `xml:"player_id"`
	Name               Name             `xml:"name"`
	DisplayPosition    string           `xml:"display_position"`
	ElligiblePositions []string         `xml:"elligible_positions>position"`
	SelectedPosition   SelectedPosition `xml:"selected_position"`
	PlayerPoints       Points           `xml:"player_points"`
}

A Player is a single player for the given sport.

type Points

type Points struct {
	CoverageType string `xml:"coverage_type"`
	Season       string `xml:"season"`
	Week         int    `xml:"week"`
	Total        float64
	TotalStr     string `xml:"total"`
}

Points represents scoring statistics for a time period specified by CoverageType.

type Record

type Record struct {
	Wins   int `xml:"wins"`
	Losses int `xml:"losses"`
	Ties   int `xml:"ties"`
}

Record is the number of wins, losses, and ties for a given team in their league.

type Roster

type Roster struct {
	CoverageType string   `xml:"coverage_type"`
	Players      []Player `xml:"players>player"`
	Week         int      `xml:"week"`
}

A Roster is the set of players belonging to one team for a given week.

type Scoreboard added in v0.4.0

type Scoreboard struct {
	Weeks    string    `xml:"week"`
	Matchups []Matchup `xml:"matchups>matchup"`
}

Scoreboard represents the matchups that occurred for one or more weeks.

type SelectedPosition

type SelectedPosition struct {
	CoverageType string `xml:"coverage_type"`
	Week         int    `xml:"week"`
	Position     string `xml:"position"`
}

SelectedPosition is the position chosen for a Player for a given week.

type Settings added in v0.4.0

type Settings struct {
	DraftType        string `xml:"draft_type"`
	ScoringType      string `xml:"scoring_type"`
	UsesPlayoff      bool   `xml:"uses_playoff"`
	PlayoffStartWeek int    `xml:"playoff_start_week"`
}

Settings describes how a league is configured

type Team

type Team struct {
	TeamKey               string        `xml:"team_key"`
	TeamID                uint64        `xml:"team_id"`
	Name                  string        `xml:"name"`
	URL                   string        `xml:"url"`
	TeamLogos             []TeamLogo    `xml:"team_logos>team_logo"`
	IsOwnedByCurrentLogin bool          `xml:"is_owned_by_current_login"`
	WavierPriority        int           `xml:"waiver_priority"`
	NumberOfMoves         int           `xml:"number_of_moves"`
	NumberOfTrades        int           `xml:"number_of_trades"`
	Managers              []Manager     `xml:"managers>manager"`
	Matchups              []Matchup     `xml:"matchups>matchup"`
	Roster                Roster        `xml:"roster"`
	TeamPoints            Points        `xml:"team_points"`
	TeamProjectedPoints   Points        `xml:"team_projected_points"`
	TeamStandings         TeamStandings `xml:"team_standings"`
	Players               []Player      `xml:"players>player"`
}

A Team is a participant in exactly one league.

type TeamLogo struct {
	Size string `xml:"size"`
	URL  string `xml:"url"`
}

TeamLogo is a image for a given team.

type TeamStandings

type TeamStandings struct {
	Rank          int
	RankStr       string  `xml:"rank"`
	Record        Record  `xml:"outcome_totals"`
	PointsFor     float64 `xml:"points_for"`
	PointsAgainst float64 `xml:"points_against"`
}

TeamStandings describes how a single Team ranks in their league.

type User

type User struct {
	Games []Game `xml:"games>game"`
}

User contains the games a user is participating in

Directories

Path Synopsis
Command debug starts a terminal based fantasy client using the OAuth consumer provided by package goff.
Command debug starts a terminal based fantasy client using the OAuth consumer provided by package goff.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL