LANCommander/LANCommander.Launcher/Program.cs

267 lines
9.3 KiB
C#
Raw Normal View History

using CommandLine;
using CommandLine.Text;
using Emzi0767.NtfsDataStreams;
using LANCommander.Launcher.Data;
using LANCommander.Launcher.Models;
using LANCommander.Launcher.Services;
using LANCommander.Launcher.Services.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
2024-06-12 23:20:31 -05:00
using Microsoft.Extensions.Logging;
using NLog;
2024-07-16 00:18:41 -05:00
using NLog.Config;
2024-06-12 23:20:31 -05:00
using NLog.Extensions.Logging;
2024-07-16 00:18:41 -05:00
using NLog.Targets;
using Photino.Blazor;
using Photino.Blazor.CustomWindow.Extensions;
using Photino.NET;
using System.Diagnostics;
using System.IO;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
namespace LANCommander.Launcher
{
class Program
{
static Logger Logger = LogManager.GetCurrentClassLogger();
[STAThread]
2024-08-07 01:20:31 -05:00
static void Main(string[] args)
{
Logger?.Debug("Starting up launcher...");
Logger?.Debug("Loading settings from file");
var settings = SettingService.GetSettings();
var builder = PhotinoBlazorAppBuilder.CreateDefault(args);
2024-07-16 00:18:41 -05:00
#region Configure Logging
Logger?.Debug("Configuring logging...");
2024-06-12 23:20:31 -05:00
builder.Services.AddLogging(loggingBuilder =>
{
2024-07-16 00:18:41 -05:00
var loggerConfig = new LoggingConfiguration();
NLog.GlobalDiagnosticsContext.Set("StoragePath", settings.Debug.LoggingPath);
NLog.GlobalDiagnosticsContext.Set("ArchiveEvery", settings.Debug.LoggingArchivePeriod);
NLog.GlobalDiagnosticsContext.Set("MaxArchiveFiles", settings.Debug.MaxArchiveFiles);
NLog.GlobalDiagnosticsContext.Set("LoggingLevel", settings.Debug.LoggingLevel);
2024-06-12 23:20:31 -05:00
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(settings.Debug.LoggingLevel);
loggingBuilder.AddNLog();
});
2024-07-16 00:18:41 -05:00
#endregion
2024-06-12 23:20:31 -05:00
builder.RootComponents.Add<App>("app");
Logger?.Debug("Registering services...");
builder.Services.AddCustomWindow();
builder.Services.AddAntDesign();
builder.Services.AddLANCommander();
#region Build Application
Logger?.Debug("Building application...");
2024-05-21 20:51:09 -05:00
var app = builder.Build();
app.MainWindow
.SetTitle("LANCommander")
.SetUseOsDefaultLocation(true)
.SetChromeless(true)
.SetResizable(true)
.RegisterCustomSchemeHandler("media", (object sender, string scheme, string url, out string contentType) =>
{
var uri = new Uri(url);
var query = HttpUtility.ParseQueryString(uri.Query);
var filePath = Path.Combine(MediaService.GetStoragePath(), uri.Host);
contentType = query["mime"];
if (File.Exists(filePath))
return new FileStream(filePath, FileMode.Open, FileAccess.Read);
else
return null;
})
.RegisterWebMessageReceivedHandler(async (object sender, string message) =>
{
switch (message)
{
case "import":
using (var scope = app.Services.CreateScope())
{
var importService = scope.ServiceProvider.GetService<ImportService>();
var window = (PhotinoWindow)sender;
await importService.ImportAsync();
window.SendWebMessage("importComplete");
}
break;
}
});
#endregion
AppDomain.CurrentDomain.UnhandledException += (sender, error) =>
{
app.MainWindow.ShowMessage("Fatal exception", error.ExceptionObject.ToString());
};
#region Scaffold Required Directories
try
2024-05-31 23:49:45 -05:00
{
Logger?.Debug("Scaffolding required directories...");
2024-05-31 23:49:45 -05:00
string[] requiredDirectories = new string[]
{
settings.Debug.LoggingPath,
settings.Media.StoragePath,
settings.Games.DefaultInstallDirectory,
settings.Database.BackupsPath,
settings.Updates.StoragePath
};
foreach (var directory in requiredDirectories)
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, directory);
2024-05-31 23:49:45 -05:00
if (!Directory.Exists(path))
{
Logger?.Debug("Creating path {Path}", path);
Directory.CreateDirectory(path);
}
}
}
catch (Exception ex)
{
Logger?.Error(ex, "Could not scaffold required directories");
2024-05-31 23:49:45 -05:00
}
#endregion
2024-05-31 23:49:45 -05:00
#region Migrate Database
2024-05-21 20:51:09 -05:00
using var scope = app.Services.CreateScope();
using var db = scope.ServiceProvider.GetService<DatabaseContext>();
if (db.Database.GetPendingMigrations().Any())
{
Logger?.Debug("Migrations are pending!");
2024-05-23 19:14:51 -05:00
var backupPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backups");
var dataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LANCommander.db");
var backupName = Path.Combine(backupPath, $"LANCommander.db.{DateTime.Now.ToString("dd-MM-yyyy-HH.mm.ss.bak")}");
2024-05-21 20:51:09 -05:00
if (File.Exists(dataSource))
{
Logger?.Debug("Database already exists, backing up as {BackupName}", backupName);
2024-05-21 20:51:09 -05:00
File.Copy(dataSource, backupName);
}
Logger?.Debug("Migrating database...");
2024-05-21 20:51:09 -05:00
db.Database.Migrate();
}
#endregion
2024-05-21 20:51:09 -05:00
if (settings.LaunchCount == 0)
{
2024-07-31 21:51:43 -05:00
var workingDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
Logger?.Debug("Current working directory is {WorkingDirectory}", workingDirectory);
2024-07-30 01:09:58 -05:00
#region Fix Zone Identifier
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
Logger?.Debug("Attempting to fix security zone identifier all files...");
var files = Directory.GetFiles(workingDirectory, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
try
{
var fileInfo = new FileInfo(file);
fileInfo.GetDataStream("Zone.Identifier")?.Delete();
}
catch (Exception ex)
{
Logger?.Error(ex, "Could not fix zone identifier");
}
}
}
catch (Exception ex)
{
Logger?.Error(ex, "Could not get files to fix zone identifier");
}
}
#endregion
2024-07-29 00:46:01 -05:00
#region Rename Autoupdater
2024-07-30 01:09:58 -05:00
var updaterPath = Path.Combine(workingDirectory, "LANCommander.AutoUpdater.exe");
try
2024-07-29 00:46:01 -05:00
{
2024-07-30 01:09:58 -05:00
if (File.Exists($"{updaterPath}.Update"))
{
if (File.Exists(updaterPath))
File.Delete(updaterPath);
2024-07-29 00:46:01 -05:00
2024-07-30 01:09:58 -05:00
File.Move($"{updaterPath}.Update", updaterPath);
}
}
catch (Exception ex)
{
Logger?.Error(ex, "Could not rename updater");
2024-07-29 00:46:01 -05:00
}
2024-07-30 01:09:58 -05:00
updaterPath = Path.Combine(workingDirectory, "LANCommander.AutoUpdater");
try
2024-07-29 00:46:01 -05:00
{
2024-07-30 01:09:58 -05:00
if (File.Exists($"{updaterPath}.Update"))
{
if (File.Exists(updaterPath))
File.Delete(updaterPath);
2024-07-29 00:46:01 -05:00
2024-07-30 01:09:58 -05:00
File.Move($"{updaterPath}.Update", updaterPath);
}
}
catch (Exception ex)
{
Logger?.Error(ex, "Could not rename updater");
2024-07-29 00:46:01 -05:00
}
#endregion
}
if (args.Length > 0)
{
2024-08-07 19:03:07 -05:00
var commandLineService = scope.ServiceProvider.GetService<CommandLineService>();
Task.Run(async () => await commandLineService.ParseCommandLineAsync(args)).GetAwaiter().GetResult();
return;
}
else
{
settings.LaunchCount++;
SettingService.SaveSettings(settings);
Logger?.Debug("Starting application...");
app.Run();
Logger?.Debug("Closing application...");
}
}
}
}