mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
//! Blessing Skin / LittleSkin v6 REST API and CustomSkinLoader (`CustomSkinAPI`) client.

mod closet;
mod csl;
pub mod models;
mod players;
mod public;
mod skinlib;

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

use self::models::BlessingEnvelope;
use crate::error::{Error, Result};
use crate::http::HttpCore;
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 (<https://blessing.netlify.app/dev/api.html>)
/// 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: HttpCore,
}

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

    /// Creates a new [`BlessingClient`] sharing an existing [`HttpCore`].
    pub fn from_http(http: HttpCore, site_url: impl Into<String>) -> Self {
        Self {
            site_url: trim_trailing_slash(site_url),
            http,
        }
    }

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

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

    /// Returns the underlying shared [`HttpCore`].
    pub fn http(&self) -> &HttpCore {
        &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<F>(&self, path: &str, mut build: F) -> Result<reqwest::Response>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
    {
        let url = self.client.api(path);
        self.client
            .http
            .send_direct(&url, |client, target| {
                build(client, target)
                    .header(ACCEPT, ACCEPT_JSON)
                    .bearer_auth(self.token)
            })
            .await
    }

    pub(crate) async fn send_envelope<F, T>(&self, path: &str, build: F) -> Result<T>
    where
        F: FnMut(&reqwest::Client, &str) -> reqwest::RequestBuilder,
        T: DeserializeOwned,
    {
        let resp = self.send_authed(path, 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(path, 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(path, |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(path, |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(path, |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(Error::MissingData)
}

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