72 Commits

Author SHA1 Message Date
GotPPay
ce79c0e1e7 improved search for same questions and question variants 2018-04-03 14:49:36 +02:00
GotPPay
4a43dda852 fixed PR #15 comments 2018-04-03 14:19:07 +02:00
GotPPay
284cdcd7ba fix promise answer 2018-03-30 14:30:30 +02:00
GotPPay
0ebadcd3f7 promisify answer on user defined question 2018-03-30 12:08:38 +02:00
GotPPay
f163dde5b2 wait until unswer is ready 2018-03-30 11:52:04 +02:00
GotPPay
431daa3182 return answer instead of promise 2018-03-30 11:43:44 +02:00
GotPPay
fae0e0db23 return result instead of promise 2018-03-30 11:26:42 +02:00
GotPPay
443dc53dbd 4a. import content from WP ; change design to reflect 4a 2018-03-30 10:54:15 +02:00
MirnaM
5484a9a461 Add ui for answers from source 2018-03-28 15:51:10 +02:00
MirnaM
85d1b01dab Merge pull request #14 from GotPPay/handle-user-input
Handle user input
2018-02-07 11:06:37 +01:00
GotPPay
779e2d61f4 backend user input handling 2018-01-29 23:23:36 +01:00
GotPPay
5e92314938 frontend user input handling 2018-01-29 21:32:24 +01:00
GotPPay
3b5c287ef9 . 2018-01-27 10:53:06 +01:00
GotPPay
7ffbf42da9 update tokens 2018-01-27 03:15:47 +01:00
GotPPay
6b4256b7ab switch to saburly amazon account 2018-01-26 23:21:59 +01:00
GotPPay
e712693dd0 switch to saburly amazon account 2018-01-26 23:21:18 +01:00
GotPPay
220d76c2be test saburly account 2018-01-26 17:46:16 +01:00
GotPPay
2870695b25 Fix regex 2018-01-26 15:35:38 +01:00
GotPPay
bca71604fb Allow only letters for question name 2018-01-25 17:42:17 +01:00
GotPPay
84edb5563f prevent space in question name 2018-01-25 16:09:12 +01:00
MirnaM
bad8ccdce3 Merge pull request #13 from GotPPay/implement-built-in-intents
Implement built in intents
2018-01-25 15:59:16 +01:00
GotPPay
9b58f7745b improve code 2018-01-25 15:56:45 +01:00
GotPPay
b0737efb4e add missing spread operator 2018-01-25 15:39:48 +01:00
GotPPay
5d2a15bc93 apply comment from PR 2018-01-25 15:19:30 +01:00
GotPPay
145fff3b51 fix alexa bug with no speak action 2018-01-24 13:14:47 +01:00
GotPPay
4f6c714fa3 Rephrase continuation question 2018-01-24 13:11:35 +01:00
GotPPay
f714fdf70a improve No intent 2018-01-24 13:07:08 +01:00
GotPPay
adc1f1c099 improve default built-in intents 2018-01-24 13:02:46 +01:00
GotPPay
c0a177d39b experiment with yes no help cancel 2018-01-23 14:40:01 +01:00
GotPPay
3700d9bb58 Simulate built-in intents 2018-01-23 13:46:02 +01:00
GotPPay
7a5ddc6b52 Experiment with user-defined help intent 2018-01-23 13:33:53 +01:00
GotPPay
39b8e7608e Test built-in intents 2018-01-23 13:24:56 +01:00
MirnaM
a8ffe0a5c0 Merge pull request #11 from GotPPay/send-message-feature
Send message feature
2018-01-23 12:19:57 +01:00
MirnaM
def591224e Merge pull request #12 from GotPPay/question-explanation
Question explanation
2018-01-23 12:19:14 +01:00
GotPPay
d8b2f5f0b4 fix typo 2018-01-23 12:18:20 +01:00
GotPPay
dc2c8f384e use foreach instead of map 2018-01-23 12:15:04 +01:00
GotPPay
cc579133c0 Amazon default intents not working with dialog 2018-01-23 02:23:59 +01:00
GotPPay
0a8eb2e280 fix code 2018-01-23 02:18:08 +01:00
GotPPay
6b26db3d18 fix code 2018-01-23 02:15:44 +01:00
GotPPay
3202bf5f0b Implement help intent 2018-01-23 01:56:07 +01:00
GotPPay
370edd6ef0 fix inherited explanation bug 2018-01-23 01:51:36 +01:00
GotPPay
0d858ad1c7 List only questions with explanation 2018-01-23 01:46:02 +01:00
GotPPay
c6cd49a66f fix typo 2018-01-23 01:41:34 +01:00
GotPPay
97b6755f2f No magic numbers 2018-01-23 01:40:19 +01:00
GotPPay
b2386ea0d6 Yes and No intent dont work with dialog 2018-01-23 01:03:59 +01:00
GotPPay
2ae983d211 Experiment with Yes and No intent 2018-01-23 00:40:19 +01:00
GotPPay
b1a853c363 experiment with Yes and No intents 2018-01-23 00:20:50 +01:00
GotPPay
d58d4b89e3 experiment with yes intent 2018-01-23 00:08:39 +01:00
GotPPay
2c6953fe97 list all questions on Launch 2018-01-22 23:35:25 +01:00
GotPPay
af19108e9c fix InteractionModel generator 2018-01-22 22:34:58 +01:00
GotPPay
a00859c594 fix InteractionModel generator 2018-01-22 22:34:13 +01:00
GotPPay
085a0324b3 . 2018-01-22 20:12:16 +01:00
GotPPay
d8799fa40d fix JSON model 2018-01-19 23:26:59 +01:00
GotPPay
de0a4f3176 fix reverting skill on failed update 2018-01-19 22:54:50 +01:00
GotPPay
48578d3ffe Change UI 2018-01-19 22:42:37 +01:00
GotPPay
e2d648980b fix code 2018-01-19 20:28:26 +01:00
GotPPay
b73086291c code fix and improvements 2018-01-19 20:23:50 +01:00
GotPPay
434d45248c fix error in validation and undefined email value 2018-01-19 20:15:27 +01:00
GotPPay
00272ec67d validate email using regex 2018-01-19 20:05:49 +01:00
GotPPay
0727328e58 improve email preview 2018-01-19 19:53:49 +01:00
GotPPay
e2d76ff03e improve email preview 2018-01-19 19:50:21 +01:00
GotPPay
9cff3cd9ae change email service 2018-01-19 19:28:46 +01:00
GotPPay
2f82709f11 improve dialog ; send email 2018-01-19 16:29:47 +01:00
MirnaM
f6bf3a05b2 Merge pull request #10 from GotPPay/switch-to-alexa-sdk
Switch to alexa sdk
2018-01-19 11:24:23 +01:00
GotPPay
4b594898b1 Complete dialogtest 2018-01-19 08:00:51 +01:00
GotPPay
b07a9e21b3 Testing dialog handler 2018-01-19 07:43:10 +01:00
GotPPay
a570640fe1 hande unknown questions 2018-01-18 22:07:23 +01:00
GotPPay
9e4b06bd4c keep session open - fix 2018-01-18 21:56:56 +01:00
GotPPay
6bfd4adcaf keep session open 2018-01-18 21:50:26 +01:00
GotPPay
48badce0f0 fix 'res not defined' 2018-01-18 21:43:25 +01:00
GotPPay
68287d49ff complete switch to new alexa package 2018-01-18 21:33:44 +01:00
GotPPay
2f59e12aa7 test new library 2018-01-18 19:50:13 +01:00
31 changed files with 4756 additions and 1227 deletions

View File

@@ -1,6 +1,11 @@
To obtain new Auth Code :
To obtain client ID and secret :
https://developer.amazon.com/lwa/sp/overview.html
Click create new security profile, and add whitelist redirect uri : https://layla.amazon.com/api/skill/link/M2ODJY6EXOY6KO
https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.c748ca56ded04a95b236979898585ff7&scope=alexa::ask:skills:readwrite alexa::ask:models:readwrite alexa::ask:skills:test&response_type=code&redirect_uri=https://layla.amazon.com/api/skill/link/M2ODJY6EXOY6KO
To obtain new Auth Code :
https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.8c183daec15c488c9126b62bda9f7832&scope=alexa::ask:skills:readwrite alexa::ask:models:readwrite alexa::ask:skills:test&response_type=code&redirect_uri=https://layla.amazon.com/api/skill/link/M2ODJY6EXOY6KO
Response URL (Decoded) :
@@ -67,7 +72,8 @@ Prerequests for step 3 (run on server):
requires running mongodb service
Database (tellall) with collection (skill_list)
* Insert dummy skill with : db.skill_list.insert({"skillID" : "amzn1.ask.skill.efbf0564-a732-4ba9-958f-57939138adae", "intents" : [ { "intentName" : "GetFirstQuestion", "questions" : [ "tell me something about projects", "tell me all about projects" ], "answer" : "blablabla bla bla" }, { "intentName" : "GetThirdQuestion", "questions" : [ "Give me third question" ], "answer" : "This is answer to the third question" } ], "invocationName" : "Saburly", "invocationAnswer" : "We are Saburly team one" })
* Insert dummy skill with : db.skill_list.insert({"skillID" : "amzn1.ask.skill.2445552d-954d-4cd6-b77f-295368e02842", "intents" : [ { "intentName" : "GetFirstQuestion", "questionExplanation" : "","questions" : [ "tell me something about projects", "tell me all about projects" ], "answer" : "blablabla bla bla", "answerType":0, "externalAnswerSource":"" }, { "intentName" : "GetThirdQuestion", "questionExplanation" : "","questions" : [ "Give me third question" ], "answer" : "This is answer to the third question", "answerType":1, "externalAnswerSource":"http://sarajevotimes.com" } ], "invocationName" : "saburly", "invocationAnswer" : "We are Saburly team one", "contactEmail":"bilal@saburly.com" })
*obtain _id and change in web/src/App.js, and also skill_db_id in backend/config.js
*enter web/ dir and run "npm run build"

View File

