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