mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Blessing Skin / LittleSkin v6 REST API and CustomSkinLoader (`CustomSkinAPI`) client.
//!
//! Reference spec: <https://blessing.netlify.app/dev/api.html>.

mod closet;
mod csl;
/// Data models for Blessing Skin REST API and CustomSkinLoader responses.
pub mod models;
mod players;
mod public;
mod skinlib;
mod user;

use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderValue};
use serde::Serialize;
use serde::de::DeserializeOwned;

use self::models::BlessingEnvelope;
use crate::error::{Error, Result};
use crate::http::{HttpClient, bearer_header};
use crate::util::{define_authed, trim_trailing_slash};

pub(crate) const ACCEPT_JSON: HeaderValue = HeaderValue::from_static("application/json");

#[derive(Serialize)]
pub(crate) struct NameBody<'a> {
    pub name: &'a str,
}

/// Async client for Blessing Skin v6 REST API and CustomSkinLoader `CustomSkinAPI` endpoints.
///
/// Always attaches `Accept: application/json` on `/api/*` requests so Laravel returns JSON
/// errors instead of HTML login redirects, and bypasses [`crate::Mirror`] rewriting on
/// authenticated and mutating endpoints.
#[derive(Clone, Debug)]
pub struct BlessingClient {
    pub(crate) site_url: String,
    pub(crate) http: HttpClient,
}

impl BlessingClient {
    /// Creates a new [`BlessingClient`] pointing at `site_url` (e.g. `"https://littleskin.cn"`).
    pub fn new(site_url: impl AsRef<str>) -> Result<Self> {
        Self::from_http(HttpClient::new()?, site_url)
    }

    /// Creates a new [`BlessingClient`] sharing an existing [`HttpClient`].
    ///
    /// Returns [`Error::Url`] or [`Error::InvalidInput`] if `site_url` is not a valid
    /// `http://` or `https://` URL.
    pub fn from_http(http: HttpClient, site_url: impl AsRef<str>) -> Result<Self> {
        let mut parsed = crate::util::validate_http_url(site_url.as_ref())?;
        parsed.set_query(None);
        parsed.set_fragment(None);
        Ok(Self {
            site_url: trim_trailing_slash(parsed.as_str()),
            http,
        })
    }

    /// Returns an authenticated view bound to a Blessing Skin JWT / API Bearer token.
    #[must_use]
    pub fn authed<'a>(&'a self, token: &'a str) -> Authed<'a> {
        Authed::new(self, token)
    }

    /// Returns the normalized Blessing Skin site URL.
    #[must_use]
    pub fn site_url(&self) -> &str {
        &self.site_url
    }

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

    pub(crate) fn api(&self, path: &str) -> String {
        format!("{}/api{}", self.site_url, path)
    }

    pub(crate) async fn post_public_envelope<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let url = self.api(path);
        let resp = self
            .http
            .send_direct(&url, |client, target| {
                client.post(target).header(ACCEPT, ACCEPT_JSON).json(body)
            })
            .await?;
        unwrap_envelope(resp.json::<BlessingEnvelope<T>>().await?)
    }
}

define_authed!(BlessingClient);

impl<'a> Authed<'a> {
    async fn send_authed_inner<F>(
        &self,
        path: &str,
        idempotent: bool,
        mut build: F,
    ) -> Result<reqwest::Response>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    {
        let url = self.client.api(path);
        let auth = bearer_header(self.token)?;
        let req_fn = |client: &reqwest::Client, target: &str| {
            build(client, target)
                .header(ACCEPT, ACCEPT_JSON)
                .header(AUTHORIZATION, auth.clone())
        };
        if idempotent {
            self.client.http.send_direct_idempotent(&url, req_fn).await
        } else {
            self.client.http.send_direct(&url, req_fn).await
        }
    }

    pub(crate) async fn send_envelope_inner<F, T>(
        &self,
        path: &str,
        idempotent: bool,
        build: F,
    ) -> Result<T>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
        T: DeserializeOwned,
    {
        let resp = self.send_authed_inner(path, idempotent, build).await?;
        unwrap_envelope(resp.json::<BlessingEnvelope<T>>().await?)
    }

    pub(crate) async fn send_unit<F>(&self, path: &str, build: F) -> Result<()>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    {
        let resp = self.send_authed_inner(path, false, build).await?;
        let env: BlessingEnvelope<serde_json::Value> = resp.json().await?;
        check_code(env.code, env.message)
    }

    pub(crate) async fn get_envelope<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.send_envelope_inner(path, true, |c, t| c.get(t)).await
    }

    pub(crate) async fn get_envelope_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        query: &Q,
    ) -> Result<T> {
        self.send_envelope_inner(path, true, |c, t| c.get(t).query(query))
            .await
    }

    pub(crate) async fn post_envelope<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.send_envelope_inner(path, false, |c, t| c.post(t).json(body))
            .await
    }

    pub(crate) async fn post_unit<B: Serialize + ?Sized>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<()> {
        self.send_unit(path, |c, t| c.post(t).json(body)).await
    }

    pub(crate) async fn put_unit<B: Serialize + ?Sized>(&self, path: &str, body: &B) -> Result<()> {
        self.send_unit(path, |c, t| c.put(t).json(body)).await
    }

    pub(crate) async fn delete_unit(&self, path: &str) -> Result<()> {
        self.send_unit(path, |c, t| c.delete(t)).await
    }
}

pub(crate) fn unwrap_envelope<T>(env: BlessingEnvelope<T>) -> Result<T> {
    check_code(env.code, env.message)?;
    env.data.ok_or_else(|| Error::BlessingApi {
        code: 0,
        message: "Blessing Skin API response missing expected data field".to_string(),
    })
}

pub(crate) fn check_code(code: i32, message: String) -> Result<()> {
    if code == 0 {
        Ok(())
    } else {
        Err(Error::BlessingApi { code, message })
    }
}