mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
use std::collections::HashMap;

use serde::Serialize;

#[cfg(feature = "modrinth-write")]
use super::Authed;
use super::models::{HashAlgorithm, LatestVersionRequest, LatestVersionsRequest, Version};
use super::{ModrinthClient, is_valid_sha1, is_valid_sha512};
use crate::error::{Error, Result};

#[derive(Serialize)]
struct HashesBody<'a> {
    hashes: &'a [&'a str],
    algorithm: HashAlgorithm,
}

#[cfg(feature = "modrinth-write")]
#[derive(Serialize)]
struct DeleteHashQuery<'a> {
    algorithm: HashAlgorithm,
    version_id: Option<&'a str>,
}

fn check_hash(hash: &str, algo: HashAlgorithm) -> Result<()> {
    let valid = match algo {
        HashAlgorithm::Sha1 => is_valid_sha1(hash),
        HashAlgorithm::Sha512 => is_valid_sha512(hash),
    };
    if valid {
        Ok(())
    } else {
        Err(Error::InvalidInput(format!(
            "invalid {} hash: {hash}",
            algo.as_str()
        )))
    }
}

impl ModrinthClient {
    /// Looks up a single version from a file hash via `GET /v2/version_file/{hash}`.
    pub async fn version_from_hash(&self, hash: &str, algorithm: HashAlgorithm) -> Result<Version> {
        check_hash(hash, algorithm)?;
        self.get_json_query(
            &format!("/version_file/{hash}"),
            &[("algorithm", algorithm.as_str())],
        )
        .await
    }

    /// Looks up all versions matching a file hash via `GET /v2/version_file/{hash}?multiple=true`.
    pub async fn versions_from_hash(
        &self,
        hash: &str,
        algorithm: HashAlgorithm,
    ) -> Result<Vec<Version>> {
        check_hash(hash, algorithm)?;
        self.get_json_query(
            &format!("/version_file/{hash}"),
            &[("algorithm", algorithm.as_str()), ("multiple", "true")],
        )
        .await
    }

    /// Batch looks up versions from file hashes via `POST /v2/version_files`.
    pub async fn versions_from_hashes(
        &self,
        hashes: &[impl AsRef<str>],
        algorithm: HashAlgorithm,
    ) -> Result<HashMap<String, Version>> {
        let hash_refs: Vec<&str> = hashes.iter().map(AsRef::as_ref).collect();
        for hash in &hash_refs {
            check_hash(hash, algorithm)?;
        }
        self.post_json(
            "/version_files",
            &HashesBody {
                hashes: &hash_refs,
                algorithm,
            },
        )
        .await
    }

    /// Finds the latest compatible version for a file hash via
    /// `POST /v2/version_file/{hash}/update`.
    pub async fn latest_version_from_hash(
        &self,
        hash: &str,
        algorithm: HashAlgorithm,
        body: &LatestVersionRequest,
    ) -> Result<Version> {
        check_hash(hash, algorithm)?;
        let url = self.v2(&format!("/version_file/{hash}/update"));
        self.http()
            .send_json_with(&url, |client, target| {
                client
                    .post(target)
                    .query(&[("algorithm", algorithm.as_str())])
                    .json(body)
            })
            .await
    }

    /// Batch finds latest compatible versions for multiple hashes via
    /// `POST /v2/version_files/update`.
    pub async fn latest_versions_from_hashes(
        &self,
        body: &LatestVersionsRequest,
    ) -> Result<HashMap<String, Version>> {
        for hash in &body.hashes {
            check_hash(hash, body.algorithm)?;
        }
        self.post_json("/version_files/update", body).await
    }
}

#[cfg(feature = "modrinth-write")]
#[cfg_attr(docsrs, doc(cfg(feature = "modrinth-write")))]
impl<'a> Authed<'a> {
    /// Deletes a file by hash via `DELETE /v2/version_file/{hash}`.
    pub async fn delete_file_from_hash(
        &self,
        hash: &str,
        algorithm: HashAlgorithm,
        version_id: Option<&str>,
    ) -> Result<()> {
        check_hash(hash, algorithm)?;
        let query = DeleteHashQuery {
            algorithm,
            version_id,
        };
        self.send_authed(&format!("/version_file/{hash}"), |c, t| {
            c.delete(t).query(&query)
        })
        .await?;
        Ok(())
    }
}