microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Bot.Core/TurnMiddleware.cs
51lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Collections; |
| 5 | |
| 6 | using Microsoft.Bot.Core.Schema; |
| 7 | |
| 8 | namespace Microsoft.Bot.Core; |
| 9 | |
| 10 | internal sealed class TurnMiddleware : ITurnMiddleWare, IEnumerable<ITurnMiddleWare> |
| 11 | { |
| 12 | |
| 13 | private readonly IList<ITurnMiddleWare> _middlewares = []; |
| 14 | internal TurnMiddleware Use(ITurnMiddleWare middleware) |
| 15 | { |
| 16 | _middlewares.Add(middleware); |
| 17 | return this; |
| 18 | } |
| 19 | |
| 20 | |
| 21 | public async Task OnTurnAsync(BotApplication botApplication, CoreActivity activity, NextTurn next, CancellationToken cancellationToken = default) |
| 22 | { |
| 23 | await RunPipelineAsync(botApplication, activity, null!, 0, cancellationToken).ConfigureAwait(false); |
| 24 | await next(cancellationToken).ConfigureAwait(false); |
| 25 | } |
| 26 | |
| 27 | public Task RunPipelineAsync(BotApplication botApplication, CoreActivity activity, Func<CoreActivity, CancellationToken, Task>? callback, int nextMiddlewareIndex, CancellationToken cancellationToken) |
| 28 | { |
| 29 | if (nextMiddlewareIndex == _middlewares.Count) |
| 30 | { |
| 31 | return callback is not null ? callback!(activity, cancellationToken) ?? Task.CompletedTask : Task.CompletedTask; |
| 32 | } |
| 33 | ITurnMiddleWare nextMiddleware = _middlewares[nextMiddlewareIndex]; |
| 34 | return nextMiddleware.OnTurnAsync( |
| 35 | botApplication, |
| 36 | activity, |
| 37 | (ct) => RunPipelineAsync(botApplication, activity, callback, nextMiddlewareIndex + 1, ct), |
| 38 | cancellationToken); |
| 39 | |
| 40 | } |
| 41 | |
| 42 | public IEnumerator<ITurnMiddleWare> GetEnumerator() |
| 43 | { |
| 44 | return _middlewares.GetEnumerator(); |
| 45 | } |
| 46 | |
| 47 | IEnumerator IEnumerable.GetEnumerator() |
| 48 | { |
| 49 | return GetEnumerator(); |
| 50 | } |
| 51 | } |
| 52 | |