Skip to content

Commit

Permalink
Merge pull request #2 from MegaPiggy/main
Browse files Browse the repository at this point in the history
Add Console Port and Socket Listener
  • Loading branch information
loco-choco authored May 29, 2022
2 parents 04222a0 + c3896b1 commit eb0d3ea
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 25 deletions.
22 changes: 15 additions & 7 deletions OWAML/ConsoleUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,20 @@ ConsoleColor GetColorFromMessageType(MessageType messageType)
}
public enum MessageType
{
Message,
Error,
Warning,
Info,
Success,
Fatal,
Debug
Message = 0,

Error = 1,

Warning = 2,

Info = 3,

Success = 4,

Quit = 5,

Fatal = 6,

Debug = 7
}
}
19 changes: 18 additions & 1 deletion OWAML/FileVerificationAndInitialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public class FileVerificationAndInitialization

private string gameFolder;
private string bepInExFolder;
private string consolePort;
private SocketListener socketListener;

public bool CheckArguments(ArgumentHelper argumentHelper)
{
if (!argumentHelper.HasArgument("gamePath"))
Expand All @@ -31,6 +34,13 @@ public bool CheckArguments(ArgumentHelper argumentHelper)

gameFolder = argumentHelper.GetArgument("gamePath");
bepInExFolder = argumentHelper.GetArgument("bepInExFolder");
if (argumentHelper.HasArgument("consolePort"))
consolePort = argumentHelper.GetArgument("consolePort");
else
{
socketListener = new SocketListener();
consolePort = socketListener.Init().ToString();
}

if (!argumentHelper.HasArgument("bepInExFolder"))
{
Expand Down Expand Up @@ -141,7 +151,14 @@ public bool StartGame()
ConsoleUtils.WriteByType($"Game executable ({gameEXEPath}) wasn't found", MessageType.Error);
return false;
}
Process.Start(gameEXEPath);
if (string.IsNullOrWhiteSpace(consolePort))
{
Process.Start(gameEXEPath);
}
else
{
Process.Start(gameEXEPath, $"-consolePort {consolePort}");
}
ConsoleUtils.WriteByType("Game was started", MessageType.Success);

return true;
Expand Down
19 changes: 19 additions & 0 deletions OWAML/ModSocketMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Newtonsoft.Json;

namespace OWAML
{
public class ModSocketMessage
{
[JsonProperty("senderName")]
public string SenderName { get; set; }

[JsonProperty("senderType")]
public string SenderType { get; set; }

[JsonProperty("type")]
public MessageType Type { get; set; }

[JsonProperty("message")]
public string Message { get; set; }
}
}
4 changes: 2 additions & 2 deletions OWAML/OWAML.Manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"author": "Locochoco",
"name": "OWAML",
"uniqueName": "Locochoco.OWAML",
"version": "1.0.1",
"version": "1.0.2",
"minBepInExVersion": "5.4.17",
"maxBepInExVersion": "5.4.19"
"maxBepInExVersion": "5.4.19.1"
}
2 changes: 2 additions & 0 deletions OWAML/OWAML.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@
<Compile Include="ConfigurationFileCheckData.cs" />
<Compile Include="ConsoleUtil.cs" />
<Compile Include="FileVerificationAndInitialization.cs" />
<Compile Include="ModSocketMessage.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SocketListener.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
Expand Down
15 changes: 7 additions & 8 deletions OWAML/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ static void Main(string[] args)
}
catch (Exception ex)
{
exit = false;
ConsoleUtils.WriteByType("CMOWA crashed unexpectedly with the following message: " + ex.Message, MessageType.Fatal);
ConsoleUtils.WriteByType("OWAML crashed unexpectedly with the following message: " + ex.Message, MessageType.Fatal);
ConsoleUtils.WriteByType("Source: " + ex.Source, MessageType.Fatal);
ConsoleUtils.WriteByType("StackTrace:" + ex.StackTrace, MessageType.Fatal);
}
Expand All @@ -26,31 +25,31 @@ static void Main(string[] args)

