Private
Public Access
1
0

Add 'core/' from commit 'b0dfc4146ca0da535a87f8509aec68817fb2ab14'

git-subtree-dir: core
git-subtree-mainline: a07f3dcd23
git-subtree-split: b0dfc4146c
This commit is contained in:
2025-09-06 19:33:33 -07:00
83 changed files with 12352 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
use crate::api::Credentials;
use crate::api::JwtToken;
use async_trait::async_trait;
#[async_trait]
pub trait AuthenticationStore {
async fn get_credentials(&mut self) -> Option<Credentials>;
async fn get_token(&mut self) -> Option<String>;
async fn set_token(&mut self, token: String);
}
pub struct InMemoryAuthenticationStore {
credentials: Option<Credentials>,
token: Option<JwtToken>,
}
impl Default for InMemoryAuthenticationStore {
fn default() -> Self {
Self::new(None)
}
}
impl InMemoryAuthenticationStore {
pub fn new(credentials: Option<Credentials>) -> Self {
Self {
credentials,
token: None,
}
}
}
#[async_trait]
impl AuthenticationStore for InMemoryAuthenticationStore {
async fn get_credentials(&mut self) -> Option<Credentials> {
self.credentials.clone()
}
async fn get_token(&mut self) -> Option<String> {
self.token.clone().map(|token| token.to_string())
}
async fn set_token(&mut self, token: String) {
self.token = Some(JwtToken::new(&token).unwrap());
}
}

View File

@@ -0,0 +1,38 @@
use crate::model::event::Event;
use crate::model::update::UpdateItem;
use async_trait::async_trait;
use futures_util::stream::Stream;
use futures_util::Sink;
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum SinkMessage {
Ping,
}
pub enum SocketUpdate {
Update(Vec<UpdateItem>),
Pong,
}
pub enum SocketEvent {
Update(Event),
Pong,
}
#[async_trait]
pub trait EventSocket {
type Error;
type EventStream: Stream<Item = Result<SocketEvent, Self::Error>>;
type UpdateStream: Stream<Item = Result<SocketUpdate, Self::Error>>;
/// Modern event pipeline
async fn events(
self,
) -> (
Self::EventStream,
impl Sink<SinkMessage, Error = Self::Error>,
);
/// Raw update items from the v1 API.
async fn raw_updates(self) -> Self::UpdateStream;
}

View File

