Private
Public Access
1
0

cargo fmt

This commit is contained in:
2025-06-16 19:26:13 -07:00
parent 75fe4d4608
commit 032573d23b
14 changed files with 168 additions and 113 deletions

View File

@@ -168,8 +168,7 @@ impl<'a> Repository<'a> {
let mut participant_cache: HashMap<String, i32> = HashMap::new();
// Prepare collections for the batch inserts.
let mut db_messages: Vec<MessageRecord> =
Vec::with_capacity(in_messages.len());
let mut db_messages: Vec<MessageRecord> = Vec::with_capacity(in_messages.len());
let mut conv_msg_records: Vec<InsertableConversationMessage> =
Vec::with_capacity(in_messages.len());
@@ -178,7 +177,8 @@ impl<'a> Repository<'a> {
let sender_id = match &message.sender {
Participant::Me => None,
Participant::Remote { display_name, .. } => {
if let Some(cached_participant_id) = participant_cache.get(display_name) {
if let Some(cached_participant_id) = participant_cache.get(display_name)
{
Some(*cached_participant_id)
} else {
// Try to load from DB first
@@ -239,10 +239,13 @@ impl<'a> Repository<'a> {
// processed instead of re-querying the DB.
if let Some(last_msg) = db_messages.last() {
use crate::schema::conversations::dsl as conv_dsl;
diesel::update(conv_dsl::conversations.filter(conv_dsl::id.eq(conversation_guid)))
diesel::update(
conv_dsl::conversations.filter(conv_dsl::id.eq(conversation_guid)),
)
.set((
conv_dsl::date.eq(last_msg.date),
conv_dsl::last_message_preview.eq::<Option<String>>(Some(last_msg.text.clone())),
conv_dsl::last_message_preview
.eq::<Option<String>>(Some(last_msg.text.clone())),
))
.execute(conn)?;
}

View File

@@ -26,7 +26,12 @@ pub trait EventSocket {
type UpdateStream: Stream<Item = Result<SocketUpdate, Self::Error>>;
/// Modern event pipeline
async fn events(self) -> (Self::EventStream, impl Sink<SinkMessage, Error = Self::Error>);
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

@@ -115,19 +115,26 @@ impl<B> AuthSetting for hyper::http::Request<B> {
}
}
type WebsocketSink = futures_util::stream::SplitSink<WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, tungstenite::Message>;
type WebsocketStream = futures_util::stream::SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
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
stream: WebsocketStream,
}
impl WebsocketEventSocket {
pub fn new(socket: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
let (sink, stream) = socket.split();
Self { sink: Some(sink), stream }
Self {
sink: Some(sink),
stream,
}
}
}
@@ -150,9 +157,7 @@ impl WebsocketEventSocket {
// We don't expect the server to send us pings.
Ok(None)
}
tungstenite::Message::Pong(_) => {
Ok(Some(SocketUpdate::Pong))
}
tungstenite::Message::Pong(_) => Ok(Some(SocketUpdate::Pong)),
tungstenite::Message::Close(_) => {
// Connection was closed cleanly
Err(Error::ClientError("WebSocket connection closed".into()))
@@ -169,33 +174,40 @@ impl EventSocket for WebsocketEventSocket {
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>) {
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 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>> {
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))))
updates
.into_iter()
.map(|u| Ok(SocketEvent::Update(Event::from(u)))),
);
iter_stream.boxed()
}
SocketUpdate::Pong => {
iter(std::iter::once(Ok(SocketEvent::Pong))).boxed()
SocketUpdate::Pong => iter(std::iter::once(Ok(SocketEvent::Pong))).boxed(),
}
}
})
},
)
.try_flatten()
.boxed();
(stream, sink)
}
@@ -212,9 +224,7 @@ 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)
self.body.poll_next_unpin(cx).map_err(Error::HTTPError)
}
}
@@ -578,7 +588,11 @@ impl<K: AuthenticationStore + Send + Sync> HTTPAPIClient<K> {
_ => {
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));
let message = format!(
"Request failed ({:}). Response body: {:?}",
status,
String::from_utf8_lossy(&body_str)
);
return Err(Error::ClientError(message));
}
}

View File

