2025-05-15 07:25:08 +00:00
|
|
|
using BotSharp.Abstraction.Hooks;
|
2024-02-28 16:21:14 +00:00
|
|
|
using BotSharp.Abstraction.Infrastructures;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Infrastructures;
|
|
|
|
|
|
|
|
|
|
public static class HookEmitter
|
|
|
|
|
{
|
2025-05-15 07:25:08 +00:00
|
|
|
public static HookEmittedResult Emit<T>(IServiceProvider services, Action<T> action, string agentId, HookEmitOption<T>? option = null) where T : IHookBase
|
2024-02-28 16:21:14 +00:00
|
|
|
{
|
|
|
|
|
var logger = services.GetRequiredService<ILogger<T>>();
|
|
|
|
|
var result = new HookEmittedResult();
|
2025-05-15 07:25:08 +00:00
|
|
|
var hooks = services.GetServices<T>().Where(p => p.IsMatch(agentId));
|
2024-11-12 22:51:33 +00:00
|
|
|
option = option ?? new();
|
2024-02-28 16:21:14 +00:00
|
|
|
|
|
|
|
|
foreach (var hook in hooks)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2025-04-29 06:08:08 +00:00
|
|
|
if (option.ShouldExecute == null || option.ShouldExecute(hook))
|
2024-11-12 22:51:33 +00:00
|
|
|
{
|
2025-04-29 06:08:08 +00:00
|
|
|
logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})");
|
|
|
|
|
action(hook);
|
|
|
|
|
|
|
|
|
|
if (option.OnlyOnce)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
2024-11-12 22:51:33 +00:00
|
|
|
}
|
2024-02-28 16:21:14 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(ex.ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
2024-10-12 14:58:42 +00:00
|
|
|
|
2025-05-15 07:25:08 +00:00
|
|
|
public static async Task<HookEmittedResult> Emit<T>(IServiceProvider services, Func<T, Task> action, string agentId, HookEmitOption<T>? option = null) where T : IHookBase
|
2024-10-12 14:58:42 +00:00
|
|
|
{
|
|
|
|
|
var logger = services.GetRequiredService<ILogger<T>>();
|
|
|
|
|
var result = new HookEmittedResult();
|
2025-05-15 07:25:08 +00:00
|
|
|
var hooks = services.GetServices<T>().Where(p => p.IsMatch(agentId));
|
2024-11-12 22:51:33 +00:00
|
|
|
option = option ?? new();
|
2024-10-12 14:58:42 +00:00
|
|
|
|
|
|
|
|
foreach (var hook in hooks)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2025-04-29 06:08:08 +00:00
|
|
|
if (option.ShouldExecute == null || option.ShouldExecute(hook))
|
2024-11-12 22:51:33 +00:00
|
|
|
{
|
2025-04-29 06:08:08 +00:00
|
|
|
logger.LogDebug($"Emit hook action on {action.Method.Name}({hook.GetType().Name})");
|
|
|
|
|
await action(hook);
|
|
|
|
|
|
|
|
|
|
if (option.OnlyOnce)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
2024-11-12 22:51:33 +00:00
|
|
|
}
|
2024-10-12 14:58:42 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(ex.ToString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
2024-02-28 16:21:14 +00:00
|
|
|
}
|