gostuff

package
v0.0.0-...-6155437 Latest Latest
Warning

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

Go to latest
Published: May 21, 2023 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Author: Josh Hoak aka Kashomon

Author: Josh Hoak aka Kashomon

Author: Josh Hoak aka Kashomon

Index

Constants

View Source
const (
	White = iota
	Black
)

Variables

View Source
var (
	USER_CONFIG_PATH = "secret/config.txt"
	ROOT_CONFIG_PATH = "secret/root.txt"
)
View Source
var (
	// Constrains the volatility. Typically set between 0.3 and 1.2.  Often
	// referred to as the 'system' constant.
	DefaultTau = 0.3

	DefaultRat = 1500.0 // Default starting rating
	DefaultDev = 350.0  // Default starting deviation
	DefaultVol = 0.06   // Default starting volatility
)

Overrideable Defaults

View Source
var Active = struct {
	sync.RWMutex
	Clients map[string]*websocket.Conn
}{Clients: make(map[string]*websocket.Conn)}

active users connected to chess room socket

View Source
var All = struct {
	sync.RWMutex
	Games map[int]*ChessGame
}{Games: make(map[int]*ChessGame)}

active and running games on the server

View Source
var Chat = struct {
	sync.RWMutex
	Lobby map[string]*websocket.Conn
}{Lobby: make(map[string]*websocket.Conn)}

active users connected to lobby socket

View Source
var DeviceManager = make(map[string]string)
View Source
var LeaderBoard = struct {
	sync.RWMutex
	Scores ScoreBoard
}{}
View Source
var Pending = struct {
	sync.RWMutex
	Matches map[int]*SeekMatch
}{Matches: make(map[int]*SeekMatch)}

pending matches in the lobby waiting for someone to accept

View Source
var PrivateChat = make(map[string]string)

used for quick access to identify two people who are private chatting and playing a game against each other

View Source
var SessionManager = make(map[string]string)

global SessionManager["username"] = sessionID

Functions

func CheckDBConnection

func CheckDBConnection(path string) bool

checks if database connection is open, returns true if MySQL is running the parameter path is where the text file is located

func CheckInGame

func CheckInGame(w http.ResponseWriter, r *http.Request)

checks if a player is in a game

func CheckNullInTable

func CheckNullInTable(table string)

check if there are any null fields in a table

func CheckUserName

func CheckUserName(w http.ResponseWriter, r *http.Request)

func CheckUserNameInDb

func CheckUserNameInDb(username string) bool

returns true if username already exists, this function assumes database is already pinged

func Cleanup

func Cleanup()

this function gets executed on ctrl-c

func CompressDatabase

func CompressDatabase()

zips up exported database

func ComputeRating

func ComputeRating(name string, gameID int, gameType string, result float64)

computes the rating for one player and the other player and updates the database and notifies both players, result can be white, black or draw

func CreateDirIfNotExist

func CreateDirIfNotExist(dir string)

func DbSetup

func DbSetup(backup string) bool

returns false if database setup failed, backup directory is passed in

func EngineSearchTimeRaw

func EngineSearchTimeRaw(fen string, engine *uci.Engine, t time.Duration) (bool, string)

func EnterChess

func EnterChess(ws *websocket.Conn)

websocket handler for gameroom

func EnterGuest

func EnterGuest(w http.ResponseWriter, r *http.Request)

func EnterLobby

func EnterLobby(ws *websocket.Conn)

websocket handler for lobby

func ExportDatabase

func ExportDatabase(isTemplate bool)

exports database(without Grandmaster games) to an .sql file as a hot backup @param isTemplate If true then export template database

func FetchLogs

func FetchLogs(w http.ResponseWriter, r *http.Request)

Show logs only to admins

func GetAllClosedCommits

func GetAllClosedCommits()

func GetCountry

func GetCountry(username string) string

Fetches country from database for a given player every time they login If country is null then it returns blank string which should be checked

func GetDb

func GetDb() *sql.DB

Returns global database handler

func GetGameID

