microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
e2efe052792ba394b46f2004d1390a3cdfcd0c1e

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/src/Microsoft.Teams.Bot.Compat/CompatBotAdapter.cs

131lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using System.Text.Json;
5using Microsoft.AspNetCore.Http;
6using Microsoft.Bot.Builder;
7using Microsoft.Bot.Schema;
8using Microsoft.Extensions.Logging;
9using Microsoft.Teams.Bot.Apps;
10using Microsoft.Teams.Bot.Core;
11using Newtonsoft.Json;
12
13
14namespace Microsoft.Teams.Bot.Compat;
15
16/// <summary>
17/// Provides a Bot Framework adapter that enables compatibility between the Bot Framework SDK and a custom bot
18/// application implementation.
19/// </summary>
20/// <remarks>Use this adapter to bridge Bot Framework turn contexts and activities with a custom bot application.
21/// This class is intended for scenarios where integration with non-standard bot runtimes or legacy systems is
22/// required.</remarks>
23/// <param name="botApplication">The Teams bot application instance.</param>
24/// <param name="httpContextAccessor">The HTTP context accessor.</param>
25/// <param name="logger">The logger instance.</param>
26public class CompatBotAdapter(
27 TeamsBotApplication botApplication,
28 IHttpContextAccessor? httpContextAccessor = null,
29 ILogger? logger = null) : BotAdapter
30{
31 private readonly JsonSerializerOptions _writeIndentedJsonOptions = new() { WriteIndented = true };
32 private readonly TeamsBotApplication botApplication = botApplication;
33 private readonly IHttpContextAccessor? httpContextAccessor = httpContextAccessor;
34 private readonly ILogger? logger = logger;
35
36 /// <summary>
37 /// Deletes an activity from the conversation.
38 /// </summary>
39 /// <param name="turnContext">The turn context containing the activity information. Cannot be null.</param>
40 /// <param name="reference">The conversation reference identifying the activity to delete.</param>
41 /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
42 /// <returns>A task that represents the asynchronous delete operation.</returns>
43 public override async Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
44 {
45 ArgumentNullException.ThrowIfNull(turnContext);
46 await botApplication.ConversationClient.DeleteActivityAsync(turnContext.Activity.FromCompatActivity(), cancellationToken: cancellationToken).ConfigureAwait(false);
47 }
48
49 /// <summary>
50 /// Sends a set of activities to the conversation.
51 /// </summary>
52 /// <param name="turnContext">The turn context for the conversation. Cannot be null.</param>
53 /// <param name="activities">An array of activities to send. Cannot be null.</param>
54 /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
55 /// <returns>
56 /// A task that represents the asynchronous operation. The task result contains an array of <see cref="ResourceResponse"/>
57 /// objects with the IDs of the sent activities.
58 /// </returns>
59 public override async Task<ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
60 {
61 ArgumentNullException.ThrowIfNull(activities);
62 ArgumentNullException.ThrowIfNull(turnContext);
63
64 ResourceResponse[] responses = new Microsoft.Bot.Schema.ResourceResponse[activities.Length];
65
66 for (int i = 0; i < activities.Length; i++)
67 {
68 Activity activity = activities[i];
69
70 if (activity.Type == ActivityTypes.Trace)
71 {
72 return [new ResourceResponse() { Id = null }];
73 }
74
75 if (activity.Type == "invokeResponse")
76 {
77 WriteInvokeResponseToHttpResponse(activity.Value as InvokeResponse);
78 return [new ResourceResponse() { Id = null }];
79 }
80
81 SendActivityResponse? resp = await botApplication.SendActivityAsync(activity.FromCompatActivity(), cancellationToken).ConfigureAwait(false);
82
83 logger?.LogInformation("Resp from SendActivitiesAsync: {RespId}", resp?.Id);
84
85 responses[i] = new Microsoft.Bot.Schema.ResourceResponse() { Id = resp?.Id };
86 }
87 return responses;
88 }
89
90 /// <summary>
91 /// Updates an existing activity in the conversation.
92 /// </summary>
93 /// <param name="turnContext">The turn context for the conversation.</param>
94 /// <param name="activity">The activity with updated content. Cannot be null.</param>
95 /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
96 /// <returns>
97 /// A task that represents the asynchronous operation. The task result contains a <see cref="ResourceResponse"/>
98 /// with the ID of the updated activity.
99 /// </returns>
100 public override async Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
101 {
102 ArgumentNullException.ThrowIfNull(activity);
103 UpdateActivityResponse res = await botApplication.ConversationClient.UpdateActivityAsync(
104 activity.Conversation.Id,
105 activity.Id,
106 activity.FromCompatActivity(),
107 cancellationToken: cancellationToken).ConfigureAwait(false);
108 return new ResourceResponse() { Id = res.Id };
109 }
110
111 private void WriteInvokeResponseToHttpResponse(InvokeResponse? invokeResponse)
112 {
113 ArgumentNullException.ThrowIfNull(invokeResponse);
114 HttpResponse? response = httpContextAccessor?.HttpContext?.Response;
115 if (response is not null && !response.HasStarted)
116 {
117 response.StatusCode = invokeResponse.Status;
118 using StreamWriter httpResponseStreamWriter = new(response.BodyWriter.AsStream());
119 using JsonTextWriter httpResponseJsonWriter = new(httpResponseStreamWriter);
120 logger?.LogTrace("Sending Invoke Response: \n {InvokeResponse} with status: {Status} \n", System.Text.Json.JsonSerializer.Serialize(invokeResponse.Body, _writeIndentedJsonOptions), invokeResponse.Status);
121 if (invokeResponse.Body is not null)
122 {
123 Microsoft.Bot.Builder.Integration.AspNet.Core.HttpHelper.BotMessageSerializer.Serialize(httpResponseJsonWriter, invokeResponse.Body);
124 }
125 }
126 else
127 {
128 logger?.LogWarning("HTTP response is null or has started. Cannot write invoke response. ResponseStarted: {ResponseStarted}", response?.HasStarted);
129 }
130 }
131}
132