@@ -0,0 +1,710 @@
extern crate hyper;
extern crate serde;
use std::{path::PathBuf, pin::Pin, str, task::Poll};
use crate::api::event_socket::{EventSocket, SinkMessage, SocketEvent, SocketUpdate};
use crate::api::AuthenticationStore;
use bytes::Bytes;
use hyper::{Body, Client, Method, Request, Uri};
use hyper_tls::HttpsConnector;
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tokio::net::TcpStream;
use futures_util::stream::{BoxStream, Stream};
use futures_util::task::Context;
use futures_util::{Sink, SinkExt, StreamExt, TryStreamExt};
use tokio_tungstenite::connect_async;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use crate::{
model::{
Conversation, ConversationID, Event, JwtToken, Message, MessageID, OutgoingMessage,
UpdateItem,
},
APIInterface,
};
type HttpClient = Client<HttpsConnector<hyper::client::HttpConnector>>;
pub struct HTTPAPIClient<K: AuthenticationStore + Send + Sync> {
pub base_url: Uri,
pub auth_store: K,
client: HttpClient,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Credentials {
pub username: String,
pub password: String,
}
#[derive(Debug)]
pub enum Error {
ClientError(String),
HTTPError(hyper::Error),
SerdeError(serde_json::Error),
DecodeError(String),
PongError(tungstenite::Error),
URLError,
Unauthorized,
}
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)
}
}
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)
}
}
impl From<tungstenite::Error> for Error {
fn from(err: tungstenite::Error) -> Error {
Error::ClientError(err.to_string())
}
}
trait AuthBuilder {
fn with_auth_string(self, token: &Option<String>) -> Self;
}
impl AuthBuilder for hyper::http::request::Builder {
fn with_auth_string(self, token: &Option<String>) -> Self {
if let Some(token) = &token {
self.header("Authorization", format!("Bearer: {}", token))
} else {
self
}
}
}
#[cfg(test)]
#[allow(dead_code)]
trait AuthSetting {
fn authenticate(&mut self, token: &Option<JwtToken>);
}
#[cfg(test)]
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());
}
}
}
type WebsocketSink = futures_util::stream::SplitSink<
WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
tungstenite::Message,
>;
type WebsocketStream =
futures_util::stream::SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
pub struct WebsocketEventSocket {
sink: Option<WebsocketSink>,
stream: WebsocketStream,
}
impl WebsocketEventSocket {
pub fn new(socket: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
let (sink, stream) = socket.split();
Self {
sink: Some(sink),
stream,
}
}
}
impl WebsocketEventSocket {
fn raw_update_stream(self) -> impl Stream<Item = Result<SocketUpdate, Error>> {
self.stream
.map_err(Error::from)
.try_filter_map(|msg| async move {
match msg {
tungstenite::Message::Text(text) => {
match serde_json::from_str::<Vec<UpdateItem>>(&text) {
Ok(updates) => Ok(Some(SocketUpdate::Update(updates))),
Err(e) => {
log::error!("Error parsing update: {:?}", e);
Err(Error::from(e))
}
}
}
tungstenite::Message::Ping(_) => {
// We don't expect the server to send us pings.
Ok(None)
}
tungstenite::Message::Pong(_) => Ok(Some(SocketUpdate::Pong)),
tungstenite::Message::Close(_) => {
// Connection was closed cleanly
Err(Error::ClientError("WebSocket connection closed".into()))
}
_ => Ok(None),
}
})
}
}
#[async_trait]
impl EventSocket for WebsocketEventSocket {
type Error = Error;
type EventStream = BoxStream<'static, Result<SocketEvent, Error>>;
type UpdateStream = BoxStream<'static, Result<SocketUpdate, Error>>;
async fn events(
mut self,
) -> (
Self::EventStream,
impl Sink<SinkMessage, Error = Self::Error>,
) {
use futures_util::stream::iter;
let sink = self.sink.take().unwrap().with(|f| match f {
SinkMessage::Ping => futures_util::future::ready(Ok::<tungstenite::Message, Error>(
tungstenite::Message::Ping(Bytes::new()),
)),
});
let stream = self
.raw_update_stream()
.map_ok(
|updates| -> BoxStream<'static, Result<SocketEvent, Error>> {
match updates {
SocketUpdate::Update(updates) => {
let iter_stream = iter(
updates
.into_iter()
.map(|u| Ok(SocketEvent::Update(Event::from(u)))),
);
iter_stream.boxed()
}
SocketUpdate::Pong => iter(std::iter::once(Ok(SocketEvent::Pong))).boxed(),
}
},
)
.try_flatten()
.boxed();
(stream, sink)
}
async fn raw_updates(self) -> Self::UpdateStream {
self.raw_update_stream().boxed()
}
}
pub struct ResponseStream {
body: hyper::Body,
}
impl Stream for ResponseStream {
type Item = Result<Bytes, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.body.poll_next_unpin(cx).map_err(Error::HTTPError)
}
}
impl From<hyper::Body> for ResponseStream {
fn from(value: hyper::Body) -> Self {
ResponseStream { body: value }
}
}
#[async_trait]
impl<K: AuthenticationStore + Send + Sync> APIInterface for HTTPAPIClient<K> {
type Error = Error;
type ResponseStream = ResponseStream;
async fn get_version(&mut self) -> Result<String, Self::Error> {
let version: String = self.deserialized_response("version", Method::GET).await?;
Ok(version)
}
async fn get_conversations(&mut self) -> Result<Vec<Conversation>, Self::Error> {
let conversations: Vec<Conversation> = self
.deserialized_response("conversations", Method::GET)
.await?;
Ok(conversations)
}
async fn authenticate(&mut self, credentials: Credentials) -> Result<JwtToken, Self::Error> {
#[derive(Deserialize, Debug)]
struct AuthResponse {
jwt: String,
}
log::debug!("Authenticating with username: {:?}", credentials.username);
let body = || -> Body { serde_json::to_string(&credentials).unwrap().into() };
let token: AuthResponse = self
.deserialized_response_with_body_retry("authenticate", Method::POST, body, false)
.await?;
let token = JwtToken::new(&token.jwt).map_err(|e| Error::DecodeError(e.to_string()))?;
log::debug!("Saving token: {:?}", token);
self.auth_store.set_token(token.to_string()).await;
Ok(token)
}
async fn mark_conversation_as_read(
&mut self,
conversation_id: &ConversationID,
) -> Result<(), Self::Error> {
// SERVER JANK: This should be POST, but it's GET for some reason.
let endpoint = format!("markConversation?guid={}", conversation_id);
self.response_with_body_retry(&endpoint, Method::GET, Body::empty, true)
.await?;
Ok(())
}
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));
}
let messages: Vec<Message> = self.deserialized_response(&endpoint, Method::GET).await?;
Ok(messages)
}
async fn send_message(
&mut self,
outgoing_message: &OutgoingMessage,
) -> Result<Message, Self::Error> {
let message: Message = self
.deserialized_response_with_body("sendMessage", Method::POST, || {
serde_json::to_string(&outgoing_message).unwrap().into()
})
.await?;
Ok(message)
}
async fn fetch_attachment_data(
&mut self,
guid: &str,
preview: bool,
) -> Result<ResponseStream, Self::Error> {
let endpoint = format!("attachment?guid={}&preview={}", guid, preview);
self.response_with_body_retry(&endpoint, Method::GET, Body::empty, true)
.await
.map(hyper::Response::into_body)
.map(ResponseStream::from)
}
async fn upload_attachment<R>(
&mut self,
mut data: tokio::io::BufReader<R>,
filename: &str,
_size: u64,
) -> Result<String, Self::Error>
where
R: tokio::io::AsyncRead + Unpin + Send + Sync + 'static,
{
use tokio::io::AsyncReadExt;
#[derive(Deserialize, Debug)]
struct UploadAttachmentResponse {
#[serde(rename = "fileTransferGUID")]
guid: String,
}
// TODO: We can still use Body::wrap_stream here, but we need to make sure to plumb the CONTENT_LENGTH header,
// otherwise CocoaHTTPServer will crash because of a bug.
//
// See ff03e73758f30c081a9319a8c04025cba69b8393 for what this was like before.
let mut bytes = Vec::new();
data.read_to_end(&mut bytes)
.await
.map_err(|e| Error::ClientError(e.to_string()))?;
let encoded_filename = urlencoding::encode(filename);
let endpoint = format!("uploadAttachment?filename={}", encoded_filename);
let mut bytes_opt = Some(bytes);
let response: UploadAttachmentResponse = self
.deserialized_response_with_body_retry(
&endpoint,
Method::POST,
move || {
Body::from(
bytes_opt
.take()
.expect("Body already consumed during retry"),
)
},
false,
)
.await?;
Ok(response.guid)
}
async fn open_event_socket(
&mut self,
update_seq: Option<u64>,
) -> Result<WebsocketEventSocket, Self::Error> {
use tungstenite::handshake::client::generate_key;
use tungstenite::handshake::client::Request as TungsteniteRequest;
let endpoint = match update_seq {
Some(seq) => format!("updates?seq={}", seq),
None => "updates".to_string(),
};
let uri = self
.uri_for_endpoint(&endpoint, 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");
match &auth {
Some(token) => {
request.headers_mut().insert(
"Authorization",
format!("Bearer: {}", token).parse().unwrap(),
);
}
None => {
log::warn!(target: "websocket", "Proceeding without auth token.");
}
}
log::debug!("Websocket request: {:?}", request);
match connect_async(request).await.map_err(Error::from) {
Ok((socket, response)) => {
log::debug!("Websocket connected: {:?}", response.status());
Ok(WebsocketEventSocket::new(socket))
}
Err(e) => match &e {
Error::ClientError(ce) => match ce.as_str() {
"HTTP error: 401 Unauthorized" | "Unauthorized" => {
// Try to authenticate
if let Some(credentials) = &self.auth_store.get_credentials().await {
log::warn!("Websocket connection failed, attempting to authenticate");
let new_token = self.authenticate(credentials.clone()).await?;
self.auth_store.set_token(new_token.to_string()).await;
// try again on the next attempt.
return Err(Error::Unauthorized);
} else {
log::error!("Websocket unauthorized, no credentials provided");
return Err(Error::ClientError(
"Unauthorized, no credentials provided".into(),
));
}
}
_ => Err(e),
},
_ => Err(e),
},
}
}
}
impl<K: AuthenticationStore + Send + Sync> HTTPAPIClient<K> {
pub fn new(base_url: Uri, auth_store: K) -> HTTPAPIClient<K> {
let https = HttpsConnector::new();
let client = Client::builder().build::<_, Body>(https);
HTTPAPIClient { base_url, auth_store, client }
}
fn uri_for_endpoint(&self, endpoint: &str, scheme: Option<&str>) -> Result<Uri, Error> {
let mut parts = self.base_url.clone().into_parts();
let root_path: PathBuf = parts
.path_and_query
.ok_or(Error::URLError)?
.path()
.into();
let path = root_path.join(endpoint);
let path_str = path.to_str().ok_or(Error::URLError)?;
parts.path_and_query = Some(path_str.parse().map_err(|_| Error::URLError)?);
if let Some(scheme) = scheme {
parts.scheme = Some(scheme.parse().map_err(|_| Error::URLError)?);
}
Uri::try_from(parts).map_err(|_| Error::URLError)
}
fn websocket_scheme(&self) -> &str {
if self.base_url.scheme().unwrap() == "https" {
"wss"
} else {
"ws"
}
}
async fn deserialized_response<T: DeserializeOwned>(
&mut self,
endpoint: &str,
method: Method,
) -> Result<T, Error> {
self.deserialized_response_with_body(endpoint, method, Body::empty)
.await
}
async fn deserialized_response_with_body<T>(
&mut self,
endpoint: &str,
method: Method,
body_fn: impl FnMut() -> Body,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
self.deserialized_response_with_body_retry(endpoint, method, body_fn, true)
.await
}
async fn deserialized_response_with_body_retry<T>(
&mut self,
endpoint: &str,
method: Method,
body_fn: impl FnMut() -> Body,
retry_auth: bool,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
let response = self
.response_with_body_retry(endpoint, method, body_fn, retry_auth)
.await?;
// Read and parse response body
let body = hyper::body::to_bytes(response.into_body()).await?;
let parsed: T = match serde_json::from_slice(&body) {
Ok(result) => Ok(result),
Err(json_err) => {
log::error!("Error deserializing JSON: {:?}", json_err);
log::error!("Body: {:?}", String::from_utf8_lossy(&body));
// 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(|e| Error::DecodeError(e.to_string()))?;
serde_plain::from_str(s).map_err(|_| json_err)
}
}?;
Ok(parsed)
}
async fn response_with_body_retry(
&mut self,
endpoint: &str,
method: Method,
mut body_fn: impl FnMut() -> Body,
retry_auth: bool,
) -> Result<hyper::Response<Body>, Error> {
use hyper::StatusCode;
let uri = self.uri_for_endpoint(endpoint, None)?;
log::debug!("Requesting {:?} {:?}", method, uri);
let mut build_request = |auth: &Option<String>| {
let body = body_fn();
Request::builder()
.method(&method)
.uri(uri.clone())
.with_auth_string(auth)
.body(body)
.expect("Unable to build request")
};
log::trace!("Obtaining token from auth store");
let token = self.auth_store.get_token().await;
log::trace!("Token: {:?}", token);
let request = build_request(&token);
log::trace!("Request: {:?}. Sending request...", request);
let mut response = self.client.request(request).await?;
log::debug!("-> Response: {:}", response.status());
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()));
}
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?;
let request = build_request(&Some(new_token.to_string()));
response = self.client.request(request).await?;
} else {
return Err(Error::ClientError(
"Unauthorized, no credentials provided".into(),
));
}
}
// Other errors: bubble up.
_ => {
let status = response.status();
let body_str = hyper::body::to_bytes(response.into_body()).await?;
let message = format!(
"Request failed ({:}). Response body: {:?}",
status,
String::from_utf8_lossy(&body_str)
);
return Err(Error::ClientError(message));
}
}
Ok(response)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::api::InMemoryAuthenticationStore;
#[cfg(test)]
fn local_mock_client() -> HTTPAPIClient<InMemoryAuthenticationStore> {
let base_url = "http://localhost:5738".parse().unwrap();
let credentials = Credentials {
username: "test".to_string(),
password: "test".to_string(),
};
HTTPAPIClient::new(
base_url,
InMemoryAuthenticationStore::new(Some(credentials)),
)
}
#[cfg(test)]
async fn mock_client_is_reachable() -> bool {
let mut client = local_mock_client();
let version = client.get_version().await;
match version {
Ok(_) => true,
Err(e) => {
log::error!("Mock client error: {:?}", e);
false
}
}
}
#[tokio::test]
async fn test_version() {
if !mock_client_is_reachable().await {
log::warn!("Skipping http_client tests (mock server not reachable)");
return;
}
let mut client = local_mock_client();
let version = client.get_version().await.unwrap();
assert!(version.starts_with("KordophoneMock-"));
}
#[tokio::test]
async fn test_conversations() {
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();
assert!(!conversations.is_empty());
}
#[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();
let messages = client
.get_messages(&conversation.guid, None, None, None)
.await
.unwrap();
assert!(!messages.is_empty());
}
#[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(None).await.unwrap();
assert!(true);
}
}

