census

package module
v0.0.0-...-bfc898f Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2016 License: MIT Imports: 17 Imported by: 5

README

GoDoc

census

census is a client library written for Go.

It's writen for stats-bot which is a slack bot the VS-U use

Documentation

Overview

The census package is used to query data from the Daybreak Game's census API for use in getting data for Planetside 2

Index

Constants

View Source
const (
	CACHE_CHARACTER cacheType = iota
	CACHE_CHARACTER_EVENTS
	CACHE_CHARACTER_NAME_ID

	CACHE_TEST
)
View Source
const (
	VS = "1"
	NC = "2"
	TR = "3"
)
View Source
const (
	// Player Events
	EventNil eventType = iota
	EventAcheivementEarned
	EventBattleRankUp
	EventDeath
	EventItemAdded
	EventSkillAdded
	EventVehicleDestory
	EventGainXP
	EventFacilityCapture
	EventFacilityDefend

	// World Events
	EventContinentLock
	EventContinentUnlock
	EventFacilityControl
	EventAlertEvent

	// Both
	EventPlayerLogin
	EventPlayerLogout
)

Cosntants not used.. May do some stuff with these in the future

View Source
const (
	REQUEST_CHARACTER        requestType = "character"
	REQUEST_CHARACTER_EVENTS requestType = "characters_event"
	REQUEST_WORLD            requestType = "world"
	REQUEST_OUTFIT           requestType = "outfit"
)

Variables

View Source
var (
	ErrCacheNotFound = fmt.Errorf("No Cache was found")
	ErrNoCache       = fmt.Errorf("census: Cache method called with cache disabled")
)
View Source
var BaseURL = "http://census.daybreakgames.com/"
View Source
var BaseURLOld = "http://census.soe.com/"
View Source
var CacheTypes = []string{
	"character",
	"character_events",
	"character_name",

	"tests",
}
View Source
var ErrCharDoesNotExist = fmt.Errorf("census: That character doesn't exist")

ErrCharDoesNotExist occurs when a function or method cannot find the given user in the current context

View Source
var ErrNoRedisURL = fmt.Errorf("census: no redis url specified.  Use SetRedisURL or REDIS_URL")
View Source
var ErrOutfitNotExist = fmt.Errorf("census: the outfit doesn't exist")
View Source
var ErrRedisCachingNotEnabled = fmt.Errorf("census: redis caching is not enabled")
View Source
var ErrTooManyRetries = fmt.Errorf("Failed too many retries")
View Source
var GlobalDecoder = ffjson.NewDecoder()

GlobalDecoder exists so we don't allocate a new decoder every response

Functions

This section is empty.

Types

type Cache

type Cache struct {
	Expires     time.Time `json:"expires"`
	LastUpdated time.Time `json:"last-updated"`
	// contains filtered or unexported fields
}

Cache is a struct

func NewCache

func NewCache() Cache

NewCache is going to change to NewCacheUpdate soon

func NewCacheUpdate

func NewCacheUpdate(dur time.Duration) Cache

NewCacheUpdate soon to be NewCache returns a new Cache object that

func (*Cache) InvalidateIn

func (c *Cache) InvalidateIn(dur time.Duration)

InvalidateIn invalidates the cache in the duration provided

func (*Cache) IsInvalid

func (c *Cache) IsInvalid() bool

IsInvalid returns if the data needs to be requested again OR updated

type Census

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

Census is the main object you use to query data

func NewCensus

func NewCensus(ServiceID string, Namespace string) *Census

NewCensus returns a new census object given your service ID

func NewCensusCache

func NewCensusCache(ServiceID string, Namespace string, cacheType CensusCacheType) *Census

NewCensusCache allows you to specify how to cache.

func (*Census) CleanNamespace

func (c *Census) CleanNamespace() string

CleanNamespace returns a proper namespace for internal use in queries

func (*Census) GetAllKillEvents

func (c *Census) GetAllKillEvents(characterID string) (*CharacterEventList, error)

GetAllKillEvents returns all kill events for a given character Notice: This method can do seveeral requets

: This method can take several seconds to run

func (*Census) GetCharacterByID

func (c *Census) GetCharacterByID(ID string) (*Character, error)

GetCharacterByID returns a Character if possible, otherwise returns nil and an error

