mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
use super::models::public::{NameUuidEntry, PublicKeysResponse, SessionProfile};
use super::{
    DEFAULT_API_MOJANG_URL, DEFAULT_MINECRAFT_SERVICES_URL, DEFAULT_SESSIONSERVER_URL, MojangClient,
};
use crate::error::{Error, Result};
use crate::util::encode_path_segment;
use crate::uuid::McUuid;

impl MojangClient {
    /// Looks up a player's UUID from their current username via
    /// `GET /users/profiles/minecraft/{username}`
    /// (<https://minecraft.wiki/w/Mojang_API#Query_player_UUIDs>).
    pub async fn uuid_by_username(&self, username: &str) -> Result<Option<NameUuidEntry>> {
        let encoded = encode_path_segment(username)?;
        let url = self.url(
            DEFAULT_API_MOJANG_URL,
            &format!("/users/profiles/minecraft/{encoded}"),
        );
        self.http
            .send_optional_json(&url, |client, target| client.get(target))
            .await
    }

    /// Looks up a player's current profile name/UUID via
    /// `GET /user/profile/{uuid}` on `api.mojang.com`.
    pub async fn username_by_uuid(&self, uuid: McUuid) -> Result<Option<NameUuidEntry>> {
        let url = self.url(
            DEFAULT_API_MOJANG_URL,
            &format!("/user/profile/{}", uuid.to_undashed()),
        );
        self.http
            .send_optional_json(&url, |client, target| client.get(target))
            .await
    }

    /// Batch looks up up to 10 usernames via `POST /profiles/minecraft`.
    pub async fn uuids_by_usernames(&self, usernames: &[&str]) -> Result<Vec<NameUuidEntry>> {
        if usernames.is_empty() || usernames.len() > 10 {
            return Err(Error::InvalidInput(
                "uuids_by_usernames accepts between 1 and 10 usernames".to_string(),
            ));
        }
        let url = self.url(DEFAULT_API_MOJANG_URL, "/profiles/minecraft");
        self.http.post_direct_json(&url, &usernames).await
    }

    /// Batch looks up arbitrarily many usernames by chunking requests into groups of 10
    /// (the Mojang `POST /profiles/minecraft` maximum).
    pub async fn uuids_by_usernames_chunked(
        &self,
        usernames: &[&str],
    ) -> Result<Vec<NameUuidEntry>> {
        if usernames.is_empty() {
            return Ok(Vec::new());
        }
        let mut all = Vec::with_capacity(usernames.len());
        for chunk in usernames.chunks(10) {
            all.extend(self.uuids_by_usernames(chunk).await?);
        }
        Ok(all)
    }

    /// Fetches a player's session profile (with textures and optional signature) via
    /// `GET /session/minecraft/profile/{uuid}`.
    pub async fn session_profile(
        &self,
        uuid: McUuid,
        unsigned: bool,
    ) -> Result<Option<SessionProfile>> {
        let url = self.url(
            DEFAULT_SESSIONSERVER_URL,
            &format!("/session/minecraft/profile/{}", uuid.to_undashed()),
        );
        let query = [("unsigned", if unsigned { "true" } else { "false" })];
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
    }

    /// Verifies whether a player joined a multiplayer server via
    /// `GET /session/minecraft/hasJoined`.
    pub async fn has_joined_server(
        &self,
        username: &str,
        server_id: &str,
        ip: Option<&str>,
    ) -> Result<Option<SessionProfile>> {
        let url = self.url(DEFAULT_SESSIONSERVER_URL, "/session/minecraft/hasJoined");
        let mut query = vec![("username", username), ("serverId", server_id)];
        if let Some(ip_addr) = ip {
            query.push(("ip", ip_addr));
        }
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
    }

    /// Fetches Mojang's SHA-1 blocked server hashes via `GET /blockedservers`.
    pub async fn blocked_servers(&self) -> Result<Vec<String>> {
        let url = self.url(DEFAULT_SESSIONSERVER_URL, "/blockedservers");
        let text = self.http.get_text(&url).await?;
        Ok(text
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect())
    }

    /// Fetches Mojang's public RSA verification keys via `GET /publickeys`.
    pub async fn public_keys(&self) -> Result<PublicKeysResponse> {
        let url = self.url(DEFAULT_MINECRAFT_SERVICES_URL, "/publickeys");
        self.http.get_json(&url).await
    }
}