@@ -2,8 +2,7 @@ use super::conversation::Conversation;
use super::message::Message;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
#[derive(Default)]
#[derive(Debug, Clone, Deserialize, Default)]
pub struct UpdateItem {
#[serde(rename = "messageSequenceNumber")]
pub seq: u64,
@@ -17,4 +16,3 @@ pub struct UpdateItem {
#[serde(default)]
pub pong: bool,
}

View File

@@ -56,7 +56,12 @@ impl EventSocket for TestEventSocket {
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>) {
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(),

View File

@@ -115,7 +115,7 @@ impl AttachmentStore {
database: &mut Arc<Mutex<Database>>,
daemon_event_sink: &Sender<DaemonEvent>,
guid: &String,
preview: bool
preview: bool,
) -> Result<()> {
let attachment = Self::get_attachment_impl(store_path, guid);
@@ -150,7 +150,10 @@ impl AttachmentStore {
file.sync_all()?;
// Atomically move the temporary file to the final location
std::fs::rename(&temporary_path, &attachment.get_path_for_preview_scratch(preview, false))?;
std::fs::rename(
&temporary_path,
&attachment.get_path_for_preview_scratch(preview, false),
)?;
log::info!(target: target::ATTACHMENTS, "Completed download for attachment: {}", attachment.guid);

View File

@@ -267,10 +267,12 @@ impl Daemon {
self.spawn_conversation_list_sync();
// Also restart the update monitor.
if let Err(e) = self.update_monitor_command_tx
if let Err(e) = self
.update_monitor_command_tx
.as_ref()
.unwrap()
.try_send(UpdateMonitorCommand::Restart) {
.try_send(UpdateMonitorCommand::Restart)
{
log::warn!(target: target::UPDATES, "Failed to send restart command to update monitor: {}", e);
}
}
@@ -428,7 +430,12 @@ impl Daemon {
.await
}
async fn enqueue_outgoing_message(&mut self, text: String, conversation_id: String, attachment_guids: Vec<String>) -> Uuid {
async fn enqueue_outgoing_message(
&mut self,
text: String,
conversation_id: String,
attachment_guids: Vec<String>,
) -> Uuid {
let conversation_id = conversation_id.clone();
let outgoing_message = OutgoingMessage::builder()
.text(text)
@@ -557,7 +564,8 @@ impl Daemon {
// the typing indicator or stuff like that. In the future, we need to move to ChatItems instead of Messages.
let insertable_messages: Vec<kordophone::model::Message> = messages
.into_iter()
.filter(|m| !m.text.is_empty() && !m.text.trim().is_empty()).collect();
.filter(|m| !m.text.is_empty() && !m.text.trim().is_empty())
.collect();
let db_messages: Vec<kordophone_db::models::Message> = insertable_messages
.into_iter()

View File

@@ -30,7 +30,8 @@ impl Attachment {
pub fn get_path_for_preview_scratch(&self, preview: bool, scratch: bool) -> PathBuf {
let extension = if preview { "preview" } else { "full" };
if scratch {
self.base_path.with_extension(format!("{}.download", extension))
self.base_path
.with_extension(format!("{}.download", extension))
} else {
self.base_path.with_extension(extension)
}

View File

@@ -50,10 +50,7 @@ impl UpdateMonitor {
self.command_tx.take().unwrap()
}
async fn send_event<T>(
&self,
make_event: impl FnOnce(Reply<T>) -> Event,
) -> DaemonResult<T> {
async fn send_event<T>(&self, make_event: impl FnOnce(Reply<T>) -> Event) -> DaemonResult<T> {
let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
self.event_sender
.send(make_event(reply_tx))

View File

@@ -10,10 +10,10 @@ pub mod interface {
include!(concat!(env!("OUT_DIR"), "/kordophone-server.rs"));
pub mod signals {
pub use crate::interface::NetBuzzertKordophoneRepositoryConversationsUpdated as ConversationsUpdated;
pub use crate::interface::NetBuzzertKordophoneRepositoryMessagesUpdated as MessagesUpdated;
pub use crate::interface::NetBuzzertKordophoneRepositoryAttachmentDownloadCompleted as AttachmentDownloadCompleted;
pub use crate::interface::NetBuzzertKordophoneRepositoryAttachmentUploadCompleted as AttachmentUploadCompleted;
pub use crate::interface::NetBuzzertKordophoneRepositoryConversationsUpdated as ConversationsUpdated;
pub use crate::interface::NetBuzzertKordophoneRepositoryMessagesUpdated as MessagesUpdated;
pub use crate::interface::NetBuzzertKordophoneRepositoryUpdateStreamReconnected as UpdateStreamReconnected;
}
}

View File

@@ -272,10 +272,7 @@ impl DbusRepository for ServerImpl {
self.send_event_sync(|r| Event::DownloadAttachment(attachment_id, preview, r))
}
fn upload_attachment(
&mut self,
path: String,
) -> Result<String, dbus::MethodErr> {
fn upload_attachment(&mut self, path: String) -> Result<String, dbus::MethodErr> {
use std::path::PathBuf;
let path = PathBuf::from(path);

View File

@@ -100,9 +100,15 @@ async fn main() {
}
Signal::AttachmentDownloaded(attachment_id) => {
log::debug!("Sending signal: AttachmentDownloaded for attachment {}", attachment_id);
log::debug!(
"Sending signal: AttachmentDownloaded for attachment {}",
attachment_id
);
dbus_registry
.send_signal(interface::OBJECT_PATH, DbusSignals::AttachmentDownloadCompleted { attachment_id })
.send_signal(
interface::OBJECT_PATH,
DbusSignals::AttachmentDownloadCompleted { attachment_id },
)
.unwrap_or_else(|_| {
log::error!("Failed to send signal");
0
@@ -110,9 +116,19 @@ async fn main() {
}
Signal::AttachmentUploaded(upload_guid, attachment_guid) => {
log::debug!("Sending signal: AttachmentUploaded for upload {}, attachment {}", upload_guid, attachment_guid);
log::debug!(
"Sending signal: AttachmentUploaded for upload {}, attachment {}",
upload_guid,
attachment_guid
);
dbus_registry
.send_signal(interface::OBJECT_PATH, DbusSignals::AttachmentUploadCompleted { upload_guid, attachment_guid })
.send_signal(
interface::OBJECT_PATH,
DbusSignals::AttachmentUploadCompleted {
upload_guid,
attachment_guid,
},
)
.unwrap_or_else(|_| {
log::error!("Failed to send signal");
0
@@ -122,7 +138,10 @@ async fn main() {
Signal::UpdateStreamReconnected => {
log::debug!("Sending signal: UpdateStreamReconnected");
dbus_registry
.send_signal(interface::OBJECT_PATH, DbusSignals::UpdateStreamReconnected {})
.send_signal(
interface::OBJECT_PATH,
DbusSignals::UpdateStreamReconnected {},
)
.unwrap_or_else(|_| {
log::error!("Failed to send signal");
0

View File

@@ -113,8 +113,7 @@ impl ClientCli {
let (mut stream, _) = socket.events().await;
while let Some(Ok(socket_event)) = stream.next().await {
match socket_event {
SocketEvent::Update(event) => {
match event.data {
SocketEvent::Update(event) => match event.data {
EventData::ConversationChanged(conversation) => {
println!("Conversation changed: {}", conversation.guid);
}
@@ -124,8 +123,7 @@ impl ClientCli {
message.guid, conversation.guid
);
}
}
}
},
SocketEvent::Pong => {
println!("Pong");
}

View File

@@ -54,14 +54,10 @@ pub enum Commands {
},
/// Downloads an attachment from the server to the attachment store. Returns the path to the attachment.
DownloadAttachment {
attachment_id: String,
},
DownloadAttachment { attachment_id: String },
/// Uploads an attachment to the server, returns upload guid.
UploadAttachment {
path: String,
},
UploadAttachment { path: String },
}
#[derive(Subcommand)]
@@ -100,7 +96,9 @@ impl Commands {
text,
} => client.enqueue_outgoing_message(conversation_id, text).await,
Commands::UploadAttachment { path } => client.upload_attachment(path).await,
Commands::DownloadAttachment { attachment_id } => client.download_attachment(attachment_id).await,
Commands::DownloadAttachment { attachment_id } => {
client.download_attachment(attachment_id).await
}
}
}
}
@@ -178,8 +176,12 @@ impl DaemonCli {
text: String,
) -> Result<()> {
let attachment_guids: Vec<&str> = vec![];
let outgoing_message_id =
KordophoneRepository::send_message(&self.proxy(), &conversation_id, &text, attachment_guids)?;
let outgoing_message_id = KordophoneRepository::send_message(
&self.proxy(),
&conversation_id,
&text,
attachment_guids,
)?;
println!("Outgoing message ID: {}", outgoing_message_id);
Ok(())
}
@@ -244,7 +246,8 @@ impl DaemonCli {
KordophoneRepository::download_attachment(&self.proxy(), &attachment_id, false)?;
// Get attachment info.
let attachment_info = KordophoneRepository::get_attachment_info(&self.proxy(), &attachment_id)?;
let attachment_info =
KordophoneRepository::get_attachment_info(&self.proxy(), &attachment_id)?;
let (path, preview_path, downloaded, preview_downloaded) = attachment_info;
if downloaded {
@@ -256,14 +259,18 @@ impl DaemonCli {
// Attach to the signal that the attachment has been downloaded.
let _id = self.proxy().match_signal(
move |h: dbus_interface::NetBuzzertKordophoneRepositoryAttachmentDownloadCompleted, _: &Connection, _: &dbus::message::Message| {
move |h: dbus_interface::NetBuzzertKordophoneRepositoryAttachmentDownloadCompleted,
_: &Connection,
_: &dbus::message::Message| {
println!("Signal: Attachment downloaded: {}", path);
std::process::exit(0);
},
);
let _id = self.proxy().match_signal(
|h: dbus_interface::NetBuzzertKordophoneRepositoryAttachmentDownloadFailed, _: &Connection, _: &dbus::message::Message| {
|h: dbus_interface::NetBuzzertKordophoneRepositoryAttachmentDownloadFailed,
_: &Connection,
_: &dbus::message::Message| {
println!("Signal: Attachment download failed: {}", h.attachment_id);
std::process::exit(1);
},