generated from Bims-sh/BattleBitApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
279 lines (239 loc) · 8.67 KB
/
Program.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
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using BattleBitAPI.Common;
using BattleBitAPI.Server;
using BattleBitMinigames.Api;
using BattleBitMinigames.Handlers;
using BattleBitMinigames.Helpers;
using log4net;
using log4net.Config;
using Microsoft.Extensions.Configuration;
namespace BattleBitMinigames;
internal class Program
{
public static ILog Logger { get; private set; } = null!;
public static BattleBitServer Server { get; private set; } = null!;
public static Configuration.ServerConfiguration ServerConfiguration { get; } = new();
private static void Main()
{
Program program = new();
program.StartApi();
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true,
AllowTrailingCommas = true
};
private void StartApi()
{
try
{
Logger = SetupLogger();
LoadConfiguration();
ValidateConfiguration();
StartServerListener();
}
catch (Exception ex)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (Logger == null)
{
Console.WriteLine("Failed to initialize logger" + Environment.NewLine + ex);
}
else
{
Logger.Error($"Initialization error: {Environment.NewLine}{ex}");
}
// kill it with fire and dip out of here if we failed to initialize
Environment.Exit(-1);
}
try
{
StartCommandHandler();
}
catch (Exception ex)
{
Logger.Error($"Command handler error: {Environment.NewLine}{ex}");
}
}
private static ILog SetupLogger()
{
const string log4NetConfig = "log4net.config";
if (!File.Exists(log4NetConfig))
{
File.WriteAllText(log4NetConfig, @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<log4net>
<root>
<level value=""INFO"" />
<appender-ref ref=""ManagedColoredConsoleAppender"" />
<appender-ref ref=""ManagedFileAppender"" />
</root>
<appender name=""ManagedColoredConsoleAppender"" type=""log4net.Appender.ManagedColoredConsoleAppender"">
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%date [%logger] %level - %message%newline"" />
</layout>
<mapping>
<level value=""WARN"" />
<foreColor value=""Yellow"" />
</mapping>
<mapping>
<level value=""ERROR"" />
<foreColor value=""Red"" />
</mapping>
</appender>
<appender name=""ManagedFileAppender"" type=""log4net.Appender.FileAppender"">
<file value=""logs\log.txt"" />
<appendToFile value=""true"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%date [%logger] %level - %message%newline"" />
</layout>
</appender>
</log4net>");
}
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
XmlConfigurator.Configure(new FileInfo(log4NetConfig));
}
catch (Exception ex)
{
Console.WriteLine("Failed to load log4net.config" + Environment.NewLine + ex);
throw;
}
try
{
return LogManager.GetLogger("API");
}
catch (Exception ex)
{
Console.WriteLine("Failed to initialize logger" + Environment.NewLine + ex);
throw;
}
}
private static void LoadConfiguration()
{
if (!File.Exists("appsettings.json"))
{
File.WriteAllText("appsettings.json", JsonSerializer.Serialize(ServerConfiguration, JsonOptions));
}
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build()
.Bind(ServerConfiguration);
}
public static void SaveConfiguration(Configuration.ServerConfiguration serverConfigurationToSave)
{
File.WriteAllText("appsettings.json", JsonSerializer.Serialize(serverConfigurationToSave, JsonOptions));
}
public static void ReloadConfiguration()
{
foreach (var map in Server.MapRotation.GetMapRotation())
{
Server.MapRotation.RemoveFromRotation(map);
}
foreach (var gamemode in Server.GamemodeRotation.GetGamemodeRotation())
{
Server.GamemodeRotation.RemoveFromRotation(gamemode);
}
if (!ServerConfiguration.MapRotation.Any())
{
ServerConfiguration.MapRotation.Add("AZAGOR");
SaveConfiguration(ServerConfiguration);
}
if (!ServerConfiguration.GamemodeRotation.Any())
{
ServerConfiguration.GamemodeRotation.Add("CONQ");
SaveConfiguration(ServerConfiguration);
}
foreach (var map in ServerConfiguration.MapRotation)
{
Server.MapRotation.AddToRotation(map);
}
foreach (var gamemode in ServerConfiguration.GamemodeRotation)
{
Server.GamemodeRotation.AddToRotation(gamemode);
}
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build()
.Bind(ServerConfiguration);
}
private static void ValidateConfiguration()
{
List<ValidationResult> validationResults = new();
IPAddress? ipAddress = null;
var isValid = Validator.TryValidateObject(ServerConfiguration, new ValidationContext(ServerConfiguration), validationResults, true)
&& IPAddress.TryParse(ServerConfiguration.IP, out ipAddress);
if (ServerConfiguration.Password == "")
{
Logger.Warn("No password set, server will be public.");
}
if (!isValid || ipAddress == null)
{
var errorMessages = validationResults.Select(x => x.ErrorMessage);
if (ipAddress == null)
{
errorMessages = errorMessages.Append($"Invalid IP address: {ServerConfiguration.IP}");
}
var errorString = $"Invalid configuration:{Environment.NewLine}{string.Join(Environment.NewLine, errorMessages)}";
throw new ValidationException(errorString);
}
Logger.Info("Configuration is valid.");
ServerConfiguration.IPAddress = ipAddress;
}
private void StartServerListener()
{
Logger.Info("Starting server listener...");
var listener = new ServerListener<BattleBitPlayer, BattleBitServer>();
listener.OnCreatingGameServerInstance += InitializeServer;
listener.OnGameServerDisconnected = OnGameServerDisconnected;
listener.OnGameServerConnected = OnGameServerConnected;
listener.LogLevel = ServerConfiguration.LogLevel;
listener.OnLog += OnLog;
listener.Start(ServerConfiguration.Port);
Logger.Info($"Started server listener on {ServerConfiguration.IPAddress}:{ServerConfiguration.Port}");
}
private static void OnLog(LogLevel level, string message, object? obj)
{
Logger.Info($"[{level}] {message}");
}
private static BattleBitServer InitializeServer(IPAddress ip, ushort port)
{
var server = new BattleBitServer();
Server = server;
return server;
}
private static void UnloadServer()
{
Server.Dispose();
Server = null!;
}
private static async Task OnGameServerDisconnected(GameServer<BattleBitPlayer> server)
{
Logger.Warn("Server disconnected. Unloading server...");
await Task.Delay(1000);
UnloadServer();
}
private static async Task OnGameServerConnected(GameServer<BattleBitPlayer> server)
{
Logger.Info("Server connected.");
Server = (BattleBitServer) server;
if (ServerConfiguration.Password != string.Empty)
Server.ExecuteCommand("setpass " + ServerConfiguration.Password);
if (ServerConfiguration.LaunchCustomGamemode != string.Empty && Server.RoundSettings.State != GameState.EndingGame)
{
CustomGamemodeHelper.SetCustomGameMode(ServerConfiguration.LaunchCustomGamemode, Server);
}
await Task.CompletedTask;
}
private static void StartCommandHandler()
{
ConsoleCommandHandler.Listen();
}
}