forked from BotBuilderCommunity/botbuilder-community-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoogleAdapter.cs
448 lines (382 loc) · 17.4 KB
/
GoogleAdapter.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bot.Builder.Community.Adapters.Google.Integration;
using Bot.Builder.Community.Adapters.Google.Model;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Newtonsoft.Json.Linq;
namespace Bot.Builder.Community.Adapters.Google
{
public class GoogleAdapter : BotAdapter
{
public GoogleWebhookType WebhookType { get; set; } = GoogleWebhookType.DialogFlow;
public bool ShouldEndSessionByDefault { get; set; }
public bool TryConvertFirstActivityAttachmentToGoogleCard { get; set; }
public string ActionInvocationName { get; set; }
public string ActionProjectId { get; set; }
private Dictionary<string, List<Activity>> Responses { get; set; }
public GoogleAdapter()
{
ShouldEndSessionByDefault = true;
TryConvertFirstActivityAttachmentToGoogleCard = false;
}
public new GoogleAdapter Use(IMiddleware middleware)
{
MiddlewareSet.Use(middleware);
return this;
}
public async Task<object> ProcessActivity(Payload actionPayload, BotCallbackHandler callback, string uniqueRequestId = null)
{
TurnContext context = null;
try
{
var activity = RequestToActivity(actionPayload, uniqueRequestId);
BotAssert.ActivityNotNull(activity);
context = new TurnContext(this, activity);
context.TurnState.Add("GoogleUserId", activity.From.Id);
Responses = new Dictionary<string, List<Activity>>();
await base.RunPipelineAsync(context, callback, default(CancellationToken)).ConfigureAwait(false);
var key = $"{activity.Conversation.Id}:{activity.Id}";
try
{
object response = null;
var activities = Responses.ContainsKey(key) ? Responses[key] : new List<Activity>();
if (WebhookType == GoogleWebhookType.DialogFlow)
{
response = CreateDialogFlowResponseFromLastActivity(activities, context);
}
else
{
response = CreateConversationResponseFromLastActivity(activities, context);
}
return response;
}
finally
{
if (Responses.ContainsKey(key))
{
Responses.Remove(key);
}
}
}
catch (Exception ex)
{
await OnTurnError(context, ex);
throw;
}
}
public override Task<ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken CancellationToken)
{
var resourceResponses = new List<ResourceResponse>();
foreach (var activity in activities)
{
switch (activity.Type)
{
case ActivityTypes.Message:
case ActivityTypes.EndOfConversation:
var conversation = activity.Conversation ?? new ConversationAccount();
var key = $"{conversation.Id}:{activity.ReplyToId}";
if (Responses.ContainsKey(key))
{
Responses[key].Add(activity);
}
else
{
Responses[key] = new List<Activity> { activity };
}
break;
default:
Trace.WriteLine(
$"GoogleAdapter.SendActivities(): Activities of type '{activity.Type}' aren't supported.");
break;
}
resourceResponses.Add(new ResourceResponse(activity.Id));
}
return Task.FromResult(resourceResponses.ToArray());
}
private Activity RequestToActivity(Payload actionPayload, string uniqueRequestId = null)
{
var activity = new Activity
{
ChannelId = "google",
ServiceUrl = $"",
Recipient = new ChannelAccount("", "action"),
Conversation = new ConversationAccount(false, "conversation",
$"{actionPayload.Conversation.ConversationId}"),
Type = ActivityTypes.Message,
Text = StripInvocation(actionPayload.Inputs[0]?.RawInputs[0]?.Query, ActionInvocationName),
Id = uniqueRequestId ?? Guid.NewGuid().ToString(),
Timestamp = DateTime.UtcNow,
Locale = actionPayload.User.Locale,
Value = actionPayload.Inputs[0]?.Intent
};
if (!string.IsNullOrEmpty(actionPayload.User.UserId))
{
activity.From = new ChannelAccount(actionPayload.User.UserId, "user");
}
else
{
if (!string.IsNullOrEmpty(actionPayload.User.UserStorage))
{
var values = JObject.Parse(actionPayload.User.UserStorage);
if (values.ContainsKey("UserId"))
{
activity.From = new ChannelAccount(values["UserId"].ToString(), "user");
}
}
else
{
activity.From = new ChannelAccount(Guid.NewGuid().ToString(), "user");
}
}
if (actionPayload.Inputs.FirstOrDefault()?.Arguments?.FirstOrDefault()?.Name == "OPTION")
{
activity.Text = actionPayload.Inputs.First().Arguments.First().TextValue;
}
activity.ChannelData = actionPayload;
return activity;
}
private ConversationResponseBody CreateConversationResponseFromLastActivity(IEnumerable<Activity> activities, ITurnContext context)
{
var activity = activities != null && activities.Any() ? activities.Last() : null;
var response = new ConversationResponseBody();
var userStorage = new JObject
{
{ "UserId", context.TurnState["GoogleUserId"].ToString() }
};
response.UserStorage = userStorage.ToString();
if (activity?.Attachments != null
&& activity.Attachments.FirstOrDefault(a => a.ContentType == SigninCard.ContentType) != null)
{
response.ExpectUserResponse = true;
response.ResetUserStorage = null;
response.ExpectedInputs = new ExpectedInput[]
{
new ExpectedInput()
{
PossibleIntents = new PossibleIntent[]
{
new PossibleIntent()
{
Intent = "actions.intent.SIGN_IN",
InputValueData = new InputValueData()
{
type = "type.googleapis.com/google.actions.v2.SignInValueSpec"
}
},
},
InputPrompt = new InputPrompt()
{
RichInitialPrompt = new RichResponse()
{
Items = new Item[]
{
new SimpleResponse()
{
Content = new SimpleResponseContent()
{
TextToSpeech = "PLACEHOLDER"
}
}
}
}
}
}
};
return response;
}
if (!string.IsNullOrEmpty(activity?.Text))
{
var simpleResponse = new SimpleResponse
{
Content = new SimpleResponseContent
{
DisplayText = activity.Text,
Ssml = activity.Speak,
TextToSpeech = activity.Text
}
};
var responseItems = new List<Item> { simpleResponse };
// Add Google card to response if set
AddCardToResponse(context, ref responseItems, activity);
// Add Media response to response if set
AddMediaResponseToResponse(context, ref responseItems, activity);
if (activity.InputHint == null || activity.InputHint == InputHints.AcceptingInput)
{
activity.InputHint =
ShouldEndSessionByDefault ? InputHints.IgnoringInput : InputHints.ExpectingInput;
}
// check if we should be listening for more input from the user
switch (activity.InputHint)
{
case InputHints.IgnoringInput:
response.ExpectUserResponse = false;
response.FinalResponse = new FinalResponse()
{
RichResponse = new RichResponse() { Items = responseItems.ToArray() }
};
break;
case InputHints.ExpectingInput:
response.ExpectUserResponse = true;
response.ExpectedInputs = new ExpectedInput[]
{
new ExpectedInput()
{
PossibleIntents = new PossibleIntent[]
{
new PossibleIntent() {Intent = "actions.intent.TEXT"},
},
InputPrompt = new InputPrompt()
{
RichInitialPrompt = new RichResponse() {Items = responseItems.ToArray()}
}
}
};
var suggestionChips = AddSuggestionChipsToResponse(context);
if (suggestionChips.Any())
{
response.ExpectedInputs.First().InputPrompt.RichInitialPrompt.Suggestions =
suggestionChips.ToArray();
}
break;
default:
break;
}
}
else
{
response.ExpectUserResponse = false;
}
return response;
}
private DialogFlowResponseBody CreateDialogFlowResponseFromLastActivity(IEnumerable<Activity> activities, ITurnContext context)
{
var activity = activities != null && activities.Any() ? activities.Last() : null;
var response = new DialogFlowResponseBody()
{
Payload = new ResponsePayload()
{
Google = new PayloadContent()
{
RichResponse = new RichResponse(),
ExpectUserResponse = !ShouldEndSessionByDefault
}
}
};
if (!string.IsNullOrEmpty(activity?.Text))
{
var simpleResponse = new SimpleResponse
{
Content = new SimpleResponseContent
{
DisplayText = activity.Text,
Ssml = activity.Speak,
TextToSpeech = activity.Text
}
};
var responseItems = new List<Item> { simpleResponse };
// Add Google card to response if set
AddCardToResponse(context, ref responseItems, activity);
// Add Media response to response if set
AddMediaResponseToResponse(context, ref responseItems, activity);
response.Payload.Google.RichResponse.Items = responseItems.ToArray();
// If suggested actions have been added to outgoing activity
// add these to the response as Google Suggestion Chips
var suggestionChips = AddSuggestionChipsToResponse(context);
if (suggestionChips.Any())
{
response.Payload.Google.RichResponse.Suggestions = suggestionChips.ToArray();
}
if (context.TurnState.ContainsKey("systemIntent"))
{
var optionSystemIntent = context.TurnState.Get<ISystemIntent>("systemIntent");
response.Payload.Google.SystemIntent = optionSystemIntent;
}
// check if we should be listening for more input from the user
switch (activity.InputHint)
{
case InputHints.IgnoringInput:
response.Payload.Google.ExpectUserResponse = false;
break;
case InputHints.ExpectingInput:
response.Payload.Google.ExpectUserResponse = true;
break;
case InputHints.AcceptingInput:
default:
break;
}
}
else
{
response.Payload.Google.ExpectUserResponse = false;
}
return response;
}
private void AddMediaResponseToResponse(ITurnContext context, ref List<Item> responseItems, Activity activity)
{
if (context.TurnState.ContainsKey("GoogleMediaResponse") && context.TurnState["GoogleMediaResponse"] is MediaResponse)
{
responseItems.Add(context.TurnState.Get<MediaResponse>("GoogleMediaResponse"));
}
}
private static List<Suggestion> AddSuggestionChipsToResponse(ITurnContext context)
{
var suggestionChips = new List<Suggestion>();
if (context.TurnState.ContainsKey("GoogleSuggestionChips") && context.TurnState["GoogleSuggestionChips"] is List<Suggestion>)
{
suggestionChips.AddRange(context.TurnState.Get<List<Suggestion>>("GoogleSuggestionChips"));
}
if (context.Activity.SuggestedActions != null && context.Activity.SuggestedActions.Actions.Any())
{
foreach (var suggestion in context.Activity.SuggestedActions.Actions)
{
suggestionChips.Add(new Suggestion { Title = suggestion.Title });
}
}
return suggestionChips;
}
private void AddCardToResponse(ITurnContext context, ref List<Item> responseItems, Activity activity)
{
if (context.TurnState.ContainsKey("GoogleCard") && context.TurnState["GoogleCard"] is GoogleBasicCard)
{
responseItems.Add(context.TurnState.Get<GoogleBasicCard>("GoogleCard"));
}
else if (TryConvertFirstActivityAttachmentToGoogleCard)
{
//TODO: Implement automatic conversion from hero card to Google basic card
//CreateAlexaCardFromAttachment(activity, response);
}
}
private static string StripInvocation(string query, string invocationName)
{
if (query != null && (query.ToLower().StartsWith("talk to") || query.ToLower().StartsWith("speak to")
|| query.ToLower().StartsWith("i want to speak to") ||
query.ToLower().StartsWith("ask")))
{
query = query.ToLower().Replace($"talk to", string.Empty);
query = query.ToLower().Replace($"speak to", string.Empty);
query = query.ToLower().Replace($"I want to speak to", string.Empty);
query = query.ToLower().Replace($"ask", string.Empty);
}
query = query?.TrimStart().TrimEnd();
if (!string.IsNullOrEmpty(invocationName)
&& query.ToLower().StartsWith(invocationName.ToLower()))
{
query = query.ToLower().Replace(invocationName.ToLower(), string.Empty);
}
return query?.TrimStart().TrimEnd();
}
public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
}