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
//! # brawlhalla - An async Brawlhalla API Wrapper using tokio
//! With this crate, you can now conveniently call [the official Brawlhalla API](https://dev.brawlhalla.com) from Rust!
//! At this point in time, this crate has 100% API coverage, but no additional functionality.
//!
//! # Creating an API Connector
//! To call the API, you must first create an `APIConnection`. To do so, you should use a ConnectionBuilder.
//! A typical API call would look like this:
//! ```
//! extern crate brawlhalla;
//! use brawlhalla::ConnectionBuilder;
//! #[tokio::main]
//! async fn main() -> Result<(), brawlhalla::APIError> {
//!     let conn = ConnectionBuilder::default() // Make a builder struct
//!         .with_apikey("your personal API key") // Configure your API key
//!         .build(); // Create an APIConnection from the template
//!
//!     let legends = conn.legends().await?; // Retrieves data about all legends
//!     println!("{}", legends[0].bio_aka());
//!     Ok(())
//! }
//! ```
//!
//! At this time, the API can only be called via async/tokio.
#[macro_use]
extern crate shorthand;

mod apistructs;
use apistructs::result::APIResult;
pub use apistructs::*;

macro_rules! apicall {
    ($c:expr, $s:expr,$($args:expr),*) => {
        match Ok($c
            .get(
                format!(
                    $s,
                    $($args),+,
                )
                .as_str(),
            )
            .send()
            .await?
            .json()
            .await?) {
            Ok(v) => match v {
                APIResult::Ok(r) => Ok(r),
                APIResult::Err(e) => Err(APIError::CallingError(e)),
            },
            Err(e) => Err(APIError::ReqwestError(e)),
        }
    };
}

/// Builder struct for an APIConnection.
///
/// You would use it like this:
/// ```
/// extern crate brawlhalla;
/// use brawlhalla::ConnectionBuilder;
///
/// #[tokio::main]
/// async fn main() -> Result<(), brawlhalla::APIError> {
///     let steamid: u64 = 42069;
///     ConnectionBuilder::default()
///     .with_apikey("your_apikey")
///     .build()
///     .search_by_steam_id(steamid)
///     .await?;
///     println!("{}", steamid);
///     Ok(())
/// }
/// ```
///
pub struct ConnectionBuilder<'a> {
    apikey: &'a str,
    apiurl: &'a str,
}

impl<'a> ConnectionBuilder<'a> {
    /// Configures an API Key for your builder
    pub fn with_apikey(mut self, apikey: &'a str) -> Self {
        self.apikey = apikey;
        self
    }

    /// Configures the API URL for the builder. You will probably never need this function.
    pub fn with_apiurl(mut self, apiurl: &'a str) -> Self {
        self.apiurl = apiurl;
        self
    }

    /// Builds an APIConnection struct from your builder.
    pub fn build(self) -> APIConnection {
        APIConnection::new(self.apikey, self.apiurl)
    }

    /// This constructor is probably not what you want, use `ConnectionBuilder::default()` instead.
    /// Creates a builder struct with a custom API URL. This allows you to call any API that works like [the official Brawlhalla API](https://dev.brawlhalla.com).
    pub fn new(apikey: &'a str, apiurl: &'a str) -> Self {
        Self { apikey, apiurl }
    }
}

impl<'a> Default for ConnectionBuilder<'a> {
    /// The default constructor for the builder. This is probably the constructor you want to use.
    fn default() -> Self {
        Self {
            apikey: "",
            apiurl: "https://api.brawlhalla.com",
        }
    }
}

/// The actual API handler struct which is created from a [ConnectionBuilder](struct.ConnectionBuilder.html).
///
/// This struct handles all the API calling. You can construct it with a Builder struct, which you can get
/// either from a [ConnectionBuilder](struct.ConnectionBuilder.html) or the `.builder()` method.
pub struct APIConnection {
    client: reqwest::Client,
    apikey: String,
    apiurl: String,
}

impl APIConnection {
    fn new(apikey: &str, apiurl: &str) -> Self {
        Self {
            client: reqwest::Client::new(),
            apikey: apikey.to_owned(),
            apiurl: apiurl.to_owned(),
        }
    }

    /// Returns a builder for an APIConnection. This just calls `ConnectionBuilder::default()`.
    pub fn builder<'a>() -> ConnectionBuilder<'a> {
        ConnectionBuilder::default()
    }

    /// Searches a Brawlhalla player by their steam64 id.
    pub async fn search_by_steam_id(
        &self,
        steamid: u64,
    ) -> Result<apistructs::SearchResult, APIError> {
        apicall!(
            self.client,
            "{}/search?steamid={}&api_key={}",
            &self.apiurl,
            steamid,
            &self.apikey
        )
    }

    /// Retrieves a specific page of ranked player stats. One page contains 50 entries.
    /// Warning: Indexing starts at 1 here!
    pub async fn rankings(
        &self,
        bracket: &str,
        region: &str,
        page: u64,
    ) -> Result<Vec<apistructs::rankings::Rankings>, APIError> {
        apicall!(
            self.client,
            "{}/rankings/{}/{}/{}?api_key={}",
            &self.apiurl,
            bracket,
            region,
            page,
            &self.apikey
        )
    }

    /// Searches a player by their name and returns ranked data for every possible match.
    pub async fn rankings_search(
        &self,
        bracket: &str,
        region: &str,
        name: &str,
    ) -> Result<Vec<apistructs::Rankings>, APIError> {
        apicall!(
            self.client,
            "{}/rankings/{}/{}/1?name={}&api_key={}",
            &self.apiurl,
            bracket,
            region,
            name,
            &self.apikey
        )
    }

    /// Retrieves information about the player with the specified Brawlhalla ID.
    pub async fn player_stats(&self, brawlhalla_id: u64) -> Result<apistructs::Player, APIError> {
        apicall!(
            self.client,
            "{}/player/{}/stats?api_key={}",
            &self.apiurl,
            brawlhalla_id,
            &self.apikey
        )
    }

    /// Retrieves ranked stats about the player with the specified Brawlhalla ID.
    pub async fn ranked_stats(
        &self,
        brawlhalla_id: u64,
    ) -> Result<apistructs::RankedStats, APIError> {
        apicall!(
            self.client,
            "{}/player/{}/ranked?api_key={}",
            &self.apiurl,
            brawlhalla_id,
            &self.apikey
        )
    }

    /// Retrieves clan stats about the clan with the specified clan ID.
    pub async fn claninfo(&self, clan_id: u64) -> Result<apistructs::Clan, APIError> {
        apicall!(
            self.client,
            "{}/clan/{}?api_key={}",
            &self.apiurl,
            clan_id,
            &self.apikey
        )
    }

    /// Retrieves miscellanous data about all legends, such as legend ID, bio, name etc.
    pub async fn legends(&self) -> Result<Vec<apistructs::SmallLegend>, APIError> {
        apicall!(
            self.client,
            "{}/legend/all?api_key={}",
            &self.apiurl,
            &self.apikey
        )
    }

    /// Retrieves extensive data about a single legend specified by their legend ID.
    pub async fn legendinfo(&self, legendid: u64) -> Result<apistructs::FullLegend, APIError> {
        apicall!(
            self.client,
            "{}/legend/{}?api_key={}",
            &self.apiurl,
            legendid,
            &self.apikey
        )
    }
}