-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProgram.cs
More file actions
500 lines (420 loc) · 17.4 KB
/
Copy pathProgram.cs
File metadata and controls
500 lines (420 loc) · 17.4 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#if WINDOWS
using System.Runtime.InteropServices;
#endif
using Spectre.Console;
using System.Net.NetworkInformation;
using System.Text;
using System.Reflection;
namespace Pings
{
internal partial class Program
{
public static string GetAppVersion()
{
var full = Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion;
if (string.IsNullOrWhiteSpace(full))
return "Unknown";
return full.Split('-', '+')[0];
}
private static CancellationTokenSource CTS { get; set; } = new();
private static Logging Logging { get; set; } = new("pings.log");
private static NotificationService? Notifier { get; set; }
#if WINDOWS
internal static partial class WindowsAPI
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CONSOLE_FONT_INFO_EX
{
public uint cbSize;
public uint nFont;
public short dwFontSizeX;
public short dwFontSizeY;
public int FontFamily;
public int FontWeight;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string FaceName;
}
[StructLayout(LayoutKind.Sequential)]
public struct COORD
{
public short X;
public short Y;
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOW_BUFFER_SIZE_RECORD
{
public COORD dwSize;
}
[StructLayout(LayoutKind.Explicit)]
public struct INPUT_RECORD
{
[FieldOffset(0)]
public ushort EventType;
[FieldOffset(4)]
public WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
}
[LibraryImport("kernel32.dll", SetLastError = true)]
public static partial IntPtr GetStdHandle(int nStdHandle);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetConsoleOutputCP(uint wCodePageID);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetConsoleCP(uint wCodePageID);
public delegate bool HandlerRoutine(int ctrlType);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetConsoleCtrlHandler(HandlerRoutine handler, [MarshalAs(UnmanagedType.Bool)] bool add);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetCurrentConsoleFontEx(IntPtr consoleOutput, [MarshalAs(UnmanagedType.Bool)] bool maximumWindow, ref CONSOLE_FONT_INFO_EX consoleFontEx);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool GetConsoleMode(
IntPtr hConsoleHandle,
out uint lpMode);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetConsoleMode(
IntPtr hConsoleHandle,
uint dwMode);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool PeekConsoleInputW(
IntPtr hConsoleInput,
[Out] INPUT_RECORD[] lpBuffer,
uint nLength,
out uint lpNumberOfEventsRead);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ReadConsoleInputW(
IntPtr hConsoleInput,
[Out] INPUT_RECORD[] buffer,
uint length,
out uint eventsRead);
}
internal static partial class WindowsConsoleCompatible
{
private const int STD_OUTPUT_HANDLE = -11;
public static void ForceSetConsoleFont(string fontName, short fontSizeY = 16)
{
var handle = WindowsAPI.GetStdHandle(STD_OUTPUT_HANDLE);
if (handle == IntPtr.Zero || handle == new IntPtr(-1))
return;
var info = new WindowsAPI.CONSOLE_FONT_INFO_EX
{
cbSize = (uint)Marshal.SizeOf<WindowsAPI.CONSOLE_FONT_INFO_EX>(),
FaceName = fontName,
dwFontSizeX = 0,
dwFontSizeY = fontSizeY,
FontFamily = 54,
FontWeight = 400
};
WindowsAPI.SetCurrentConsoleFontEx(handle, false, ref info);
}
public static void EnableUTF8Support()
{
const uint CP_UTF8 = 65001;
if (!WindowsAPI.SetConsoleOutputCP(CP_UTF8))
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "无法设置控制台输出代码页为UTF-8");
}
if (!WindowsAPI.SetConsoleCP(CP_UTF8))
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "无法设置控制台输入代码页为UTF-8");
}
}
public static void RegisterConsoleShutdown(WindowsAPI.HandlerRoutine handler)
{
WindowsAPI.SetConsoleCtrlHandler(handler, true);
}
}
internal static partial class ConsoleResizeWatcher
{
private const int STD_INPUT_HANDLE = -10;
private const ushort WINDOW_BUFFER_SIZE_EVENT = 0x0004;
private const uint ENABLE_WINDOW_INPUT = 0x0008;
private const uint ENABLE_EXTENDED_FLAGS = 0x0080;
private const uint ENABLE_QUICK_EDIT = 0x0040;
private static Task? worker;
private static int lastWidth;
private static int lastHeight;
public static bool IsRunning => worker != null && !worker.IsCompleted;
public static event Action<int, int>? Resized;
public static void Start(CancellationToken token)
{
if (IsRunning)
return;
worker = Task.Run(() => Worker(token), token);
}
private static void Worker(CancellationToken token)
{
var handle = WindowsAPI.GetStdHandle(STD_INPUT_HANDLE);
if (handle == IntPtr.Zero || handle == new IntPtr(-1))
return;
if (WindowsAPI.GetConsoleMode(handle, out uint mode))
{
uint newMode =
mode
| ENABLE_WINDOW_INPUT
| ENABLE_EXTENDED_FLAGS;
newMode &= ~ENABLE_QUICK_EDIT;
WindowsAPI.SetConsoleMode(handle, newMode);
}
lastWidth = Console.WindowWidth;
lastHeight = Console.WindowHeight;
var buffer = new WindowsAPI.INPUT_RECORD[16];
while (!token.IsCancellationRequested)
{
try
{
if (!WindowsAPI.PeekConsoleInputW(
handle,
buffer,
(uint)buffer.Length,
out uint count))
{
Thread.Sleep(50);
continue;
}
if (count == 0)
{
Thread.Sleep(50);
continue;
}
bool hasResize = false;
for (int i = 0; i < count; i++)
{
if (buffer[i].EventType == WINDOW_BUFFER_SIZE_EVENT)
{
hasResize = true;
break;
}
}
if (!hasResize)
{
Thread.Sleep(50);
continue;
}
WindowsAPI.ReadConsoleInputW(
handle,
buffer,
count,
out _);
int w = Console.WindowWidth;
int h = Console.WindowHeight;
if (w == lastWidth && h == lastHeight)
continue;
lastWidth = w;
lastHeight = h;
Resized?.Invoke(w, h);
}
catch
{
break;
}
}
}
}
#endif
public static void Exit(int code = 0, string msg = "结束运行")
{
Logging.Log(msg);
Environment.Exit(code);
}
private static void InitializeConsoleRuntime()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
#if WINDOWS
WindowsConsoleCompatible.EnableUTF8Support();
WindowsConsoleCompatible.ForceSetConsoleFont("Consolas", 18);
AnsiConsole.Profile.Capabilities.Unicode = true;
ConsoleResizeWatcher.Resized += (w, h) =>
{
if (w < 64)
{
Exit(1, "控制台窗口宽度过小!");
}
};
ConsoleResizeWatcher.Start(CTS.Token);
#endif
}
private static void RegisterShutdownEvents()
{
#if WINDOWS
WindowsConsoleCompatible.RegisterConsoleShutdown(ctrlType =>
{
Exit();
return false;
});
#endif
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
Notifier?.Dispose();
Logging.Dispose();
CTS.Cancel();
};
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Exit();
};
}
static async Task Main(string[] args)
{
try
{
Logging.Log($"开始运行");
InitializeConsoleRuntime();
RegisterShutdownEvents();
#if WINDOWS
Console.Title = $"Pings {GetAppVersion()}";
#endif
string configPath = Path.GetFullPath(args.Length > 0 ? args[0] : "config.json");
if (!File.Exists(configPath))
{
string oldConfigPath = Path.ChangeExtension(configPath, ".txt");
if (File.Exists(oldConfigPath))
{
AnsiConsole.WriteLine($"检测到旧版配置文件 {oldConfigPath},正在转换为JSON格式...");
try
{
ConvertOldConfigToJson(oldConfigPath, configPath);
}
catch (Exception ex)
{
throw new Exception($"配置升级失败: {ex.Message}");
}
}
else if (AnsiConsole.Confirm($"JSON配置文件 {configPath} 不存在,是否创建默认配置文件?"))
{
ConfigLoader.CreateDefaultConfig(configPath);
AnsiConsole.WriteLine($"已创建默认配置文件: {configPath}");
}
else
{
throw new Exception("未找到配置文件。");
}
}
AppConfig appConfig = ConfigLoader.LoadConfig(configPath);
var (IsValid, ErrorMessage) = ConfigLoader.ValidateConfig(appConfig);
if (!IsValid)
{
throw new Exception($"配置文件验证失败: {ErrorMessage}");
}
if (appConfig.Logging.LogFilePath != "Pings.log") Logging = new Logging(appConfig.Logging.LogFilePath);
if (appConfig.Notifications.Webhook.Enabled || appConfig.Notifications.Email.Enabled)
{
Notifier = new NotificationService(Logging, appConfig.Notifications);
Logging.Log("通知功能已启用");
}
ICMPMonitor monitor = new(Logging, Notifier);
foreach (var taskConfig in appConfig.Tasks)
{
monitor.AddHost(new(CTS, ConfigLoader.ToICMPTaskConfig(taskConfig)));
}
Task displayTask = StartLiveTable(monitor);
while (!CTS.IsCancellationRequested)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Q)
{
Exit();
break;
}
if (key.Key == ConsoleKey.C)
{
foreach (var task in monitor.Tasks.FindAll(i => i.Warnings.Count > 0))
_ = task.Warnings.DequeueAsync();
}
#if DEBUG
if (key.Key == ConsoleKey.T)
{
foreach (var task in monitor.Tasks)
{
task.State = IPStatus.Unknown;
//await task.Warnings.EnqueueAsync($"Test Warning! {task.Warnings.Count+1}");
}
}
#endif
}
try
{
displayTask.Wait();
}
catch { }
}
catch (TaskCanceledException)
{
Exit();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.WriteLine("按任意键退出...");
Console.ReadKey(true);
Exit(1, e.ToString());
}
}
private static Task StartLiveTable(ICMPMonitor monitor)
{
return AnsiConsole.Live(monitor.TasksTable).StartAsync(async ctx =>
{
AnsiConsole.WriteLine();
while (!CTS.Token.IsCancellationRequested)
{
try
{
monitor.TasksTable.Title = new TableTitle($"{DateTime.Now:yyyy年MM月dd日 HH:mm:ss} 网络监测");
ctx.Refresh();
await Task.Delay(1000, CTS.Token);
}
catch (TaskCanceledException)
{
break;
}
catch (Exception ex)
{
Exit(1, $"发生未知错误,程序即将退出.{ex}");
}
}
});
}
private static void ConvertOldConfigToJson(string oldConfigPath, string newConfigPath)
{
string[] configLines = [.. File.ReadAllLines(oldConfigPath)
.Select(line => line.Trim())
.Where(line => !string.IsNullOrWhiteSpace(line) && line.Split(' ').Length > 1)];
if (configLines.Length == 0)
throw new InvalidOperationException("旧版配置文件为空或格式错误");
var appConfig = new AppConfig { Tasks = [] };
foreach (var line in configLines)
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
appConfig.Tasks.Add(new ICMPTaskConfigJson
{
Name = parts[0],
IP = parts[1],
Timeout = Parse(parts, 2, 1000),
MaxRecentPackets = Parse(parts, 3, 255),
SignificantDelayThreshold = Parse(parts, 4, 20),
PacketLossDuration = ParseDouble(parts, 5, 30.0),
PacketLossCount = Parse(parts, 6, 5)
});
}
}
ConfigLoader.SaveConfig(appConfig, newConfigPath);
AnsiConsole.WriteLine($"成功转换配置文件: {newConfigPath}");
}
private static int Parse(string[] parts, int index, int defaultValue)
=> parts.Length > index && int.TryParse(parts[index], out int v) ? v : defaultValue;
private static double ParseDouble(string[] parts, int index, double defaultValue)
=> parts.Length > index && double.TryParse(parts[index], out double v) ? v : defaultValue;
}
}