Rename SDK services -> clients, implement new configuration, use dependency injection for clients

This commit is contained in:
Pat Hartl 2025-09-24 20:58:23 -05:00
parent 9f17f92b78
commit d875377f15
142 changed files with 1546 additions and 926 deletions

View file

@ -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<SDK.Models.Settings> settings,
ILogger<AuthenticationService> 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<AuthenticationService> 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<bool> 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<bool> 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;

View file

@ -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<Collection>
{
public CollectionService(DatabaseContext dbContext, SDK.Client client, ILogger<CollectionService> logger) : base(dbContext, client, logger)
public CollectionService(DatabaseContext dbContext, ILogger<CollectionService> logger) : base(dbContext, logger)
{
}
}

View file

@ -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<CommandLineService> 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<CommandLineService> 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<GameManifest>(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}");
}

View file

@ -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<Company>
public class CompanyService(
DatabaseContext dbContext,
ILogger<CompanyService> logger) : BaseDatabaseService<Company>(dbContext, logger)
{
public CompanyService(DatabaseContext dbContext, SDK.Client client, ILogger<CompanyService> logger) : base(dbContext, client, logger)
{
}
}
}

View file

@ -18,10 +18,13 @@ namespace LANCommander.Launcher.Services
public delegate Task OnItemsFilteredHandler(IEnumerable<ListItem> items);
public event OnItemsFilteredHandler OnItemsFiltered;
private SDK.Client _client;
public DepotService(
Client client,
ILogger<DepotService> logger) : base(client, logger)
ILogger<DepotService> 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);

View file

@ -11,7 +11,7 @@ namespace LANCommander.Launcher.Services
{
public class EngineService : BaseDatabaseService<Engine>
{
public EngineService(DatabaseContext dbContext, SDK.Client client, ILogger<EngineService> logger) : base(dbContext, client, logger)
public EngineService(DatabaseContext dbContext, ILogger<EngineService> logger) : base(dbContext, logger)
{
}
}

View file

@ -22,8 +22,6 @@ namespace LANCommander.Launcher.Services.Extensions
using (var scope = serviceProvider.CreateScope())
{
var logger = scope.ServiceProvider.GetService<ILogger>();
var authenticationService = scope.ServiceProvider.GetService<AuthenticationService>();
var keepAliveService = scope.ServiceProvider.GetService<KeepAliveService>();
#region Scaffold Required Directories
try

View file

@ -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<MessageBusService>();
services.AddSingleton<AuthenticationService>();
services.AddSingleton<KeepAliveService>();

View file

@ -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<FilterService> logger,
LibraryService libraryService) : BaseService(logger)
{
private readonly LibraryService LibraryService;
private readonly GameService GameService;
public LibraryFilterModel Filter { get; set; }
public ICollection<Engine> 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<FilterService> logger,
LibraryService libraryService,
GameService gameService) : base(client, logger)
{
GameService = gameService;
LibraryService = libraryService;
}
public void Populate(IEnumerable<Game> 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();
}

View file

@ -10,17 +10,17 @@ using System.Diagnostics;
namespace LANCommander.Launcher.Services
{
public class GameService : BaseDatabaseService<Game>
public class GameService(
DatabaseContext dbContext,
ILogger<GameService> logger,
AuthenticationService authenticationService,
PlaySessionService playSessionService,
SDK.Client client,
IServiceProvider serviceProvider) : BaseDatabaseService<Game>(dbContext, logger)
{
private readonly AuthenticationService AuthenticationService;
private readonly PlaySessionService PlaySessionService;
private readonly IServiceProvider ServiceProvider;
private readonly SaveService SaveService;
private readonly MessageBusService MessageBusService;
public Dictionary<Guid, Process> RunningProcesses = new Dictionary<Guid, Process>();
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<GameService> 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<LibraryService>();
var libraryService = serviceProvider.GetService<LibraryService>();
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);
}
}

View file

@ -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<Genre>
{
public GenreService(DatabaseContext dbContext, SDK.Client client, ILogger<GenreService> logger) : base(dbContext, client, logger)
public GenreService(DatabaseContext dbContext,ILogger<GenreService> logger) : base(dbContext, logger)
{
}
}

