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