use crate::api;
use crate::model::{Abilities, ActivePlayer, AllGameData, Events, FullRunes, GameData, Player};
use reqwest::{Certificate, IntoUrl};
use serde::Deserialize;
use thiserror::Error;
pub struct GameClient {
client: reqwest::Client,
}
#[cold]
pub fn get_riot_root_certificate() -> Certificate {
Certificate::from_pem(include_bytes!("riotgames.cer")).unwrap()
}
#[derive(Debug, Error)]
pub enum QueryError {
#[error("Failed to query the API. Is the game running ? '{}'", _0)]
Reqwest(#[from] reqwest::Error), }
impl Default for GameClient {
fn default() -> Self {
Self::new()
}
}
impl GameClient {
pub fn new() -> Self {
GameClient::_from_certificate(get_riot_root_certificate()).unwrap()
}
pub fn _from_certificate(certificate: Certificate) -> Result<Self, QueryError> {
Ok(GameClient {
client: reqwest::ClientBuilder::new()
.add_root_certificate(certificate)
.build()?,
})
}
async fn get_data<T: for<'de> Deserialize<'de>, U: IntoUrl>(
&self,
endpoint: U,
) -> Result<T, QueryError> {
let data = self.client.get(endpoint).send().await?.json::<T>().await?;
Ok(data)
}
}
impl GameClient {
pub async fn all_game_data(&self) -> Result<AllGameData, QueryError> {
self.get_data(api!("allgamedata")).await
}
pub async fn active_player(&self) -> Result<ActivePlayer, QueryError> {
self.get_data(api!("activeplayer")).await
}
pub async fn active_player_name(&self) -> Result<String, QueryError> {
self.get_data(api!("activeplayername")).await
}
pub async fn active_player_abilities(&self) -> Result<Abilities, QueryError> {
self.get_data(api!("activeplayerabilities")).await
}
pub async fn active_player_runes(&self) -> Result<FullRunes, QueryError> {
self.get_data(api!("activeplayerrunes")).await
}
pub async fn player_list(&self) -> Result<Vec<Player>, QueryError> {
self.get_data(api!("playerlist")).await
}
pub async fn event_data(&self) -> Result<Events, QueryError> {
self.get_data(api!("eventdata")).await
}
pub async fn game_stats(&self) -> Result<GameData, QueryError> {
self.get_data(api!("gamestats")).await
}
}
#[macro_export]
macro_rules! api {
($endpoint:expr) => {
concat!("https://127.0.0.1:2999/liveclientdata/", $endpoint)
};
}