-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathValheimServer.cs
2041 lines (1995 loc) · 76.7 KB
/
ValheimServer.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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using System.Text.Json.Serialization;
using System.ServiceProcess;
using System.Runtime.InteropServices;
using System.IO;
using System.Globalization;
using RazzTools;
using System.Net;
namespace ValheimServerWarden
{
public class ValheimServer : IEditableObject, IComparable, IDisposable
{
public enum ServerStatus
{
Stopped,
Running,
Starting,
Stopping,
Updating
}
public enum ServerInstallMethod
{
Manual,
Steam,
SteamCMD
}
public static List<ValheimServer> Servers { get; } = new List<ValheimServer>();
public static string DefaultSaveDir { get { return $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\AppData\LocalLow\IronGate\Valheim"; } }
public static string ExecutableName { get { return "valheim_server.exe"; } }
public static Dictionary<string, string> DiscordWebhookDefaultMessages { get; } = new Dictionary<string, string> {
{"OnStarted", "Server {Server.Name} has started on {Server.IP}:{Server.Port} ({Server.Version})." },
{"OnStartFailed", "Server {Server.Name} failed to start." },
{"OnStopped", "Server {Server.Name} has stopped." },
{"OnFailedPassword", "User with SteamID {Player.SteamID} tried to join with an invalid password." },
{"OnPlayerConnected", "{Player.Name} has entered the fray!" },
{"OnPlayerDisconnected", "{Player.Name} has departed." },
{"OnPlayerDied", "{Player.Name} met an untimely demise." },
{"OnRandomServerEvent", "{EventName} are attacking!" },
{"OnUpdateEnded", "Server update complete." }
};
public static Dictionary<string, string> DiscordWebhookDefaultAttackNames { get; } = new Dictionary<string, string>
{
{ "army_eikthyr", "Eikthyr's Kin" },
{ "army_theelder", "The Elder's Minions" },
{ "army_bonemass", "Swamp Monsters" },
{ "army_moder", "Moder's Minions" },
{ "army_goblin", "Fulings" },
{ "foresttrolls", "Forest Trolls" },
{ "skeletons", "Skeletons" },
{ "blobs", "Blobs" },
{ "wolves", "Wolves" },
{ "surtlings", "Surtlings" }
};
public static string SteamID { get { return "896660"; } }
struct ServerData
{
internal string name;
internal int port;
internal string world;
internal string password;
internal string savedir;
internal bool pub;
internal bool autostart;
internal bool rawlog;
internal int restartHours;
internal bool updateOnRestart;
internal int updateCheckMinutes;
internal string discordWebhook;
internal ProcessPriorityClass processPriority;
internal bool autoUpdateuMod;
}
public event EventHandler<UpdatedEventArgs> Updated;
public event EventHandler<FailedPasswordEventArgs> FailedPassword;
public event EventHandler<PlayerEventArgs> PlayerConnected;
public event EventHandler<PlayerEventArgs> PlayerDisconnected;
public event EventHandler<PlayerEventArgs> PlayerDied;
public event EventHandler<RandomServerEventArgs> RandomServerEvent;
public event EventHandler<EventArgs> Starting;
public event EventHandler<EventArgs> Started;
public event EventHandler<ServerErrorEventArgs> StartFailed;
public event EventHandler<ServerErrorEventArgs> StopFailed;
public event EventHandler<EventArgs> ScheduledRestart;
public event EventHandler<EventArgs> AutomaticUpdate;
public event EventHandler<ServerStoppedEventArgs> Stopped;
public event EventHandler<EventArgs> Stopping;
public event EventHandler<ServerStoppedEventArgs> StoppedUnexpectedly;
public event EventHandler<ServerErrorEventArgs> ErrorOccurred;
public event EventHandler<UpdateCheckEventArgs> CheckingForUpdate;
public event EventHandler<UpdateCheckEventArgs> CheckedForUpdate;
public event EventHandler<UpdateEndedEventArgs> UpdateEnded;
public event DataReceivedEventHandler OutputDataReceived
{
add
{
this.process.OutputDataReceived += value;
}
remove
{
this.process.OutputDataReceived -= value;
}
}
public event DataReceivedEventHandler ErrorDataReceived
{
add
{
this.process.ErrorDataReceived += value;
}
remove
{
this.process.ErrorDataReceived -= value;
}
}
public event EventHandler<LoggedMessageEventArgs> LoggedMessage;
private ServerData data;
private Dictionary<string, string> _discordWebhookMesssages;
private ServerData backupData;
private Process process;
private PlayerList players;
private ServerStatus status;
private DateTime startTime;
private bool intentionalExit;
private List<string> connectingSteamIds;
private bool needsRestart;
private bool needsUpdate;
private bool scheduledRestart;
private bool automaticUpdate;
private System.Timers.Timer restartTimer;
private System.Timers.Timer updateTimer;
private List<LogEntry> logEntries;
private bool inTxn = false;
private int stopAttempts;
private bool disposed = false;
private static string externalIP;
public string Name
{
get
{
return this.data.name;
}
set
{
this.data.name = value;
}
}
public int Port
{
get
{
return this.data.port;
}
set
{
this.data.port = value;
}
}
public string World
{
get
{
return this.data.world;
}
set
{
this.data.world = value;
}
}
public string Password
{
get
{
return this.data.password;
}
set
{
this.data.password = value;
}
}
public string SaveDir
{
get
{
return this.data.savedir;
}
set
{
this.data.savedir = value;
}
}
public bool Public
{
get
{
return this.data.pub;
}
set
{
this.data.pub = value;
}
}
public bool Autostart
{
get
{
return this.data.autostart;
}
set
{
this.data.autostart = value;
}
}
public bool RawLog
{
get
{
return this.data.rawlog;
}
set
{
this.data.rawlog = value;
}
}
public int RestartHours
{
get
{
return this.data.restartHours;
}
set
{
this.data.restartHours = value;
if (value > 0 && (this.Status == ServerStatus.Running || this.Status == ServerStatus.Starting))
{
restartTimer.Interval = this.GetMilisecondsUntilRestart();
restartTimer.Enabled = true;
restartTimer.Start();
}
else
{
restartTimer.Enabled = false;
}
}
}
public int UpdateCheckMinutes
{
get
{
return this.data.updateCheckMinutes;
}
set
{
this.data.updateCheckMinutes = value;
if (value > 0 && (this.Status == ServerStatus.Running || this.Status == ServerStatus.Starting))
{
updateTimer.Interval = this.GetMilisecondsUntilUpdateCheck();
updateTimer.Enabled = true;
updateTimer.Start();
}
else
{
restartTimer.Enabled = false;
}
}
}
public bool UpdateOnRestart
{
get
{
return this.data.updateOnRestart;
}
set
{
this.data.updateOnRestart = value;
}
}
public string DiscordWebhook
{
get
{
return this.data.discordWebhook;
}
set
{
this.data.discordWebhook = value;
}
}
public Dictionary<string,string> DiscordWebhookMessages
{
get
{
return this._discordWebhookMesssages;
}
set
{
this._discordWebhookMesssages = value;
}
}
public Dictionary<string, string> DiscordServerEventNames { get; set; }
public string InstallPath { get; set; }
public ProcessPriorityClass ProcessPriority
{
get
{
return this.data.processPriority;
}
set
{
this.data.processPriority = value;
}
}
public bool AutoUpdateuMod
{
get
{
return this.data.autoUpdateuMod;
}
set
{
this.data.autoUpdateuMod = value;
}
}
public ServerInstallMethod InstallMethod { get; set; }
[JsonIgnore]
public bool Running
{
get
{
return (this.Status == ServerStatus.Running || this.Status == ServerStatus.Starting || this.Status == ServerStatus.Stopping);
}
}
[JsonIgnore]
public ServerStatus Status
{
get
{
return this.status;
}
}
[JsonIgnore]
public int PlayerCount
{
get
{
return this.Players.Count;
}
}
[JsonIgnore]
public PlayerList Players
{
get
{
return this.players;
}
}
[JsonIgnore]
public string PlayerList
{
get
{
return this.players.ToString();
}
}
[JsonIgnore]
public DateTime StartTime
{
get { return this.startTime; }
}
[JsonIgnore]
public List<LogEntry> LogEntries
{
get
{
return logEntries;
}
}
[JsonIgnore]
public string DisplayName
{
get
{
try
{
var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(Name);
return htmlDoc.DocumentNode.InnerText.Trim();
}
catch (Exception ex)
{
addToLog($"Error getting server display name: {ex.Message}", LogEntryType.Error);
return Name;
}
}
}
[JsonIgnore]
public string LogRawName
{
get
{
return LogName.Replace(".log", "-raw.log");
}
}
[JsonIgnore]
public string LogName
{
get
{
string logname = this.DisplayName.Replace(" ", "_");
logname = Regex.Replace(logname, @"[<]", "[");
logname = Regex.Replace(logname, @"[>]", "]");
foreach (var c in Path.GetInvalidFileNameChars()) { logname = logname.Replace(c, '-'); }
return $"{logname}-{this.Port}-{this.World}.log";
}
}
[JsonIgnore]
public double MemoryUsed
{
get
{
if (this.Status == ServerStatus.Running)
{
try
{
process.Refresh();
return Math.Round(process.WorkingSet64 / (1024.0 * 1024.0));
}
catch (Exception ex)
{
addToLog($"Error getting server memory usage: {ex.Message}", LogEntryType.Error);
return 0;
}
}
return 0;
}
}
//[JsonIgnore]
public string Version { get; set; }
[JsonIgnore]
public static string ExternalIP
{
get
{
return externalIP;
}
}
static ValheimServer()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
UpdateExternalIP();
}
private static void UpdateExternalIP()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
try
{
externalIP = new WebClient().DownloadString("http://icanhazip.com").Trim();
}
catch (Exception ex)
{
Debug.WriteLine("Error getting external IP.");
Debug.WriteLine(ex);
}
}).Start();
}
public ValheimServer(string name, int port, string world, string password, bool pubserver, bool autostart, bool rawlog, int restarthours, bool updateonrestart, int updatecheckminutes, string discordwebhook, Dictionary<string,string> discordmessages, Dictionary<string, string> discordservereventnames, ServerInstallMethod install, string instpath, ProcessPriorityClass processpriority, bool umodupdating)
{
this.data.name = name;
this.data.port = 2456;
this.data.world = world;
this.data.password = password;
this.data.savedir = "";
this.data.pub = pubserver;
this.data.autostart = autostart;
this.data.rawlog = rawlog;
this.data.restartHours = restarthours;
this.data.updateOnRestart = updateonrestart;
this.data.discordWebhook = discordwebhook;
this.data.processPriority = processpriority;
this._discordWebhookMesssages = discordmessages;
this.DiscordServerEventNames = discordservereventnames;
this.data.autoUpdateuMod = umodupdating;
InstallMethod = install;
InstallPath = instpath;
Version = "Unknown";
this.process = new Process();
this.process.StartInfo.EnvironmentVariables["SteamAppId"] = "892970";
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.StartInfo.RedirectStandardError = true;
this.process.StartInfo.RedirectStandardInput = true;
this.process.EnableRaisingEvents = true;
this.process.OutputDataReceived += Process_OutputDataReceived;
this.process.Exited += Process_Exited;
restartTimer = new System.Timers.Timer();
restartTimer.AutoReset = false;
restartTimer.Elapsed += RestartTimer_Elapsed;
updateTimer = new System.Timers.Timer();
updateTimer.AutoReset = false;
updateTimer.Elapsed += UpdateTimer_Elapsed;
this.players = new PlayerList();
this.status = ServerStatus.Stopped;
this.scheduledRestart = false;
this.needsRestart = false;
this.automaticUpdate = false;
this.needsUpdate = false;
this.logEntries = new List<LogEntry>();
connectingSteamIds = new List<string>();
stopAttempts = 0;
Servers.Add(this);
}
private void UpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CheckedForUpdate += ValheimServer_ScheduledCheckedForUpdate;
this.CheckForUpdate(false);
}
private void ValheimServer_ScheduledCheckedForUpdate(object sender, UpdateCheckEventArgs e)
{
CheckedForUpdate -= ValheimServer_ScheduledCheckedForUpdate;
if (e.UpdateAvailable)
{
if (this.PlayerCount == 0)
{
OnAutomaticUpdate(new EventArgs());
}
else
{
this.needsUpdate = true;
}
}
else
{
UpdateCheckMinutes = UpdateCheckMinutes;
}
}
private void RestartTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (this.PlayerCount == 0)
{
OnScheduledRestart(new EventArgs());
} else
{
this.needsRestart = true;
}
}
public ValheimServer() : this("My Server", 2456, "Dedicated", "Secret", false, false, false, 0, false, 0, null, new Dictionary<string, string>(), new Dictionary<string, string>(), ServerInstallMethod.Manual, Properties.Settings.Default.ServerFilePath, ProcessPriorityClass.Normal, false)
{
}
public ValheimServer(string name) : this(name, 2456, "Dedicated", "Secret", false, false, false, 0, false, 0, null, new Dictionary<string,string>(), new Dictionary<string, string>(), ServerInstallMethod.Manual, Properties.Settings.Default.ServerFilePath, ProcessPriorityClass.Normal, false)
{
}
public double GetMilisecondsUntilRestart()
{
DateTime restartTime = this.startTime.AddHours(this.RestartHours);
//DateTime restartTime = this.startTime.AddMinutes(1);
TimeSpan ts = restartTime - this.startTime;
return ts.TotalMilliseconds;
}
public double GetMilisecondsUntilUpdateCheck()
{
DateTime updateCheckTime = this.startTime.AddMinutes(this.UpdateCheckMinutes);
TimeSpan ts = updateCheckTime - this.startTime;
return ts.TotalMilliseconds;
}
public string GetWebhookMessage(string EventName)
{
try
{
if (this.DiscordWebhookMessages.ContainsKey(EventName))
{
return this.DiscordWebhookMessages[EventName];
}
else if (DiscordWebhookDefaultMessages.ContainsKey(EventName))
{
return DiscordWebhookDefaultMessages[EventName];
}
}
catch (Exception ex)
{
addToLog($"Error getting webhook message for {EventName}: {ex.Message}", LogEntryType.Error);
}
return null;
}
public string GetWebhookServerEventName(string serverEventName) {
try
{
if (this.DiscordServerEventNames.ContainsKey(serverEventName))
{
return this.DiscordServerEventNames[serverEventName];
}
else if (DiscordWebhookDefaultAttackNames.ContainsKey(serverEventName))
{
return DiscordWebhookDefaultAttackNames[serverEventName];
}
return serverEventName;
}
catch (Exception ex)
{
addToLog($"Error getting webhook server event name for {serverEventName}: {ex.Message}", LogEntryType.Error);
}
return null;
}
public void SendDiscordWebhook(string EventName, Player player, string serverEventName)
{
try
{
string message = GetWebhookMessage(EventName);
if (message == "" || message == null) return;
message = message.Replace("{Server.Name}", this.DisplayName);
message = message.Replace("{Server.PlayerCount}", this.PlayerCount.ToString());
message = message.Replace("{Server.Version}", this.Version);
message = message.Replace("{Server.IP}", ValheimServer.ExternalIP);
message = message.Replace("{Server.Port}", this.Port.ToString());
if (player != null)
{
message = message.Replace("{Player.Name}", player.Name);
message = message.Replace("{Player}", player.Name);
message = message.Replace("{Player.SteamID}", player.SteamID);
message = message.Replace("{SteamID}", player.SteamID);
message = message.Replace("{Player.Deaths}", player.Deaths.ToString());
message = message.Replace("{Player.JoinTime}", player.JoinTime.ToString());
}
if (serverEventName != null)
{
message = message.Replace("{EventName}", GetWebhookServerEventName(serverEventName));
}
SendDiscordWebhook(message);
}
catch (Exception ex) {
addToLog($"Error sending webhook for {EventName}: {ex.Message}", LogEntryType.Error);
}
}
public void SendDiscordWebhook(string EventName, Player player)
{
SendDiscordWebhook(EventName, player, null);
}
public void SendDiscordWebhook(string message)
{
if (this.DiscordWebhook != null && this.DiscordWebhook != "")
{
using (DiscordWebhook webhook = new DiscordWebhook())
{
try
{
//webhook.ProfilePicture = "https://static.giantbomb.com/uploads/original/4/42381/1196379-gas_mask_respirator.jpg";
//webhook.UserName = "Bot";
webhook.WebHook = this.DiscordWebhook;
webhook.SendMessage(message);
}
catch (Exception ex)
{
addToLog($"Error sending Discord webhook: {ex.Message}", LogEntryType.Error);
}
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
try
{
string msg = e.Data;
if (msg == null) return;
//Debug.WriteLine(msg);
if (this.RawLog)
{
try
{
StreamWriter writer = System.IO.File.AppendText(LogRawName);
writer.WriteLine(msg);
writer.Close();
}
catch (Exception)
{
//not being able to clear the log is not a major problem
}
}
Regex rx;
Match match;
//Monitor for incorrect password attempts
rx = new Regex(@"Peer (\d+) has wrong password", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
if (connectingSteamIds.Contains(match.Groups[1].ToString()))
{
connectingSteamIds.Remove(match.Groups[1].ToString());
}
OnFailedPassword(new FailedPasswordEventArgs(match.Groups[1].ToString()));
return;
}
//Monitor for initiation of new connection
rx = new Regex(@"Got handshake from client (\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
connectingSteamIds.Add(match.Groups[1].ToString());
return;
}
//Monitor for new player connected and player deaths
rx = new Regex(@"Got character ZDOID from (.+) : (-?\d+:-?\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
var playername = FixPlayerNameEncoding(match.Groups[1].Value);
if (match.Groups[2].ToString().Equals("0:0"))
{
//player died
foreach (Player player in this.players)
{
if (player.Name.Equals(playername))
{
player.Deaths++;
OnPlayerDied(new PlayerEventArgs(player));
break;
}
}
}
else if (connectingSteamIds.Count > 0)
{
//player connected
var steamid = connectingSteamIds.First();
Player player = new Player(playername, steamid);
this.players.Add(player);
connectingSteamIds.Remove(steamid);
OnPlayerConnected(new PlayerEventArgs(player));
}
return;
}
//Monitor for player disconnected
rx = new Regex(@"Closing socket (\d{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
string steamid = match.Groups[1].ToString();
//Player player = new Player(match.Groups[1].ToString(), this.connectingSteamID);
var playerfound = false;
foreach (Player player in this.players)
{
if (steamid.Equals(player.SteamID))
{
this.players.Remove(player);
OnPlayerDisconnected(new PlayerEventArgs(player));
playerfound = true;
if (this.PlayerCount == 0)
{
if (this.needsRestart)
{
OnScheduledRestart(new EventArgs());
}
else if (this.needsUpdate)
{
OnAutomaticUpdate(new EventArgs());
}
}
break;
}
}
if (!playerfound)
{
if (connectingSteamIds.Contains(match.Groups[1].ToString()))
{
connectingSteamIds.Remove(match.Groups[1].ToString());
}
}
return;
}
//Monitor for random events
rx = new Regex(@"Random event set:([a-zA-Z0-9_]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
OnRandomServerEvent(new RandomServerEventArgs(match.Groups[1].ToString()));
return;
//army_moder
}
if (this.Status == ServerStatus.Starting)
{
//Monitor for server version
rx = new Regex(@"Valheim version:(\d+\.\d+\.\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
Version = match.Groups[1].ToString();
//logMessage($"Server {this.Name}: started", LogType.Success);
return;
}
//Monitor for server finishes starting
//Last since it should only happen once per server restart, so more efficient overall to check others first
rx = new Regex(@"DungeonDB Start \d+", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
OnStarted(new EventArgs());
//logMessage($"Server {this.Name}: started", LogType.Success);
return;
}
}
//Monitor for server fails to start
// handled more robustly in the process exited event handler
/*rx = new Regex(@"GameServer.Init\(\) failed", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
this.status = ServerStatus.Stopping;
OnStartFailed(new ServerEventArgs(this));
logMessage($"Server {this.Name} failed to start. Maybe try a different port", LogType.Error);
return;
}*/
//Monitor for update to number of players connected
/*rx = new Regex(@"Connections (\d+) ZDOS:(?:\d+) sent:(?:\d+) recv:(?:\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
match = rx.Match(msg);
if (match.Success)
{
this.playerCount = Int16.Parse(match.Groups[1].ToString());
OnPlayerCountUpdated(new ServerEventArgs(this));
}*/
}
catch (Exception ex)
{
addToLog($"Error processing server output: {ex.Message}", LogEntryType.Error);
}
}
public void Start()
{
try
{
if (this.Status != ValheimServer.ServerStatus.Stopped)
{
var oldstatus = this.Status;
OnStartFailed(new ServerErrorEventArgs("Server cannot start; it is already running."));
this.status = oldstatus;
return;
}
OnStarting(new EventArgs());
if (uMod.AgentInstalled && AutoUpdateuMod)
{
var umod = new uMod(this.InstallPath, "valheim");
umod.UpdateEnded += StartuMod_UpdateEnded;
umod.LoggedMessage += ((sender, args) => {
//addToLog("uMod: "+args.LogEntry.Message, args.LogEntry.Type);
});
umod.Update("core apps extensions");
}
else
{
StartServer();
}
}
catch (Exception ex)
{
addToLog($"Error initiating server start: {ex.Message}", LogEntryType.Error);
}
}
private void StartuMod_UpdateEnded(object sender, uMod.ProcessEndedEventArgs e)
{
if (e.ExitCode == 0)
{
addToLog("uMod update compelete.");
}
else if (e.ExitCode == 2)
{
addToLog($"No uMod updates needed.");
}
else
{
addToLog($"uMod terminated with code {e.ExitCode}; unable to update uMod core or uMod apps.");
}
StartServer();
}
private void StartServer()
{
try
{
if (this.Status != ServerStatus.Starting)
{
OnStartFailed(new ServerErrorEventArgs($"Server cannot start; it is {this.Status}."));
return;
}
foreach (var s in ValheimServer.Servers)
{
if (s.Running && s != this)
{
IEnumerable<int> range = Enumerable.Range(s.Port, 2);
if (range.Contains(this.Port) || range.Contains(this.Port + 1))
{
OnStartFailed(new ServerErrorEventArgs($"Server cannot start; server {s.DisplayName} is already running on conflicting port {s.Port}."));
return;
}
if (s.SaveDir == this.SaveDir && s.World == this.World)
{
OnStartFailed(new ServerErrorEventArgs($"Server cannot start; server {s.DisplayName} is already running using world {s.World}."));
return;
}
}
}
string saveDir = this.SaveDir;
if (saveDir == null || saveDir.Length == 0)
{
saveDir = DefaultSaveDir;
}
string serverpath = InstallPath;//Properties.Settings.Default.ServerFilePath;
if (!File.Exists(serverpath))
{
OnStartFailed(new ServerErrorEventArgs($"Server cannot start because {ValheimServer.ExecutableName} was not found at the server executable path ({serverpath}). Please update the server executable path."));
return;
}
string arguments = $"-nographics -batchmode -name \"{this.Name}\" -port {this.Port} -world \"{this.World}\" -public {Convert.ToInt32(Public)}";
if (Password != null & Password.Length > 0)
{
arguments += $" -password \"{this.Password}\"";
}
if (!saveDir.Equals(DefaultSaveDir))
{
arguments += $" -savedir \"{this.SaveDir}\"";
}
this.intentionalExit = false;
new Thread(() =>
{
try
{
if (this.RawLog)
{
System.IO.File.WriteAllText(LogRawName, "");
}
this.startTime = DateTime.Now;
if (this.RestartHours > 0)
{
restartTimer.Interval = this.GetMilisecondsUntilRestart();
restartTimer.Enabled = true;
restartTimer.Start();
}
else
{
restartTimer.Enabled = false;
}
if (this.UpdateCheckMinutes > 0)
{
updateTimer.Interval = this.GetMilisecondsUntilUpdateCheck();
updateTimer.Enabled = true;
updateTimer.Start();
}
else
{
updateTimer.Enabled = false;
}
stopAttempts = 0;
this.process.StartInfo.FileName = serverpath;
this.process.StartInfo.Arguments = arguments;
this.process.Refresh();
this.needsRestart = false;
this.scheduledRestart = false;
this.needsUpdate = false;
this.automaticUpdate = false;
this.process.Start();
this.process.PriorityClass = this.ProcessPriority;
this.process.BeginOutputReadLine();
this.process.WaitForExit();
}
catch (Exception ex)
{
addToLog($"Error waiting for server process exit: {ex.Message}", LogEntryType.Error);
}
}).Start();
}
catch (Exception ex)