client mezzo interattivo

This commit is contained in:
clizia 2025-03-04 14:32:49 +01:00
parent ed3c9694c0
commit 6fe2cfb5d7
3 changed files with 92 additions and 30 deletions

View file

@ -1,41 +1,93 @@
use std::{io::{Stdout, Write}, ops::BitOrAssign, time::Duration};
use axum::response::sse::Event;
use clap::builder::NonEmptyStringValueParser;
use lib::{client::Client, message::{Message, MessageKind}, message_read::MessageReader, player::Player};
use crossterm::{
execute,
terminal::{
Clear,
ClearType,
enable_raw_mode,
disable_raw_mode
},
event::Event,
cursor, event::{self, poll, Event as TermEvent, KeyCode, KeyModifiers}, execute, queue, style, terminal::{
disable_raw_mode, enable_raw_mode, Clear, ClearType, EnableLineWrap
}
};
const HELP: &str = r#"CIAOTERPIA
atm posso fare questo:
(ricorda di premere i bottoni)
- '1' mando giocante
- '2' mando lobbando (futuro)
"#;
fn create_message_player(player: &Player) -> anyhow::Result<Message, anyhow::Error> {
Message::new(
&player.get_name(),
MessageKind::Test,
player.encode()?
)
}
async fn send_player(player: &Player, client: reqwest::Client, addr: &str) -> anyhow::Result<()> {
let player_message = create_message_player(&player)?;
let response = client
.post([&addr, "/create/player"].concat())
.header("Content-Type", "application/json")
.body(player_message.encode()?)
.send().await;
if let Err(e) = &response {
println!("{e}\n");
return Ok(())
}
Ok(())
}
async fn handle_terminal(player: &Player, stdout: &mut Stdout, client: reqwest::Client, addr: &str) -> anyhow::Result<()> {
'handler: loop {
for line in HELP.split('\n') {
queue!(stdout, style::Print(line), cursor::MoveToNextLine(1))?;
}
stdout.flush()?;
while let Ok(_event_happened) = poll(Duration::from_millis(2)) {
match event::read().expect("diomerds") {
TermEvent::Key(key) => {
match (key.code, key.modifiers) {
(KeyCode::Char('c'), KeyModifiers::CONTROL) => break 'handler,
(KeyCode::Char('1'), KeyModifiers::NONE) => send_player(&player, client.clone(), addr).await?,
(_, _) => println!("{:?}\n", key),
}
},
_ => continue,
}
}
}
Ok(())
}
#[tokio::main]
pub async fn main() -> anyhow::Result<()> {
// let mut client = Client::connect("127.0.0.1", 8080).await?;
// let local_address = client.stream.local_addr()?;
// enable_raw_mode()?;
// execute!(
// std::io::stdout(),
// Clear(ClearType::All),
// )?;
let mut stdout = std::io::stdout();
let addr = "http://127.0.0.1:8080";
let client = reqwest::Client::new();
enable_raw_mode()?;
execute!(
stdout,
Clear(ClearType::All),
EnableLineWrap,
cursor::Show,
cursor::EnableBlinking,
)?;
let player = Player::new()?;
let message = Message::new(&player.get_name(), MessageKind::Test, player.encode()?)?;
let response = client
.post([&addr, "/create/player"].concat())
.header("Content-Type", "application/json")
.body(message.encode()?)
.send().await?
.text().await?;
println!("{}", response);
let addr = "http://127.0.0.1:8080";
let client = reqwest::Client::new();
println!("{}", HELP);
handle_terminal(&player, &mut stdout, client.clone(), &addr).await?;
disable_raw_mode()?;
Ok(())
}

View file

@ -1,10 +1,13 @@
use anyhow::Result;
use axum::{
body::Bytes, extract::{
rejection::JsonRejection, Json, State
}, response::ErrorResponse, Router
rejection::JsonRejection,
Json,
State,
},
http::StatusCode,
Router
};
use hyper::StatusCode;
use crate::{message::Message, player::Player};
use crate::db::AppState;
@ -33,8 +36,7 @@ impl App {
pub async fn create_player(
State(db): State<AppState>,
json_body: Result<Json<Message>, JsonRejection>,
) -> Result<axum::Json<Message>, StatusCode>
{
) -> Result<axum::Json<Message>, StatusCode> {
match json_body {
Ok(Json(message)) => {
println!("{:?}", message);
@ -55,4 +57,11 @@ impl App {
Err(_) => Err(StatusCode::UNPROCESSABLE_ENTITY)
}
}
pub async fn create_lobby(
State(db): State<AppState>,
json_body: Result<Json<Message>, JsonRejection>,
) -> Result<axum::Json<Message>, StatusCode> {
todo!()
}
}

View file

@ -30,6 +30,7 @@ impl Server {
let router = app.router
.route("/echo", post(App::echo))
.route("/create/player", post(App::create_player))
.route("/create/lobby", post(App::create_lobby))
.with_state(app.db);
axum::serve(listener, router).await.unwrap();