#[cfg(feature = "http")]
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(feature = "http")]
use reqwest::header::HeaderMap;
use thiserror::Error;
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RateLimitInfo {
pub retry_after_secs: Option<u64>,
pub limit: Option<u32>,
pub remaining: Option<u32>,
}
#[derive(Debug, Error)]
pub enum Error {
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[error("HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("failed to serialize or deserialize JSON: {0}")]
Json(#[from] serde_json::Error),
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[error("invalid URL: {0}")]
Url(#[from] url::ParseError),
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[error("invalid HTTP header value: {0}")]
InvalidHeader(#[from] reqwest::header::InvalidHeaderValue),
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[error("rate limit exceeded, retry after {retry_after_secs}s")]
RateLimitExceeded {
retry_after_secs: u64,
limit: Option<u32>,
remaining: Option<u32>,
},
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[error("API returned HTTP {status} for {url}: {message}")]
ApiStatus {
status: u16,
url: String,
message: String,
body: String,
},
#[error("invalid input: {0}")]
InvalidInput(String),
#[cfg(any(feature = "yggdrasil", feature = "slp"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "yggdrasil", feature = "slp"))))]
#[error("base64 decode error: {0}")]
Base64(#[from] base64::DecodeError),
#[cfg(feature = "loaders")]
#[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
#[error("XML parse error: {0}")]
Xml(#[from] quick_xml::DeError),
#[cfg(feature = "modrinth")]
#[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
#[error("invalid Modrinth project/version/user ID or slug: {0}")]
InvalidIdOrSlug(String),
#[cfg(feature = "modrinth")]
#[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
#[error("invalid {algorithm} hash: {hash}")]
InvalidHash {
algorithm: &'static str,
hash: String,
},
#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
#[error("XSTS rejected ({:?}, XErr={}): {}", .0.kind, .0.xerr, .0.message)]
XstsRejected(crate::mojang::XstsError),
#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
#[error("missing Xbox user hash (uhs) in XBL/XSTS DisplayClaims")]
MissingUserHash,
#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
#[error("Microsoft device code expired before authorization")]
DeviceCodeExpired,
#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
#[error("Microsoft device code authorization was declined by the user")]
DeviceCodeDeclined,
#[cfg(feature = "mojang")]
#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
#[error("Microsoft account does not own Minecraft: Java Edition")]
DoesNotOwnMinecraft,
#[cfg(any(feature = "mojang", feature = "yggdrasil"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "mojang", feature = "yggdrasil"))))]
#[error("profile has no textures property")]
MissingTexturesProperty,
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
#[error("Yggdrasil error ({error}): {error_message}")]
Yggdrasil {
error: String,
error_message: String,
cause: Option<String>,
},
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
#[error("invalid X-Authlib-Injector-API-Location header")]
InvalidAliLocation,
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
#[error("profile property '{0}' is missing a signature")]
MissingSignature(String),
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
#[error("invalid profile signature or public key: {0}")]
InvalidSignature(String),
#[cfg(feature = "blessing")]
#[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
#[error("Blessing Skin API returned code {code}: {message}")]
BlessingApi { code: i32, message: String },
#[cfg(feature = "blessing")]
#[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
#[error("Blessing Skin API response missing expected data field")]
MissingData,
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("operation timed out")]
Timeout,
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("malformed VarInt in Minecraft protocol frame")]
MalformedVarInt,
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("unexpected Minecraft packet ID: 0x{0:02X}")]
UnexpectedPacketId(i32),
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("packet frame too large: {0} bytes")]
FrameTooLarge(usize),
#[cfg(feature = "slp")]
#[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
#[error("invalid server status response: {0}")]
InvalidResponse(String),
}
impl Error {
pub fn status_code(&self) -> Option<u16> {
match self {
#[cfg(feature = "http")]
Error::ApiStatus { status, .. } => Some(*status),
#[cfg(feature = "http")]
Error::RateLimitExceeded { .. } => Some(429),
_ => None,
}
}
pub fn is_not_found(&self) -> bool {
self.status_code() == Some(404)
}
pub fn is_rate_limited(&self) -> bool {
self.status_code() == Some(429)
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub fn parse_rate_limit_headers(headers: &HeaderMap) -> RateLimitInfo {
let retry_after_secs = parse_header::<u64>(headers, "retry-after").or_else(|| {
parse_header::<u64>(headers, "x-ratelimit-reset").map(|val| {
if val >= 1_000_000_000 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
val.saturating_sub(now)
} else {
val
}
})
});
let limit = parse_header::<u32>(headers, "x-ratelimit-limit");
let remaining = parse_header::<u32>(headers, "x-ratelimit-remaining");
RateLimitInfo {
retry_after_secs,
limit,
remaining,
}
}
#[cfg(feature = "http")]
fn parse_header<T: std::str::FromStr>(headers: &HeaderMap, name: &str) -> Option<T> {
headers.get(name)?.to_str().ok()?.trim().parse::<T>().ok()
}
#[cfg(feature = "http")]
pub(crate) fn extract_api_error_message(body: &str, status: reqwest::StatusCode) -> String {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
for key in [
"errorMessage",
"description",
"message",
"error_description",
"error",
] {
if let Some(msg) = value.get(key).and_then(|v| v.as_str())
&& !msg.trim().is_empty()
{
return msg.to_string();
}
}
}
let trimmed = body.trim();
if trimmed.is_empty() {
status
.canonical_reason()
.unwrap_or("unexpected status")
.to_string()
} else if trimmed.len() > 240 {
let end = (0..=240)
.rev()
.find(|&i| trimmed.is_char_boundary(i))
.unwrap_or(0);
format!("{}...", &trimmed[..end])
} else {
trimmed.to_string()
}
}