elemental-core 0.3.0

Core library for Elemental, providing common utilities and abstractions used across the project.
Documentation
use async_trait::async_trait;
use nidhogg::{
    client::Nidhogg,
    request::{refresh::Refresh, texture::TextureType as NidhoggTextureType},
    types::{
        meta::Meta,
        profile::{Profile, ProfilePropertyError},
        textures::{ModelType, Texture},
    },
};

use reqwest::Url;
use serde::{Deserialize, Serialize};

use crate::auth::accounts::yggdrasil::{
    YGGDRASIL_AUTHORIZER_ID, YggdrasilAccount, YggdrasilProfile, preferred_language, user_id,
};
use crate::auth::error::{Error, Result};
use crate::auth::providers::{TypedAccountProvider, TypedTextureProvider};
use crate::auth::texture::{
    Cape, ProfileTextures, Skin, SkinModel, TextureType as AccountTextureType,
};
use crate::http::SwappableClient;

/// Canonical Yggdrasil API root normalized to lowercase scheme/host, without
/// default ports, query/fragment components, or trailing slashes.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct YggdrasilSiteId(String);

impl YggdrasilSiteId {
    pub fn new(base_url: &str) -> Option<Self> {
        let trimmed = base_url.trim();
        if trimmed.is_empty() {
            return None;
        }
        let mut parsed = match Url::parse(trimmed) {
            Ok(url) => url,
            Err(_) if !trimmed.contains("://") => Url::parse(&format!("https://{trimmed}")).ok()?,
            Err(_) => return None,
        };
        if !matches!(parsed.scheme(), "http" | "https")
            || !parsed.has_host()
            || !parsed.username().is_empty()
            || parsed.password().is_some()
        {
            return None;
        }
        parsed.set_query(None);
        parsed.set_fragment(None);
        let trimmed_path = parsed.path().trim_end_matches('/').to_owned();
        parsed.set_path(&trimmed_path);

        let normalized = parsed.as_str().trim_end_matches('/');
        (!normalized.is_empty()).then(|| Self(normalized.to_owned()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, Default)]
pub struct YggdrasilAccountProvider {
    http_client: SwappableClient,
}

impl YggdrasilAccountProvider {
    pub fn new(http_client: SwappableClient) -> Self {
        Self { http_client }
    }

    fn client(&self, account: &YggdrasilAccount) -> Result<Nidhogg> {
        let base_url = account
            .base_url
            .as_deref()
            .ok_or(Error::YggdrasilBaseUrlMissing)?;
        nidhogg_client(base_url, Some(&self.http_client))
    }

    async fn upload(
        &self,
        account: &YggdrasilAccount,
        texture_type: NidhoggTextureType,
        image: Vec<u8>,
        file_name: &str,
        model: Option<ModelType>,
    ) -> Result<()> {
        self.client(account)?
            .upload_texture(
                account.selected_profile.id.clone(),
                account.access_token.clone(),
                texture_type,
                image,
                file_name.to_owned(),
                model,
            )
            .await
            .map_err(|source| Error::Yggdrasil { source })
    }

    async fn delete(
        &self,
        account: &YggdrasilAccount,
        texture_type: NidhoggTextureType,
    ) -> Result<()> {
        self.client(account)?
            .delete_texture(
                account.selected_profile.id.clone(),
                account.access_token.clone(),
                texture_type,
            )
            .await
            .map_err(|source| Error::Yggdrasil { source })
    }

    pub async fn fetch_site_metadata(&self, base_url: &str) -> Result<Meta> {
        fetch_site_metadata_with_client(base_url, &self.http_client).await
    }

    /// Fetches the metadata document exposed by the account's Yggdrasil API.
    ///
    /// Returns `None` for offline accounts because they have no remote API
    /// root.
    pub async fn metadata(&self, account: &YggdrasilAccount) -> Result<Option<Meta>> {
        let Some(base_url) = account.base_url.as_deref() else {
            return Ok(None);
        };
        self.fetch_site_metadata(base_url).await.map(Some)
    }
}

#[async_trait]
impl TypedAccountProvider for YggdrasilAccountProvider {
    type Account = YggdrasilAccount;

    fn authorizer_id(&self) -> &'static str {
        YGGDRASIL_AUTHORIZER_ID
    }

    async fn refresh(&self, account: &Self::Account) -> Result<Self::Account> {
        if account.base_url.is_none() {
            return Ok(account.clone());
        }
        let response = self
            .client(account)?
            .refresh(&Refresh::new(
                account.access_token.clone(),
                Some(account.client_token.clone()),
                true,
                Some(Profile {
                    id: account.selected_profile.id.clone(),
                    name: account.selected_profile.name.clone(),
                    properties: None,
                }),
            ))
            .await
            .map_err(|source| Error::Yggdrasil { source })?;

        Ok(YggdrasilAccount {
            account_id: account.account_id,
            base_url: account.base_url.clone(),
            user_id: user_id(response.user.as_ref()).or_else(|| account.user_id.clone()),
            preferred_language: preferred_language(response.user.as_ref())
                .or_else(|| account.preferred_language.clone()),
            access_token: response.access_token,
            client_token: response.client_token,
            selected_profile: response
                .selected_profile
                .as_ref()
                .map(YggdrasilProfile::from)
                .unwrap_or_else(|| account.selected_profile.clone()),
        })
    }
}

#[async_trait]
impl TypedTextureProvider for YggdrasilAccountProvider {
    async fn textures(&self, account: &Self::Account) -> Result<ProfileTextures> {
        let profile = self
            .client(account)?
            .get_profile(account.selected_profile.id.clone(), false)
            .await
            .map_err(|source| Error::Yggdrasil { source })?;
        profile_textures(&profile)
    }