@@ -1,204 +0,0 @@
var alexa = require ('alexa-app');
const config = require ('../config/config');
var databaseHelper = require ('../helpers/database');
//User data for sending message, this is skill-related and will be in some skill container
var Name = null;
var Email = null;
var Message = null;
var State = 0; // states should be defined in seperate file. (Not sending message, Waiting for name, Waiting for email, Waiting for message)
//For now (this is not long term solution)
// 0 : Not sending Message
// 1 : Waiting for name
// 2 : Waiting for email
// 3 : Waiting for message
var alexaApp = new alexa.app ('saburly'); // this means we still work with one skill
module.exports = {
init: function (express) {
alexaApp.express ({
expressApp: express,
// verifies requests come from amazon alexa. Must be enabled for production.
// You can disable this if you're running a dev environment and want to POST
// things to test behavior. enabled by default.
checkCert: false,
// sets up a GET route when set to true. This is handy for testing in
// development, but not recommended for production. disabled by default
debug: true,
});
},
updateIntentsJSON: function () {
databaseHelper
.getSkill (config.SKILL_DB_ID)
.then (skill => {
skill.intents.map (intent => {
alexaApp.intent (
intent.intentName,
{
slots: [],
utterances: intent.questions,
},
function (request, response) {
return response.say (intent.answer).shouldEndSession (false);
}
);
});
alexaApp.launch ((request, response) => {
return response.say (skill.invocationAnswer).shouldEndSession (false);
});
alexaApp.intent (
'EmailIntentLaunch',
{
slots: [],
utterances: [
'I want to send a message',
'I would like to send a message',
'I would like to leave a message',
'Leave a message',
],
},
function (request, response) {
Name = null;
Email = null;
Message = null;
State = 1;
return response
.say ('Ok. What is your name')
.shouldEndSession (false);
}
);
//TODO : Watch out for this intent. It will make trouble with other regular intents
//if other intents have utterance with just one slot like {Data}
//It should be taken care somwhere before this, to check if Email Intent is invoked
//This is problem only if we introduce slot options for regular intents for users
alexaApp.intent (
'EmailIntent',
{
slots: {
Name: 'AMAZON.US_FIRST_NAME',
Email: 'AMAZON.LITERAL',
Message: 'AMAZON.LITERAL',
Data: 'AMAZON.LITERAL',
},
utterances: [
'My name is {-|Name}',
'I am {-|Name}',
'{dawdw at dwd wdw|Data}',
'My email is {wadwwdw at wadwwd wdw|Email}',
'Send replay to {fkofkeofe at dppfam wd|Email}',
'My message is {Quick brown fox jumps over lazy dog|Message}',
],
},
function (request, response) {
let Data = undefined;
try {
if (!Name) Name = request.slot ('Name');
} catch (e) {
console.log ('Error. No name slot ');
Name = undefined;
}
try {
if (!Email) Email = request.slot ('Email');
} catch (e) {
console.log ('Error. No Email slot');
Email = undefined;
}
try {
if (!Message) Message = request.slot ('Message');
} catch (e) {
console.log ('Error. No Message slot');
Message = undefined;
}
try {
Data = request.slot ('Data');
} catch (e) {
console.log ('Error. No Data slot');
Data = undefined;
}
console.log ('State : ' + State);
//TODO : Responses could be configurable for each skill ?
if (State === 1) {
//Was waiting for name, so if Name is null, name is probably in Data
if ((!Name && Data) || Name) {
//got the name, let's continue for the email
if (!Name) Name = Data;
State = 2;
return response
.say ('Ok ' + Name + '. What is your email ?')
.shouldEndSession (false);
} else {
//Something is wrong, ask for name again
return response
.say (
'Sorry, I didnt understand your name. Can you say it again ?'
)
.shouldEndSession (false);
}
} else if (State === 2) {
//was waiting for email, so if Email is null, email is probably in Data
if ((!Email && Data) || Email) {
//Got the email, first verify email and than continue to message
if (!Email) Email = Data;
//TODO : verify email
State = 3;
return response
.say ('Great. Whats the message ?')
.shouldEndSession (false);
} else {
//Something is wrong, ask for the email again
return response
.say (
'Sorry, I didnt understan you email. Can you say it again ?'
)
.shouldEndSession (false);
}
} else if (State === 3) {
//Was waiting for message, so if Message is null, message is probably in Data
if ((!Message && Data) || Message) {
//Ok, we got all informations. Exit email intent
if (!Message) Message = Data;
State = 0;
//TODO : Send email
console.log (
'Name : ' +
Name +
' | Email : ' +
Email +
' | Message : ' +
Message
);
return response.say (
'Message sent. Someone will contact you ASAP'
);
} else {
//Something is wrong, ask for the message again
return response
.say (
'Sorry, I didnt understand your message. Can you say it again ?'
)
.shouldEndSession (false);
}
} else {
console.log ('State strange ! ' + State);
}
}
);
})
.catch (err => {
console.log (err);
alexaApp.launch ((request, response) => {
return response.say ('Sorry, there was no skill with that name');
});
});
},
};

View File

@@ -1,17 +1,33 @@
constants = require('./constants')
var config = {};
config.SKILL_STAGE = constants.skillStage.IN_DEVELOPMENT;
config.DB_URL = 'mongodb://localhost:27017/tellall';
config.PORT = 5000;
config.TOKEN = 'Atza|IwEBIBe6gDqrrowEEav6N-_6s4NztYeP3oG8PGWmu8ZiZw6lbOh3wNla3TK6pY-VEpT1d8an-dVf_n3kXJzVFsNo_4xBfZyFHGoCTDTFjs3yBRul4PVdBOhwwiH3-sgRLcUofZbe2oE06GmTcbfYtaStfXpQI5dfpldfnsJg_CvhSA6AHb_snJT3F6lyXzbV076d_3cYUMJxFldJGnYcviNHHxjjmuQTD06hhGzCbAxxe9eBmkuopRsNfyedLT2UlKP_ublah9CUGA3AdIX_3Iuke82jMwGnNl9gv7pbaDNEjAbj7IQSl3B08uuREtJq-oTBOjALNXRvFxTJmQjZwXNf9eHC7fSHJDdEPdZQU0AcffRQObAyAkUuL6Jv39OHzhb3Q64-zzoyODqnJyLP5SQZ2JVF53Kc_cTBqjIc9pXljqe7yEVk6JDs7q1zKbBibx_AQm57TO79IzWyLBzBMlYL5HdTsqEfRzLeDw2tws-hGMgkx2HWfdbYnmf5Qb4SyIhzvmmdfPLg3MVKTxjIBu1rx0xf3n0PLZP1EO6jsJPoMRPg77Gm4oit5Zp6s37ek3A3Vxh-ntoASpkrkxGTG9kVtRNt';
config.REFRESH_TOKEN = 'Atzr|IwEBICA3kDhfSJxlwvnQp9AD1o115AC_KBbFd5GBg8oN_QHWn2or5xFQ09BruuK6a07tGHtTt_9q2Y21mnOMH4RDtYXTVG9ADgLE6mHWKZFxYVwt3kHMiUJdY5lJcsOtWLoblrS-bJ0BEXXK5nVDt_bSI5IB7NUf-9QVZxhovRH_ANSxdTjJT0_rMIAZY3WEj68FEap49q_pg72BhnxHVZD2TC3zvX96_DN65HE5SoSgT7OiMAeiJewB_SyemW_HxBwaB-_X-G1ifOtnrzZ4gXTpOrEUlHI2YPuvRMBMtmz1h-nXDZYv3vwU3RA57Qj_ZNVcScj8_RXf2xq8w48v0PzZFXYBSalfnqPq6eUvSSbAJUp6bB8y596JlvR5dFQe_Z--X0Gkfo85IcyrI9D44vK9sJhrGhCVi2FDDa8pHczmNSen99JYZvDif-zpYzgbcymAkOV0gC7JvYMxlZfETT3NTBy7eVA7fJI1SZaeA_qW49xRcBkZBu5gkqTpeGWUU1cGr2aXRVVmXGM22NfV5E7KzvEBsCeHml_tCfxZeKY8Msd8hJb0Cd59u-_hsuc8oNjsOpIdFF976dY3uTmAgHWpG2PH';
//Bilal TOKENS
//config.TOKEN = 'Atza|IwEBIBe6gDqrrowEEav6N-_6s4NztYeP3oG8PGWmu8ZiZw6lbOh3wNla3TK6pY-VEpT1d8an-dVf_n3kXJzVFsNo_4xBfZyFHGoCTDTFjs3yBRul4PVdBOhwwiH3-sgRLcUofZbe2oE06GmTcbfYtaStfXpQI5dfpldfnsJg_CvhSA6AHb_snJT3F6lyXzbV076d_3cYUMJxFldJGnYcviNHHxjjmuQTD06hhGzCbAxxe9eBmkuopRsNfyedLT2UlKP_ublah9CUGA3AdIX_3Iuke82jMwGnNl9gv7pbaDNEjAbj7IQSl3B08uuREtJq-oTBOjALNXRvFxTJmQjZwXNf9eHC7fSHJDdEPdZQU0AcffRQObAyAkUuL6Jv39OHzhb3Q64-zzoyODqnJyLP5SQZ2JVF53Kc_cTBqjIc9pXljqe7yEVk6JDs7q1zKbBibx_AQm57TO79IzWyLBzBMlYL5HdTsqEfRzLeDw2tws-hGMgkx2HWfdbYnmf5Qb4SyIhzvmmdfPLg3MVKTxjIBu1rx0xf3n0PLZP1EO6jsJPoMRPg77Gm4oit5Zp6s37ek3A3Vxh-ntoASpkrkxGTG9kVtRNt';
//config.REFRESH_TOKEN = 'Atzr|IwEBICA3kDhfSJxlwvnQp9AD1o115AC_KBbFd5GBg8oN_QHWn2or5xFQ09BruuK6a07tGHtTt_9q2Y21mnOMH4RDtYXTVG9ADgLE6mHWKZFxYVwt3kHMiUJdY5lJcsOtWLoblrS-bJ0BEXXK5nVDt_bSI5IB7NUf-9QVZxhovRH_ANSxdTjJT0_rMIAZY3WEj68FEap49q_pg72BhnxHVZD2TC3zvX96_DN65HE5SoSgT7OiMAeiJewB_SyemW_HxBwaB-_X-G1ifOtnrzZ4gXTpOrEUlHI2YPuvRMBMtmz1h-nXDZYv3vwU3RA57Qj_ZNVcScj8_RXf2xq8w48v0PzZFXYBSalfnqPq6eUvSSbAJUp6bB8y596JlvR5dFQe_Z--X0Gkfo85IcyrI9D44vK9sJhrGhCVi2FDDa8pHczmNSen99JYZvDif-zpYzgbcymAkOV0gC7JvYMxlZfETT3NTBy7eVA7fJI1SZaeA_qW49xRcBkZBu5gkqTpeGWUU1cGr2aXRVVmXGM22NfV5E7KzvEBsCeHml_tCfxZeKY8Msd8hJb0Cd59u-_hsuc8oNjsOpIdFF976dY3uTmAgHWpG2PH';
//Saburly TOKENS
config.TOKEN = 'Atza|IwEBIABS0RvlVshGGO64X0tabhUuzpJKjbWNgxpRiy7YTftFD_lWlp-cbeXuVjRAu8kior2W2C5swf_rEHYvELQXdw78gB9WJQh4ITncPgqNCxvEnwVpIXiyeC_O287DRErnTYbI3s34i4NcxrXzobB8fIpTZxOkg6BI6vQGvvaiNLsTim2ElDYgAEmdgTN77llcMai521aovDqEw_XFc6GspeXhiGKxRomCMIL2UaT649owapDQ3y3Ug9eHvEaBzqjYdOUAtRtv19BGkG8YPs3npHmP5AD0Oc3ByCfrofcGk7fdd_nq28pRX6h4LXk4ylM279qlneWh9EErsWh8vtWuGEGusnDxW17OzEzf7HuwNDqdCJ6gCrIEkZaHISrSQ-vTsYGhKbv0z4nNjf_W_aoc9UJr9LnISCXx424R--iGDKZXhYWlZRjaiHsXE33MpS_M-sdN6GXYQwIjanTUahVXh5h-IBam5uJzTejE6CkIh5iUJ6um2IlDelJRMGS-T_aaG3zUvEagvEd9V9Z5mVN_kmO8bH4H2VefZuFGHRsCPa6SoLrlN0rkXK5fMw-zXfV2MHvQFdkgqYqGKxiEwWJ-g4n1ZrcPtWQowHT2z2yWrfnM2A6g8GIdPT23znmRcrdz4EU';
config.REFRESH_TOKEN = 'Atzr|IwEBIENdBZntrzvJYesv8SGhnty4Nyk2ZySL09elw5N0wH8S1Brz1UgIYLqenw3sKKxnc-VrIUbNtl1Ka4GDKwcTr2fDU_AbKQ6YXzeRBrfRQVvNOeCtjZE8P6Kg1PxAeQoCsqo7WPxK8ZdUaLwPjt_xiZ1FXtr01g-211PJs4KEg5jyF5nY2S14jA_TbwDW6ihpNqWd6ZklTZSRaOeSGa1mXZCSZ5yTsZIQV1Pn0fKhCXtcVg2L833YqRmextmHij4-2NtBQdW3gif5MPdhYjTqDNwgxO3OOagK1uSFqXOnMcmEDnxZuQQApugfDzClfN6DiDALCKN4dVAX8-OU_L2xsUkKiFP9rQjvHWJoRFBT1FpXjBfoVyzM1AaJ6C83WX6SjOBE0hhikQKIaPSe1ikK8_MzOIs2wqLLPnLGnKj3kcKMkDmY6DMgxfWj2H0hwLy0oZ7_qykS7wUHMGjRO5yScuBWFIr0RFFu00GS7zrKjkhFc_E4ZBBKskn0gywS-5pogo0U1rQtLg8lQJsVbxXQwtq2TxkGFMBiVxtQcXtHM1qbCVXpZQbk7ezxvasj4yAIsF4H7KBiZSGmWHkk4yADykWJSntTjFcM2wG0wSiEYoYzJQ';
config.TOKEN_EXPIRES_IN = 1515100500;
config.SKILL_ID = 'amzn1.ask.skill.efbf0564-a732-4ba9-958f-57939138adae';
//config.SKILL_DB_ID = '5a5016e775becaef2015da10'; //for server
config.SKILL_DB_ID = '5a232fb86ce046c749739455'; //for local
config.CLIENT_ID = 'amzn1.application-oa2-client.c748ca56ded04a95b236979898585ff7';
config.CLIENT_SECRET = '6dea8125cecd049d3c4cff7bb5bdfd3ff17bc6fed246c4c8f6b519d9ed08d0b3';
//config.SKILL_ID = 'amzn1.ask.skill.efbf0564-a732-4ba9-958f-57939138adae'; //bilal
config.SKILL_ID = 'amzn1.ask.skill.2445552d-954d-4cd6-b77f-295368e02842'; //saburly
//config.SKILL_DB_ID = '5a5016e775becaef2015da10'; //for server
config.SKILL_DB_ID = '5abd461329f85e4ec728d945'; //for local
//Bilal
//config.CLIENT_ID = 'amzn1.application-oa2-client.c748ca56ded04a95b236979898585ff7';
//config.CLIENT_SECRET = '6dea8125cecd049d3c4cff7bb5bdfd3ff17bc6fed246c4c8f6b519d9ed08d0b3';
//Saburly
config.CLIENT_ID = 'amzn1.application-oa2-client.8c183daec15c488c9126b62bda9f7832';
config.CLIENT_SECRET = '3acaa0755291132ee11e1cceaa100feef96a0244662df712a52189199cc655de';
module.exports = config;

