screenshotbase 0.1.0

Rust client for the screenshotbase.com API
Documentation
//! Rust client for the screenshotbase.com API.
//!
//! Endpoints: `/status`, `/render`.

use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE, USER_AGENT};
use serde::{Deserialize, Serialize};

const DEFAULT_BASE_URL: &str = "https://api.screenshotbase.com/v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMethod {
    Header,
    QueryParam,
}

#[derive(thiserror::Error, Debug)]
pub enum ScreenshotBaseError {
    #[error("http error: {0}")]
    Http(#[from] reqwest::Error),

    #[error("api returned error: {0}")]
    Api(String),

    #[error("serialization error: {0}")]
    Serde(#[from] serde_json::Error),
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct StatusResponse {
    #[serde(default)]
    pub up: Option<bool>,
    #[serde(default)]
    pub status: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RenderResponse {
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
}

pub struct ScreenshotBaseClientBuilder {
    api_key: String,
    base_url: String,
    auth_method: AuthMethod,
    user_agent: Option<String>,
}

impl ScreenshotBaseClientBuilder {
    pub fn new<S: Into<String>>(api_key: S) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: DEFAULT_BASE_URL.to_string(),
            auth_method: AuthMethod::Header,
            user_agent: None,
        }
    }

    pub fn with_base_url<S: Into<String>>(mut self, base_url: S) -> Self {
        self.base_url = base_url.into();
        self
    }

    pub fn with_auth_method(mut self, method: AuthMethod) -> Self {
        self.auth_method = method;
        self
    }

    pub fn with_user_agent<S: Into<String>>(mut self, ua: S) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    pub fn build(self) -> ScreenshotBaseClient {
        let mut default_headers = HeaderMap::new();
        default_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        if let Some(ua) = self.user_agent.as_ref() {
            if let Ok(value) = HeaderValue::from_str(ua) {
                default_headers.insert(USER_AGENT, value);
            }
        } else {
            let _ = default_headers.insert(USER_AGENT, HeaderValue::from_static("screenshotbase-rs/0.1 (reqwest)"));
        }

        let http = reqwest::Client::builder()
            .default_headers(default_headers)
            .build()
            .expect("failed to build reqwest client");

        ScreenshotBaseClient {
            http,
            api_key: self.api_key,
            base_url: self.base_url,
            auth_method: self.auth_method,
        }
    }
}

pub struct ScreenshotBaseClient {
    http: reqwest::Client,
    api_key: String,
    base_url: String,
    auth_method: AuthMethod,
}

impl ScreenshotBaseClient {
    pub fn builder<S: Into<String>>(api_key: S) -> ScreenshotBaseClientBuilder {
        ScreenshotBaseClientBuilder::new(api_key)
    }

    pub fn new<S: Into<String>>(api_key: S) -> Self { Self::builder(api_key).build() }

    pub async fn status(&self) -> Result<StatusResponse, ScreenshotBaseError> {
        let url = self.join_path("/status");
        let req = self.apply_auth(self.http.get(url));
        let resp = req.send().await?;
        Self::handle_json_response::<StatusResponse>(resp).await
    }

    pub async fn render(&self, params: &[(&str, &str)]) -> Result<RenderResponse, ScreenshotBaseError> {
        let url = self.join_path("/render");
        let req = self.apply_auth(self.http.get(url).query(params));
        let resp = req.send().await?;
        Self::handle_json_response::<RenderResponse>(resp).await
    }

    fn join_path(&self, path: &str) -> String {
        let base = self.base_url.trim_end_matches('/');
        let child = path.trim_start_matches('/');
        format!("{}/{}", base, child)
    }

    fn apply_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match self.auth_method {
            AuthMethod::Header => req.header("apikey", &self.api_key),
            AuthMethod::QueryParam => req.query(&[("apikey", self.api_key.as_str())]),
        }
    }

    async fn handle_json_response<T: for<'de> Deserialize<'de>>(
        resp: reqwest::Response,
    ) -> Result<T, ScreenshotBaseError> {
        let status = resp.status();
        let text = resp.text().await?;
        if !status.is_success() {
            return Err(ScreenshotBaseError::Api(format!("HTTP {}: {}", status, text)));
        }
        let parsed: T = serde_json::from_str(&text)?;
        Ok(parsed)
    }
}