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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
//! Contains models for the `/rankings/:country_code/players?limit=x` Brawl Stars API endpoint. //! Included by the feature `"rankings"`; removing that feature will disable the usage of this module. use serde::{self, Serialize, Deserialize}; use crate::traits::{PropLimRouteable, PropLimFetchable}; use crate::serde::{one_default, oxffffff_default, deserialize_number_from_string}; use std::ops::{Deref, DerefMut}; use crate::util::fetch_route; use crate::error::Result; #[cfg(feature = "async")] use async_trait::async_trait; #[cfg(feature = "async")] use crate::util::a_fetch_route; use crate::http::Client; use crate::http::routes::Route; /// Represents a leaderboard of [`PlayerRanking`]s - the top x players in a regional or global /// leaderboard, sorted by total trophies. /// /// **NOTE:** The API only allows fetching up to the top 200 players. /// /// [`PlayerRanking`]: ./struct.PlayerRanking.html #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct PlayerLeaderboard { /// The players in the ranking. #[serde(default)] pub items: Vec<PlayerRanking>, } impl Deref for PlayerLeaderboard { type Target = Vec<PlayerRanking>; /// Obtain the players in the ranking - dereferencing returns the [`items`] field. /// /// # Examples /// /// ```rust,ignore /// use brawl_api::{Client, PlayerLeaderboard, traits::*}; /// /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth token"); /// let top50players = PlayerLeaderboard::fetch( /// &client, // <- the client containing the auth key /// "global", // <- the region of the leaderboard to fetch ("global" - world-wide) /// 50 // <- limit of rankings to fetch (i.e. top 50) /// )?; /// /// assert_eq!(top50players.items, *top50players); /// /// # Ok(()) /// # } /// /// ``` /// /// [`items`]: #structfield.items fn deref(&self) -> &Vec<PlayerRanking> { &self.items } } impl DerefMut for PlayerLeaderboard { /// Obtain the players in the ranking - dereferencing returns the [`items`] field. /// /// # Examples /// /// ```rust,ignore /// use brawl_api::{Client, PlayerLeaderboard, traits::*}; /// /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth token"); /// let top50players = PlayerLeaderboard::fetch( /// &client, // <- the client containing the auth key /// "global", // <- the region of the leaderboard to fetch ("global" - world-wide) /// 50 // <- limit of rankings to fetch (i.e. top 50) /// )?; /// /// assert_eq!(top50players.items, *top50players); /// /// # Ok(()) /// # } /// /// ``` /// /// [`items`]: #structfield.items fn deref_mut(&mut self) -> &mut Vec<PlayerRanking> { &mut self.items } } #[cfg_attr(feature = "async", async_trait)] impl PropLimFetchable for PlayerLeaderboard { type Property = str; type Limit = u8; /// (Sync) Fetches the top `limit` players in the regional (two-letter) `country_code` /// leaderboard (or global leaderboard, if `country_code == "global"`). /// /// # Errors /// /// This function may error: /// - While requesting (will return an [`Error::Request`]); /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]); /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]); /// - While parsing incoming JSON (will return an [`Error::Json`]). /// /// (All of those, of course, wrapped inside an `Err`.) /// /// # Examples /// /// World-wide player leaderboard: /// ```rust,ignore /// use brawl_api::{PlayerLeaderboard, Client, traits::PropLimFetchable}; /// /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth key"); /// /// // if the fetch is successful, then the variable below will have the global top 100 players /// // in the 'items' field (i.e. '*top100players'). /// let top100players: PlayerLeaderboard = PlayerLeaderboard::fetch(&client, "global", 100)?; /// /// // get player ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2 /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort() /// let player1 = &top100players[0]; /// /// assert_eq!(player1.rank, 1); /// /// # Ok(()) /// # } /// ``` /// /// Regional (in this case, zimbabwean) player leaderboard: /// ```rust,ignore /// use brawl_api::{PlayerLeaderboard, Client, traits::PropLimFetchable}; /// /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth key"); /// /// // if the fetch is successful, then the variable below will have the top 100 zimbabwean /// // players in the 'items' field (i.e. '*top100zwplayers'). /// let top100zwplayers: PlayerLeaderboard = PlayerLeaderboard::fetch(&client, "ZW", 100)?; /// /// // get player ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2 /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort() /// let player1 = &top100zwplayers[0]; /// /// assert_eq!(player1.rank, 1); /// /// # Ok(()) /// # } /// ``` /// /// [`Error::Request`]: error/enum.Error.html#variant.Request /// [`Error::Status`]: error/enum.Error.html#variant.Status /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited /// [`Error::Json`]: error/enum.Error.html#variant.Json fn fetch(client: &Client, country_code: &str, limit: u8) -> Result<PlayerLeaderboard> { let route = PlayerLeaderboard::get_route(country_code, limit); fetch_route::<PlayerLeaderboard>(client, &route) } /// (Async) Fetches the top `limit` players in the regional (two-letter) `country_code` /// leaderboard (or global leaderboard, if `country_code == "global"`). /// /// # Errors /// /// This function may error: /// - While requesting (will return an [`Error::Request`]); /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]); /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]); /// - While parsing incoming JSON (will return an [`Error::Json`]). /// /// (All of those, of course, wrapped inside an `Err`.) /// /// # Examples /// /// World-wide player leaderboard: /// ```rust,ignore /// use brawl_api::{PlayerLeaderboard, Client, traits::PropLimFetchable}; /// /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth key"); /// /// // if the fetch is successful, then the variable below will have the global top 100 players /// // in the 'items' field (i.e. '*top100players'). /// let top100players: PlayerLeaderboard = PlayerLeaderboard::a_fetch(&client, "global", 100).await?; /// /// // get player ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2 /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort() /// let player1 = &top100players[0]; /// /// assert_eq!(player1.rank, 1); /// /// # Ok(()) /// # } /// ``` /// /// Regional (in this case, zimbabwean) player leaderboard: /// ```rust,ignore /// use brawl_api::{PlayerLeaderboard, Client, traits::PropLimFetchable}; /// /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> { /// let client = Client::new("my auth key"); /// /// // if the fetch is successful, then the variable below will have the top 100 zimbabwean /// // players in the 'items' field (i.e. '*top100zwplayers'). /// let top100zwplayers: PlayerLeaderboard = PlayerLeaderboard::a_fetch(&client, "ZW", 100).await?; /// /// // get player ranked #1. The items are usually sorted (i.e. rank 1 on index [0], rank 2 /// // on index [1] etc.), but, to make the program absolutely safe, might want to .sort() /// let player1 = &top100zwplayers[0]; /// /// assert_eq!(player1.rank, 1); /// /// # Ok(()) /// # } /// ``` /// /// [`Error::Request`]: error/enum.Error.html#variant.Request /// [`Error::Status`]: error/enum.Error.html#variant.Status /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited /// [`Error::Json`]: error/enum.Error.html#variant.Json #[cfg(feature="async")] async fn a_fetch( client: &Client, country_code: &'async_trait str, limit: u8 ) -> Result<PlayerLeaderboard> where Self: 'async_trait, Self::Property: 'async_trait, { let route = PlayerLeaderboard::get_route(&country_code, limit); a_fetch_route::<PlayerLeaderboard>(client, &route).await } } impl PropLimRouteable for PlayerLeaderboard { type Property = str; type Limit = u8; /// Get the route for fetching the top `limit` players in the regional `country_code` /// leaderboard (or global, if `country_code == "global"`). fn get_route(country_code: &str, limit: u8) -> Route { Route::PlayerRankings { country_code: country_code.to_owned(), limit } } } /// Represents a player's ranking, based on a regional or global leaderboard. /// To obtain the player's full data (a [`Player`] instance), see [`Player::fetch_from`]. /// /// [`Player`]: ../players/player/struct.Player.html /// [`Player::fetch_from`]: ../players/player/struct.Player.html#method.fetch_from #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlayerRanking { /// The club the player is in - at the moment, only its name is available for this data model. /// To convert to a full [`Club`] object, see the [`PlayerRankingClub`] docs. /// /// [`Player`]: ../../players/struct.Player.html /// [`Player::fetch_from`]: ../../players/struct.Player.html#method.fetch_from #[serde(default)] pub club: PlayerRankingClub, /// The player's tag. #[serde(default)] pub tag: String, /// The player's name. #[serde(default)] pub name: String, /// The player's trophies. #[serde(default)] pub trophies: usize, /// The player's rank in the leaderboard. #[serde(default = "one_default")] pub rank: u8, /// The player's name color. Defaults to `0xffffff` (white). #[serde(default = "oxffffff_default")] #[serde(deserialize_with = "deserialize_number_from_string")] pub name_color: u64, } /// Represents the club in a player's ranking (a [`PlayerRanking`] object). Since the only data /// available at the moment is its name, it cannot be converted into a full [`Club`] object /// using a convenient method. For that, one must have the original `PlayerRanking` object, /// then convert it into a [`Player`] with [`Player::fetch_from`]. /// /// [`PlayerRanking`]: ./struct.PlayerRanking.html /// [`Player`]: ../../players/player/struct.Player.html /// [`Player::fetch_from`]: ../../players/player/struct.Player.html#method.fetch_from #[non_exhaustive] #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct PlayerRankingClub { /// The club's name. #[serde(default)] pub name: String, } impl PlayerRankingClub { /// Creates a new `PlayerRankingClub` instance with the given name. pub fn new(name: &str) -> PlayerRankingClub { PlayerRankingClub { name: name.to_owned() } } } impl Default for PlayerRankingClub { /// Returns an instance of `PlayerRankingClub` with initial values (empty name). /// /// # Examples /// /// ```rust /// use brawl_api::model::PlayerRankingClub; /// /// assert_eq!( /// PlayerRankingClub::default(), /// PlayerRankingClub::new("") /// ); /// ``` fn default() -> PlayerRankingClub { PlayerRankingClub { name: String::from(""), } } } /////////////////////////////////// tests /////////////////////////////////// #[cfg(test)] mod tests { use serde_json; use super::{PlayerLeaderboard, PlayerRanking, PlayerRankingClub}; use crate::error::Error; /// Tests for PlayerLeaderboard deserialization from API-provided JSON. #[test] fn rankings_players_deser() -> Result<(), Box<dyn ::std::error::Error>> { let rp_json_s = r##"{ "items": [ { "tag": "#AAAAAAAAA", "name": "Player", "nameColor": "0xfff05637", "trophies": 30000, "rank": 1, "club": { "name": "Scary Club" } }, { "tag": "#EEEEEEE", "name": "Also Player", "nameColor": "0xffa2e3fe", "trophies": 25000, "rank": 2, "club": { "name": "Another Club" } }, { "tag": "#QQQQQQQ", "name": "Youtuber", "nameColor": "0xfff05637", "trophies": 23000, "rank": 3, "club": { "name": "Different Club" } }, { "tag": "#55555553Q", "name": "Not a valid player", "nameColor": "0xfff9cf08", "trophies": 20000, "rank": 4, "club": { "name": "Different Club" } } ], "paging": { "cursors": {} } }"##; let p_leaders = serde_json::from_str::<PlayerLeaderboard>(rp_json_s) .map_err(Error::Json)?; assert_eq!( p_leaders, PlayerLeaderboard { items: vec![ PlayerRanking { tag: String::from("#AAAAAAAAA"), name: String::from("Player"), name_color: 0xfff05637, trophies: 30000, rank: 1, club: PlayerRankingClub { name: String::from("Scary Club") } }, PlayerRanking { tag: String::from("#EEEEEEE"), name: String::from("Also Player"), name_color: 0xffa2e3fe, trophies: 25000, rank: 2, club: PlayerRankingClub { name: String::from("Another Club") } }, PlayerRanking { tag: String::from("#QQQQQQQ"), name: String::from("Youtuber"), name_color: 0xfff05637, trophies: 23000, rank: 3, club: PlayerRankingClub { name: String::from("Different Club") } }, PlayerRanking { tag: String::from("#55555553Q"), name: String::from("Not a valid player"), name_color: 0xfff9cf08, trophies: 20000, rank: 4, club: PlayerRankingClub { name: String::from("Different Club") } } ] } ); Ok(()) } }