cfapi

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package cfapi provides a client for the Codeforces API

Index

Constants

View Source
const (
	BaseURL         = "https://codeforces.com/api"
	DefaultTimeout  = 30 * time.Second
	DefaultTTL      = 5 * time.Minute
	RateLimit       = 5                // requests per second
	MaxResponseSize = 10 * 1024 * 1024 // 10MB max response size to prevent OOM
)
View Source
const (
	VerdictOK                  = "OK"
	VerdictFailed              = "FAILED"
	VerdictPartial             = "PARTIAL"
	VerdictCompilationError    = "COMPILATION_ERROR"
	VerdictRuntimeError        = "RUNTIME_ERROR"
	VerdictWrongAnswer         = "WRONG_ANSWER"
	VerdictPresentationError   = "PRESENTATION_ERROR"
	VerdictTimeLimitExceeded   = "TIME_LIMIT_EXCEEDED"
	VerdictMemoryLimitExceeded = "MEMORY_LIMIT_EXCEEDED"
	VerdictIdlenessLimitExc    = "IDLENESS_LIMIT_EXCEEDED"
	VerdictSecurityViolated    = "SECURITY_VIOLATED"
	VerdictCrashed             = "CRASHED"
	VerdictInputPrepCrashed    = "INPUT_PREPARATION_CRASHED"
	VerdictChallenged          = "CHALLENGED"
	VerdictSkipped             = "SKIPPED"
	VerdictTesting             = "TESTING"
	VerdictRejected            = "REJECTED"
)

Verdict constants

View Source
const (
	PhaseBefore      = "BEFORE"
	PhaseCoding      = "CODING"
	PhasePendingTest = "PENDING_SYSTEM_TEST"
	PhaseSystemTest  = "SYSTEM_TEST"
	PhaseFinished    = "FINISHED"
)

ContestPhase constants

Variables

View Source
var RankThresholds = map[string]int{
	"newbie":                    0,
	"pupil":                     1200,
	"specialist":                1400,
	"expert":                    1600,
	"candidate master":          1900,
	"master":                    2100,
	"international master":      2300,
	"grandmaster":               2400,
	"international grandmaster": 2600,
	"legendary grandmaster":     3000,
}

Rank thresholds

Functions

This section is empty.

Types

type Cache

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

Cache provides thread-safe in-memory caching with TTL

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache with the given TTL

func (*Cache) Clear

func (c *Cache) Clear()

Clear removes all items from the cache

func (*Cache) Delete

func (c *Cache) Delete(key string)

Delete removes an item from the cache

func (*Cache) Get

func (c *Cache) Get(key string) (interface{}, bool)

Get retrieves an item from the cache

func (*Cache) GetOrSet

func (c *Cache) GetOrSet(key string, fn func() (interface{}, error)) (interface{}, error)

GetOrSet retrieves from cache or calls the function to set

func (*Cache) Set

func (c *Cache) Set(key string, value interface{})

Set stores an item in the cache

func (*Cache) SetWithTTL

func (c *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration)

SetWithTTL stores an item with a custom TTL

func (*Cache) Size

func (c *Cache) Size() int

Size returns the number of items in the cache

type CacheEntry

type CacheEntry struct {
	Value      interface{}
	Expiration time.Time
}

CacheEntry represents a cached item with expiration

type Client

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

Client is the Codeforces API client

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new Codeforces API client

func (*Client) ClearCache

func (c *Client) ClearCache()

ClearCache clears the API cache

func (*Client) FilterProblems

func (c *Client) FilterProblems(ctx context.Context, minRating, maxRating int, tags []string, excludeSolved bool, handle string) ([]Problem, error)

FilterProblems filters problems by criteria

func (*Client) GetContest

func (c *Client) GetContest(ctx context.Context, contestID int) (*Contest, error)

GetContest retrieves contest information

func (*Client) GetContestStandings

func (c *Client) GetContestStandings(ctx context.Context, contestID int, from, count int, handles []string, showUnofficial bool) (*ContestStandings, error)

GetContestStandings retrieves contest standings

func (*Client) GetContests

func (c *Client) GetContests(ctx context.Context, gym bool) ([]Contest, error)

GetContests retrieves list of contests

func (*Client) GetProblem

func (c *Client) GetProblem(ctx context.Context, contestID int, index string) (*Problem, error)

GetProblem retrieves a single problem by contest ID and index

func (*Client) GetProblems