func (*Census) GetCharacterByIDRes

func (c *Census) GetCharacterByIDRes(ID, resolves string) (*Character, error)

GetCharacterByIDRes will return a character by the given ID with only the resolves

resolves is a comma seperated list of fields to resolve

This method doesn't cache.

func (*Census) GetCharacterByName

func (c *Census) GetCharacterByName(name string) (*Character, error)

GetCharacterByName is a method to get a character instance by name it internally caches information and will pull new information if fifteen minutes has passed since the update.

func (*Census) GetCharacterID

func (c *Census) GetCharacterID(name string) (string, error)

GetCharacterID @TODO: Update to use Cache if possible

func (*Census) GetItemName

func (c *Census) GetItemName(id int, lang string) string

GetItemName returns the name of a given id in the language provided

func (*Census) GetKillEvents

func (c *Census) GetKillEvents(count int, characterID string) *CharacterEventList

GetKillEvents returns a CharacterEventList given a count and characterID

func (*Census) GetOutfitByName

func (c *Census) GetOutfitByName(name string) (*Outfit, error)

GetOutfitByName returns an outfit instance if it exists, otherwise it returns an error

func (*Census) GetServerByID

func (c *Census) GetServerByID(id string) Server

GetServerByID returns a server by a given ID.

TODO: This may need breaking changes to indicated an error

func (*Census) IsEU

func (c *Census) IsEU() bool

func (*Census) NewEventStream

func (c *Census) NewEventStream() *EventStream

NewEventStream returns an EventStream

NOTICE: This method dials a websocket

: This method starts a Go routine

func (*Census) NewPopulationSet

func (c *Census) NewPopulationSet() *PopulationSet

func (*Census) NewRequest

func (c *Census) NewRequest(Type requestType, query string, resolves string, limit int, more ...string) *Request

func (*Census) ReadCache

func (c *Census) ReadCache(ct cacheType, id interface{}, v interface{}) error

ReadCache reads the cache of the given type for the identifier and writes into the given interface

func (*Census) RedisConnect

func (c *Census) RedisConnect() error

func (*Census) SetRedisURL

func (c *Census) SetRedisURL(url string)

func (*Census) WriteCache

func (c *Census) WriteCache(ct cacheType, id interface{}, v interface{}) error

WriteCache writes the given interface to our caching filesystem

@TODO: Maybe use a cacheType type with constants to aid in pulling cache? @TODO: Switch to encoding/gob for performance?

I hear msgpack performance is good: github.com/vmihailenco/msgpack
gob has bad performance, but has very powerful reflection powers.

type CensusCacheType

type CensusCacheType int
const (
	CensusCacheNone CensusCacheType = iota
	CensusCacheDisk
	CensusCacheRedis
)

type CensusData

type CensusData struct {
	Error string `json:"error"`
}

CensusData is a struct that contains various metadata that a Census request can have.

type Character

