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
//! Simple crate to interact with the Steam API

#![deny(clippy::pedantic)]

pub mod functions;
pub mod structs;

use anyhow::Result;
use log::info;
use reqwest::{blocking, Error};
use structs::{bans, friends, level, profile, summaries};

/// Calls the `GetSteamLevel` API
///
/// # Returns
/// Returns an [`anyhow::Result`] containing [`structs::level::Response`] and an [`anyhow::Error`]
///
/// # Arguments
/// * `steamids` - A string that contains a single Steam ID
/// * `api_key` - A string slice containing the API Key to use with the API.
///
/// # Errors
/// * [`reqwest::blocking::get`]
///
/// # Examples
/// Single Steam ID
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamid: &str = "76561198421169032";
///
/// let user = steam_api::get_steam_level(&steamid, &api_key)?;
///
/// match user.response.player_level {
///     Some(x) => println!("Player level\t{}", x),
///     None => println!("The profile is private or has not set up a community profile yet"),
/// }
///
/// # assert_eq!(user.response.player_level.unwrap_or_default(), 321);
/// # Ok(())
/// # }
/// ```
///
/// Multiple Steam ID's
/// `GetSteamLevel` does **NOT** support multiple steamids, blame Valve.
pub fn get_steam_level(steamids: &str, api_key: &str) -> Result<level::Response, Error> {
    info!("Calling GetSteamLevel on steamid: {}", &steamids);
    blocking::get(functions::manage_api_url("GetSteamLevel", &steamids, &api_key).as_str())?.json()
}

/// Calls the `GetPlayerSummaries` API
///
/// # Returns
/// Returns an [`anyhow::Result`] containing [`structs::summaries::Response`] and [`anyhow::Error`]
///
/// # Arguments
/// * `steamids` - A string that contains either a single Steam ID or a comma separated string of
/// Steam IDs
/// * `api_key` - A string slice containing the API Key to use with the API.
///
/// # Errors
/// * [`reqwest::blocking::get`]
///
/// # Examples
/// Single Steam ID
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamid: &str = "76561198421169032";
///
/// let user = steam_api::get_player_summaries(&steamid, &api_key)?;
///
/// println!("Steam ID\t{:?}", user.response.players[0].steamid);
/// println!("Persona Name\t{:?}", user.response.players[0].personaname);
///
/// assert_eq!(user.response.players[0].personaname, "dind");
/// assert_eq!(user.response.players[0].profileurl, "https://steamcommunity.com/id/ageofconsent/");
/// # Ok(())
/// # }
/// ```
/// Multiple Steam ID's
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamids: &str = "76561198421169032, 76561198421169032";
///
/// let users = steam_api::get_player_summaries(&steamids, &api_key)?
///     .response
///     .players;
///
/// for i in users {
///     println!("Persona Name\t{}", i.personaname);
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_player_summaries(steamids: &str, api_key: &str) -> Result<summaries::Response, Error> {
    info!("Calling GetPlayerSummaries on steamids: {}", &steamids);
    blocking::get(functions::manage_api_url("GetPlayerSummaries", &steamids, &api_key).as_str())?
        .json()
}

/// Calls the `GetPlayerBans` API
///
/// # Returns
/// Returns an [`anyhow::Result`] containing [`structs::bans::Response`] and [`anyhow::Error`]
///
/// # Arguments
/// * `steamids` - A string that contains either a single Steam ID or a comma separated string of
/// Steam IDs
/// * `api_key` - A string slice containing the API Key to use with the API.
///
/// # Errors
/// * [`reqwest::blocking::get`]
///
/// # Examples
/// Single Steam ID
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamid: &str = "76561198421169032";
///
/// let user = steam_api::get_player_bans(&steamid, &api_key)?;
///
/// println!("{}", user.players[0].SteamId);
/// println!("{}", user.players[0].VACBanned);
///
/// assert_eq!(user.players[0].SteamId, "76561198421169032");
/// assert!(!user.players[0].VACBanned);
/// # Ok(())
/// # }
/// ```
/// Multiple Steam ID's
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamids: &str = "76561198421169032,76561198421169032";
///
/// let user = steam_api::get_player_bans(&steamids, &api_key)?;
///
/// for i in user.players {
///     println!("Steam ID\t{}", i.SteamId);
///     println!("VAC Banned\t{}", i.VACBanned);
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_player_bans(steamids: &str, api_key: &str) -> Result<bans::Response, Error> {
    info!("Calling GetPlayerBans on steamids: {}", &steamids);
    blocking::get(functions::manage_api_url("GetPlayerBans", &steamids, &api_key).as_str())?.json()
}

