1
0
mirror of https://github.com/RaidMax/IW4M-Admin.git synced 2025-06-07 21:58:06 -05:00

Refactor MuteManager constructor and clean up code (#329)

The MuteManager constructor within the Mute plugin has been refactored for better dependency injection. This change simplifies the class construction by directly initializing fields in the constructor parameters. Additionally, several minor code improvements have been made, including spelling corrections and replacing some conditional checks for readability. Other arrays or methods in the plugin are also revised for better maintainability and readability of the code.
This commit is contained in:
Amos 2024-06-30 03:50:00 +01:00 committed by GitHub
parent 40f912542b
commit ba633be034
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 89 additions and 71 deletions

View File

@ -20,8 +20,8 @@ public class MuteCommand : Command
Permission = EFClient.Permission.Moderator; Permission = EFClient.Permission.Moderator;
RequiresTarget = true; RequiresTarget = true;
SupportedGames = Plugin.SupportedGames; SupportedGames = Plugin.SupportedGames;
Arguments = new[] Arguments =
{ [
new CommandArgument new CommandArgument
{ {
Name = translationLookup["COMMANDS_ARGS_PLAYER"], Name = translationLookup["COMMANDS_ARGS_PLAYER"],
@ -32,7 +32,7 @@ public class MuteCommand : Command
Name = translationLookup["COMMANDS_ARGS_REASON"], Name = translationLookup["COMMANDS_ARGS_REASON"],
Required = true Required = true
} }
}; ];
} }
public override async Task ExecuteAsync(GameEvent gameEvent) public override async Task ExecuteAsync(GameEvent gameEvent)

View File

@ -21,14 +21,14 @@ public class MuteInfoCommand : Command
Permission = EFClient.Permission.Moderator; Permission = EFClient.Permission.Moderator;
RequiresTarget = true; RequiresTarget = true;
SupportedGames = Plugin.SupportedGames; SupportedGames = Plugin.SupportedGames;
Arguments = new[] Arguments =
{ [
new CommandArgument new CommandArgument
{ {
Name = translationLookup["COMMANDS_ARGS_PLAYER"], Name = translationLookup["COMMANDS_ARGS_PLAYER"],
Required = true Required = true
} }
}; ];
} }
public override async Task ExecuteAsync(GameEvent gameEvent) public override async Task ExecuteAsync(GameEvent gameEvent)

View File

@ -7,10 +7,9 @@ using SharedLibraryCore.Interfaces;
namespace IW4MAdmin.Plugins.Mute.Commands; namespace IW4MAdmin.Plugins.Mute.Commands;
public class TempMuteCommand : Command public partial class TempMuteCommand : Command
{ {
private readonly MuteManager _muteManager; private readonly MuteManager _muteManager;
private const string TempBanRegex = @"([0-9]+\w+)\ (.+)";
public TempMuteCommand(CommandConfiguration config, ITranslationLookup translationLookup, MuteManager muteManager) : base(config, public TempMuteCommand(CommandConfiguration config, ITranslationLookup translationLookup, MuteManager muteManager) : base(config,
translationLookup) translationLookup)
@ -22,8 +21,8 @@ public class TempMuteCommand : Command
Permission = EFClient.Permission.Moderator; Permission = EFClient.Permission.Moderator;
RequiresTarget = true; RequiresTarget = true;
SupportedGames = Plugin.SupportedGames; SupportedGames = Plugin.SupportedGames;
Arguments = new[] Arguments =
{ [
new CommandArgument new CommandArgument
{ {
Name = translationLookup["COMMANDS_ARGS_PLAYER"], Name = translationLookup["COMMANDS_ARGS_PLAYER"],
@ -39,7 +38,7 @@ public class TempMuteCommand : Command
Name = translationLookup["COMMANDS_ARGS_REASON"], Name = translationLookup["COMMANDS_ARGS_REASON"],
Required = true Required = true
} }
}; ];
} }
public override async Task ExecuteAsync(GameEvent gameEvent) public override async Task ExecuteAsync(GameEvent gameEvent)
@ -50,7 +49,7 @@ public class TempMuteCommand : Command
return; return;
} }
var match = Regex.Match(gameEvent.Data, TempBanRegex); var match = TempBanRegex().Match(gameEvent.Data);
if (match.Success) if (match.Success)
{ {
var expiration = DateTime.UtcNow + match.Groups[1].ToString().ParseTimespan(); var expiration = DateTime.UtcNow + match.Groups[1].ToString().ParseTimespan();
@ -72,4 +71,7 @@ public class TempMuteCommand : Command
gameEvent.Origin.Tell(_translationLookup["PLUGINS_MUTE_COMMANDS_TEMPMUTE_BAD_FORMAT"]); gameEvent.Origin.Tell(_translationLookup["PLUGINS_MUTE_COMMANDS_TEMPMUTE_BAD_FORMAT"]);
} }
[GeneratedRegex(@"([0-9]+\w+)\ (.+)")]
private static partial Regex TempBanRegex();
} }

