├── WordPressAlexa ├── wwwroot │ ├── js │ │ └── site.js │ └── css │ │ └── site.css ├── Views │ ├── _ViewStart.cshtml │ └── Shared │ │ └── Error.cshtml ├── appsettings.Development.json ├── appsettings.json ├── Program.cs ├── Utility │ ├── AlexaRequestValidationMiddlewareExtension.cs │ ├── Helpers.cs │ ├── AlexaRequestValidationMiddleware.cs │ └── RequestVerification.cs ├── WordPressAlexa.csproj ├── Startup.cs └── Controllers │ └── AlexaController.cs ├── README.md ├── LICENSE ├── WordPressAlexa.sln ├── .gitattributes └── .gitignore /WordPressAlexa/wwwroot/js/site.js: -------------------------------------------------------------------------------- 1 | // Write your Javascript code. -------------------------------------------------------------------------------- /WordPressAlexa/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } 4 | -------------------------------------------------------------------------------- /WordPressAlexa/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /WordPressAlexa/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "Debug": { 5 | "LogLevel": { 6 | "Default": "Warning" 7 | } 8 | }, 9 | "Console": { 10 | "LogLevel": { 11 | "Default": "Warning" 12 | } 13 | } 14 | }, 15 | "WordPressUri": "https://worpresssite.com/wp-json/", 16 | "SkillApplicationId": "appid", 17 | "WordPressUsername": "Username", 18 | "WordPressPassword": "Password" 19 | } 20 | -------------------------------------------------------------------------------- /WordPressAlexa/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace WordPressAlexa 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | BuildWebHost(args).Run(); 11 | } 12 | 13 | public static IWebHost BuildWebHost(string[] args) => 14 | WebHost.CreateDefaultBuilder(args) 15 | .UseStartup() 16 | .Build(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /WordPressAlexa/Utility/AlexaRequestValidationMiddlewareExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace WordPressAlexa.Utility 8 | { 9 | public static class AlexaRequestValidationMiddlewareExtension 10 | { 11 | public static IApplicationBuilder UseAlexaRequestValidation(this IApplicationBuilder builder) 12 | { 13 | return builder.UseMiddleware(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /WordPressAlexa/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Error"; 3 | } 4 | 5 |

Error.

6 |

An error occurred while processing your request.

7 | 8 |

Development Mode

9 |

10 | Swapping to Development environment will display more detailed information about the error that occurred. 11 |

12 |

13 | Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application. 14 |

