2024-04-24 23:41:42 -07:00
|
|
|
extern crate hyper;
|
|
|
|
|
extern crate serde;
|
|
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
use std::{path::PathBuf, str};
|
2024-04-24 23:41:42 -07:00
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
use crate::api::AuthenticationStore;
|
2025-05-01 18:07:18 -07:00
|
|
|
use crate::api::event_socket::EventSocket;
|
2024-06-14 20:26:56 -07:00
|
|
|
use hyper::{Body, Client, Method, Request, Uri};
|
2024-06-01 18:16:25 -07:00
|
|
|
|
2024-04-24 23:41:42 -07:00
|
|
|
use async_trait::async_trait;
|
2024-06-14 20:23:44 -07:00
|
|
|
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
2024-06-01 18:17:57 -07:00
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
use tokio::net::TcpStream;
|
|
|
|
|
|
|
|
|
|
use futures_util::{StreamExt, TryStreamExt};
|
2025-05-01 18:08:04 -07:00
|
|
|
use futures_util::stream::{SplitStream, SplitSink, Stream};
|
2025-05-01 18:07:18 -07:00
|
|
|
use futures_util::stream::BoxStream;
|
|
|
|
|
|
|
|
|
|
use tokio_tungstenite::connect_async;
|
|
|
|
|
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
|
|
|
|
|
|
2025-01-20 19:43:21 -08:00
|
|
|
use crate::{
|
2025-05-02 12:03:56 -07:00
|
|
|
model::{
|
|
|
|
|
Conversation,
|
|
|
|
|
ConversationID,
|
|
|
|
|
JwtToken,
|
|
|
|
|
Message,
|
|
|
|
|
MessageID,
|
|
|
|
|
UpdateItem,
|
|
|
|
|
Event,
|
|
|
|
|
OutgoingMessage,
|
|
|
|
|
},
|
|
|
|
|
|
2025-01-20 19:43:21 -08:00
|
|
|
APIInterface
|
|
|
|
|
};
|
2024-04-24 23:41:42 -07:00
|
|
|
|
|
|
|
|
type HttpClient = Client<hyper::client::HttpConnector>;
|
|
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
pub struct HTTPAPIClient<K: AuthenticationStore + Send + Sync> {
|
2024-04-24 23:41:42 -07:00
|
|
|
pub base_url: Uri,
|
2025-05-01 01:02:36 -07:00
|
|
|
pub auth_store: K,
|
2024-04-24 23:41:42 -07:00
|
|
|
client: HttpClient,
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
|
|
|
|
pub struct Credentials {
|
|
|
|
|
pub username: String,
|
|
|
|
|
pub password: String,
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-24 23:41:42 -07:00
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub enum Error {
|
|
|
|
|
ClientError(String),
|
|
|
|
|
HTTPError(hyper::Error),
|
|
|
|
|
SerdeError(serde_json::Error),
|
2024-06-01 18:16:25 -07:00
|
|
|
DecodeError,
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
|
|
|
|
|
2024-11-10 19:40:39 -08:00
|
|
|
impl std::error::Error for Error {
|
|
|
|
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
|
|
|
match self {
|
|
|
|
|
Error::HTTPError(ref err) => Some(err),
|
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Display for Error {
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
|
write!(f, "{:?}", self)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-24 23:41:42 -07:00
|
|
|
impl From <hyper::Error> for Error {
|
|
|
|
|
fn from(err: hyper::Error) -> Error {
|
|
|
|
|
Error::HTTPError(err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl From <serde_json::Error> for Error {
|
|
|
|
|
fn from(err: serde_json::Error) -> Error {
|
|
|
|
|
Error::SerdeError(err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
impl From <tungstenite::Error> for Error {
|
|
|
|
|
fn from(err: tungstenite::Error) -> Error {
|
|
|
|
|
Error::ClientError(err.to_string())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
trait AuthBuilder {
|
|
|
|
|
fn with_auth(self, token: &Option<JwtToken>) -> Self;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl AuthBuilder for hyper::http::request::Builder {
|
|
|
|
|
fn with_auth(self, token: &Option<JwtToken>) -> Self {
|
|
|
|
|
if let Some(token) = &token {
|
|
|
|
|
self.header("Authorization", token.to_header_value())
|
|
|
|
|
} else { self }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
#[cfg(test)]
|
|
|
|
|
#[allow(dead_code)]
|
2024-06-14 20:23:44 -07:00
|
|
|
trait AuthSetting {
|
|
|
|
|
fn authenticate(&mut self, token: &Option<JwtToken>);
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
#[cfg(test)]
|
2024-06-14 20:23:44 -07:00
|
|
|
impl<B> AuthSetting for hyper::http::Request<B> {
|
|
|
|
|
fn authenticate(&mut self, token: &Option<JwtToken>) {
|
|
|
|
|
if let Some(token) = &token {
|
|
|
|
|
self.headers_mut().insert("Authorization", token.to_header_value());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
type WebsocketSink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tungstenite::Message>;
|
|
|
|
|
type WebsocketStream = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
|
|
|
|
|
|
|
|
|
|
pub struct WebsocketEventSocket {
|
|
|
|
|
_sink: WebsocketSink,
|
|
|
|
|
stream: WebsocketStream,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl WebsocketEventSocket {
|
|
|
|
|
pub fn new(socket: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
|
|
|
|
|
let (sink, stream) = socket.split();
|
|
|
|
|
Self { _sink: sink, stream }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl WebsocketEventSocket {
|
|
|
|
|
fn raw_update_stream(self) -> impl Stream<Item = Result<Vec<UpdateItem>, Error>> {
|
|
|
|
|
self.stream
|
|
|
|
|
.map_err(Error::from)
|
|
|
|
|
.try_filter_map(|msg| async move {
|
|
|
|
|
match msg {
|
|
|
|
|
tungstenite::Message::Text(text) => {
|
|
|
|
|
serde_json::from_str::<Vec<UpdateItem>>(&text)
|
|
|
|
|
.map(Some)
|
|
|
|
|
.map_err(Error::from)
|
|
|
|
|
}
|
|
|
|
|
_ => Ok(None)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
|
impl EventSocket for WebsocketEventSocket {
|
|
|
|
|
type Error = Error;
|
|
|
|
|
type EventStream = BoxStream<'static, Result<Event, Error>>;
|
|
|
|
|
type UpdateStream = BoxStream<'static, Result<Vec<UpdateItem>, Error>>;
|
|
|
|
|
|
|
|
|
|
async fn events(self) -> Self::EventStream {
|
|
|
|
|
use futures_util::stream::iter;
|
|
|
|
|
|
|
|
|
|
self.raw_update_stream()
|
|
|
|
|
.map_ok(|updates| iter(updates.into_iter().map(|update| Ok(Event::from(update)))))
|
|
|
|
|
.try_flatten()
|
|
|
|
|
.boxed()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn raw_updates(self) -> Self::UpdateStream {
|
|
|
|
|
self.raw_update_stream().boxed()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-24 23:41:42 -07:00
|
|
|
#[async_trait]
|
2025-05-01 01:02:36 -07:00
|
|
|
impl<K: AuthenticationStore + Send + Sync> APIInterface for HTTPAPIClient<K> {
|
2024-04-24 23:41:42 -07:00
|
|
|
type Error = Error;
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
async fn get_version(&mut self) -> Result<String, Self::Error> {
|
2024-11-10 19:40:39 -08:00
|
|
|
let version: String = self.request("version", Method::GET).await?;
|
2024-04-24 23:41:42 -07:00
|
|
|
Ok(version)
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
async fn get_conversations(&mut self) -> Result<Vec<Conversation>, Self::Error> {
|
2024-11-10 19:40:39 -08:00
|
|
|
let conversations: Vec<Conversation> = self.request("conversations", Method::GET).await?;
|
2024-04-24 23:41:42 -07:00
|
|
|
Ok(conversations)
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
async fn authenticate(&mut self, credentials: Credentials) -> Result<JwtToken, Self::Error> {
|
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
|
|
|
struct AuthResponse {
|
|
|
|
|
jwt: String,
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
log::debug!("Authenticating with username: {:?}", credentials.username);
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
let body = || -> Body { serde_json::to_string(&credentials).unwrap().into() };
|
2024-11-10 19:40:39 -08:00
|
|
|
let token: AuthResponse = self.request_with_body_retry("authenticate", Method::POST, body, false).await?;
|
2024-06-14 20:23:44 -07:00
|
|
|
let token = JwtToken::new(&token.jwt).map_err(|_| Error::DecodeError)?;
|
2025-05-01 01:02:36 -07:00
|
|
|
|
|
|
|
|
log::debug!("Saving token: {:?}", token);
|
|
|
|
|
self.auth_store.set_token(token.clone()).await;
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
Ok(token)
|
|
|
|
|
}
|
2025-01-20 19:43:21 -08:00
|
|
|
|
2025-04-28 15:17:58 -07:00
|
|
|
async fn get_messages(
|
|
|
|
|
&mut self,
|
|
|
|
|
conversation_id: &ConversationID,
|
|
|
|
|
limit: Option<u32>,
|
|
|
|
|
before: Option<MessageID>,
|
|
|
|
|
after: Option<MessageID>,
|
|
|
|
|
) -> Result<Vec<Message>, Self::Error> {
|
|
|
|
|
let mut endpoint = format!("messages?guid={}", conversation_id);
|
|
|
|
|
|
|
|
|
|
if let Some(limit_val) = limit {
|
|
|
|
|
endpoint.push_str(&format!("&limit={}", limit_val));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(before_id) = before {
|
|
|
|
|
endpoint.push_str(&format!("&beforeMessageGUID={}", before_id));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(after_id) = after {
|
|
|
|
|
endpoint.push_str(&format!("&afterMessageGUID={}", after_id));
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-20 19:43:21 -08:00
|
|
|
let messages: Vec<Message> = self.request(&endpoint, Method::GET).await?;
|
|
|
|
|
Ok(messages)
|
|
|
|
|
}
|
2025-05-01 18:07:18 -07:00
|
|
|
|
2025-05-02 12:03:56 -07:00
|
|
|
async fn send_message(
|
|
|
|
|
&mut self,
|
|
|
|
|
outgoing_message: OutgoingMessage,
|
|
|
|
|
) -> Result<Message, Self::Error> {
|
|
|
|
|
let message: Message = self.request_with_body(
|
|
|
|
|
"sendMessage",
|
|
|
|
|
Method::POST,
|
|
|
|
|
|| serde_json::to_string(&outgoing_message).unwrap().into()
|
|
|
|
|
).await?;
|
|
|
|
|
|
|
|
|
|
Ok(message)
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
async fn open_event_socket(&mut self) -> Result<WebsocketEventSocket, Self::Error> {
|
|
|
|
|
use tungstenite::http::StatusCode;
|
|
|
|
|
use tungstenite::handshake::client::Request as TungsteniteRequest;
|
|
|
|
|
use tungstenite::handshake::client::generate_key;
|
|
|
|
|
|
|
|
|
|
let uri = self.uri_for_endpoint("updates", Some(self.websocket_scheme()));
|
|
|
|
|
|
|
|
|
|
log::debug!("Connecting to websocket: {:?}", uri);
|
|
|
|
|
|
|
|
|
|
let auth = self.auth_store.get_token().await;
|
|
|
|
|
let host = uri.authority().unwrap().host();
|
|
|
|
|
let mut request = TungsteniteRequest::builder()
|
|
|
|
|
.header("Host", host)
|
|
|
|
|
.header("Connection", "Upgrade")
|
|
|
|
|
.header("Upgrade", "websocket")
|
|
|
|
|
.header("Sec-WebSocket-Version", "13")
|
|
|
|
|
.header("Sec-WebSocket-Key", generate_key())
|
|
|
|
|
.uri(uri.to_string())
|
|
|
|
|
.body(())
|
|
|
|
|
.expect("Unable to build websocket request");
|
|
|
|
|
|
|
|
|
|
log::debug!("Websocket request: {:?}", request);
|
|
|
|
|
|
|
|
|
|
if let Some(token) = &auth {
|
|
|
|
|
let header_value = token.to_header_value().to_str().unwrap().parse().unwrap(); // ugh
|
|
|
|
|
request.headers_mut().insert("Authorization", header_value);
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 20:36:43 -07:00
|
|
|
let (socket, response) = connect_async(request).await.map_err(Error::from)?;
|
2025-05-01 18:07:18 -07:00
|
|
|
log::debug!("Websocket connected: {:?}", response.status());
|
|
|
|
|
|
|
|
|
|
if response.status() != StatusCode::SWITCHING_PROTOCOLS {
|
|
|
|
|
return Err(Error::ClientError("Websocket connection failed".into()));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(WebsocketEventSocket::new(socket))
|
|
|
|
|
}
|
2024-06-14 20:23:44 -07:00
|
|
|
}
|
2024-06-01 18:16:25 -07:00
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
impl<K: AuthenticationStore + Send + Sync> HTTPAPIClient<K> {
|
|
|
|
|
pub fn new(base_url: Uri, auth_store: K) -> HTTPAPIClient<K> {
|
2024-06-14 20:23:44 -07:00
|
|
|
HTTPAPIClient {
|
2024-06-14 20:26:56 -07:00
|
|
|
base_url,
|
2025-05-01 01:02:36 -07:00
|
|
|
auth_store,
|
2024-06-14 20:23:44 -07:00
|
|
|
client: Client::new(),
|
2024-06-01 18:16:25 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
fn uri_for_endpoint(&self, endpoint: &str, scheme: Option<&str>) -> Uri {
|
2024-04-24 23:41:42 -07:00
|
|
|
let mut parts = self.base_url.clone().into_parts();
|
|
|
|
|
let root_path: PathBuf = parts.path_and_query.unwrap().path().into();
|
|
|
|
|
let path = root_path.join(endpoint);
|
|
|
|
|
parts.path_and_query = Some(path.to_str().unwrap().parse().unwrap());
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
if let Some(scheme) = scheme {
|
|
|
|
|
parts.scheme = Some(scheme.parse().unwrap());
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-24 23:41:42 -07:00
|
|
|
Uri::try_from(parts).unwrap()
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
fn websocket_scheme(&self) -> &str {
|
|
|
|
|
if self.base_url.scheme().unwrap() == "https" {
|
|
|
|
|
"wss"
|
|
|
|
|
} else {
|
|
|
|
|
"ws"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
async fn request<T: DeserializeOwned>(&mut self, endpoint: &str, method: Method) -> Result<T, Error> {
|
2025-05-02 12:03:56 -07:00
|
|
|
self.request_with_body(endpoint, method, Body::empty).await
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
|
|
|
|
|
2025-05-02 12:03:56 -07:00
|
|
|
async fn request_with_body<T>(&mut self, endpoint: &str, method: Method, body_fn: impl Fn() -> Body) -> Result<T, Error>
|
|
|
|
|
where T: DeserializeOwned
|
2024-06-14 20:23:44 -07:00
|
|
|
{
|
|
|
|
|
self.request_with_body_retry(endpoint, method, body_fn, true).await
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-02 12:03:56 -07:00
|
|
|
async fn request_with_body_retry<T>(
|
2024-06-14 20:23:44 -07:00
|
|
|
&mut self,
|
|
|
|
|
endpoint: &str,
|
|
|
|
|
method: Method,
|
2025-05-02 12:03:56 -07:00
|
|
|
body_fn: impl Fn() -> Body,
|
2024-06-14 20:23:44 -07:00
|
|
|
retry_auth: bool) -> Result<T, Error>
|
|
|
|
|
where
|
|
|
|
|
T: DeserializeOwned,
|
|
|
|
|
{
|
|
|
|
|
use hyper::StatusCode;
|
|
|
|
|
|
2025-05-01 18:07:18 -07:00
|
|
|
let uri = self.uri_for_endpoint(endpoint, None);
|
2024-11-10 19:40:39 -08:00
|
|
|
log::debug!("Requesting {:?} {:?}", method, uri);
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
let build_request = move |auth: &Option<JwtToken>| {
|
|
|
|
|
let body = body_fn();
|
|
|
|
|
Request::builder()
|
|
|
|
|
.method(&method)
|
|
|
|
|
.uri(&uri)
|
|
|
|
|
.with_auth(auth)
|
|
|
|
|
.body(body)
|
|
|
|
|
.expect("Unable to build request")
|
|
|
|
|
};
|
|
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
let token = self.auth_store.get_token().await;
|
2025-04-27 14:01:19 -07:00
|
|
|
let request = build_request(&token);
|
2024-06-14 20:23:44 -07:00
|
|
|
let mut response = self.client.request(request).await?;
|
2024-11-10 19:40:39 -08:00
|
|
|
|
|
|
|
|
log::debug!("-> Response: {:}", response.status());
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
match response.status() {
|
|
|
|
|
StatusCode::OK => { /* cool */ },
|
|
|
|
|
|
|
|
|
|
// 401: Unauthorized. Token may have expired or is invalid. Attempt to renew.
|
|
|
|
|
StatusCode::UNAUTHORIZED => {
|
|
|
|
|
if !retry_auth {
|
|
|
|
|
return Err(Error::ClientError("Unauthorized".into()));
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
if let Some(credentials) = &self.auth_store.get_credentials().await {
|
|
|
|
|
log::debug!("Renewing token using credentials: u: {:?}", credentials.username);
|
|
|
|
|
let new_token = self.authenticate(credentials.clone()).await?;
|
2024-06-14 20:23:44 -07:00
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
let request = build_request(&Some(new_token));
|
2024-06-14 20:23:44 -07:00
|
|
|
response = self.client.request(request).await?;
|
2025-05-01 01:02:36 -07:00
|
|
|
} else {
|
|
|
|
|
return Err(Error::ClientError("Unauthorized, no credentials provided".into()));
|
2024-06-14 20:23:44 -07:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
// Other errors: bubble up.
|
|
|
|
|
_ => {
|
|
|
|
|
let message = format!("Request failed ({:})", response.status());
|
|
|
|
|
return Err(Error::ClientError(message));
|
|
|
|
|
}
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Read and parse response body
|
2024-06-14 20:23:44 -07:00
|
|
|
let body = hyper::body::to_bytes(response.into_body()).await?;
|
2024-06-01 18:16:25 -07:00
|
|
|
let parsed: T = match serde_json::from_slice(&body) {
|
|
|
|
|
Ok(result) => Ok(result),
|
|
|
|
|
Err(json_err) => {
|
2025-05-01 01:02:36 -07:00
|
|
|
log::error!("Error deserializing JSON: {:?}", json_err);
|
|
|
|
|
log::error!("Body: {:?}", String::from_utf8_lossy(&body));
|
|
|
|
|
|
2024-06-01 18:16:25 -07:00
|
|
|
// If JSON deserialization fails, try to interpret it as plain text
|
|
|
|
|
// Unfortunately the server does return things like this...
|
|
|
|
|
let s = str::from_utf8(&body).map_err(|_| Error::DecodeError)?;
|
|
|
|
|
serde_plain::from_str(s).map_err(|_| json_err)
|
|
|
|
|
}
|
|
|
|
|
}?;
|
2024-04-24 23:41:42 -07:00
|
|
|
|
|
|
|
|
Ok(parsed)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
#[cfg(test)]
|
2024-04-24 23:41:42 -07:00
|
|
|
mod test {
|
|
|
|
|
use super::*;
|
2025-05-01 01:02:36 -07:00
|
|
|
use crate::api::InMemoryAuthenticationStore;
|
2025-04-28 16:06:51 -07:00
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
#[cfg(test)]
|
2025-05-01 01:02:36 -07:00
|
|
|
fn local_mock_client() -> HTTPAPIClient<InMemoryAuthenticationStore> {
|
2024-04-24 23:41:42 -07:00
|
|
|
let base_url = "http://localhost:5738".parse().unwrap();
|
2025-05-01 01:02:36 -07:00
|
|
|
let credentials = Credentials {
|
2024-06-14 20:23:44 -07:00
|
|
|
username: "test".to_string(),
|
|
|
|
|
password: "test".to_string(),
|
|
|
|
|
};
|
|
|
|
|
|
2025-05-01 01:02:36 -07:00
|
|
|
HTTPAPIClient::new(base_url, InMemoryAuthenticationStore::new(Some(credentials)))
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
|
|
|
|
|
2025-01-20 22:13:44 -08:00
|
|
|
#[cfg(test)]
|
2024-04-24 23:41:42 -07:00
|
|
|
async fn mock_client_is_reachable() -> bool {
|
2024-06-14 20:23:44 -07:00
|
|
|
let mut client = local_mock_client();
|
2024-04-24 23:41:42 -07:00
|
|
|
let version = client.get_version().await;
|
2024-06-01 18:16:25 -07:00
|
|
|
|
|
|
|
|
match version {
|
|
|
|
|
Ok(_) => true,
|
|
|
|
|
Err(e) => {
|
2025-01-20 22:13:44 -08:00
|
|
|
log::error!("Mock client error: {:?}", e);
|
2024-06-01 18:16:25 -07:00
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn test_version() {
|
|
|
|
|
if !mock_client_is_reachable().await {
|
2024-06-01 18:16:25 -07:00
|
|
|
log::warn!("Skipping http_client tests (mock server not reachable)");
|
2024-04-24 23:41:42 -07:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
let mut client = local_mock_client();
|
2024-04-24 23:41:42 -07:00
|
|
|
let version = client.get_version().await.unwrap();
|
|
|
|
|
assert!(version.starts_with("KordophoneMock-"));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn test_conversations() {
|
|
|
|
|
if !mock_client_is_reachable().await {
|
2024-06-01 18:16:25 -07:00
|
|
|
log::warn!("Skipping http_client tests (mock server not reachable)");
|
2024-04-24 23:41:42 -07:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 20:23:44 -07:00
|
|
|
let mut client = local_mock_client();
|
2024-04-24 23:41:42 -07:00
|
|
|
let conversations = client.get_conversations().await.unwrap();
|
2024-06-01 18:17:57 -07:00
|
|
|
assert!(!conversations.is_empty());
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|
2025-01-20 19:43:21 -08:00
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn test_messages() {
|
|
|
|
|
if !mock_client_is_reachable().await {
|
|
|
|
|
log::warn!("Skipping http_client tests (mock server not reachable)");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mut client = local_mock_client();
|
|
|
|
|
let conversations = client.get_conversations().await.unwrap();
|
|
|
|
|
let conversation = conversations.first().unwrap();
|
2025-04-28 15:17:58 -07:00
|
|
|
let messages = client.get_messages(&conversation.guid, None, None, None).await.unwrap();
|
2025-01-20 19:43:21 -08:00
|
|
|
assert!(!messages.is_empty());
|
|
|
|
|
}
|
2025-05-01 18:07:18 -07:00
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn test_updates() {
|
|
|
|
|
if !mock_client_is_reachable().await {
|
|
|
|
|
log::warn!("Skipping http_client tests (mock server not reachable)");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mut client = local_mock_client();
|
|
|
|
|
|
|
|
|
|
// We just want to see if the connection is established, we won't wait for any events
|
|
|
|
|
let _ = client.open_event_socket().await.unwrap();
|
|
|
|
|
assert!(true);
|
|
|
|
|
}
|
2024-04-24 23:41:42 -07:00
|
|
|
}
|