View File

@@ -0,0 +1,78 @@
pub use crate::model::{Conversation, ConversationID, Message, MessageID, OutgoingMessage};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::Stream;
pub mod auth;
pub use crate::api::auth::{AuthenticationStore, InMemoryAuthenticationStore};
use crate::model::JwtToken;
pub mod http_client;
pub use http_client::HTTPAPIClient;
pub mod event_socket;
pub use event_socket::EventSocket;
use self::http_client::Credentials;
use std::fmt::Debug;
#[async_trait]
pub trait APIInterface {
type Error: Debug;
type ResponseStream: Stream<Item = Result<Bytes, Self::Error>>;
// (GET) /version
async fn get_version(&mut self) -> Result<String, Self::Error>;
// (GET) /conversations
async fn get_conversations(&mut self) -> Result<Vec<Conversation>, Self::Error>;
// (GET) /messages
async fn get_messages(
&mut self,
conversation_id: &ConversationID,
limit: Option<u32>,
before: Option<MessageID>,
after: Option<MessageID>,
) -> Result<Vec<Message>, Self::Error>;
// (POST) /sendMessage
async fn send_message(
&mut self,
outgoing_message: &OutgoingMessage,
) -> Result<Message, Self::Error>;
// (GET) /attachment
async fn fetch_attachment_data(
&mut self,
guid: &str,
preview: bool,
) -> Result<Self::ResponseStream, Self::Error>;
// (POST) /uploadAttachment
async fn upload_attachment<R>(
&mut self,
data: tokio::io::BufReader<R>,
filename: &str,
size: u64,
) -> Result<String, Self::Error>
where
R: tokio::io::AsyncRead + Unpin + Send + Sync + 'static;
// (POST) /authenticate
async fn authenticate(&mut self, credentials: Credentials) -> Result<JwtToken, Self::Error>;
// (GET) /markConversation
async fn mark_conversation_as_read(
&mut self,
conversation_id: &ConversationID,
) -> Result<(), Self::Error>;
// (WS) /updates
async fn open_event_socket(
&mut self,
update_seq: Option<u64>,
) -> Result<impl EventSocket, Self::Error>;
}

