rust-mc-status 2.0.0

High-performance asynchronous Rust library for querying Minecraft server status (Java & Bedrock)
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Data models for Minecraft server status responses.
//!
//! This module provides structured data types for representing server status
//! information from both Java Edition and Bedrock Edition servers.
//!
//! # Examples
//!
//! ## Basic Usage
//!
//! ```no_run
//! use rust_mc_status::{McClient, ServerEdition};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = McClient::new();
//! let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
//!
//! println!("Server: {}:{}", status.ip, status.port);
//! println!("Online: {}", status.online);
//! println!("Latency: {:.2}ms", status.latency);
//!
//! match status.data {
//!     rust_mc_status::ServerData::Java(java) => {
//!         println!("Players: {}/{}", java.players.online, java.players.max);
//!     }
//!     rust_mc_status::ServerData::Bedrock(bedrock) => {
//!         println!("Players: {}/{}", bedrock.online_players, bedrock.max_players);
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use std::fmt;
use std::fs::File;
use std::io::Write;

use base64::{engine::general_purpose, Engine as _};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::McError;

/// Server status information.
///
/// This structure contains all information about a Minecraft server's status.
/// Even if the server is offline, some fields may still be populated (e.g., DNS info).
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new();
/// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
///
/// println!("Hostname: {}", status.hostname);
/// println!("IP: {}", status.ip);
/// println!("Port: {}", status.port);
/// println!("Online: {}", status.online);
/// println!("Latency: {:.2}ms", status.latency);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ServerStatus {
    /// Whether the server is online and responding.
    ///
    /// This field is always `true` for successful pings. If the server
    /// is offline or unreachable, the `ping()` method returns an error instead.
    pub online: bool,

    /// Resolved IP address of the server.
    ///
    /// This is the actual IP address that was connected to, which may differ
    /// from the hostname if SRV records were used or if the hostname resolves
    /// to multiple IP addresses.
    ///
    /// Example: `"172.65.197.160"`
    pub ip: String,

    /// Port number of the server.
    ///
    /// This is the actual port that was connected to. For Java servers, this
    /// may differ from the default port (25565) if an SRV record was found.
    ///
    /// Example: `25565` (Java) or `19132` (Bedrock)
    pub port: u16,

    /// Original hostname used for the query.
    ///
    /// This is the hostname that was provided to the `ping()` method, before
    /// any DNS resolution or SRV lookup.
    ///
    /// Example: `"mc.hypixel.net"`
    pub hostname: String,

    /// Latency in milliseconds.
    ///
    /// This is the round-trip time (RTT) from sending the ping request to
    /// receiving the response. Lower values indicate better network connectivity.
    ///
    /// Example: `45.23` (45.23 milliseconds)
    pub latency: f64,

    /// Optional DNS information (A records, CNAME, TTL).
    ///
    /// This field contains DNS resolution details if available. It may be `None`
    /// if DNS information could not be retrieved or if an IP address was used
    /// directly instead of a hostname.
    pub dns: Option<DnsInfo>,

    /// Server data (Java or Bedrock specific information).
    ///
    /// This field contains edition-specific server information including version,
    /// players, plugins, mods, and more. Use pattern matching to access the data:
    ///
    /// ```no_run
    /// # use rust_mc_status::ServerData;
    /// # let data = ServerData::Java(rust_mc_status::JavaStatus {
    /// #     version: rust_mc_status::JavaVersion { name: "1.20.1".to_string(), protocol: 763 },
    /// #     players: rust_mc_status::JavaPlayers { online: 0, max: 100, sample: None },
    /// #     description: "".to_string(),
    /// #     favicon: None,
    /// #     map: None,
    /// #     gamemode: None,
    /// #     software: None,
    /// #     plugins: None,
    /// #     mods: None,
    /// #     raw_data: serde_json::Value::Null,
    /// # });
    /// match data {
    ///     ServerData::Java(java) => println!("Java server: {}", java.version.name),
    ///     ServerData::Bedrock(bedrock) => println!("Bedrock server: {}", bedrock.version),
    /// }
    /// ```
    pub data: ServerData,
}

impl ServerStatus {
    /// Get player count information.
    ///
    /// Returns a tuple of `(online, max)` players, or `None` if not available.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use rust_mc_status::{McClient, ServerEdition};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = McClient::new();
    /// # let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
    /// if let Some((online, max)) = status.players() {
    ///     println!("Players: {}/{}", online, max);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn players(&self) -> Option<(i64, i64)> {
        match &self.data {
            ServerData::Java(java) => Some((java.players.online, java.players.max)),
            ServerData::Bedrock(bedrock) => {
                let online = bedrock.online_players.parse().ok()?;
                let max = bedrock.max_players.parse().ok()?;
                Some((online, max))
            }
        }
    }
}

/// Server data (Java or Bedrock specific).
///
/// This enum contains edition-specific server information.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum ServerData {
    /// Java Edition server data.
    Java(JavaStatus),
    /// Bedrock Edition server data.
    Bedrock(BedrockStatus),
}