type Character struct {
	CensusData
	Cache
	ID string `json:"character_id"`

	Name struct {
		First string `json:"first"`
		Lower string `json:"first_lower"`
	} `json:"name"`

	FactionID string `json:"faction_id"`

	TitleID string `json:"title_id"`

	Times struct {
		Creation      string `json:"creation"`
		LastSave      string `json:"last_save"`
		LastLogin     string `json:"last_login"`
		LoginCount    string `json:"login_count"`
		MinutesPlayed string `json:"minutes_played"`
	} `json:"times"`

	Certs struct {
		Earned        string `json:"earned_points"`
		Gifted        string `json:"gifted_points"`
		Spent         string `json:"spent_points"`
		Available     string `json:"available_points"`
		PercentToNext string `json:"percent_to_next"`
	} `json:"certs"`

	Battlerank struct {
		Rank          string `json:"value"`
		PercentToNext string `json:"percent_to_next"`
	} `json:"battle_rank"`

	DailyRibbon struct {
		Count string `json:"count"`
		Time  string `json:"time"`
	} `json:"daily_ribbon"`

	ProfileID string `json:"profile_id"`

	Outfit struct {
		ID          string `json:"outfit_id"`
		Name        string `json:"name"`
		Alias       string `json:"alias"`
		LeaderID    string `json:"leader_character_id"`
		MemberCount string `json:"member_count"`
		TimeCreated string `json:"time_created"`
	} `json:"outfit"`

	OnlineStatus string `json:"online_status"`

	Stats struct {
		Stat []struct {
			Name            string `json:"stat_name"`
			ProfileID       string `json:"profile_id"`
			ValueForever    string `json:"value_forever"`
			ValueMonthly    string `json:"value_monthly"`
			ValueWeekly     string `json:"value_weekly"`
			ValueDaily      string `json:"value_daily"`
			ValueOneLifeMax string `json:"value_one_life_max"`
			LastSave        string `json:"last_save"`
		} `json:"stat"`
		StatHistory []struct {
			Name       string            `json:"stat_name"`
			AllTime    string            `json:"all_time"`
			OneLifeMax string            `json:"one_life_max"`
			Day        map[string]string `json:"day"`
			Month      map[string]string `json:"Month"`
			Week       map[string]string `json:"Week"`
		} `json:"stat_history"`
		WeaponStat []struct {
			Name      string `json:"weapon_deaths"`
			ItemID    string `json:"item_id"`
			VehicleID string `json:"vehicle_id"`
			Value     string `json:"value"`
			LastSave  string `json:"last_save"`
		} `json:"weapon_stat"`
	} `json:"stats"`
	Faction struct {
		Name struct {
			En string `json:"en"`
			De string `json:"de"`
			Es string `json:"es"`
			Fr string `json:"fr"`
			It string `json:"it"`
			Tr string `json:"tr"`
		} `json:"name"`
		ImageSetID     string `json:"image_set_id"`
		ImageID        string `json:"image_id"`
		ImagePath      string `json:"image_path"`
		CodeTag        string `json:"code_tag"`
		UserSelectable string `json:"user_selectable"`
	} `json:"faction"`

	Items []struct {
		ID         string `json:"item_id"`
		StackCount string `json:"stack_count"`
	} `json:"items"`

	FriendsList []struct {
		ID            string `json:"character_id"`
		LastLoginTime string `json:"last_login_time"`
		Onlint        string `json:"online"`
	} `json:"friends_list"`

	World string `json:"world_id"`

	Parent   *Census `json:"-"`
	IsCached bool    `json:"-"`
}

Character is a struct representing a character in the Census API with all possible useful resolves

TODO: Maybe break this up into sub-structures. Too huge

func (*Character) GetCerts

func (c *Character) GetCerts() int

GetCerts returns the total certs a Character has earned from all possible sources

func (*Character) GetDeaths

func (c *Character) GetDeaths() int

GetDeaths returns the total death count for a given Character

func (*Character) GetFacilitiesCaptured

func (c *Character) GetFacilitiesCaptured() int

GetFacilitiesCaptured returns the facilities captured via the stats history

func (*Character) GetFacilitiesDefended

func (c *Character) GetFacilitiesDefended() int

GetFaciliesDefended returns the total amount of facilities a Character has defended

func (*Character) GetKills

func (c *Character) GetKills() int

GetKills returns the total kill count for a given Character

func (*Character) GetMedals

func (c *Character) GetMedals() int

GetMedals returns the total medals a Character has earned

func (*Character) GetRibbons

func (c *Character) GetRibbons() int

GetRibbons returns the total ribbons earned by the Character

func (*Character) GetScore

func (c *Character) GetScore() int

GetScore returns the total score of a Character

func (*Character) KDR

func (c *Character) KDR() float64

KDR returns the KDR of a Character

func (*Character) KDRS

func (c *Character) KDRS() string

KDRS returns the KDR of a Character in a more human readable format

func (*Character) MarshalJSON

func (mj *Character) MarshalJSON() ([]byte, error)

func (*Character) MarshalJSONBuf

func (mj *Character) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Character) ServerName

func (c *Character) ServerName() string

ServerName returns the English name for the server the Character resides on

func (*Character) TKPercent

func (c *Character) TKPercent() int

TKPercent is the percent of TKs in the last 1000 kills. This is changing to total once my caching system is in place. TODO: Error handle? Nahh TODO: Change this to work more like the implementation in th

func (*Character) TeamKillsInLast

func (c *Character) TeamKillsInLast(count int) int

func (*Character) UnmarshalJSON

func (uj *Character) UnmarshalJSON(input []byte) error

