-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
237 lines (207 loc) · 7.58 KB
/
MainWindow.xaml.cs
File metadata and controls
237 lines (207 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Windows;
using WebSocketSharp.Server;
namespace PCRemoteControlServer
{
public partial class MainWindow : Window
{
private WebSocketServer? _server;
private NotifyIcon _notifyIcon;
private readonly AppSettings _settings;
public MainWindow()
{
InitializeComponent();
KeyCommandExecutor.Logger = Log;
InitializeNotifyIcon();
StateChanged += MainWindow_StateChanged;
_settings = AppSettings.Load();
PortTextBox.Text = _settings.Port.ToString();
RequireAuthCheckBox.IsChecked = _settings.RequireAuth;
PinTextBox.Text = _settings.Secret;
PinTextBox.IsEnabled = _settings.RequireAuth;
RandomizePinButton.IsEnabled = _settings.RequireAuth;
}
private void InitializeNotifyIcon()
{
var iconUri = new Uri("pack://application:,,,/icon/icon.ico");
using var stream = System.Windows.Application.GetResourceStream(iconUri).Stream;
_notifyIcon = new NotifyIcon
{
Icon = new Icon(stream),
Text = "Remote Control Server",
Visible = false
};
_notifyIcon.Click += NotifyIcon_Click;
}
private void MainWindow_StateChanged(object? sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
Hide();
_notifyIcon.Visible = true;
}
}
private void NotifyIcon_Click(object? sender, EventArgs e)
{
Show();
WindowState = WindowState.Normal;
Activate();
_notifyIcon.Visible = false;
}
private void StartStopButton_Click(object sender, RoutedEventArgs e)
{
if (_server == null)
{
StartServer();
}
else
{
StopServer();
}
}
private void RequireAuthCheckBox_Changed(object sender, RoutedEventArgs e)
{
PinTextBox.IsEnabled = RequireAuthCheckBox.IsChecked == true;
RandomizePinButton.IsEnabled = RequireAuthCheckBox.IsChecked == true;
}
private void StartServer()
{
if (!int.TryParse(PortTextBox.Text, out int port) || port < 1 || port > 65535)
{
Log("Invalid port number. Must be between 1 and 65535.");
return;
}
bool requireAuth = RequireAuthCheckBox.IsChecked == true;
string pin = PinTextBox.Text.Trim();
if (requireAuth)
{
if (pin.Length != 6 || !int.TryParse(pin, out _))
{
Log("PIN must be exactly 6 digits.");
return;
}
}
try
{
var ip = TryGetLanIPv4Address() ?? IPAddress.Any;
_server = new WebSocketServer(ip, port);
_server.ReuseAddress = true;
CommandBehavior.Secret = requireAuth ? pin : null;
_server.AddWebSocketService<CommandBehavior>("/remote");
_server.Start();
_settings.Port = port;
_settings.RequireAuth = requireAuth;
_settings.Secret = pin;
_settings.Save();
StartStopButton.Content = "Stop";
var host = ip.Equals(IPAddress.Any) ? "0.0.0.0" : ip.ToString();
StatusTextBlock.Text = "Listening on ws://" + host + ":" + port + "/remote";
Log("Server started.");
if (requireAuth)
Log("PIN: " + pin);
else
Log("Authentication disabled.");
if (!ip.Equals(IPAddress.Any))
Log("LAN address: " + ip);
}
catch (Exception ex)
{
Log("Error starting server: " + ex.Message);
_server = null;
}
}
private static IPAddress? TryGetLanIPv4Address()
{
IPAddress? fallbackPrivate = null;
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up)
continue;
if (ni.NetworkInterfaceType is NetworkInterfaceType.Loopback or NetworkInterfaceType.Tunnel)
continue;
if (IsLikelyVirtualAdapter(ni))
continue;
var ipProps = ni.GetIPProperties();
bool hasGateway = ipProps.GatewayAddresses.Any(g => g?.Address is not null && !g.Address.Equals(IPAddress.Any));
foreach (var ua in ipProps.UnicastAddresses)
{
if (ua.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
var ip = ua.Address;
if (IPAddress.IsLoopback(ip) || ip.Equals(IPAddress.Any))
continue;
if (!IsPrivateIPv4(ip))
continue;
// Best guess: a non-virtual interface that has a default gateway.
if (hasGateway)
return ip;
// Otherwise keep the first reasonable private IP as a fallback.
fallbackPrivate ??= ip;
}
}
return fallbackPrivate;
}
private static bool IsLikelyVirtualAdapter(NetworkInterface ni)
{
var name = (ni.Name + " " + ni.Description).ToLowerInvariant();
return name.Contains("virtual")
|| name.Contains("vethernet")
|| name.Contains("hyper-v")
|| name.Contains("vmware")
|| name.Contains("virtualbox")
|| name.Contains("wsl")
|| name.Contains("tunnel")
|| name.Contains("tap");
}
private static bool IsPrivateIPv4(IPAddress ip)
{
var b = ip.GetAddressBytes();
return b[0] == 10
|| (b[0] == 172 && b[1] >= 16 && b[1] <= 31)
|| (b[0] == 192 && b[1] == 168);
}
private void StopServer()
{
try
{
_server?.Stop();
}
catch (Exception ex)
{
Log("Error stopping server: " + ex.Message);
}
finally
{
_server = null;
StartStopButton.Content = "Start";
StatusTextBlock.Text = "Stopped";
Log("Server stopped.");
}
}
private void Log(string message)
{
Dispatcher.Invoke(() =>
{
LogTextBox.AppendText("[" + DateTime.Now.ToString("HH:mm:ss") + "] " + message + Environment.NewLine);
LogTextBox.ScrollToEnd();
});
}
private void RandomizePinButton_Click(object sender, RoutedEventArgs e)
{
PinTextBox.Text = AppSettings.GenerateSecret();
}
protected override void OnClosed(EventArgs e)
{
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
if (_server != null)
{
_server.Stop();
_server = null;
}
base.OnClosed(e);
}
} // class
} // namespace