impl ServerData {
    /// Get player count if available.
    ///
    /// Returns `(online, max)` for Java servers, or parsed values for Bedrock servers.
    pub fn players(&self) -> Option<(i64, i64)> {
        match self {
            ServerData::Java(java) => Some((java.players.online, java.players.max)),
            ServerData::Bedrock(bedrock) => {
                let online = bedrock.online_players.parse().ok()?;
                let max = bedrock.max_players.parse().ok()?;
                Some((online, max))
            }
        }
    }
}

/// DNS information about the server.
///
/// Contains resolved A records, optional CNAME, and TTL information.
/// This information is retrieved during DNS resolution and cached for 5 minutes.
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new();
/// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
///
/// if let Some(dns) = status.dns {
///     println!("A records: {:?}", dns.a_records);
///     if let Some(cname) = dns.cname {
///         println!("CNAME: {}", cname);
///     }
///     println!("TTL: {} seconds", dns.ttl);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DnsInfo {
    /// A record IP addresses.
    ///
    /// This is a list of IPv4 and IPv6 addresses that the hostname resolves to.
    /// Typically contains one or more IP addresses.
    ///
    /// Example: `vec!["172.65.197.160".to_string()]`
    pub a_records: Vec<String>,

    /// Optional CNAME record.
    ///
    /// If the hostname is a CNAME (canonical name), this field contains the
    /// canonical hostname. Most servers don't use CNAME records.
    ///
    /// Example: `Some("canonical.example.com".to_string())`
    pub cname: Option<String>,

    /// Time-to-live in seconds.
    ///
    /// This is the DNS cache TTL used by the library. DNS records are cached
    /// for this duration to improve performance.
    ///
    /// Default: `300` (5 minutes)
    pub ttl: u32,
}

/// Java Edition server status.
///
/// Contains detailed information about a Java Edition server, including version,
/// players, plugins, mods, and more.
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new();
/// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
///
/// if let rust_mc_status::ServerData::Java(java) = status.data {
///     println!("Version: {}", java.version.name);
///     println!("Players: {}/{}", java.players.online, java.players.max);
///     println!("Description: {}", java.description);
///     
///     if let Some(plugins) = &java.plugins {
///         println!("Plugins: {}", plugins.len());
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Clone)]
pub struct JavaStatus {
    /// Server version information.
    pub version: JavaVersion,
    /// Player information.
    pub players: JavaPlayers,
    /// Server description (MOTD).
    pub description: String,
    /// Base64-encoded favicon (PNG image data).
    #[serde(skip_serializing)]
    pub favicon: Option<String>,
    /// Current map name.
    pub map: Option<String>,
    /// Game mode.
    pub gamemode: Option<String>,
    /// Server software (e.g., "Paper", "Spigot", "Vanilla").
    pub software: Option<String>,
    /// List of installed plugins.
    pub plugins: Option<Vec<JavaPlugin>>,
    /// List of installed mods.
    pub mods: Option<Vec<JavaMod>>,
    /// Raw JSON data from server response.
    #[serde(skip)]
    pub raw_data: Value,
}

impl JavaStatus {
    /// Save the server favicon to a file.
    ///
    /// The favicon is decoded from base64 and saved as a PNG image.
    ///
    /// # Arguments
    ///
    /// * `filename` - Path where the favicon should be saved
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No favicon is available
    /// - Base64 decoding fails
    /// - File I/O fails
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_mc_status::{McClient, ServerEdition};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = McClient::new();
    /// let status = client.ping("mc.hypixel.net", ServerEdition::Java).await?;
    ///
    /// if let rust_mc_status::ServerData::Java(java) = status.data {
    ///     java.save_favicon("server_icon.png")?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn save_favicon(&self, filename: &str) -> Result<(), McError> {
        if let Some(favicon) = &self.favicon {
            let data = favicon.split(',').nth(1).unwrap_or(favicon);
            let bytes = general_purpose::STANDARD
                .decode(data)
                .map_err(McError::Base64Error)?;

            let mut file = File::create(filename).map_err(McError::IoError)?;
            file.write_all(&bytes).map_err(McError::IoError)?;

            Ok(())
        } else {
            Err(McError::InvalidResponse("No favicon available".to_string()))
        }
    }
}

impl fmt::Debug for JavaStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JavaStatus")
            .field("version", &self.version)
            .field("players", &self.players)
            .field("description", &self.description)
            .field("map", &self.map)
            .field("gamemode", &self.gamemode)
            .field("software", &self.software)
            .field("plugins", &self.plugins.as_ref().map(|p| p.len()))
            .field("mods", &self.mods.as_ref().map(|m| m.len()))
            .field("favicon", &self.favicon.as_ref().map(|_| "[Favicon data]"))
            .field("raw_data", &"[Value]")
            .finish()
    }
}

