How to use different_request method in wpt

Best JavaScript code snippet using wpt

index.js

Source:index.js Github

copy

Full Screen

1/* Core Libraries for Skill */2const Alexa = require('ask-sdk-core');3const i18n = require('i18next');4const sprintf = require('i18next-sprintf-postprocessor');56/* Custom Constants for volume and speed */7const volume_levels = ['silent','x-soft','soft','medium','loud','x-loud']; //used to adjuste the sound volume8const rate_levels = ['40%','50%','60%','75%','90%','100%','120%','150%','200%']; // used to adjust the speech speed910//includes the file that loads any custom content file.11const skill_files = require('./requirer');1213/**14 * Setup for const value for content files..15 *16 * languageString will only have text responses..17 * everything that needs info or more instructions will be in a content file.18 *19 * languageString will be used only for the initial startup of the skill (default language).20 */21const languageString = {22 'en-US':{23 translation: {24 INITIAL_LANGUAGE: "english",//language of alexa25 INITIAL_LANGUAGE_ENGLISH: "english",26 NATIVE_VOICE: "Kendra",27 SKILL_NAME: 'Lexicon beginner',28 WELCOME: 'Welcome to %s. I am going to teach you Vocabulary in different languages. Native Language is set to %s. ',29 },30 },31 'es-ES':{32 translation: {33 INITIAL_LANGUAGE: "español",//language of alexa34 INITIAL_LANGUAGE_ENGLISH: "spanish",35 NATIVE_VOICE: "Lucia",36 SKILL_NAME: 'Lexicon principiante',37 WELCOME: 'Bienvenido a %s. Te voy a enseñar vocabulario en diferentes idiomas. El idioma nativo está configurado en %s. ',38 },39 },40 'it-IT':{41 translation: {42 INITIAL_LANGUAGE: "italiano",//language of alexa43 INITIAL_LANGUAGE_ENGLISH: "italian",44 NATIVE_VOICE: "Carla",45 SKILL_NAME: 'Lexicon principiante',46 WELCOME: 'Benvenuto in %s. Ti insegnerò il vocabolario in diverse lingue. La lingua nativa è impostata su %s.',47 },48 },49 'fr-FR':{50 translation: {51 INITIAL_LANGUAGE: "Français",//language of alexa52 INITIAL_LANGUAGE_ENGLISH: "french",53 NATIVE_VOICE: "Celine",54 SKILL_NAME: 'Lexicon novice',55 WELCOME: 'Bienvenue en %s. Je vais vous enseigner le vocabulaire dans différentes langues. La langue maternelle est définie sur le %s.',56 },57 },58 'de-DE':{59 translation: {60 INITIAL_LANGUAGE: "Deutsche",//language of alexa61 INITIAL_LANGUAGE_ENGLISH: "german",62 NATIVE_VOICE: "Marlene",63 SKILL_NAME: 'Lexicon neuling',64 WELCOME: 'Willkommen bei %s. Ich werde Ihnen Vokabeln in verschiedenen Sprachen beibringen. Die Muttersprache ist auf %s eingestellt',65 },66 },67 };6869// INTENTS7071/**72 * Internal Alexa skill intent that triggers when an error occurs during runtime73 */74const FallbackHandler = {7576 // 2018-May-01: AMAZON.FallackIntent is only currently available in en-US locale.7778 // This handler will not be triggered except in that locale, so it can be7980 // safely deployed for any locale.8182 canHandle(handlerInput) {8384 const request = handlerInput.requestEnvelope.request;85 return request.type === 'IntentRequest' && request.intent.name === 'AMAZON.FallbackIntent';86 },87 handle(handlerInput) {88 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();89 return handlerInput.responseBuilder90 .speak(retrieve_Strings("general",sessionAttributes.native_language,"fallback"))91 .getResponse();92 },93};9495/**96 * Responsible to setup the locale of the skill's initial speaking language97 */98let LocalizationInterceptor = {99 process(handlerInput) {100 const localizationClient = i18n.use(sprintf).init({101 lng: handlerInput.requestEnvelope.request.locale,102 overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,103 resources: languageString,104 returnObjects: true105 });106107 const attributes = handlerInput.attributesManager.getRequestAttributes();108 attributes.t = function (...args) {109 return localizationClient.t(...args);110 };111 },112};113114/**115 * Handles real-time application errors and shows the results to the user.116 */117const ErrorHandler = {118 canHandle() {119 return true;120 },121 handle(handlerInput, error) {122 console.log(`Error handled: ${error.message}`);123124 return handlerInput.responseBuilder125 .speak("Run-Time Error: "+error.message)126 .getResponse();127 },128};129130/**131 * Intent that is triggered when the user cancels/ends session132 */133const SessionEndedRequest = {134 canHandle(handlerInput) {135 return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';136 },137 handle(handlerInput) {138 const output = `Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`;139 console.log(output);140141 return handlerInput.responseBuilder142 .speak(output)143 .withShouldEndSession(true)144 .getResponse();145 },146};147148/**149 * Intent is triggered when user chooses to cancel and stop the operation of the skill150 */151const CancelAndStopIntentHandler = {152 canHandle(handlerInput) {153 return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'154 && (Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.CancelIntent'155 || Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.StopIntent');156 },157 handle(handlerInput) {158 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();159160 return handlerInput.responseBuilder161 .withShouldEndSession(true)162 .speak(retrieve_Strings("warnings",sessionAttributes.native_language,"cancel_stop"))163 .getResponse();164 },165};166167/** CUSTOM INTENTS */168169/**170 * Custom Intent to show help/options for each specific location in the process.171 * And according to user input.172 */173const HelpIntent = {174 canHandle(handlerInput) {175 const { request } = handlerInput.requestEnvelope;176177 return request.type === 'IntentRequest' && (request.intent.name === 'AMAZON.HelpIntent' || request.intent.name === 'HelpIntent');178 },179 handle(handlerInput) {180181 let helpmsg;182 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();183 const slots = handlerInput.requestEnvelope.request.intent.slots;184 //option requested by the user185 let options = slots['help_options'].value;186187 //check if keyword for options slot given in native or learning language188 if (options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.native_language,"help").toUpperCase()189 || options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.learning_language,"help").toUpperCase())190 { //to show help messages.191 if (sessionAttributes.helpmsg == "Launch")192 {193 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"launch");194 }195 else if (sessionAttributes.helpmsg == "ShowCategories" || sessionAttributes.helpmsg=="UserSelectionCategory")196 {197 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"show_categories");198 }199 else if (sessionAttributes.helpmsg == "UserSelectionSubcategory" || sessionAttributes.helpmsg == "UserSelection" )200 {201 if (sessionAttributes.subcategory != undefined)202 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"select_categories" );203 else204 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"show_categories");205 }206 else if (sessionAttributes.helpmsg == "ExampleIntent")207 {208 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"example");209 }210 else if (sessionAttributes.helpmsg == "DetailsIntent")211 helpmsg= retrieve_Strings("help",sessionAttributes.native_language,"details")+retrieve_Strings("help",sessionAttributes.native_language,"example");212 else if (sessionAttributes.helpmsg == "IndexIntent")213 if (sessionAttributes.learning_language == "none")214 helpmsg = retrieve_Strings("help",sessionAttributes.native_language,"lauch");215 else216 helpmsg = retrieve_Strings("help",sessionAttributes.native_language,"show_categories");217 else if (sessionAttributes.helpmsg == "LanguageSelection")218 {//check if selected a category or a subcategory.. or an example, give option to continue where left off219 if (sessionAttributes.reset == false)220 helpmsg = retrieve_Strings("help",sessionAttributes.native_language,"resume");221 else222 helpmsg = retrieve_Strings("help",sessionAttributes.native_language,"reset");223 }224 helpmsg+= retrieve_Strings("general",sessionAttributes.native_language,"options");225 }226 else if (options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.native_language,"options").toUpperCase() || options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.learning_language,"options").toUpperCase() || options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.native_language,"instructions").toUpperCase() || options.toUpperCase() == checkEditor("help_options_list",sessionAttributes.learning_language,"instructions").toUpperCase())227 {//to give instructions...228 if (sessionAttributes.helpmsg == "Launch")229 {230 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"welcome");231 }232 else if (sessionAttributes.helpmsg == "ShowCategories" || sessionAttributes.helpmsg=="UserSelectionCategory")233 {234 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"show_categories");235 }236 else if (sessionAttributes.helpmsg == "UserSelectionSubcategory" || sessionAttributes.helpmsg == "UserSelection" )237 {238 if (sessionAttributes.subcategory != undefined)239 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"select_categories");240 else241 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"show_categories");242 }243 else if (sessionAttributes.helpmsg == "ExampleIntent")244 {245 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"example")+retrieve_Strings("options",sessionAttributes.native_language,"details");246 }247 else if (sessionAttributes.helpmsg == "DetailsIntent")248 helpmsg= retrieve_Strings("options",sessionAttributes.native_language,"details")+retrieve_Strings("options",sessionAttributes.native_language,"example");249 else if (sessionAttributes.helpmsg == "IndexIntent")250 if (sessionAttributes.learning_language == "none")251 helpmsg = retrieve_Strings("options",sessionAttributes.native_language,"welcome");252 else if (sessionAttributes.subcategory != undefined)253 helpmsg = retrieve_Strings("options",sessionAttributes.native_language,"index");254 else255 helpmsg = retrieve_Strings("options",sessionAttributes.native_language,"show_categories");256 else if (sessionAttributes.helpmsg == "LanguageSelection")257 {258 if (sessionAttributes.reset == false)259 helpmsg = retrieve_Strings("options",sessionAttributes.native_language,"resume");260 else261 helpmsg = retrieve_Strings("options",sessionAttributes.native_language,"reset");262 }263 }264 else265 helpmsg = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");266 Object.assign(sessionAttributes,267 {268 lastmsg: helpmsg,269 break: 0,270 voice: retrieve_Strings("voices",sessionAttributes.native_language,false),271 });272 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);273274 //setting the return help/options message in correct voice attributes275 helpmsg = switchVoice(helpmsg,handlerInput.attributesManager.getSessionAttributes());276 return handlerInput.responseBuilder277 .withShouldEndSession(false)278 .speak(helpmsg)279 .getResponse();280 },281};282283/**284 * Custom Intent to repeat last message given to the user.285 * Checks user preference in speed and volume before repeating..286 * User can select to hear it faster/slower or louder/quieter.287 */288const RepeatMessageIntent = {289 canHandle(handlerInput)290 {291 return handlerInput.requestEnvelope.request.type === 'IntentRequest'292 && handlerInput.requestEnvelope.request.intent.name === 'RepeatMessageIntent';293 },294 handle(handlerInput)295 {296 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();297 const slots = handlerInput.requestEnvelope.request.intent.slots;298 const speed = slots['speed'].value;299 const volume = slots['volume'].value;300 const repeat = slots['Repeat'].value;301302 let repeat_rate = sessionAttributes.rate;303 let repeat_volume = sessionAttributes.volume;304 let output = sessionAttributes.lastmsg != undefined ? sessionAttributes.lastmsg : retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");305306 if (speed!= undefined)307 {308 if (speed.toUpperCase() == checkEditor("speed_list",sessionAttributes.native_language,"faster").toUpperCase() || speed.toUpperCase() == checkEditor("speed_list",sessionAttributes.learning_language,"faster").toUpperCase())309 {//faster310 for (let i =0;i<rate_levels.length;i++)311 if (sessionAttributes.rate == rate_levels[i])312 if (i==rate_levels.length-1)313 repeat_rate = rate_levels[i];314 else315 repeat_rate = rate_levels[i+1];316 }317 else if (speed.toUpperCase() == checkEditor("speed_list",sessionAttributes.native_language,"slower").toUpperCase() || speed.toUpperCase() == checkEditor("speed_list",sessionAttributes.learning_language,"slower").toUpperCase())318 {//slower319 for (let i =0;i<rate_levels.length;i++)320 if (sessionAttributes.rate == rate_levels[i])321 if (i==0)322 repeat_rate = rate_levels[0];323 else324 repeat_rate = rate_levels[i-1];325 }326 else327 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request")+". But sure..:"+output;328329 }330 else if (volume != undefined)331 {332 if (volume.toUpperCase() == checkEditor("volume_list",sessionAttributes.native_language,"louder").toUpperCase() || volume.toUpperCase() == checkEditor("volume_list",sessionAttributes.learning_language,"louder").toUpperCase())333 {//louder334 for (let i=0;i<volume_levels.length;i++)335 {336 if (sessionAttributes.volume == volume_levels[i])337 if (i==volume_levels.length-1)338 repeat_volume = volume_levels[i];339 else340 repeat_volume = volume_levels[i+1];341 }342 }343 else if (volume.toUpperCase() == checkEditor("volume_list",sessionAttributes.native_language,"quieter").toUpperCase() || volume.toUpperCase() == checkEditor("volume_list",sessionAttributes.learning_language,"quieter").toUpperCase())344 {//quieter345 for (let i=0;i<volume_levels.length;i++)346 {347 if (sessionAttributes.volume == volume_levels[i])348 if (i==0)349 repeat_volume = volume_levels[0];350 else351 repeat_volume = volume_levels[i-1];352 }353 }354 else355 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");356 }357 else if (repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.native_language,"repeat").toUpperCase()358 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.learning_language,"repeat").toUpperCase()359 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.native_language,"again").toUpperCase()360 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.learning_language,"again").toUpperCase()361 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.native_language,"repeat again").toUpperCase()362 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.learning_language,"repeat again").toUpperCase()363 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.native_language,"repeat normal").toUpperCase()364 || repeat.toUpperCase() == checkEditor("repeat_list",sessionAttributes.learning_language,"repeat normal").toUpperCase())365 {366 repeat_rate = "100%";367 repeat_volume = "medium";368 }369 else370 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");371372 Object.assign(sessionAttributes,373 {374 break:1,375 rate:repeat_rate,376 volume: repeat_volume,377 });378 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);379 //setting up the return message with appropriate voice attributes.380 output = switchVoice(output,handlerInput.attributesManager.getSessionAttributes());381 return handlerInput.responseBuilder382 .withShouldEndSession(false)383 .speak(output)384 .getResponse();385 },386};387388/**389 * Starting point of application390 * Intent to Launch Skill.391 * Shows initial welcoming messages, in the default language of alexa and sets392 * the speaking language (native) to the default393 */394const LaunchRequest = {395 canHandle(handlerInput)396 {397 const {request} = handlerInput.requestEnvelope;398 return request.type === 'LaunchRequest'399 || (request.type === 'IntentRequest' && request.intent.name === 'AMAZON.StartOverIntent');400 },401 handle(handlerInput)402 {403 const requestAttributes = handlerInput.attributesManager.getRequestAttributes();404 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();405 let output = requestAttributes.t("WELCOME",requestAttributes.t("SKILL_NAME"),requestAttributes.t("INITIAL_LANGUAGE"))+retrieve_Strings("help",requestAttributes.t("INITIAL_LANGUAGE_ENGLISH"),"launch");406 Object.assign(sessionAttributes,407 {408 lastmsg: output,409 helpmsg: "Launch",410 voice: requestAttributes.t("NATIVE_VOICE"),411 learning_language: "none",412 native_language: requestAttributes.t("INITIAL_LANGUAGE_ENGLISH"),413 native_name: requestAttributes.t("INITIAL_LANGUAGE"),414 learning_name: "none",415 break: 0,416 rate: "100%",417 volume: "medium",418 });419 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);420 //setting up the return message of Alexa with appropriate voice attributes.421 output = switchVoice(output,handlerInput.attributesManager.getSessionAttributes());422423 return handlerInput.responseBuilder424 .withShouldEndSession(false)425 .speak(output)426 .getResponse();427 },428};429430/**431 * Custom Intent to change Native or Learning language432 */433const LanguageSelectionIntent = {434 canHandle(handlerInput)435 {436 return handlerInput.requestEnvelope.request.type === 'IntentRequest'437 && handlerInput.requestEnvelope.request.intent.name === 'LanguageSelectionIntent';438 },439 handle(handlerInput)440 {441 let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();442 const slots = handlerInput.requestEnvelope.request.intent.slots;443 const language = slots['language'].value;444 const type = slots['language_type'].value;445 let output = "";446 let native=sessionAttributes.native_language;447 let learning= sessionAttributes.learning_language;448 let native_name=sessionAttributes.native_name449 let learning_name=sessionAttributes.learning_name;450 let reset = false;451 let category = sessionAttributes.category;452 let subcategory = sessionAttributes.subcategory;453454 let language_request_english = returnSpokenLanguage(language); //language that the request was given. (in english)455456 if (language_request_english == "unidentified" || language_request_english == "undefined"457 || language_request_english.toUpperCase() != native.toUpperCase())458 {459 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request")+retrieve_Strings("warnings",sessionAttributes.native_language,"given_request")+retrieve_Strings("translation",sessionAttributes.native_language,language_request_english)+". ";460 }461 else462 {463 if (language != undefined && type !=undefined)464 {//request to change native or learning language465 if (type.toUpperCase() == checkEditor("language_type",sessionAttributes.native_language,"native").toUpperCase()466 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.learning_language,"native").toUpperCase()467 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.native_language,"mother").toUpperCase()468 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.learning_language,"mother").toUpperCase())469 {//request to change the native language470 if (native.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())471 output = retrieve_Strings("warnings",sessionAttributes.native_language,"native_warn")+language+". ";472 else if (learning.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())473 output = language+retrieve_Strings("warnings",sessionAttributes.native_language,"same_selection");474 else475 {//validation for changing native language is approved476 output = retrieve_Strings("warnings",language,"native_selection")+language+". ";477 native_name = language;478 native = retrieve_Strings("translation",language,"return");479 reset = true;480 }481 }482 else if (type.toUpperCase() == checkEditor("language_type",sessionAttributes.native_language,"teaching").toUpperCase()483 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.learning_language,"teaching").toUpperCase()484 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.native_language,"second").toUpperCase()485 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.learning_language,"second").toUpperCase()486 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.native_language,"learning").toUpperCase()487 || type.toUpperCase() == checkEditor("language_type",sessionAttributes.learning_language,"learning").toUpperCase())488 {//request to change learning language489490 if (learning.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())491 output = retrieve_Strings("warnings",sessionAttributes.native_language,"learning_warn")+language+". ";//same selection as before492 else if (native.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())493 output = language+retrieve_Strings("warnings",sessionAttributes.native_language,"same_selection"); //both languages are the same494 else495 {//validation for changing learning language is approved496 output = retrieve_Strings("language",native,"selection")+retrieve_Strings("warnings",sessionAttributes.native_language,"learning_selection")+language+". ";497 learning_name = language;498 learning = retrieve_Strings("translation",language,"return");499 reset = true;500 }501 }502 else503 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");504 }505 else if (type == undefined && language!= undefined)506 {//learn "language", set learning language to this507 // check if learning language is the same as before..508 if (learning.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())509 output = retrieve_Strings("warnings",sessionAttributes.native_language,"learning_warn")+language+". ";510 else if (native.toUpperCase() == returnSpokenLanguage(retrieve_Strings("translation",language,native)).toUpperCase())511 output = language+retrieve_Strings("warnings",sessionAttributes.native_language,"same_selection"); //if same selection for both languages512 else513 {//updating learning language514 output = retrieve_Strings("language",native,"selection")+retrieve_Strings("warnings",sessionAttributes.native_language,"learning_selection")+language+". ";515 learning_name = language;516 learning = retrieve_Strings("translation",language,"return");517 reset = true;518 }519 //changes learning language only.520 }521 else//something wasn't given correctly522 output= retrieve_Strings("warnings",sessionAttributes.native_language,"missing_info");523 }524525 //updating the session Attributes526 Object.assign(sessionAttributes,527 {528 native_language: native,529 learning_language: learning,530 native_name: native_name,531 learning_name: learning_name,532 lastmsg: output,533 helpmsg: "LanguageSelection",534 voice: retrieve_Strings("voices",native),535 break: 0,536 rate: "100%",537 volume: "medium",538 reset: reset,539 category: category,540 subcategory: subcategory,541 });542 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);543544 //if learning language change then all categories are changed.. (different info)545 // so must reset all category and subcategory selections and reset the examples.546 if (reset == true)547 {548 Object.assign(sessionAttributes,549 {550 category: undefined,551 subcategory: undefined,552 });553 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);554 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"reset");555 }556 //setting appropriate voice for the return message.557 output = switchVoice(output/* +retrieve_Strings("language",native,"selection")+sessionAttributes.learning_name */,sessionAttributes);558 return handlerInput.responseBuilder559 .withShouldEndSession(false)560 .speak(output)561 .getResponse();562 }563};564565/**566 * Custom Intent to show currrent category, subcategory, example, native and learning languages.567 */568const IndexIntent = {569 canHandle(handlerInput)570 {571 return handlerInput.requestEnvelope.request.type === 'IntentRequest'572 && handlerInput.requestEnvelope.request.intent.name === 'IndexIntent';573 },574 handle(handlerInput)575 {576 let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();577 const slots = handlerInput.requestEnvelope.request.intent.slots;578579 const request = slots['request'].value;580 let output ="";581 if (sessionAttributes.category != undefined &&582 (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"current_category").toUpperCase()583 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"current_category").toUpperCase()584 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"current_theme").toUpperCase()585 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"current_theme").toUpperCase()))586 {//current category587 output = request+" . "+sessionAttributes.category;588 }589 else if (sessionAttributes.subcategory != undefined &&590 (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"current_subcategory").toUpperCase()591 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"current_subcategory").toUpperCase()592 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"current_topic").toUpperCase()593 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"current_topic").toUpperCase()))594 {//current subcategory595 output = request+" . "+sessionAttributes.subcategory;596 }597 else if (sessionAttributes.examples_ids != undefined && sessionAttributes.category != undefined && sessionAttributes.subcategory != undefined &&598 (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"current_example").toUpperCase()599 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"current_example").toUpperCase()))600 {//current example601 if (sessionAttributes.examples_ids.length>0)602 output = request+" . "+sessionAttributes.native_word;603 else604 output = retrieve_Strings("warnings",sessionAttributes.native_language,"missing_info");605 }606 else if (sessionAttributes.learning_language != undefined &&607 (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"learning_language").toUpperCase()608 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"learning_language").toUpperCase()))609 {//current learning language610 output = request + " . "+sessionAttributes.learning_name;611 }612 else if (sessionAttributes.native_language != undefined &&613 (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"native_language").toUpperCase()614 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"native_language").toUpperCase()615 ||request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"mother_language").toUpperCase()616 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"mother_language").toUpperCase()))617 {//current native language618 output = request + " . "+sessionAttributes.native_name;619 }620 else if (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"language_list").toUpperCase()621 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"language_list").toUpperCase())622 {//show language list623 output = retrieve_Strings("language",sessionAttributes.native_language,"list");624 }625 else if (request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"category_list").toUpperCase()626 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"category_list").toUpperCase()627 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.native_language,"theme_list").toUpperCase()628 || request.toUpperCase() == checkEditor("request_list",sessionAttributes.learning_language,"theme_list").toUpperCase())629 {//show category list630 section = createReturnList('category',sessionAttributes,retrieveFromJson(sessionAttributes),"native");631 output+= retrieve_Strings("general",sessionAttributes.native_language,"category_list")+". "+section;632 }633 else //something was wrong in the selection of the user. information not available634 output = retrieve_Strings("warnings",sessionAttributes.native_language,"missing_info");635 //updating the session Attributes636 Object.assign(sessionAttributes,637 {638 lastmsg: output,639 helpmsg: "IndexIntent",640 voice: retrieve_Strings("voices",sessionAttributes.native_language),641 break: 0,642 rate: "100%",643 volume: "medium",644 });645 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);646647 //setting appropriate voice for the return message.648 output = switchVoice(output,sessionAttributes);649 return handlerInput.responseBuilder650 .withShouldEndSession(false)651 .speak(output)652 .getResponse();653 },654};655656/**657 * Custom Intent to handle the request to show the list of categories/subcategories.658 * User must trigger the option slot to activate this intention.659 */660const ShowCategoriesIntent ={661 canHandle(handlerInput)662 {663 return handlerInput.requestEnvelope.request.type === 'IntentRequest'664 && handlerInput.requestEnvelope.request.intent.name === 'ShowCategoriesIntent';665 },666 handle(handlerInput)667 {668 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();669 const slots = handlerInput.requestEnvelope.request.intent.slots;670 const option = slots['option'].value;671 let output = "";672 if (sessionAttributes.learning_language == "none")673 {//learning language not configured674 output = retrieve_Strings("warnings",sessionAttributes.native_language,"no_learning_lang");675 }676 else677 {//learning language is set678 if (option)679 {//option is given. Always true680 let section;681 if (option.toUpperCase() == checkEditor("option_list",sessionAttributes.native_language,"categories").toUpperCase()682 || option.toUpperCase() == checkEditor("option_list",sessionAttributes.learning_language,"categories").toUpperCase()683 ||option.toUpperCase() == checkEditor("option_list",sessionAttributes.native_language,"themes").toUpperCase()684 || option.toUpperCase() == checkEditor("option_list",sessionAttributes.learning_language,"themes").toUpperCase())685 {//user requested to display all categories available686 section = createReturnList('category',sessionAttributes,retrieveFromJson(sessionAttributes),"native");687 if (section != undefined)// check if section list retrieved without errors688 output+= retrieve_Strings("general",sessionAttributes.native_language,"category_list")+ ". "+section;689 else690 output += retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");691 }692 else if (option.toUpperCase() == checkEditor("option_list",sessionAttributes.native_language,"subcategories").toUpperCase()693 || option.toUpperCase() == checkEditor("option_list",sessionAttributes.learning_language,"subcategories").toUpperCase()694 || option.toUpperCase() == checkEditor("option_list",sessionAttributes.native_language,"topics").toUpperCase()695 || option.toUpperCase() == checkEditor("option_list",sessionAttributes.learning_language,"topics").toUpperCase())696 {//user requested to display all subcategories available697 //category must be selected first for this698 if (sessionAttributes.category == undefined)699 {//no category is selected700 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"category")+retrieve_Strings("general",sessionAttributes.native_language,"suggested");701 }702 else703 {//category is set before704 section= createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,sessionAttributes.category),"native");705 if (section != undefined) // check if section list retrieved without errors706 {707 output+= retrieve_Strings("general",sessionAttributes.native_language,"subcategory_list");708 for (var i=0;i<section.length;i++)709 {710 output += i==0 ? " " : ", ";711 output += section[i].replace(","," and")+" ";712 }713 }714 else715 output += retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");716 }717 }718 else719 {//request is not matched for showing categories or subcategories in native or learning language720 //=> request given in different language721 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");722 }723 }724 }725726 //updating the session Attributes727 Object.assign(sessionAttributes,728 {729 lastmsg: output,730 helpmsg: "ShowCategories",731 break: 0,732 voice: retrieve_Strings("voices",sessionAttributes.native_language),733 });734 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);735 //setting appropriate voice for the return message.736 output = switchVoice(output,sessionAttributes);737 return handlerInput.responseBuilder738 .withShouldEndSession(false)739 .speak(output)740 .getResponse();741 }742}743744/**745 * Custom intent to select random category/subcategory746 */747const UserSelectionIntent = {748 canHandle(handlerInput)749 {750 return handlerInput.requestEnvelope.request.type === 'IntentRequest'751 && handlerInput.requestEnvelope.request.intent.name === 'UserSelectionIntent';752 },753 handle(handlerInput)754 {755 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();756 const slots = handlerInput.requestEnvelope.request.intent.slots;757 /* Const values for slots*/758 const option = slots['option_selection'].value;759760761 //subcategory length.762 let sub_length = sessionAttributes.subcategories_length != undefined ? sessionAttributes.subcategories_length : 0;763 let examples_length = sessionAttributes.examples_length != undefined ? sessionAttributes.examples_length : 0;764 let category = sessionAttributes.category;765 let subcategory = sessionAttributes.subcategory;766 let subcategory_ids = sessionAttributes.subcategory_ids ? sessionAttributes.subcategory_ids : [];767 var output="";768769 // if learning language selected doesn't show anything here..770 if (sessionAttributes.learning_language == "none")771 {772 output = retrieve_Strings("warnings",sessionAttributes.native_language,"no_learning_lang");773 }774 else775 {//learning language set, safe to proceed776 if (option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.native_language,"category").toUpperCase()777 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.learning_language,"category").toUpperCase()778 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.native_language,"theme").toUpperCase()779 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.learning_language,"theme").toUpperCase())780 {//option is given in native or learning language for keyword category781 const section = createReturnList('category',sessionAttributes,retrieveFromJson(sessionAttributes),"native");782 if (section != undefined)783 {784 //removing value of subcategory785 subcategory = undefined;786 //removing values of subcategories ids787 subcategory_ids = [];788 category = section[Math.floor(Math.random()*section.length)];789 //message for new category selection790 output += retrieve_Strings("general",sessionAttributes.native_language,"new_category")+category+" . ";791 //message for subcategory list available792 output += retrieve_Strings("general",sessionAttributes.native_language,"subcategory_list");793 //get subcategory list.794 const subcategory_list = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,category),"native");795 //updating value of subcategories length796 sub_length = subcategory_list.length;797 //reseting the length of the examples. no subcategory set at this point.798 examples_length = 0;799 if (subcategory_list != undefined)800 {801 for (var i=0; i< subcategory_list.length; i++)802 {//for showing the correct format of the subcategory name803 output += i==0 ? " " : ", ";804 output +=subcategory_list[i].replace(","," and")+" ";805 }806 }807 else808 output = retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");809 }810 else811 output += retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");812 }813 else if (option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.native_language,"subcategory").toUpperCase()814 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.learning_language,"subcategory").toUpperCase()815 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.native_language,"topic").toUpperCase()816 || option.toUpperCase() == checkEditor("random_option_list",sessionAttributes.learning_language,"topic").toUpperCase())817 {//option is given in native or learning language for keyword subcategory818 if (category != undefined)819 {//category is set. moving to randomizing subcategories820 const subcategory_list = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,category),"native");821 if (subcategory_list!= undefined)822 {823 const id = Math.floor(Math.random()*subcategory_list.length); //to set for array position824 subcategory = subcategory_list[id];825826 examples_length = createReturnList("word",sessionAttributes,[retrieveFromJson(sessionAttributes,category,subcategory)],"native",true)[0].length;827 let exists=false;828 //check if subcaregory already exists. don't add again.829 for (let i=0; i<subcategory_ids.length; i++)830 {831 if (subcategory_ids[i]==id)832 {833 exists = true;834 break;835 }836 else837 exists = false;838 }839 //add the subcategory id to the list if it wasn't added before840 if (exists == false)841 subcategory_ids.push(id);842 //sorting the subcategory ids843 subcategory_ids.sort(sortIds);844 //message for new category selection845 output += retrieve_Strings("general",sessionAttributes.native_language,"new_subcategory")+subcategory.replace(","," and")+" . ";846 }847 }848 else849 output += retrieve_Strings("warnings",sessionAttributes.native_language,"not_category");850 }851 else852 {//return message for wrong keyword853 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");854 }855 }856 //update values of session attributes857 Object.assign(sessionAttributes,858 {859 lastmsg: output,860 helpmsg: "UserSelection",861 category: category,862 subcategory: subcategory, //changing category, means reseting the subcategory name863 subcategory_ids: subcategory_ids, //if category is changed then the subcategory_ids will be reset864 subcategories_length: sub_length != undefined ? sub_length : 0,//maximum number of category's subcategories865 examples_ids: [], //changing category or subcategory => reset the examples866 examples_length: examples_length,//length of current subcategory's examples867 voice: retrieve_Strings("voices",sessionAttributes.native_language),868 break: 0,869 });870 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);871872 //setting appropriate voice for the return message.873 output = switchVoice(output,sessionAttributes);874 return handlerInput.responseBuilder875 .withShouldEndSession(false)876 .speak(output)877 .getResponse();878 }879}880881/**882 * Custom Intent to handle the user request to select a new category883 * Only triggered when given the command to set a category884 */885const UserCategorySelectionIntent = {886 canHandle(handlerInput)887 {888 return handlerInput.requestEnvelope.request.type === 'IntentRequest'889 && handlerInput.requestEnvelope.request.intent.name === 'UserCategorySelectionIntent';890 },891 handle(handlerInput)892 {893 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();894 const slots = handlerInput.requestEnvelope.request.intent.slots;895896 //the value of query_response should be a category name897 const query_response = slots['query'].value;898 //value for next theme request899 const next_theme = slots['next_theme'].value;900901 let category = sessionAttributes.category;902 let subcategory = sessionAttributes.subcategory;903 let output = "";904905 //subcategory length.906 let sub_length = sessionAttributes.subcategories_length != undefined ? sessionAttributes.subcategories_length : 0;907 //examples length908 let examples_length = sessionAttributes.examples_length != undefined ? sessionAttributes.examples_length : 0;909 // if learning language selected doesn't show anything here..910 911 if (sessionAttributes.learning_language == "none")912 {913 output = retrieve_Strings("warnings",sessionAttributes.native_language,"no_learning_lang");914 }915 else916 {//learning language is configured, safe to proceed917 //getting all categories names in native and learning language918 const category_list = createReturnList('category',sessionAttributes,retrieveFromJson(sessionAttributes),"all");919 if (category_list != undefined)920 {921 //request to select category by name or number922 if (query_response != undefined)923 {924 //returns the numerical value of category in the category index.925 //checks if request was given through the actual name or the index value of category926 const position = check_if_Number(query_response) == "true" ? infoFound(query_response,category_list) : check_if_Number(query_response);927 //checks if given position exists and is within range of categories index928 if (position != undefined && position < category_list.length)929 {//category requested is found. update values930 //to provide the native version of category931 category = category_list[position<category_list.length/2 ? position : position-(category_list.length/2)];932 //updating subcategory value933 subcategory = undefined;934 //updating examples length value935 examples_length = 0;936 //message for new category selection937 output += retrieve_Strings("general",sessionAttributes.native_language,"new_category")+category+" . ";938 //message for subcategory list available939 output += retrieve_Strings("general",sessionAttributes.native_language,"subcategory_list");940 //get subcategory list.941 const subcategory_list = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,category),"native");942 //updating subcategories length value943 sub_length = subcategory_list.length;944 if (subcategory_list != undefined)945 {946 for (var i=0; i< subcategory_list.length; i++)947 {948 output += i==0 ? " " : ", ";949 output +=subcategory_list[i].replace(","," and")+" ";950 }951 }952 else953 output = query_response+retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");954 }955 else956 {//category name given was not valid/not found, assume given in different language957 output = query_response+retrieve_Strings("warnings",sessionAttributes.native_language,"name_not_found");958 }959 }960 else961 {//request to select next theme/category.962 //check if request for next category/theme given in appropriate language963 if (next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.native_language,"next_category").toUpperCase()964 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.learning_language,"next_category").toUpperCase()965 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.native_language,"another_category").toUpperCase()966 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.learning_language,"another_category").toUpperCase()967 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.native_language,"next_theme").toUpperCase()968 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.learning_language,"next_theme").toUpperCase()969 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.native_language,"another_theme").toUpperCase()970 || next_theme.toUpperCase() == checkEditor("continue_in_cat_list",sessionAttributes.learning_language,"another_theme").toUpperCase())971 {972 if (category == undefined)973 {//no category/theme selected prior to this request. Add the first category available.974 //first category in the list975 category = category_list[0];976 }977 else978 {//category/theme was defined before, need to add the very next one.979 //find the position of the current category in the list980 const position = infoFound(category,category_list);981 if (position != undefined && position < category_list.length)982 {//position of current category/theme found983 //check if current category is the last one in list (add the first one again in that case)984 category = (position + 1) < category_list.length/2 ? category_list[position+1] : category_list[0];985 }986 else987 {//category name given was not valid/not found, assume given in different language988 output = next_theme+retrieve_Strings("warnings",sessionAttributes.native_language,"name_not_found");989 }990 }991 //updating values after new category/theme992 //updating subcategory value993 subcategory = undefined;994 //updating examples length value995 examples_length = 0;996 //message for new category selection997 output += retrieve_Strings("general",sessionAttributes.native_language,"new_category")+category+" . ";998 //message for subcategory list available999 output += retrieve_Strings("general",sessionAttributes.native_language,"subcategory_list");1000 //get subcategory list.1001 const subcategory_list = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,category),"native");1002 //updating subcategories length value1003 sub_length = subcategory_list.length;1004 if (subcategory_list != undefined)1005 {1006 for (var i=0; i< subcategory_list.length; i++)1007 {1008 output += i==0 ? " " : ", ";1009 output +=subcategory_list[i].replace(","," and")+" ";1010 }1011 }1012 else1013 output = next_theme+retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");1014 }1015 else1016 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1017 }1018 }1019 else1020 {//return message for content error1021 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1022 }1023 }1024 //update values of session attributes1025 Object.assign(sessionAttributes,1026 {1027 lastmsg: output,1028 helpmsg: "UserSelectionCategory",1029 category: category,1030 subcategory: subcategory,1031 subcategory_ids: [], //reseting values of subcategory ids, new category1032 subcategories_length: sub_length,//maximum number of category's subcategories1033 examples_ids: [], //reseting values of examples, new category,1034 examples_length: examples_length, // length of examples of subcategory1035 native_word: undefined,1036 native_phrase: undefined,1037 learning_word:undefined,1038 learning_phrase: undefined,1039 voice: retrieve_Strings("voices",sessionAttributes.native_language),1040 break: 0,1041 });1042 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);10431044 //setting appropriate voice for the return message.1045 output = switchVoice(output,sessionAttributes);1046 return handlerInput.responseBuilder1047 .withShouldEndSession(false)1048 .speak(output)1049 .getResponse();1050 }1051}10521053/**1054 * Custom Intent to handle the user request to select a new subcategory1055 * Only triggered when given the command to set a subcategory1056 */1057const UserSubcategorySelectionIntent = {1058 canHandle(handlerInput)1059 {1060 return handlerInput.requestEnvelope.request.type === 'IntentRequest'1061 && handlerInput.requestEnvelope.request.intent.name === 'UserSubcategorySelectionIntent';1062 },1063 handle(handlerInput)1064 {1065 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();1066 const slots = handlerInput.requestEnvelope.request.intent.slots;10671068 //value of query_response must be a subcategory name1069 const query_response = slots['query'].value;1070 let subcategory = sessionAttributes.subcategory;1071 let output = "";1072 let subcategory_ids = sessionAttributes.subcategory_ids == undefined ? [] : sessionAttributes.subcategory_ids;1073 let examples_length = sessionAttributes.examples_length != undefined ? sessionAttributes.examples_length : 0;1074 // if learning language selected doesn't show anything here..1075 if (sessionAttributes.learning_language == "none")1076 {1077 output = retrieve_Strings("warnings",sessionAttributes.native_language,"no_learning_lang");1078 }1079 else1080 {//learning language is configured, safe to proceed1081 //check for category to be defined first1082 if (sessionAttributes.category)1083 {//category is set1084 const subcategory_list = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,sessionAttributes.category),"all");1085 //output +=subcategory_list;1086 if (subcategory_list != undefined)1087 {1088 //id in list of native and learning subcategory names1089 //returns the numerical value of category in the category index.1090 //checks if request was given through the actual name or the index value of category1091 const id = check_if_Number(query_response) == "true" ? infoFound(query_response,subcategory_list) : ( check_if_Number(query_response)>subcategory_list.length/2 ? -1 : check_if_Number(query_response)-1);1092 if (id!= undefined && id < subcategory_list.length && id >= 0 )1093 {//subcategory requested is found.1094 subcategory = subcategory_list[id<subcategory_list.length/2 ? id : id-(subcategory_list.length/2)];1095 //setting examples length1096 examples_length = createReturnList("word",sessionAttributes,[retrieveFromJson(sessionAttributes,sessionAttributes.category,subcategory)],"native",true)[0].length;1097 let exists=false;1098 //check if subcaregory already exists. don't add again.1099 for (let i=0; i<subcategory_ids.length; i++)1100 {1101 if (subcategory_ids[i]==id)1102 {1103 exists = true;1104 break;1105 }1106 else1107 exists = false;1108 }1109 //add the subcategory id to the list if it wasn't added before1110 if (exists == false)1111 subcategory_ids.push(id);1112 //sorting the subcategory ids1113 subcategory_ids.sort(sortIds);1114 //message for new category selection1115 output += retrieve_Strings("general",sessionAttributes.native_language,"new_subcategory")+subcategory.replace(","," and")+" . ";1116 }1117 else1118 {//category name given was not valid/not found, assume given in different language1119 output += query_response+retrieve_Strings("warnings",sessionAttributes.native_language,"name_not_found");1120 }1121 }1122 else1123 {1124 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"content_error");1125 }11261127 }1128 else1129 {1130 output+= retrieve_Strings("warnings",sessionAttributes.native_language,"not_category");1131 }1132 }11331134 //update values of session attributes1135 Object.assign(sessionAttributes,1136 {1137 lastmsg: output,1138 helpmsg: subcategory != undefined ? "UserSelectionSubcategory" : "ShowCategories",1139 subcategory: subcategory,1140 subcategory_ids: subcategory_ids,1141 examples_ids: [], //new subcategory, reseting examples..1142 examples_length: examples_length,//length of current subcategory's examples1143 voice: retrieve_Strings("voices",sessionAttributes.native_language),1144 break: 0,1145 });1146 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);11471148 //setting appropriate voice for the return message.1149 output = switchVoice(output,sessionAttributes);1150 return handlerInput.responseBuilder1151 .withShouldEndSession(false)1152 .speak(output)1153 .getResponse();1154 }1155}11561157/**1158 * Custom Intent to set the next Example for the user1159 * User can select to see next or random example.1160 */1161const ExampleIntent = {1162 canHandle(handlerInput)1163 {1164 return handlerInput.requestEnvelope.request.type === 'IntentRequest'1165 && handlerInput.requestEnvelope.request.intent.name === 'ExampleIntent';1166 },1167 handle(handlerInput)1168 {1169 let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();11701171 const slots = handlerInput.requestEnvelope.request.intent.slots;1172 let resume = slots['continue'] != undefined ? slots['continue'].value : undefined;1173 let random = slots['random_example'] != undefined ? slots['random_example'].value : undefined;1174 let output="";1175 let category = sessionAttributes.category;1176 let subcategory = sessionAttributes.subcategory;1177 let examples_ids = sessionAttributes.examples_ids == undefined ? [] : sessionAttributes.examples_ids;1178 let subcategory_ids = sessionAttributes.subcategory_ids == undefined ? [] : sessionAttributes.subcategory_ids;1179 let examples_length = sessionAttributes.examples_length == undefined ? 0 : sessionAttributes.examples_length;1180 let subcategories_length = sessionAttributes.subcategories_length == undefined ? 0 : sessionAttributes.subcategories_length;1181 let keyword_check;1182 if (sessionAttributes.learning_language == "none")1183 {//learning language not configured1184 output = retrieve_Strings("warnings",sessionAttributes.native_language,"no_learning_lang");1185 }1186 else1187 {//learning language is set1188 if (category == undefined || subcategory == undefined)1189 {//both category and subcategory must be set before continuing with this1190 output += retrieve_Strings("warnings",sessionAttributes.native_language,"category")+retrieve_Strings("general",sessionAttributes.native_language,"suggested");1191 }1192 else1193 {//safe to proceed further checks.1194 if (resume != undefined)1195 {//resume keyword triggered1196 if (resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.native_language,"another").toUpperCase()1197 || resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.learning_language,"another").toUpperCase()1198 || resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.native_language,"next").toUpperCase()1199 || resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.learning_language,"next").toUpperCase()1200 || resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.native_language,"start").toUpperCase()1201 || resume.toUpperCase() == checkEditor("continue_in_sub_list",sessionAttributes.learning_language,"start").toUpperCase())1202 {//keyword given correctly1203 keyword_check = true;1204 }1205 else1206 {//keyword was given in a different language.1207 output += retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1208 keyword_check = false;1209 }1210 }1211 if (random != undefined)1212 {//random keyword triggered1213 if ((random.toUpperCase() == checkEditor("random_list",sessionAttributes.native_language,"random").toUpperCase()1214 || random.toUpperCase() == checkEditor("random_list",sessionAttributes.learning_language,"random").toUpperCase()1215 || random.toUpperCase() == checkEditor("random_list",sessionAttributes.native_language,"shuffle").toUpperCase()1216 || random.toUpperCase() == checkEditor("random_list",sessionAttributes.learning_language,"shuffle").toUpperCase()))1217 {1218 keyword_check = true;1219 }1220 else1221 {1222 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1223 keyword_check = false;1224 }1225 }1226 if (keyword_check)1227 {1228 let test_count = 0;1229 let new_example_entry;1230 let change = 0 ; //0 = no change, 1 = subcategory change, 2 = category change1231 while(new_example_entry == undefined || new_example_entry == false)1232 {//while loop until a valid example is found.1233 test_count ++;1234 if (examples_ids.length < examples_length)1235 {//still valid examples in current subcategory. Get next example from there12361237 /* setting the example proces */1238 //get the subcategory section information1239 const subcategory_section = [retrieveFromJson(sessionAttributes,category,subcategory)];1240 //create the object for the subcategory info1241 const subcategory_info = Object.assign({},{//value in each field will have the String value or "false" value -> doesn't exist for that example1242 native_words: createReturnList("word",sessionAttributes,subcategory_section,"native",true)[0],1243 learning_words: createReturnList("word",sessionAttributes,subcategory_section,"learning",true)[0],1244 native_phrases: createReturnList("phrase",sessionAttributes,subcategory_section,"native",true)[0],1245 learning_phrases: createReturnList("phrase",sessionAttributes,subcategory_section,"learning",true)[0]1246 });1247 new_example_entry = getExample(subcategory_info,examples_ids,random);1248 break;1249 }1250 else1251 {//all examples of current subcategory are done. change subcategory.1252 if (subcategory_ids.length < subcategories_length)1253 {//change subcategory in same category1254 //TODO: set examples_ids = 0, examples_length -> to current subcategory length1255 let id;1256 for (id = 0;id <subcategory_ids.length; id++)1257 {//loop until an id is not found in sequencial order. (if randomly added a subcategory)1258 if (subcategory_ids[id] > id)1259 {//greater subcategory id (randomly added before) is found. change to undone subcategory1260 break;1261 }1262 }1263 //if all subcategories were added sequencially then, id holds the value of the very next subcategory id.1264 //adding new subcategory id to ids list1265 subcategory_ids.push(id);1266 //sorting the ids.1267 subcategory_ids.sort(sortIds);1268 //reseting the values of examples ids1269 examples_ids = [];1270 //updating value of subcategory1271 subcategory = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,sessionAttributes.category),"native")[id];1272 //setting value of examples length in current subcategory1273 examples_length = createReturnList("word",sessionAttributes,[retrieveFromJson(sessionAttributes,category,subcategory)],"native",true)[0].length;1274 change = 1;1275 }1276 else1277 {//change category and add first subcategory1278 //TODO: set examples_ids = 0, examples_length -> to current subcategory length, set subcategories_ids = 0, subcategories_length -> current category length1279 //reset subcategory ids1280 subcategory_ids = [];1281 //reset example ids1282 examples_ids = [];1283 //get categories names1284 const categories_info = createReturnList('category',sessionAttributes,retrieveFromJson(sessionAttributes),"native");1285 //current category id1286 const current_category_id = infoFound(category,categories_info);1287 //check which category is next and update the category value1288 category = (current_category_id == categories_info.length-1) ? categories_info[0] : categories_info[current_category_id+1];1289 //updating value of new subcategory1290 subcategory = createReturnList('title',sessionAttributes,retrieveFromJson(sessionAttributes,category),"native")[0];1291 //pushing to subcategory_ids the first sub_id.1292 subcategory_ids.push(0);1293 //setting value of examples length in current subcategory1294 examples_length = createReturnList("word",sessionAttributes,[retrieveFromJson(sessionAttributes,category,subcategory)],"native",true)[0].length;1295 change = 2;1296 }1297 }1298 }1299 if (change == 1)1300 {1301 output += retrieve_Strings("general",sessionAttributes.native_language,"subcategory_completed");1302 output+= retrieve_Strings("general",sessionAttributes.native_language,"next_subcategory")+" "+subcategory.replace(","," and")+" . ";1303 output += retrieve_Strings("general",sessionAttributes.native_language,"new_subcategory")+subcategory.replace(","," and")+" . ";1304 }1305 else if (change == 2)1306 {1307 output += retrieve_Strings("general",sessionAttributes.native_language,"subcategory_completed");1308 output += retrieve_Strings("general",sessionAttributes.native_language,"category_completed");1309 output += retrieve_Strings("general",sessionAttributes.native_language,"new_category")+" "+category+". ";1310 output += retrieve_Strings("general",sessionAttributes.native_language,"new_subcategory")+subcategory.replace(","," and")+" . ";1311 }1312 //proceeding to seting up example.1313 if (new_example_entry)1314 {//example validation done. updating values1315 //updating the values of current example to the session attributes.1316 Object.assign(sessionAttributes,new_example_entry);1317 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1318 Object.assign(sessionAttributes,1319 {1320 voice: retrieve_Strings("voices",sessionAttributes.learning_language),1321 break: 1,1322 level: "strong",1323 });1324 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1325 output = output+switchVoice(sessionAttributes.learning_word,sessionAttributes)+". ";1326 Object.assign(sessionAttributes,1327 {1328 voice: retrieve_Strings("voices",sessionAttributes.native_language),1329 break: 1,1330 level: "strong",1331 });1332 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1333 output = output+" "+switchVoice(sessionAttributes.native_word,sessionAttributes)+". ";1334 }1335 }1336 }1337 }13381339 //updating the session Attributes1340 Object.assign(sessionAttributes,1341 {1342 lastmsg: output,1343 subcategory: subcategory,1344 subcategory_ids: subcategory_ids,1345 examples_length: examples_length,1346 helpmsg: (category!= undefined && subcategory != undefined) ? "ExampleIntent" : "ShowCategories",1347 break: 0,1348 rate: "100%",1349 volume: "medium",1350 });1351 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);13521353 //setting appropriate voice for the return message.1354 output = switchVoice(output,sessionAttributes);13551356 return handlerInput.responseBuilder1357 .withShouldEndSession(false)1358 .speak(output)1359 .getResponse();1360 },1361}13621363/**1364 * Custom Intent to show current example details.1365 * word or phrase. (in both languages - native & learning)1366 */1367const DetailsIntent = {1368 canHandle(handlerInput)1369 {1370 return handlerInput.requestEnvelope.request.type === 'IntentRequest'1371 && handlerInput.requestEnvelope.request.intent.name === 'DetailsIntent';1372 },1373 handle(handlerInput)1374 {1375 let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();1376 const slots = handlerInput.requestEnvelope.request.intent.slots;13771378 const detail = slots['detail'].value;1379 let language = slots['language'].value;1380 let output ="";1381 let language_request_english = returnSpokenLanguage(language); //language that the request was given. (in english)13821383 if (sessionAttributes.category == undefined || sessionAttributes.subcategory == undefined )1384 {//in case category or subcategory were reset prior to this request1385 output = retrieve_Strings("help",sessionAttributes.native_language,"show_categories");1386 Object.assign(sessionAttributes,1387 {1388 lastmsg: output,1389 helpmsg: "ShowCategories",1390 voice: retrieve_Strings("voices",sessionAttributes.native_language),1391 break: 0,1392 rate: "100%",1393 volume: "medium",1394 });1395 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1396 }1397 else1398 {//valid to proceed. category and subcategory are set.1399 if (language !=undefined1400 && language_request_english.toUpperCase() != sessionAttributes.learning_language.toUpperCase()1401 && language_request_english.toUpperCase() != sessionAttributes.native_language.toUpperCase())1402 {//request given in different language1403 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1404 }1405 else if (sessionAttributes.category == undefined || sessionAttributes.subcategory == undefined) // category and subcategory were reset prior to this request1406 output = retrieve_Strings("help",sessionAttributes.native_language,"show_categories");1407 else1408 {1409 if (sessionAttributes.examples_ids != undefined && sessionAttributes.examples_ids.length>0)1410 {//validation for existance of an example1411 if (language == undefined)1412 language = sessionAttributes.native_language;14131414 if (language.toUpperCase() != retrieve_Strings("translation",sessionAttributes.native_language,sessionAttributes.native_language).toUpperCase()1415 && language.toUpperCase() != retrieve_Strings("translation",sessionAttributes.native_language,sessionAttributes.learning_language).toUpperCase()1416 && language.toUpperCase() != retrieve_Strings("translation",sessionAttributes.learning_language,sessionAttributes.native_language).toUpperCase()1417 && language.toUpperCase() != retrieve_Strings("translation",sessionAttributes.learning_language,sessionAttributes.learning_language).toUpperCase() )1418 {//request given in different language1419 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1420 }1421 else1422 {//validation for languages completed1423 if (detail.toUpperCase() == checkEditor("details_list",sessionAttributes.native_language,"word").toUpperCase()1424 || detail.toUpperCase() == checkEditor("details_list",sessionAttributes.learning_language,"word").toUpperCase())1425 {//user requested to see the word of the example1426 if (language.toUpperCase() == sessionAttributes.native_language.toUpperCase()1427 || language.toUpperCase() == retrieve_Strings("translation",sessionAttributes.learning_language,sessionAttributes.native_language.toUpperCase()).toUpperCase())1428 {//in native language1429 Object.assign(sessionAttributes,1430 {1431 voice:retrieve_Strings("voices",sessionAttributes.native_language),1432 });1433 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1434 output = switchVoice(sessionAttributes.native_word,sessionAttributes);1435 }1436 else if (language.toUpperCase() == sessionAttributes.learning_language.toUpperCase()1437 || language.toUpperCase() == retrieve_Strings("translation",sessionAttributes.native_language,sessionAttributes.learning_language.toUpperCase()).toUpperCase()1438 || language.toUpperCase() == retrieve_Strings("translation",sessionAttributes.learning_language,sessionAttributes.learning_language.toUpperCase()).toUpperCase())1439 {//in learning language1440 Object.assign(sessionAttributes,1441 {1442 voice:retrieve_Strings("voices",sessionAttributes.learning_language),1443 });1444 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1445 output = switchVoice(sessionAttributes.learning_word,sessionAttributes);1446 }1447 //level = "strong";1448 }1449 else if (detail.toUpperCase() == checkEditor("details_list",sessionAttributes.native_language,"phrase").toUpperCase()1450 || detail.toUpperCase() == checkEditor("details_list",sessionAttributes.learning_language,"phrase").toUpperCase())1451 {//user requested to see the phrase of the example1452 if (language.toUpperCase() == sessionAttributes.native_language.toUpperCase() || language.toUpperCase() == retrieve_Strings("translation",sessionAttributes.learning_language,sessionAttributes.native_language.toUpperCase()).toUpperCase())1453 {//in native language1454 Object.assign(sessionAttributes,1455 {1456 voice:retrieve_Strings("voices",sessionAttributes.native_language),1457 });1458 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1459 output = switchVoice(sessionAttributes.native_phrase,sessionAttributes);1460 }1461 else if (language.toUpperCase() == sessionAttributes.learning_language.toUpperCase() || language.toUpperCase() == retrieve_Strings("translation",sessionAttributes.native_language,sessionAttributes.learning_language.toUpperCase()).toUpperCase())1462 {//in learning language1463 Object.assign(sessionAttributes,1464 {1465 voice:retrieve_Strings("voices",sessionAttributes.learning_language),1466 });1467 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1468 output = switchVoice(sessionAttributes.learning_phrase,sessionAttributes);1469 }1470 //level = "strong";1471 }1472 else1473 output = retrieve_Strings("warnings",sessionAttributes.native_language,"different_request");1474 }1475 //updating the session Attributes1476 Object.assign(sessionAttributes,1477 {1478 lastmsg: output,1479 helpmsg: "DetailsIntent",1480 voice: retrieve_Strings("voices",sessionAttributes.native_language),1481 break: 1,1482 rate: "100%",1483 volume: "medium",1484 });1485 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);14861487 }1488 else1489 {//no example was selected previous this request.1490 output = retrieve_Strings("warnings",sessionAttributes.native_language,"example");1491 //updating the session Attributes1492 Object.assign(sessionAttributes,1493 {1494 lastmsg: output,1495 helpmsg: "Launch",1496 voice: retrieve_Strings("voices",sessionAttributes.native_language),1497 break: 0,1498 rate: "100%",1499 volume: "medium",1500 });1501 handlerInput.attributesManager.setSessionAttributes(sessionAttributes);1502 }1503 }1504 }150515061507 //setting appropriate voice for the return message.1508 output = switchVoice(output,sessionAttributes);15091510 return handlerInput.responseBuilder1511 .withShouldEndSession(false)1512 .speak(output)1513 .getResponse();1514 },1515};15161517// USER DEFINED FUNCTIONS15181519/**1520 * @description Returns a specific section of the content file1521 *1522 * @author CharalamposTheodorou1523 * @since 1.01524 *1525 * @param {String} category Name of category in JSON format1526 * @param {String} subcategory Name of subcategory in JSON fromat1527 *1528 * @return Object of specified section of content file1529 */1530function retrieveFromJson(sessionAttributes,category = undefined,subcategory = undefined)1531{1532 if (category == undefined && subcategory == undefined)1533 {//return the categories info section for all categories1534 //categories info is static section in all json vocabulary files created1535 return skill_files.content().CATEGORIES_INFO;1536 }1537 else if(category!= undefined && subcategory == undefined)1538 {//category given, must retrieve the category section.1539 //must transform the category name into english (json static field values)1540 //get the values of all categories info. to transform the name1541 const cat_info_keys = Object.values(skill_files.content().CATEGORIES_INFO);1542 for (var j=0; j<cat_info_keys.length; j++)1543 {1544 if (removeSSML(languageProvider(sessionAttributes.learning_language,cat_info_keys[j],"category")).toUpperCase() == category.toUpperCase() || removeSSML(languageProvider(sessionAttributes.native_language,cat_info_keys[j],"category")).toUpperCase() == category.toUpperCase())1545 {//category name found in learning or native language1546 category = removeSSML(languageProvider("english",cat_info_keys[j],"category"));1547 }1548 }1549 const keys = Object.keys(skill_files.content());1550 //to skip the categories_info section1551 for (var i=1; i<keys.length; i++)1552 if (keys[i].toUpperCase() == category.toUpperCase().split(" ").join("_"))1553 {//found here1554 return Object.values(skill_files.content())[i];1555 }1556 return undefined;1557 }1558 else if (category != undefined && subcategory != undefined)1559 {1560 let test_out="";1561 //section of category containing all subcategories1562 const category_sections = retrieveFromJson(sessionAttributes,category);15631564 for (var k=0; k<category_sections.length; k++)1565 {//find correct subcategory section1566 if ( removeSSML(languageProvider(sessionAttributes.learning_language,category_sections[k],"title")).toUpperCase()== subcategory.toUpperCase()1567 || removeSSML(languageProvider(sessionAttributes.native_language,category_sections[k],"title")).toUpperCase()== subcategory.toUpperCase())1568 {//found clean subcategory name1569 return category_sections[k];1570 }1571 else1572 test_out+= 'nope for '+k;15731574 }1575 return "here:"+test_out;1576 }1577 return undefined;1578}15791580/**1581 * @description Checks if the given keyword (category or subcategory) exists for the selected languages1582 *1583 * @author CharalamposTheodorou1584 * @since 1.01585 *1586 * @param {String} query_response Name of category or subcategory1587 * @param {Array} category_list List of category/subcategory names to check1588 *1589 * @return Position in list or undefined if not found1590 */1591function infoFound(query_response, category_list)1592{1593 for (var i=0; i<category_list.length/2; i++)1594 {1595 if (category_list[i].toUpperCase() == query_response.toUpperCase()1596 || category_list[i].toUpperCase() == query_response.replace(" and",",").toUpperCase()1597 || category_list[category_list.length/2+i].toUpperCase() == query_response.toUpperCase()1598 || category_list[category_list.length/2+i].toUpperCase() == query_response.replace(" and",",").toUpperCase())1599 return category_list[i].toUpperCase() == query_response.toUpperCase() ? i : category_list.length/2+i;1600 }1601 return undefined;1602}16031604/**1605 * @description Takes the custom parameters and creates and returns a clean list (no ssml tags) of content information1606 *1607 * @author CharalamposTheodorou1608 * @since 1.01609 *1610 * @param {String} option The type of section to return from the language provider options1611 * @param {Object} sessionAttributes Object that contains the session attributes of the user1612 * @param {Object} section_info Json Section retrieved from the content file1613 * @param {String} return_option Option for the return values1614 *1615 * @return the list of categories/subcategories or undefined if content error1616 */1617function createReturnList(option,sessionAttributes,section_info,return_option,tags = false)1618{1619 //2 languages to check in the categories info list.1620 const learning_language = sessionAttributes.learning_language;1621 const native_language = sessionAttributes.native_language;16221623 if (section_info != undefined)1624 {//successfully retrieved the section info1625 var learning_list = [section_info.length];1626 var native_list = [section_info.length];1627 //get the categories info section from json.1628 if (learning_language != undefined)1629 {1630 for (var i=0; i < section_info.length; i++)1631 {1632 const learning_title = languageProvider(learning_language,section_info[i],option);1633 const native_title = languageProvider(native_language,section_info[i],option);1634 if (tags)1635 {1636 native_list[i]= native_title == undefined ? "false" : native_title;1637 learning_list[i]= learning_title == undefined ? "false" : learning_title;1638 }1639 else1640 {1641 native_list[i]= removeSSML(native_title) == "false" ? "false" : removeSSML(native_title);1642 learning_list[i]= removeSSML(learning_title) == "false" ? "false" : removeSSML(learning_title);1643 }1644 }1645 if (return_option == "all")1646 return native_list.concat(learning_list);1647 else if (return_option == "native")1648 return native_list;1649 else if (return_option == "learning")1650 return learning_list;1651 }1652 }1653 return undefined;1654}16551656/**1657 * @description Takes parameter a string and removes any ssml tags included before. Returns clean text.1658 *1659 * @author CharalamposTheodorou1660 * @since 1.01661 *1662 * @param {String} ssmltext Text with ssml tags1663 *1664 * @return text with tags stripped1665 */1666function removeSSML(ssmltext)1667{1668 if (ssmltext == undefined)1669 return "false";1670 //index variable to remove the ssml tags from the values1671 var index = ssmltext.indexOf('<');1672 let tag;1673 while(index!=-1)1674 {1675 //to cleanse the text1676 tag = ssmltext.substring(index,ssmltext.indexOf('>')+1);1677 ssmltext = ssmltext.replace(tag,"");1678 index = ssmltext.indexOf('<');1679 }1680 return ssmltext;1681}16821683/**1684 * @description Finds and returns a new example1685 *1686 * @author CharalamposTheodorou1687 * @since 1.01688 *1689 * @param {Object} subcategory_info Current subcategory information for all examples1690 * @param {Array} examples_ids All examples' ids already done1691 * @param {Boolean} random Whether to set a random or next example1692 */1693function getExample(subcategory_info,examples_ids,random)1694{1695 let example_id;1696 //To find the examples not shown yet.1697 if (random)1698 {//random example is enabled here1699 while(example_id == undefined)1700 {1701 //next random example id1702 example_id = Math.floor(Math.random()*subcategory_info.native_words.length);1703 for (let i=0; i<examples_ids.length; i++)1704 {1705 if (examples_ids[i] == example_id)1706 {//example id found reset random id1707 example_id = undefined;1708 break;1709 }1710 }1711 }1712 }1713 else1714 {//just the next.. (all checks for end of subcategory is done before this.)1715 if (examples_ids.length == 0)1716 {//first example of a new category1717 example_id = 0;1718 }1719 else1720 {//find next available example1721 for(let i=0; i<examples_ids.length; i++)1722 {//loop through all examples ids.1723 if (examples_ids[i] > i)1724 {//sorted list1725 example_id = i;1726 break;1727 }1728 }1729 //examples were done in sequence add he very next1730 if (example_id == undefined)1731 example_id = examples_ids.length;1732 }1733 }1734 if (example_id != undefined)1735 {//id of next example is set1736 examples_ids.push(example_id);1737 //Object value of next example information1738 return Object.assign({},1739 {1740 native_word: subcategory_info.native_words[example_id],1741 learning_word: subcategory_info.learning_words[example_id],1742 native_phrase: subcategory_info.native_phrases[example_id],1743 learning_phrase: subcategory_info.learning_phrases[example_id],1744 examples_ids: examples_ids.sort(sortIds),1745 });1746 }1747 else1748 return false;1749}17501751/**1752 * @description Returns the text given with ssml tags for modifiation in the return message of Alexa1753 *1754 * @author CharalamposTheodorou1755 * @since 1.01756 *1757 * @param {Strings} text : text given to modify before returing1758 * @param {Object} sessionAttributes Object that contains the session attributes of the user1759 *1760 * @return String Spoken message for Alexa with ssml tags for customization.1761 */1762function switchVoice(text,sessionAttributes) {1763 if (text){1764 return "<voice name = '"+sessionAttributes.voice +"'><break time='"+sessionAttributes.break+"s'/><prosody rate='"+sessionAttributes.rate+"' volume='"+sessionAttributes.volume+"'>"+text+"</prosody></voice>"1765 }1766 }17671768/**1769 * @description Returns the selected value from the content file, given a specific key and language option1770 *1771 * @author CharalamposTheodorou1772 * @since 1.01773 *1774 * @param {String} language language that the value will be returned1775 * @param {Object} info Object that holds all the info for the current section1776 * @param {String} option category | subcategory | example | word | phrase: which part of the section to return1777 *1778 * @return Value requested or false if not found.1779 */1780function languageProvider(language,info,option)1781{1782 if (option == "category")1783 {//inside CATEGORIES_INFO.1784 switch(language.toUpperCase())1785 {1786 case "ENGLISH":1787 return info.english_title;1788 case "SPANISH" :1789 return info.spanish_title;1790 case "GERMAN":1791 return info.german_title;1792 case "FRENCH":1793 return info.french_title;1794 case "ITALIAN":1795 return info.italian_title;1796 }1797 }1798 else if (option == "subcategory")1799 {//inside CATEGORIES_INFO.1800 switch(language.toUpperCase())1801 {1802 case "ENGLISH":1803 return info.english_sub;1804 case "SPANISH":1805 return info.spanish_sub;1806 case "GERMAN":1807 return info.german_sub;1808 case "FRENCH":1809 return info.french_sub;1810 case "ITALIAN":1811 return info.italian_sub;1812 }1813 }1814 else if (option == "title")1815 {//inside a category content information1816 switch(language.toUpperCase())1817 {1818 case "ENGLISH":1819 return info.english_title;1820 case "SPANISH":1821 return info.spanish_title;1822 case "GERMAN":1823 return info.german_title;1824 case "FRENCH":1825 return info.french_title;1826 case "ITALIAN":1827 return info.italian_title;1828 }1829 }1830 else if (option == "word")1831 {1832 switch(language.toUpperCase())1833 {1834 case "ENGLISH":1835 return info.english_word;1836 case "SPANISH":1837 return info.spanish_word;1838 case "GERMAN":1839 return info.german_word;1840 case "FRENCH":1841 return info.french_word;1842 case "ITALIAN":1843 return info.italian_word;1844 }1845 }1846 else if (option == "phrase")1847 {1848 switch(language.toUpperCase())1849 {1850 case "ENGLISH":1851 return info.english_phrase;1852 case "SPANISH":1853 return info.spanish_phrase;1854 case "GERMAN":1855 return info.german_phrase;1856 case "FRENCH":1857 return info.french_phrase;1858 case "ITALIAN":1859 return info.italian_phrase;1860 }1861 }18621863 return "false";1864}18651866/**1867 * @description Takes as parameter 2 numbers and sorts them in a list of ids1868 *1869 * @author CharalamposTheodorou1870 * @since 1.01871 *1872 * @param {Integer} id_1 First id to sort1873 * @param {Integer} id_2 Second id to sort1874 *1875 * @return Sorted list of ids1876 */1877function sortIds(id_1, id_2)1878{1879 return id_1-id_2;1880}18811882/**1883 * @description Responsible to check if given keyword is in correct language.1884 *1885 * @author CharalamposTheodorou1886 * @since 1.01887 *1888 * @param {String} keyword_category the category of the keyword for all languages.1889 * @param {String} language Language to check with1890 * @param {String} type type of keyword.1891 *1892 * @return Requested keyword or false if not found1893 */1894function checkEditor(keyword_category,language,type)1895{1896 let retriever;1897 if (language != undefined)1898 {1899 switch(keyword_category)1900 {1901 case "language_type":1902 {1903 retriever = skill_files.editor_options().LANGUAGE_TYPE_LIST;1904 for (let i=0;i<retriever.length; i++)1905 {1906 if (retriever[i].language.toUpperCase() == language.toUpperCase())1907 switch(type)1908 {//given in english.. by program.1909 case "native":1910 return retriever[i].native;1911 case "mother":1912 return retriever[i].mother;1913 case "teaching":1914 return retriever[i].teaching;1915 case "second":1916 return retriever[i].second;1917 case "learning":1918 return retriever[i].learning;1919 }1920 }1921 }1922 case "speed_list":1923 {1924 retriever = skill_files.editor_options().SPEED_LIST;1925 for (let i=0;i<retriever.length; i++)1926 {1927 if (retriever[i].language.toUpperCase() == language.toUpperCase())1928 switch(type)1929 {//given in english.. by program.1930 case "faster":1931 return retriever[i].faster;1932 case "slower":1933 return retriever[i].slower;1934 }1935 }1936 }1937 case "volume_list":1938 {1939 retriever = skill_files.editor_options().VOLUME_LIST;1940 for (let i=0;i<retriever.length; i++)1941 {1942 if (retriever[i].language.toUpperCase() == language.toUpperCase())1943 switch(type)1944 {//given in english.. by program.1945 case "louder":1946 return retriever[i].louder;1947 case "quieter":1948 return retriever[i].quieter;1949 }1950 }1951 }1952 case "help_options_list":1953 {1954 retriever = skill_files.editor_options().HELP_OPTIONS_LIST;1955 for (let i=0;i<retriever.length; i++)1956 {1957 if (retriever[i].language.toUpperCase() == language.toUpperCase())1958 switch(type)1959 {//given in english.. by program.1960 case "help":1961 return retriever[i].help;1962 case "instructions":1963 return retriever[i].instructions;1964 case "options":1965 return retriever[i].options;1966 }1967 }1968 }1969 case "request_list":1970 {1971 retriever = skill_files.editor_options().REQUEST_LIST;1972 for (let i=0;i<retriever.length; i++)1973 {1974 if (retriever[i].language.toUpperCase() == language.toUpperCase())1975 switch(type)1976 {//given in english.. by program.1977 case "current_category":1978 return retriever[i].current_category;1979 case "current_theme":1980 return retriever[i].current_theme;1981 case "current_subcategory":1982 return retriever[i].current_subcategory;1983 case "current_topic":1984 return retriever[i].current_topic;1985 case "current_example":1986 return retriever[i].current_example;1987 case "native_language":1988 return retriever[i].native_language;1989 case "mother_language":1990 return retriever[i].mother_language;1991 case "learning_language":1992 return retriever[i].learning_language;1993 case "language_list":1994 return retriever[i].language_list;1995 case "category_list":1996 return retriever[i].category_list;1997 case "theme_list":1998 return retriever[i].theme_list;1999 }2000 }2001 }2002 case "details_list":2003 {2004 retriever = skill_files.editor_options().DETAILS_LIST;2005 for (let i=0;i<retriever.length; i++)2006 {2007 if (retriever[i].language.toUpperCase() == language.toUpperCase())2008 switch(type)2009 {//given in english.. by program.2010 case "word":2011 return retriever[i].word;2012 case "phrase":2013 return retriever[i].phrase;2014 }2015 }2016 }2017 case "continue_in_sub_list":2018 {2019 retriever = skill_files.editor_options().CONTINUE_IN_SUB_LIST;2020 for (let i=0;i<retriever.length; i++)2021 {2022 if (retriever[i].language.toUpperCase() == language.toUpperCase())2023 switch(type)2024 {//given in english.. by program.2025 case "more":2026 return retriever[i].more;2027 case "another":2028 return retriever[i].another;2029 case "next":2030 return retriever[i].next;2031 case "reset":2032 return retriever[i].reset;2033 case "restart":2034 return retriever[i].restart;2035 case "start":2036 return retriever[i].start;2037 }2038 }2039 }2040 case "continue_in_cat_list":2041 {2042 retriever = skill_files.editor_options().CONTINUE_IN_CAT_LIST;2043 for (let i=0;i<retriever.length; i++)2044 {2045 if (retriever[i].language.toUpperCase() == language.toUpperCase())2046 switch(type)2047 {//given in english.. by program.2048 case "next_category":2049 return retriever[i].next_category;2050 case "another_category":2051 return retriever[i].another_category;2052 case "next_theme":2053 return retriever[i].next_theme;2054 case "another_theme":2055 return retriever[i].another_theme;2056 }2057 }2058 }2059 case "option_list":2060 {2061 retriever = skill_files.editor_options().OPTION_LIST;2062 for (let i=0;i<retriever.length; i++)2063 {2064 if (retriever[i].language.toUpperCase() == language.toUpperCase())2065 switch(type)2066 {//given in english.. by program.2067 case "categories":2068 return retriever[i].categories;2069 case "subcategories":2070 return retriever[i].subcategories;2071 case "themes":2072 return retriever[i].themes;2073 case "topics":2074 return retriever[i].topics;2075 }2076 }2077 }2078 case "random_option_list":2079 {2080 retriever = skill_files.editor_options().RANDOM_OPTION_LIST;2081 for (let i=0;i<retriever.length; i++)2082 {2083 if (retriever[i].language.toUpperCase() == language.toUpperCase())2084 switch(type)2085 {//given in english.. by program.2086 case "category":2087 return retriever[i].category;2088 case "subcategory":2089 return retriever[i].subcategory;2090 case "topic":2091 return retriever[i].topic;2092 case "theme":2093 return retriever[i].theme;2094 }2095 }2096 }2097 case "repeat_list":2098 {2099 retriever = skill_files.editor_options().REPEAT_LIST;2100 for (let i=0;i<retriever.length; i++)2101 {2102 if (retriever[i].language.toUpperCase() == language.toUpperCase())2103 switch(type.toUpperCase())2104 {//given in english.. by program.2105 case "repeat".toUpperCase():2106 return retriever[i].repeat;2107 case "again".toUpperCase():2108 return retriever[i].again;2109 case "repeat again".toUpperCase():2110 return retriever[i].repeat_again;2111 case "repeat normal".toUpperCase():2112 return retriever[i].repeat_normal;2113 }2114 }2115 }2116 case "random_list":2117 {2118 retriever = skill_files.editor_options().RANDOM_LIST;2119 for (let i=0;i<retriever.length; i++)2120 {2121 if (retriever[i].language.toUpperCase() == language.toUpperCase())2122 switch(type)2123 {//given in english.. by program.2124 case "random":2125 return retriever[i].random;2126 case "shuffle":2127 return retriever[i].shuffle;2128 }2129 }2130 }2131 }2132 }2133 return "false";2134}21352136/**2137 * @description Finds and returns the language's name in the requested language2138 *2139 * @author CharalamposTheodorou2140 * @since 1.02141 *2142 * @param {String} language Language to return the native name2143 *2144 * @return Native name of language or undefined if not found2145 */2146function returnSpokenLanguage(language)2147{2148 if (language == undefined)2149 return "undefined";2150 let retriever = skill_files.content_language_strings().LANGUAGE_TRANSLATIONS;2151 for (let i=0;i<retriever.length;i++)2152 {2153 for (let j=0;j<retriever[i].language.length;j++)2154 {2155 if (language.toUpperCase() == retriever[i].language[j].toUpperCase())2156 switch(j)2157 {2158 case 0: return "english";2159 case 1: return "spanish";2160 case 2: return "german";2161 case 3: return "french";2162 case 4: return "italian";2163 default: return "unidentified";2164 }2165 }2166 }2167 return "undefined";2168}21692170/**2171 * @description Returns a requested message that Alexa will display next2172 *2173 * @author CharalamposTheodorou2174 * @since 1.02175 *2176 * @param {String} string_category Category of string to search for2177 * @param {String} language Language that the string was requested in2178 * @param {String} type Type of message to return.2179 *2180 * @return Requested string to show or false if not found2181 */2182function retrieve_Strings(string_category,language,type)2183{2184 let retriever;2185 switch(string_category)2186 {2187 case "voices":2188 {2189 retriever = skill_files.content_language_strings().VOICES;2190 for (let i=0;i<retriever.length; i++)2191 {2192 if (retriever[i].language.toUpperCase() == language.toUpperCase())2193 return retriever[i].voice;2194 }2195 }2196 case "general":2197 {2198 retriever = skill_files.content_language_strings().GENERAL_STRINGS;2199 for (let i=0;i<retriever.length; i++)2200 {2201 if (retriever[i].language.toUpperCase() == language.toUpperCase())2202 {2203 switch(type)2204 {2205 case "options":2206 return retriever[i].options;2207 case "suggested":2208 return retriever[i].suggested_example;2209 case "category_list":2210 return retriever[i].category_list;2211 case "subcategory_list":2212 return retriever[i].subcategory_list;2213 case "new_category":2214 return retriever[i].new_category;2215 case "new_subcategory":2216 return retriever[i].new_subcategory;2217 case "fallback":2218 return retriever[i].fallback;2219 case "category_completed":2220 return retriever[i].category_completed;2221 case "subcategory_completed":2222 return retriever[i].subcategory_completed;2223 case "next_subcategory":2224 return retriever[i].next_subcategory;2225 case "example":2226 return retriever[i].example;2227 }2228 }2229 }2230 }2231 case "help":2232 {2233 retriever = skill_files.content_language_strings().HELP_STRINGS;2234 for (let i=0;i<retriever.length; i++)2235 {2236 if (retriever[i].language.toUpperCase() == language.toUpperCase())2237 {2238 switch(type)2239 {2240 case "launch":2241 return retriever[i].launch;2242 case "show_categories":2243 return retriever[i].show_categories;2244 case "example":2245 return retriever[i].example;2246 case "select_categories":2247 return retriever[i].select_categories;2248 case "details":2249 return retriever[i].details;2250 case "resume":2251 return retriever[i].resume;2252 case "reset":2253 return retriever[i].reset;2254 }2255 }2256 }2257 }2258 case "options":2259 {2260 retriever = skill_files.content_language_strings().OPTION_STRINGS;2261 for (let i=0;i<retriever.length; i++)2262 {2263 if (retriever[i].language.toUpperCase() == language.toUpperCase())2264 {2265 switch(type)2266 {2267 case "welcome":2268 return retriever[i].welcome;2269 case "show_categories":2270 return retriever[i].show_categories;2271 case "example":2272 return retriever[i].example;2273 case "select_categories":2274 return retriever[i].select_categories;2275 case "details":2276 return retriever[i].details;2277 case "resume":2278 return retriever[i].resume;2279 case "reset":2280 return retriever[i].reset;2281 case "index":2282 return retriever[i].index;2283 }2284 }2285 }2286 }2287 case "warnings":2288 {2289 retriever = skill_files.content_language_strings().WARNING_STRINGS;2290 for (let i=0;i<retriever.length; i++)2291 {2292 if (retriever[i].language.toUpperCase() == language.toUpperCase())2293 {2294 switch(type)2295 {2296 case "category":2297 return retriever[i].category;2298 case "example":2299 return retriever[i].example;2300 case "missing_info":2301 return retriever[i].missing_info;2302 case "no_learning_lang":2303 return retriever[i].no_learning_lang;2304 case "different_request":2305 return retriever[i].different_request;2306 case "same_selection":2307 return retriever[i].same_selection;2308 case "native_selection":2309 return retriever[i].native_selection;2310 case "learning_selection":2311 return retriever[i].learning_selection;2312 case "native_warn":2313 return retriever[i].native_warn;2314 case "learning_warn":2315 return retriever[i].learning_warn;2316 case "reset":2317 return retriever[i].reset;2318 case "given_request":2319 return retriever[i].given_request;2320 case "content_error":2321 return retriever[i].content_error;2322 case "name_not_found":2323 return retriever[i].name_not_found;2324 case "not_category":2325 return retriever[i].not_category;2326 case "cancel_stop":2327 return retriever[i].cancel_stop;2328 }2329 }2330 }2331 }2332 case "language":2333 {2334 retriever = skill_files.content_language_strings().LANGUAGE_STRINGS;2335 for (let i=0;i<retriever.length; i++)2336 {2337 if (retriever[i].language.toUpperCase() == language.toUpperCase())2338 {2339 switch(type)2340 {2341 case "list":2342 return retriever[i].list;2343 case "selection":2344 return retriever[i].selection;2345 case "learning":2346 return retriever[i].learning;2347 }2348 }2349 }2350 }2351 case "translation":2352 {2353 retriever = skill_files.content_language_strings().LANGUAGE_TRANSLATIONS;2354 for (let i=0;i<retriever.length; i++)2355 {2356 for (let j=0;j<retriever[i].language.length;j++)2357 {2358 if (retriever[i].language[j].toUpperCase() == language.toUpperCase())2359 {2360 switch(type.toUpperCase())2361 {2362 case "GERMAN":2363 return retriever[i].german;2364 case "SPANISH":2365 return retriever[i].spanish;2366 case "ITALIAN":2367 return retriever[i].italian;2368 case "FRENCH":2369 return retriever[i].french;2370 case "ENGLISH":2371 return retriever[i].english;2372 case "RETURN":2373 return retriever[i].language[0];2374 default:2375 return "unidentified";23762377 }2378 }2379 }2380 }2381 }2382 default:2383 return "unidentified";2384 }2385}23862387/**2388 * @description Checks if request was to give a category by name or number2389 * 2390 * @author CharalamposTheodorou2391 * @since 1.02392 * 2393 * @param {String} query_response String to check if contains a numberical value2394 * 2395 * @return Returns true if doesn't contains a number in the request2396 */2397function check_if_Number(query_response)2398{2399 return isNaN(query_response) == true ? "true" : query_response;2400}24012402 /** All Intents declarations */2403 const skillBuilder = Alexa.SkillBuilders.custom();2404 exports.handler = skillBuilder2405 .addRequestHandlers(2406 LaunchRequest,2407 ExampleIntent,2408 SessionEndedRequest,2409 HelpIntent,2410 CancelAndStopIntentHandler,2411 FallbackHandler,2412 UserSelectionIntent,2413 UserCategorySelectionIntent,2414 UserSubcategorySelectionIntent,2415 ShowCategoriesIntent,2416 RepeatMessageIntent,2417 DetailsIntent,2418 IndexIntent,2419 LanguageSelectionIntent,2420 )2421 .addRequestInterceptors(LocalizationInterceptor)2422 .addErrorHandlers(ErrorHandler) ...

