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
extern crate reqwest;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate serde_json;
use reqwest::{Client, Method, StatusCode};
use reqwest::header::{Accept, Authorization, UserAgent};
use std::collections::BTreeMap;
use std::io::Read;
const API_URL: &str = "https://api.rocketleaguestats.com/v1";
#[derive(Debug)]
pub enum Error {
RateLimited,
ResponseCode(ResponseCode),
ReqwestError(reqwest::Error),
SerdeJson(serde_json::error::Error),
}
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Self {
Error::ReqwestError(err)
}
}
#[derive(Debug, Deserialize)]
pub struct ResponseCode {
pub code: i32,
pub message: String,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Platform {
pub id: i32,
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct Season {
#[serde(rename = "seasonId")]
pub season_id: i64,
#[serde(rename = "startedOn")]
pub started_on: i64,
#[serde(rename = "endedOn")]
pub ended_on: Option<i64>,
}
#[derive(Debug, Deserialize)]
pub struct Population {
pub players: i32,
#[serde(rename = "updatedAt")]
pub updated_at: i64,
}
#[derive(Debug, Deserialize)]
pub struct Playlist {
pub id: i32,
#[serde(rename = "platformId")]
pub platform_id: i32,
pub name: String,
pub population: Population,
}
#[derive(Debug, Deserialize)]
pub struct Tier {
#[serde(rename = "tierId")]
pub id: i32,
#[serde(rename = "tierName")]
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct Stats {
pub wins: i32,
pub goals: i32,
pub mvps: i32,
pub saves: i32,
pub shots: i32,
pub assists: i32,
}
#[derive(Debug, Deserialize)]
pub struct RankedData {
#[serde(rename = "rankPoints")]
pub rank_points: Option<i32>,
#[serde(rename = "matchesPlayed")]
pub matches_played: Option<i32>,
pub tier: Option<i32>,
pub division: Option<i32>,
}
#[derive(Debug, Deserialize)]
pub struct Player {
#[serde(rename = "uniqueId")]
pub unique_id: String,
#[serde(rename = "displayName")]
pub display_name: String,
pub platform: Platform,
pub avatar: Option<String>,
#[serde(rename = "profileUrl")]
pub profile_url: String,
#[serde(rename = "signatureUrl")]
pub signature_url: String,
pub stats: Stats,
#[serde(rename = "rankedSeasons")]
pub ranked_seasons: BTreeMap<String, BTreeMap<String, RankedData>>,
#[serde(rename = "lastRequested")]
pub last_requested: i64,
#[serde(rename = "createdAt")]
pub created_at: i64,
#[serde(rename = "updatedAt")]
pub updated_at: i64,
#[serde(rename = "nextUpdateAt")]
pub next_update_at: i64,
}
#[derive(Debug, Deserialize)]
pub struct SearchResponse {
pub page: Option<i32>,
pub results: i32,
#[serde(rename = "totalResults")]
pub total_results: i32,
#[serde(rename = "maxResultsPerPage")]
pub max_results_per_page: i32,
pub data: Vec<Player>,
}
#[derive(Debug, Serialize)]
pub struct BatchPlayer {
#[serde(rename = "uniqueId")]
pub id: String,
#[serde(rename = "platformId")]
pub platform_id: i32,
}
pub struct RlStats {
client: Client,
api_key: String,
}
impl RlStats {
pub fn new<K>(api_key: K) -> Result<Self, Error>
where K: Into<String>
{
Ok(Self {
client: Client::new()?,
api_key: api_key.into(),
})
}
pub fn get_platforms(&self) -> Result<Vec<Platform>, Error> {
self.get("/data/platforms")
}
pub fn get_seasons(&self) -> Result<Vec<Season>, Error> {
self.get("/data/seasons")
}
pub fn get_playlists(&self) -> Result<Vec<Playlist>, Error> {
self.get("/data/playlists")
}
pub fn get_tiers(&self) -> Result<Vec<Tier>, Error> {
self.get("/data/tiers")
}
pub fn get_player(&self, unique_id: &str, platform_id: i32) -> Result<Player, Error> {
self.get(&format!("/player?unique_id={}&platform_id={}", unique_id, platform_id))
}
pub fn search_players(&self, display_name: &str, page: u32) -> Result<SearchResponse, Error> {
self.get(&format!("/search/players?display_name={}&page={}", display_name, page))
}
pub fn batch_players(&self, players: Vec<BatchPlayer>) -> Result<Vec<Player>, Error> {
self.request("/player/batch", reqwest::Method::Post, &players)
}
pub fn get_ranked_leaderboard(&self, playlist_id: i32) -> Result<Vec<Player>, Error> {
self.get(&format!("/leaderboard/ranked?playlist_id={}", playlist_id))
}
pub fn get_stat_leaderboard(&self, ty: &str) -> Result<Vec<Player>, Error> {
self.get(&format!("/leaderboard/stat?type={}", ty))
}
fn get<T>(&self, endpoint: &str) -> Result<T, Error>
where T: serde::de::DeserializeOwned
{
self.request(endpoint, Method::Get, ())
}
fn request<T, J>(&self, endpoint: &str, method: reqwest::Method, j: J) -> Result<T, Error>
where T: serde::de::DeserializeOwned,
J: serde::Serialize
{
let user_agent = format!("{} (v {})", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
self.client.request(method, &format!("{}{}", API_URL, endpoint))?
.header(Authorization(self.api_key.clone()))
.header(Accept::json())
.header(UserAgent::new(user_agent))
.json(&j)?
.send()
.map_err(Error::ReqwestError)
.and_then(|mut resp| match resp.status() {
StatusCode::TooManyRequests => Err(Error::RateLimited),
_ => {
let mut content = String::new();
resp.read_to_string(&mut content).unwrap();
serde_json::from_str::<T>(&content)
.or_else(|_| serde_json::from_str::<ResponseCode>(&content)
.map_err(Error::SerdeJson)
.and_then(|r| Err(Error::ResponseCode(r))))
}
})
}
}