scpsl-api 0.1.0-alpha.10

A SCP: Secret Laboratory API wrapper
Documentation
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! This module contains structs and functions these can be used
//! for working with the `serverinfo` API request.
//! # Examples
//! ```
//! use scpsl_api::server_info::{get, RequestParameters, Response};
//! use std::env::var;
//! use url::Url;
//!
//! #[tokio::main]
//! async fn main() {
//!     let account_id = var("ACCOUNT_ID")
//!         .expect("Expected an account id in the environment")
//!         .parse::<u64>()
//!         .unwrap();
//!     let api_key = var("API_KEY").expect("Expected an account id in the environment");
//!
//!     let parameters = RequestParameters::builder()
//!         .url(Url::parse("https://api.scpslgame.com/serverinfo.php").unwrap())
//!         .id(account_id)
//!         .key(api_key)
//!         .players(true)
//!         .build();
//!
//!     if let Response::Success(response) = get(&parameters).await.unwrap() {
//!         println!(
//!             "Total players on your servers: {}",
//!             response
//!                 .servers()
//!                 .iter()
//!                 .map(|server| server.players_count().unwrap().current_players())
//!                 .sum::<u32>()
//!         )
//!     }
//! }
//! ```

#[cfg(not(feature = "raw"))]
mod raw;
#[cfg(feature = "raw")]
pub mod raw;

use chrono::{Date, NaiveDate, Utc};
use raw::*;
use reqwest::Error;
use url::Url;

/// An enum representing a parsed API response for the `serverinfo` request.
pub enum Response {
    /// Successful response.
    Success(SuccessResponse),
    /// Unsuccessful response.
    Error(ErrorResponse),
}

impl From<RawResponse> for Response {
    fn from(raw: RawResponse) -> Self {
        if let Some(error) = raw.error {
            Self::Error(ErrorResponse { error })
        } else {
            Self::Success(SuccessResponse {
                cooldown: raw.cooldown.unwrap(),
                servers: raw
                    .servers
                    .unwrap()
                    .into_iter()
                    .map(ServerInfo::from)
                    .collect(),
            })
        }
    }
}

/// A struct representing a successful API response for the `serverinfo` request.
#[derive(Clone, Default)]
pub struct SuccessResponse {
    cooldown: u64,
    servers: Vec<ServerInfo>,
}

impl SuccessResponse {
    /// Get a reference to the success response's cooldown.
    pub fn cooldown(&self) -> u64 {
        self.cooldown
    }

    /// Get a reference to the success response's servers.
    pub fn servers(&self) -> &[ServerInfo] {
        self.servers.as_slice()
    }

    /// Get a mutable reference to the success response's cooldown.
    pub fn cooldown_mut(&mut self) -> &mut u64 {
        &mut self.cooldown
    }

    /// Get a mutable reference to the success response's servers.
    pub fn servers_mut(&mut self) -> &mut Vec<ServerInfo> {
        &mut self.servers
    }
}

/// A struct representing an unsuccessful API response for the `serverinfo` request.
#[derive(Clone, Default)]
pub struct ErrorResponse {
    error: String,
}

impl ErrorResponse {
    /// Get a reference to the error response's error.
    pub fn error(&self) -> &str {
        self.error.as_str()
    }

    /// Get a mutable reference to the error response's error.
    pub fn error_mut(&mut self) -> &mut String {
        &mut self.error
    }
}

/// A struct representing a server info for the `serverinfo` request.
#[derive(Clone, Default)]
pub struct ServerInfo {
    id: u64,
    port: u16,
    last_online: Option<Date<Utc>>,
    players_count: Option<PlayersCount>,
    players: Option<Vec<Player>>,
    info: Option<String>,
    friendly_fire: Option<bool>,
    whitelist: Option<bool>,
    modded: Option<bool>,
    mods: Option<u64>,
    suppress: Option<bool>,
    auto_suppress: Option<bool>,
}

impl ServerInfo {
    /// Get a reference to the server info's id.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Get a reference to the server info's port.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Get a reference to the server info's last online.
    pub fn last_online(&self) -> Option<Date<Utc>> {
        self.last_online
    }

    /// Get a reference to the server info's players count.
    pub fn players_count(&self) -> Option<&PlayersCount> {
        self.players_count.as_ref()
    }

    /// Get a reference to the server info's players.
    pub fn players(&self) -> Option<&Vec<Player>> {
        self.players.as_ref()
    }

    /// Get a reference to the server info's info.
    pub fn info(&self) -> Option<&String> {
        self.info.as_ref()
    }