func (*Character) UnmarshalJSONFFLexer

func (uj *Character) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type CharacterEvent

type CharacterEvent struct {
	Character          Character `json:"character"`
	CharacterID        string    `json:"character_id"`
	AttackerID         string    `json:"attacker_character_id"`
	IsHeadshot         string    `json:"is_headshot"`
	IsCrit             string    `json:"is_critical"`
	AttackerWeaponID   string    `json:"attacker_weapon_id"`
	AttackerVehicleID  string    `json:"attacker_vehicle_id"`
	Time               string    `json:"timestamp"`
	Zone               string    `json:"zone_id"`
	World              string    `json:"world_id"`
	CharacterLoadoutID string    `json:"character_loadout_id"`
	AttackerLoadoutID  string    `json:"attacker_loadout_id"`
	TableType          string    `json:"table_type"`
}

CharacterEvent is a single frame of a /characters_event/ request

type CharacterEventList

type CharacterEventList struct {
	Cache    `json:"cache"`
	List     []CharacterEvent `json:"characters_event_list"`
	Returned int              `json:"returned"`
}

CharacterEventList is a struct capable of being Unmarshaled from a /characters_event/ request

func (*CharacterEventList) UpdateCache

func (c *CharacterEventList) UpdateCache(census *Census, characterID string) error

type Characters

type Characters struct {
	Characters []Character `json:"character_list"`
}

Character is a struct that contains all available information for a character in Planetside 2 We've factored out all of the date constants and instead convert it using the unix timestamps given. it leads to quicker conversions

func (*Characters) MarshalJSON

func (mj *Characters) MarshalJSON() ([]byte, error)

func (*Characters) MarshalJSONBuf

func (mj *Characters) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Characters) UnmarshalJSON

func (uj *Characters) UnmarshalJSON(input []byte) error

func (*Characters) UnmarshalJSONFFLexer

func (uj *Characters) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Collection

type Collection struct {
	Count        int
	Dynamic      bool
	UnknownCount bool
	Hidden       bool
	Name         string
	ResolveList  []string
}

Collection represents a single collection

func GetCollections

func GetCollections(c *Census) ([]*Collection, error)

func (*Collection) MarshalJSON

func (mj *Collection) MarshalJSON() ([]byte, error)

func (*Collection) MarshalJSONBuf

func (mj *Collection) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Collection) UnmarshalJSON

func (uj *Collection) UnmarshalJSON(input []byte) error

func (*Collection) UnmarshalJSONFFLexer

func (uj *Collection) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Event

type Event struct {
	Payload EventPayload
	Service string `json:"service"`
	Type    string `json:"type"`
}

Event is an event from the Planetside real time event streaming API. @TODO: Add the rest of the fields. They're all in the documentation

func (*Event) MarshalJSON

func (mj *Event) MarshalJSON() ([]byte, error)

func (*Event) MarshalJSONBuf

func (mj *Event) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Event) UnmarshalJSON

func (uj *Event) UnmarshalJSON(input []byte) error

func (*Event) UnmarshalJSONFFLexer

func (uj *Event) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type EventPayload

type EventPayload struct {
	EventName   string `json:"event_name"`
	Time        string `json:"timestamp"`
	CharacterID string `json:"character_id"`
	WorldID     string `json:"world_id"`
}

func (*EventPayload) MarshalJSON

func (mj *EventPayload) MarshalJSON() ([]byte, error)

func (*EventPayload) MarshalJSONBuf

func (mj *EventPayload) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*EventPayload) UnmarshalJSON

func (uj *EventPayload) UnmarshalJSON(input []byte) error

func (*EventPayload) UnmarshalJSONFFLexer

func (uj *EventPayload) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type EventSent

type EventSent struct {
	Service    string   `json:"service"`
	Action     string   `json:"action"`
	Worlds     []string `json:"worlds"`
	Characters []string `json:"characters"`
	EventNames []string `json:"eventNames"`
}

EventSent is a representation of any data we send to the API

func NewEventSubscription

func NewEventSubscription() *EventSent

NewEventSubscription returns an EventSent with the required fields for an event subscription already filled out

func (*EventSent) MarshalJSON

func (mj *EventSent) MarshalJSON() ([]byte, error)

