From 24980707ec539a68566656d747de407306ae1f21 Mon Sep 17 00:00:00 2001 From: ThePerkinrex Date: Sat, 14 Nov 2020 20:14:12 +0100 Subject: [PATCH] Add server properties --- protobuf/game.proto | 5 +- server/.gitignore | 3 +- server/Cargo.toml | 2 +- server/schema/server-properties.json | 19 +++++ server/src/games/mod.rs | 3 - server/src/grpc.rs | 17 +++-- server/src/grpc/game.rs | 43 +++++++++-- server/src/logger.rs | 85 ++++++++++++++++------ server/src/main.rs | 6 +- server/src/server_properties.rs | 70 ++++++++++++++++++ unity/Assets/Scripts/Client.cs | 37 +++++++++- unity/Assets/Scripts/MainMenuController.cs | 4 + unity/Assets/Scripts/grpc/Game.cs | 85 +++++++++++----------- unity/Assets/Scripts/grpc/GameGrpc.cs | 50 ++++++++++--- 14 files changed, 328 insertions(+), 101 deletions(-) create mode 100644 server/schema/server-properties.json create mode 100644 server/src/server_properties.rs diff --git a/protobuf/game.proto b/protobuf/game.proto index 86f486b..48dddad 100644 --- a/protobuf/game.proto +++ b/protobuf/game.proto @@ -4,7 +4,8 @@ package game; // Connection utilities to get a client_id service Connection { - rpc connect(Username) returns(UserID); + rpc name(Null) returns(Name); + rpc connect(Name) returns(UserID); rpc joinLobbyWithCode(LobbyCode) returns(Null); rpc joinLobbyWithoutCode(Null) returns(LobbyCode); } @@ -22,7 +23,7 @@ message UserID { string id = 1; } -message Username { +message Name { string name = 1; } diff --git a/server/.gitignore b/server/.gitignore index 416be0b..d4e2763 100644 --- a/server/.gitignore +++ b/server/.gitignore @@ -2,4 +2,5 @@ Cargo.lock db.sqlite* /games -output.log \ No newline at end of file +output.log +properties.json \ No newline at end of file diff --git a/server/Cargo.toml b/server/Cargo.toml index 46f02e1..f579886 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -30,7 +30,7 @@ sqlx = { version = "0.3", default-features = false, features = [ "runtime-tokio" # TUI crossterm = "0.18.2" log = "0.4.11" -fern = "0.6.0" +fern = {version = "0.6.0", features = ["colored"]} chrono = "0.4.19" [build-dependencies] # Grpc codegen diff --git a/server/schema/server-properties.json b/server/schema/server-properties.json new file mode 100644 index 0000000..9a26295 --- /dev/null +++ b/server/schema/server-properties.json @@ -0,0 +1,19 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "ServerProperties", + "type": "object", + "properties": { + "addr": { + "default": "0.0.0.0:50052", + "type": "string" + }, + "name": { + "default": "Spah's sappin' mah sentreh", + "type": "string" + }, + "use_colors": { + "default": true, + "type": "boolean" + } + } +} \ No newline at end of file diff --git a/server/src/games/mod.rs b/server/src/games/mod.rs index 8b829c8..dfd3ce2 100644 --- a/server/src/games/mod.rs +++ b/server/src/games/mod.rs @@ -1,6 +1,3 @@ -use rhai::AST; -use log::info; - use std::fs::read_dir; mod config; mod run; diff --git a/server/src/grpc.rs b/server/src/grpc.rs index c727b01..348cd88 100644 --- a/server/src/grpc.rs +++ b/server/src/grpc.rs @@ -8,17 +8,18 @@ mod game; use game::connection_server::{Connection, ConnectionServer}; use game::lobby_server::{Lobby, LobbyServer}; -use game::{LobbyCode, Null, UserId, Username, CardId, Image}; +use game::{LobbyCode, Null, UserId, Name, CardId, Image}; use crate::db; pub struct ConnectionService { conn: Arc, + properties: Arc } #[tonic::async_trait] impl Connection for ConnectionService { - async fn connect(&self, request: Request) -> Result, Status> { + async fn connect(&self, request: Request) -> Result, Status> { let name = request.into_inner().name; let mut conn = self.conn.acquire().await; let uuid = conn.add_user(&name).await; @@ -59,7 +60,12 @@ impl Connection for ConnectionService { Ok(Response::new(LobbyCode{code: lobby})) } - + async fn name( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(game::Name {name: self.properties.name.clone() })) + } } @@ -116,9 +122,10 @@ impl Lobby for LobbyService { } } -pub async fn start(pool: db::DbPool, games: Vec) { +pub async fn start(pool: db::DbPool, games: Vec, properties: crate::server_properties::ServerProperties) { let arc = Arc::new(pool); - let connection = ConnectionService { conn: arc.clone() }; + let properties = Arc::new(properties); + let connection = ConnectionService { conn: arc.clone(), properties }; let lobby = LobbyService {conn: arc.clone(), games: Arc::new(games)}; Server::builder() diff --git a/server/src/grpc/game.rs b/server/src/grpc/game.rs index 38fb7fd..366d02f 100644 --- a/server/src/grpc/game.rs +++ b/server/src/grpc/game.rs @@ -4,7 +4,7 @@ pub struct UserId { pub id: std::string::String, } #[derive(Clone, PartialEq, ::prost::Message)] -pub struct Username { +pub struct Name { #[prost(string, tag = "1")] pub name: std::string::String, } @@ -66,9 +66,13 @@ pub mod connection_server { #[doc = "Generated trait containing gRPC methods that should be implemented for use with ConnectionServer."] #[async_trait] pub trait Connection: Send + Sync + 'static { + async fn name( + &self, + request: tonic::Request, + ) -> Result, tonic::Status>; async fn connect( &self, - request: tonic::Request, + request: tonic::Request, ) -> Result, tonic::Status>; async fn join_lobby_with_code( &self, @@ -112,16 +116,41 @@ pub mod connection_server { fn call(&mut self, req: http::Request) -> Self::Future { let inner = self.inner.clone(); match req.uri().path() { + "/game.Connection/name" => { + #[allow(non_camel_case_types)] + struct nameSvc(pub Arc); + impl tonic::server::UnaryService for nameSvc { + type Response = super::Name; + type Future = BoxFuture, tonic::Status>; + fn call(&mut self, request: tonic::Request) -> Self::Future { + let inner = self.0.clone(); + let fut = async move { (*inner).name(request).await }; + Box::pin(fut) + } + } + let inner = self.inner.clone(); + let fut = async move { + let interceptor = inner.1.clone(); + let inner = inner.0; + let method = nameSvc(inner); + let codec = tonic::codec::ProstCodec::default(); + let mut grpc = if let Some(interceptor) = interceptor { + tonic::server::Grpc::with_interceptor(codec, interceptor) + } else { + tonic::server::Grpc::new(codec) + }; + let res = grpc.unary(method, req).await; + Ok(res) + }; + Box::pin(fut) + } "/game.Connection/connect" => { #[allow(non_camel_case_types)] struct connectSvc(pub Arc); - impl tonic::server::UnaryService for connectSvc { + impl tonic::server::UnaryService for connectSvc { type Response = super::UserId; type Future = BoxFuture, tonic::Status>; - fn call( - &mut self, - request: tonic::Request, - ) -> Self::Future { + fn call(&mut self, request: tonic::Request) -> Self::Future { let inner = self.0.clone(); let fut = async move { (*inner).connect(request).await }; Box::pin(fut) diff --git a/server/src/logger.rs b/server/src/logger.rs index b361888..ebcbf0f 100644 --- a/server/src/logger.rs +++ b/server/src/logger.rs @@ -10,35 +10,63 @@ use crossterm::{ terminal::{Clear, ClearType}, }; +use fern::colors::{ColoredLevelConfig, Color}; pub fn setup() -> Result<(Close, Stdin), fern::InitError> { let (stdout, stdin, close, join_handle) = TerminalHandler::new(|x| { if x == "sv_cheats" { log::info!("CHEATS ENABLED") } x - }); + }); + let colors_line = ColoredLevelConfig::new() + .error(Color::Red) + .warn(Color::Yellow) + // we actually don't need to specify the color for debug and info, they are white by default + .info(Color::White) + .debug(Color::BrightBlack) + // depending on the terminals color scheme, this is the same as the background color + .trace(Color::BrightBlack); + let colors_level = colors_line.clone().info(Color::Green).debug(Color::BrightBlack); + let stdout_logger = fern::Dispatch::new() + .format(move |out, message, record| { + out.finish(format_args!( + "{colors_line}{}[{}{colors_line}][{}] {}\x1B[0m", + chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), + colors_level.clone().color(record.level()), + record.target(), + message, + colors_line = format!("\x1B[{}m", colors_line.clone().get_color(&record.level()).to_fg_str()), + // colors_level = colors_level.clone().get_color(&record.level()).to_fg_str(), + )) + }) + .level(log::LevelFilter::Debug) + .chain(stdout); + let file = fern::Dispatch::new().format(|out, message, record| { + out.finish(format_args!( + "{}[{}][{}] {}", + chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), + record.level(), + record.target(), + message, + )) + }) + .chain( + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open("output.log")?, + ); + fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{}[{}][{}] {}", - chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), - record.target(), - record.level(), - message - )) - }) - .level(log::LevelFilter::Debug) - .chain(stdout) - .chain( - std::fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .open("output.log")?, - ) + .level_for("h2::codec", log::LevelFilter::Info) + .level_for("tokio::codec", log::LevelFilter::Info) + .level_for("sqlx::query", log::LevelFilter::Info) + .chain(stdout_logger) + .chain(file) .apply()?; - log::info!("TEST1"); - log::info!("TEST2"); + log::warn!("TEST1"); + log::error!("TEST2"); // std::process::exit(1); Ok((Close{close, handle: join_handle}, stdin)) } @@ -122,13 +150,16 @@ where KeyCode::Char(c) => self.command.push(c), KeyCode::Backspace => {self.command.pop();}, KeyCode::Enter => { + log::info!(target: "COMMAND", "{}", self.command); match self.stdin.send((self.handler)(self.command.clone())) { Ok(_) => (), Err(e) => log::error!("{}", e), }; - self.lines.push(format!(" >> {}", self.command)); self.command = String::new(); - } + } + KeyCode::Esc => { + self.lines.scroll_to_bottom(); + } _ => () } }, @@ -244,14 +275,20 @@ impl LimitedVec { } fn scroll_up(&mut self) { - if self.pos + 1 < self.inner.len() { + if self.pos + self.size < self.inner.len() { + // log::info!("SCROLLING UP"); self.pos += 1; } } fn scroll_down(&mut self) { if self.pos > 0 { + // log::info!("SCROLLING DOWN"); self.pos -= 1; } } + + fn scroll_to_bottom(&mut self) { + self.pos = 0; + } } diff --git a/server/src/main.rs b/server/src/main.rs index c9f9d0e..dd91764 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -2,9 +2,12 @@ mod grpc; mod db; mod games; mod logger; +mod server_properties; #[tokio::main] async fn main() { + server_properties::setup(); + let p = server_properties::ServerProperties::load(); let (close, _stdin) = logger::setup().unwrap(); // protobuf::route_guide_grpc::RouteGuid // for i in 0..100 { @@ -26,7 +29,6 @@ async fn main() { // println!("{}", conn.add_user("Hi").await); // println!("{:?}", conn.users().await); // conn.close().await; - grpc::start(pool, games).await; - + grpc::start(pool, games, p).await; close.close(); } diff --git a/server/src/server_properties.rs b/server/src/server_properties.rs new file mode 100644 index 0000000..d0ee069 --- /dev/null +++ b/server/src/server_properties.rs @@ -0,0 +1,70 @@ +use std::net::SocketAddr; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)] +pub struct ServerProperties { + #[serde(default = "default_name")] + pub name: String, + #[serde(default = "default_addr")] + pub addr: SocketAddr, + #[serde(default = "default_colors")] + pub use_colors: bool, +} + +impl ServerProperties { + pub fn load() -> Self { + serde_json::from_str(&match std::fs::read_to_string("properties.json") { + Ok(v) => v, + Err(e) => { + println!("properties.json parsing error: {}", e); + std::process::exit(1) + } + }) + .unwrap() + } +} + +impl Default for ServerProperties { + fn default() -> Self { + Self { + name: default_name(), + addr: default_addr(), + use_colors: default_colors(), + } + } +} + +const fn default_colors() -> bool { + true +} + +fn default_addr() -> SocketAddr { + "0.0.0.0:50052".parse().unwrap() +} + +fn default_name() -> String { + "Spah's sappin' mah sentreh".into() +} + +pub fn setup() { + if cfg!(debug_assertions) { + if let Ok(e) = std::env::var("CARGO_MANIFEST_DIR") { + std::fs::write( + AsRef::::as_ref(&e) + .join("schema") + .join("server-properties.json"), + serde_json::to_string_pretty(&schemars::schema_for!(ServerProperties)).unwrap(), + ) + .unwrap() + } + } + if !std::path::PathBuf::from("properties.json").exists() { + std::fs::write("properties.json", serde_json::to_string_pretty(&ServerProperties::default()).unwrap()).unwrap(); + } + + if !std::path::PathBuf::from("games").exists() { + std::fs::create_dir("games").unwrap(); + } +} diff --git a/unity/Assets/Scripts/Client.cs b/unity/Assets/Scripts/Client.cs index 655417d..9c2be37 100644 --- a/unity/Assets/Scripts/Client.cs +++ b/unity/Assets/Scripts/Client.cs @@ -1,10 +1,12 @@ using Grpc.Core; -// using UnityEngine; +using System.Collections.Generic; +using System.Threading.Tasks; +using UnityEngine; public static class Client { private static Connection reference; - public static void Connect(string name, string address="127.0.0.1:50052") + public static void Connect(string name, string address = "127.0.0.1:50052") { reference = new Connection(name, address); } @@ -35,7 +37,11 @@ public static class Client channel = new Channel(address, ChannelCredentials.Insecure); connection = new Game.Connection.ConnectionClient(channel); lobby_client = new Game.Lobby.LobbyClient(channel); - connId = connection.connect(new Game.Username { Name = user }).Id; + connId = connection.connect(new Game.Name { Name_ = user }).Id; + } + + public string Name() { + return connection.name(new Game.Null()).Name_; } public void JoinLobby(string code) @@ -62,9 +68,32 @@ public static class Client } } + public List getGames() + { + AsyncServerStreamingCall stream = lobby_client.getGames(new Game.Null()); + List l = new List(); + + while (runSync(stream.ResponseStream.MoveNext())) + { + Game.Game g = stream.ResponseStream.Current; + l.Add(g); + // Debug.Log("Received " + feature.ToString()); + } + // Debug.Log(stream.ResponseStream.Current); + return l; + } + + static T runSync(Task task) + { + task.Wait(); + return task.Result; + } + public void Close() { channel.ShutdownAsync().Wait(); } } -} + + +} \ No newline at end of file diff --git a/unity/Assets/Scripts/MainMenuController.cs b/unity/Assets/Scripts/MainMenuController.cs index a6dc200..0eb69f3 100644 --- a/unity/Assets/Scripts/MainMenuController.cs +++ b/unity/Assets/Scripts/MainMenuController.cs @@ -39,6 +39,10 @@ public class MainMenuController : MonoBehaviour { Client.Connect(username.text); conn = Client.GetConnection(); } + + foreach (Game.Game g in conn.getGames()) { + Debug.Log(g.ToString()); + } if (conn != null) { mainMenu.SetActive(false); diff --git a/unity/Assets/Scripts/grpc/Game.cs b/unity/Assets/Scripts/grpc/Game.cs index 8fb98a7..dabb116 100644 --- a/unity/Assets/Scripts/grpc/Game.cs +++ b/unity/Assets/Scripts/grpc/Game.cs @@ -24,28 +24,29 @@ namespace Game { static GameReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( - "CgpnYW1lLnByb3RvEgRnYW1lIhQKBlVzZXJJRBIKCgJpZBgBIAEoCSIYCghV", - "c2VybmFtZRIMCgRuYW1lGAEgASgJIgYKBE51bGwiKAoGQ2FyZElEEg4KBmdh", - "bWVJZBgBIAEoBBIOCgZjYXJkSWQYAiABKAkiGAoFSW1hZ2USDwoHY29udGVu", - "dBgBIAEoDCIZCglMb2JieUNvZGUSDAoEY29kZRgBIAEoDSJCCgRHYW1lEgwK", - "BG5hbWUYASABKAkSDwoHdmVyc2lvbhgCIAEoCRIPCgdhdXRob3JzGAMgAygJ", - "EgoKAmlkGAQgASgEIhIKBFZvdGUSCgoCaWQYASABKAQiWQoLTG9iYnlTdGF0", - "dXMSGQoFdm90ZXMYASADKAsyCi5nYW1lLlZvdGUSGwoFcmVhZHkYAiADKAsy", - "DC5nYW1lLlBsYXllchISCgppc1N0YXJ0aW5nGAMgASgIIiIKBlBsYXllchIM", - "CgRuYW1lGAEgASgJEgoKAmlkGAIgASgEMpwBCgpDb25uZWN0aW9uEicKB2Nv", - "bm5lY3QSDi5nYW1lLlVzZXJuYW1lGgwuZ2FtZS5Vc2VySUQSMAoRam9pbkxv", - "YmJ5V2l0aENvZGUSDy5nYW1lLkxvYmJ5Q29kZRoKLmdhbWUuTnVsbBIzChRq", - "b2luTG9iYnlXaXRob3V0Q29kZRIKLmdhbWUuTnVsbBoPLmdhbWUuTG9iYnlD", - "b2RlMsIBCgVMb2JieRIkCghnZXRHYW1lcxIKLmdhbWUuTnVsbBoKLmdhbWUu", - "R2FtZTABEikKDGdldENhcmRJbWFnZRIMLmdhbWUuQ2FyZElEGgsuZ2FtZS5J", - "bWFnZRIeCgR2b3RlEgouZ2FtZS5Wb3RlGgouZ2FtZS5OdWxsEh8KBXJlYWR5", - "EgouZ2FtZS5OdWxsGgouZ2FtZS5OdWxsEicKBnN0YXR1cxIKLmdhbWUuTnVs", - "bBoRLmdhbWUuTG9iYnlTdGF0dXNiBnByb3RvMw==")); + "CgpnYW1lLnByb3RvEgRnYW1lIhQKBlVzZXJJRBIKCgJpZBgBIAEoCSIUCgRO", + "YW1lEgwKBG5hbWUYASABKAkiBgoETnVsbCIoCgZDYXJkSUQSDgoGZ2FtZUlk", + "GAEgASgEEg4KBmNhcmRJZBgCIAEoCSIYCgVJbWFnZRIPCgdjb250ZW50GAEg", + "ASgMIhkKCUxvYmJ5Q29kZRIMCgRjb2RlGAEgASgNIkIKBEdhbWUSDAoEbmFt", + "ZRgBIAEoCRIPCgd2ZXJzaW9uGAIgASgJEg8KB2F1dGhvcnMYAyADKAkSCgoC", + "aWQYBCABKAQiEgoEVm90ZRIKCgJpZBgBIAEoBCJZCgtMb2JieVN0YXR1cxIZ", + "CgV2b3RlcxgBIAMoCzIKLmdhbWUuVm90ZRIbCgVyZWFkeRgCIAMoCzIMLmdh", + "bWUuUGxheWVyEhIKCmlzU3RhcnRpbmcYAyABKAgiIgoGUGxheWVyEgwKBG5h", + "bWUYASABKAkSCgoCaWQYAiABKAQyuAEKCkNvbm5lY3Rpb24SHgoEbmFtZRIK", + "LmdhbWUuTnVsbBoKLmdhbWUuTmFtZRIjCgdjb25uZWN0EgouZ2FtZS5OYW1l", + "GgwuZ2FtZS5Vc2VySUQSMAoRam9pbkxvYmJ5V2l0aENvZGUSDy5nYW1lLkxv", + "YmJ5Q29kZRoKLmdhbWUuTnVsbBIzChRqb2luTG9iYnlXaXRob3V0Q29kZRIK", + "LmdhbWUuTnVsbBoPLmdhbWUuTG9iYnlDb2RlMsIBCgVMb2JieRIkCghnZXRH", + "YW1lcxIKLmdhbWUuTnVsbBoKLmdhbWUuR2FtZTABEikKDGdldENhcmRJbWFn", + "ZRIMLmdhbWUuQ2FyZElEGgsuZ2FtZS5JbWFnZRIeCgR2b3RlEgouZ2FtZS5W", + "b3RlGgouZ2FtZS5OdWxsEh8KBXJlYWR5EgouZ2FtZS5OdWxsGgouZ2FtZS5O", + "dWxsEicKBnN0YXR1cxIKLmdhbWUuTnVsbBoRLmdhbWUuTG9iYnlTdGF0dXNi", + "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Game.UserID), global::Game.UserID.Parser, new[]{ "Id" }, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::Game.Username), global::Game.Username.Parser, new[]{ "Name" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Game.Name), global::Game.Name.Parser, new[]{ "Name_" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Game.Null), global::Game.Null.Parser, null, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Game.CardID), global::Game.CardID.Parser, new[]{ "GameId", "CardId" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Game.Image), global::Game.Image.Parser, new[]{ "Content" }, null, null, null, null), @@ -232,15 +233,15 @@ namespace Game { } - public sealed partial class Username : pb::IMessage + public sealed partial class Name : pb::IMessage #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { - private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Username()); + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Name()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public static pb::MessageParser Parser { get { return _parser; } } + public static pb::MessageParser Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { @@ -253,28 +254,28 @@ namespace Game { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public Username() { + public Name() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public Username(Username other) : this() { + public Name(Name other) : this() { name_ = other.name_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public Username Clone() { - return new Username(this); + public Name Clone() { + return new Name(this); } /// Field number for the "name" field. - public const int NameFieldNumber = 1; + public const int Name_FieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public string Name { + public string Name_ { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); @@ -283,25 +284,25 @@ namespace Game { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { - return Equals(other as Username); + return Equals(other as Name); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public bool Equals(Username other) { + public bool Equals(Name other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } - if (Name != other.Name) return false; + if (Name_ != other.Name_) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; - if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Name_.Length != 0) hash ^= Name_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } @@ -318,9 +319,9 @@ namespace Game { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else - if (Name.Length != 0) { + if (Name_.Length != 0) { output.WriteRawTag(10); - output.WriteString(Name); + output.WriteString(Name_); } if (_unknownFields != null) { _unknownFields.WriteTo(output); @@ -331,9 +332,9 @@ namespace Game { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { - if (Name.Length != 0) { + if (Name_.Length != 0) { output.WriteRawTag(10); - output.WriteString(Name); + output.WriteString(Name_); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); @@ -344,8 +345,8 @@ namespace Game { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; - if (Name.Length != 0) { - size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + if (Name_.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name_); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); @@ -354,12 +355,12 @@ namespace Game { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] - public void MergeFrom(Username other) { + public void MergeFrom(Name other) { if (other == null) { return; } - if (other.Name.Length != 0) { - Name = other.Name; + if (other.Name_.Length != 0) { + Name_ = other.Name_; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } @@ -376,7 +377,7 @@ namespace Game { _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { - Name = input.ReadString(); + Name_ = input.ReadString(); break; } } @@ -394,7 +395,7 @@ namespace Game { _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { - Name = input.ReadString(); + Name_ = input.ReadString(); break; } } diff --git a/unity/Assets/Scripts/grpc/GameGrpc.cs b/unity/Assets/Scripts/grpc/GameGrpc.cs index 85392f0..f1b4e3e 100644 --- a/unity/Assets/Scripts/grpc/GameGrpc.cs +++ b/unity/Assets/Scripts/grpc/GameGrpc.cs @@ -45,16 +45,23 @@ namespace Game { return parser.ParseFrom(context.PayloadAsNewBuffer()); } - static readonly grpc::Marshaller __Marshaller_game_Username = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Username.Parser)); + static readonly grpc::Marshaller __Marshaller_game_Null = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Null.Parser)); + static readonly grpc::Marshaller __Marshaller_game_Name = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Name.Parser)); static readonly grpc::Marshaller __Marshaller_game_UserID = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.UserID.Parser)); static readonly grpc::Marshaller __Marshaller_game_LobbyCode = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.LobbyCode.Parser)); - static readonly grpc::Marshaller __Marshaller_game_Null = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Null.Parser)); - static readonly grpc::Method __Method_connect = new grpc::Method( + static readonly grpc::Method __Method_name = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "name", + __Marshaller_game_Null, + __Marshaller_game_Name); + + static readonly grpc::Method __Method_connect = new grpc::Method( grpc::MethodType.Unary, __ServiceName, "connect", - __Marshaller_game_Username, + __Marshaller_game_Name, __Marshaller_game_UserID); static readonly grpc::Method __Method_joinLobbyWithCode = new grpc::Method( @@ -81,7 +88,12 @@ namespace Game { [grpc::BindServiceMethod(typeof(Connection), "BindService")] public abstract partial class ConnectionBase { - public virtual global::System.Threading.Tasks.Task connect(global::Game.Username request, grpc::ServerCallContext context) + public virtual global::System.Threading.Tasks.Task name(global::Game.Null request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task connect(global::Game.Name request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } @@ -121,19 +133,35 @@ namespace Game { { } - public virtual global::Game.UserID connect(global::Game.Username request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + public virtual global::Game.Name name(global::Game.Null request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return name(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::Game.Name name(global::Game.Null request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_name, null, options, request); + } + public virtual grpc::AsyncUnaryCall nameAsync(global::Game.Null request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return nameAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall nameAsync(global::Game.Null request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_name, null, options, request); + } + public virtual global::Game.UserID connect(global::Game.Name request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return connect(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } - public virtual global::Game.UserID connect(global::Game.Username request, grpc::CallOptions options) + public virtual global::Game.UserID connect(global::Game.Name request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_connect, null, options, request); } - public virtual grpc::AsyncUnaryCall connectAsync(global::Game.Username request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + public virtual grpc::AsyncUnaryCall connectAsync(global::Game.Name request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return connectAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } - public virtual grpc::AsyncUnaryCall connectAsync(global::Game.Username request, grpc::CallOptions options) + public virtual grpc::AsyncUnaryCall connectAsync(global::Game.Name request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_connect, null, options, request); } @@ -181,6 +209,7 @@ namespace Game { public static grpc::ServerServiceDefinition BindService(ConnectionBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_name, serviceImpl.name) .AddMethod(__Method_connect, serviceImpl.connect) .AddMethod(__Method_joinLobbyWithCode, serviceImpl.joinLobbyWithCode) .AddMethod(__Method_joinLobbyWithoutCode, serviceImpl.joinLobbyWithoutCode).Build(); @@ -192,7 +221,8 @@ namespace Game { /// An object implementing the server-side handling logic. public static void BindService(grpc::ServiceBinderBase serviceBinder, ConnectionBase serviceImpl) { - serviceBinder.AddMethod(__Method_connect, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.connect)); + serviceBinder.AddMethod(__Method_name, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.name)); + serviceBinder.AddMethod(__Method_connect, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.connect)); serviceBinder.AddMethod(__Method_joinLobbyWithCode, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.joinLobbyWithCode)); serviceBinder.AddMethod(__Method_joinLobbyWithoutCode, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.joinLobbyWithoutCode)); }