Add desktop diagnostics and resilient message handling

This commit is contained in:
Misaka
2026-05-15 21:29:55 +08:00
parent 4c314c510b
commit d4b7a23e38
4 changed files with 71 additions and 7 deletions

View File

@@ -0,0 +1,32 @@
namespace WirelessTextSyncer.Windows.Services;
public static class AppLogger
{
private static readonly object SyncRoot = new();
private static readonly string LogDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"WirelessTextSyncer");
public static string LogPath => Path.Combine(LogDirectory, "desktop.log");
public static void Info(string message)
{
Write("INFO", message);
}
public static void Error(string message, Exception? exception = null)
{
Write("ERROR", exception is null ? message : $"{message}{Environment.NewLine}{exception}");
}
private static void Write(string level, string message)
{
lock (SyncRoot)
{
Directory.CreateDirectory(LogDirectory);
File.AppendAllText(
LogPath,
$"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff zzz} [{level}] {message}{Environment.NewLine}");
}
}
}

View File

@@ -17,6 +17,7 @@ public sealed class KeyboardInjectionService : IKeyboardInjectionService
return; return;
} }
AppLogger.Info($"Injecting text length: {text.Length}");
foreach (var character in text) foreach (var character in text)
{ {
SendUnicode(character); SendUnicode(character);
@@ -25,11 +26,13 @@ public sealed class KeyboardInjectionService : IKeyboardInjectionService
public void Backspace() public void Backspace()
{ {
AppLogger.Info("Injecting backspace.");
SendVirtualKey(VirtualKeyBack); SendVirtualKey(VirtualKeyBack);
} }
public void Enter() public void Enter()
{ {
AppLogger.Info("Injecting enter.");
SendVirtualKey(VirtualKeyReturn); SendVirtualKey(VirtualKeyReturn);
} }
@@ -54,7 +57,9 @@ public sealed class KeyboardInjectionService : IKeyboardInjectionService
var sent = SendInput((uint)inputs.Length, inputs, Marshal.SizeOf<INPUT>()); var sent = SendInput((uint)inputs.Length, inputs, Marshal.SizeOf<INPUT>());
if (sent != inputs.Length) if (sent != inputs.Length)
{ {
throw new InvalidOperationException("Windows did not accept all keyboard input events."); var error = Marshal.GetLastWin32Error();
AppLogger.Error(
$"Windows accepted {sent}/{inputs.Length} keyboard input events. Win32 error: {error}");
} }
} }

View File

@@ -1,4 +1,5 @@
using System.Net; using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text.Json; using System.Text.Json;
using Fleck; using Fleck;
@@ -44,6 +45,7 @@ public sealed class WebSocketServerService : IDisposable
{ {
Port = port; Port = port;
LocalIpAddress = ResolveLocalIpAddress(); LocalIpAddress = ResolveLocalIpAddress();
AppLogger.Info($"Starting WebSocket server on 0.0.0.0:{Port}. Local IP: {LocalIpAddress}");
server = new WebSocketServer($"ws://0.0.0.0:{Port}"); server = new WebSocketServer($"ws://0.0.0.0:{Port}");
server.Start(socket => server.Start(socket =>
@@ -55,6 +57,7 @@ public sealed class WebSocketServerService : IDisposable
clients.Add(socket); clients.Add(socket);
} }
AppLogger.Info($"Client connected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
StatusChanged?.Invoke(this, EventArgs.Empty); StatusChanged?.Invoke(this, EventArgs.Empty);
}; };
socket.OnClose = () => socket.OnClose = () =>
@@ -64,6 +67,12 @@ public sealed class WebSocketServerService : IDisposable
clients.Remove(socket); clients.Remove(socket);
} }
AppLogger.Info($"Client disconnected: {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
StatusChanged?.Invoke(this, EventArgs.Empty);
};
socket.OnError = exception =>
{
AppLogger.Error("WebSocket connection error.", exception);
StatusChanged?.Invoke(this, EventArgs.Empty); StatusChanged?.Invoke(this, EventArgs.Empty);
}; };
socket.OnMessage = HandleRawMessage; socket.OnMessage = HandleRawMessage;
@@ -91,26 +100,42 @@ public sealed class WebSocketServerService : IDisposable
{ {
try try
{ {
AppLogger.Info($"Received message: {rawMessage}");
var message = JsonSerializer.Deserialize<SyncMessage>(rawMessage, JsonOptions); var message = JsonSerializer.Deserialize<SyncMessage>(rawMessage, JsonOptions);
if (message is null) if (message is null)
{ {
AppLogger.Info("Ignored empty sync message.");
return; return;
} }
messageHandler.Handle(message); messageHandler.Handle(message);
} }
catch (JsonException) catch (JsonException exception)
{ {
return; AppLogger.Error($"Invalid sync message: {rawMessage}", exception);
}
catch (Exception exception)
{
AppLogger.Error($"Failed to handle sync message: {rawMessage}", exception);
} }
} }
private static string ResolveLocalIpAddress() private static string ResolveLocalIpAddress()
{ {
var host = Dns.GetHostEntry(Dns.GetHostName()); var address = NetworkInterface.GetAllNetworkInterfaces()
var address = host.AddressList.FirstOrDefault( .Where(networkInterface =>
address => address.AddressFamily == AddressFamily.InterNetwork networkInterface.OperationalStatus == OperationalStatus.Up
&& !IPAddress.IsLoopback(address)); && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(networkInterface => networkInterface.GetIPProperties())
.Where(properties => properties.GatewayAddresses.Any(
gateway => gateway.Address.AddressFamily == AddressFamily.InterNetwork
&& !IPAddress.Any.Equals(gateway.Address)))
.SelectMany(properties => properties.UnicastAddresses)
.Select(unicast => unicast.Address)
.FirstOrDefault(address =>
address.AddressFamily == AddressFamily.InterNetwork
&& !IPAddress.IsLoopback(address)
&& !address.ToString().StartsWith("169.254.", StringComparison.Ordinal));
return address?.ToString() ?? "127.0.0.1"; return address?.ToString() ?? "127.0.0.1";
} }

View File

@@ -9,6 +9,7 @@ public sealed class TrayApplicationContext : ApplicationContext
public TrayApplicationContext() public TrayApplicationContext()
{ {
AppLogger.Info("Tray application starting.");
var keyboard = new KeyboardInjectionService(); var keyboard = new KeyboardInjectionService();
var handler = new SyncMessageHandler(keyboard); var handler = new SyncMessageHandler(keyboard);
@@ -31,6 +32,7 @@ public sealed class TrayApplicationContext : ApplicationContext
} }
catch (Exception ex) catch (Exception ex)
{ {
AppLogger.Error("Failed to start tray application.", ex);
notifyIcon.BalloonTipTitle = "WirelessTextSyncer"; notifyIcon.BalloonTipTitle = "WirelessTextSyncer";
notifyIcon.BalloonTipText = $"Failed to start: {ex.Message}"; notifyIcon.BalloonTipText = $"Failed to start: {ex.Message}";
notifyIcon.ShowBalloonTip(5000); notifyIcon.ShowBalloonTip(5000);