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
mod server;

use crate::error::CobbleError;
use crate::CobbleResult;
use quartz_nbt::io::{read_nbt, Flavor};
use quartz_nbt::{NbtList, NbtTag};
pub use server::{AcceptTextures, Server};
use std::fs::File;
use std::path::{Path, PathBuf};

/// Load all servers from the servers.dat file.
pub fn load_servers(minecraft_path: impl AsRef<Path>) -> CobbleResult<Vec<Server>> {
    debug!(
        "Loading servers at {}",
        minecraft_path.as_ref().to_string_lossy()
    );

    let mut server_dat_path = PathBuf::from(minecraft_path.as_ref());
    server_dat_path.push("servers.dat");

    if !server_dat_path.is_file() {
        return Ok(vec![]);
    }

    // Read NBT file
    let mut nbt_file = File::open(server_dat_path)?;
    let (nbt_compound, _root_name) = read_nbt(&mut nbt_file, Flavor::Uncompressed)?;

    nbt_compound
        .get::<_, &NbtList>("servers")?
        .iter()
        .map(|tag| match tag {
            NbtTag::Compound(c) => Server::try_from(c),
            _ => Err(CobbleError::InvalidNbtValue),
        })
        .collect::<Result<Vec<_>, _>>()
}