15 | -------------------------------------------------------------------------------- /WordPressAlexa/WordPressAlexa.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WordPressAlexa 2 | An ASP.NET Core 2.0 project for creating Alexa skills for WordPress sites 3 | The REST API will take requests from the Amazon Alexa service, process them and return an answer for Alexa to say. 4 | 5 | # Gettings started 6 | 7 | ## Deploy the backend 8 | - Clone or download this repository 9 | - Go to `appsettings.json` and change the `WordPressUri` to your site (including /wp-json/), `SkillApplicationId` to your Alexa Skill ID and add the WordPress credentials of an account with Post-edit rights. 10 | - Pubslish the site. You'll need a valid SSL certificate for Amazon to accept your API endpoints. Easiest way is to publish to Azure since all of their subdomains (e.g. https://myalexaskill.azurewebsites.net) are covered by their wildcard certificate. 11 | 12 | ## Create the Alexa skill 13 | -------------------------------------------------------------------------------- /WordPressAlexa/wwwroot/css/site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Set width on the form input elements since they're 100% wide by default */ 13 | input, 14 | select, 15 | textarea { 16 | max-width: 280px; 17 | } 18 | 19 | /* styles for validation helpers */ 20 | .field-validation-error { 21 | color: #b94a48; 22 | } 23 | 24 | .field-validation-valid { 25 | display: none; 26 | } 27 | 28 | input.input-validation-error { 29 | border: 1px solid #b94a48; 30 | } 31 | 32 | input[type="checkbox"].input-validation-error { 33 | border: 0 none; 34 | } 35 | 36 | .validation-summary-errors { 37 | color: #b94a48; 38 | } 39 | 40 | .validation-summary-valid { 41 | display: none; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 WordPress.NET 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /WordPressAlexa.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.15 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WordPressAlexa", "WordPressAlexa\WordPressAlexa.csproj", "{44599AB1-AF4F-4E8B-8582-8435068E2D0F}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {44599AB1-AF4F-4E8B-8582-8435068E2D0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {44599AB1-AF4F-4E8B-8582-8435068E2D0F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {44599AB1-AF4F-4E8B-8582-8435068E2D0F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {44599AB1-AF4F-4E8B-8582-8435068E2D0F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {7F0B6FB4-9655-49A9-B619-5891FE4A5EAE} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /WordPressAlexa/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using WordPressAlexa.Utility; 6 | 7 | namespace WordPressAlexa 8 | { 9 | public class Startup 10 | { 11 | public Startup(IConfiguration configuration) 12 | { 13 | Configuration = configuration; 14 | } 15 | 16 | public IConfiguration Configuration { get; } 17 | 18 | // This method gets called by the runtime. Use this method to add services to the container. 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | services.AddMvc(); 22 | } 23 | 24 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 25 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 26 | { 27 | if (env.IsDevelopment()) 28 | { 29 | app.UseDeveloperExceptionPage(); 30 | } 31 | 32 | app.UseAlexaRequestValidation(); 33 | app.UseMvc(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /WordPressAlexa/Utility/Helpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | using System.Web; 4 | 5 | namespace WordPressAlexa.Utility 6 | { 7 | public static class Helpers 8 | { 9 | public static string ScrubHtml(string value) 10 | { 11 | var step = Regex.Replace(value, @"<[^>]+>| ", "").Trim(); 12 | step = ScrubCustom(step); 13 | step = Regex.Replace(step, @"http[^\s]+", "").Trim(); // remove urls 14 | step = Regex.Replace(step, @"\p{Cs}", "").Trim(); // remove UTF-16 surrogate code units, e.g. Emoticons 15 | step = HttpUtility.HtmlDecode(step); 16 | step = step.Replace("&", "und"); 17 | step = Regex.Replace(step, @"\s{2,}", " "); // remove additional whitespace 18 | return step; 19 | } 20 | 21 | public static string ScrubCustom(string value) 22 | { 23 | var step = value; 24 | 25 | // remove sources form post end 26 | var indexOfText = value.IndexOf("Quelle: ", StringComparison.InvariantCultureIgnoreCase); 27 | if (indexOfText >= 0) 28 | step = step.Remove(indexOfText); 29 | 30 | return step; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /WordPressAlexa/Utility/AlexaRequestValidationMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Http.Internal; 3 | using System; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Threading.Tasks; 7 | 8 | namespace WordPressAlexa.Utility 9 | { 10 | public class AlexaRequestValidationMiddleware 11 | { 12 | private readonly RequestDelegate _next; 13 | 14 | public AlexaRequestValidationMiddleware(RequestDelegate next) 15 | { 16 | _next = next; 17 | } 18 | 19 | public async Task Invoke(HttpContext context) 20 | { 21 | Debug.WriteLine("alexa request middleware"); 22 | context.Request.EnableRewind(); 23 | 24 | // Verify SignatureCertChainUrl is present 25 | context.Request.Headers.TryGetValue("SignatureCertChainUrl", out var signatureChainUrl); 26 | if (string.IsNullOrWhiteSpace(signatureChainUrl)) 27 | { 28 | context.Response.StatusCode = StatusCodes.Status400BadRequest; 29 | return; 30 | } 31 | var certUrl = new Uri(signatureChainUrl); 32 | 33 | // Verify SignatureCertChainUrl is Signature 34 | context.Request.Headers.TryGetValue("Signature", out var signature); 35 | if (string.IsNullOrWhiteSpace(signature)) 36 | { 37 | context.Response.StatusCode = StatusCodes.Status400BadRequest; 38 | return; 39 | } 40 | 41 | var body = new StreamReader(context.Request.Body).ReadToEnd(); 42 | context.Request.Body.Position = 0; 43 | 44 | if (string.IsNullOrWhiteSpace(body)) 45 | { 46 | context.Response.StatusCode = StatusCodes.Status400BadRequest; 47 | return; 48 | } 49 | 50 | var valid = await RequestVerification.Verify(signature, certUrl, body); 51 | if (!valid) 52 | { 53 | context.Response.StatusCode = StatusCodes.Status400BadRequest; 54 | return; 55 | } 56 | 57 | await _next(context); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /WordPressAlexa/Utility/RequestVerification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Security.Cryptography; 4 | using System.Security.Cryptography.X509Certificates; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace WordPressAlexa.Utility 9 | { 10 | public static class RequestVerification 11 | { 12 | public static async Task Verify(string encodedSignature, Uri certificatePath, string body) 13 | { 14 | if (!VerifyCertificateUrl(certificatePath)) 15 | return false; 16 | 17 | var certificate = await GetCertificate(certificatePath); 18 | if (!ValidSigningCertificate(certificate) || !VerifyChain(certificate)) 19 | return false; 20 | 21 | if (!AssertHashMatch(certificate, encodedSignature, body)) 22 | return false; 23 | 24 | return true; 25 | } 26 | 27 | public static bool AssertHashMatch(X509Certificate2 certificate, string encodedSignature, string body) 28 | { 29 | byte[] signature; 30 | try 31 | { 32 | signature = Convert.FromBase64String(encodedSignature); 33 | } 34 | catch 35 | { 36 | return false; 37 | } 38 | var rsa = certificate.GetRSAPublicKey(); 39 | 40 | return rsa.VerifyData(Encoding.UTF8.GetBytes(body), signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); 41 | } 42 | 43 | public static async Task GetCertificate(Uri certificatePath) 44 | { 45 | var response = await new HttpClient().GetAsync(certificatePath); 46 | var bytes = await response.Content.ReadAsByteArrayAsync(); 47 | return new X509Certificate2(bytes); 48 | } 49 | 50 | public static bool VerifyChain(X509Certificate2 certificate) 51 | { 52 | // see https://stackoverflow.com/questions/24618798/automated-downloading-of-x509-certificatePath-chain-from-remote-host 53 | //If you do not provide revokation information, use the following line. 54 | var certificateChain = new X509Chain { ChainPolicy = { RevocationMode = X509RevocationMode.NoCheck } }; 55 | return certificateChain.Build(certificate); 56 | } 57 | 58 | private static bool ValidSigningCertificate(X509Certificate2 certificate) 59 | { 60 | return DateTime.Now < certificate.NotAfter && DateTime.Now > certificate.NotBefore && certificate.GetNameInfo(X509NameType.SimpleName, false) == "echo-api.amazon.com"; 61 | } 62 | 63 | public static bool VerifyCertificateUrl(Uri certificate) 64 | { 65 | return certificate.Scheme == "https" && certificate.Host == "s3.amazonaws.com" && certificate.LocalPath.StartsWith("/echo.api") && certificate.IsDefaultPort; 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /WordPressAlexa/Controllers/AlexaController.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Mvc; 4 | using WordPressPCL; 5 | using Microsoft.Extensions.Configuration; 6 | using Alexa.NET.Request; 7 | using Alexa.NET.Request.Type; 8 | using Alexa.NET.Response; 9 | using Alexa.NET; 10 | using System.Text; 11 | using WordPressPCL.Utility; 12 | using WordPressAlexa.Utility; 13 | using WordPressPCL.Models; 14 | 15 | namespace WordPressAlexa.Controllers 16 | { 17 | [Produces("application/json")] 18 | [Route("api/Alexa")] 19 | public class AlexaController : Controller 20 | { 21 | private readonly WordPressClient _client; 22 | private readonly IConfiguration _config; 23 | private readonly string _appid; 24 | 25 | public AlexaController(IConfiguration config) 26 | { 27 | _config = config; 28 | 29 | // get values from config 30 | var wordpressuri = _config.GetValue("WordPressUri"); 31 | _appid = _config.GetValue("SkillApplicationId"); 32 | 33 | // create wordpress client 34 | _client = new WordPressClient(wordpressuri) { AuthMethod = AuthMethod.JWT }; 35 | } 36 | 37 | [HttpPost] 38 | public async Task HandleSkillRequest([FromBody]SkillRequest input) 39 | { 40 | // Security check 41 | if (input.Session.Application.ApplicationId != _appid) 42 | return BadRequest(); 43 | 44 | var requestType = input.GetRequestType(); 45 | 46 | if (requestType == typeof(IntentRequest)) 47 | { 48 | var response = await HandleIntentsAsync(input); 49 | 50 | return Ok(response); 51 | } 52 | 53 | if (requestType == typeof(LaunchRequest)) 54 | { 55 | var headlines = await GetHeadlinesAsync(); 56 | var speech = new SsmlOutputSpeech { Ssml = headlines.ToString() }; 57 | 58 | var finalResponse = ResponseBuilder.Tell(speech); 59 | 60 | return Ok(finalResponse); 61 | } 62 | 63 | return Ok(ErrorResponse()); 64 | } 65 | 66 | /// 67 | /// Handles different intents of the Alexa skill. 68 | /// 69 | /// current skill request 70 | /// 71 | private async Task HandleIntentsAsync(SkillRequest input) 72 | { 73 | if (!(input.Request is IntentRequest intentRequest)) 74 | return ErrorResponse(); 75 | 76 | var speech = new SsmlOutputSpeech(); 77 | 78 | // check the name to determine what you should do 79 | var intentName = intentRequest.Intent.Name; 80 | if (intentName.Equals("Headlines")) 81 | { 82 | var headlines = await GetHeadlinesAsync(); 83 | speech.Ssml = headlines.ToString(); 84 | 85 | // create the response using the ResponseBuilder 86 | var finalResponse = ResponseBuilder.Tell(speech); 87 | return finalResponse; 88 | } 89 | 90 | if (intentName.Equals("LatestPost")) 91 | { 92 | var sb = await GetLatestPostAsync(); 93 | speech.Ssml = sb.ToString(); 94 | var finalResponse = ResponseBuilder.Tell(speech); 95 | return finalResponse; 96 | } 97 | 98 | return ErrorResponse(); 99 | } 100 | 101 | /// 102 | /// Gets the latest post from WordPress. 103 | /// 104 | /// 105 | private async Task GetLatestPostAsync() 106 | { 107 | // get values from config 108 | var username = _config.GetValue("WordPressUsername"); 109 | var password = _config.GetValue("WordPressPassword"); 110 | await _client.RequestJWToken(username, password); 111 | 112 | var stringBuilder = new StringBuilder(); 113 | 114 | var latestPosts = await _client.Posts.Query(new PostsQueryBuilder { Context = WordPressPCL.Models.Context.Edit }, true); 115 | var post = latestPosts.FirstOrDefault(); 116 | 117 | if (post != null) 118 | { 119 | var content = Helpers.ScrubHtml(post.Content.Raw); 120 | var title = Helpers.ScrubHtml(post.Title.Rendered); 121 | 122 | stringBuilder.Append($"{title}{content}"); 123 | } 124 | else 125 | { 126 | stringBuilder.Append("Irgendwas ist schiefgelaufen."); 127 | } 128 | 129 | return stringBuilder; 130 | } 131 | 132 | /// 133 | /// Gets the latest Headlines from WordPress. 134 | /// 135 | /// 136 | private async Task GetHeadlinesAsync() 137 | { 138 | var stringBuilder = new StringBuilder(); 139 | var posts = await _client.Posts.Get(); 140 | var enumerableOfPosts = posts as Post[] ?? posts.ToArray(); 141 | 142 | stringBuilder.Append("Hier die Schlagzeilen."); 143 | 144 | 145 | // build the speech response 146 | for (var i = 0; i < 5; i++) 147 | { 148 | 149 | stringBuilder.Append($"{enumerableOfPosts.ElementAt(i).Title.Rendered}"); 150 | if (i == 4) 151 | stringBuilder.Append("."); 152 | 153 | stringBuilder.Append(""); 154 | } 155 | 156 | stringBuilder.Append(""); 157 | 158 | return stringBuilder; 159 | } 160 | 161 | /// 162 | /// Creates an error skill response. 163 | /// 164 | /// 165 | private static SkillResponse ErrorResponse() 166 | { 167 | var speech = new SsmlOutputSpeech { Ssml = "Irgendwas ist schiefgelaufen." }; 168 | return ResponseBuilder.Tell(speech); 169 | } 170 | } 171 | } --------------------------------------------------------------------------------