go_cod

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2021 License: MIT Imports: 9 Imported by: 0

README

go-cod

go-cod is the unofficial Go SDK of the Call of Duty API used in the callofduty.com site

Getting Started

import "github.com/carlocayos/go-cod/v2"

Create a new go-cod client then use the services to access the COD APIs.

A short example:

// create the client
c := go_cod.NewClient(nil)

// get leader board list
leaderBoardResp, _ := c.LeaderBoard(context.Background(), 
    go_cod.ModernWarfare, go_cod.Battlenet, 3)
fmt.Println(leaderBoardResp.Status)
fmt.Println(leaderBoardResp.Data.Title)

The cod client is composed of an authentication client and service client.

Authentication

Authentication client is for getting a security token that will be used for most of the API requests.

See example on how to login and send authenticated requests.

// =======================================================
// 1) First, is creating a client and sending a register device request
// =======================================================
c := go_cod.NewClient(nil)

// send a register device request with a unique device id
// ksuid is used here to generate a unique id, but any uid generator would be fine
deviceId := ksuid.New().String()
registerDeviceRes, _ := c.RegisterDevice(context.Background(), deviceId)

// =======================================================
// 2) Next is the Login request. Replace it with your email and password
//    and pass the returned AuthHeader and Device ID
// =======================================================
email := "<< CHANGE ME >>"
password := "<< CHANGE ME >>"
loginRes, _ := c.Login(context.Background(), deviceId, email, 
    password, *registerDeviceRes.Data.AuthHeader)
fmt.Println(loginRes.ACTSSOCOOKIE)

// =======================================================
// 3) Final step is to send a Get Gamer Match List.
//    You need to call Login() before using this authenticated request.
//    The token is stored in the client and will be implicitly sent along 
//    each Authenticated request.
// =======================================================
// create Gamer struct - MUST CHANGE this to your own account
gamer := &go_cod.Gamer{
    Platform:   go_cod.Battlenet,
    LookupType: go_cod.BattlenetLookup,
    GamerTag:   "MrExcitement#6438",
}

gamerMatchListResp, _ := c.GamerMatchList(context.Background(), 
    go_cod.ModernWarfare, gamer, go_cod.Multiplayer, 0, 0, 3)

fmt.Println(gamerMatchListResp.Status)
for _, v := range gamerMatchListResp.Data {
    fmt.Printf("\tMap = %v\n", v.Map)
    fmt.Printf("\tMatchID = %v\n", v.MatchID)
    fmt.Printf("\tPlatform = %v\n", v.Platform)
    fmt.Printf("\tTimestamp = %v\n", v.Timestamp)
    fmt.Printf("\tTitle = %v\n", v.Title)
    fmt.Printf("\tType = %v\n\n", v.Type)
}
Unmapped fields

As there is no official API documentation, the swagger spec and JSON schema mapping is inferred through the actual JSON response payload.

Fields that are not mapped to a struct field can be accessed from the *AdditionalProperties field of type map[string]interface{}

missingField := response.Data.SampleResponseDataAdditionalProperties["missing_field_name"].(map[string]interface{})
anotherMissingField := missingField["another_missing_field"]
fmt.Printf("anotherMissingField")

See How to request missing APIs and fields

Sample codes and Payload

Sample codes are in examples

Actual JSON response payload *_sample.json can be found in json-schema

Generate Models and Client from Swagger Spec

The model and client codes are generated using go-swagger and OpenAPI Version 2.0

See here for more information on how to generate an API client

Generating client and models

For any changes in the COD API, update the swagger spec and generate a new client and model

Run this command to generate the client and model codes

make swagger-gen
API Documentation

Run this command to run the ReDoc container

make swagger-docs

Then open http://localhost:9000 to see the list of APIs.

Roadmap

  • Added facade to simplify API call process
  • Improve field mapping for Friend Stats API Response
  • Improve field mapping for Gamer Stats API Response
  • Improve field mapping for Battlepass Loot API Response
  • Improve field mapping for Match Details API Response
  • Improve field mapping for Loadout API Response
  • Improve field mapping for COD Points API Response
  • Improve field mapping for Purchasable API Response
  • Imoproved field mapping. See issue#3
  • Add more example codes and helper functions (e.g. Get Uno ID...)
  • Context handling

