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 std::collections::HashMap;

use serde::Serialize;

use super::models::{HashAlgorithm, LatestVersionBody, LatestVersionsBody, Version};
use super::{Authed, ModrinthClient, is_valid_sha1, is_valid_sha512};
use crate::error::{Error, Result};

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

#[derive(Serialize)]
struct HashLookupQuery {
    algorithm: HashAlgorithm,
    multiple: Option<bool>,
}

#[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::InvalidHash {
            algorithm: algo.as_str(),
            hash: hash.to_string(),
        })
    }
}

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

    /// Batch looks up versions from file hashes via `POST /v2/version_files`.
    pub async fn get_versions_from_hashes(
        &self,
        hashes: &[&str],
        algorithm: HashAlgorithm,
    ) -> Result<HashMap<String, Version>> {
        for hash in hashes {
            check_hash(hash, algorithm)?;
        }
        self.post_json("/version_files", &HashesBody { hashes, algorithm })
            .await
    }

    /// Batch looks up versions from arbitrarily many file hashes by splitting `hashes`
    /// into chunks of `chunk_size` via `POST /v2/version_files`.
    pub async fn get_versions_from_hashes_chunked(
        &self,
        hashes: &[&str],
        algorithm: HashAlgorithm,
        chunk_size: usize,
    ) -> Result<HashMap<String, Version>> {
        if hashes.is_empty() {
            return Ok(HashMap::new());
        }
        for hash in hashes {
            check_hash(hash, algorithm)?;
        }
        let mut all = HashMap::with_capacity(hashes.len());
        for chunk in hashes.chunks(chunk_size.max(1)) {
            all.extend(self.get_versions_from_hashes(chunk, algorithm).await?);
        }
        Ok(all)
    }

    /// Finds the latest compatible version for a file hash via
    /// `POST /v2/version_file/{hash}/update`.
    pub async fn get_latest_version_from_hash(
        &self,
        hash: &str,
        algorithm: HashAlgorithm,
        body: &LatestVersionBody,
    ) -> 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 get_latest_versions_from_hashes(
        &self,
        body: &LatestVersionsBody,
    ) -> Result<HashMap<String, Version>> {
        for hash in &body.hashes {
            check_hash(hash, body.algorithm)?;
        }
        self.post_json("/version_files/update", body).await
    }
}

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(())
    }
}