View File

@@ -0,0 +1,20 @@
pub mod api;
pub mod model;
pub use self::api::APIInterface;
#[cfg(test)]
pub mod tests;
// Ensure a process-level rustls CryptoProvider is installed for TLS (wss).
// Rustls 0.23 requires an explicit provider installation (e.g., ring or aws-lc).
// We depend on rustls with feature "ring" and install it once at startup.
#[ctor::ctor]
fn install_rustls_crypto_provider() {
// If already installed, this is a no-op. Ignore the result.
#[allow(unused_must_use)]
{
use rustls::crypto::ring;
ring::default_provider().install_default();
}
}

View File

@@ -0,0 +1,112 @@
use serde::Deserialize;
use time::OffsetDateTime;
use uuid::Uuid;
use super::Identifiable;
use crate::model::message::Message;
pub type ConversationID = <Conversation as Identifiable>::ID;
#[derive(Debug, Clone, Deserialize)]
pub struct Conversation {
pub guid: String,
#[serde(with = "time::serde::iso8601")]
pub date: OffsetDateTime,
#[serde(rename = "unreadCount")]
pub unread_count: i32,
#[serde(rename = "lastMessagePreview")]
pub last_message_preview: Option<String>,
#[serde(rename = "participantDisplayNames")]
pub participant_display_names: Vec<String>,
#[serde(rename = "displayName")]
pub display_name: Option<String>,
#[serde(rename = "lastMessage")]
pub last_message: Option<Message>,
}
impl Conversation {
pub fn builder() -> ConversationBuilder {
ConversationBuilder::new()
}
}
impl Identifiable for Conversation {
type ID = String;
fn id(&self) -> &Self::ID {
&self.guid
}
}
#[derive(Default)]
pub struct ConversationBuilder {
guid: Option<String>,
date: Option<OffsetDateTime>,
unread_count: Option<i32>,
last_message_preview: Option<String>,
participant_display_names: Option<Vec<String>>,
display_name: Option<String>,
last_message: Option<Message>,
}
impl ConversationBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn guid(mut self, guid: String) -> Self {
self.guid = Some(guid);
self
}
pub fn date(mut self, date: OffsetDateTime) -> Self {
self.date = Some(date);
self
}
pub fn unread_count(mut self, unread_count: i32) -> Self {
self.unread_count = Some(unread_count);
self
}
pub fn last_message_preview(mut self, last_message_preview: String) -> Self {
self.last_message_preview = Some(last_message_preview);
self
}
pub fn participant_display_names(mut self, participant_display_names: Vec<String>) -> Self {
self.participant_display_names = Some(participant_display_names);
self
}
pub fn display_name<T>(mut self, display_name: T) -> Self
where
T: Into<String>,
{
self.display_name = Some(display_name.into());
self
}
pub fn last_message(mut self, last_message: Message) -> Self {
self.last_message = Some(last_message);
self
}
pub fn build(self) -> Conversation {
Conversation {
guid: self.guid.unwrap_or(Uuid::new_v4().to_string()),
date: self.date.unwrap_or(OffsetDateTime::now_utc()),
unread_count: self.unread_count.unwrap_or(0),
last_message_preview: self.last_message_preview,
participant_display_names: self.participant_display_names.unwrap_or_default(),
display_name: self.display_name,
last_message: self.last_message,
}
}
}

