forked from KirosHan/Palworld-server-protector-DotNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form1.cs
1202 lines (1002 loc) · 46.5 KB
/
Form1.cs
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Palworld_server_protector_DotNet
{
using Microsoft.VisualBasic.Devices;
using System.Diagnostics;
using System.Windows.Forms;
using System;
using System.IO;
using System.IO.Compression;
using System.Drawing;
using static System.Net.WebRequestMethods;
using System.Runtime.InteropServices;
using System.Text;
using static System.Windows.Forms.LinkLabel;
using System.Net;
using System.Globalization;
using System.Reflection;
public partial class Form1 : Form
{
private Timer? memTimer;
private Timer? saveTimer;
private Timer? getplayerTimer;
private Timer? getversionTimer;
private configForm? configForm;
private Settings Settings = new Settings();
private string errorLogname = $"error_{DateTime.Now.ToString("yyyyMMddHHmmss")}.log";
private string projectUrl = $"https://github.com/KirosHan/Palworld-server-protector-DotNet";
private int playersTimercounter = 0;
private int playersTimerthreshold = 600;//每半小时触发600次
private int getversionErrorCounter = 0;
private string versionChcekUrl = $"http://127.0.0.1/version?v=";
private const string ConfigFilePath = "config.ini";
private const string JsonConfigFilePath = "config.json";
private Dictionary<string, DateTime> playerNotificationTimes = new Dictionary<string, DateTime>();//记录玩家触发通知时间
private List<PalUserInfo> lastPlayerlist = new List<PalUserInfo>();
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public Form1()
{
InitializeComponent();
}
private void InitializeTimer()
{
memTimer = new Timer();
memTimer.Interval = 35000; // 设置定时器间隔为5秒
memTimer.Tick += Timer_Tick;
saveTimer = new Timer();
saveTimer.Interval = 35000; // 设置定时器间隔为5秒
saveTimer.Tick += saveTimer_Tick;
getplayerTimer = new Timer();
getplayerTimer.Interval = 3000; // 设置定时器间隔为s秒
getplayerTimer.Tick += getplayerTimer_Tick;
getversionTimer = new Timer();
getversionTimer.Interval = 10000; // 设置定时器间隔为s秒
getversionTimer.Tick += getversionTimer_Tick;
}
private async void Timer_Tick(object sender, EventArgs e)
{
// 获取系统内存使用百分比
var memoryUsage = Math.Round(GetSystemMemoryUsagePercentage(), 2);
memProcessbar.Value = (int)memoryUsage;
memOutput.Text = $"{memoryUsage}%";
if (Settings.IsOutputMemInfo)
{
//OutputMessageAsync($"当前时间:{DateTime.Now}");
OutputMessageAsync($"内存使用百分比:{memoryUsage}%");
}
if (checkBox_reboot.Checked)//自动关服
{
if (memoryUsage >= Settings.MemTarget)
{
try
{
var isProcessRunning = IsProcessRunning(Settings.CmdPath);
if (isProcessRunning)
{
OutputMessageAsync($"内存达到警戒阈值!!!");
// 使用rcon向服务端发送指令
var info = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, "save");
OutputMessageAsync($"{info}");
var result = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, $"Shutdown {Settings.RebootSeconds} The_server_will_restart_in_{Settings.RebootSeconds}_seconds.");
OutputMessageAsync($"{result}");
OutputMessageAsync($"紧急存档中...");
CopyGameDataToBackupPath();
if (checkbox_web_reboot.Checked == true) { SendWebhookAsync("内存达到警戒阈值", $"内存使用率:{memoryUsage}%,已尝试关闭服务器。"); }
ShowNotification($"内存使用率:{memoryUsage}%,已尝试关闭服务器。");
}
}
catch (Exception ex)
{
OutputMessageAsync($"发送指令失败,请检查配置。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x69>>>指令发送错误>>>错误信息:{ex.Message}"));
if (checkbox_web_reboot.Checked == true) { SendWebhookAsync("Rcon失败", $"发送关服指令失败,请及时检查。"); }
ShowNotification($"发送关服指令失败,请及时检查。");
}
}
}
if (checkBox_startprocess.Checked)
{ //监控&自启
// 检查进程是否在运行
var isProcessRunning = IsProcessRunning(Settings.CmdPath);
labelForprogram.Text = $"{(isProcessRunning ? "运行中" : "未运行")}";
OutputMessageAsync($"进程运行状态:{(isProcessRunning ? "运行中" : "未运行")}");
if (!isProcessRunning)
{
try
{
Process process;
int processId;
if (checkBox_args.Checked && arguments.Text != "")
{
OutputMessageAsync($"正在尝试启动服务端({arguments.Text})...");
process = Process.Start(Settings.CmdPath, arguments.Text);
processId = process.Id;
}
else
{
OutputMessageAsync($"正在尝试启动服务端...");
process = Process.Start(Settings.CmdPath);
processId = process.Id;
}
if (processId > 0)
{
labelForPid.Text = processId.ToString();
labelForpidText.Visible = true;
labelForPid.Visible = true;
OutputMessageAsync($"服务端启动成功。");
if (checkBox_web_startprocess.Checked) { SendWebhookAsync("服务端启动成功", $"服务端启动成功。"); }
ShowNotification($"服务端启动成功。");
}
else
{
OutputMessageAsync($"服务端启动失败。");
if (checkBox_web_startprocess.Checked) { SendWebhookAsync("服务端启动失败", $"服务端启动失败。"); }
ShowNotification($"服务端启动失败。");
}
}
catch (Exception ex)
{
OutputMessageAsync($"服务端启动失败。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x71>>>服务端启动错误>>>错误信息:{ex.Message}"));
if (checkBox_web_startprocess.Checked) { SendWebhookAsync("服务端启动失败", $"服务端启动失败,请及时检查。"); }
ShowNotification($"服务端启动失败,请及时检查。");
}
}
}
}
private async void getplayerTimer_Tick(object sender, EventArgs e) //获取在线玩家
{
try
{
if (!checkBox_geplayers.Checked)
{
return;
}
//var players = RconUtils.ShowPlayers(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text);
var players = await Rcon.GetPlayers(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text);
playersCounterLabel.Text = $"当前在线:{players.Count}人";
// Clear the playersView
playersView.Items.Clear();
var playerList = "";
// Add the players information to the playersView
foreach (var player in players)
{
var item = new ListViewItem(new[] { player.Name, player.Uid, player.SteamId });
playersView.Items.Add(item);
playerList = playerList + player.Name + ",";
}
DateTime now = DateTime.Now;
List<string> toNotifyNewPlayers = new List<string>();
List<string> toNotifyOffPlayers = new List<string>();
var newPlayerlist = "";
List<PalUserInfo> newPlayers = players.Except(lastPlayerlist).ToList();
foreach (var p in newPlayers)
{
if (!playerNotificationTimes.ContainsKey(p.Name) || (now - playerNotificationTimes[p.Name]).TotalSeconds >= 5)
{
toNotifyNewPlayers.Add(p.Name);
playerNotificationTimes[p.Name] = now;
}
}
var offPlayerlist = "";
List<PalUserInfo> offPlayers = lastPlayerlist.Except(players).ToList();
foreach (var p in offPlayers)
{
if (!playerNotificationTimes.ContainsKey(p.Name) || (now - playerNotificationTimes[p.Name]).TotalSeconds >= 5)
{
toNotifyOffPlayers.Add(p.Name);
playerNotificationTimes[p.Name] = now;
}
}
newPlayerlist = string.Join(",", toNotifyNewPlayers.Select(p => $"[{p}]"));
offPlayerlist = string.Join(",", toNotifyOffPlayers.Select(p => $"[{p}]"));
/*f发不了中文,qnmd
var info = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, $"Broadcast {newPlayerlist.Replace(" ", "_")}_join_the_game.");
OutputMessageAsync($"{info}");
*/
if (checkBox_playerStatus.Checked == true)
{
if (newPlayerlist != "")
{
OutputMessageAsync($"{newPlayerlist.TrimEnd(',')}加入了游戏。");
SendWebhookAsync("玩家加入游戏", $"{newPlayerlist.TrimEnd(',')}加入了游戏。");
}
if (offPlayerlist != "")
{
OutputMessageAsync($"{offPlayerlist.TrimEnd(',')}离开了游戏。");
SendWebhookAsync("玩家离开游戏", $"{offPlayerlist.TrimEnd(',')}离开了游戏。");
}
}
lastPlayerlist = players;
playersTimercounter += 1;
if (playersTimercounter >= playersTimerthreshold)
{
playersTimercounter = 0;
playerList = playerList.TrimEnd(',');
if (checkBox_web_getplayers.Checked == true) { SendWebhookAsync("在线玩家统计", $"当前在线玩家:{players.Count}人。\r\n{playerList}"); }
}
}
catch (Exception ex)
{
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x67>>>获取在线玩家失败>>>错误信息:{ex.Message}"));
}
}
private async void CopyGameDataToBackupPath()
{
await Task.Run(() =>
{
try
{
if (Settings.BackupPath == "")
{
Invoke(new Action(() => OutputMessageAsync($"未设置备份存放目录。无法备份。")));
return;
}
string backupFolderName = $"SaveGames-{DateTime.Now.ToString("yyyyMMdd-HHmmss")}.zip";
string backupFilePath = Path.Combine(Settings.BackupPath, backupFolderName);
if (!Directory.Exists(Settings.GameDataPath))
{
Invoke(new Action(() => OutputMessageAsync($"游戏存档路径不存在:{Settings.GameDataPath}")));
return;
}
if (!Directory.Exists(Settings.BackupPath))
{
Invoke(new Action(() => OutputMessageAsync($"存档备份路径不存在:{Settings.BackupPath}")));
return;
}
// 使用唯一标识符确保每次都创建一个新的临时目录
string tempGameDataPath = Path.Combine(Path.GetTempPath(), $"TempGameData-{Guid.NewGuid()}");
Directory.CreateDirectory(tempGameDataPath);
string tempGameDataCopyPath = Path.Combine(tempGameDataPath, "GameData");
// Copy the game data to the temporary directory
DirectoryCopy(Settings.GameDataPath, tempGameDataCopyPath, true);
ZipFile.CreateFromDirectory(tempGameDataCopyPath, backupFilePath);
try
{
Directory.Delete(tempGameDataPath, true);
}
catch (IOException)
{
// 如果删除失败,可能需要重试或记录错误
Task.Delay(1000).Wait(); // 稍等一会儿再次尝试
Directory.Delete(tempGameDataPath, true); // 重新尝试删除
}
Invoke(new Action(() => OutputMessageAsync($"游戏存档已成功备份")));
if (checkBox_web_save.Checked) { SendWebhookAsync("存档备份", $"游戏存档已成功备份。"); }
ShowNotification($"游戏存档已成功备份。");
}
catch (Exception ex)
{
Invoke(new Action(() => OutputMessageAsync($"备份存档失败")));
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x92>>>备份存档错误>>>错误信息:{ex.Message}"));
if (checkBox_web_save.Checked) { SendWebhookAsync("存档备份失败", $"存档备份失败,请及时检查。"); }
ShowNotification($"存档备份失败,请及时检查。");
}
});
}
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception
if (!dir.Exists)
{
OutputMessageAsync($"游戏存档路径不存在:{sourceDirName}");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x91>>>游戏存档路径不存在>>>错误信息:{sourceDirName}"));
ShowNotification($"游戏存档路径不存在:{sourceDirName}");
}
// If the destination directory does not exist, create it
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void saveTimer_Tick(object sender, EventArgs e) //存档逻辑
{
OutputMessageAsync($"自动存档中...");
CopyGameDataToBackupPath();
}
private float GetSystemMemoryUsagePercentage()
{
var info = new ComputerInfo();
var totalMemory = (float)info.TotalPhysicalMemory;
var availableMemory = (float)info.AvailablePhysicalMemory;
var memoryUsage = (totalMemory - availableMemory) / totalMemory;
return memoryUsage * 100;
}
private bool IsProcessRunning(string processPath)
{
var processName = Path.GetFileNameWithoutExtension(processPath);
var processes = Process.GetProcessesByName(processName);
return processes.Length > 0;
}
private void selectCmdbutton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Executable Files|*.exe";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
cmdbox.Text = openFileDialog.FileName;
OutputMessageAsync($"已选择服务端路径为:{Settings.CmdPath}");
gamedataBox.Text = Path.Combine(Path.GetDirectoryName(Settings.CmdPath), "Pal", "Saved", "SaveGames");
OutputMessageAsync($"游戏存档路径修改为:{Settings.GameDataPath}");
}
}
private void OutputMessageAsync(string message)
{
outPutbox.Invoke(new Action(() =>
{
outPutbox.AppendText($"[{DateTime.Now.ToString("HH:mm:ss")}] {message}" + Environment.NewLine);
if (outPutbox.Lines.Length > 100)
{
outPutbox.Text = string.Join(Environment.NewLine, outPutbox.Lines.Skip(outPutbox.Lines.Length - 100));
outPutbox.SelectionStart = outPutbox.Text.Length;
outPutbox.ScrollToCaret();
}
else
{
outPutbox.SelectionStart = outPutbox.Text.Length;
outPutbox.ScrollToCaret();
}
}));
}
private void getversionTimer_Tick(object sender, EventArgs e) //获取版本信息
{
string buildVersion = Application.ProductVersion;
int endIndex = buildVersion.IndexOf('+');
string version = endIndex > 0 ? buildVersion.Substring(0, endIndex) : buildVersion; //去掉构建标识符
checkVersion(version);
}
private void Form1_Load(object sender, EventArgs e)
{
playersView.View = View.Details;
playersView.Columns.Add(new ColumnHeader() { Text = "Name", Width = playersView.Width / 3 });
playersView.Columns.Add(new ColumnHeader() { Text = "UID", Width = playersView.Width / 3 });
playersView.Columns.Add(new ColumnHeader() { Text = "Steam ID", Width = playersView.Width / 3 });
playersView.FullRowSelect = true;
playersView.MultiSelect = false;
playersView.HideSelection = false;
comboBox_id.SelectedIndex = 0;
InitializeTimer();
string buildVersion = Application.ProductVersion;
int endIndex = buildVersion.IndexOf('+'); // 找到版本号中的"+"符号的索引位置
string version = endIndex > 0 ? buildVersion.Substring(0, endIndex) : buildVersion;
this.Text = $"Palworld Server Protector v{version}";
// 加载配置文件,处理配置文件和UI之间数据绑定
LoadConfig();
SyncUIWithSettings(Settings);
SetupDataBindings(Settings);
memTimer.Start();
verisionLabel.Text = $"当前版本:{version}";
checkVersion(version);
OutputMessageAsync($"当前构建版本号:{version}");
}
private async void checkVersion(string myversion)
{
try
{
using (WebClient client = new WebClient())
{
string json = await client.DownloadStringTaskAsync(new Uri(versionChcekUrl + myversion));
dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string latestVersion = data[0].version;
string notice = data[0].notice;
string news = data[0].news;
string updatetime = data[0].date.ToString("yyyy/MM/dd");
if (notice != "")
{
OutputMessageAsync($"{notice}");
ShowNotification($"{notice}", true);
}
if (news != "")
{
OutputMessageAsync($"{news}");
}
if (IsVersionNewer(latestVersion, myversion))
{
this.Invoke(new Action(() =>
{
linkLabel2.Text = $"点击下载最新版本(v{latestVersion})";
projectUrl = data[0].url;
linkLabel2.Visible = true;
}));
OutputMessageAsync($"【更新】新版本v{latestVersion}({updatetime})已经发布,请点击最下方链接前往下载更新。");
}
}
getversionTimer.Stop();
}
catch
{
if (getversionErrorCounter == 0)
{
getversionTimer.Start();
}
getversionErrorCounter++;
if (getversionErrorCounter >= 5)
{
getversionTimer.Stop();
}
}
}
private bool IsVersionNewer(string latestVersion, string myVersion)
{
Version latest = new Version(latestVersion);
Version current = new Version(myVersion);
return latest > current;
}
private void SyncUIWithSettings(Settings settings)
{
// 同步字符串和数值属性
cmdbox.Text = settings.CmdPath;
backupPathbox.Text = settings.BackupPath;
gamedataBox.Text = settings.GameDataPath;
memTargetbox.Value = settings.MemTarget;
//Settings.RconHostbox.Text = settings.RconHost;
rconPortbox.Text = settings.RconPort.ToString();
passWordbox.Text = settings.RconPassword;
rebootSecondbox.Value = settings.RebootSeconds;
checkSecondbox.Value = settings.CheckSeconds;
backupSecondsbox.Value = settings.BackupSeconds;
arguments.Text = settings.Parameters;
webhookBox.Text = settings.WebhookUrl;
// 同步布尔属性(复选框)
checkBox_reboot.Checked = settings.IsReboot;
checkBox_startprocess.Checked = settings.IsStartProcess;
checkBox_args.Checked = settings.IsParameters;
checkBox_Noti.Checked = settings.IsNoti;
checkBox_save.Checked = settings.IsSave;
checkBox_geplayers.Checked = settings.IsGetPlayers;
checkBox_webhook.Checked = settings.IsWebhook;
checkBox_web_getplayers.Checked = settings.IsWebGetPlayers;
checkbox_web_reboot.Checked = settings.IsWebReboot;
checkBox_web_save.Checked = settings.IsWebSave;
checkBox_web_startprocess.Checked = settings.IsWebStartProcess;
checkBox_playerStatus.Checked = settings.IsWebPlayerStatus;
checkBox_mem.Checked = settings.IsOutputMemInfo;
}
private void SetupDataBindings(Settings settings)
{
// 清除现有的绑定
ClearDataBindings();
// 字符串和数值属性的绑定
cmdbox.DataBindings.Add("Text", settings, nameof(Settings.CmdPath), false, DataSourceUpdateMode.OnPropertyChanged);
backupPathbox.DataBindings.Add("Text", settings, nameof(Settings.BackupPath), false, DataSourceUpdateMode.OnPropertyChanged);
gamedataBox.DataBindings.Add("Text", settings, nameof(Settings.GameDataPath), false, DataSourceUpdateMode.OnPropertyChanged);
memTargetbox.DataBindings.Add("Value", settings, nameof(Settings.MemTarget), false, DataSourceUpdateMode.OnPropertyChanged);
rconPortbox.DataBindings.Add("Text", settings, nameof(Settings.RconPort), false, DataSourceUpdateMode.OnPropertyChanged);
passWordbox.DataBindings.Add("Text", settings, nameof(Settings.RconPassword), false, DataSourceUpdateMode.OnPropertyChanged);
rebootSecondbox.DataBindings.Add("Value", settings, nameof(Settings.RebootSeconds), false, DataSourceUpdateMode.OnPropertyChanged);
checkSecondbox.DataBindings.Add("Value", settings, nameof(Settings.CheckSeconds), false, DataSourceUpdateMode.OnPropertyChanged);
backupSecondsbox.DataBindings.Add("Value", settings, nameof(Settings.BackupSeconds), false, DataSourceUpdateMode.OnPropertyChanged);
arguments.DataBindings.Add("Text", settings, nameof(Settings.Parameters), false, DataSourceUpdateMode.OnPropertyChanged);
webhookBox.DataBindings.Add("Text", settings, nameof(Settings.WebhookUrl), false, DataSourceUpdateMode.OnPropertyChanged);
// 布尔属性(复选框)的绑定
checkBox_reboot.DataBindings.Add("Checked", settings, nameof(Settings.IsReboot), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_startprocess.DataBindings.Add("Checked", settings, nameof(Settings.IsStartProcess), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_args.DataBindings.Add("Checked", settings, nameof(Settings.IsParameters), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_Noti.DataBindings.Add("Checked", settings, nameof(Settings.IsNoti), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_save.DataBindings.Add("Checked", settings, nameof(Settings.IsSave), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_geplayers.DataBindings.Add("Checked", settings, nameof(Settings.IsGetPlayers), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_webhook.DataBindings.Add("Checked", settings, nameof(Settings.IsWebhook), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_web_getplayers.DataBindings.Add("Checked", settings, nameof(Settings.IsWebGetPlayers), false, DataSourceUpdateMode.OnPropertyChanged);
checkbox_web_reboot.DataBindings.Add("Checked", settings, nameof(Settings.IsWebReboot), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_web_save.DataBindings.Add("Checked", settings, nameof(Settings.IsWebSave), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_web_startprocess.DataBindings.Add("Checked", settings, nameof(Settings.IsWebStartProcess), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_playerStatus.DataBindings.Add("Checked", settings, nameof(Settings.IsWebPlayerStatus), false, DataSourceUpdateMode.OnPropertyChanged);
checkBox_mem.DataBindings.Add("Checked", settings, nameof(Settings.IsOutputMemInfo), false, DataSourceUpdateMode.OnPropertyChanged);
}
private void ClearDataBindings()
{
cmdbox.DataBindings.Clear();
backupPathbox.DataBindings.Clear();
gamedataBox.DataBindings.Clear();
memTargetbox.DataBindings.Clear();
rconPortbox.DataBindings.Clear();
passWordbox.DataBindings.Clear();
rebootSecondbox.DataBindings.Clear();
checkSecondbox.DataBindings.Clear();
backupSecondsbox.DataBindings.Clear();
arguments.DataBindings.Clear();
webhookBox.DataBindings.Clear();
checkBox_reboot.DataBindings.Clear();
checkBox_startprocess.DataBindings.Clear();
checkBox_args.DataBindings.Clear();
checkBox_Noti.DataBindings.Clear();
checkBox_save.DataBindings.Clear();
checkBox_geplayers.DataBindings.Clear();
checkBox_webhook.DataBindings.Clear();
checkBox_web_getplayers.DataBindings.Clear();
checkbox_web_reboot.DataBindings.Clear();
checkBox_web_save.DataBindings.Clear();
checkBox_web_startprocess.DataBindings.Clear();
checkBox_playerStatus.DataBindings.Clear();
checkBox_mem.DataBindings.Clear();
}
private void LoadConfig()
{
try
{
if (System.IO.File.Exists(JsonConfigFilePath))
{
Settings = Settings.LoadFromConfigFile(JsonConfigFilePath);
OutputMessageAsync($"从 {JsonConfigFilePath} 读取配置");
}
else
{
if (System.IO.File.Exists(ConfigFilePath))
{
Settings = Settings.LoadSettingsFromIniFile(ConfigFilePath);
OutputMessageAsync($"从 {ConfigFilePath} 读取配置");
}
else
{
OutputMessageAsync($"未找到配置文件,已加载默认配置。");
ShowNotification($"未找到配置文件,已加载默认配置。");
}
}
}
catch (Exception ex)
{
OutputMessageAsync($"读取配置文件失败。");
ShowNotification($"读取配置文件失败。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0xA1>>>读取配置文件错误>>>错误信息:{ex.Message}"));
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveConfig();
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true; // 取消关闭事件
this.Hide(); // 隐藏窗体
ShowNotification($"程序已最小化到托盘。", true);
notifyIcon1.Visible = true; // 显示托盘图标
}
}
private void SaveConfig()
{
Settings.SaveToConfigFile(JsonConfigFilePath);
}
private void checkBox_startprocess_CheckedChanged(object sender, EventArgs e)
{
if (Settings.CmdPath == "")
{
labelForstart.Text = "[ 关闭 ]";
OutputMessageAsync($"请先设置服务端路径。");
labelForPid.Visible = false;
labelForpidText.Visible = false;
checkBox_startprocess.Checked = false;
}
else if (checkBox_startprocess.Checked)
{
labelForstart.Text = "[ 开启 ]";
OutputMessageAsync($"已开始监控服务端。");
}
else
{
labelForprogram.Text = "未知";
labelForstart.Text = "[ 关闭 ]";
labelForPid.Visible = false;
labelForpidText.Visible = false;
OutputMessageAsync($"已停止监控服务端。");
}
}
private void checkBox_save_CheckedChanged(object sender, EventArgs e)
{
if (checkBox_save.Checked)
{
if (Settings.GameDataPath == "")
{
OutputMessageAsync($"请先选择游戏存档路径。");
labelForsave.Text = "[ 关闭 ]";
checkBox_save.Checked = false;
}
else if (Settings.BackupPath == "")
{
OutputMessageAsync($"请先选择存档备份路径。");
labelForsave.Text = "[ 关闭 ]";
checkBox_save.Checked = false;
}
else
{
saveTimer.Interval = Convert.ToInt32(backupSecondsbox.Value) * 1000;
saveTimer.Start();
labelForsave.Text = "[ 开启 ]";
OutputMessageAsync($"已启用自动备份存档。");
OutputMessageAsync($"自动存档中...");
CopyGameDataToBackupPath();
}
}
else
{
saveTimer.Stop();
labelForsave.Text = "[ 关闭 ]";
OutputMessageAsync($"已停用自动备份存档。");
}
}
private void selectBackuppathButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
backupPathbox.Text = folderBrowserDialog.SelectedPath;
OutputMessageAsync($"已选择存档备份路径为:{backupPathbox.Text}");
}
}
private void rconPortbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8)
{
e.Handled = true;
}
}
private void checkBox_reboot_CheckedChanged(object sender, EventArgs e)
{
if (Settings.CmdPath == "")
{
checkBox_reboot.Checked = false;
labelForreboot.Text = "[ 关闭 ]";
OutputMessageAsync($"请先选择服务端路径。");
}
else if (checkBox_reboot.Checked)
{
labelForreboot.Text = "[ 开启 ]";
OutputMessageAsync($"已启用自动关服。");
}
else
{
labelForreboot.Text = "[ 关闭 ]";
OutputMessageAsync($"已停用自动关服。");
}
}
private void checkBox_geplayers_CheckedChanged(object sender, EventArgs e)
{
if (checkBox_geplayers.Checked)
{
playersTimercounter = playersTimerthreshold;//启动即触发一次
getplayerTimer.Start();
labelForgetplayers.Text = "[ 开启 ]";
OutputMessageAsync($"已启用自动获取在线玩家。");
}
else
{
getplayerTimer.Stop();
labelForgetplayers.Text = "[ 关闭 ]";
OutputMessageAsync($"已停用自动获取在线玩家。");
playersCounterLabel.Text = $"当前在线:未知";
}
}
private void memOutput_Click(object sender, EventArgs e)
{
}
private async void button2_Click(object sender, EventArgs e)
{
var info = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, "save");
OutputMessageAsync($"{info}");
}
private async void button3_Click(object sender, EventArgs e)
{
try
{
var result = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, $"Shutdown 10 The_server_will_restart_in_10econds.");
OutputMessageAsync($"{result}");
}
catch (Exception ex)
{
OutputMessageAsync($"关服指令发送失败。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x69>>>指令发送错误>>>错误信息:{ex.Message}"));
}
}
private async void button4_Click(object sender, EventArgs e)
{
var info = "";
try
{
info = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, "info");
int startIndex = info.IndexOf("[") + 1;
int endIndex = info.IndexOf("]");
string version = info.Substring(startIndex, endIndex - startIndex);
int lastIndex = info.IndexOf("] ");
string serverName = info.Substring(lastIndex + 2);
labelForservername.Text = $"服务器名称:{serverName}";
versionLabel.Text = $"服务端版本:{version}";
OutputMessageAsync($"当前服务端版本:{version}");
}
catch (Exception ex)
{
OutputMessageAsync($"发送命令时发生错误。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x68>>>处理服务端版本信息错误>>>返回值为[{info}]>>>错误信息:{ex.Message}"));
}
}
private async void button1_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = textBox1.Text.Replace(" ", "_");
var info = await Rcon.SendCommand(Settings.RconHost, Convert.ToInt32(rconPortbox.Text), passWordbox.Text, $"broadcast {textBox1.Text.Trim()}");
OutputMessageAsync($"{info}");
}
catch (Exception ex)
{
OutputMessageAsync($"broadcast指令发送失败。");
Task.Run(() => Logger.AppendToErrorLog($"ErrorCode:0x69>>>指令发送错误>>>错误信息:{ex.Message}"));
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
string url = "https://github.com/KirosHan/Palworld-server-protector-DotNet";
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
catch (Exception ex)
{
}
}
private void checkBox_args_CheckedChanged(object sender, EventArgs e)
{
if (checkBox_args.Checked)
{
arguments.Enabled = true;
OutputMessageAsync($"请填写服务端启动参数。");
}
else
{
arguments.Enabled = false;
}
}
private void selectCustombutton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
gamedataBox.Text = folderBrowserDialog.SelectedPath;
OutputMessageAsync($"已选择游戏存档路径为:{Settings.GameDataPath}");
}
}
private bool isKeyUpEvent_backupSecond = false;
private void backupSecondsbox_KeyUp(object sender, KeyEventArgs e)
{
var newBackupSecond = Convert.ToInt32(backupSecondsbox.Value) * 1000;
saveTimer.Interval = newBackupSecond;
isKeyUpEvent_backupSecond = true;
OutputMessageAsync($"存档周期已调整为:{newBackupSecond / 1000}秒");
}
private void backupSecondsbox_ValueChanged(object sender, EventArgs e)
{
if (isKeyUpEvent_backupSecond)
{
isKeyUpEvent_backupSecond = false;
return;
}
var newBackupSecond = Convert.ToInt32(backupSecondsbox.Value) * 1000;
saveTimer.Interval = newBackupSecond;
OutputMessageAsync($"存档周期已调整为:{newBackupSecond / 1000}秒");
}
private void rebootSecondbox_ValueChanged(object sender, EventArgs e)
{
OutputMessageAsync($"重启延迟已设置为:{Settings.RebootSeconds}秒");
}
private bool isKeyUpEvent_checkSecond = false;
private void checkSecondbox_ValueChanged(object sender, EventArgs e)
{
if (isKeyUpEvent_checkSecond)
{
isKeyUpEvent_checkSecond = false;
return;
}
var newSecond = Convert.ToInt32(checkSecondbox.Value);
memTimer.Interval = newSecond * 1000;
OutputMessageAsync($"监测周期已调整为:{newSecond}秒");
}
private void checkSecondbox_KeyUp(object sender, KeyEventArgs e)
{
var newSecond = Convert.ToInt32(checkSecondbox.Value);
memTimer.Interval = newSecond * 1000;
isKeyUpEvent_checkSecond = true;
OutputMessageAsync($"监测周期已调整为:{newSecond}秒");
}
private void memTargetbox_ValueChanged(object sender, EventArgs e)
{
OutputMessageAsync($"内存阈值已调整为:{memTargetbox.Value}%");
}
private void playersView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (playersView.SelectedItems.Count > 0)
{
string Uid = playersView.SelectedItems[0].SubItems[1].Text;
string Steamid = playersView.SelectedItems[0].SubItems[2].Text;
string Name = playersView.SelectedItems[0].SubItems[0].Text;
if (comboBox_id.SelectedIndex == 0)
{
UIDBox.Text = Uid;
}