mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! CurseForge Core REST API (v1/v2) client and Murmur2 file fingerprinting.
//!
//! Reference spec: <https://docs.curseforge.com/rest-api/>.

mod files;
mod fingerprints;
mod games;
mod minecraft;
/// Data models for CurseForge games, categories, mods, files, fingerprints, and search queries.
pub mod models;
mod mods;
/// CurseForge Murmur2 file fingerprint hashing utilities.
pub mod murmur2;

pub use murmur2::{fingerprint, fingerprint_file, fingerprint_reader, fingerprint_reader_with_len};

use reqwest::header::HeaderValue;
use serde::Serialize;
use serde::de::DeserializeOwned;

use self::models::{DataEnvelope, PaginatedData};
use crate::error::{Error, Result};
use crate::http::HttpClient;
use crate::mirror::Mirror;
use crate::util::{impl_redacted_debug, trim_trailing_slash};

/// Default CurseForge Core API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.curseforge.com";
const API_KEY_HEADER: &str = "x-api-key";

/// Async client for the CurseForge Core REST API.
///
/// May be constructed with an official `x-api-key`, or without one via
/// [`CurseForgeClient::keyless`] / [`CurseForgeClient::from_http`] (`api_key = None`)
/// when routing requests through keyless mirrors such as `Mirror::Mcim`. When an API key is
/// configured, it is attached **only** to requests targeting `base_url` and never forwarded
/// to third-party mirrors.
#[derive(Clone)]
pub struct CurseForgeClient {
    base_url: String,
    api_key: Option<HeaderValue>,
    http: HttpClient,
}

impl_redacted_debug!(CurseForgeClient {
    base_url, http;
    redacted:;
    optional_redacted: api_key,
});

impl CurseForgeClient {
    /// Creates a new [`CurseForgeClient`] authenticated with `api_key`.
    pub fn new(api_key: impl AsRef<str>) -> Result<Self> {
        Self::from_http(HttpClient::new()?, Some(api_key.as_ref()))
    }

    /// Creates a keyless [`CurseForgeClient`] configured with `mirror` (e.g. `Mirror::Mcim`).
    pub fn keyless(mirror: Mirror) -> Result<Self> {
        Self::from_http(HttpClient::builder().mirror(mirror).build()?, None)
    }

    /// Creates a [`CurseForgeClient`] sharing `http` with an optional `api_key`.
    ///
    /// - When `api_key` is `Some(key)` (non-blank), attaches `x-api-key` only to unrewritten
    ///   requests targeting `base_url` (including custom gateways set via
    ///   [`CurseForgeClient::with_base_url`], never forwarded to [`Mirror`]-rewritten hosts).
    /// - When `api_key` is `None` (or blank) and `http.mirror()` rewrites [`DEFAULT_BASE_URL`],
    ///   constructs a keyless mirror client (which skips falling back to official
    ///   `api.curseforge.com`).
    /// - Otherwise returns [`Error::InvalidInput`].
    pub fn from_http(http: HttpClient, api_key: Option<&str>) -> Result<Self> {
        match api_key.filter(|k| !k.trim().is_empty()) {
            Some(key) => {
                let mut val = HeaderValue::from_str(key)?;
                val.set_sensitive(true);
                Ok(Self {
                    base_url: DEFAULT_BASE_URL.to_string(),
                    api_key: Some(val),
                    http,
                })
            }
            None if http.mirror().is_rewritten(DEFAULT_BASE_URL) => Ok(Self {
                base_url: DEFAULT_BASE_URL.to_string(),
                api_key: None,
                http,
            }),
            None => Err(Error::InvalidInput(
                "CurseForge official API requires an x-api-key (or a mirror rewriting api.curseforge.com)"
                    .to_string(),
            )),
        }
    }

    /// Overrides the base API URL (e.g., for mock servers or custom gateways).
    ///
    /// Any configured `api_key` will be sent directly to this `base_url` (never to
    /// [`Mirror`]-rewritten candidates).
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = trim_trailing_slash(base_url);
        self
    }

    /// Returns the configured CurseForge API base URL.
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Returns a reference to the underlying shared [`HttpClient`].
    #[must_use]
    pub fn http(&self) -> &HttpClient {
        &self.http
    }

    async fn send_json<F, T>(&self, path: &str, mut build: F) -> Result<T>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
        T: DeserializeOwned,
    {
        let url = format!("{}{}", self.base_url, path);
        // Keyless mirror clients targeting official DEFAULT_BASE_URL cannot authenticate against
        // api.curseforge.com directly, so skip falling back to official when mirror candidates fail.
        let allow_official_fallback = self.api_key.is_some() || self.base_url != DEFAULT_BASE_URL;
        self.http
            .send_json_with_fallback_policy(&url, allow_official_fallback, |client, target| {
                let req = build(client, target);
                // Attach x-api-key only when hitting our configured base_url directly (not a
                // Mirror-rewritten candidate URL) so keys never leak to third-party mirrors.
                let is_direct_base_target = target == url;
                if let Some(ref key) = self.api_key
                    && is_direct_base_target
                {
                    req.header(API_KEY_HEADER, key.clone())
                } else {
                    req
                }
            })
            .await
    }

    pub(crate) async fn get_data<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.get(target))
            .await?;
        Ok(env.data)
    }

    pub(crate) async fn get_data_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.get(target).query(query))
            .await?;
        Ok(env.data)
    }

    pub(crate) async fn get_paginated<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<PaginatedData<T>> {
        self.send_json(path, |client, target| client.get(target).query(query))
            .await
    }

    pub(crate) async fn post_data<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let env: DataEnvelope<T> = self
            .send_json(path, |client, target| client.post(target).json(body))
            .await?;
        Ok(env.data)
    }
}