View File

@@ -0,0 +1,39 @@
use crate::model::{Conversation, Message, UpdateItem};
#[derive(Debug, Clone)]
pub struct Event {
pub data: EventData,
pub update_seq: u64,
}
#[derive(Debug, Clone)]
pub enum EventData {
ConversationChanged(Conversation),
MessageReceived(Conversation, Message),
}
impl From<UpdateItem> for Event {
fn from(update: UpdateItem) -> Self {
match update {
UpdateItem {
conversation: Some(conversation),
message: None,
..
} => Event {
data: EventData::ConversationChanged(conversation),
update_seq: update.seq,
},
UpdateItem {
conversation: Some(conversation),
message: Some(message),
..
} => Event {
data: EventData::MessageReceived(conversation, message),
update_seq: update.seq,
},
_ => panic!("Invalid update item: {:?}", update),
}
}
}

View File

@@ -0,0 +1,146 @@
use std::error::Error;
use base64::{
engine::{self, general_purpose},
Engine,
};
use chrono::{DateTime, Utc};
use hyper::http::HeaderValue;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone)]
#[allow(dead_code)]
struct JwtHeader {
alg: String,
typ: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[allow(dead_code)]
enum ExpValue {
Integer(i64),
String(String),
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[allow(dead_code)]
struct JwtPayload {
#[serde(deserialize_with = "deserialize_exp")]
exp: i64,
iss: Option<String>,
user: Option<String>,
}
fn deserialize_exp<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(untagged)]
enum ExpValue {
String(String),
Number(i64),
}
match ExpValue::deserialize(deserializer)? {
ExpValue::String(s) => s.parse().map_err(D::Error::custom),
ExpValue::Number(n) => Ok(n),
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[allow(dead_code)]
pub struct JwtToken {
header: JwtHeader,
payload: JwtPayload,
signature: Vec<u8>,
expiration_date: DateTime<Utc>,
token: String,
}
impl JwtToken {
fn decode_token_using_engine(
token: &str,
engine: engine::GeneralPurpose,
) -> Result<Self, Box<dyn Error + Send + Sync>> {
let mut parts = token.split('.');
let header = parts.next().unwrap();
let payload = parts.next().unwrap();
let signature = parts.next().unwrap();
let header = engine.decode(header)?;
let payload = engine.decode(payload)?;
let signature = engine.decode(signature)?;
// Parse jwt header
let header: JwtHeader = serde_json::from_slice(&header)?;
// Parse jwt payload
let payload: JwtPayload = serde_json::from_slice(&payload)?;
// Parse jwt expiration date
let timestamp = DateTime::from_timestamp(payload.exp, 0)
.unwrap()
.naive_utc();
let expiration_date = DateTime::from_naive_utc_and_offset(timestamp, Utc);
Ok(JwtToken {
header,
payload,
signature,
expiration_date,
token: token.to_string(),
})
}
pub fn new(token: &str) -> Result<Self, Box<dyn Error + Send + Sync>> {
// STUPID: My mock server uses a different encoding than the real server, so we have to
// try both encodings here.
log::debug!("Attempting to decode JWT token: {}", token);
let result = Self::decode_token_using_engine(token, general_purpose::STANDARD).or(
Self::decode_token_using_engine(token, general_purpose::URL_SAFE_NO_PAD),
);
if let Err(ref e) = result {
log::error!("Failed to decode JWT token: {}", e);
log::error!("Token length: {}", token.len());
log::error!("Token parts: {:?}", token.split('.').collect::<Vec<_>>());
}
result
}
pub fn dummy() -> Self {
JwtToken {
header: JwtHeader {
alg: "none".to_string(),
typ: "JWT".to_string(),
},
payload: JwtPayload {
exp: 0,
iss: None,
user: None,
},
signature: vec![],
expiration_date: Utc::now(),
token: "".to_string(),
}
}
pub fn is_valid(&self) -> bool {
self.expiration_date > Utc::now()
}
pub fn to_header_value(&self) -> HeaderValue {
format!("Bearer {}", self.token).parse().unwrap()
}
pub fn to_string(&self) -> String {
self.token.clone()
}
}

View File

@@ -0,0 +1,121 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use time::OffsetDateTime;
use uuid::Uuid;
use super::Identifiable;
pub type MessageID = <Message as Identifiable>::ID;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttributionInfo {
/// Picture width
#[serde(rename = "pgensw")]
pub width: Option<u32>,
/// Picture height
#[serde(rename = "pgensh")]
pub height: Option<u32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttachmentMetadata {
#[serde(rename = "attributionInfo")]
pub attribution_info: Option<AttributionInfo>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Message {
pub guid: String,
#[serde(rename = "text")]
pub text: String,
#[serde(rename = "sender")]
pub sender: Option<String>,
#[serde(with = "time::serde::iso8601")]
pub date: OffsetDateTime,
/// Array of file transfer GUIDs for attachments
#[serde(rename = "fileTransferGUIDs", default)]
pub file_transfer_guids: Vec<String>,
/// Optional attachment metadata, keyed by attachment GUID
#[serde(rename = "attachmentMetadata")]
pub attachment_metadata: Option<HashMap<String, AttachmentMetadata>>,
}
impl Message {
pub fn builder() -> MessageBuilder {
MessageBuilder::new()
}
}
impl Identifiable for Message {
type ID = String;
fn id(&self) -> &Self::ID {
&self.guid
}
}
#[derive(Default)]
pub struct MessageBuilder {
guid: Option<String>,
text: Option<String>,
sender: Option<String>,
date: Option<OffsetDateTime>,
file_transfer_guids: Option<Vec<String>>,
attachment_metadata: Option<HashMap<String, AttachmentMetadata>>,
}
impl MessageBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn guid(mut self, guid: String) -> Self {
self.guid = Some(guid);
self
}
pub fn text(mut self, text: String) -> Self {
self.text = Some(text);
self
}
pub fn sender(mut self, sender: String) -> Self {
self.sender = Some(sender);
self
}
pub fn date(mut self, date: OffsetDateTime) -> Self {
self.date = Some(date);
self
}
pub fn file_transfer_guids(mut self, file_transfer_guids: Vec<String>) -> Self {
self.file_transfer_guids = Some(file_transfer_guids);
self
}
pub fn attachment_metadata(
mut self,
attachment_metadata: HashMap<String, AttachmentMetadata>,
) -> Self {
self.attachment_metadata = Some(attachment_metadata);
self
}
pub fn build(self) -> Message {
Message {
guid: self.guid.unwrap_or(Uuid::new_v4().to_string()),
text: self.text.unwrap_or("".to_string()),
sender: self.sender,
date: self.date.unwrap_or(OffsetDateTime::now_utc()),
file_transfer_guids: self.file_transfer_guids.unwrap_or_default(),
attachment_metadata: self.attachment_metadata,
}
}
}

View File

@@ -0,0 +1,26 @@
pub mod conversation;
pub mod event;
pub mod message;
pub mod outgoing_message;
pub mod update;
pub use conversation::Conversation;
pub use conversation::ConversationID;
pub use message::Message;
pub use message::MessageID;
pub use outgoing_message::OutgoingMessage;
pub use outgoing_message::OutgoingMessageBuilder;
pub use update::UpdateItem;
pub use event::Event;
pub mod jwt;
pub use jwt::JwtToken;
pub trait Identifiable {
type ID;
fn id(&self) -> &Self::ID;
}

View File

@@ -0,0 +1,72 @@
use super::conversation::ConversationID;
use chrono::NaiveDateTime;
use serde::Serialize;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize)]
pub struct OutgoingMessage {
#[serde(skip)]
pub guid: Uuid,
#[serde(skip)]
pub date: NaiveDateTime,
#[serde(rename = "body")]
pub text: String,
#[serde(rename = "guid")]
pub conversation_id: ConversationID,
#[serde(rename = "fileTransferGUIDs")]
pub file_transfer_guids: Vec<String>,
}
impl OutgoingMessage {
pub fn builder() -> OutgoingMessageBuilder {
OutgoingMessageBuilder::new()
}
}
#[derive(Default)]
pub struct OutgoingMessageBuilder {
guid: Option<Uuid>,
text: Option<String>,
conversation_id: Option<ConversationID>,
file_transfer_guids: Option<Vec<String>>,
}
impl OutgoingMessageBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn guid(mut self, guid: Uuid) -> Self {
self.guid = Some(guid);
self
}
pub fn text(mut self, text: String) -> Self {
self.text = Some(text);
self
}
pub fn conversation_id(mut self, conversation_id: ConversationID) -> Self {
self.conversation_id = Some(conversation_id);
self
}
pub fn file_transfer_guids(mut self, file_transfer_guids: Vec<String>) -> Self {
self.file_transfer_guids = Some(file_transfer_guids);
self
}
pub fn build(self) -> OutgoingMessage {
OutgoingMessage {
guid: self.guid.unwrap_or_else(Uuid::new_v4),
text: self.text.unwrap(),
conversation_id: self.conversation_id.unwrap(),
file_transfer_guids: self.file_transfer_guids.unwrap_or_default(),
date: chrono::Utc::now().naive_utc(),
}
}
}

