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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
extern crate hyper;
extern crate itertools;
extern crate num_rational;
extern crate ratelimit_meter;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
pub mod dto;
mod queue_type;
use itertools::Itertools;
use num_rational::Ratio;
pub use queue_type::QueueType;
use ratelimit_meter::{Decider, Decision, GCRA};
use reqwest::StatusCode;
use reqwest::header::{Formatter, Header, Raw, RetryAfter};
use serde::de;
use std::fmt::{self, Display};
use std::str;
use std::sync::Mutex;
use std::thread;
use std::time::{Duration, Instant};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Region {
	NA1,
}
impl Region {
	fn to_str(self) -> &'static str {
		match self {
			Region::NA1 => "na1",
		}
	}
}

pub struct LolApiClient<K> {
	region: &'static str,
	key: K,
	app_limit: Mutex<Option<GCRA>>,
	get_champion_masteries_limit: Mutex<Option<GCRA>>,
	get_champion_mastery_limit: Mutex<Option<GCRA>>,
	get_champion_mastery_score: Mutex<Option<GCRA>>,
	get_champions_limit: Mutex<Option<GCRA>>,
	get_champion_limit: Mutex<Option<GCRA>>,
	get_challenger_league_limit: Mutex<Option<GCRA>>,
	get_summoner_leagues_limit: Mutex<Option<GCRA>>,
	get_master_league_limit: Mutex<Option<GCRA>>,
	get_summoner_positions_limit: Mutex<Option<GCRA>>,
}
impl<K: Display> LolApiClient<K> {
	pub fn new(region: Region, key: K) -> Self {
		Self {
			region: region.to_str(),
			key: key,
			app_limit: Mutex::default(),
			get_champion_masteries_limit: Mutex::default(),
			get_champion_mastery_limit: Mutex::default(),
			get_champion_mastery_score: Mutex::default(),
			get_champions_limit: Mutex::default(),
			get_champion_limit: Mutex::default(),
			get_challenger_league_limit: Mutex::default(),
			get_summoner_leagues_limit: Mutex::default(),
			get_master_league_limit: Mutex::default(),
			get_summoner_positions_limit: Mutex::default(),
		}
	}

	/// "Get all champion mastery entries sorted by number of champion points descending."
	///
	/// **Endpoint**: `/lol/champion-mastery/v3/champion-masteries/by-summoner/{summoner_id}`
	pub fn get_champion_masteries(&self, summoner_id: i64) -> Result<Vec<dto::ChampionMastery>, StatusCode> {
		let path =
			format!("/lol/champion-mastery/v3/champion-masteries/by-summoner/{summoner_id}", summoner_id = summoner_id);
		self.request(&path, &self.get_champion_masteries_limit)
	}

	/// "Get a champion mastery by player ID and champion ID."
	///
	/// **Endpoint**: `/lol/champion-mastery/v3/champion-masteries/by-summoner/{summoner_id}/by-champion/{champion_id}`
	pub fn get_champion_mastery(&self, summoner_id: i64, champion_id: i64) -> Result<dto::ChampionMastery, StatusCode> {
		let path = format!(
			"/lol/champion-mastery/v3/champion-masteries/by-summoner/{summoner_id}/by-champion/{champion_id}",
			summoner_id = summoner_id,
			champion_id = champion_id
		);
		self.request(&path, &self.get_champion_mastery_limit)
	}

	/// "Get a player's total champion mastery score, which is the sum of individual champion mastery levels."
	///
	/// **Endpoint**: `/lol/champion-mastery/v3/scores/by-summoner/{summoner_id}`
	pub fn get_champion_mastery_score(&self, summoner_id: i64) -> Result<i32, StatusCode> {
		let path = format!("/lol/champion-mastery/v3/scores/by-summoner/{summoner_id}", summoner_id = summoner_id);
		self.request(&path, &self.get_champion_mastery_score)
	}

	/// "Retrieve all champions."
	///
	/// **Endpoint**: `/lol/platform/v3/champions`
	pub fn get_champions(&self) -> Result<Vec<dto::Champion>, StatusCode> {
		let path = "/lol/platform/v3/champions";
		self.request::<dto::ChampionList>(path, &self.get_champions_limit).map(|x| x.champions)
	}

	/// "Retrieve champion by ID."
	///
	/// **Endpoint**: `/lol/platform/v3/champions/{id}`
	pub fn get_champion(&self, id: i64) -> Result<dto::Champion, StatusCode> {
		let path = format!("/lol/platform/v3/champions/{id}", id = id);
		self.request(&path, &self.get_champion_limit)
	}

