[client][server] file transfer working, ui not ready for it
This commit is contained in:
@ -1,26 +1,36 @@
|
||||
#![allow(clippy::missing_errors_doc)]
|
||||
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use std::{fs::File, io::Write as _, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use lanspread_db::db::Game;
|
||||
use lanspread_db::db::{Game, GameFileDescription};
|
||||
use lanspread_proto::{Message as _, Request, Response};
|
||||
use lanspread_utils::maybe_addr;
|
||||
use s2n_quic::{client::Connect, provider::limits::Limits, Client as QuicClient, Connection};
|
||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
|
||||
use tokio::{
|
||||
io::AsyncWriteExt,
|
||||
stream,
|
||||
sync::{
|
||||
mpsc::{UnboundedReceiver, UnboundedSender},
|
||||
Mutex,
|
||||
},
|
||||
};
|
||||
|
||||
static CERT_PEM: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../cert.pem"));
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientEvent {
|
||||
ListGames(Vec<Game>),
|
||||
GotGameFiles(Vec<GameFileDescription>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientCommand {
|
||||
ListGames,
|
||||
GetGame(String),
|
||||
DownloadGameFiles(Vec<GameFileDescription>),
|
||||
ServerAddr(SocketAddr),
|
||||
SetGameDir(String),
|
||||
}
|
||||
|
||||
async fn initial_server_alive_check(conn: &mut Connection) -> bool {
|
||||
@ -55,6 +65,73 @@ async fn initial_server_alive_check(conn: &mut Connection) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn download_game_files(
|
||||
game_file_descs: Vec<GameFileDescription>,
|
||||
games_dir: String,
|
||||
server_addr: SocketAddr,
|
||||
) -> eyre::Result<()> {
|
||||
let limits = Limits::default()
|
||||
.with_max_handshake_duration(Duration::from_secs(3))?
|
||||
.with_max_idle_timeout(Duration::from_secs(1))?;
|
||||
|
||||
let client = QuicClient::builder()
|
||||
.with_tls(CERT_PEM)?
|
||||
.with_io("0.0.0.0:0")?
|
||||
.with_limits(limits)?
|
||||
.start()?;
|
||||
|
||||
let conn = Connect::new(server_addr).with_server_name("localhost");
|
||||
let mut conn = client.connect(conn).await?;
|
||||
conn.keep_alive(true)?;
|
||||
|
||||
let game_file_descs = game_file_descs
|
||||
.into_iter()
|
||||
.filter(|desc| !desc.is_dir)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for file_desc in game_file_descs {
|
||||
log::info!("downloading file: {}", file_desc.relative_path);
|
||||
|
||||
let stream = conn.open_bidirectional_stream().await?;
|
||||
let (mut rx, mut tx) = stream.split();
|
||||
|
||||
let request = Request::GetGameFileData(file_desc.clone());
|
||||
|
||||
if let Ok(()) = tx.write_all(&request.encode()).await {
|
||||
let path = PathBuf::from(&games_dir).join(&file_desc.relative_path);
|
||||
let mut file = match File::create(&path) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::error!("failed to create file: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// if let Err(e) = tokio::io::copy(&mut rx, &mut file).await {
|
||||
// log::error!("failed to download file: {e}");
|
||||
// continue;
|
||||
// }
|
||||
|
||||
while let Ok(Some(data)) = rx.receive().await {
|
||||
if let Err(e) = file.write_all(&data) {
|
||||
log::error!("failed to write to file: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
log::error!("file download complete: {}", path.display());
|
||||
}
|
||||
if let Err(e) = tx.close().await {
|
||||
log::error!("failed to close stream: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Ctx {
|
||||
game_dir: Arc<Mutex<Option<String>>>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub async fn run(
|
||||
mut rx_control: UnboundedReceiver<ClientCommand>,
|
||||
@ -69,6 +146,11 @@ pub async fn run(
|
||||
}
|
||||
};
|
||||
|
||||
// client context
|
||||
let ctx = Ctx {
|
||||
game_dir: Arc::new(Mutex::new(None)),
|
||||
};
|
||||
|
||||
loop {
|
||||
let limits = Limits::default()
|
||||
.with_max_handshake_duration(Duration::from_secs(3))?
|
||||
@ -106,11 +188,36 @@ pub async fn run(
|
||||
while let Some(cmd) = rx_control.recv().await {
|
||||
let request = match cmd {
|
||||
ClientCommand::ListGames => Request::ListGames,
|
||||
ClientCommand::GetGame(id) => Request::GetGame { id },
|
||||
ClientCommand::ServerAddr(_) => Request::Invalid(
|
||||
Bytes::new(),
|
||||
"invalid control message (ServerAddr), should not happen".into(),
|
||||
),
|
||||
ClientCommand::GetGame(id) => {
|
||||
log::debug!("requesting game from server: {id}");
|
||||
Request::GetGame { id }
|
||||
}
|
||||
ClientCommand::ServerAddr(_) => {
|
||||
log::warn!("unexpected ServerAddr command from UI client");
|
||||
continue;
|
||||
}
|
||||
ClientCommand::SetGameDir(game_dir) => {
|
||||
*ctx.game_dir.lock().await = Some(game_dir.clone());
|
||||
continue;
|
||||
}
|
||||
ClientCommand::DownloadGameFiles(game_file_descs) => {
|
||||
log::info!("got ClientCommand::DownloadGameFiles");
|
||||
|
||||
let games_dir = { ctx.game_dir.lock().await.clone() };
|
||||
if let Some(games_dir) = games_dir {
|
||||
tokio::task::spawn(async move {
|
||||
if let Err(e) =
|
||||
download_game_files(game_file_descs, games_dir, server_addr).await
|
||||
{
|
||||
log::error!("failed to download game files: {e}");
|
||||
}
|
||||
});
|
||||
} else {
|
||||
log::error!("Cannot handle game file descriptions: game_dir is not set");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let data = request.encode();
|
||||
@ -152,7 +259,37 @@ pub async fn run(
|
||||
log::info!("sent ClientEvent::ListGames to Tauri client");
|
||||
}
|
||||
}
|
||||
Response::Game(game) => log::debug!("game received: {game:?}"),
|
||||
Response::GetGame(game_file_descs) => {
|
||||
log::info!(
|
||||
"got {} game file descriptions from server",
|
||||
game_file_descs.len()
|
||||
);
|
||||
|
||||
let games_dir = { ctx.game_dir.lock().await.clone() };
|
||||
|
||||
match games_dir {
|
||||
Some(games_dir) => {
|
||||
game_file_descs.iter().filter(|f| f.is_dir).for_each(|dir| {
|
||||
let path = PathBuf::from(&games_dir).join(&dir.relative_path);
|
||||
if let Err(e) = std::fs::create_dir_all(path) {
|
||||
log::error!("failed to create directory: {e}");
|
||||
}
|
||||
});
|
||||
if let Err(e) =
|
||||
tx_notify_ui.send(ClientEvent::GotGameFiles(game_file_descs))
|
||||
{
|
||||
log::error!(
|
||||
"failed to send ClientEvent::GotGameFiles to client: {e}"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
log::error!(
|
||||
"Cannot handle game file descriptions: game_dir is not set"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Response::GameNotFound(id) => log::debug!("game not found {id}"),
|
||||
Response::InvalidRequest(request_bytes, err) => log::error!(
|
||||
"server says our request was invalid (error: {}): {}",
|
||||
|
Reference in New Issue
Block a user