Move away from top level statements to keep everything under LANCommander namespace

This commit is contained in:
Pat Hartl 2023-09-14 17:44:16 -05:00
parent 485b6febbe
commit 006bfcb866

View file

@ -11,59 +11,65 @@ using System.Text;
using Hangfire; using Hangfire;
using NLog; using NLog;
Logger Logger = LogManager.GetCurrentClassLogger(); namespace LANCommander
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
// Add services to the container.
Logger.Debug("Loading settings");
var settings = SettingService.GetSettings(true);
Logger.Debug("Loaded!");
#region Validate Settings
Logger.Debug("Validating settings");
if (settings?.Authentication?.TokenSecret?.Length < 16)
{ {
internal class Program
{
static async Task Main(string[] args)
{
Logger Logger = LogManager.GetCurrentClassLogger();
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
// Add services to the container.
Logger.Debug("Loading settings");
var settings = SettingService.GetSettings(true);
Logger.Debug("Loaded!");
#region Validate Settings
Logger.Debug("Validating settings");
if (settings?.Authentication?.TokenSecret?.Length < 16)
{
Logger.Debug("JWT token secret is too short. Regenerating..."); Logger.Debug("JWT token secret is too short. Regenerating...");
settings.Authentication.TokenSecret = Guid.NewGuid().ToString(); settings.Authentication.TokenSecret = Guid.NewGuid().ToString();
SettingService.SaveSettings(settings); SettingService.SaveSettings(settings);
} }
Logger.Debug("Done validating settings"); Logger.Debug("Done validating settings");
#endregion #endregion
Logger.Debug("Configuring MVC and Blazor"); Logger.Debug("Configuring MVC and Blazor");
builder.Services.AddMvc(options => options.EnableEndpointRouting = false); builder.Services.AddMvc(options => options.EnableEndpointRouting = false);
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor().AddCircuitOptions(option => builder.Services.AddServerSideBlazor().AddCircuitOptions(option =>
{ {
option.DetailedErrors = true; option.DetailedErrors = true;
}).AddHubOptions(option => }).AddHubOptions(option =>
{ {
option.MaximumReceiveMessageSize = 1024 * 1024 * 11; option.MaximumReceiveMessageSize = 1024 * 1024 * 11;
option.DisableImplicitFromServicesParameters = true; option.DisableImplicitFromServicesParameters = true;
}); });
Logger.Debug("Starting web server on port {Port}", settings.Port); Logger.Debug("Starting web server on port {Port}", settings.Port);
builder.WebHost.ConfigureKestrel(options => builder.WebHost.ConfigureKestrel(options =>
{ {
// Configure as HTTP only // Configure as HTTP only
options.ListenAnyIP(settings.Port); options.ListenAnyIP(settings.Port);
}); });
Logger.Debug("Initializing DatabaseContext with connection string {ConnectionString}", settings.DatabaseConnectionString); Logger.Debug("Initializing DatabaseContext with connection string {ConnectionString}", settings.DatabaseConnectionString);
builder.Services.AddDbContext<LANCommander.Data.DatabaseContext>(b => builder.Services.AddDbContext<LANCommander.Data.DatabaseContext>(b =>
{ {
b.UseLazyLoadingProxies(); b.UseLazyLoadingProxies();
b.UseSqlite(settings.DatabaseConnectionString); b.UseSqlite(settings.DatabaseConnectionString);
}); });
builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDatabaseDeveloperPageExceptionFilter();
Logger.Debug("Initializing Identity"); Logger.Debug("Initializing Identity");
builder.Services.AddDefaultIdentity<User>((IdentityOptions options) => builder.Services.AddDefaultIdentity<User>((IdentityOptions options) =>
{ {
options.SignIn.RequireConfirmedAccount = false; options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false; options.SignIn.RequireConfirmedEmail = false;
@ -72,17 +78,17 @@ builder.Services.AddDefaultIdentity<User>((IdentityOptions options) =>
options.Password.RequireUppercase = settings.Authentication.PasswordRequireUppercase; options.Password.RequireUppercase = settings.Authentication.PasswordRequireUppercase;
options.Password.RequireDigit = settings.Authentication.PasswordRequireDigit; options.Password.RequireDigit = settings.Authentication.PasswordRequireDigit;
options.Password.RequiredLength = settings.Authentication.PasswordRequiredLength; options.Password.RequiredLength = settings.Authentication.PasswordRequiredLength;
}) })
.AddRoles<Role>() .AddRoles<Role>()
.AddEntityFrameworkStores<LANCommander.Data.DatabaseContext>() .AddEntityFrameworkStores<LANCommander.Data.DatabaseContext>()
.AddDefaultTokenProviders(); .AddDefaultTokenProviders();
builder.Services.AddAuthentication(options => builder.Services.AddAuthentication(options =>
{ {
/*options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; /*options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;*/ options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;*/
}) })
.AddJwtBearer(options => .AddJwtBearer(options =>
{ {
options.SaveToken = true; options.SaveToken = true;
@ -97,129 +103,129 @@ builder.Services.AddAuthentication(options =>
}; };
}); });
Logger.Debug("Initializing Controllers"); Logger.Debug("Initializing Controllers");
builder.Services.AddControllers().AddJsonOptions(x => builder.Services.AddControllers().AddJsonOptions(x =>
{ {
x.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles; x.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
}); });
Logger.Debug("Initializing Hangfire"); Logger.Debug("Initializing Hangfire");
builder.Services.AddHangfire(configuration => builder.Services.AddHangfire(configuration =>
configuration configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer() .UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings() .UseRecommendedSerializerSettings()
.UseInMemoryStorage()); .UseInMemoryStorage());
builder.Services.AddHangfireServer(); builder.Services.AddHangfireServer();
Logger.Debug("Registering Swashbuckle"); Logger.Debug("Registering Swashbuckle");
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
Logger.Debug("Registering AntDesign Blazor"); Logger.Debug("Registering AntDesign Blazor");
builder.Services.AddAntDesign(); builder.Services.AddAntDesign();
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
Logger.Debug("Registering Services"); Logger.Debug("Registering Services");
builder.Services.AddScoped<SettingService>(); builder.Services.AddScoped<SettingService>();
builder.Services.AddScoped<ArchiveService>(); builder.Services.AddScoped<ArchiveService>();
builder.Services.AddScoped<CategoryService>(); builder.Services.AddScoped<CategoryService>();
builder.Services.AddScoped<GameService>(); builder.Services.AddScoped<GameService>();
builder.Services.AddScoped<ScriptService>(); builder.Services.AddScoped<ScriptService>();
builder.Services.AddScoped<GenreService>(); builder.Services.AddScoped<GenreService>();
builder.Services.AddScoped<KeyService>(); builder.Services.AddScoped<KeyService>();
builder.Services.AddScoped<TagService>(); builder.Services.AddScoped<TagService>();
builder.Services.AddScoped<CompanyService>(); builder.Services.AddScoped<CompanyService>();
builder.Services.AddScoped<IGDBService>(); builder.Services.AddScoped<IGDBService>();
builder.Services.AddScoped<ServerService>(); builder.Services.AddScoped<ServerService>();
builder.Services.AddScoped<ServerConsoleService>(); builder.Services.AddScoped<ServerConsoleService>();
builder.Services.AddScoped<GameSaveService>(); builder.Services.AddScoped<GameSaveService>();
builder.Services.AddSingleton<ServerProcessService>(); builder.Services.AddSingleton<ServerProcessService>();
builder.Services.AddSingleton<IPXRelayService>(); builder.Services.AddSingleton<IPXRelayService>();
if (settings.Beacon) if (settings.Beacon)
{ {
Logger.Debug("The beacons have been lit! LANCommander calls for players!"); Logger.Debug("The beacons have been lit! LANCommander calls for players!");
builder.Services.AddHostedService<BeaconService>(); builder.Services.AddHostedService<BeaconService>();
} }
builder.WebHost.UseStaticWebAssets(); builder.WebHost.UseStaticWebAssets();
builder.WebHost.UseKestrel(options => builder.WebHost.UseKestrel(options =>
{ {
options.Limits.MaxRequestBodySize = 1024 * 1024 * 150; options.Limits.MaxRequestBodySize = 1024 * 1024 * 150;
}); });
builder.Host.UseNLog(); builder.Host.UseNLog();
Logger.Debug("Building Application"); Logger.Debug("Building Application");
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {
Logger.Debug("App has been run in a development environment"); Logger.Debug("App has been run in a development environment");
app.UseMigrationsEndPoint(); app.UseMigrationsEndPoint();
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(); app.UseSwaggerUI();
} }
else else
{ {
app.UseExceptionHandler("/Home/Error"); app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts(); app.UseHsts();
} }
app.UseHangfireDashboard(); app.UseHangfireDashboard();
// app.UseHttpsRedirection(); // app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseMvcWithDefaultRoute(); app.UseMvcWithDefaultRoute();
app.MapHub<GameServerHub>("/hubs/gameserver"); app.MapHub<GameServerHub>("/hubs/gameserver");
Logger.Debug("Registering Endpoints"); Logger.Debug("Registering Endpoints");
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapBlazorHub(); endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host"); endpoints.MapFallbackToPage("/_Host");
endpoints.MapControllers(); endpoints.MapControllers();
}); });
Logger.Debug("Ensuring required directories exist"); Logger.Debug("Ensuring required directories exist");
if (!Directory.Exists(settings.Archives.StoragePath)) if (!Directory.Exists(settings.Archives.StoragePath))
Directory.CreateDirectory(settings.Archives.StoragePath); Directory.CreateDirectory(settings.Archives.StoragePath);
if (!Directory.Exists("Icon")) if (!Directory.Exists("Icon"))
Directory.CreateDirectory("Icon"); Directory.CreateDirectory("Icon");
if (!Directory.Exists(settings.UserSaves.StoragePath)) if (!Directory.Exists(settings.UserSaves.StoragePath))
Directory.CreateDirectory(settings.UserSaves.StoragePath); Directory.CreateDirectory(settings.UserSaves.StoragePath);
if (!Directory.Exists("Snippets")) if (!Directory.Exists("Snippets"))
Directory.CreateDirectory("Snippets"); Directory.CreateDirectory("Snippets");
// Migrate // Migrate
Logger.Debug("Migrating database if required"); Logger.Debug("Migrating database if required");
await using var scope = app.Services.CreateAsyncScope(); await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DatabaseContext>(); using var db = scope.ServiceProvider.GetService<DatabaseContext>();
await db.Database.MigrateAsync(); await db.Database.MigrateAsync();
// Autostart any server processes // Autostart any server processes
Logger.Debug("Autostarting Servers"); Logger.Debug("Autostarting Servers");
var serverService = scope.ServiceProvider.GetService<ServerService>(); var serverService = scope.ServiceProvider.GetService<ServerService>();
var serverProcessService = scope.ServiceProvider.GetService<ServerProcessService>(); var serverProcessService = scope.ServiceProvider.GetService<ServerProcessService>();
foreach (var server in await serverService.Get(s => s.Autostart).ToListAsync()) foreach (var server in await serverService.Get(s => s.Autostart).ToListAsync())
{ {
try try
{ {
Logger.Debug("Autostarting server {ServerName} with a delay of {AutostartDelay} seconds", server.Name, server.AutostartDelay); Logger.Debug("Autostarting server {ServerName} with a delay of {AutostartDelay} seconds", server.Name, server.AutostartDelay);
@ -233,6 +239,10 @@ foreach (var server in await serverService.Get(s => s.Autostart).ToListAsync())
{ {
Logger.Debug(ex, "An unexpected error occurred while trying to autostart the server {ServerName}", server.Name); Logger.Debug(ex, "An unexpected error occurred while trying to autostart the server {ServerName}", server.Name);
} }
}
app.Run();
}
}
} }
app.Run();