mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
use super::models::public::{NameUuidEntry, PublicKeysResponse, SessionProfile};
use super::{DEFAULT_MINECRAFT_SERVICES_URL, DEFAULT_SESSIONSERVER_URL, MojangClient};
use crate::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 /minecraft/profile/lookup/name/{username}` on `api.minecraftservices.com`.
    pub async fn uuid_by_username(&self, username: &str) -> Result<Option<NameUuidEntry>> {
        let encoded = encode_path_segment(username)?;
        let url = self.url(
            DEFAULT_MINECRAFT_SERVICES_URL,
            &format!("/minecraft/profile/lookup/name/{encoded}"),
        );
        self.http
            .send_optional_json(&url, |client, target| client.get(target))
            .await
    }

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

    /// Batch looks up usernames via `POST /minecraft/profile/lookup/bulk/byname`
    /// on `api.minecraftservices.com`.
    ///
    /// Automatically chunks requests into batches of 10 (Mojang's per-request limit);
    /// empty slices return `Ok(vec![])` without issuing any HTTP request.
    pub async fn uuids_by_usernames(
        &self,
        usernames: &[impl AsRef<str>],
    ) -> Result<Vec<NameUuidEntry>> {
        if usernames.is_empty() {
            return Ok(Vec::new());
        }
        let names: Vec<&str> = usernames.iter().map(AsRef::as_ref).collect();
        let url = self.url(
            DEFAULT_MINECRAFT_SERVICES_URL,
            "/minecraft/profile/lookup/bulk/byname",
        );
        if names.len() <= 10 {
            let resp = self
                .http
                .send_direct_idempotent(&url, |client, target| client.post(target).json(&names))
                .await?;
            return Ok(resp.json().await?);
        }
        let mut all = Vec::with_capacity(names.len());
        for chunk in names.chunks(10) {
            let resp = self
                .http
                .send_direct_idempotent(&url, |client, target| client.post(target).json(chunk))
                .await?;
            let batch: Vec<NameUuidEntry> = resp.json().await?;
            all.extend(batch);
        }
        Ok(all)
    }

    /// Fetches a player's unsigned session profile via
    /// `GET /session/minecraft/profile/{uuid}?unsigned=true`.
    pub async fn profile(&self, uuid: McUuid) -> Result<Option<SessionProfile>> {
        self.profile_inner(uuid, true).await
    }

    /// Fetches a player's signed session profile (including RSA signature on `textures`) via
    /// `GET /session/minecraft/profile/{uuid}?unsigned=false`.
    pub async fn signed_profile(&self, uuid: McUuid) -> Result<Option<SessionProfile>> {
        self.profile_inner(uuid, false).await
    }

    async fn profile_inner(&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(
        &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
    }
}