microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
feature/pabot-httpcontext-botid

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Plugins/Microsoft.Teams.Plugins.AspNetCore/AspNetCorePlugin.cs

267lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System.Text.Json;
5using System.Text.Json.Serialization;
6
7using Microsoft.AspNetCore.Builder;
8using Microsoft.AspNetCore.Http;
9using Microsoft.Teams.Api.Activities;
10using Microsoft.Teams.Api.Auth;
11using Microsoft.Teams.Api.Clients;
12using Microsoft.Teams.Apps;
13using Microsoft.Teams.Apps.Events;
14using Microsoft.Teams.Apps.Plugins;
15using Microsoft.Teams.Common.Http;
16using Microsoft.Teams.Common.Logging;
17
18using HttpRequest = Microsoft.AspNetCore.Http.HttpRequest;
19
20namespace Microsoft.Teams.Plugins.AspNetCore;
21
22[Plugin]
23public partial class AspNetCorePlugin : ISenderPlugin, IAspNetCorePlugin
24{
25 [Dependency]
26 public ILogger Logger { get; set; }
27
28 [Dependency("Token", optional: true)]
29 public IToken? Token { get; set; }
30
31 [Dependency]
32 public IHttpClient Client { get; set; }
33
34 public event EventFunction Events;
35
36 private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
37 {
38 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
39 };
40
41 public IApplicationBuilder Configure(IApplicationBuilder builder)
42 {
43 return builder;
44 }
45
46 public Task OnInit(App app, CancellationToken cancellationToken = default)
47 {
48 return Task.CompletedTask;
49 }
50
51 public Task OnStart(App app, CancellationToken cancellationToken = default)
52 {
53 Logger.Debug("OnStart");
54 return Task.CompletedTask;
55 }
56
57 public Task OnError(App app, IPlugin plugin, ErrorEvent @event, CancellationToken cancellationToken = default)
58 {
59 Logger.Debug("OnError");
60 return Task.CompletedTask;
61 }
62
63 public Task OnActivity(App app, ISenderPlugin sender, ActivityEvent @event, CancellationToken cancellationToken = default)
64 {
65 Logger.Debug("OnActivity");
66 return Task.CompletedTask;
67 }
68
69 public Task OnActivitySent(App app, ISenderPlugin sender, ActivitySentEvent @event, CancellationToken cancellationToken = default)
70 {
71 Logger.Debug("OnActivitySent");
72 return Task.CompletedTask;
73 }
74
75 public Task OnActivityResponse(App app, ISenderPlugin sender, ActivityResponseEvent @event, CancellationToken cancellationToken = default)
76 {
77 Logger.Debug("OnActivityResponse");
78 return Task.CompletedTask;
79 }
80
81 public Task<IActivity> Send(IActivity activity, Api.ConversationReference reference, CancellationToken cancellationToken = default)
82 {
83 return Send<IActivity>(activity, reference, cancellationToken);
84 }
85
86 public async Task<TActivity> Send<TActivity>(TActivity activity, Api.ConversationReference reference, CancellationToken cancellationToken = default) where TActivity : IActivity
87 {
88 var client = new ApiClient(reference.ServiceUrl, Client, cancellationToken);
89
90 activity.Conversation = reference.Conversation;
91 activity.From = reference.Bot;
92 activity.ChannelId = reference.ChannelId;
93
94 // For targeted messages with an explicit Recipient (proactive sends), preserve it.
95 // Otherwise, use the reference User from the conversation context.
96 #pragma warning disable ExperimentalTeamsTargeted
97 var isTargeted = activity.Recipient?.IsTargeted == true;
98
99 if (isTargeted && reference.Conversation.Type?.IsPersonal == true)
100 {
101 throw new InvalidOperationException(
102 "Targeted messages are not supported in personal (1:1) chats.");
103 }
104
105 if (!isTargeted)
106 {
107 activity.Recipient = reference.User;
108 }
109
110 if (activity.Id is not null && !activity.IsStreaming)
111 {
112 if (isTargeted)
113 {
114 await client
115 .Conversations
116 .Activities
117 .UpdateTargetedAsync(reference.Conversation.Id, activity.Id, activity).ConfigureAwait(false);
118 }
119 else
120 {
121 await client
122 .Conversations
123 .Activities
124 .UpdateAsync(reference.Conversation.Id, activity.Id, activity).ConfigureAwait(false);
125 }
126
127 return activity;
128 }
129
130 var res = isTargeted
131 ? await client.Conversations.Activities.CreateTargetedAsync(reference.Conversation.Id, activity).ConfigureAwait(false)
132 : await client.Conversations.Activities.CreateAsync(reference.Conversation.Id, activity).ConfigureAwait(false);
133 #pragma warning restore ExperimentalTeamsTargeted
134
135 activity.Id = res?.Id;
136 return activity;
137 }
138
139 public IStreamer CreateStream(Api.ConversationReference reference, CancellationToken cancellationToken = default)
140 {
141 return new Stream()
142 {
143 Send = async activity =>
144 {
145 var res = await Send(activity, reference, cancellationToken).ConfigureAwait(false);
146 return res;
147 },
148 Logger = Logger.Child("stream")
149 };
150 }
151
152 public async Task<Response> Do(ActivityEvent @event, CancellationToken cancellationToken = default)
153 {
154 try
155 {
156 var @out = await Events(
157 this,
158 "activity",
159 @event,
160 cancellationToken
161 ).ConfigureAwait(false);
162
163 var res = (Response?)@out ?? throw new Exception("expected activity response");
164 Logger.Debug(res);
165 return res;
166 }
167 catch (Exception ex)
168 {
169 Logger.Error(ex);
170 await Events(
171 this,
172 "error",
173 new ErrorEvent() { Exception = ex },
174 cancellationToken
175 ).ConfigureAwait(false);
176
177 return new Response(System.Net.HttpStatusCode.InternalServerError, ex.ToString());
178 }
179 }
180
181 public async Task<IResult> Do(HttpContext httpContext, CancellationToken cancellationToken = default)
182 {
183 try
184 {
185 var request = httpContext.Request;
186 var token = ExtractToken(request);
187 var activity = await ParseActivity(request).ConfigureAwait(false);
188
189 if (activity is null)
190 {
191 return Results.BadRequest("Missing activity");
192 }
193
194 var data = new Dictionary<string, object?>
195 {
196 ["Request.TraceId"] = httpContext.TraceIdentifier
197 };
198
199 foreach (var pair in httpContext.Items)
200 {
201 var key = pair.Key.ToString();
202
203 if (key is null) continue;
204
205 data[key] = pair.Value;
206 }
207
208 var res = await Do(new ActivityEvent()
209 {
210 Token = token,
211 Activity = activity,
212 Extra = data,
213 Services = httpContext.RequestServices
214 }, cancellationToken).ConfigureAwait(false);
215
216 // convert response metadata to headers
217 foreach (var (key, value) in res.Meta)
218 {
219 var str = value?.ToString();
220 if (string.IsNullOrEmpty(str)) continue;
221 httpContext.Response.Headers.Append($"X-Teams-{char.ToUpper(key[0]) + key[1..]}", str);
222 }
223
224 return Results.Json(
225 res.Body,
226 _jsonSerializerOptions,
227 contentType: null,
228 statusCode: (int)res.Status
229 );
230 }
231 catch (Exception ex)
232 {
233 Logger.Error(ex);
234 await Events(
235 this,
236 "error",
237 new ErrorEvent() { Exception = ex },
238 cancellationToken
239 ).ConfigureAwait(false);
240
241 return Results.Problem(detail: ex.Message, statusCode: 500);
242 }
243 }
244
245 public JsonWebToken ExtractToken(HttpRequest httpRequest)
246 {
247 var authHeader = httpRequest.Headers.Authorization.FirstOrDefault() ?? throw new UnauthorizedAccessException();
248 return new JsonWebToken(authHeader.Replace("Bearer ", ""));
249 }
250
251 public async Task<Activity?> ParseActivity(HttpRequest httpRequest)
252 {
253 httpRequest.EnableBuffering();
254
255 if (httpRequest.Body.CanSeek)
256 {
257 // reset the stream position to the beginning in case it was read before
258 httpRequest.Body.Position = 0;
259 }
260
261 using StreamReader sr = new(httpRequest.Body);
262 var body = await sr.ReadToEndAsync().ConfigureAwait(false);
263 Activity? activity = JsonSerializer.Deserialize<Activity>(body);
264
265 return activity;
266 }
267}