2022-10-15 08:12:02 +00:00
|
|
|
use crate::cli_args::cli_args;
|
|
|
|
use crate::server;
|
2022-10-15 09:45:45 +00:00
|
|
|
use futures::stream::{SplitSink, SplitStream};
|
2022-10-15 08:12:02 +00:00
|
|
|
use futures::{SinkExt, StreamExt};
|
2022-10-18 06:58:36 +00:00
|
|
|
use sea_battle_backend::data::*;
|
2022-10-15 08:12:02 +00:00
|
|
|
use sea_battle_backend::human_player_ws::{ClientMessage, ServerMessage};
|
2022-10-17 16:47:33 +00:00
|
|
|
use sea_battle_backend::server::{
|
|
|
|
AcceptInviteQuery, BotPlayQuery, CreateInviteQuery, PlayRandomQuery,
|
|
|
|
};
|
2022-10-17 06:24:40 +00:00
|
|
|
use sea_battle_backend::utils::res_utils::{boxed_error, Res};
|
2022-10-18 06:58:36 +00:00
|
|
|
use std::error::Error;
|
2022-10-16 15:47:41 +00:00
|
|
|
use std::fmt::Display;
|
2022-10-15 09:45:45 +00:00
|
|
|
use std::sync::mpsc::TryRecvError;
|
2022-10-16 15:47:41 +00:00
|
|
|
use std::sync::{mpsc, Arc};
|
2022-10-15 08:12:02 +00:00
|
|
|
use tokio::net::TcpStream;
|
|
|
|
use tokio_tungstenite::tungstenite::Message;
|
|
|
|
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
|
|
|
|
|
2022-10-15 09:45:45 +00:00
|
|
|
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
|
|
|
|
2022-10-18 06:58:36 +00:00
|
|
|
pub enum GetRemoteVersionError {
|
|
|
|
ConnectionFailed,
|
|
|
|
Other(Box<dyn Error>),
|
|
|
|
}
|
|
|
|
|
2022-10-15 08:12:02 +00:00
|
|
|
/// Connection client
|
|
|
|
///
|
|
|
|
/// This structure acts as a wrapper around websocket connection that handles automatically parsing
|
|
|
|
/// of incoming messages and encoding of outgoing messages
|
|
|
|
pub struct Client {
|
2022-10-15 09:45:45 +00:00
|
|
|
sink: SplitSink<WsStream, Message>,
|
|
|
|
receiver: mpsc::Receiver<ServerMessage>,
|
2022-10-15 08:12:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Client {
|
2022-10-18 06:58:36 +00:00
|
|
|
/// Get remote server version
|
|
|
|
pub async fn get_server_version() -> Result<VersionInfo, GetRemoteVersionError> {
|
|
|
|
let url = format!("{}/version", cli_args().remote_server);
|
|
|
|
log::debug!("Getting remote information from {} ...", url);
|
|
|
|
|
|
|
|
let res = match reqwest::get(url).await {
|
|
|
|
Ok(r) => r,
|
|
|
|
Err(e) if e.is_timeout() || e.is_connect() => {
|
|
|
|
return Err(GetRemoteVersionError::ConnectionFailed)
|
|
|
|
}
|
|
|
|
Err(e) => return Err(GetRemoteVersionError::Other(Box::new(e))),
|
|
|
|
};
|
|
|
|
|
|
|
|
res.json()
|
|
|
|
.await
|
|
|
|
.map_err(|e| GetRemoteVersionError::Other(Box::new(e)))
|
|
|
|
}
|
|
|
|
|
2022-10-15 08:12:02 +00:00
|
|
|
/// Start to play against a bot
|
|
|
|
///
|
|
|
|
/// When playing against a bot, local server is always used
|
|
|
|
pub async fn start_bot_play(rules: &GameRules) -> Res<Self> {
|
|
|
|
server::start_server_if_missing().await;
|
|
|
|
|
|
|
|
Self::connect_url(
|
|
|
|
&cli_args().local_server_address(),
|
|
|
|
&format!(
|
|
|
|
"/play/bot?{}",
|
2023-05-01 08:28:43 +00:00
|
|
|
serde_urlencoded::to_string(BotPlayQuery {
|
2022-10-15 08:12:02 +00:00
|
|
|
rules: rules.clone(),
|
|
|
|
player_name: "Human".to_string()
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2022-10-16 15:47:41 +00:00
|
|
|
/// Start to play against a random player
|
|
|
|
pub async fn start_random_play<D: Display>(player_name: D) -> Res<Self> {
|
|
|
|
Self::connect_url(
|
2022-10-18 06:58:36 +00:00
|
|
|
&cli_args().remote_server,
|
2022-10-16 15:47:41 +00:00
|
|
|
&format!(
|
|
|
|
"/play/random?{}",
|
2023-05-01 08:28:43 +00:00
|
|
|
serde_urlencoded::to_string(PlayRandomQuery {
|
2022-10-16 15:47:41 +00:00
|
|
|
player_name: player_name.to_string()
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2022-10-17 16:47:33 +00:00
|
|
|
/// Start a play by creating an invite
|
|
|
|
pub async fn start_create_invite<D: Display>(rules: &GameRules, player_name: D) -> Res<Self> {
|
|
|
|
Self::connect_url(
|
2022-10-18 06:58:36 +00:00
|
|
|
&cli_args().remote_server,
|
2022-10-17 16:47:33 +00:00
|
|
|
&format!(
|
|
|
|
"/play/create_invite?{}",
|
2023-05-01 08:28:43 +00:00
|
|
|
serde_urlencoded::to_string(CreateInviteQuery {
|
2022-10-17 16:47:33 +00:00
|
|
|
rules: rules.clone(),
|
|
|
|
player_name: player_name.to_string()
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start a play by accepting an invite
|
|
|
|
pub async fn start_accept_invite<D: Display>(code: String, player_name: D) -> Res<Self> {
|
|
|
|
Self::connect_url(
|
2022-10-18 06:58:36 +00:00
|
|
|
&cli_args().remote_server,
|
2022-10-17 16:47:33 +00:00
|
|
|
&format!(
|
|
|
|
"/play/accept_invite?{}",
|
2023-05-01 08:28:43 +00:00
|
|
|
serde_urlencoded::to_string(AcceptInviteQuery {
|
2022-10-17 16:47:33 +00:00
|
|
|
code,
|
|
|
|
player_name: player_name.to_string()
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
2022-10-15 08:12:02 +00:00
|
|
|
/// Do connect to a server, returning
|
|
|
|
async fn connect_url(server: &str, uri: &str) -> Res<Self> {
|
2022-10-16 15:47:41 +00:00
|
|
|
let mut ws_url = server.replace("http", "ws");
|
|
|
|
ws_url.push_str(uri);
|
|
|
|
log::debug!("Connecting to {}", ws_url);
|
|
|
|
|
|
|
|
let (socket, _) = if ws_url.starts_with("wss") {
|
|
|
|
// Perform a connection over TLS
|
2024-01-17 18:08:38 +00:00
|
|
|
let mut roots = rustls::RootCertStore::empty();
|
|
|
|
for cert in rustls_native_certs::load_native_certs()? {
|
|
|
|
roots.add(cert).unwrap();
|
|
|
|
}
|
|
|
|
|
2022-10-16 15:47:41 +00:00
|
|
|
let config = rustls::ClientConfig::builder()
|
2024-01-17 18:08:38 +00:00
|
|
|
.with_root_certificates(roots)
|
2022-10-16 15:47:41 +00:00
|
|
|
.with_no_client_auth();
|
|
|
|
let connector = tokio_tungstenite::Connector::Rustls(Arc::new(config));
|
|
|
|
|
2024-01-17 17:52:47 +00:00
|
|
|
tokio_tungstenite::connect_async_tls_with_config(ws_url, None, false, Some(connector))
|
|
|
|
.await?
|
2022-10-16 15:47:41 +00:00
|
|
|
} else {
|
|
|
|
// Perform an unsecure connection
|
|
|
|
tokio_tungstenite::connect_async(ws_url).await?
|
|
|
|
};
|
2022-10-15 08:12:02 +00:00
|
|
|
|
2022-10-15 09:45:45 +00:00
|
|
|
let (sink, mut stream) = socket.split();
|
2022-10-15 08:12:02 +00:00
|
|
|
|
2022-10-15 09:45:45 +00:00
|
|
|
// Receive server message on a separate task
|
|
|
|
let (sender, receiver) = mpsc::channel();
|
|
|
|
tokio::task::spawn(async move {
|
|
|
|
loop {
|
|
|
|
match Self::recv_next_msg(&mut stream).await {
|
|
|
|
Ok(msg) => {
|
|
|
|
if let Err(e) = sender.send(msg.clone()) {
|
2022-10-16 16:06:31 +00:00
|
|
|
log::debug!("Failed to forward ws message! {} (msg={:?})", e, msg);
|
2022-10-15 09:45:45 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => {
|
2022-10-16 16:06:31 +00:00
|
|
|
log::debug!("Failed receive next message from websocket! {}", e);
|
2022-10-15 09:45:45 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(Self { sink, receiver })
|
2022-10-15 08:12:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Receive next message from stream
|
2022-10-15 09:45:45 +00:00
|
|
|
async fn recv_next_msg(stream: &mut SplitStream<WsStream>) -> Res<ServerMessage> {
|
2022-10-15 08:12:02 +00:00
|
|
|
loop {
|
2022-10-15 09:45:45 +00:00
|
|
|
let chunk = match stream.next().await {
|
2022-10-15 08:12:02 +00:00
|
|
|
None => return Err(boxed_error("No more message in queue!")),
|
|
|
|
Some(d) => d,
|
|
|
|
};
|
|
|
|
|
|
|
|
match chunk? {
|
|
|
|
Message::Text(t) => {
|
|
|
|
log::debug!("TEXT Got a text message from server!");
|
|
|
|
let msg: ServerMessage = serde_json::from_str(&t)?;
|
|
|
|
return Ok(msg);
|
|
|
|
}
|
|
|
|
Message::Binary(_) => {
|
|
|
|
log::debug!("BINARY Got an unexpected binary message");
|
|
|
|
return Err(boxed_error("Received an unexpected binary message!"));
|
|
|
|
}
|
|
|
|
Message::Ping(_) => {
|
|
|
|
log::debug!("PING Got a ping message from server");
|
|
|
|
}
|
|
|
|
Message::Pong(_) => {
|
|
|
|
log::debug!("PONG Got a pong message");
|
|
|
|
}
|
|
|
|
Message::Close(_) => {
|
|
|
|
log::debug!("CLOSE Got a close websocket message");
|
|
|
|
return Err(boxed_error("Server requested to close connection!"));
|
|
|
|
}
|
|
|
|
Message::Frame(_) => {
|
|
|
|
log::debug!("FRAME Got an unexpected frame from server!");
|
|
|
|
return Err(boxed_error("Got an unexpected frame!"));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Send a message through the stream
|
|
|
|
pub async fn send_message(&mut self, msg: &ClientMessage) -> Res {
|
2022-10-15 09:45:45 +00:00
|
|
|
self.sink
|
2022-10-15 08:12:02 +00:00
|
|
|
.send(Message::Text(serde_json::to_string(&msg)?))
|
|
|
|
.await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2022-10-15 09:45:45 +00:00
|
|
|
|
|
|
|
/// Try to receive next message from websocket, in a non-blocking way
|
|
|
|
pub async fn try_recv_next_message(&self) -> Res<Option<ServerMessage>> {
|
|
|
|
match self.receiver.try_recv() {
|
|
|
|
Ok(msg) => Ok(Some(msg)),
|
|
|
|
Err(TryRecvError::Empty) => Ok(None),
|
|
|
|
Err(TryRecvError::Disconnected) => Err(boxed_error("Receiver channel disconnected!")),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Block until the next message from websocket is availabl
|
|
|
|
pub async fn recv_next_message(&self) -> Res<ServerMessage> {
|
|
|
|
Ok(self.receiver.recv()?)
|
|
|
|
}
|
2022-10-16 16:35:07 +00:00
|
|
|
|
|
|
|
/// Close connection
|
|
|
|
pub async fn close_connection(&mut self) {
|
|
|
|
if let Err(e) = self.sink.send(Message::Close(None)).await {
|
|
|
|
log::debug!("Failed to close WS connection! {:?}", e);
|
|
|
|
}
|
|
|
|
}
|
2022-10-15 08:12:02 +00:00
|
|
|
}
|