예제 #1
0
        public async void ContinueConversationAsyncShouldFailWithNullConversationReference()
        {
            var alexaAdapter = new AlexaAdapter(new Mock <AlexaAdapterOptions>().Object);

            Task BotsLogic(ITurnContext turnContext, CancellationToken cancellationToken)
            {
                return(Task.CompletedTask);
            }

            await Assert.ThrowsAsync <ArgumentNullException>(async() => { await alexaAdapter.ContinueConversationAsync(null, BotsLogic, default); });
        }
예제 #2
0
        public async void ContinueConversationAsyncShouldSucceed()
        {
            var callbackInvoked = false;

            var alexaAdapter          = new AlexaAdapter(new Mock <AlexaAdapterOptions>().Object);
            var conversationReference = new ConversationReference();

            Task BotsLogic(ITurnContext turnContext, CancellationToken cancellationToken)
            {
                callbackInvoked = true;
                return(Task.CompletedTask);
            }

            await alexaAdapter.ContinueConversationAsync(conversationReference, BotsLogic, default);

            Assert.True(callbackInvoked);
        }
예제 #3
0
        public static HttpConfiguration MapAlexaBotFramework(this HttpConfiguration httpConfiguration, Action <AlexaBotConfigurationBuilder> configurer)
        {
            var options        = new AlexaBotOptions();
            var optionsBuilder = new AlexaBotConfigurationBuilder(options);

            configurer(optionsBuilder);

            ConfigureAlexaBotRoutes(BuildAdapter());

            return(httpConfiguration);

            AlexaAdapter BuildAdapter()
            {
                var adapter = new AlexaAdapter();

                foreach (var middleware in options.Middleware)
                {
                    adapter.Use(middleware);
                }

                return(adapter);
            }

            void ConfigureAlexaBotRoutes(AlexaAdapter adapter)
            {
                var routes  = httpConfiguration.Routes;
                var baseUrl = options.Paths.BasePath;

                if (!baseUrl.StartsWith("/"))
                {
                    baseUrl = baseUrl.Substring(1, baseUrl.Length - 1);
                }

                if (!baseUrl.EndsWith("/"))
                {
                    baseUrl += "/";
                }

                routes.MapHttpRoute(
                    "Alexa Skill Requests Handler",
                    baseUrl + options.Paths.SkillRequestsPath,
                    defaults: null,
                    constraints: null,
                    handler: new AlexaRequestHandler(adapter, options.AlexaOptions));
            }
        }
        /// <summary>
        /// Initializes and adds a bot adapter to the HTTP request pipeline, using custom endpoint paths for the bot.
        /// </summary>
        /// <param name="applicationBuilder">The application builder for the ASP.NET application.</param>
        /// <param name="configurePaths">Allows you to modify the endpoints for the bot.</param>
        /// <returns>The updated application builder.</returns>
        /// <remarks>This method adds any middleware from the <see cref="AlexaBotOptions"/> provided in the
        /// <see cref="ServiceCollectionExtensions.AddBot{TBot}(IServiceCollection, Action{AlexaBotOptions})"/>
        /// method to the adapter.</remarks>
        public static IApplicationBuilder UseAlexa(this IApplicationBuilder applicationBuilder, Action <AlexaBotPaths> configurePaths)
        {
            if (applicationBuilder == null)
            {
                throw new ArgumentNullException(nameof(applicationBuilder));
            }

            if (configurePaths == null)
            {
                throw new ArgumentNullException(nameof(configurePaths));
            }

            var options = applicationBuilder.ApplicationServices.GetRequiredService <IOptions <AlexaBotOptions> >().Value;

            var alexaAdapter = new AlexaAdapter()
            {
                ShouldEndSessionByDefault          = options.AlexaOptions.ShouldEndSessionByDefault,
                ConvertBotBuilderCardsToAlexaCards = options.AlexaOptions.TryConvertFirstActivityAttachmentToAlexaCard
            };

            foreach (var middleware in options.Middleware)
            {
                alexaAdapter.Use(middleware);
            }

            var paths = options.Paths;

            configurePaths(paths);

            if (!options.Paths.BasePath.EndsWith("/"))
            {
                options.Paths.BasePath += "/";
            }

            applicationBuilder.Map(
                $"{paths.BasePath}{paths.SkillRequestsPath}",
                botActivitiesAppBuilder => botActivitiesAppBuilder.Run(new AlexaRequestHandler(alexaAdapter, options.AlexaOptions).HandleAsync));

            return(applicationBuilder);
        }
        protected async Task <AlexaResponseBody> ProcessMessageRequestAsync(HttpRequest request, AlexaAdapter alexaAdapter, BotCallbackHandler botCallbackHandler)
        {
            AlexaRequestBody skillRequest;

            var memoryStream = new MemoryStream();

            request.Body.CopyTo(memoryStream);
            var requestBytes = memoryStream.ToArray();

            memoryStream.Position = 0;

            using (var bodyReader = new JsonTextReader(new StreamReader(memoryStream, Encoding.UTF8)))
            {
                skillRequest = AlexaBotMessageSerializer.Deserialize <AlexaRequestBody>(bodyReader);
            }

            if (skillRequest.Version != "1.0")
            {
                throw new Exception($"Unexpected version of '{skillRequest.Version}' received.");
            }

            if (_alexaOptions.ValidateIncomingAlexaRequests)
            {
                request.Headers.TryGetValue("SignatureCertChainUrl", out var certUrls);
                request.Headers.TryGetValue("Signature", out var signatures);
                var certChainUrl = certUrls.FirstOrDefault();
                var signature    = signatures.FirstOrDefault();
                await AlexaValidateRequestSecurityHelper.Validate(skillRequest, requestBytes, certChainUrl, signature);
            }

            var alexaResponseBody = await alexaAdapter.ProcessActivity(
                skillRequest,
                _alexaOptions,
                botCallbackHandler);

            return(alexaResponseBody);
        }
 public AlexaRequestHandler(AlexaAdapter alexaAdapter, AlexaOptions alexaOptions)
 {
     _alexaAdapter = alexaAdapter;
     _alexaOptions = alexaOptions;
 }
 public AlexaController(AlexaAdapter adapter, IBot bot)
 {
     Adapter = adapter;
     Bot     = bot;
 }