/// Java Edition server version information.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JavaVersion {
    /// Version name (e.g., "1.20.1").
    pub name: String,
    /// Protocol version number.
    pub protocol: i64,
}

/// Java Edition player information.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JavaPlayers {
    /// Number of players currently online.
    pub online: i64,
    /// Maximum number of players.
    pub max: i64,
    /// Sample of online players (if provided by server).
    pub sample: Option<Vec<JavaPlayer>>,
}

/// Java Edition player sample.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JavaPlayer {
    /// Player name.
    pub name: String,
    /// Player UUID.
    pub id: String,
}

/// Java Edition plugin information.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JavaPlugin {
    /// Plugin name.
    pub name: String,
    /// Plugin version (if available).
    pub version: Option<String>,
}

/// Java Edition mod information.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JavaMod {
    /// Mod ID.
    pub modid: String,
    /// Mod version (if available).
    pub version: Option<String>,
}

/// Bedrock Edition server status.
///
/// Contains information about a Bedrock Edition server.
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new();
/// let status = client.ping("geo.hivebedrock.network:19132", ServerEdition::Bedrock).await?;
///
/// if let rust_mc_status::ServerData::Bedrock(bedrock) = status.data {
///     println!("Edition: {}", bedrock.edition);
///     println!("Version: {}", bedrock.version);
///     println!("Players: {}/{}", bedrock.online_players, bedrock.max_players);
///     println!("MOTD: {}", bedrock.motd);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Clone)]
pub struct BedrockStatus {
    /// Minecraft edition (e.g., "MCPE").
    pub edition: String,
    /// Message of the day.
    pub motd: String,
    /// Protocol version.
    pub protocol_version: String,
    /// Server version.
    pub version: String,
    /// Number of online players (as string).
    pub online_players: String,
    /// Maximum number of players (as string).
    pub max_players: String,
    /// Server UID.
    pub server_uid: String,
    /// Secondary MOTD.
    pub motd2: String,
    /// Game mode.
    pub game_mode: String,
    /// Game mode numeric value.
    pub game_mode_numeric: String,
    /// IPv4 port.
    pub port_ipv4: String,
    /// IPv6 port.
    pub port_ipv6: String,
    /// Current map name.
    pub map: Option<String>,
    /// Server software.
    pub software: Option<String>,
    /// Raw response data.
    pub raw_data: String,
}

impl fmt::Debug for BedrockStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BedrockStatus")
            .field("edition", &self.edition)
            .field("motd", &self.motd)
            .field("protocol_version", &self.protocol_version)
            .field("version", &self.version)
            .field("online_players", &self.online_players)
            .field("max_players", &self.max_players)
            .field("server_uid", &self.server_uid)
            .field("motd2", &self.motd2)
            .field("game_mode", &self.game_mode)
            .field("game_mode_numeric", &self.game_mode_numeric)
            .field("port_ipv4", &self.port_ipv4)
            .field("port_ipv6", &self.port_ipv6)
            .field("map", &self.map)
            .field("software", &self.software)
            .field("raw_data", &self.raw_data.len())
            .finish()
    }
}

/// Server information for batch queries.
///
/// Used to specify multiple servers to ping in parallel.
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::{McClient, ServerEdition, ServerInfo};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = McClient::new();
/// let servers = vec![
///     ServerInfo {
///         address: "mc.hypixel.net".to_string(),
///         edition: ServerEdition::Java,
///     },
///     ServerInfo {
///         address: "geo.hivebedrock.network:19132".to_string(),
///         edition: ServerEdition::Bedrock,
///     },
/// ];
///
/// let results = client.ping_many(&servers).await;
/// for (server, result) in results {
///     println!("{}: {:?}", server.address, result.is_ok());
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ServerInfo {
    /// Server address (hostname or IP, optionally with port).
    pub address: String,
    /// Server edition.
    pub edition: ServerEdition,
}

/// Minecraft server edition.
///
/// Specifies whether the server is Java Edition or Bedrock Edition.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum ServerEdition {
    /// Java Edition server (default port: 25565).
    Java,
    /// Bedrock Edition server (default port: 19132).
    Bedrock,
}

/// Cache statistics.
///
/// Provides information about the current state of DNS and SRV caches.
///
/// # Example
///
/// ```no_run
/// use rust_mc_status::McClient;
///
/// # #[tokio::main]
/// # async fn main() {
/// let client = McClient::new();
/// let stats = client.cache_stats();
/// println!("DNS entries: {}, SRV entries: {}", stats.dns_entries, stats.srv_entries);
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct CacheStats {
    /// Number of entries in DNS cache.
    pub dns_entries: usize,
    /// Number of entries in SRV cache.
    pub srv_entries: usize,
}

impl std::str::FromStr for ServerEdition {
    type Err = McError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "java" => Ok(ServerEdition::Java),
            "bedrock" => Ok(ServerEdition::Bedrock),
            _ => Err(McError::InvalidEdition(s.to_string())),
        }
    }
}