Request for missing APIs and fields

Report new or missing COD APIs and fields here

Contribution

Code improvements, suggestions, and updates are most welcome. Please feel free to raise an issue or create a pull request for your changes. 🙂

There is no official COD API and documentation released by Activision. If there is a breaking change on the COD API then let me know, so I can update this project.

Credits

Thanks to Lierrmm for his work on the NodeJS Call of Duty API Wrapper

Developer

Personal Site: carlocayos.com

Buy Me A Coffee

BTC address: 32zunH725N7PjBYj2TfbVoC3jVCyhqyn5h

ETH address: 0x2A17e4031FFeF64C638Dd9B190e05a150b2B8FBc

Documentation

Index

Constants

View Source
const (
	// API request
	DefaultServiceHost            = "my.callofduty.com"
	DefaultServiceBasePath        = "/api/papi-client"
	DefaultAuthenticationHost     = "profile.callofduty.com"
	DefaultAuthenticationBasePath = "/"
	ActSSOCookie                  = "ACT_SSO_COOKIE"

	// game title
	ColdWar       GameTitle = "cw"
	ModernWarfare GameTitle = "mw"

	// game types
	Multiplayer GameType = "mp"
	Warzone     GameType = "wz"

	// platforms
	Battlenet Platform = "battle"

	// Lookup type
	BattlenetLookup LookupType = "gamer"
)

Variables

View Source
var DefaultSchemes = []string{"https"}

Functions

This section is empty.

Types

type AuthToken

type AuthToken struct {
	ActSSOCookie string
}

Stores the Authentication for all authenticated requests

type AuthenticationClient

type AuthenticationClient struct {
	Operations authentication.ClientService
	Transport  runtime.ClientTransport
}

AuthenticationClient is the client containing authentication operations

func NewAuthenticationClient

func NewAuthenticationClient(transport runtime.ClientTransport, formats strfmt.Registry) *AuthenticationClient

New creates a new Authentication client

func NewAuthenticationClientWithConfig

func NewAuthenticationClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *AuthenticationClient

NewAuthenticationClientWithConfig creates a new Authentication client with config

func (*AuthenticationClient) SetTransport

func (c *AuthenticationClient) SetTransport(transport runtime.ClientTransport)

SetTransport changes the transport on the Authentication client and all its subresources

type Client

type Client struct {
	AuthenticationClient *AuthenticationClient
	ServiceClient        *ServiceClient
	AuthToken            *AuthToken
}

Go COD Client contains both an Authentication and Service Client

  1. Authentication client is usedfor authentication
  2. Service client is for common api requests

func NewClient

func NewClient(formats strfmt.Registry) *Client

Creates a default COD Client

func (*Client) BattlePassLoot

func (c *Client) BattlePassLoot(ctx context.Context, title GameTitle, platform Platform, season int64) (*models.BattlePassLootResponse, error)

BattlePassLoot returns the available loots for the specified battle pass season

func (*Client) CODPoints

func (c *Client) CODPoints(ctx context.Context, title GameTitle, gamer *Gamer) (*models.CodPointsResponse, error)

CODPoints returns the gamer COD Points. Authentication required

func (*Client) FriendsStats

func (c *Client) FriendsStats(ctx context.Context, title GameTitle, gamer *Gamer, gameType GameType) (*models.FriendStatsResponse, error)

FriendsStats returns the friend stats profile. Authentication required

func (*Client) FullMatchInfo

func (c *Client) FullMatchInfo(ctx context.Context, title GameTitle, platform Platform, gameType GameType,
	matchId string) (*models.FullMatchInfoResponse, error)

FullMatchInfo returns the match information

func (*Client) GamerLoot

func (c *Client) GamerLoot(ctx context.Context, title GameTitle, gamer *Gamer) (*models.GamerLootResponse, error)

GamerLoot returns the gamer loots. Authentication required

func (*Client) GamerMatchDetails