View file

@ -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;

View file

@ -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<ImportService> 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<Tag> Tags;
private IEnumerable<MultiplayerMode> MultiplayerModes;
public ImportService(
SDK.Client client,
ILogger<ImportService> 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<Game> 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<Collection, SDK.Models.Collection>()
await databaseContext.BulkImport<Collection, SDK.Models.Collection>()
.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<Genre, SDK.Models.Genre>()
await databaseContext.BulkImport<Genre, SDK.Models.Genre>()
.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<Company, SDK.Models.Company>()
await databaseContext.BulkImport<Company, SDK.Models.Company>()
.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<Company, SDK.Models.Company>()
await databaseContext.BulkImport<Company, SDK.Models.Company>()
.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<Tag, SDK.Models.Tag>()
await databaseContext.BulkImport<Tag, SDK.Models.Tag>()
.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<MultiplayerMode, SDK.Models.MultiplayerMode>()
await databaseContext.BulkImport<MultiplayerMode, SDK.Models.MultiplayerMode>()
.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<Platform, SDK.Models.Platform>()
await databaseContext.BulkImport<Platform, SDK.Models.Platform>()
.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<PlaySession, SDK.Models.PlaySession>()
/*await databaseContext.BulkImport<PlaySession, SDK.Models.PlaySession>()
.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<Media, SDK.Models.Media>()
var importedMedia = await databaseContext.BulkImport<Media, SDK.Models.Media>()
.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<PlaySession, SDK.Models.PlaySession>()
await databaseContext.BulkImport<PlaySession, SDK.Models.PlaySession>()
.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<EntityReference>();
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<Media> 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
{

View file

@ -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<InstallService> logger,
GameService gameService) : base(client, logger)
GameService gameService) : base(logger)
{
Client = client;
GameService = gameService;
Stopwatch = new Stopwatch();

View file

@ -31,9 +31,8 @@ public class KeepAliveService : BaseService
public event EventHandler ConnectionEstablished;
public KeepAliveService(
Client client,
ILogger<KeepAliveService> 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);
}
}
}

View file

@ -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<Guid, Process> RunningProcesses = new Dictionary<Guid, Process>();
@ -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;

View file

@ -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<Media>
public class MediaService(
ILogger<MediaService> logger,
DatabaseContext dbContext) : BaseDatabaseService<Media>(dbContext, logger)
{
private readonly Settings Settings;
public MediaService(DatabaseContext dbContext, SDK.Client client, ILogger<CollectionService> logger) : base(dbContext, client, logger)
{
Settings = SettingService.GetSettings();
}
private readonly Settings Settings = SettingService.GetSettings();
public override Task DeleteAsync(Media entity)
{

View file

@ -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<MessageBusService> logger) : BaseService(logger)
{
public delegate Task OnMediaChangedHandler(Media media);
public event OnMediaChangedHandler OnMediaChanged;
public MessageBusService(SDK.Client client, ILogger<MessageBusService> logger) : base(client, logger) { }
public void MediaChanged(Media media)
{
OnMediaChanged?.Invoke(media);

View file

@ -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<MultiplayerMode>
public class MultiplayerModeService(
ILogger<MultiplayerModeService> logger,
DatabaseContext dbContext) : BaseDatabaseService<MultiplayerMode>(dbContext, logger)
{
public MultiplayerModeService(DatabaseContext dbContext, SDK.Client client, ILogger<MultiplayerModeService> logger) : base(dbContext, client, logger)
{
}
}
}

View file

@ -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<Platform>
public class PlatformService(
ILogger<PlatformService> logger,
DatabaseContext dbContext) : BaseDatabaseService<Platform>(dbContext, logger)
{
public PlatformService(DatabaseContext dbContext, SDK.Client client, ILogger<PlatformService> logger) : base(dbContext, client, logger)
{
}
}
}

View file

@ -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<PlaySession>
public class PlaySessionService(
ILogger<PlaySessionService> logger,
DatabaseContext dbContext,
SDK.Client client) : BaseDatabaseService<PlaySession>(dbContext, logger)
{
public PlaySessionService(DatabaseContext dbContext, SDK.Client client, ILogger<CollectionService> logger) : base(dbContext, client, logger) { }
public async Task<PlaySession> 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);
}
}
}

View file

@ -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<ProfileService> 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,
};

View file

@ -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<Redistributable>
public class RedistributableService(
ILogger<RedistributableService> logger,
DatabaseContext dbContext) : BaseDatabaseService<Redistributable>(dbContext, logger)
{
public RedistributableService(DatabaseContext dbContext, SDK.Client client, ILogger<RedistributableService> logger) : base(dbContext, client, logger)
{
}
}
}

View file

@ -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<SaveService> logger,
SDK.Client client) : BaseService(logger)
{
public SaveService(SDK.Client client, ILogger<SaveService> saveService) : base(client, saveService) { }
public async Task<IEnumerable<GameSave>> Get(Guid gameId)
{
var saves = await Client.Saves.GetAsync(gameId);
var saves = await client.Saves.GetAsync(gameId);
if (saves == null)
saves = new List<GameSave>();
@ -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);
}
}
}

View file

@ -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<Tag>
public class TagService(
DatabaseContext dbContext,
ILogger<TagService> logger) : BaseDatabaseService<Tag>(dbContext, logger)
{
public TagService(DatabaseContext dbContext, SDK.Client client, ILogger<TagService> logger) : base(dbContext, client, logger)
{
}
}
}

View file

@ -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<UpdateService> logger,
SDK.Client client) : BaseService(logger)
{
public delegate Task OnUpdateAvailableHandler(CheckForUpdateResponse response);
public event OnUpdateAvailableHandler OnUpdateAvailable;
public UpdateService(SDK.Client client, ILogger<UpdateService> logger) : base(client, logger) { }
public async Task<CheckForUpdateResponse> 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);

View file

@ -5,18 +5,11 @@ using Microsoft.Extensions.Logging;
namespace LANCommander.Launcher.Services
{
public class UserService : BaseDatabaseService<User>
public class UserService(
ILogger<UserService> logger,
DatabaseContext dbContext,
AuthenticationService authenticationService) : BaseDatabaseService<User>(dbContext, logger)
{
private readonly AuthenticationService AuthenticationService;
public UserService(
DatabaseContext dbContext,
SDK.Client client,
ILogger<UserService> logger,
AuthenticationService authenticationService) : base(dbContext, client, logger)
{
AuthenticationService = authenticationService;
}
public override async Task<User> 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<string> GetAliasAsync(Guid id)

View file

@ -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;
}

View file

@ -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;
}
}

View file

@ -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<LocalizationService>();
builder.Services.AddLANCommander();
builder.Services.AddLANCommander(options =>
{
options.ServerAddress = settings.Authentication.ServerAddress;

View file

@ -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<Settings>(configBuilder);
builder.Services.Configure<Settings>(configuration);
builder.Services.AddSingleton(refresher);
settings = new Settings();
configBuilder.Bind(settings);
configuration.Bind(settings);
Log.Debug("Validating settings");

View file

@ -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>("app");
builder.Services.AddCustomWindow();
builder.Services.AddAntDesign();
builder.Services.AddSingleton<LocalizationService>();
builder.Services.AddLANCommander(options =>
{
options.ServerAddress = settings.Authentication.ServerAddress;
//options.Logger = new SerilogLoggerFactory(Logger).CreateLogger<SDK.Client>();
});
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();
}
});

View file

@ -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; }
}

View file

@ -69,7 +69,7 @@
<AuthenticationProviderDialog @ref="AuthenticationProviderDialog" OnTokenReceived="UseToken" />
@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<string> 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();

View file

@ -40,20 +40,20 @@
</Form>
@code {
[Parameter] public string ServerAddress { get; set; }
[Parameter] public Uri ServerAddress { get; set; }
[Parameter] public EventCallback OnBack { get; set; }
[Parameter] public IEnumerable<string> 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;
}
}
}

View file

@ -36,7 +36,7 @@
<AntList DataSource="DiscoveredServers">
<ChildContent>
<ListItem OnClick="() => SelectServer(context.Address.ToString())">
<ListItem OnClick="() => SelectServer(context.Address)">
<ListItemMeta Title="@context.Name" Description="@context.Address.ToString()"/>
</ListItem>
</ChildContent>
@ -65,14 +65,14 @@
</AntList>
@code {
[Parameter] public EventCallback<string> OnSelected { get; set; }
[Parameter] public EventCallback<Uri> 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<DiscoveredServer> 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();

View file

@ -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
<CustomWindow HeaderHeight="37">
<WindowContent>
<ErrorHandler Title="@LocalizationService.GetString("LauncherCrashed")">
<Body>
<AuthenticatedView NoAutoValidate="false">
<Authenticated>
@Body
</Authenticated>
<NotAuthenticated>
<AuthenticationForm/>
</NotAuthenticated>
</AuthenticatedView>
<AntContainer/>
</Body>
<Extra>
<Button Type="ButtonType.Primary" OnClick="@(() => NavigationManager.NavigateTo("/", true))">@LocalizationService.GetString("Reload")</Button>
</Extra>
</ErrorHandler>
</WindowContent>
</CustomWindow>
@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"));
}
}

View file

@ -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;
}
}

View file

@ -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)

View file

@ -2,7 +2,6 @@
@using Newtonsoft.Json
@using Photino.NET
@inject SDK.Client Client
@inject IJSRuntime JSRuntime
@inject IMessageService MessageService
@inject ILogger<AuthenticationProviderDialog> Logger
@inject LocalizationService LocalizationService
@ -10,15 +9,15 @@
@code {
[Parameter] public EventCallback<AuthToken> 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))

View file

@ -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> Settings
@inject NavigationManager NavigationManager
@inject LocalizationService LocalizationService
@inject IJSRuntime JS
<Flex Justify="FlexJustify.Center" Align="FlexAlign.Center" Gap="FlexGap.Small" Class="footer">
<div style="flex: 1;">
@ -14,7 +18,7 @@
}
else
{
if (Client.Settings?.EnableUserLibraries ?? false)
if (true)
{
<ConnectionStateView>
<Online>
@ -51,9 +55,7 @@
</ConnectionStateView>
<div style="flex: 1; text-align: right;">
<Tooltip Title="@LocalizationService.GetString("ComingSoon")" Placement="Placement.TopRight">
<Button Type="@ButtonType.Text" Icon="@IconType.Outline.Team" Disabled>@LocalizationService.GetString("Friends")</Button>
</Tooltip>
<Button Type="@ButtonType.Text" Icon="@IconType.Outline.Message" OnClick="OpenChatWindow">@LocalizationService.GetString("Chat")</Button>
</div>
</Flex>
@ -78,4 +80,9 @@
{
await DownloadQueue.Show();
}
async Task OpenChatWindow()
{
await JS.InvokeVoidAsync("window.external.sendMessage", "openChat");
}
}

View file

@ -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);
}

View file

@ -103,9 +103,9 @@
NavigationManager.NavigateTo("/Authenticate");
}
void SwitchToOfflineMode()
async Task SwitchToOfflineMode()
{
AuthenticationService.SetOfflineMode(true);
await AuthenticationService.SetOfflineModeAsync(true);
NavigationManager.NavigateTo("/", forceLoad: true);
}

View file

@ -66,7 +66,7 @@
}
</SpaceItem>
@if (!IsInstalled && Client.IsConnected())
@if (!IsInstalled && Client.Connection.IsConnected())
{
<SpaceItem>
<Statistic Title="@LocalizationService.GetString("DownloadSize")" Value="@ByteSizeLib.ByteSize.FromBytes(GetDownloadSize()).ToString()" />

View file

@ -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();
}

View file

@ -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"));

View file

@ -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");
}

View file

@ -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;
}

View file

@ -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<ServerConfigurationProvider?> getProvider) : IServerConfigurationRefresher
{
private readonly Func<ServerConfigurationProvider?> _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);
}
}
}

View file

@ -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<ILANCommanderConfiguration, LANCommanderConfiguration>();
services.AddSingleton<ITokenProvider, TokenProvider>();
services.AddSingleton<INetworkInformationProvider, NetworkInformationProvider>();
services.AddSingleton<IRpcClient, RpcClient>();
services.AddScoped<ApiRequestFactory>();
services.AddScoped<ProcessExecutionContextFactory>();
services.AddScoped<AuthenticationService>();
services.AddSingleton<BeaconService>();
services.AddScoped<ChatService>();
services.AddSingleton<IConnectionService, ConnectionService>();
services.AddScoped<DepotService>();
services.AddScoped<GameService>();
services.AddScoped<IssueService>();
services.AddScoped<LauncherService>();
services.AddScoped<LobbyService>();
services.AddScoped<AuthenticationClient>();
services.AddSingleton<BeaconClient>();
services.AddScoped<ChatClient>();
services.AddSingleton<IConnectionClient, ConnectionClient>();
services.AddScoped<DepotClient>();
services.AddScoped<GameClient>();
services.AddScoped<IssueClient>();
services.AddScoped<LauncherClient>();
services.AddScoped<LibraryClient>();
services.AddScoped<LobbyClient>();
services.AddScoped<MediaService>();
services.AddScoped<PlaySessionService>();
services.AddScoped<ProfileService>();
services.AddScoped<RedistributableService>();
services.AddScoped<SaveService>();
services.AddScoped<ScriptService>();
services.AddScoped<ServerService>();
services.AddScoped<TagService>();
services.AddScoped<PlaySessionClient>();
services.AddScoped<ProfileClient>();
services.AddScoped<RedistributableClient>();
services.AddScoped<SaveClient>();
services.AddScoped<ScriptClient>();
services.AddScoped<ServerClient>();
services.AddScoped<TagClient>();
services.AddScoped<Client>();
return services;
}

View file

@ -11,6 +11,6 @@ public class ProcessExecutionContextFactory(IServiceProvider serviceProvider)
{
return new ProcessExecutionContext(
serviceProvider.GetService<ILogger<ProcessExecutionContext>>(),
serviceProvider.GetService<LobbyService>());
serviceProvider.GetService<LobbyClient>());
}
}

View file

@ -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;

View file

@ -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);
}
}
}

View file

@ -22,12 +22,16 @@
<PackageReference Include="MadMilkman.Ini" Version="1.0.6" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="9.0.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client.SourceGenerator" Version="7.0.0-preview.7.22376.6" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.9" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
<PackageReference Include="Microsoft.PowerShell.Commands.Diagnostics" Version="7.4.7" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.4.7" />
<PackageReference Include="NetEscapades.Configuration.Yaml" Version="3.1.0" />
<PackageReference Include="PeanutButter.INI" Version="3.0.339" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="Semver" Version="3.0.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="SharpCompress" Version="0.39.0" />
<PackageReference Include="System.Management.Automation" Version="7.4.7" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />

View file

@ -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; }
}
}

View file

@ -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; }
}

View file

@ -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;
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public class GameSettings : IGameSettings
{
public string[] InstallDirectories { get; set; } = [];
}

View file

@ -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; }
}

View file

@ -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; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public interface IGameSettings
{
public string[] InstallDirectories { get; set; }
}

View file

@ -0,0 +1,7 @@
namespace LANCommander.SDK.Models;
public interface IIPXRelaySettings
{
public int Port { get; set; }
public string Host { get; set; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public interface ILibrarySettings
{
public bool EnableUserLibraries { get; set; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public interface IMediaSettings
{
public string StoragePath { get; set; }
}

View file

@ -0,0 +1,7 @@
namespace LANCommander.SDK.Models;
public class IPXRelaySettings : IIPXRelaySettings
{
public int Port { get; set; }
public string Host { get; set; }
}

View file

@ -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; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public interface IUpdateSettings
{
public string StoragePath { get; set; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public class LibrarySettings : ILibrarySettings
{
public bool EnableUserLibraries { get; set; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public class MediaSettings : IMediaSettings
{
public string StoragePath { get; set; } = "Media";
}

View file

@ -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; }
}

View file

@ -0,0 +1,6 @@
namespace LANCommander.SDK.Models;
public class UpdateSettings : IUpdateSettings
{
public string StoragePath { get; set; } = "Updates";
}

View file

@ -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);
}

View file

@ -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);
}

View file

@ -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);
}

View file

@ -14,7 +14,7 @@ namespace LANCommander.SDK
{
public class ProcessExecutionContext(
ILogger<ProcessExecutionContext> logger,
LobbyService lobbyService) : IDisposable
LobbyClient lobbyClient) : IDisposable
{
private Process Process;
@ -209,7 +209,7 @@ namespace LANCommander.SDK
}
catch { }
lobbyService.ReleaseSteam();
lobbyClient.ReleaseSteam();
}
}
}

View file

@ -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;
}
}

View file

@ -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<string, string>(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)
{
}
}
}

View file

@ -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()
{
}
}

View file

@ -8,30 +8,30 @@ namespace LANCommander.SDK.Rpc;
public partial class RpcClient
{
private readonly ChatService _chatService = serviceProvider.GetService<ChatService>();
private readonly ChatClient _chatClient = serviceProvider.GetService<ChatClient>();
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);
}
}

View file

@ -5,7 +5,6 @@ namespace LANCommander.SDK.Rpc.Client;
public partial interface IRpcClient
{
public IRpcHub Server { get; set; }
public Task<bool> ConnectAsync();
public Task<bool> DisconnectAsync();
}

View file

@ -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<IConnectionService>();
private readonly IConnectionClient _connectionClient = serviceProvider.GetService<IConnectionClient>();
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<IRpcHub>();

View file

@ -13,11 +13,11 @@ using Microsoft.Extensions.Logging;
namespace LANCommander.SDK.Services;
public class AuthenticationService(
ILogger<AuthenticationService> logger,
public class AuthenticationClient(
ILogger<AuthenticationClient> logger,
ITokenProvider tokenProvider,
ApiRequestFactory apiRequestFactory,
IConnectionService connectionService)
IConnectionClient connectionClient)
{
public async Task<AuthToken> 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<bool> 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<object>();
logger?.LogTrace("Validated token successfully");
return true;
}
catch (Exception ex)
{
logger?.LogError("Validating token failed", ex);
}
return false;
}
public async Task<IEnumerable<AuthenticationProvider>> 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<ErrorResponse> ParseErrorResponseAsync(HttpResponseMessage response, bool defaultToGenericResponse = false)

View file

@ -12,8 +12,8 @@ using Microsoft.Extensions.Logging;
namespace LANCommander.SDK.Services;
public class BeaconService(
ILogger<BeaconService> logger,
public class BeaconClient(
ILogger<BeaconClient> logger,
INetworkInformationProvider networkInformationProvider)
{
public delegate void OnBeaconResponseHandler(object sender, BeaconResponseArgs e);
@ -29,7 +29,7 @@ public class BeaconService(
_beaconMessageInterceptors = new List<IBeaconMessageInterceptor>();
}
public BeaconService AddBeaconMessageInterceptor(IBeaconMessageInterceptor interceptor)
public BeaconClient AddBeaconMessageInterceptor(IBeaconMessageInterceptor interceptor)
{
_beaconMessageInterceptors.Add(interceptor);

View file

@ -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<Guid, ChatThread> _threads = new();
public ChatThread GetThread(Guid threadId)
@ -17,7 +17,8 @@ public class ChatService(IRpcClient rpc)
public async Task<Guid> StartThreadAsync(IEnumerable<string> 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<IEnumerable<ChatThread>> GetThreadsAsync()
{
var threads = await rpc.Server.Chat_GetThreadsAsync();
var threads = new List<ChatThread>();
//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);
}
}

View file

@ -12,9 +12,9 @@ using Microsoft.Extensions.Logging;
namespace LANCommander.SDK.Services;
public class ConnectionService(
ILogger<ConnectionService> logger,
IRpcClient rpc) : IConnectionService
public class ConnectionClient(
ILogger<ConnectionClient> 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))

View file

@ -7,8 +7,8 @@ using LANCommander.SDK.Factories;
namespace LANCommander.SDK.Services
{
public class DepotService(
ILogger<DepotService> logger,
public class DepotClient(
ILogger<DepotClient> logger,
ApiRequestFactory apiRequestFactory)
{
public async Task<DepotResults> GetAsync()

View file

@ -59,18 +59,18 @@ namespace LANCommander.SDK.Services
public GameInstallationFileList FileList { get; set; } = GameInstallationFileList.Empty;
}
public class GameService(
ILogger<GameService> logger,
public class GameClient(
ILogger<GameClient> 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<GameManifest> 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;
});

View file

@ -5,7 +5,7 @@ using System.Threading.Tasks;
namespace LANCommander.SDK.Services;
public interface IArchiveService
public interface IArchiveClient
{
public Task<IEnumerable<ZipArchiveEntry>> GetContentsAsync(Guid archiveId);
}

View file

@ -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
/// </summary>
/// <param name="address">The address to resolve for a LANCommander server</param>
public Task UpdateServerAddressAsync(string address);
public Task UpdateServerAddressAsync(Uri address);
public Task<bool> DisconnectAsync();
public Task<bool> PingAsync(Uri serverAddress = null);
}

View file

@ -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<bool> Open(string description, Guid gameId)
{

View file

@ -6,8 +6,8 @@ using LANCommander.SDK.Factories;
namespace LANCommander.SDK.Services
{
public class LauncherService(
ILogger<LauncherService> logger,
public class LauncherClient(
ILogger<LauncherClient> logger,
ApiRequestFactory apiRequestFactory)
{
public async Task<CheckForUpdateResponse> CheckForUpdateAsync()

View file

@ -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<IEnumerable<EntityReference>> GetAsync()
{

View file

@ -7,7 +7,7 @@ using System.IO;
namespace LANCommander.SDK.Services
{
public class LobbyService(ILogger<LobbyService> logger)
public class LobbyClient(ILogger<LobbyClient> logger)
{
/// <summary>
/// Get all Steam lobbies for a specified game. Game install directory must contain a file called steam_appid.txt.

View file

@ -10,7 +10,7 @@ namespace LANCommander.SDK.Services
{
public class MediaService(
ApiRequestFactory apiRequestFactory,
IConnectionService connectionService)
IConnectionClient connectionClient)
{
public async Task<Media> 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)

View file

@ -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<IEnumerable<EntityReference>> GetAsync()
{

View file

@ -7,7 +7,7 @@ using LANCommander.SDK.Factories;
namespace LANCommander.SDK.Services
{
public class ProfileService(ApiRequestFactory apiRequestFactory, ILogger<ProfileService> logger)
public class ProfileClient(ApiRequestFactory apiRequestFactory, ILogger<ProfileClient> logger)
{
private User _user;

View file

@ -15,12 +15,12 @@ using LANCommander.SDK.Factories;
namespace LANCommander.SDK.Services
{
public class RedistributableService(
ILogger<RedistributableService> _logger,
public class RedistributableClient(
ILogger<RedistributableClient> _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<ExtractionResult.FileEntry>();
_logger?.LogTrace("Downloading and extracting {Redistributable} to path {Destination}", redistributable.Name, destination);

View file

@ -28,10 +28,10 @@ using Action = System.Action;
namespace LANCommander.SDK.Services
{
public class SaveService(
public class SaveClient(
ApiRequestFactory apiRequestFactory,
ILANCommanderConfiguration config,
ILogger<SaveService> logger)
ILogger<SaveClient> logger)
{
public delegate void OnDownloadProgressHandler(DownloadProgressChangedEventArgs e);
public event OnDownloadProgressHandler OnDownloadProgress;

View file

@ -12,10 +12,10 @@ using LANCommander.SDK.Abstractions;
namespace LANCommander.SDK.Services
{
public class ScriptService(
ILogger<ScriptService> logger,
public class ScriptClient(
ILogger<ScriptClient> logger,
ILANCommanderConfiguration config,
IConnectionService connectionService)
IConnectionClient connectionClient)
{
public delegate Task<bool> 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
{

Some files were not shown because too many files have changed in this diff Show more