/// Calls the `GetFriendList` API
///
/// # Returns
/// Returns an [`anyhow::Result`] containing [`structs::friends::Response`] and [`anyhow::Error`]
///
/// # Arguments
/// * `steamids` - A string that contains a single Steam ID
/// * `api_key` - A string slice containing the API Key to use with the API.
///
/// # Errors
/// * [`reqwest::blocking::get`]
///
/// # Examples
/// Single Steam ID
/// ```
/// use std::env;
/// # fn main() -> anyhow::Result<()> {
/// let api_key = &env::var("API_KEY")?;
/// let steamid: &str = "76561198421169032";
///
/// let user = steam_api::get_friends_list(&steamid, &api_key)?;
///
/// for i in user.friendslist.friends {
///     println!("Steam ID\t{}", i.steamid);
///     println!("Friends since\t{}", i.friend_since);
/// }
/// # Ok(())
/// # }
/// ```
/// Multiple Steam ID's
///
/// `GetFriendList` does **NOT** support multiple steamids, blame Valve.
pub fn get_friends_list(steamids: &str, api_key: &str) -> Result<friends::Response, Error> {
    info!("Calling GetFriendList on steamid: {}", &steamids);
    blocking::get(functions::manage_api_url("GetFriendList", &steamids, &api_key).as_str())?.json()
}