func GetGameID(name string) (int, bool)

gets the game ID that a player is currently playing the bool indicates whether the player is currently playing a game

func GetPlayerData

func GetPlayerData(w http.ResponseWriter, r *http.Request)

displays player data when mouse hovers over

func GetRating

func GetRating(name string) (errMessage string, bullet, blitz, standard int16, correspondence int16)

fetches players bullet, blitz and standard rating

func GetRatingAndRD

func GetRatingAndRD(name string) (errRate string, bullet, blitz, standard, correspondence, bulletRD,
	blitzRD, standardRD float64, correspondenceRD float64)

fetches players bullet, blitz and standard rating and RD

func HasTimeElapsed

func HasTimeElapsed(targetTime string, timeCompare int, timeFormat string, useHour bool) (bool, int)

Returns true if the number of seconds is greater then the difference of targetTime - (this moment) Also returns time difference of targetTime and now, returns zero could mean there was an error timeFormat is the time format targetTime is in useHour is true to get difference in hours for rating history and false for forum spam control timeCompare can be in hours or seconds depending on useHour

func InitForum

func InitForum()

Checks forum to see if initial forum rows are missing, if they are then initialize them

func InitGame

func InitGame(gameID int, name string, fighter string)

intitalize all pawns to false as they have not moved yet, and also initialize all en passent to false

func IsAdmin

func IsAdmin(username string) bool

func IsDirectory

func IsDirectory(path string) bool

return trues if path is a directory, errors are explicitly not logged

func IsEnvironmentAppVeyor

func IsEnvironmentAppVeyor() bool

Returns true if the environment is in App Veyor

func IsEnvironmentTravis

func IsEnvironmentTravis() bool

Returns true if the environment is in Travis

func IsFileExist

func IsFileExist(path string) bool

Returns true if a given file exist in the path

func IsFloatEqual

func IsFloatEqual(a, b float64) bool

Returns true if floats are equal withing the tolerance level set by EPSILON

func IsMod

func IsMod(username string) bool

func OneTimeParseTemplates

func OneTimeParseTemplates()

Goes through all templates and parses then on startup

func ParseTemplates

func ParseTemplates(templateArgs interface{}, writer http.ResponseWriter, outputPath string,
	templatePaths ...string)

@templateArgs Template arguments that will be parsed @writer http.ResponseWriter or nil, if nil a file will be created and served @outputPath the output file of the parsed template @templatePath relative location to template that is to be parsed

func PrintMemoryStats

func PrintMemoryStats()

Print out memory usage

func ProcessLogin

func ProcessLogin(w http.ResponseWriter, r *http.Request)

process user input when signing in

func ProcessRegister

func ProcessRegister(w http.ResponseWriter, r *http.Request)

processes the users input when signing up

func Quit

func Quit(engine *uci.Engine)

func RandomString

func RandomString() string

func ReadFile

func ReadFile(path string) (string, string)

the parameter path is where the text file is located containing the database connection info if password is blank when encoded it will be blank when decoded

func ReadOneLine

func ReadOneLine(path string) string

Reads one line in the file and returns its contents, usually used to get activiation tokens for services

func RecurseDirectory

func RecurseDirectory(searchDir string, fp func(string), pattern string)

Recursives through directory and calls the function pointer fp on each file Pattern is the file pattern to apply the function to for example *json would apply the fp on all files recursively in the directory

func RemoveOldActivate

func RemoveOldActivate(days string)

Remove old entries in activate table in database

func RemoveOldForgot

func RemoveOldForgot(days string)

Remove old entries in the forgot table in the database If the entry is older then the days parameter then it will be deleted

func RemoveOldGames

func RemoveOldGames(days string)

remove games older then 180 days to clean up profile page, activated only on server startup

func ReplaceString

func ReplaceString(target, desired, source string) bool

Replaces target string in file with desired string in the file path Returns false if there was an error in the operation

func ResizeImages

func ResizeImages()

check if images need to be resized, if they do then resize them

func ResumeGame

func ResumeGame(w http.ResponseWriter, r *http.Request)