View File

@@ -1,31 +1,72 @@
const constants = {};
constants.amazonResultCodes = {
OK:200,
ACCEPTED:202,
BAD_REQUEST:400,
UNAUTHORIZED:401,
NOT_FOUND:404,
CONFLICT:409,
PAYLOAD_TOO_LARGE:413
constants.skillStage = {
IN_DEVELOPMENT : 'development',
LIVE : 'live'
}
constants.amazonResultCodes = {
OK: 200,
ACCEPTED: 202,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
NOT_FOUND: 404,
CONFLICT: 409,
PAYLOAD_TOO_LARGE: 413,
};
constants.apiResultCodes = {
GENERIC_ERROR : -1,
OK:0,
AMAZON_ERROR:1, //amazon api works, but error is some of the amazonResultCodes
AMAZON_FAIL:2, //amazon api doesn't work
DATABASE_ERROR:3,
NO_SKILL:4,
INCONSISTEN_STATE:5,
}
GENERIC_ERROR: -1,
OK: 0,
AMAZON_ERROR: 1, //amazon api works, but error is some of the amazonResultCodes
AMAZON_FAIL: 2, //amazon api doesn't work
DATABASE_ERROR: 3,
NO_SKILL: 4,
INCONSISTENT_STATE: 5,
INVALID_SKILL: 6,
};
constants.HTTPResultCodes = {
INTERNAL_SERVER_ERROR : 500,
}
INTERNAL_SERVER_ERROR: 500,
};
constants.SKILL_ID_LENGTH = 24;
constants.voiceResponseStrings = {
QUESTION_NOT_FOUND: 'Sorry, I didnt understand',
GENERIC_CONTINUE: 'Say something to continue',
DIDNT_ASK_ANYTHING: 'There was no question to answer to',
};
//Timing is given in [ms]
constants.voiceResponseTimings = {
PAUSE_BETWEEN_QUESTIONS: 650,
PAUSE_AFTER_WELCOME_MESSAGE: 650,
};
module.exports = constants;
constants.stringConstraints = {
INTENT_EXPLANATION_MAX_LENGTH: 70,
INTENT_NAME_MAX_LENGTH: 30,
INTENT_NAME_MIN_LENGTH: 2,
QUESTION_MAX_LENGTH: 150,
QUESTION_MIN_LENGTH: 2,
ANSWER_MAX_LENGTH: 150,
ANSWER_MIN_LENGTH: 2,
INVOCATION_NAME_MAX_LENGTH: 50,
INVOCATION_NAME_MIN_LENGTH: 2,
INVOCATION_ANSWER_MAX_LENGTH: 100,
EMAIL_MAX_LENGTH: 100,
};
constants.answerType = {
PREDEFINED: 0,
EXTERNAL_SOURCE_WP_TITLES : 1,
EXTERNAL_SOURCE_WP_NEWS : 2
}
module.exports = constants;

14
backend/config/email.js Normal file
View File

@@ -0,0 +1,14 @@
var config = {};
config.PORT = 587;
config.SMTP_HOST = 'smtp.mail.com';
config.SECURE = false;
config.AUTH = {
user: 'saburly@mail.com',
pass: 'KeepSaburly',
};
config.FROM_EMAIL = 'saburly@mail.com';
config.SUBJECT = 'Message from Saburly service';
module.exports = config;

View File

@@ -1,5 +1,6 @@
var express = require ('express'), router = express.Router ();
router.use ('/skill', require ('./skill'));
router.use ('/saburly', require('./saburlyEntryPoint'));
module.exports = router;

View File

@@ -0,0 +1,9 @@
var express = require ('express'), router = express.Router ();
var bodyParser = require ('body-parser');
var alexa = require ('../models/alexa');
router.post ('/', bodyParser.json (), async (req, res) => {
alexa.run (req, res);
});
module.exports = router;

View File

@@ -1,9 +1,10 @@
var express = require ('express'), router = express.Router ();
let express = require ('express'), router = express.Router ();
const constants = require ('../config/constants');
var databaseHelper = require ('../helpers/database');
var amazonHelper = require ('../helpers/amazon');
var bodyParser = require ('body-parser');
var alexa = require ('../components/alexa');
let databaseHelper = require ('../helpers/database');
let amazonHelper = require ('../helpers/amazon');
let skillValidator = require('../helpers/skillValidator');
let bodyParser = require ('body-parser');
let alexa = require ('../models/alexa');
router.get ('/:id', async (req, res, next) => {
const id = req.params.id;
@@ -31,6 +32,20 @@ router.put ('/:id', bodyParser.json (), async (req, res, next) => {
delete skill.updateOnAmazon;
delete skill._id;
//Validate skill
if (!skillValidator.validateSkill(skill)){
//skill not valid
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.INVALID_SKILL,
message: '',
});
return;
}
//First get current skill from DB
databaseHelper
.getSkill (id)
@@ -41,6 +56,7 @@ router.put ('/:id', bodyParser.json (), async (req, res, next) => {
.then (() => {
//Ok, done, now update skill on Amazon (if needed)
if (updateOnAmazon) {
//We need to update skill on Amazon
amazonHelper
.updateSkill (skill)
.then (amazonResult => {
@@ -49,47 +65,80 @@ router.put ('/:id', bodyParser.json (), async (req, res, next) => {
amazonResult === constants.amazonResultCodes.ACCEPTED
) {
res.json ({result: constants.apiResultCodes.OK, message: ''});
alexa.updateIntentsJSON ();
alexa.updateModel ();
} else {
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({
result: constants.apiResultCodes.AMAZON_ERROR,
message: amazonResult,
});
//Update on amazon failed, revert changes in database and send error to user
databaseHelper
.updateSkill (id, currentSkillState)
.then (() => {
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.AMAZON_ERROR,
message: amazonResult,
});
})
.catch (() => {
//This should never happen, something is seriously wrong, like no database connection
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.INCONSISTENT_STATE,
message: '',
});
});
}
})
.catch (e => {
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({
result: constants.apiResultCodes.AMAZON_FAIL,
message: e,
});
//Update on amazon failed, revert changes in database and send error to user
databaseHelper
.updateSkill (id, currentSkillState)
.then (() => {
res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({
result: constants.apiResultCodes.AMAZON_FAIL,
message: e,
});
})
.catch (() => {
//This should never happen, something is seriously wrong, like no database connection
res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({
result: constants.apiResultCodes.INCONSISTENT_STATE,
message: '',
});
});
});
}else{
} else {
//No need to update on Amazon, tell to user it's ok
res.json ({result: constants.apiResultCodes.OK, message: ''});
alexa.updateIntentsJSON ();
alexa.updateModel ();
}
})
.catch (() => {
//Update in database didn't go well, revert changes
databaseHelper
.updateSkill (id, currentSkillState)
.then (() => {
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({
result: constants.apiResultCodes.DATABASE_ERROR,
message: '',
});
})
.catch (() => {
//This should never happen, something is seriously wrong, like no database connection
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({
result: constants.apiResultCodes.INCONSISTEN_STATE,
message: '',
});
});
//Update in database didn't go well, no need to revert since it failed to write in the first place
//just send error to user
res
.status (
constants.HTTPResultCodes.INTERNAL_SERVER_ERROR
)
.json ({
result: constants.apiResultCodes.DATABASE_ERROR,
message: '',
});
});
})
.catch (e => {
//I don't know why, but something went wrong, possibly ID of skill is wrong, doesn't exist in DB
res.status(constants.HTTPResultCodes.INTERNAL_SERVER_ERROR).json ({result: constants.apiResultCodes.NO_SKILL, message: ''});
res
.status (constants.HTTPResultCodes.INTERNAL_SERVER_ERROR)
.json ({result: constants.apiResultCodes.NO_SKILL, message: ''});
});
});

