microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/setup-copilot-instructions

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Apps/App.cs

454lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System.Reflection;
5
6using Microsoft.Teams.Api;
7using Microsoft.Teams.Api.Activities;
8using Microsoft.Teams.Api.Auth;
9using Microsoft.Teams.Api.Clients;
10using Microsoft.Teams.Apps.Activities.Invokes;
11using Microsoft.Teams.Apps.Events;
12using Microsoft.Teams.Apps.Plugins;
13using Microsoft.Teams.Common.Http;
14using Microsoft.Teams.Common.Logging;
15using Microsoft.Teams.Common.Storage;
16
17namespace Microsoft.Teams.Apps;
18
19public partial class App
20{
21 public static AppBuilder Builder(AppOptions? options = null) => new(options);
22
23 /// <summary>
24 /// the apps id
25 /// </summary>
26 public string? Id => Token?.AppId;
27
28 /// <summary>
29 /// the apps name
30 /// </summary>
31 public string? Name => Token?.AppDisplayName;
32
33 public Status? Status { get; internal set; }
34 public ILogger Logger { get; }
35 public IStorage<string, object> Storage { get; }
36 public ApiClient Api { get; internal set; }
37 public IHttpClient Client { get; }
38 public IHttpCredentials? Credentials { get; }
39 public IToken? Token { get; internal set; }
40 public OAuthSettings OAuth { get; internal set; }
41
42 internal IHttpClient TokenClient { get; set; }
43 internal IServiceProvider? Provider { get; set; }
44 internal IContainer Container { get; set; }
45 internal string UserAgent
46 {
47 get
48 {
49 var version = ThisAssembly.AssemblyFileVersion;
50 version ??= "0.0.0";
51 return $"teams.net[apps]/{version}";
52 }
53 }
54
55 public App(AppOptions? options = null)
56 {
57 Logger = options?.Logger ?? new ConsoleLogger();
58 Storage = options?.Storage ?? new LocalStorage<object>();
59 Credentials = options?.Credentials;
60 Plugins = options?.Plugins ?? [];
61 OAuth = options?.OAuth ?? new OAuthSettings();
62 Provider = options?.Provider;
63
64 TokenClient = new Common.Http.HttpClient();
65 Client = options?.Client ?? options?.ClientFactory?.CreateClient() ?? new Common.Http.HttpClient();
66 Client.Options.AddUserAgent(UserAgent);
67 Client.Options.TokenFactory ??= () =>
68 {
69 if (Credentials is not null)
70 {
71 if (Token is null)
72 {
73 var res = Api!.Bots.Token.GetAsync(Credentials, TokenClient)
74 .ConfigureAwait(false)
75 .GetAwaiter()
76 .GetResult();
77
78 Token = new JsonWebToken(res.AccessToken);
79 }
80
81 if (Token.IsExpired)
82 {
83 var res = Credentials.Resolve(TokenClient, [.. Token.Scopes.DefaultIfEmpty(BotTokenClient.BotScope)])
84 .ConfigureAwait(false)
85 .GetAwaiter()
86 .GetResult();
87
88 Token = new JsonWebToken(res.AccessToken);
89 }
90 }
91
92 return Token;
93 };
94
95 Api = new ApiClient("https://smba.trafficmanager.net/teams/", Client);
96 Container = new Container();
97 Container.Register(Logger);
98 Container.Register(Storage);
99 Container.Register(Client);
100 Container.Register(Api);
101 Container.Register<IHttpCredentials>(new FactoryProvider(() => Credentials));
102 Container.Register("AppId", new FactoryProvider(() => Id));
103 Container.Register("AppName", new FactoryProvider(() => Name));
104 Container.Register("Token", new FactoryProvider(() => Token));
105
106 this.OnTokenExchange(OnTokenExchangeActivity);
107 this.OnVerifyState(OnVerifyStateActivity);
108 this.OnError(OnErrorEvent);
109 this.OnActivitySent(OnActivitySentEvent);
110 this.OnActivityResponse(OnActivityResponseEvent);
111
112 Events.On(EventType.Activity, (plugin, @event, token) =>
113 {
114 return OnActivityEvent((ISenderPlugin)plugin, (ActivityEvent)@event, token);
115 });
116
117 Status = Apps.Status.Ready;
118 }
119
120 /// <summary>
121 /// start the app
122 /// </summary>
123 public async Task Start(CancellationToken cancellationToken = default)
124 {
125 try
126 {
127 foreach (var plugin in Plugins)
128 {
129 Inject(plugin);
130 }
131
132 if (Credentials is not null)
133 {
134 try
135 {
136 var res = await Api.Bots.Token.GetAsync(Credentials, TokenClient);
137 Token = new JsonWebToken(res.AccessToken);
138 }
139 catch (Exception ex)
140 {
141 Logger.Error("Failed to get bot token on app startup.", ex);
142 }
143 }
144
145 Logger.Debug(Id);
146 Logger.Debug(Name);
147
148 foreach (var plugin in Plugins)
149 {
150 await plugin.OnInit(this, cancellationToken);
151 }
152
153 foreach (var plugin in Plugins)
154 {
155 await plugin.OnStart(this, cancellationToken);
156 }
157
158 Status = Apps.Status.Started;
159 }
160 catch (Exception ex)
161 {
162 Status = Apps.Status.Stopped;
163 await Events.Emit(
164 null!,
165 EventType.Error,
166 new ErrorEvent() { Exception = ex }
167 );
168 }
169 }
170
171 /// <summary>
172 /// send an activity to the conversation
173 /// </summary>
174 /// <param name="activity">activity activity to send</param>
175 public async Task<T> Send<T>(string conversationId, T activity, ConversationType? conversationType = null, string? serviceUrl = null, CancellationToken cancellationToken = default) where T : IActivity
176 {
177 return await Send(conversationId, activity, conversationType, serviceUrl, false, cancellationToken);
178 }
179
180 /// <summary>
181 /// send an activity to the conversation
182 /// </summary>
183 /// <param name="activity">activity activity to send</param>
184 /// <param name="isTargeted">when true, sends the message privately to the specified recipient; when false, sends to all conversation participants</param>
185 /// <remarks>
186 /// <para>Targeted messages are delivered privately to the recipient specified in the activity's Recipient property.</para>
187 /// <para>The <paramref name="isTargeted"/> parameter is in preview.</para>
188 /// </remarks>
189 public async Task<T> Send<T>(string conversationId, T activity, ConversationType? conversationType, string? serviceUrl, bool isTargeted = false, CancellationToken cancellationToken = default) where T : IActivity
190 {
191 if (Id is null)
192 {
193 throw new InvalidOperationException("app not started");
194 }
195
196 if (isTargeted && activity.Recipient is null)
197 {
198 throw new ArgumentException("activity.Recipient is required for targeted messages", nameof(activity));
199 }
200
201 var reference = new ConversationReference()
202 {
203 ChannelId = ChannelId.MsTeams,
204 ServiceUrl = serviceUrl ?? Api.ServiceUrl,
205 Bot = new()
206 {
207 Id = Id,
208 Name = Name,
209 Role = Role.Bot
210 },
211 User = isTargeted ? activity.Recipient : null,
212 Conversation = new()
213 {
214 Id = conversationId,
215 Type = conversationType ?? ConversationType.Personal
216 }
217 };
218
219 var sender = Plugins.Where(plugin => plugin is ISenderPlugin).Select(plugin => plugin as ISenderPlugin).First();
220
221 if (sender is null)
222 {
223 throw new Exception("no plugin that can send activities was found");
224 }
225
226 var res = await sender.Send(activity, reference, isTargeted, cancellationToken);
227
228 await Events.Emit(
229 sender,
230 EventType.ActivitySent,
231 new ActivitySentEvent() { Activity = res },
232 cancellationToken
233 );
234
235 return res;
236 }
237
238 /// <summary>
239 /// send a message activity to the conversation
240 /// </summary>
241 /// <param name="text">the text to send</param>
242 public async Task<MessageActivity> Send(string conversationId, string text, ConversationType? conversationType = null, string? serviceUrl = null, CancellationToken cancellationToken = default)
243 {
244 return await Send(conversationId, new MessageActivity(text), conversationType, serviceUrl, false, cancellationToken);
245 }
246
247 /// <summary>
248 /// send a message activity to the conversation
249 /// </summary>
250 /// <param name="text">the text to send</param>
251 /// <param name="isTargeted">when true, sends the message privately to the specified recipient; when false, sends to all conversation participants</param>
252 /// <remarks>
253 /// <para>Targeted messages are delivered privately to the recipient specified in the activity's Recipient property.</para>
254 /// <para>The <paramref name="isTargeted"/> parameter is in preview.</para>
255 /// </remarks>
256 public async Task<MessageActivity> Send(string conversationId, string text, ConversationType? conversationType, string? serviceUrl, bool isTargeted = false, CancellationToken cancellationToken = default)
257 {
258 return await Send(conversationId, new MessageActivity(text), conversationType, serviceUrl, isTargeted, cancellationToken);
259 }
260
261 /// <summary>
262 /// send a message activity with a card attachment
263 /// </summary>
264 /// <param name="card">the card to send as an attachment</param>
265 public async Task<MessageActivity> Send(string conversationId, Cards.AdaptiveCard card, ConversationType? conversationType = null, string? serviceUrl = null, CancellationToken cancellationToken = default)
266 {
267 return await Send(conversationId, new MessageActivity().AddAttachment(card), conversationType, serviceUrl, false, cancellationToken);
268 }
269
270 /// <summary>
271 /// send a message activity with a card attachment
272 /// </summary>
273 /// <param name="card">the card to send as an attachment</param>
274 /// <param name="isTargeted">when true, sends the message privately to the specified recipient; when false, sends to all conversation participants</param>
275 /// <remarks>
276 /// <para>Targeted messages are delivered privately to the recipient specified in the activity's Recipient property.</para>
277 /// <para>The <paramref name="isTargeted"/> parameter is in preview.</para>
278 /// </remarks>
279 public async Task<MessageActivity> Send(string conversationId, Cards.AdaptiveCard card, ConversationType? conversationType, string? serviceUrl, bool isTargeted = false, CancellationToken cancellationToken = default)
280 {
281 return await Send(conversationId, new MessageActivity().AddAttachment(card), conversationType, serviceUrl, isTargeted, cancellationToken);
282 }
283
284 /// <summary>
285 /// process an activity
286 /// </summary>
287 /// <param name="sender">the plugin to use</param>
288 /// <param name="token">the request token</param>
289 /// <param name="activity">the inbound activity</param>
290 /// <param name="cancellationToken">the cancellation token</param>
291 public async Task<Response> Process(ISenderPlugin sender, IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default)
292 {
293 return await Process(sender, new()
294 {
295 Token = token,
296 Activity = activity,
297 Extra = extra
298 }, cancellationToken);
299 }
300
301 /// <summary>
302 /// process an activity
303 /// </summary>
304 /// <param name="sender">the plugin to use</param>
305 /// <param name="token">the request token</param>
306 /// <param name="activity">the inbound activity</param>
307 /// <param name="cancellationToken">the cancellation token</param>
308 /// <exception cref="Exception"></exception>
309 public Task<Response> Process(string sender, IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default)
310 {
311 var plugin = ((ISenderPlugin?)GetPlugin(sender)) ?? throw new Exception($"sender plugin '{sender}' not found");
312 return Process(plugin, token, activity, extra, cancellationToken);
313 }
314
315 /// <summary>
316 /// process an activity
317 /// </summary>
318 /// <param name="token">the request token</param>
319 /// <param name="activity">the inbound activity</param>
320 /// <param name="cancellationToken">the cancellation token</param>
321 /// <exception cref="Exception"></exception>
322 public Task<Response> Process<TPlugin>(IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default) where TPlugin : ISenderPlugin
323 {
324 var plugin = GetPlugin<TPlugin>() ?? throw new Exception($"sender plugin '{typeof(TPlugin).Name}' not found");
325 return Process(plugin, token, activity, extra, cancellationToken);
326 }
327
328 /// <summary>
329 /// process an activity
330 /// </summary>
331 /// <param name="sender">the plugin to use</param>
332 /// <param name="@event">the activity event</param>
333 /// <param name="cancellationToken">the cancellation token</param>
334 private async Task<Response> Process(ISenderPlugin sender, ActivityEvent @event, CancellationToken cancellationToken = default)
335 {
336 var start = DateTime.UtcNow;
337 var routes = Router.Select(@event.Activity);
338 JsonWebToken? userToken = null;
339
340 var api = new ApiClient(Api);
341
342 try
343 {
344 var tokenResponse = await api.Users.Token.GetAsync(new()
345 {
346 UserId = @event.Activity.From.Id,
347 ChannelId = @event.Activity.ChannelId,
348 ConnectionName = OAuth.DefaultConnectionName
349 });
350
351 userToken = new JsonWebToken(tokenResponse);
352 }
353 catch { }
354
355 var path = @event.Activity.GetPath();
356 Logger.Debug(path);
357
358 var reference = new ConversationReference()
359 {
360 ServiceUrl = @event.Activity.ServiceUrl ?? @event.Token.ServiceUrl,
361 ChannelId = @event.Activity.ChannelId,
362 Bot = @event.Activity.Recipient,
363 User = @event.Activity.From,
364 Locale = @event.Activity.Locale,
365 Conversation = @event.Activity.Conversation,
366 };
367
368 object? data = null;
369 var i = -1;
370 async Task<object?> Next(IContext<IActivity> context)
371 {
372 if (i + 1 == routes.Count) return data;
373
374 i++;
375 var res = await routes[i].Invoke(context);
376
377 if (res is not null)
378 data = res;
379
380 return res;
381 }
382
383 var stream = sender.CreateStream(reference, cancellationToken);
384 var context = new Context<IActivity>(sender, stream)
385 {
386 AppId = @event.Token.AppId ?? Id ?? string.Empty,
387 TenantId = @event.Token.TenantId ?? string.Empty,
388 Log = Logger.Child(path),
389 Storage = Storage,
390 Api = api,
391 Activity = @event.Activity,
392 Ref = reference,
393 IsSignedIn = userToken is not null,
394 OnNext = Next,
395 Extra = @event.Extra ?? new Dictionary<string, object?>(),
396 UserGraphToken = userToken,
397 CancellationToken = cancellationToken,
398 ConnectionName = OAuth.DefaultConnectionName,
399 OnActivitySent = async (activity, context) =>
400 {
401 await Events.Emit(
402 context.Sender,
403 EventType.ActivitySent,
404 new ActivitySentEvent() { Activity = activity },
405 context.CancellationToken
406 );
407 }
408 };
409
410 stream.OnChunk += async activity =>
411 {
412 await Events.Emit(
413 sender,
414 EventType.ActivitySent,
415 new ActivitySentEvent() { Activity = activity },
416 cancellationToken
417 );
418 };
419
420 if (@event.Services is not null)
421 {
422 var accessor = (IContext.Accessor?)@event.Services.GetService(typeof(IContext.Accessor));
423
424 if (accessor is not null)
425 {
426 accessor.Value = context;
427 }
428 }
429
430 foreach (var plugin in Plugins)
431 {
432 await plugin.OnActivity(this, sender, @event, cancellationToken);
433 }
434
435 var res = await Next(context);
436 await stream.Close();
437
438 var response = res is Response value
439 ? value
440 : new Response(System.Net.HttpStatusCode.OK, res);
441
442 response.Meta.Routes = i + 1;
443 response.Meta.Elapse = (DateTime.UtcNow - start).Milliseconds;
444
445 await Events.Emit(
446 sender,
447 EventType.ActivityResponse,
448 new ActivityResponseEvent() { Response = response },
449 cancellationToken
450 );
451
452 return response;
453 }
454}