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
use crate::json_rpc::{RpcRequest, RpcResponse};
use crate::result::{Error, Result};
use reqwest::{Client, Identity};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
#[derive(Debug, Serialize)]
struct LoginRequestForm {
username: String,
password: String,
}
#[derive(Debug, Deserialize)]
#[allow(non_snake_case)]
struct LoginResponse {
sessionToken: Option<String>,
loginStatus: String,
}
pub struct BFCredentials {
username: String,
password: String,
pfx: Vec<u8>,
app_key: String,
}
impl BFCredentials {
pub 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,
})
}
fn req_internal<T1: Serialize, T2: DeserializeOwned>(
&self,
maybe_token: &Option<String>,
rpc_request: &RpcRequest<T1>,
) -> Result<RpcResponse<T2>> {
match maybe_token {
None => Err(Error::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())
}
}
}
pub(super) fn req<T1: Serialize, T2: DeserializeOwned>(
&self,
req: RpcRequest<T1>,
) -> Result<RpcResponse<T2>> {
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 {
info!("Performing a request");
match self.req_internal(&token, &req) {
Ok(resp) => return Ok(resp),
Err(_) => {
info!("Not logged in");
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);
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(Error::BFLoginFailure(format!(
"loginStatus: {}",
login_response.loginStatus
))),
}
}
}