api

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2022 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package api contains methods to interact with the online-go.com REST API and Realtime API. For methods that require authentication, populate api.OauthClientID and call AuthenticatePassword or AuthenticateRefreshToken first before using the rest of the API. If successful, AuthData will contain relevant information about the user and tokens.

Index

Constants

This section is empty.

Variables

View Source
var (
	OauthClientID = strings.TrimSpace(oauthClientIDRaw)
	BaseURL       = "https://online-go.com"
	AuthData      UserInfo

	//errors
	InvalidRefreshToken = errors.New("Invalid refresh token")
)

Functions

func AuthenticatePassword

func AuthenticatePassword(username, password string) error

func AuthenticateRefreshToken

func AuthenticateRefreshToken(refreshToken string) error

AuthenticateRefreshToken authenticates with a token from the user. Either this function or

func ConvertSGFCoords

func ConvertSGFCoords(sgf string) *[]BoardPos

ConvertSGCoords turns an SGF coordinates string (2 letters for col+row) to a list of board positions. This doesn't contain any other context, like which player's turn it is. This function is currently not used for anything, but is left here as a reference.

func PosSGF

func PosSGF(p BoardPos) string

PosSGF converts a BoardPos x, y struct to SGF coordinate notation, which is required for posting moves to the realtime API. The SGF notation has two letters per coordinate, where "aa" is the upper left corner, "ba" is one stone to the right of that, "bc" is two stones below "ba", etc.

func SGFInt

func SGFInt(r byte) int

SGFInt converts a sgf notation letter to integer, which is required for reading the initial state parameter of the legacy single game endpoint. This function is currently not used for anything, but is left here as a reference.

Types

type BoardData

type BoardData struct {
	Width                 int               `json:"width"`
	Height                int               `json:"height"`
	InitialPlayer         string            `json:"initial_player"`
	Handicap              int               `json:"handicap"`
	FreeHandicapPlacement bool              `json:"free_handicap_placement"`
	InitialState          map[string]string `json:"initial_state"`
	Moves                 []BoardPos        `json:"moves"`
}

BoardData is a currently unused struct used to unmarshal the older api/v1/games/<id> endpoint. It requires reconstructing the game state based on Moves, which is incomplete. Use BoardState and its related functions instead.

func GetGameData

func GetGameData(gameID int64) *BoardData

GetGameData returns metadata for the given game ID, if it is public. If it is not, BoardData will be uninitialized. For getting the actual contents of the board, consider using GetGameState.

func (*BoardData) ColorForMove

func (b *BoardData) ColorForMove(i int) bool

ColorForMove(i) Get whether move i belongs to "black" or "white" (true = black, false = white) This is part of the unfinished BoardData struct and should not be relied on, but can serve as a starting point if you're considering using it.

type BoardPos

type BoardPos struct {
	X int
	Y int
}

func (*BoardPos) UnmarshalJSON

func (p *BoardPos) UnmarshalJSON(data []byte) error

type BoardState

type BoardState struct {
	MoveNumber   int     `json:"move_number"`
	PlayerToMove int64   `json:"player_to_move"`
	Phase        string  `json:"phase"`
	Board        [][]int `json:"board"`
	Outcome      string  `json:"outcome"`
	Removal      [][]int `json:"removal"`
	LastMove     struct {
		X int `json:"x"`
		Y int `json:"y"`
	} `json:"last_move"`
}

BoardState unmarshals the termination-api/game endpoint. In OGS, Board is represented as a 2D array, containing values from 0 to 2 (0 = empty, 1 = black, 2 = white). Board is indexed as Board[y][x].

func GetGameState

func GetGameState(gameID int64) *BoardState

GetGameState returns the whole board's state and the last played move, among other things. This endpoint contains little to no other metadata.

func (*BoardState) Finished

func (b *BoardState) Finished() bool

func (*BoardState) Height

func (b *BoardState) Height() int

func (*BoardState) Width

func (b *BoardState) Width() int

type EmitAuth

type EmitAuth struct {
	Auth     string `json:"auth"`
	PlayerID int64  `json:"player_id"`
	Username string `json:"username"`
}

type EmitGameConnect

type EmitGameConnect struct {
	GameID   int64 `json:"game_id"`
	PlayerID int64 `json:"player_id"`
	Chat     bool  `json:"chat"`
}

type EmitMove

type EmitMove struct {
	GameID   int64  `json:"game_id"`
	PlayerID int64  `json:"player_id"`
	Move     string `json:"move"`
}

type GameList

type GameList struct {
	Games []GameListData `json:"results"`
}

