microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
91427f12753b43af544fcd5f77244b200b039c87

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Apps/App.cs

420lines · 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 = Assembly.GetExecutingAssembly().GetName().Version?.ToString();
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])
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 if (Id is null)
178 {
179 throw new InvalidOperationException("app not started");
180 }
181
182 var reference = new ConversationReference()
183 {
184 ChannelId = ChannelId.MsTeams,
185 ServiceUrl = serviceUrl ?? Api.ServiceUrl,
186 Bot = new()
187 {
188 Id = Id,
189 Name = Name,
190 Role = Role.Bot
191 },
192 Conversation = new()
193 {
194 Id = conversationId,
195 Type = conversationType ?? ConversationType.Personal
196 }
197 };
198
199 var sender = Plugins.Where(plugin => plugin is ISenderPlugin).Select(plugin => plugin as ISenderPlugin).First();
200
201 if (sender is null)
202 {
203 throw new Exception("no plugin that can send activities was found");
204 }
205
206 var res = await sender.Send(activity, reference, cancellationToken);
207
208 await Events.Emit(
209 sender,
210 EventType.ActivitySent,
211 new ActivitySentEvent() { Activity = res },
212 cancellationToken
213 );
214
215 return res;
216 }
217
218 /// <summary>
219 /// send a message activity to the conversation
220 /// </summary>
221 /// <param name="text">the text to send</param>
222 public async Task<MessageActivity> Send(string conversationId, string text, ConversationType? conversationType = null, string? serviceUrl = null, CancellationToken cancellationToken = default)
223 {
224 return await Send(conversationId, new MessageActivity(text), conversationType, serviceUrl, cancellationToken);
225 }
226
227 /// <summary>
228 /// send a message activity with a card attachment
229 /// </summary>
230 /// <param name="card">the card to send as an attachment</param>
231 public async Task<MessageActivity> Send(string conversationId, Cards.AdaptiveCard card, ConversationType? conversationType = null, string? serviceUrl = null, CancellationToken cancellationToken = default)
232 {
233 return await Send(conversationId, new MessageActivity().AddAttachment(card), conversationType, serviceUrl, cancellationToken);
234 }
235
236 /// <summary>
237 /// process an activity
238 /// </summary>
239 /// <param name="sender">the plugin to use</param>
240 /// <param name="token">the request token</param>
241 /// <param name="activity">the inbound activity</param>
242 /// <param name="cancellationToken">the cancellation token</param>
243 public async Task<Response> Process(ISenderPlugin sender, IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default)
244 {
245 return await Process(sender, new()
246 {
247 Token = token,
248 Activity = activity,
249 Extra = extra
250 }, cancellationToken);
251 }
252
253 /// <summary>
254 /// process an activity
255 /// </summary>
256 /// <param name="sender">the plugin to use</param>
257 /// <param name="token">the request token</param>
258 /// <param name="activity">the inbound activity</param>
259 /// <param name="cancellationToken">the cancellation token</param>
260 /// <exception cref="Exception"></exception>
261 public Task<Response> Process(string sender, IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default)
262 {
263 var plugin = ((ISenderPlugin?)GetPlugin(sender)) ?? throw new Exception($"sender plugin '{sender}' not found");
264 return Process(plugin, token, activity, extra, cancellationToken);
265 }
266
267 /// <summary>
268 /// process an activity
269 /// </summary>
270 /// <param name="token">the request token</param>
271 /// <param name="activity">the inbound activity</param>
272 /// <param name="cancellationToken">the cancellation token</param>
273 /// <exception cref="Exception"></exception>
274 public Task<Response> Process<TPlugin>(IToken token, IActivity activity, IDictionary<string, object?>? extra = null, CancellationToken cancellationToken = default) where TPlugin : ISenderPlugin
275 {
276 var plugin = GetPlugin<TPlugin>() ?? throw new Exception($"sender plugin '{typeof(TPlugin).Name}' not found");
277 return Process(plugin, token, activity, extra, cancellationToken);
278 }
279
280 /// <summary>
281 /// process an activity
282 /// </summary>
283 /// <param name="sender">the plugin to use</param>
284 /// <param name="@event">the activity event</param>
285 /// <param name="cancellationToken">the cancellation token</param>
286 private async Task<Response> Process(ISenderPlugin sender, ActivityEvent @event, CancellationToken cancellationToken = default)
287 {
288 var start = DateTime.UtcNow;
289 var routes = Router.Select(@event.Activity);
290 JsonWebToken? userToken = null;
291
292 var api = new ApiClient(Api);
293
294 try
295 {
296 var tokenResponse = await api.Users.Token.GetAsync(new()
297 {
298 UserId = @event.Activity.From.Id,
299 ChannelId = @event.Activity.ChannelId,
300 ConnectionName = OAuth.DefaultConnectionName
301 });
302
303 userToken = new JsonWebToken(tokenResponse);
304 }
305 catch { }
306
307 var path = @event.Activity.GetPath();
308 Logger.Debug(path);
309
310 var reference = new ConversationReference()
311 {
312 ServiceUrl = @event.Activity.ServiceUrl ?? @event.Token.ServiceUrl,
313 ChannelId = @event.Activity.ChannelId,
314 Bot = @event.Activity.Recipient,
315 User = @event.Activity.From,
316 Locale = @event.Activity.Locale,
317 Conversation = @event.Activity.Conversation,
318 };
319
320 object? data = null;
321 var i = -1;
322 async Task<object?> Next(IContext<IActivity> context)
323 {
324 if (i + 1 == routes.Count) return data;
325
326 i++;
327 var res = await routes[i].Invoke(context);
328
329 if (res is not null)
330 data = res;
331
332 return res;
333 }
334
335 var stream = sender.CreateStream(reference, cancellationToken);
336 var context = new Context<IActivity>(sender, stream)
337 {
338 AppId = @event.Token.AppId ?? Id ?? string.Empty,
339 TenantId = @event.Token.TenantId ?? string.Empty,
340 Log = Logger.Child(path),
341 Storage = Storage,
342 Api = api,
343 Activity = @event.Activity,
344 Ref = reference,
345 IsSignedIn = userToken is not null,
346 OnNext = Next,
347 Extra = @event.Extra ?? new Dictionary<string, object?>(),
348 UserGraphToken = userToken,
349 CancellationToken = cancellationToken,
350 ConnectionName = OAuth.DefaultConnectionName,
351 OnActivitySent = async (activity, context) =>
352 {
353 await Events.Emit(
354 context.Sender,
355 EventType.ActivitySent,
356 new ActivitySentEvent() { Activity = activity },
357 context.CancellationToken
358 );
359 }
360 };
361
362 stream.OnChunk += async activity =>
363 {
364 await Events.Emit(
365 sender,
366 EventType.ActivitySent,
367 new ActivitySentEvent() { Activity = activity },
368 cancellationToken
369 );
370 };
371
372 try
373 {
374 if (@event.Services is not null)
375 {
376 var accessor = (IContext.Accessor?)@event.Services.GetService(typeof(IContext.Accessor));
377
378 if (accessor is not null)
379 {
380 accessor.Value = context;
381 }
382 }
383
384 foreach (var plugin in Plugins)
385 {
386 await plugin.OnActivity(this, sender, @event, cancellationToken);
387 }
388
389 var res = await Next(context);
390 await stream.Close();
391
392 var response = res is Response value
393 ? value
394 : new Response(System.Net.HttpStatusCode.OK, res);
395
396 response.Meta.Routes = i + 1;
397 response.Meta.Elapse = (DateTime.UtcNow - start).Milliseconds;
398
399 await Events.Emit(
400 sender,
401 EventType.ActivityResponse,
402 new ActivityResponseEvent() { Response = response },
403 cancellationToken
404 );
405
406 return response;
407 }
408 catch (Exception ex)
409 {
410 await Events.Emit(
411 sender,
412 EventType.Error,
413 new ErrorEvent() { Exception = ex, Context = context.ToActivityType<IActivity>() },
414 cancellationToken
415 );
416
417 return new Response(System.Net.HttpStatusCode.InternalServerError);
418 }
419 }
420}