vrchatapi 1.20.8

VRChat API Client for Rust
Documentation
use std::error;
use std::fmt;
{{#withAWSV4Signature}}
use aws_sigv4;
{{/withAWSV4Signature}}

#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
    pub status: reqwest::StatusCode,
    pub content: String,
    pub entity: Option<T>,
}

#[derive(Debug)]
pub enum Error<T> {
    Reqwest(reqwest::Error),
    {{#supportMiddleware}}
    ReqwestMiddleware(reqwest_middleware::Error),
    {{/supportMiddleware}}
    Serde(serde_json::Error),
    {{#useSerdePathToError}}
    SerdePathToError(serde_path_to_error::Error<serde_json::Error>),
    {{/useSerdePathToError}}
    Io(std::io::Error),
    ResponseError(ResponseContent<T>),
    {{#withAWSV4Signature}}
    AWSV4SignatureError(aws_sigv4::http_request::Error),
    {{/withAWSV4Signature}}
    {{#supportAsync}}
    {{#supportTokenSource}}
    TokenSource(Box<dyn std::error::Error + Send + Sync>),
    {{/supportTokenSource}}
    {{/supportAsync}}
}

impl <T> fmt::Display for Error<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (module, e) = match self {
            Error::Reqwest(e) => ("reqwest", e.to_string()),
            {{#supportMiddleware}}
            Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()),
            {{/supportMiddleware}}
            Error::Serde(e) => ("serde", e.to_string()),
            {{#useSerdePathToError}}
            Error::SerdePathToError(e) => ("serde", format!("{}: {}", e.path().to_string(), e.inner().to_string())),
            {{/useSerdePathToError}}
            Error::Io(e) => ("IO", e.to_string()),
            Error::ResponseError(e) => ("response", format!("status code {}", e.status)),
            {{#withAWSV4Signature}}
            Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()),
            {{/withAWSV4Signature}}
            {{#supportAsync}}
            {{#supportTokenSource}}
            Error::TokenSource(e) => ("token source failure", e.to_string()),
            {{/supportTokenSource}}
            {{/supportAsync}}
        };
        write!(f, "error in {}: {}", module, e)
    }
}

impl <T: fmt::Debug> error::Error for Error<T> {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(match self {
            Error::Reqwest(e) => e,
            {{#supportMiddleware}}
            Error::ReqwestMiddleware(e) => e,
            {{/supportMiddleware}}
            Error::Serde(e) => e,
            {{#useSerdePathToError}}
            Error::SerdePathToError(e) => e,
            {{/useSerdePathToError}}
            Error::Io(e) => e,
            Error::ResponseError(_) => return None,
            {{#withAWSV4Signature}}
            Error::AWSV4SignatureError(_) => return None,
            {{/withAWSV4Signature}}
            {{#supportAsync}}
            {{#supportTokenSource}}
            Error::TokenSource(e) => &**e,
            {{/supportTokenSource}}
            {{/supportAsync}}
        })
    }
}

impl <T> From<reqwest::Error> for Error<T> {
    fn from(e: reqwest::Error) -> Self {
        Error::Reqwest(e)
    }
}

{{#supportMiddleware}}
impl<T> From<reqwest_middleware::Error> for Error<T> {
    fn from(e: reqwest_middleware::Error) -> Self {
        Error::ReqwestMiddleware(e)
    }
}

{{/supportMiddleware}}
impl <T> From<serde_json::Error> for Error<T> {
    fn from(e: serde_json::Error) -> Self {
        Error::Serde(e)
    }
}

{{#useSerdePathToError}}
impl<T> From<serde_path_to_error::Error<serde_json::Error>> for Error<T> {
    fn from(e: serde_path_to_error::Error<serde_json::Error>) -> Self {
        Error::SerdePathToError(e)
    }
}

{{/useSerdePathToError}}
impl <T> From<std::io::Error> for Error<T> {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

fn parse_percent_encoded(bytes: &[u8; 3]) -> Option<u8> {
    if bytes[0] != b'%' { 
      return None;
    }
    let hi = hex_digit(bytes[1])?;
    let lo = hex_digit(bytes[2])?;
    Some((hi << 4) | lo)
}

pub fn urlencode<T: AsRef<str>>(s: T) -> String {
    ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes())
        .map(|string| {
            debug_assert!(
                !string.starts_with('%') || string.len() == 3,
                "the iterator should yield percent-encoded strings of exactly 3 bytes, or unescaped strings"
            );

            let parsed = match string.as_bytes().try_into() {
                Ok(bytes) => parse_percent_encoded(bytes),
                Err(_) => None,
            };

            // The VRChat API deviates from the application/x-www-form-urlencoded percent-encode set, for values like the InstanceID.
            // The characters bellow should remain unchanged for URI parameters, or requests will be rejected as malformed.
            match parsed {
                Some(b'(') => "(",
                Some(b')') => ")",
                _ => string
            }
        })
        .collect()
}

pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> {
    if let serde_json::Value::Object(object) = value {
        let mut params = vec![];

        for (key, value) in object {
            match value {
                serde_json::Value::Object(_) => params.append(&mut parse_deep_object(
                    &format!("{}[{}]", prefix, key),
                    value,
                )),
                serde_json::Value::Array(array) => {
                    for (i, value) in array.iter().enumerate() {
                        params.append(&mut parse_deep_object(
                            &format!("{}[{}][{}]", prefix, key, i),
                            value,
                        ));
                    }
                },
                serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())),
                _ => params.push((format!("{}[{}]", prefix, key), value.to_string())),
            }
        }

        return params;
    }

    unimplemented!("Only objects are supported with style=deepObject")
}

/// Internal use only
/// A content type supported by this client.
#[allow(dead_code)]
enum ContentType {
    Json,
    Text,
    Unsupported(String)
}

impl From<&str> for ContentType {
    fn from(content_type: &str) -> Self {
        if content_type.starts_with("application") && content_type.contains("json") {
            return Self::Json;
        } else if content_type.starts_with("text/plain") {
            return Self::Text;
        } else {
            return Self::Unsupported(content_type.to_string());
        }
    }
}

{{#apiInfo}}
{{#apis}}
pub mod {{{classFilename}}};
{{/apis}}
{{/apiInfo}}

pub mod configuration;