View File

@@ -37,15 +37,22 @@ var refreshTokens = function () {
request (options, function (error, response, body) {
if (error) {
reject (error);
}else{
} else {
parsedResponse = JSON.parse (body);
if (parsedResponse.refresh_token){
databaseHelper.updateTokens(parsedResponse.refresh_token, parsedResponse.access_token, parsedResponse.expires_in).then(()=>{
resolve();
}).catch(e=>{
reject(e);
});
}else{
if (parsedResponse.refresh_token) {
databaseHelper
.updateTokens (
parsedResponse.refresh_token,
parsedResponse.access_token,
parsedResponse.expires_in
)
.then (() => {
resolve ();
})
.catch (e => {
reject (e);
});
} else {
reject (body);
}
}
@@ -56,93 +63,223 @@ var refreshTokens = function () {
var generateInteractionModel = function (skill) {
let result = {};
let allIntents = [];
let defaultIntents = [
{
name: 'AMAZON.CancelIntent',
samples: [],
},
{
name: 'AMAZON.HelpIntent',
samples: [],
},
{
name: 'AMAZON.StopIntent',
samples: [],
},
];
/*
defaultIntents.map(intent=>{
allIntents.push(intent);
});
*/
skill.intents.map (intent => {
allIntents.push ({name: intent.intentName, samples: intent.questions});
});
//Special Email Intents :
//Built-In like intents (Amazon built-in don't work, probably something related to existance of dialog intent
allIntents.push ({
name: 'EmailIntentLaunch',
name: 'HelpIntent',
samples: ['Help', 'Can you help me', 'I need help'],
slots: [],
},
{
name: 'CancelIntent',
samples: ['Cancel', 'Stop', 'Please stop'],
slots: [],
},
{
name: 'YesIntent',
samples: [
'I want to send a message',
'I would like to send a message',
'I would like to leave a message',
'Leave a message',
'Yes',
'Yes please',
'I would like that',
'Yes I would like that',
],
slots: [],
},
{
name: 'NoIntent',
samples: ['No', 'No thank you'],
slots: [],
});
//Special intent for sending message (Dialog)
allIntents.push ({
name: 'EmailIntent',
name: 'SendMessageIntent',
samples: [
'I would like to send a message',
'I want to send a message',
'Send message',
],
slots: [
{
name: 'Name',
type: 'AMAZON.US_FIRST_NAME',
samples: ['My name is {Name}', 'I am {Name}', '{Name}'],
},
{
name: 'Email',
type: 'AMAZON.LITERAL',
type: 'EmailSlot',
samples: ['My email is {Email}', '{Email}'],
},
{
name: 'Message',
type: 'AMAZON.LITERAL',
type: 'MessageSlot',
samples: ['{Message}'],
},
{
name: 'Data',
type: 'AMAZON.LITERAL',
},
],
samples: [
'My name is {Name}',
'I am {Name}',
'{exampleww at wwdwdw|Data}',
'My email is {example at efefegedd|Email}',
'Send replay to {example at abcdefg|Email}',
'My message is {The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.|Message}',
],
});
let customSlotTypes = [
{
name: 'EmailSlot',
values: [
{
id: null,
name: {
value: 'bla@bla.bla',
synonyms: [],
},
},
{
id: null,
name: {
value: 'bla.bla@bla.bla.bla',
synonyms: [],
},
},
{
id: null,
name: {
value: 'bla_bla@bla.bla',
synonyms: [],
},
},
],
},
{
name: 'MessageSlot',
values: [
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog',
synonyms: [],
},
},
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog.',
synonyms: [],
},
},
{
id: null,
name: {
value: 'Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog. Quick brown fox jumps over lazy dog.',
synonyms: [],
},
},
],
},
];
let dialogPrompts = [
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Name',
variations: [
{
type: 'PlainText',
value: 'What is your name ?',
},
{
type: 'PlainText',
value: 'Tell me your name',
},
],
},
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Email',
variations: [
{
type: 'PlainText',
value: 'What is your email ?',
},
{
type: 'PlainText',
value: 'Tell me your email',
},
],
},
{
id: 'Elicit.Intent-SendMessageIntent.IntentSlot-Message',
variations: [
{
type: 'PlainText',
value: 'What is your message',
},
],
},
];
let dialogIntents = [
{
name: 'SendMessageIntent',
confirmationRequired: false,
prompts: {},
slots: [
{
name: 'Name',
type: 'AMAZON.US_FIRST_NAME',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Name',
},
},
{
name: 'Email',
type: 'EmailSlot',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Email',
},
},
{
name: 'Message',
type: 'MessageSlot',
elicitationRequired: true,
confirmationRequired: false,
prompts: {
elicitation: 'Elicit.Intent-SendMessageIntent.IntentSlot-Message',
},
},
],
},
];
result.interactionModel = {};
result.interactionModel.languageModel = {
invocationName: skill.invocationName,
types: customSlotTypes,
intents: allIntents,
};
result.interactionModel.prompts = dialogPrompts;
result.interactionModel.dialog = {};
result.interactionModel.dialog.intents = dialogIntents;
return JSON.stringify (result);
};
var uploadSkill = function (skill) {
let generatedInteractionModel = generateInteractionModel (skill);
console.log(skill.skillID);
return fetch (
`https://api.amazonalexa.com/v0/skills/${skill.skillID}/interactionModel/locales/en-US`,
`https://api.amazonalexa.com/v1/skills/${skill.skillID}/stages/development/interactionModel/locales/en-US`,
{
method: 'POST',
method: 'PUT',
headers: {
Authorization: config.TOKEN,
},
body: generateInteractionModel (skill),
body: generatedInteractionModel,
}
);
};

75
backend/helpers/email.js Normal file
View File

@@ -0,0 +1,75 @@
const nodemailer = require ('nodemailer');
const emailConfig = require('../config/email');
module.exports = {
transformEmailFromAlexaResponse: function (email) {
//email from alexa response will contain words instead of symbols, like :
//at = @
//underscore = _
//dash = -
//dot = .
//TODO: This list should be longer
let transformedEmail = email
.replace (/\s/g, '') //remove all spaces
.replace (/at/gi, '@')
.replace (/underscore/gi, '_')
.replace (/dash/gi, '-')
.replace (/dot/gi, '.');
return transformedEmail;
},
isEmailValid: function (email) {
console.log ('Email to validate : ' + email);
let validEmailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return validEmailRegex.test (email);
},
sendEmail: function (name, fromEmail, message, toEmail) {
return new Promise ((resolve, reject) => {
fromEmail = this.transformEmailFromAlexaResponse(fromEmail);
let messageBody =
'Hello. User left you a message on Saburly service using Alexa skill. \r\nMessage : ' +
message +
'\r\nName : ' +
name +
'\r\nEmail : ' +
fromEmail +
'\r\nYour Saburly team';
let messageBodyHTML =
'<p>Hello. User left you a message on Saburly service using Alexa skill.</p><br/><b>Message : </b><br/><p>' +
message +
'</p><br/><b>Name : </b>' +
name +
'<br/><b>Email : </b>' +
fromEmail +
'<br/><br/><b>Your Saburly team</b>';
let transporter = nodemailer.createTransport ({
host: emailConfig.SMTP_HOST,
port: emailConfig.PORT,
secure: emailConfig.SECURE,
auth: emailConfig.AUTH,
});
var mailOptions = {
from: emailConfig.FROM_EMAIL,
replyTo: fromEmail,
to: toEmail,
subject: emailConfig.SUBJECT,
text: messageBody,
html: messageBodyHTML,
};
transporter.sendMail (mailOptions, (error, info) => {
if (error) {
reject (error);
} else {
resolve (info);
}
});
});
},
};

View File

@@ -0,0 +1,44 @@
let request = require ('request');
let Parser = require ('rss-parser');
let parser = new Parser ();
getDataFromWPJSON = function (sourceUrl, page = 1, maxPosts = 10) {
return new Promise ((resolve, reject) => {
var options = {
method: 'GET',
url: `${sourceUrl}/wp-json/wp/v2/posts`,
qs:{
page:page,
per_page:maxPosts
}
};
request (options, (error, response, body)=> {
if (error) {
reject (error);
} else {
resolve(JSON.parse (body));
}
});
});
}
module.exports = {
getAnswerFromWP : function (sourceUrl){
//This function will extract needed data from JSON, which we got from getDataFromWPJSON
//At the moment, it's taking titles and creates answer
return new Promise((resolve,reject)=>{
getDataFromWPJSON(sourceUrl).then(rawData=>{
let result='';
rawData.forEach(post=>{
result += post.title.rendered + '<break time="300ms"/> '
});
resolve(result);
}).catch(err=>{
reject('Failed to get answer');
});
});
}
}

View File