View File

@@ -0,0 +1,18 @@
use super::conversation::Conversation;
use super::message::Message;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, Default)]
pub struct UpdateItem {
#[serde(rename = "messageSequenceNumber")]
pub seq: u64,
#[serde(rename = "conversation")]
pub conversation: Option<Conversation>,
#[serde(rename = "message")]
pub message: Option<Message>,
#[serde(default)]
pub pong: bool,
}

View File

@@ -0,0 +1,31 @@
mod test_client;
use self::test_client::TestClient;
use crate::APIInterface;
pub mod api_interface {
use crate::model::Conversation;
use super::*;
#[tokio::test]
async fn test_version() {
let mut client = TestClient::new();
let version = client.get_version().await.unwrap();
assert_eq!(version, client.version);
}
#[tokio::test]
async fn test_conversations() {
let mut client = TestClient::new();
let test_convo = Conversation::builder()
.display_name("Test Conversation")
.build();
client.conversations.push(test_convo.clone());
let conversations = client.get_conversations().await.unwrap();
assert_eq!(conversations.len(), 1);
assert_eq!(conversations[0].display_name, test_convo.display_name);
}
}

View File

@@ -0,0 +1,158 @@
use async_trait::async_trait;
use std::collections::HashMap;
use time::OffsetDateTime;
use uuid::Uuid;
pub use crate::APIInterface;
use crate::{
api::event_socket::{EventSocket, SinkMessage, SocketEvent, SocketUpdate},
api::http_client::Credentials,
model::{
Conversation, ConversationID, Event, JwtToken, Message, MessageID, OutgoingMessage,
UpdateItem,
},
};
use bytes::Bytes;
use futures_util::stream::BoxStream;
use futures_util::Sink;
use futures_util::StreamExt;
pub struct TestClient {
pub version: &'static str,
pub conversations: Vec<Conversation>,
pub messages: HashMap<ConversationID, Vec<Message>>,
}
#[derive(Debug)]
pub enum TestError {
ConversationNotFound,
}
impl TestClient {
pub fn new() -> TestClient {
TestClient {
version: "KordophoneTest-1.0",
conversations: vec![],
messages: HashMap::<ConversationID, Vec<Message>>::new(),
}
}
}
pub struct TestEventSocket {
pub events: Vec<Event>,
}
impl TestEventSocket {
pub fn new() -> Self {
Self { events: vec![] }
}
}
#[async_trait]
impl EventSocket for TestEventSocket {
type Error = TestError;
type EventStream = BoxStream<'static, Result<SocketEvent, TestError>>;
type UpdateStream = BoxStream<'static, Result<SocketUpdate, TestError>>;
async fn events(
self,
) -> (
Self::EventStream,
impl Sink<SinkMessage, Error = Self::Error>,
) {
(
futures_util::stream::iter(self.events.into_iter().map(Ok)).boxed(),
futures_util::sink::sink(),
)
}
async fn raw_updates(self) -> Self::UpdateStream {
let results: Vec<Result<Vec<UpdateItem>, TestError>> = vec![];
futures_util::stream::iter(results.into_iter()).boxed()
}
}
#[async_trait]
impl APIInterface for TestClient {
type Error = TestError;
type ResponseStream = BoxStream<'static, Result<Bytes, TestError>>;
async fn authenticate(&mut self, _credentials: Credentials) -> Result<JwtToken, Self::Error> {
Ok(JwtToken::dummy())
}
async fn get_version(&mut self) -> Result<String, Self::Error> {
Ok(self.version.to_string())
}
async fn get_conversations(&mut self) -> Result<Vec<Conversation>, Self::Error> {
Ok(self.conversations.clone())
}
async fn get_messages(
&mut self,
conversation_id: &ConversationID,
limit: Option<u32>,
before: Option<MessageID>,
after: Option<MessageID>,
) -> Result<Vec<Message>, Self::Error> {
if let Some(messages) = self.messages.get(conversation_id) {
return Ok(messages.clone());
}
Err(TestError::ConversationNotFound)
}
async fn send_message(
&mut self,
outgoing_message: &OutgoingMessage,
) -> Result<Message, Self::Error> {
let message = Message::builder()
.guid(Uuid::new_v4().to_string())
.text(outgoing_message.text.clone())
.date(OffsetDateTime::now_utc())
.build();
self.messages
.entry(outgoing_message.conversation_id.clone())
.or_insert(vec![])
.push(message.clone());
Ok(message)
}
async fn open_event_socket(
&mut self,
_update_seq: Option<u64>,
) -> Result<impl EventSocket, Self::Error> {
Ok(TestEventSocket::new())
}
async fn fetch_attachment_data(
&mut self,
guid: &str,
preview: bool,
) -> Result<Self::ResponseStream, Self::Error> {
Ok(futures_util::stream::iter(vec![Ok(Bytes::from_static(b"test"))]).boxed())
}
async fn upload_attachment<R>(
&mut self,
data: tokio::io::BufReader<R>,
filename: &str,
size: u64,
) -> Result<String, Self::Error>
where
R: tokio::io::AsyncRead + Unpin + Send + Sync + 'static,
{
Ok(String::from("test"))
}
async fn mark_conversation_as_read(
&mut self,
conversation_id: &ConversationID,
) -> Result<(), Self::Error> {
Ok(())
}
}