-
Notifications
You must be signed in to change notification settings - Fork 170
/
ManagementExtensions.cs
419 lines (349 loc) · 16.2 KB
/
ManagementExtensions.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
using System;
using System.Collections.Generic;
using System.Linq;
using Bot.Builder.Community.Cards.Management.Tree;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Bot.Builder.Community.Cards.Management
{
public static class ManagementExtensions
{
public static void SeparateAttachments(this List<Activity> activities)
{
BotAssert.ActivityListNotNull(activities);
// We need to iterate backwards because we're potentially changing the length of the list
for (int i = activities.Count() - 1; i > -1; i--)
{
var activity = activities[i];
var attachments = activity.Attachments;
var attachmentCount = attachments?.Count();
var hasText = activity.Text != null;
// Should the activity be split into multiple activities?
if ((attachmentCount > 0 && hasText)
|| (attachmentCount > 1 && activity.AttachmentLayout != AttachmentLayoutTypes.Carousel))
{
var separateActivities = new List<Activity>();
// Prepare the activity for serialization by removing its attachments
activity.Attachments = null;
// If an activity ID is present then it should be removed
// because two activities shouldn't have the same ID
activity.Id = null;
var jss = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.All,
};
// Serialize the activity to JSON so it can be cloned
var json = JsonConvert.SerializeObject(activity, jss);
// Leave the original activity intact just in case it's needed later
activity.Attachments = attachments;
if (hasText)
{
var textActivity = JsonConvert.DeserializeObject<Activity>(json, jss);
separateActivities.Add(textActivity);
}
// AttachmentLayoutTypes.List is the default in the sense that
// ABS interprets any string other that "carousel" as "list"
if (activity.AttachmentLayout == AttachmentLayoutTypes.Carousel)
{
var carouselActivity = JsonConvert.DeserializeObject<Activity>(json, jss);
carouselActivity.Text = null;
carouselActivity.Attachments = attachments;
separateActivities.Add(carouselActivity);
}
else
{
foreach (var attachment in attachments)
{
var attachmentActivity = JsonConvert.DeserializeObject<Activity>(json, jss);
attachmentActivity.Text = null;
attachmentActivity.Attachments = new List<Attachment> { attachment };
separateActivities.Add(attachmentActivity);
}
}
activities.RemoveAt(i);
activities.InsertRange(i, separateActivities);
}
}
}
/// <summary>
/// This will convert Adaptive Cards to JObject instances to work around this issue:
/// https://github.com/microsoft/AdaptiveCards/issues/2148.
/// </summary>
/// <param name="activities">A batch of activities.</param>
public static void ConvertAdaptiveCards(this IEnumerable<IMessageActivity> activities)
{
if (activities is null)
{
throw new ArgumentNullException(nameof(activities));
}
CardTree.Recurse(activities, (Attachment attachment) =>
{
if (attachment.ContentType == ContentTypes.AdaptiveCard)
{
attachment.Content = attachment.Content.ToJObject();
}
});
}
public static void ApplyIdsToBatch(this IEnumerable<IMessageActivity> activities, DataIdOptions options = null)
{
if (activities is null)
{
throw new ArgumentNullException(nameof(activities));
}
CardTree.ApplyIds(activities, options);
}
public static ISet<DataId> GetIdsFromBatch(this IEnumerable<IMessageActivity> activities)
{
if (activities is null)
{
throw new ArgumentNullException(nameof(activities));
}
return CardTree.GetIds(activities);
}
public static void AdaptOutgoingCardActions(this IEnumerable<IMessageActivity> activities, string channelId = null)
{
if (activities is null)
{
throw new ArgumentNullException(nameof(activities));
}
foreach (var activity in activities)
{
var activityChannelId = channelId ?? activity.ChannelId;
CardTree.Recurse(activity, (CardAction action) =>
{
var text = action.Text;
var value = action.Value;
void EnsureText()
{
if (text == null)
{
action.Text = value.SerializeIfNeeded();
}
}
void EnsureValue()
{
if (value == null)
{
action.Value = text;
}
}
void EnsureStringValue()
{
if (!(value is string))
{
if (value == null && text != null)
{
action.Value = text;
}
else
{
action.Value = value.SerializeIfNeeded();
}
}
}
void EnsureObjectValue()
{
// Check if value is null or otherwise primitive
if (value.ToJObject() is null)
{
if (value is string stringValue && stringValue.TryParseJObject() is JObject parsedValue)
{
action.Value = parsedValue;
}
else if (text.TryParseJObject() is JObject parsedText)
{
action.Value = parsedText;
}
}
}
if (action.Type == ActionTypes.MessageBack)
{
switch (activityChannelId)
{
case Channels.Cortana:
case Channels.Skype:
// MessageBack does not work on these channels
action.Type = ActionTypes.PostBack;
break;
case Channels.Directline:
case Channels.Emulator:
case Channels.Line:
case Channels.Webchat:
EnsureValue();
break;
case Channels.Email:
case Channels.Slack:
case Channels.Telegram:
EnsureText();
break;
case Channels.Facebook:
EnsureStringValue();
break;
case Channels.Msteams:
EnsureObjectValue();
break;
}
}
// Using if instead of else-if so this block can be executed in addition to the previous one
if (action.Type == ActionTypes.PostBack)
{
switch (activityChannelId)
{
case Channels.Cortana:
case Channels.Facebook:
case Channels.Slack:
case Channels.Telegram:
EnsureStringValue();
break;
case Channels.Directline:
case Channels.Email:
case Channels.Emulator:
case Channels.Line:
case Channels.Skype:
case Channels.Webchat:
EnsureValue();
break;
case Channels.Msteams:
EnsureObjectValue();
break;
}
}
if (action.Type == ActionTypes.ImBack)
{
switch (activityChannelId)
{
case Channels.Cortana:
case Channels.Directline:
case Channels.Emulator:
case Channels.Facebook:
case Channels.Msteams:
case Channels.Skype:
case Channels.Slack:
case Channels.Telegram:
case Channels.Webchat:
EnsureStringValue();
break;
case Channels.Email:
case Channels.Line:
EnsureValue();
break;
}
}
});
}
}
/// <summary>
/// This will return null if the incoming activity is not from a button.
/// The returned value is guaranteed to not be a string.
/// </summary>
/// <param name="turnContext">The turn context.</param>
/// <returns>A button's action data if valid, null otherwise.</returns>
public static object GetIncomingActionData(this ITurnContext turnContext)
{
BotAssert.ContextNotNull(turnContext);
var activity = turnContext.Activity;
if (activity is null || activity.Type != ActivityTypes.Message)
{
return null;
}
var text = activity.Text;
var parsedText = text.TryParseJObject();
var value = activity.Value.ToJObject(true);
var channelData = activity.ChannelData.ToJObject(true); // Channel data will have been serialized into a string in Kik
var entities = activity.Entities;
var incomingData = value;
// Many channels have button responses that are hard to distinguish from user-entered text.
// A common theme is that button responses often have a property in channel data that isn't
// present in a typed user-to-bot message, so this local function helps check for that.
void CheckForChannelDataProperty(string propName, JObject newResult = null)
{
if (channelData?.GetValue(propName) != null)
{
incomingData = newResult ?? parsedText;
}
}
switch (activity.ChannelId)
{
case Channels.Cortana:
// In Cortana, the only defining characteristic of button responses
// is that they won't have an "Intent" entity.
// This if statement uses `!= true` because we're interpreting a null entities list
// as confirmation of a missing "Intent" entity.
if (entities?.Any(entity => entity.Type.EqualsCI(EntityTypes.Intent)) != true)
{
incomingData = parsedText;
}
break;
case Channels.Directline:
case Channels.Emulator:
case Channels.Webchat:
// In Direct Line / Web Chat, button responses can be recognized by a property of channel data.
CheckForChannelDataProperty(ChannelData.PostBack, value);
CheckForChannelDataProperty(ChannelData.MessageBack, value);
break;
case Channels.Kik:
// In Kik, button responses can be recognized by a property of channel data.
// Note that this condition will be true because metadata will not be a C# null,
// even though it's a "null" JValue.
CheckForChannelDataProperty(ChannelData.Metadata);
break;
case Channels.Line:
// In LINE, button responses can be recognized by a property of channel data.
CheckForChannelDataProperty(ChannelData.LinePostback);
break;
case Channels.Skype:
// In Skype, the only defining characteristic of button responses
// is that the channel data text does not match the activity text.
// This if statement uses `== false` because if the channel data is null or has no text property
// then we're interpreting that to mean that this is not a button response.
if (channelData?.GetValue(ChannelData.Text)?.ToString().Equals(text) == false)
{
incomingData = parsedText;
}
break;
case Channels.Slack:
// In Slack, button responses can be recognized by a property of channel data.
CheckForChannelDataProperty(ChannelData.Payload);
break;
case Channels.Telegram:
// In Telegram, button responses can be recognized by a property of channel data.
CheckForChannelDataProperty(ChannelData.CallbackQuery);
break;
}
// Teams and Facebook values don't need to be adapted any further
return incomingData;
}
internal static void ApplyIdsToActionData(this JObject data, DataIdOptions options)
{
foreach (var kvp in options.GetIds())
{
var type = kvp.Key;
if (options.Overwrite || data.GetIdFromActionData(type) is null)
{
var id = kvp.Value;
if (id is null)
{
if (type == DataIdTypes.Action)
{
// Only generate an ID for the action
id = DataId.GenerateValue(DataIdTypes.Action);
}
else
{
// If any other ID's are null,
// don't apply them to the data
continue;
}
}
data[DataId.GetKey(type)] = id;
}
}
}
internal static string GetIdFromActionData(this JObject data, string type = DataIdTypes.Action)
=> data?.GetValue(DataId.GetKey(type)) is JToken id ? id.ToString() : null;
}
}