Skip to content

Commit 4dece4b

Browse files
authored
Merge pull request #398 from iceljc/features/add-state-change-hook-remove-state
add hook
2 parents 7c061af + 76de65e commit 4dece4b

2 files changed

Lines changed: 26 additions & 7 deletions

File tree

src/Infrastructure/BotSharp.Abstraction/Conversations/Models/StateChangeModel.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ public class StateChangeModel
1212
public string Name { get; set; }
1313

1414
[JsonPropertyName("before_value")]
15-
public string BeforeValue { get; set; }
15+
public string? BeforeValue { get; set; }
1616

1717
[JsonPropertyName("before_active_rounds")]
1818
public int? BeforeActiveRounds { get; set; }
1919

2020
[JsonPropertyName("after_value")]
21-
public string AfterValue { get; set; }
21+
public string? AfterValue { get; set; }
2222

2323
[JsonPropertyName("after_active_rounds")]
2424
public int? AfterActiveRounds { get; set; }

src/Infrastructure/BotSharp.Core/Conversations/Services/ConversationStateService.cs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,9 @@ public void Save()
201201
var key = pair.Key;
202202
var curValue = pair.Value;
203203

204-
if (!_historyStates.TryGetValue(key, out var historyValue)
205-
|| historyValue == null
206-
|| historyValue.Values.IsNullOrEmpty()
204+
if (!_historyStates.TryGetValue(key, out var historyValue)
205+
|| historyValue == null
206+
|| historyValue.Values.IsNullOrEmpty()
207207
|| !curValue.Versioning)
208208
{
209209
states.Add(curValue);
@@ -232,8 +232,9 @@ public bool RemoveState(string name)
232232
if (!ContainsState(name)) return false;
233233

234234
var routingCtx = _services.GetRequiredService<IRoutingContext>();
235-
var leafNode = _curStates[name].Values?.LastOrDefault();
236-
if (leafNode == null) return false;
235+
var value = _curStates[name];
236+
var leafNode = value?.Values?.LastOrDefault();
237+
if (value == null || !value.Versioning || leafNode == null) return false;
237238

238239
_curStates[name].Values.Add(new StateValue
239240
{
@@ -246,6 +247,24 @@ public bool RemoveState(string name)
246247
UpdateTime = DateTime.UtcNow
247248
});
248249

250+
var hooks = _services.GetServices<IConversationHook>();
251+
foreach (var hook in hooks)
252+
{
253+
hook.OnStateChanged(new StateChangeModel
254+
{
255+
ConversationId = _conversationId,
256+
MessageId = routingCtx.MessageId,
257+
Name = name,
258+
BeforeValue = leafNode.Data,
259+
BeforeActiveRounds = leafNode.ActiveRounds,
260+
AfterValue = null,
261+
AfterActiveRounds = leafNode.ActiveRounds,
262+
DataType = leafNode.DataType,
263+
Source = leafNode.Source,
264+
Readonly = _curStates[name].Readonly
265+
}).Wait();
266+
}
267+
249268
return true;
250269
}
251270

0 commit comments

Comments
 (0)