	/// "Get the challenger league for a given queue."
	///
	/// **Endpoint**: `/lol/league/v3/challengerleagues/by-queue/{queue}`
	pub fn get_challenger_league(&self, queue: QueueType) -> Result<dto::LeagueList, StatusCode> {
		let path = format!("/lol/league/v3/challengerleagues/by-queue/{queue}", queue = queue.to_str());
		self.request(&path, &self.get_challenger_league_limit)
	}

	/// "Get leagues in all queues for a given summoner ID."
	///
	/// **Endpoint**: `/lol/league/v3/leagues/by-summoner/{summonerId}`
	pub fn get_summoner_leagues(&self, summoner_id: i64) -> Result<Vec<dto::LeagueList>, StatusCode> {
		let path = format!("/lol/league/v3/leagues/by-summoner/{summoner_id}", summoner_id = summoner_id);
		self.request(&path, &self.get_summoner_leagues_limit)
	}

	/// "Get the master league for a given queue."
	///
	/// **Endpoint**: `/lol/league/v3/masterleagues/by-queue/{queue}`
	pub fn get_master_league(&self, queue: QueueType) -> Result<dto::LeagueList, StatusCode> {
		let path = format!("/lol/league/v3/masterleagues/by-queue/{queue}", queue = queue.to_str());
		self.request(&path, &self.get_master_league_limit)
	}

	/// "Get leagues in all queues for a given summoner ID."
	///
	/// **Endpoint**: `/lol/league/v3/leagues/by-summoner/{summonerId}`
	pub fn get_summoner_positions(&self, summoner_id: i64) -> Result<Vec<dto::LeaguePosition>, StatusCode> {
		let path = format!("/lol/league/v3/leagues/by-summoner/{summoner_id}", summoner_id = summoner_id);
		self.request(&path, &self.get_summoner_positions_limit)
	}

	fn request<T: de::DeserializeOwned>(
		&self,
		route: &str,
		method_mutex: &Mutex<Option<GCRA>>,
	) -> Result<T, StatusCode> {
		wait(&mut self.app_limit.lock().unwrap());
		wait(&mut method_mutex.lock().unwrap());

		loop {
			let mut response = reqwest::get(&format!(
				"https://{region}.api.riotgames.com{route}?api_key={key}",
				region = self.region,
				route = route,
				key = self.key
			)).unwrap();

			match response.status() {
				StatusCode::TooManyRequests => {
					let mut app_limit_lock = self.app_limit.lock().unwrap();
					let mut method_limit_lock = method_mutex.lock().unwrap();

					let app_limit = response.headers().get::<XAppRateLimit>();
					let app_limit_count = response.headers().get::<XAppRateLimitCount>();
					match (app_limit, app_limit_count) {
						(Some(&XAppRateLimit { ref limits }), Some(&XAppRateLimitCount { ref limit_counts })) => {
							*app_limit_lock = Some(headers_to_gcra(limits, limit_counts));
						},
						_ => (),
					}

					let method_limit = response.headers().get::<XMethodRateLimit>();
					let method_limit_count = response.headers().get::<XMethodRateLimitCount>();
					match (method_limit, method_limit_count) {
						(Some(&XMethodRateLimit { ref limits }), Some(&XMethodRateLimitCount { ref limit_counts })) => {
							*method_limit_lock = Some(headers_to_gcra(&limits, &limit_counts));
						},
						_ => (),
					}

					match response.headers().get::<RetryAfter>() {
						Some(&RetryAfter::Delay(duration)) => thread::sleep(duration),
						Some(_) => unreachable!(),
						None => thread::sleep(Duration::from_secs(1)),
					}
				},
				StatusCode::Ok => return Ok(response.json().unwrap()),
				status => return Err(status),
			}
		}
	}
}
unsafe impl<K> Send for LolApiClient<K> {}
unsafe impl<K> Sync for LolApiClient<K> {}

fn wait(gcra: &mut Option<GCRA>) {
	if let Some(ref mut gcra) = *gcra {
		while let Decision::No(time) = gcra.check().unwrap() {
			thread::sleep(time.duration_since(Instant::now()));
		}
	}
}

fn headers_to_gcra(limits: &[(u64, std::time::Duration)], limit_counts: &[(u64, std::time::Duration)]) -> GCRA {
	let rate = limits
		.iter()
		.zip(limit_counts.into_iter())
		.map(|(l, lc)| {
			assert!(l.1 == lc.1);
			Ratio::new(l.0, l.1.as_secs())
		})
		.min()
		.unwrap();

	GCRA::for_capacity((*rate.numer()) as u32).unwrap().per(Duration::from_secs(*rate.denom())).build()
}