func Round

func Round(f float64) float64

func RoundPlus

func RoundPlus(f float64, places int) float64

func SetDb

func SetDb(dataDb *sql.DB)

Sets the global database handler

func SetupMySqlIni

func SetupMySqlIni()

Configures settings of MySQL .ini file

func SetupSecretDir

func SetupSecretDir()

For brand new installations this will setup credentials in the secret directory

func Show404Page

func Show404Page(w http.ResponseWriter, r *http.Request)

func StartCron

func StartCron()

func StartEngine

func StartEngine(args []string) *uci.Engine

Run starts an engine executable, with the given arguments. Returns the engine, make sure to call Quit() on the engine to clean up

func StartStockfishBot

func StartStockfishBot()

func TimeOutHttp

func TimeOutHttp(seconds time.Duration) http.Client

returns a http client to time out requests that take too long @seconds number of seconds for the request before it times out

func UpdateCaptcha

func UpdateCaptcha(w http.ResponseWriter, r *http.Request)

func UpdateHighScore

func UpdateHighScore()

fetches top ten bullet, blitz and standard ratings as well as the most recent 10 registered players

func ValidateCredentials

func ValidateCredentials(w http.ResponseWriter, r *http.Request) bool

returns true if user is an registered user that is logged in

func ValidateJSONFiles

func ValidateJSONFiles()

Validates all json files in project

Types

type AcceptMatch

type AcceptMatch struct {
	Type         string
	Name         string
	TargetPlayer string
	MatchID      int
}

used to store two player's name for redirecting on the front end in JavaScript

type ChatInfo

type ChatInfo struct {
	Type string
	Name string
	Text string
}

stores information for a message from chat for JSON

type ChessGame

type ChessGame struct {
	Type         string
	ID           int
	WhitePlayer  string
	BlackPlayer  string
	WhiteRating  int16
	BlackRating  int16
	GameMoves    []GameMove //stores chess move for games
	Status       string     //white to move, black to move, white won, black won, or draw
	Result       int8       //0 means black won, 1 means white won and 2 means draw. 2 is used intead of 0.5 as database type is int
	GameType     string     //bullet, blitz, standard, correspondence
	TimeControl  int
	BlackMinutes int
	BlackSeconds int
	WhiteMinutes int
	WhiteSeconds int
	StartMinutes int    // used to keep track of start time for correspondence
	PendingDraw  bool   //used to keep track if a player has offered a draw
	Rated        string //Yes if the game is rated, No if the game is unrated
	Spectate     bool
	CountryWhite string
	CountryBlack string
	Validator    *chess.Game
	// contains filtered or unexported fields
}

stores chess game information

func (*ChessGame) StartClock

func (table *ChessGame) StartClock(gameID int, minutes int, seconds int, name string)

keep track of both sides of the clock, when function exits the game is over

type Connection

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

used to identify who the socket connection is

func (*Connection) ChessConnect

func (c *Connection) ChessConnect()

Manages web sockets for the game room

func (*Connection) LobbyConnect

func (c *Connection) LobbyConnect()

type DatabaseInfo

type DatabaseInfo struct {
	Host     string
	User     string
	Password string
	DbName   string
	Port     string
}

func (*DatabaseInfo) ReadFile

func (databaseInfo *DatabaseInfo) ReadFile(path string)

type GameMove

type GameMove struct {
	Type string
	ID   int
	S    string // Source move
	T    string // Destination move
	P    string // Promotion piece
	Fen  string // FEN string of the board with the move played
}

source and destination of piece moves

type GoGame

type GoGame struct {
	ID           int
	White        string
	Black        string
	GameType     string
	WhiteRating  int
	BlackRating  int
	WhiteMinutes int
	WhiteSeconds int
	BlackMinutes int
	BlackSeconds int
	TimeControl  int
	Moves        string //json this back to a struct of Moves
	Total        int
	Result       int //2 means draw
	Status       string
	Date         string
	Time         string
	Rated        string
	CountryWhite string
	CountryBlack string
}