func (c *Client) GamerMatchDetails(ctx context.Context, title GameTitle, gamer *Gamer, gameType GameType,
	start int64, end int64, limit int32) (*models.GamerMatchDetailsResponse, error)

GamerMatchDetails returns the gamer match details. Authentication required

func (*Client) GamerMatchList

func (c *Client) GamerMatchList(ctx context.Context, title GameTitle, gamer *Gamer, gameType GameType,
	start int64, end int64, limit int32) (*models.GamerMatchListResponse, error)

GamerMatchList returns a list of gamer matches. Authentication required

func (*Client) GamerStats

func (c *Client) GamerStats(ctx context.Context, title GameTitle, gamer *Gamer, gameType GameType) (*models.GamerStatsResponse, error)

GamerStats returns the gamer stats profile. Authentication required

func (*Client) LeaderBoard

func (c *Client) LeaderBoard(ctx context.Context, title GameTitle, platform Platform, page int64) (*models.LeaderBoardResponse, error)

LeaderBoard returns the leader board details

func (*Client) Loadout

func (c *Client) Loadout(ctx context.Context, title GameTitle, gameType GameType) (*models.LoadoutResponse, error)

Loadout returns all the loadout information

func (*Client) LoggedIn

func (c *Client) LoggedIn() error

LoggedIn checks if the user has logged in and generated a valid token

func (*Client) Login

func (c *Client) Login(ctx context.Context, deviceId string, email string, password string, token string) (*models.LoginResponse, error)

Login uses the token received from register device authHeader, then returns cookie security tokens

used for all authenticated requests

func (*Client) MapList

func (c *Client) MapList(ctx context.Context, title GameTitle, platform Platform, gameType GameType) (*models.MapListResponse, error)

Map List returns a list of maps and its available game modes

func (*Client) MatchAnalysis

func (c *Client) MatchAnalysis(ctx context.Context, title GameTitle, gamer *Gamer, end int64) (*models.MatchAnalysisResponse, error)

MatchAnalysis returns the full match information. Authentication required

func (*Client) Purchasable

func (c *Client) Purchasable(ctx context.Context, title GameTitle, platform Platform) (*models.PurchasableResponse, error)

Purchasable returns all the purchasable items

func (*Client) RegisterDevice

func (c *Client) RegisterDevice(ctx context.Context, deviceId string) (*models.RegisterDeviceResponse, error)

RegisterDevice registers the device and returns the Auth Header token

type GameTitle

type GameTitle string

type GameType

type GameType string

type Gamer

type Gamer struct {
	Platform   Platform
	LookupType LookupType
	GamerTag   string
}

Gamer ID details

type LookupType

type LookupType string

type Platform

type Platform string

type ServiceClient

type ServiceClient struct {
	Operations service.ClientService
	Transport  runtime.ClientTransport
}

ServiceClient is the client containing common service operations

func NewServiceClient

func NewServiceClient(transport runtime.ClientTransport, formats strfmt.Registry) *ServiceClient

New creates a new Service client

func NewServiceClientWithConfig

func NewServiceClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *ServiceClient

NewServiceClientWithConfig creates a new Service client with config

func (*ServiceClient) SetTransport

func (c *ServiceClient) SetTransport(transport runtime.ClientTransport)

SetTransport changes the transport on the Service client and all its subresources

type TransportConfig

type TransportConfig struct {
	Host     string
	BasePath string
	Schemes  []string
}

TransportConfig contains the transport related info

func DefaultAuthTransportConfig

func DefaultAuthTransportConfig() *TransportConfig

DefaultAuthTransportConfig creates a TransportConfig with the default settings for the Authentication Client

func DefaultServiceTransportConfig

func DefaultServiceTransportConfig() *TransportConfig

DefaultServiceTransportConfig creates a TransportConfig with the default settings for the Service Client

func (*TransportConfig) WithBasePath

func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig

WithBasePath overrides the default basePath

func (*TransportConfig) WithHost

func (cfg *TransportConfig) WithHost(host string) *TransportConfig

WithHost overrides the default host

func (*TransportConfig) WithSchemes

func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig

WithSchemes overrides the default schemes

Jump to

Keyboard shortcuts

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