├── icons └── alexa.png ├── .gitignore ├── package.json ├── vendor ├── to-ssml.js └── alexa-app.js ├── README.md ├── locales └── en-US │ └── alexa.json ├── LICENSE ├── alexa.js └── alexa.html /icons/alexa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattotodd/node-red-contrib-alexa/HEAD/icons/alexa.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 18 | .grunt 19 | 20 | # node-waf configuration 21 | .lock-wscript 22 | 23 | # Compiled binary addons (http://nodejs.org/api/addons.html) 24 | build/Release 25 | 26 | # Dependency directory 27 | node_modules 28 | 29 | # Optional npm cache directory 30 | .npm 31 | 32 | # Optional REPL history 33 | .node_repl_history 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-red-contrib-alexa", 3 | "version": "0.0.7", 4 | "description": "a node-red node for integration with alexa skills", 5 | "scripts": {}, 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/mattotodd/node-red-contrib-alexa.git" 9 | }, 10 | "keywords": [ 11 | "node-red", 12 | "alexa" 13 | ], 14 | "node-red": { 15 | "nodes": { 16 | "alexa": "alexa.js" 17 | } 18 | }, 19 | "author": "mattotodd@gmail.com", 20 | "license": "Apache-2.0", 21 | "bugs": { 22 | "url": "https://github.com/mattotodd/node-red-contrib-alexa/issues" 23 | }, 24 | "homepage": "https://github.com/mattotodd/node-red-contrib-alexa#readme", 25 | "dependencies": { 26 | "alexa-utterances": "0.2.0", 27 | "alexa-verifier": "0.0.5", 28 | "bluebird": "2.10.2", 29 | "mustache": "2.2.1", 30 | "numbered": "1.0.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /vendor/to-ssml.js: -------------------------------------------------------------------------------- 1 | /** 2 | Copyright 2015 Rick Wargo. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | */ 10 | 11 | "use strict"; 12 | 13 | // Util functions for generating valid SSML from plain text 14 | // ======================================================== 15 | 16 | var ssml = { 17 | fromStr: function(str, current_ssml) { 18 | // remove any tags from the input string, if they exist. There can only be one set of tags. 19 | str = str || ""; 20 | str = str.replace(//gi, " ").replace(/<\/speak>/gi, " ").trim(); 21 | 22 | // and remove them from the concatenated string, if exists 23 | current_ssml = current_ssml || ""; 24 | current_ssml = current_ssml.replace(//gi, " ").replace(/<\/speak>/gi, " ").trim(); 25 | 26 | //TODO: Need a library with how to easily construct these statements with appropriate spacing, etc. 27 | //TODO: make sure all attribute values are surrounded by "..." 28 | var ssml_str = "" + current_ssml + (current_ssml === "" ? "" : " ") + str + ""; 29 | 30 | return ssml_str.replace(/ +/, " "); 31 | }, 32 | cleanse: function(str) { 33 | //

