-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
337 lines (271 loc) · 8.32 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package betfair
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"math/rand/v2"
"net/http"
"net/url"
)
type SessionStatus string
const (
SS_SUCCESS = "SUCCESS"
SS_FAIL = "FAIL"
)
type SessionStatusError string
const (
SS_ERR_INPUT_VALIDATION_ERROR = "INPUT_VALIDATION_ERROR"
SS_ERR_INTERNAL_ERROR = "INTERNAL_ERROR"
SS_ERR_NO_SESSION = "NO_SESSION"
)
type (
Client struct {
HttpClient *http.Client
Tls *tls.Config
ApplicationName string
ApplicationKey string
SessionToken string
Rest bool
}
SessionResponse struct {
SessionToken string `json:"sessionToken"`
LoginStatus string `json:"loginStatus"`
}
SessionStatusResponse struct {
Token string `json:"token"`
Product string `json:"product"`
Status SessionStatus `json:"status"`
Error SessionStatusError `json:"error"`
}
)
func NewClient(tls *tls.Config, app_key string, applicationName string) *Client {
return &Client{Tls: tls, ApplicationKey: app_key, ApplicationName: applicationName}
}
func (client *Client) Do(req *http.Request) (*http.Response, error) {
if client.HttpClient == nil {
return nil, errors.New("client not initialised: please resume or create a new session")
}
req.Header.Add("X-Authentication", client.SessionToken)
req.Header.Add("X-Application", client.ApplicationKey)
req.Header.Add("Accept", "application/json")
req.Header.Add("content-type", "application/json")
return client.HttpClient.Do(req)
}
func (client *Client) Resume(sessionToken string) (*http.Response, error) {
client.HttpClient = &http.Client{}
client.SessionToken = sessionToken
keepAliveUrl := url.URL{Path: "https://identitysso.betfair.com/api/keepAlive"}
req, _ := http.NewRequest("POST", keepAliveUrl.RequestURI(), nil)
resp, err := client.Do(req)
if err != nil {
client.HttpClient = nil
client.SessionToken = ""
return resp, err
}
json := SessionStatusResponse{}
if err := ReadJson(resp, &json); err != nil {
client.HttpClient = nil
client.SessionToken = ""
return resp, err
}
if json.Error != "" {
client.HttpClient = nil
client.SessionToken = ""
return resp, errors.New(string(json.Error))
}
return resp, nil
}
func (client *Client) Login(username string, password string) (*http.Response, error) {
postUrl := url.URL{Path: "https://identitysso-cert.betfair.com/api/certlogin"}
q := postUrl.Query()
q.Set("username", username)
q.Set("password", password)
postUrl.RawQuery = q.Encode()
req, _ := http.NewRequest("POST", postUrl.RequestURI(), nil)
req.SetBasicAuth(username, password)
req.Header.Add("X-Application", client.ApplicationName)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client.HttpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: client.Tls,
},
}
resp, err := client.HttpClient.Do(req)
if err != nil {
client.HttpClient = nil
return resp, err
}
json := SessionResponse{}
if err := ReadJson(resp, &json); err != nil {
client.HttpClient = nil
return resp, err
}
client.SessionToken = json.SessionToken
return resp, nil
}
func (client *Client) Logout() (*http.Response, error) {
postUrl := url.URL{Path: "https://identitysso.betfair.com/api/logout"}
req, _ := http.NewRequest("POST", postUrl.RequestURI(), nil)
resp, err := client.Do(req)
if err != nil {
return resp, err
}
json := SessionStatusResponse{}
if err := ReadJson(resp, &json); err != nil {
return resp, err
}
if json.Error != "" {
return resp, errors.New(string(json.Error))
}
client.HttpClient = nil
client.SessionToken = ""
return resp, nil
}
func (client *Client) GetStream(sc *StreamingClient) error {
if client.HttpClient == nil {
return errors.New("client not initialised: please resume or create a new session")
}
return sc.Authenticate(client.Tls, client.ApplicationKey, client.SessionToken)
}
const (
api_account = "account"
api_betting = "betting"
api_heartbeat = "heartbeat"
api_scores = "scores"
)
func (client *Client) GetAccounts(method string, params any, response any) error {
return client.get(api_account, method, params, response)
}
func (client *Client) GetSports(method string, params any, response any) error {
return client.get(api_betting, method, params, response)
}
func (client *Client) GetHeartbeats(method string, params any, response any) error {
return client.get(api_heartbeat, method, params, response)
}
func (client *Client) GetScores(method string, params any, response any) error {
return client.getRPC(api_scores, method, params, response) //Only supported by RPC for now.
}
func (client *Client) get(api string, method string, params any, response any) error {
if client.Rest {
return client.getRest(api, method, params, response)
} else {
return client.getRPC(api, method, params, response)
}
}
type JsonAPINGExceptionErrorCode string
const (
EC_UNEXPECTED_ERROR = "UNEXPECTED_ERROR"
EC_INVALID_INPUT_DATA = "INVALID_INPUT_DATA"
EC_INVALID_SESSION_INFORMATION = "INVALID_SESSION_INFORMATION"
EC_INVALID_APP_KEY = "INVALID_APP_KEY"
EC_SERVICE_BUSY = "SERVICE_BUSY"
EC_TIMEOUT_ERROR = "TIMEOUT_ERROR"
EC_NO_SESSION = "NO_SESSION"
EC_NO_APP_KEY = "NO_APP_KEY"
EC_TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS"
EC_SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
EC_REQUEST_SIZE_EXCEEDS_LIMIT = "REQUEST_SIZE_EXCEEDS_LIMIT"
EC_TOO_MUCH_DATA = "TOO_MUCH_DATA"
EC_ACCESS_DENIED = "ACCESS_DENIED"
)
type (
JsonRpcResponse struct {
JsonRPC string `json:"jsonrpc"`
Result any `json:"result"`
Error JsonError `json:"error,omitempty"`
ID int `json:"id"`
}
JsonError struct {
Code int `json:"code"`
Message string `json:"message"`
Data JsonData `json:"data"`
}
JsonData struct {
APINGException JsonAPINGException `json:"APINGException"`
ExceptionName string `json:"exceptionname"`
}
JsonAPINGException struct {
RequestUUID string `json:"requestUUID"`
ErrorCode JsonAPINGExceptionErrorCode `json:"errorCode"`
ErrorDetails string `json:"errorDetails"`
}
JsonRPC struct {
JsonRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params any `json:"params"`
ID int `json:"id"`
}
)
var apis = map[string]string{
api_account: "AccountAPING",
api_betting: "SportsAPING",
api_heartbeat: "HeartbeatAPING",
api_scores: "ScoresAPING",
}
func (client *Client) getRPC(api string, method string, params any, response any) error {
query := JsonRPC{
JsonRPC: "2.0",
Method: fmt.Sprintf("%v/v1.0/%v", apis[api], method),
Params: params,
ID: int(rand.Uint64()),
}
body, err := json.Marshal(&query)
if err != nil {
return err
}
apiUrl := fmt.Sprintf("https://api.betfair.com/exchange/%v/json-rpc/v1/", api)
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(body))
if err != nil {
return err
}
res, err := client.Do(req)
if err != nil {
return err
}
jsonRpc := JsonRpcResponse{}
if err = ReadJson(res, &jsonRpc); err != nil {
return err
}
if jsonError, errorCode := jsonRpc.Error, jsonRpc.Error.Code; errorCode < 0 {
ex := jsonError.Data.APINGException
return fmt.Errorf("%v -> %v: %v (%v)", jsonRpc.ID, jsonError.Code, jsonError.Message, ex.ErrorCode)
}
if m, err := json.Marshal(jsonRpc.Result); err == nil {
return json.Unmarshal(m, &response)
}
return nil
}
type JsonRestErrorResponse struct {
FaultCode string `json:"faultcode"`
FaultString string `json:"faultstring"`
Detail struct {
} `json:"detail"`
}
func (client *Client) getRest(api string, method string, params any, response any) error {
body, err := json.Marshal(¶ms)
if err != nil {
return err
}
apiUrl := fmt.Sprintf("https://api.betfair.com/exchange/%v/rest/v1.0/%v/", api, method)
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(body))
if err != nil {
return err
}
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
jsonRestError := JsonRestErrorResponse{}
if err = ReadJson(res, &jsonRestError); err != nil {
return err
}
return fmt.Errorf("%v: %v", jsonRestError.FaultCode, jsonRestError.FaultString)
}
if err = ReadJson(res, &response); err != nil {
return err
}
return nil
}