/// Calls all the APIs builds the [`structs::profile::Users`] struct
///
/// # Returns
/// Returns an `anyhow::Result` containing [`structs::profile::Users`] and [`anyhow::Error`]
///
/// # Arguments
/// * `steamids` - A Vector of `str`s
/// * `api_key` - A string slice containing the API Key to use with the API.
///
/// # Errors
/// * [`get_friends_list`]
/// * [`get_player_bans`]
/// * [`get_player_summaries`]
/// * [`get_steam_level`]
///
/// # Examples
/// Single Steam ID
/// ```
/// # fn main() -> anyhow::Result<()> {
/// use std::env;
/// let api_key = &env::var("API_KEY")?;
/// let steamids = vec![
///     "76561198421169032",
/// ];
///
/// let users = steam_api::handle_userinfo(&steamids, &api_key)?;
///
/// for user in users.user {
///     println!("Persona Name\t{}", user.personaname);
///     println!("Steam Level\t{}", user.player_level);
///     println!("Profile URL\t{}", user.profileurl);
/// }
/// # Ok(())
/// # }
/// ```
/// Multiple Steam ID's
/// ```
/// # fn main() -> anyhow::Result<()> {
/// use std::env;
/// let api_key = &env::var("API_KEY")?;
/// let steamids = vec![
///     "76561198421169032",
///     "76561198421169032",
///     "76561198421169032",
///     "76561198421169032",
/// ];
///
/// let users = steam_api::handle_userinfo(&steamids, &api_key)?;
///
/// for user in users.user {
///     println!("Persona Name\t{}", user.personaname);
///     println!("Steam Level\t{}", user.player_level);
///     println!("Profile URL\t{}", user.profileurl);
/// }
/// # Ok(())
/// # }
/// ```
pub fn handle_userinfo(steamids: &[&str], api_key: &str) -> Result<profile::Users, Error> {
    // Initialize users struct
    let mut users: profile::Users = profile::Users::default();

    // we store the raw responses here
    let mut summaries_raw: summaries::Response = summaries::Response::default();
    let mut bans_raw: bans::Response = bans::Response::default();

    if steamids.len() > 32 {
        info!("Steamids are >32, splitting them into multiple api calls");
        // split the vector into chunks of 32
        let split_vec: Vec<&[&str]> = steamids.chunks(32).collect();

        // iterate over the chunks
        for i in split_vec {
            // combine chunk into nice sendable string
            let steamids_string = i.join(",");

            // get ban chunk info and push to raw_data vector
            let bans = get_player_bans(&steamids_string, api_key)?.players;
            users.api_call_count += 1;
            for i in bans {
                bans_raw.players.push(i);
            }

            // get summaries chunk info and push to raw_data vector
            let summaries = get_player_summaries(&steamids_string, api_key)?
                .response
                .players;
            users.api_call_count += 1;

            for i in summaries {
                summaries_raw.response.players.push(i);
            }
        }
    } else {
        let steamids_string = steamids.join(",");
        let bans = get_player_bans(&steamids_string, api_key)?.players;
        users.api_call_count += 1;
        for i in bans {
            bans_raw.players.push(i);
        }

        // get summaries chunk info and push to raw_data vector
        let summaries = get_player_summaries(&steamids_string, api_key)?
            .response
            .players;
        users.api_call_count += 1;
        for i in summaries {
            summaries_raw.response.players.push(i);
        }
    }

    // sort the vectors
    bans_raw.players.sort_by(|a, b| b.SteamId.cmp(&a.SteamId));
    summaries_raw
        .response
        .players
        .sort_by(|a, b| b.steamid.cmp(&a.steamid));

    // Null values will be 0 or ""
    // iterate over GetPlayerSummaries response
    for (index, player) in summaries_raw.response.players.iter().enumerate() {
        let mut user = profile::User {
            steamid: player.steamid.clone(),
            communityvisibilitystate: player.communityvisibilitystate,
            profilestate: player.profilestate,
            personaname: player.personaname.clone(),
            commentpermissions: player.commentpermissions.unwrap_or(0),
            profileurl: player.profileurl.clone(),
            avatar: player.avatar.clone(),
            avatarmedium: player.avatarmedium.clone(),
            avatarfull: player.avatarfull.clone(),
            avatarhash: player.avatarhash.clone(),
            lastlogoff: player.lastlogoff.unwrap_or(0),
            personastate: player.personastate,
            realname: player.realname.clone().unwrap_or_default(),
            primaryclanid: player.primaryclanid.clone().unwrap_or_default(),
            timecreated: player.timecreated.unwrap_or(0),
            gameid: player.gameid.clone().unwrap_or_default(),
            gameserverip: player.gameserverip.clone().unwrap_or_default(),
            gameextrainfo: player.gameextrainfo.clone().unwrap_or_default(),
            loccountrycode: player.loccountrycode.clone().unwrap_or_default(),
            locstatecode: player.locstatecode.clone().unwrap_or_default(),
            loccityid: player.loccityid.unwrap_or(0),
            CommunityBanned: bans_raw.players[index].CommunityBanned,
            VACBanned: bans_raw.players[index].VACBanned,
            NumberOfVACBans: bans_raw.players[index].NumberOfVACBans,
            DaysSinceLastBan: bans_raw.players[index].DaysSinceLastBan,
            NumberOfGameBans: bans_raw.players[index].NumberOfGameBans,
            EconomyBan: bans_raw.players[index].EconomyBan.clone(),
            player_level: 0,
        };
        // If the profile is private, don't bother calling the api
        if user.communityvisibilitystate == 3 {
            user.player_level = get_steam_level(&player.steamid, api_key)?
                .response
                .player_level
                .unwrap_or(0);
            users.api_call_count += 1;
        } else {
            info!("{} is private, skipping GetSteamLevel", user.steamid);
        }
        users.user.push(user);
    }

    Ok(users)
}