an individual game

func GetGames

func GetGames(name string) (storage []GoGame)

gets all games by player from database and stores them in array of structs

func GetSaved

func GetSaved(name string) (storage []GoGame)

type IPLocation

type IPLocation struct {
	IP           string
	Country_code string
	Country_name string
	Region_code  string
	Region_name  string
	City         string
	Zip_code     string
	Time_zone    string
	Latitude     float32
	Longitude    float32
	Metro_code   string
}

type MessageType

type MessageType struct {
	Type    string
	Name    string
	Message string
}

stores information of players that are online used to identify what kind of message it for incoming socket messages for JSON and check authentication

type Nrating

type Nrating struct {
	Type        string
	WhiteRating float64
	BlackRating float64
}

type Observers

type Observers struct {
	sync.RWMutex
	Names []string
}

contains an array of player names observing the table

type Rating

type Rating struct {
	Rating     float64 // Player's rating. Usually starts off at 1500.
	Deviation  float64 // Confidence/uncertainty in a player's rating
	Volatility float64 // Measures erratic performances
}

Represents a player's rating and the confidence in a player's rating.

func CalculateRating

func CalculateRating(player *Rating, opponent *Rating, res float64) (*Rating, error)

func DefaultRating

func DefaultRating() *Rating

Creates a default Rating using:

Rating     = DefaultRat
Deviation  = DefaultDev
Volatility = DefaultVol

func NewRating

func NewRating(r, rd, s float64) *Rating

Creates a new custom Rating.

func (*Rating) Copy

func (r *Rating) Copy() *Rating

Create a duplicate rating with the same values.

func (*Rating) FromGlicko2

func (r *Rating) FromGlicko2() *Rating

Creates a new rating, converted from Glicko2 scaling to Glicko1 scaling. This assumes the starting rating value is 1500.

func (*Rating) MostlyEquals

func (r *Rating) MostlyEquals(o *Rating, epsilon float64) bool

Ensure that some other Rating is equal to this rating, given some epsilon. In other words, find the error between this rating's values and the other rating's values and make sure it's less than epsilon in absolute value.

func (*Rating) String

func (r *Rating) String() string

func (*Rating) ToGlicko2

func (r *Rating) ToGlicko2() *Rating

Creates a new rating, converted from Glicko1 scaling to Glicko2 scaling. This assumes the starting rating value is 1500.

type RecentPlayer

type RecentPlayer struct {
	Name  string
	Date  string
	Index int
}

type ScoreBoard

type ScoreBoard struct {
	Bullet         [total]TopRating
	Blitz          [total]TopRating
	Standard       [total]TopRating
	Correspondence [total]TopRating
	Recent         [total]RecentPlayer //ten most recently registered players
}

type SeekMatch

type SeekMatch struct {
	Type        string
	Name        string
	Opponent    string
	Rating      int16  //player own rating
	GameType    string //bullet, blitz, standard, correspondence
	MatchID     int
	TimeControl int
	MinRating   int16
	MaxRating   int16
	Rated       string
	IsBot       bool
}

sends out seek matches real time in the lobby

type SpectateGame

type SpectateGame struct {
	Type     string
	ID       int `json:"ID,string"`
	Name     string
	Spectate string
}

used to unmarshall game ID that is being observed by player(Name)

type TopRating

type TopRating struct {
	Name   string
	Rating int
	Index  int
}

used for bullet, blitz and standard

type UserInfo

type UserInfo struct {
	Username        string
	Password        string
	IpAddress       string
	CaptchaId       string
	CaptchaSolution string
	InvalidLogins   int // Number of times an account had incorrect logins, resets on lockup
	IsLocked        bool
}

func (*UserInfo) Login

func (userinfo *UserInfo) Login(method string, url string, agent string, host string) (string, error)

func (*UserInfo) Register

func (userInfo *UserInfo) Register(host string) (string, error)

After all credentials are validated adds users info to database host param is used to handle corner case for localhost testing returns an error if there was a problem

Jump to

Keyboard shortcuts

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