    async fn upload_skin(
        &self,
        account: &Self::Account,
        image: Vec<u8>,
        model: SkinModel,
    ) -> Result<()> {
        let model = match model {
            SkinModel::Classic => None,
            SkinModel::Slim => Some(ModelType::SLIM),
        };
        self.upload(account, NidhoggTextureType::SKIN, image, "skin.png", model)
            .await
    }

    async fn delete_skin(&self, account: &Self::Account) -> Result<()> {
        self.delete(account, NidhoggTextureType::SKIN).await
    }

    async fn upload_cape(&self, account: &Self::Account, image: Vec<u8>) -> Result<()> {
        self.upload(account, NidhoggTextureType::CAPE, image, "cape.png", None)
            .await
    }

    async fn delete_cape(&self, account: &Self::Account) -> Result<()> {
        self.delete(account, NidhoggTextureType::CAPE).await
    }
}

pub(crate) fn nidhogg_client(
    base_url: &str,
    http_client: Option<&SwappableClient>,
) -> Result<Nidhogg> {
    let site = YggdrasilSiteId::new(base_url);
    let normalized = site
        .as_ref()
        .map(YggdrasilSiteId::as_str)
        .unwrap_or_else(|| base_url.trim().trim_end_matches('/'));
    match http_client {
        Some(client) => Ok(Nidhogg::with_client(normalized, client.client())),
        None => Nidhogg::new(normalized).map_err(|source| Error::Yggdrasil { source }),
    }
}

pub async fn fetch_site_metadata_with_client(
    base_url: &str,
    http_client: &SwappableClient,
) -> Result<Meta> {
    nidhogg_client(base_url, Some(http_client))?
        .metadata()
        .await
        .map_err(|source| Error::Yggdrasil { source })
}

fn profile_textures(profile: &Profile) -> Result<ProfileTextures> {
    let textures = optional_property(profile.get_textures())?;
    let skin = textures
        .as_ref()
        .and_then(|textures| textures.textures.skin.as_ref())
        .map(skin_from)
        .transpose()?;
    let capes = textures
        .and_then(|textures| textures.textures.cape)
        .map(cape_from)
        .into_iter()
        .collect();
    let uploadable = optional_property(profile.get_uploadable_textures())?
        .unwrap_or_default()
        .into_iter()
        .filter_map(uploadable_texture)
        .collect();

    Ok(ProfileTextures {
        skin,
        capes,
        uploadable,
    })
}

fn optional_property<T>(result: std::result::Result<T, ProfilePropertyError>) -> Result<Option<T>> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(ProfilePropertyError::NoPropertyFound(_)) => Ok(None),
        Err(source) => Err(Error::YggdrasilTexture { source }),
    }
}

fn skin_from(texture: &Texture) -> Result<Skin> {
    let model = match texture.metadata.as_ref().map(|metadata| &metadata.model) {
        Some(ModelType::SLIM) => SkinModel::Slim,
        Some(ModelType::DEFAULT) | None => SkinModel::Classic,
    };
    Ok(Skin {
        url: texture.url.clone(),
        model,
    })
}

fn cape_from(texture: Texture) -> Cape {
    Cape {
        id: None,
        alias: None,
        url: texture.url,
        active: true,
    }
}

fn uploadable_texture(value: String) -> Option<AccountTextureType> {
    if value.eq_ignore_ascii_case("skin") {
        Some(AccountTextureType::Skin)
    } else if value.eq_ignore_ascii_case("cape") {
        Some(AccountTextureType::Cape)
    } else {
        None
    }
}