is left in place to support intended HTML output 34 | return str.replace(/<\/?(speak|break|phoneme|audio|say-as|s\b|w\b)[^>]*>/gi, " ") 35 | .replace(/\s*\n\s*/g, "\n") 36 | .replace(/ +/g, " ") 37 | .replace(/ ([.,!?;:])/g, "$1") 38 | .trim(); 39 | } 40 | }; 41 | 42 | module.change_code = 1; 43 | module.exports = ssml; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | node-red-contrib-alexa 2 | ====================== 3 | 4 | [![NPM](https://nodei.co/npm/node-red-contrib-alexa.png)](https://nodei.co/npm/node-red-contrib-alexa/) 5 | 6 | [Node-Red][1] node for Amazon [Alexa Skills Kit (ASK)][2]. 7 | 8 | The library makes use of the [alexa-app][3] package to format requests as well as define your schema and utterances 9 | 10 | #Install 11 | 12 | Run the following command in the root directory of your Node-RED install 13 | 14 | npm install node-red-contrib-alexa 15 | 16 | #Example 17 | 18 | For an example, see the [node-red-alexa](https://github.com/mattotodd/node-red-alexa) fork of node-red that includes this library 19 | 20 | #Usage 21 | 22 | The pattern of usage is similar to using node-reds http in and out nodes. 23 | 24 | #### Enable Verification of incoming requests 25 | 26 | To verify incoming requests are coming from Amazon, you can set `alexa.verifyRequests` to true in your node-red settings. 27 | (add the alexa key if it doesn't already exist) 28 | 29 | ```javascript 30 | // node-red settings file 31 | 32 | }, 33 | alexa: { 34 | verifyRequests: true 35 | }, 36 | ``` 37 | 38 | #Nodes 39 | 40 | ### Config Node (alexa-skill-config) 41 | 42 | This node is used to define your skill, and can be used across multiple Alexa Request nodes. The skills tab will 43 | format you schema and untterances to make it easier to submit them to amazon. 44 | 45 | The nodes within this library map to the [ASK documentation][4] 46 | 47 | ### Launch Request (alexa-http launch) 48 | 49 | This node receives a LaunchRequest when the user invokes the skill with the invocation name, but does not provide any command mapping to an intent. 50 | 51 | ### Intent Request (alexa-http intent) 52 | 53 | This node receives an IntentRequest when the user speaks a command that maps to an intent. The request object sent to your service includes the specific intent and any defined slot values. 54 | 55 | ### SessionEnd Request (alexa-http session-end) 56 | 57 | Your service receives a SessionEndedRequest when a currently open session is closed 58 | 59 | ### Say (alexa-say) 60 | 61 | Tell Alexa to say something. Can use multiple `say` nodes and the phrases will be appended to each other 62 | 63 | ### Card (alexa-card) 64 | 65 | Adds a card to the users Alexa app 66 | 67 | ### Link Account (alexa-link-account) 68 | 69 | Adds a card to the response instructing the user how to link their account to the skill. 70 | 71 | ### Response (alexa-http response) 72 | 73 | Completes a response from an alexa request. Required for any Launch, Intent or SessionEnd request. 74 | 75 | 76 | [1]:http://nodered.org 77 | [2]:https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit 78 | [3]:https://www.npmjs.com/package/alexa-app 79 | [4]:https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference -------------------------------------------------------------------------------- /locales/en-US/alexa.json: -------------------------------------------------------------------------------- 1 | { 2 | "common": { 3 | "label": { 4 | "name": "Name" 5 | }, 6 | "errors": { 7 | "no-alexa-response": "No Alexa response in node message", 8 | "http-root-not-enabled": "Can not setup endpoint, httpNodeRoot not enabled" 9 | } 10 | }, 11 | "alexa-skill-config":{ 12 | "label": { 13 | "skillname": "Skill Name", 14 | "intents": "Intents", 15 | "intent": "Intent", 16 | "setup": "Setup", 17 | "account-linking":"Account Linking", 18 | "skill":"Skill" 19 | }, 20 | "placeholder": { 21 | "skillname": "New Skill Name" 22 | }, 23 | "tip": { 24 | "intents":"Note: Expects a json array of {name, options} intent objects. alexa-app Reference

using Amazon Slot Types", 25 | "endpoint":"Note: This it the url you will enter at developer.amazon.com when you configure your skill." 26 | }, 27 | "errors": { 28 | } 29 | }, 30 | "alexa-httpin":{ 31 | "label": { 32 | "skill": "Skill", 33 | "name": "Name" 34 | }, 35 | "setby": "- set by msg.method -", 36 | "basicauth": "Use basic authentication?", 37 | "utf8": "a UTF-8 string", 38 | "binary": "a binary buffer", 39 | "json": "a parsed JSON object", 40 | "tip": { 41 | "in": "The url will be relative to ", 42 | "res": "The messages sent to this node must originate from an http input node", 43 | "req": "Tip: If the JSON parse fails the fetched string is returned as-is." 44 | }, 45 | "httpreq": "http request", 46 | "errors": { 47 | "not-created": "Cannot create http-in node when httpNodeRoot set to false", 48 | "missing-path": "missing path", 49 | "no-response": "No response object", 50 | "no-alexa-response": "No alexa response object", 51 | "json-error": "JSON parse error", 52 | "no-url": "No url specified", 53 | "deprecated-call":"Deprecated call to __method__" 54 | }, 55 | "status": { 56 | "requesting": "requesting" 57 | } 58 | }, 59 | "alexa-card": { 60 | "label": { 61 | "name":"Name", 62 | "object": "Card JSON" 63 | 64 | }, 65 | "tip": "Note: Card Object Reference" 66 | } 67 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /vendor/alexa-app.js: -------------------------------------------------------------------------------- 1 | var Promise = require("bluebird"); 2 | var AlexaUtterances = require("alexa-utterances"); 3 | var SSML = require("./to-ssml"); 4 | var alexa = {}; 5 | 6 | alexa.response = function() { 7 | this.resolved = false; 8 | this.response = { 9 | "version": "1.0", 10 | "sessionAttributes": {}, 11 | "response": { 12 | "shouldEndSession": true 13 | } 14 | }; 15 | this.say = function(str) { 16 | if (typeof this.response.response.outputSpeech == "undefined") { 17 | this.response.response.outputSpeech = { 18 | "type": "SSML", 19 | "ssml": SSML.fromStr(str) 20 | }; 21 | } else { 22 | // append str to the current outputSpeech, stripping the out speak tag 23 | this.response.response.outputSpeech.ssml = SSML.fromStr(str, this.response.response.outputSpeech.ssml); 24 | } 25 | return this; 26 | }; 27 | this.clear = function(/*str*/) { 28 | this.response.response.outputSpeech = { 29 | "type": "PlainText", 30 | "text": "" 31 | }; 32 | return this; 33 | }; 34 | this.reprompt = function(str) { 35 | if (typeof this.response.response.reprompt == "undefined") { 36 | this.response.response.reprompt = { 37 | "outputSpeech": { 38 | "type": "SSML", 39 | "ssml": SSML.fromStr(str) 40 | } 41 | }; 42 | } else { 43 | // append str to the current outputSpeech, stripping the out speak tag 44 | this.response.response.reprompt.outputSpeech.ssml = SSML.fromStr(str, this.response.response.reprompt.outputSpeech.text); 45 | } 46 | return this; 47 | }; 48 | this.card = function(oCard) { 49 | if (2 == arguments.length) { //backwards compat 50 | oCard = { 51 | type: "Simple", 52 | title: arguments[0], 53 | content: arguments[1] 54 | }; 55 | } 56 | 57 | var requiredAttrs = [], 58 | clenseAttrs = []; 59 | 60 | switch (oCard.type) { 61 | case 'Simple': 62 | requiredAttrs.push('content'); 63 | clenseAttrs.push('content'); 64 | break; 65 | case 'Standard': 66 | requiredAttrs.push('text'); 67 | clenseAttrs.push('text'); 68 | if (('image' in oCard) && ( !('smallImageUrl' in oCard['image']) && !('largeImageUrl' in oCard['image']) )) { 69 | console.error('If card.image is defined, must specify at least smallImageUrl or largeImageUrl'); 70 | return this; 71 | } 72 | break; 73 | default: 74 | break; 75 | } 76 | 77 | var hasAllReq = requiredAttrs.every(function(idx) { 78 | if (!(idx in oCard)) { 79 | console.error('Card object is missing required attr "' + idx + '"'); 80 | return false; 81 | } 82 | return true; 83 | }); 84 | 85 | if (!hasAllReq) { 86 | return this; 87 | } 88 | 89 | // remove all SSML to keep the card clean 90 | clenseAttrs.forEach(function(idx) { 91 | oCard[idx] = SSML.cleanse(oCard[idx]); 92 | }); 93 | 94 | this.response.response.card = oCard; 95 | 96 | return this; 97 | }; 98 | this.linkAccount = function() { 99 | this.response.response.card = { 100 | "type": "LinkAccount" 101 | }; 102 | return this; 103 | }; 104 | this.shouldEndSession = function(bool, reprompt) { 105 | this.response.response.shouldEndSession = bool; 106 | if (reprompt) { 107 | this.reprompt(reprompt); 108 | } 109 | return this; 110 | }; 111 | this.session = function(key, val) { 112 | if (typeof val == "undefined") { 113 | return this.response.sessionAttributes[key]; 114 | } else { 115 | this.response.sessionAttributes[key] = val; 116 | } 117 | return this; 118 | }; 119 | this.clearSession = function(key) { 120 | if (typeof key == "string" && typeof this.response.sessionAttributes[key] != "undefined") { 121 | delete this.response.sessionAttributes[key]; 122 | } else { 123 | this.response.sessionAttributes = {}; 124 | } 125 | return this; 126 | }; 127 | 128 | }; 129 | 130 | alexa.request = function(json) { 131 | this.data = json; 132 | this.slot = function(slotName, defaultValue) { 133 | try { 134 | return this.data.request.intent.slots[slotName].value; 135 | } catch (e) { 136 | console.error("missing intent in request: " + slotName, e); 137 | return defaultValue; 138 | } 139 | }; 140 | this.type = function() { 141 | try { 142 | return this.data.request.type; 143 | } catch (e) { 144 | console.error("missing type", e); 145 | return null; 146 | } 147 | }; 148 | this.sessionDetails = { 149 | "new": this.data.session.new, 150 | "sessionId": this.data.session.sessionId, 151 | "userId": this.data.session.user.userId, 152 | "accessToken": this.data.session.user.accessToken || null, 153 | "attributes": this.data.session.attributes, 154 | "application": this.data.session.application 155 | }; 156 | this.userId = this.data.session.user.userId; 157 | this.applicationId = this.data.session.application.applicationId; 158 | this.sessionId = this.data.session.sessionId; 159 | this.sessionAttributes = this.data.session.attributes; 160 | this.isSessionNew = (true === this.data.session.new); 161 | this.session = function(key) { 162 | try { 163 | return this.data.session.attributes[key]; 164 | } catch (e) { 165 | console.error("key not found on session attributes: " + key, e); 166 | return; 167 | } 168 | }; 169 | }; 170 | 171 | alexa.apps = {}; 172 | 173 | alexa.app = function(name, endpoint) { 174 | var self = this; 175 | this.name = name; 176 | this.messages = { 177 | // When an intent was passed in that the application was not configured to handle 178 | "NO_INTENT_FOUND": "Sorry, the application didn't know what to do with that intent", 179 | // When the app was used with 'open' or 'launch' but no launch handler was defined 180 | "NO_LAUNCH_FUNCTION": "Try telling the application what to do instead of opening it", 181 | // When a request type was not recognized 182 | "INVALID_REQUEST_TYPE": "Error: not a valid request", 183 | // If some other exception happens 184 | "GENERIC_ERROR": "Sorry, the application encountered an error" 185 | }; 186 | 187 | // Persist session variables from every request into every response? 188 | this.persistentSession = true; 189 | 190 | // use a minimal set of utterances or the full cartesian product? 191 | this.exhaustiveUtterances = false; 192 | 193 | // A catch-all error handler - do nothing by default 194 | this.error = null; 195 | 196 | // pre/post hooks to be run on every request 197 | this.pre = function(/*request, response, type*/) {}; 198 | this.post = function(/*request, response, type*/) {}; 199 | 200 | this.endpoint = endpoint; 201 | // A mapping of keywords to arrays of possible values, for expansion of sample utterances 202 | this.dictionary = {}; 203 | this.intents = {}; 204 | this.intent = function(intentName, schema, func) { 205 | if (typeof schema == "function") { 206 | func = schema; 207 | schema = null; 208 | } 209 | self.intents[intentName] = { 210 | "name": intentName, 211 | "function": func 212 | }; 213 | if (schema) { 214 | self.intents[intentName].schema = schema; 215 | } 216 | }; 217 | this.launchFunc = null; 218 | this.launch = function(func) { 219 | self.launchFunc = func; 220 | }; 221 | this.sessionEndedFunc = null; 222 | this.sessionEnded = function(func) { 223 | self.sessionEndedFunc = func; 224 | }; 225 | this.request = function(request_json, state) { 226 | return new Promise(function(resolve, reject) { 227 | var request = new alexa.request(request_json); 228 | var response = new alexa.response(); 229 | var postExecuted = false; 230 | // Attach Promise resolve/reject functions to the response object 231 | response.send = function(exception) { 232 | if (typeof self.post == "function" && !postExecuted) { 233 | postExecuted = true; 234 | self.post(request, response, requestType, exception); 235 | } 236 | if (!response.resolved) { 237 | response.resolved = true; 238 | resolve(response.response); 239 | } 240 | }; 241 | response.fail = function(msg, exception) { 242 | if (typeof self.post == "function" && !postExecuted) { 243 | postExecuted = true; 244 | self.post(request, response, requestType, exception); 245 | } 246 | if (!response.resolved) { 247 | response.resolved = true; 248 | reject(msg); 249 | } 250 | }; 251 | try { 252 | var key; 253 | // Copy all the session attributes from the request into the response so they persist. 254 | // The Alexa API doesn't think session variables should persist for the entire 255 | // duration of the session, but I do. 256 | if (request.sessionAttributes && self.persistentSession) { 257 | for (key in request.sessionAttributes) { 258 | response.session(key, request.sessionAttributes[key]); 259 | } 260 | } 261 | var requestType = request.type(); 262 | if (typeof self.pre == "function") { 263 | self.pre(request, response, requestType); 264 | } 265 | if (!response.resolved) { 266 | if ("IntentRequest" === requestType) { 267 | var intent = request_json.request.intent.name; 268 | if (typeof self.intents[intent] != "undefined" && typeof self.intents[intent]["function"] == "function") { 269 | if (false !== self.intents[intent]["function"](request, response, state)) { 270 | response.send(); 271 | } 272 | } else { 273 | throw "NO_INTENT_FOUND"; 274 | } 275 | } else if ("LaunchRequest" === requestType) { 276 | if (typeof self.launchFunc == "function") { 277 | if (false !== self.launchFunc(request, response, state)) { 278 | response.send(); 279 | } 280 | } else { 281 | throw "NO_LAUNCH_FUNCTION"; 282 | } 283 | } else if ("SessionEndedRequest" === requestType) { 284 | if (typeof self.sessionEndedFunc == "function") { 285 | if (false !== self.sessionEndedFunc(request, response, state)) { 286 | response.send(); 287 | } 288 | } 289 | } else { 290 | throw "INVALID_REQUEST_TYPE"; 291 | } 292 | } 293 | } catch (e) { 294 | if (typeof self.error == "function") { 295 | self.error(e, request, response); 296 | } else if (typeof e == "string" && self.messages[e]) { 297 | response.say(self.messages[e]); 298 | response.send(e); 299 | } 300 | if (!response.resolved) { 301 | response.fail("Unhandled exception" + e.message, e); 302 | } 303 | } 304 | }); 305 | }; 306 | 307 | // Extract the schema and generate a schema JSON object 308 | this.schema = function() { 309 | var schema = { 310 | "intents": [] 311 | }, intentName, intent, key; 312 | for (intentName in self.intents) { 313 | intent = self.intents[intentName]; 314 | var intentSchema = { 315 | "intent": intent.name, 316 | "slots": [] 317 | }; 318 | if (intent.schema) { 319 | if (intent.schema.slots) { 320 | for (key in intent.schema.slots) { 321 | intentSchema.slots.push({ 322 | "name": key, 323 | "type": intent.schema.slots[key] 324 | }); 325 | } 326 | } 327 | } 328 | schema.intents.push(intentSchema); 329 | } 330 | return JSON.stringify(schema, null, 3); 331 | }; 332 | 333 | // Generate a list of sample utterances 334 | this.utterances = function() { 335 | var intentName, 336 | intent, 337 | out = ""; 338 | for (intentName in self.intents) { 339 | intent = self.intents[intentName]; 340 | if (intent.schema && intent.schema.utterances) { 341 | intent.schema.utterances.forEach(function(sample) { 342 | var list = AlexaUtterances(sample, 343 | intent.schema.slots, 344 | self.dictionary, 345 | self.exhaustiveUtterances); 346 | list.forEach(function(utterance) { 347 | out += intent.name + "\t" + (utterance.replace(/\s+/g, " ")).trim() + "\n"; 348 | }); 349 | }); 350 | } 351 | } 352 | return out; 353 | }; 354 | 355 | // A built-in handler for AWS Lambda 356 | this.handler = function(event, context) { 357 | self.request(event) 358 | .then(function(response) { 359 | context.succeed(response); 360 | }) 361 | .catch(function(response) { 362 | context.fail(response); 363 | }); 364 | }; 365 | 366 | // For backwards compatibility 367 | this.lambda = function() { 368 | return self.handler; 369 | }; 370 | 371 | // A utility method to bootstrap alexa endpoints into express automatically 372 | this.express = function(express, path, enableDebug) { 373 | var endpoint = (path || "/") + (self.endpoint || self.name); 374 | express.post(endpoint, function(req, res) { 375 | self.request(req.body).then(function(response) { 376 | res.json(response); 377 | }, function() { 378 | res.status(500).send("Server Error"); 379 | }); 380 | }); 381 | if (typeof enableDebug != "boolean") { 382 | enableDebug = true; 383 | } 384 | if (enableDebug) { 385 | express.get(endpoint, function(req, res) { 386 | res.render("test", { 387 | "json": self, 388 | "schema": self.schema(), 389 | "utterances": self.utterances() 390 | }); 391 | }); 392 | } 393 | }; 394 | 395 | // Add the app to the global list of named apps 396 | if (name) { 397 | alexa.apps[name] = self; 398 | } 399 | 400 | return this; 401 | }; 402 | 403 | module.exports = alexa; -------------------------------------------------------------------------------- /alexa.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 IBM Corp. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | **/ 16 | 17 | module.exports = function(RED) { 18 | "use strict"; 19 | var alexa = require('./vendor/alexa-app'); 20 | var verifier = require('alexa-verifier'); 21 | var mustache = require('mustache'); 22 | 23 | var skills = {}; 24 | 25 | function createResponseWrapper(node,res) { 26 | var wrapper = { 27 | _res: res 28 | }; 29 | var toWrap = [ 30 | "append", 31 | "attachment", 32 | "cookie", 33 | "clearCookie", 34 | "download", 35 | "end", 36 | "format", 37 | "get", 38 | "json", 39 | "jsonp", 40 | "links", 41 | "location", 42 | "redirect", 43 | "render", 44 | "send", 45 | "sendfile", 46 | "sendFile", 47 | "sendStatus", 48 | "set", 49 | "status", 50 | "type", 51 | "vary" 52 | ]; 53 | toWrap.forEach(function(f) { 54 | wrapper[f] = function() { 55 | node.warn(RED._("alexa-httpin.errors.deprecated-call",{method:"msg.res."+f})); 56 | var result = res[f].apply(res,arguments); 57 | if (result === res) { 58 | return wrapper; 59 | } else { 60 | return result; 61 | } 62 | } 63 | }); 64 | return wrapper; 65 | } 66 | 67 | function validateAlexaRequest(req, res, next) { 68 | if (!RED.settings.alexa || !RED.settings.alexa.verifyRequests){ 69 | return next(); 70 | }else if(!req.headers.signaturecertchainurl){ 71 | res.status(403).json({ status: 'failure', reason: er }); 72 | } 73 | var er; 74 | // mark the request body as already having been parsed so it's ignored by 75 | // other body parser middlewares 76 | req._body = true; 77 | req.rawBody = ''; 78 | req.on('data', function(data) { 79 | return req.rawBody += data; 80 | }); 81 | req.on('end', function() { 82 | var cert_url, er, error, requestBody, signature; 83 | try { 84 | req.body = JSON.parse(req.rawBody); 85 | } catch (error) { 86 | er = error; 87 | req.body = {}; 88 | } 89 | cert_url = req.headers.signaturecertchainurl; 90 | signature = req.headers.signature; 91 | requestBody = req.rawBody; 92 | verifier(cert_url, signature, requestBody, function(er) { 93 | if (er) { 94 | RED.log.error('error validating the alexa cert:', er); 95 | res.status(401).json({ status: 'failure', reason: er }); 96 | } else { 97 | next(); 98 | } 99 | }); 100 | }); 101 | } 102 | 103 | function setupAlexaHttpHandler(node, type){ 104 | var skillConfig = node.skillConfig; 105 | if(!skills.hasOwnProperty(skillConfig.id)){ 106 | skillConfig.intents = JSON.parse(skillConfig.intents); 107 | //setup skill 108 | var skill = new alexa.app(skillConfig.skillname); 109 | skills[skillConfig.id] = { 110 | skill: skill, 111 | launches: [], 112 | intents: [], 113 | sessionEnds: [] 114 | }; 115 | 116 | for (var i =0;i 2 |

3 |
    4 |
    5 |
    6 | 21 | 26 | 45 |
    46 | 47 | 48 | 49 | 115 | 116 | 126 | 127 | 130 | 131 | 164 | 165 | 175 | 176 | 179 | 180 | 214 | 215 | 225 | 226 | 236 | 237 | 269 | 270 | 280 | 281 | 284 | 285 | 310 | 311 | 327 | 328 | 333 | 334 | 370 | 371 | 377 | 378 | 381 | 382 | 403 | 404 | 410 | 411 | 414 | 415 | 441 | --------------------------------------------------------------------------------