rustybook 0.2.1

An ergonomic Facebook client in Rust
Documentation
use std::sync::Arc;

use rustybook_http::ClientBuilder as HttpClientBuilder;
#[cfg(feature = "messenger")]
use rustybook_messenger::client::{
    MessengerClient,
    events::EventHandler,
};

use crate::{
    Inner,
    Rustybook,
    error::Error,
    session::SessionConfig,
};

/// Builder for creating a Rustybook client.
pub struct RustybookBuilder {
    redirect_limit: u32,
    cookies_file_path: String,
    user_agent: Option<String>,
    proxy: Option<String>,
    #[cfg(feature = "messenger")]
    handler: Option<Arc<dyn EventHandler>>,
}

impl Default for RustybookBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RustybookBuilder {
    /// Creates a builder with default options.
    pub fn new() -> Self {
        Self {
            redirect_limit: 10,
            cookies_file_path: String::new(),
            user_agent: None,
            proxy: None,
            #[cfg(feature = "messenger")]
            handler: None,
        }
    }

    /// Sets cookie JSON path used for shared HTTP session and messenger auth.
    pub fn cookies_file_path(mut self, path: impl Into<String>) -> Self {
        self.cookies_file_path = path.into();
        self
    }

    /// Sets a custom user agent header.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Sets an HTTP proxy URL.
    pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
        self.proxy = Some(proxy.into());
        self
    }

    #[cfg(feature = "messenger")]
    pub fn handler(mut self, handler: Arc<dyn EventHandler>) -> Self {
        self.handler = Some(handler);
        self
    }

    /// Builds a Rustybook client.
    pub fn build(self) -> Result<Rustybook, Error> {
        let session = SessionConfig::from_file(&self.cookies_file_path)?;

        let mut builder = HttpClientBuilder::new()
            .cookie_header(session.cookie_header.clone())
            .max_redirect(self.redirect_limit);

        if let Some(user_agent) = self.user_agent.as_deref() {
            builder = builder.user_agent(user_agent.to_string());
        }

        if let Some(proxy) = self.proxy.as_deref() {
            builder = builder.proxy(proxy.to_string());
        }

        let http = builder.build()?;

        #[cfg(feature = "messenger")]
        let messenger = MessengerClient::builder()
            .shared_session(
                session.user_id.clone(),
                session.cookie_header.clone(),
                http.clone(),
            )
            .build()?;

        Ok(Rustybook {
            inner: Arc::new(Inner {
                http,
                #[cfg(feature = "messenger")]
                messenger,
                #[cfg(feature = "messenger")]
                handler: self.handler,
            }),
        })
    }
}