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
|
#[macro_use]
extern crate log;
use reqwest::{Client, Identity};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
mod generated_api;
mod json_rpc;
use crate::json_rpc::{RpcRequest, RpcResponse};
#[derive(Debug)]
pub enum AnyError {
Io(std::io::Error),
Reqwest(reqwest::Error),
SerdeJson(serde_json::Error),
BFLoginFailure(String),
General(String),
Other,
}
type Result<T> = std::result::Result<T, AnyError>;
impl From<std::io::Error> for AnyError {
fn from(e: std::io::Error) -> Self {
AnyError::Io(e)
}
}
impl From<reqwest::Error> for AnyError {
fn from(e: reqwest::Error) -> Self {
AnyError::Reqwest(e)
}
}
impl From<serde_json::Error> for AnyError {
fn from(e: serde_json::Error) -> Self {
AnyError::SerdeJson(e)
}
}
#[derive(Debug, Serialize)]
struct LoginRequestForm {
username: String,
password: String,
}
#[derive(Debug, Deserialize)]
#[allow(non_snake_case)]
struct LoginResponse {
sessionToken: Option<String>,
loginStatus: String, // TODO enum this
}
pub struct BFCredentials {
username: String,
password: String,
pfx: Vec<u8>,
app_key: String,
}
impl BFCredentials {
fn new(
username: String,
password: String,
pfx_path: String,
app_key: String,
) -> Result<Self> {
let pfx = std::fs::read(pfx_path)?;
Ok(BFCredentials {
username,
password,
pfx,
app_key,
})
}
fn as_login_request_form(&self) -> LoginRequestForm {
LoginRequestForm {
username: self.username.clone(),
password: self.password.clone(),
}
}
fn pfx(&self) -> &Vec<u8> {
&self.pfx
}
fn app_key(&self) -> &String {
&self.app_key
}
}
pub struct BFClient {
client: reqwest::Client,
session_token: Arc<RwLock<Option<String>>>,
creds: BFCredentials,
proxy_uri: Option<String>,
}
impl BFClient {
pub fn new(
creds: BFCredentials,
proxy_uri: Option<String>,
) -> Result<Self> {
let client: reqwest::Client = match &proxy_uri {
Some(uri) => {
let proxy = reqwest::Proxy::all(uri)?;
Client::builder().proxy(proxy).build()?
}
None => reqwest::Client::new(),
};
Ok(BFClient {
client,
session_token: Arc::new(RwLock::new(None)),
creds,
proxy_uri,
})
}
// TODO keepalive
// https://identitysso.betfair.com/api/keepAliveo
// Accept (mandatory)
// Header that signals that the response should be returned as JSON application/json
// X-Authentication (mandatory)
// Header that represents the session token that needs to be keep alive Session Token
// X-Application (optional)
// Header the Application Key used by the customer to identify the product. App Key
// Response structure
//
//
// {
// "token":"<token_passed_as_header>",
// "product":"product_passed_as_header",
// "status":"<status>",
// "error":"<error>"
// }
// Status values
//
//
// SUCCESS
// FAIL
// Error values
//
//
// INPUT_VALIDATION_ERROR
// INTERNAL_ERROR
// NO_SESSION
// general notes
// We would therefore recommend that all Betfair API request are sent with the ‘Accept-Encoding: gzip, deflate’ request header.
// We recommend that Connection: keep-alive header is set for all requests to guarantee a persistent connection and therefore reducing latency. Please note: Idle keep-alive connection to the API endpoints are closed every 3 minutes.
// You should ensure that you handle the INVALID_SESSION_TOKEN error within your code by creating a new session token via the API login method.
fn req_internal<T1: Serialize, T2: DeserializeOwned>(
&self,
maybe_token: &Option<String>,
rpc_request: &RpcRequest<T1>,
) -> Result<RpcResponse<T2>> {
match maybe_token {
None => Err(AnyError::General(
"req_internal: must login first".to_owned(),
)),
Some(token) => {
const JSONRPC_URI: &str =
"https://api.betfair.com/exchange/betting/json-rpc/v1";
Ok(self
.client
.post(JSONRPC_URI)
.header("X-Application", self.creds.app_key())
.header("X-Authentication", token)
.json(&rpc_request)
.send()?
.json()
.unwrap())
}
}
}
/// Perform a request, logging in if necessary, fail if login
pub fn req<T1: Serialize, T2: DeserializeOwned>(
&self,
req: RpcRequest<T1>,
) -> Result<RpcResponse<T2>> {
// Initially acquire the token via a read lock
trace!("Taking token read lock");
let token_lock = self.session_token.read().unwrap();
let mut token = token_lock.clone();
drop(token_lock);
trace!("Dropped token read lock");
loop {
// TODO: exponential backoff
info!("Performing a request");
match self.req_internal(&token, &req) {
Ok(resp) => return Ok(resp),
Err(_) => {
info!("Not logged in");
// Assume the only error possible is an auth error
trace!("Taking token write lock");
let mut token_lock = self.session_token.write().unwrap();
if *token_lock == token {
*token_lock = Some(self.login()?);
}
token = token_lock.clone();
drop(token_lock); // drops at end of scope but we log
trace!("Dropped token read lock");
}
}
}
}
fn login(&self) -> Result<String> {
const CERTLOGIN_URI: &str =
"https://identitysso-cert.betfair.com/api/certlogin";
let ident =
Identity::from_pkcs12_der(self.creds.pfx().as_slice(), "")?;
let client: reqwest::Client = match &(self.proxy_uri) {
Some(uri) => {
let proxy = reqwest::Proxy::all(uri)?;
Client::builder().identity(ident).proxy(proxy).build()?
}
None => Client::builder().identity(ident).build()?,
};
let login_request_form = self.creds.as_login_request_form();
info!("LoginRequest ...");
let login_response: LoginResponse = client
.post(CERTLOGIN_URI)
.header(
"X-Application",
format!("schroedinger_{}", rand::random::<u128>()),
)
.form(&login_request_form)
.send()?
.json()?;
info!("LoginResponse: {:?}", login_response.loginStatus);
match login_response.sessionToken {
Some(token) => Ok(token),
None => Err(AnyError::BFLoginFailure(format!(
"loginStatus: {}",
login_response.loginStatus
))),
}
}
}
use generated_api::*;
fn main() -> Result<()> {
env_logger::Builder::from_default_env()
.target(env_logger::Target::Stderr)
.init();
const USER_PATH: &str = "/home/esotericnonsense/betfair/betfair-user";
const PASS_PATH: &str = "/home/esotericnonsense/betfair/betfair-pass";
const PFX_PATH: &str = "/home/esotericnonsense/betfair/identity.pfx";
const APPKEY_PATH: &str = "/home/esotericnonsense/betfair/betfair-app-key";
const PROXY_URI: &str = "socks5h://127.0.0.1:40001";
let username = std::fs::read_to_string(USER_PATH)?.replace("\n", "");
let password = std::fs::read_to_string(PASS_PATH)?.replace("\n", "");
let app_key = std::fs::read_to_string(APPKEY_PATH)?.replace("\n", "");
let bf_creds =
BFCredentials::new(username, password, PFX_PATH.to_owned(), app_key)?;
let bf_client = BFClient::new(bf_creds, Some(PROXY_URI.to_owned()))?;
info!("Created client!");
let catalogues: Vec<MarketCatalogue> = bf_client.listMarketCatalogue(
MarketFilter::default(),
None,
None,
10,
None,
)?;
// for catalogue in catalogues.iter() {
// println!(
// "{} {} {:?}",
// catalogue.marketId, catalogue.marketName, catalogue.totalMatched
// );
// }
let market_ids: Vec<MarketId> = catalogues
.iter()
.map(|x: &MarketCatalogue| x.marketId.clone())
.collect();
let books: Vec<MarketBook> = bf_client.listMarketBook(
market_ids, None, None, None, None, None, None, None, None, None, None,
)?;
// println!("{:?}", books);
let s: String = serde_json::to_string(&books).expect("whatever");
println!("{}", s);
Ok(())
}
|