func (c *Client) GetProblems(ctx context.Context, tags []string) (*ProblemsResponse, error)

GetProblems retrieves all problems from the problemset

func (*Client) GetSolvedProblems

func (c *Client) GetSolvedProblems(ctx context.Context, handle string) ([]Problem, error)

GetSolvedProblems returns all problems solved by a user

func (*Client) GetUserInfo

func (c *Client) GetUserInfo(ctx context.Context, handles []string) ([]User, error)

GetUserInfo retrieves information about users

func (*Client) GetUserRating

func (c *Client) GetUserRating(ctx context.Context, handle string) ([]RatingChange, error)

GetUserRating retrieves rating history for a user

func (*Client) GetUserSubmissions

func (c *Client) GetUserSubmissions(ctx context.Context, handle string, from, count int) ([]Submission, error)

GetUserSubmissions retrieves submissions for a user

func (*Client) HasCredentials

func (c *Client) HasCredentials() bool

HasCredentials returns true if API credentials are configured

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks if the API is accessible

type ClientOption

type ClientOption func(*Client)

ClientOption configures the client

func WithAPICredentials

func WithAPICredentials(key, secret string) ClientOption

WithAPICredentials sets API key and secret for authenticated requests

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) ClientOption

WithCacheTTL sets custom cache TTL

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

type Contest

type Contest struct {
	ID                  int    `json:"id"`
	Name                string `json:"name"`
	Type                string `json:"type"`
	Phase               string `json:"phase"`
	Frozen              bool   `json:"frozen"`
	DurationSeconds     int64  `json:"durationSeconds"`
	StartTimeSeconds    int64  `json:"startTimeSeconds,omitempty"`
	RelativeTimeSeconds int64  `json:"relativeTimeSeconds,omitempty"`
	PreparedBy          string `json:"preparedBy,omitempty"`
	WebsiteURL          string `json:"websiteUrl,omitempty"`
	Description         string `json:"description,omitempty"`
	Difficulty          int    `json:"difficulty,omitempty"`
	Kind                string `json:"kind,omitempty"`
	ICPCRegion          string `json:"icpcRegion,omitempty"`
	Country             string `json:"country,omitempty"`
	City                string `json:"city,omitempty"`
	Season              string `json:"season,omitempty"`
}

Contest represents a Codeforces contest

func (*Contest) Duration

func (c *Contest) Duration() time.Duration

Duration returns the contest duration

func (*Contest) IsFinished

func (c *Contest) IsFinished() bool

IsFinished returns true if the contest has finished

func (*Contest) IsRunning

func (c *Contest) IsRunning() bool

IsRunning returns true if the contest is currently running

func (*Contest) StartTime

func (c *Contest) StartTime() time.Time

StartTime returns the contest start time

type ContestStandings

type ContestStandings struct {
	Contest  Contest       `json:"contest"`
	Problems []Problem     `json:"problems"`
	Rows     []RanklistRow `json:"rows"`
}

ContestStandings represents contest standings

type Member

type Member struct {
	Handle string `json:"handle"`
	Name   string `json:"name,omitempty"`
}

Member represents a party member

type Party

type Party struct {
	ContestID        int      `json:"contestId,omitempty"`
	Members          []Member `json:"members"`
	ParticipantType  string   `json:"participantType"`
	TeamID           int      `json:"teamId,omitempty"`
	TeamName         string   `json:"teamName,omitempty"`
	Ghost            bool     `json:"ghost"`
	Room             int      `json:"room,omitempty"`
	StartTimeSeconds int64    `json:"startTimeSeconds,omitempty"`
}

Party represents submission author info

type Problem

type Problem struct {
	ContestID      int      `json:"contestId"`
	ProblemsetName string   `json:"problemsetName,omitempty"`
	Index          string   `json:"index"`
	Name           string   `json:"name"`
	Type           string   `json:"type"`
	Points         float64  `json:"points,omitempty"`
	Rating         int      `json:"rating,omitempty"`
	Tags           []string `json:"tags"`
}

Problem represents a Codeforces problem

func (*Problem) ContestURL

func (p *Problem) ContestURL() string

ContestURL returns the contest URL for this problem

func (*Problem) ProblemID

func (p *Problem) ProblemID() string

ProblemID returns a unique identifier for the problem

func (*Problem) URL

func (p *Problem) URL() string

URL returns the problem URL

type ProblemResult