예제 #8
0
        public async Task <HttpResponseMessage> ProcessMessageRequestAsync(HttpRequestMessage request, AlexaAdapter alexaAdapter, Func <ITurnContext, Task> botCallbackHandler, CancellationToken cancellationToken)
        {
            AlexaRequestBody skillRequest;

            byte[] requestByteArray;

            try
            {
                requestByteArray = await request.Content.ReadAsByteArrayAsync();

                skillRequest = await request.Content.ReadAsAsync <AlexaRequestBody>(AlexaMessageMediaTypeFormatters, cancellationToken);
            }
            catch (Exception)
            {
                throw new JsonSerializationException("Invalid JSON received");
            }

            if (skillRequest.Version != "1.0")
            {
                throw new Exception($"Unexpected version of '{skillRequest.Version}' received.");
            }

            if (_alexaOptions.ValidateIncomingAlexaRequests)
            {
                request.Headers.TryGetValues("SignatureCertChainUrl", out var certUrls);
                request.Headers.TryGetValues("Signature", out var signatures);
                var certChainUrl = certUrls.FirstOrDefault();
                var signature    = signatures.FirstOrDefault();
                await AlexaValidateRequestSecurityHelper.Validate(skillRequest, requestByteArray, certChainUrl, signature);
            }

            var alexaResponseBody = await alexaAdapter.ProcessActivity(
                skillRequest,
                _alexaOptions,
                null);

            if (alexaResponseBody == null)
            {
                return(null);
            }

            var alexaResponseBodyJson = JsonConvert.SerializeObject(alexaResponseBody, Formatting.None,
                                                                    new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver  = new DefaultContractResolver {
                    NamingStrategy = new CamelCaseNamingStrategy()
                }
            });

            var response = request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(alexaResponseBodyJson);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            return(response);
        }
 public async void ContinueConversationAsyncShouldFailWithNullConversationReference()
 {
     var alexaAdapter = new AlexaAdapter(new Mock <AlexaAdapterOptions>().Object);