forked from BotBuilderCommunity/botbuilder-community-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlexaAdapter.cs
173 lines (143 loc) · 6.92 KB
/
AlexaAdapter.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Alexa.NET.Request;
using Alexa.NET.Response;
using Bot.Builder.Community.Adapters.Alexa.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Bot.Builder.Community.Adapters.Alexa
{
public class AlexaAdapter : BotAdapter, IBotFrameworkHttpAdapter
{
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
private readonly AlexaAdapterOptions _options;
private readonly ILogger _logger;
private readonly AlexaRequestMapper _requestMapper;
public AlexaAdapter(AlexaAdapterOptions options = null, ILogger logger = null)
{
_options = options ?? new AlexaAdapterOptions();
_logger = logger ?? NullLogger.Instance;
_requestMapper = new AlexaRequestMapper(new AlexaRequestMapperOptions
{
ShouldEndSessionByDefault = _options.ShouldEndSessionByDefault
});
}
public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default)
{
if (httpRequest == null)
{
throw new ArgumentNullException(nameof(httpRequest));
}
if (httpResponse == null)
{
throw new ArgumentNullException(nameof(httpResponse));
}
if (bot == null)
{
throw new ArgumentNullException(nameof(bot));
}
string body;
using (var sr = new StreamReader(httpRequest.Body))
{
body = await sr.ReadToEndAsync();
}
var skillRequest = JsonConvert.DeserializeObject<SkillRequest>(body, JsonSerializerSettings);
if (skillRequest.Version != "1.0")
{
throw new Exception($"Unexpected request version of '{skillRequest.Version}' received.");
}
if (_options.ValidateIncomingAlexaRequests
&& !await ValidationHelper.ValidateRequest(httpRequest, skillRequest, body, _options.AlexaSkillId, _logger))
{
throw new AuthenticationException("Failed to validate incoming request.");
}
var alexaResponse = await ProcessAlexaRequestAsync(skillRequest, bot.OnTurnAsync);
if (alexaResponse == null)
{
throw new ArgumentNullException(nameof(alexaResponse));
}
httpResponse.ContentType = "application/json";
httpResponse.StatusCode = (int)HttpStatusCode.OK;
var responseJson = JsonConvert.SerializeObject(alexaResponse, JsonSerializerSettings);
var responseData = Encoding.UTF8.GetBytes(responseJson);
await httpResponse.Body.WriteAsync(responseData, 0, responseData.Length, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a proactive message to a conversation.
/// </summary>
/// <param name="reference">A reference to the conversation to continue.</param>
/// <param name="logic">The method to call for the resulting bot turn.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A task that represents the work queued to execute.</returns>
/// <remarks>Call this method to proactively send a message to a conversation.
/// Most channels require a user to initiate a conversation with a bot
/// before the bot can send activities to the user.</remarks>
/// <seealso cref="BotAdapter.RunPipelineAsync(ITurnContext, BotCallbackHandler, CancellationToken)"/>
/// <exception cref="ArgumentNullException"><paramref name="reference"/> or
/// <paramref name="logic"/> is <c>null</c>.</exception>
public async Task ContinueConversationAsync(ConversationReference reference, BotCallbackHandler logic, CancellationToken cancellationToken)
{
if (reference == null)
{
throw new ArgumentNullException(nameof(reference));
}
if (logic == null)
{
throw new ArgumentNullException(nameof(logic));
}
var request = reference.GetContinuationActivity().ApplyConversationReference(reference, true);
using (var context = new TurnContext(this, request))
{
await RunPipelineAsync(context, logic, cancellationToken).ConfigureAwait(false);
}
}
public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
{
return Task.FromException<ResourceResponse>(new NotImplementedException("Alexa adapter does not support updateActivity."));
}
public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
{
return Task.FromException(new NotImplementedException("Alexa adapter does not support deleteActivity."));
}
private async Task<SkillResponse> ProcessAlexaRequestAsync(SkillRequest alexaRequest, BotCallbackHandler logic)
{
var activity = RequestToActivity(alexaRequest);
var context = new TurnContextEx(this, activity);
await RunPipelineAsync(context, logic, default).ConfigureAwait(false);
var activities = context.SentActivities;
var outgoingActivity = ProcessOutgoingActivities(activities);
var response = _requestMapper.ActivityToResponse(outgoingActivity, alexaRequest);
return response;
}
public virtual MergedActivityResult ProcessOutgoingActivities(List<Activity> activities)
{
return _requestMapper.MergeActivities(activities);
}
public virtual Activity RequestToActivity(SkillRequest request)
{
return _requestMapper.RequestToActivity(request);
}
public override Task<ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
{
return Task.FromResult(new ResourceResponse[0]);
}
}
}