Game information

func GetGamesList

func GetGamesList() *GameList

GetGamesList returns a number of ongoing games you are actively participating in. Pagination is currently not implemented, so only the first few active games will be returned.

type GameListData

type GameListData struct {
	ID        int64             `json:"id"`
	Name      string            `json:"name"`
	Width     int               `json:"width"`
	Height    int               `json:"height"`
	Players   map[string]Player `json:"players"`
	BlackLost bool              `json:"black_lost"`
	WhiteLost bool              `json:"white_lost"`
}

GameListData contains data from the current games endpoint. This does not contain game details; these are contained in BoardState and are only loaded when a game is selected.

func (GameListData) Description

func (g GameListData) Description() string

Description returns a formatted description of the game. Do not rely on this string remaining stable; it is purely a utility function for termsuji and may change or be removed entirely.

func (GameListData) GameOver

func (g GameListData) GameOver() bool

GameOver returns true if the game has ended, otherwise false.

type OGSApiError

type OGSApiError struct {
	Code int
	// contains filtered or unexported fields
}

OGSApiError is returned on non-200 return codes from the online-go API.

func (*OGSApiError) Error

func (o *OGSApiError) Error() string

type OGSConfig

type OGSConfig struct {
	ChatAuth string `json:"chat_auth"`
}

func GetOGSConfig

func GetOGSConfig() *OGSConfig

GetOGSConfig gets the ui/config endpoint from OGS. Only one parameter, chat_auth, is extracted for use with the realtime API.

type OauthResponse

type OauthResponse struct {
	AccessToken      string `json:"access_token"`
	ExpiresIn        int    `json:"expires_in"`
	TokenType        string `json:"token_type"`
	RefreshToken     string `json:"refresh_token"`
	RawScope         string `json:"scope"` //must still be parsed, not necessary at the moment
	Error            string `json:"error"` //will be empty string if all went well
	ErrorDescription string `json:"error_description"`
}

OauthResponse is returned by the oauth/token endpoint of OGS.

func (*OauthResponse) GetError

func (o *OauthResponse) GetError() string

type OnClockResult

type OnClockResult struct {
	CurrentPlayerID int64 `json:"current_player"`
	BlackPlayerID   int64 `json:"black_player_id"`
	WhitePlayerID   int64 `json:"white_player_id"`
	LastMove        int64 `json:"last_move"` //ms since epoch
	Now             int64 `json:"now"`       //ms since epoch
}

type OnMoveResult

type OnMoveResult struct {
	GameID     int64    `json:"game_id"`
	Move       BoardPos `json:"move"`
	MoveNumber int      `json:"move_number"`
}

OnMoveResult is used as a return for the OnMove callback event.

type Player

type Player struct {
	ID         int64   `json:"id"`
	Username   string  `json:"username"`
	RawRanking float32 `json:"ranking"`
}

Player information

func (Player) Ranking

func (p Player) Ranking() string

func (Player) String

func (p Player) String() string

type RealtimeClient

type RealtimeClient struct {
	GameID int64
	// contains filtered or unexported fields
}

A socket client wrapper for communicating with the realtime API

func Connect

func Connect(gameID int64, f func(map[string]interface{})) (*RealtimeClient, error)

Create a new RealtimeClient which opens a socket connection for a specific game ID. The RealtimeClient is currently made to connect to one game at a time. An optional function f may be provided that will get called whenever the "game/<id>/gamedata" event is received, which happens directly after connecting and during the stone removal/finished phases. You are responsible for calling Disconnect() when the RealtimeClient is no longer required.

func (*RealtimeClient) Authenticate

func (r *RealtimeClient) Authenticate()

Authenticate gets a token from the REST API which is submitted through the Realtime API websocket. This is required before calling authenticated functions, like RealtimeClient.Move. This function requires being authenticated through api.Authenticate first.

func (*RealtimeClient) Disconnect

func (r *RealtimeClient) Disconnect()

Disconnect closes the underlying websocket.

func (*RealtimeClient) Move

func (r *RealtimeClient) Move(x, y int)

func (*RealtimeClient) OnClock

func (r *RealtimeClient) OnClock(f func(OnClockResult))

func (*RealtimeClient) OnMove

func (r *RealtimeClient) OnMove(f func(OnMoveResult))

OnMove registers a callback for whenever a move is played in the connected game.

type UserInfo

type UserInfo struct {
	Authenticated bool
	Player        Player
	Oauth         OauthResponse
}

UserInfo contains info about the logged in user after calling either Authenticate function.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