-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathFacebookAdapter.cs
299 lines (267 loc) · 15.9 KB
/
FacebookAdapter.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Bot.Builder.Community.Adapters.Facebook.FacebookEvents;
using Bot.Builder.Community.Adapters.Facebook.FacebookEvents.Handover;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
namespace Bot.Builder.Community.Adapters.Facebook
{
/// <summary>
/// BotAdapter to allow for handling Facebook App payloads and responses via the Facebook API.
/// </summary>
public class FacebookAdapter : BotAdapter, IBotFrameworkHttpAdapter
{
private const string HubModeSubscribe = "subscribe";
private const string FacebookVerifyTokenSettingKey = "FacebookVerifyToken";
private const string FacebookAppSecretSettingKey = "FacebookAppSecret";
private const string FacebookAccessTokenSettingKey = "FacebookAccessToken";
/// <summary>
/// An instance of the FacebookClientWrapper class.
/// </summary>
private readonly FacebookClientWrapper _facebookClient;
private readonly ILogger _logger;
private readonly FacebookAdapterOptions _options;
/// <summary>
/// Initializes a new instance of the <see cref="FacebookAdapter"/> class using configuration settings.
/// </summary>
/// <param name="configuration">An <see cref="IConfiguration"/> instance.</param>
/// <remarks>
/// The adapter uses these configuration keys:
/// - `VerifyToken`, the token to respond to the initial verification request.
/// - `AppSecret`, the secret used to validate incoming webhooks.
/// - `AccessToken`, an access token for the bot.
/// </remarks>
/// <param name="options">An instance of <see cref="FacebookAdapterOptions"/>.</param>
/// <param name="logger">The logger this adapter should use.</param>
public FacebookAdapter(IConfiguration configuration, FacebookAdapterOptions options = null, ILogger logger = null)
: this(new FacebookClientWrapper(new FacebookClientWrapperOptions(configuration[FacebookVerifyTokenSettingKey], configuration[FacebookAppSecretSettingKey], configuration[FacebookAccessTokenSettingKey])), options, logger)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FacebookAdapter"/> class using an existing Facebook client.
/// </summary>
/// /// <param name="facebookClient">Client used to interact with the Facebook API.</param>
/// <param name="options">Options for the Facebook Adapter.</param>
/// <param name="logger">The logger this adapter should use.</param>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
public FacebookAdapter(FacebookClientWrapper facebookClient, FacebookAdapterOptions options, ILogger logger = null)
{
_options = options ?? new FacebookAdapterOptions();
_facebookClient = facebookClient ?? throw new ArgumentNullException(nameof(facebookClient));
_logger = logger ?? NullLogger.Instance;
}
/// <summary>
/// Sends activities to the conversation.
/// </summary>
/// <param name="turnContext">The context object for the turn.</param>
/// <param name="activities">The activities to send.</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>If the activities are successfully sent, the task result contains
/// an array of <see cref="ResourceResponse"/> objects containing the IDs that
/// the receiving channel assigned to the activities.</remarks>
public override async Task<ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
{
var responses = new List<ResourceResponse>();
foreach (var activity in activities)
{
if (activity.Type != ActivityTypes.Message && activity.Type != ActivityTypes.Event)
{
_logger.LogTrace($"Unsupported Activity Type: '{activity.Type}'. Only Activities of type 'Message' or 'Event' are supported.");
}
else
{
var message = CreateFacebookMessageFromActivity(activity);
if (message.Message?.Attachment != null)
{
message.Message.Text = null;
}
var res = await _facebookClient.SendMessageAsync("/me/messages", message, null, cancellationToken)
.ConfigureAwait(false);
if (activity.Type == ActivityTypes.Event)
{
if (activity.Name.Equals(HandoverConstants.PassThreadControl, StringComparison.Ordinal))
{
var recipient = (string)activity.Value == "inbox" ? HandoverConstants.PageInboxId : (string)activity.Value;
await _facebookClient.PassThreadControlAsync(recipient, activity.Conversation.Id, HandoverConstants.MetadataPassThreadControl, cancellationToken).ConfigureAwait(false);
}
else if (activity.Name.Equals(HandoverConstants.TakeThreadControl, StringComparison.Ordinal))
{
await _facebookClient.TakeThreadControlAsync(activity.Conversation.Id, HandoverConstants.MetadataTakeThreadControl, cancellationToken).ConfigureAwait(false);
}
else if (activity.Name.Equals(HandoverConstants.RequestThreadControl, StringComparison.Ordinal))
{
await _facebookClient.RequestThreadControlAsync(activity.Conversation.Id, HandoverConstants.MetadataRequestThreadControl, cancellationToken).ConfigureAwait(false);
}
}
var response = new ResourceResponse()
{
Id = res,
};
responses.Add(response);
}
}
return responses.ToArray();
}
/// <summary>
/// Throws a <see cref="NotImplementedException"/> exception in all cases.
/// </summary>
/// <param name="turnContext">The context object for the turn.</param>
/// <param name="activity">New replacement activity.</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>
public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
{
return Task.FromException<ResourceResponse>(new NotImplementedException("Facebook adapter does not support updateActivity."));
}
/// <summary>
/// Throws a <see cref="NotImplementedException"/> exception in all cases.
/// </summary>
/// <param name="turnContext">The context object for the turn.</param>
/// <param name="reference">Conversation reference for the activity to delete.</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>
public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
{
return Task.FromException(new NotImplementedException("Facebook adapter does not support deleteActivity."));
}
/// <summary>
/// Sends a proactive message to a conversation using a conversation reference.
/// </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.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="logic"/> or
/// <paramref name="reference"/> is null.</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);
}
}
/// <summary>
/// Sends a proactive message from the bot to a conversation.
/// </summary>
/// <param name="claimsIdentity">A <see cref="ClaimsIdentity"/> for the conversation.</param>
/// <param name="reference">A reference to the conversation to continue.</param>
/// <param name="callback">The method to call for the resulting bot turn.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that represents the work queued to execute.</returns>
/// <remarks>Call this method to proactively send a message to a conversation.
/// <para>This method registers the following services for the turn.<list type="bullet">
/// <item><description><see cref="IIdentity"/> (key = "BotIdentity"), a claims claimsIdentity for the bot.
/// </description></item>
/// </list></para>
/// </remarks>
/// <seealso cref="BotAdapter.RunPipelineAsync(ITurnContext, BotCallbackHandler, CancellationToken)"/>
public override async Task ContinueConversationAsync(ClaimsIdentity claimsIdentity, ConversationReference reference, BotCallbackHandler callback, CancellationToken cancellationToken)
{
using (var context = new TurnContext(this, reference.GetContinuationActivity()))
{
context.TurnState.Add<IIdentity>(BotIdentityKey, claimsIdentity);
context.TurnState.Add<BotCallbackHandler>(callback);
await RunPipelineAsync(context, callback, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Accepts an incoming webhook request, creates a turn context,
/// and runs the middleware pipeline for an incoming TRUSTED activity.
/// </summary>
/// <param name="httpRequest">Represents the incoming side of an HTTP request.</param>
/// <param name="httpResponse">Represents the outgoing side of an HTTP request.</param>
/// <param name="bot">The code to run at the end of the adapter's middleware pipeline.</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>
/// <exception cref="AuthenticationException">The webhook receives message with invalid signature.</exception>
public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default)
{
if (httpRequest.Query["hub.mode"] == HubModeSubscribe && _options.VerifyIncomingRequests)
{
await _facebookClient.VerifyWebhookAsync(httpRequest, httpResponse, cancellationToken).ConfigureAwait(false);
return;
}
string stringifiedBody;
using (var sr = new StreamReader(httpRequest.Body))
{
stringifiedBody = await sr.ReadToEndAsync().ConfigureAwait(false);
}
if (!_facebookClient.VerifySignature(httpRequest, stringifiedBody) && _options.VerifyIncomingRequests)
{
await FacebookHelper.WriteAsync(httpResponse, HttpStatusCode.Unauthorized, string.Empty, Encoding.UTF8, cancellationToken).ConfigureAwait(false);
throw new AuthenticationException("Webhook received message with invalid signature. Potential malicious behavior!");
}
FacebookResponseEvent facebookResponseEvent = null;
facebookResponseEvent = JsonConvert.DeserializeObject<FacebookResponseEvent>(stringifiedBody);
foreach (var entry in facebookResponseEvent.Entry)
{
var payload = entry.Changes.Count > 0 ? entry.Changes : entry.Messaging.Count > 0 ? entry.Messaging : entry.Standby.Count > 0 ? entry.Standby : new List<FacebookMessage>();
foreach (var message in payload)
{
message.IsStandby = entry.Standby.Count > 0;
var activity = FacebookHelper.ProcessSingleMessage(message);
using (var context = new TurnContext(this, activity))
{
await RunPipelineAsync(context, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false);
}
}
}
}
/// <summary>
/// Determines whether the provided <see cref="IConfiguration"/> has the settings needed to
/// configure a <see cref="FacebookAdapter"/>.
/// </summary>
/// <param name="configuration"><see cref="IConfiguration"/> to verify for settings.</param>
/// <returns>A value indicating whether the configuration has the necessary settings required to create a <see cref="FacebookAdapter"/>.</returns>
internal static bool HasConfiguration(IConfiguration configuration)
{
// Do we have the config needed to create a facebook adapter?
return !string.IsNullOrEmpty(configuration.GetValue<string>(FacebookVerifyTokenSettingKey))
&& !string.IsNullOrEmpty(configuration.GetValue<string>(FacebookAccessTokenSettingKey))
&& !string.IsNullOrEmpty(configuration.GetValue<string>(FacebookAppSecretSettingKey));
}
/// <summary>
/// Factory method to create the <see cref="FacebookMessage"/> instance of the <see cref="Activity"/> to be sent to Facebook.
/// </summary>
/// <remarks>
/// This lets an override add a Facebook-supported message tag to an outgoing message.
/// See https://developers.facebook.com/docs/messenger-platform/send-messages/message-tags/.
/// </remarks>
/// <param name="activity">An <see cref="Activity"/> instance to build the message.</param>
/// <returns>A <see cref="FacebookMessage"/> built from the activity instance.</returns>
protected virtual FacebookMessage CreateFacebookMessageFromActivity(Activity activity)
{
return FacebookHelper.ActivityToFacebook(activity);
}
}
}