public static bool Initialization(ArgumentHelper argumentHelper)
{
ConsoleUtils.WriteByType($"Starting CMOWA", MessageType.Info);
ConsoleUtils.WriteByType($"Starting OWAML", MessageType.Info);

FileVerificationAndInitialization initialization = new FileVerificationAndInitialization();

if (!initialization.CheckArguments(argumentHelper))
{
ConsoleUtils.WriteByType("CMOWA failed on CheckArguments", MessageType.Fatal);
ConsoleUtils.WriteByType("OWAML failed on CheckArguments", MessageType.Fatal);
return false;
}
if (!initialization.CheckBepInExConfig())
{
ConsoleUtils.WriteByType("CMOWA failed on CheckAndBepInExFiles", MessageType.Fatal);
ConsoleUtils.WriteByType("OWAML failed on CheckAndBepInExFiles", MessageType.Fatal);
return false;
}
if (!initialization.CheckBepInExDoorstopAndWinhttp())
{
ConsoleUtils.WriteByType("CMOWA failed on CheckBepInExDoorstopAndWinhttp", MessageType.Fatal);
ConsoleUtils.WriteByType("OWAML failed on CheckBepInExDoorstopAndWinhttp", MessageType.Fatal);
return false;
}
if (!initialization.StartGame())
{
ConsoleUtils.WriteByType("CMOWA failed on StartGame", MessageType.Fatal);
ConsoleUtils.WriteByType("OWAML failed on StartGame", MessageType.Fatal);
return false;
}
return true;
return argumentHelper.HasArgument("consolePort");
}
}
}
14 changes: 7 additions & 7 deletions OWAML/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
// As informações gerais sobre um assembly são controladas por
// conjunto de atributos. Altere estes valores de atributo para modificar as informações
// associadas a um assembly.
[assembly: AssemblyTitle("CMOWA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("OWAML")]
[assembly: AssemblyDescription("BepinEx helper for OWMM")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CMOWA")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyCompany("Locochoco")]
[assembly: AssemblyProduct("OWAML")]
[assembly: AssemblyCopyright("Copyright © Locochoco 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

Expand All @@ -32,5 +32,5 @@
// É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão
// usando o "*" como mostrado abaixo:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
120 changes: 120 additions & 0 deletions OWAML/SocketListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace OWAML
{
public class SocketListener
{
private const string Separator = "\n--------------------------------";
private const int BufferSize = 262144;
private static int _port;
private static TcpListener _server;
private bool _hasReceivedFatalMessage;

public int Init()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
_port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();

new Task(SetupSocketListener).Start();
return _port;
}

private void SetupSocketListener()
{
try
{
ListenToSocket();
}
catch (SocketException ex)
{
ConsoleUtils.WriteByType($"Error in socket listener: {ex}", MessageType.Error);
}
catch (Exception ex)
{
ConsoleUtils.WriteByType($"Error while listening: {ex}", MessageType.Error);
}
finally
{
_server?.Stop();
}
}

private void ListenToSocket()
{
var localAddress = IPAddress.Parse("127.0.0.1");

_server = new TcpListener(localAddress, _port);
_server.Start();

var bytes = new byte[BufferSize];

while (true)
{
var client = _server.AcceptTcpClient();

ConsoleUtils.WriteByType("Console connected to socket!", MessageType.Success);

var stream = client.GetStream();

int i;

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
ProcessMessage(bytes, i);
}

ConsoleUtils.WriteByType("Closing client!", MessageType.Success);
client.Close();
}
}

private void ProcessMessage(byte[] bytes, int count)
{
var message = Encoding.UTF8.GetString(bytes, 0, count);
var jsons = message.Split('\n');
foreach (var json in jsons)
{
if (string.IsNullOrWhiteSpace(json))
{
continue;
}

ModSocketMessage data;
try
{
data = JsonConvert.DeserializeObject<ModSocketMessage>(json);
}
catch (Exception ex)
{
ConsoleUtils.WriteByType($"Failed to process following message:{Separator}\n{json}{Separator}", MessageType.Warning);
ConsoleUtils.WriteByType($"Reason: {ex.Message}", MessageType.Warning);
continue;
}

if (data.Type == MessageType.Quit && !_hasReceivedFatalMessage)
{
Environment.Exit(0);
}
else if (data.Type == MessageType.Fatal)
{
_hasReceivedFatalMessage = true;
}

var nameTypePrefix = $"[{data.SenderName}] : ";

var messageData = data.Message;
messageData = messageData.Replace("\n", $"\n{new string(' ', nameTypePrefix.Length)}");

ConsoleUtils.WriteByType($"{nameTypePrefix}{messageData}", data.Type);
}
}
}
}

0 comments on commit eb0d3ea

Please sign in to comment.