GithubHelp home page GithubHelp logo

carlocayos / go-cod Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 1.0 533 KB

Call of Duty API Go SDK

Home Page: https://github.com/carlocayos/go-cod

License: MIT License

Makefile 3.19% Shell 0.70% Go 96.11%
go cod call-of-duty sdk modern-warfare warzone coldwar activision blackops golang

go-cod's Introduction

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

go-cod's People

Contributors

carlocayos avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

bradselph

go-cod's Issues

Update swagger-spec to change `stream` field into type `map[string]SomeStruct`

Problem:

In the Gamer Loot response payload, it returns a "streams" object with repeating objects (i.e. loot_season_1, loot_season_2, etc).

{
  "status": "success",
  "data": {
    "streams": {
      "loot_season_1": {
        "name": "loot_season_1",
        "categoryNameLabel": "Season 1",
        "categoryTitleLabel": "Season 1",
        "tier": 0,
        "streamType": "season",
        "rarity": null,
        "lootType": null,
        "seasonInfoUrlKey": "season-1",
        "itemsObtained": null,
        "premiumTokenOwnedNotRedeemed": false,
        "tierSkipTokensUnredeemed": null,
        "premium": false
      },
      "loot_season_0": {
        "name": "loot_season_0",
        "categoryNameLabel": "Season 0",
        "categoryTitleLabel": "Season 0",
        "tier": 0,
        "streamType": "season",
        "rarity": null,
        "lootType": null,
        "seasonInfoUrlKey": "season-0",
        "itemsObtained": null,
        "premiumTokenOwnedNotRedeemed": false,
        "tierSkipTokensUnredeemed": null,
        "premium": false
      }
    }
  }
}

Find a way using go-swagger to autogenerate and represent the streams field as type map[string]SomeStruct

Sample

type SomeStruct struct {
  Name string
  CategoryNameLabel string
  CategoryTitleLabel string
  ...
}

someStruct := streams["loot_season_1"]
someStruct.CategoryNameLabel

Cannot import v2 of the module

When trying to import v2 I get the following message:

require github.com/carlocayos/go-cod: version "v2.0.0" invalid: should be v0 or v1, not v2

Add facade to protect codes from breaking API changes

Problem:
Activision can introduce breaking changes to the COD API. The SDK, along with all SDK users will then have to update their codes to adhere to the changes.

Solution:
Implement a facade pattern for simplicity and protecting SDK users of any breaking changes (e.g. Activision changing API format). The facade must be simple, allowing users to pass only the necessary values to the request without managing the swagger auto-generated codes.

Example:

Current steps in sending a leader board request.

c := gocod.NewClient(nil)
serviceOperations := c.ServiceClient.Operations

leaderBoardParams := service.LeaderBoardParams{
    Page:     1,
    Platform: "battle",
    Title:    "mw",
    Context:  context.Background(),
}

leaderBoardResponse, err := serviceOperations.LeaderBoard(&leaderBoardParams)

We can simplify it to this code

c := gocod.NewClient(nil)
c.LeaderBoard(context.Background, 1, "battle", "mw") 
   // or create a simple struct containing passed parameter values

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.