@@ -0,0 +1,107 @@
const constants = require ('../config/constants');
validateEmail = function (email) {
if (email.length > constants.stringConstraints.EMAIL_MAX_LENGTH) return false;
let validEmailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return validEmailRegex.test (email);
};
validateIntentName = function (intentName) {
if (
intentName.length < constants.stringConstraints.INTENT_NAME_MIN_LENGTH ||
intentName.length > constants.stringConstraints.INTENT_NAME_MAX_LENGTH
)
return false;
let validIntentNameRegex = /^[a-z]*$/i;
return validIntentNameRegex.test (intentName);
};
validateQuestion = function (question) {
if (
question.length < constants.stringConstraints.QUESTION_MIN_LENGTH ||
question.length > constants.stringConstraints.QUESTION_MAX_LENGTH
)
return false;
let validQuestionNameRegex = /^[a-z,.' ]*$/i;
return validQuestionNameRegex.test (question);
};
validateAnswer = function (answer, answerType) {
if (answerType !== constants.answerType.PREDEFINED) return true;
if (
answer.length < constants.stringConstraints.ANSWER_MIN_LENGTH ||
answer.length > constants.stringConstraints.ANSWER_MAX_LENGTH
)
return false;
let validAnswerRegex = /^[a-z,.' ]*$/i;
return validAnswerRegex.test (answer);
};
validateExternalAnswerSource = function (externalAnswerSource, answerType){
// TODO: implement validation logic
return true;
}
validateInvocationName = function (invocationName) {
if (
invocationName.length < constants.stringConstraints.INVOCATION_NAME_MIN_LENGTH ||
invocationName.length > constants.stringConstraints.INVOCATION_NAME_MAX_LENGTH
)
return false;
let validInvocationNameRegex = /^[a-z,.' ]*$/;
return validInvocationNameRegex.test (invocationName);
};
validateInvocationAnswer = function (invocationAnswer) {
if (invocationAnswer.length > constants.stringConstraints.INVOCATION_ANSWER_MAX_LENGTH)
return false;
let validInvocationAnswerRegex = /^[a-z,.' ]*$/i;
return validInvocationAnswerRegex.test (invocationAnswer);
};
validateIntentExplanation = function (explanation) {
if (explanation.length > constants.stringConstraints.INTENT_EXPLANATION_MAX_LENGTH)
return false;
let validExplanationRegex = /^[a-z,.' ]*$/i;
return validExplanationRegex.test (explanation);
};
module.exports = {
validateSkill: function (skill) {
try {
if (
!validateEmail (skill.contactEmail) ||
!validateInvocationName (skill.invocationName) ||
!validateInvocationAnswer (skill.invocationAnswer)
)
return false;
for (let i = 0; i < skill.intents.length; i++) {
if (!validateIntentName (skill.intents[i].intentName)) return false;
if (!validateAnswer (skill.intents[i].answer, skill.intents[i].answerType)) return false;
if (!validateExternalAnswerSource(skill.intents[i].externalAnswerSource, skill.intents[i].answerType)) return false;
for (let j = 0; j < skill.intents.length; j++) {
if (i === j) continue;
if (skill.intents[i].intentName === skill.intents[j].intentName)
return false;
}
for (let j = 0; j < skill.intents[i].questions.length; j++) {
if (!validateQuestion (skill.intents[i].questions[j])) return false;
for (let k = 0; k < skill.intents[i].questions.length; k++) {
if (j === k) continue;
if (skill.intents[i].questions[j] === skill.intents[i].questions[k])
return false;
}
}
}
return true;
} catch (e) {
console.log ('Error : ' + e);
return false;
}
},
};

280
backend/models/alexa.js Normal file
View File

@@ -0,0 +1,280 @@
var Alexa = require ('alexa-sdk');
const config = require ('../config/config');
var databaseHelper = require ('../helpers/database');
var emailHelper = require ('../helpers/email');
const constants = require ('../config/constants');
let predefinedSourceHelper = require ('../helpers/externalSource');
var handlers = {};
var destinationEmail;
let skillName;
module.exports = {
run: function (req, res) {
// Build the context manually, because Amazon Lambda is missing
var context = {
succeed: function (result) {
res.json (result);
},
fail: function (error) {
console.log (error);
//We could send error json from here
},
};
var alexa = Alexa.handler (req.body, context);
alexa.appId = config.SKILL_ID;
alexa.registerHandlers (handlers);
alexa.execute ();
},
updateModel: function () {
//Get info from database, and store it for faster response on intent
databaseHelper
.getSkill (config.SKILL_DB_ID)
.then (activeSkill => {
handlers = {};
destinationEmail = activeSkill.contactEmail;
skillName = activeSkill.invocationName;
let listOfPossibleQuestions = '';
activeSkill.intents.forEach (intent => {
if (intent.questions.length > 0 && intent.intentExplanation) {
listOfPossibleQuestions +=
intent.intentExplanation +
intent.questions[0] +
'<break time="' +
constants.voiceResponseTimings.PAUSE_BETWEEN_QUESTIONS +
'ms"/>';
}
});
listOfPossibleQuestions +=
'If you dont know what to do, just say help or stop';
//Handler for launch requestconsole.log()
handlers = {
LaunchRequest: function () {
this.response
.speak (
activeSkill.invocationAnswer +
'<break time="' +
constants.voiceResponseTimings.PAUSE_AFTER_WELCOME_MESSAGE +
'ms"/>' +
'Would you like to hear list of questions that you can ask me'
)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.attributes['LaunchRequestYesNo'] = true;
this.emit (':responseReady');
},
};
//Handlers for user defined questions
activeSkill.intents.map (intent => {
handlers[intent.intentName] = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
}
let answerPromiseProps = {
resolve: null,
reject: null
}
let answerPromise = new Promise ((resolve, reject) => {
answerPromiseProps = {
resolve:resolve,
reject:reject
}
});
switch (intent.answerType){
case constants.answerType.PREDEFINED:
answerPromiseProps.resolve(intent.answer);
break;
case constants.answerType.EXTERNAL_SOURCE_WP_TITLES:
predefinedSourceHelper.getAnswerFromWP(intent.externalAnswerSource).then(answer=>{
answerPromiseProps.resolve(answer);
}).catch(error=>{
answerPromiseProps.reject(error);
});
break;
case constants.answerType.EXTERNAL_SOURCE_WP_NEWS:
answer = 'Not implemented yet'
answerPromiseProps.resolve(answer);
break;
}
answerPromise
.then (answer => {
this.response
.speak (answer)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.emit (':responseReady');
})
.catch (error => {
this.response
.speak (error)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.emit (':responseReady');
});
};
});
//Handler for sending message
handlers.SendMessageIntent = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
}
let intent = this.event.request.intent;
console.log ('Dialog state : ' + this.event.request.dialogState);
console.log (intent);
//STARTED, IN_PROGRESS
if (!intent.slots.Name.value) {
//Name not defined yet, ask user for name
const slotToElicit = 'Name';
const speechOutput = 'What is your name';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else if (!intent.slots.Email.value) {
//Name not defined yet, ask user for email
const slotToElicit = 'Email';
const speechOutput =
'Ok ' + intent.slots.Name.value + '. What is your email';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else if (!intent.slots.Message.value) {
intent.slots.Email.value = emailHelper.transformEmailFromAlexaResponse (
intent.slots.Email.value
);
if (!emailHelper.isEmailValid (intent.slots.Email.value)) {
//Email is not valid, ask again
const slotToElicit = 'Email';
const speechOutput =
'Sorry, that was not valid email. What is your email';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
} else {
//Email is valid
const slotToElicit = 'Message';
const speechOutput = 'Great. What is your message';
const repromptSpeech = speechOutput;
this.emit (
':elicitSlot',
slotToElicit,
speechOutput,
repromptSpeech
);
}
} else {
//all slots are filled
console.log ('Name : ' + intent.slots.Name.value);
console.log ('Email : ' + intent.slots.Email.value);
console.log ('Message : ' + intent.slots.Message.value);
emailHelper
.sendEmail (
intent.slots.Name.value,
intent.slots.Email.value,
intent.slots.Message.value,
destinationEmail
)
.then (info => {
console.log (info);
this.response.speak (
'Ok. Message sent. Someone will contact you ASAP'
);
this.emit (':responseReady');
})
.catch (error => {
console.log (error);
this.response.speak (
'Sorry, there was a problem with sending message.'
);
this.emit (':responseReady');
});
}
};
//Built-In intents
handlers.CancelIntent = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
}
this.response.speak (`Thank you for using ${skillName}`);
this.emit (':responseReady');
};
handlers.HelpIntent = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
}
this.response
.speak (listOfPossibleQuestions)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE); //Phrase from listen doesn't work !!!
this.emit (':responseReady');
};
handlers.YesIntent = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
this.emit ('HelpIntent');
} else {
this.response
.speak (constants.voiceResponseStrings.DIDNT_ASK_ANYTHING)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE);
this.emit (':responseReady');
}
};
handlers.NoIntent = function () {
if (this.attributes['LaunchRequestYesNo']) {
this.attributes['LaunchRequestYesNo'] = false;
this.response
.speak ('')
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE);
this.emit (':responseReady');
} else {
this.response
.speak (constants.voiceResponseStrings.DIDNT_ASK_ANYTHING)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE);
this.emit (':responseReady');
}
};
//Default handler for unknown question
handlers.Unhandled = function () {
this.response
.speak (constants.voiceResponseStrings.QUESTION_NOT_FOUND)
.listen (constants.voiceResponseStrings.GENERIC_CONTINUE);
};
//Session handlers
handlers.SessionEndedRequest = function () {
//We don't care for now
};
})
.catch (e => {
//Something is wrong, skill is not ready, use catch-all intent to inform user
console.log ('Error. Skill doesnt exist');
});
},
};

1717
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +1,18 @@
{
"name": "example",
"name": "tellall",
"version": "1.0.0",
"description": "",
"main": "test.js",
"dependencies": {
"alexa-app": "4.2.0",
"alexa-sdk": "^1.0.25",
"body-parser": "^1.13.1",
"ejs": "^2.5.7",
"express": "^4.13.0",
"isomorphic-fetch": "^2.2.1",
"mongodb": "^2.2.33",
"request": "^2.83.0"
},
"author": "Matt Kruse <github@mattkruse.com> (http://mattkruse.com/)",
"license": "MIT"
"nodejs-text-summarizer": "^2.0.3",
"nodemailer": "^4.4.1",
"request": "^2.83.0",
"rss-parser": "^3.1.1"
}
}

View File

@@ -1,11 +1,7 @@
var amazonHelper = require ('./helpers/amazon');
var databaseHelper = require ('./helpers/database');
const config = require ('./config/config');
const constants = require ('./config/constants');
require ('isomorphic-fetch');
var express = require ('express');
var alexa = require('./components/alexa');
var alexa = require ('./models/alexa');
var MongoClient = require ('mongodb').MongoClient;
var ObjectID = require ('mongodb').ObjectID;
@@ -13,10 +9,7 @@ var ObjectID = require ('mongodb').ObjectID;
const router = express.Router ();
var app = express ();
// ALWAYS setup the alexa app and attach it to express before anything else.
alexa.init (app);
app.set ('view engine', 'ejs');
app.set ('view engine', 'ejs'); // Should be removed
app.use (require ('./middleware')); //common middleware for all requests
app.use (require ('./controllers')); //all routes
@@ -26,7 +19,7 @@ MongoClient.connect (config.DB_URL)
app.listen (config.PORT, () => {
console.log ('Express server running on port ' + config.PORT);
alexa.updateIntentsJSON ();
alexa.updateModel ();
databaseHelper.loadTokens ();
});
})

