Skip to content

Commit 1735389

Browse files
committed
chore: rewrite the interface for the core_lib part 2
Signed-off-by: Martichou <[email protected]>
1 parent 5114c8f commit 1735389

File tree

9 files changed

+439
-420
lines changed

9 files changed

+439
-420
lines changed

app/main/src-tauri/src/cmds/change_download_path.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ use std::path::PathBuf;
33
use crate::AppState;
44

55
#[tauri::command]
6-
pub fn change_download_path(message: Option<String>, state: tauri::State<'_, AppState>) {
6+
pub fn change_download_path(message: Option<String>, state: tauri::State<'_, AppState>) -> Result<(), String> {
77
info!("change_download_path: {message:?}");
88

9-
state
10-
.rqs_handle
11-
.set_download_path(message.map(PathBuf::from));
9+
state.rqs_handle.set_download_path(message.map(PathBuf::from))
10+
.map_err(|e| format!("Failed to change download path: {}", e))
1211
}

app/main/src-tauri/src/cmds/change_visibility.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ use rqs_lib::Visibility;
33
use crate::AppState;
44

55
#[tauri::command]
6-
pub fn change_visibility(message: Visibility, state: tauri::State<'_, AppState>) {
6+
pub fn change_visibility(message: Visibility, state: tauri::State<'_, AppState>) -> Result<(), String> {
77
info!("change_visibility: {message:?}");
88

9-
state.rqs_handle.change_visibility(message);
9+
state.rqs_handle.change_visibility(message)
10+
.map_err(|e| format!("Failed to change visibility: {}", e))
1011
}

app/main/src-tauri/src/main.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -271,10 +271,12 @@ fn kill_app(app_handle: &AppHandle) {
271271
// Shutdown RQS service
272272
let state: tauri::State<AppState> = app_handle.state();
273273
let rqs_handle = state.rqs_handle.clone();
274-
274+
275275
tauri::async_runtime::spawn(async move {
276-
rqs_handle.shutdown().await;
276+
if let Err(e) = rqs_handle.shutdown().await {
277+
error!("Error shutting down RQS: {}", e);
278+
}
277279
});
278-
280+
279281
app_handle.exit(-1);
280282
}

core_lib/src/bin.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ async fn main() -> Result<(), anyhow::Error> {
1717
tracing_subscriber::fmt::init();
1818

1919
// Create the RQuickShare service with default configuration
20-
let mut rqs = RQS::default();
20+
let rqs = RQS::default();
2121
let config = RqsConfig::default();
2222

2323
// Start the service and get the handle
@@ -39,7 +39,7 @@ async fn main() -> Result<(), anyhow::Error> {
3939
info!("Stopping service.");
4040

4141
// Shutdown the service
42-
handle.shutdown().await;
42+
let _ = handle.shutdown().await;
4343
rqs.shutdown().await;
4444

4545
Ok(())

core_lib/src/hdl/inbound.rs

+101-68
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::fs::File;
22
use std::os::unix::fs::FileExt;
3-
use std::time::Duration;
43

54
use anyhow::anyhow;
65
use bytes::Bytes;
@@ -38,93 +37,123 @@ use crate::utils::{
3837
encode_point, gen_ecdsa_keypair, gen_random, get_download_dir, hkdf_extract_expand,
3938
stream_read_exact, to_four_digit_string, DeviceType, RemoteDeviceInfo,
4039
};
41-
use crate::{location_nearby_connections, sharing_nearby};
40+
use crate::{location_nearby_connections, sharing_nearby, RqsEvent};
4241

4342
type HmacSha256 = Hmac<Sha256>;
4443

4544
const SANE_FRAME_LENGTH: i32 = 5 * 1024 * 1024;
46-
const SANITY_DURATION: Duration = Duration::from_micros(10);
4745

4846
#[derive(Debug)]
4947
pub struct InboundRequest {
5048
socket: TcpStream,
5149
pub state: InnerState,
52-
sender: Sender<ChannelMessage>,
53-
receiver: Receiver<ChannelMessage>,
50+
sender: Sender<RqsEvent>,
51+
receiver: Receiver<RqsEvent>,
5452
}
5553

5654
impl InboundRequest {
57-
pub fn new(socket: TcpStream, id: String, sender: Sender<ChannelMessage>) -> Self {
55+
pub fn new(socket: TcpStream, id: String, sender: Sender<RqsEvent>) -> Self {
56+
// Create a receiver for the unified event channel
5857
let receiver = sender.subscribe();
5958

59+
// We'll filter messages in the handle method instead of trying to create a custom filtered receiver
6060
Self {
6161
socket,
6262
state: InnerState {
63-
id,
63+
id: id.clone(),
6464
server_seq: 0,
6565
client_seq: 0,
66+
encryption_done: false,
6667
state: State::Initial,
67-
encryption_done: true,
68-
..Default::default()
68+
remote_device_info: None,
69+
pin_code: None,
70+
transfer_metadata: None,
71+
transferred_files: Default::default(),
72+
cipher_commitment: None,
73+
private_key: None,
74+
public_key: None,
75+
server_init_data: None,
76+
client_init_msg_data: None,
77+
ukey_client_finish_msg_data: None,
78+
decrypt_key: None,
79+
recv_hmac_key: None,
80+
encrypt_key: None,
81+
send_hmac_key: None,
82+
text_payload: None,
83+
payload_buffers: Default::default(),
6984
},
7085
sender,
7186
receiver,
7287
}
7388
}
7489

7590
pub async fn handle(&mut self) -> Result<(), anyhow::Error> {
91+
// Check for any pending messages from the frontend
92+
if let Ok(Some(channel_msg)) = self.wait_for_channel_message().await {
93+
if let Some(action) = channel_msg.action {
94+
match action {
95+
ChannelAction::AcceptTransfer => {
96+
return self.accept_transfer().await;
97+
}
98+
ChannelAction::RejectTransfer => {
99+
return self
100+
.reject_transfer(Some(
101+
sharing_nearby::connection_response_frame::Status::Reject,
102+
))
103+
.await;
104+
}
105+
ChannelAction::CancelTransfer => {
106+
// Use an appropriate status value from the actual enum
107+
return self
108+
.reject_transfer(Some(
109+
sharing_nearby::connection_response_frame::Status::Reject,
110+
))
111+
.await;
112+
}
113+
}
114+
}
115+
}
116+
76117
// Buffer for the 4-byte length
77118
let mut length_buf = [0u8; 4];
78119

79120
tokio::select! {
80121
i = self.receiver.recv() => {
81-
match i {
82-
Ok(channel_msg) => {
83-
if channel_msg.direction == ChannelDirection::LibToFront {
84-
return Ok(());
85-
}
122+
if let Ok(RqsEvent::Message(channel_msg)) = i {
123+
if channel_msg.direction == ChannelDirection::LibToFront {
124+
return Ok(());
125+
}
86126

87-
if channel_msg.id != self.state.id {
88-
return Ok(());
89-
}
127+
if channel_msg.id != self.state.id {
128+
return Ok(());
129+
}
90130

91-
debug!("inbound: got: {:?}", channel_msg);
92-
match channel_msg.action {
93-
Some(ChannelAction::AcceptTransfer) => {
131+
debug!("inbound: got: {:?}", channel_msg);
132+
if let Some(action) = channel_msg.action {
133+
match action {
134+
ChannelAction::AcceptTransfer => {
94135
self.accept_transfer().await?;
95136
},
96-
Some(ChannelAction::RejectTransfer) => {
137+
ChannelAction::RejectTransfer => {
97138
self.update_state(
98139
|e| {
99140
e.state = State::Rejected;
100141
},
101142
true,
102143
).await;
103-
104-
self.reject_transfer(Some(
105-
sharing_nearby::connection_response_frame::Status::Reject
106-
)).await?;
107-
return Err(anyhow!(crate::errors::AppError::NotAnError));
108144
},
109-
Some(ChannelAction::CancelTransfer) => {
145+
ChannelAction::CancelTransfer => {
110146
self.update_state(
111147
|e| {
112148
e.state = State::Cancelled;
113149
},
114150
true,
115151
).await;
116-
self.disconnection().await?;
117-
return Err(anyhow!(crate::errors::AppError::NotAnError));
118-
},
119-
None => {
120-
trace!("inbound: nothing to do")
121-
},
152+
}
122153
}
123154
}
124-
Err(e) => {
125-
error!("inbound: channel error: {}", e);
126-
}
127155
}
156+
return Ok(());
128157
},
129158
h = stream_read_exact(&mut self.socket, &mut length_buf) => {
130159
h?;
@@ -978,24 +1007,15 @@ impl InboundRequest {
9781007
}
9791008

9801009
async fn disconnection(&mut self) -> Result<(), anyhow::Error> {
981-
let frame = location_nearby_connections::OfflineFrame {
982-
version: Some(location_nearby_connections::offline_frame::Version::V1.into()),
983-
v1: Some(location_nearby_connections::V1Frame {
984-
r#type: Some(
985-
location_nearby_connections::v1_frame::FrameType::Disconnection.into(),
986-
),
987-
disconnection: Some(location_nearby_connections::DisconnectionFrame {
988-
..Default::default()
989-
}),
990-
..Default::default()
991-
}),
992-
};
1010+
self.update_state(
1011+
|s| {
1012+
s.state = State::Disconnected;
1013+
},
1014+
true,
1015+
)
1016+
.await;
9931017

994-
if self.state.encryption_done {
995-
self.encrypt_and_send(&frame).await
996-
} else {
997-
self.send_frame(frame.encode_to_vec()).await
998-
}
1018+
Ok(())
9991019
}
10001020

10011021
async fn accept_transfer(&mut self) -> Result<(), anyhow::Error> {
@@ -1327,22 +1347,35 @@ impl InboundRequest {
13271347
{
13281348
f(&mut self.state);
13291349

1330-
if !inform {
1331-
return;
1350+
if inform {
1351+
let _ = self.sender.send(RqsEvent::Message(ChannelMessage {
1352+
id: self.state.id.clone(),
1353+
direction: ChannelDirection::LibToFront,
1354+
state: Some(self.state.state.clone()),
1355+
meta: self.state.transfer_metadata.clone(),
1356+
..Default::default()
1357+
}));
13321358
}
1359+
}
13331360

1334-
trace!("Sending msg into the channel");
1335-
let _ = self.sender.send(ChannelMessage {
1336-
id: self.state.id.clone(),
1337-
direction: ChannelDirection::LibToFront,
1338-
rtype: Some(crate::channel::TransferType::Inbound),
1339-
state: Some(self.state.state.clone()),
1340-
meta: self.state.transfer_metadata.clone(),
1341-
..Default::default()
1342-
});
1343-
// Add a small sleep timer to allow the Tokio runtime to have
1344-
// some spare time to process channel's message. Otherwise it
1345-
// get spammed by new requests. Currently set to 10 micro secs.
1346-
tokio::time::sleep(SANITY_DURATION).await;
1361+
// Add a helper method to check for relevant messages
1362+
async fn wait_for_channel_message(&mut self) -> Result<Option<ChannelMessage>, anyhow::Error> {
1363+
let mut timeout = tokio::time::interval(tokio::time::Duration::from_millis(100));
1364+
1365+
for _ in 0..50 {
1366+
// Try for 5 seconds
1367+
tokio::select! {
1368+
_ = timeout.tick() => {},
1369+
result = self.receiver.recv() => {
1370+
if let Ok(RqsEvent::Message(msg)) = result {
1371+
if msg.direction == ChannelDirection::FrontToLib && msg.id == self.state.id {
1372+
return Ok(Some(msg));
1373+
}
1374+
}
1375+
}
1376+
}
1377+
}
1378+
1379+
Ok(None)
13471380
}
13481381
}

0 commit comments

Comments
 (0)