#[derive(Clone)]
struct XAppRateLimit {
	limits: Vec<(u64, Duration)>,
}
impl Header for XAppRateLimit {
	fn header_name() -> &'static str {
		"X-App-Rate-Limit"
	}

	fn parse_header(raw: &Raw) -> Result<Self, hyper::Error> {
		let limits = str::from_utf8(raw.one().unwrap())
			.unwrap()
			.split(',')
			.map(|limit| {
				let mut nums = limit.split(':').map(|x| x.parse::<u64>().unwrap());
				(nums.next().unwrap(), Duration::from_secs(nums.next().unwrap()))
			})
			.collect();

		Ok(Self { limits: limits })
	}

	fn fmt_header(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
		f.fmt_line(&self.limits.iter().map(|&(count, duration)| format!("{}:{}", count, duration.as_secs())).join(","))
	}
}

#[derive(Clone)]
struct XAppRateLimitCount {
	limit_counts: Vec<(u64, Duration)>,
}
impl Header for XAppRateLimitCount {
	fn header_name() -> &'static str {
		"X-App-Rate-Limit-Count"
	}

	fn parse_header(raw: &Raw) -> Result<Self, hyper::Error> {
		let limit_counts = str::from_utf8(raw.one().unwrap())
			.unwrap()
			.split(',')
			.map(|limit| {
				let mut nums = limit.split(':').map(|x| x.parse::<u64>().unwrap());
				(nums.next().unwrap(), Duration::from_secs(nums.next().unwrap()))
			})
			.collect();

		Ok(Self { limit_counts: limit_counts })
	}

	fn fmt_header(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
		f.fmt_line(
			&self.limit_counts.iter().map(|&(count, duration)| format!("{}:{}", count, duration.as_secs())).join(","),
		)
	}
}

#[derive(Clone)]
struct XMethodRateLimit {
	limits: Vec<(u64, Duration)>,
}
impl Header for XMethodRateLimit {
	fn header_name() -> &'static str {
		"X-Method-Rate-Limit"
	}

	fn parse_header(raw: &Raw) -> Result<Self, hyper::Error> {
		let limits = str::from_utf8(raw.one().unwrap())
			.unwrap()
			.split(',')
			.map(|limit| {
				let mut nums = limit.split(':').map(|x| x.parse::<u64>().unwrap());
				(nums.next().unwrap(), Duration::from_secs(nums.next().unwrap()))
			})
			.collect();

		Ok(Self { limits: limits })
	}

	fn fmt_header(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
		f.fmt_line(&self.limits.iter().map(|&(count, duration)| format!("{}:{}", count, duration.as_secs())).join(","))
	}
}

#[derive(Clone)]
struct XMethodRateLimitCount {
	limit_counts: Vec<(u64, Duration)>,
}
impl Header for XMethodRateLimitCount {
	fn header_name() -> &'static str {
		"X-Method-Rate-Limit-Count"
	}

	fn parse_header(raw: &Raw) -> Result<Self, hyper::Error> {
		let limit_counts = str::from_utf8(raw.one().unwrap())
			.unwrap()
			.split(',')
			.map(|limit| {
				let mut nums = limit.split(':').map(|x| x.parse::<u64>().unwrap());
				(nums.next().unwrap(), Duration::from_secs(nums.next().unwrap()))
			})
			.collect();

		Ok(Self { limit_counts: limit_counts })
	}

	fn fmt_header(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
		f.fmt_line(
			&self.limit_counts.iter().map(|&(count, duration)| format!("{}:{}", count, duration.as_secs())).join(","),
		)
	}
}

#[cfg(test)]
#[macro_use]
extern crate lazy_static;

#[cfg(test)]
mod tests {
	lazy_static! {
		static ref CLIENT: ::LolApiClient<&'static str> = ::LolApiClient::new(::Region::NA1, env!("LOL_API_KEY"));
	}

	#[test]
	fn get_champion_masteries() {
		CLIENT.get_champion_masteries(24338059).unwrap();
	}

	#[test]
	fn get_champion_mastery() {
		CLIENT.get_champion_mastery(24338059, 266).unwrap();
	}

	#[test]
	fn get_champion_mastery_score() {
		CLIENT.get_champion_mastery_score(24338059).unwrap();
	}

	#[test]
	fn get_champions() {
		CLIENT.get_champions().unwrap();
	}

	#[test]
	fn get_champion() {
		CLIENT.get_champion(266).unwrap();
	}

	#[test]
	fn get_challenger_league() {
		CLIENT.get_challenger_league(::QueueType::RankedSolo5x5).unwrap();
	}

	#[test]
	fn get_summoner_leagues() {
		CLIENT.get_summoner_leagues(24338059).unwrap();
	}

	#[test]
	fn get_master_league() {
		CLIENT.get_master_league(::QueueType::RankedSolo5x5).unwrap();
	}

	#[test]
	fn get_summoner_positions() {
		CLIENT.get_summoner_positions(24338059).unwrap();
	}
}