diff options
author | Wim <wim@42.be> | 2017-06-22 01:00:27 +0200 |
---|---|---|
committer | Wim <wim@42.be> | 2017-06-22 01:00:27 +0200 |
commit | 1f914618538920db4bfec7b106ee97038b157c9b (patch) | |
tree | 6bd0ab107fe1673dbacdf9dfd10004289cd7bfab /vendor/github.com/Philipp15b/go-steam/steam_directory.go | |
parent | 1f9874102aaca09ce5e0289beff376c307b8c57b (diff) | |
download | matterbridge-msglm-1f914618538920db4bfec7b106ee97038b157c9b.tar.gz matterbridge-msglm-1f914618538920db4bfec7b106ee97038b157c9b.tar.bz2 matterbridge-msglm-1f914618538920db4bfec7b106ee97038b157c9b.zip |
Add vendor (steam)
Diffstat (limited to 'vendor/github.com/Philipp15b/go-steam/steam_directory.go')
-rw-r--r-- | vendor/github.com/Philipp15b/go-steam/steam_directory.go | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/vendor/github.com/Philipp15b/go-steam/steam_directory.go b/vendor/github.com/Philipp15b/go-steam/steam_directory.go new file mode 100644 index 00000000..80d919f0 --- /dev/null +++ b/vendor/github.com/Philipp15b/go-steam/steam_directory.go @@ -0,0 +1,76 @@ +package steam + +import ( + "encoding/json" + "fmt" + "math/rand" + "net/http" + "sync" + "time" + + "github.com/Philipp15b/go-steam/netutil" +) + +// Load initial server list from Steam Directory Web API. +// Call InitializeSteamDirectory() before Connect() to use +// steam directory server list instead of static one. +func InitializeSteamDirectory() error { + return steamDirectoryCache.Initialize() +} + +var steamDirectoryCache *steamDirectory = &steamDirectory{} + +type steamDirectory struct { + sync.RWMutex + servers []string + isInitialized bool +} + +// Get server list from steam directory and save it for later +func (sd *steamDirectory) Initialize() error { + sd.Lock() + defer sd.Unlock() + client := new(http.Client) + resp, err := client.Get(fmt.Sprintf("https://api.steampowered.com/ISteamDirectory/GetCMList/v1/?cellId=0")) + if err != nil { + return err + } + defer resp.Body.Close() + r := struct { + Response struct { + ServerList []string + Result uint32 + Message string + } + }{} + if err = json.NewDecoder(resp.Body).Decode(&r); err != nil { + return err + } + if r.Response.Result != 1 { + return fmt.Errorf("Failed to get steam directory, result: %v, message: %v\n", r.Response.Result, r.Response.Message) + } + if len(r.Response.ServerList) == 0 { + return fmt.Errorf("Steam returned zero servers for steam directory request\n") + } + sd.servers = r.Response.ServerList + sd.isInitialized = true + return nil +} + +func (sd *steamDirectory) GetRandomCM() *netutil.PortAddr { + sd.RLock() + defer sd.RUnlock() + if !sd.isInitialized { + panic("steam directory is not initialized") + } + rng := rand.New(rand.NewSource(time.Now().UnixNano())) + addr := netutil.ParsePortAddr(sd.servers[rng.Int31n(int32(len(sd.servers)))]) + return addr +} + +func (sd *steamDirectory) IsInitialized() bool { + sd.RLock() + defer sd.RUnlock() + isInitialized := sd.isInitialized + return isInitialized +} |