#![allow(clippy::derive_partial_eq_without_eq)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::nonstandard_macro_braces)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::tabs_in_doc_comments)]
#![allow(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod booking_data;
pub mod types;
#[doc(hidden)]
pub mod utils;
pub use reqwest::{header::HeaderMap, StatusCode};
#[derive(Debug)]
pub struct Response<T> {
pub status: reqwest::StatusCode,
pub headers: reqwest::header::HeaderMap,
pub body: T,
}
impl<T> Response<T> {
pub fn new(status: reqwest::StatusCode, headers: reqwest::header::HeaderMap, body: T) -> Self {
Self {
status,
headers,
body,
}
}
}
type ClientResult<T> = Result<T, ClientError>;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ClientError {
#[error(transparent)]
FromUtf8Error(#[from] std::string::FromUtf8Error),
#[error(transparent)]
UrlParserError(#[from] url::ParseError),
#[error(transparent)]
SerdeJsonError(#[from] serde_json::Error),
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error(transparent)]
InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),
#[error(transparent)]
ReqwestMiddleWareError(#[from] reqwest_middleware::Error),
#[error("HTTP Error. Code: {status}, message: {error}")]
HttpError {
status: http::StatusCode,
headers: reqwest::header::HeaderMap,
error: String,
},
}
pub const FALLBACK_HOST: &str = "https://api.tripactions.com";
mod progenitor_support {
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
const PATH_SET: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}');
#[allow(dead_code)]
pub(crate) fn encode_path(pc: &str) -> String {
utf8_percent_encode(pc, PATH_SET).to_string()
}
}
#[derive(Debug, Default)]
pub(crate) struct Message {
pub body: Option<reqwest::Body>,
pub content_type: Option<String>,
}
use std::env;
const TOKEN_ENDPOINT: &str = "https://api.tripactions.com/ta-auth/oauth/token";
#[derive(Clone)]
pub struct Client {
host: String,
host_override: Option<String>,
token: String,
client_id: String,
client_secret: String,
client: reqwest_middleware::ClientWithMiddleware,
}
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, JsonSchema, Clone, Default, Serialize, Deserialize)]
pub struct AccessToken {
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub token_type: String,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub access_token: String,
#[serde(default)]
pub expires_in: i64,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub refresh_token: String,
#[serde(default, alias = "x_refresh_token_expires_in")]
pub refresh_token_expires_in: i64,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub scope: String,
}
impl Client {
pub fn new<I, K, T>(client_id: I, client_secret: K, token: T) -> Self
where
I: ToString,
K: ToString,
T: ToString,
{
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build();
let retry_policy =
reqwest_retry::policies::ExponentialBackoff::builder().build_with_max_retries(3);
match client {
Ok(c) => {
let client = reqwest_middleware::ClientBuilder::new(c)
.with(reqwest_tracing::TracingMiddleware::default())
.with(reqwest_conditional_middleware::ConditionalMiddleware::new(
reqwest_retry::RetryTransientMiddleware::new_with_policy(retry_policy),
|req: &reqwest::Request| req.try_clone().is_some(),
))
.build();
let host = FALLBACK_HOST.to_string();
Client {
host,
host_override: None,
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
token: token.to_string(),
client,
}
}
Err(e) => panic!("creating reqwest client failed: {:?}", e),
}
}
pub fn with_host_override<H>(&mut self, host: H) -> &mut Self
where
H: ToString,
{
self.host_override = Some(host.to_string());
self
}
pub fn remove_host_override(&mut self) -> &mut Self {
self.host_override = None;
self
}
pub fn get_host_override(&self) -> Option<&str> {
self.host_override.as_deref()
}
pub(crate) fn url(&self, path: &str, host: Option<&str>) -> String {
format!(
"{}{}",
self.get_host_override()
.or(host)
.unwrap_or(self.host.as_str()),
path
)
}
pub fn new_from_env<T>(token: T) -> Self
where
T: ToString,
{
let client_id = env::var("TRIPACTIONS_CLIENT_ID").expect("must set TRIPACTIONS_CLIENT_ID");
let client_secret =
env::var("TRIPACTIONS_CLIENT_SECRET").expect("must set TRIPACTIONS_CLIENT_SECRET");
Client::new(client_id, client_secret, token)
}
pub async fn get_access_token(&mut self) -> ClientResult<AccessToken> {
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
let params = [
("grant_type", "client_credentials"),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
let client = reqwest::Client::new();
let resp = client
.post(TOKEN_ENDPOINT)
.headers(headers)
.form(¶ms)
.basic_auth(&self.client_id, Some(&self.client_secret))
.send()
.await?;
let t: AccessToken = resp.json().await?;
self.token = t.access_token.to_string();
Ok(t)
}
async fn url_and_auth(&self, uri: &str) -> ClientResult<(reqwest::Url, Option<String>)> {
let parsed_url = uri.parse::<reqwest::Url>()?;
let auth = format!("Bearer {}", self.token);
Ok((parsed_url, Some(auth)))
}
async fn request_raw(
&self,
method: reqwest::Method,
uri: &str,
message: Message,
) -> ClientResult<reqwest::Response> {
let (url, auth) = self.url_and_auth(uri).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method.clone(), url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
if let Some(content_type) = &message.content_type {
req = req.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_str(content_type).unwrap(),
);
} else {
req = req.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
}
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
if let Some(body) = message.body {
req = req.body(body);
}
Ok(req.send().await?)
}
async fn request<Out>(
&self,
method: reqwest::Method,
uri: &str,
message: Message,
) -> ClientResult<crate::Response<Out>>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let response = self.request_raw(method, uri, message).await?;
let status = response.status();
let headers = response.headers().clone();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")?
} else {
serde_json::from_slice::<Out>(&response_body)?
};
Ok(crate::Response::new(status, headers, parsed_response))
} else {
let error = if response_body.is_empty() {
ClientError::HttpError {
status,
headers,
error: "empty response".into(),
}
} else {
ClientError::HttpError {
status,
headers,
error: String::from_utf8_lossy(&response_body).into(),
}
};
Err(error)
}
}
async fn request_with_links<Out>(
&self,
method: http::Method,
uri: &str,
message: Message,
) -> ClientResult<(Option<crate::utils::NextLink>, crate::Response<Out>)>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let response = self.request_raw(method, uri, message).await?;
let status = response.status();
let headers = response.headers().clone();
let link = response
.headers()
.get(http::header::LINK)
.and_then(|l| l.to_str().ok())
.and_then(|l| parse_link_header::parse(l).ok())
.as_ref()
.and_then(crate::utils::next_link);
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")?
} else {
serde_json::from_slice::<Out>(&response_body)?
};
Ok((link, crate::Response::new(status, headers, parsed_response)))
} else {
let error = if response_body.is_empty() {
ClientError::HttpError {
status,
headers,
error: "empty response".into(),
}
} else {
ClientError::HttpError {
status,
headers,
error: String::from_utf8_lossy(&response_body).into(),
}
};
Err(error)
}
}
#[allow(dead_code)]
async fn post_form<Out>(
&self,
uri: &str,
form: reqwest::multipart::Form,
) -> ClientResult<crate::Response<Out>>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let (url, auth) = self.url_and_auth(uri).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(http::Method::POST, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
req = req.multipart(form);
let response = req.send().await?;
let status = response.status();
let headers = response.headers().clone();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")?
} else if std::any::TypeId::of::<Out>() == std::any::TypeId::of::<String>() {
let s = String::from_utf8(response_body.to_vec())?;
serde_json::from_value(serde_json::json!(&s))?
} else {
serde_json::from_slice::<Out>(&response_body)?
};
Ok(crate::Response::new(status, headers, parsed_response))
} else {
let error = if response_body.is_empty() {
ClientError::HttpError {
status,
headers,
error: "empty response".into(),
}
} else {
ClientError::HttpError {
status,
headers,
error: String::from_utf8_lossy(&response_body).into(),
}
};
Err(error)
}
}
#[allow(dead_code)]
async fn request_with_accept_mime<Out>(
&self,
method: reqwest::Method,
uri: &str,
accept_mime_type: &str,
) -> ClientResult<crate::Response<Out>>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let (url, auth) = self.url_and_auth(uri).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_str(accept_mime_type)?,
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
let response = req.send().await?;
let status = response.status();
let headers = response.headers().clone();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")?
} else if std::any::TypeId::of::<Out>() == std::any::TypeId::of::<String>() {
let s = String::from_utf8(response_body.to_vec())?;
serde_json::from_value(serde_json::json!(&s))?
} else {
serde_json::from_slice::<Out>(&response_body)?
};
Ok(crate::Response::new(status, headers, parsed_response))
} else {
let error = if response_body.is_empty() {
ClientError::HttpError {
status,
headers,
error: "empty response".into(),
}
} else {
ClientError::HttpError {
status,
headers,
error: String::from_utf8_lossy(&response_body).into(),
}
};
Err(error)
}
}
#[allow(dead_code)]
async fn request_with_mime<Out>(
&self,
method: reqwest::Method,
uri: &str,
content: &[u8],
mime_type: &str,
) -> ClientResult<crate::Response<Out>>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let (url, auth) = self.url_and_auth(uri).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
req = req.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_bytes(mime_type.as_bytes()).unwrap(),
);
req = req.header(
reqwest::header::HeaderName::from_static("x-upload-content-type"),
reqwest::header::HeaderValue::from_static("application/octet-stream"),
);
req = req.header(
reqwest::header::HeaderName::from_static("x-upload-content-length"),
reqwest::header::HeaderValue::from_bytes(format!("{}", content.len()).as_bytes())
.unwrap(),
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
if content.len() > 1 {
let b = bytes::Bytes::copy_from_slice(content);
req = req.body(b);
}
let response = req.send().await?;
let status = response.status();
let headers = response.headers().clone();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")?
} else {
serde_json::from_slice::<Out>(&response_body)?
};
Ok(crate::Response::new(status, headers, parsed_response))
} else {
let error = if response_body.is_empty() {
ClientError::HttpError {
status,
headers,
error: "empty response".into(),
}
} else {
ClientError::HttpError {
status,
headers,
error: String::from_utf8_lossy(&response_body).into(),
}
};
Err(error)
}
}
async fn request_entity<D>(
&self,
method: http::Method,
uri: &str,
message: Message,
) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
let r = self.request(method, uri, message).await?;
Ok(r)
}
#[allow(dead_code)]
async fn get<D>(&self, uri: &str, message: Message) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::GET, uri, message).await
}
#[allow(dead_code)]
async fn get_all_pages<D>(&self, uri: &str, _message: Message) -> ClientResult<Response<Vec<D>>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.unfold(uri).await
}
#[allow(dead_code)]
async fn unfold<D>(&self, uri: &str) -> ClientResult<crate::Response<Vec<D>>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
let mut global_items = Vec::new();
let (new_link, mut response) = self.get_pages(uri).await?;
let mut link = new_link;
while !response.body.is_empty() {
global_items.append(&mut response.body);
if let Some(url) = &link {
let url = reqwest::Url::parse(&url.0)?;
let (new_link, new_response) = self.get_pages_url(&url).await?;
link = new_link;
response = new_response;
}
}
Ok(Response::new(
response.status,
response.headers,
global_items,
))
}
#[allow(dead_code)]
async fn get_pages<D>(
&self,
uri: &str,
) -> ClientResult<(Option<crate::utils::NextLink>, crate::Response<Vec<D>>)>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_with_links(http::Method::GET, uri, Message::default())
.await
}
#[allow(dead_code)]
async fn get_pages_url<D>(
&self,
url: &reqwest::Url,
) -> ClientResult<(Option<crate::utils::NextLink>, crate::Response<Vec<D>>)>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_with_links(http::Method::GET, url.as_str(), Message::default())
.await
}
#[allow(dead_code)]
async fn post<D>(&self, uri: &str, message: Message) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::POST, uri, message).await
}
#[allow(dead_code)]
async fn patch<D>(&self, uri: &str, message: Message) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::PATCH, uri, message).await
}
#[allow(dead_code)]
async fn put<D>(&self, uri: &str, message: Message) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::PUT, uri, message).await
}
#[allow(dead_code)]
async fn delete<D>(&self, uri: &str, message: Message) -> ClientResult<crate::Response<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::DELETE, uri, message)
.await
}
pub fn booking_data(&self) -> booking_data::BookingData {
booking_data::BookingData::new(self.clone())
}
}