type ProblemResult struct {
	Points                    float64 `json:"points"`
	Penalty                   int     `json:"penalty,omitempty"`
	RejectedAttemptCount      int     `json:"rejectedAttemptCount"`
	Type                      string  `json:"type"`
	BestSubmissionTimeSeconds int64   `json:"bestSubmissionTimeSeconds,omitempty"`
}

ProblemResult represents result for a specific problem in standings

type ProblemStatistics

type ProblemStatistics struct {
	ContestID   int    `json:"contestId"`
	Index       string `json:"index"`
	SolvedCount int    `json:"solvedCount"`
}

ProblemStatistics represents problem solve statistics

type ProblemsResponse

type ProblemsResponse struct {
	Problems          []Problem           `json:"problems"`
	ProblemStatistics []ProblemStatistics `json:"problemStatistics"`
}

ProblemsResponse contains problems and their statistics

type RanklistRow

type RanklistRow struct {
	Party                 Party           `json:"party"`
	Rank                  int             `json:"rank"`
	Points                float64         `json:"points"`
	Penalty               int             `json:"penalty"`
	SuccessfulHackCount   int             `json:"successfulHackCount"`
	UnsuccessfulHackCount int             `json:"unsuccessfulHackCount"`
	ProblemResults        []ProblemResult `json:"problemResults"`
}

RanklistRow represents a row in contest standings

type RatingChange

type RatingChange struct {
	ContestID               int    `json:"contestId"`
	ContestName             string `json:"contestName"`
	Handle                  string `json:"handle"`
	Rank                    int    `json:"rank"`
	RatingUpdateTimeSeconds int64  `json:"ratingUpdateTimeSeconds"`
	OldRating               int    `json:"oldRating"`
	NewRating               int    `json:"newRating"`
}

RatingChange represents a user's rating change after a contest

func (*RatingChange) RatingDelta

func (rc *RatingChange) RatingDelta() int

RatingDelta returns the rating change amount

type Response

type Response[T any] struct {
	Status  string `json:"status"`
	Result  T      `json:"result,omitempty"`
	Comment string `json:"comment,omitempty"`
}

API Response wrapper

type Submission

type Submission struct {
	ID                  int64   `json:"id"`
	ContestID           int     `json:"contestId,omitempty"`
	CreationTimeSeconds int64   `json:"creationTimeSeconds"`
	RelativeTimeSeconds int64   `json:"relativeTimeSeconds"`
	Problem             Problem `json:"problem"`
	Author              Party   `json:"author"`
	ProgrammingLanguage string  `json:"programmingLanguage"`
	Verdict             string  `json:"verdict,omitempty"`
	Testset             string  `json:"testset"`
	PassedTestCount     int     `json:"passedTestCount"`
	TimeConsumedMillis  int64   `json:"timeConsumedMillis"`
	MemoryConsumedBytes int64   `json:"memoryConsumedBytes"`
	Points              float64 `json:"points,omitempty"`
}

Submission represents a problem submission

func (*Submission) IsAccepted

func (s *Submission) IsAccepted() bool

IsAccepted returns true if the submission was accepted

func (*Submission) SubmissionTime

func (s *Submission) SubmissionTime() time.Time

SubmissionTime returns the submission time as time.Time

type User

type User struct {
	Handle                  string `json:"handle"`
	Email                   string `json:"email,omitempty"`
	FirstName               string `json:"firstName,omitempty"`
	LastName                string `json:"lastName,omitempty"`
	Country                 string `json:"country,omitempty"`
	City                    string `json:"city,omitempty"`
	Organization            string `json:"organization,omitempty"`
	Contribution            int    `json:"contribution"`
	Rank                    string `json:"rank"`
	Rating                  int    `json:"rating"`
	MaxRank                 string `json:"maxRank"`
	MaxRating               int    `json:"maxRating"`
	LastOnlineTimeSeconds   int64  `json:"lastOnlineTimeSeconds"`
	RegistrationTimeSeconds int64  `json:"registrationTimeSeconds"`
	FriendOfCount           int    `json:"friendOfCount"`
	Avatar                  string `json:"avatar"`
	TitlePhoto              string `json:"titlePhoto"`
}

User represents a Codeforces user

func (*User) LastOnline

func (u *User) LastOnline() time.Time

LastOnline returns when the user was last online

func (*User) RegistrationTime

func (u *User) RegistrationTime() time.Time

RegistrationTime returns when the user registered

Jump to

Keyboard shortcuts

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