using BotSharp.Abstraction.Hooks; using BotSharp.Abstraction.Infrastructures; namespace BotSharp.Core.Infrastructures; public static class HookEmitter { public static HookEmittedResult Emit(IServiceProvider services, Action action, string agentId, HookEmitOption? option = null) where T : IHookBase { var logger = services.GetRequiredService>(); var result = new HookEmittedResult(); var hooks = services.GetServices().Where(p => p.IsMatch(agentId)); option = option ?? new(); foreach (var hook in hooks) { try { if (option.ShouldExecute == null || option.ShouldExecute(hook)) { logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})"); action(hook); if (option.OnlyOnce) { break; } } } catch (Exception ex) { logger.LogError(ex.ToString()); } } return result; } public static async Task Emit(IServiceProvider services, Func action, string agentId, HookEmitOption? option = null) where T : IHookBase { var logger = services.GetRequiredService>(); var result = new HookEmittedResult(); var hooks = services.GetServices().Where(p => p.IsMatch(agentId)); option = option ?? new(); foreach (var hook in hooks) { try { if (option.ShouldExecute == null || option.ShouldExecute(hook)) { logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})"); await action(hook); if (option.OnlyOnce) { break; } } } catch (Exception ex) { logger.LogError(ex.ToString()); } } return result; } }