Skip to content

Commit

Permalink
Merge pull request #59 from ChrisFeline/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
ChrisFeline authored Oct 4, 2024
2 parents d595dc3 + c7cd419 commit 8e5c93d
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 25 deletions.
2 changes: 1 addition & 1 deletion ToNSaveManager.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
<PackageReference Include="Jint" Version="4.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="OpenRGB.NET" Version="3.1.1" />
<PackageReference Include="websocketsharp.core" Version="1.0.0" />
<PackageReference Include="WatsonWebsocket" Version="4.1.2" />
</ItemGroup>

<ItemGroup>
Expand Down
51 changes: 32 additions & 19 deletions Utils/API/WebSocketAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,49 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ToNSaveManager.Models;
using ToNSaveManager.Models.Index;
using ToNSaveManager.Models.Stats;
using ToNSaveManager.Utils.LogParser;
using WebSocketSharp;
using WebSocketSharp.Server;
// using WebSocketSharp;
// using WebSocketSharp.Server;
using WebSocketServer = WatsonWebsocket.WatsonWsServer;

namespace ToNSaveManager.Utils.API {
internal class WebSocketAPI : WebSocketBehavior {
internal class WebSocketAPI {
static readonly LoggerSource Logger = new LoggerSource(nameof(WebSocketAPI));
internal static WebSocketServer? Server;

protected override void OnMessage(MessageEventArgs e) {
Logger.Log("Received: " + e.Data);
}

protected override void OnOpen() {
Logger.Log("WebSocket client connected.");
static void OnOpen(WatsonWebsocket.ClientMetadata metadata) {
Logger.Log("WebSocket client connected: " + metadata.Guid + " | " + metadata.Ip);

SendEvent(new EventConnected() {
Args = EventBuffer.ToArray(),
DisplayName = ToNLogContext.Instance?.DisplayName ?? string.Empty,
UserID = ToNLogContext.Instance?.UserID ?? string.Empty
}, this);
}, metadata);

SendEvent(new EventValue<string?>("INSTANCE", ToNLogContext.Instance?.InstanceID), this);
SendEvent(new EventValue<string?>("INSTANCE", ToNLogContext.Instance?.InstanceID), metadata);

// Send All Stats
foreach (string key in ToNStats.PropertyKeys) {
SendEvent(new EventStats() { Name = key, Value = ToNStats.Get(key) }, this);
SendEvent(new EventStats() { Name = key, Value = ToNStats.Get(key) }, metadata);
}
}

const int DEFAULT_PORT = 11398;
internal static void Initialize() {
if (Settings.Get.WebSocketEnabled && Server == null) {
int port = Settings.Get.WebSocketPort > 0 ? Settings.Get.WebSocketPort : DEFAULT_PORT;
Server = new WebSocketServer(port);
Server.AddWebSocketService<WebSocketAPI>("/");
Server = new WebSocketServer(new List<string>() { IPAddress.Loopback.ToString(), "localhost" }, port);
//Server.AddWebSocketService<WebSocketAPI>("/");

Server.ClientConnected += Server_ClientConnected;
Server.ClientDisconnected += Server_ClientDisconnected;
}

if (Settings.Get.WebSocketEnabled && Server != null && !Server.IsListening) {
Expand All @@ -54,23 +55,35 @@ internal static void Initialize() {
} else if (!Settings.Get.WebSocketEnabled && Server != null && Server.IsListening) {
Logger.Debug("Stopping Server...");
Server.Stop();
Server.RemoveWebSocketService("/");
Server.Dispose();
Server = null;
}
}

private static void Server_ClientDisconnected(object? sender, WatsonWebsocket.DisconnectionEventArgs e) {
Logger.Log("WebSocket client disconnected" + e.Client.Guid);
}

private static void Server_ClientConnected(object? sender, WatsonWebsocket.ConnectionEventArgs e) {
OnOpen(e.Client);
}

internal static void Broadcast(string data) {
if (Server == null) return;
Logger.Debug("Broadcasting: " + data);
Server?.WebSocketServices?.Broadcast(data);

foreach (var metadata in Server.ListClients()) {
_ = Server.SendAsync(metadata.Guid, data).Result;
}
}
internal static void SendEvent<T>(T value, WebSocketAPI? connection) where T : IEvent {
internal static void SendEvent<T>(T value, WatsonWebsocket.ClientMetadata? metadata) where T : IEvent {
if (!Settings.Get.WebSocketEnabled) return;
string jsonData = JsonConvert.SerializeObject(value);

try {
if (connection != null) {
if (metadata != null) {
Logger.Debug("Sending: " + jsonData);
connection.Send(jsonData);
_ = Server?.SendAsync(metadata.Guid, jsonData).Result;
return;
}

Expand Down
2 changes: 1 addition & 1 deletion Utils/LilOSC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ internal static void SendData(bool force = false) {
if (LastStarted != IsRoundActive || force) SendParam(ParamStarted, LastStarted = IsRoundActive);
}

if (ChatboxClear || (Settings.Get.OSCSendChatbox && MainWindow.Started && !force && !string.IsNullOrEmpty(ChatboxMessage))) {
if (ChatboxClear || (ToNLogContext.CanSendChatbox && MainWindow.Started && !force && !string.IsNullOrEmpty(ChatboxMessage))) {
ChatboxCountdown -= MainWindow.LogWatcher.Interval;
if (ChatboxCountdown < 0) {
ChatboxCountdown = ChatboxInterval;
Expand Down
2 changes: 1 addition & 1 deletion Utils/LogParser/LogWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ private bool ParseLocation(string line, DateTime lineDate, T logContext)
if (index >= line.Length) return false;

var instanceId = line.Substring(index).Trim('\n', '\r');
logContext.Enter(instanceId, instanceId.StartsWith(HomeWorldID));
logContext.Enter(instanceId, instanceId.Contains(HomeWorldID));

return true;
}
Expand Down
3 changes: 2 additions & 1 deletion Utils/LogParser/ToNLogContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace ToNSaveManager.Utils.LogParser
{
internal class ToNLogContext : LogContext {
internal static ToNLogContext? Instance { get; private set; }
internal static bool CanSendChatbox => Instance != null && Instance.IsHomeWorld && Settings.Get.OSCSendChatbox;

public bool HasLoadedSave { get; set; }

Expand Down Expand Up @@ -66,7 +67,7 @@ public override void OnAwake() {
if (IsRecent) {
Instance = this;
ToNGameState.ClearStates();
Logger.Debug("Log Context Path: " + this.FilePath);
LilOSC.SetChatboxMessage(string.Empty);
}

ClearSummary();
Expand Down
5 changes: 4 additions & 1 deletion Windows/MainWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ private void mainWindow_Loaded(object sender, EventArgs e) {
TooltipUtil.Set(linkSupport, "Buy Me A Coffee ♥");

// TODO: Implement this after a week or whatever.
// if (Program.ContainsArg("--emulator") || Program.ContainsArg("--emu") || Program.ContainsArg("-e")) EmulatorWindow.Open(this);
// if (Program.ContainsArg("--emulator") || Program.ContainsArg("--emu") || Program.ContainsArg("-e"))
#if DEBUG
// EmulatorWindow.Open(this);
#endif
}

private void mainWindow_Shown(object sender, EventArgs e) {
Expand Down
3 changes: 2 additions & 1 deletion Windows/StatsWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using ToNSaveManager.Models.Index;
using ToNSaveManager.Models.Stats;
using ToNSaveManager.Utils;
using ToNSaveManager.Utils.LogParser;
using static System.Windows.Forms.AxHost;

namespace ToNSaveManager
Expand Down Expand Up @@ -229,7 +230,7 @@ public static string NormalizeLabelText(string text) {
*/

internal static void UpdateChatboxContent() {
if (IsRoundActive || !MainWindow.Started || !Settings.Get.OSCSendChatbox || string.IsNullOrEmpty(Settings.Get.OSCMessageInfoTemplate.Template)) return;
if (IsRoundActive || !MainWindow.Started || !ToNLogContext.CanSendChatbox || string.IsNullOrEmpty(Settings.Get.OSCMessageInfoTemplate.Template)) return;
string template = TemplateManager.ReplaceTemplate(Settings.Get.OSCMessageInfoTemplate.Template);
LilOSC.SetChatboxMessage(template);
}
Expand Down

0 comments on commit 8e5c93d

Please sign in to comment.