[code] improve structure (focus: server)
This commit is contained in:
129
crates/lanspread-server/src/req.rs
Normal file
129
crates/lanspread-server/src/req.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use lanspread_db::db::{GameDB, GameFileDescription};
|
||||
use lanspread_proto::{Request, Response};
|
||||
use lanspread_utils::maybe_addr;
|
||||
use s2n_quic::stream::SendStream;
|
||||
use tokio::sync::Mutex;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct RequestHandler {
|
||||
db: Arc<Mutex<GameDB>>,
|
||||
}
|
||||
|
||||
impl RequestHandler {
|
||||
pub(crate) fn new(games: GameDB) -> RequestHandler {
|
||||
RequestHandler {
|
||||
db: Arc::new(Mutex::new(games)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_request(&self, request: Request, games_folder: &Path) -> Response {
|
||||
match request {
|
||||
Request::Ping => Response::Pong,
|
||||
Request::ListGames => {
|
||||
let db = self.db.lock().await;
|
||||
Response::Games(db.all_games().into_iter().cloned().collect())
|
||||
}
|
||||
Request::GetGame { id } => {
|
||||
if self.db.lock().await.get_game_by_id(&id).is_none() {
|
||||
tracing::error!("Game not found in DB: {id}");
|
||||
return Response::GameNotFound(id);
|
||||
}
|
||||
|
||||
let game_dir = games_folder.join(&id);
|
||||
if !game_dir.exists() {
|
||||
tracing::error!("Game folder does not exist: {}", game_dir.display());
|
||||
return Response::GameNotFound(id);
|
||||
}
|
||||
|
||||
let mut game_files_descs: Vec<GameFileDescription> = vec![];
|
||||
|
||||
for entry in WalkDir::new(&game_dir)
|
||||
.into_iter()
|
||||
.filter_map(std::result::Result::ok)
|
||||
{
|
||||
match get_relative_path(games_folder, entry.path()) {
|
||||
Ok(relative_path) => match relative_path.to_str() {
|
||||
Some(relative_path) => {
|
||||
let game_file_description = GameFileDescription {
|
||||
game_id: id.clone(),
|
||||
relative_path: relative_path.to_string(),
|
||||
is_dir: entry.file_type().is_dir(),
|
||||
};
|
||||
|
||||
tracing::debug!("Found game file: {:?}", game_file_description);
|
||||
|
||||
game_files_descs.push(game_file_description);
|
||||
}
|
||||
None => {
|
||||
tracing::error!("Failed to get relative path: {relative_path:?}",);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to get relative path: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Response::GetGame(game_files_descs)
|
||||
}
|
||||
Request::GetGameFileData(_) => {
|
||||
Response::InvalidRequest(Bytes::new(), "Not implemented".to_string())
|
||||
}
|
||||
Request::Invalid(data, err_msg) => {
|
||||
tracing::error!(
|
||||
"got invalid request from client (error: {}): {}",
|
||||
err_msg,
|
||||
String::from_utf8_lossy(&data)
|
||||
);
|
||||
Response::InvalidRequest(data, err_msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn send_game_file_data(
|
||||
game_file_desc: &GameFileDescription,
|
||||
tx: &mut SendStream,
|
||||
game_dir: &Path,
|
||||
) {
|
||||
let remote_addr = maybe_addr!(tx.connection().remote_addr());
|
||||
|
||||
tracing::debug!("{remote_addr} client requested game file data: {game_file_desc:?}",);
|
||||
|
||||
// deliver file data to client
|
||||
let path = game_dir.join(&game_file_desc.relative_path);
|
||||
|
||||
if let Ok(mut file) = tokio::fs::File::open(&path).await {
|
||||
if let Err(e) = tokio::io::copy(&mut file, tx).await {
|
||||
tracing::error!("{remote_addr} failed to send file data: {e}",);
|
||||
}
|
||||
} else {
|
||||
tracing::error!("{remote_addr} failed to open file: {}", path.display());
|
||||
}
|
||||
|
||||
if let Err(e) = tx.close().await {
|
||||
tracing::error!("{remote_addr} failed to close stream: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn get_relative_path(base: &Path, deep_path: &Path) -> std::io::Result<PathBuf> {
|
||||
let base_canonical = base.canonicalize()?;
|
||||
let full_canonical = deep_path.canonicalize()?;
|
||||
|
||||
full_canonical
|
||||
.strip_prefix(&base_canonical)
|
||||
.map(std::path::Path::to_path_buf)
|
||||
.map_err(|_| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Path is not within base directory",
|
||||
)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user