func (*EventSent) MarshalJSONBuf

func (mj *EventSent) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*EventSent) UnmarshalJSON

func (uj *EventSent) UnmarshalJSON(input []byte) error

func (*EventSent) UnmarshalJSONFFLexer

func (uj *EventSent) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type EventStream

type EventStream struct {
	Err    chan error
	Events chan Event
	Closed chan struct{}
	// contains filtered or unexported fields
}

EventStream is an abstraction for the Planetside 2 streaming data API instead of using a raw websocket connection you can just use channels.

func (*EventStream) ClearSubscriptions

func (e *EventStream) ClearSubscriptions() error

ClearSubscriptions sends an event to clear all event subscriptions

func (*EventStream) Close

func (c *EventStream) Close()

Close closes the unlderlying websocket. This will send a struct{}{} down the Closed channel

func (*EventStream) MarshalJSON

func (mj *EventStream) MarshalJSON() ([]byte, error)

func (*EventStream) MarshalJSONBuf

func (mj *EventStream) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*EventStream) RawEventSent

func (e *EventStream) RawEventSent(sent *EventSent) error

RawEventSent sends a Raw, user formed EventSent

func (*EventStream) Subscribe

func (e *EventStream) Subscribe(sub *EventSent) error

Subscribe verifies that the provided EventSent is a subscripton event and sends it

@TODO: Need checks to make sure it's a subscribe

func (*EventStream) UnmarshalJSON

func (uj *EventStream) UnmarshalJSON(input []byte) error

func (*EventStream) UnmarshalJSONFFLexer

func (uj *EventStream) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Outfit

type Outfit struct {
	ID           string `json:"outfit_id"`
	Name         string `json:"name"`
	NameLower    string `json:"name_lower"`
	Alias        string `json:"alias"`
	AliasLower   string `json:"alias_lower"`
	TimeCreated  string `json:"time_created"`
	LeaderCharID string `json:"leader_character_id"`
	MemberCount  string `json:"member_count"`
}

func (*Outfit) MarshalJSON

func (mj *Outfit) MarshalJSON() ([]byte, error)

func (*Outfit) MarshalJSONBuf

func (mj *Outfit) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Outfit) UnmarshalJSON

func (uj *Outfit) UnmarshalJSON(input []byte) error

func (*Outfit) UnmarshalJSONFFLexer

func (uj *Outfit) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Outfits

type Outfits struct {
	CensusData
	Outfits []Outfit `json:"outfit_list"`
}

func (*Outfits) MarshalJSON

func (mj *Outfits) MarshalJSON() ([]byte, error)

func (*Outfits) MarshalJSONBuf

func (mj *Outfits) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*Outfits) UnmarshalJSON

func (uj *Outfits) UnmarshalJSON(input []byte) error

func (*Outfits) UnmarshalJSONFFLexer

func (uj *Outfits) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Population

type Population struct {
	VS uint
	TR uint
	NC uint
}

func (*Population) NCPercent

func (p *Population) NCPercent() int

func (*Population) TRPercent

func (p *Population) TRPercent() int

func (*Population) Total

func (p *Population) Total() int

func (*Population) VSPercent

func (p *Population) VSPercent() int

type PopulationSet

type PopulationSet struct {
	Servers map[string]*Population
	// contains filtered or unexported fields
}

func (*PopulationSet) PlayerLogin

func (c *PopulationSet) PlayerLogin(server, factionID string)

func (*PopulationSet) PlayerLogout

func (c *PopulationSet) PlayerLogout(server, factionID string)

type Request

type Request struct {
	*Census
	// contains filtered or unexported fields
}

func (*Request) Do

func (r *Request) Do(v interface{}) error

type Server

type Server struct {
	ID    string `json:"world_id"`
	State string `json:"state"`
	Name  struct {
		En string `json:"en"`
	} `json:"name"`
}

Server represents a single server or in other contexts a world

type Servers

type Servers struct {
	CensusData
	Servers []Server `json:"world_list"`
}

Servers is a group of servers. Usually would be used to parse a server from a census response

Directories

Path Synopsis
examples
pop
pop shows how to use the streaming API and PopulationSet struct to poll for population data
pop shows how to use the streaming API and PopulationSet struct to poll for population data

Jump to

Keyboard shortcuts

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