117 lines
2.3 KiB
Go
117 lines
2.3 KiB
Go
package ts3
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/asaskevich/EventBus"
|
|
"github.com/jkoenig134/schema"
|
|
)
|
|
|
|
type Config struct {
|
|
// e.g. https://example.com:10080 or http://example.com:10443
|
|
BaseURL string
|
|
|
|
APIKey string
|
|
|
|
// default 10s
|
|
Timeout time.Duration
|
|
}
|
|
|
|
type TeamspeakHttpClient struct {
|
|
config Config
|
|
netHttp http.Client
|
|
eventBus EventBus.Bus
|
|
encoder schema.Encoder
|
|
serverID int
|
|
eventClient *EventClient
|
|
}
|
|
|
|
func (c *TeamspeakHttpClient) SetServerID(serverID int) {
|
|
c.serverID = serverID
|
|
|
|
if c.eventClient != nil {
|
|
_ = c.eventClient.SwitchServer(serverID)
|
|
}
|
|
}
|
|
|
|
func NewClient(config Config) TeamspeakHttpClient {
|
|
if config.Timeout == 0 {
|
|
config.Timeout = 10 * time.Second
|
|
}
|
|
return TeamspeakHttpClient{
|
|
config,
|
|
http.Client{ Timeout: config.Timeout },
|
|
EventBus.New(),
|
|
*schema.NewEncoder(),
|
|
1,
|
|
nil,
|
|
}
|
|
}
|
|
|
|
type status struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
type tsResponse struct {
|
|
Body interface{} `json:"body"`
|
|
Status status `json:"status"`
|
|
}
|
|
|
|
func (t *tsResponse) asError() error {
|
|
return fmt.Errorf(
|
|
"Query returned non 0 exit code: '%d'. Message: '%s' ",
|
|
t.Status.Code,
|
|
t.Status.Message)
|
|
}
|
|
|
|
func (c *TeamspeakHttpClient) requestWithParams(path string, paramStruct interface{}, v interface{}) error {
|
|
param, err := c.encodeStruct(paramStruct)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
merged := fmt.Sprintf("%s%s", path, param)
|
|
return c.request(merged, v)
|
|
}
|
|
|
|
func (c *TeamspeakHttpClient) request(path string, v interface{}) error {
|
|
url := fmt.Sprintf("%s/%d/%s", c.config.BaseURL, c.serverID, path)
|
|
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
|
|
if err != nil { return err }
|
|
req.Header.Set("x-api-key", c.config.APIKey)
|
|
|
|
resp, err := c.netHttp.Do(req)
|
|
if err != nil { return err }
|
|
|
|
if resp.StatusCode != 200 {
|
|
return fmt.Errorf("Error Code: %d\n%v", resp.StatusCode, resp.Body)
|
|
}
|
|
|
|
tsResponse := &tsResponse{}
|
|
err = json.NewDecoder(resp.Body).Decode(tsResponse)
|
|
if err != nil { return err }
|
|
|
|
if tsResponse.Status.Code != 0 {
|
|
return tsResponse.asError()
|
|
}
|
|
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
|
|
jsonBody, err := json.Marshal(tsResponse.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err = json.Unmarshal(jsonBody, v); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|