-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
TeamsMessagingExtensionsSearchAuthConfigBot.cs
419 lines (369 loc) · 19.4 KB
/
TeamsMessagingExtensionsSearchAuthConfigBot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveCards;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Teams;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Microsoft.Bot.Schema.Teams;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
namespace Microsoft.BotBuilderSamples.Bots
{
public class TeamsMessagingExtensionsSearchAuthConfigBot : TeamsActivityHandler
{
private readonly string _connectionName;
private readonly string _siteUrl;
private readonly UserState _userState;
private readonly IStatePropertyAccessor<string> _userConfigProperty;
public TeamsMessagingExtensionsSearchAuthConfigBot(IConfiguration configuration, UserState userState)
{
_connectionName = configuration["ConnectionName"] ?? throw new NullReferenceException("ConnectionName");
_siteUrl = configuration["SiteUrl"] ?? throw new NullReferenceException("SiteUrl");
_userState = userState ?? throw new NullReferenceException(nameof(userState));
_userConfigProperty = userState.CreateProperty<string>("UserConfiguration");
}
public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
{
await base.OnTurnAsync(turnContext, cancellationToken);
// After the turn is complete, persist any UserState changes.
await _userState.SaveChangesAsync(turnContext);
}
protected async override Task<MessagingExtensionResponse> OnTeamsAppBasedLinkQueryAsync(ITurnContext<IInvokeActivity> turnContext, AppBasedLinkQuery query, CancellationToken cancellationToken)
{
var state = query.State; // Check the state value
var tokenResponse = await GetTokenResponse(turnContext, state, cancellationToken);
if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
{
// There is no token, so the user has not signed in yet.
// Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
var signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false);
return new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "auth",
SuggestedActions = new MessagingExtensionSuggestedAction
{
Actions = new List<CardAction>
{
new CardAction
{
Type = ActionTypes.OpenUrl,
Value = signInLink,
Title = "Bot Service OAuth",
},
},
},
},
};
}
var client = new SimpleGraphClient(tokenResponse.Token);
var profile = await client.GetMyProfile();
var heroCard = new ThumbnailCard
{
Title = "Thumbnail Card",
Text = $"Hello, {profile.DisplayName}",
Images = new List<CardImage> { new CardImage("https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png") },
};
var attachments = new MessagingExtensionAttachment(HeroCard.ContentType, null, heroCard);
var result = new MessagingExtensionResult("list", "result", new[] { attachments });
return new MessagingExtensionResponse(result);
}
protected override async Task<MessagingExtensionResponse> OnTeamsMessagingExtensionConfigurationQuerySettingUrlAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionQuery query, CancellationToken cancellationToken)
{
// The user has requested the Messaging Extension Configuration page.
var escapedSettings = string.Empty;
var userConfigSettings = await _userConfigProperty.GetAsync(turnContext, () => string.Empty);
if (!string.IsNullOrEmpty(userConfigSettings))
{
escapedSettings = Uri.EscapeDataString(userConfigSettings);
}
return new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "config",
SuggestedActions = new MessagingExtensionSuggestedAction
{
Actions = new List<CardAction>
{
new CardAction
{
Type = ActionTypes.OpenUrl,
Value = $"{_siteUrl}/searchSettings.html?settings={escapedSettings}",
},
},
},
},
};
}
protected override async Task OnTeamsMessagingExtensionConfigurationSettingAsync(ITurnContext<IInvokeActivity> turnContext, JObject settings, CancellationToken cancellationToken)
{
// When the user submits the settings page, this event is fired.
var state = settings["state"];
if (state != null)
{
var userConfigSettings = state.ToString();
await _userConfigProperty.SetAsync(turnContext, userConfigSettings, cancellationToken);
}
}
protected override async Task<MessagingExtensionResponse> OnTeamsMessagingExtensionQueryAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionQuery action, CancellationToken cancellationToken)
{
var text = action?.Parameters?[0]?.Name as string ?? string.Empty;
var attachments = new List<MessagingExtensionAttachment>();
var userConfigSettings = await _userConfigProperty.GetAsync(turnContext, () => string.Empty);
if (userConfigSettings.ToUpper().Contains("EMAIL"))
{
// When the Bot Service Auth flow completes, the action.State will contain a magic code used for verification.
var state = action.State; // Check the state value
var tokenResponse = await GetTokenResponse(turnContext, state, cancellationToken);
if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
{
// There is no token, so the user has not signed in yet.
// Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
var signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false);
return new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "auth",
SuggestedActions = new MessagingExtensionSuggestedAction
{
Actions = new List<CardAction>
{
new CardAction
{
Type = ActionTypes.OpenUrl,
Value = signInLink,
Title = "Bot Service OAuth",
},
},
},
},
};
}
var client = new SimpleGraphClient(tokenResponse.Token);
var messages = await client.SearchMailInboxAsync(text);
// Here we construct a ThumbnailCard for every attachment, and provide a HeroCard which will be
// displayed if the selects that item.
attachments = messages.Select(msg => new MessagingExtensionAttachment
{
ContentType = HeroCard.ContentType,
Content = new HeroCard
{
Title = msg.From.EmailAddress.Address,
Subtitle = msg.Subject,
Text = msg.Body.Content,
},
Preview = new ThumbnailCard
{
Title = msg.From.EmailAddress.Address,
Text = $"{msg.Subject}<br />{msg.BodyPreview}",
Images = new List<CardImage>()
{
new CardImage("https://raw.githubusercontent.com/microsoft/botbuilder-samples/master/docs/media/OutlookLogo.jpg", "Outlook Logo"),
},
}.ToAttachment()
}
).ToList();
}
else
{
var packages = await FindPackages(text);
// We take every row of the results and wrap them in cards wrapped in in MessagingExtensionAttachment objects.
// The Preview is optional, if it includes a Tap, that will trigger the OnTeamsMessagingExtensionSelectItemAsync event back on this bot.
attachments = packages.Select(package =>
{
var previewCard = new ThumbnailCard { Title = package.Item1, Tap = new CardAction { Type = "invoke", Value = package } };
if (!string.IsNullOrEmpty(package.Item5))
{
previewCard.Images = new List<CardImage>() { new CardImage(package.Item5, "Icon") };
}
var attachment = new MessagingExtensionAttachment
{
ContentType = HeroCard.ContentType,
Content = new HeroCard { Title = package.Item1 },
Preview = previewCard.ToAttachment()
};
return attachment;
}).ToList();
}
// The list of MessagingExtensionAttachments must we wrapped in a MessagingExtensionResult wrapped in a MessagingExtensionResponse.
return new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "result",
AttachmentLayout = "list",
Attachments = attachments
}
};
}
protected override Task<MessagingExtensionResponse> OnTeamsMessagingExtensionSelectItemAsync(ITurnContext<IInvokeActivity> turnContext, JObject query, CancellationToken cancellationToken)
{
// The Preview card's Tap should have a Value property assigned, this will be returned to the bot in this event.
var (packageId, version, description, projectUrl, iconUrl) = query.ToObject<(string, string, string, string, string)>();
// We take every row of the results and wrap them in cards wrapped in in MessagingExtensionAttachment objects.
// The Preview is optional, if it includes a Tap, that will trigger the OnTeamsMessagingExtensionSelectItemAsync event back on this bot.
var card = new ThumbnailCard
{
Title = $"{packageId}, {version}",
Subtitle = description,
Buttons = new List<CardAction>
{
new CardAction { Type = ActionTypes.OpenUrl, Title = "Nuget Package", Value = $"https://www.nuget.org/packages/{packageId}" },
new CardAction { Type = ActionTypes.OpenUrl, Title = "Project", Value = projectUrl },
},
};
if (!string.IsNullOrEmpty(iconUrl))
{
card.Images = new List<CardImage>() { new CardImage(iconUrl, "Icon") };
}
var attachment = new MessagingExtensionAttachment
{
ContentType = ThumbnailCard.ContentType,
Content = card,
};
return Task.FromResult(new MessagingExtensionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "result",
AttachmentLayout = "list",
Attachments = new List<MessagingExtensionAttachment> { attachment }
}
});
}
protected override Task<MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
{
// This method is to handle the 'Close' button on the confirmation Task Module after the user signs out.
return Task.FromResult(new MessagingExtensionActionResponse());
}
protected override async Task<MessagingExtensionActionResponse> OnTeamsMessagingExtensionFetchTaskAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)
{
if (action.CommandId.ToUpper() == "SHOWPROFILE")
{
var state = action.State; // Check the state value
var tokenResponse = await GetTokenResponse(turnContext, state, cancellationToken);
if (tokenResponse == null || string.IsNullOrEmpty(tokenResponse.Token))
{
// There is no token, so the user has not signed in yet.
// Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions
var signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false);
return new MessagingExtensionActionResponse
{
ComposeExtension = new MessagingExtensionResult
{
Type = "auth",
SuggestedActions = new MessagingExtensionSuggestedAction
{
Actions = new List<CardAction>
{
new CardAction
{
Type = ActionTypes.OpenUrl,
Value = signInLink,
Title = "Bot Service OAuth",
},
},
},
},
};
}
var client = new SimpleGraphClient(tokenResponse.Token);
var profile = await client.GetMyProfile();
return new MessagingExtensionActionResponse
{
Task = new TaskModuleContinueResponse
{
Value = new TaskModuleTaskInfo
{
Card = GetProfileCard(profile),
Height = 250,
Width = 400,
Title = "Adaptive Card: Inputs",
},
},
};
}
if (action.CommandId.ToUpper() == "SIGNOUTCOMMAND")
{
var userTokenClient = turnContext.TurnState.Get<UserTokenClient>();
await userTokenClient.SignOutUserAsync(turnContext.Activity.From.Id, _connectionName, turnContext.Activity.ChannelId, cancellationToken).ConfigureAwait(false);
return new MessagingExtensionActionResponse
{
Task = new TaskModuleContinueResponse
{
Value = new TaskModuleTaskInfo
{
Card = new Attachment
{
Content = new AdaptiveCard(new AdaptiveSchemaVersion("1.0"))
{
Body = new List<AdaptiveElement>() { new AdaptiveTextBlock() { Text = "You have been signed out." } },
Actions = new List<AdaptiveAction>() { new AdaptiveSubmitAction() { Title = "Close" } },
},
ContentType = AdaptiveCard.ContentType,
},
Height = 200,
Width = 400,
Title = "Adaptive Card: Inputs",
},
},
};
}
return null;
}
private async Task<string> GetSignInLinkAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
var userTokenClient = turnContext.TurnState.Get<UserTokenClient>();
var resource = await userTokenClient.GetSignInResourceAsync(_connectionName, turnContext.Activity as Activity, null, cancellationToken).ConfigureAwait(false);
return resource.SignInLink;
}
private static Attachment GetProfileCard(Graph.User profile)
{
var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
card.Body.Add(new AdaptiveTextBlock()
{
Text = $"Hello, {profile.DisplayName}",
Size = AdaptiveTextSize.ExtraLarge
});
card.Body.Add(new AdaptiveImage()
{
Url = new Uri("http://adaptivecards.io/content/cats/1.png")
});
return new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card,
};
}
// Generate a set of substrings to illustrate the idea of a set of results coming back from a query.
private async Task<IEnumerable<(string, string, string, string, string)>> FindPackages(string text)
{
var obj = JObject.Parse(await (new HttpClient()).GetStringAsync($"https://azuresearch-usnc.nuget.org/query?q=id:{text}&prerelease=true"));
return obj["data"].Select(item => (item["id"].ToString(), item["version"].ToString(), item["description"].ToString(), item["projectUrl"]?.ToString(), item["iconUrl"]?.ToString()));
}
private async Task<TokenResponse> GetTokenResponse(ITurnContext<IInvokeActivity> turnContext, string state, CancellationToken cancellationToken)
{
var magicCode = string.Empty;
if (!string.IsNullOrEmpty(state))
{
if (int.TryParse(state, out var parsed))
{
magicCode = parsed.ToString();
}
}
var userTokenClient = turnContext.TurnState.Get<UserTokenClient>();
var tokenResponse = await userTokenClient.GetUserTokenAsync(turnContext.Activity.From.Id, _connectionName, turnContext.Activity.ChannelId, magicCode, cancellationToken).ConfigureAwait(false);
return tokenResponse;
}
}
}