use std::sync::Arc;
pub use client::Client;
pub use reqwest;
pub(crate) use reqwest::{
cookie::{CookieStore, Jar},
header,
};
use crate::{errors::session::SessionError, session::access_info::AccessInfos};
pub mod access_info;
mod client;
#[derive(Clone, Debug)]
pub struct Session {
cookie_jar: Arc<Jar>,
pub(crate) is_login: bool,
pub(crate) access_infos: AccessInfos,
}
impl Session {
pub fn new() -> Self {
Session {
cookie_jar: Arc::new(Jar::default()),
is_login: false,
access_infos: AccessInfos::default(),
}
}
pub async fn execute(
&self,
mut builder: reqwest::RequestBuilder,
) -> Result<reqwest::Response, SessionError> {
let builder_cloned = builder
.try_clone()
.expect(
"RequestBuilder can't be cloned which is unexpected as stream request body should not exist in current api",
)
.build()?;
let cookie_header = self.cookie_jar.cookies(builder_cloned.url());
if let Some(cookie_header) = cookie_header {
builder = builder.header(header::COOKIE, cookie_header)
};
let response = builder.send().await?;
let response_url = response.url().clone();
let headers = response.headers().clone();
for cookie_str in headers
.get_all(header::SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
{
self.cookie_jar.add_cookie_str(cookie_str, &response_url);
}
Ok(response)
}
}
impl Session {
pub fn is_login(&self) -> bool {
self.is_login
}
pub fn access_infos(&self) -> &AccessInfos {
&self.access_infos
}
pub fn set_access_infos(self, infos: AccessInfos) -> Self {
Session {
access_infos: infos,
..self
}
}
}
impl Default for Session {
fn default() -> Self {
Session::new()
}
}