Full Screen

Full Screen

language_strings.js

Source:language_strings.js Github

copy

Full Screen

1module.exports = {2 CONTENT:3 {4 //this must not change..5 VOICES:6 [7 {8 language: "english",9 voice: "Kendra",10 },11 {12 language: "french",13 voice: "Celine",14 },1516 {17 language: "german",18 voice: "Marlene",19 },20 {21 language: "italian",22 voice: "Carla",23 },24 {25 language: "spanish",26 voice: "Lucia",27 }28 ],29 GENERAL_STRINGS:30 [31 {32 language: "english",33 options: "Say Options to get the available commands. ",34 suggested_example: "You can say random theme. ",35 category_list: "The themes are: ",36 subcategory_list: "The topics are: ",37 new_category: "Theme selected: ",38 new_subcategory: "Say start for learning the topic selected: ",39 fallback: "Something was given wrong, please follow the instructions. See you later. ",40 category_completed: "All topics are completed. ",41 subcategory_completed: "All examples of current topic are completed. ",42 next_subcategory: "Moving to topic .",43 example: " example of .",44 },45 {46 language: "french",47 options: "Dites Options pour voir les étapes disponibles. ",48 suggested_example: "Vous pouvez dire catégorie aléatoire. ",49 category_list: "Les catégories sont : ",50 subcategory_list: "Les sous-catégories sont : ",51 new_category: "Catégorie sélectionnée : ",52 new_subcategory: "Sous-catégorie sélectionnée : ",53 fallback: "La demande n'a pas été faite correctement, Veuillez suivre les instructions. A bientôt. ",54 category_completed: "Toutes les sous-catégories sont complètes. ",55 subcategory_completed: "Tous les exemples de la sous-catégorie sélectionnée sont complets. ",56 next_subcategory: "Passons à la sous-catégorie .",57 example: " exemple ",58 },59 {60 language: "german",61 options: "Sagen Sie Optionen, um die verfügbaren Schritte zu bekommen. ",62 suggested_example: "Sie können zufällige Kategorie oder zufällige Unterkategorie sagen. ",63 category_list: "Die folgende Liste ist ein Index aller verfügbaren Kategorien. ",64 subcategory_list: "Die folgende Liste ist ein Index aller Unterkategorien der Kategorie ",65 new_category: "Kategorie ausgewählt: ",66 new_subcategory: "Unterkategorie ausgewählt: ",67 fallback: "Etwas wurde verkehrt gegeben, folgen Sie bitte den Anweisungen. Bis später. ",68 category_completed: "Alle Unterkategorien sind abgeschlossen. ",69 subcategory_completed: "Alle Beispiele der laufenden Unterkategorie sind abgeschlossen. ",70 next_subcategory: "Wechseln zur Unterkategorie .",71 example: " Beispiel ",72 },73 {74 language: "italian",75 options: "Di'Opzioni per visualizzare i passaggi disponibili. ",76 suggested_example: "Puoi dire una categoria casuale o una sottocategoria casuale. ",77 category_list: "La seguente lista è l'indice di tutte le categorie disponibili. ",78 subcategory_list: "La seguente lista è un indice di tutte le sottocategorie di questa categoria.",79 new_category: "Categoria selezionata: ",80 new_subcategory: "Sottocategoria selezionata: ",81 fallback: "Il comando è stato dato in modo incorretto, per favore, segui le istruzioni. A presto. ",82 category_completed: "Tutte le sottocategorie sono completate. ",83 subcategory_completed: "Tutti gli esempi della seguente sottocategoria sono completati. ",84 next_subcategory: "Spostamento alla sottocategoria .",85 example: " esempio di ",86 },87 {88 language: "spanish",89 options: "Di, opciones, para obtener los pasos disponibles. ",90 suggested_example: "Puedes decir, tema aleatorio. ",91 category_list: "Lo temas son: ",92 subcategory_list: "Los topics son: ",93 new_category: "Tema seleccionado: ",94 new_subcategory: "Di, empezar, para aprender el topic seleccionado: ",95 fallback: "Un comando fue dado de manera incorrecta, por favor, siga las instrucciones. Hasta luego. ",96 category_completed: "Todos los topics han sido completados. ",97 subcategory_completed: "Todos los ejemplos del topic actual han sido completados. ",98 next_subcategory: "Moviendo al topic .",99 example: "ejemplo de .",100 }101 ],102 HELP_STRINGS:103 [104 {105 language: "english",106 launch: "Select a learning language to get started. Say Help to get the available steps. ",107 show_categories: "You have to select both a category and a subcategory before preceeding . ",108 example: "Say the language and then word or phrase to get the word or example respectively. ",109 select_categories: "You can now say, start, or next, to move to the next example. Or say, random, to get a random example. ",110 details: "Say the language and then word or phrase to get the word or example respectively. ",111 resume: "Say current and theme, topic or example to relocate yourself. ",112 reset: "Language has changed, select a theme to continue. "113 },114 {115 language: "french",116 launch: "Pour commencer, sélectionnez une langue d'apprentissage. Dites Options pour obtenir plus d'information. ",117 show_categories: "Avant de procéder, vous devez sélectionner une catégorie et une sous-catégorie. ",118 example: "Dites la langue d'apprentissage puis le mot ou l'expression pour obtenir respectivement une traduction ou un exemple. ",119 select_categories: "Maintenant, vous pouvez dire commencer ou suivant pour passer à l'exemple suivant. Dites aléatoir pour obtenir un exemple aléatoir. ",120 details: "Dites votre langue d'apprentissage puis le mot ou expression pour obtenir respectivement une traduction ou un exemple. ",121 resume: "Dites catégorie actuelle, sous-catégorie ou exemple pour vous déplacer. ",122 reset: "Langue d'apprentissage modifiée. Sélectionnez une catégorie pour continuer. "123 },124 {125 language: "german",126 launch: "Wählen Sie eine Lernsprache aus, um loszulegen. Sagen Sie Optionen oder Anweisungen, um weitere Hilfe zu erhalten. ",127 show_categories: "Sie müssen vor dem Vorgeben sowohl eine Kategorie als auch eine Unterkategorie auswählen. Zufällig ist immer eine Option. ",128 example: "Sagen Sie Wort oder Mutterwort lernen, um das Wort oder den spanischen Oder englischen Satz zu erhalten, um das Beispiel zu erhalten. ",129 select_categories: "Sie können nun sagen, start oder next, um zum nächsten Beispiel zu wechseln. Oder sagen Sie zufällig, um ein zufälliges Beispiel zu erhalten. ",130 details: "Sagen Sie spanisches Wort oder englisches Wort, um das Wort oder den spanischen Ausdruck oder den englischen Ausdruck zu erhalten, um das Beispiel zu erhalten.",131 resume: "Sagen Sie Strom und Kategorie, Unterkategorie oder Beispiel, um sich selbst zu verschieben. ",132 reset: "Das Erlernen der Sprache hat sich geändert, wählen Sie kategorie aus, um fortzufahren. "133 },134 {135 language: "italian",136 launch: "Seleziona una lingua di apprendimento per iniziare. Di'opzioni o istruzioni per ricevere ulteriore aiuto. ",137 show_categories: "Devi selezionare sia una categoria che una sottocategoria prima di procedere. Casuale è sempre un'opzione. ",138 example: "Di'una parola nella lingua di apprendimento o una parola nella lingua materna per ottenere la parola o una frase in spagnolo o una frase in inglese per ottenere un esempio casuale. ",139 select_categories: "Adesso puoi dire inizio o successivo per passare all'esempio seguente. Oppure di' casuale per ottenere un esempio casuale. ",140 details: "Di' una parola in spagnolo o in inglese per ottenere la parola oppure una frase in spagnolo o in inglese per ottenere un esempio casuale.",141 resume: "Di'attuale e categoria, sottocategoria o esempio per riposizionarti. ",142 reset: "Lingua di apprendimento cambiata, seleziona una categoria per continuare. ",143 },144 {145 language: "spanish",146 launch: "Selecciona un idioma de aprendizaje para empezar. Dí, ayuda, para obtener más información. ",147 show_categories: "Tienes que seleccinar ambas, un tema y un topic antes de poder proceder. ",148 example: "Diga el idioma y luego la palabra o frase para obtener la palabra o ejemplo respectivo.",149 select_categories: "Ahora puedes decir, inicio, o, siguiente, para pasar al siguiente ejemplo. O decir, aleatorio, para obtener un ejemplo aleatorio. ",150 details: "Diga el idioma y luego la palabra o frase para obtener la palabra o ejemplo respectivo. ",151 resume: "Dí tema actual, topic actual, o, ejemplo, para rehubicarte. ",152 reset: "El idioma de aprenizaje ha cambiado, selecciona un tema para continuar. ",153 }154 ],155 OPTION_STRINGS:156 [157 {158 language: "english",159 welcome: "Say learn and the language. Say language list to get all languages available. Say change native language to and the language if you need a different native language. ",160 show_categories: "Say, show themes, or, show topics, to see list of categories or subcategories. You can use the index numbers of the categories as a shortcut to access the categories. Random is always an option. ",161 select_categories: "Say next to give next in order example. Repeat, to repeat the word, Random, to give the next random example, view current subcategory, to give the next random example and next category, to move forward. ",162 example: "Say, random, to give the next random example. Say next to give next in order example. View current example by saying view example. ",163 details: "Say the language you want to view and word or phrase. ",164 reset: "Say theme list, to get the list of available themes. Say open theme, and the theme number, to open a theme. ",165 resume: "Continue where you left of before. Say, themes, to get the list themes. ",166 index: "Say, next, or, random, to continue with the next example. Say, current topic, to get the current topic. "167 },168 {169 language: "french",170 welcome: "Dites apprendre et une langue. Dites liste des langues pour connaître toutes les langues disponibles. Dites changer la langue maternelle pour et une langue pour changer la langue maternelle. ",171 show_categories: "Dites montrer les catégories ou sous-catégories pour obtenir la liste des catégories ou sous-catégories. Vous pouvez utiliser le numéro de chapitre des catégories comme raccourci pour accéder aux catégories. Aléatoir est toujours une option. Si vous connaissez la catégorie, dites ouvrir catégorie et le nom de la catégorie. ",172 select_categories: "Dites suivant pour obtenir l'exemple suivant dans la liste. Dites aléatoir pour obtenir l'exemple aléatoir suivant. Accédez à la sous-catégorie actuelle en disant voir sous-catégorie. Dites catégorie suivante pour avancer. ",173 example: "Dites aléatoir pour obtenir l'exemple aléatoir suivant. Dites suivant pour obtenir l'exemple suivant dans la liste. Accédez à l'exemple actuel en disant voir exemple. ",174 details: "Dites la langue que vous voulez et un mot ou une expression ",175 reset: "Dites liste des catégories pour obtenir la liste des catégories disponibles. ",176 resume: "Reprenez là où vous vous êtes arrêté ou avant. Dites catégories pour obtenir la liste des catégories. ",177 index: "Dites suivant ou aléatoir pour continuer avec l'exemple suivant. Dites sous-catégorie actuelle pour obtenir la sous-catégorie actuelle. "178 },179 {180 language: "german",181 welcome: "Sagen Sie Lernen und die Sprache. Sagen Sie die Sprachliste, um alle verfügbaren Sprachen verfügbar zu machen. ",182 show_categories: "Sagen Sie anzeigen Kategorien oder Unterkategorien, um eine Liste von Kategorien oder Unterkategorien anzuzeigen. ",183 select_categories: "Sagen Sie zufällig, um das nächste zufällige Beispiel zu geben. Sagen Sie nächste, um das nächste in der Reihenfolge Beispiel zu geben. Sagen Sie Ansichtsunterkategorie um die aktuelle Unterkategorie zu anzeigen. Sagen Sie die nächste Kategorie, um voranzukommen. ",184 example: "Sagen Sie zufällig, um das nächste zufällige Beispiel zu geben. Sagen Sie als nächstes, um als nächstes in der Reihenfolge Beispiel zu geben. Zeigen Sie das aktuelle Beispiel an, indem Sie ein Ansichtsbeispiel sagen ",185 details: "Sagen Sie die Sprache, die Sie anzeigen möchten, und Wort oder Ausdruck. ",186 reset: "Angenommen, Kategorienliste, um eine Liste der verfügbaren Kategorien abrufbar zu machen. ",187 resume: "Fahren Sie dort fort, wo Sie vorher geblieben sind. Angenommen Kategorien, um die Liste abzubekommen. ",188 index: " Sagen Sie als nächstes oder zufällig, um mit dem nächsten Beispiel fortzufahren. Angenommen, aktuelle Unterkategorie, um die aktuelle Unterkategorie abzuerhalten."189 },190 {191 language: "italian",192 welcome: "Di' impara e la lingua. Di' elenco lingue per ottenere tutte le lingue disponibili. ",193 show_categories: "Dì' visualizza categorie o sottocategorie per vedere l'elenco delle categorie o sottocategorie. ",194 select_categories: "Di' casuale per accedere al successivo esempio casuale. Di' casuale per accedere all'esempio successivo in ordine. Vedi l'attuale sottocategoria dicendo vedere sottocategoria. Di' categoria successiva per proseguire. ",195 example: "Di' casuale per accedere all'esempio succesivo. Di' successivo per accedere all'esempio successivo in ordine. Vedi l'attuale esempio dicendo vedere esempio ",196 details: "Di' la lingua che vuoi visualizzare e la parola o frase. ",197 reset: "Di' lista categorie per accedere alla lista delle categorie disponibili. ",198 resume: "Continua da dove hai interrotto. Di' categorie per accedere alla lista.",199 index: "Di' successivo o casuale per continuare con l'esempio successivo. Di' categoria attuale per accedere alla categoria attuale."200 },201 {202 language: "spanish",203 welcome: "Dí, aprender, y, el idioma. Dí, lista de idiomas, para obtener todos los idiomas que hay disponibles. ",204 show_categories: "Di, mostrar temas, o, mostrar topics, para ver la lista completa de temas o topics disponibles. ",205 select_categories: "Di, aleagorio, para obtener el próximo ejemplo aleagorio. Di, próximo, para recibir el siguiente ejempl de la lista según su orden. Dí subcategría actual para ver en que subcagetoría estamos. Dí próxima categorá para cambiar a la próxima categoría. ",206 example: "Dí aleatorio para obtener el próxmo ejemplo aleatorio. Say next to give next in order example. View current example by saying view example. ",207 details: "Dí el nombre del idioma, y luego, palabra, o, frase. ",208 reset: "Dí, lista de temas, para obtener la lista de los temas disponibles. ",209 resume: "Continua desde donde lo dejaste la vez anterior. Dí, temas, para acceder a la lista de temas. ",210 index: "Dí, próximo, o, aleatorio, para continuar con el próximo ejemplo. Dí, topic actual, para obtener el topic en el que estás estudiando. "211 }212 ],213 WARNING_STRINGS:214 [215 {216 language:"english",217 category: "No theme or topic selected before. Please select both first. ",218 example: "No example selected before. Nothing to show. ",219 missing_info: "Missing some selections, can not provide that information. ",220 no_learning_lang: "You haven't selected a learning language. Say, language list, to hear to all available languages.. ",221 different_request: "Why are asking in different language? ",222 same_selection: " Can not be selected for both native and learning language. ",223 native_selection: "Native language changed to ",224 learning_selection: "Learning language change to ",225 native_warn: "Native language is already set to ",226 learning_warn: "Learning language is already set to ",227 reset: "Themes and topics are reset. Select a theme and a topic, and say, start. ",228 given_request: "Request must be given in English but received it in ",229 content_error: "Something wrong with the skill's content information. Please try again. ",230 name_not_found: " doesn't exist in my available list .",231 not_category: "You have to selected a theme first .",232 cancel_stop: "Thank you for using Lexicon, see you around. ",233234 },235 {236 language:"french",237 category: "Aucune catégorie ou sous-catégorie n'a été sélectionnée. Veuillez les sélectionner avant de continuer. ",238 example: "Aucun n'exemple n'a été sélectionné. Rien à montrer. ",239 missing_info: "Il manque certaines sélections. Impossible de fournir l'information. ",240 no_learning_lang: "Aucune langue d'apprentissage sélectionnée. Dites liste des langues pour connaître les options. ",241 different_request: "Pourquoi faites-vous votre demande dans une autre langue? ",242 same_selection: " ne peut être sélectionné comme langue maternelle et langue d'apprentissage. ",243 native_selection: "Langue maternelle modifiée pour ",244 learning_selection: "Langue d'apprentissage modifiée pour ",245 native_warn: " est déjà sélectionné comme langue maternelle",246 learning_warn: " est déjà sélectionné comme langue d'apprentissage",247 reset: "Les catégories et sous-catégories ont été réinitialisées. ",248 given_request: "Les demandes doivent être faites en français. Cette demande est en ",249 content_error: "Il y a un problème avec les informations du contenu de compétence. Veuillez réessayer. ",250 name_not_found: " ne se trouve pas dans ma liste.",251 not_category: "Veuillez d'abord sélectionner une catégorie.",252 cancel_stop: "Merci d'avoir utilisé Lexicon, à bientôt. ",253 },254 {255 language:"german",256 category: "Keine Kategorie oder Unterkategorie zuvor ausgewählt. Bitte wählen Sie beide zuerst aus. ",257 example: "Kein Beispiel zuvor ausgewählt. Nichts zu zeigen. ",258 missing_info: " Wenn einige Auswahlen fehlen, können diese Informationen nicht zur Verfügung stehen.",259 no_learning_lang: "Sie haben keine Lernsprache ausgewählt. Sagen Sie sprachliste, um alle Optionen zu hören. ",260 different_request: "Warum fragen Sie in einer anderen Sprache? ",261 same_selection: "Kann nicht sowohl für muttersprachliche als auch für Lernsprache ausgewählt werden.",262 native_selection: "Muttersprache geändert, um",263 learning_selection: "Sprachwechsel zum Lernen ",264 native_warn: "Die Muttersprache ist bereits auf ",265 learning_warn: "Die Lernsprache ist bereits auf ",266 reset: "Kategorien und Unterkategorien werden zurückgesetzt. ",267 given_request: "Der Antrag muss in Deutsch gestellt werden, erhält sie aber in",268 content_error: "Etwas, das mit den Inhaltsinformationen der Fertigkeit nicht stimmt. Bitte versuchen Sie es erneut. ",269 name_not_found: " Ist in meiner verfügbaren Liste nicht vorhanden.",270 not_category: "Sie müssen eine Kategorie zu aussuchen.",271 cancel_stop: "Vielen Dank, dass Sie Lexicon verwenden. Wir sehen uns.",272 },273 {274 language:"italian",275 category: "Nessuna categoria o sottocategoria è stata selezionata in precedenza. Sei pregato di selezionare entrambe prima di procedere ",276 example: "Nessun esempio selezionato in precedenza. Niente da mostrare. ",277 missing_info: "Mancano alcune sezioni, l'informazione non può essere fornita ",278 no_learning_lang: "Non è stata selezionata una lingua di apprendimento. Di'lista di lingue per ascoltare tutte le opzioni. ",279 different_request: "Perché stai domandando in un'altra lingua? ",280 same_selection: " Non può essere selezionato né per la lingua materna né per la lingua di apprendimento. ",281 native_selection: "Lingua materna cambiata in ",282 learning_selection: "Lingua di apprendimento cambiata in",283 native_warn: "La lingua materna è già stata impostata su",284 learning_warn: "La lingua di apprendimento è già stata impostata su ",285 reset: "Categorie e sottocategorie sono state resettate ",286 given_request: "La richiesta deve essere formulata in italiano ma è stata ricebuta in ",287 content_error: "Qualcosa che non va con la creazione del contenuto. Per favore, riprova. ",288 name_not_found: " Non esiste nella mia lista disponibile .",289 not_category: "Devi prima selezionare una categoria.",290 cancel_stop: "Grazie per aver usato Lexicon, ci vediamo in giro.",291 },292 {293 language:"spanish",294 category: "No hay un tema o topic previamene seleccionado. Por favor, elija ambos primero. ",295 example: "No hay un ejemplo previamente seleccionado. No hay nada que mostrar. ",296 missing_info: "Faltan algunas selecciones, no se puede proporcionar esa información. ",297 no_learning_lang: "No has elegido un idioma para el aprendizaje. Di, lista de idiomas, para escuchar todos los idiomas disponibles. ",298 different_request: "Por que preguntas en un idioma diferente? ",299 same_selection: " No puede ser seleccionado en ambas situaciones, como idioma nativo y de estudio. ",300 native_selection: "El idioma nativo ha sido cambiado a ",301 learning_selection: "El idioma de estudio ha sido cambiado a ",302 native_warn: "El idoma nativo está configurado a ",303 learning_warn: "El idioma de estudio está configurado a ",304 reset: "Los temas y topics han sido reiniciados. Elige un tema y un topic y di, empezar.",305 given_request: "La petición debería haber sido realizada en Español, pero ha sido recibida en ",306 content_error: "Algo salió mal con la información de contenido. Por favor, inténtelo de nuevo. ",307 name_not_found: " no existe en mi lista disponible.",308 not_category: "Tienes que seleccionar una lista primero.",309 cancel_stop: "Gracias por usar Lexicon, nos vemos. ",310 }311 ],312 LANGUAGE_STRINGS:313 [314 {315 language: "english",316 list: "Languages available are English, French, German, Italian, and Spanish. ",317 selection: "Native language is English. and "318 },319 {320 language: "french",321 list: "Les langues disponibles sont anglais, espagnol, italien et allemand. ",322 selection: "La langue maternelle est le français. Et "323 },324 {325 language: "german",326 list: "Verfügbare Sprachen sind Englisch, Spanisch, Italienisch, Französisch und Deutsch.",327 selection: "Muttersprache ist Deutsch. und "328 },329 {330 language: "italian",331 list: "Le lingue disponibili sono Inglese, Spagnolo, Italiano, Francese e Tedesco. ",332 selection: "La lingua materna è l'italiano. e "333 },334 {335 language: "spanish",336 list: "Las lenguas disponibles son: Alemán, Español, Francés, Inglés e Italiano. ",337 selection: "El idioma seleccionado como nativo es Español. Y "338 }339 ],//This must not change..340 LANGUAGE_TRANSLATIONS:341 [342 {343 language:["english","inglés","Englisch","Anglais","inglese"], // Languages of the aplication344 english: "english",345 french: "french",346 german: "german",347 italian: "italian",348 spanish: "spanish",349 },350 {351 language:["french","francés","Französisch","Français","francese"],352 french: "français",353 english: "anglais",354 german: "allemand",355 italian: "italien",356 spanish: "espagnol",357 },358 {359 language:["german","aleman","Deutsche","allemand","tedesca"],360 german: "deutsche",361 english:"englisch",362 french: "französisch",363 italian: "italienisch",364 spanish: "spanisch",365 },366 {367 language:["italian","italiano","Italienisch","italien","italiano"],368 italian: "italiano",369 english:"inglese",370 french: "francese ",371 german: "tedesca",372 spanish: "spagnolo",373 },374 {375 language:["spanish","español","spanisch","espagnol","spagnolo"],376 spanish: "español",377 english: "inglés",378 french: "francés",379 german: "aleman",380 italian: "italiano",381 },382 ],383 } ...

Full Screen

Full Screen

cache-match.js

Source:cache-match.js Github

copy

Full Screen

1if (self.importScripts) {2 importScripts('/resources/testharness.js');3 importScripts('../resources/test-helpers.js');4 importScripts('/common/get-host-info.sub.js');5}6prepopulated_cache_test(simple_entries, function(cache, entries) {7 return cache.match('not-present-in-the-cache')8 .then(function(result) {9 assert_equals(result, undefined,10 'Cache.match failures should resolve with undefined.');11 });12 }, 'Cache.match with no matching entries');13prepopulated_cache_test(simple_entries, function(cache, entries) {14 return cache.match(entries.a.request.url)15 .then(function(result) {16 assert_response_equals(result, entries.a.response,17 'Cache.match should match by URL.');18 });19 }, 'Cache.match with URL');20prepopulated_cache_test(simple_entries, function(cache, entries) {21 return cache.match(entries.a.request)22 .then(function(result) {23 assert_response_equals(result, entries.a.response,24 'Cache.match should match by Request.');25 });26 }, 'Cache.match with Request');27prepopulated_cache_test(simple_entries, function(cache, entries) {28 var alt_response = new Response('', {status: 201});29 return self.caches.open('second_matching_cache')30 .then(function(cache) {31 return cache.put(entries.a.request, alt_response.clone());32 })33 .then(function() {34 return cache.match(entries.a.request);35 })36 .then(function(result) {37 assert_response_equals(38 result, entries.a.response,39 'Cache.match should match the first cache.');40 });41 }, 'Cache.match with multiple cache hits');42prepopulated_cache_test(simple_entries, function(cache, entries) {43 return cache.match(new Request(entries.a.request.url))44 .then(function(result) {45 assert_response_equals(result, entries.a.response,46 'Cache.match should match by Request.');47 });48 }, 'Cache.match with new Request');49prepopulated_cache_test(simple_entries, function(cache, entries) {50 return cache.match(new Request(entries.a.request.url, {method: 'HEAD'}))51 .then(function(result) {52 assert_equals(result, undefined,53 'Cache.match should not match HEAD Request.');54 });55 }, 'Cache.match with HEAD');56prepopulated_cache_test(simple_entries, function(cache, entries) {57 return cache.match(entries.a.request,58 {ignoreSearch: true})59 .then(function(result) {60 assert_response_in_array(61 result,62 [63 entries.a.response,64 entries.a_with_query.response65 ],66 'Cache.match with ignoreSearch should ignore the ' +67 'search parameters of cached request.');68 });69 },70 'Cache.match with ignoreSearch option (request with no search ' +71 'parameters)');72prepopulated_cache_test(simple_entries, function(cache, entries) {73 return cache.match(entries.a_with_query.request,74 {ignoreSearch: true})75 .then(function(result) {76 assert_response_in_array(77 result,78 [79 entries.a.response,80 entries.a_with_query.response81 ],82 'Cache.match with ignoreSearch should ignore the ' +83 'search parameters of request.');84 });85 },86 'Cache.match with ignoreSearch option (request with search parameter)');87cache_test(function(cache) {88 var request = new Request('http://example.com/');89 var head_request = new Request('http://example.com/', {method: 'HEAD'});90 var response = new Response('foo');91 return cache.put(request.clone(), response.clone())92 .then(function() {93 return cache.match(head_request.clone());94 })95 .then(function(result) {96 assert_equals(97 result, undefined,98 'Cache.match should resolve as undefined with a ' +99 'mismatched method.');100 return cache.match(head_request.clone(),101 {ignoreMethod: true});102 })103 .then(function(result) {104 assert_response_equals(105 result, response,106 'Cache.match with ignoreMethod should ignore the ' +107 'method of request.');108 });109 }, 'Cache.match supports ignoreMethod');110cache_test(function(cache) {111 var vary_request = new Request('http://example.com/c',112 {headers: {'Cookies': 'is-for-cookie'}});113 var vary_response = new Response('', {headers: {'Vary': 'Cookies'}});114 var mismatched_vary_request = new Request('http://example.com/c');115 return cache.put(vary_request.clone(), vary_response.clone())116 .then(function() {117 return cache.match(mismatched_vary_request.clone());118 })119 .then(function(result) {120 assert_equals(121 result, undefined,122 'Cache.match should resolve as undefined with a ' +123 'mismatched vary.');124 return cache.match(mismatched_vary_request.clone(),125 {ignoreVary: true});126 })127 .then(function(result) {128 assert_response_equals(129 result, vary_response,130 'Cache.match with ignoreVary should ignore the ' +131 'vary of request.');132 });133 }, 'Cache.match supports ignoreVary');134cache_test(function(cache) {135 let has_cache_name = false;136 const opts = {137 get cacheName() {138 has_cache_name = true;139 return undefined;140 }141 };142 return self.caches.open('foo')143 .then(function() {144 return cache.match('bar', opts);145 })146 .then(function() {147 assert_false(has_cache_name,148 'Cache.match does not support cacheName option ' +149 'which was removed in CacheQueryOptions.');150 });151 }, 'Cache.match does not support cacheName option');152prepopulated_cache_test(simple_entries, function(cache, entries) {153 return cache.match(entries.cat.request.url + '#mouse')154 .then(function(result) {155 assert_response_equals(result, entries.cat.response,156 'Cache.match should ignore URL fragment.');157 });158 }, 'Cache.match with URL containing fragment');159prepopulated_cache_test(simple_entries, function(cache, entries) {160 return cache.match('http')161 .then(function(result) {162 assert_equals(163 result, undefined,164 'Cache.match should treat query as a URL and not ' +165 'just a string fragment.');166 });167 }, 'Cache.match with string fragment "http" as query');168prepopulated_cache_test(vary_entries, function(cache, entries) {169 return cache.match('http://example.com/c')170 .then(function(result) {171 assert_response_in_array(172 result,173 [174 entries.vary_cookie_absent.response175 ],176 'Cache.match should honor "Vary" header.');177 });178 }, 'Cache.match with responses containing "Vary" header');179cache_test(function(cache) {180 var request = new Request('http://example.com');181 var response;182 var request_url = new URL('../resources/simple.txt', location.href).href;183 return fetch(request_url)184 .then(function(fetch_result) {185 response = fetch_result;186 assert_equals(187 response.url, request_url,188 '[https://fetch.spec.whatwg.org/#dom-response-url] ' +189 'Reponse.url should return the URL of the response.');190 return cache.put(request, response.clone());191 })192 .then(function() {193 return cache.match(request.url);194 })195 .then(function(result) {196 assert_response_equals(197 result, response,198 'Cache.match should return a Response object that has the same ' +199 'properties as the stored response.');200 return cache.match(response.url);201 })202 .then(function(result) {203 assert_equals(204 result, undefined,205 'Cache.match should not match cache entry based on response URL.');206 });207 }, 'Cache.match with Request and Response objects with different URLs');208cache_test(function(cache) {209 var request_url = new URL('../resources/simple.txt', location.href).href;210 return fetch(request_url)211 .then(function(fetch_result) {212 return cache.put(new Request(request_url), fetch_result);213 })214 .then(function() {215 return cache.match(request_url);216 })217 .then(function(result) {218 return result.text();219 })220 .then(function(body_text) {221 assert_equals(body_text, 'a simple text file\n',222 'Cache.match should return a Response object with a ' +223 'valid body.');224 })225 .then(function() {226 return cache.match(request_url);227 })228 .then(function(result) {229 return result.text();230 })231 .then(function(body_text) {232 assert_equals(body_text, 'a simple text file\n',233 'Cache.match should return a Response object with a ' +234 'valid body each time it is called.');235 });236 }, 'Cache.match invoked multiple times for the same Request/Response');237cache_test(function(cache) {238 var request_url = new URL('../resources/simple.txt', location.href).href;239 return fetch(request_url)240 .then(function(fetch_result) {241 return cache.put(new Request(request_url), fetch_result);242 })243 .then(function() {244 return cache.match(request_url);245 })246 .then(function(result) {247 return result.blob();248 })249 .then(function(blob) {250 var sliced = blob.slice(2,8);251 return new Promise(function (resolve, reject) {252 var reader = new FileReader();253 reader.onloadend = function(event) {254 resolve(event.target.result);255 };256 reader.readAsText(sliced);257 });258 })259 .then(function(text) {260 assert_equals(text, 'simple',261 'A Response blob returned by Cache.match should be ' +262 'sliceable.' );263 });264 }, 'Cache.match blob should be sliceable');265prepopulated_cache_test(simple_entries, function(cache, entries) {266 var request = new Request(entries.a.request.clone(), {method: 'POST'});267 return cache.match(request)268 .then(function(result) {269 assert_equals(result, undefined,270 'Cache.match should not find a match');271 });272 }, 'Cache.match with POST Request');273prepopulated_cache_test(simple_entries, function(cache, entries) {274 var response = entries.non_2xx_response.response;275 return cache.match(entries.non_2xx_response.request.url)276 .then(function(result) {277 assert_response_equals(278 result, entries.non_2xx_response.response,279 'Cache.match should return a Response object that has the ' +280 'same properties as a stored non-2xx response.');281 });282 }, 'Cache.match with a non-2xx Response');283prepopulated_cache_test(simple_entries, function(cache, entries) {284 var response = entries.error_response.response;285 return cache.match(entries.error_response.request.url)286 .then(function(result) {287 assert_response_equals(288 result, entries.error_response.response,289 'Cache.match should return a Response object that has the ' +290 'same properties as a stored network error response.');291 });292 }, 'Cache.match with a network error Response');293cache_test(function(cache) {294 // This test validates that we can get a Response from the Cache API,295 // clone it, and read just one side of the clone. This was previously296 // bugged in FF for Responses with large bodies.297 var data = [];298 data.length = 80 * 1024;299 data.fill('F');300 var response;301 return cache.put('/', new Response(data.toString()))302 .then(function(result) {303 return cache.match('/');304 })305 .then(function(r) {306 // Make sure the original response is not GC'd.307 response = r;308 // Return only the clone. We purposefully test that the other309 // half of the clone does not need to be read here.310 return response.clone().text();311 })312 .then(function(text) {313 assert_equals(text, data.toString(), 'cloned body text can be read correctly');314 });315 }, 'Cache produces large Responses that can be cloned and read correctly.');316cache_test(async (cache) => {317 const url = get_host_info().HTTPS_REMOTE_ORIGIN +318 '/service-workers/cache-storage/resources/simple.txt?pipe=' +319 'header(access-control-allow-origin,*)|' +320 'header(access-control-expose-headers,*)|' +321 'header(foo,bar)|' +322 'header(set-cookie,X)';323 const response = await fetch(url);324 await cache.put(new Request(url), response);325 const cached_response = await cache.match(url);326 const headers = cached_response.headers;327 assert_equals(headers.get('access-control-expose-headers'), '*');328 assert_equals(headers.get('foo'), 'bar');329 assert_equals(headers.get('set-cookie'), null);330 }, 'cors-exposed header should be stored correctly.');331cache_test(async (cache) => {332 // A URL that should load a resource with a known mime type.333 const url = '/service-workers/cache-storage/resources/blank.html';334 const expected_mime_type = 'text/html';335 // Verify we get the expected mime type from the network. Note,336 // we cannot use an exact match here since some browsers append337 // character encoding information to the blob.type value.338 const net_response = await fetch(url);339 const net_mime_type = (await net_response.blob()).type;340 assert_true(net_mime_type.includes(expected_mime_type),341 'network response should include the expected mime type');342 // Verify we get the exact same mime type when reading the same343 // URL resource back out of the cache.344 await cache.add(url);345 const cache_response = await cache.match(url);346 const cache_mime_type = (await cache_response.blob()).type;347 assert_equals(cache_mime_type, net_mime_type,348 'network and cache response mime types should match');349 }, 'MIME type should be set from content-header correctly.');350cache_test(async (cache) => {351 const url = '/dummy';352 const original_type = 'text/html';353 const override_type = 'text/plain';354 const init_with_headers = {355 headers: {356 'content-type': original_type357 }358 }359 // Verify constructing a synthetic response with a content-type header360 // gets the correct mime type.361 const response = new Response('hello world', init_with_headers);362 const original_response_type = (await response.blob()).type;363 assert_true(original_response_type.includes(original_type),364 'original response should include the expected mime type');365 // Verify overwriting the content-type header changes the mime type.366 const overwritten_response = new Response('hello world', init_with_headers);367 overwritten_response.headers.set('content-type', override_type);368 const overwritten_response_type = (await overwritten_response.blob()).type;369 assert_equals(overwritten_response_type, override_type,370 'mime type can be overridden');371 // Verify the Response read from Cache uses the original mime type372 // computed when it was first constructed.373 const tmp = new Response('hello world', init_with_headers);374 tmp.headers.set('content-type', override_type);375 await cache.put(url, tmp);376 const cache_response = await cache.match(url);377 const cache_mime_type = (await cache_response.blob()).type;378 assert_equals(cache_mime_type, override_type,379 'overwritten and cached response mime types should match');380 }, 'MIME type should reflect Content-Type headers of response.');381cache_test(async (cache) => {382 const url = new URL('../resources/vary.py?vary=foo',383 get_host_info().HTTPS_REMOTE_ORIGIN + self.location.pathname);384 const original_request = new Request(url, { mode: 'no-cors',385 headers: { 'foo': 'bar' } });386 const fetch_response = await fetch(original_request);387 assert_equals(fetch_response.type, 'opaque');388 await cache.put(original_request, fetch_response);389 const match_response_1 = await cache.match(original_request);390 assert_not_equals(match_response_1, undefined);391 // Verify that cache.match() finds the entry even if queried with a varied392 // header that does not match the cache key. Vary headers should be ignored393 // for opaque responses.394 const different_request = new Request(url, { headers: { 'foo': 'CHANGED' } });395 const match_response_2 = await cache.match(different_request);396 assert_not_equals(match_response_2, undefined);397}, 'Cache.match ignores vary headers on opaque response.');...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org');3var options = {4};5 if (err) {6 console.log(err);7 } else {8 console.log('Test ID: ' + data.data.testId);9 }10});11var wpt = require('webpagetest');12var test = new wpt('www.webpagetest.org');13var options = {14};15 if (err) {16 console.log(err);17 } else {18 console.log('Test ID: ' + data.data.testId);19 }20});21var wpt = require('webpagetest');22var test = new wpt('www.webpagetest.org');23test.getTestStatus('160808_8B_2P', function(err, data) {24 if (err) {25 console.log(err);26 } else {27 console.log(data);28 }29});30var wpt = require('webpagetest');31var test = new wpt('www.webpagetest.org');32test.getTestResults('160808_8B_2P', function(err, data) {33 if (err) {34 console.log(err);35 } else {36 console.log(data);37 }38});39var wpt = require('webpagetest');40var test = new wpt('www.webpagetest.org');41test.getLocations(function(err, data) {42 if (err)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var request = {3 params: {4 }5};6wpt.different_request(request, function(err, data) {7 if (err) {8 console.log(err);9 } else {10 console.log(data);11 }12});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.3d0e1c7f3e3a2f7c1d2a6a7a8b8c9d0');3var params = {4};5wpt.runTest(url, params, function(err, data) {6 if (err) return console.log(err);7 console.log('Test submitted to WebPagetest for %s', url);8 console.log('View your test at: %s', data.data.userUrl);9 console.log('Test ID: %s', data.data.testId);10 console.log('Poll results every %s seconds', params.pollResults);11 console.log('Press CTRL+C to abort.');12 wpt.getTestResults(data.data.testId, function(err, data) {13 if (err) return console.log(err);14 console.log('Test completed for %s', url);15 console.log('View your test at: %s', data.data.userUrl);16 console.log('Test ID: %s', data.data.testId);17 console.log('First View (fvonly): %s', data.data.average.firstView.loadTime);18 console.log('Repeat View: %s', data.data.average.repeatView.loadTime);19 });20});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful