microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v2.0.7

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

266lines · 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);
118 }
119 else
120 {
121 await client
122 .Conversations
123 .Activities
124 .UpdateAsync(reference.Conversation.Id, activity.Id, activity);
125 }
126
127 return activity;
128 }
129
130 var res = isTargeted
131 ? await client.Conversations.Activities.CreateTargetedAsync(reference.Conversation.Id, activity)
132 : await client.Conversations.Activities.CreateAsync(reference.Conversation.Id, activity);
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);
146 return res;
147 }
148 };
149 }
150
151 public async Task<Response> Do(ActivityEvent @event, CancellationToken cancellationToken = default)
152 {
153 try
154 {
155 var @out = await Events(
156 this,
157 "activity",
158 @event,
159 cancellationToken
160 );
161
162 var res = (Response?)@out ?? throw new Exception("expected activity response");
163 Logger.Debug(res);
164 return res;
165 }
166 catch (Exception ex)
167 {
168 Logger.Error(ex);
169 await Events(
170 this,
171 "error",
172 new ErrorEvent() { Exception = ex },
173 cancellationToken
174 );
175
176 return new Response(System.Net.HttpStatusCode.InternalServerError, ex.ToString());
177 }
178 }
179
180 public async Task<IResult> Do(HttpContext httpContext, CancellationToken cancellationToken = default)
181 {
182 try
183 {
184 var request = httpContext.Request;
185 var token = ExtractToken(request);
186 var activity = await ParseActivity(request);
187
188 if (activity is null)
189 {
190 return Results.BadRequest("Missing activity");
191 }
192
193 var data = new Dictionary<string, object?>
194 {
195 ["Request.TraceId"] = httpContext.TraceIdentifier
196 };
197
198 foreach (var pair in httpContext.Items)
199 {
200 var key = pair.Key.ToString();
201
202 if (key is null) continue;
203
204 data[key] = pair.Value;
205 }
206
207 var res = await Do(new ActivityEvent()
208 {
209 Token = token,
210 Activity = activity,
211 Extra = data,
212 Services = httpContext.RequestServices
213 }, cancellationToken);
214
215 // convert response metadata to headers
216 foreach (var (key, value) in res.Meta)
217 {
218 var str = value?.ToString();
219 if (string.IsNullOrEmpty(str)) continue;
220 httpContext.Response.Headers.Append($"X-Teams-{char.ToUpper(key[0]) + key[1..]}", str);
221 }
222
223 return Results.Json(
224 res.Body,
225 _jsonSerializerOptions,
226 contentType: null,
227 statusCode: (int)res.Status
228 );
229 }
230 catch (Exception ex)
231 {
232 Logger.Error(ex);
233 await Events(
234 this,
235 "error",
236 new ErrorEvent() { Exception = ex },
237 cancellationToken
238 );
239
240 return Results.Problem(detail: ex.Message, statusCode: 500);
241 }
242 }
243
244 public JsonWebToken ExtractToken(HttpRequest httpRequest)
245 {
246 var authHeader = httpRequest.Headers.Authorization.FirstOrDefault() ?? throw new UnauthorizedAccessException();
247 return new JsonWebToken(authHeader.Replace("Bearer ", ""));
248 }
249
250 public async Task<Activity?> ParseActivity(HttpRequest httpRequest)
251 {
252 httpRequest.EnableBuffering();
253
254 if (httpRequest.Body.CanSeek)
255 {
256 // reset the stream position to the beginning in case it was read before
257 httpRequest.Body.Position = 0;
258 }
259
260 using StreamReader sr = new(httpRequest.Body);
261 var body = await sr.ReadToEndAsync();
262 Activity? activity = JsonSerializer.Deserialize<Activity>(body);
263
264 return activity;
265 }
266}