microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
feature/user-agent-header

Branches

Tags

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

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Apps/App.cs

403lines · modecode

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