View File

@ -20,8 +20,8 @@ public class UnmuteCommand : Command
Permission = EFClient.Permission.Moderator; Permission = EFClient.Permission.Moderator;
RequiresTarget = true; RequiresTarget = true;
SupportedGames = Plugin.SupportedGames; SupportedGames = Plugin.SupportedGames;
Arguments = new[] Arguments =
{ [
new CommandArgument new CommandArgument
{ {
Name = translationLookup["COMMANDS_ARGS_PLAYER"], Name = translationLookup["COMMANDS_ARGS_PLAYER"],
@ -32,7 +32,7 @@ public class UnmuteCommand : Command
Name = translationLookup["COMMANDS_ARGS_REASON"], Name = translationLookup["COMMANDS_ARGS_REASON"],
Required = true Required = true
} }
}; ];
} }
public override async Task ExecuteAsync(GameEvent gameEvent) public override async Task ExecuteAsync(GameEvent gameEvent)

View File

@ -8,6 +8,7 @@
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<Configurations>Debug;Release;Prerelease</Configurations> <Configurations>Debug;Release;Prerelease</Configurations>
<Platforms>AnyCPU</Platforms> <Platforms>AnyCPU</Platforms>
<RootNamespace>IW4MAdmin.Plugins.Mute</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -10,23 +10,15 @@ using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace IW4MAdmin.Plugins.Mute; namespace IW4MAdmin.Plugins.Mute;
public class MuteManager public class MuteManager(
ILogger<MuteManager> logger,
IDatabaseContextFactory databaseContextFactory,
IMetaServiceV2 metaService,
ITranslationLookup translationLookup)
{ {
private readonly IMetaServiceV2 _metaService; private readonly ILogger _logger = logger;
private readonly ITranslationLookup _translationLookup;
private readonly ILogger _logger;
private readonly IDatabaseContextFactory _databaseContextFactory;
private readonly SemaphoreSlim _onMuteAction = new(1, 1); private readonly SemaphoreSlim _onMuteAction = new(1, 1);
public MuteManager(ILogger<MuteManager> logger, IDatabaseContextFactory databaseContextFactory,
IMetaServiceV2 metaService, ITranslationLookup translationLookup)
{
_logger = logger;
_databaseContextFactory = databaseContextFactory;
_metaService = metaService;
_translationLookup = translationLookup;
}
public static bool IsExpiredMute(MuteStateMeta muteStateMeta) => public static bool IsExpiredMute(MuteStateMeta muteStateMeta) =>
muteStateMeta.Expiration is not null && muteStateMeta.Expiration < DateTime.UtcNow; muteStateMeta.Expiration is not null && muteStateMeta.Expiration < DateTime.UtcNow;
@ -42,7 +34,7 @@ public class MuteManager
var muteState = await ReadPersistentDataV1(client); var muteState = await ReadPersistentDataV1(client);
clientMuteMeta = new MuteStateMeta clientMuteMeta = new MuteStateMeta
{ {
Reason = muteState is null ? string.Empty : _translationLookup["PLUGINS_MUTE_MIGRATED"], Reason = muteState is null ? string.Empty : translationLookup["PLUGINS_MUTE_MIGRATED"],
Expiration = muteState switch Expiration = muteState switch
{ {
null => DateTime.UtcNow, null => DateTime.UtcNow,
@ -149,7 +141,7 @@ public class MuteManager
private async Task ExpireMutePenalties(EFClient client) private async Task ExpireMutePenalties(EFClient client)
{ {
await using var context = _databaseContextFactory.CreateContext(); await using var context = databaseContextFactory.CreateContext();
var mutePenalties = await context.Penalties var mutePenalties = await context.Penalties
.Where(penalty => penalty.OffenderId == client.ClientId) .Where(penalty => penalty.OffenderId == client.ClientId)
.Where(penalty => penalty.Type == EFPenalty.PenaltyType.Mute || penalty.Type == EFPenalty.PenaltyType.TempMute) .Where(penalty => penalty.Type == EFPenalty.PenaltyType.Mute || penalty.Type == EFPenalty.PenaltyType.TempMute)
@ -184,7 +176,7 @@ public class MuteManager
} }
private async Task<MuteState?> ReadPersistentDataV1(EFClient client) => TryParse<MuteState>( private async Task<MuteState?> ReadPersistentDataV1(EFClient client) => TryParse<MuteState>(
(await _metaService.GetPersistentMeta(Plugin.MuteKey, client.ClientId))?.Value, out var muteState) (await metaService.GetPersistentMeta(Plugin.MuteKey, client.ClientId))?.Value, out var muteState)
? muteState ? muteState
: null; : null;
@ -195,7 +187,7 @@ public class MuteManager
if (clientMuteMeta is not null) return clientMuteMeta; if (clientMuteMeta is not null) return clientMuteMeta;
// Get meta from database and store in client if exists // Get meta from database and store in client if exists
clientMuteMeta = await _metaService.GetPersistentMetaValue<MuteStateMeta>(Plugin.MuteKey, client.ClientId); clientMuteMeta = await metaService.GetPersistentMetaValue<MuteStateMeta>(Plugin.MuteKey, client.ClientId);
if (clientMuteMeta is not null) client.SetAdditionalProperty(Plugin.MuteKey, clientMuteMeta); if (clientMuteMeta is not null) client.SetAdditionalProperty(Plugin.MuteKey, clientMuteMeta);
return clientMuteMeta; return clientMuteMeta;
@ -204,6 +196,6 @@ public class MuteManager
private async Task WritePersistentData(EFClient client, MuteStateMeta clientMuteMeta) private async Task WritePersistentData(EFClient client, MuteStateMeta clientMuteMeta)
{ {
client.SetAdditionalProperty(Plugin.MuteKey, clientMuteMeta); client.SetAdditionalProperty(Plugin.MuteKey, clientMuteMeta);
await _metaService.SetPersistentMetaValue(Plugin.MuteKey, clientMuteMeta, client.ClientId); await metaService.SetPersistentMetaValue(Plugin.MuteKey, clientMuteMeta, client.ClientId);
} }
} }

View File

@ -21,15 +21,14 @@ public class Plugin : IPluginV2
public const string MuteKey = "IW4MMute"; public const string MuteKey = "IW4MMute";
public static IManager Manager { get; private set; } = null!; public static IManager Manager { get; private set; } = null!;
public static Server.Game[] SupportedGames { get; private set; } = Array.Empty<Server.Game>(); public static Server.Game[] SupportedGames { get; private set; } = [];
private static readonly string[] DisabledCommands = [nameof(PrivateMessageAdminsCommand), "PrivateMessageCommand"]; private static readonly string[] DisabledCommands = [nameof(PrivateMessageAdminsCommand), "PrivateMessageCommand"];
private readonly IInteractionRegistration _interactionRegistration; private readonly IInteractionRegistration _interactionRegistration;
private readonly IRemoteCommandService _remoteCommandService; private readonly IRemoteCommandService _remoteCommandService;
private readonly MuteManager _muteManager; private readonly MuteManager _muteManager;
private const string MuteInteraction = "Webfront::Profile::Mute"; private const string MuteInteraction = "Webfront::Profile::Mute";
public Plugin(IInteractionRegistration interactionRegistration, public Plugin(IInteractionRegistration interactionRegistration, IRemoteCommandService remoteCommandService, MuteManager muteManager)
IRemoteCommandService remoteCommandService, MuteManager muteManager)
{ {
_interactionRegistration = interactionRegistration; _interactionRegistration = interactionRegistration;
_remoteCommandService = remoteCommandService; _remoteCommandService = remoteCommandService;
@ -37,7 +36,6 @@ public class Plugin : IPluginV2
IManagementEventSubscriptions.Load += OnLoad; IManagementEventSubscriptions.Load += OnLoad;
IManagementEventSubscriptions.Unload += OnUnload; IManagementEventSubscriptions.Unload += OnUnload;
IManagementEventSubscriptions.ClientStateInitialized += OnClientStateInitialized; IManagementEventSubscriptions.ClientStateInitialized += OnClientStateInitialized;
IGameServerEventSubscriptions.ClientDataUpdated += OnClientDataUpdated; IGameServerEventSubscriptions.ClientDataUpdated += OnClientDataUpdated;
@ -73,7 +71,7 @@ public class Plugin : IPluginV2
return !DisabledCommands.Contains(command.GetType().Name) && !command.IsBroadcast; return !DisabledCommands.Contains(command.GetType().Name) && !command.IsBroadcast;
}); });
_interactionRegistration.RegisterInteraction(MuteInteraction, async (targetClientId, game, token) => _interactionRegistration.RegisterInteraction(MuteInteraction, async (targetClientId, game, _) =>
{ {
if (!targetClientId.HasValue || game.HasValue && !SupportedGames.Contains((Server.Game)game.Value)) if (!targetClientId.HasValue || game.HasValue && !SupportedGames.Contains((Server.Game)game.Value))
{ {
@ -85,12 +83,12 @@ public class Plugin : IPluginV2
.MuteState; .MuteState;
var server = manager.GetServers().First(); var server = manager.GetServers().First();
string GetCommandName(Type commandType) =>
manager.Commands.FirstOrDefault(command => command.GetType() == commandType)?.Name ?? "";
return clientMuteMetaState is MuteState.Unmuted or MuteState.Unmuting return clientMuteMetaState is MuteState.Unmuted or MuteState.Unmuting
? CreateMuteInteraction(targetClientId.Value, server, GetCommandName) ? CreateMuteInteraction(targetClientId.Value, server, GetCommandName)
: CreateUnmuteInteraction(targetClientId.Value, server, GetCommandName); : CreateUnmuteInteraction(targetClientId.Value, server, GetCommandName);
string GetCommandName(Type commandType) =>
manager.Commands.FirstOrDefault(command => command.GetType() == commandType)?.Name ?? string.Empty;
}); });
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -109,9 +107,9 @@ public class Plugin : IPluginV2
} }
var networkIds = updateEvent.Clients.Select(client => client.NetworkId).ToList(); var networkIds = updateEvent.Clients.Select(client => client.NetworkId).ToList();
var ingameClients = updateEvent.Server.ConnectedClients.Where(client => networkIds.Contains(client.NetworkId)); var inGameClients = updateEvent.Server.ConnectedClients.Where(client => networkIds.Contains(client.NetworkId));
await Task.WhenAll(ingameClients.Select(async client => await Task.WhenAll(inGameClients.Select(async client =>
{ {
var muteMetaUpdate = await _muteManager.GetCurrentMuteState(client); var muteMetaUpdate = await _muteManager.GetCurrentMuteState(client);
if (!muteMetaUpdate.CommandExecuted) if (!muteMetaUpdate.CommandExecuted)
@ -137,7 +135,7 @@ public class Plugin : IPluginV2
{ {
var muteMetaSay = await _muteManager.GetCurrentMuteState(messageEvent.Origin); var muteMetaSay = await _muteManager.GetCurrentMuteState(messageEvent.Origin);
if (muteMetaSay.MuteState == MuteState.Muted) if (muteMetaSay.MuteState is MuteState.Muted)
{ {
// Let the client know when their mute expires. // Let the client know when their mute expires.
messageEvent.Origin.Tell(Utilities.CurrentLocalization messageEvent.Origin.Tell(Utilities.CurrentLocalization
@ -191,6 +189,29 @@ public class Plugin : IPluginV2
Values = (Dictionary<string, string>?)null Values = (Dictionary<string, string>?)null
}; };
var presetReasonInput = new
{
Name = "PresetReason",
Label = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_ACTION_LABEL_PRESET_REASON"],
Type = "select",
Values = (Dictionary<string, string>?)new Dictionary<string, string>
{
{ string.Empty, string.Empty },
{
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_ABUSIVE"],
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_ABUSIVE"]
},
{
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_SPAMMING"],
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_SPAMMING"]
},
{
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_OTHER"],
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_MUTE_REASON_OTHER"]
}
}
};
var durationInput = new var durationInput = new
{ {
Name = "Duration", Name = "Duration",
@ -207,7 +228,7 @@ public class Plugin : IPluginV2
} }
}; };
var inputs = new[] {reasonInput, durationInput}; var inputs = new[] { reasonInput, presetReasonInput, durationInput };
var inputsJson = JsonSerializer.Serialize(inputs); var inputsJson = JsonSerializer.Serialize(inputs);
return new InteractionData return new InteractionData
@ -216,7 +237,7 @@ public class Plugin : IPluginV2
Name = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_CONTEXT_MENU_ACTION_MUTE"], Name = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_CONTEXT_MENU_ACTION_MUTE"],
DisplayMeta = "oi-volume-off", DisplayMeta = "oi-volume-off",
ActionPath = "DynamicAction", ActionPath = "DynamicAction",
ActionMeta = new() ActionMeta = new Dictionary<string, string>
{ {
{ "InteractionId", MuteInteraction }, { "InteractionId", MuteInteraction },
{ "Inputs", inputsJson }, { "Inputs", inputsJson },
@ -250,11 +271,14 @@ public class Plugin : IPluginV2
args.Add(duration); args.Add(duration);
} }
if (meta.TryGetValue(reasonInput.Name, out var reason)) var definedReason = meta.TryGetValue(reasonInput.Name, out var reason) ? reason : string.Empty;
if (meta.TryGetValue(presetReasonInput.Name, out var presetReason) && string.IsNullOrWhiteSpace(definedReason))
{ {
args.Add(reason); definedReason = presetReason;
} }
args.Add(definedReason);
var commandResponse = var commandResponse =
await _remoteCommandService.Execute(originId, targetId, muteCommand, args, server); await _remoteCommandService.Execute(originId, targetId, muteCommand, args, server);
return string.Join(".", commandResponse.Select(result => result.Response)); return string.Join(".", commandResponse.Select(result => result.Response));
@ -278,11 +302,10 @@ public class Plugin : IPluginV2
return new InteractionData return new InteractionData
{ {
EntityId = targetClientId, EntityId = targetClientId,
Name = Utilities.CurrentLocalization.LocalizationIndex[ Name = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_CONTEXT_MENU_ACTION_UNMUTE"],
"WEBFRONT_PROFILE_CONTEXT_MENU_ACTION_UNMUTE"],
DisplayMeta = "oi-volume-high", DisplayMeta = "oi-volume-high",
ActionPath = "DynamicAction", ActionPath = "DynamicAction",
ActionMeta = new() ActionMeta = new Dictionary<string, string>
{ {
{ "InteractionId", MuteInteraction }, { "InteractionId", MuteInteraction },
{ "Outputs", reasonInput.Name }, { "Outputs", reasonInput.Name },