pub mod models;
mod projects;
mod tags;
mod teams;
mod users;
mod version_files;
mod versions;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue};
use reqwest::multipart::{Form, Part};
use serde::Serialize;
use serde::de::DeserializeOwned;
use self::models::UploadFile;
use crate::error::{Error, Result};
use crate::http::HttpCore;
use crate::util::{define_authed, encode_path_segment, trim_trailing_slash};
pub const DEFAULT_BASE_URL: &str = "https://api.modrinth.com";
pub fn is_valid_id_or_slug(value: &str) -> bool {
let len = value.len();
if !(3..=64).contains(&len) {
return false;
}
value.bytes().all(|b| {
b.is_ascii_alphanumeric()
|| matches!(
b,
b'_' | b'-' | b'!' | b'@' | b'$' | b'(' | b')' | b'.' | b'+' | b',' | b'"' | b'\''
)
})
}
pub fn is_valid_sha1(hash: &str) -> bool {
hash.len() == 40 && hash.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn is_valid_sha512(hash: &str) -> bool {
hash.len() == 128 && hash.bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) fn check_id_or_slug(value: &str) -> Result<()> {
if is_valid_id_or_slug(value) {
Ok(())
} else {
Err(Error::InvalidIdOrSlug(value.to_string()))
}
}
pub(crate) fn encode_id_or_slug(value: &str) -> Result<String> {
check_id_or_slug(value)?;
encode_path_segment(value)
}
#[derive(Clone, Debug)]
pub struct ModrinthClient {
base_url: String,
http: HttpCore,
}
impl ModrinthClient {
pub fn new(user_agent: impl Into<String>) -> Result<Self> {
Ok(Self::from_http(
HttpCore::builder().user_agent(user_agent).build()?,
))
}
pub fn from_http(http: HttpCore) -> Self {
Self {
base_url: DEFAULT_BASE_URL.to_string(),
http,
}
}
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = trim_trailing_slash(base_url);
self
}
pub fn authed<'a>(&'a self, token: &'a str) -> Authed<'a> {
Authed::new(self, token)
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn http(&self) -> &HttpCore {
&self.http
}
pub(crate) fn v2(&self, path: &str) -> String {
format!("{}/v2{}", self.base_url, path)
}
pub(crate) async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let url = self.v2(path);
self.http.get_json(&url).await
}
pub(crate) async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
&self,
path: &str,
query: &Q,
) -> Result<T> {
let url = self.v2(path);
self.http.get_json_query(&url, query).await
}
pub(crate) async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let url = self.v2(path);
self.http.post_json(&url, body).await
}
pub(crate) async fn get_by_ids<T: DeserializeOwned>(
&self,
path: &str,
ids: &[&str],
) -> Result<Vec<T>> {
for id in ids {
check_id_or_slug(id)?;
}
let ids_json = serde_json::to_string(ids)?;
self.get_json_query(path, &[("ids", ids_json)]).await
}
pub(crate) async fn get_by_ids_chunked<T: DeserializeOwned>(
&self,
path: &str,
ids: &[&str],
chunk_size: usize,
) -> Result<Vec<T>> {
if ids.is_empty() {
return Ok(Vec::new());
}
for id in ids {
check_id_or_slug(id)?;
}
let mut all = Vec::with_capacity(ids.len());
for chunk in ids.chunks(chunk_size.max(1)) {
let ids_json = serde_json::to_string(chunk)?;
let batch: Vec<T> = self.get_json_query(path, &[("ids", ids_json)]).await?;
all.extend(batch);
}
Ok(all)
}
}
define_authed!(ModrinthClient);
impl<'a> Authed<'a> {
pub(crate) fn auth_header(&self) -> Result<HeaderValue> {
let mut val = HeaderValue::from_str(self.token)?;
val.set_sensitive(true);
Ok(val)
}
pub(crate) async fn send_authed<F>(&self, path: &str, mut build: F) -> Result<reqwest::Response>
where
F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
{
let url = self.client.v2(path);
let auth = self.auth_header()?;
self.client
.http
.send_direct(&url, |client, target| {
build(client, target).header(AUTHORIZATION, auth.clone())
})
.await
}
pub(crate) async fn get_authed_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let resp = self.send_authed(path, |c, t| c.get(t)).await?;
Ok(resp.json().await?)
}
pub(crate) async fn post_authed_empty<B: Serialize + ?Sized>(
&self,
path: &str,
body: &B,
) -> Result<()> {
self.send_authed(path, |c, t| c.post(t).json(body)).await?;
Ok(())
}
pub(crate) async fn post_authed_no_body(&self, path: &str) -> Result<()> {
self.send_authed(path, |c, t| c.post(t)).await?;
Ok(())
}
pub(crate) async fn patch_authed_json<B: Serialize + ?Sized>(
&self,
path: &str,
body: &B,
) -> Result<()> {
self.send_authed(path, |c, t| c.patch(t).json(body)).await?;
Ok(())
}
pub(crate) async fn patch_authed_query<Q: Serialize + ?Sized, B: Serialize + ?Sized>(
&self,
path: &str,
query: &Q,
body: &B,
) -> Result<()> {
self.send_authed(path, |c, t| c.patch(t).query(query).json(body))
.await?;
Ok(())
}
pub(crate) async fn delete_authed(&self, path: &str) -> Result<()> {
self.send_authed(path, |c, t| c.delete(t)).await?;
Ok(())
}
pub(crate) async fn upload_icon(
&self,
path: &str,
ext: &str,
bytes: Vec<u8>,
content_type: &str,
) -> Result<()> {
let url = self.client.v2(path);
let auth = self.auth_header()?;
self.client
.http
.send_direct_oneshot(&url, move |client, target| {
client
.patch(target)
.header(AUTHORIZATION, auth)
.header(CONTENT_TYPE, content_type)
.query(&[("ext", ext)])
.body(bytes)
})
.await?;
Ok(())
}
pub(crate) async fn send_multipart(
&self,
path: &str,
data_json: String,
files: Vec<(String, UploadFile)>,
) -> Result<reqwest::Response> {
let url = self.client.v2(path);
let auth = self.auth_header()?;
let parts = files
.into_iter()
.map(|(part_name, file)| {
let part = Part::bytes(file.bytes)
.file_name(file.file_name)
.mime_str(&file.mime_type)?;
Ok((part_name, part))
})
.collect::<Result<Vec<_>>>()?;
self.client
.http
.send_direct_oneshot(&url, move |client, target| {
let mut form = Form::new().text("data", data_json);
for (part_name, part) in parts {
form = form.part(part_name, part);
}
client
.post(target)
.header(AUTHORIZATION, auth)
.multipart(form)
})
.await
}
}