From 7c74d3a0cd6cdb5ba53a80133f132cb4cfb3aaab Mon Sep 17 00:00:00 2001 From: Jack Bishop Date: Sat, 26 Sep 2020 22:28:10 +0200 Subject: [PATCH 01/32] First pass at altering and streamline current method to send or recieve data from the api --- SwitchMe/Commands.cs | 206 ++++---------------------------- SwitchMe/SwitchMe.csproj | 16 +-- SwitchMe/SwitchMePlugin.cs | 238 ++++++++++++++++--------------------- SwitchMe/Utilities.cs | 18 +++ 4 files changed, 151 insertions(+), 327 deletions(-) diff --git a/SwitchMe/Commands.cs b/SwitchMe/Commands.cs index 3021986..78954c2 100644 --- a/SwitchMe/Commands.cs +++ b/SwitchMe/Commands.cs @@ -71,6 +71,13 @@ public async Task SwitchLocalAsync() { await voidManager.PlayerTransfer("single", Sandbox.Game.Multiplayer.Sync.MyId); } + + [Command("debug")] + [Permission(MyPromoteLevel.Admin)] + public void debug(bool state) { + Plugin.debug = state; + } + [Command("all", "Automatically connects all players to your server of choice within this network. USAGE: !switch all ")] [Permission(MyPromoteLevel.Admin)] public async Task SwitchAllAsync() { @@ -208,154 +215,29 @@ public async void Recover() { string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; Log.Warn("Removing conneciton flag for " + player); + + Dictionary webData = new Dictionary(); + + webData.Add("BindKey", Plugin.Config.LocalKey); + webData.Add("CurrentIP", currentIp); + webData.Add("RemoveConnection", player.ToString()); + using (HttpClient client = new HttpClient()) { + + List> test = new List>(); List> pairs = new List> { new KeyValuePair("BindKey", Plugin.Config.LocalKey), new KeyValuePair("CurrentIP", currentIp ), new KeyValuePair("RemoveConnection", player.ToString()) }; + + test.Add(new KeyValuePair("BindKey",Plugin.Config.LocalKey)); FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); await client.PostAsync(Plugin.API_URL, content); } } - /* - [Command("grid", "Transfers the target grid to the target server")] - [Permission(MyPromoteLevel.None)] - public async Task GridAsync(string gridTarget, string serverTarget) { - - if (!Plugin.Config.Enabled) { - Context.Respond("SwitchMe not enabled"); - return; - } - if (Context.Player == null) { - Context.Respond("Console cannot run this command"); - return; - } - if (!Plugin.Config.EnabledTransfers) { - Context.Respond("Grid Transfers are not enabled!"); - return; - } - - int i = 0; - string ip = ""; - string name = ""; - string port = ""; - string existanceCheck = ""; - - IEnumerable channelIds = Plugin.Config.Servers; - foreach (string chId in channelIds) { - - ip = chId.Split(':')[1]; - name = chId.Split(':')[0]; - port = chId.Split(':')[2]; - i++; - } - channelIds = Plugin.Config.Servers.Where(c => c.Split(':')[0].Equals(serverTarget)); - foreach (string chId in channelIds) { - - ip = chId.Split(':')[1]; - name = chId.Split(':')[0]; - port = chId.Split(':')[2]; - } - - string target = ip + ":" + port; - ip += ":" + port; - if (ip == null || name == null || port == null) { - Context.Respond("Invalid Configuration!"); - return; - } - - - string slotinfo = await Plugin.CheckSlotsAsync(target); - existanceCheck = slotinfo.Split(';').Last(); - bool paired = await Plugin.CheckKeyAsync(target); - - if (target.Length < 1) { - Context.Respond("Unknown Server. Please use '!switch list' to see a list of validated servers!"); - return; - } - - if (existanceCheck != "1") { - Context.Respond("Cannot communicate with target, please make sure SwitchMe is installed there!"); - return; - } - - if (!paired) { - Context.Respond("Unauthorised Switch! Please make sure the servers have the same Bind Key!"); - return; - } - - if (!Plugin.CheckStatus(target)) { - Context.Respond("Target server is offline... preventing switch"); - return; - } - - bool InboundCheck = await Plugin.CheckInboundAsync(target); - if (!InboundCheck) { - Context.Respond("The target server does not allow inbound transfers"); - return; - } - - Log.Warn("Checking " + target); - int currentRemotePlayers = int.Parse(slotinfo.Substring(0, slotinfo.IndexOf(":"))); - string max = slotinfo.Substring(slotinfo.IndexOf(':') + 1, slotinfo.IndexOf(';') - slotinfo.IndexOf(':') - 1); - Log.Warn("MAX: " + max); - int maxi = int.Parse(max); - int maxcheck = 1 + currentRemotePlayers; - Context.Respond("Slot Checking..."); - Log.Warn(maxcheck + " Player Count Prediction|Player Count Threshold " + max); - if (maxcheck > maxi && Context.Player.PromoteLevel != MyPromoteLevel.Admin) { - Log.Warn("Not enough slots available."); - Context.Respond("No slots available."); - return; - } - var player = MySession.Static.Players.GetPlayerByName(Context.Player.DisplayName); - if (player != null) { - // If he is online we check if he is currently seated. If he is eject him. - if (player?.Controller.ControlledEntity is MyCockpit controller) { - MyAPIGateway.Utilities.InvokeOnGameThread(() => { - controller.Use(); - }); - } - try { - - string externalIP = utils.CreateExternalIP(Plugin.Config); - string pagesource = ""; - string currentIp = externalIP + ":" + MySandboxGame.ConfigDedicated.ServerPort; - - //Not sure what this does but it does not belong here - using (WebClient client = new WebClient()) { - NameValueCollection postData = new NameValueCollection() - { - {"steamID", Context.Player.SteamUserId + ""}, - {"currentIP", currentIp }, - {"gridCheck", ""} - }; - pagesource = Encoding.UTF8.GetString(client.UploadValues("http://switchplugin.net/gridHandle.php", postData)); - } - - if (pagesource == "0") { - if (!await new VoidManager(Plugin).SendGrid(gridTarget, serverTarget, Context.Player.DisplayName, Context.Player.IdentityId, target)) { - return; - } - Log.Warn("Connected clients to " + serverTarget + " @ " + ip); - } - else { - Log.Fatal(pagesource); - Context.Respond("Cannot transfer! You have a transfer ready to be recieved!"); - return; - } - } - catch (Exception e) { - Log.Fatal(e, e.Message); - Context.Respond("Failure"); - } - } - } - */ - [Command("restore", "Completes the transfer of one grid from one server to another")] [Permission(MyPromoteLevel.None)] public void Restore() { @@ -365,56 +247,14 @@ public void Restore() { [Command("reload", "Reload and refresh jumpgates with debug options")] [Permission(MyPromoteLevel.Admin)] public void reload() { - //Delete all registered gates - int i = 0; - foreach (var zone in Plugin.zones) { - foreach (var entity in MyEntities.GetEntities()) { - if (entity?.DisplayName?.Contains(zone, StringComparison.CurrentCultureIgnoreCase) ?? false) { - i++; - entity.Close(); - } - } - } - IMyPlayer player = Context.Player; - if (player == null) { - Context.Respond($"{i} Jumpgates closed!"); - } - else { - utils.NotifyMessage($"{i} Jumpgates closed!", Context.Player.SteamUserId); - } - - //Rebuild all gates - int gates = 0; - IEnumerable channelIds = Plugin.Config.Gates; - string name = ""; - string location = ""; - foreach (string chId in channelIds) { - name = chId.Split('/')[0]; - location = chId.Split('/')[1]; - location = location.TrimStart('{').TrimEnd('}'); - Vector3D.TryParse(location, out Vector3D gps); - var ob = new MyObjectBuilder_SafeZone(); - ob.PositionAndOrientation = new MyPositionAndOrientation(gps, Vector3.Forward, Vector3.Up); - ob.PersistentFlags = MyPersistentEntityFlags2.InScene; - ob.Shape = MySafeZoneShape.Sphere; - ob.Radius = Plugin.Config.GateSize; - ob.Enabled = true; - ob.DisplayName = $"SM-{gps}"; - ob.AccessTypeGrids = MySafeZoneAccess.Blacklist; - ob.AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist; - ob.AccessTypeFactions = MySafeZoneAccess.Blacklist; - ob.AccessTypePlayers = MySafeZoneAccess.Blacklist; - var zone = MyEntities.CreateFromObjectBuilderAndAdd(ob, true); - gates++; - if (!Plugin.zones.Contains(ob.DisplayName)) { - Plugin.zones.Add(ob.DisplayName); - } - } + var player = Context.Player; + Plugin.CloseGates(); + Plugin.OpenGates(); if (player == null) { - Context.Respond($"{gates} Jumpgates created!"); + Context.Respond($"Jumpgates created!"); } else { - utils.NotifyMessage($"{gates} Jumpgates created!", Context.Player.SteamUserId); + utils.NotifyMessage($"Jumpgates created!", Context.Player.SteamUserId); } } diff --git a/SwitchMe/SwitchMe.csproj b/SwitchMe/SwitchMe.csproj index b5cc7e3..d5ff6e2 100644 --- a/SwitchMe/SwitchMe.csproj +++ b/SwitchMe/SwitchMe.csproj @@ -69,27 +69,27 @@ - ..\packages\System.Buffers.4.5.0\lib\netstandard2.0\System.Buffers.dll + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll - ..\packages\System.Memory.4.5.3\lib\netstandard2.0\System.Memory.dll + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll - ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + ..\packages\System.Runtime.CompilerServices.Unsafe.4.7.1\lib\net461\System.Runtime.CompilerServices.Unsafe.dll - ..\packages\System.Text.Encodings.Web.4.7.0\lib\netstandard2.0\System.Text.Encodings.Web.dll + ..\packages\System.Text.Encodings.Web.4.7.1\lib\net461\System.Text.Encodings.Web.dll - - ..\packages\System.Text.Json.4.7.1\lib\net461\System.Text.Json.dll + + ..\packages\System.Text.Json.4.7.2\lib\net461\System.Text.Json.dll - - ..\packages\System.Threading.Tasks.Extensions.4.5.2\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll ..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll diff --git a/SwitchMe/SwitchMePlugin.cs b/SwitchMe/SwitchMePlugin.cs index 4e8ff1b..86cbf09 100644 --- a/SwitchMe/SwitchMePlugin.cs +++ b/SwitchMe/SwitchMePlugin.cs @@ -104,6 +104,7 @@ public sealed class SwitchMePlugin : TorchPluginBase, IWpfPlugin { public UserControl GetControl() => _control ?? (_control = new SwitchMeControl(this)); public void Save() => _config?.Save(); MyPlayer player; + public bool debug = false; public string API_URL = "http://switchplugin.net/api/index.php"; public bool loadFailure = false; @@ -149,16 +150,11 @@ private async void Multibase_PlayerJoined(IPlayer obj) { string externalIP = Sandbox.MySandboxExternal.ConfigDedicated.IP; string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; - using (HttpClient clients = new HttpClient()) { - List> pairs = new List> - { - new KeyValuePair("existanceCheck",obj.SteamId.ToString()), - new KeyValuePair("currentIP", currentIp) - }; - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - response = await clients.PostAsync(API_URL, content); - } - Dictionary gridData = utils.ParseQueryString(await response.Content.ReadAsStringAsync()); + var utils = new utils(); + utils.webdata.Add("existanceCheck", obj.SteamId.ToString()); + utils.webdata.Add("currentIP", currentIp); + Dictionary gridData = utils.ParseQueryString(await utils.SendAPIRequestAsync()); + Directory.CreateDirectory("SwitchTemp"); if (gridData["filename"] != "NULL") { filename = gridData["filename"] + ".xml"; @@ -185,61 +181,53 @@ private async void Multibase_PlayerJoined(IPlayer obj) { } string POS = ""; - string POSsource = ""; - using (HttpClient clients = new HttpClient()) { - List> pairs = new List> - { - new KeyValuePair("recover", obj.SteamId.ToString()), - new KeyValuePair("currentIP", currentIp), - new KeyValuePair("bindKey", Config.LocalKey) - }; - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - HttpResponseMessage httpResponseMessage = await clients.PostAsync(API_URL, content); - response = httpResponseMessage; - httpResponseMessage = null; - string texts = await response.Content.ReadAsStringAsync(); - POSsource = texts; - // - // DO THE RANDOMISER SHIT BISH - // - bool foundGate = false; - IEnumerable channelIds = Config.Gates.Where(c => c.Split('/')[2].Equals(POSsource)); - foreach (string chId in channelIds) { - POS = chId.Split('/')[1]; - foundGate = true; - } - if (Config.RandomisedExit) { - Dictionary gateSelection = new Dictionary(); - channelIds = Config.Gates; - int i = 0; - foreach (string gate in channelIds) { - i++; - gateSelection.Add(gate.Split('/')[2], gate.Split('/')[1]); - } - if (i != 0) { - POS = utils.SelectRandomGate(gateSelection); - } - } - if (!Config.RandomisedExit) { - Log.Warn($"API: Gate elected = {POSsource}"); + utils.webdata.Add("recover", obj.SteamId.ToString()); + utils.webdata.Add("currentIP", currentIp); + utils.webdata.Add("bindkey", Config.LocalKey); + string api_response = await utils.SendAPIRequestAsync(); + + + // + // DO THE RANDOMISER SHIT BISH + // + bool foundGate = false; + IEnumerable channelIds = Config.Gates.Where(c => c.Split('/')[2].Equals(api_response)); + foreach (string chId in channelIds) { + POS = chId.Split('/')[1]; + foundGate = true; + } + if (Config.RandomisedExit) { + Dictionary gateSelection = new Dictionary(); + channelIds = Config.Gates; + int i = 0; + foreach (string gate in channelIds) { + i++; + gateSelection.Add(gate.Split('/')[2], gate.Split('/')[1]); } - else { - Log.Warn("Using randomly selected gate as exit"); + if (i != 0) { + POS = utils.SelectRandomGate(gateSelection); } + } + if (!Config.RandomisedExit) { + Log.Warn($"API: Gate elected = {api_response}"); + } + else { + Log.Warn("Using randomly selected gate as exit"); + } - if (!foundGate) { - POS = "{X:" + Config.XCord + " Y:" + Config.YCord + " Z:" + Config.ZCord + "}"; - Log.Error($"Target gate ({POSsource}) does not exist... Using default"); - } - /* - else if (config.EnabledMirror) - POS = POSsource.Substring(0, POSsource.IndexOf("^")); - */ - POS = POS.TrimStart('{').TrimEnd('}'); - Vector3D.TryParse(POS, out Vector3D gps); - spawn_vector_location = gps; - Log.Info("Selected GPS: " + gps.ToString()); + if (!foundGate) { + POS = "{X:" + Config.XCord + " Y:" + Config.YCord + " Z:" + Config.ZCord + "}"; + Log.Error($"Target gate ({api_response}) does not exist... Using default"); } + /* + else if (config.EnabledMirror) + POS = POSsource.Substring(0, POSsource.IndexOf("^")); + */ + POS = POS.TrimStart('{').TrimEnd('}'); + Vector3D.TryParse(POS, out Vector3D gps); + spawn_vector_location = gps; + Log.Info("Selected GPS: " + gps.ToString()); + if (!connecting.ContainsKey(obj.SteamId)) { connecting.Add(obj.SteamId, true); } @@ -699,7 +687,7 @@ public bool UpdateGridsPosition(MyObjectBuilder_CubeGrid[] grids, Vector3D newPo return true; } - public async Task RemoveConnection(ulong player) { + public string currentIP() { string externalIP = Sandbox.MySandboxExternal.ConfigDedicated.IP; if (externalIP.Contains("0.0") || externalIP.Contains("127.0") @@ -708,59 +696,29 @@ public async Task RemoveConnection(ulong player) { } string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; + + return currentIp; + } + public async Task RemoveConnection(ulong player) { Log.Warn("Removing conneciton flag for " + player); - using (HttpClient client = new HttpClient()) { - List> pairs = new List> - { - new KeyValuePair("BindKey", Config.LocalKey), - new KeyValuePair("CurrentIP", currentIp ), - new KeyValuePair("RemoveConnection", player.ToString()) - }; - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - await client.PostAsync(API_URL, content); - } + utils.webdata.Add("BindKey", Config.LocalKey); + utils.webdata.Add("CurrnetIP", currentIP()); + utils.webdata.Add("RemoveConnection", player.ToString()); + await utils.SendAPIRequestAsync(); } public async Task CheckConnection(IPlayer player) { - string externalIP; - if (Sandbox.MySandboxExternal.ConfigDedicated.IP.Contains("0.0") - || Sandbox.MySandboxExternal.ConfigDedicated.IP.Contains("127.0") - || Sandbox.MySandboxExternal.ConfigDedicated.IP.Contains("192.168") - || Sandbox.MySandboxExternal.ConfigDedicated.IP.Contains("10.0")) { + + Log.Warn("Checking inbound conneciton for " + player.SteamId); - externalIP = Config.LocalIP; - if (externalIP.Contains("127.0") - || externalIP.Contains("192.168") - || externalIP.Contains("0.0") - || externalIP.Contains("10.0")) { - Log.Error("Incorrect IP setup... SwitchMe will NOT work"); - return false; - } + utils.webdata.Add("BindKey", Config.LocalKey); + utils.webdata.Add("CurrentIP", currentIP()); + utils.webdata.Add("ConnectionCheck", player.SteamId.ToString()); + string text = await utils.SendAPIRequestAsync(); - } - else { - externalIP = Sandbox.MySandboxExternal.ConfigDedicated.IP; - } - string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; - Log.Warn("Checking inbound conneciton for " + player.SteamId); - string pagesource; - using (HttpClient client = new HttpClient()) { - List> pairs = new List> - { - new KeyValuePair("BindKey", Config.LocalKey), - new KeyValuePair("CurrentIP", currentIp ), - new KeyValuePair("ConnectionCheck", player.SteamId.ToString()) - }; - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - HttpResponseMessage httpResponseMessage = await client.PostAsync(API_URL, content); - HttpResponseMessage response = httpResponseMessage; - httpResponseMessage = null; - string text = await response.Content.ReadAsStringAsync(); - pagesource = text; - Log.Warn(pagesource); - } - if (pagesource.Contains("connecting=false")) { + if (debug) {Log.Warn(text);} + if (text.Contains("connecting=false")) { return false; } return true ; @@ -848,35 +806,9 @@ private void SessionChanged(ITorchSession session, TorchSessionState state) { case TorchSessionState.Loaded: //load - int gates = 0; MyVisualScriptLogicProvider.PlayerConnected += PlayerConnect; LoadSEDB(); - IEnumerable channelIds = Config.Gates; - string name = ""; - string location = ""; - foreach (string chId in channelIds) { - name = chId.Split('/')[0]; - location = chId.Split('/')[1]; - Vector3D.TryParse(location, out Vector3D gps); - var ob = new MyObjectBuilder_SafeZone(); - ob.PositionAndOrientation = new MyPositionAndOrientation(gps, Vector3.Forward, Vector3.Up); - ob.PersistentFlags = MyPersistentEntityFlags2.InScene; - ob.Shape = MySafeZoneShape.Sphere; - ob.Radius = (float)50; - ob.Enabled = true; - ob.DisplayName = $"SM-{gps}"; - ob.AccessTypeGrids = MySafeZoneAccess.Blacklist; - ob.AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist; - ob.AccessTypeFactions = MySafeZoneAccess.Blacklist; - ob.AccessTypePlayers = MySafeZoneAccess.Blacklist; - var zone = MyEntities.CreateFromObjectBuilderAndAdd(ob, true); - gates++; - if (!zones.Contains(ob.DisplayName)) { - zones.Add(ob.DisplayName); - } - } - Log.Info($"{gates} Jumpgates created!"); - break; + break; case TorchSessionState.Unloaded: //unload @@ -895,6 +827,35 @@ private void SessionChanged(ITorchSession session, TorchSessionState state) { } } + + public void OpenGates() { + int gates = 0; + IEnumerable channelIds = Config.Gates; + string name = ""; + string location = ""; + foreach (string chId in channelIds) { + name = chId.Split('/')[0]; + location = chId.Split('/')[1]; + Vector3D.TryParse(location, out Vector3D gps); + var ob = new MyObjectBuilder_SafeZone(); + ob.PositionAndOrientation = new MyPositionAndOrientation(gps, Vector3.Forward, Vector3.Up); + ob.PersistentFlags = MyPersistentEntityFlags2.InScene; + ob.Shape = MySafeZoneShape.Sphere; + ob.Radius = (float)50; + ob.Enabled = true; + ob.DisplayName = $"SM-{gps}"; + ob.AccessTypeGrids = MySafeZoneAccess.Blacklist; + ob.AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist; + ob.AccessTypeFactions = MySafeZoneAccess.Blacklist; + ob.AccessTypePlayers = MySafeZoneAccess.Blacklist; + var zone = MyEntities.CreateFromObjectBuilderAndAdd(ob, true); + gates++; + if (!zones.Contains(ob.DisplayName)) { + zones.Add(ob.DisplayName); + } + } + Log.Info($"{gates} Jumpgates created!"); + } public void CloseGates() { int i = 0; foreach (var zone in zones) { @@ -1102,7 +1063,7 @@ private void InitPost() { StartTimer(); } - public void DeleteFromWeb(ulong steamid) { + public async void DeleteFromWeb(ulong steamid) { string externalIP = Sandbox.MySandboxExternal.ConfigDedicated.IP; if (externalIP.Contains("0.0") || externalIP.Contains("127.0") @@ -1122,6 +1083,11 @@ public void DeleteFromWeb(ulong steamid) { client.UploadValues(API_URL, postData); } + + utils.webdata.Add("proccessed",steamid.ToString()); + utils.webdata.Add("currentIP", currentIP()); + await utils.SendAPIRequestAsync(); + } private void _timer_Elapsed(object sender, ElapsedEventArgs e) { diff --git a/SwitchMe/Utilities.cs b/SwitchMe/Utilities.cs index f60a4de..10f434e 100644 --- a/SwitchMe/Utilities.cs +++ b/SwitchMe/Utilities.cs @@ -24,8 +24,10 @@ namespace SwitchMe { public class utils { + public static string API_URL = "http://switchplugin.net/api/index.php"; public static ITorchBase Torch { get; } public static readonly Logger Log = LogManager.GetCurrentClassLogger(); + public static Dictionary webdata = new Dictionary(); public static string CreateExternalIP(SwitchMeConfig Config) { if (MySandboxGame.ConfigDedicated.IP.Contains("0.0") || MySandboxGame.ConfigDedicated.IP.Contains("127.0") || Sandbox.MySandboxExternal.ConfigDedicated.IP.Contains("192.168")) @@ -196,5 +198,21 @@ public static IMyPlayer GetPlayerByNameOrId(string nameOrPlayerId) { return null; } + + public static async Task SendAPIRequestAsync() { + using (HttpClient client = new HttpClient()) { + + List> pairs = new List>(); + + foreach(var kvp in webdata) { + pairs.Add(new KeyValuePair(kvp.Key, kvp.Value)); + } + + FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); + HttpResponseMessage response = await client.PostAsync(API_URL, content); + webdata.Clear(); + return await response.Content.ReadAsStringAsync(); + } + } } } From c382340625de51954292b1cfc60e04a6d872be49 Mon Sep 17 00:00:00 2001 From: Jack Bishop Date: Sun, 27 Sep 2020 19:25:55 +0100 Subject: [PATCH 02/32] Further optimization of api code --- SwitchMe/SwitchMe.csproj | 7 +- SwitchMe/SwitchMePlugin.cs | 147 ++++++++++++++----------------------- SwitchMe/Utilities.cs | 5 +- SwitchMe/VoidManager.cs | 39 +++------- 4 files changed, 75 insertions(+), 123 deletions(-) diff --git a/SwitchMe/SwitchMe.csproj b/SwitchMe/SwitchMe.csproj index d5ff6e2..41d343f 100644 --- a/SwitchMe/SwitchMe.csproj +++ b/SwitchMe/SwitchMe.csproj @@ -60,12 +60,15 @@ ..\GameBinaries\Sandbox.Graphics.dll False + + ..\..\..\..\Torch\DedicatedServer64\Sandbox.RenderDirect.dll + - ..\..\Torch\DedicatedServer64\SpaceEngineers.Game.dll + C:\Users\PC\Desktop\Torch\DedicatedServer64\SpaceEngineers.Game.dll False - ..\..\Torch\DedicatedServer64\SpaceEngineers.ObjectBuilders.dll + ..\..\..\..\Torch\DedicatedServer64\SpaceEngineers.ObjectBuilders.dll diff --git a/SwitchMe/SwitchMePlugin.cs b/SwitchMe/SwitchMePlugin.cs index 86cbf09..86d701f 100644 --- a/SwitchMe/SwitchMePlugin.cs +++ b/SwitchMe/SwitchMePlugin.cs @@ -45,11 +45,13 @@ using Sandbox.Common.ObjectBuilders; using VRage; using Sandbox.Game.Screens.Helpers; +using System.Reflection; namespace SwitchMe { public sealed class SwitchMePlugin : TorchPluginBase, IWpfPlugin { + public utils utils = new utils(); public SwitchMeConfig Config => _config?.Data; private Persistent _config; #pragma warning disable 649 @@ -139,21 +141,19 @@ private async void Multibase_PlayerJoined(IPlayer obj) { Log.Warn("Invalid GPS configuration - cancelling spawn operation"); return; } - bool SwitchConnection = await CheckConnection(obj); + bool SwitchConnection = await CheckConnectionAsync(obj); if (!SwitchConnection) { return; } - HttpResponseMessage response; string filename = ""; string targetFile = ""; string externalIP = Sandbox.MySandboxExternal.ConfigDedicated.IP; string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; - var utils = new utils(); utils.webdata.Add("existanceCheck", obj.SteamId.ToString()); utils.webdata.Add("currentIP", currentIp); - Dictionary gridData = utils.ParseQueryString(await utils.SendAPIRequestAsync()); + Dictionary gridData = await utils.SendAPIRequestAsync(); Directory.CreateDirectory("SwitchTemp"); if (gridData["filename"] != "NULL") { @@ -181,17 +181,15 @@ private async void Multibase_PlayerJoined(IPlayer obj) { } string POS = ""; - utils.webdata.Add("recover", obj.SteamId.ToString()); - utils.webdata.Add("currentIP", currentIp); - utils.webdata.Add("bindkey", Config.LocalKey); - string api_response = await utils.SendAPIRequestAsync(); + + string gateName = GetGateAsync(obj.SteamId.ToString()).ToString(); // // DO THE RANDOMISER SHIT BISH // bool foundGate = false; - IEnumerable channelIds = Config.Gates.Where(c => c.Split('/')[2].Equals(api_response)); + IEnumerable channelIds = Config.Gates.Where(c => c.Split('/')[2].Equals(gateName)); foreach (string chId in channelIds) { POS = chId.Split('/')[1]; foundGate = true; @@ -209,7 +207,7 @@ private async void Multibase_PlayerJoined(IPlayer obj) { } } if (!Config.RandomisedExit) { - Log.Warn($"API: Gate elected = {api_response}"); + Log.Warn($"API: Gate elected = {gateName}"); } else { Log.Warn("Using randomly selected gate as exit"); @@ -217,7 +215,7 @@ private async void Multibase_PlayerJoined(IPlayer obj) { if (!foundGate) { POS = "{X:" + Config.XCord + " Y:" + Config.YCord + " Z:" + Config.ZCord + "}"; - Log.Error($"Target gate ({api_response}) does not exist... Using default"); + Log.Error($"Target gate ({gateName}) does not exist... Using default"); } /* else if (config.EnabledMirror) @@ -271,21 +269,31 @@ private void Multibase_PlayerLeft(IPlayer obj) { } } + public async Task CheckExistance(string targetIP) { + var api_reponse = await utils.SendAPIRequestAsync(); + return api_reponse["existance"]; + } + public async Task GetGateAsync(string steamid) { + utils.webdata.Add("STEAMID", steamid); + utils.webdata.Add("CURRRENTIP", currentIP()); + utils.webdata.Add("bindkey", Config.LocalKey); + utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); + var api_response = await utils.SendAPIRequestAsync(); + return api_response["gate"]; + } + public async Task CheckServer(IMyPlayer player, string servername, string target) { - string slotinfo = await CheckSlotsAsync(target); - string existanceCheck = slotinfo.Split(';').Last(); - bool paired = await CheckKeyAsync(target); - + bool paired = await CheckKeyAsync(target); if (target.Length < 1) { Log.Warn("Unknown Server. Please use '!switch list' to see a list of valid servers!"); utils.NotifyMessage("Unknown Server. Please use '!switch list' to see a list of valid servers!", player.SteamUserId); return false; } - if (existanceCheck != "1") { + if (!bool.Parse(await CheckExistance(target))) { Log.Warn("Cannot communicate with target, please make sure SwitchMe is installed there!"); utils.NotifyMessage("Cannot communicate with target, please make sure SwitchMe is installed there!", player.SteamUserId); return false; @@ -298,14 +306,8 @@ public async Task CheckServer(IMyPlayer player, string servername, string } /// Slot checking - Log.Warn("Checking " + target); - int currentRemotePlayers = int.Parse(slotinfo.Substring(0, slotinfo.IndexOf(":"))); - string max = slotinfo.Substring(slotinfo.IndexOf(':') + 1, slotinfo.IndexOf(';') - slotinfo.IndexOf(':') - 1); - int currentLocalPlayers = int.Parse(MySession.Static.Players.GetOnlinePlayers().Count.ToString()); - currentLocalPlayers = 1; - int maxi = int.Parse(max); - int maxcheck = currentLocalPlayers + currentRemotePlayers; - if (maxcheck > maxi && player.PromoteLevel != MyPromoteLevel.Admin) { + bool slotsAvailable = bool.Parse(await CheckSlotsAsync(target, "1")); + if (!slotsAvailable && player.PromoteLevel != MyPromoteLevel.Admin) { utils.NotifyMessage("Not enough slots free to use gate!", player.SteamUserId); return false; } @@ -555,7 +557,7 @@ private async Task recovery(long playerid, Vector3D spawn_vector_location) { string currentIp = externalIP + ":" + Sandbox.MySandboxGame.ConfigDedicated.ServerPort; if (!failure) { DeleteFromWeb(steamid); - await RemoveConnection(steamid); + await RemoveConnectionAsync(steamid); } return; @@ -699,29 +701,28 @@ public string currentIP() { return currentIp; } - public async Task RemoveConnection(ulong player) { + + public async Task RemoveConnectionAsync(ulong player) { Log.Warn("Removing conneciton flag for " + player); - utils.webdata.Add("BindKey", Config.LocalKey); - utils.webdata.Add("CurrnetIP", currentIP()); - utils.webdata.Add("RemoveConnection", player.ToString()); + utils.webdata.Add("BINDKEY", Config.LocalKey); + utils.webdata.Add("CURRENTIP", currentIP()); + utils.webdata.Add("STEAMID", player.ToString()); + utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); await utils.SendAPIRequestAsync(); } - public async Task CheckConnection(IPlayer player) { - - Log.Warn("Checking inbound conneciton for " + player.SteamId); + public async Task CheckConnectionAsync(IPlayer player) { + Log.Warn("Checking inbound conneciton for " + player.SteamId); + utils.webdata.Add("BINDKEY", Config.LocalKey); + utils.webdata.Add("CURRENTIP", currentIP()); + utils.webdata.Add("STEAMID", player.SteamId.ToString()); + utils.webdata.Add("FUNCTION", player.SteamId.ToString()); + var api_response = await utils.SendAPIRequestAsync(); - utils.webdata.Add("BindKey", Config.LocalKey); - utils.webdata.Add("CurrentIP", currentIP()); - utils.webdata.Add("ConnectionCheck", player.SteamId.ToString()); - string text = await utils.SendAPIRequestAsync(); + if (debug) {Log.Warn($"Is {player.Name} ({player.SteamId}) transferee: {api_response["connecting"]}");} - if (debug) {Log.Warn(text);} - if (text.Contains("connecting=false")) { - return false; - } - return true ; + return bool.Parse(api_response["connecting"]); } public void Delete(string entityName) { @@ -768,33 +769,19 @@ public static IMyPlayer GetPlayerByNameOrId(string nameOrPlayerId) { } - public async Task CheckSlotsAsync(string targetIP) { + public async Task CheckSlotsAsync(string targetIP, string NumberOfPlayers) { string maxPlayers = MySession.Static.MaxPlayers.ToString(); string currentPlayers = MySession.Static.Players.GetOnlinePlayers().Count.ToString(); - string pagesource = ""; - - using (HttpClient client = new HttpClient()) { - - List> pairs = new List> - { - new KeyValuePair("currentplayers", currentPlayers ), - new KeyValuePair("maxplayers", maxPlayers), - new KeyValuePair("targetip", targetIP) - }; - - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - - HttpResponseMessage httpResponseMessage = await client.PostAsync("http://switchplugin.net/index.php", content); - HttpResponseMessage response = httpResponseMessage; - httpResponseMessage = null; - string text = await response.Content.ReadAsStringAsync(); + utils.webdata.Add("TARGETIP", targetIP); + utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); + utils.webdata.Add("PLAYERCOUNT", MethodBase.GetCurrentMethod().Name); + utils.webdata.Add("maxplayers", maxPlayers); + utils.webdata.Add("currentplayers", currentPlayers); - pagesource = text; - } - - return pagesource; + var api_response = await utils.SendAPIRequestAsync(); + return api_response["available"]; } private void SessionChanged(ITorchSession session, TorchSessionState state) { @@ -897,30 +884,16 @@ public void UnloadSEDB() { public async Task CheckKeyAsync(string target) { - string pagesource; - try { - using (HttpClient client = new HttpClient()) { - - List> pairs = new List> - { - new KeyValuePair("targetip", target), - new KeyValuePair("bindKey", Config.LocalKey), - new KeyValuePair("bindCheck", "1") - }; - - FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); - HttpResponseMessage httpResponseMessage = await client.PostAsync("http://switchplugin.net/index.php", content); - HttpResponseMessage response = httpResponseMessage; - httpResponseMessage = null; + utils.webdata.Add("targetIP", target); + utils.webdata.Add("bindKey", Config.LocalKey); + utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); - string text = await response.Content.ReadAsStringAsync(); - - pagesource = text; - } - return pagesource == Config.LocalKey; + //NEW API + var api_response = await utils.SendAPIRequestAsync(); + return Config.LocalKey == api_response["key"]; } catch (Exception e) { Log.Warn("Error communcating with API: " + e.ToString()); @@ -1143,13 +1116,7 @@ private void _timer_Elapsed(object sender, ElapsedEventArgs e) { name = chId.Split('/')[0]; location = chId.Split('/')[1]; alias = chId.Split('/')[2]; - targetAlias = chId.Split('/')[3]; - //gateData.Add(name, location); - //gate.Add(targetAlias,gateData); - //gates.Add($"{alias}-{currentIp}", gate); - //gate.Clear(); - //gateData.Clear(); - + targetAlias = chId.Split('/')[3]; } string json = JsonSerializer.Serialize(channelIds); diff --git a/SwitchMe/Utilities.cs b/SwitchMe/Utilities.cs index 10f434e..298900b 100644 --- a/SwitchMe/Utilities.cs +++ b/SwitchMe/Utilities.cs @@ -199,7 +199,7 @@ public static IMyPlayer GetPlayerByNameOrId(string nameOrPlayerId) { return null; } - public static async Task SendAPIRequestAsync() { + public static async Task> SendAPIRequestAsync() { using (HttpClient client = new HttpClient()) { List> pairs = new List>(); @@ -211,7 +211,8 @@ public static async Task SendAPIRequestAsync() { FormUrlEncodedContent content = new FormUrlEncodedContent(pairs); HttpResponseMessage response = await client.PostAsync(API_URL, content); webdata.Clear(); - return await response.Content.ReadAsStringAsync(); + + return ParseQueryString(await response.Content.ReadAsStringAsync()); } } } diff --git a/SwitchMe/VoidManager.cs b/SwitchMe/VoidManager.cs index b4e2454..f277250 100644 --- a/SwitchMe/VoidManager.cs +++ b/SwitchMe/VoidManager.cs @@ -277,7 +277,10 @@ public async Task PlayerTransfer(string type, ulong steamid) { string ip = ""; string name = ""; string port = ""; - string existanceCheck = ""; + int currentLocalPlayers = int.Parse(MySession.Static.Players.GetOnlinePlayers().Count.ToString()); + if (type == "single") { + currentLocalPlayers = 1; + } int i = 0; IEnumerable channelIds = Plugin.Config.Servers; @@ -294,8 +297,7 @@ public async Task PlayerTransfer(string type, ulong steamid) { string target = ip + ":" + port; ip += ":" + port; - string slotinfo = await Plugin.CheckSlotsAsync(target); - existanceCheck = slotinfo.Split(';').Last(); + bool slotsAvailable = bool.Parse(await Plugin.CheckSlotsAsync(target, currentLocalPlayers.ToString())); bool paired = await Plugin.CheckKeyAsync(target); if (ip == null || name == null || port == null) { @@ -308,7 +310,7 @@ public async Task PlayerTransfer(string type, ulong steamid) { return; } - if (existanceCheck != "1") { + if (!bool.Parse(await Plugin.CheckExistance(target))) { utils.Respond("Cannot communicate with target, please make sure SwitchMe is installed there!", "Server", steamid); return; } @@ -319,19 +321,8 @@ public async Task PlayerTransfer(string type, ulong steamid) { } /// Slot checking - Log.Warn("Checking " + target); - int currentRemotePlayers = int.Parse(slotinfo.Substring(0, slotinfo.IndexOf(":"))); - string max = slotinfo.Substring(slotinfo.IndexOf(':') + 1, slotinfo.IndexOf(';') - slotinfo.IndexOf(':') - 1); - Log.Warn("MAX: " + max); - int currentLocalPlayers = int.Parse(MySession.Static.Players.GetOnlinePlayers().Count.ToString()); - if (type == "single") { - currentLocalPlayers = 1; - } - int maxi = int.Parse(max); - int maxcheck = currentLocalPlayers + currentRemotePlayers; utils.Respond("Slot Checking...", "Server", steamid); - Log.Warn(maxcheck + " Player Count Prediction|Player Count Threshold " + max); - if (maxcheck > maxi && Context.Player.PromoteLevel != MyPromoteLevel.Admin) { + if (!slotsAvailable && Context.Player.PromoteLevel != MyPromoteLevel.Admin) { return; } @@ -367,8 +358,7 @@ public async Task PlayerTransfer(string type, ulong steamid) { string target = ip + ":" + port; ip += ":" + port; - string slotinfo = await Plugin.CheckSlotsAsync(target); - existanceCheck = slotinfo.Split(';').Last(); + bool slotsAvailable = bool.Parse(await Plugin.CheckSlotsAsync(target, currentLocalPlayers.ToString())); bool paired = await Plugin.CheckKeyAsync(target); if (ip == null || name == null || port == null) { @@ -381,7 +371,7 @@ public async Task PlayerTransfer(string type, ulong steamid) { return; } - if (existanceCheck != "1") { + if (!bool.Parse(await Plugin.CheckExistance(target))) { Context.Respond("Cannot communicate with target, please make sure SwitchMe is installed there!"); return; } @@ -392,16 +382,7 @@ public async Task PlayerTransfer(string type, ulong steamid) { } /// Slot checking - Log.Warn("Checking " + target); - int currentRemotePlayers = int.Parse(slotinfo.Substring(0, slotinfo.IndexOf(":"))); - string max = slotinfo.Substring(slotinfo.IndexOf(':') + 1, slotinfo.IndexOf(';') - slotinfo.IndexOf(':') - 1); - Log.Warn("MAX: " + max); - int currentLocalPlayers = int.Parse(MySession.Static.Players.GetOnlinePlayers().Count.ToString()); - int maxi = int.Parse(max); - int maxcheck = currentLocalPlayers + currentRemotePlayers; - Context.Respond("Slot Checking..."); - Log.Warn(maxcheck + " Player Count Prediction|Player Count Threshold " + max); - if (maxcheck > maxi) { + if (slotsAvailable) { Context.Respond("Cannot switch, not enough slots available"); return; } From 1a416a45f429a60dc3f0081c219cd87d5960723f Mon Sep 17 00:00:00 2001 From: Jack Bishop Date: Sun, 27 Sep 2020 20:46:21 +0100 Subject: [PATCH 03/32] remove sending of unessecary data --- SwitchMe/SwitchMePlugin.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/SwitchMe/SwitchMePlugin.cs b/SwitchMe/SwitchMePlugin.cs index 86d701f..2ab8bf9 100644 --- a/SwitchMe/SwitchMePlugin.cs +++ b/SwitchMe/SwitchMePlugin.cs @@ -777,8 +777,6 @@ public async Task CheckSlotsAsync(string targetIP, string NumberOfPlayer utils.webdata.Add("TARGETIP", targetIP); utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); utils.webdata.Add("PLAYERCOUNT", MethodBase.GetCurrentMethod().Name); - utils.webdata.Add("maxplayers", maxPlayers); - utils.webdata.Add("currentplayers", currentPlayers); var api_response = await utils.SendAPIRequestAsync(); return api_response["available"]; From 1523b0b5cd97cb64148a1fb8d837e47baab239b0 Mon Sep 17 00:00:00 2001 From: Jack Bishop Date: Sun, 27 Sep 2020 21:59:59 +0100 Subject: [PATCH 04/32] name changes --- SwitchMe/SwitchMePlugin.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SwitchMe/SwitchMePlugin.cs b/SwitchMe/SwitchMePlugin.cs index 2ab8bf9..5913254 100644 --- a/SwitchMe/SwitchMePlugin.cs +++ b/SwitchMe/SwitchMePlugin.cs @@ -376,7 +376,7 @@ public override async void Update() { DisplayedMessage[player.SteamUserId] = true; } - if (Config.Debug && tick % 64 == 0) { + if (debug && tick % 64 == 0) { Log.Warn($"{player.DisplayName} is {closestDistance[player.SteamUserId]} away (meters squared)"); } @@ -884,8 +884,8 @@ public async Task CheckKeyAsync(string target) { try { - utils.webdata.Add("targetIP", target); - utils.webdata.Add("bindKey", Config.LocalKey); + utils.webdata.Add("TARGETIP", target); + utils.webdata.Add("BINDKEY", Config.LocalKey); utils.webdata.Add("FUNCTION", MethodBase.GetCurrentMethod().Name); From 6c5c0210cf3432bfc7278952cb7616b0f472e00e Mon Sep 17 00:00:00 2001 From: Jack Bishop Date: Mon, 28 Sep 2020 00:55:06 +0100 Subject: [PATCH 05/32] Fix various crashes and other minor improvements --- SwitchMe/Commands.cs | 1 + SwitchMe/SwitchMeControl.xaml | 4 +-- SwitchMe/SwitchMePlugin.cs | 50 ++++++++++++++++++++--------------- SwitchMe/Utilities.cs | 30 ++++++++++++--------- 4 files changed, 50 insertions(+), 35 deletions(-) diff --git a/SwitchMe/Commands.cs b/SwitchMe/Commands.cs index 78954c2..0b184c3 100644 --- a/SwitchMe/Commands.cs +++ b/SwitchMe/Commands.cs @@ -76,6 +76,7 @@ public async Task SwitchLocalAsync() { [Permission(MyPromoteLevel.Admin)] public void debug(bool state) { Plugin.debug = state; + Context.Respond($"Debug mode set to {Plugin.debug} "); } [Command("all", "Automatically connects all players to your server of choice within this network. USAGE: !switch all ")] diff --git a/SwitchMe/SwitchMeControl.xaml b/SwitchMe/SwitchMeControl.xaml index 3b4fc5f..eff0307 100644 --- a/SwitchMe/SwitchMeControl.xaml +++ b/SwitchMe/SwitchMeControl.xaml @@ -66,8 +66,8 @@ -