    /// Get a reference to the server info's friendly fire.
    pub fn friendly_fire(&self) -> Option<bool> {
        self.friendly_fire
    }

    /// Get a reference to the server info's whitelist.
    pub fn whitelist(&self) -> Option<bool> {
        self.whitelist
    }

    /// Get a reference to the server info's modded.
    pub fn modded(&self) -> Option<bool> {
        self.modded
    }

    /// Get a reference to the server info's mods.
    pub fn mods(&self) -> Option<u64> {
        self.mods
    }

    /// Get a reference to the server info's suppress.
    pub fn suppress(&self) -> Option<bool> {
        self.suppress
    }

    /// Get a reference to the server info's auto suppress.
    pub fn auto_suppress(&self) -> Option<bool> {
        self.auto_suppress
    }

    /// Get a mutable reference to the server info's id.
    pub fn id_mut(&mut self) -> &mut u64 {
        &mut self.id
    }

    /// Get a mutable reference to the server info's port.
    pub fn port_mut(&mut self) -> &mut u16 {
        &mut self.port
    }

    /// Get a mutable reference to the server info's last online.
    pub fn last_online_mut(&mut self) -> &mut Option<Date<Utc>> {
        &mut self.last_online
    }

    /// Get a mutable reference to the server info's players count.
    pub fn players_count_mut(&mut self) -> &mut Option<PlayersCount> {
        &mut self.players_count
    }

    /// Get a mutable reference to the server info's players.
    pub fn players_mut(&mut self) -> &mut Option<Vec<Player>> {
        &mut self.players
    }

    /// Get a mutable reference to the server info's info.
    pub fn info_mut(&mut self) -> &mut Option<String> {
        &mut self.info
    }

    /// Get a mutable reference to the server info's friendly fire.
    pub fn friendly_fire_mut(&mut self) -> &mut Option<bool> {
        &mut self.friendly_fire
    }

    /// Get a mutable reference to the server info's whitelist.
    pub fn whitelist_mut(&mut self) -> &mut Option<bool> {
        &mut self.whitelist
    }

    /// Get a mutable reference to the server info's modded.
    pub fn modded_mut(&mut self) -> &mut Option<bool> {
        &mut self.modded
    }

    /// Get a mutable reference to the server info's mods.
    pub fn mods_mut(&mut self) -> &mut Option<u64> {
        &mut self.mods
    }

    /// Get a mutable reference to the server info's suppress.
    pub fn suppress_mut(&mut self) -> &mut Option<bool> {
        &mut self.suppress
    }

    /// Get a mutable reference to the server info's auto suppress.
    pub fn auto_suppress_mut(&mut self) -> &mut Option<bool> {
        &mut self.auto_suppress
    }
}

impl From<RawServerInfo> for ServerInfo {
    fn from(raw: RawServerInfo) -> Self {
        Self {
            id: raw.id,
            port: raw.port,
            last_online: raw.last_online.map(|last_online| {
                Date::from_utc(
                    NaiveDate::parse_from_str(last_online.as_str(), "%Y-%m-%d").unwrap(),
                    Utc,
                )
            }),
            players_count: raw.players_count.map(|players_count| {
                let mut splitted = players_count.split('/');
                PlayersCount {
                    current_players: splitted.next().unwrap().parse().unwrap(),
                    max_players: splitted.next().unwrap().parse().unwrap(),
                }
            }),
            players: raw
                .players
                .map(|players| players.into_iter().map(Player::from).collect()),
            info: raw.info.map(|info| {
                std::str::from_utf8(base64::decode(info).unwrap().as_slice())
                    .unwrap()
                    .to_string()
            }),
            friendly_fire: raw.friendly_fire,
            whitelist: raw.whitelist,
            modded: raw.modded,
            mods: raw.mods,
            suppress: raw.suppress,
            auto_suppress: raw.auto_suppress,
        }
    }
}

/// A struct representing the server's players count.
#[derive(Clone, Default)]
pub struct PlayersCount {
    max_players: u32,
    current_players: u32,
}

impl PlayersCount {
    /// Get a reference to the players count's max players.
    pub fn max_players(&self) -> u32 {
        self.max_players
    }

    /// Get a reference to the players count's current players.
    pub fn current_players(&self) -> u32 {
        self.current_players
    }

    /// Get a mutable reference to the players count's max players.
    pub fn max_players_mut(&mut self) -> &mut u32 {
        &mut self.max_players
    }

    /// Get a mutable reference to the players count's current players.
    pub fn current_players_mut(&mut self) -> &mut u32 {
        &mut self.current_players
    }
}

