forked from LittleBigRefresh/Refresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRefreshGameServer.cs
More file actions
376 lines (309 loc) · 13.2 KB
/
Copy pathRefreshGameServer.cs
File metadata and controls
376 lines (309 loc) · 13.2 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
using System.Diagnostics.CodeAnalysis;
using Bunkum.AutoDiscover.Extensions;
using Bunkum.Core;
using Bunkum.Core.Authentication;
using Bunkum.Core.Configuration;
using Bunkum.Core.RateLimit;
using Bunkum.Core.Services;
using Bunkum.Core.Storage;
using Bunkum.HealthChecks;
using Bunkum.Protocols.Http;
using Refresh.Common;
using Refresh.Common.Time;
using Refresh.Common.Verification;
using Refresh.Core.Configuration;
using Refresh.Core.Extensions;
using Refresh.Core.Importing;
using Refresh.Core.Metrics;
using Refresh.Core.Services;
using Refresh.Core.Storage;
using Refresh.Core.Types.Categories;
using Refresh.Core.Types.Data;
using Refresh.GameServer.Authentication;
using Refresh.Database.Models.Authentication;
using Refresh.Database;
using Refresh.GameServer.Middlewares;
using Refresh.Database.Models.Users;
using Refresh.Database.Models.Levels;
using Refresh.Interfaces.APIv3;
using Refresh.Interfaces.APIv3.Documentation;
using Refresh.Interfaces.Game;
using Refresh.Interfaces.Internal;
using Refresh.Interfaces.Workers;
using Refresh.Interfaces.Workers.Repeating;
using Refresh.Workers;
using Refresh.Database.Models.Assets;
namespace Refresh.GameServer;
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class RefreshGameServer : RefreshServer
{
protected WorkerManager? WorkerManager;
protected readonly GameDatabaseProvider _databaseProvider;
protected readonly IDataStore _dataStore;
protected readonly ConfigStore _configStore;
public RefreshGameServer(
BunkumHttpListener? listener = null,
Func<GameDatabaseProvider>? databaseProvider = null,
IAuthenticationProvider<Token>? authProvider = null,
IDataStore? dataStore = null
) : base(listener)
{
dataStore ??= new FileSystemDataStore();
List<IDataStore> dataStores = [];
try
{
// ReSharper disable once VirtualMemberCallInConstructor (you can't stop me)
this._configStore = this.CreateConfigStore();
}
catch (Exception ex)
{
this.Logger.LogCritical(RefreshContext.Database, "Failed to read the configuration files: " + ex);
this.Logger.Dispose();
Environment.Exit(1);
}
if (this._configStore.DryArchive.Enabled)
dataStores.Add(new DownloadingDataStore(dataStore, new DryDataStore(this._configStore.DryArchive)));
databaseProvider ??= () => new GameDatabaseProvider(this.Logger, this._configStore.Database);
this._databaseProvider = databaseProvider.Invoke();
this._databaseProvider.Initialize();
// Uncomment if you want to use production refresh as a source for assets
// TODO: remove config option when test.lbpbonsai.com instance no longer needs prod assets
#if DEBUG
if (this._configStore.DryArchive?.TemporaryWillBeRemoved_UseProductionRefreshData ?? false)
dataStores.Add(new DownloadingDataStore(dataStore, new RemoteRefreshDataStore()));
#endif
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (dataStores.Count > 0)
this._dataStore = new AggregateDataStore(dataStore, dataStores.ToArray());
else
this._dataStore = dataStore;
this.SetupInitializer(() =>
{
GameDatabaseProvider provider = databaseProvider.Invoke();
this.WorkerManager?.Stop();
authProvider ??= new GameAuthenticationProvider(this._configStore.GameServer, this.Logger);
this.InjectBaseServices(provider, authProvider, this._dataStore);
});
}
protected virtual ConfigStore CreateConfigStore()
{
return new ConfigStore(this.Logger);
}
private void InjectBaseServices(GameDatabaseProvider databaseProvider, IAuthenticationProvider<Token> authProvider, IDataStore dataStore)
{
this.Server.UseDatabaseProvider(databaseProvider);
this.Server.AddService(new GameAuthenticationService(this.Server.Logger, authProvider));
this.Server.AddStorageService(dataStore);
}
protected override void Initialize()
{
base.Initialize();
this.Server.DiscoverEndpointsFromAssembly(typeof(ApiV3EndpointAttribute).Assembly);
this.Server.DiscoverEndpointsFromAssembly(typeof(GameEndpointAttribute).Assembly);
this.Server.DiscoverEndpointsFromAssembly(typeof(PresenceEndpointAttribute).Assembly);
this.SetupWorkers();
}
protected override void SetupMiddlewares()
{
this.Server.AddMiddleware<WebsiteMiddleware>();
this.Server.AddMiddleware(new DeflateMiddleware(this._configStore.GameServer));
this.Server.AddMiddleware<LegacyAdapterMiddleware>();
// Digest middleware must be run before LegacyAdapterMiddleware, because digest is based on the raw route, not the fixed route
this.Server.AddMiddleware(new DigestMiddleware(this._configStore.GameServer));
this.Server.AddMiddleware<CrossOriginMiddleware>();
this.Server.AddMiddleware<PspVersionMiddleware>();
this.Server.AddMiddleware(new PresenceAuthenticationMiddleware(this._configStore.Integration!));
this.Server.AddMiddleware<RequestStatisticTrackingMiddleware>();
}
protected override void SetupConfiguration()
{
this._configStore.AddToBunkum(this.Server);
}
protected override void SetupServices()
{
this.Server.AddService<TimeProviderService>(this.GetTimeProvider());
this.Server.AddService<GameRateLimitService>(new RateLimiter(new RateLimitSettings(90, 380, 45, "global")));
this.Server.AddService<CategoryService>();
this.Server.AddService(new MatchService(this.Server.Logger, this._configStore.GameServer));
this.Server.AddService<ImportService>();
this.Server.AddService<DocumentationService>();
this.Server.AddService(new GuidCheckerService(this._configStore.GameServer, this.Server.Logger));
this.Server.AddAutoDiscover(serverBrand: $"{this._configStore.GameServer.InstanceName} (Refresh)",
baseEndpoint: GameEndpointAttribute.BaseRoute[..^1],
usesCustomDigestKey: true,
serverDescription: this._configStore.GameServer.InstanceDescription,
bannerImageUrl: "https://github.com/LittleBigRefresh/Branding/blob/main/logos/refresh_type.png?raw=true");
#pragma warning disable CA1825
#pragma warning disable CA1861
this.Server.AddHealthCheckService(this._databaseProvider, [
// TODO: add postgres health check
]);
#pragma warning restore CA1861
#pragma warning restore CA1825
this.Server.AddService<RoleService>();
this.Server.AddService<SmtpService>();
this.Server.AddService<PresenceService>();
this.Server.AddService<PlayNowService>();
this.Server.AddService<CommandService>();
this.Server.AddService<ChallengeGhostRateLimitService>();
this.Server.AddService<DiscordStaffService>();
this.Server.AddService<CacheService>();
if(this._configStore.Integration!.AipiEnabled)
this.Server.AddService<AipiService>();
#if DEBUG
this.Server.AddService<DebugService>();
#endif
// !!! HEY! !!!
// This service depends on most services that come before it.
// This should always be added last.
this.Server.AddService<DataContextService>();
}
protected virtual void SetupWorkers()
{
this.WorkerManager = RefreshWorkerManager.Create(this.Logger, this._dataStore, this._databaseProvider);
if (this._configStore.Integration.DiscordWebhookEnabled && this._configStore.GameServer.PermitShowingOnlineUsers)
{
this.WorkerManager.AddJob(new DiscordIntegrationJob(this._configStore.Integration, this._configStore.GameServer));
}
}
/// <inheritdoc/>
public override void Start()
{
this.Server.Start();
this.WorkerManager?.Start();
if (this._configStore.GameServer.MaintenanceMode)
{
this.Logger.LogWarning(RefreshContext.Startup, "The server is currently in maintenance mode! " +
"Only administrators will be able to log in and interact with the server.");
}
}
/// <inheritdoc/>
public override void Stop()
{
this.Server.Stop();
this.WorkerManager?.Stop();
}
internal GameDatabaseContext GetContext()
{
return this._databaseProvider.GetContext();
}
protected virtual IDateTimeProvider GetTimeProvider()
{
return new SystemDateTimeProvider();
}
public void ImportAssets(bool force = false)
{
AssetImporter importer = new();
importer.ImportFromDataStore(this._databaseProvider, this._dataStore);
}
public void ImportImages()
{
using GameDatabaseContext context = this.GetContext();
ImageImporter importer = new();
importer.ImportFromDataStore(context, this._dataStore);
}
public void FlagModdedLevels()
{
using GameDatabaseContext context = this.GetContext();
// Iterate over all levels
GameLevel[] allLevels = context.GetAllUserLevels().ToArray();
Dictionary<GameLevel, bool> statuses = new(allLevels.Length);
int i = 0;
foreach (GameLevel level in allLevels)
{
bool modded = context.GetLevelModdedStatus(level);
statuses[level] = modded;
i++;
this.Logger.LogInfo(RefreshContext.Worker, "[{3}/{4}] Marked level {0} ({1}) as {2}", level.Title, level.LevelId, modded ? "modded" : "vanilla", i, allLevels.Length);
}
context.SetLevelModdedStatuses(statuses);
}
public void CreateUser(string username, string emailAddress)
{
using GameDatabaseContext context = this.GetContext();
GameUser user = context.CreateUser(username, emailAddress);
context.VerifyUserEmail(user);
}
public void SetUserAsRole(GameUser user, GameUserRole role)
{
using GameDatabaseContext context = this.GetContext();
context.SetUserRole(user, role);
}
public bool DisallowUser(string username)
{
using GameDatabaseContext context = this.GetContext();
return context.DisallowUser(username);
}
public bool ReallowUser(string username)
{
using GameDatabaseContext context = this.GetContext();
return context.ReallowUser(username);
}
public bool DisallowEmailAddress(string address)
{
using GameDatabaseContext context = this.GetContext();
return context.DisallowEmailAddress(address);
}
public bool ReallowEmailAddress(string address)
{
using GameDatabaseContext context = this.GetContext();
return context.ReallowEmailAddress(address);
}
public bool DisallowEmailDomain(string domain)
{
using GameDatabaseContext context = this.GetContext();
return context.DisallowEmailDomain(domain);
}
public bool ReallowEmailDomain(string domain)
{
using GameDatabaseContext context = this.GetContext();
return context.ReallowEmailDomain(domain);
}
public bool DisallowAsset(string hash, GameAssetType? type, string? reason)
{
using GameDatabaseContext context = this.GetContext();
type ??= context.GetAssetFromHash(hash)?.AssetType;
(DisallowedAsset disallowed, bool success) = context.DisallowAsset(hash, type ?? GameAssetType.Unknown, reason ?? "");
return success;
}
public bool ReallowAsset(string hash)
{
using GameDatabaseContext context = this.GetContext();
return context.ReallowAsset(hash);
}
public void RenameUser(GameUser user, string newUsername, bool force = false)
{
using GameDatabaseContext context = this.GetContext();
context.RenameUser(user, newUsername, force);
}
public void DeleteUser(GameUser user)
{
using GameDatabaseContext context = this.GetContext();
context.DeleteUser(user);
}
public void FullyDeleteUser(GameUser user)
{
using GameDatabaseContext context = this.GetContext();
context.FullyDeleteUser(user);
}
public void MarkAllReuploads(GameUser user)
{
using GameDatabaseContext context = this.GetContext();
context.MarkAllReuploads(user);
}
public string AskUserForVerification(GameUser user)
{
using GameDatabaseContext context = this.GetContext();
string code = CodeHelper.GenerateDigitCode();
string text = $"An admin is requesting a code to verify that you currently have access to your account. " +
$"Please share the code '{code}' with the admin you're currently speaking with. " +
"If you're not in contact with any such staff member, please report this immediately.";
context.AddNotification("Admin Verification Request (Action Required)", text, user, "shield");
return code;
}
public override void Dispose()
{
this._databaseProvider.Dispose();
base.Dispose();
}
}