mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
#[cfg(feature = "modrinth-write")]
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE};

#[cfg(feature = "modrinth-write")]
use super::models::{
    AddGalleryImageRequest, BulkEditProjectsRequest, CreateProjectRequest,
    ModifyGalleryImageRequest, ModifyProjectRequest, ScheduleProjectRequest, UploadFile,
};
use super::models::{Project, ProjectDependencies, ProjectValidity, SearchQuery, SearchResults};
#[cfg(feature = "modrinth-write")]
use super::{Authed, check_id_or_slug};
use super::{ModrinthClient, encode_id_or_slug};
use crate::error::Result;

impl ModrinthClient {
    /// Searches Modrinth projects via `GET /v2/search`.
    pub async fn search(&self, query: &SearchQuery) -> Result<SearchResults> {
        self.get_json_query("/search", query).await
    }

    /// Fetches a project by ID or slug via `GET /v2/project/{id|slug}`.
    pub async fn project(&self, id_or_slug: &str) -> Result<Project> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.get_json(&format!("/project/{seg}")).await
    }

    /// Batch-fetches projects via `GET /v2/projects?ids=[...]`.
    pub async fn projects(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Project>> {
        self.get_by_ids("/projects", ids).await
    }

    /// Fetches random projects via `GET /v2/projects_random`.
    pub async fn random_projects(&self, count: u32) -> Result<Vec<Project>> {
        self.get_json_query("/projects_random", &[("count", count)])
            .await
    }

    /// Checks whether a project ID or slug is valid via `GET /v2/project/{id|slug}/check`.
    pub async fn check_project_validity(&self, id_or_slug: &str) -> Result<ProjectValidity> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.get_json(&format!("/project/{seg}/check")).await
    }

    /// Lists all dependencies of a project via `GET /v2/project/{id|slug}/dependencies`.
    pub async fn project_dependencies(&self, id_or_slug: &str) -> Result<ProjectDependencies> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.get_json(&format!("/project/{seg}/dependencies")).await
    }
}

#[cfg(feature = "modrinth-write")]
#[cfg_attr(docsrs, doc(cfg(feature = "modrinth-write")))]
impl<'a> Authed<'a> {
    /// Creates a new project via `POST /v2/project` (multipart `data` + optional `icon`).
    pub async fn create_project(
        &self,
        req: &CreateProjectRequest,
        icon: Option<UploadFile>,
    ) -> Result<Project> {
        let data_json = serde_json::to_string(req)?;
        let files = icon.into_iter().map(|f| ("icon".to_string(), f)).collect();
        let resp = self.send_multipart("/project", data_json, files).await?;
        Ok(resp.json().await?)
    }

    /// Modifies a project via `PATCH /v2/project/{id|slug}`.
    pub async fn modify_project(&self, id_or_slug: &str, req: &ModifyProjectRequest) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.patch_authed_json(&format!("/project/{seg}"), req)
            .await
    }

    /// Deletes a project via `DELETE /v2/project/{id|slug}`.
    pub async fn delete_project(&self, id_or_slug: &str) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.delete_authed(&format!("/project/{seg}")).await
    }

    /// Bulk-edits multiple projects via `PATCH /v2/projects`.
    pub async fn bulk_edit_projects(
        &self,
        ids: &[impl AsRef<str>],
        req: &BulkEditProjectsRequest,
    ) -> Result<()> {
        let id_refs: Vec<&str> = ids.iter().map(AsRef::as_ref).collect();
        for id in &id_refs {
            check_id_or_slug(id)?;
        }
        let ids_json = serde_json::to_string(&id_refs)?;
        self.patch_authed_query("/projects", &[("ids", ids_json)], req)
            .await
    }

    /// Uploads/replaces a project's icon via `PATCH /v2/project/{id|slug}/icon`.
    pub async fn change_project_icon(
        &self,
        id_or_slug: &str,
        ext: &str,
        bytes: Vec<u8>,
        content_type: &str,
    ) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.upload_icon(&format!("/project/{seg}/icon"), ext, bytes, content_type)
            .await
    }

    /// Deletes a project's icon via `DELETE /v2/project/{id|slug}/icon`.
    pub async fn delete_project_icon(&self, id_or_slug: &str) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.delete_authed(&format!("/project/{seg}/icon")).await
    }

    /// Adds a gallery image via `POST /v2/project/{id|slug}/gallery`.
    pub async fn add_gallery_image(
        &self,
        id_or_slug: &str,
        req: &AddGalleryImageRequest,
        bytes: Vec<u8>,
        content_type: &str,
    ) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        let url = self.client.v2(&format!("/project/{seg}/gallery"));
        let auth = self.auth_header()?;
        self.client
            .http()
            .send_direct_oneshot(&url, move |client, target| {
                client
                    .post(target)
                    .header(AUTHORIZATION, auth)
                    .header(CONTENT_TYPE, content_type)
                    .query(req)
                    .body(bytes)
            })
            .await?;
        Ok(())
    }

    /// Modifies gallery image metadata via `PATCH /v2/project/{id|slug}/gallery`.
    pub async fn modify_gallery_image(
        &self,
        id_or_slug: &str,
        req: &ModifyGalleryImageRequest,
    ) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.send_authed(&format!("/project/{seg}/gallery"), |c, t| {
            c.patch(t).query(req)
        })
        .await?;
        Ok(())
    }

    /// Deletes a gallery image via `DELETE /v2/project/{id|slug}/gallery`.
    pub async fn delete_gallery_image(&self, id_or_slug: &str, image_url: &str) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.send_authed(&format!("/project/{seg}/gallery"), |c, t| {
            c.delete(t).query(&[("url", image_url)])
        })
        .await?;
        Ok(())
    }

    /// Follows a project via `POST /v2/project/{id|slug}/follow`.
    pub async fn follow_project(&self, id_or_slug: &str) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.post_authed_no_body(&format!("/project/{seg}/follow"))
            .await
    }

    /// Unfollows a project via `DELETE /v2/project/{id|slug}/follow`.
    pub async fn unfollow_project(&self, id_or_slug: &str) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.delete_authed(&format!("/project/{seg}/follow")).await
    }

    /// Schedules a project status transition via `POST /v2/project/{id|slug}/schedule`.
    pub async fn schedule_project(
        &self,
        id_or_slug: &str,
        req: &ScheduleProjectRequest,
    ) -> Result<()> {
        let seg = encode_id_or_slug(id_or_slug)?;
        self.post_authed_empty(&format!("/project/{seg}/schedule"), req)
            .await
    }
}