From d875377f15848dd4fc31dbef337681f602d353f4 Mon Sep 17 00:00:00 2001 From: Pat Hartl Date: Wed, 24 Sep 2025 20:58:23 -0500 Subject: [PATCH] Rename SDK services -> clients, implement new configuration, use dependency injection for clients --- .../AuthenticationService.cs | 77 ++--- .../CollectionService.cs | 7 +- .../CommandLineService.cs | 105 +++---- .../CompanyService.cs | 12 +- .../DepotService.cs | 7 +- .../EngineService.cs | 2 +- .../Extensions/IServiceProviderExtensions.cs | 2 - .../Extensions/ServiceCollectionExtensions.cs | 6 +- .../FilterService.cs | 28 +- LANCommander.Launcher.Services/GameService.cs | 54 ++-- .../GenreService.cs | 7 +- .../ImportManagerService.cs | 9 - .../ImportService.cs | 169 +++++------ .../InstallService.cs | 13 +- .../KeepAliveService.cs | 7 +- .../LibraryService.cs | 17 +- .../MediaService.cs | 16 +- .../MessageBusService.cs | 10 +- .../MultiplayerModeService.cs | 12 +- .../PlatformService.cs | 12 +- .../PlaySessionService.cs | 23 +- .../ProfileService.cs | 13 +- .../RedistributableService.cs | 12 +- LANCommander.Launcher.Services/SaveService.cs | 26 +- LANCommander.Launcher.Services/TagService.cs | 12 +- .../UpdateService.cs | 15 +- LANCommander.Launcher.Services/UserService.cs | 17 +- .../_BaseDatabaseService.cs | 2 +- .../_BaseService.cs | 4 +- LANCommander.Launcher/Program.cs | 2 + .../Startup/ApplicationSettings.cs | 13 +- LANCommander.Launcher/Startup/Window.cs | 43 ++- .../Components/AuthenticationFormState.cs | 2 +- .../Authenticate/Components/LoginForm.razor | 15 +- .../Components/RegistrationForm.razor | 29 +- .../Components/ServerSelector.razor | 13 +- .../UI/ChatWindowLayout.razor | 108 +++++++ .../UI/ChatWindowLayout.razor.css | 77 +++++ .../UI/Components/AuthenticationForm.razor | 8 +- .../AuthenticationProviderDialog.razor | 9 +- .../UI/Components/Footer.razor | 15 +- .../Components/LibraryItemContextMenu.razor | 2 +- .../UI/Components/ProfileButton.razor | 4 +- .../Depot/Components/DepotGameDetails.razor | 2 +- LANCommander.Launcher/UI/MainLayout.razor | 8 +- LANCommander.Launcher/UI/Settings/Index.razor | 2 +- LANCommander.Launcher/wwwroot/css/main.js | 0 LANCommander.SDK.Tests/SaveService.cs | 4 +- LANCommander.SDK/Client.cs | 43 +++ .../IConfigurationBuilderExtensions.cs | 54 ++++ .../IServiceCollectionExtensions.cs | 38 ++- .../ProcessExecutionContextFactory.cs | 2 +- LANCommander.SDK/Helpers/ApiRequestBuilder.cs | 7 - LANCommander.SDK/Helpers/ManifestHelper.cs | 2 +- LANCommander.SDK/LANCommander.SDK.csproj | 6 +- LANCommander.SDK/Models/Settings.cs | 13 - .../Models/Settings/AuthenticationSettings.cs | 10 + .../Models/Settings/DebugSettings.cs | 13 + .../Models/Settings/GameSettings.cs | 6 + .../Settings/IAuthenticationSettings.cs | 10 + .../Models/Settings/IDebugSettings.cs | 13 + .../Models/Settings/IGameSettings.cs | 6 + .../Models/Settings/IIPXRelaySettings.cs | 7 + .../Models/Settings/ILibrarySettings.cs | 6 + .../Models/Settings/IMediaSettings.cs | 6 + .../Models/Settings/IPXRelaySettings.cs | 7 + LANCommander.SDK/Models/Settings/ISettings.cs | 10 + .../Models/Settings/IUpdateSettings.cs | 6 + .../Models/Settings/LibrarySettings.cs | 6 + .../Models/Settings/MediaSettings.cs | 6 + LANCommander.SDK/Models/Settings/Settings.cs | 13 + .../Models/Settings/UpdateSettings.cs | 6 + .../PowerShell/Cmdlets/Get-UserCustomField.cs | 4 +- .../PowerShell/Cmdlets/Out-PlayerAvatar.cs | 4 +- .../Cmdlets/Update-UserCustomField.cs | 4 +- LANCommander.SDK/ProcessExecutionContext.cs | 4 +- .../Providers/AuthenticationProvider.cs | 13 + .../Providers/ServerConfigurationProvider.cs | 89 ++++++ .../Providers/SettingsProvider.cs | 20 ++ LANCommander.SDK/Rpc/Chat.cs | 12 +- .../Rpc/Interfaces/Client/_IRpcClient.cs | 1 - LANCommander.SDK/Rpc/RpcClient.cs | 4 +- ...tionService.cs => AuthenticationClient.cs} | 43 ++- .../{BeaconService.cs => BeaconClient.cs} | 6 +- .../{ChatService.cs => ChatClient.cs} | 12 +- ...nnectionService.cs => ConnectionClient.cs} | 8 +- .../{DepotService.cs => DepotClient.cs} | 4 +- .../{GameService.cs => GameClient.cs} | 80 ++--- .../{IArchiveService.cs => IArchiveClient.cs} | 2 +- ...nectionService.cs => IConnectionClient.cs} | 4 +- .../{IssueService.cs => IssueClient.cs} | 2 +- .../{LauncherService.cs => LauncherClient.cs} | 4 +- .../{LibraryService.cs => LibraryClient.cs} | 2 +- .../{LobbyService.cs => LobbyClient.cs} | 2 +- LANCommander.SDK/Services/MediaService.cs | 6 +- ...SessionService.cs => PlaySessionClient.cs} | 2 +- .../{ProfileService.cs => ProfileClient.cs} | 2 +- ...bleService.cs => RedistributableClient.cs} | 16 +- .../{SaveService.cs => SaveClient.cs} | 4 +- .../{ScriptService.cs => ScriptClient.cs} | 54 ++-- .../{ServerService.cs => ServerClient.cs} | 2 +- .../Services/{TagService.cs => TagClient.cs} | 2 +- LANCommander.SDK/VersionInterceptor.cs | 61 ---- .../Exporters/ArchiveExporter.cs | 10 +- .../Importers/ArchiveImporter.cs | 20 +- .../{ArchiveService.cs => ArchiveClient.cs} | 6 +- .../AuthenticationService.cs | 17 +- .../IServiceCollectionExtensions.cs | 3 +- LANCommander.Server.Services/GameService.cs | 18 +- LANCommander.Server.Services/MediaService.cs | 2 +- .../RedistributableService.cs | 2 +- .../ServerEngines/DockerServerEngine.cs | 7 +- .../ServerEngines/LocalServerEngine.cs | 11 +- ...GameServiceTests.cs => GameClientTests.cs} | 2 +- .../Services/ImporterTests.cs | 278 ++++++++++++++++++ ...SaveServiceTests.cs => SaveClientTests.cs} | 2 +- .../Controllers/Api/ArchivesController.cs | 20 +- .../Controllers/Api/GamesController.cs | 22 +- .../Api/RedistributablesController.cs | 18 +- .../Controllers/Api/UploadController.cs | 10 +- .../Controllers/RedistributablesController.cs | 8 +- .../Controllers/UploadController.cs | 6 +- .../Endpoints/DownloadEndpoints.cs | 6 +- .../Background/PatchArchiveBackgroundJob.cs | 12 +- LANCommander.Server/Startup/Beacon.cs | 9 +- .../UI/Components/ArchiveEditor.razor | 12 +- .../UI/Components/ArchiveUploader.razor | 18 +- .../UI/Components/ExportDialog.razor | 4 +- .../UI/Components/FilePickerButton.razor | 4 +- .../UI/Components/ImportUploadDialog.razor | 4 +- .../UI/Components/TaxonomyInput.razor | 36 +++ .../UI/Pages/Games/Edit/Actions.razor | 4 +- .../UI/Pages/Games/Edit/General.razor | 12 +- .../UI/Pages/Settings/Beacon.razor | 10 +- .../UI/Pages/Settings/Tools/Index.razor | 6 +- .../Settings/Tools/MissingArchives.razor | 14 +- .../Pages/Settings/Tools/OrphanedFiles.razor | 6 +- LANCommander.UI/Components/Chat/Chat.razor | 8 +- .../Components/Chat/ChatThread.razor | 7 +- .../Components/FileManager/FileManager.razor | 4 +- .../Sources/FileManagerArchiveSource.cs | 8 +- .../Components/SafeImage/SafeImage.razor | 5 +- 142 files changed, 1546 insertions(+), 926 deletions(-) create mode 100644 LANCommander.Launcher/UI/ChatWindowLayout.razor create mode 100644 LANCommander.Launcher/UI/ChatWindowLayout.razor.css create mode 100644 LANCommander.Launcher/wwwroot/css/main.js create mode 100644 LANCommander.SDK/Client.cs create mode 100644 LANCommander.SDK/Extensions/IConfigurationBuilderExtensions.cs delete mode 100644 LANCommander.SDK/Models/Settings.cs create mode 100644 LANCommander.SDK/Models/Settings/AuthenticationSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/DebugSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/GameSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IAuthenticationSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IDebugSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IGameSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IIPXRelaySettings.cs create mode 100644 LANCommander.SDK/Models/Settings/ILibrarySettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IMediaSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IPXRelaySettings.cs create mode 100644 LANCommander.SDK/Models/Settings/ISettings.cs create mode 100644 LANCommander.SDK/Models/Settings/IUpdateSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/LibrarySettings.cs create mode 100644 LANCommander.SDK/Models/Settings/MediaSettings.cs create mode 100644 LANCommander.SDK/Models/Settings/Settings.cs create mode 100644 LANCommander.SDK/Models/Settings/UpdateSettings.cs create mode 100644 LANCommander.SDK/Providers/AuthenticationProvider.cs create mode 100644 LANCommander.SDK/Providers/ServerConfigurationProvider.cs create mode 100644 LANCommander.SDK/Providers/SettingsProvider.cs rename LANCommander.SDK/Services/{AuthenticationService.cs => AuthenticationClient.cs} (84%) rename LANCommander.SDK/Services/{BeaconService.cs => BeaconClient.cs} (97%) rename LANCommander.SDK/Services/{ChatService.cs => ChatClient.cs} (82%) rename LANCommander.SDK/Services/{ConnectionService.cs => ConnectionClient.cs} (92%) rename LANCommander.SDK/Services/{DepotService.cs => DepotClient.cs} (94%) rename LANCommander.SDK/Services/{GameService.cs => GameClient.cs} (95%) rename LANCommander.SDK/Services/{IArchiveService.cs => IArchiveClient.cs} (87%) rename LANCommander.SDK/Services/{IConnectionService.cs => IConnectionClient.cs} (76%) rename LANCommander.SDK/Services/{IssueService.cs => IssueClient.cs} (90%) rename LANCommander.SDK/Services/{LauncherService.cs => LauncherClient.cs} (93%) rename LANCommander.SDK/Services/{LibraryService.cs => LibraryClient.cs} (96%) rename LANCommander.SDK/Services/{LobbyService.cs => LobbyClient.cs} (97%) rename LANCommander.SDK/Services/{PlaySessionService.cs => PlaySessionClient.cs} (92%) rename LANCommander.SDK/Services/{ProfileService.cs => ProfileClient.cs} (97%) rename LANCommander.SDK/Services/{RedistributableService.cs => RedistributableClient.cs} (94%) rename LANCommander.SDK/Services/{SaveService.cs => SaveClient.cs} (99%) rename LANCommander.SDK/Services/{ScriptService.cs => ScriptClient.cs} (96%) rename LANCommander.SDK/Services/{ServerService.cs => ServerClient.cs} (98%) rename LANCommander.SDK/Services/{TagService.cs => TagClient.cs} (94%) delete mode 100644 LANCommander.SDK/VersionInterceptor.cs rename LANCommander.Server.Services/{ArchiveService.cs => ArchiveClient.cs} (99%) rename LANCommander.Server.Tests/Services/{GameServiceTests.cs => GameClientTests.cs} (99%) create mode 100644 LANCommander.Server.Tests/Services/ImporterTests.cs rename LANCommander.Server.Tests/Services/{SaveServiceTests.cs => SaveClientTests.cs} (98%) create mode 100644 LANCommander.Server/UI/Components/TaxonomyInput.razor diff --git a/LANCommander.Launcher.Services/AuthenticationService.cs b/LANCommander.Launcher.Services/AuthenticationService.cs index 632f0579..59e3233f 100644 --- a/LANCommander.Launcher.Services/AuthenticationService.cs +++ b/LANCommander.Launcher.Services/AuthenticationService.cs @@ -1,15 +1,19 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using LANCommander.Launcher.Models; -using LANCommander.SDK; +using LANCommander.SDK.Abstractions; using Microsoft.Extensions.Logging; -using Microsoft.IdentityModel.Tokens; +using Microsoft.Extensions.Options; namespace LANCommander.Launcher.Services; -public class AuthenticationService : BaseService +public class AuthenticationService( + ITokenProvider tokenProvider, + SDK.Client client, + IOptions settings, + ILogger logger) : BaseService(logger) { - private Settings Settings; + private Settings Settings = SettingService.GetSettings(); private bool TemporarilyOffline; public event EventHandler OnLogin; @@ -18,32 +22,17 @@ public class AuthenticationService : BaseService public delegate void OnOfflineModeChangedHandler(bool state); public event OnOfflineModeChangedHandler OnOfflineModeChanged; - - public AuthenticationService( - Client client, - ILogger logger) : base(client, logger) - { - Settings = SettingService.GetSettings(); - } public bool IsConnected() { - return Client.IsConnected(); - } - - public string GetServerAddress() - { - return Client.IsConfigured() ? Client.GetServerAddress() : string.Empty; + return client.Connection.IsConnected(); } public async Task IsServerOnlineAsync() { try { - if (Client.IsConfigured()) - { - return await Client.PingAsync(); - } + return await client.Connection.PingAsync(); } catch { @@ -54,44 +43,44 @@ public class AuthenticationService : BaseService public async Task Login() { - await Login(Settings.Authentication.ServerAddress, new SDK.Models.AuthToken + await Login(settings.Value.Authentication.ServerAddress, new SDK.Models.AuthToken { AccessToken = Settings.Authentication.AccessToken, RefreshToken = Settings.Authentication.RefreshToken, }); } - public async Task Login(string serverAddress, string username, string password) + public async Task Login(Uri serverAddress, string username, string password) { - await Client.ChangeServerAddressAsync(serverAddress); + await client.Connection.UpdateServerAddressAsync(serverAddress.ToString()); - var token = await Client.AuthenticateAsync(username, password); + var token = await client.Authentication.AuthenticateAsync(username, password); await Login(serverAddress, token); } - public async Task Login(string serverAddress, SDK.Models.AuthToken token) + public async Task Login(Uri serverAddress, SDK.Models.AuthToken token) { try { - await Client.ChangeServerAddressAsync(serverAddress); + await client.Connection.UpdateServerAddressAsync(serverAddress.ToString()); Settings = SettingService.GetSettings(); - Settings.Authentication.ServerAddress = serverAddress; + Settings.Authentication.ServerAddress = serverAddress.ToString(); Settings.Authentication.AccessToken = token.AccessToken; Settings.Authentication.RefreshToken = token.RefreshToken; - Client.UseToken(token); + tokenProvider.SetToken(token.AccessToken); - if (await Client.ValidateTokenAsync()) + if (await client.Authentication.ValidateTokenAsync()) { - SetOfflineMode(false); + //SetOfflineMode(false); TemporarilyOffline = false; SettingService.SaveSettings(Settings); - var user = await Client.Profile.GetAsync(); + var user = await client.Profile.GetAsync(); OnLogin?.Invoke(this, EventArgs.Empty); } @@ -101,11 +90,8 @@ public class AuthenticationService : BaseService } } - public async Task Register(string serverAddress, string username, string password, string passwordConfirmation) + public async Task Register(string username, string password, string passwordConfirmation) { - if (String.IsNullOrWhiteSpace(serverAddress)) - throw new Exception("Server address cannot be blank"); - if (String.IsNullOrWhiteSpace(username)) throw new Exception("Username cannot be blank"); @@ -115,17 +101,12 @@ public class AuthenticationService : BaseService if (password != passwordConfirmation) throw new Exception("Passwords do not match"); - await Client.ChangeServerAddressAsync(serverAddress); - - var token = await Client.RegisterAsync(username, password, passwordConfirmation); - - Client.UseToken(token); + await client.Authentication.RegisterAsync(username, password, passwordConfirmation); Settings = SettingService.GetSettings(); - Settings.Authentication.ServerAddress = serverAddress; - Settings.Authentication.AccessToken = token.AccessToken; - Settings.Authentication.RefreshToken = token.RefreshToken; + Settings.Authentication.ServerAddress = client.Connection.GetServerAddress().ToString(); + Settings.Authentication.AccessToken = tokenProvider.GetToken(); SettingService.SaveSettings(Settings); @@ -134,7 +115,7 @@ public class AuthenticationService : BaseService public async Task ValidateConnectionAsync() { - return await Client.ValidateTokenAsync(); + return await client.Authentication.ValidateTokenAsync(); } public bool OfflineModeEnabled() @@ -148,14 +129,14 @@ public class AuthenticationService : BaseService OnOfflineModeChanged?.Invoke(true); } - public void SetOfflineMode(bool state) + public async Task SetOfflineModeAsync(bool state) { Settings = SettingService.GetSettings(); Settings.Authentication.OfflineMode = state; if (state) - Client.Disconnect(); + await client.Connection.DisconnectAsync(); SettingService.SaveSettings(Settings); @@ -164,7 +145,7 @@ public class AuthenticationService : BaseService public async Task Logout() { - await Client.LogoutAsync(); + await client.Authentication.LogoutAsync(); TemporarilyOffline = false; diff --git a/LANCommander.Launcher.Services/CollectionService.cs b/LANCommander.Launcher.Services/CollectionService.cs index b71050d7..3c59a8c0 100644 --- a/LANCommander.Launcher.Services/CollectionService.cs +++ b/LANCommander.Launcher.Services/CollectionService.cs @@ -1,17 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { public class CollectionService : BaseDatabaseService { - public CollectionService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) + public CollectionService(DatabaseContext dbContext, ILogger logger) : base(dbContext, logger) { } } diff --git a/LANCommander.Launcher.Services/CommandLineService.cs b/LANCommander.Launcher.Services/CommandLineService.cs index 24559cd2..8312694d 100644 --- a/LANCommander.Launcher.Services/CommandLineService.cs +++ b/LANCommander.Launcher.Services/CommandLineService.cs @@ -2,47 +2,25 @@ using LANCommander.Launcher.Models; using LANCommander.SDK.Helpers; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using LANCommander.SDK; namespace LANCommander.Launcher.Services { - public class CommandLineService : BaseService + public class CommandLineService( + ILogger logger, + AuthenticationService authenticationService, + UserService userService, + GameService gameService, + InstallService installService, + ImportService importService, + ProfileService profileService, + SDK.Client client) : BaseService(logger) { - private readonly AuthenticationService AuthenticationService; - private readonly UserService UserService; - private readonly GameService GameService; - private readonly InstallService InstallService; - private readonly ImportService ImportService; - private readonly ProfileService ProfileService; - private Settings Settings = SettingService.GetSettings(); - public CommandLineService( - SDK.Client client, - ILogger logger, - AuthenticationService authenticationService, - UserService userService, - GameService gameService, - InstallService installService, - ImportService importService, - ProfileService profileService) : base(client, logger) - { - AuthenticationService = authenticationService; - UserService = userService; - GameService = gameService; - InstallService = installService; - ImportService = importService; - ProfileService = profileService; - } - public async Task ParseCommandLineAsync(string[] args) { - await Client.ValidateTokenAsync(); + await client.Authentication.ValidateTokenAsync(); var result = Parser.Default.ParseArguments @@ -77,27 +55,27 @@ namespace LANCommander.Launcher.Services switch (options.Type) { case SDK.Enums.ScriptType.Install: - await Client.Scripts.RunInstallScriptAsync(options.InstallDirectory, options.GameId); + await client.Scripts.RunInstallScriptAsync(options.InstallDirectory, options.GameId); break; case SDK.Enums.ScriptType.Uninstall: - await Client.Scripts.RunUninstallScriptAsync(options.InstallDirectory, options.GameId); + await client.Scripts.RunUninstallScriptAsync(options.InstallDirectory, options.GameId); break; case SDK.Enums.ScriptType.BeforeStart: - await Client.Scripts.RunBeforeStartScriptAsync(options.InstallDirectory, options.GameId); + await client.Scripts.RunBeforeStartScriptAsync(options.InstallDirectory, options.GameId); break; case SDK.Enums.ScriptType.AfterStop: - await Client.Scripts.RunAfterStopScriptAsync(options.InstallDirectory, options.GameId); + await client.Scripts.RunAfterStopScriptAsync(options.InstallDirectory, options.GameId); break; case SDK.Enums.ScriptType.NameChange: - await Client.Scripts.RunNameChangeScriptAsync(options.InstallDirectory, options.GameId, options.NewPlayerAlias ?? Settings.DEFAULT_GAME_USERNAME); + await client.Scripts.RunNameChangeScriptAsync(options.InstallDirectory, options.GameId, options.NewPlayerAlias ?? Settings.DEFAULT_GAME_USERNAME); break; case SDK.Enums.ScriptType.KeyChange: - await Client.Scripts.RunKeyChangeScriptAsync(options.InstallDirectory, options.GameId, options.AllocatedKey); + await client.Scripts.RunKeyChangeScriptAsync(options.InstallDirectory, options.GameId, options.AllocatedKey); break; } } @@ -108,12 +86,12 @@ namespace LANCommander.Launcher.Services try { - var game = await GameService.GetAsync(options.GameId); + var game = await gameService.GetAsync(options.GameId); - await InstallService.Add(game, options.InstallDirectory); - await InstallService.Next(); + await installService.Add(game, options.InstallDirectory); + await installService.Next(); - game = await GameService.GetAsync(options.GameId); + game = await gameService.GetAsync(options.GameId); Logger.LogInformation($"Successfully installed {game.Title} to directory {game.InstallDirectory}"); } @@ -129,9 +107,9 @@ namespace LANCommander.Launcher.Services try { - var game = await GameService.GetAsync(options.GameId); + var game = await gameService.GetAsync(options.GameId); - await GameService.UninstallAsync(game); + await gameService.UninstallAsync(game); Logger.LogInformation($"Game successfully uninstalled from {game.InstallDirectory}"); } @@ -147,14 +125,14 @@ namespace LANCommander.Launcher.Services try { - var game = await GameService.GetAsync(options.GameId); + var game = await gameService.GetAsync(options.GameId); var manifest = await ManifestHelper.ReadAsync(game.InstallDirectory, game.Id); var action = manifest.Actions.FirstOrDefault(a => a.Id == options.ActionId); if (action == null) action = manifest.Actions.OrderBy(a => a.SortOrder).FirstOrDefault(a => a.IsPrimaryAction); - await GameService.Run(game, action); + await gameService.Run(game, action); } catch (Exception ex) { @@ -166,17 +144,17 @@ namespace LANCommander.Launcher.Services { Logger.LogInformation("Syncing games from server..."); - ImportService.OnImportComplete += async () => + importService.OnImportComplete += async () => { Logger.LogInformation("Sync complete!"); }; - ImportService.OnImportFailed += async (Exception ex) => + importService.OnImportFailed += async (Exception ex) => { Logger.LogError(ex, "Sync failed!"); }; - await ImportService.ImportAsync(); + await importService.ImportAsync(); } private async Task Import(ImportCommandLineOptions options) @@ -192,19 +170,19 @@ namespace LANCommander.Launcher.Services case ArchiveType.Game: Logger.LogInformation("Uploading game import file to server..."); - await Client.Games.ImportAsync(options.Path); + await client.Games.ImportAsync(options.Path); break; case ArchiveType.Redistributable: Logger.LogInformation("Uploading redistributable archive file to server..."); - await Client.Redistributables.ImportAsync(options.Path); + await client.Redistributables.ImportAsync(options.Path); break; case ArchiveType.Server: Logger.LogInformation("Uploading server archive file to server..."); - await Client.Servers.ImportAsync(options.Path); + await client.Servers.ImportAsync(options.Path); break; } @@ -224,19 +202,19 @@ namespace LANCommander.Launcher.Services case ArchiveType.Game: Logger.LogInformation("Exporting game from server..."); - await Client.Games.ExportAsync(options.Path, options.Id); + await client.Games.ExportAsync(options.Path, options.Id); break; case ArchiveType.Redistributable: Logger.LogInformation("Exporting redistributable from server..."); - await Client.Redistributables.ExportAsync(options.Path, options.Id); + await client.Redistributables.ExportAsync(options.Path, options.Id); break; case ArchiveType.Server: Logger.LogInformation("Exporting server from server..."); - await Client.Servers.ExportAsync(options.Path, options.Id); + await client.Servers.ExportAsync(options.Path, options.Id); break; } @@ -256,13 +234,13 @@ namespace LANCommander.Launcher.Services case ArchiveType.Game: Logger.LogInformation("Uploading game archive to server..."); - await Client.Games.UploadArchiveAsync(options.Path, options.Id, options.Version, options.Changelog); + await client.Games.UploadArchiveAsync(options.Path, options.Id, options.Version, options.Changelog); break; case ArchiveType.Redistributable: Logger.LogInformation("Uploading redistributable archive to server..."); - await Client.Redistributables.UploadArchiveAsync(options.Path, options.Id, options.Version, options.Changelog); + await client.Redistributables.UploadArchiveAsync(options.Path, options.Id, options.Version, options.Changelog); break; } } @@ -277,13 +255,12 @@ namespace LANCommander.Launcher.Services if (String.IsNullOrWhiteSpace(options.ServerAddress)) throw new ArgumentException("A server address must be specified"); - await Client.ChangeServerAddressAsync(options.ServerAddress); + await client.Connection.UpdateServerAddressAsync(options.ServerAddress); - var token = await Client.AuthenticateAsync(options.Username, options.Password); + var token = await client.Authentication.AuthenticateAsync(options.Username, options.Password); Settings.Authentication.AccessToken = token.AccessToken; - Settings.Authentication.RefreshToken = token.RefreshToken; - Settings.Authentication.ServerAddress = Client.GetServerAddress(); + Settings.Authentication.ServerAddress = client.Connection.GetServerAddress().ToString(); SettingService.SaveSettings(Settings); @@ -297,7 +274,7 @@ namespace LANCommander.Launcher.Services private async Task Logout(LogoutCommandLineOptions options) { - await Client.LogoutAsync(); + await client.Authentication.LogoutAsync(); Settings.Authentication.AccessToken = ""; Settings.Authentication.RefreshToken = ""; @@ -308,9 +285,9 @@ namespace LANCommander.Launcher.Services private async Task ChangeAlias(ChangeAliasCommandLineOptions options) { - var currentUser = await UserService.GetAsync(AuthenticationService.GetUserId()); + var currentUser = await userService.GetAsync(authenticationService.GetUserId()); - await ProfileService.ChangeAlias(options.Alias); + await profileService.ChangeAlias(options.Alias); Logger.LogInformation($"Changed current user's alias from {currentUser.Alias} to {options.Alias}"); } diff --git a/LANCommander.Launcher.Services/CompanyService.cs b/LANCommander.Launcher.Services/CompanyService.cs index 65b15a28..653f2269 100644 --- a/LANCommander.Launcher.Services/CompanyService.cs +++ b/LANCommander.Launcher.Services/CompanyService.cs @@ -1,18 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class CompanyService : BaseDatabaseService + public class CompanyService( + DatabaseContext dbContext, + ILogger logger) : BaseDatabaseService(dbContext, logger) { - public CompanyService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - } } } diff --git a/LANCommander.Launcher.Services/DepotService.cs b/LANCommander.Launcher.Services/DepotService.cs index a4776fc0..3774ff65 100644 --- a/LANCommander.Launcher.Services/DepotService.cs +++ b/LANCommander.Launcher.Services/DepotService.cs @@ -18,10 +18,13 @@ namespace LANCommander.Launcher.Services public delegate Task OnItemsFilteredHandler(IEnumerable items); public event OnItemsFilteredHandler OnItemsFiltered; + private SDK.Client _client; + public DepotService( Client client, - ILogger logger) : base(client, logger) + ILogger logger) : base(logger) { + _client = client; Filter.OnChanged += Filter_OnChanged; } @@ -54,7 +57,7 @@ namespace LANCommander.Launcher.Services using (var op = Logger.BeginOperation(LogLevel.Trace, "Loading depot items from host")) { - var results = await Client.Depot.GetAsync(); + var results = await _client.Depot.GetAsync(); Filter.Populate(results); diff --git a/LANCommander.Launcher.Services/EngineService.cs b/LANCommander.Launcher.Services/EngineService.cs index df604d88..cd12807b 100644 --- a/LANCommander.Launcher.Services/EngineService.cs +++ b/LANCommander.Launcher.Services/EngineService.cs @@ -11,7 +11,7 @@ namespace LANCommander.Launcher.Services { public class EngineService : BaseDatabaseService { - public EngineService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) + public EngineService(DatabaseContext dbContext, ILogger logger) : base(dbContext, logger) { } } diff --git a/LANCommander.Launcher.Services/Extensions/IServiceProviderExtensions.cs b/LANCommander.Launcher.Services/Extensions/IServiceProviderExtensions.cs index f7cba313..42b209bb 100644 --- a/LANCommander.Launcher.Services/Extensions/IServiceProviderExtensions.cs +++ b/LANCommander.Launcher.Services/Extensions/IServiceProviderExtensions.cs @@ -22,8 +22,6 @@ namespace LANCommander.Launcher.Services.Extensions using (var scope = serviceProvider.CreateScope()) { var logger = scope.ServiceProvider.GetService(); - var authenticationService = scope.ServiceProvider.GetService(); - var keepAliveService = scope.ServiceProvider.GetService(); #region Scaffold Required Directories try diff --git a/LANCommander.Launcher.Services/Extensions/ServiceCollectionExtensions.cs b/LANCommander.Launcher.Services/Extensions/ServiceCollectionExtensions.cs index 04cd0b56..7cbb3562 100644 --- a/LANCommander.Launcher.Services/Extensions/ServiceCollectionExtensions.cs +++ b/LANCommander.Launcher.Services/Extensions/ServiceCollectionExtensions.cs @@ -48,12 +48,12 @@ namespace LANCommander.Launcher.Services.Extensions configure(options); - var client = new SDK.Client(options.ServerAddress, settings.Games.InstallDirectories.First(), options.Logger); + /*var client = new SDK.Client(options.ServerAddress, settings.Games.InstallDirectories.First(), options.Logger); client.Scripts.Debug = settings.Debug.EnableScriptDebugging; - client.Scripts.ExternalScriptRunner += Scripts_ExternalScriptRunner; + client.Scripts.ExternalScriptRunner += Scripts_ExternalScriptRunner;*/ - services.AddSingleton(client); + // services.AddSingleton(client); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/LANCommander.Launcher.Services/FilterService.cs b/LANCommander.Launcher.Services/FilterService.cs index f98dfc9f..dceff45e 100644 --- a/LANCommander.Launcher.Services/FilterService.cs +++ b/LANCommander.Launcher.Services/FilterService.cs @@ -1,22 +1,14 @@ using LANCommander.Launcher.Data.Models; using LANCommander.Launcher.Models; -using LANCommander.Launcher.Models.Enums; using LANCommander.SDK.Extensions; using Microsoft.Extensions.Logging; -using Steamworks.Ugc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class FilterService : BaseService + public class FilterService( + ILogger logger, + LibraryService libraryService) : BaseService(logger) { - private readonly LibraryService LibraryService; - private readonly GameService GameService; - public LibraryFilterModel Filter { get; set; } public ICollection Engines { get; private set; } @@ -31,16 +23,6 @@ namespace LANCommander.Launcher.Services public delegate Task OnFilterChangedHandler(); public event OnFilterChangedHandler OnFilterChanged; - public FilterService( - SDK.Client client, - ILogger logger, - LibraryService libraryService, - GameService gameService) : base(client, logger) - { - GameService = gameService; - LibraryService = libraryService; - } - public void Populate(IEnumerable games) { var multiplayerModes = games.Where(g => g.MultiplayerModes != null).SelectMany(g => g.MultiplayerModes); @@ -139,7 +121,7 @@ namespace LANCommander.Launcher.Services public async Task ApplyFilter() { - await LibraryService.FilterChanged(); + await libraryService.FilterChanged(); SaveSettings(); } @@ -148,7 +130,7 @@ namespace LANCommander.Launcher.Services { Filter = new LibraryFilterModel(); - await LibraryService.FilterChanged(); + await libraryService.FilterChanged(); SaveSettings(); } diff --git a/LANCommander.Launcher.Services/GameService.cs b/LANCommander.Launcher.Services/GameService.cs index f8dc3342..b14c8cfe 100644 --- a/LANCommander.Launcher.Services/GameService.cs +++ b/LANCommander.Launcher.Services/GameService.cs @@ -10,17 +10,17 @@ using System.Diagnostics; namespace LANCommander.Launcher.Services { - public class GameService : BaseDatabaseService + public class GameService( + DatabaseContext dbContext, + ILogger logger, + AuthenticationService authenticationService, + PlaySessionService playSessionService, + SDK.Client client, + IServiceProvider serviceProvider) : BaseDatabaseService(dbContext, logger) { - private readonly AuthenticationService AuthenticationService; - private readonly PlaySessionService PlaySessionService; - private readonly IServiceProvider ServiceProvider; - private readonly SaveService SaveService; - private readonly MessageBusService MessageBusService; - public Dictionary RunningProcesses = new Dictionary(); - private Settings Settings { get; set; } + private Settings Settings = SettingService.GetSettings(); public delegate Task OnUninstallCompleteHandler(Game game); public event OnUninstallCompleteHandler OnUninstallComplete; @@ -28,24 +28,6 @@ namespace LANCommander.Launcher.Services public delegate Task OnUninstallHandler(Game game); public event OnUninstallHandler OnUninstall; - public GameService( - DatabaseContext dbContext, - SDK.Client client, - ILogger logger, - AuthenticationService authenticationService, - PlaySessionService playSessionService, - IServiceProvider serviceProvider, - SaveService saveService, - MessageBusService messageBusService) : base(dbContext, client, logger) - { - Settings = SettingService.GetSettings(); - AuthenticationService = authenticationService; - PlaySessionService = playSessionService; - ServiceProvider = serviceProvider; - SaveService = saveService; - MessageBusService = messageBusService; - } - public async Task UninstallAsync(Game game) { using (var operation = Logger.BeginOperation("Uninstalling game {GameTitle} ({GameId})", game.Title, game.Id)) @@ -54,18 +36,18 @@ namespace LANCommander.Launcher.Services { OnUninstall?.Invoke(game); - await Client.Games.UninstallAsync(game.InstallDirectory, game.Id); + await client.Games.UninstallAsync(game.InstallDirectory, game.Id); if (game.BaseGameId.HasValue) { - var libraryService = ServiceProvider.GetService(); + var libraryService = serviceProvider.GetService(); var isInstalled = await libraryService!.IsInstalledAsync(game.BaseGameId.Value); if (!isInstalled) { var baseGame = await GetAsync(game.BaseGameId.Value); - await Client.Games.UninstallAsync(game.InstallDirectory, baseGame?.Id ?? game.BaseGameId.Value); + await client.Games.UninstallAsync(game.InstallDirectory, baseGame?.Id ?? game.BaseGameId.Value); ClearGameState(baseGame!, skipAddons: true); } @@ -89,24 +71,24 @@ namespace LANCommander.Launcher.Services { Guid userId; - if (Client.IsConnected()) + if (client.Connection.IsConnected()) { - var profile = await Client.Profile.GetAsync(); + var profile = await client.Profile.GetAsync(); userId = profile.Id; } else { - userId = AuthenticationService.GetUserId(); + userId = authenticationService.GetUserId(); } try { - var latestSession = await PlaySessionService.GetLatestSession(game.Id, userId); + var latestSession = await playSessionService.GetLatestSession(game.Id, userId); - await PlaySessionService.StartSession(game.Id, userId); + await playSessionService.StartSession(game.Id, userId); - await Client.Games.RunAsync(game.InstallDirectory, game.Id, action, latestSession?.CreatedOn); + await client.Games.RunAsync(game.InstallDirectory, game.Id, action, latestSession?.CreatedOn); } catch (Exception ex) { @@ -114,7 +96,7 @@ namespace LANCommander.Launcher.Services } finally { - await PlaySessionService.EndSession(game.Id, userId); + await playSessionService.EndSession(game.Id, userId); } } diff --git a/LANCommander.Launcher.Services/GenreService.cs b/LANCommander.Launcher.Services/GenreService.cs index ebd9048b..0c4bd85c 100644 --- a/LANCommander.Launcher.Services/GenreService.cs +++ b/LANCommander.Launcher.Services/GenreService.cs @@ -1,17 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { public class GenreService : BaseDatabaseService { - public GenreService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) + public GenreService(DatabaseContext dbContext,ILogger logger) : base(dbContext, logger) { } } diff --git a/LANCommander.Launcher.Services/ImportManagerService.cs b/LANCommander.Launcher.Services/ImportManagerService.cs index befa4c5b..ed3925fe 100644 --- a/LANCommander.Launcher.Services/ImportManagerService.cs +++ b/LANCommander.Launcher.Services/ImportManagerService.cs @@ -1,16 +1,7 @@ -using System.Threading.Tasks; - namespace LANCommander.Launcher.Services; public class ImportManagerService { - private readonly ImportService ImportService; - - public ImportManagerService(ImportService importService) - { - ImportService = importService; - } - public delegate Task OnImportRequestedHandler(); public event OnImportRequestedHandler OnImportRequested; diff --git a/LANCommander.Launcher.Services/ImportService.cs b/LANCommander.Launcher.Services/ImportService.cs index 30bfe58d..cbea3bb1 100644 --- a/LANCommander.Launcher.Services/ImportService.cs +++ b/LANCommander.Launcher.Services/ImportService.cs @@ -4,16 +4,8 @@ using LANCommander.SDK.Extensions; using LANCommander.SDK.Helpers; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; using LANCommander.Launcher.Services.Extensions; using LANCommander.SDK.Models; -using Microsoft.EntityFrameworkCore.Storage; using BaseModel = LANCommander.Launcher.Data.Models.BaseModel; using Collection = LANCommander.Launcher.Data.Models.Collection; using Company = LANCommander.Launcher.Data.Models.Company; @@ -29,17 +21,16 @@ using Tag = LANCommander.Launcher.Data.Models.Tag; namespace LANCommander.Launcher.Services { - public class ImportService : BaseService + public class ImportService( + ILogger logger, + DatabaseContext databaseContext, + LibraryService libraryService, + MediaService mediaService, + EngineService engineService, + GameService gameService, + MessageBusService messageBusService, + SDK.Client client) : BaseService(logger) { - private readonly AuthenticationService AuthenticationService; - private readonly MediaService MediaService; - private readonly EngineService EngineService; - private readonly GameService GameService; - private readonly LibraryService LibraryService; - private readonly MessageBusService MessageBusService; - private readonly Settings Settings; - private readonly DatabaseContext DatabaseContext; - private ImportProgress _importProgress = new(); public ImportProgress Progress => _importProgress; @@ -60,27 +51,7 @@ namespace LANCommander.Launcher.Services private IEnumerable Tags; private IEnumerable MultiplayerModes; - public ImportService( - SDK.Client client, - ILogger logger, - AuthenticationService authenticationService, - LibraryService libraryService, - MediaService mediaService, - EngineService engineService, - GameService gameService, - MessageBusService messageBusService, - DatabaseContext databaseContext) : base(client, logger) - { - AuthenticationService = authenticationService; - LibraryService = libraryService; - MediaService = mediaService; - EngineService = engineService; - GameService = gameService; - MessageBusService = messageBusService; - DatabaseContext = databaseContext; - - Settings = SettingService.GetSettings(); - } + private Settings Settings = SettingService.GetSettings(); public void ImportHasCompleted() { @@ -103,7 +74,7 @@ namespace LANCommander.Launcher.Services public async Task ImportGameAsync(Guid id) { - var game = await Client.Games.GetAsync(id); + var game = await client.Games.GetAsync(id); return await ImportGameAsync(game); } @@ -115,7 +86,7 @@ namespace LANCommander.Launcher.Services try { var existing = false; - var localGame = await GameService.GetAsync(game.Id); + var localGame = await gameService.GetAsync(game.Id); if (localGame == null) localGame = new Game() @@ -141,17 +112,17 @@ namespace LANCommander.Launcher.Services localGame.Singleplayer = game.Singleplayer; if (!existing) - localGame = await GameService.AddAsync(localGame); + localGame = await gameService.AddAsync(localGame); if (game.BaseGameId != Guid.Empty && localGame.BaseGameId != game.BaseGameId) { - var baseGame = await GameService.GetAsync(game.BaseGameId); + var baseGame = await gameService.GetAsync(game.BaseGameId); if (baseGame == null) { await ImportGameAsync(game.BaseGameId); - localGame.BaseGame = await GameService.GetAsync(game.BaseGameId); + localGame.BaseGame = await gameService.GetAsync(game.BaseGameId); } else { @@ -174,7 +145,7 @@ namespace LANCommander.Launcher.Services } else if (game.Engine != null) { - var engine = await EngineService.GetAsync(game.Engine.Id); + var engine = await engineService.GetAsync(game.Engine.Id); if (engine != null) { @@ -185,7 +156,7 @@ namespace LANCommander.Launcher.Services #endregion - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Collections) .UseSource(game.Collections) .AsBatch() @@ -196,11 +167,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.Games) .Query() .Any(g => g.Id == localGame.Id); @@ -210,7 +181,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Genres) .UseSource(game.Genres) .AsBatch() @@ -221,11 +192,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.Games) .Query() .Any(g => g.Id == localGame.Id); @@ -235,7 +206,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Publishers) .UseSource(game.Publishers) .AsBatch() @@ -246,11 +217,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.PublishedGames) .Query() .Any(g => g.Id == localGame.Id); @@ -260,7 +231,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Developers) .UseSource(game.Developers) .AsBatch() @@ -271,11 +242,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.DevelopedGames) .Query() .Any(g => g.Id == localGame.Id); @@ -285,7 +256,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Tags) .UseSource(game.Tags) .AsBatch() @@ -296,11 +267,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.Games) .Query() .Any(g => g.Id == localGame.Id); @@ -310,7 +281,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.MultiplayerModes) .UseSource(game.MultiplayerModes) .AsBatch() @@ -327,8 +298,8 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); var linked = t.GameId == localGame.Id; @@ -337,7 +308,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.Platforms) .UseSource(game.Platforms) .AsBatch() @@ -349,11 +320,11 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); // Check if the relationship already exists - var linked = DatabaseContext.Entry(t) + var linked = databaseContext.Entry(t) .Collection(x => x.Games) .Query() .Any(g => g.Id == localGame.Id); @@ -363,7 +334,7 @@ namespace LANCommander.Launcher.Services }) .ImportAsync(); - /*await DatabaseContext.BulkImport() + /*await databaseContext.BulkImport() .SetTarget(localGame.PlaySessions) .UseSource(game.PlaySessions) .Include(p => p.Game) @@ -377,7 +348,7 @@ namespace LANCommander.Launcher.Services .AsNoRemove() .ImportAsync();*/ - var importedMedia = await DatabaseContext.BulkImport() + var importedMedia = await databaseContext.BulkImport() .SetTarget(localGame.Media) .UseSource(game.Media) .AsBatch() @@ -393,8 +364,8 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); var linked = t.GameId == localGame.Id; @@ -410,13 +381,13 @@ namespace LANCommander.Launcher.Services if (!File.Exists(localPath) && media.Type != SDK.Enums.MediaType.Manual) { - await Client.Media.DownloadAsync(new SDK.Models.Media + await client.Media.DownloadAsync(new SDK.Models.Media { Id = media.Id, FileId = media.FileId }, localPath); - MessageBusService.MediaChanged(media); + messageBusService.MediaChanged(media); } } @@ -424,7 +395,7 @@ namespace LANCommander.Launcher.Services foreach (var installDirectory in Settings.Games.InstallDirectories) { - var gameDirectory = await Client.Games.GetInstallDirectory(game, installDirectory); + var gameDirectory = await client.Games.GetInstallDirectory(game, installDirectory); if (Directory.Exists(gameDirectory)) { @@ -444,11 +415,11 @@ namespace LANCommander.Launcher.Services #endregion - var playSessions = await Client.PlaySessions.GetAsync(localGame.Id); + var playSessions = await client.PlaySessions.GetAsync(localGame.Id); if (playSessions != null) { - await DatabaseContext.BulkImport() + await databaseContext.BulkImport() .SetTarget(localGame.PlaySessions) .UseSource(playSessions) .Include(p => p.Game) @@ -461,8 +432,8 @@ namespace LANCommander.Launcher.Services .AssignRelationships((t, s) => { // Ensure the game is tracked before checking relationships - if (DatabaseContext.Entry(localGame).State == EntityState.Detached) - DatabaseContext.Attach(localGame); + if (databaseContext.Entry(localGame).State == EntityState.Detached) + databaseContext.Attach(localGame); var linked = t.GameId == localGame.Id; @@ -474,9 +445,9 @@ namespace LANCommander.Launcher.Services } // Save all pending changes from batch operations - await DatabaseContext.SaveChangesAsync(); + await databaseContext.SaveChangesAsync(); - localGame = await GameService.UpdateAsync(localGame); + localGame = await gameService.UpdateAsync(localGame); return localGame; } @@ -495,7 +466,7 @@ namespace LANCommander.Launcher.Services public async Task ImportLibraryAsync() { - var remoteLibrary = await Client.Library.GetAsync(); + var remoteLibrary = await client.Library.GetAsync(); try { @@ -518,11 +489,11 @@ namespace LANCommander.Launcher.Services foreach (var game in games) { - using var transaction = await DatabaseContext.Database.BeginTransactionAsync(); + using var transaction = await databaseContext.Database.BeginTransactionAsync(); try { - var remoteGame = await Client.Games.GetAsync(game.Id); + var remoteGame = await client.Games.GetAsync(game.Id); _importProgress.CurrentItem = new ImportItem(game.Id, game.Name); @@ -540,10 +511,10 @@ namespace LANCommander.Launcher.Services { var importedGame = await ImportGameAsync(remoteGame); - await LibraryService.AddToLibraryAsync(importedGame); + await libraryService.AddToLibraryAsync(importedGame); } - await DatabaseContext.SaveChangesAsync(); + await databaseContext.SaveChangesAsync(); await transaction.CommitAsync(); } catch (Exception ex) @@ -567,7 +538,7 @@ namespace LANCommander.Launcher.Services public async Task ImportGamesAsync(params Guid[] ids) { - var games = await Client.Library.GetAsync(); + var games = await client.Library.GetAsync(); var toImport = new List(); foreach (var id in ids) @@ -596,16 +567,16 @@ namespace LANCommander.Launcher.Services SDK.Models.Game game = null; if (gameId.HasValue) - game = await Client.Games.GetAsync(gameId.Value); + game = await client.Games.GetAsync(gameId.Value); - var media = await Client.Media.Get(importMediaId); + var media = await client.Media.GetAsync(importMediaId); return await ImportMediaAsync(media, game); } public async Task ImportMediaAsync(SDK.Models.Media importMedia, SDK.Models.Game game = null) { - var media = await MediaService.GetAsync(importMedia.Id); + var media = await mediaService.GetAsync(importMedia.Id); if (media == null) media = new Media(); @@ -622,23 +593,23 @@ namespace LANCommander.Launcher.Services { media.Id = importMedia.Id; - await MediaService.AddAsync(media); + await mediaService.AddAsync(media); } else - await MediaService.UpdateAsync(media); + await mediaService.UpdateAsync(media); var mediaStoragePath = MediaService.GetStoragePath(); var localPath = MediaService.GetImagePath(media); if (!File.Exists(localPath) && media.Type != SDK.Enums.MediaType.Manual) { - await Client.Media.DownloadAsync(new SDK.Models.Media + await client.Media.DownloadAsync(new SDK.Models.Media { Id = media.Id, FileId = media.FileId }, localPath); - MessageBusService.MediaChanged(media); + messageBusService.MediaChanged(media); } return media; @@ -657,7 +628,7 @@ namespace LANCommander.Launcher.Services foreach (var importModel in importModels) { - using (var transaction = DatabaseContext.Database.BeginTransaction()) + using (var transaction = databaseContext.Database.BeginTransaction()) { try { diff --git a/LANCommander.Launcher.Services/InstallService.cs b/LANCommander.Launcher.Services/InstallService.cs index 26bd3dbd..5c10aa1e 100644 --- a/LANCommander.Launcher.Services/InstallService.cs +++ b/LANCommander.Launcher.Services/InstallService.cs @@ -3,18 +3,9 @@ using LANCommander.Launcher.Models; using LANCommander.SDK.Enums; using LANCommander.SDK.Exceptions; using LANCommander.SDK.Extensions; -using LANCommander.SDK.Helpers; -using LANCommander.SDK.PowerShell; using Microsoft.Extensions.Logging; - -// using Microsoft.Toolkit.Uwp.Notifications; -using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using LANCommander.SDK.Services; namespace LANCommander.Launcher.Services @@ -22,6 +13,7 @@ namespace LANCommander.Launcher.Services public class InstallService : BaseService { private readonly GameService GameService; + private readonly SDK.Client Client; private Stopwatch Stopwatch { get; set; } @@ -43,8 +35,9 @@ namespace LANCommander.Launcher.Services public InstallService( SDK.Client client, ILogger logger, - GameService gameService) : base(client, logger) + GameService gameService) : base(logger) { + Client = client; GameService = gameService; Stopwatch = new Stopwatch(); diff --git a/LANCommander.Launcher.Services/KeepAliveService.cs b/LANCommander.Launcher.Services/KeepAliveService.cs index 5eb0b239..b5ce11d9 100644 --- a/LANCommander.Launcher.Services/KeepAliveService.cs +++ b/LANCommander.Launcher.Services/KeepAliveService.cs @@ -31,9 +31,8 @@ public class KeepAliveService : BaseService public event EventHandler ConnectionEstablished; public KeepAliveService( - Client client, ILogger logger, - AuthenticationService authenticationService) : base(client, logger) + AuthenticationService authenticationService) : base(logger) { AuthenticationService = authenticationService; @@ -134,7 +133,7 @@ public class KeepAliveService : BaseService ConnectionEstablished?.Invoke(this, EventArgs.Empty); - AuthenticationService.SetOfflineMode(false); + await AuthenticationService.SetOfflineModeAsync(false); } else { @@ -150,7 +149,7 @@ public class KeepAliveService : BaseService ConnectionLostPermanently?.Invoke(this, EventArgs.Empty); - AuthenticationService.SetOfflineMode(true); + await AuthenticationService.SetOfflineModeAsync(true); } } } diff --git a/LANCommander.Launcher.Services/LibraryService.cs b/LANCommander.Launcher.Services/LibraryService.cs index 5cdad5ca..1443d680 100644 --- a/LANCommander.Launcher.Services/LibraryService.cs +++ b/LANCommander.Launcher.Services/LibraryService.cs @@ -1,23 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using LANCommander.Launcher.Models; -using LANCommander.Launcher.Services.Extensions; using LANCommander.SDK; using LANCommander.SDK.Extensions; -using LANCommander.SDK.Helpers; -using LANCommander.SDK.PowerShell; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -using Steamworks.Ugc; -using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Linq; -using System.Management.Automation.Language; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { @@ -26,7 +15,7 @@ namespace LANCommander.Launcher.Services private readonly AuthenticationService AuthenticationService; private readonly InstallService InstallService; private readonly GameService GameService; - private readonly UserService UserService; + private readonly SDK.Client Client; public Dictionary RunningProcesses = new Dictionary(); @@ -53,12 +42,12 @@ namespace LANCommander.Launcher.Services AuthenticationService authenticationService, InstallService installService, GameService gameService, - UserService userService) : base(databaseContext, client, logger) + UserService userService) : base(databaseContext, logger) { AuthenticationService = authenticationService; InstallService = installService; GameService = gameService; - UserService = userService; + Client = client; InstallService.OnInstallComplete += InstallService_OnInstallComplete; Filter.OnChanged += Filter_OnChanged; diff --git a/LANCommander.Launcher.Services/MediaService.cs b/LANCommander.Launcher.Services/MediaService.cs index d12d87c1..dc5012b8 100644 --- a/LANCommander.Launcher.Services/MediaService.cs +++ b/LANCommander.Launcher.Services/MediaService.cs @@ -2,23 +2,15 @@ using LANCommander.Launcher.Data.Models; using LANCommander.Launcher.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using LANCommander.SDK; namespace LANCommander.Launcher.Services { - public class MediaService : BaseDatabaseService + public class MediaService( + ILogger logger, + DatabaseContext dbContext) : BaseDatabaseService(dbContext, logger) { - private readonly Settings Settings; - - public MediaService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - Settings = SettingService.GetSettings(); - } + private readonly Settings Settings = SettingService.GetSettings(); public override Task DeleteAsync(Media entity) { diff --git a/LANCommander.Launcher.Services/MessageBusService.cs b/LANCommander.Launcher.Services/MessageBusService.cs index 20227899..1d9d49a6 100644 --- a/LANCommander.Launcher.Services/MessageBusService.cs +++ b/LANCommander.Launcher.Services/MessageBusService.cs @@ -1,21 +1,13 @@ using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using Semver; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class MessageBusService : BaseService + public class MessageBusService(ILogger logger) : BaseService(logger) { public delegate Task OnMediaChangedHandler(Media media); public event OnMediaChangedHandler OnMediaChanged; - public MessageBusService(SDK.Client client, ILogger logger) : base(client, logger) { } - public void MediaChanged(Media media) { OnMediaChanged?.Invoke(media); diff --git a/LANCommander.Launcher.Services/MultiplayerModeService.cs b/LANCommander.Launcher.Services/MultiplayerModeService.cs index 54ad4e29..871fc2bf 100644 --- a/LANCommander.Launcher.Services/MultiplayerModeService.cs +++ b/LANCommander.Launcher.Services/MultiplayerModeService.cs @@ -1,18 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class MultiplayerModeService : BaseDatabaseService + public class MultiplayerModeService( + ILogger logger, + DatabaseContext dbContext) : BaseDatabaseService(dbContext, logger) { - public MultiplayerModeService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - } } } diff --git a/LANCommander.Launcher.Services/PlatformService.cs b/LANCommander.Launcher.Services/PlatformService.cs index 10a73088..09a0d912 100644 --- a/LANCommander.Launcher.Services/PlatformService.cs +++ b/LANCommander.Launcher.Services/PlatformService.cs @@ -1,18 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class PlatformService : BaseDatabaseService + public class PlatformService( + ILogger logger, + DatabaseContext dbContext) : BaseDatabaseService(dbContext, logger) { - public PlatformService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - } } } diff --git a/LANCommander.Launcher.Services/PlaySessionService.cs b/LANCommander.Launcher.Services/PlaySessionService.cs index 4a36fe50..a7a570d9 100644 --- a/LANCommander.Launcher.Services/PlaySessionService.cs +++ b/LANCommander.Launcher.Services/PlaySessionService.cs @@ -1,21 +1,15 @@ -using JetBrains.Annotations; -using LANCommander.Launcher.Data; +using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class PlaySessionService : BaseDatabaseService + public class PlaySessionService( + ILogger logger, + DatabaseContext dbContext, + SDK.Client client) : BaseDatabaseService(dbContext, logger) { - - public PlaySessionService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) { } - public async Task GetLatestSession(Guid gameId, Guid userId) { return await Query(ps => ps.GameId == gameId && ps.UserId == userId).OrderByDescending(ps => ps.End).FirstOrDefaultAsync(); @@ -38,9 +32,8 @@ namespace LANCommander.Launcher.Services }; await AddAsync(session); - - if (Client.IsConnected()) - await Client.Games.StartedAsync(gameId); + + await client.Games.StartedAsync(gameId); } catch (Exception ex) { @@ -67,7 +60,7 @@ namespace LANCommander.Launcher.Services } finally { - await Client.Games.StoppedAsync(gameId); + await client.Games.StoppedAsync(gameId); } } } diff --git a/LANCommander.Launcher.Services/ProfileService.cs b/LANCommander.Launcher.Services/ProfileService.cs index 7ebbb913..0d34c823 100644 --- a/LANCommander.Launcher.Services/ProfileService.cs +++ b/LANCommander.Launcher.Services/ProfileService.cs @@ -1,13 +1,7 @@ -using JetBrains.Annotations; -using LANCommander.Launcher.Data.Models; +using LANCommander.Launcher.Data.Models; using LANCommander.Launcher.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; using System.Net.Mime; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { @@ -16,6 +10,7 @@ namespace LANCommander.Launcher.Services private readonly AuthenticationService AuthenticationService; private readonly MediaService MediaService; private readonly UserService UserService; + private readonly SDK.Client Client; private Settings Settings; @@ -26,7 +21,7 @@ namespace LANCommander.Launcher.Services ILogger logger, AuthenticationService authenticationService, MediaService mediaService, - UserService userService) : base(client, logger) + UserService userService) : base(logger) { AuthenticationService = authenticationService; MediaService = mediaService; @@ -90,7 +85,7 @@ namespace LANCommander.Launcher.Services FileId = Guid.NewGuid(), Type = SDK.Enums.MediaType.Avatar, MimeType = MediaTypeNames.Image.Png, - Crc32 = SDK.Services.MediaService.CalculateChecksum(tempAvatarPath), + Crc32 = await SDK.Services.MediaService.CalculateChecksumAsync(tempAvatarPath), UserId = remoteProfile.Id, }; diff --git a/LANCommander.Launcher.Services/RedistributableService.cs b/LANCommander.Launcher.Services/RedistributableService.cs index 6be37c12..5ffab087 100644 --- a/LANCommander.Launcher.Services/RedistributableService.cs +++ b/LANCommander.Launcher.Services/RedistributableService.cs @@ -1,18 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class RedistributableService : BaseDatabaseService + public class RedistributableService( + ILogger logger, + DatabaseContext dbContext) : BaseDatabaseService(dbContext, logger) { - public RedistributableService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - } } } diff --git a/LANCommander.Launcher.Services/SaveService.cs b/LANCommander.Launcher.Services/SaveService.cs index c3fbf0b7..6aa53ed9 100644 --- a/LANCommander.Launcher.Services/SaveService.cs +++ b/LANCommander.Launcher.Services/SaveService.cs @@ -1,21 +1,15 @@ -using LANCommander.Launcher.Data.Models; -using LANCommander.SDK.Models; +using LANCommander.SDK.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class SaveService : BaseService + public class SaveService( + ILogger logger, + SDK.Client client) : BaseService(logger) { - public SaveService(SDK.Client client, ILogger saveService) : base(client, saveService) { } - public async Task> Get(Guid gameId) { - var saves = await Client.Saves.GetAsync(gameId); + var saves = await client.Saves.GetAsync(gameId); if (saves == null) saves = new List(); @@ -25,28 +19,28 @@ namespace LANCommander.Launcher.Services public async Task DownloadLatestAsync(string installDirectory, Guid gameId) { - await Client.Saves.DownloadAsync(installDirectory, gameId); + await client.Saves.DownloadAsync(installDirectory, gameId); } public async Task DownloadLatest(string installDirectory, Guid gameId) { - await Client.Saves.DownloadAsync(installDirectory, gameId); + await client.Saves.DownloadAsync(installDirectory, gameId); } public async Task DownloadAsync(string installDirectory, Guid gameId, Guid saveId) { - await Client.Saves.DownloadAsync(installDirectory, gameId, saveId); + await client.Saves.DownloadAsync(installDirectory, gameId, saveId); } public async Task UploadAsync(string installDirectory, Guid gameId) { - await Client.Saves.UploadAsync(installDirectory, gameId); + await client.Saves.UploadAsync(installDirectory, gameId); } public async Task DeleteAsync(Guid saveId) { - await Client.Saves.DeleteAsync(saveId); + await client.Saves.DeleteAsync(saveId); } } } diff --git a/LANCommander.Launcher.Services/TagService.cs b/LANCommander.Launcher.Services/TagService.cs index 9191406d..3e8ee4a0 100644 --- a/LANCommander.Launcher.Services/TagService.cs +++ b/LANCommander.Launcher.Services/TagService.cs @@ -1,18 +1,12 @@ using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class TagService : BaseDatabaseService + public class TagService( + DatabaseContext dbContext, + ILogger logger) : BaseDatabaseService(dbContext, logger) { - public TagService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(dbContext, client, logger) - { - } } } diff --git a/LANCommander.Launcher.Services/UpdateService.cs b/LANCommander.Launcher.Services/UpdateService.cs index 370c01e5..33f03a6d 100644 --- a/LANCommander.Launcher.Services/UpdateService.cs +++ b/LANCommander.Launcher.Services/UpdateService.cs @@ -1,27 +1,22 @@ using LANCommander.SDK.Models; using Microsoft.Extensions.Logging; using Semver; -using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO.Compression; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace LANCommander.Launcher.Services { - public class UpdateService : BaseService + public class UpdateService( + ILogger logger, + SDK.Client client) : BaseService(logger) { public delegate Task OnUpdateAvailableHandler(CheckForUpdateResponse response); public event OnUpdateAvailableHandler OnUpdateAvailable; - public UpdateService(SDK.Client client, ILogger logger) : base(client, logger) { } - public async Task CheckForUpdateAsync() { - var response = await Client.Launcher.CheckForUpdateAsync(); + var response = await client.Launcher.CheckForUpdateAsync(); if (response != null && response.UpdateAvailable) OnUpdateAvailable?.Invoke(response); @@ -37,7 +32,7 @@ namespace LANCommander.Launcher.Services string path = Path.Combine(settings.Updates.StoragePath, $"{version}.zip"); - await Client.Launcher.DownloadAsync(path); + await client.Launcher.DownloadAsync(path); Logger?.LogInformation("Update version {Version} has been downloaded", version); diff --git a/LANCommander.Launcher.Services/UserService.cs b/LANCommander.Launcher.Services/UserService.cs index 3b722ec7..1bd2d3bc 100644 --- a/LANCommander.Launcher.Services/UserService.cs +++ b/LANCommander.Launcher.Services/UserService.cs @@ -5,18 +5,11 @@ using Microsoft.Extensions.Logging; namespace LANCommander.Launcher.Services { - public class UserService : BaseDatabaseService + public class UserService( + ILogger logger, + DatabaseContext dbContext, + AuthenticationService authenticationService) : BaseDatabaseService(dbContext, logger) { - private readonly AuthenticationService AuthenticationService; - public UserService( - DatabaseContext dbContext, - SDK.Client client, - ILogger logger, - AuthenticationService authenticationService) : base(dbContext, client, logger) - { - AuthenticationService = authenticationService; - } - public override async Task GetAsync(Guid id) { return await Context @@ -32,7 +25,7 @@ namespace LANCommander.Launcher.Services .Users .AsQueryable() .Include(u => u.Avatar) - .FirstOrDefaultAsync(u => u.Id == AuthenticationService.GetUserId()); + .FirstOrDefaultAsync(u => u.Id == authenticationService.GetUserId()); } public async Task GetAliasAsync(Guid id) diff --git a/LANCommander.Launcher.Services/_BaseDatabaseService.cs b/LANCommander.Launcher.Services/_BaseDatabaseService.cs index 910db914..c8bc1240 100644 --- a/LANCommander.Launcher.Services/_BaseDatabaseService.cs +++ b/LANCommander.Launcher.Services/_BaseDatabaseService.cs @@ -11,7 +11,7 @@ namespace LANCommander.Launcher.Services { protected DatabaseContext Context { get; set; } - public BaseDatabaseService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(client, logger) + public BaseDatabaseService(DatabaseContext dbContext, ILogger logger) : base(logger) { Context = dbContext; } diff --git a/LANCommander.Launcher.Services/_BaseService.cs b/LANCommander.Launcher.Services/_BaseService.cs index eac4d08f..c9425f05 100644 --- a/LANCommander.Launcher.Services/_BaseService.cs +++ b/LANCommander.Launcher.Services/_BaseService.cs @@ -4,12 +4,10 @@ namespace LANCommander.Launcher.Services { public abstract class BaseService { - protected readonly SDK.Client Client; protected readonly ILogger Logger; - protected BaseService(SDK.Client client, ILogger logger) + protected BaseService(ILogger logger) { - Client = client; Logger = logger; } } diff --git a/LANCommander.Launcher/Program.cs b/LANCommander.Launcher/Program.cs index 2b5f3cb5..d14e8c30 100644 --- a/LANCommander.Launcher/Program.cs +++ b/LANCommander.Launcher/Program.cs @@ -11,6 +11,7 @@ using Serilog.Extensions.Logging; using System.Runtime.InteropServices; using System.Web; using LANCommander.Launcher.Startup; +using LANCommander.SDK.Extensions; namespace LANCommander.Launcher { @@ -54,6 +55,7 @@ namespace LANCommander.Launcher builder.Services.AddCustomWindow(); builder.Services.AddAntDesign(); builder.Services.AddSingleton(); + builder.Services.AddLANCommander(); builder.Services.AddLANCommander(options => { options.ServerAddress = settings.Authentication.ServerAddress; diff --git a/LANCommander.Launcher/Startup/ApplicationSettings.cs b/LANCommander.Launcher/Startup/ApplicationSettings.cs index 90dea41f..555f4588 100644 --- a/LANCommander.Launcher/Startup/ApplicationSettings.cs +++ b/LANCommander.Launcher/Startup/ApplicationSettings.cs @@ -1,5 +1,7 @@ using LANCommander.Launcher.Models; using LANCommander.Launcher.Services; +using LANCommander.SDK.Extensions; +using LANCommander.SDK.Providers; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Photino.Blazor; @@ -29,14 +31,17 @@ public static class ApplicationSettings Log.Debug("Loading settings file"); - var configBuilder = new ConfigurationBuilder() - .AddYamlFile(SettingService.SettingsFile) + IServerConfigurationRefresher refresher; + + var configuration = new ConfigurationBuilder() + .AddLANCommanderConfiguration(out refresher) .Build(); - builder.Services.Configure(configBuilder); + builder.Services.Configure(configuration); + builder.Services.AddSingleton(refresher); settings = new Settings(); - configBuilder.Bind(settings); + configuration.Bind(settings); Log.Debug("Validating settings"); diff --git a/LANCommander.Launcher/Startup/Window.cs b/LANCommander.Launcher/Startup/Window.cs index c68e9bd0..f407119d 100644 --- a/LANCommander.Launcher/Startup/Window.cs +++ b/LANCommander.Launcher/Startup/Window.cs @@ -2,11 +2,15 @@ using System.Configuration; using System.Web; using LANCommander.Launcher.Models; using LANCommander.Launcher.Services; +using LANCommander.Launcher.Services.Extensions; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Photino.Blazor; +using Photino.Blazor.CustomWindow.Extensions; using Photino.NET; using Serilog; +using Serilog.Extensions.Logging; using Services_LocalizationService = LANCommander.Launcher.Services.LocalizationService; namespace LANCommander.Launcher.Startup; @@ -62,6 +66,17 @@ public static class MainWindow return app; } + public static PhotinoBlazorApp RegisterNotificationHandler(this PhotinoBlazorApp app) + { + app.MainWindow.RegisterWebMessageReceivedHandler(async (object sender, string message) => + { + if (message == "notification") + app.MainWindow.SendNotification("Test", "test"); + }); + + return app; + } + public static PhotinoBlazorApp RegisterImportHandler(this PhotinoBlazorApp app) { app.MainWindow.RegisterWebMessageReceivedHandler(async (object sender, string message) => @@ -88,14 +103,28 @@ public static class MainWindow { if (message == "openChat") { - var parent = (PhotinoWindow)sender; + var settings = SettingService.GetSettings(); + var builder = PhotinoBlazorAppBuilder.CreateDefault(); + + builder.RootComponents.Add("app"); + + builder.Services.AddCustomWindow(); + builder.Services.AddAntDesign(); + builder.Services.AddSingleton(); + + builder.Services.AddLANCommander(options => + { + options.ServerAddress = settings.Authentication.ServerAddress; + //options.Logger = new SerilogLoggerFactory(Logger).CreateLogger(); + }); + + var app = builder.Build(); - new PhotinoWindow(parent) - .SetTitle("Chat") - .SetUseOsDefaultSize(true) - .SetUseOsDefaultLocation(true) - .Load("wwwroot/chat.html") - .WaitForClose(); + app.MainWindow + .SetTitle("LANCommander Chat") + .Load("wwwroot/index.html"); + + app.Run(); } }); diff --git a/LANCommander.Launcher/UI/Authenticate/Components/AuthenticationFormState.cs b/LANCommander.Launcher/UI/Authenticate/Components/AuthenticationFormState.cs index 0b1583c5..8e4ae317 100644 --- a/LANCommander.Launcher/UI/Authenticate/Components/AuthenticationFormState.cs +++ b/LANCommander.Launcher/UI/Authenticate/Components/AuthenticationFormState.cs @@ -3,5 +3,5 @@ namespace LANCommander.Launcher.UI.Authenticate.Components; public class AuthenticationFormState { public AuthenticationStage Stage { get; set; } - public string ServerAddress { get; set; } + public Uri ServerAddress { get; set; } } \ No newline at end of file diff --git a/LANCommander.Launcher/UI/Authenticate/Components/LoginForm.razor b/LANCommander.Launcher/UI/Authenticate/Components/LoginForm.razor index 3b64ba18..88ffbd88 100644 --- a/LANCommander.Launcher/UI/Authenticate/Components/LoginForm.razor +++ b/LANCommander.Launcher/UI/Authenticate/Components/LoginForm.razor @@ -69,7 +69,7 @@ @code { - [Parameter] public string ServerAddress { get; set; } + [Parameter] public Uri ServerAddress { get; set; } [Parameter] public EventCallback OnBack { get; set; } [Parameter] public EventCallback OnRegister { get; set; } [Parameter] public IEnumerable Errors { get; set; } = []; @@ -78,7 +78,7 @@ AuthRequest Model = new(); bool Loading = false; - private string? PreviousServerAddress; + private Uri? PreviousServerAddress; AuthenticationProviderDialog AuthenticationProviderDialog; Models.Settings Settings = SettingService.GetSettings(); @@ -87,12 +87,12 @@ { AuthenticationProviders = new(); - await Client.ChangeServerAddressAsync(ServerAddress); + await Client.Connection.UpdateServerAddressAsync(ServerAddress); ClearErrors(); try { - var authenticationProviders = await Client.GetAuthenticationProvidersAsync(); + var authenticationProviders = await Client.Authentication.GetAuthenticationProvidersAsync(); if (authenticationProviders != null && authenticationProviders.Any()) AuthenticationProviders = authenticationProviders.ToList(); @@ -114,9 +114,8 @@ protected override async Task OnParametersSetAsync() { if (ServerAddress != PreviousServerAddress) - { - await Client.ChangeServerAddressAsync(ServerAddress); - } + await Client.Connection.UpdateServerAddressAsync(ServerAddress); + PreviousServerAddress = ServerAddress; } @@ -128,7 +127,7 @@ { ClearErrors(); - await AuthenticationService.Login(Client.GetServerAddress(), Model.UserName, Model.Password); + await AuthenticationService.Login(Client.Connection.GetServerAddress(), Model.UserName, Model.Password); await ImportManagerService.RequestImport(); diff --git a/LANCommander.Launcher/UI/Authenticate/Components/RegistrationForm.razor b/LANCommander.Launcher/UI/Authenticate/Components/RegistrationForm.razor index 7b076e15..44d2cb44 100644 --- a/LANCommander.Launcher/UI/Authenticate/Components/RegistrationForm.razor +++ b/LANCommander.Launcher/UI/Authenticate/Components/RegistrationForm.razor @@ -40,20 +40,20 @@ @code { - [Parameter] public string ServerAddress { get; set; } + [Parameter] public Uri ServerAddress { get; set; } [Parameter] public EventCallback OnBack { get; set; } [Parameter] public IEnumerable Errors { get; set; } = []; RegistrationRequest Model = new(); bool Loading = false; - private string? PreviousServerAddress; + private Uri? PreviousServerAddress; Models.Settings Settings = SettingService.GetSettings(); protected override async Task OnParametersSetAsync() { if (ServerAddress != PreviousServerAddress) - await Client.ChangeServerAddressAsync(ServerAddress); + await Client.Connection.UpdateServerAddressAsync(ServerAddress.ToString()); PreviousServerAddress = ServerAddress; @@ -75,7 +75,7 @@ { ClearErrors(); - await AuthenticationService.Register(Client.GetServerAddress(), Model.UserName, Model.Password, Model.PasswordConfirmation); + await AuthenticationService.Register(Model.UserName, Model.Password, Model.PasswordConfirmation); await ImportManagerService.RequestImport(); @@ -96,25 +96,4 @@ Loading = false; } } - - async Task UseToken(AuthToken token) - { - Settings.Authentication.AccessToken = token.AccessToken; - Settings.Authentication.RefreshToken = token.RefreshToken; - - try - { - await AuthenticationService.Login(ServerAddress, token); - - await ImportManagerService.RequestImport(); - - NavigationManager.NavigateTo("/"); - } - catch (Exception ex) - { - MessageService.Error(ex.Message, 5); - Logger.LogError(ex, ex.Message); - Loading = false; - } - } } \ No newline at end of file diff --git a/LANCommander.Launcher/UI/Authenticate/Components/ServerSelector.razor b/LANCommander.Launcher/UI/Authenticate/Components/ServerSelector.razor index 877a52ac..c7c429ae 100644 --- a/LANCommander.Launcher/UI/Authenticate/Components/ServerSelector.razor +++ b/LANCommander.Launcher/UI/Authenticate/Components/ServerSelector.razor @@ -36,7 +36,7 @@ - + @@ -65,14 +65,14 @@ @code { - [Parameter] public EventCallback OnSelected { get; set; } + [Parameter] public EventCallback OnSelected { get; set; } [Parameter] public bool Connecting { get; set; } = false; bool IsInitializing = false; bool BeaconActive = false; bool OfflineModeAvailable = false; - string ServerAddress = String.Empty; + Uri ServerAddress; AuthRequest Model = new(); List DiscoveredServers = new(); @@ -84,10 +84,7 @@ { IsInitializing = true; - if (Client.IsConfigured()) - { - ServerAddress = Client.GetServerAddress() ?? string.Empty; - } + ServerAddress = Client.Connection.GetServerAddress(); Connecting = true; OfflineModeAvailable = await AuthenticationService.OfflineModeAvailableAsync(); @@ -111,7 +108,7 @@ DiscoveredServers.Add(discoveredServer); } - async Task SelectServer(string serverAddress) + async Task SelectServer(Uri serverAddress) { await Client.Beacon.StopProbeAsync(); diff --git a/LANCommander.Launcher/UI/ChatWindowLayout.razor b/LANCommander.Launcher/UI/ChatWindowLayout.razor new file mode 100644 index 00000000..e3ec60ab --- /dev/null +++ b/LANCommander.Launcher/UI/ChatWindowLayout.razor @@ -0,0 +1,108 @@ +@using Photino.Blazor.CustomWindow.Components +@using ConnectionState = LANCommander.Launcher.Models.ConnectionState +@inherits LayoutComponentBase +@inject ProfileService ProfileService +@inject AuthenticationService AuthenticationService +@inject IMessageService MessageService +@inject NavigationManager NavigationManager +@inject LANCommander.SDK.Client LANCommander +@inject IJSRuntime JS +@inject LocalizationService LocalizationService + + + + + + + + @Body + + + + + + + + + + + + + + + +@code { + Models.Settings Settings = null; + + public bool Connecting; + + public ConnectionState ConnectionState = default!; + + string RandomQuip = ""; + + string[] _crashQuips; + + protected override async Task OnInitializedAsync() + { + Settings = SettingService.GetSettings(); + + var token = new SDK.Models.AuthToken + { + AccessToken = Settings.Authentication.AccessToken, + RefreshToken = Settings.Authentication.RefreshToken + }; + + if (await LANCommander.Authentication.ValidateTokenAsync()) + { + ConnectionState.IsStartup = true; + await AuthenticationService.Login(); + + ConnectionState.IsConnected = true; + ConnectionState.OfflineModeEnabled = false; + ConnectionState.IsStartup = false; + + await InvokeAsync(StateHasChanged); + } + + _crashQuips = new[] + { + LocalizationService.GetString("CrashQuip_YouDied"), + LocalizationService.GetString("CrashQuip_Snake"), + LocalizationService.GetString("CrashQuip_Wasted"), + LocalizationService.GetString("CrashQuip_MajorFracture"), + LocalizationService.GetString("CrashQuip_PastIsGapingHole"), + LocalizationService.GetString("CrashQuip_TownCenterDestroyed"), + LocalizationService.GetString("CrashQuip_ForcesUnderAttack"), + LocalizationService.GetString("CrashQuip_LostLead"), + LocalizationService.GetString("CrashQuip_TerroristsWin"), + LocalizationService.GetString("CrashQuip_WarNeverChanges"), + LocalizationService.GetString("CrashQuip_DiedOfDysentery"), + LocalizationService.GetString("CrashQuip_FailedToRestoreBooks"), + LocalizationService.GetString("CrashQuip_PlayerSplattered"), + LocalizationService.GetString("CrashQuip_BlameISP"), + LocalizationService.GetString("CrashQuip_BabaNoMore"), + LocalizationService.GetString("CrashQuip_GuestsLost"), + LocalizationService.GetString("CrashQuip_DarknessOvercome"), + LocalizationService.GetString("CrashQuip_GordonFreemanTerminated"), + LocalizationService.GetString("CrashQuip_MissionFailedSpotted"), + LocalizationService.GetString("CrashQuip_CriticalDamageEject"), + LocalizationService.GetString("CrashQuip_MinionsUnhappy"), + LocalizationService.GetString("CrashQuip_EmpireTriumphed"), + LocalizationService.GetString("CrashQuip_QuestEndedFailure"), + LocalizationService.GetString("CrashQuip_EatenByGrue"), + LocalizationService.GetString("CrashQuip_NoMessWithLoWang"), + LocalizationService.GetString("CrashQuip_SamKilled"), + LocalizationService.GetString("CrashQuip_AlienBastardsPay") + }; + + var randIndex = new Random().Next(0, _crashQuips.Length - 1); + RandomQuip = _crashQuips[randIndex]; + } + + async Task CopyError(Exception ex) + { + await JS.InvokeVoidAsync("navigator.clipboard.writeText", ex.Message + "\n" + ex.StackTrace); + + MessageService.Info(LocalizationService.GetString("ErrorCopiedToClipboard")); + } +} \ No newline at end of file diff --git a/LANCommander.Launcher/UI/ChatWindowLayout.razor.css b/LANCommander.Launcher/UI/ChatWindowLayout.razor.css new file mode 100644 index 00000000..85211458 --- /dev/null +++ b/LANCommander.Launcher/UI/ChatWindowLayout.razor.css @@ -0,0 +1,77 @@ +.page { + position: relative; + display: flex; + flex-direction: column; +} + +main { + flex: 1; +} + +.sidebar { + background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); +} + +.top-row { + background-color: #f7f7f7; + border-bottom: 1px solid #d6d5d5; + justify-content: flex-end; + height: 3.5rem; + display: flex; + align-items: center; +} + + .top-row ::deep a, .top-row ::deep .btn-link { + white-space: nowrap; + margin-left: 1.5rem; + text-decoration: none; + } + + .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { + text-decoration: underline; + } + + .top-row ::deep a:first-child { + overflow: hidden; + text-overflow: ellipsis; + } + +@media (max-width: 640.98px) { + .top-row { + justify-content: space-between; + } + + .top-row ::deep a, .top-row ::deep .btn-link { + margin-left: 0; + } +} + +@media (min-width: 641px) { + .page { + flex-direction: row; + } + + .sidebar { + width: 250px; + height: 100vh; + position: sticky; + top: 0; + } + + .top-row { + position: sticky; + top: 0; + z-index: 1; + } + + .top-row.auth ::deep a:first-child { + flex: 1; + text-align: right; + width: 0; + } + + .top-row, article { + padding-left: 2rem !important; + padding-right: 1.5rem !important; + } +} diff --git a/LANCommander.Launcher/UI/Components/AuthenticationForm.razor b/LANCommander.Launcher/UI/Components/AuthenticationForm.razor index 7eb3c065..28628637 100644 --- a/LANCommander.Launcher/UI/Components/AuthenticationForm.razor +++ b/LANCommander.Launcher/UI/Components/AuthenticationForm.razor @@ -53,7 +53,7 @@ State = new() { Stage = AuthenticationStage.None, - ServerAddress = AuthenticationService.GetServerAddress(), + ServerAddress = Client.Connection.GetServerAddress(), }; bool hasServer = await AuthenticationService.IsServerOnlineAsync(); @@ -72,14 +72,14 @@ } } - async Task ServerSelected(string serverAddress) + async Task ServerSelected(Uri serverAddress) { try { _connecting = true; - await Client.ChangeServerAddressAsync(serverAddress); - State.ServerAddress = Client.GetServerAddress(); + await Client.Connection.UpdateServerAddressAsync(serverAddress); + State.ServerAddress = Client.Connection.GetServerAddress(); State.Stage = AuthenticationStage.Login; } catch (Exception ex) diff --git a/LANCommander.Launcher/UI/Components/AuthenticationProviderDialog.razor b/LANCommander.Launcher/UI/Components/AuthenticationProviderDialog.razor index 58f3b3ac..7ffb28f4 100644 --- a/LANCommander.Launcher/UI/Components/AuthenticationProviderDialog.razor +++ b/LANCommander.Launcher/UI/Components/AuthenticationProviderDialog.razor @@ -2,7 +2,6 @@ @using Newtonsoft.Json @using Photino.NET @inject SDK.Client Client -@inject IJSRuntime JSRuntime @inject IMessageService MessageService @inject ILogger Logger @inject LocalizationService LocalizationService @@ -10,15 +9,15 @@ @code { [Parameter] public EventCallback OnTokenReceived { get; set; } - string AuthenticationProviderLoginUrl; + Uri AuthenticationProviderLoginUrl; PhotinoWindow Window; - public async Task Open(string baseUrl, AuthenticationProvider authenticationProvider) + public async Task Open(Uri baseUrl, AuthenticationProvider authenticationProvider) { - await Client.ChangeServerAddressAsync(baseUrl); + await Client.Connection.UpdateServerAddressAsync(baseUrl); - AuthenticationProviderLoginUrl = Client.GetAuthenticationProviderLoginUrl(authenticationProvider.Slug); + AuthenticationProviderLoginUrl = Client.Authentication.GetAuthenticationProviderLoginUrl(authenticationProvider.Slug); Window = new PhotinoWindow() .SetTitle(LocalizationService.GetString("SignInUsingProvider", authenticationProvider.Name)) diff --git a/LANCommander.Launcher/UI/Components/Footer.razor b/LANCommander.Launcher/UI/Components/Footer.razor index 8942bd77..27053593 100644 --- a/LANCommander.Launcher/UI/Components/Footer.razor +++ b/LANCommander.Launcher/UI/Components/Footer.razor @@ -1,10 +1,14 @@ @using LANCommander.Launcher.Models +@using Settings = LANCommander.SDK.Models.Settings +@using Microsoft.Extensions.Options @using System.Diagnostics @inject SDK.Client Client @inject InstallService InstallService @inject GameService GameService +@inject IOptions Settings @inject NavigationManager NavigationManager @inject LocalizationService LocalizationService +@inject IJSRuntime JS
@@ -14,7 +18,7 @@ } else { - if (Client.Settings?.EnableUserLibraries ?? false) + if (true) { @@ -51,9 +55,7 @@
- - - +
@@ -78,4 +80,9 @@ { await DownloadQueue.Show(); } + + async Task OpenChatWindow() + { + await JS.InvokeVoidAsync("window.external.sendMessage", "openChat"); + } } diff --git a/LANCommander.Launcher/UI/Components/LibraryItemContextMenu.razor b/LANCommander.Launcher/UI/Components/LibraryItemContextMenu.razor index a5d8ae40..7fc5637a 100644 --- a/LANCommander.Launcher/UI/Components/LibraryItemContextMenu.razor +++ b/LANCommander.Launcher/UI/Components/LibraryItemContextMenu.razor @@ -309,7 +309,7 @@ else foreach (var manifest in manifests) { - var key = Client.Games.GetAllocatedKey(manifest.Id); + var key = await Client.Games.GetAllocatedKeyAsync(manifest.Id); await Client.Scripts.RunKeyChangeScriptAsync(Game.InstallDirectory, Game.Id, key); } diff --git a/LANCommander.Launcher/UI/Components/ProfileButton.razor b/LANCommander.Launcher/UI/Components/ProfileButton.razor index 2cdd10bf..971afd3b 100644 --- a/LANCommander.Launcher/UI/Components/ProfileButton.razor +++ b/LANCommander.Launcher/UI/Components/ProfileButton.razor @@ -103,9 +103,9 @@ NavigationManager.NavigateTo("/Authenticate"); } - void SwitchToOfflineMode() + async Task SwitchToOfflineMode() { - AuthenticationService.SetOfflineMode(true); + await AuthenticationService.SetOfflineModeAsync(true); NavigationManager.NavigateTo("/", forceLoad: true); } diff --git a/LANCommander.Launcher/UI/Depot/Components/DepotGameDetails.razor b/LANCommander.Launcher/UI/Depot/Components/DepotGameDetails.razor index 35c5fad3..7f185d10 100644 --- a/LANCommander.Launcher/UI/Depot/Components/DepotGameDetails.razor +++ b/LANCommander.Launcher/UI/Depot/Components/DepotGameDetails.razor @@ -66,7 +66,7 @@ } - @if (!IsInstalled && Client.IsConnected()) + @if (!IsInstalled && Client.Connection.IsConnected()) { diff --git a/LANCommander.Launcher/UI/MainLayout.razor b/LANCommander.Launcher/UI/MainLayout.razor index bfcfb1f8..1b8b227a 100644 --- a/LANCommander.Launcher/UI/MainLayout.razor +++ b/LANCommander.Launcher/UI/MainLayout.razor @@ -128,7 +128,7 @@ RefreshToken = Settings.Authentication.RefreshToken }; - if (await LANCommander.ValidateTokenAsync(token)) + if (await LANCommander.Authentication.ValidateTokenAsync()) { ConnectionState.IsStartup = true; await AuthenticationService.Login(); @@ -188,7 +188,7 @@ async void OnOfflineModeChanged(bool state) { ConnectionState.OfflineModeEnabled = state; - ConnectionState.IsConnected = LANCommander.IsConnected(); + ConnectionState.IsConnected = LANCommander.Connection.IsConnected(); await InvokeAsync(StateHasChanged); } @@ -217,7 +217,7 @@ RefreshToken = Settings.Authentication.RefreshToken }; - if (await LANCommander.ValidateTokenAsync(token)) + if (await LANCommander.Authentication.ValidateTokenAsync()) { await AuthenticationService.Login(); await ProfileService.DownloadProfileInfoAsync(); @@ -231,7 +231,7 @@ } else { - if (await LANCommander.PingAsync()) + if (await LANCommander.Connection.PingAsync()) { await Logout(); } diff --git a/LANCommander.Launcher/UI/Settings/Index.razor b/LANCommander.Launcher/UI/Settings/Index.razor index 9a8507b3..c80378fd 100644 --- a/LANCommander.Launcher/UI/Settings/Index.razor +++ b/LANCommander.Launcher/UI/Settings/Index.razor @@ -118,7 +118,7 @@ SettingService.SaveSettings(_settings); - Client.DefaultInstallDirectory = _settings.Games.InstallDirectories.First(); + // Client.DefaultInstallDirectory = _settings.Games.InstallDirectories.First(); Client.Scripts.Debug = _settings.Debug.EnableScriptDebugging; MessageService.Success(LocalizationService.GetString("SettingsSaved")); diff --git a/LANCommander.Launcher/wwwroot/css/main.js b/LANCommander.Launcher/wwwroot/css/main.js new file mode 100644 index 00000000..e69de29b diff --git a/LANCommander.SDK.Tests/SaveService.cs b/LANCommander.SDK.Tests/SaveService.cs index 57dabd1f..3a043f15 100644 --- a/LANCommander.SDK.Tests/SaveService.cs +++ b/LANCommander.SDK.Tests/SaveService.cs @@ -3,12 +3,12 @@ using System.Management.Automation.Language; namespace LANCommander.SDK.Tests { - public class SaveServiceTests + public class SaveClientTests { Guid SaveId; Client Client; - public SaveServiceTests() { + public SaveClientTests() { Client = new Client("http://localhost:1337", "C:\\Games"); } diff --git a/LANCommander.SDK/Client.cs b/LANCommander.SDK/Client.cs new file mode 100644 index 00000000..788dee4c --- /dev/null +++ b/LANCommander.SDK/Client.cs @@ -0,0 +1,43 @@ +using LANCommander.SDK.Services; + +namespace LANCommander.SDK; + +public class Client( + AuthenticationClient authenticationClient, + BeaconClient beaconClient, + ChatClient chatClient, + IConnectionClient connectionClient, + DepotClient depotClient, + GameClient gameClient, + IssueClient issueClient, + LauncherClient launcherClient, + LibraryClient libraryClient, + LobbyClient lobbyClient, + MediaService mediaClient, + PlaySessionClient playSessionClient, + ProfileClient profileClient, + RedistributableClient redistributableClient, + SaveClient saveClient, + ScriptClient scriptClient, + ServerClient serverClient, + TagClient tagClient) +{ + public AuthenticationClient Authentication = authenticationClient; + public BeaconClient Beacon = beaconClient; + public ChatClient Chat = chatClient; + public IConnectionClient Connection = connectionClient; + public DepotClient Depot = depotClient; + public GameClient Games = gameClient; + public IssueClient Issues = issueClient; + public LauncherClient Launcher = launcherClient; + public LibraryClient Library = libraryClient; + public LobbyClient Lobbies = lobbyClient; + public MediaService Media = mediaClient; + public PlaySessionClient PlaySessions = playSessionClient; + public ProfileClient Profile = profileClient; + public RedistributableClient Redistributables = redistributableClient; + public SaveClient Saves = saveClient; + public ScriptClient Scripts = scriptClient; + public ServerClient Servers = serverClient; + public TagClient Tags = tagClient; +} \ No newline at end of file diff --git a/LANCommander.SDK/Extensions/IConfigurationBuilderExtensions.cs b/LANCommander.SDK/Extensions/IConfigurationBuilderExtensions.cs new file mode 100644 index 00000000..81a44e72 --- /dev/null +++ b/LANCommander.SDK/Extensions/IConfigurationBuilderExtensions.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using LANCommander.SDK.Models; +using LANCommander.SDK.Providers; +using Microsoft.Extensions.Configuration; + +namespace LANCommander.SDK.Extensions; + +public static class IConfigurationBuilderExtensions +{ + public static IConfigurationBuilder AddLANCommanderConfiguration( + this IConfigurationBuilder configurationBuilder, + out IServerConfigurationRefresher refresher) + { + var bootstrap = new ConfigurationBuilder() + .AddYamlFile(Settings.SETTINGS_FILE_NAME) + .Build(); + + return configurationBuilder + .AddConfiguration(bootstrap) + .AddServerConfiguration(bootstrap, out refresher); + } + + public static IConfigurationBuilder AddServerConfiguration( + this IConfigurationBuilder configurationBuilder, + IConfiguration configuration, + out IServerConfigurationRefresher refresher) + { + var src = new ServerConfigurationSource + { + Configuration = configuration, + }; + + configurationBuilder.Add(src); + + refresher = new LazyRefresher(() => src.Provider); + + return configurationBuilder; + } + + private sealed class LazyRefresher(Func getProvider) : IServerConfigurationRefresher + { + private readonly Func _getProvider = getProvider; + + public async Task RefreshAsync(CancellationToken cancellationToken = default) + { + var provider = _getProvider() ?? + throw new InvalidOperationException("Server configuration provider is not yet built"); + + await provider.RefreshAsync(cancellationToken); + } + } +} \ No newline at end of file diff --git a/LANCommander.SDK/Extensions/IServiceCollectionExtensions.cs b/LANCommander.SDK/Extensions/IServiceCollectionExtensions.cs index be67d860..38cb0061 100644 --- a/LANCommander.SDK/Extensions/IServiceCollectionExtensions.cs +++ b/LANCommander.SDK/Extensions/IServiceCollectionExtensions.cs @@ -2,6 +2,8 @@ using LANCommander.SDK.Abstractions; using LANCommander.SDK.Configuration; using LANCommander.SDK.Factories; using LANCommander.SDK.Providers; +using LANCommander.SDK.Rpc; +using LANCommander.SDK.Rpc.Client; using LANCommander.SDK.Services; using Microsoft.Extensions.DependencyInjection; @@ -14,26 +16,30 @@ public static class IServiceCollectionExtensions services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); - services.AddSingleton(); - services.AddScoped(); - services.AddSingleton(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + services.AddScoped(); return services; } diff --git a/LANCommander.SDK/Factories/ProcessExecutionContextFactory.cs b/LANCommander.SDK/Factories/ProcessExecutionContextFactory.cs index bf387530..b5925266 100644 --- a/LANCommander.SDK/Factories/ProcessExecutionContextFactory.cs +++ b/LANCommander.SDK/Factories/ProcessExecutionContextFactory.cs @@ -11,6 +11,6 @@ public class ProcessExecutionContextFactory(IServiceProvider serviceProvider) { return new ProcessExecutionContext( serviceProvider.GetService>(), - serviceProvider.GetService()); + serviceProvider.GetService()); } } \ No newline at end of file diff --git a/LANCommander.SDK/Helpers/ApiRequestBuilder.cs b/LANCommander.SDK/Helpers/ApiRequestBuilder.cs index 06b152f0..562dcd07 100644 --- a/LANCommander.SDK/Helpers/ApiRequestBuilder.cs +++ b/LANCommander.SDK/Helpers/ApiRequestBuilder.cs @@ -1,20 +1,13 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.IO; -using System.Net; using System.Net.Http; using System.Net.Http.Headers; -using System.Net.Mime; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using LANCommander.SDK.Abstractions; using LANCommander.SDK.Extensions; using LANCommander.SDK.Models; -using LANCommander.SDK.Providers; -using RestSharp; -using RestSharp.Interceptors; using Action = System.Action; namespace LANCommander.SDK.Helpers; diff --git a/LANCommander.SDK/Helpers/ManifestHelper.cs b/LANCommander.SDK/Helpers/ManifestHelper.cs index 68097634..ada595ad 100644 --- a/LANCommander.SDK/Helpers/ManifestHelper.cs +++ b/LANCommander.SDK/Helpers/ManifestHelper.cs @@ -165,7 +165,7 @@ namespace LANCommander.SDK.Helpers public static string GetPath(string installDirectory, Guid id) { - return GameService.GetMetadataFilePath(installDirectory, id, ManifestFilename); + return GameClient.GetMetadataFilePath(installDirectory, id, ManifestFilename); } } } diff --git a/LANCommander.SDK/LANCommander.SDK.csproj b/LANCommander.SDK/LANCommander.SDK.csproj index 89a91ebf..a976349b 100644 --- a/LANCommander.SDK/LANCommander.SDK.csproj +++ b/LANCommander.SDK/LANCommander.SDK.csproj @@ -22,12 +22,16 @@ + + + - + + diff --git a/LANCommander.SDK/Models/Settings.cs b/LANCommander.SDK/Models/Settings.cs deleted file mode 100644 index cfe3afce..00000000 --- a/LANCommander.SDK/Models/Settings.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace LANCommander.SDK.Models -{ - public class Settings - { - public int IPXRelayPort { get; set; } - public string IPXRelayHost { get; set; } - public bool EnableUserLibraries { get; set; } - } -} diff --git a/LANCommander.SDK/Models/Settings/AuthenticationSettings.cs b/LANCommander.SDK/Models/Settings/AuthenticationSettings.cs new file mode 100644 index 00000000..e53d4a50 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/AuthenticationSettings.cs @@ -0,0 +1,10 @@ +using System; + +namespace LANCommander.SDK.Models; + +public class AuthenticationSettings : IAuthenticationSettings +{ + public Uri ServerAddress { get; set; } + public string Token { get; set; } + public bool OfflineModeEnabled { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/DebugSettings.cs b/LANCommander.SDK/Models/Settings/DebugSettings.cs new file mode 100644 index 00000000..dad59585 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/DebugSettings.cs @@ -0,0 +1,13 @@ +using Microsoft.Extensions.Logging; +using Serilog; + +namespace LANCommander.SDK.Models; + +public class DebugSettings : IDebugSettings +{ + public bool EnableScriptDebugging { get; set; } = false; + public LogLevel LogLevel { get; set; } = LogLevel.Warning; + public string LoggingPath { get; set; } = "Logs"; + public RollingInterval LoggingArchivePeriod { get; set; } = RollingInterval.Day; + public int MaxArchiveFiles { get; set; } = 10; +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/GameSettings.cs b/LANCommander.SDK/Models/Settings/GameSettings.cs new file mode 100644 index 00000000..2a996047 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/GameSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public class GameSettings : IGameSettings +{ + public string[] InstallDirectories { get; set; } = []; +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IAuthenticationSettings.cs b/LANCommander.SDK/Models/Settings/IAuthenticationSettings.cs new file mode 100644 index 00000000..5832390b --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IAuthenticationSettings.cs @@ -0,0 +1,10 @@ +using System; + +namespace LANCommander.SDK.Models; + +public interface IAuthenticationSettings +{ + public Uri ServerAddress { get; set; } + public string Token { get; set; } + public bool OfflineModeEnabled { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IDebugSettings.cs b/LANCommander.SDK/Models/Settings/IDebugSettings.cs new file mode 100644 index 00000000..28ac8a2a --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IDebugSettings.cs @@ -0,0 +1,13 @@ +using Microsoft.Extensions.Logging; +using Serilog; + +namespace LANCommander.SDK.Models; + +public interface IDebugSettings +{ + public bool EnableScriptDebugging { get; set; } + public LogLevel LogLevel { get; set; } + public string LoggingPath { get; set; } + public RollingInterval LoggingArchivePeriod { get; set; } + public int MaxArchiveFiles { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IGameSettings.cs b/LANCommander.SDK/Models/Settings/IGameSettings.cs new file mode 100644 index 00000000..043a3c06 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IGameSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public interface IGameSettings +{ + public string[] InstallDirectories { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IIPXRelaySettings.cs b/LANCommander.SDK/Models/Settings/IIPXRelaySettings.cs new file mode 100644 index 00000000..ace7a607 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IIPXRelaySettings.cs @@ -0,0 +1,7 @@ +namespace LANCommander.SDK.Models; + +public interface IIPXRelaySettings +{ + public int Port { get; set; } + public string Host { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/ILibrarySettings.cs b/LANCommander.SDK/Models/Settings/ILibrarySettings.cs new file mode 100644 index 00000000..ea7550e2 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/ILibrarySettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public interface ILibrarySettings +{ + public bool EnableUserLibraries { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IMediaSettings.cs b/LANCommander.SDK/Models/Settings/IMediaSettings.cs new file mode 100644 index 00000000..c7b7f96f --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IMediaSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public interface IMediaSettings +{ + public string StoragePath { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IPXRelaySettings.cs b/LANCommander.SDK/Models/Settings/IPXRelaySettings.cs new file mode 100644 index 00000000..a5d48347 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IPXRelaySettings.cs @@ -0,0 +1,7 @@ +namespace LANCommander.SDK.Models; + +public class IPXRelaySettings : IIPXRelaySettings +{ + public int Port { get; set; } + public string Host { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/ISettings.cs b/LANCommander.SDK/Models/Settings/ISettings.cs new file mode 100644 index 00000000..e3a6e49e --- /dev/null +++ b/LANCommander.SDK/Models/Settings/ISettings.cs @@ -0,0 +1,10 @@ +namespace LANCommander.SDK.Models; + +public interface ISettings +{ + public AuthenticationSettings Authentication { get; set; } + public GameSettings Games { get; set; } + public MediaSettings Media { get; set; } + public DebugSettings Debug { get; set; } + public UpdateSettings Updates { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/IUpdateSettings.cs b/LANCommander.SDK/Models/Settings/IUpdateSettings.cs new file mode 100644 index 00000000..7c97434a --- /dev/null +++ b/LANCommander.SDK/Models/Settings/IUpdateSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public interface IUpdateSettings +{ + public string StoragePath { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/LibrarySettings.cs b/LANCommander.SDK/Models/Settings/LibrarySettings.cs new file mode 100644 index 00000000..b9dab6e0 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/LibrarySettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public class LibrarySettings : ILibrarySettings +{ + public bool EnableUserLibraries { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/MediaSettings.cs b/LANCommander.SDK/Models/Settings/MediaSettings.cs new file mode 100644 index 00000000..16b010cd --- /dev/null +++ b/LANCommander.SDK/Models/Settings/MediaSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public class MediaSettings : IMediaSettings +{ + public string StoragePath { get; set; } = "Media"; +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/Settings.cs b/LANCommander.SDK/Models/Settings/Settings.cs new file mode 100644 index 00000000..dca8e915 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/Settings.cs @@ -0,0 +1,13 @@ +namespace LANCommander.SDK.Models; + +public class Settings : ISettings +{ + public const string DEFAULT_GAME_USERNAME = "Player"; + public const string SETTINGS_FILE_NAME = "Settings.yml"; + + public AuthenticationSettings Authentication { get; set; } + public GameSettings Games { get; set; } + public MediaSettings Media { get; set; } + public DebugSettings Debug { get; set; } + public UpdateSettings Updates { get; set; } +} \ No newline at end of file diff --git a/LANCommander.SDK/Models/Settings/UpdateSettings.cs b/LANCommander.SDK/Models/Settings/UpdateSettings.cs new file mode 100644 index 00000000..7d6b5394 --- /dev/null +++ b/LANCommander.SDK/Models/Settings/UpdateSettings.cs @@ -0,0 +1,6 @@ +namespace LANCommander.SDK.Models; + +public class UpdateSettings : IUpdateSettings +{ + public string StoragePath { get; set; } = "Updates"; +} \ No newline at end of file diff --git a/LANCommander.SDK/PowerShell/Cmdlets/Get-UserCustomField.cs b/LANCommander.SDK/PowerShell/Cmdlets/Get-UserCustomField.cs index 2a239d7a..1a971089 100644 --- a/LANCommander.SDK/PowerShell/Cmdlets/Get-UserCustomField.cs +++ b/LANCommander.SDK/PowerShell/Cmdlets/Get-UserCustomField.cs @@ -8,14 +8,14 @@ namespace LANCommander.SDK.PowerShell.Cmdlets { [Cmdlet(VerbsCommon.Get, "UserCustomField")] [OutputType(typeof(string))] - public class GetUserCustomFieldCmdlet(ProfileService profileService) : BaseCmdlet + public class GetUserCustomFieldCmdlet(ProfileClient profileClient) : BaseCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Name { get; set; } protected override void ProcessRecord() { - var result = profileService.GetCustomFieldAsync(Name).GetAwaiter().GetResult(); + var result = profileClient.GetCustomFieldAsync(Name).GetAwaiter().GetResult(); WriteObject(result); } diff --git a/LANCommander.SDK/PowerShell/Cmdlets/Out-PlayerAvatar.cs b/LANCommander.SDK/PowerShell/Cmdlets/Out-PlayerAvatar.cs index 3ef3fb2f..91348d3a 100644 --- a/LANCommander.SDK/PowerShell/Cmdlets/Out-PlayerAvatar.cs +++ b/LANCommander.SDK/PowerShell/Cmdlets/Out-PlayerAvatar.cs @@ -5,11 +5,11 @@ namespace LANCommander.SDK.PowerShell.Cmdlets { [Cmdlet(VerbsData.Out, "PlayerAvatar")] [OutputType(typeof(string))] - public class OutPlayerAvatarCmdlet(ProfileService profileService) : BaseCmdlet + public class OutPlayerAvatarCmdlet(ProfileClient profileClient) : BaseCmdlet { protected override void ProcessRecord() { - var result = profileService.GetAvatarAsync().GetAwaiter().GetResult(); + var result = profileClient.GetAvatarAsync().GetAwaiter().GetResult(); WriteObject(result, false); } diff --git a/LANCommander.SDK/PowerShell/Cmdlets/Update-UserCustomField.cs b/LANCommander.SDK/PowerShell/Cmdlets/Update-UserCustomField.cs index eb3ab062..bd93f5f9 100644 --- a/LANCommander.SDK/PowerShell/Cmdlets/Update-UserCustomField.cs +++ b/LANCommander.SDK/PowerShell/Cmdlets/Update-UserCustomField.cs @@ -5,7 +5,7 @@ namespace LANCommander.SDK.PowerShell.Cmdlets { [Cmdlet(VerbsData.Update, "UserCustomField")] [OutputType(typeof(string))] - public class UpdateUserCustomFieldCmdlet(ProfileService profileService) : BaseCmdlet + public class UpdateUserCustomFieldCmdlet(ProfileClient profileClient) : BaseCmdlet { [Parameter(Mandatory = true, Position = 0)] public string Name { get; set; } @@ -15,7 +15,7 @@ namespace LANCommander.SDK.PowerShell.Cmdlets protected override void ProcessRecord() { - var result = profileService.UpdateCustomFieldAsync(Name, Value).GetAwaiter().GetResult(); + var result = profileClient.UpdateCustomFieldAsync(Name, Value).GetAwaiter().GetResult(); WriteObject(result); } diff --git a/LANCommander.SDK/ProcessExecutionContext.cs b/LANCommander.SDK/ProcessExecutionContext.cs index 652456e5..3cfb3d75 100644 --- a/LANCommander.SDK/ProcessExecutionContext.cs +++ b/LANCommander.SDK/ProcessExecutionContext.cs @@ -14,7 +14,7 @@ namespace LANCommander.SDK { public class ProcessExecutionContext( ILogger logger, - LobbyService lobbyService) : IDisposable + LobbyClient lobbyClient) : IDisposable { private Process Process; @@ -209,7 +209,7 @@ namespace LANCommander.SDK } catch { } - lobbyService.ReleaseSteam(); + lobbyClient.ReleaseSteam(); } } } diff --git a/LANCommander.SDK/Providers/AuthenticationProvider.cs b/LANCommander.SDK/Providers/AuthenticationProvider.cs new file mode 100644 index 00000000..6f5e5d58 --- /dev/null +++ b/LANCommander.SDK/Providers/AuthenticationProvider.cs @@ -0,0 +1,13 @@ +using LANCommander.SDK.Models; + +namespace LANCommander.SDK.Providers; + +public class AuthenticationProvider +{ + private AuthToken _token { get; set; } + + public AuthToken GetToken() + { + return _token; + } +} \ No newline at end of file diff --git a/LANCommander.SDK/Providers/ServerConfigurationProvider.cs b/LANCommander.SDK/Providers/ServerConfigurationProvider.cs new file mode 100644 index 00000000..59868e2b --- /dev/null +++ b/LANCommander.SDK/Providers/ServerConfigurationProvider.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using LANCommander.SDK.Models; +using Microsoft.Extensions.Configuration; + +namespace LANCommander.SDK.Providers; + +public interface IServerConfigurationRefresher +{ + Task RefreshAsync(CancellationToken cancellationToken = default); +} + +public sealed class ServerConfigurationSource : IConfigurationSource +{ + public required IConfiguration Configuration { get; set; } + + internal ServerConfigurationProvider? Provider { get; set; } + + public IConfigurationProvider Build(IConfigurationBuilder builder) => Provider = new ServerConfigurationProvider(this); +} + +public sealed class ServerConfigurationProvider : ConfigurationProvider +{ + private readonly ServerConfigurationSource _source; + private readonly HttpClient _httpClient; + + public ServerConfigurationProvider(ServerConfigurationSource source) + { + var settings = new Settings(); + + _source = source; + _source.Configuration.Bind(settings); + + _httpClient = new HttpClient + { + BaseAddress = settings.Authentication.ServerAddress + }; + } + + public override void Load() => RefreshAsync().GetAwaiter().GetResult(); + + public async Task RefreshAsync(CancellationToken cancellationToken = default) + { + try + { + var response = await _httpClient.GetAsync("/api/Settings", cancellationToken); + + response.EnsureSuccessStatusCode(); + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + var payload = await JsonNode.ParseAsync(stream, cancellationToken: cancellationToken) ?? new JsonObject(); + + var prefix = ""; + var data = new Dictionary(StringComparer.OrdinalIgnoreCase); + + void Walk(JsonNode? node, string keyPrefix) + { + switch (node) + { + case JsonObject obj: + foreach (var kvp in obj) + Walk(kvp.Value, keyPrefix + kvp.Key + ":"); + break; + + case JsonArray array: + for (int i = 0; i < array.Count; i++) + Walk(array[i], keyPrefix + i + ":"); + break; + + default: + data[keyPrefix.TrimEnd(':')] = node?.ToJsonString(); + break; + } + } + + Walk(payload, prefix); + Data = data; + OnReload(); + } + catch (Exception ex) + { + + } + } +} \ No newline at end of file diff --git a/LANCommander.SDK/Providers/SettingsProvider.cs b/LANCommander.SDK/Providers/SettingsProvider.cs new file mode 100644 index 00000000..746befcc --- /dev/null +++ b/LANCommander.SDK/Providers/SettingsProvider.cs @@ -0,0 +1,20 @@ +using System.Threading.Tasks; +using LANCommander.SDK.Factories; +using LANCommander.SDK.Models; + +namespace LANCommander.SDK.Providers; + +public class SettingsProvider(ApiRequestFactory apiRequestFactory) +{ + private ISettings _settings; + + public ISettings GetSettings() + { + return _settings; + } + + public async Task LoadSettingsAsync() + { + + } +} \ No newline at end of file diff --git a/LANCommander.SDK/Rpc/Chat.cs b/LANCommander.SDK/Rpc/Chat.cs index 1f47aa73..f8f715ad 100644 --- a/LANCommander.SDK/Rpc/Chat.cs +++ b/LANCommander.SDK/Rpc/Chat.cs @@ -8,30 +8,30 @@ namespace LANCommander.SDK.Rpc; public partial class RpcClient { - private readonly ChatService _chatService = serviceProvider.GetService(); + private readonly ChatClient _chatClient = serviceProvider.GetService(); public async Task Chat_AddedToThreadAsync(ChatThread thread) { - await _chatService.AddedToThreadAsync(thread); + await _chatClient.AddedToThreadAsync(thread); } public async Task Chat_ReceiveMessagesAsync(Guid threadId, ChatMessage[] messages) { - await _chatService.ReceiveMessagesAsync(threadId, messages); + await _chatClient.ReceiveMessagesAsync(threadId, messages); } public async Task Chat_ReceiveMessageAsync(Guid threadId, ChatMessage message) { - await _chatService.ReceiveMessageAsync(threadId, message); + await _chatClient.ReceiveMessageAsync(threadId, message); } public async Task Chat_StartTyping(Guid threadId, string userIdentifier) { - await _chatService.StartTypingAsync(threadId, userIdentifier); + await _chatClient.StartTypingAsync(threadId, userIdentifier); } public async Task Chat_StopTyping(Guid threadId, string userIdentifier) { - await _chatService.StopTypingAsync(threadId, userIdentifier); + await _chatClient.StopTypingAsync(threadId, userIdentifier); } } \ No newline at end of file diff --git a/LANCommander.SDK/Rpc/Interfaces/Client/_IRpcClient.cs b/LANCommander.SDK/Rpc/Interfaces/Client/_IRpcClient.cs index 2c8a900b..b09227b3 100644 --- a/LANCommander.SDK/Rpc/Interfaces/Client/_IRpcClient.cs +++ b/LANCommander.SDK/Rpc/Interfaces/Client/_IRpcClient.cs @@ -5,7 +5,6 @@ namespace LANCommander.SDK.Rpc.Client; public partial interface IRpcClient { - public IRpcHub Server { get; set; } public Task ConnectAsync(); public Task DisconnectAsync(); } \ No newline at end of file diff --git a/LANCommander.SDK/Rpc/RpcClient.cs b/LANCommander.SDK/Rpc/RpcClient.cs index 18b35d92..5bc6259f 100644 --- a/LANCommander.SDK/Rpc/RpcClient.cs +++ b/LANCommander.SDK/Rpc/RpcClient.cs @@ -12,7 +12,7 @@ namespace LANCommander.SDK.Rpc; public partial class RpcClient(IServiceProvider serviceProvider) : IRpcClient { private HubConnection _connection = default!; - private readonly IConnectionService _connectionService = serviceProvider.GetService(); + private readonly IConnectionClient _connectionClient = serviceProvider.GetService(); public IRpcHub Server { get; set; } = default!; @@ -21,7 +21,7 @@ public partial class RpcClient(IServiceProvider serviceProvider) : IRpcClient try { _connection = new HubConnectionBuilder() - .WithUrl(_connectionService.GetServerAddress().Join("rpc")) + .WithUrl(_connectionClient.GetServerAddress().Join("rpc")) .Build(); Server = _connection.ServerProxy(); diff --git a/LANCommander.SDK/Services/AuthenticationService.cs b/LANCommander.SDK/Services/AuthenticationClient.cs similarity index 84% rename from LANCommander.SDK/Services/AuthenticationService.cs rename to LANCommander.SDK/Services/AuthenticationClient.cs index ff0fade1..0cf4b552 100644 --- a/LANCommander.SDK/Services/AuthenticationService.cs +++ b/LANCommander.SDK/Services/AuthenticationClient.cs @@ -13,11 +13,11 @@ using Microsoft.Extensions.Logging; namespace LANCommander.SDK.Services; -public class AuthenticationService( - ILogger logger, +public class AuthenticationClient( + ILogger logger, ITokenProvider tokenProvider, ApiRequestFactory apiRequestFactory, - IConnectionService connectionService) + IConnectionClient connectionClient) { public async Task AuthenticateAsync(string username, string password) { @@ -88,7 +88,7 @@ public class AuthenticationService( tokenProvider.SetToken(null); - await connectionService.DisconnectAsync(); + await connectionClient.DisconnectAsync(); } public async Task RegisterAsync(string username, string password, string passwordConfirmation) @@ -118,8 +118,7 @@ public class AuthenticationService( switch (response.StatusCode) { case HttpStatusCode.OK: - tokenProvider.SetToken(null); - + tokenProvider.SetToken(response.Data.AccessToken); return; case HttpStatusCode.BadRequest: @@ -139,6 +138,36 @@ public class AuthenticationService( throw; } } + + public async Task ValidateTokenAsync() + { + logger?.LogTrace("Validating token"); + + if (String.IsNullOrWhiteSpace(tokenProvider.GetToken())) + { + logger?.LogError("Token is empty"); + return false; + } + + try + { + await apiRequestFactory + .Create() + .UseAuthenticationToken() + .UseRoute("/api/Auth/Validate") + .PostAsync(); + + logger?.LogTrace("Validated token successfully"); + + return true; + } + catch (Exception ex) + { + logger?.LogError("Validating token failed", ex); + } + + return false; + } public async Task> GetAuthenticationProvidersAsync() { @@ -151,7 +180,7 @@ public class AuthenticationService( public Uri GetAuthenticationProviderLoginUrl(string provider) { - return connectionService.GetServerAddress().Join($"api/Auth/Login?Provider={provider}"); + return connectionClient.GetServerAddress().Join($"api/Auth/Login?Provider={provider}"); } internal async Task ParseErrorResponseAsync(HttpResponseMessage response, bool defaultToGenericResponse = false) diff --git a/LANCommander.SDK/Services/BeaconService.cs b/LANCommander.SDK/Services/BeaconClient.cs similarity index 97% rename from LANCommander.SDK/Services/BeaconService.cs rename to LANCommander.SDK/Services/BeaconClient.cs index 9e1a4fcc..e7231d55 100644 --- a/LANCommander.SDK/Services/BeaconService.cs +++ b/LANCommander.SDK/Services/BeaconClient.cs @@ -12,8 +12,8 @@ using Microsoft.Extensions.Logging; namespace LANCommander.SDK.Services; -public class BeaconService( - ILogger logger, +public class BeaconClient( + ILogger logger, INetworkInformationProvider networkInformationProvider) { public delegate void OnBeaconResponseHandler(object sender, BeaconResponseArgs e); @@ -29,7 +29,7 @@ public class BeaconService( _beaconMessageInterceptors = new List(); } - public BeaconService AddBeaconMessageInterceptor(IBeaconMessageInterceptor interceptor) + public BeaconClient AddBeaconMessageInterceptor(IBeaconMessageInterceptor interceptor) { _beaconMessageInterceptors.Add(interceptor); diff --git a/LANCommander.SDK/Services/ChatService.cs b/LANCommander.SDK/Services/ChatClient.cs similarity index 82% rename from LANCommander.SDK/Services/ChatService.cs rename to LANCommander.SDK/Services/ChatClient.cs index 9fd7d1ab..bafe1ea0 100644 --- a/LANCommander.SDK/Services/ChatService.cs +++ b/LANCommander.SDK/Services/ChatClient.cs @@ -7,7 +7,7 @@ using LANCommander.SDK.Rpc.Client; namespace LANCommander.SDK.Services; -public class ChatService(IRpcClient rpc) +public class ChatClient(IRpcClient rpc) { private readonly Dictionary _threads = new(); public ChatThread GetThread(Guid threadId) @@ -17,7 +17,8 @@ public class ChatService(IRpcClient rpc) public async Task StartThreadAsync(IEnumerable userIdentifiers) { - var threadId = await rpc.Server.Chat_StartThreadAsync(userIdentifiers.ToArray()); + var threadId = Guid.NewGuid(); + // var threadId = await rpc.Server.Chat_StartThreadAsync(userIdentifiers.ToArray()); if (threadId != Guid.Empty) _threads[threadId] = new ChatThread @@ -35,7 +36,8 @@ public class ChatService(IRpcClient rpc) public async Task> GetThreadsAsync() { - var threads = await rpc.Server.Chat_GetThreadsAsync(); + var threads = new List(); + //var threads = await rpc.Server.Chat_GetThreadsAsync(); _threads.Clear(); @@ -71,11 +73,11 @@ public class ChatService(IRpcClient rpc) public async Task GetMessagesAsync(Guid threadId) { - await rpc.Server.Chat_GetMessagesAsync(threadId); + //await rpc.Server.Chat_GetMessagesAsync(threadId); } public async Task SendMessageAsync(Guid threadId, string contents) { - await rpc.Server.Chat_SendMessageAsync(threadId, contents); + //await rpc.Server.Chat_SendMessageAsync(threadId, contents); } } \ No newline at end of file diff --git a/LANCommander.SDK/Services/ConnectionService.cs b/LANCommander.SDK/Services/ConnectionClient.cs similarity index 92% rename from LANCommander.SDK/Services/ConnectionService.cs rename to LANCommander.SDK/Services/ConnectionClient.cs index aedd922d..19302b94 100644 --- a/LANCommander.SDK/Services/ConnectionService.cs +++ b/LANCommander.SDK/Services/ConnectionClient.cs @@ -12,9 +12,9 @@ using Microsoft.Extensions.Logging; namespace LANCommander.SDK.Services; -public class ConnectionService( - ILogger logger, - IRpcClient rpc) : IConnectionService +public class ConnectionClient( + ILogger logger, + IRpcClient rpc) : IConnectionClient { private Uri _serverAddress; @@ -25,6 +25,8 @@ public class ConnectionService( public Uri GetServerAddress() => _serverAddress; + public async Task UpdateServerAddressAsync(Uri address) => await UpdateServerAddressAsync(address.ToString()); + public async Task UpdateServerAddressAsync(string address) { if (String.IsNullOrWhiteSpace(address)) diff --git a/LANCommander.SDK/Services/DepotService.cs b/LANCommander.SDK/Services/DepotClient.cs similarity index 94% rename from LANCommander.SDK/Services/DepotService.cs rename to LANCommander.SDK/Services/DepotClient.cs index fab03e39..4876cc51 100644 --- a/LANCommander.SDK/Services/DepotService.cs +++ b/LANCommander.SDK/Services/DepotClient.cs @@ -7,8 +7,8 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class DepotService( - ILogger logger, + public class DepotClient( + ILogger logger, ApiRequestFactory apiRequestFactory) { public async Task GetAsync() diff --git a/LANCommander.SDK/Services/GameService.cs b/LANCommander.SDK/Services/GameClient.cs similarity index 95% rename from LANCommander.SDK/Services/GameService.cs rename to LANCommander.SDK/Services/GameClient.cs index f0aa6ebf..0c52c9d9 100644 --- a/LANCommander.SDK/Services/GameService.cs +++ b/LANCommander.SDK/Services/GameClient.cs @@ -59,18 +59,18 @@ namespace LANCommander.SDK.Services public GameInstallationFileList FileList { get; set; } = GameInstallationFileList.Empty; } - public class GameService( - ILogger logger, + public class GameClient( + ILogger logger, ApiRequestFactory apiRequestFactory, ProcessExecutionContextFactory processExecutionContextFactory, INetworkInformationProvider networkInformationProvider, ILANCommanderConfiguration config, - IConnectionService connectionService, - RedistributableService redistributableService, - SaveService saveService, - ScriptService scriptService, - ProfileService profileService, - LobbyService lobbyService) + IConnectionClient connectionClient, + RedistributableClient redistributableClient, + SaveClient saveClient, + ScriptClient scriptClient, + ProfileClient profileClient, + LobbyClient lobbyClient) { public delegate void OnArchiveEntryExtractionProgressHandler(object sender, ArchiveEntryExtractionProgressArgs e); public event OnArchiveEntryExtractionProgressHandler OnArchiveEntryExtractionProgress; @@ -161,7 +161,7 @@ namespace LANCommander.SDK.Services try { - if (connectionService.IsConnected()) + if (connectionClient.IsConnected()) { actions.AddRange( await apiRequestFactory @@ -196,7 +196,7 @@ namespace LANCommander.SDK.Services try { - var lobbies = lobbyService.GetSteamLobbies(installDirectory, id); + var lobbies = lobbyClient.GetSteamLobbies(installDirectory, id); foreach (var lobby in lobbies) { @@ -255,6 +255,9 @@ namespace LANCommander.SDK.Services public async Task StartedAsync(Guid id) { + if (!connectionClient.IsConnected()) + return; + logger?.LogTrace("Signaling to the server that we started the game..."); try @@ -274,6 +277,9 @@ namespace LANCommander.SDK.Services public async Task StoppedAsync(Guid id) { + if (!connectionClient.IsConnected()) + return; + logger?.LogTrace("Signaling to the server that we stopped the game..."); try @@ -457,7 +463,7 @@ namespace LANCommander.SDK.Services { logger?.LogTrace("Installing redistributables"); - await redistributableService.InstallAsync(game); + await redistributableClient.InstallAsync(game); } #endregion @@ -468,7 +474,7 @@ namespace LANCommander.SDK.Services OnInstallProgressUpdate?.Invoke(_installProgress); - await saveService.DownloadAsync(game.InstallDirectory, game.Id); + await saveClient.DownloadAsync(game.InstallDirectory, game.Id); #endregion await RunPostInstallScripts(game); @@ -690,7 +696,7 @@ namespace LANCommander.SDK.Services } #endregion - await scriptService.RunUninstallScriptAsync(installDirectory, gameId); + await scriptClient.RunUninstallScriptAsync(installDirectory, gameId); #region Cleanup Install Directory var metadataPath = GetMetadataDirectoryPath(installDirectory, gameId); @@ -787,7 +793,7 @@ namespace LANCommander.SDK.Services foreach (var entry in gameAndAddons) { if (await IsInstalled(oldInstallDirectory, game, entry.Id)) - await saveService.UploadAsync(oldInstallDirectory, entry.Id); + await saveClient.UploadAsync(oldInstallDirectory, entry.Id); } if (Directory.Exists(newInstallDirectory)) @@ -861,7 +867,7 @@ namespace LANCommander.SDK.Services { await RunPostInstallScripts(entry); - await saveService.DownloadAsync(newInstallDirectory, entry.Id); + await saveClient.DownloadAsync(newInstallDirectory, entry.Id); } } @@ -921,9 +927,9 @@ namespace LANCommander.SDK.Services { var allocatedKey = await GetAllocatedKeyAsync(game.Id); - await scriptService.RunInstallScriptAsync(game.InstallDirectory, game.Id); - await scriptService.RunKeyChangeScriptAsync(game.InstallDirectory, game.Id, allocatedKey); - await scriptService.RunNameChangeScriptAsync(game.InstallDirectory, game.Id, await profileService.GetAliasAsync()); + await scriptClient.RunInstallScriptAsync(game.InstallDirectory, game.Id); + await scriptClient.RunKeyChangeScriptAsync(game.InstallDirectory, game.Id, allocatedKey); + await scriptClient.RunNameChangeScriptAsync(game.InstallDirectory, game.Id, await profileClient.GetAliasAsync()); } catch (Exception ex) { @@ -1212,7 +1218,7 @@ namespace LANCommander.SDK.Services gameArchives.BaseGame.Entries.AddRange(entries); manifests = manifests.Except([baseManifest]).ToList(); - var savePathEntries = baseManifest.SavePaths?.SelectMany(p => saveService.GetFileSavePathEntries(p, installDirectory)).ToList() ?? []; + var savePathEntries = baseManifest.SavePaths?.SelectMany(p => saveClient.GetFileSavePathEntries(p, installDirectory)).ToList() ?? []; gameArchives.BaseGame.SavePaths = savePathEntries; } @@ -1230,7 +1236,7 @@ namespace LANCommander.SDK.Services depArchiveInfo.Manifest = depManifest; depArchiveInfo.Entries.AddRange(depEntries); - var savePathEntries = depManifest.SavePaths?.SelectMany(p => saveService.GetFileSavePathEntries(p, installDirectory)).ToList() ?? []; + var savePathEntries = depManifest.SavePaths?.SelectMany(p => saveClient.GetFileSavePathEntries(p, installDirectory)).ToList() ?? []; depArchiveInfo.SavePaths = savePathEntries; } @@ -1243,7 +1249,7 @@ namespace LANCommander.SDK.Services using (var context = processExecutionContextFactory.Create()) { - context.AddVariable("ServerAddress", connectionService.GetServerAddress().ToString()); + context.AddVariable("ServerAddress", connectionClient.GetServerAddress().ToString()); try { @@ -1259,7 +1265,7 @@ namespace LANCommander.SDK.Services try { - if (connectionService.IsConnected() && !String.IsNullOrWhiteSpace(config.IPXRelayHost)) + if (connectionClient.IsConnected() && !String.IsNullOrWhiteSpace(config.IPXRelayHost)) { context.AddVariable("IPXRelayHost", config.IPXRelayHost); context.AddVariable("IPXRelayPort", config.IPXRelayPort.ToString()); @@ -1280,19 +1286,19 @@ namespace LANCommander.SDK.Services var currentGameKey = await GetCurrentKeyAsync(installDirectory, manifest.Id); #region Check Game's Player Name - if (connectionService.IsConnected()) + if (connectionClient.IsConnected()) { - var alias = await profileService.GetAliasAsync(); + var alias = await profileClient.GetAliasAsync(); if (currentGamePlayerAlias != alias) { - await scriptService.RunNameChangeScriptAsync(installDirectory, gameId, alias); + await scriptClient.RunNameChangeScriptAsync(installDirectory, gameId, alias); if (manifest.Redistributables != null) { foreach (var redistributable in manifest.Redistributables.Where(r => r.Scripts != null)) { - await scriptService.RunNameChangeScriptAsync(installDirectory, gameId, redistributable.Id, alias); + await scriptClient.RunNameChangeScriptAsync(installDirectory, gameId, redistributable.Id, alias); } } } @@ -1300,26 +1306,26 @@ namespace LANCommander.SDK.Services #endregion #region Check Key Allocation - if (connectionService.IsConnected()) + if (connectionClient.IsConnected()) { var newKey = await GetAllocatedKeyAsync(manifest.Id); if (currentGameKey != newKey) - await scriptService.RunKeyChangeScriptAsync(installDirectory, manifest.Id, newKey); + await scriptClient.RunKeyChangeScriptAsync(installDirectory, manifest.Id, newKey); } #endregion #region Download Latest Saves - if (connectionService.IsConnected()) + if (connectionClient.IsConnected()) { await RetryHelper.RetryOnExceptionAsync(10, TimeSpan.FromSeconds(1), false, async () => { logger?.LogTrace("Attempting to download save"); - var latestSave = await saveService.GetLatestAsync(manifest.Id); + var latestSave = await saveClient.GetLatestAsync(manifest.Id); if (latestSave != null && (latestSave.CreatedOn > lastRun || lastRun == null)) - await saveService.DownloadAsync(installDirectory, manifest.Id); + await saveClient.DownloadAsync(installDirectory, manifest.Id); return true; }); @@ -1327,13 +1333,13 @@ namespace LANCommander.SDK.Services #endregion #region Run Before Start Script - await scriptService.RunBeforeStartScriptAsync(installDirectory, manifest.Id); + await scriptClient.RunBeforeStartScriptAsync(installDirectory, manifest.Id); if (manifest.Redistributables != null) { foreach (var redistributable in manifest.Redistributables.Where(r => r.Scripts != null)) { - await scriptService.RunBeforeStartScriptAsync(installDirectory, gameId, redistributable.Id); + await scriptClient.RunBeforeStartScriptAsync(installDirectory, gameId, redistributable.Id); } } #endregion @@ -1361,13 +1367,13 @@ namespace LANCommander.SDK.Services foreach (var manifest in manifests) { #region Run After Stop Script - await scriptService.RunAfterStopScriptAsync(installDirectory, gameId); + await scriptClient.RunAfterStopScriptAsync(installDirectory, gameId); if (manifest.Redistributables != null) { foreach (var redistributable in manifest.Redistributables.Where(r => r.Scripts != null)) { - await scriptService.RunAfterStopScriptAsync(installDirectory, gameId, redistributable.Id); + await scriptClient.RunAfterStopScriptAsync(installDirectory, gameId, redistributable.Id); } } #endregion @@ -1377,7 +1383,7 @@ namespace LANCommander.SDK.Services private async Task UploadSavesAsync(ICollection manifests, string installDirectory) { - if (connectionService.IsConnected()) + if (connectionClient.IsConnected()) { foreach (var manifest in manifests) { @@ -1385,7 +1391,7 @@ namespace LANCommander.SDK.Services { logger?.LogTrace("Attempting to upload save"); - await saveService.UploadAsync(installDirectory, manifest.Id); + await saveClient.UploadAsync(installDirectory, manifest.Id); return true; }); diff --git a/LANCommander.SDK/Services/IArchiveService.cs b/LANCommander.SDK/Services/IArchiveClient.cs similarity index 87% rename from LANCommander.SDK/Services/IArchiveService.cs rename to LANCommander.SDK/Services/IArchiveClient.cs index af3bbcc0..3e6ab34b 100644 --- a/LANCommander.SDK/Services/IArchiveService.cs +++ b/LANCommander.SDK/Services/IArchiveClient.cs @@ -5,7 +5,7 @@ using System.Threading.Tasks; namespace LANCommander.SDK.Services; -public interface IArchiveService +public interface IArchiveClient { public Task> GetContentsAsync(Guid archiveId); } \ No newline at end of file diff --git a/LANCommander.SDK/Services/IConnectionService.cs b/LANCommander.SDK/Services/IConnectionClient.cs similarity index 76% rename from LANCommander.SDK/Services/IConnectionService.cs rename to LANCommander.SDK/Services/IConnectionClient.cs index 30a15a76..bb30e19c 100644 --- a/LANCommander.SDK/Services/IConnectionService.cs +++ b/LANCommander.SDK/Services/IConnectionClient.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; namespace LANCommander.SDK.Services; -public interface IConnectionService +public interface IConnectionClient { public bool IsConnected(); public Uri GetServerAddress(); @@ -13,6 +13,8 @@ public interface IConnectionService /// /// The address to resolve for a LANCommander server public Task UpdateServerAddressAsync(string address); + public Task UpdateServerAddressAsync(Uri address); public Task DisconnectAsync(); + public Task PingAsync(Uri serverAddress = null); } \ No newline at end of file diff --git a/LANCommander.SDK/Services/IssueService.cs b/LANCommander.SDK/Services/IssueClient.cs similarity index 90% rename from LANCommander.SDK/Services/IssueService.cs rename to LANCommander.SDK/Services/IssueClient.cs index cd5d6dac..c53e23e8 100644 --- a/LANCommander.SDK/Services/IssueService.cs +++ b/LANCommander.SDK/Services/IssueClient.cs @@ -6,7 +6,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class IssueService(ApiRequestFactory apiRequestFactory) + public class IssueClient(ApiRequestFactory apiRequestFactory) { public async Task Open(string description, Guid gameId) { diff --git a/LANCommander.SDK/Services/LauncherService.cs b/LANCommander.SDK/Services/LauncherClient.cs similarity index 93% rename from LANCommander.SDK/Services/LauncherService.cs rename to LANCommander.SDK/Services/LauncherClient.cs index 7461fc31..a87f0850 100644 --- a/LANCommander.SDK/Services/LauncherService.cs +++ b/LANCommander.SDK/Services/LauncherClient.cs @@ -6,8 +6,8 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class LauncherService( - ILogger logger, + public class LauncherClient( + ILogger logger, ApiRequestFactory apiRequestFactory) { public async Task CheckForUpdateAsync() diff --git a/LANCommander.SDK/Services/LibraryService.cs b/LANCommander.SDK/Services/LibraryClient.cs similarity index 96% rename from LANCommander.SDK/Services/LibraryService.cs rename to LANCommander.SDK/Services/LibraryClient.cs index 36cceb0b..b318f1ba 100644 --- a/LANCommander.SDK/Services/LibraryService.cs +++ b/LANCommander.SDK/Services/LibraryClient.cs @@ -6,7 +6,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class LibraryService(ApiRequestFactory apiRequestFactory) + public class LibraryClient(ApiRequestFactory apiRequestFactory) { public async Task> GetAsync() { diff --git a/LANCommander.SDK/Services/LobbyService.cs b/LANCommander.SDK/Services/LobbyClient.cs similarity index 97% rename from LANCommander.SDK/Services/LobbyService.cs rename to LANCommander.SDK/Services/LobbyClient.cs index dac7079e..706e4d6e 100644 --- a/LANCommander.SDK/Services/LobbyService.cs +++ b/LANCommander.SDK/Services/LobbyClient.cs @@ -7,7 +7,7 @@ using System.IO; namespace LANCommander.SDK.Services { - public class LobbyService(ILogger logger) + public class LobbyClient(ILogger logger) { /// /// Get all Steam lobbies for a specified game. Game install directory must contain a file called steam_appid.txt. diff --git a/LANCommander.SDK/Services/MediaService.cs b/LANCommander.SDK/Services/MediaService.cs index 59fc9097..f4cf3140 100644 --- a/LANCommander.SDK/Services/MediaService.cs +++ b/LANCommander.SDK/Services/MediaService.cs @@ -10,7 +10,7 @@ namespace LANCommander.SDK.Services { public class MediaService( ApiRequestFactory apiRequestFactory, - IConnectionService connectionService) + IConnectionClient connectionClient) { public async Task GetAsync(Guid mediaId) { @@ -34,7 +34,7 @@ namespace LANCommander.SDK.Services public string GetAbsoluteUrl(Media media) { - return connectionService.GetServerAddress().Join(GetDownloadPath(media)).ToString(); + return connectionClient.GetServerAddress().Join(GetDownloadPath(media)).ToString(); } public string GetDownloadPath(Media media) @@ -44,7 +44,7 @@ namespace LANCommander.SDK.Services public string GetAbsoluteThumbnailUrl(Media media) { - return connectionService.GetServerAddress().Join(GetThumbnailPath(media)).ToString(); + return connectionClient.GetServerAddress().Join(GetThumbnailPath(media)).ToString(); } public string GetThumbnailPath(Media media) diff --git a/LANCommander.SDK/Services/PlaySessionService.cs b/LANCommander.SDK/Services/PlaySessionClient.cs similarity index 92% rename from LANCommander.SDK/Services/PlaySessionService.cs rename to LANCommander.SDK/Services/PlaySessionClient.cs index 6b747d13..4d3ac2f4 100644 --- a/LANCommander.SDK/Services/PlaySessionService.cs +++ b/LANCommander.SDK/Services/PlaySessionClient.cs @@ -7,7 +7,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class PlaySessionService(ApiRequestFactory apiRequestFactory) + public class PlaySessionClient(ApiRequestFactory apiRequestFactory) { public async Task> GetAsync() { diff --git a/LANCommander.SDK/Services/ProfileService.cs b/LANCommander.SDK/Services/ProfileClient.cs similarity index 97% rename from LANCommander.SDK/Services/ProfileService.cs rename to LANCommander.SDK/Services/ProfileClient.cs index 4ac942e5..c2a1aa36 100644 --- a/LANCommander.SDK/Services/ProfileService.cs +++ b/LANCommander.SDK/Services/ProfileClient.cs @@ -7,7 +7,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class ProfileService(ApiRequestFactory apiRequestFactory, ILogger logger) + public class ProfileClient(ApiRequestFactory apiRequestFactory, ILogger logger) { private User _user; diff --git a/LANCommander.SDK/Services/RedistributableService.cs b/LANCommander.SDK/Services/RedistributableClient.cs similarity index 94% rename from LANCommander.SDK/Services/RedistributableService.cs rename to LANCommander.SDK/Services/RedistributableClient.cs index 6bcb0061..0d375463 100644 --- a/LANCommander.SDK/Services/RedistributableService.cs +++ b/LANCommander.SDK/Services/RedistributableClient.cs @@ -15,12 +15,12 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class RedistributableService( - ILogger _logger, + public class RedistributableClient( + ILogger _logger, ILANCommanderConfiguration config, ApiRequestFactory apiRequestFactory, - ScriptService scriptService, - ProfileService profileService) + ScriptClient scriptClient, + ProfileClient profileClient) { public delegate void OnArchiveEntryExtractionProgressHandler(object sender, ArchiveEntryExtractionProgressArgs e); public event OnArchiveEntryExtractionProgressHandler OnArchiveEntryExtractionProgress; @@ -80,7 +80,7 @@ namespace LANCommander.SDK.Services } var installed = - await scriptService.RunDetectInstallScriptAsync(game.InstallDirectory, game.Id, redistributable.Id); + await scriptClient.RunDetectInstallScriptAsync(game.InstallDirectory, game.Id, redistributable.Id); _logger?.LogTrace("Redistributable install detection returned {Result}", installed); @@ -142,8 +142,8 @@ namespace LANCommander.SDK.Services try { - await scriptService.RunInstallScriptAsync(game.InstallDirectory, game.Id, redistributable.Id); - await scriptService.RunNameChangeScriptAsync(game.InstallDirectory, game.Id, redistributable.Id, await profileService.GetAliasAsync()); + await scriptClient.RunInstallScriptAsync(game.InstallDirectory, game.Id, redistributable.Id); + await scriptClient.RunNameChangeScriptAsync(game.InstallDirectory, game.Id, redistributable.Id, await profileClient.GetAliasAsync()); } catch (Exception ex) { @@ -160,7 +160,7 @@ namespace LANCommander.SDK.Services throw new ArgumentNullException(nameof(redistributable)); } - var destination = Path.Combine(GameService.GetMetadataDirectoryPath(game.InstallDirectory, redistributable.Id), "Files"); + var destination = Path.Combine(GameClient.GetMetadataDirectoryPath(game.InstallDirectory, redistributable.Id), "Files"); var files = new List(); _logger?.LogTrace("Downloading and extracting {Redistributable} to path {Destination}", redistributable.Name, destination); diff --git a/LANCommander.SDK/Services/SaveService.cs b/LANCommander.SDK/Services/SaveClient.cs similarity index 99% rename from LANCommander.SDK/Services/SaveService.cs rename to LANCommander.SDK/Services/SaveClient.cs index b51693a1..6bb569fa 100644 --- a/LANCommander.SDK/Services/SaveService.cs +++ b/LANCommander.SDK/Services/SaveClient.cs @@ -28,10 +28,10 @@ using Action = System.Action; namespace LANCommander.SDK.Services { - public class SaveService( + public class SaveClient( ApiRequestFactory apiRequestFactory, ILANCommanderConfiguration config, - ILogger logger) + ILogger logger) { public delegate void OnDownloadProgressHandler(DownloadProgressChangedEventArgs e); public event OnDownloadProgressHandler OnDownloadProgress; diff --git a/LANCommander.SDK/Services/ScriptService.cs b/LANCommander.SDK/Services/ScriptClient.cs similarity index 96% rename from LANCommander.SDK/Services/ScriptService.cs rename to LANCommander.SDK/Services/ScriptClient.cs index 97eb9a95..a1bd3106 100644 --- a/LANCommander.SDK/Services/ScriptService.cs +++ b/LANCommander.SDK/Services/ScriptClient.cs @@ -12,10 +12,10 @@ using LANCommander.SDK.Abstractions; namespace LANCommander.SDK.Services { - public class ScriptService( - ILogger logger, + public class ScriptClient( + ILogger logger, ILANCommanderConfiguration config, - IConnectionService connectionService) + IConnectionClient connectionClient) { public delegate Task ExternalScriptRunnerHandler(PowerShellScript script); public event ExternalScriptRunnerHandler ExternalScriptRunner; @@ -121,7 +121,7 @@ namespace LANCommander.SDK.Services script.AddVariable("GameManifest", gameManifest); script.AddVariable("RedistributableManifest", redistributableManifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); try { @@ -147,7 +147,7 @@ namespace LANCommander.SDK.Services } } - script.UseWorkingDirectory(Path.Combine(GameService.GetMetadataDirectoryPath(installDirectory, redistributableId))); + script.UseWorkingDirectory(Path.Combine(GameClient.GetMetadataDirectoryPath(installDirectory, redistributableId))); script.UseFile(path); try @@ -221,7 +221,7 @@ namespace LANCommander.SDK.Services script.AddVariable("GameManifest", gameManifest); script.AddVariable("RedistributableManifest", redistributableManifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); try { @@ -248,7 +248,7 @@ namespace LANCommander.SDK.Services } } - var extractionPath = Path.Combine(GameService.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); + var extractionPath = Path.Combine(GameClient.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); script.UseWorkingDirectory(extractionPath); script.UseFile(path); @@ -303,7 +303,7 @@ namespace LANCommander.SDK.Services if (File.Exists(path)) { var script = new PowerShellScript(Enums.ScriptType.BeforeStart); - var playerAlias = await GameService.GetPlayerAliasAsync(installDirectory, gameId); + var playerAlias = await GameClient.GetPlayerAliasAsync(installDirectory, gameId); if (Debug) script.DebugHandler.OnDebugStart = OnDebugStart; @@ -312,7 +312,7 @@ namespace LANCommander.SDK.Services script.AddVariable("GameManifest", gameManifest); script.AddVariable("RedistributableManifest", redistributableManifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); script.AddVariable("PlayerAlias", playerAlias); try @@ -341,7 +341,7 @@ namespace LANCommander.SDK.Services } } - var extractionPath = Path.Combine(GameService.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); + var extractionPath = Path.Combine(GameClient.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); script.UseWorkingDirectory(extractionPath); script.UseFile(path); @@ -408,8 +408,8 @@ namespace LANCommander.SDK.Services script.AddVariable("GameManifest", gameManifest); script.AddVariable("RedistributableManifest", redistributableManifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); - script.AddVariable("PlayerAlias", GameService.GetPlayerAlias(installDirectory, gameId)); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); + script.AddVariable("PlayerAlias", GameClient.GetPlayerAlias(installDirectory, gameId)); try { @@ -437,7 +437,7 @@ namespace LANCommander.SDK.Services } } - var extractionPath = Path.Combine(GameService.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); + var extractionPath = Path.Combine(GameClient.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); script.UseWorkingDirectory(extractionPath); script.UseFile(path); @@ -496,7 +496,7 @@ namespace LANCommander.SDK.Services { if (File.Exists(path)) { - var oldName = await GameService.GetPlayerAliasAsync(installDirectory, gameId); + var oldName = await GameClient.GetPlayerAliasAsync(installDirectory, gameId); if (oldName == newName) oldName = string.Empty; @@ -515,7 +515,7 @@ namespace LANCommander.SDK.Services script.AddVariable("GameManifest", gameManifest); script.AddVariable("RedistributableManifest", redistributableManifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); script.AddVariable("OldPlayerAlias", oldName); script.AddVariable("NewPlayerAlias", newName); @@ -545,7 +545,7 @@ namespace LANCommander.SDK.Services } } - var extractionPath = Path.Combine(GameService.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); + var extractionPath = Path.Combine(GameClient.GetMetadataDirectoryPath(installDirectory, redistributableId), "Files"); script.UseWorkingDirectory(extractionPath); script.UseFile(path); @@ -612,7 +612,7 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); if (manifest.CustomFields != null && manifest.CustomFields.Any()) { @@ -696,7 +696,7 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); if (manifest.CustomFields != null && manifest.CustomFields.Any()) { @@ -773,7 +773,7 @@ namespace LANCommander.SDK.Services if (File.Exists(path)) { var script = new PowerShellScript(Enums.ScriptType.BeforeStart); - var playerAlias = GameService.GetPlayerAlias(installDirectory, gameId); + var playerAlias = GameClient.GetPlayerAlias(installDirectory, gameId); if (Debug) script.DebugHandler.OnDebugStart = OnDebugStart; @@ -781,7 +781,7 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); script.AddVariable("PlayerAlias", playerAlias); if (manifest.CustomFields != null && manifest.CustomFields.Any()) @@ -867,8 +867,8 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); - script.AddVariable("PlayerAlias", GameService.GetPlayerAlias(installDirectory, gameId)); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); + script.AddVariable("PlayerAlias", GameClient.GetPlayerAlias(installDirectory, gameId)); if (manifest.CustomFields != null && manifest.CustomFields.Any()) { @@ -945,7 +945,7 @@ namespace LANCommander.SDK.Services { if (File.Exists(path)) { - var oldName = await GameService.GetPlayerAliasAsync(installDirectory, gameId); + var oldName = await GameClient.GetPlayerAliasAsync(installDirectory, gameId); if (oldName == newName) oldName = string.Empty; @@ -963,7 +963,7 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); script.AddVariable("OldPlayerAlias", oldName); script.AddVariable("NewPlayerAlias", newName); @@ -992,7 +992,7 @@ namespace LANCommander.SDK.Services script.UseFile(path); - GameService.UpdatePlayerAlias(installDirectory, gameId, newName); + GameClient.UpdatePlayerAlias(installDirectory, gameId, newName); try { @@ -1055,7 +1055,7 @@ namespace LANCommander.SDK.Services script.AddVariable("InstallDirectory", installDirectory); script.AddVariable("GameManifest", manifest); script.AddVariable("DefaultInstallDirectory", config.InstallDirectories.FirstOrDefault()); - script.AddVariable("ServerAddress", connectionService.GetServerAddress()); + script.AddVariable("ServerAddress", connectionClient.GetServerAddress()); script.AddVariable("AllocatedKey", key); if (manifest.CustomFields != null && manifest.CustomFields.Any()) @@ -1082,7 +1082,7 @@ namespace LANCommander.SDK.Services logger?.LogError(ex, "Could not enrich logs"); } - GameService.UpdateCurrentKey(installDirectory, gameId, key); + GameClient.UpdateCurrentKey(installDirectory, gameId, key); try { diff --git a/LANCommander.SDK/Services/ServerService.cs b/LANCommander.SDK/Services/ServerClient.cs similarity index 98% rename from LANCommander.SDK/Services/ServerService.cs rename to LANCommander.SDK/Services/ServerClient.cs index b4f40ab8..eae0e3bc 100644 --- a/LANCommander.SDK/Services/ServerService.cs +++ b/LANCommander.SDK/Services/ServerClient.cs @@ -8,7 +8,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class ServerService( + public class ServerClient( ILANCommanderConfiguration config, ApiRequestFactory apiRequestFactory) { diff --git a/LANCommander.SDK/Services/TagService.cs b/LANCommander.SDK/Services/TagClient.cs similarity index 94% rename from LANCommander.SDK/Services/TagService.cs rename to LANCommander.SDK/Services/TagClient.cs index 5b176525..78a25f75 100644 --- a/LANCommander.SDK/Services/TagService.cs +++ b/LANCommander.SDK/Services/TagClient.cs @@ -4,7 +4,7 @@ using LANCommander.SDK.Factories; namespace LANCommander.SDK.Services { - public class TagService(ApiRequestFactory apiRequestFactory) + public class TagClient(ApiRequestFactory apiRequestFactory) { public async Task CreateAsync(Tag tag) { diff --git a/LANCommander.SDK/VersionInterceptor.cs b/LANCommander.SDK/VersionInterceptor.cs deleted file mode 100644 index cc4f1ae1..00000000 --- a/LANCommander.SDK/VersionInterceptor.cs +++ /dev/null @@ -1,61 +0,0 @@ -using LANCommander.SDK.Exceptions; -using Microsoft.Extensions.Logging; -using RestSharp; -using RestSharp.Interceptors; -using Semver; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace LANCommander.SDK -{ - internal class VersionInterceptor : Interceptor - { - private readonly ILogger Logger; - - public override ValueTask AfterRequest(RestResponse response, CancellationToken cancellationToken) - { - try - { - var version = Client.GetCurrentVersion(); - var header = response.Headers.FirstOrDefault(h => h.Name.Equals("X-API-Version", StringComparison.OrdinalIgnoreCase)); - - if (response.IsSuccessful && header == null) - { - response.ErrorException = new ApiVersionMismatchException(version, null, $"The server is out of date and does not support client version {version}."); - - return new ValueTask(); - } - else if (!response.IsSuccessful && header == null) - { - return new ValueTask(); - } - - var apiVersion = SemVersion.Parse((string)header.Value, SemVersionStyles.Any); - - if (version.Major != apiVersion.Major || version.Minor != apiVersion.Minor) - { - switch (version.ComparePrecedenceTo(apiVersion)) - { - case -1: - response.ErrorException = new ApiVersionMismatchException(version, apiVersion, $"Your client (v{version}) is out of date and is not supported by the server (v{apiVersion})"); - break; - - case 1: - response.ErrorException = new ApiVersionMismatchException(version, apiVersion, $"Your client (v{version}) is on a version not supported by the server (v{apiVersion})"); - break; - } - } - } - catch (Exception ex) - { - Logger?.LogError(ex, "Could not validate API version"); - } - - return new ValueTask(); - } - } -} diff --git a/LANCommander.Server.ImportExport/Exporters/ArchiveExporter.cs b/LANCommander.Server.ImportExport/Exporters/ArchiveExporter.cs index c68bd055..d8e9588c 100644 --- a/LANCommander.Server.ImportExport/Exporters/ArchiveExporter.cs +++ b/LANCommander.Server.ImportExport/Exporters/ArchiveExporter.cs @@ -11,14 +11,14 @@ namespace LANCommander.Server.ImportExport.Exporters; /// Implements exporting for archive records /// /// AutoMapper instance for mapping between models -/// Service for archive operations +/// Service for archive operations public class ArchiveExporter( IMapper mapper, - ArchiveService archiveService) : BaseExporter + ArchiveClient archiveClient) : BaseExporter { public override async Task GetExportInfoAsync(Data.Models.Archive record) { - var archivePath = await archiveService.GetArchiveFileLocationAsync(record.ObjectKey); + var archivePath = await archiveClient.GetArchiveFileLocationAsync(record.ObjectKey); var info = new ExportItemInfo { @@ -42,11 +42,11 @@ public class ArchiveExporter( public override async Task ExportAsync(Guid id) { - var entity = await archiveService.GetAsync(id); + var entity = await archiveClient.GetAsync(id); try { - var path = await archiveService.GetArchiveFileLocationAsync(entity); + var path = await archiveClient.GetArchiveFileLocationAsync(entity); var fileInfo = new FileInfo(path); if (fileInfo.Exists) diff --git a/LANCommander.Server.ImportExport/Importers/ArchiveImporter.cs b/LANCommander.Server.ImportExport/Importers/ArchiveImporter.cs index 483d8e39..605b2ab8 100644 --- a/LANCommander.Server.ImportExport/Importers/ArchiveImporter.cs +++ b/LANCommander.Server.ImportExport/Importers/ArchiveImporter.cs @@ -14,7 +14,7 @@ namespace LANCommander.Server.ImportExport.Importers; /// The context (archive, parent record> of the import public class ArchiveImporter( IMapper mapper, - ArchiveService archiveService) : BaseImporter + ArchiveClient archiveClient) : BaseImporter { public override async Task GetImportInfoAsync(Archive record) { @@ -59,15 +59,15 @@ public class ArchiveImporter( throw new ImportSkippedException(record, $"Cannot import an archive for a {record.GetType().Name}"); - archive = await archiveService.AddAsync(newArchive); - archive = await archiveService.WriteToFileAsync(archive, archiveEntry.OpenEntryStream()); + archive = await archiveClient.AddAsync(newArchive); + archive = await archiveClient.WriteToFileAsync(archive, archiveEntry.OpenEntryStream()); return archive; } catch (Exception ex) { if (archive != null) - await archiveService.DeleteAsync(archive); + await archiveClient.DeleteAsync(archive); throw new ImportSkippedException(record, "An unknown error occured while importing archive file", ex); } @@ -76,8 +76,8 @@ public class ArchiveImporter( public override async Task UpdateAsync(Archive archive) { var archiveEntry = ImportContext.Archive.Entries.FirstOrDefault(e => e.Key == $"Archives/{archive.Id}"); - var existing = await archiveService.Include(a => a.StorageLocation).FirstOrDefaultAsync(a => archive.Id == a.Id); - var existingPath = await archiveService.GetArchiveFileLocationAsync(existing); + var existing = await archiveClient.Include(a => a.StorageLocation).FirstOrDefaultAsync(a => archive.Id == a.Id); + var existingPath = await archiveClient.GetArchiveFileLocationAsync(existing); if (archiveEntry == null) throw new ImportSkippedException(archive, "Matching archive file does not exist in import archive"); @@ -88,8 +88,8 @@ public class ArchiveImporter( existing.Changelog = archive.Changelog; existing.StorageLocation = ImportContext.ArchiveStorageLocation; - existing = await archiveService.UpdateAsync(existing); - existing = await archiveService.WriteToFileAsync(existing, archiveEntry.OpenEntryStream()); + existing = await archiveClient.UpdateAsync(existing); + existing = await archiveClient.WriteToFileAsync(existing, archiveEntry.OpenEntryStream()); if (File.Exists(existingPath)) File.Delete(existingPath); @@ -105,10 +105,10 @@ public class ArchiveImporter( public override async Task ExistsAsync(Archive archive) { if (ImportContext.DataRecord is Data.Models.Game game) - return await archiveService.ExistsAsync(a => a.Version == archive.Version && a.GameId == game.Id); + return await archiveClient.ExistsAsync(a => a.Version == archive.Version && a.GameId == game.Id); if (ImportContext.DataRecord is Data.Models.Redistributable redistributable) - return await archiveService.ExistsAsync(a => a.Version == archive.Version && a.RedistributableId == redistributable.Id); + return await archiveClient.ExistsAsync(a => a.Version == archive.Version && a.RedistributableId == redistributable.Id); throw new ImportSkippedException(archive, $"Cannot import an archive for a {ImportContext.DataRecord.GetType().Name}"); } diff --git a/LANCommander.Server.Services/ArchiveService.cs b/LANCommander.Server.Services/ArchiveClient.cs similarity index 99% rename from LANCommander.Server.Services/ArchiveService.cs rename to LANCommander.Server.Services/ArchiveClient.cs index 2a2e6dc6..29f77ee0 100644 --- a/LANCommander.Server.Services/ArchiveService.cs +++ b/LANCommander.Server.Services/ArchiveClient.cs @@ -19,13 +19,13 @@ using PascalCaseNamingConvention = YamlDotNet.Serialization.NamingConventions.Pa namespace LANCommander.Server.Services { - public sealed class ArchiveService( - ILogger logger, + public sealed class ArchiveClient( + ILogger logger, IFusionCache cache, IMapper mapper, IHttpContextAccessor httpContextAccessor, IDbContextFactory dbContextFactory, - StorageLocationService storageLocationService) : BaseDatabaseService(logger, cache, mapper, httpContextAccessor, dbContextFactory), IArchiveService + StorageLocationService storageLocationService) : BaseDatabaseService(logger, cache, mapper, httpContextAccessor, dbContextFactory), IArchiveClient { public async Task GetLatestArchive(Expression> predicate) { diff --git a/LANCommander.Server.Services/AuthenticationService.cs b/LANCommander.Server.Services/AuthenticationService.cs index 15ebc6cb..f95ad63a 100644 --- a/LANCommander.Server.Services/AuthenticationService.cs +++ b/LANCommander.Server.Services/AuthenticationService.cs @@ -4,6 +4,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using AutoMapper; +using LANCommander.SDK.Abstractions; using LANCommander.SDK.Enums; using LANCommander.SDK.Models; using LANCommander.Server.Services.Exceptions; @@ -18,7 +19,9 @@ namespace LANCommander.Server.Services IMapper mapper, UserService userService, RoleService roleService, - ScriptService scriptService) : BaseService(logger) + ScriptService scriptService, + ITokenProvider tokenProvider, + SDK.Services.ScriptClient scriptClient) : BaseService(logger) { public async Task LoginAsync(string userName, string password) { @@ -34,13 +37,11 @@ namespace LANCommander.Server.Services if (scripts.Any()) { - var client = new SDK.Client(_settings.Beacon.Address, "", logger); - - client.UseToken(token); + tokenProvider.SetToken(token.AccessToken); foreach (var script in scripts) { - await client.Scripts.RunUserLoginScript(script, user); + await scriptClient.RunUserLoginScript(script, user); } } } @@ -188,13 +189,11 @@ namespace LANCommander.Server.Services if (scripts.Any()) { - var client = new SDK.Client(_settings.Beacon.Address, "", logger); - - client.UseToken(token); + tokenProvider.SetToken(token.AccessToken); foreach (var script in scripts) { - await client.Scripts.RunUserRegistrationScript(script, mapper.Map(user)); + await scriptClient.RunUserRegistrationScript(script, mapper.Map(user)); } } } diff --git a/LANCommander.Server.Services/Extensions/IServiceCollectionExtensions.cs b/LANCommander.Server.Services/Extensions/IServiceCollectionExtensions.cs index b0a03538..41efa35c 100644 --- a/LANCommander.Server.Services/Extensions/IServiceCollectionExtensions.cs +++ b/LANCommander.Server.Services/Extensions/IServiceCollectionExtensions.cs @@ -13,12 +13,11 @@ public static class IServiceCollectionExtensions { public static IServiceCollection AddLANCommanderServer(this IServiceCollection services, Settings settings) { - services.AddSingleton(new Client("", "")); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/LANCommander.Server.Services/GameService.cs b/LANCommander.Server.Services/GameService.cs index c5e54113..ee95a578 100644 --- a/LANCommander.Server.Services/GameService.cs +++ b/LANCommander.Server.Services/GameService.cs @@ -6,6 +6,7 @@ using LANCommander.Server.Services.Extensions; using LANCommander.SDK; using LANCommander.SDK.Enums; using System.Linq.Expressions; +using LANCommander.SDK.Services; using ZiggyCreatures.Caching.Fusion; using LANCommander.Server.Services.Models; using Microsoft.Extensions.Logging; @@ -20,8 +21,9 @@ namespace LANCommander.Server.Services IMapper mapper, IHttpContextAccessor httpContextAccessor, IDbContextFactory contextFactory, - ArchiveService archiveService, - MediaService mediaService) : BaseDatabaseService(logger, cache, mapper, httpContextAccessor, contextFactory) + ArchiveClient archiveClient, + MediaService mediaService, + SDK.Services.ScriptClient scriptClient) : BaseDatabaseService(logger, cache, mapper, httpContextAccessor, contextFactory) { public override async Task AddAsync(Game entity) { @@ -101,7 +103,7 @@ namespace LANCommander.Server.Services if (game.Archives != null) foreach (var archive in game.Archives.ToList()) - await archiveService.DeleteAsync(archive); + await archiveClient.DeleteAsync(archive); if (game.Media != null) foreach (var media in game.Media.ToList()) @@ -326,11 +328,9 @@ namespace LANCommander.Server.Services if (game.Scripts?.Any(s => s.Type == ScriptType.Package) ?? false) { - var client = new SDK.Client(_settings.Beacon.Address, "", logger); - foreach (var script in game.Scripts.Where(s => s.Type == ScriptType.Package)) { - var package = await client.Scripts.RunPackageScriptAsync(mapper.Map(script), mapper.Map(game)); + var package = await scriptClient.RunPackageScriptAsync(mapper.Map(script), mapper.Map(game)); var archive = new Archive { @@ -341,11 +341,11 @@ namespace LANCommander.Server.Services StorageLocationId = storageLocationId.GetValueOrDefault(), }; - archive = await archiveService.AddAsync(archive); + archive = await archiveClient.AddAsync(archive); if (Directory.Exists(package.Path)) { - var destination = await archiveService.GetArchiveFileLocationAsync(archive); + var destination = await archiveClient.GetArchiveFileLocationAsync(archive); ZipFile.CreateFromDirectory(package.Path, destination); @@ -355,7 +355,7 @@ namespace LANCommander.Server.Services { logger?.LogError("Could not package game {GameTitle}, the path {Path} could not be found", game.Title, package.Path); - await archiveService.DeleteAsync(archive); + await archiveClient.DeleteAsync(archive); } } } diff --git a/LANCommander.Server.Services/MediaService.cs b/LANCommander.Server.Services/MediaService.cs index 137f3cdc..2857dd17 100644 --- a/LANCommander.Server.Services/MediaService.cs +++ b/LANCommander.Server.Services/MediaService.cs @@ -153,7 +153,7 @@ namespace LANCommander.Server.Services await stream.CopyToAsync(fs); } - media.Crc32 = SDK.Services.MediaService.CalculateChecksum(path); + media.Crc32 = await SDK.Services.MediaService.CalculateChecksumAsync(path); await GenerateThumbnailAsync(media); diff --git a/LANCommander.Server.Services/RedistributableService.cs b/LANCommander.Server.Services/RedistributableService.cs index 3a2ba841..e9a4cd66 100644 --- a/LANCommander.Server.Services/RedistributableService.cs +++ b/LANCommander.Server.Services/RedistributableService.cs @@ -10,7 +10,7 @@ using ZiggyCreatures.Caching.Fusion; namespace LANCommander.Server.Services { public sealed class RedistributableService( - ILogger logger, + ILogger logger, IFusionCache cache, IMapper mapper, IHttpContextAccessor httpContextAccessor, diff --git a/LANCommander.Server.Services/ServerEngines/DockerServerEngine.cs b/LANCommander.Server.Services/ServerEngines/DockerServerEngine.cs index 3426edbe..e9476497 100644 --- a/LANCommander.Server.Services/ServerEngines/DockerServerEngine.cs +++ b/LANCommander.Server.Services/ServerEngines/DockerServerEngine.cs @@ -2,6 +2,7 @@ using AutoMapper; using Docker.DotNet; using Docker.DotNet.Models; using LANCommander.SDK; +using LANCommander.SDK.Abstractions; using LANCommander.SDK.Enums; using LANCommander.SDK.PowerShell; using LANCommander.Server.Data.Enums; @@ -18,7 +19,7 @@ public class DockerServerEngine( ILogger logger, IServiceProvider serviceProvider, IMapper mapper, - SDK.Client client) : IServerEngine + ILANCommanderConfiguration config) : IServerEngine { private ServerEngineConfiguration _config; private Dictionary _dockerClients = new(); @@ -116,7 +117,7 @@ public class DockerServerEngine( logger?.LogInformation("Executing script \"{ScriptName}\"", serverScript.Name); - if (client.Scripts.Debug) + if (config.DebugScripts) script.EnableDebug(); await script.ExecuteAsync(); @@ -169,7 +170,7 @@ public class DockerServerEngine( logger?.LogInformation("Executing script \"{ScriptName}\"", serverScript.Name); - if (client.Scripts.Debug) + if (config.DebugScripts) script.EnableDebug(); await script.ExecuteAsync(); diff --git a/LANCommander.Server.Services/ServerEngines/LocalServerEngine.cs b/LANCommander.Server.Services/ServerEngines/LocalServerEngine.cs index 4a83671c..ee85f7e8 100644 --- a/LANCommander.Server.Services/ServerEngines/LocalServerEngine.cs +++ b/LANCommander.Server.Services/ServerEngines/LocalServerEngine.cs @@ -1,6 +1,8 @@ using AutoMapper; using LANCommander.SDK; +using LANCommander.SDK.Abstractions; using LANCommander.SDK.Enums; +using LANCommander.SDK.Factories; using LANCommander.SDK.PowerShell; using LANCommander.Server.Data.Enums; using LANCommander.Server.Data.Models; @@ -17,8 +19,9 @@ namespace LANCommander.Server.Services.ServerEngines; public class LocalServerEngine( ILogger logger, IMapper mapper, - SDK.Client client, - IServiceProvider serviceProvider) : IServerEngine + IServiceProvider serviceProvider, + ProcessExecutionContextFactory processExecutionContextFactory, + ILANCommanderConfiguration config) : IServerEngine { public event EventHandler? OnServerStatusUpdate; public event EventHandler? OnServerLog; @@ -99,7 +102,7 @@ public class LocalServerEngine( } } - using (var executionContext = new ProcessExecutionContext(client, logger)) + using (var executionContext = processExecutionContextFactory.Create()) { try { @@ -189,7 +192,7 @@ public class LocalServerEngine( logger?.LogInformation("Executing script \"{ScriptName}\"", serverScript.Name); - if (client.Scripts.Debug) + if (config.DebugScripts) script.EnableDebug(); await script.ExecuteAsync(); diff --git a/LANCommander.Server.Tests/Services/GameServiceTests.cs b/LANCommander.Server.Tests/Services/GameClientTests.cs similarity index 99% rename from LANCommander.Server.Tests/Services/GameServiceTests.cs rename to LANCommander.Server.Tests/Services/GameClientTests.cs index 16e7d989..137b6632 100644 --- a/LANCommander.Server.Tests/Services/GameServiceTests.cs +++ b/LANCommander.Server.Tests/Services/GameClientTests.cs @@ -6,7 +6,7 @@ using Shouldly; namespace LANCommander.Server.Tests.Services; [Collection("Application")] -public class GameServiceTests(ApplicationFixture fixture) : BaseTest(fixture) +public class GameClientTests(ApplicationFixture fixture) : BaseTest(fixture) { /*[Fact] public async Task ImportMetadataExportShouldWorkAsync() diff --git a/LANCommander.Server.Tests/Services/ImporterTests.cs b/LANCommander.Server.Tests/Services/ImporterTests.cs new file mode 100644 index 00000000..5389dfc2 --- /dev/null +++ b/LANCommander.Server.Tests/Services/ImporterTests.cs @@ -0,0 +1,278 @@ +using LANCommander.Server.Services.Factories; +using Action = LANCommander.SDK.Models.Manifest.Action; +using LANCommander.SDK.Enums; +using LANCommander.Server.ImportExport.Factories; + +namespace LANCommander.Server.Tests.Services; + +[Collection("Application")] +public class ImporterTests(ApplicationFixture fixture) : BaseTest(fixture) +{ + [Fact] + public async Task ImportGameWorks() + { + var importContextFactory = GetService(); + var importContext = importContextFactory.Create(); + + var manifest = new SDK.Models.Manifest.Game + { + Id = Guid.NewGuid(), + Title = "Test Game", + SortTitle = "Test Game", + DirectoryName = "TestGame", + Description = "A comprehensive test game for import testing", + Notes = "Test notes for the game", + Singleplayer = true, + ReleasedOn = DateTime.Now.AddYears(-1), + InstallDirectory = "C:\\Games\\TestGame", + Type = GameType.MainGame, + BaseGame = null, + + // Actions + Actions = new List + { + new Action + { + Name = "Launch Game", + Arguments = "-fullscreen", + Path = "game.exe", + WorkingDirectory = "", + IsPrimaryAction = true, + SortOrder = 0 + }, + new Action + { + Name = "Launch Editor", + Arguments = "-editor", + Path = "editor.exe", + WorkingDirectory = "", + IsPrimaryAction = false, + SortOrder = 1 + } + }, + + // Archives + Archives = new List + { + new SDK.Models.Manifest.Archive + { + Id = Guid.NewGuid(), + Version = "1.0.0", + Changelog = "Initial release", + CompressedSize = 1024000, + UncompressedSize = 2048000, + ObjectKey = "test-archive-1.0.0.zip" + } + }, + + // Collections + Collections = new List + { + new SDK.Models.Manifest.Collection + { + Name = "Test Collection" + } + }, + + // Custom Fields + CustomFields = new List + { + new SDK.Models.Manifest.GameCustomField("TestField", "TestValue"), + new SDK.Models.Manifest.GameCustomField("AnotherField", "AnotherValue") + }, + + // Developers + Developers = new List + { + new SDK.Models.Manifest.Company + { + Name = "Test Developer" + } + }, + + // Engine + Engine = new SDK.Models.Manifest.Engine + { + Name = "Test Engine" + }, + + // Genres + Genres = new List + { + new SDK.Models.Manifest.Genre + { + Name = "Action" + }, + new SDK.Models.Manifest.Genre + { + Name = "Adventure" + } + }, + + // Keys + Keys = new List + { + new SDK.Models.Manifest.Key + { + Value = "TEST-KEY-1234-5678-9ABC", + AllocationMethod = KeyAllocationMethod.UserAccount, + ClaimedByComputerName = null, + ClaimedByIpv4Address = null, + ClaimedByMacAddress = null + } + }, + + // Media + Media = new List + { + new SDK.Models.Manifest.Media + { + Id = Guid.NewGuid(), + FileId = Guid.NewGuid(), + Name = "Game Cover", + Type = MediaType.Cover, + SourceUrl = "https://example.com/cover.jpg", + MimeType = "image/jpeg", + Crc32 = "12345678" + }, + new SDK.Models.Manifest.Media + { + Id = Guid.NewGuid(), + FileId = Guid.NewGuid(), + Name = "Game Icon", + Type = MediaType.Icon, + SourceUrl = "https://example.com/icon.ico", + MimeType = "image/x-icon", + Crc32 = "87654321" + } + }, + + // Multiplayer Modes + MultiplayerModes = new List + { + new SDK.Models.Manifest.MultiplayerMode + { + Type = MultiplayerType.Local, + NetworkProtocol = NetworkProtocol.TCPIP, + Description = "Local multiplayer for 2-4 players", + MinPlayers = 2, + MaxPlayers = 4, + Spectators = 0 + } + }, + + // Platforms + Platforms = new List + { + new SDK.Models.Manifest.Platform + { + Name = "Windows" + }, + new SDK.Models.Manifest.Platform + { + Name = "Linux" + } + }, + + // Play Sessions + PlaySessions = new List + { + new SDK.Models.Manifest.PlaySession + { + Start = DateTime.Now.AddDays(-1), + End = DateTime.Now.AddHours(-2), + User = "DoctorDalek" + } + }, + + // Publishers + Publishers = new List + { + new SDK.Models.Manifest.Company + { + Name = "Test Publisher" + } + }, + + // Saves + Saves = new List + { + new SDK.Models.Manifest.Save + { + Id = Guid.NewGuid(), + User = "TestUser" + } + }, + + // Save Paths + SavePaths = new List + { + new SDK.Models.Manifest.SavePath + { + Id = Guid.NewGuid(), + Type = SavePathType.File, + Path = "save\\*.sav", + WorkingDirectory = "", + IsRegex = false, + } + }, + + // Scripts + Scripts = new List + { + new SDK.Models.Manifest.Script + { + Id = Guid.NewGuid(), + Type = ScriptType.Install, + Name = "Install Script", + Description = "Script to install the game", + RequiresAdmin = false, + } + }, + + // Tags + Tags = new List + { + new SDK.Models.Manifest.Tag + { + Name = "Test Tag" + }, + new SDK.Models.Manifest.Tag + { + Name = "Another Tag" + } + } + }; + + // Set the manifest on the import context + + // Prepare the import queue with all flags + var importFlags = ImportRecordFlags.Actions | ImportRecordFlags.Archives | ImportRecordFlags.Collections | + ImportRecordFlags.CustomFields | ImportRecordFlags.Developers | ImportRecordFlags.Engine | + ImportRecordFlags.Genres | ImportRecordFlags.Keys | ImportRecordFlags.Media | + ImportRecordFlags.MultiplayerModes | ImportRecordFlags.Platforms | ImportRecordFlags.PlaySessions | + ImportRecordFlags.Publishers | ImportRecordFlags.Saves | ImportRecordFlags.SavePaths | + ImportRecordFlags.Scripts | ImportRecordFlags.Tags; + + await importContext.PrepareGameImportQueueAsync(manifest, importFlags); + + // Import the queue + await importContext.ImportQueueAsync(); + + // Assert that the game was imported successfully + Assert.NotNull(importContext.DataRecord); + Assert.IsType(importContext.DataRecord); + + var importedGame = (LANCommander.Server.Data.Models.Game)importContext.DataRecord; + Assert.Equal("Test Game", importedGame.Title); + Assert.Equal("A comprehensive test game for import testing", importedGame.Description); + + // Assert that all items were processed + // Note: The exact count may vary depending on how the importers handle the data + // We expect at least some items to be processed + Assert.True(importContext.Processed > 0, "At least some items should have been processed"); + + // Clean up + importContext.Dispose(); + } +} \ No newline at end of file diff --git a/LANCommander.Server.Tests/Services/SaveServiceTests.cs b/LANCommander.Server.Tests/Services/SaveClientTests.cs similarity index 98% rename from LANCommander.Server.Tests/Services/SaveServiceTests.cs rename to LANCommander.Server.Tests/Services/SaveClientTests.cs index 275f9f46..f21d881c 100644 --- a/LANCommander.Server.Tests/Services/SaveServiceTests.cs +++ b/LANCommander.Server.Tests/Services/SaveClientTests.cs @@ -15,7 +15,7 @@ using Shouldly; namespace LANCommander.Server.Tests.Services; [Collection("Application")] -public class SaveServiceTests(ApplicationFixture fixture) : BaseTest(fixture) +public class SaveClientTests(ApplicationFixture fixture) : BaseTest(fixture) { [Fact] public async Task ArchiveCreationWorks() diff --git a/LANCommander.Server/Controllers/Api/ArchivesController.cs b/LANCommander.Server/Controllers/Api/ArchivesController.cs index 6e7daa9d..95d71499 100644 --- a/LANCommander.Server/Controllers/Api/ArchivesController.cs +++ b/LANCommander.Server/Controllers/Api/ArchivesController.cs @@ -18,27 +18,27 @@ namespace LANCommander.Server.Controllers.Api public class ArchivesController : BaseApiController { private readonly IFusionCache Cache; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; public ArchivesController( ILogger logger, IFusionCache cache, - ArchiveService archiveService) : base(logger) + ArchiveClient archiveClient) : base(logger) { Cache = cache; - ArchiveService = archiveService; + _archiveClient = archiveClient; } [HttpGet] public async Task>> GetAsync() { - return Ok(await ArchiveService.GetAsync()); + return Ok(await _archiveClient.GetAsync()); } [HttpGet("{id}")] public async Task> GetAsync(Guid id) { - var archive = await ArchiveService.GetAsync(id); + var archive = await _archiveClient.GetAsync(id); if (archive != null) return Ok(archive); @@ -49,7 +49,7 @@ namespace LANCommander.Server.Controllers.Api [HttpGet("Download/{id}")] public async Task DownloadAsync(Guid id) { - var archive = await ArchiveService.GetAsync(id); + var archive = await _archiveClient.GetAsync(id); if (archive == null) { @@ -57,7 +57,7 @@ namespace LANCommander.Server.Controllers.Api return NotFound(); } - var filename = await ArchiveService.GetArchiveFileLocationAsync(archive); + var filename = await _archiveClient.GetArchiveFileLocationAsync(archive); if (!System.IO.File.Exists(filename)) { @@ -71,7 +71,7 @@ namespace LANCommander.Server.Controllers.Api [HttpGet("Contents/{gameId}/{version}")] public async Task ByVersionAsync(Guid gameId, string version) { - var archive = await ArchiveService.FirstOrDefaultAsync(a => a.GameId == gameId && a.Version == version); + var archive = await _archiveClient.FirstOrDefaultAsync(a => a.GameId == gameId && a.Version == version); if (archive == null) return NotFound(); @@ -82,7 +82,7 @@ namespace LANCommander.Server.Controllers.Api [HttpGet("Contents/{id}")] public async Task ContentsAsync(Guid id, string version = null) { - var archive = await ArchiveService.GetAsync(id); + var archive = await _archiveClient.GetAsync(id); if (archive == null) { @@ -92,7 +92,7 @@ namespace LANCommander.Server.Controllers.Api var entries = await Cache.GetOrSetAsync>($"Archive/{archive.Id}/Contents", async _ => { - var filename = await ArchiveService.GetArchiveFileLocationAsync(archive); + var filename = await _archiveClient.GetArchiveFileLocationAsync(archive); if (!System.IO.File.Exists(filename)) { diff --git a/LANCommander.Server/Controllers/Api/GamesController.cs b/LANCommander.Server/Controllers/Api/GamesController.cs index 018027a4..1aaa31f9 100644 --- a/LANCommander.Server/Controllers/Api/GamesController.cs +++ b/LANCommander.Server/Controllers/Api/GamesController.cs @@ -24,7 +24,7 @@ namespace LANCommander.Server.Controllers.Api private readonly GameService GameService; private readonly LibraryService LibraryService; private readonly StorageLocationService StorageLocationService; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; private readonly UserService UserService; private readonly PlaySessionService PlaySessionService; private readonly ServerService ServerService; @@ -41,7 +41,7 @@ namespace LANCommander.Server.Controllers.Api GameService gameService, LibraryService libraryService, StorageLocationService storageLocationService, - ArchiveService archiveService, + ArchiveClient archiveClient, UserService userService, PlaySessionService playSessionService, ServerService serverService, @@ -51,7 +51,7 @@ namespace LANCommander.Server.Controllers.Api LibraryService = libraryService; StorageLocationService = storageLocationService; - ArchiveService = archiveService; + _archiveClient = archiveClient; UserService = userService; PlaySessionService = playSessionService; ServerService = serverService; @@ -287,7 +287,7 @@ namespace LANCommander.Server.Controllers.Api [HttpGet("{id}/CheckForUpdate")] public async Task CheckForUpdateAsync(Guid id, string version) { - var gameArchives = await ArchiveService.GetAsync(a => a.GameId == id); + var gameArchives = await _archiveClient.GetAsync(a => a.GameId == id); var latestArchive = gameArchives.OrderByDescending(a => a.CreatedOn).FirstOrDefault(); @@ -325,7 +325,7 @@ namespace LANCommander.Server.Controllers.Api var archive = game.Archives.OrderByDescending(a => a.CreatedOn).First(); - var filename = await ArchiveService.GetArchiveFileLocationAsync(archive); + var filename = await _archiveClient.GetArchiveFileLocationAsync(archive); if (!System.IO.File.Exists(filename)) { @@ -342,7 +342,7 @@ namespace LANCommander.Server.Controllers.Api { try { - var uploadedPath = await ArchiveService.GetArchiveFileLocationAsync(objectKey.ToString()); + var uploadedPath = await _archiveClient.GetArchiveFileLocationAsync(objectKey.ToString()); var result = await ImportContext.InitializeImportAsync(uploadedPath); @@ -362,12 +362,12 @@ namespace LANCommander.Server.Controllers.Api try { var storageLocation = await StorageLocationService.FirstOrDefaultAsync(l => request.StorageLocationId.HasValue ? l.Id == request.StorageLocationId.Value : l.Default); - var archive = await ArchiveService.FirstOrDefaultAsync(a => a.GameId == request.Id && a.Version == request.Version); - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var archive = await _archiveClient.FirstOrDefaultAsync(a => a.GameId == request.Id && a.Version == request.Version); + var archivePath = await _archiveClient.GetArchiveFileLocationAsync(archive); if (archive != null) { - var existingArchivePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var existingArchivePath = await _archiveClient.GetArchiveFileLocationAsync(archive); System.IO.File.Delete(existingArchivePath); @@ -376,7 +376,7 @@ namespace LANCommander.Server.Controllers.Api archive.CompressedSize = new System.IO.FileInfo(archivePath).Length; archive.StorageLocation = storageLocation; - archive = await ArchiveService.UpdateAsync(archive); + archive = await _archiveClient.UpdateAsync(archive); } else { @@ -389,7 +389,7 @@ namespace LANCommander.Server.Controllers.Api StorageLocation = storageLocation }; - await ArchiveService.AddAsync(archive); + await _archiveClient.AddAsync(archive); } return Ok(); diff --git a/LANCommander.Server/Controllers/Api/RedistributablesController.cs b/LANCommander.Server/Controllers/Api/RedistributablesController.cs index 6ea5a418..4a94cdee 100644 --- a/LANCommander.Server/Controllers/Api/RedistributablesController.cs +++ b/LANCommander.Server/Controllers/Api/RedistributablesController.cs @@ -18,7 +18,7 @@ namespace LANCommander.Server.Controllers.Api private readonly IMapper Mapper; private readonly RedistributableService RedistributableService; private readonly StorageLocationService StorageLocationService; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; private readonly ImportContext ImportContext; public RedistributablesController( @@ -26,13 +26,13 @@ namespace LANCommander.Server.Controllers.Api IMapper mapper, RedistributableService redistributableService, StorageLocationService storageLocationService, - ArchiveService archiveService, + ArchiveClient archiveClient, ImportContext importContext) : base(logger) { Mapper = mapper; RedistributableService = redistributableService; StorageLocationService = storageLocationService; - ArchiveService = archiveService; + _archiveClient = archiveClient; ImportContext = importContext; } @@ -71,7 +71,7 @@ namespace LANCommander.Server.Controllers.Api var archive = redistributable.Archives.OrderByDescending(a => a.CreatedOn).First(); - var filename = await ArchiveService.GetArchiveFileLocationAsync(archive); + var filename = await _archiveClient.GetArchiveFileLocationAsync(archive); if (!System.IO.File.Exists(filename)) return NotFound(); @@ -85,7 +85,7 @@ namespace LANCommander.Server.Controllers.Api { try { - var uploadedPath = await ArchiveService.GetArchiveFileLocationAsync(objectKey.ToString()); + var uploadedPath = await _archiveClient.GetArchiveFileLocationAsync(objectKey.ToString()); var result = await ImportContext.InitializeImportAsync(uploadedPath); @@ -105,8 +105,8 @@ namespace LANCommander.Server.Controllers.Api try { var storageLocation = await StorageLocationService.FirstOrDefaultAsync(l => request.StorageLocationId.HasValue ? l.Id == request.StorageLocationId.Value : l.Default); - var archive = await ArchiveService.FirstOrDefaultAsync(a => a.RedistributableId == request.Id && a.Version == request.Version); - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var archive = await _archiveClient.FirstOrDefaultAsync(a => a.RedistributableId == request.Id && a.Version == request.Version); + var archivePath = await _archiveClient.GetArchiveFileLocationAsync(archive); if (archive != null) { @@ -117,7 +117,7 @@ namespace LANCommander.Server.Controllers.Api archive.CompressedSize = new System.IO.FileInfo(archivePath).Length; archive.StorageLocation = storageLocation; - archive = await ArchiveService.UpdateAsync(archive); + archive = await _archiveClient.UpdateAsync(archive); } else { @@ -130,7 +130,7 @@ namespace LANCommander.Server.Controllers.Api StorageLocation = storageLocation, }; - await ArchiveService.AddAsync(archive); + await _archiveClient.AddAsync(archive); } return Ok(); diff --git a/LANCommander.Server/Controllers/Api/UploadController.cs b/LANCommander.Server/Controllers/Api/UploadController.cs index b44ee25e..62e466df 100644 --- a/LANCommander.Server/Controllers/Api/UploadController.cs +++ b/LANCommander.Server/Controllers/Api/UploadController.cs @@ -14,17 +14,17 @@ namespace LANCommander.Server.Controllers.Api public class UploadController : BaseApiController { private readonly StorageLocationService StorageLocationService; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; private readonly IFusionCache Cache; public UploadController( ILogger logger, StorageLocationService storageLocationService, - ArchiveService archiveService, + ArchiveClient archiveClient, IFusionCache cache) : base(logger) { StorageLocationService = storageLocationService; - ArchiveService = archiveService; + _archiveClient = archiveClient; Cache = cache; } @@ -43,9 +43,9 @@ namespace LANCommander.Server.Controllers.Api Version = "" }; - archive = await ArchiveService.AddAsync(archive); + archive = await _archiveClient.AddAsync(archive); - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var archivePath = await _archiveClient.GetArchiveFileLocationAsync(archive); await Cache.SetAsync($"ChunkArchivePath/{archive.ObjectKey}", archivePath, TimeSpan.FromHours(6)); diff --git a/LANCommander.Server/Controllers/RedistributablesController.cs b/LANCommander.Server/Controllers/RedistributablesController.cs index a10a878c..3bda1c00 100644 --- a/LANCommander.Server/Controllers/RedistributablesController.cs +++ b/LANCommander.Server/Controllers/RedistributablesController.cs @@ -12,17 +12,17 @@ namespace LANCommander.Server.Controllers { private readonly IMapper Mapper; private readonly RedistributableService RedistributableService; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; public RedistributablesController( ILogger logger, IMapper mapper, RedistributableService redistributableService, - ArchiveService archiveService) : base(logger) + ArchiveClient archiveClient) : base(logger) { Mapper = mapper; RedistributableService = redistributableService; - ArchiveService = archiveService; + _archiveClient = archiveClient; } [HttpGet("/Redistributables/{id:guid}/Export")] @@ -67,7 +67,7 @@ namespace LANCommander.Server.Controllers if (redistributable.Archives != null) foreach (var archive in redistributable.Archives) { - var archiveFilePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var archiveFilePath = await _archiveClient.GetArchiveFileLocationAsync(archive); var entry = export.CreateEntry($"Archives/{archive.ObjectKey}", CompressionLevel.NoCompression); using (var entryStream = entry.Open()) diff --git a/LANCommander.Server/Controllers/UploadController.cs b/LANCommander.Server/Controllers/UploadController.cs index 2fc6e489..7f170434 100644 --- a/LANCommander.Server/Controllers/UploadController.cs +++ b/LANCommander.Server/Controllers/UploadController.cs @@ -13,17 +13,17 @@ namespace LANCommander.Server.Controllers public class UploadController : BaseController { private readonly StorageLocationService StorageLocationService; - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; private readonly IFusionCache Cache; public UploadController( ILogger logger, StorageLocationService storageLocationService, - ArchiveService archiveService, + ArchiveClient archiveClient, IFusionCache cache) : base(logger) { StorageLocationService = storageLocationService; - ArchiveService = archiveService; + _archiveClient = archiveClient; Cache = cache; } diff --git a/LANCommander.Server/Endpoints/DownloadEndpoints.cs b/LANCommander.Server/Endpoints/DownloadEndpoints.cs index 5858539c..3bdeafb9 100644 --- a/LANCommander.Server/Endpoints/DownloadEndpoints.cs +++ b/LANCommander.Server/Endpoints/DownloadEndpoints.cs @@ -20,9 +20,9 @@ public static class DownloadEndpoints internal static async Task DownloadArchiveAsync( Guid id, - [FromServices] ArchiveService archiveService) + [FromServices] ArchiveClient archiveClient) { - var archive = await archiveService + var archive = await archiveClient .Include(a => a.Game) .Include(a => a.Redistributable) .GetAsync(id); @@ -30,7 +30,7 @@ public static class DownloadEndpoints if (archive == null) return TypedResults.NotFound(); - var fileName = await archiveService.GetArchiveFileLocationAsync(archive); + var fileName = await archiveClient.GetArchiveFileLocationAsync(archive); if (!File.Exists(fileName)) return TypedResults.NotFound(); diff --git a/LANCommander.Server/Jobs/Background/PatchArchiveBackgroundJob.cs b/LANCommander.Server/Jobs/Background/PatchArchiveBackgroundJob.cs index 83354179..64ffa852 100644 --- a/LANCommander.Server/Jobs/Background/PatchArchiveBackgroundJob.cs +++ b/LANCommander.Server/Jobs/Background/PatchArchiveBackgroundJob.cs @@ -4,19 +4,19 @@ namespace LANCommander.Server.Jobs.Background { public class PatchArchiveBackgroundJob { - private readonly ArchiveService ArchiveService; + private readonly ArchiveClient _archiveClient; - public PatchArchiveBackgroundJob(ArchiveService archiveService) + public PatchArchiveBackgroundJob(ArchiveClient archiveClient) { - ArchiveService = archiveService; + _archiveClient = archiveClient; } public async Task Execute(Guid originalArchiveId, Guid alteredArchiveId) { - var originalArchive = await ArchiveService.GetAsync(originalArchiveId); - var alteredArchive = await ArchiveService.GetAsync(alteredArchiveId); + var originalArchive = await _archiveClient.GetAsync(originalArchiveId); + var alteredArchive = await _archiveClient.GetAsync(alteredArchiveId); - await ArchiveService.PatchArchiveAsync(originalArchive, alteredArchive); + await _archiveClient.PatchArchiveAsync(originalArchive, alteredArchive); } } } diff --git a/LANCommander.Server/Startup/Beacon.cs b/LANCommander.Server/Startup/Beacon.cs index b83c38b1..eb5f8fbe 100644 --- a/LANCommander.Server/Startup/Beacon.cs +++ b/LANCommander.Server/Startup/Beacon.cs @@ -1,4 +1,5 @@ using LANCommander.SDK; +using LANCommander.SDK.Services; using LANCommander.Server.Interceptors; using LANCommander.Server.Services; @@ -9,12 +10,12 @@ public static class Beacon public static async Task StartBeaconAsync(this WebApplication app) { var settings = SettingService.GetSettings(); - var client = app.Services.GetRequiredService(); + var beaconService = app.Services.GetRequiredService(); - client.Beacon.Initialize(); - client.Beacon.AddBeaconMessageInterceptor(new BeaconMessageInterceptor()); + beaconService.Initialize(); + beaconService.AddBeaconMessageInterceptor(new BeaconMessageInterceptor()); if (settings.Beacon.Enabled) - await client.Beacon.StartBeaconAsync(settings.Beacon.Port, settings.Beacon.Address, settings.Beacon.Name); + await beaconService.StartBeaconAsync(settings.Beacon.Port, settings.Beacon.Address, settings.Beacon.Name); } } \ No newline at end of file diff --git a/LANCommander.Server/UI/Components/ArchiveEditor.razor b/LANCommander.Server/UI/Components/ArchiveEditor.razor index 5d8551dc..ddd4f89c 100644 --- a/LANCommander.Server/UI/Components/ArchiveEditor.razor +++ b/LANCommander.Server/UI/Components/ArchiveEditor.razor @@ -3,7 +3,7 @@ @using Hangfire; @using LANCommander.Server.Jobs.Background; @using Microsoft.EntityFrameworkCore; -@inject ArchiveService archiveService +@inject ArchiveClient ArchiveClient @inject HttpClient HttpClient @inject NavigationManager Navigator @inject ModalService ModalService @@ -79,7 +79,7 @@ var results = new List(); foreach (var archive in archives) { - var result = await archiveService.RecalculateFileSizeArchiveAsync(archive); + var result = await ArchiveClient.RecalculateFileSizeArchiveAsync(archive); results.Add(result); } @@ -97,8 +97,8 @@ { MessageService.Info("Recalculating File Sizes..."); - archive = await archiveService.AsNoTracking().GetAsync(archive.Id); - var result = await archiveService.RecalculateFileSizeArchiveAsync(archive); + archive = await ArchiveClient.AsNoTracking().GetAsync(archive.Id); + var result = await ArchiveClient.RecalculateFileSizeArchiveAsync(archive); await ArchiveUploaded(archive.Id); if(result) @@ -142,7 +142,7 @@ { try { - await archiveService.UpdateAsync(archive); + await ArchiveClient.UpdateAsync(archive); Table.Reload(); @@ -159,7 +159,7 @@ { try { - await archiveService.DeleteAsync(archive); + await ArchiveClient.DeleteAsync(archive); Table.Reload(); diff --git a/LANCommander.Server/UI/Components/ArchiveUploader.razor b/LANCommander.Server/UI/Components/ArchiveUploader.razor index 5c821810..e882c4af 100644 --- a/LANCommander.Server/UI/Components/ArchiveUploader.razor +++ b/LANCommander.Server/UI/Components/ArchiveUploader.razor @@ -1,7 +1,7 @@ @using Hangfire; @using LANCommander.SDK.Enums @using LANCommander.Server.Jobs.Background; -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject HttpClient HttpClient @inject NavigationManager Navigator @inject IMessageService MessageService @@ -94,7 +94,7 @@ { if (archiveId.HasValue && archiveId != Guid.Empty) { - Archive = await ArchiveService.GetAsync(archiveId.Value); + Archive = await ArchiveClient.GetAsync(archiveId.Value); } else { @@ -117,16 +117,16 @@ if (Guid.TryParse(data, out var objectKey)) { - var uploadedArchive = await ArchiveService.FirstOrDefaultAsync(a => a.ObjectKey == objectKey.ToString()); + var uploadedArchive = await ArchiveClient.FirstOrDefaultAsync(a => a.ObjectKey == objectKey.ToString()); uploadedArchive.GameId = Archive.GameId; uploadedArchive.RedistributableId = Archive.RedistributableId; uploadedArchive.Version = Archive.Version; uploadedArchive.Changelog = Archive.Changelog; - uploadedArchive.CompressedSize = await ArchiveService.GetCompressedSizeAsync(uploadedArchive); - uploadedArchive.UncompressedSize = await ArchiveService.GetUncompressedSizeAsync(uploadedArchive); + uploadedArchive.CompressedSize = await ArchiveClient.GetCompressedSizeAsync(uploadedArchive); + uploadedArchive.UncompressedSize = await ArchiveClient.GetUncompressedSizeAsync(uploadedArchive); - await ArchiveService.UpdateAsync(uploadedArchive); + await ArchiveClient.UpdateAsync(uploadedArchive); Visible = false; @@ -139,9 +139,9 @@ if (settings.Archives.EnablePatching) { if (Archive.GameId != Guid.Empty) - lastArchive = await ArchiveService.GetLatestArchive(a => a.Id != Archive.Id && a.GameId == Archive.GameId); + lastArchive = await ArchiveClient.GetLatestArchive(a => a.Id != Archive.Id && a.GameId == Archive.GameId); else if (Archive.RedistributableId != Guid.Empty) - lastArchive = await ArchiveService.GetLatestArchive(a => a.Id != Archive.Id && a.RedistributableId == Archive.RedistributableId); + lastArchive = await ArchiveClient.GetLatestArchive(a => a.Id != Archive.Id && a.RedistributableId == Archive.RedistributableId); if (lastArchive != null && settings.Archives.EnablePatching) BackgroundJob.Enqueue(x => x.Execute(lastArchive.Id, Archive.Id)); @@ -180,7 +180,7 @@ { try { - var objectKey = await ArchiveService.CopyFromLocalFileAsync(path); + var objectKey = await ArchiveClient.CopyFromLocalFileAsync(path); await OnUploadCompleted(objectKey.ToString()); } diff --git a/LANCommander.Server/UI/Components/ExportDialog.razor b/LANCommander.Server/UI/Components/ExportDialog.razor index 556be5a0..8f1179ad 100644 --- a/LANCommander.Server/UI/Components/ExportDialog.razor +++ b/LANCommander.Server/UI/Components/ExportDialog.razor @@ -4,7 +4,7 @@ @using LANCommander.Server.ImportExport.Models @using LANCommander.Server.ImportExport.Services @inherits FeedbackComponent -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject ExportService ExportService @inject ExportContextFactory ExportContextFactory @inject IMessageService MessageService @@ -149,7 +149,7 @@ { try { - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(objectKey.ToString()); + var archivePath = await ArchiveClient.GetArchiveFileLocationAsync(objectKey.ToString()); ExportItems = await ExportContext.InitializeExportAsync(Options.RecordId, Options.RecordType); diff --git a/LANCommander.Server/UI/Components/FilePickerButton.razor b/LANCommander.Server/UI/Components/FilePickerButton.razor index c9b54efb..05f4175a 100644 --- a/LANCommander.Server/UI/Components/FilePickerButton.razor +++ b/LANCommander.Server/UI/Components/FilePickerButton.razor @@ -1,4 +1,4 @@ -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject ModalService ModalService @if (ArchiveId != Guid.Empty) @@ -32,7 +32,7 @@ else if (!String.IsNullOrWhiteSpace(Root)) protected override async Task OnInitializedAsync() { if (ArchiveId != Guid.Empty) - ArchiveExists = await ArchiveService.ExistsAsync(ArchiveId); + ArchiveExists = await ArchiveClient.ExistsAsync(ArchiveId); } private async void BrowseForFile() diff --git a/LANCommander.Server/UI/Components/ImportUploadDialog.razor b/LANCommander.Server/UI/Components/ImportUploadDialog.razor index 996f43b4..3e89e7ea 100644 --- a/LANCommander.Server/UI/Components/ImportUploadDialog.razor +++ b/LANCommander.Server/UI/Components/ImportUploadDialog.razor @@ -5,7 +5,7 @@ @using LANCommander.Server.ImportExport.Services @inherits FeedbackComponent @inject GameService GameService -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject StorageLocationService StorageLocationService @inject ImportContextFactory ImportContextFactory @inject IMessageService MessageService @@ -231,7 +231,7 @@ else if (_stage == ImportStage.Importing) { try { - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(objectKey.ToString()); + var archivePath = await ArchiveClient.GetArchiveFileLocationAsync(objectKey.ToString()); ImportItems = await ImportContext.InitializeImportAsync(archivePath); diff --git a/LANCommander.Server/UI/Components/TaxonomyInput.razor b/LANCommander.Server/UI/Components/TaxonomyInput.razor new file mode 100644 index 00000000..bffc221c --- /dev/null +++ b/LANCommander.Server/UI/Components/TaxonomyInput.razor @@ -0,0 +1,36 @@ +@typeparam TTaxonomy where TTaxonomy : BaseTaxonomyModel + + + +@code { + [Parameter] public BaseDatabaseService DataService { get; set; } + [Parameter] public ICollection Values { get; set; } + [Parameter] public EventCallback> ValuesChanged { get; set; } + + ICollection _entities = new List(); + + protected override async Task OnInitializedAsync() + { + _entities = await DataService.AsNoTracking().GetAsync(); + } + + async Task Add(string name) + { + var taxonomy = Activator.CreateInstance(typeof(TTaxonomy)) as TTaxonomy; + + taxonomy.Name = name; + + taxonomy = await DataService.AddAsync(taxonomy); + + _entities.Add(taxonomy); + Values.Add(taxonomy); + + if (ValuesChanged.HasDelegate) + await ValuesChanged.InvokeAsync(Values); + } +} \ No newline at end of file diff --git a/LANCommander.Server/UI/Pages/Games/Edit/Actions.razor b/LANCommander.Server/UI/Pages/Games/Edit/Actions.razor index 00650c49..31779f8e 100644 --- a/LANCommander.Server/UI/Pages/Games/Edit/Actions.razor +++ b/LANCommander.Server/UI/Pages/Games/Edit/Actions.razor @@ -1,6 +1,6 @@ @page "/Games/{id:guid}/Actions" @attribute [Authorize(Roles = RoleService.AdministratorRoleName)] -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @@ -25,7 +25,7 @@ protected override async Task OnInitializedAsync() { - var latestArchive = await ArchiveService.GetLatestArchive(a => a.GameId == Id); + var latestArchive = await ArchiveClient.GetLatestArchive(a => a.GameId == Id); if (latestArchive != null) ArchiveId = latestArchive.Id; diff --git a/LANCommander.Server/UI/Pages/Games/Edit/General.razor b/LANCommander.Server/UI/Pages/Games/Edit/General.razor index 43611420..00461e6c 100644 --- a/LANCommander.Server/UI/Pages/Games/Edit/General.razor +++ b/LANCommander.Server/UI/Pages/Games/Edit/General.razor @@ -121,22 +121,22 @@ - + - + - + - + - + - + Logger @attribute [Authorize(Roles = RoleService.AdministratorRoleName)] @@ -41,9 +43,9 @@ MessageService.Success("Settings saved!"); if (Settings.Beacon.Enabled) - await Client.Beacon.StartBeaconAsync(Settings.Beacon.Port, Settings.Beacon.Address, Settings.Beacon.Name); + await BeaconClient.StartBeaconAsync(Settings.Beacon.Port, Settings.Beacon.Address, Settings.Beacon.Name); else - await Client.Beacon.StopBeaconAsync(); + await BeaconClient.StopBeaconAsync(); } catch (Exception ex) { diff --git a/LANCommander.Server/UI/Pages/Settings/Tools/Index.razor b/LANCommander.Server/UI/Pages/Settings/Tools/Index.razor index 1961a9c3..a9dc8485 100644 --- a/LANCommander.Server/UI/Pages/Settings/Tools/Index.razor +++ b/LANCommander.Server/UI/Pages/Settings/Tools/Index.razor @@ -4,7 +4,7 @@ @using LANCommander.Server.Jobs.Background @using LANCommander.Server.Services.Exceptions @using ZiggyCreatures.Caching.Fusion -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject PageService PageService @inject UpdateService UpdateService @inject StorageLocationService StorageLocationService @@ -80,13 +80,13 @@ await Task.Yield(); await InvokeAsync(StateHasChanged); - var archives = await ArchiveService.AsNoTracking().GetAsync(); + var archives = await ArchiveClient.AsNoTracking().GetAsync(); var results = new List(); foreach (var archive in archives) { - var result = await ArchiveService.RecalculateFileSizeArchiveAsync(archive); + var result = await ArchiveClient.RecalculateFileSizeArchiveAsync(archive); results.Add(result); } diff --git a/LANCommander.Server/UI/Pages/Settings/Tools/MissingArchives.razor b/LANCommander.Server/UI/Pages/Settings/Tools/MissingArchives.razor index 192bde91..c41c3187 100644 --- a/LANCommander.Server/UI/Pages/Settings/Tools/MissingArchives.razor +++ b/LANCommander.Server/UI/Pages/Settings/Tools/MissingArchives.razor @@ -1,5 +1,5 @@ @page "/Settings/Tools/MissingArchives" -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject IMessageService MessageService @inject ILogger Logger @attribute [Authorize(Roles = RoleService.AdministratorRoleName)] @@ -53,10 +53,10 @@ Archives = new List(); - foreach (var archive in await ArchiveService.GetAsync()) + foreach (var archive in await ArchiveClient.GetAsync()) { - var archivePath = await ArchiveService.GetArchiveFileLocationAsync(archive); - var exists = await ArchiveService.ExistsAsync(archive.Id); + var archivePath = await ArchiveClient.GetArchiveFileLocationAsync(archive); + var exists = await ArchiveClient.ExistsAsync(archive.Id); if (!exists) Archives.Add(archive); @@ -69,9 +69,9 @@ async Task Upload(Archive archive) { - var archiveFilePath = await ArchiveService.GetArchiveFileLocationAsync(archive); + var archiveFilePath = await ArchiveClient.GetArchiveFileLocationAsync(archive); - if (await ArchiveService.ExistsAsync(archive.Id)) + if (await ArchiveClient.ExistsAsync(archive.Id)) File.Delete(archiveFilePath); File.Create(archiveFilePath).Close(); @@ -83,7 +83,7 @@ { try { - await ArchiveService.DeleteAsync(archive); + await ArchiveClient.DeleteAsync(archive); await LoadData(); diff --git a/LANCommander.Server/UI/Pages/Settings/Tools/OrphanedFiles.razor b/LANCommander.Server/UI/Pages/Settings/Tools/OrphanedFiles.razor index d429c45a..4f907794 100644 --- a/LANCommander.Server/UI/Pages/Settings/Tools/OrphanedFiles.razor +++ b/LANCommander.Server/UI/Pages/Settings/Tools/OrphanedFiles.razor @@ -1,7 +1,7 @@ @page "/Settings/Tools/OrphanedFiles" @using LANCommander.Helpers; @attribute [Authorize(Roles = RoleService.AdministratorRoleName)] -@inject ArchiveService ArchiveService +@inject ArchiveClient ArchiveClient @inject StorageLocationService StorageLocationService @inject MediaService MediaService @@ -55,8 +55,8 @@ Orphans = new List(); var storageLocations = await StorageLocationService.GetAsync(); - var archives = await ArchiveService.GetAsync(); - var archiveFiles = await Task.WhenAll(archives.Select(a => ArchiveService.GetArchiveFileLocationAsync(a))); + var archives = await ArchiveClient.GetAsync(); + var archiveFiles = await Task.WhenAll(archives.Select(a => ArchiveClient.GetArchiveFileLocationAsync(a))); foreach (var storageLocation in storageLocations.Where(l => l.Type == SDK.Enums.StorageLocationType.Archive)) { diff --git a/LANCommander.UI/Components/Chat/Chat.razor b/LANCommander.UI/Components/Chat/Chat.razor index 7928fffb..f09cadfe 100644 --- a/LANCommander.UI/Components/Chat/Chat.razor +++ b/LANCommander.UI/Components/Chat/Chat.razor @@ -1,6 +1,6 @@ -@using LANCommander.SDK +@using LANCommander.SDK.Services @using Microsoft.AspNetCore.Components.Authorization -@inject Client Client +@inject ChatClient ChatClient @inject AuthenticationStateProvider AuthenticationStateProvider @namespace LANCommander.UI.Components @@ -22,14 +22,14 @@ protected override async Task OnInitializedAsync() { - _threads = await Client.Chat.GetThreadsAsync(); + _threads = await ChatClient.GetThreadsAsync(); } async Task StartThread() { var user = await AuthenticationStateProvider.GetAuthenticationStateAsync(); - var newThreadId = await Client.Chat.StartThreadAsync([user.User.Identity.Name]); + var newThreadId = await ChatClient.StartThreadAsync([user.User.Identity.Name]); _currentThreadId = newThreadId; diff --git a/LANCommander.UI/Components/Chat/ChatThread.razor b/LANCommander.UI/Components/Chat/ChatThread.razor index fe5a3f13..18c4010a 100644 --- a/LANCommander.UI/Components/Chat/ChatThread.razor +++ b/LANCommander.UI/Components/Chat/ChatThread.razor @@ -1,7 +1,8 @@ @using System.Collections.Specialized @using LANCommander.SDK +@using LANCommander.SDK.Services @using Microsoft.AspNetCore.Components.Web.Virtualization -@inject Client Client +@inject ChatClient ChatClient @namespace LANCommander.UI.Components @@ -34,7 +35,7 @@ { if (Id != Guid.Empty) { - _thread = Client.Chat.GetThread(Id); + _thread = ChatClient.GetThread(Id); _thread.MessageGroups.CollectionChanged += MessageGroupsOnCollectionChanged; } @@ -51,7 +52,7 @@ { _sendingMessage = true; - await Client.Chat.SendMessageAsync(Id, _inputContents); + await ChatClient.SendMessageAsync(Id, _inputContents); } } } \ No newline at end of file diff --git a/LANCommander.UI/Components/FileManager/FileManager.razor b/LANCommander.UI/Components/FileManager/FileManager.razor index 7fb32d90..020a12ff 100644 --- a/LANCommander.UI/Components/FileManager/FileManager.razor +++ b/LANCommander.UI/Components/FileManager/FileManager.razor @@ -2,7 +2,7 @@ @using AntDesign.TableModels; @using LANCommander.SDK.Services @using Microsoft.Extensions.Logging -@inject IArchiveService ArchiveService +@inject IArchiveClient ArchiveClient @inject IMessageService MessageService @inject ILogger Logger @namespace LANCommander.UI.Components @@ -181,7 +181,7 @@ if (!String.IsNullOrWhiteSpace(WorkingDirectory)) FileSource = new FileManagerLocalDiskSource(WorkingDirectory); else if (ArchiveId != Guid.Empty) - FileSource = new FileManagerArchiveSource(ArchiveService, ArchiveId); + FileSource = new FileManagerArchiveSource(ArchiveClient, ArchiveId); Directories = FileSource.GetDirectoryTree().ToHashSet(); diff --git a/LANCommander.UI/Components/FileManager/Sources/FileManagerArchiveSource.cs b/LANCommander.UI/Components/FileManager/Sources/FileManagerArchiveSource.cs index c6d95aa1..c0d11913 100644 --- a/LANCommander.UI/Components/FileManager/Sources/FileManagerArchiveSource.cs +++ b/LANCommander.UI/Components/FileManager/Sources/FileManagerArchiveSource.cs @@ -6,7 +6,7 @@ namespace LANCommander.UI.Components { public class FileManagerArchiveSource : IFileManagerSource { - private IArchiveService ArchiveService; + private IArchiveClient _archiveClient; private Guid ArchiveId { get; set; } private FileManagerDirectory CurrentPath { get; set; } @@ -15,11 +15,11 @@ namespace LANCommander.UI.Components private const char Separator = '/'; - public FileManagerArchiveSource(IArchiveService archiveService, Guid archiveId) { - ArchiveService = archiveService; + public FileManagerArchiveSource(IArchiveClient archiveClient, Guid archiveId) { + _archiveClient = archiveClient; ArchiveId = archiveId; - var task = ArchiveService.GetContentsAsync(ArchiveId); + var task = _archiveClient.GetContentsAsync(ArchiveId); task.Wait(); diff --git a/LANCommander.UI/Components/SafeImage/SafeImage.razor b/LANCommander.UI/Components/SafeImage/SafeImage.razor index ab64a6d9..29882d69 100644 --- a/LANCommander.UI/Components/SafeImage/SafeImage.razor +++ b/LANCommander.UI/Components/SafeImage/SafeImage.razor @@ -1,5 +1,6 @@ @using LANCommander.SDK.Models -@inject SDK.Client Client +@using LANCommander.SDK.Services +@inject MediaService MediaService @namespace LANCommander.UI.Components @@ -11,7 +12,7 @@ } else if (Media != null) { - + } else {