use std::fmt;
use std::sync::Arc;
use crate::client::{
ClientBuilder, GetImage, GetMarkdown, GetPageSource, GetPageWithCookies, GetParsed,
ListElements, Plugin, Serp,
};
use crate::error::{Error, Result};
use crate::request::{Call, Decode};
#[derive(Clone)]
pub struct Client {
inner: crate::Client,
runtime: Arc<tokio::runtime::Runtime>,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("blocking::Client")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
impl Client {
pub fn new(api_key: impl Into<String>) -> Result<Self> {
Self::wrap(crate::Client::new(api_key)?)
}
pub fn from_env() -> Result<Self> {
Self::wrap(crate::Client::from_env()?)
}
pub fn from_builder(builder: ClientBuilder) -> Result<Self> {
Self::wrap(builder.build()?)
}
fn wrap(inner: crate::Client) -> Result<Self> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| Error::Config(format!("could not start the blocking runtime: {e}")))?;
Ok(Client {
inner,
runtime: Arc::new(runtime),
})
}
pub(crate) fn execute<T: Decode>(&self, call: Call) -> Result<T> {
self.runtime.block_on(self.inner.execute(call))
}
pub fn get_page_source(&self, url: impl Into<String>) -> GetPageSource<Client> {
GetPageSource::new(self.clone(), url.into())
}
pub fn list_elements(&self, url: impl Into<String>) -> ListElements<Client> {
ListElements::new(self.clone(), url.into())
}
pub fn get_markdown(&self, url: impl Into<String>) -> GetMarkdown<Client> {
GetMarkdown::new(self.clone(), url.into())
}
pub fn get_parsed(&self, url: impl Into<String>) -> GetParsed<Client> {
GetParsed::new(self.clone(), url.into())
}
pub fn get_page_with_cookies(&self, url: impl Into<String>) -> GetPageWithCookies<Client> {
GetPageWithCookies::new(self.clone(), url.into())
}
pub fn serp(&self, keyword: impl Into<String>) -> Serp<Client> {
Serp::new(self.clone(), keyword.into())
}
pub fn get_image(&self, url: impl Into<String>) -> GetImage<Client> {
GetImage::new(self.clone(), url.into())
}
pub fn plugin(&self, path: impl Into<String>) -> Plugin<Client> {
Plugin::new(self.clone(), path.into())
}
}