2099
web/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,7 @@
"private": true,
"dependencies": {
"keymaster": "^1.6.2",
"node-sass-chokidar": "0.0.3",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-md": "^1.2.8",
@@ -17,7 +18,7 @@
"watch-css": "nodemon -e scss -x \"npm run watch-css-mine\"",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"react-build" : "react-scripts build",
"react-build": "react-scripts build",
"build": "npm-run-all -p build-css react-build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"

View File

@@ -1,4 +1,4 @@
import React, { Component } from 'react';
import React, {Component} from 'react';
import './css/App.css';
import './css/popup.css';
import IntentList from './components/IntentList';
@@ -6,90 +6,125 @@ import IntentDetails from './components/IntentDetails';
import LaunchRequest from './components/LaunchRequest';
import Contact from './components/Contact';
import Popup from 'react-popup';
import {getSkill, updateSkill} from './lib/api'
import {getSkill, updateSkill} from './lib/api';
import {isEmailValid} from './lib/helpers';
import {
NEW_INTENT_SELECTED_INDEX,
LAUNCH_REQUEST_SELECTED_INDEX,
CONTACT_SELECTED_INDEX,
RESULT_CODES} from './config/constants'
NEW_INTENT_SELECTED_INDEX,
LAUNCH_REQUEST_SELECTED_INDEX,
CONTACT_SELECTED_INDEX,
RESULT_CODES,
INVOCATION_NAME_MIN_LENGTH,
INTENT_NAME_MIN_LENGTH,
QUESTION_MIN_LENGTH,
ANSWER_MIN_LENGTH,
ANSWER_TYPE,
} from './config/constants';
class App extends Component {
constructor (props) {
super (props);
constructor(props){
super(props);
this.state = {
_id: '5abd461329f85e4ec728d945',
skillID: '',
skillName: '',
invocationName: 'Saburly',
invocationAnswer: 'We are saburly',
allIntents: [],
selectedIntent: {
intentName: '',
intentExplanation: '',
questions: [''],
answer: '',
answerType: ANSWER_TYPE.PREDEFINED,
externalAnswerSource: '',
},
selectedIndex: NEW_INTENT_SELECTED_INDEX,
contactEmail: '',
waiting: false,
};
this.state={_id:'5a232fb86ce046c749739455',
skillID:'',
skillName:'',
invocationName:'Saburly',
invocationAnswer:'We are saburly',
allIntents:[],
selectedIntent: {intentName:'',questions:[''],answer:''},
selectedIndex:NEW_INTENT_SELECTED_INDEX,
contactEmail:'',
waiting: false
};
getSkill (this.state._id).then (l => l.json ()).then (result => {
if (result === undefined) return;
this.setState ({
skillID: result.skillID,
skillName: result.skillName,
invocationName: result.invocationName,
invocationAnswer: result.invocationAnswer,
allIntents: result.intents,
contactEmail: result.contactEmail,
});
});
getSkill(this.state._id).then(l=>l.json()).then(result=>{
if (result===undefined) return;
this.setState({ skillID:result.skillID,skillName:result.skillName, invocationName: result.invocationName,
invocationAnswer: result.invocationAnswer,
allIntents: result.intents, contactEmail: result.contactEmail})
})
this.handleIntentClick = this.handleIntentClick.bind(this);
this.handleLaunchRequestClick = this.handleLaunchRequestClick.bind(this);
this.handleDeleteIntentClick = this.handleDeleteIntentClick.bind(this);
this.handleSaveIntentClick = this.handleSaveIntentClick.bind(this);
this.handleAddIntentClick = this.handleAddIntentClick.bind(this);
this.handleSaveLaunchRequestClick = this.handleSaveLaunchRequestClick.bind(this);
this.createSkill = this.createSkill.bind(this);
this.sendSkill = this.sendSkill.bind(this);
this.handleContactClick = this.handleContactClick.bind(this);
this.handleSaveEmailClick = this.handleSaveEmailClick.bind(this);
this.handleIntentClick = this.handleIntentClick.bind (this);
this.handleLaunchRequestClick = this.handleLaunchRequestClick.bind (this);
this.handleDeleteIntentClick = this.handleDeleteIntentClick.bind (this);
this.handleSaveIntentClick = this.handleSaveIntentClick.bind (this);
this.handleAddIntentClick = this.handleAddIntentClick.bind (this);
this.handleSaveLaunchRequestClick = this.handleSaveLaunchRequestClick.bind (
this
);
this.createSkill = this.createSkill.bind (this);
this.sendSkill = this.sendSkill.bind (this);
this.handleContactClick = this.handleContactClick.bind (this);
this.handleSaveEmailClick = this.handleSaveEmailClick.bind (this);
}
render() {
render () {
let rightPanel;
switch (this.state.selectedIndex) {
case LAUNCH_REQUEST_SELECTED_INDEX:
rightPanel = <LaunchRequest invocationName={this.state.invocationName}
invocationAnswer={this.state.invocationAnswer}
onSaveClick={this.handleSaveLaunchRequestClick}
waiting={this.state.waiting}/> ;
rightPanel = (
<LaunchRequest
invocationName={this.state.invocationName}
invocationAnswer={this.state.invocationAnswer}
onSaveClick={this.handleSaveLaunchRequestClick}
waiting={this.state.waiting}
/>
);
break;
case CONTACT_SELECTED_INDEX:
rightPanel = <Contact contactEmail={this.state.contactEmail}
onSaveEmailClick={this.handleSaveEmailClick}
waiting={this.state.waiting}/> ;
rightPanel = (
<Contact
contactEmail={this.state.contactEmail}
onSaveEmailClick={this.handleSaveEmailClick}
waiting={this.state.waiting}
/>
);
break;
default:
rightPanel = <IntentDetails selectedIntent={this.state.selectedIntent}
onDeleteIntentClick={this.handleDeleteIntentClick}
onSaveIntentClick={this.handleSaveIntentClick}
waiting={this.state.waiting}/>;
rightPanel = (
<IntentDetails
selectedIntent={this.state.selectedIntent}
onDeleteIntentClick={this.handleDeleteIntentClick}
onSaveIntentClick={this.handleSaveIntentClick}
waiting={this.state.waiting}
/>
);
}
return(
return (
<div className="App">
<Popup/>
<Popup />
<div className="App-header">
<h1> Tell All </h1>
</div>
<IntentList allIntents={this.state.allIntents}
onLaunchRequestClick={this.handleLaunchRequestClick}
onContactClick={this.handleContactClick}
onIntentClick={this.handleIntentClick}
onAddIntentClick={this.handleAddIntentClick}
selectedIndex={this.state.selectedIndex}
waiting={this.state.waiting}/>
<IntentList
allIntents={this.state.allIntents}
onLaunchRequestClick={this.handleLaunchRequestClick}
onContactClick={this.handleContactClick}
onIntentClick={this.handleIntentClick}
onAddIntentClick={this.handleAddIntentClick}
selectedIndex={this.state.selectedIndex}
waiting={this.state.waiting}
/>
{rightPanel}
</div>
);
}
createSkill(intents, name, answer, email, updateOnAmazon){
createSkill (intents, name, answer, email, updateOnAmazon) {
return {
_id: this.state._id,
skillID: this.state.skillID,
@@ -97,97 +132,239 @@ class App extends Component {
invocationName: name,
invocationAnswer: answer,
contactEmail: email,
updateOnAmazon: updateOnAmazon
updateOnAmazon: updateOnAmazon,
};
}
handleIntentClick(selectedIntent, index){
this.setState({selectedIntent:selectedIntent, selectedIndex: index, launchRequest:false});
handleIntentClick (selectedIntent, index) {
this.setState ({
selectedIntent: selectedIntent,
selectedIndex: index,
});
}
handleLaunchRequestClick(){
this.setState({selectedIndex: LAUNCH_REQUEST_SELECTED_INDEX});
handleLaunchRequestClick () {
this.setState ({selectedIndex: LAUNCH_REQUEST_SELECTED_INDEX});
}
handleContactClick(){
this.setState({selectedIndex: CONTACT_SELECTED_INDEX})
handleContactClick () {
this.setState ({selectedIndex: CONTACT_SELECTED_INDEX});
}
handleSaveLaunchRequestClick(name, answer){
this.setState({waiting:true, invocationName:name, invocationAnswer: answer});
this.sendSkill(this.state.allIntents,true,{waiting:false},{waiting:false},name,answer,this.state.contactEmail,true);
handleSaveLaunchRequestClick (name, answer) {
if (name.length < INVOCATION_NAME_MIN_LENGTH) {
Popup.alert ('Invocation name should be at least 2 characters long');
return;
}
this.setState ({
waiting: true,
invocationName: name,
invocationAnswer: answer,
});
this.sendSkill (
this.state.allIntents,
true,
{waiting: false},
{waiting: false},
name,
answer,
this.state.contactEmail,
true
);
}
handleSaveEmailClick(email){
this.setState({waiting:true});
this.sendSkill(this.state.allIntents,true,{contactEmail: email, waiting:false},{waiting:false},this.state.invocationName,this.state.invocationAnswer,email,false);
handleSaveEmailClick (email) {
if (isEmailValid (email)) {
this.setState ({waiting: true});
this.sendSkill (
this.state.allIntents,
true,
{contactEmail: email, waiting: false},
{waiting: false},
this.state.invocationName,
this.state.invocationAnswer,
email,
false
);
} else {
Popup.alert ('Please enter valid email');
}
}
handleDeleteIntentClick(selectedIntent){
handleDeleteIntentClick (selectedIntent) {
let id = -1;
//TODO : Change comparsion method ! Same object with different proeprty sorting will not be same string
this.state.allIntents.map((intent,index)=>{
if ((id===-1) && (JSON.stringify(selectedIntent)===JSON.stringify(intent)))
id = index;
this.state.allIntents.map ((intent, index) => {
if (
id === -1 &&
JSON.stringify (selectedIntent) === JSON.stringify (intent)
)
id = index;
});
if (id!==-1){
try{
let newAllIntentsJSON = JSON.stringify(this.state.allIntents);
let newAllIntents = JSON.parse(newAllIntentsJSON);
newAllIntents.splice(id,1);
this.setState({waiting:true});
if (id !== -1) {
try {
let newAllIntentsJSON = JSON.stringify (this.state.allIntents);
let newAllIntents = JSON.parse (newAllIntentsJSON);
newAllIntents.splice (id, 1);
this.setState ({waiting: true});
let newState = {allIntents: newAllIntents, selectedIntent: {intentName:'', questions:[''],answer:''}, waiting:false};
this.sendSkill(newAllIntents,true,newState,{waiting:false},this.state.invocationName,this.state.invocationAnswer,this.state.contactEmail,true);
}catch(e){
console.log("error : " + e);
let newState = {
allIntents: newAllIntents,
selectedIntent: {intentName: '', questions: [''], answer: ''},
waiting: false,
};
this.sendSkill (
newAllIntents,
true,
newState,
{waiting: false},
this.state.invocationName,
this.state.invocationAnswer,
this.state.contactEmail,
true
);
} catch (e) {
console.log ('error : ' + e);
}
}
}
handleSaveIntentClick(selectedIntent){
let newAllIntentsJSON = JSON.stringify(this.state.allIntents);
let newAllIntents = JSON.parse(newAllIntentsJSON);
let newState = null;
if (this.state.selectedIndex === NEW_INTENT_SELECTED_INDEX){
//new intent
newAllIntents.push(selectedIntent);
newState = {allIntents: newAllIntents, selectedIntent: selectedIntent, selectedIndex: newAllIntents.length-1, waiting:false};
}else{
newAllIntents[this.state.selectedIndex] = selectedIntent;
newState = {allIntents: newAllIntents, selectedIntent: selectedIntent, waiting: false};
handleSaveIntentClick (selectedIntent) {
if (selectedIntent.intentName.length < INTENT_NAME_MIN_LENGTH) {
Popup.alert ('Question name should have at least 2 characters');
return;
}
this.setState({waiting:true});
this.sendSkill(newAllIntents, true, newState, {waiting:false}, this.state.invocationName,this.state.invocationAnswer,this.state.contactEmail, true);
}
handleAddIntentClick(){
this.setState({allIntents: this.state.allIntents, selectedIndex: NEW_INTENT_SELECTED_INDEX,launchRequest:false,selectedIntent: {intentName:'',questions:[''], answer:''}});
}
if (
selectedIntent.answerType === ANSWER_TYPE.PREDEFINED &&
selectedIntent.answer.length < ANSWER_MIN_LENGTH
) {
Popup.alert ('Answer should have at least 2 characters');
return;
}
sendSkill(newAllIntents, showPopUp, resolveState, rejectState, newName, newAnswer, email, updateOnAmazon){
return new Promise((resolve,reject)=>{
updateSkill(this.createSkill(newAllIntents,newName,newAnswer,email,updateOnAmazon)).then(l=>l.json()).then(result=>{
if (result.result !== RESULT_CODES.OK){
console.log(result.result);
if (showPopUp) Popup.alert('Model was not saved. Please try again');
this.setState(rejectState);
//reject('Error code : ' + jResult.result);
}else{
if (showPopUp) Popup.alert('Saved');
this.setState(resolveState);
resolve();
}
}).catch(e=>{
console.log('error : ' + e);
if (showPopUp) Popup.alert('Model was not saved. Please try again');
this.setState(rejectState);
//reject(e);
for (let i = 0; i < selectedIntent.questions.length; i++) {
if (selectedIntent.questions[i].length < QUESTION_MIN_LENGTH) {
Popup.alert ('Question variant should have at least 2 characters');
return;
}
}
//Check for same question variants and same question name in other intents
//all intents with the same intentName, or some of the questions are the same
//will be kept in filteredIntents. After filterring, there should be only one
//intent left, the selected one
let selectedIntentQuestionsForSearch = selectedIntent.questions.map(question=>
question.toLowerCase().trim());
let filteredIntents = this.state.allIntents.filter(intent=>{
let result = (selectedIntent.intentName.toLowerCase().trim() === intent.intentName.toLowerCase().trim());
let filteredQuestions = intent.questions.filter(question=>{
return (selectedIntentQuestionsForSearch.indexOf(question.toLowerCase().trim())!==-1);
});
return (result || filteredQuestions.length > 0);
});
if (filteredIntents.length > 1){
Popup.alert('Question name or question variant already exists');
return;
}
let newAllIntentsJSON = JSON.stringify (this.state.allIntents);
let newAllIntents = JSON.parse (newAllIntentsJSON);
let resolveState = null;
let rejectState = {waiting: false};
if (this.state.selectedIndex === NEW_INTENT_SELECTED_INDEX) {
//new intent
newAllIntents.push (selectedIntent);
resolveState = {
allIntents: newAllIntents,
selectedIntent: selectedIntent,
selectedIndex: newAllIntents.length - 1,
waiting: false,
};
} else {
newAllIntents[this.state.selectedIndex] = selectedIntent;
resolveState = {
allIntents: newAllIntents,
selectedIntent: selectedIntent,
waiting: false,
};
}
this.setState ({waiting: true});
this.sendSkill (
newAllIntents,
true,
resolveState,
rejectState,
this.state.invocationName,
this.state.invocationAnswer,
this.state.contactEmail,
true
);
}
handleAddIntentClick () {
this.setState ({
allIntents: this.state.allIntents,
selectedIndex: NEW_INTENT_SELECTED_INDEX,
launchRequest: false,
selectedIntent: {
intentName: '',
questions: [''],
answer: '',
intentExplanation: '',
answerType: ANSWER_TYPE.PREDEFINED,
externalAnswerSource: '',
},
});
}
sendSkill (
newAllIntents,
showPopUp,
resolveState,
rejectState,
newName,
newAnswer,
email,
updateOnAmazon
) {
return new Promise ((resolve, reject) => {
updateSkill (
this.createSkill (
newAllIntents,
newName,
newAnswer,
email,
updateOnAmazon
)
)
.then (l => l.json ())
.then (result => {
if (result.result !== RESULT_CODES.OK) {
console.log (result);
if (showPopUp)
Popup.alert ('Model was not saved. Please try again');
this.setState (rejectState);
//reject('Error code : ' + jResult.result);
} else {
if (showPopUp) Popup.alert ('Saved');
this.setState (resolveState);
resolve ();
}
})
.catch (e => {
console.log ('error : ' + e);
if (showPopUp) Popup.alert ('Model was not saved. Please try again');
this.setState (rejectState);
//reject(e);
});
});
}
}

View File

@@ -0,0 +1,60 @@
import React, {Component} from 'react';
import {Button} from 'react-md';
import AnswerSourceForm from './helper/AnswerSourceForm';
import '../css/components/IntentDetails.css';
class AnswerSource extends Component {
constructor (props) {
super (props);
this.state = {
isModalOpen: false,
answerType: this.props.answerType
};
}
onOpen () {
this.setState ({
isModalOpen: true,
answerType: this.props.answerType
});
}
onClose () {
this.setState ({
isModalOpen: false,
});
}
onSave(){
this.onClose();
this.props.onSaveAnswerType(this.state.answerType);
}
onSourceChange(value, event){
this.setState({answerType:parseInt(value,10)});
}
render () {
let modal;
if (this.state.isModalOpen) {
modal = <AnswerSourceForm
isModalOpen={this.state.isModalOpen}
answerType={this.state.answerType}
onSave={this.onSave.bind(this)}
onClose={this.onClose.bind(this)}
onSourceChange={this.onSourceChange.bind(this)}
/>
}
return (
<div>
<Button flat primary onClick={this.onOpen.bind (this)}>
Answer type
</Button>
{modal}
</div>
);
}
}
export default AnswerSource;

View File

@@ -1,115 +1,201 @@
import React, { Component } from 'react';
import React, {Component} from 'react';
import {Button, SVGIcon, TextField} from 'react-md';
import AnswerSource from './AnswerSource.js';
import '../css/components/IntentDetails.css';
import {QUESTION_MAX_LENGTH, ANSWER_MAX_LENGTH, INTENT_NAME_MAX_LENGTH} from '../config/constants';
import '../css/Common.css';
import {
QUESTION_MAX_LENGTH,
ANSWER_MAX_LENGTH,
INTENT_NAME_MAX_LENGTH,
INTENT_EXPLANATION_MAX_LENGTH,
ANSWER_TYPE,
} from '../config/constants';
import AnswerTextBox from './helper/AnswerTextBox.js';
class IntentDetails extends Component {
constructor(props){
super(props);
constructor (props) {
super (props);
this.state= {intent: props.selectedIntent};
this.state = {intent: props.selectedIntent};
this.addQuestion = this.addQuestion.bind(this);
this.deleteQuestion = this.deleteQuestion.bind(this);
this.handleQuestionEdit = this.handleQuestionEdit.bind(this);
this.handleAnswerEdit = this.handleAnswerEdit.bind(this);
this.handleIntentNameEdit = this.handleIntentNameEdit.bind(this);
this.addQuestion = this.addQuestion.bind (this);
this.deleteQuestion = this.deleteQuestion.bind (this);
this.handleQuestionEdit = this.handleQuestionEdit.bind (this);
this.handleIntentNameEdit = this.handleIntentNameEdit.bind (this);
this.handleIntentExplanationEdit = this.handleIntentExplanationEdit.bind (
this
);
}
componentWillReceiveProps(props){
this.setState({intent: props.selectedIntent});
componentWillReceiveProps (props) {
this.setState ({intent: props.selectedIntent});
}
render() {
render () {
return (
<div className="RightPanelBox">
<div className="QuestionBox">
<h5 className="PanelSubTitle">
{' '}
In introduction, Alexa will help users to ask her the right questions about your business. For Example, she will say : "To ask us about our services, say : What do you do ? ". What do you do ? is defined in question field. Alexa will use first variation of question in intro.
</h5>
<TextField
id="intent explanation"
lineDirection="center"
placeholder="To ask us about our services, say "
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={this.handleIntentExplanationEdit}
maxLength={INTENT_EXPLANATION_MAX_LENGTH}
value={this.state.intent.intentExplanation}
/>
<br />
<TextField
id="intent name"
lineDirection="center"
placeholder="Intent name"
label="Question name"
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={this.handleIntentNameEdit}
maxLength={INTENT_NAME_MAX_LENGTH}
value={this.state.intent.intentName} />
value={this.state.intent.intentName}
/>
</div>
<h5 className="QuestionTitle">Question variants</h5>
{
this.state.intent.questions.map((question, index)=>{
return (
<div key={index} className="QuestionBox">
<TextField
id="intent question"
lineDirection="center"
placeholder="Question"
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
maxLength={QUESTION_MAX_LENGTH}
rightIcon={<SVGIcon onClick={()=>{this.deleteQuestion(question)}}> <path fill="#000000" d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"/> </SVGIcon>}
onChange={(e)=>{this.handleQuestionEdit(e,index)}}
value={question}/>
</div>
);
})
}
<br></br>
{
<div className="QuestionBox">
<TextField
id="intent answer"
lineDirection="center"
label="Answer"
placeholder="Answer"
maxLength={ANSWER_MAX_LENGTH}
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={this.handleAnswerEdit}
value={this.state.intent.answer}/>
</div>
}
<br></br>
<br></br>
<Button className="IntentDetailsButton" flat primary onClick={()=>{this.props.onDeleteIntentClick(this.state.intent)}} disabled={this.props.waiting}>Delete question</Button>
<Button className="IntentDetailsButton" flat primary swapTheming onClick={this.addQuestion} disabled={this.props.waiting}>Add variant</Button>
<Button className="IntentDetailsButton" flat primary swapTheming onClick={()=>{this.props.onSaveIntentClick(this.state.intent)}} disabled={this.props.waiting}>Save</Button>
{this.state.intent.questions.map ((question, index) => {
return (
<div key={index} className="QuestionBox">
<TextField
id="intent question"
lineDirection="center"
placeholder="Question"
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
maxLength={QUESTION_MAX_LENGTH}
rightIcon={
<SVGIcon
onClick={() => {
this.deleteQuestion (question);
}}
>
{' '}
<path
fill="#000000"
d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"
/>
{' '}
</SVGIcon>
}
onChange={e => {
this.handleQuestionEdit (e, index);
}}
value={question}
/>
</div>
);
})}
<Button
className="AddQuestionVariantButton"
icon
primary
onClick={this.addQuestion}
disabled={this.props.waiting}
>
add
</Button>
<AnswerSource
className="AnswerTypeButton"
onSaveAnswerType={this.handleExternalSourceSave.bind(this)}
answerType={this.state.intent.answerType}
/>
<AnswerTextBox
answerType={this.state.intent.answerType}
externalAnswerSource={this.state.intent.externalAnswerSource}
handleAnswerSourceEdit={this.handleAnswerSourceEdit.bind(this)}
handleAnswerEdit={this.handleAnswerEdit.bind(this)}
answer={this.state.intent.answer}
/>
<Button
className="IntentDetailsButton-firstInRow"
flat
primary
swapTheming
onClick={() => {
this.props.onSaveIntentClick (this.state.intent);
}}
disabled={this.props.waiting}
>
Save
</Button>
<Button
className="IntentDetailsButton"
flat
primary
onClick={() => {
this.props.onDeleteIntentClick (this.state.intent);
}}
disabled={this.props.waiting}
>
Delete
</Button>
</div>
);
}
addQuestion(){
addQuestion () {
let newIntent = this.state.intent;
newIntent.questions.push('');
this.setState({intent: newIntent});
newIntent.questions.push ('');
this.setState ({intent: newIntent});
}
deleteQuestion(question){
let newIntent = this.state.intent;
let removeId = newIntent.questions.indexOf(question);
if (removeId !== -1)
newIntent.questions.splice(removeId,1);
this.setState({intent: newIntent});
deleteQuestion (question) {
if (this.state.intent.questions.length > 1) {
let newIntent = this.state.intent;
let removeId = newIntent.questions.indexOf (question);
if (removeId !== -1) newIntent.questions.splice (removeId, 1);
this.setState ({intent: newIntent});
}
}
handleQuestionEdit(e,index){
if (e.length === QUESTION_MAX_LENGTH) return;
handleQuestionEdit (e, index) {
if (e.length === QUESTION_MAX_LENGTH || !/^[a-z,.' ]*$/i.test (e)) return;
let newIntent = this.state.intent;
newIntent.questions[index] = e;
this.setState({intent: newIntent});
this.setState ({intent: newIntent});
}
handleAnswerEdit(e){
if (e.length === ANSWER_MAX_LENGTH) return;
handleIntentExplanationEdit (e, index) {
if (e.length === INTENT_EXPLANATION_MAX_LENGTH || !/^[a-z,.' ]*$/i.test (e))
return;
let newIntent = this.state.intent;
newIntent.intentExplanation = e;
this.setState ({intent: newIntent});
}
handleAnswerEdit (e) {
if (e.length === ANSWER_MAX_LENGTH || !/^[a-z,.' ]*$/i.test (e)) return;
let newIntent = this.state.intent;
newIntent.answer = e;
this.setState({intent: newIntent});
this.setState ({intent: newIntent});
}
handleIntentNameEdit(e){
if (e.length === INTENT_NAME_MAX_LENGTH) return;
handleAnswerSourceEdit (e) {
if (e.length === ANSWER_MAX_LENGTH) return;
let newIntent = this.state.intent;
newIntent.externalAnswerSource = e;
this.setState ({intent: newIntent});
}
handleIntentNameEdit (e) {
if (e.length === INTENT_NAME_MAX_LENGTH || !/^[a-z]*$/i.test (e)) return;
let newIntent = this.state.intent;
newIntent.intentName = e;
this.setState({intent: newIntent});
this.setState ({intent: newIntent});
}
handleExternalSourceSave (answerType) {
let newIntent = this.state.intent;
newIntent.answerType = answerType;
this.setState ({intent: newIntent});
}
}

View File

@@ -25,7 +25,7 @@ class LaunchRequest extends Component {
<TextField
id="invocation name"
lineDirection="center"
placeholder="Saburly"
placeholder="saburly"
label="Invocation name"
className="md-cell md-cell--bottom InvocationInputBoxes"
maxLength={INVOCATION_NAME_MAX_LENGTH}
@@ -52,12 +52,12 @@ class LaunchRequest extends Component {
}
handleNameEdit(e){
if (e.length === INVOCATION_NAME_MAX_LENGTH) return;
if (e.length === INVOCATION_NAME_MAX_LENGTH || !(/^[a-z,.' ]*$/.test(e))) return;
this.setState({invocationName: e});
}
handleAnswerEdit(e){
if (e.length === INVOCATION_ANSWER_MAX_LENGTH) return;
if (e.length === INVOCATION_ANSWER_MAX_LENGTH || !(/^[a-z,.' ]*$/i.test(e))) return;
this.setState({invocationAnswer: e});
}
}

View File

@@ -0,0 +1,57 @@
import React, {Component} from 'react';
import {Button, SelectionControlGroup} from 'react-md';
import Modal from './Modal';
class AnswerSourceForm extends Component{
render(){
return(
<Modal
title="Answer type"
actions={[
<Button
flat
swapTheming
onClick={this.props.onClose.bind (this)}
key="cancel"
>
Cancel
</Button>,
<Button
flat
primary
swapTheming
key="save"
onClick={this.props.onSave.bind(this)}
>
Save
</Button>,
]}
>
<SelectionControlGroup
id="answer-source"
name="answer-source"
type="radio"
label="Import answer from:"
onChange={this.props.onSourceChange.bind(this)}
controls={[
{
label: 'Predefined answer',
value: '0'
},
{
label: 'WordPress titles',
value: '1',
},
{
label: 'WordPress latest news',
value: '2',
},
]}
defaultValue={String(this.props.answerType)}
/>
</Modal>);
}
}
export default AnswerSourceForm;

View File

@@ -0,0 +1,44 @@
import React, {Component} from 'react';
import {TextField} from 'react-md';
import '../../css/components/IntentDetails.css';
import '../../css/Common.css';
import {
ANSWER_MAX_LENGTH,
ANSWER_TYPE,
} from '../../config/constants';
class AnswerTextBox extends Component {
render () {
//theese are defaults for ANSWER_TYPE.PREDEFINED
let labelText="Answer";
let valueText=this.props.answer;
let onChangeValue=this.props.handleAnswerEdit;
switch(this.props.answerType){
case ANSWER_TYPE.EXTERNAL_SOURCE_WP_TITLES:
case ANSWER_TYPE.EXTERNAL_SOURCE_WP_NEWS:
labelText="Answer source";
valueText=this.props.externalAnswerSource;
onChangeValue=this.props.handleAnswerSourceEdit
break;
}
return(
<div className="QuestionBox">
<TextField
id="intent answer"
lineDirection="center"
label={labelText}
placeholder={labelText}
maxLength={ANSWER_MAX_LENGTH}
className="md-cell md-cell--bottom IntentDetailsInputBoxes"
onChange={onChangeValue}
value={valueText}
/>
</div>
);
}
}
export default AnswerTextBox;

View File

@@ -0,0 +1,23 @@
import React, { Component } from 'react';
import '../../css/components/Modal.css';
class Modal extends Component {
render() {
const { title, children, actions } = this.props;
return (
<div className="modal">
<div className="modal-content">
<h2 className="header">
{title}
</h2>
{children}
<div className="actions">
{actions}
</div>
</div>
</div>
);
}
}
export default Modal;

View File

@@ -1,11 +1,19 @@
export const INTENT_EXPLANATION_MAX_LENGTH = 70;
export const INTENT_NAME_MAX_LENGTH = 30;
export const INTENT_NAME_MIN_LENGTH = 2;
export const QUESTION_MAX_LENGTH = 150;
export const QUESTION_MIN_LENGTH = 2;
export const ANSWER_MAX_LENGTH = 150;
export const ANSWER_MIN_LENGTH = 2;
export const INTENT_TITLE_MAX_LENGTH = 20;
export const INTENT_TITLE_TOOLTIP_DELAY = 700;
export const INVOCATION_NAME_MAX_LENGTH = 15;
export const INVOCATION_NAME_MAX_LENGTH = 50;
export const INVOCATION_NAME_MIN_LENGTH = 2;
export const INVOCATION_ANSWER_MAX_LENGTH = 100;
export const EMAIL_MAX_LENGTH = 100;
@@ -14,6 +22,12 @@ export const NEW_INTENT_SELECTED_INDEX = -1;
export const LAUNCH_REQUEST_SELECTED_INDEX = -2;
export const CONTACT_SELECTED_INDEX = -3;
export const ANSWER_TYPE = {
PREDEFINED: 0,
EXTERNAL_SOURCE_WP_TITLES : 1,
EXTERNAL_SOURCE_WP_NEWS : 2
}
export const RESULT_CODES = {
OK: 0,
ERROR: -1,

View File

@@ -9,10 +9,25 @@
}
.IntentDetailsInputBoxes{
width: 60%;
width: 90%;
}
.IntentDetailsButton{
float: left;
margin-left: 25px;
float: right;
margin-right: 25px;
}
.IntentDetailsButton-firstInRow{
float: right;
margin-right: 10%;
}
.AddQuestionVariantButton{
float: right;
margin-right: 10%;
}
.AnswerTypeButton{
float: right;
margin-right: 30px;
}

View File

@@ -0,0 +1,32 @@
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(37, 37, 37, .7);
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
.modal-content {
color: black;
padding: 20px;
padding-bottom: 0px;
display: flex;
flex-direction: column;
align-items: flex-start;
height: auto;
background-color: #FFF;
min-width: 500px;
.actions {
border-top: 1px solid #bebebe;
width: 100%;
display: flex;
justify-content: flex-end;
min-width: 500px;
margin: 0 -20px;
padding: 10px;
}
}
}

View File

@@ -115,10 +115,10 @@ h5, .md-subheading-1 {
line-height: 24px; }
p, .md-body-1 {
line-height: 1.42857; }
line-height: 20px; }
h6, .md-body-2 {
line-height: 1.42857; }
line-height: 24px; }
caption, .md-caption {
font-size: 12px; }
@@ -1378,7 +1378,7 @@ tbody .md-table-row {
line-height: inherit; }
.md-table-checkbox .md-selection-control-label {
display: block; }
display: flex; }
.md-table-checkbox .md-selection-control-container {
margin-left: 12px;

View File

@@ -17,4 +17,4 @@ export const updateSkill = (skill)=>{
},
body: JSON.stringify(skill),
});
}
}

5
web/src/lib/helpers.js Normal file
View File

@@ -0,0 +1,5 @@
export const isEmailValid = email => {
let validEmailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return validEmailRegex.test (email);
};