/// A struct representing a player on the server.
#[derive(Clone, Default)]
pub struct Player {
    id: String,
    nickname: Option<String>,
}

impl Player {
    /// Get a reference to the player's id.
    pub fn id(&self) -> &str {
        self.id.as_str()
    }

    /// Get a reference to the player's nickname.
    pub fn nickname(&self) -> Option<&String> {
        self.nickname.as_ref()
    }
}

impl From<RawPlayer> for Player {
    fn from(raw: RawPlayer) -> Self {
        match raw {
            RawPlayer::UserId(id) => Self { id, nickname: None },
            RawPlayer::UserIdWithNickname { id, nickname } => Self { id, nickname },
        }
    }
}

/// A struct representing a parameters for the `serverinfo` request.
pub struct RequestParameters {
    url: Url,
    id: Option<u64>,
    key: Option<String>,
    last_online: bool,
    players: bool,
    list: bool,
    info: bool,
    pastebin: bool,
    version: bool,
    flags: bool,
    nicknames: bool,
    online: bool,
}

impl RequestParameters {
    /// Returns a new instance of the [`RequestParametersBuilder`].
    pub fn builder() -> RequestParametersBuilder {
        RequestParametersBuilder::new()
    }
}

/// A struct representing a builder for the [`RequestParameters`].
#[derive(Default)]
pub struct RequestParametersBuilder {
    url: Option<Url>,
    id: Option<u64>,
    key: Option<String>,
    last_online: bool,
    players: bool,
    list: bool,
    info: bool,
    pastebin: bool,
    version: bool,
    flags: bool,
    nicknames: bool,
    online: bool,
}

impl RequestParametersBuilder {
    /// Returns a new instance of the [`RequestParametersBuilder`].
    pub fn new() -> Self {
        Default::default()
    }

    /// Consumes the [`RequestParametersBuilder`] instance and returns an instance of the [`RequestParameters`].
    /// # Panics
    /// Panics if `self.url` is [`None`].
    pub fn build(self) -> RequestParameters {
        RequestParameters {
            url: self.url.unwrap(),
            id: self.id,
            key: self.key,
            last_online: self.last_online,
            players: self.players,
            list: self.list,
            info: self.info,
            pastebin: self.pastebin,
            version: self.version,
            flags: self.flags,
            nicknames: self.nicknames,
            online: self.online,
        }
    }

    /// Sets the url to be used.
    pub fn url(mut self, value: Url) -> Self {
        self.url = Some(value);
        self
    }

    /// Sets the `id` query parameter to be used.
    pub fn id(mut self, value: u64) -> Self {
        self.id = Some(value);
        self
    }

    /// Sets the `key` query parameter to be used.
    pub fn key(mut self, value: String) -> Self {
        self.key = Some(value);
        self
    }

    /// Sets the `lo` query parameter to be used.
    pub fn last_online(mut self, value: bool) -> Self {
        self.last_online = value;
        self
    }

    /// Sets the `players` query parameter to be used.
    pub fn players(mut self, value: bool) -> Self {
        self.players = value;
        self
    }

    /// Sets the `list` query parameter to be used.
    pub fn list(mut self, value: bool) -> Self {
        self.list = value;
        self
    }

    /// Sets the `info` query parameter to be used.
    pub fn info(mut self, value: bool) -> Self {
        self.info = value;
        self
    }

    /// Sets the `pastebin` query parameter to be used.
    pub fn pastebin(mut self, value: bool) -> Self {
        self.pastebin = value;
        self
    }

    /// Sets the `version` query parameter to be used.
    pub fn version(mut self, value: bool) -> Self {
        self.version = value;
        self
    }

    /// Sets the `flags` query parameter to be used.
    pub fn flags(mut self, value: bool) -> Self {
        self.flags = value;
        self
    }

    /// Sets the `nicknames` query parameter to be used.
    pub fn nicknames(mut self, value: bool) -> Self {
        self.nicknames = value;
        self
    }

    /// Sets the `online` query parameter to be used.
    pub fn online(mut self, value: bool) -> Self {
        self.online = value;
        self
    }
}

/// Returns info about own servers. See [official API reference](https://api.scpslgame.com/#/default/Get%20Server%20Info).
/// # Errors
/// Returns [`Error`] if there was an error in the [`reqwest`] crate.  
pub async fn get<'a>(parameters: &RequestParameters) -> Result<Response, Error> {
    raw::get(parameters).await.map(|response| response.into())
}