diff --git a/examples/SimpleModule/SimpleModule.csproj b/examples/SimpleModule/SimpleModule.csproj index c06b84691..5032231f7 100644 --- a/examples/SimpleModule/SimpleModule.csproj +++ b/examples/SimpleModule/SimpleModule.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable 1.0.0 @@ -22,7 +22,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.CLI/EvoSC.CLI.csproj b/src/EvoSC.CLI/EvoSC.CLI.csproj index 368ab7f59..76ac0a12d 100644 --- a/src/EvoSC.CLI/EvoSC.CLI.csproj +++ b/src/EvoSC.CLI/EvoSC.CLI.csproj @@ -1,13 +1,13 @@ - net7.0 + net8.0 enable enable - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.CLI/EvoScCliApp.cs b/src/EvoSC.CLI/EvoScCliApp.cs index 6921b8644..e428edfb3 100644 --- a/src/EvoSC.CLI/EvoScCliApp.cs +++ b/src/EvoSC.CLI/EvoScCliApp.cs @@ -8,19 +8,14 @@ public class EvoScCliApp : IEvoSCApplication public IStartupPipeline StartupPipeline { get; } public CancellationToken MainCancellationToken { get; } public Container Services { get; } - - public EvoScCliApp() - { - - } public Task RunAsync() { - throw new NotImplementedException(); + throw new NotSupportedException(); } public Task ShutdownAsync() { - throw new NotImplementedException(); + throw new NotSupportedException(); } } diff --git a/src/EvoSC.Commands/Attributes/CommandAliasAttribute.cs b/src/EvoSC.Commands/Attributes/CommandAliasAttribute.cs index 47dbb95be..147f36a11 100644 --- a/src/EvoSC.Commands/Attributes/CommandAliasAttribute.cs +++ b/src/EvoSC.Commands/Attributes/CommandAliasAttribute.cs @@ -1,28 +1,23 @@ namespace EvoSC.Commands.Attributes; [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] -public class CommandAliasAttribute : Attribute +public class CommandAliasAttribute(string name, bool hide, params object[] args) : Attribute { /// /// The name of the alias, which the player must type to call the command. /// - public string Name { get; } + public string Name { get; } = name; + /// /// Default arguments for this alias, passed to the command. /// - public object[] Arguments { get; } + public object[] Arguments { get; } = args; + /// /// Whether to hide the chat message that triggered this alias. /// - public bool Hide { get; } + public bool Hide { get; } = hide; - public CommandAliasAttribute(string name, bool hide, params object[] args) - { - Name = name; - Arguments = args; - Hide = hide; - } - public CommandAliasAttribute(string name, params object[] args) : this(name, false, args) { } diff --git a/src/EvoSC.Commands/CommandAlias.cs b/src/EvoSC.Commands/CommandAlias.cs index 059e4521d..6ca7c6533 100644 --- a/src/EvoSC.Commands/CommandAlias.cs +++ b/src/EvoSC.Commands/CommandAlias.cs @@ -3,23 +3,13 @@ namespace EvoSC.Commands; -public class CommandAlias : ICommandAlias +public class CommandAlias(string name, bool hide, params object[] args) : ICommandAlias { - public string Name { get; init; } - public object[] DefaultArgs { get; init; } - public bool Hide { get; } + public string Name { get; init; } = name; + public object[] DefaultArgs { get; init; } = args; + public bool Hide { get; } = hide; - public CommandAlias(string name, bool hide, params object[] args) + public CommandAlias(CommandAliasAttribute attr) : this(attr.Name, attr.Hide, attr.Arguments) { - Name = name; - DefaultArgs = args; - Hide = hide; - } - - public CommandAlias(CommandAliasAttribute attr) - { - Name = attr.Name; - DefaultArgs = attr.Arguments; - Hide = attr.Hide; } } diff --git a/src/EvoSC.Commands/CommandInteractionContext.cs b/src/EvoSC.Commands/CommandInteractionContext.cs index 7087e6b5c..8a0e39e54 100644 --- a/src/EvoSC.Commands/CommandInteractionContext.cs +++ b/src/EvoSC.Commands/CommandInteractionContext.cs @@ -5,11 +5,9 @@ namespace EvoSC.Commands; -public class CommandInteractionContext : PlayerInteractionContext, ICommandInteractionContext +public class CommandInteractionContext + (IOnlinePlayer player, IControllerContext context) : PlayerInteractionContext(player, context), + ICommandInteractionContext { public required IChatCommand CommandExecuted { get; init; } - - public CommandInteractionContext(IOnlinePlayer player, IControllerContext context) : base(player, context) - { - } } diff --git a/src/EvoSC.Commands/EvoSC.Commands.csproj b/src/EvoSC.Commands/EvoSC.Commands.csproj index 4a91e3b8a..868300b6f 100644 --- a/src/EvoSC.Commands/EvoSC.Commands.csproj +++ b/src/EvoSC.Commands/EvoSC.Commands.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable EvoSC.Commands @@ -9,8 +9,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.Commands/Exceptions/CommandNotFoundException.cs b/src/EvoSC.Commands/Exceptions/CommandNotFoundException.cs index 257f5c196..143b539a8 100644 --- a/src/EvoSC.Commands/Exceptions/CommandNotFoundException.cs +++ b/src/EvoSC.Commands/Exceptions/CommandNotFoundException.cs @@ -3,14 +3,7 @@ /// /// Thrown when a command that does not exist was attempted retrieval. /// -public class CommandNotFoundException : CommandParserException +public class CommandNotFoundException(string cmdName, bool intendedCommand) : CommandParserException(intendedCommand) { - private readonly string _cmdName; - - public CommandNotFoundException(string cmdName, bool intendedCommand) : base(intendedCommand) - { - _cmdName = cmdName; - } - - public override string Message => $"The command '{_cmdName}' was not found."; + public override string Message => $"The command '{cmdName}' was not found."; } diff --git a/src/EvoSC.Commands/Exceptions/DuplicateChatCommandException.cs b/src/EvoSC.Commands/Exceptions/DuplicateChatCommandException.cs index ebadbd493..8b3585c20 100644 --- a/src/EvoSC.Commands/Exceptions/DuplicateChatCommandException.cs +++ b/src/EvoSC.Commands/Exceptions/DuplicateChatCommandException.cs @@ -3,14 +3,7 @@ /// /// Thrown when a command or alias is registered more than one time. /// -public class DuplicateChatCommandException : CommandException +public class DuplicateChatCommandException(string name) : CommandException { - private readonly string _name; - - public DuplicateChatCommandException(string name) - { - _name = name; - } - - public override string Message => $"Chat command with name '{_name}' already exists."; + public override string Message => $"Chat command with name '{name}' already exists."; } diff --git a/src/EvoSC.Commands/Exceptions/InvalidCommandArgumentException.cs b/src/EvoSC.Commands/Exceptions/InvalidCommandArgumentException.cs index d73ba521b..2de1acd69 100644 --- a/src/EvoSC.Commands/Exceptions/InvalidCommandArgumentException.cs +++ b/src/EvoSC.Commands/Exceptions/InvalidCommandArgumentException.cs @@ -3,14 +3,7 @@ /// /// Thrown when the user input has an invalid format for a given command's parameter. /// -public class InvalidCommandArgumentException : InvalidCommandFormatException +public class InvalidCommandArgumentException(string name, bool intendedCommand) : InvalidCommandFormatException(intendedCommand) { - private readonly string _name; - - public InvalidCommandArgumentException(string name, bool intendedCommand) : base(intendedCommand) - { - _name = name; - } - - public override string Message => $"The argument '{_name}' is in an invalid format."; + public override string Message => $"The argument '{name}' is in an invalid format."; } diff --git a/src/EvoSC.Commands/Exceptions/NotEnoughArgumentsException.cs b/src/EvoSC.Commands/Exceptions/NotEnoughArgumentsException.cs index a064df06a..68fb13704 100644 --- a/src/EvoSC.Commands/Exceptions/NotEnoughArgumentsException.cs +++ b/src/EvoSC.Commands/Exceptions/NotEnoughArgumentsException.cs @@ -3,14 +3,7 @@ /// /// Thrown when the input does not have enough arguments to call a command's handler. /// -public class NotEnoughArgumentsException : CommandParserException +public class NotEnoughArgumentsException(int requiredArgs, bool intendedCommand) : CommandParserException(intendedCommand) { - private readonly int _requiredArgs; - - public NotEnoughArgumentsException(int requiredArgs, bool intendedCommand) : base(intendedCommand) - { - _requiredArgs = requiredArgs; - } - - public override string Message => $"The command requires {_requiredArgs} argument(s)."; + public override string Message => $"The command requires {requiredArgs} argument(s)."; } diff --git a/src/EvoSC.Commands/Middleware/CommandsMiddleware.cs b/src/EvoSC.Commands/Middleware/CommandsMiddleware.cs index 4521590c3..9730deefb 100644 --- a/src/EvoSC.Commands/Middleware/CommandsMiddleware.cs +++ b/src/EvoSC.Commands/Middleware/CommandsMiddleware.cs @@ -14,26 +14,11 @@ namespace EvoSC.Commands.Middleware; -public class CommandsMiddleware +public class CommandsMiddleware(ActionDelegate next, ILogger logger, + IChatCommandManager cmdManager, IControllerManager controllers, IServerClient serverClient, + IActionPipelineManager actionPipeline) { - private readonly ActionDelegate _next; - private readonly ILogger _logger; - private readonly IControllerManager _controllers; - private readonly IServerClient _serverClient; - private readonly IActionPipelineManager _actionPipeline; - private readonly ChatCommandParser _parser; - - public CommandsMiddleware(ActionDelegate next, ILogger logger, - IChatCommandManager cmdManager, IControllerManager controllers, IServerClient serverClient, - IActionPipelineManager actionPipeline) - { - _next = next; - _logger = logger; - _controllers = controllers; - _serverClient = serverClient; - _actionPipeline = actionPipeline; - _parser = new ChatCommandParser(cmdManager); - } + private readonly ChatCommandParser _parser = new(cmdManager); async Task HandleUserErrorsAsync(IParserResult result, string playerLogin) { @@ -45,22 +30,22 @@ async Task HandleUserErrorsAsync(IParserResult result, string playerLogin) } var message = $"Error: {cmdParserException.Message}"; - await _serverClient.SendChatMessageAsync($"Error: {message}", playerLogin); + await serverClient.SendChatMessageAsync($"Error: {message}", playerLogin); } if (result.Exception is PlayerNotFoundException playerNotFoundException) { - await _serverClient.SendChatMessageAsync($"Error: {playerNotFoundException.Message}", playerLogin); + await serverClient.SendChatMessageAsync($"Error: {playerNotFoundException.Message}", playerLogin); } else { - _logger.LogError(result.Exception, "Failed to parse command"); + logger.LogError(result.Exception, "Failed to parse command"); } } private async Task ExecuteCommandAsync(IChatCommand cmd, object[] args, ChatRouterPipelineContext routerContext) { - var (controller, context) = _controllers.CreateInstance(cmd.ControllerType); + var (controller, context) = controllers.CreateInstance(cmd.ControllerType); var playerInteractionContext = new CommandInteractionContext((IOnlinePlayer)routerContext.Player, context) { @@ -71,7 +56,7 @@ private async Task ExecuteCommandAsync(IChatCommand cmd, object[] args, ChatRout var contextService = context.ServiceScope.GetInstance(); contextService.UpdateContext(playerInteractionContext); - var actionChain = _actionPipeline.BuildChain(PipelineType.ControllerAction, _ => + var actionChain = actionPipeline.BuildChain(PipelineType.ControllerAction, _ => (Task?)cmd.HandlerMethod.Invoke(controller, args) ?? Task.CompletedTask ); @@ -93,7 +78,7 @@ private async Task ExecuteCommandAsync(IChatCommand cmd, object[] args, ChatRout } else if (cmd.Permission != null) { - _logger.LogWarning("Command '{Name}' has permissions set but does not activate an audit", cmd.Name); + logger.LogWarning("Command '{Name}' has permissions set but does not activate an audit", cmd.Name); } } } @@ -133,16 +118,16 @@ public async Task ExecuteAsync(ChatRouterPipelineContext context) } else { - _logger.LogError( + logger.LogError( "An unknown error occured while trying to parse command. No exception thrown, but parsing failed"); } } catch (Exception ex) { - _logger.LogCritical(ex, "A fatal error occured while trying to handle chat command"); + logger.LogCritical(ex, "A fatal error occured while trying to handle chat command"); throw; } - await _next(context); + await next(context); } } diff --git a/src/EvoSC.Commands/Middleware/CommandsPermissionMiddleware.cs b/src/EvoSC.Commands/Middleware/CommandsPermissionMiddleware.cs index 5ba769ec7..90b76820d 100644 --- a/src/EvoSC.Commands/Middleware/CommandsPermissionMiddleware.cs +++ b/src/EvoSC.Commands/Middleware/CommandsPermissionMiddleware.cs @@ -6,19 +6,8 @@ namespace EvoSC.Commands.Middleware; -public class CommandsPermissionMiddleware +public class CommandsPermissionMiddleware(ActionDelegate next, IPermissionManager permissions, IServerClient server) { - private readonly ActionDelegate _next; - private readonly IPermissionManager _permissions; - private readonly IServerClient _server; - - public CommandsPermissionMiddleware(ActionDelegate next, IPermissionManager permissions, IServerClient server) - { - _next = next; - _permissions = permissions; - _server = server; - } - public async Task ExecuteAsync(IControllerContext context) { var cmdContext = context as CommandInteractionContext; @@ -26,17 +15,17 @@ public async Task ExecuteAsync(IControllerContext context) if (cmdContext == null) { // not a command interaction - await _next(context); + await next(context); return; } if (cmdContext.CommandExecuted.Permission == null || - await _permissions.HasPermissionAsync(cmdContext.Player, cmdContext.CommandExecuted.Permission)) + await permissions.HasPermissionAsync(cmdContext.Player, cmdContext.CommandExecuted.Permission)) { - await _next(context); + await next(context); return; } - await _server.SendChatMessageAsync("Insufficient permissions to run this command.", cmdContext.Player); + await server.SendChatMessageAsync("Insufficient permissions to run this command.", cmdContext.Player); } } diff --git a/src/EvoSC.Commands/Parser/ChatCommandParser.cs b/src/EvoSC.Commands/Parser/ChatCommandParser.cs index 5234b0fa8..b15ff7876 100644 --- a/src/EvoSC.Commands/Parser/ChatCommandParser.cs +++ b/src/EvoSC.Commands/Parser/ChatCommandParser.cs @@ -3,17 +3,10 @@ namespace EvoSC.Commands.Parser; -public class ChatCommandParser +public class ChatCommandParser(IChatCommandManager cmdManager) { - private readonly IChatCommandManager _cmdManager; - public static string CommandPrefix = "/"; - public ChatCommandParser(IChatCommandManager cmdManager) - { - _cmdManager = cmdManager; - } - public async Task ParseAsync(string userInput) { try @@ -27,7 +20,7 @@ public async Task ParseAsync(string userInput) var cmdAlias = parts[0]; bool intendedCommand = cmdAlias.StartsWith(CommandPrefix, StringComparison.Ordinal); - var cmd = _cmdManager.FindCommand(cmdAlias, false); + var cmd = cmdManager.FindCommand(cmdAlias, false); if (cmd == null) { @@ -77,7 +70,7 @@ private async Task> ConvertArgumentsAsync(IChatCommand cmd, string[ var parameter = cmd.Parameters[i]; try { - var value = await _cmdManager.ValueReader.ConvertValueAsync(parameter.Type, parts[i - aliasArgCount]); + var value = await cmdManager.ValueReader.ConvertValueAsync(parameter.Type, parts[i - aliasArgCount]); convertedArgs.Add(value); } catch (FormatException e) diff --git a/src/EvoSC.Common/Application/ServicesBuilder.cs b/src/EvoSC.Common/Application/ServicesBuilder.cs index 790c0671b..5b25a9f4d 100644 --- a/src/EvoSC.Common/Application/ServicesBuilder.cs +++ b/src/EvoSC.Common/Application/ServicesBuilder.cs @@ -2,6 +2,4 @@ namespace EvoSC.Common.Application; -public class ServicesBuilder : Container -{ -} +public class ServicesBuilder : Container; diff --git a/src/EvoSC.Common/Application/StartupPipeline.cs b/src/EvoSC.Common/Application/StartupPipeline.cs index 6b6b3da31..9d8e60f47 100644 --- a/src/EvoSC.Common/Application/StartupPipeline.cs +++ b/src/EvoSC.Common/Application/StartupPipeline.cs @@ -9,20 +9,13 @@ namespace EvoSC.Common.Application; -public class StartupPipeline : IStartupPipeline, IDisposable +public class StartupPipeline(IEvoScBaseConfig config) : IStartupPipeline, IDisposable { - private readonly ServicesBuilder _services; - private readonly ILogger _logger; + private readonly ServicesBuilder _services = new(); + private readonly ILogger _logger = new Container().AddEvoScLogging(config.Logging).GetInstance>(); private readonly Dictionary _components = new(); public Container ServiceContainer => _services; - - public StartupPipeline(IEvoScBaseConfig config) - { - _services = new ServicesBuilder(); - - _logger = new Container().AddEvoScLogging(config.Logging).GetInstance>(); - } private void CreatedDependencyOrder(IEnumerable components, Dictionary services, Dictionary actions, HashSet previousComponents) diff --git a/src/EvoSC.Common/Clients/Dtos/MxMapInfoDto.cs b/src/EvoSC.Common/Clients/Dtos/MxMapInfoDto.cs deleted file mode 100644 index 7f188f880..000000000 --- a/src/EvoSC.Common/Clients/Dtos/MxMapInfoDto.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Text.Json.Serialization; - -namespace EvoSC.Common.Clients.Dtos; - -// Should be expanded with more properties from TMX, however not necessary at time of implementation -public class MxMapInfoDto -{ - public string Username { get; set; } - - public string GbxMapName { get; set; } - - public string AuthorLogin { get; set; } - - [JsonPropertyName("TrackUID")] - public string TrackUid { get; set; } -} diff --git a/src/EvoSC.Common/Config/Models/IThemeConfig.cs b/src/EvoSC.Common/Config/Models/IThemeConfig.cs deleted file mode 100644 index 584dbdeb3..000000000 --- a/src/EvoSC.Common/Config/Models/IThemeConfig.cs +++ /dev/null @@ -1,9 +0,0 @@ -using EvoSC.Common.Config.Models.ThemeOptions; - -namespace EvoSC.Common.Config.Models; - -public interface IThemeConfig -{ - public IChatThemeConfig Chat { get; } - public IUIThemeConfig UI { get; } -} diff --git a/src/EvoSC.Common/Config/Models/ThemeOptions/IChatThemeConfig.cs b/src/EvoSC.Common/Config/Models/ThemeOptions/IChatThemeConfig.cs deleted file mode 100644 index d2a961bed..000000000 --- a/src/EvoSC.Common/Config/Models/ThemeOptions/IChatThemeConfig.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.ComponentModel; -using Config.Net; -using EvoSC.Common.Util.TextFormatting; - -namespace EvoSC.Common.Config.Models.ThemeOptions; - -public interface IChatThemeConfig -{ - [Description("The primary text color to use.")] - [Option(Alias = "primaryTextColor", DefaultValue = "fff")] - public TextColor PrimaryColor { get; } - - [Description("The secondary text color to use.")] - [Option(Alias = "secondaryTextColor", DefaultValue = "eee")] - public TextColor SecondaryColor { get; } - - [Description("The color to use for info messages.")] - [Option(Alias = "infoTextColor", DefaultValue = "29b")] - public TextColor InfoColor { get; } - - [Description("The color to use for error messages.")] - [Option(Alias = "errorTextColor", DefaultValue = "c44")] - public TextColor ErrorColor { get; } - - [Description("The color to use for warning messages.")] - [Option(Alias = "warningTextColor", DefaultValue = "e83")] - public TextColor WarningColor { get; } - - [Description("The color to use for success messages.")] - [Option(Alias = "successTextColor", DefaultValue = "5b6")] - public TextColor SuccessColor { get; } -} diff --git a/src/EvoSC.Common/Config/Models/ThemeOptions/IUIScoreboardThemeConfig.cs b/src/EvoSC.Common/Config/Models/ThemeOptions/IUIScoreboardThemeConfig.cs deleted file mode 100644 index 3179f496f..000000000 --- a/src/EvoSC.Common/Config/Models/ThemeOptions/IUIScoreboardThemeConfig.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.ComponentModel; -using Config.Net; - -namespace EvoSC.Common.Config.Models.ThemeOptions; - -public interface IUIScoreboardThemeConfig -{ - [Description("Background color of the position box.")] - [Option(Alias = "positionBackgroundColor", DefaultValue = "383b4a")] - public string PositionBackgroundColor { get; } - - [Description("Player row background color on hover.")] - [Option(Alias = "playerRowHighlightColor", DefaultValue = "767987")] - public string PlayerRowHighlightColor { get; } -} diff --git a/src/EvoSC.Common/Config/Models/ThemeOptions/IUIThemeConfig.cs b/src/EvoSC.Common/Config/Models/ThemeOptions/IUIThemeConfig.cs deleted file mode 100644 index 8e2d54b2e..000000000 --- a/src/EvoSC.Common/Config/Models/ThemeOptions/IUIThemeConfig.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.ComponentModel; -using Config.Net; - -namespace EvoSC.Common.Config.Models.ThemeOptions; - -public interface IUIThemeConfig -{ - [Description("Primary color used for accents/highlights in UI.")] - [Option(Alias = "primaryColor", DefaultValue = "1253a3")] - public string PrimaryColor { get; } - - [Description("Default background color for UI.")] - [Option(Alias = "backgroundColor", DefaultValue = "24262f")] - public string BackgroundColor { get; } - - [Description("Background color for widget headers.")] - [Option(Alias = "headerBackgroundColor", DefaultValue = "d41e67")] - public string HeaderBackgroundColor { get; } - - [Description("Player row background color")] - [Option(Alias = "playerRowBackgroundColor", DefaultValue = "626573")] - public string PlayerRowBackgroundColor { get; } - - [Description("Colored logo to be displayed on UI elements like headers.")] - [Option(Alias = "logoUrl", DefaultValue = "")] - public string LogoUrl { get; } - - [Description("White logo to be displayed on UI elements like headers.")] - [Option(Alias = "logoWhiteUrl", DefaultValue = "")] - public string LogoWhiteUrl { get; } - - public IUIScoreboardThemeConfig Scoreboard { get; } -} diff --git a/src/EvoSC.Common/Config/Stores/DatabaseStore.cs b/src/EvoSC.Common/Config/Stores/DatabaseStore.cs index 07f834970..65ee6430d 100644 --- a/src/EvoSC.Common/Config/Stores/DatabaseStore.cs +++ b/src/EvoSC.Common/Config/Stores/DatabaseStore.cs @@ -6,25 +6,17 @@ namespace EvoSC.Common.Config.Stores; -public class DatabaseStore : IConfigStore +public class DatabaseStore(string prefix, Type type, IConfigStoreRepository configStoreRepository) + : IConfigStore { - private readonly IConfigStoreRepository _configStoreRepository; - private readonly Type _type; - private readonly string _prefix; - - public DatabaseStore(string prefix, Type type, IConfigStoreRepository configStoreRepository) - { - _prefix = $"{prefix}.{GetSettingsName(type)}"; - _configStoreRepository = configStoreRepository; - _type = type; - } - + private readonly string _prefix = $"{prefix}.{GetSettingsName(type)}"; + private static string GetSettingsName(Type type) { return type.Name[0] == 'I' ? type.Name.Substring(1) : type.Name; } - public Task SetupDefaultSettingsAsync() => SetupDefaultSettingsRecursiveAsync(_type, _prefix); + public Task SetupDefaultSettingsAsync() => SetupDefaultSettingsRecursiveAsync(type, _prefix); private async Task SetupDefaultSettingsRecursiveAsync(Type type, string name) { @@ -49,12 +41,12 @@ private async Task SetupDefaultSettingsRecursiveAsync(Type type, string name) } else { - var option = await _configStoreRepository.GetConfigOptionsByKeyAsync(keyName); + var option = await configStoreRepository.GetConfigOptionsByKeyAsync(keyName); if (option == null) { // option not set, so add it's defaults to the db - await _configStoreRepository.AddConfigOptionAsync(new DbConfigOption + await configStoreRepository.AddConfigOptionAsync(new DbConfigOption { Key = keyName, Value = optionAttr?.DefaultValue?.ToString() ?? @@ -74,7 +66,7 @@ public void Dispose() public string? Read(string key) { var dbKey = $"{_prefix}.{key}"; - var option = _configStoreRepository.GetConfigOptionsByKeyAsync(dbKey).GetAwaiter().GetResult(); + var option = configStoreRepository.GetConfigOptionsByKeyAsync(dbKey).GetAwaiter().GetResult(); if (option == null) { @@ -87,13 +79,13 @@ public void Dispose() public void Write(string key, string? value) { var dbKey = $"{_prefix}.{key}"; - var option = _configStoreRepository.GetConfigOptionsByKeyAsync(dbKey).Result; + var option = configStoreRepository.GetConfigOptionsByKeyAsync(dbKey).Result; if (option == null) { option = new DbConfigOption {Key = $"{_prefix}.{key}", Value = value}; - _configStoreRepository.AddConfigOptionAsync(new DbConfigOption + configStoreRepository.AddConfigOptionAsync(new DbConfigOption { Key = option.Key, Value = option.Value ?? "" @@ -102,7 +94,7 @@ public void Write(string key, string? value) else { option.Value = value; - _configStoreRepository.UpdateConfigOptionAsync(option).GetAwaiter().GetResult(); + configStoreRepository.UpdateConfigOptionAsync(option).GetAwaiter().GetResult(); } } diff --git a/src/EvoSC.Common/Config/Stores/EvSCModuleConfigStore.cs b/src/EvoSC.Common/Config/Stores/EvSCModuleConfigStore.cs index 71b50f83a..54ed3697c 100644 --- a/src/EvoSC.Common/Config/Stores/EvSCModuleConfigStore.cs +++ b/src/EvoSC.Common/Config/Stores/EvSCModuleConfigStore.cs @@ -3,18 +3,11 @@ namespace EvoSC.Common.Config.Stores; -public class EvSCModuleConfigStore : IConfigStore +public class EvSCModuleConfigStore(string moduleName, DatabaseStore dbStore) : IConfigStore { private const string EnviKeyPrefix = "EVOSC_MODULE_"; - - private readonly DatabaseStore _dbStore; - private readonly string _moduleName; - - public EvSCModuleConfigStore(string moduleName, DatabaseStore dbStore) - { - _dbStore = dbStore; - _moduleName = moduleName.ToUpper(CultureInfo.InvariantCulture); - } + + private readonly string _moduleName = moduleName.ToUpper(CultureInfo.InvariantCulture); public string? Read(string key) { @@ -26,7 +19,7 @@ public EvSCModuleConfigStore(string moduleName, DatabaseStore dbStore) return enviValue; } - return _dbStore.Read(key); + return dbStore.Read(key); } public void Write(string key, string? value) @@ -39,13 +32,13 @@ public void Write(string key, string? value) Environment.SetEnvironmentVariable(enviKey, value); } - _dbStore.Write(key, value); + dbStore.Write(key, value); } public bool CanRead => true; public bool CanWrite => true; - public void Dispose() => _dbStore.Dispose(); + public void Dispose() => dbStore.Dispose(); private string MakeEnviKey(string key) { diff --git a/src/EvoSC.Common/Config/Stores/EvoSCBaseConfigStore.cs b/src/EvoSC.Common/Config/Stores/EvoSCBaseConfigStore.cs index 9dacc0dad..087f20dd9 100644 --- a/src/EvoSC.Common/Config/Stores/EvoSCBaseConfigStore.cs +++ b/src/EvoSC.Common/Config/Stores/EvoSCBaseConfigStore.cs @@ -4,16 +4,9 @@ namespace EvoSC.Common.Config.Stores; -public class EvoScBaseConfigStore : IConfigStore +public class EvoScBaseConfigStore(string path, Dictionary cliOptions) : IConfigStore { - private readonly TomlConfigStore _tomlConfigStore; - private readonly Dictionary _cliOptions; - - public EvoScBaseConfigStore(string path, Dictionary cliOptions) - { - _cliOptions = cliOptions; - _tomlConfigStore = new TomlConfigStore(path); - } + private readonly TomlConfigStore _tomlConfigStore = new(path); public void Dispose() { @@ -33,7 +26,7 @@ public void Dispose() var enviName = $"EVOSC_{enviKey}"; var enviValue = Environment.GetEnvironmentVariable(enviName); - _cliOptions.TryGetValue(key, out var cliValue); + cliOptions.TryGetValue(key, out var cliValue); // try cli options, then environment variables and then config file return cliValue?.ToString() ?? enviValue ?? configValue; diff --git a/src/EvoSC.Common/Controllers/Attributes/ControllerAttribute.cs b/src/EvoSC.Common/Controllers/Attributes/ControllerAttribute.cs index 9b8a8502a..1afa9a759 100644 --- a/src/EvoSC.Common/Controllers/Attributes/ControllerAttribute.cs +++ b/src/EvoSC.Common/Controllers/Attributes/ControllerAttribute.cs @@ -3,8 +3,5 @@ /// /// Defines the annotated class as a controller class and that it should be registered. /// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] -public class ControllerAttribute : Attribute -{ - -} +[AttributeUsage(AttributeTargets.Class)] +public class ControllerAttribute : Attribute; diff --git a/src/EvoSC.Common/Controllers/Context/EventControllerContext.cs b/src/EvoSC.Common/Controllers/Context/EventControllerContext.cs index 6910a0f42..0aca5b7da 100644 --- a/src/EvoSC.Common/Controllers/Context/EventControllerContext.cs +++ b/src/EvoSC.Common/Controllers/Context/EventControllerContext.cs @@ -5,9 +5,5 @@ namespace EvoSC.Common.Controllers.Context; /// /// Context that contains info about the fired event. /// -public class EventControllerContext : GenericControllerContext, IEventControllerContext -{ - public EventControllerContext(IControllerContext context) : base(context.ServiceScope) - { - } -} +public class EventControllerContext(IControllerContext context) : GenericControllerContext(context.ServiceScope), + IEventControllerContext; diff --git a/src/EvoSC.Common/Controllers/ControllerManager.cs b/src/EvoSC.Common/Controllers/ControllerManager.cs index 390508736..01c6f5a97 100644 --- a/src/EvoSC.Common/Controllers/ControllerManager.cs +++ b/src/EvoSC.Common/Controllers/ControllerManager.cs @@ -10,20 +10,13 @@ namespace EvoSC.Common.Controllers; -public class ControllerManager : IControllerManager +public class ControllerManager(ILogger logger) : IControllerManager { - private readonly ILogger _logger; - private readonly Dictionary _controllers = new(); private readonly Dictionary> _instances = new(); private readonly List _registries = new(); public IEnumerable Controllers => _controllers.Values; - - public ControllerManager(ILogger logger) - { - _logger = logger; - } public void AddController(Type controllerType, Guid moduleId, Container services) { @@ -42,13 +35,13 @@ private void ValidateController(Type controllerType) { if (!controllerType.IsControllerClass()) { - _logger.LogError("{Type} does not implement IController. Make sure to inherit the EvoScController base class", controllerType); + logger.LogError("{Type} does not implement IController. Make sure to inherit the EvoScController base class", controllerType); throw new InvalidControllerClassException("The controller must implement IController."); } if (controllerType.GetCustomAttribute() == null) { - _logger.LogError("{Type} does not annotate the [Controller] attribute", controllerType); + logger.LogError("{Type} does not annotate the [Controller] attribute", controllerType); throw new InvalidControllerClassException("The controller must annotate the Controller attribute."); } } @@ -91,7 +84,7 @@ private void DisposeControllerInstances(Type controllerType) } catch (Exception ex) { - _logger.LogError("Failed to dispose controller instance of type '{Type}'", controllerType); + logger.LogError("Failed to dispose controller instance of type '{Type}'", controllerType); } } diff --git a/src/EvoSC.Common/Database/DbConnectionFactory.cs b/src/EvoSC.Common/Database/DbConnectionFactory.cs index ae0ccbb3f..8bee30751 100644 --- a/src/EvoSC.Common/Database/DbConnectionFactory.cs +++ b/src/EvoSC.Common/Database/DbConnectionFactory.cs @@ -10,19 +10,11 @@ namespace EvoSC.Common.Database; -public class DbConnectionFactory : IDbConnectionFactory +public class DbConnectionFactory(IEvoScBaseConfig config, ILogger logger) + : IDbConnectionFactory { - private readonly IEvoScBaseConfig _config; - private readonly object _mutex = new(); private DataConnection? _connection; - private readonly ILogger _logger; - public DbConnectionFactory(IEvoScBaseConfig config, ILogger logger) - { - _config = config; - _logger = logger; - } - public DataContext GetConnection() { return CreateConnection(); @@ -35,26 +27,26 @@ public DataContext GetConnection() /// Thrown when an invalid database type was specified in the config. private DataContext CreateConnection() { - var configBuilder = CreateConfigBuilder(); - - configBuilder.UseConnectionString(_config.Database.Type switch - { - IDatabaseConfig.DatabaseType.MySql => ProviderName.MySql, - IDatabaseConfig.DatabaseType.SQLite => ProviderName.SQLite, - IDatabaseConfig.DatabaseType.PostgreSql => ProviderName.PostgreSQL, - _ => throw new InvalidOperationException("Invalid database type requested.") - }, _config.Database.GetConnectionString()); - - return new DataContext(configBuilder.Build()); + var options = CreateDatabaseOptions(); + return new DataContext(options); } /// /// Create a new database config builder with common configuration. /// /// - private LinqToDBConnectionOptionsBuilder CreateConfigBuilder() => - new LinqToDBConnectionOptionsBuilder() - .WithTraceLevel(_config.Logging.LogLevel.ToUpper(CultureInfo.InvariantCulture) switch + private DataOptions CreateDatabaseOptions() => + new DataOptions(new ConnectionOptions( + ProviderName: config.Database.Type switch + { + IDatabaseConfig.DatabaseType.MySql => ProviderName.MySql, + IDatabaseConfig.DatabaseType.SQLite => ProviderName.SQLite, + IDatabaseConfig.DatabaseType.PostgreSql => ProviderName.PostgreSQL, + _ => throw new InvalidOperationException("Invalid database type requested.") + }, + ConnectionString: config.Database.GetConnectionString() + )) + .UseTraceLevel(config.Logging.LogLevel.ToUpper(CultureInfo.InvariantCulture) switch { "INFORMATION" => TraceLevel.Info, "ERROR" => TraceLevel.Error, @@ -62,7 +54,7 @@ private LinqToDBConnectionOptionsBuilder CreateConfigBuilder() => "TRACE" => TraceLevel.Verbose, _ => TraceLevel.Off }) - .WriteTraceWith(LogTracing); + .UseTraceWith(LogTracing); /// /// Write database tracing to the logger. @@ -72,6 +64,6 @@ private LinqToDBConnectionOptionsBuilder CreateConfigBuilder() => /// private void LogTracing(string? s1, string? s2, TraceLevel level) { - _logger.LogTrace("Database Trace: {One} | {Two}", s1, s2); + logger.LogTrace("Database Trace: {One} | {Two}", s1, s2); } } diff --git a/src/EvoSC.Common/Database/MigrationManager.cs b/src/EvoSC.Common/Database/MigrationManager.cs index 697d5f6fc..ddae6f9c1 100644 --- a/src/EvoSC.Common/Database/MigrationManager.cs +++ b/src/EvoSC.Common/Database/MigrationManager.cs @@ -10,15 +10,8 @@ namespace EvoSC.Common.Database; -public class MigrationManager : IMigrationManager +public class MigrationManager(IEvoScBaseConfig config) : IMigrationManager { - private readonly IEvoScBaseConfig _config; - - public MigrationManager(IEvoScBaseConfig config) - { - _config = config; - } - public void MigrateFromAssembly(Assembly asm) { var provider = new ServiceCollection() @@ -27,11 +20,11 @@ public void MigrateFromAssembly(Assembly asm) .AddMySql5() .AddSQLite() .AddPostgres() - .WithGlobalConnectionString(_config.Database.GetConnectionString()) + .WithGlobalConnectionString(config.Database.GetConnectionString()) .ScanIn(asm).For.Migrations()) .Configure(x => - x.GeneratorId = GetDatabaseTypeIdentifier(_config.Database.Type)) - .AddEvoScLogging(_config.Logging) + x.GeneratorId = GetDatabaseTypeIdentifier(config.Database.Type)) + .AddEvoScLogging(config.Logging) .Configure(opt => { opt.Tags = new[] { "Production" }; diff --git a/src/EvoSC.Common/Database/Repository/Audit/AuditRepository.cs b/src/EvoSC.Common/Database/Repository/Audit/AuditRepository.cs index 80cbed3cd..5253ab6c0 100644 --- a/src/EvoSC.Common/Database/Repository/Audit/AuditRepository.cs +++ b/src/EvoSC.Common/Database/Repository/Audit/AuditRepository.cs @@ -6,12 +6,8 @@ namespace EvoSC.Common.Database.Repository.Audit; -public class AuditRepository : DbRepository, IAuditRepository +public class AuditRepository(IDbConnectionFactory dbConnFactory) : DbRepository(dbConnFactory), IAuditRepository { - public AuditRepository(IDbConnectionFactory dbConnFactory) : base(dbConnFactory) - { - } - public async Task AddRecordAsync(DbAuditRecord record) { var id = await Database.InsertWithIdentityAsync(record); diff --git a/src/EvoSC.Common/Database/Repository/Maps/MapRepository.cs b/src/EvoSC.Common/Database/Repository/Maps/MapRepository.cs index 0a6498c0c..e4213ca9d 100644 --- a/src/EvoSC.Common/Database/Repository/Maps/MapRepository.cs +++ b/src/EvoSC.Common/Database/Repository/Maps/MapRepository.cs @@ -10,15 +10,9 @@ namespace EvoSC.Common.Database.Repository.Maps; -public class MapRepository : DbRepository, IMapRepository +public class MapRepository(IDbConnectionFactory dbConnFactory, ILogger logger) + : DbRepository(dbConnFactory), IMapRepository { - private readonly ILogger _logger; - - public MapRepository(IDbConnectionFactory dbConnFactory, ILogger logger) : base(dbConnFactory) - { - _logger = logger; - } - public async Task GetMapByIdAsync(long id) => await Table() .LoadWith(t => t.DbAuthor) .SingleOrDefaultAsync(m => m.Id == id); @@ -57,7 +51,7 @@ public async Task AddMapAsync(MapMetadata map, IPlayer author, string file } catch (Exception e) { - _logger.LogError(e, "Failed adding map with UID {MapMapUid} to the database", map.MapUid); + logger.LogError(e, "Failed adding map with UID {MapMapUid} to the database", map.MapUid); await transaction.RollbackTransactionAsync(); throw new EvoScDatabaseException($"Failed adding map with UID {map.MapUid} to the database", e); } @@ -96,7 +90,7 @@ await Table() } catch (Exception e) { - _logger.LogError(e, "Failed to update map with UID {MapMapUid}", map.MapUid); + logger.LogError(e, "Failed to update map with UID {MapMapUid}", map.MapUid); await transaction.RollbackTransactionAsync(); throw new EvoScDatabaseException($"Failed to update map with UID {map.MapUid}", e); } diff --git a/src/EvoSC.Common/Database/Repository/Permissions/PermissionRepository.cs b/src/EvoSC.Common/Database/Repository/Permissions/PermissionRepository.cs index 1e2c5a315..66bc9e4db 100644 --- a/src/EvoSC.Common/Database/Repository/Permissions/PermissionRepository.cs +++ b/src/EvoSC.Common/Database/Repository/Permissions/PermissionRepository.cs @@ -8,15 +8,9 @@ namespace EvoSC.Common.Database.Repository.Permissions; -public class PermissionRepository : DbRepository, IPermissionRepository +public class PermissionRepository(IDbConnectionFactory dbConnFactory, ILogger logger) + : DbRepository(dbConnFactory), IPermissionRepository { - private readonly ILogger _logger; - - public PermissionRepository(IDbConnectionFactory dbConnFactory, ILogger logger) : base(dbConnFactory) - { - _logger = logger; - } - public async Task AddPermissionAsync(IPermission permission) { var id = await Database.InsertWithIdentityAsync(new DbPermission(permission)); @@ -53,7 +47,7 @@ await Table() } catch (Exception ex) { - _logger.LogError(ex, "Failed to remove permission"); + logger.LogError(ex, "Failed to remove permission"); await transaction.RollbackTransactionAsync(); throw; } @@ -90,7 +84,7 @@ public async Task RemoveGroupAsync(IGroup group) } catch (Exception ex) { - _logger.LogError(ex, "Failed to remove group"); + logger.LogError(ex, "Failed to remove group"); await transaction.RollbackTransactionAsync(); throw; } diff --git a/src/EvoSC.Common/Database/Repository/Players/PlayerRepository.cs b/src/EvoSC.Common/Database/Repository/Players/PlayerRepository.cs index 37d554a22..e3d974f91 100644 --- a/src/EvoSC.Common/Database/Repository/Players/PlayerRepository.cs +++ b/src/EvoSC.Common/Database/Repository/Players/PlayerRepository.cs @@ -8,12 +8,8 @@ namespace EvoSC.Common.Database.Repository.Players; -public class PlayerRepository : DbRepository, IPlayerRepository +public class PlayerRepository(IDbConnectionFactory dbConnFactory) : DbRepository(dbConnFactory), IPlayerRepository { - public PlayerRepository(IDbConnectionFactory dbConnFactory) : base(dbConnFactory) - { - } - public async Task GetPlayerByAccountIdAsync(string accountId) => await Table() .LoadWith(p => p.DbSettings) .SingleOrDefaultAsync(t => t.AccountId == accountId); diff --git a/src/EvoSC.Common/Database/Repository/Stores/ConfigStoreRepository.cs b/src/EvoSC.Common/Database/Repository/Stores/ConfigStoreRepository.cs index 4d03ed64f..2e74ef684 100644 --- a/src/EvoSC.Common/Database/Repository/Stores/ConfigStoreRepository.cs +++ b/src/EvoSC.Common/Database/Repository/Stores/ConfigStoreRepository.cs @@ -5,12 +5,9 @@ namespace EvoSC.Common.Database.Repository.Stores; -public class ConfigStoreRepository : DbRepository, IConfigStoreRepository +public class ConfigStoreRepository(IDbConnectionFactory dbConnFactory) : DbRepository(dbConnFactory), + IConfigStoreRepository { - public ConfigStoreRepository(IDbConnectionFactory dbConnFactory) : base(dbConnFactory) - { - } - public async Task GetConfigOptionsByKeyAsync(string keyName) => await Table() .SingleOrDefaultAsync(t => t.Key == keyName); diff --git a/src/EvoSC.Common/Events/Arguments/EvoScEventArgs.cs b/src/EvoSC.Common/Events/Arguments/EvoScEventArgs.cs index 85840f675..9dc5d6696 100644 --- a/src/EvoSC.Common/Events/Arguments/EvoScEventArgs.cs +++ b/src/EvoSC.Common/Events/Arguments/EvoScEventArgs.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Events.Arguments; -public class EvoScEventArgs : EventArgs -{ - -} +public class EvoScEventArgs : EventArgs; diff --git a/src/EvoSC.Common/Events/EventManager.cs b/src/EvoSC.Common/Events/EventManager.cs index 38f2b24af..50e94cb97 100644 --- a/src/EvoSC.Common/Events/EventManager.cs +++ b/src/EvoSC.Common/Events/EventManager.cs @@ -12,22 +12,12 @@ namespace EvoSC.Common.Events; -public class EventManager : IEventManager +public class EventManager(ILogger logger, IEvoSCApplication app, IControllerManager controllers) + : IEventManager { - private readonly ILogger _logger; - private readonly IEvoSCApplication _app; - private readonly IControllerManager _controllers; - private readonly Dictionary> _subscriptions = new(); private readonly Dictionary> _controllerSubscriptions = new(); - public EventManager(ILogger logger, IEvoSCApplication app, IControllerManager controllers) - { - _logger = logger; - _app = app; - _controllers = controllers; - } - public void Subscribe(EventSubscription subscription) { if (!_subscriptions.ContainsKey(subscription.Name)) @@ -39,7 +29,7 @@ public void Subscribe(EventSubscription subscription) _subscriptions[subscription.Name].Sort(CompareSubscriptionPriority); _subscriptions[subscription.Name].Sort(CompareSubscriptionSynchronization); - _logger.LogDebug("Subscribed to event '{Name}' with handler '{Handler}' in class '{Class}'. In Controller: {IsController}", + logger.LogDebug("Subscribed to event '{Name}' with handler '{Handler}' in class '{Class}'. In Controller: {IsController}", subscription.Name, subscription.HandlerMethod, subscription.InstanceClass, @@ -100,7 +90,7 @@ public void Unsubscribe(EventSubscription subscription) _subscriptions[subscription.Name].Remove(subscription); - _logger.LogDebug("handler '{Handler}' unsubscribed to event {Name}.", + logger.LogDebug("handler '{Handler}' unsubscribed to event {Name}.", subscription.HandlerMethod, subscription.Name); @@ -126,7 +116,7 @@ public async Task RaiseAsync(string name, EventArgs args, object? sender) return; } - _logger.LogTrace("Attempting to fire event '{Event}'", name); + logger.LogTrace("Attempting to fire event '{Event}'", name); var tasks = InvokeEventTasks(name, args, sender ?? this); await WaitEventTasksAsync(tasks); @@ -145,7 +135,7 @@ public async Task RaiseAsync(string name, EventArgs args, object? sender) { Task.Run(() => { - _logger.LogTrace("run async"); + logger.LogTrace("run async"); InvokeTaskMethodAsync(args, sender, subscription, tasks).GetAwaiter().GetResult(); }); } @@ -156,7 +146,7 @@ public async Task RaiseAsync(string name, EventArgs args, object? sender) } catch (Exception ex) { - _logger.LogError(ex, "Failed to execute subscription handler: {name}", subscription.HandlerMethod.Name); + logger.LogError(ex, "Failed to execute subscription handler: {name}", subscription.HandlerMethod.Name); } } @@ -175,7 +165,7 @@ private Task InvokeTaskMethodAsync(EventArgs args, object? sender, EventSubscrip if (task == null) { - _logger.LogError("An error occured while calling event, task is null for event: {Name}", + logger.LogError("An error occured while calling event, task is null for event: {Name}", subscription.Name); return Task.CompletedTask; } @@ -186,7 +176,7 @@ private Task InvokeTaskMethodAsync(EventArgs args, object? sender, EventSubscrip } catch (Exception ex) { - _logger.LogError(ex, "Failed to execute subscription"); + logger.LogError(ex, "Failed to execute subscription"); } return Task.CompletedTask; @@ -210,11 +200,11 @@ private async Task WaitEventTasksAsync(ConcurrentQueue<(Task, EventSubscription) if (!task.IsCompletedSuccessfully) { - _logger.LogError("Event execution failed for {Name}, status: {Status}", sub.Name, task.Status); + logger.LogError("Event execution failed for {Name}, status: {Status}", sub.Name, task.Status); if (task.IsFaulted) { - _logger.LogError(task.Exception?.InnerException, "Event handler faulted"); + logger.LogError(task.Exception?.InnerException, "Event handler faulted"); } } } @@ -232,12 +222,12 @@ private object GetTarget(EventSubscription subscription) return CreateControllerInstance(subscription); } - return ActivatorUtilities.CreateInstance(_app.Services, subscription.InstanceClass); + return ActivatorUtilities.CreateInstance(app.Services, subscription.InstanceClass); } private IController CreateControllerInstance(EventSubscription subscription) { - var (instance, scopeContext) = _controllers.CreateInstance(subscription.InstanceClass); + var (instance, scopeContext) = controllers.CreateInstance(subscription.InstanceClass); var context = new EventControllerContext(scopeContext); instance.SetContext(context); diff --git a/src/EvoSC.Common/EvoSC.Common.csproj b/src/EvoSC.Common/EvoSC.Common.csproj index 9e99a4cd1..f63dd2db5 100644 --- a/src/EvoSC.Common/EvoSC.Common.csproj +++ b/src/EvoSC.Common/EvoSC.Common.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable @@ -14,22 +14,22 @@ - + - - + + - - - - - - - - - - + + + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.Common/Exceptions/DatabaseExceptions/QueryCompilationFailedException.cs b/src/EvoSC.Common/Exceptions/DatabaseExceptions/QueryCompilationFailedException.cs index 70ee89308..a2e5a3618 100644 --- a/src/EvoSC.Common/Exceptions/DatabaseExceptions/QueryCompilationFailedException.cs +++ b/src/EvoSC.Common/Exceptions/DatabaseExceptions/QueryCompilationFailedException.cs @@ -1,8 +1,3 @@ namespace EvoSC.Common.Exceptions.DatabaseExceptions; -public class QueryCompilationFailedException : EvoSCException -{ - public QueryCompilationFailedException() : base("The query failed to compile. Is the syntax correct?") - { - } -} +public class QueryCompilationFailedException() : EvoSCException("The query failed to compile. Is the syntax correct?"); diff --git a/src/EvoSC.Common/Exceptions/EventSubscriptionNotFound.cs b/src/EvoSC.Common/Exceptions/EventSubscriptionNotFound.cs index 9946ffa0e..b5d194ef9 100644 --- a/src/EvoSC.Common/Exceptions/EventSubscriptionNotFound.cs +++ b/src/EvoSC.Common/Exceptions/EventSubscriptionNotFound.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Exceptions; -public class EventSubscriptionNotFoundException : EvoSCException -{ - -} +public class EventSubscriptionNotFoundException : EvoSCException; diff --git a/src/EvoSC.Common/Exceptions/GbxRemoteAuthenticationException.cs b/src/EvoSC.Common/Exceptions/GbxRemoteAuthenticationException.cs index 4ae43cb53..34489c5d0 100644 --- a/src/EvoSC.Common/Exceptions/GbxRemoteAuthenticationException.cs +++ b/src/EvoSC.Common/Exceptions/GbxRemoteAuthenticationException.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Exceptions; -public class GbxRemoteAuthenticationException: EvoSCException -{ - -} +public class GbxRemoteAuthenticationException: EvoSCException; diff --git a/src/EvoSC.Common/Exceptions/InvalidControllerClassException.cs b/src/EvoSC.Common/Exceptions/InvalidControllerClassException.cs index b11c0f08d..fb5ee7673 100644 --- a/src/EvoSC.Common/Exceptions/InvalidControllerClassException.cs +++ b/src/EvoSC.Common/Exceptions/InvalidControllerClassException.cs @@ -3,9 +3,4 @@ /// /// Thrown when the controller's class is invalid. Eg. not extending or implementing the right interfaces/classes. /// -public class InvalidControllerClassException : ControllerException -{ - public InvalidControllerClassException(string message) : base(message) - { - } -} +public class InvalidControllerClassException(string message) : ControllerException(message); diff --git a/src/EvoSC.Common/Exceptions/Parsing/ValueConversionException.cs b/src/EvoSC.Common/Exceptions/Parsing/ValueConversionException.cs index 41707f599..21efb9b10 100644 --- a/src/EvoSC.Common/Exceptions/Parsing/ValueConversionException.cs +++ b/src/EvoSC.Common/Exceptions/Parsing/ValueConversionException.cs @@ -1,5 +1,3 @@ namespace EvoSC.Common.Exceptions.Parsing; -public class ValueConversionException : Exception -{ -} +public class ValueConversionException : Exception; diff --git a/src/EvoSC.Common/Exceptions/PlayerExceptions/PlayerException.cs b/src/EvoSC.Common/Exceptions/PlayerExceptions/PlayerException.cs index f7a19d5d5..1b320c787 100644 --- a/src/EvoSC.Common/Exceptions/PlayerExceptions/PlayerException.cs +++ b/src/EvoSC.Common/Exceptions/PlayerExceptions/PlayerException.cs @@ -1,16 +1,10 @@ namespace EvoSC.Common.Exceptions.PlayerExceptions; -public class PlayerException : EvoSCException +public class PlayerException(string accountId, string message) : EvoSCException(message) { - public string AccountId { get; set; } - - public PlayerException(string accountId) : base($"An exception occured for player '{accountId}'") - { - AccountId = accountId; - } - - public PlayerException(string accountId, string message) : base(message) + public string AccountId { get; set; } = accountId; + + public PlayerException(string accountId) : this(accountId, $"An exception occured for player '{accountId}'") { - AccountId = accountId; } } diff --git a/src/EvoSC.Common/Exceptions/ServerClientNotConnectedException.cs b/src/EvoSC.Common/Exceptions/ServerClientNotConnectedException.cs index f1154f03c..491d6a002 100644 --- a/src/EvoSC.Common/Exceptions/ServerClientNotConnectedException.cs +++ b/src/EvoSC.Common/Exceptions/ServerClientNotConnectedException.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Exceptions; -public class ServerClientNotConnectedException : EvoSCException -{ - -} +public class ServerClientNotConnectedException : EvoSCException; diff --git a/src/EvoSC.Common/Exceptions/ServerDisconnectedException.cs b/src/EvoSC.Common/Exceptions/ServerDisconnectedException.cs index 3556938be..32f4e7594 100644 --- a/src/EvoSC.Common/Exceptions/ServerDisconnectedException.cs +++ b/src/EvoSC.Common/Exceptions/ServerDisconnectedException.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Exceptions; -public class ServerDisconnectedException : EvoSCException -{ - -} +public class ServerDisconnectedException : EvoSCException; diff --git a/src/EvoSC.Common/Localization/LocaleResource.cs b/src/EvoSC.Common/Localization/LocaleResource.cs index 8f701a15b..ae60231d1 100644 --- a/src/EvoSC.Common/Localization/LocaleResource.cs +++ b/src/EvoSC.Common/Localization/LocaleResource.cs @@ -10,12 +10,9 @@ namespace EvoSC.Common.Localization; -public class LocaleResource : Locale +public class LocaleResource(ILocalizationManager localeManager, IContextService context, IEvoScBaseConfig config) + : Locale { - private readonly ILocalizationManager _localeManager; - private readonly IContextService _context; - private readonly IEvoScBaseConfig _config; - private bool _useDefaultCulture = true; private static readonly Regex TranslationTag = @@ -25,15 +22,8 @@ public class LocaleResource : Locale public override Locale PlayerLanguage => UsePlayerLanguage(); - public LocaleResource(ILocalizationManager localeManager, IContextService context, IEvoScBaseConfig config) - { - _localeManager = localeManager; - _context = context; - _config = config; - } - public override ResourceSet? GetResourceSet() => - _localeManager.Manager.GetResourceSet(GetCulture(), true, true); + localeManager.Manager.GetResourceSet(GetCulture(), true, true); public override string Translate(string pattern, params object[] args) { @@ -60,14 +50,14 @@ public override string Translate(string pattern, params object[] args) private CultureInfo GetCulture() { - var context = _context.GetContext() as PlayerInteractionContext; + var currentContext = context.GetContext() as PlayerInteractionContext; - if (_useDefaultCulture || context?.Player?.Settings == null) + if (_useDefaultCulture || currentContext?.Player?.Settings == null) { - return CultureInfo.GetCultureInfo(_config.Locale.DefaultLanguage); + return CultureInfo.GetCultureInfo(config.Locale.DefaultLanguage); } - return CultureInfo.GetCultureInfo(context.Player.Settings.DisplayLanguage); + return CultureInfo.GetCultureInfo(currentContext.Player.Settings.DisplayLanguage); } private Locale UsePlayerLanguage() @@ -78,7 +68,7 @@ private Locale UsePlayerLanguage() private string GetString(string name, params object[] args) { - var localString = _localeManager.GetString(GetCulture(), name, args); + var localString = localeManager.GetString(GetCulture(), name, args); _useDefaultCulture = true; return localString; } diff --git a/src/EvoSC.Common/Models/Maps/MapStream.cs b/src/EvoSC.Common/Models/Maps/MapStream.cs index b9bb92a15..dfca07b91 100644 --- a/src/EvoSC.Common/Models/Maps/MapStream.cs +++ b/src/EvoSC.Common/Models/Maps/MapStream.cs @@ -4,14 +4,8 @@ /// Contains the map file and the map metadata which the map service requires in order to add the map to the database /// and the server. /// -public class MapStream +public class MapStream(MapMetadata mapMetadata, Stream mapFile) { - public MapMetadata MapMetadata { get; } - public Stream MapFile { get; } - - public MapStream(MapMetadata mapMetadata, Stream mapFile) - { - MapMetadata = mapMetadata; - MapFile = mapFile; - } + public MapMetadata MapMetadata { get; } = mapMetadata; + public Stream MapFile { get; } = mapFile; } diff --git a/src/EvoSC.Common/Permissions/Attributes/PermissionGroupAttribute.cs b/src/EvoSC.Common/Permissions/Attributes/PermissionGroupAttribute.cs index b5977e4a1..32df7bad4 100644 --- a/src/EvoSC.Common/Permissions/Attributes/PermissionGroupAttribute.cs +++ b/src/EvoSC.Common/Permissions/Attributes/PermissionGroupAttribute.cs @@ -3,8 +3,5 @@ /// /// Declares the enumeration as a list of defined permissions /// -[AttributeUsage(AttributeTargets.Enum, AllowMultiple = false)] -public class PermissionGroupAttribute : Attribute -{ - -} +[AttributeUsage(AttributeTargets.Enum)] +public class PermissionGroupAttribute : Attribute; diff --git a/src/EvoSC.Common/Permissions/PermissionManager.cs b/src/EvoSC.Common/Permissions/PermissionManager.cs index 840ce2a37..42fa00f2b 100644 --- a/src/EvoSC.Common/Permissions/PermissionManager.cs +++ b/src/EvoSC.Common/Permissions/PermissionManager.cs @@ -4,18 +4,11 @@ namespace EvoSC.Common.Permissions; -public class PermissionManager : IPermissionManager +public class PermissionManager(IPermissionRepository permissionRepository) : IPermissionManager { - private readonly IPermissionRepository _permissionRepository; - - public PermissionManager(IPermissionRepository permissionRepository) - { - _permissionRepository = permissionRepository; - } - public async Task HasPermissionAsync(IPlayer player, string permission) { - var result = await _permissionRepository.GetPlayerPermissionsAsync(player.Id); + var result = await permissionRepository.GetPlayerPermissionsAsync(player.Id); var permNames = result.Select(p => p.Name); @@ -27,7 +20,7 @@ public async Task HasPermissionAsync(IPlayer player, string permission) } } - var groups = await _permissionRepository.GetGroupsAsync(player.Id); + var groups = await permissionRepository.GetGroupsAsync(player.Id); foreach (var group in groups) { @@ -40,58 +33,58 @@ public async Task HasPermissionAsync(IPlayer player, string permission) return false; } - public async Task GetPermissionAsync(string name) => await _permissionRepository.GetPermissionAsync(name); + public async Task GetPermissionAsync(string name) => await permissionRepository.GetPermissionAsync(name); - public Task AddPermissionAsync(IPermission permission) => _permissionRepository.AddPermissionAsync(permission); + public Task AddPermissionAsync(IPermission permission) => permissionRepository.AddPermissionAsync(permission); - public Task UpdatePermissionAsync(IPermission permission) => _permissionRepository.UpdatePermissionAsync(permission); + public Task UpdatePermissionAsync(IPermission permission) => permissionRepository.UpdatePermissionAsync(permission); public async Task RemovePermissionAsync(string name) { - var permission = await _permissionRepository.GetPermissionAsync(name); + var permission = await permissionRepository.GetPermissionAsync(name); if (permission == null) { throw new InvalidOperationException($"Permission with name '{name}' does not exist."); } - await _permissionRepository.RemovePermissionAsync(permission); + await permissionRepository.RemovePermissionAsync(permission); } public Task RemovePermissionAsync(IPermission permission) => RemovePermissionAsync(permission.Name); - public Task AddGroupAsync(IGroup group) => _permissionRepository.AddGroupAsync(group); + public Task AddGroupAsync(IGroup group) => permissionRepository.AddGroupAsync(group); public async Task RemoveGroupAsync(int id) { - var group = await _permissionRepository.GetGroupAsync(id); + var group = await permissionRepository.GetGroupAsync(id); if (group == null) { throw new InvalidOperationException($"Group with id {id} does not exist."); } - await _permissionRepository.RemoveGroupAsync(group); + await permissionRepository.RemoveGroupAsync(group); } public Task RemoveGroupAsync(IGroup group) => RemoveGroupAsync(group.Id); - public Task UpdateGroupAsync(IGroup group) => _permissionRepository.UpdateGroupAsync(group); + public Task UpdateGroupAsync(IGroup group) => permissionRepository.UpdateGroupAsync(group); - public async Task GetGroupAsync(int id) => await _permissionRepository.GetGroupAsync(id); + public async Task GetGroupAsync(int id) => await permissionRepository.GetGroupAsync(id); public async Task AddPlayerToGroupAsync(IPlayer player, IGroup group) => - await _permissionRepository.AddPlayerToGroupAsync(player.Id, group.Id); + await permissionRepository.AddPlayerToGroupAsync(player.Id, group.Id); public async Task RemovePlayerFromGroupAsync(IPlayer player, IGroup group) => - await _permissionRepository.RemovePlayerFromGroupAsync(player.Id, group.Id); + await permissionRepository.RemovePlayerFromGroupAsync(player.Id, group.Id); public async Task AddPermissionToGroupAsync(IGroup group, IPermission permission) => - await _permissionRepository.AddPermissionToGroupAsync(group.Id, permission.Id); + await permissionRepository.AddPermissionToGroupAsync(group.Id, permission.Id); public async Task RemovePermissionFromGroupAsync(IGroup group, IPermission permission) => - await _permissionRepository.RemovePermissionFromGroupAsync(group.Id, permission.Id); + await permissionRepository.RemovePermissionFromGroupAsync(group.Id, permission.Id); public async Task ClearGroupPermissionsAsync(IGroup group) => - await _permissionRepository.ClearGroupPermissionsAsync(group.Id); + await permissionRepository.ClearGroupPermissionsAsync(group.Id); } diff --git a/src/EvoSC.Common/Remote/EventArgsModels/PodiumEventArgs.cs b/src/EvoSC.Common/Remote/EventArgsModels/PodiumEventArgs.cs index 60e777e24..82352a821 100644 --- a/src/EvoSC.Common/Remote/EventArgsModels/PodiumEventArgs.cs +++ b/src/EvoSC.Common/Remote/EventArgsModels/PodiumEventArgs.cs @@ -1,6 +1,3 @@ namespace EvoSC.Common.Remote.EventArgsModels; -public class PodiumEventArgs : TimedEventArgs -{ - -} +public class PodiumEventArgs : TimedEventArgs; diff --git a/src/EvoSC.Common/Services/Attributes/ServiceAttribute.cs b/src/EvoSC.Common/Services/Attributes/ServiceAttribute.cs index e27fc0057..5d4ef9b66 100644 --- a/src/EvoSC.Common/Services/Attributes/ServiceAttribute.cs +++ b/src/EvoSC.Common/Services/Attributes/ServiceAttribute.cs @@ -6,7 +6,7 @@ namespace EvoSC.Common.Services.Attributes; /// Classes annotated with this attribute will be automatically added to the /// DI container. Default lifestyle is Transient unless the service is a background service. /// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Class)] public class ServiceAttribute : Attribute { /// diff --git a/src/EvoSC.Common/Services/AuditService.cs b/src/EvoSC.Common/Services/AuditService.cs index ba8de3fb4..ac049568b 100644 --- a/src/EvoSC.Common/Services/AuditService.cs +++ b/src/EvoSC.Common/Services/AuditService.cs @@ -12,20 +12,12 @@ namespace EvoSC.Common.Services; -public class AuditService : IAuditService +public class AuditService(ILogger logger, IAuditRepository auditRepository) + : IAuditService { - private readonly ILogger _logger; - private readonly IAuditRepository _auditRepository; - - public AuditService(ILogger logger, IAuditRepository auditRepository) - { - _logger = logger; - _auditRepository = auditRepository; - } - private async Task LogDatabaseAsync(DbAuditRecord auditRecord) { - await _auditRepository.AddRecordAsync(auditRecord); + await auditRepository.AddRecordAsync(auditRecord); } private void LogLogger(DbAuditRecord auditRecord) @@ -36,7 +28,7 @@ private void LogLogger(DbAuditRecord auditRecord) _ => LogLevel.Information }; - _logger.Log(logLevel, "status={Status} event={Id} actor={Actor} comment={Comment} actionData={ActionData}", + logger.Log(logLevel, "status={Status} event={Id} actor={Actor} comment={Comment} actionData={ActionData}", auditRecord.Status, auditRecord.EventName, auditRecord.Actor?.AccountId ?? "", diff --git a/src/EvoSC.Common/Services/ContextService.cs b/src/EvoSC.Common/Services/ContextService.cs index 94e665ab5..726600411 100644 --- a/src/EvoSC.Common/Services/ContextService.cs +++ b/src/EvoSC.Common/Services/ContextService.cs @@ -7,22 +7,16 @@ namespace EvoSC.Common.Services; -public class ContextService : IContextService +public class ContextService(IAuditService auditService) : IContextService { private IControllerContext? _context; - private readonly IAuditService _auditService; - - public ContextService(IAuditService auditService) - { - _auditService = auditService; - } public IControllerContext CreateContext(Scope scope, IController controller) { IControllerContext context = new GenericControllerContext(scope) { Controller = controller, - AuditEvent = new AuditEventBuilder(_auditService) + AuditEvent = new AuditEventBuilder(auditService) }; context.SetScope(scope); diff --git a/src/EvoSC.Common/Services/MapService.cs b/src/EvoSC.Common/Services/MapService.cs index 34dc5c5a9..fa6a278e0 100644 --- a/src/EvoSC.Common/Services/MapService.cs +++ b/src/EvoSC.Common/Services/MapService.cs @@ -10,30 +10,14 @@ namespace EvoSC.Common.Services; -public class MapService : IMapService -{ - private readonly IMapRepository _mapRepository; - private readonly ILogger _logger; - private readonly IEvoScBaseConfig _config; - private readonly IPlayerManagerService _playerService; - private readonly IServerClient _serverClient; - private readonly IMatchSettingsService _matchSettings; - - public MapService(IMapRepository mapRepository, ILogger logger, IEvoScBaseConfig config, +public class MapService(IMapRepository mapRepository, ILogger logger, IEvoScBaseConfig config, IPlayerManagerService playerService, IServerClient serverClient, IMatchSettingsService matchSettings) - { - _mapRepository = mapRepository; - _logger = logger; - _config = config; - _playerService = playerService; - _serverClient = serverClient; - _matchSettings = matchSettings; - } - - public async Task GetMapByIdAsync(long id) => await _mapRepository.GetMapByIdAsync(id); + : IMapService +{ + public async Task GetMapByIdAsync(long id) => await mapRepository.GetMapByIdAsync(id); - public async Task GetMapByUidAsync(string uid) => await _mapRepository.GetMapByUidAsync(uid); - public async Task GetMapByExternalIdAsync(string id) => await _mapRepository.GetMapByExternalIdAsync(id); + public async Task GetMapByUidAsync(string uid) => await mapRepository.GetMapByUidAsync(uid); + public async Task GetMapByExternalIdAsync(string id) => await mapRepository.GetMapByExternalIdAsync(id); public async Task AddMapAsync(MapStream mapStream) { @@ -43,12 +27,12 @@ public async Task AddMapAsync(MapStream mapStream) IMap? existingMap = await GetMapByUidAsync(mapMetadata.MapUid); if (existingMap != null && MapVersionExistsInDb(existingMap, mapMetadata)) { - _logger.LogDebug("Map with UID {MapUid} already exists in database", mapMetadata.MapUid); + logger.LogDebug("Map with UID {MapUid} already exists in database", mapMetadata.MapUid); throw new DuplicateMapException($"Map with UID {mapMetadata.MapUid} already exists in database"); } var fileName = $"{mapMetadata.MapUid}.Map.Gbx"; - var filePath = Path.Combine(_config.Path.Maps, "EvoSC", fileName); + var filePath = Path.Combine(config.Path.Maps, "EvoSC", fileName); var relativePath = Path.Combine("EvoSC", fileName); await SaveMapFileAsync(mapFile, filePath); @@ -57,22 +41,22 @@ public async Task AddMapAsync(MapStream mapStream) ? mapMetadata.AuthorId : PlayerUtils.ConvertLoginToAccountId(mapMetadata.AuthorId); - var author = await _playerService.GetOrCreatePlayerAsync(playerId); + var author = await playerService.GetOrCreatePlayerAsync(playerId); IMap map; if (existingMap != null) { - _logger.LogDebug("Updating map with ID {MapId} to the database", existingMap.Id); - map = await _mapRepository.UpdateMapAsync(existingMap.Id, mapMetadata); + logger.LogDebug("Updating map with ID {MapId} to the database", existingMap.Id); + map = await mapRepository.UpdateMapAsync(existingMap.Id, mapMetadata); } else { - _logger.LogDebug("Adding map {Name} ({Uid}) to the database", mapMetadata.MapName, mapMetadata.MapUid); - map = await _mapRepository.AddMapAsync(mapMetadata, author, relativePath); + logger.LogDebug("Adding map {Name} ({Uid}) to the database", mapMetadata.MapName, mapMetadata.MapUid); + map = await mapRepository.AddMapAsync(mapMetadata, author, relativePath); } - await _matchSettings.EditMatchSettingsAsync(Path.GetFileNameWithoutExtension(_config.Path.DefaultMatchSettings), + await matchSettings.EditMatchSettingsAsync(Path.GetFileNameWithoutExtension(config.Path.DefaultMatchSettings), builder => builder.AddMap($"EvoSC/{fileName}")); return map; @@ -92,12 +76,12 @@ public async Task> AddMapsAsync(List mapStreams) public async Task RemoveMapAsync(long mapId) { - await _mapRepository.RemoveMapAsync(mapId); + await mapRepository.RemoveMapAsync(mapId); } public async Task AddCurrentMapListAsync() { - var serverMapList = await _serverClient.Remote.GetMapListAsync(-1, 0); + var serverMapList = await serverClient.Remote.GetMapListAsync(-1, 0); foreach (var serverMap in serverMapList) { @@ -111,7 +95,7 @@ public async Task AddCurrentMapListAsync() } var authorAccountId = PlayerUtils.ConvertLoginToAccountId(serverMap.Author); - var author = await _playerService.GetOrCreatePlayerAsync(authorAccountId); + var author = await playerService.GetOrCreatePlayerAsync(authorAccountId); var mapMeta = new MapMetadata { @@ -124,12 +108,12 @@ public async Task AddCurrentMapListAsync() ExternalMapProvider = null }; - _logger.LogDebug("Adding map {Name} ({Uid}) to the database", serverMap.Name, serverMap.UId); - await _mapRepository.AddMapAsync(mapMeta, author, serverMap.FileName); + logger.LogDebug("Adding map {Name} ({Uid}) to the database", serverMap.Name, serverMap.UId); + await mapRepository.AddMapAsync(mapMeta, author, serverMap.FileName); } catch (Exception ex) { - _logger.LogError(ex, "Failed to add current map to the database: {Name} ({Uid})", + logger.LogError(ex, "Failed to add current map to the database: {Name} ({Uid})", serverMap.Name, serverMap.UId); } @@ -138,7 +122,7 @@ public async Task AddCurrentMapListAsync() public async Task GetOrAddCurrentMapAsync() { - var currentMap = await _serverClient.Remote.GetCurrentMapInfoAsync(); + var currentMap = await serverClient.Remote.GetCurrentMapInfoAsync(); var map = await GetMapByUidAsync(currentMap.UId); if (map != null) @@ -147,7 +131,7 @@ public async Task GetOrAddCurrentMapAsync() } var mapAuthor = - await _playerService.GetOrCreatePlayerAsync(PlayerUtils.ConvertLoginToAccountId(currentMap.Author)); + await playerService.GetOrCreatePlayerAsync(PlayerUtils.ConvertLoginToAccountId(currentMap.Author)); var mapMeta = new MapMetadata { @@ -160,14 +144,14 @@ public async Task GetOrAddCurrentMapAsync() ExternalMapProvider = null }; - map = await _mapRepository.AddMapAsync(mapMeta, mapAuthor, currentMap.FileName); + map = await mapRepository.AddMapAsync(mapMeta, mapAuthor, currentMap.FileName); return map; } public async Task GetNextMapAsync() { - var nextMap = await _serverClient.Remote.GetNextMapInfoAsync(); + var nextMap = await serverClient.Remote.GetNextMapInfoAsync(); if (nextMap == null) { @@ -181,7 +165,7 @@ public async Task GetOrAddCurrentMapAsync() public async Task GetCurrentMapAsync() { - var currentMap = await _serverClient.Remote.GetCurrentMapInfoAsync(); + var currentMap = await serverClient.Remote.GetCurrentMapInfoAsync(); if (currentMap == null) { @@ -224,7 +208,7 @@ private async Task SaveMapFileAsync(Stream mapStream, string filePath) } catch (Exception e) { - _logger.LogWarning(e, "Failed saving the map file to storage"); + logger.LogWarning(e, "Failed saving the map file to storage"); throw; } } diff --git a/src/EvoSC.Common/Services/MatchSettingsService.cs b/src/EvoSC.Common/Services/MatchSettingsService.cs index b41723e52..bbf13a364 100644 --- a/src/EvoSC.Common/Services/MatchSettingsService.cs +++ b/src/EvoSC.Common/Services/MatchSettingsService.cs @@ -11,22 +11,12 @@ namespace EvoSC.Common.Services; -public class MatchSettingsService : IMatchSettingsService +public class MatchSettingsService(ILogger logger, IServerClient server, IEvoScBaseConfig config) + : IMatchSettingsService { - private readonly ILogger _logger; - private readonly IServerClient _server; - private readonly IEvoScBaseConfig _config; - - public MatchSettingsService(ILogger logger, IServerClient server, IEvoScBaseConfig config) - { - _logger = logger; - _server = server; - _config = config; - } - public async Task SetCurrentScriptSettingsAsync(Action> settingsAction) { - var settings = await _server.Remote.GetModeScriptSettingsAsync(); + var settings = await server.Remote.GetModeScriptSettingsAsync(); if (settings == null) { @@ -34,7 +24,7 @@ public async Task SetCurrentScriptSettingsAsync(Action SetCurrentScriptSettingsAsync(settings => @@ -49,7 +39,7 @@ public Task SetCurrentScriptSettingsAsync(IMatchSettings matchSettings) => SetCu }); public async Task?> GetCurrentScriptSettingsAsync() => - await _server.Remote.GetModeScriptSettingsAsync(); + await server.Remote.GetModeScriptSettingsAsync(); public Task LoadMatchSettingsAsync(string name) => LoadMatchSettingsAsync(name, true); @@ -58,16 +48,16 @@ public async Task LoadMatchSettingsAsync(string name, bool skipMap) try { var file = Path.GetFileName($"{name}.txt"); - await _server.Remote.LoadMatchSettingsAsync($"MatchSettings/{file}"); + await server.Remote.LoadMatchSettingsAsync($"MatchSettings/{file}"); if (skipMap) { - await _server.Remote.NextMapAsync(); + await server.Remote.NextMapAsync(); } } catch (XmlRpcFaultException ex) { - _logger.LogError(ex, "Failed to load match settings: {Msg}", ex.Fault.FaultString); + logger.LogError(ex, "Failed to load match settings: {Msg}", ex.Fault.FaultString); if (ex.Fault.FaultCode == -1000) { @@ -90,7 +80,7 @@ private async Task SaveMatchSettingsAsync(string name, MatchSett try { - if (!await _server.Remote.WriteFileAsync(fileName, contents)) + if (!await server.Remote.WriteFileAsync(fileName, contents)) { throw new InvalidOperationException("Failed to create match settings due to an unknown error."); } @@ -101,11 +91,11 @@ private async Task SaveMatchSettingsAsync(string name, MatchSett { if (ex is XmlRpcFaultException faultEx) { - _logger.LogError(faultEx, "Failed to create match settings due to XMLRPC fault"); + logger.LogError(faultEx, "Failed to create match settings due to XMLRPC fault"); } else { - _logger.LogError(ex, "An error occured while creating match settings"); + logger.LogError(ex, "An error occured while creating match settings"); } throw; @@ -122,11 +112,11 @@ public Task CreateMatchSettingsAsync(string name, Action GetFilePathAsync(string name) { - var mapsDir = _config.Path.Maps; + var mapsDir = config.Path.Maps; if (mapsDir == string.Empty) { - mapsDir = await _server.Remote.GetMapsDirectoryAsync(); + mapsDir = await server.Remote.GetMapsDirectoryAsync(); } // if it's still empty and doesn't exist, we should throw an error diff --git a/src/EvoSC.Common/Services/PlayerManagerService.cs b/src/EvoSC.Common/Services/PlayerManagerService.cs index 84bd3ee22..53b08a3e9 100644 --- a/src/EvoSC.Common/Services/PlayerManagerService.cs +++ b/src/EvoSC.Common/Services/PlayerManagerService.cs @@ -9,24 +9,12 @@ namespace EvoSC.Common.Services; -public class PlayerManagerService : IPlayerManagerService -{ - private readonly IPlayerRepository _playerRepository; - private readonly IPlayerCacheService _playerCache; - private readonly IServerClient _server; - private readonly ILogger _logger; - - public PlayerManagerService(IPlayerRepository playerRepository, IPlayerCacheService playerCache, +public class PlayerManagerService(IPlayerRepository playerRepository, IPlayerCacheService playerCache, IServerClient server, ILogger logger) - { - _playerRepository = playerRepository; - _playerCache = playerCache; - _server = server; - _logger = logger; - } - + : IPlayerManagerService +{ public async Task GetPlayerAsync(string accountId) => - await _playerRepository.GetPlayerByAccountIdAsync(accountId); + await playerRepository.GetPlayerByAccountIdAsync(accountId); public async Task GetOrCreatePlayerAsync(string accountId) { @@ -41,7 +29,7 @@ public async Task GetOrCreatePlayerAsync(string accountId) } catch (Exception ex) { - _logger.LogDebug(ex, + logger.LogDebug(ex, "Error when trying to get player with Account ID '{AccountID}'. Will attempt creating it instead", accountId); } @@ -58,21 +46,21 @@ public async Task CreatePlayerAsync(string accountId, string? name) TmPlayerDetailedInfo? playerInfo = null; try { - playerInfo = await _server.Remote.GetDetailedPlayerInfoAsync(playerLogin); + playerInfo = await server.Remote.GetDetailedPlayerInfoAsync(playerLogin); } catch (Exception ex) { - _logger.LogTrace(ex, "Failed to obtain player info, are they on the server?"); + logger.LogTrace(ex, "Failed to obtain player info, are they on the server?"); } playerInfo ??= new TmPlayerDetailedInfo {Login = playerLogin, NickName = name ?? accountId}; - return await _playerRepository.AddPlayerAsync(accountId, playerInfo); + return await playerRepository.AddPlayerAsync(accountId, playerInfo); } public async Task GetOnlinePlayerAsync(string accountId) { - var player = await _playerCache.GetOnlinePlayerCachedAsync(accountId); + var player = await playerCache.GetOnlinePlayerCachedAsync(accountId); if (player == null) { @@ -85,9 +73,9 @@ public async Task GetOnlinePlayerAsync(string accountId) public Task GetOnlinePlayerAsync(IPlayer player) => GetOnlinePlayerAsync(player.AccountId); - public Task UpdateLastVisitAsync(IPlayer player) => _playerRepository.UpdateLastVisitAsync(player); + public Task UpdateLastVisitAsync(IPlayer player) => playerRepository.UpdateLastVisitAsync(player); - public Task> GetOnlinePlayersAsync() => Task.FromResult(_playerCache.OnlinePlayers); + public Task> GetOnlinePlayersAsync() => Task.FromResult(playerCache.OnlinePlayers); private const int MinMatchingCharacters = 2; diff --git a/src/EvoSC.Common/Services/ServiceContainerManager.cs b/src/EvoSC.Common/Services/ServiceContainerManager.cs index 647b39c03..3fb980c7e 100644 --- a/src/EvoSC.Common/Services/ServiceContainerManager.cs +++ b/src/EvoSC.Common/Services/ServiceContainerManager.cs @@ -4,26 +4,19 @@ using EvoSC.Common.Services.Attributes; using EvoSC.Common.Services.Exceptions; using EvoSC.Common.Services.Models; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SimpleInjector; using SimpleInjector.Lifestyles; namespace EvoSC.Common.Services; -public class ServiceContainerManager : IServiceContainerManager +public class ServiceContainerManager(IEvoSCApplication app, ILogger logger) + : IServiceContainerManager { - private readonly IEvoSCApplication _app; - private readonly ILogger _logger; - private readonly Dictionary _containers = new(); private readonly Dictionary> _dependencyServices = new(); - public ServiceContainerManager(IEvoSCApplication app, ILogger logger) - { - _app = app; - _logger = logger; - } - public void AddContainer(Guid moduleId, Container container) { container.ResolveUnregisteredType += (_, args) => @@ -38,7 +31,7 @@ public void AddContainer(Guid moduleId, Container container) _containers.Add(moduleId, container); - _logger.LogDebug("Added service container with ID: {ContainerId}", moduleId); + logger.LogDebug("Added service container with ID: {ContainerId}", moduleId); } public Container NewContainer(Guid moduleId, IEnumerable assemblies, List loadedDependencies) @@ -120,7 +113,7 @@ public void RemoveContainer(Guid moduleId) GC.WaitForPendingFinalizers(); GC.Collect(); - _logger.LogDebug("Removed service container for container: {ContainerId}", moduleId); + logger.LogDebug("Removed service container for container: {ContainerId}", moduleId); } public void RegisterDependency(Guid moduleId, Guid dependencyId) @@ -141,7 +134,7 @@ public void RegisterDependency(Guid moduleId, Guid dependencyId) } _dependencyServices[moduleId].Add(dependencyId); - _logger.LogDebug("Registered dependency '{DepId}' for '{ContainerId}'", dependencyId, moduleId); + logger.LogDebug("Registered dependency '{DepId}' for '{ContainerId}'", dependencyId, moduleId); } public Container GetContainer(Guid moduleId) @@ -156,11 +149,16 @@ public Container GetContainer(Guid moduleId) private void ResolveCoreService(UnregisteredTypeEventArgs e, Guid containerId) { + if (e.UnregisteredServiceType == typeof(IServiceProviderIsService)) + { + return; + } + try { e.Register(() => { - _logger.LogTrace("Will attempt to resolve service '{Service}' for {Container}", + logger.LogTrace("Will attempt to resolve service '{Service}' for {Container}", e.UnregisteredServiceType, containerId); @@ -174,7 +172,7 @@ private void ResolveCoreService(UnregisteredTypeEventArgs e, Guid containerId) } catch (ActivationException ex) { - _logger.LogTrace(ex, + logger.LogTrace(ex, "Did not find service {Service} for container {Container} in dependency {Dependency}", e.UnregisteredServiceType, containerId, @@ -183,17 +181,17 @@ private void ResolveCoreService(UnregisteredTypeEventArgs e, Guid containerId) } } - _logger.LogTrace( + logger.LogTrace( "Dependencies does not have service '{Service}' for {Container}. Will try core services", e.UnregisteredServiceType, containerId); - return _app.Services.GetInstance(e.UnregisteredServiceType); + return app.Services.GetInstance(e.UnregisteredServiceType); }); } catch (Exception ex) { - _logger.LogError(ex, "An unknown error occured while trying to resolve a core service"); + logger.LogError(ex, "An unknown error occured while trying to resolve a core service"); } } } diff --git a/src/EvoSC.Common/TextParsing/ValueReaders/OnlinePlayerReader.cs b/src/EvoSC.Common/TextParsing/ValueReaders/OnlinePlayerReader.cs index b68f0b6c8..04f03a1bb 100644 --- a/src/EvoSC.Common/TextParsing/ValueReaders/OnlinePlayerReader.cs +++ b/src/EvoSC.Common/TextParsing/ValueReaders/OnlinePlayerReader.cs @@ -9,20 +9,13 @@ namespace EvoSC.Common.TextParsing.ValueReaders; /// Find a player online on the server from an input search pattern. /// Best match is returned. /// -public class OnlinePlayerReader : IValueReader +public class OnlinePlayerReader(IPlayerManagerService playerManager) : IValueReader { public IEnumerable AllowedTypes => new[] {typeof(IOnlinePlayer)}; - private readonly IPlayerManagerService _playerManager; - - public OnlinePlayerReader(IPlayerManagerService playerManager) - { - _playerManager = playerManager; - } - public async Task ReadAsync(Type type, string input) { - var players = await _playerManager.FindOnlinePlayerAsync(input); + var players = await playerManager.FindOnlinePlayerAsync(input); if (!players.Any()) { diff --git a/src/EvoSC.Common/Themes/Events/Args/ThemeUpdatedEventArgs.cs b/src/EvoSC.Common/Themes/Events/Args/ThemeUpdatedEventArgs.cs index 78012a7b1..bdbb38875 100644 --- a/src/EvoSC.Common/Themes/Events/Args/ThemeUpdatedEventArgs.cs +++ b/src/EvoSC.Common/Themes/Events/Args/ThemeUpdatedEventArgs.cs @@ -1,5 +1,3 @@ namespace EvoSC.Common.Themes.Events.Args; -public class ThemeUpdatedEventArgs : EventArgs -{ -} +public class ThemeUpdatedEventArgs : EventArgs; diff --git a/src/EvoSC.Common/Themes/Exceptions/ThemeDoesNotExistException.cs b/src/EvoSC.Common/Themes/Exceptions/ThemeDoesNotExistException.cs index b8404937a..c6b9da40f 100644 --- a/src/EvoSC.Common/Themes/Exceptions/ThemeDoesNotExistException.cs +++ b/src/EvoSC.Common/Themes/Exceptions/ThemeDoesNotExistException.cs @@ -1,8 +1,3 @@ namespace EvoSC.Common.Themes.Exceptions; -public class ThemeDoesNotExistException : ThemeException -{ - public ThemeDoesNotExistException(string name) : base($"The theme with name '{name}' does not exist.") - { - } -} +public class ThemeDoesNotExistException(string name) : ThemeException($"The theme with name '{name}' does not exist."); diff --git a/src/EvoSC.Common/Themes/ThemeManager.cs b/src/EvoSC.Common/Themes/ThemeManager.cs index 227cdd912..8e4699573 100644 --- a/src/EvoSC.Common/Themes/ThemeManager.cs +++ b/src/EvoSC.Common/Themes/ThemeManager.cs @@ -11,13 +11,10 @@ namespace EvoSC.Common.Themes; -public class ThemeManager : IThemeManager +public class ThemeManager(IServiceContainerManager serviceManager, IEvoSCApplication evoscApp, IEventManager events, + IEvoScBaseConfig evoscConfig) + : IThemeManager { - private readonly IServiceContainerManager _serviceManager; - private readonly IEvoSCApplication _evoscApp; - private readonly IEventManager _events; - private readonly IEvoScBaseConfig _evoscConfig; - private dynamic? _themeOptionsCache; private Dictionary? _componentReplacementsCache; @@ -30,14 +27,6 @@ public class ThemeManager : IThemeManager public Dictionary ComponentReplacements => _componentReplacementsCache ?? GetCurrentComponentReplacements(); - public ThemeManager(IServiceContainerManager serviceManager, IEvoSCApplication evoscApp, IEventManager events, IEvoScBaseConfig evoscConfig) - { - _serviceManager = serviceManager; - _evoscApp = evoscApp; - _events = events; - _evoscConfig = evoscConfig; - } - public async Task AddThemeAsync(Type themeType, Guid moduleId) { var attr = themeType.GetCustomAttribute(); @@ -82,7 +71,7 @@ public async Task RemoveThemeAsync(string name) if (_activeThemes.Remove(themeInfo.EffectiveThemeType)) { InvalidateCache(); - await _events.RaiseAsync(ThemeEvents.CurrentThemeChanged, new ThemeUpdatedEventArgs()); + await events.RaiseAsync(ThemeEvents.CurrentThemeChanged, new ThemeUpdatedEventArgs()); } } @@ -102,11 +91,11 @@ public async Task ActivateThemeAsync(string name) ThrowIfNotExists(name); var themeInfo = _availableThemes[name]; - var services = _evoscApp.Services; + var services = evoscApp.Services; if (!themeInfo.ModuleId.Equals(Guid.Empty)) { - services = _serviceManager.GetContainer(themeInfo.ModuleId); + services = serviceManager.GetContainer(themeInfo.ModuleId); } var theme = ActivatorUtilities.CreateInstance(services, themeInfo.ThemeType) as ITheme; @@ -121,7 +110,7 @@ public async Task ActivateThemeAsync(string name) await theme.ConfigureAsync(); InvalidateCache(); - await _events.RaiseAsync(ThemeEvents.CurrentThemeChanged, new ThemeUpdatedEventArgs()); + await events.RaiseAsync(ThemeEvents.CurrentThemeChanged, new ThemeUpdatedEventArgs()); return theme; } @@ -164,7 +153,7 @@ private Dictionary GetConfigOverrideOptions() { var themeOptions = new Dictionary(); - foreach (var defaultOption in _evoscConfig.Theme) + foreach (var defaultOption in evoscConfig.Theme) { var key = defaultOption.Key.StartsWith("Theme.", StringComparison.Ordinal) ? defaultOption.Key[6..] diff --git a/src/EvoSC.Common/Util/MatchSettings/Attributes/ScriptSettingsForAttribute.cs b/src/EvoSC.Common/Util/MatchSettings/Attributes/ScriptSettingsForAttribute.cs index 05c2bf88c..8497657c9 100644 --- a/src/EvoSC.Common/Util/MatchSettings/Attributes/ScriptSettingsForAttribute.cs +++ b/src/EvoSC.Common/Util/MatchSettings/Attributes/ScriptSettingsForAttribute.cs @@ -3,17 +3,11 @@ namespace EvoSC.Common.Util.MatchSettings.Attributes; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] -public class ScriptSettingsForAttribute : Attribute +public class ScriptSettingsForAttribute(string scriptName) : Attribute { - public string Name { get; set; } + public string Name { get; set; } = scriptName; - public ScriptSettingsForAttribute(string scriptName) + public ScriptSettingsForAttribute(DefaultModeScriptName mode) : this(mode.GetIdentifier()) { - Name = scriptName; - } - - public ScriptSettingsForAttribute(DefaultModeScriptName mode) - { - Name = mode.GetIdentifier(); } } diff --git a/src/EvoSC.Common/Util/MatchSettings/Models/MatchSettingsInfo.cs b/src/EvoSC.Common/Util/MatchSettings/Models/MatchSettingsInfo.cs index 695382284..17823b914 100644 --- a/src/EvoSC.Common/Util/MatchSettings/Models/MatchSettingsInfo.cs +++ b/src/EvoSC.Common/Util/MatchSettings/Models/MatchSettingsInfo.cs @@ -3,6 +3,4 @@ /// /// Represents an object for a match settings file. /// -public class MatchSettingsInfo : MatchSettingsXmlSerializer -{ -} +public class MatchSettingsInfo : MatchSettingsXmlSerializer; diff --git a/src/EvoSC.Common/Util/RaceTime.cs b/src/EvoSC.Common/Util/RaceTime.cs index 2f8ddf2da..0a315dc49 100644 --- a/src/EvoSC.Common/Util/RaceTime.cs +++ b/src/EvoSC.Common/Util/RaceTime.cs @@ -3,22 +3,15 @@ namespace EvoSC.Common.Util; -public class RaceTime : IRaceTime +public class RaceTime(int milliseconds, int seconds, int minutes, int hours) + : IRaceTime { public int TotalMilliseconds => Milliseconds + Seconds * 1000 + Minutes * 60 * 1000 + Hours * 60 * 60 * 1000; - public int Milliseconds { get; set; } - public int Seconds { get; set; } - public int Minutes { get; set; } - public int Hours { get; set; } + public int Milliseconds { get; set; } = milliseconds; + public int Seconds { get; set; } = seconds; + public int Minutes { get; set; } = minutes; + public int Hours { get; set; } = hours; - public RaceTime(int milliseconds, int seconds, int minutes, int hours) - { - Milliseconds = milliseconds; - Seconds = seconds; - Minutes = minutes; - Hours = hours; - } - public static IRaceTime FromMilliseconds(int totalMilliseconds) { var milliseconds = totalMilliseconds % 1000; diff --git a/src/EvoSC.Manialinks/Attributes/FormEntryModelAttribute.cs b/src/EvoSC.Manialinks/Attributes/FormEntryModelAttribute.cs index f6a924940..f3f0e93b3 100644 --- a/src/EvoSC.Manialinks/Attributes/FormEntryModelAttribute.cs +++ b/src/EvoSC.Manialinks/Attributes/FormEntryModelAttribute.cs @@ -3,8 +3,5 @@ /// /// Specifies that the annotated class is used as an Form Entry Model. /// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] -public class FormEntryModelAttribute : Attribute -{ - -} +[AttributeUsage(AttributeTargets.Class)] +public class FormEntryModelAttribute : Attribute; diff --git a/src/EvoSC.Manialinks/Attributes/ManialinkRouteAttribute.cs b/src/EvoSC.Manialinks/Attributes/ManialinkRouteAttribute.cs index 61cdafbff..347d4b2a7 100644 --- a/src/EvoSC.Manialinks/Attributes/ManialinkRouteAttribute.cs +++ b/src/EvoSC.Manialinks/Attributes/ManialinkRouteAttribute.cs @@ -3,7 +3,7 @@ /// /// Allows to set a custom route or permission to the Manialink Action or all Manialink Actions within a controller. /// -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class ManialinkRouteAttribute : Attribute { /// diff --git a/src/EvoSC.Manialinks/EvoSC.Manialinks.csproj b/src/EvoSC.Manialinks/EvoSC.Manialinks.csproj index 94f46630a..daeba3bec 100644 --- a/src/EvoSC.Manialinks/EvoSC.Manialinks.csproj +++ b/src/EvoSC.Manialinks/EvoSC.Manialinks.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable @@ -14,18 +14,5 @@ - - - - - - - - - - - - - diff --git a/src/EvoSC.Manialinks/ManialinkActionManager.cs b/src/EvoSC.Manialinks/ManialinkActionManager.cs index 8299c3990..80c60cb96 100644 --- a/src/EvoSC.Manialinks/ManialinkActionManager.cs +++ b/src/EvoSC.Manialinks/ManialinkActionManager.cs @@ -11,7 +11,7 @@ namespace EvoSC.Manialinks; -public class ManialinkActionManager : IManialinkActionManager +public class ManialinkActionManager(ILogger logger) : IManialinkActionManager { private const BindingFlags ActionMethodBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; private static readonly char RouteDelimiter = '/'; @@ -19,18 +19,12 @@ public class ManialinkActionManager : IManialinkActionManager private static readonly Regex ValidCharactersInRouteNameRegex = new("[_\\.\\w\\d]+", RegexOptions.None, TimeSpan.FromMilliseconds(100)); private static readonly string ControllerPostfix = "Controller"; private static readonly string AsyncMethodPostfix = "Async"; - - private readonly ILogger _logger; + private readonly IMlRouteNode _rootNode = new MlRouteNode(""){Children = new Dictionary()}; private readonly object _rootNodeMutex = new(); private readonly Dictionary> _controllerRoutes = new(); private readonly object _controllerRoutesMutex = new(); - public ManialinkActionManager(ILogger logger) - { - _logger = logger; - } - /// /// Get the effective route to a controller. /// @@ -284,7 +278,7 @@ private void AddActionInternal(string route, IManialinkAction action) currentNode.Action = action; } - _logger.LogDebug("Registered manialink route: {Route}", route); + logger.LogDebug("Registered manialink route: {Route}", route); } public void AddRoute(string route, IManialinkAction action) => AddActionInternal(route, action); @@ -478,7 +472,7 @@ public void UnregisterForController(Type controllerType) catch (InvalidOperationException ex) { // ignore errors when the route already doesn't exist - _logger.LogDebug(ex, "The route {Route} does not exist for controller {Controller}", + logger.LogDebug(ex, "The route {Route} does not exist for controller {Controller}", route, controllerType.ToString()); } diff --git a/src/EvoSC.Manialinks/ManialinkInteractionContext.cs b/src/EvoSC.Manialinks/ManialinkInteractionContext.cs index 92e9535b3..52710408f 100644 --- a/src/EvoSC.Manialinks/ManialinkInteractionContext.cs +++ b/src/EvoSC.Manialinks/ManialinkInteractionContext.cs @@ -6,12 +6,10 @@ namespace EvoSC.Manialinks; -public class ManialinkInteractionContext : PlayerInteractionContext, IManialinkInteractionContext +public class ManialinkInteractionContext + (IOnlinePlayer player, IControllerContext context) : PlayerInteractionContext(player, context), + IManialinkInteractionContext { public required IManialinkActionContext ManialinkAction { get; init; } public required IManialinkManager ManialinkManager { get; init; } - - public ManialinkInteractionContext(IOnlinePlayer player, IControllerContext context) : base(player, context) - { - } } diff --git a/src/EvoSC.Manialinks/Middleware/ManialinkPermissionMiddleware.cs b/src/EvoSC.Manialinks/Middleware/ManialinkPermissionMiddleware.cs index 5bb1a1291..c3ed21a57 100644 --- a/src/EvoSC.Manialinks/Middleware/ManialinkPermissionMiddleware.cs +++ b/src/EvoSC.Manialinks/Middleware/ManialinkPermissionMiddleware.cs @@ -9,33 +9,22 @@ namespace EvoSC.Manialinks.Middleware; /// This middleware checks if a user has the permission to execute a Manialink Action. /// A message in chat is sent to the player in case of insufficient permissions. /// -public class ManialinkPermissionMiddleware +public class ManialinkPermissionMiddleware(ActionDelegate next, IPermissionManager permissions, IServerClient server) { - private readonly ActionDelegate _next; - private readonly IPermissionManager _permissions; - private readonly IServerClient _server; - - public ManialinkPermissionMiddleware(ActionDelegate next, IPermissionManager permissions, IServerClient server) - { - _next = next; - _permissions = permissions; - _server = server; - } - public async Task ExecuteAsync(IControllerContext context) { if (context is not ManialinkInteractionContext mlContext || mlContext.ManialinkAction.Action.Permission == null) { - await _next(context); + await next(context); return; } - if (await _permissions.HasPermissionAsync(mlContext.Player, mlContext.ManialinkAction.Action.Permission)) + if (await permissions.HasPermissionAsync(mlContext.Player, mlContext.ManialinkAction.Action.Permission)) { - await _next(context); + await next(context); return; } - await _server.ErrorMessageAsync("Sorry, you don't have permission to do that.", mlContext.Player); + await server.ErrorMessageAsync("Sorry, you don't have permission to do that.", mlContext.Player); } } diff --git a/src/EvoSC.Manialinks/Models/MlRouteNode.cs b/src/EvoSC.Manialinks/Models/MlRouteNode.cs index 28c75a805..1e09ba9bd 100644 --- a/src/EvoSC.Manialinks/Models/MlRouteNode.cs +++ b/src/EvoSC.Manialinks/Models/MlRouteNode.cs @@ -2,19 +2,14 @@ namespace EvoSC.Manialinks.Models; -public class MlRouteNode : IMlRouteNode +/// +/// Instantiate a new manialink route node. +/// +/// The name of the route component. +public class MlRouteNode(string name) : IMlRouteNode { - public string Name { get; set; } + public string Name { get; set; } = name; public IManialinkAction? Action { get; set; } public Dictionary? Children { get; set; } public bool IsParameter { get; set; } - - /// - /// Instantiate a new manialink route node. - /// - /// The name of the route component. - public MlRouteNode(string name) - { - Name = name; - } } diff --git a/src/EvoSC.Manialinks/Themes/DefaultAlertTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultAlertTheme.cs index 5a747553b..4ac0efa13 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultAlertTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultAlertTheme.cs @@ -5,11 +5,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "Alert Component", Description = "Default theme for the Alert component.")] -public class DefaultAlertTheme : Theme +public class DefaultAlertTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultAlertTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.Alert.Default.Text").To(_theme.UI_TextPrimary); diff --git a/src/EvoSC.Manialinks/Themes/DefaultButtonTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultButtonTheme.cs index 971383385..1f772b23f 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultButtonTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultButtonTheme.cs @@ -6,10 +6,9 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "Button Component", Description = "Default theme for the Button component.")] -public class DefaultButtonTheme : Theme +public class DefaultButtonTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultButtonTheme(IThemeManager theme) => _theme = theme.Theme; + private readonly dynamic _theme = theme.Theme; public override Task ConfigureAsync() { diff --git a/src/EvoSC.Manialinks/Themes/DefaultCheckboxTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultCheckboxTheme.cs index 7952344f6..e12b77df6 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultCheckboxTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultCheckboxTheme.cs @@ -5,11 +5,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "Checkbox Component", Description = "Default theme for the Checkbox component.")] -public class DefaultCheckboxTheme : Theme +public class DefaultCheckboxTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultCheckboxTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.Checkbox.Default.Bg").To(_theme.UI_BgPrimary); diff --git a/src/EvoSC.Manialinks/Themes/DefaultRadioButtonTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultRadioButtonTheme.cs index fc8821c38..f8b2ac674 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultRadioButtonTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultRadioButtonTheme.cs @@ -5,11 +5,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "RadioButton Component", Description = "Default theme for the RadioButton component.")] -public class DefaultRadioButtonTheme : Theme +public class DefaultRadioButtonTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultRadioButtonTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.RadioButton.Default.Text").To(_theme.UI_TextPrimary); diff --git a/src/EvoSC.Manialinks/Themes/DefaultTextInputTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultTextInputTheme.cs index 18dfb01ae..0531a454d 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultTextInputTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultTextInputTheme.cs @@ -5,11 +5,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "TextInput Component", Description = "Default theme for the TextInput component.")] -public class DefaultTextInputTheme : Theme +public class DefaultTextInputTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultTextInputTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.TextField.Default.Text").To(_theme.UI_TextPrimary); diff --git a/src/EvoSC.Manialinks/Themes/DefaultToggleSwitchTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultToggleSwitchTheme.cs index 56b716dbf..2459ff048 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultToggleSwitchTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultToggleSwitchTheme.cs @@ -5,11 +5,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "ToggleSwitch Component", Description = "Default theme for the ToggleSwitch component.")] -public class DefaultToggleSwitchTheme : Theme +public class DefaultToggleSwitchTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultToggleSwitchTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.ToggleSwitch.Default.OnText").To(_theme.UI_BgPrimary); diff --git a/src/EvoSC.Manialinks/Themes/DefaultWindowTheme.cs b/src/EvoSC.Manialinks/Themes/DefaultWindowTheme.cs index ce9dda3c4..584ecb2bc 100644 --- a/src/EvoSC.Manialinks/Themes/DefaultWindowTheme.cs +++ b/src/EvoSC.Manialinks/Themes/DefaultWindowTheme.cs @@ -6,11 +6,10 @@ namespace EvoSC.Manialinks.Themes; [Theme(Name = "Window Component", Description = "Default theme for the Window component.")] -public class DefaultWindowTheme : Theme +public class DefaultWindowTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - public DefaultWindowTheme(IThemeManager theme) => _theme = theme.Theme; - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("UI.Window.Default.Bg").To(_theme.UI_BgSecondary); diff --git a/src/EvoSC.Manialinks/Util/FontManialinkHelper.cs b/src/EvoSC.Manialinks/Util/FontManialinkHelper.cs index 0bc143424..a043b6606 100644 --- a/src/EvoSC.Manialinks/Util/FontManialinkHelper.cs +++ b/src/EvoSC.Manialinks/Util/FontManialinkHelper.cs @@ -2,9 +2,9 @@ namespace EvoSC.Manialinks.Util; -public class FontManialinkHelper +public class FontManialinkHelper(IThemeManager theme) { - private readonly dynamic _theme; + private readonly dynamic _theme = theme.Theme; /// /// Thin thickness of the current font. @@ -30,12 +30,7 @@ public class FontManialinkHelper /// Mono version of the current font. /// public string Mono => ToExtraBold(_theme.UI_Font); - - public FontManialinkHelper(IThemeManager theme) - { - _theme = theme.Theme; - } - + /// /// Convert the provided font to it's regular thickness version. /// diff --git a/src/EvoSC.Manialinks/Util/GlobalManialinkUtils.cs b/src/EvoSC.Manialinks/Util/GlobalManialinkUtils.cs index c579105c0..d6418b1af 100644 --- a/src/EvoSC.Manialinks/Util/GlobalManialinkUtils.cs +++ b/src/EvoSC.Manialinks/Util/GlobalManialinkUtils.cs @@ -3,16 +3,11 @@ namespace EvoSC.Manialinks.Util; -public class GlobalManialinkUtils +public class GlobalManialinkUtils(IThemeManager themeManager) { - private readonly dynamic _theme; + private readonly dynamic _theme = themeManager.Theme; private readonly GameIcons _icons = new(); - public GlobalManialinkUtils(IThemeManager themeManager) - { - _theme = themeManager.Theme; - } - /// /// Status type to a color. /// diff --git a/src/EvoSC.Modules.SourceGeneration/EvoSC.Modules.SourceGeneration.csproj b/src/EvoSC.Modules.SourceGeneration/EvoSC.Modules.SourceGeneration.csproj index a96a14822..c479ecb8b 100644 --- a/src/EvoSC.Modules.SourceGeneration/EvoSC.Modules.SourceGeneration.csproj +++ b/src/EvoSC.Modules.SourceGeneration/EvoSC.Modules.SourceGeneration.csproj @@ -6,13 +6,13 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleAuthorAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleAuthorAttribute.cs index 3ab7e277c..e1c01d5ea 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleAuthorAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleAuthorAttribute.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly)] -public class ModuleAuthorAttribute : Attribute +public class ModuleAuthorAttribute(string author) : Attribute { /// /// The module's author. /// - public string Author { get; } - - public ModuleAuthorAttribute(string author) - { - Author = author; - } + public string Author { get; } = author; } diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleDependencyAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleDependencyAttribute.cs index f4997d566..b836a6a5c 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleDependencyAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleDependencyAttribute.cs @@ -1,21 +1,15 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] -public class ModuleDependencyAttribute : Attribute +public class ModuleDependencyAttribute(string name, string requiredVersion) : Attribute { /// /// The identifier name of the dependency. /// - public string Name { get; } - + public string Name { get; } = name; + /// /// The version required for this dependency. /// - public string RequiredVersion { get; } - - public ModuleDependencyAttribute(string name, string requiredVersion) - { - Name = name; - RequiredVersion = requiredVersion; - } + public string RequiredVersion { get; } = requiredVersion; } diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleIdentifierAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleIdentifierAttribute.cs index 8673d3e4a..7c664f0cf 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleIdentifierAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleIdentifierAttribute.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] -public class ModuleIdentifierAttribute : Attribute +public class ModuleIdentifierAttribute(string name) : Attribute { /// /// The name of the module. /// - public string Name { get; } - - public ModuleIdentifierAttribute(string name) - { - Name = name; - } + public string Name { get; } = name; } diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleSummaryAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleSummaryAttribute.cs index f5b8f4343..d20444a32 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleSummaryAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleSummaryAttribute.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly)] -public class ModuleSummaryAttribute : Attribute +public class ModuleSummaryAttribute(string summary) : Attribute { /// /// A short description of the module. /// - public string Summary { get; } - - public ModuleSummaryAttribute(string summary) - { - Summary = summary; - } + public string Summary { get; } = summary; } diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleTitleAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleTitleAttribute.cs index 4cd26e246..9029c6dd9 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleTitleAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleTitleAttribute.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly)] -public class ModuleTitleAttribute : Attribute +public class ModuleTitleAttribute(string title) : Attribute { /// /// The title of the module. /// - public string Title { get; } - - public ModuleTitleAttribute(string title) - { - Title = title; - } + public string Title { get; } = title; } diff --git a/src/EvoSC.Modules/Attributes/Assembly/ModuleVersionAttribute.cs b/src/EvoSC.Modules/Attributes/Assembly/ModuleVersionAttribute.cs index 3d218e2c1..1a30343df 100644 --- a/src/EvoSC.Modules/Attributes/Assembly/ModuleVersionAttribute.cs +++ b/src/EvoSC.Modules/Attributes/Assembly/ModuleVersionAttribute.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Attributes; [AttributeUsage(AttributeTargets.Assembly)] -public class ModuleVersionAttribute : Attribute +public class ModuleVersionAttribute(string version) : Attribute { /// /// The current version of the module. /// - public Version Version { get; } - - public ModuleVersionAttribute(string version) - { - this.Version = Version.Parse(version); - } + public Version Version { get; } = Version.Parse((string)version); } diff --git a/src/EvoSC.Modules/Attributes/ModuleAttribute.cs b/src/EvoSC.Modules/Attributes/ModuleAttribute.cs index 950cb283f..c682dfaa1 100644 --- a/src/EvoSC.Modules/Attributes/ModuleAttribute.cs +++ b/src/EvoSC.Modules/Attributes/ModuleAttribute.cs @@ -3,7 +3,7 @@ /// /// Defines a class as a module's main class. /// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Class)] public class ModuleAttribute : Attribute { /// diff --git a/src/EvoSC.Modules/Attributes/SettingsAttribute.cs b/src/EvoSC.Modules/Attributes/SettingsAttribute.cs index 6f900b209..68c6d6bab 100644 --- a/src/EvoSC.Modules/Attributes/SettingsAttribute.cs +++ b/src/EvoSC.Modules/Attributes/SettingsAttribute.cs @@ -3,8 +3,5 @@ /// /// Defines the interface as a dynamic configuration for the module in the current assembly. /// -[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] -public class SettingsAttribute : Attribute -{ - -} +[AttributeUsage(AttributeTargets.Interface)] +public class SettingsAttribute : Attribute; diff --git a/src/EvoSC.Modules/EvoSC.Modules.csproj b/src/EvoSC.Modules/EvoSC.Modules.csproj index 271b5b0cb..6c6e771ba 100644 --- a/src/EvoSC.Modules/EvoSC.Modules.csproj +++ b/src/EvoSC.Modules/EvoSC.Modules.csproj @@ -1,14 +1,14 @@ - net7.0 + net8.0 enable enable - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC.Modules/EvoScModule.cs b/src/EvoSC.Modules/EvoScModule.cs index f35fbbb1b..eb0375fcc 100644 --- a/src/EvoSC.Modules/EvoScModule.cs +++ b/src/EvoSC.Modules/EvoScModule.cs @@ -5,6 +5,4 @@ namespace EvoSC.Modules; /// /// Base class for all EvoSC modules. /// -public abstract class EvoScModule : IEvoScModule -{ -} +public abstract class EvoScModule : IEvoScModule; diff --git a/src/EvoSC.Modules/Exceptions/EvoScNotModuleException.cs b/src/EvoSC.Modules/Exceptions/EvoScNotModuleException.cs index ef9f8d13e..08d9c4a6f 100644 --- a/src/EvoSC.Modules/Exceptions/EvoScNotModuleException.cs +++ b/src/EvoSC.Modules/Exceptions/EvoScNotModuleException.cs @@ -3,7 +3,4 @@ /// /// Thrown when a module does not exist during retrieval. /// -public class EvoScNotModuleException : EvoScModuleException -{ - -} +public class EvoScNotModuleException : EvoScModuleException; diff --git a/src/EvoSC.Modules/Exceptions/MissingModulePropertyException.cs b/src/EvoSC.Modules/Exceptions/MissingModulePropertyException.cs index ed5c7b77d..8c51e710f 100644 --- a/src/EvoSC.Modules/Exceptions/MissingModulePropertyException.cs +++ b/src/EvoSC.Modules/Exceptions/MissingModulePropertyException.cs @@ -1,15 +1,10 @@ namespace EvoSC.Modules.Exceptions; -public class MissingModulePropertyException : EvoScModuleException +public class MissingModulePropertyException(string name) : EvoScModuleException( + $"The module is missing meta information. The {name} property was not found.") { /// /// The property name that was invalid. /// - public string PropertyName { get; } - - public MissingModulePropertyException(string name) : base( - $"The module is missing meta information. The {name} property was not found.") - { - PropertyName = name; - } + public string PropertyName { get; } = name; } diff --git a/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyCycleException.cs b/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyCycleException.cs index 5c47631a9..e9de74ea0 100644 --- a/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyCycleException.cs +++ b/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyCycleException.cs @@ -2,15 +2,8 @@ using DependencyGraph = Dictionary>; -public class DependencyCycleException : DependencyException +public class DependencyCycleException(DependencyGraph remainingGraph) : DependencyException { - private readonly DependencyGraph _remainingGraph; - - public DependencyCycleException(DependencyGraph remainingGraph) - { - _remainingGraph = remainingGraph; - } - private bool FindCycle(string name, List visited) { if (visited.Contains(name)) @@ -21,7 +14,7 @@ private bool FindCycle(string name, List visited) visited.Add(name); - foreach (var dep in _remainingGraph[name]) + foreach (var dep in remainingGraph[name]) { if (FindCycle(dep, visited)) { @@ -41,11 +34,11 @@ private bool FindCycle(string name, List visited) /// public IEnumerable GetCycle() { - foreach (var name in _remainingGraph.Keys) + foreach (var name in remainingGraph.Keys) { var cycle = new List(); - if (FindCycle(_remainingGraph.FirstOrDefault().Key, cycle)) + if (FindCycle(remainingGraph.FirstOrDefault().Key, cycle)) { cycle.Add(name); return cycle; diff --git a/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyNotFoundException.cs b/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyNotFoundException.cs index 70eaa9c31..04975e5fb 100644 --- a/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyNotFoundException.cs +++ b/src/EvoSC.Modules/Exceptions/ModuleDependency/DependencyNotFoundException.cs @@ -1,20 +1,15 @@ namespace EvoSC.Modules.Exceptions.ModuleDependency; -public class DependencyNotFoundException : DependencyException +public class DependencyNotFoundException(string dependent, string dependency) : DependencyException( + $"The module '{dependent}' depend on '{dependency}' which doesn't exist.") { /// /// The module that has a the non-existent dependency. /// - public string Dependent { get; } + public string Dependent { get; } = dependent; + /// /// The dependency that was not found for the dependent. /// - public string Dependency { get; } - - public DependencyNotFoundException(string dependent, string dependency) : base( - $"The module '{dependent}' depend on '{dependency}' which doesn't exist.") - { - Dependent = dependent; - Dependency = dependency; - } + public string Dependency { get; } = dependency; } diff --git a/src/EvoSC.Modules/Models/ModuleFile.cs b/src/EvoSC.Modules/Models/ModuleFile.cs index a0cd71646..959202554 100644 --- a/src/EvoSC.Modules/Models/ModuleFile.cs +++ b/src/EvoSC.Modules/Models/ModuleFile.cs @@ -2,15 +2,10 @@ namespace EvoSC.Modules.Models; -public class ModuleFile : IModuleFile +public class ModuleFile(FileInfo file) : IModuleFile { - public FileInfo File { get; init; } + public FileInfo File { get; init; } = file; - public ModuleFile(FileInfo file) - { - File = file; - } - public bool VerifySignature() { // todo: github #35 https://github.com/EvoTM/EvoSC-sharp/issues/35 diff --git a/src/EvoSC.Testing/Controllers/ControllerTestBase.cs b/src/EvoSC.Testing/Controllers/ControllerTestBase.cs index a15f70b68..a9af7878f 100644 --- a/src/EvoSC.Testing/Controllers/ControllerTestBase.cs +++ b/src/EvoSC.Testing/Controllers/ControllerTestBase.cs @@ -4,10 +4,4 @@ namespace EvoSC.Testing.Controllers; public class ControllerTestBase : ControllerContextMock where TController : class, IController - where TContext : class, IControllerContext -{ - public ControllerTestBase() - { - - } -} + where TContext : class, IControllerContext; diff --git a/src/EvoSC.Testing/Controllers/EventControllerTestBase.cs b/src/EvoSC.Testing/Controllers/EventControllerTestBase.cs index 0b37e1503..9e90b57dc 100644 --- a/src/EvoSC.Testing/Controllers/EventControllerTestBase.cs +++ b/src/EvoSC.Testing/Controllers/EventControllerTestBase.cs @@ -3,6 +3,4 @@ namespace EvoSC.Testing.Controllers; public class EventControllerTestBase : ControllerMock - where TController : class, IController -{ -} + where TController : class, IController; diff --git a/src/EvoSC.Testing/Database/TestDbConnectionFactory.cs b/src/EvoSC.Testing/Database/TestDbConnectionFactory.cs index a985dc5a0..6ad1410a9 100644 --- a/src/EvoSC.Testing/Database/TestDbConnectionFactory.cs +++ b/src/EvoSC.Testing/Database/TestDbConnectionFactory.cs @@ -26,9 +26,8 @@ public DataContext GetConnection() { if (_dbConnection == null) { - var dbOptions = new LinqToDBConnectionOptionsBuilder() - .UseSQLite(ConnectionString) - .Build(); + var dbOptions = new DataOptions() + .UseSQLite(ConnectionString); _dbConnection = new DataContext(dbOptions); } diff --git a/src/EvoSC.Testing/EvoSC.Testing.csproj b/src/EvoSC.Testing/EvoSC.Testing.csproj index 4f28d4294..5adcb0a29 100644 --- a/src/EvoSC.Testing/EvoSC.Testing.csproj +++ b/src/EvoSC.Testing/EvoSC.Testing.csproj @@ -1,14 +1,14 @@ - net7.0 + net8.0 enable enable - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/EvoSC/CliCommands/ConfigGeneratorCommand.cs b/src/EvoSC/CliCommands/ConfigGeneratorCommand.cs index 56cfb0379..ec0152805 100644 --- a/src/EvoSC/CliCommands/ConfigGeneratorCommand.cs +++ b/src/EvoSC/CliCommands/ConfigGeneratorCommand.cs @@ -15,15 +15,8 @@ namespace EvoSC.CliCommands; [CliCommand(Name = "genconfig", Description = "Generate a config file in provided formats.")] [RequiredFeatures(AppFeature.Modules)] -public class ConfigGeneratorCommand +public class ConfigGeneratorCommand(IModuleManager modules) { - private readonly IModuleManager _modules; - - public ConfigGeneratorCommand(IModuleManager modules) - { - _modules = modules; - } - public async Task ExecuteAsync( [Alias(Name = "-t"), Description("The output format, supported types: ENV")] string formatType, @@ -80,9 +73,9 @@ private void GenerateModuleConfig(ConfigGenFormatType formatType, StringBuilder return (name.Name, version.Version.ToString(), t.Assembly); })); - var modules = _modules.LoadedModules; + var loadedModules = modules.LoadedModules; - foreach (var module in modules) + foreach (var module in loadedModules) { foreach (var moduleAssembly in module.Assemblies) { diff --git a/src/EvoSC/CliCommands/RunCommand.cs b/src/EvoSC/CliCommands/RunCommand.cs index b855e93ed..9395ae3f6 100644 --- a/src/EvoSC/CliCommands/RunCommand.cs +++ b/src/EvoSC/CliCommands/RunCommand.cs @@ -7,18 +7,11 @@ namespace EvoSC.CliCommands; [CliCommand(Name = "run", Description = "Start the server controller.")] [RequiredFeatures(AppFeature.Config)] -public class RunCommand +public class RunCommand(IEvoScBaseConfig config) { - private readonly IEvoScBaseConfig _config; - - public RunCommand(IEvoScBaseConfig config) - { - _config = config; - } - public async Task ExecuteAsync([Alias(Name = "-s")]int something) { - var app = new Application(_config); + var app = new Application(config); await app.RunAsync(); app.Dispose(); } diff --git a/src/EvoSC/EvoSC.csproj b/src/EvoSC/EvoSC.csproj index 8bb625f65..0318cfab0 100644 --- a/src/EvoSC/EvoSC.csproj +++ b/src/EvoSC/EvoSC.csproj @@ -2,17 +2,17 @@ Exe - net7.0 + net8.0 enable enable appicon.ico - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -57,13 +57,7 @@ - - - - - - - + diff --git a/src/Modules/ASayModule/ASayModule.csproj b/src/Modules/ASayModule/ASayModule.csproj index ed0791028..64dd6b0d4 100644 --- a/src/Modules/ASayModule/ASayModule.csproj +++ b/src/Modules/ASayModule/ASayModule.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 enable enable EvoSC.Modules.Official.ASayModule diff --git a/src/Modules/ASayModule/Controllers/ASayController.cs b/src/Modules/ASayModule/Controllers/ASayController.cs index 0d0e1c40c..00288abc9 100644 --- a/src/Modules/ASayModule/Controllers/ASayController.cs +++ b/src/Modules/ASayModule/Controllers/ASayController.cs @@ -7,32 +7,25 @@ namespace EvoSC.Modules.Official.ASayModule.Controllers; [Controller] -public class ASayController : EvoScController +public class ASayController(IASayService asayService) : EvoScController { - private readonly IASayService _asayService; - - public ASayController(IASayService asayService) - { - _asayService = asayService; - } - [ChatCommand("asay", "Shows a message to all connected players as manialink.", ASayPermissions.UseASay, true)] public async Task ShowAnnounceMessageToPlayersAsync(string? text) { if (!string.IsNullOrEmpty(text)) { - await _asayService.ShowAnnouncementAsync(text); + await asayService.ShowAnnouncementAsync(text); } else { - await _asayService.HideAnnouncementAsync(); + await asayService.HideAnnouncementAsync(); } } [ChatCommand("clearasay", "Hides the announcement message from all connected players.", ASayPermissions.UseASay, true)] public async Task ClearAnnouncementMessageForPlayersAsync() { - await _asayService.HideAnnouncementAsync(); + await asayService.HideAnnouncementAsync(); } } diff --git a/src/Modules/ASayModule/Services/ASayService.cs b/src/Modules/ASayModule/Services/ASayService.cs index 48efdead5..aaaaa3db0 100644 --- a/src/Modules/ASayModule/Services/ASayService.cs +++ b/src/Modules/ASayModule/Services/ASayService.cs @@ -8,21 +8,13 @@ namespace EvoSC.Modules.Official.ASayModule.Services; [Service(LifeStyle = ServiceLifeStyle.Scoped)] -public class ASayService : IASayService +public class ASayService(IManialinkManager manialinkManager, IContextService context) + : IASayService { - private readonly IManialinkManager _manialinkManager; - private readonly IContextService _contextService; - - public ASayService(IManialinkManager manialinkManager, IContextService context) - { - _manialinkManager = manialinkManager; - _contextService = context; - } - public async Task ShowAnnouncementAsync(string text) { - await _manialinkManager.SendPersistentManialinkAsync("ASayModule.Announcement", new {text}); - _contextService.Audit().Success() + await manialinkManager.SendPersistentManialinkAsync("ASayModule.Announcement", new {text}); + context.Audit().Success() .WithEventName(AuditEvents.ShowAnnouncement) .HavingProperties(new {Text = text}) .Comment("Announcement was shown."); @@ -30,8 +22,8 @@ public async Task ShowAnnouncementAsync(string text) public async Task HideAnnouncementAsync() { - await _manialinkManager.HideManialinkAsync("ASayModule.Announcement"); - _contextService.Audit().Success() + await manialinkManager.HideManialinkAsync("ASayModule.Announcement"); + context.Audit().Success() .WithEventName(AuditEvents.ClearAnnouncement) .Comment("Announcement was cleared."); } diff --git a/src/Modules/ASayModule/Themes/DefaultASayTheme.cs b/src/Modules/ASayModule/Themes/DefaultASayTheme.cs index db2709c68..7d771d8ec 100644 --- a/src/Modules/ASayModule/Themes/DefaultASayTheme.cs +++ b/src/Modules/ASayModule/Themes/DefaultASayTheme.cs @@ -5,15 +5,10 @@ namespace EvoSC.Modules.Official.ASayModule.Themes; [Theme(Name = "ASay", Description = "Default theme for ASay")] -public class DefaultASayTheme : Theme +public class DefaultASayTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - - public DefaultASayTheme(IThemeManager theme) - { - _theme = theme.Theme; - } - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("ASayModule.Announcement.Default.TextSize").To(3); diff --git a/src/Modules/CurrentMapModule/Controllers/CurrentMapController.cs b/src/Modules/CurrentMapModule/Controllers/CurrentMapController.cs index 91864a25c..7c6b5dd13 100644 --- a/src/Modules/CurrentMapModule/Controllers/CurrentMapController.cs +++ b/src/Modules/CurrentMapModule/Controllers/CurrentMapController.cs @@ -10,30 +10,23 @@ namespace EvoSC.Modules.Official.CurrentMapModule.Controllers; [Controller] -public class CurrentMapController : EvoScController +public class CurrentMapController(ICurrentMapService service) : EvoScController { - private readonly ICurrentMapService _service; - - public CurrentMapController(ICurrentMapService service) - { - _service = service; - } - [Subscribe(GbxRemoteEvent.BeginMatch)] public Task OnBeginMatchAsync(object sender, EventArgs args) { - return _service.ShowWidgetAsync(); + return service.ShowWidgetAsync(); } [Subscribe(GbxRemoteEvent.BeginMap)] public Task OnBeginMapAsync(object sender, MapGbxEventArgs args) { - return _service.ShowWidgetAsync(args); + return service.ShowWidgetAsync(args); } [Subscribe(ModeScriptEvent.PodiumStart)] public Task OnPodiumStartAsync(object sender, PodiumEventArgs args) { - return _service.HideWidgetAsync(); + return service.HideWidgetAsync(); } } diff --git a/src/Modules/CurrentMapModule/CurrentMapModule.cs b/src/Modules/CurrentMapModule/CurrentMapModule.cs index 09984d181..9185a6655 100644 --- a/src/Modules/CurrentMapModule/CurrentMapModule.cs +++ b/src/Modules/CurrentMapModule/CurrentMapModule.cs @@ -5,15 +5,8 @@ namespace EvoSC.Modules.Official.CurrentMapModule; [Module(IsInternal = true)] -public class CurrentMapModule : EvoScModule, IToggleable +public class CurrentMapModule(ICurrentMapService service) : EvoScModule, IToggleable { - private readonly ICurrentMapService _service; - - public CurrentMapModule(ICurrentMapService service) - { - _service = service; - } - - public Task EnableAsync() => _service.ShowWidgetAsync(); - public Task DisableAsync() => _service.HideWidgetAsync(); + public Task EnableAsync() => service.ShowWidgetAsync(); + public Task DisableAsync() => service.HideWidgetAsync(); } diff --git a/src/Modules/CurrentMapModule/CurrentMapModule.csproj b/src/Modules/CurrentMapModule/CurrentMapModule.csproj index 775663791..12e786d01 100644 --- a/src/Modules/CurrentMapModule/CurrentMapModule.csproj +++ b/src/Modules/CurrentMapModule/CurrentMapModule.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable EvoSC.Modules.Official.CurrentMapModule @@ -16,7 +16,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Modules/CurrentMapModule/Services/CurrentMapService.cs b/src/Modules/CurrentMapModule/Services/CurrentMapService.cs index 58f1439f7..b8472aaf8 100644 --- a/src/Modules/CurrentMapModule/Services/CurrentMapService.cs +++ b/src/Modules/CurrentMapModule/Services/CurrentMapService.cs @@ -12,28 +12,14 @@ namespace EvoSC.Modules.Official.CurrentMapModule.Services; [Service(LifeStyle = ServiceLifeStyle.Transient)] -public class CurrentMapService : ICurrentMapService -{ - private readonly ILogger _logger; - private readonly IManialinkManager _manialinkManager; - private readonly IMapRepository _mapRepository; - private readonly IServerClient _client; - private readonly IWorldRecordService _worldRecordService; - - public CurrentMapService(IManialinkManager manialinkManager, ILogger logger, +public class CurrentMapService(IManialinkManager manialinkManager, ILogger logger, IMapRepository mapRepository, IServerClient client, IWorldRecordService worldRecordService) - { - _logger = logger; - _manialinkManager = manialinkManager; - _mapRepository = mapRepository; - _client = client; - _worldRecordService = worldRecordService; - } - + : ICurrentMapService +{ [ExcludeFromCodeCoverage(Justification = "GBXRemoteClient cannot be mocked.")] public async Task ShowWidgetAsync() { - var map = await _client.Remote.GetCurrentMapInfoAsync(); + var map = await client.Remote.GetCurrentMapInfoAsync(); await ShowManialinkAsync(map.UId); } @@ -44,31 +30,31 @@ public async Task ShowWidgetAsync(MapGbxEventArgs args) public async Task HideWidgetAsync() { - await _manialinkManager.HideManialinkAsync("CurrentMapModule.CurrentMapWidget"); - _logger.LogDebug("Hiding current map widget"); + await manialinkManager.HideManialinkAsync("CurrentMapModule.CurrentMapWidget"); + logger.LogDebug("Hiding current map widget"); } private async Task ShowManialinkAsync(string mapUId) { - var dbMap = await _mapRepository.GetMapByUidAsync(mapUId); + var dbMap = await mapRepository.GetMapByUidAsync(mapUId); var author = ""; - var worldRecord = await _worldRecordService.GetRecordAsync(); + var worldRecord = await worldRecordService.GetRecordAsync(); if (dbMap.Author.NickName == dbMap.Author.AccountId) { - var serverMap = await _client.Remote.GetCurrentMapInfoAsync(); + var serverMap = await client.Remote.GetCurrentMapInfoAsync(); author = serverMap.AuthorNickname.Length > 0 ? serverMap.AuthorNickname : serverMap.Author; } else { author = dbMap.Author?.NickName; } - await _manialinkManager.SendPersistentManialinkAsync("CurrentMapModule.CurrentMapWidget", + await manialinkManager.SendPersistentManialinkAsync("CurrentMapModule.CurrentMapWidget", new { map = dbMap, mapauthor = author, record = worldRecord }); - _logger.LogDebug("Showing current map widget"); + logger.LogDebug("Showing current map widget"); } } diff --git a/src/Modules/CurrentMapModule/Themes/DefaultCurrentMapTheme.cs b/src/Modules/CurrentMapModule/Themes/DefaultCurrentMapTheme.cs index 2909dc515..07e1ce4e1 100644 --- a/src/Modules/CurrentMapModule/Themes/DefaultCurrentMapTheme.cs +++ b/src/Modules/CurrentMapModule/Themes/DefaultCurrentMapTheme.cs @@ -6,15 +6,10 @@ namespace EvoSC.Modules.Official.CurrentMapModule.Themes; [Theme(Name = "Current Map", Description = "Default theme for the Current Map Module.")] -public class DefaultCurrentMapTheme : Theme +public class DefaultCurrentMapTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; - - public DefaultCurrentMapTheme(IThemeManager theme) - { - _theme = theme.Theme; - } - + private readonly dynamic _theme = theme.Theme; + public override Task ConfigureAsync() { Set("CurrentMapModule.CurrentMapWidget.Default.BgHeaderGrad1").To(_theme.UI_BgPrimary); diff --git a/src/Modules/ExampleModule/ExampleModule.csproj b/src/Modules/ExampleModule/ExampleModule.csproj index bd1bfe308..2f2ce1186 100644 --- a/src/Modules/ExampleModule/ExampleModule.csproj +++ b/src/Modules/ExampleModule/ExampleModule.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable EvoSC.Modules.Official.ExampleModule @@ -21,7 +21,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Modules/FastestCpModule/Controllers/FastestCpController.cs b/src/Modules/FastestCpModule/Controllers/FastestCpController.cs index cc1afe412..0b1124d6a 100644 --- a/src/Modules/FastestCpModule/Controllers/FastestCpController.cs +++ b/src/Modules/FastestCpModule/Controllers/FastestCpController.cs @@ -10,24 +10,17 @@ namespace EvoSC.Modules.Official.FastestCpModule.Controllers; [Controller] -public class FastestCpController : EvoScController +public class FastestCpController(IFastestCpService fastestCpService) : EvoScController { - private readonly IFastestCpService _fastestCpService; - - public FastestCpController(IFastestCpService fastestCpService) - { - _fastestCpService = fastestCpService; - } - [Subscribe(ModeScriptEvent.WayPoint)] public Task RegisterCpTimeAsync(object sender, WayPointEventArgs args) { - return _fastestCpService.RegisterCpTimeAsync(args); + return fastestCpService.RegisterCpTimeAsync(args); } [Subscribe(GbxRemoteEvent.EndMap)] public Task ResetCpTimesAsync(object sender, MapGbxEventArgs args) { - return _fastestCpService.ResetCpTimesAsync(); + return fastestCpService.ResetCpTimesAsync(); } } diff --git a/src/Modules/FastestCpModule/FastestCpModule.csproj b/src/Modules/FastestCpModule/FastestCpModule.csproj index c7681c4b7..74527c43f 100644 --- a/src/Modules/FastestCpModule/FastestCpModule.csproj +++ b/src/Modules/FastestCpModule/FastestCpModule.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable EvoSC.Modules.Official.FastestCpModule @@ -19,7 +19,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Modules/FastestCpModule/Services/FastestCpService.cs b/src/Modules/FastestCpModule/Services/FastestCpService.cs index 6e43f8499..3683c8975 100644 --- a/src/Modules/FastestCpModule/Services/FastestCpService.cs +++ b/src/Modules/FastestCpModule/Services/FastestCpService.cs @@ -10,24 +10,11 @@ namespace EvoSC.Modules.Official.FastestCpModule.Services; [Service(LifeStyle = ServiceLifeStyle.Singleton)] -public class FastestCpService : IFastestCpService -{ - private readonly ILogger _logger; - private readonly ILoggerFactory _loggerFactory; - private readonly IManialinkManager _manialinkManager; - private readonly IPlayerManagerService _playerManagerService; - - private FastestCpStore _fastestCpStore; - - public FastestCpService(IPlayerManagerService playerManagerService, IManialinkManager manialinkManager, +public class FastestCpService(IPlayerManagerService playerManagerService, IManialinkManager manialinkManager, ILoggerFactory loggerFactory, ILogger logger) - { - _playerManagerService = playerManagerService; - _logger = logger; - _loggerFactory = loggerFactory; - _manialinkManager = manialinkManager; - _fastestCpStore = GetNewFastestCpStore(); - } + : IFastestCpService +{ + private FastestCpStore _fastestCpStore = new(loggerFactory.CreateLogger()); public async Task RegisterCpTimeAsync(WayPointEventArgs args) { @@ -40,16 +27,16 @@ public async Task RegisterCpTimeAsync(WayPointEventArgs args) public async Task ResetCpTimesAsync() { - _fastestCpStore = GetNewFastestCpStore(); - await _manialinkManager.HideManialinkAsync("FastestCpModule.FastestCp"); - _logger.LogDebug("Hiding fastest cp manialink for all users"); + _fastestCpStore = new(loggerFactory.CreateLogger()); + await manialinkManager.HideManialinkAsync("FastestCpModule.FastestCp"); + logger.LogDebug("Hiding fastest cp manialink for all users"); } private async Task ShowWidgetAsync() { - await _manialinkManager.SendPersistentManialinkAsync("FastestCpModule.FastestCp", + await manialinkManager.SendPersistentManialinkAsync("FastestCpModule.FastestCp", new { times = await GetCurrentBestCpTimesAsync() }); - _logger.LogDebug("Updating fastest cp manialink for all users"); + logger.LogDebug("Updating fastest cp manialink for all users"); } private async Task GetCurrentBestCpTimesAsync() @@ -63,7 +50,7 @@ await Task.WhenAll( .Distinct() .Select(async id => { - var player = await _playerManagerService.GetOrCreatePlayerAsync(id); + var player = await playerManagerService.GetOrCreatePlayerAsync(id); playerNameCache[id] = player.StrippedNickName; })); @@ -71,9 +58,4 @@ await Task.WhenAll( new PlayerCpTime(playerNameCache[time!.AccountId], index, TimeSpan.FromMilliseconds(time.RaceTime))) .TakeLast(18).ToArray(); } - - private FastestCpStore GetNewFastestCpStore() - { - return new FastestCpStore(_loggerFactory.CreateLogger()); - } } diff --git a/src/Modules/FastestCpModule/Themes/DefaultFastestCPTheme.cs b/src/Modules/FastestCpModule/Themes/DefaultFastestCPTheme.cs index 50bbc4dae..f332ddb29 100644 --- a/src/Modules/FastestCpModule/Themes/DefaultFastestCPTheme.cs +++ b/src/Modules/FastestCpModule/Themes/DefaultFastestCPTheme.cs @@ -5,12 +5,10 @@ namespace EvoSC.Modules.Official.FastestCpModule.Themes; [Theme(Name = "Fastest CP", Description = "Default them for the Fastest CP module.")] -public class DefaultFastestCPTheme : Theme +public class DefaultFastestCPTheme(IThemeManager theme) : Theme { - private readonly dynamic _theme; + private readonly dynamic _theme = theme.Theme; - public DefaultFastestCPTheme(IThemeManager theme) => _theme = theme.Theme; - public override Task ConfigureAsync() { Set("FastestCpModule.FastestCP.Default.Text").To(_theme.UI_TextPrimary); diff --git a/src/Modules/LiveRankingModule/Controllers/LiveRankingEventController.cs b/src/Modules/LiveRankingModule/Controllers/LiveRankingEventController.cs index 0429d05b1..5f8e1c9e4 100644 --- a/src/Modules/LiveRankingModule/Controllers/LiveRankingEventController.cs +++ b/src/Modules/LiveRankingModule/Controllers/LiveRankingEventController.cs @@ -10,36 +10,32 @@ namespace EvoSC.Modules.Official.LiveRankingModule.Controllers; [Controller] -public class LiveRankingEventController : EvoScController +public class LiveRankingEventController(ILiveRankingService service) : EvoScController { - private readonly ILiveRankingService _service; - - public LiveRankingEventController(ILiveRankingService service) => _service = service; - [Subscribe(ModeScriptEvent.WayPoint)] - public Task OnPlayerWaypointAsync(object sender, WayPointEventArgs args) => _service.OnPlayerWaypointAsync(args); + public Task OnPlayerWaypointAsync(object sender, WayPointEventArgs args) => service.OnPlayerWaypointAsync(args); [Subscribe(ModeScriptEvent.GiveUp)] - public Task OnPlayerGiveUpAsync(object sender, PlayerUpdateEventArgs args) => _service.OnPlayerGiveupAsync(args); + public Task OnPlayerGiveUpAsync(object sender, PlayerUpdateEventArgs args) => service.OnPlayerGiveupAsync(args); [Subscribe(ModeScriptEvent.StartRoundStart)] - public Task OnStartRoundAsync(object sender, RoundEventArgs args) => _service.OnStartRoundAsync(args); + public Task OnStartRoundAsync(object sender, RoundEventArgs args) => service.OnStartRoundAsync(args); [Subscribe(ModeScriptEvent.EndMapStart)] - public Task OnEndMapAsync(object sender, MapEventArgs args) => _service.OnEndMapAsync(args); + public Task OnEndMapAsync(object sender, MapEventArgs args) => service.OnEndMapAsync(args); [Subscribe(ModeScriptEvent.PodiumStart)] - public Task OnPodiumStartAsync(object sender, PodiumEventArgs args) => _service.OnPodiumStartAsync(args); + public Task OnPodiumStartAsync(object sender, PodiumEventArgs args) => service.OnPodiumStartAsync(args); [Subscribe(ModeScriptEvent.EndRoundStart)] - public Task OnEndRoundAsync(object sender, RoundEventArgs args) => _service.OnEndRoundAsync(args); + public Task OnEndRoundAsync(object sender, RoundEventArgs args) => service.OnEndRoundAsync(args); [Subscribe(GbxRemoteEvent.BeginMatch)] - public Task OnBeginMatchAsync(object sender, EventArgs args) => _service.OnBeginMatchAsync(); + public Task OnBeginMatchAsync(object sender, EventArgs args) => service.OnBeginMatchAsync(); [Subscribe(GbxRemoteEvent.EndMatch)] - public Task OnEndMatchAsync(object sender, EndMatchGbxEventArgs args) => _service.OnEndMatchAsync(args); + public Task OnEndMatchAsync(object sender, EndMatchGbxEventArgs args) => service.OnEndMatchAsync(args); [Subscribe(GbxRemoteEvent.PlayerConnect)] - public Task OnPlayerConnectAsync(object sender, PlayerConnectGbxEventArgs args) => _service.SendManialinkAsync(); + public Task OnPlayerConnectAsync(object sender, PlayerConnectGbxEventArgs args) => service.SendManialinkAsync(); } diff --git a/src/Modules/LiveRankingModule/LiveRankingModule.cs b/src/Modules/LiveRankingModule/LiveRankingModule.cs index 32ee981a1..3acf50cfd 100644 --- a/src/Modules/LiveRankingModule/LiveRankingModule.cs +++ b/src/Modules/LiveRankingModule/LiveRankingModule.cs @@ -5,17 +5,10 @@ namespace EvoSC.Modules.Official.LiveRankingModule; [Module(IsInternal = true)] -public class LiveRankingModule : EvoScModule, IToggleable +public class LiveRankingModule(ILiveRankingService service) : EvoScModule, IToggleable { - private readonly ILiveRankingService _service; - - public LiveRankingModule(ILiveRankingService service) - { - _service = service; - } - - public Task EnableAsync() => _service.OnEnableAsync(); + public Task EnableAsync() => service.OnEnableAsync(); // if no cleaning for the classes needed to be done, return here a completed task, otherwise clean the classes, and then complete the task. - public Task DisableAsync() => _service.OnDisableAsync(); + public Task DisableAsync() => service.OnDisableAsync(); } diff --git a/src/Modules/LiveRankingModule/LiveRankingModule.csproj b/src/Modules/LiveRankingModule/LiveRankingModule.csproj index 89205b342..086f1bd59 100644 --- a/src/Modules/LiveRankingModule/LiveRankingModule.csproj +++ b/src/Modules/LiveRankingModule/LiveRankingModule.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 enable enable EvoSC.Modules.Official.LiveRankingModule diff --git a/src/Modules/LiveRankingModule/Models/LiveRankingPosition.cs b/src/Modules/LiveRankingModule/Models/LiveRankingPosition.cs index 79581d9bf..98d0a8764 100644 --- a/src/Modules/LiveRankingModule/Models/LiveRankingPosition.cs +++ b/src/Modules/LiveRankingModule/Models/LiveRankingPosition.cs @@ -3,9 +3,9 @@ /// /// The live ranking position of a player. /// -/// Account Id of the player. -/// The checkpoint time of the player. -/// The checkpoint index that was driven through. -/// Whether the player has given up or not. -/// Whether the player has finished. -public record LiveRankingPosition(string accountId, int cpTime, int cpIndex, bool isDNF, bool isFinish); +/// Account Id of the player. +/// The checkpoint time of the player. +/// The checkpoint index that was driven through. +/// Whether the player has given up or not. +/// Whether the player has finished. +public record LiveRankingPosition(string AccountId, int CpTime, int CpIndex, bool IsDnf, bool IsFinish); diff --git a/src/Modules/LiveRankingModule/Models/LiveRankingStore.cs b/src/Modules/LiveRankingModule/Models/LiveRankingStore.cs index 9e4fbe55c..1e2ac0c8d 100644 --- a/src/Modules/LiveRankingModule/Models/LiveRankingStore.cs +++ b/src/Modules/LiveRankingModule/Models/LiveRankingStore.cs @@ -4,21 +4,12 @@ namespace EvoSC.Modules.Official.LiveRankingModule.Models; -internal class LiveRankingStore +internal class LiveRankingStore(IPlayerManagerService playerManager) { private ConcurrentDictionary _curLiveRanking { get; set; } = new(); private ConcurrentDictionary _prevLiveRanking { get; set; } = new(); - private readonly ILogger _logger; - private readonly IPlayerManagerService _playerManager; - - private MatchInfo _matchInfo = new(); - internal LiveRankingStore(ILogger logger, IPlayerManagerService playerManager) - { - _logger = logger; - _playerManager = playerManager; - _logger.LogDebug("Instantiated LiveRankingStore"); - } + private MatchInfo _matchInfo = new(); internal Task ResetLiveRankingsAsync() { @@ -40,7 +31,7 @@ internal void RegisterPlayerGiveUp(string accountId) _prevLiveRanking = new ConcurrentDictionary(_curLiveRanking); _curLiveRanking.AddOrUpdate(accountId, _ => new LiveRankingPosition(accountId, 0, 0, true, false), - (_, arg) => new LiveRankingPosition(accountId, arg.cpTime, arg.cpIndex, true, false)); + (_, arg) => new LiveRankingPosition(accountId, arg.CpTime, arg.CpIndex, true, false)); } /// @@ -63,14 +54,14 @@ internal async Task> GetFullLiveRankingAsync() List expandedLiveRanking = new(); foreach (var rank in _curLiveRanking) { - var player = await _playerManager.GetOnlinePlayerAsync(rank.Value.accountId); + var player = await playerManager.GetOnlinePlayerAsync(rank.Value.AccountId); expandedLiveRanking.Add(new ExpandedLiveRankingPosition { Player = player, - CheckpointTime = rank.Value.cpTime, - CheckpointIndex = rank.Value.cpIndex, - IsDnf = rank.Value.isDNF, - IsFinish = rank.Value.isFinish + CheckpointTime = rank.Value.CpTime, + CheckpointIndex = rank.Value.CpIndex, + IsDnf = rank.Value.IsDnf, + IsFinish = rank.Value.IsFinish }); } @@ -84,14 +75,14 @@ internal async Task> GetFullPreviousLiveRankin List expandedLiveRanking = new(); foreach (var rank in _prevLiveRanking) { - var player = await _playerManager.GetOnlinePlayerAsync(rank.Value.accountId); + var player = await playerManager.GetOnlinePlayerAsync(rank.Value.AccountId); expandedLiveRanking.Add(new ExpandedLiveRankingPosition { Player = player, - CheckpointTime = rank.Value.cpTime, - CheckpointIndex = rank.Value.cpIndex, - IsDnf = rank.Value.isDNF, - IsFinish = rank.Value.isFinish + CheckpointTime = rank.Value.CpTime, + CheckpointIndex = rank.Value.CpIndex, + IsDnf = rank.Value.IsDnf, + IsFinish = rank.Value.IsFinish }); } diff --git a/src/Modules/LiveRankingModule/Models/LiveRankingWidgetPosition.cs b/src/Modules/LiveRankingModule/Models/LiveRankingWidgetPosition.cs index 14b2c3b89..b815f8b02 100644 --- a/src/Modules/LiveRankingModule/Models/LiveRankingWidgetPosition.cs +++ b/src/Modules/LiveRankingModule/Models/LiveRankingWidgetPosition.cs @@ -2,4 +2,4 @@ namespace EvoSC.Modules.Official.LiveRankingModule.Models; -public record LiveRankingWidgetPosition(int position, IPlayer player, string login, string time, int cpIndex, bool isFinish); +public record LiveRankingWidgetPosition(int Position, IPlayer Player, string Login, string Time, int CpIndex, bool IsFinish); diff --git a/src/Modules/LiveRankingModule/Services/LiveRankingService.cs b/src/Modules/LiveRankingModule/Services/LiveRankingService.cs index 87eca8591..a58235404 100644 --- a/src/Modules/LiveRankingModule/Services/LiveRankingService.cs +++ b/src/Modules/LiveRankingModule/Services/LiveRankingService.cs @@ -14,29 +14,18 @@ namespace EvoSC.Modules.Official.LiveRankingModule.Services; [Service(LifeStyle = ServiceLifeStyle.Singleton)] -public class LiveRankingService : ILiveRankingService +public class LiveRankingService(ILogger logger, IManialinkManager manialinkManager, + IServerClient client, IPlayerManagerService playerManager) + : ILiveRankingService { private const int ShowRows = 4; - private readonly ILogger _logger; - private readonly IManialinkManager _manialinkManager; - private readonly LiveRankingStore _liveRankingStore; - private readonly IServerClient _client; + private readonly LiveRankingStore _liveRankingStore = new(playerManager); private bool _isRoundsMode; - public LiveRankingService(ILogger logger, ILoggerFactory loggerFactory, - IManialinkManager manialinkManager, IServerClient client, IPlayerManagerService playerManager) - { - _logger = logger; - _manialinkManager = manialinkManager; - _client = client; - _liveRankingStore = - new LiveRankingStore(loggerFactory.CreateLogger(), playerManager); - } - public async Task OnEnableAsync() { - _logger.LogTrace("LiveRankingModule enabled"); + logger.LogTrace("LiveRankingModule enabled"); await CheckIsRoundsModeAsync(); await HideNadeoScoreboardAsync(); if (_isRoundsMode) @@ -46,7 +35,7 @@ public async Task OnEnableAsync() _liveRankingStore.IncreaseRoundCounter(); _liveRankingStore.IncreaseTrackCounter(); - await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", + await manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", await GetWidgetDataAsync()); } @@ -55,8 +44,8 @@ await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRank public async Task OnDisableAsync() { - _logger.LogTrace("LiveRankingModule disabled"); - await _manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); + logger.LogTrace("LiveRankingModule disabled"); + await manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); await Task.CompletedTask; } @@ -65,12 +54,12 @@ public async Task OnPlayerWaypointAsync(WayPointEventArgs args) await CheckIsRoundsModeAsync(); if (_isRoundsMode) { - _logger.LogTrace("Player crossed a checkpoint: {ArgsAccountId} - RoundsMode: {IsRoundsMode}", + logger.LogTrace("Player crossed a checkpoint: {ArgsAccountId} - RoundsMode: {IsRoundsMode}", args.AccountId, _isRoundsMode); _liveRankingStore.RegisterTime(args.AccountId, args.CheckpointInRace, args.RaceTime, args.IsEndRace); - await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", + await manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", await GetWidgetDataAsync()); } } @@ -81,10 +70,7 @@ private async Task GetWidgetDataAsync() await CalculateDiffsAsync(currentRanking); var widgetCurrentRanking = GetLiveRankingForWidget(currentRanking); - return new - { - rankings = widgetCurrentRanking, - }; + return new { rankings = widgetCurrentRanking, }; } public Task CalculateDiffsAsync(List rankings) @@ -106,19 +92,19 @@ public async Task OnPlayerGiveupAsync(PlayerUpdateEventArgs args) await CheckIsRoundsModeAsync(); if (_isRoundsMode) { - _logger.LogTrace("Player gave up: {ArgsAccountId} - RoundsMode: {IsRoundsMode}", args.AccountId, + logger.LogTrace("Player gave up: {ArgsAccountId} - RoundsMode: {IsRoundsMode}", args.AccountId, _isRoundsMode); _liveRankingStore.RegisterPlayerGiveUp(args.AccountId); - await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", + await manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", await GetWidgetDataAsync()); } } public async Task OnBeginMapAsync(MapEventArgs args) { - _logger.LogTrace("Map starts: {MapName}, IsRounds: {IsRoundsMode}", args.Map.Name, _isRoundsMode); + logger.LogTrace("Map starts: {MapName}, IsRounds: {IsRoundsMode}", args.Map.Name, _isRoundsMode); await CheckIsRoundsModeAsync(); if (!_isRoundsMode) { @@ -136,12 +122,12 @@ public async Task OnBeginMapAsync(MapEventArgs args) public async Task OnEndMapAsync(MapEventArgs args) { await CheckIsRoundsModeAsync(); - _logger.LogTrace("Map ends: {MapName} - RoundsMode: {IsRoundsMode}", args.Map.Name, _isRoundsMode); + logger.LogTrace("Map ends: {MapName} - RoundsMode: {IsRoundsMode}", args.Map.Name, _isRoundsMode); if (_isRoundsMode) { await _liveRankingStore.ResetLiveRankingsAsync(); - await _manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); - await _manialinkManager.HideManialinkAsync("LiveRankingModule.MatchInfo"); + await manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); + await manialinkManager.HideManialinkAsync("LiveRankingModule.MatchInfo"); } } @@ -152,26 +138,28 @@ public async Task ResetLiveRankingAsync() public async Task OnStartRoundAsync(RoundEventArgs args) { - _logger.LogTrace("Round {ArgsCount} starts - RoundsMode: {IsRoundsMode}", args.Count, _isRoundsMode); + logger.LogTrace("Round {ArgsCount} starts - RoundsMode: {IsRoundsMode}", args.Count, _isRoundsMode); await _liveRankingStore.ResetLiveRankingsAsync(); - await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", await GetWidgetDataAsync()); + await manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", + await GetWidgetDataAsync()); } public async Task SendManialinkAsync() { - await _manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", await GetWidgetDataAsync()); + await manialinkManager.SendPersistentManialinkAsync("LiveRankingModule.LiveRanking", + await GetWidgetDataAsync()); } public async Task OnEndRoundAsync(RoundEventArgs args) { - _logger.LogTrace("Round {ArgsCount} ends - RoundsMode: {IsRoundsMode}", args.Count, _isRoundsMode); + logger.LogTrace("Round {ArgsCount} ends - RoundsMode: {IsRoundsMode}", args.Count, _isRoundsMode); var liveRanking = await _liveRankingStore.GetFullLiveRankingAsync(); var nbFinished = liveRanking.FindAll(x => x.IsFinish); if (nbFinished.Count > 0) { - _logger.LogTrace("MatchInfo Rounds before: {ArgsCount}", _liveRankingStore.GetMatchInfo().NumRound); + logger.LogTrace("MatchInfo Rounds before: {ArgsCount}", _liveRankingStore.GetMatchInfo().NumRound); _liveRankingStore.IncreaseRoundCounter(); - _logger.LogTrace("MatchInfo Rounds after: {ArgsCount}", _liveRankingStore.GetMatchInfo().NumRound); + logger.LogTrace("MatchInfo Rounds after: {ArgsCount}", _liveRankingStore.GetMatchInfo().NumRound); } } @@ -206,12 +194,12 @@ public async Task HideNadeoScoreboardAsync() }" }; - await _client.Remote.TriggerModeScriptEventArrayAsync("Common.UIModules.SetProperties", hudSettings.ToArray()); + await client.Remote.TriggerModeScriptEventArrayAsync("Common.UIModules.SetProperties", hudSettings.ToArray()); } private async Task HideManialinkAsync() { - await _manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); + await manialinkManager.HideManialinkAsync("LiveRankingModule.LiveRanking"); } private string FormatTime(int time, bool isDelta) diff --git a/src/Modules/LiveRankingModule/Templates/Components/PlayerScore.mt b/src/Modules/LiveRankingModule/Templates/Components/PlayerScore.mt index 3dc077ad5..3cf995b4d 100644 --- a/src/Modules/LiveRankingModule/Templates/Components/PlayerScore.mt +++ b/src/Modules/LiveRankingModule/Templates/Components/PlayerScore.mt @@ -11,8 +11,8 @@