public static async Task Init(APLSkillRequest input, ILambdaContext context) { new UserEventRequestHandler().AddToRequestConverter(); //new SystemExceptionEncounteredRequestTypeConverter().AddToRequestConverter(); // initialize logger Logger = new Logger(context.Logger); Logger.Write("Core.Init()", $"{SkillSetting.SkillName} started"); // get user id string userId = input.Session != null ? input.Session.User.UserId : input.Context.System.User.UserId; // initialize components Request = new Request(input); Response = new Response(); Device = new Device(input); Context = new Context(context); // initialize database context Database = new Database(userId); await Database.VerifyTable(); State = await Database.GetState(); Logger.Write("Core.Init()", "Sonnar Core library initialization completed"); }
public static async Task <SkillResponse> SingleEventResponse(APLSkillRequest request, LocalEventTime eventToRecognise, LocalDate currentDate, Group groupData, string intro) { var response = SpeechHelper.RespondToEvent(eventToRecognise, currentDate, intro); if (request.Context.System.Device.IsInterfaceSupported(Consts.APLInterface)) { var dateDisplay = $"{eventToRecognise.Date.ToDateTimeUnspecified():MMMM dd yyyy}, {eventToRecognise.Event.LocalTime}"; var dataSource = new KeyValueDataSource { Properties = new Dictionary <string, object> { { "backgroundUrl", groupData.KeyPhoto?.HighRes ?? groupData.GroupPhoto?.HighRes }, { "groupName", groupData.Name }, { "eventDate", dateDisplay }, { "eventTitle", eventToRecognise.Event.Name } } }; var filename = request.APLInterfaceDetails().Runtime.MaxVersion == APLDocumentVersion.V1 ? "assets/NextEvent.json" : "assets/NextEvent2.json"; var document = await S3Helper.GetDocument(System.Environment.GetEnvironmentVariable("bucket"), filename); document.AddResponsiveDesign(); response.Response.Directives.Add(new RenderDocumentDirective { DataSources = new Dictionary <string, APLDataSource> { { "eventData", dataSource } }, Document = document, Token = eventToRecognise.Event.Id }); } return(response); }
public static void Set(string key, object val) { APLSkillRequest request = Input.GetRequest(); if (request.Session == null) { request.Session = new Session(); } if (request.Session.Attributes == null) { request.Session.Attributes = new Dictionary <string, object>(); } string jsonString = JsonConvert.SerializeObject(val); if (Contains(key)) { request.Session.Attributes[key] = jsonString; } else { request.Session.Attributes.Add(key, jsonString); } Logger.Write($"Session attribute key: [{key}] & value: [{JsonConvert.SerializeObject(val)}] added"); }
private string GetUserId(APLSkillRequest request) { Session session = request.Session; APLContext skillContext = request.Context; return(session != null ? session.User.UserId : skillContext.System.User.UserId); }
private void SetComponents(APLSkillRequest request, string userId) { Input = new Input(request); Echo = new Echo(); Response = new Response(); Database = new Database(userId); RequestManager = new RequestManager(); }
public Device(APLSkillRequest input) { Input = input; SetDeviceHeight(); Core.Logger.Write("Device.Device()", $"Display availability: {HasScreen}"); Core.Logger.Write("Device.Device()", $"Display Height: {DisplayHelper.BaseDeviceHeight}"); Core.Logger.Write("Device.Device()", $"Display is round: {IsRound}"); }
public SkillResponse FunctionHandler(APLSkillRequest input, ILambdaContext context) { var response = ResponseBuilder.Tell("Here's your transition"); response.Response.Directives.Add(new RenderDocumentDirective { Document = GetDocument() }); return(response); }
public static T Get <T>(string key) { APLSkillRequest request = Input.GetRequest(); if (Contains(key)) { T output = JsonConvert.DeserializeObject <T>(request.Session.Attributes[key].ToString()); return(output); } throw new NullReferenceException($"Error: The given key [{key}] does not exist in the current session"); }
public static void Clear() { APLSkillRequest request = Input.GetRequest(); if (request.Session == null) { request.Session = new Session(); } request.Session.Attributes = new Dictionary <string, object>(); Logger.Write("Session attributes all cleared"); }
public static void Remove(params string[] keys) { foreach (string key in keys) { if (Contains(key)) { APLSkillRequest request = Input.GetRequest(); request.Session.Attributes.Remove(key); Logger.Write($"Session attribute key: [{key}] removed"); } } }
public Request(APLSkillRequest request) { Skill = new APLSkillRequest(); Skill = request; SetRequestTypes(); if (request.Request.GetType() == typeof(IntentRequest)) { SetIntentTypes(); } Core.Logger.Write("Request.Request()", $"Request details: {JsonConvert.SerializeObject(request)}"); }
public async Task Init(APLSkillRequest request, ILambdaContext context) { AddRequestConverters(); Logger = new Logger(context.Logger); Logger.Write($"**************** [{SkillMetadata.Name}] started ****************"); Logger.Write($"System locale: [{request.Request.Locale}]"); Logger.Write($"Request detail: {JsonConvert.SerializeObject(request)}"); string userId = GetUserId(request); SetComponents(request, userId); await SetState(); }
public async Task <SkillResponse> FunctionHandler(APLSkillRequest request, ILambdaContext context) { Core core = new Core(); await core.Init(request, context); await InvokeHandler(core); await Database.SaveState(); SkillResponse response = Response.GetResponse(); Logger.Write($"Response detail: {JsonConvert.SerializeObject(response)}"); Logger.Write($"Latest user state detail: {JsonConvert.SerializeObject(State)}"); Logger.Write($"**************** [{SkillMetadata.Name}] processing ended ****************"); return(response); }
/// <summary> /// Handles a signed request from Alexa. This endpoint validates the certificates coming from amazon and the skill id sent. /// </summary> /// <exception cref="Voicify.Sdk.Assistant.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="applicationId"> (optional)</param> /// <param name="applicationSecret"> (optional)</param> /// <param name="request"> (optional)</param> /// <returns>SkillResponse</returns> public SkillResponse HandleSignedRequest(string applicationId = null, string applicationSecret = null, APLSkillRequest request = null) { ApiResponse <SkillResponse> localVarResponse = HandleSignedRequestWithHttpInfo(applicationId, applicationSecret, request); return(localVarResponse.Data); }
public Task <SkillResponse> FunctionHandler(APLSkillRequest input, ILambdaContext _) { return(_pipeline.Process(input)); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task <SkillResponse> FunctionHandler(APLSkillRequest input, ILambdaContext context) { var response = await Pipeline.Process(input, context); return(response); }
/// <summary> /// Handles a signed request from Alexa. This endpoint validates the certificates coming from amazon and the skill id sent. /// </summary> /// <exception cref="Voicify.Sdk.Assistant.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="applicationId"> (optional)</param> /// <param name="applicationSecret"> (optional)</param> /// <param name="request"> (optional)</param> /// <returns>Task of ApiResponse (SkillResponse)</returns> public async System.Threading.Tasks.Task <ApiResponse <SkillResponse> > HandleSignedRequestAsyncWithHttpInfo(string applicationId = null, string applicationSecret = null, APLSkillRequest request = null) { var localVarPath = "/api/Alexa/HandleSignedRequest"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "text/plain", "application/json", "text/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (applicationId != null) { localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "applicationId", applicationId)); // query parameter } if (applicationSecret != null) { localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "applicationSecret", applicationSecret)); // query parameter } if (request != null && request.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(request); // http body (model) parameter } else { localVarPostBody = request; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = this.Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("HandleSignedRequest", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <SkillResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (SkillResponse)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(SkillResponse)))); }
public Input(APLSkillRequest request) { this.request = request; intentRequest = request.Request as IntentRequest; }
public SkillResponse FunctionHandler(JObject inputObj, ILambdaContext context) { Log.logger = context.Logger; APLSkillRequest input = new APLSkillRequest(); SkillResponse respond = ResponseBuilders.BuildResponse(null, false, null, null, null); try { new SystemRequestTypeConverter().AddToRequestConverter(); new UserEventRequestHandler().AddToRequestConverter(); //new APLRequestTypeConverter().AddToRequestConverter(); //Getting input string inputString = JsonConvert.SerializeObject(inputObj); input = JsonConvert.DeserializeObject <APLSkillRequest>(inputString); //Logging input Log.Output("---INPUT---"); context.Logger.LogLine(JsonConvert.SerializeObject(input)); // Initialise data var requestType = input.GetRequestType(); // Get type of request bool VideoSupport = input.Context.System.Device.IsInterfaceSupported("VideoApp"); bool APLSupport = input.Context.System.Device.IsInterfaceSupported("Alexa.Presentation.APL"); Log.Output("Video Support - APL - is: " + APLSupport); // ***REQUESTS*** // if (input.Request is LaunchRequest && APLSupport) // Launch Request for Video { // Launch request for echo spot/show -> Return APL + Ask Log.Output("Video App Launch Request"); respond = Dependencies.CreateAPL(); } else if (input.Request is LaunchRequest && !APLSupport) // Launch Request for speakers { Log.Output("Launch Request for smart speaker"); Reprompt reprompt = new Reprompt("How can I help you today?"); respond = ResponseBuilder.Ask("Welcome to ASMR video. Please ask for the list of songs or ask me to play a song", reprompt); } else if (input.Request is SessionEndedRequest) // SessionEndedRequest { // End Session by playing message Log.Output("Session Ended Request Called"); respond = ResponseBuilder.Tell("Thank you for using this skill. Goodbye."); respond.Response.ShouldEndSession = true; } else if (input.Request is UserEventRequest usrEvent && APLSupport) // User Event Request for TouchWrappers { Log.Output("User Event Launch requst"); var Id = Convert.ToInt32(usrEvent.Source.ComponentId); // Take ID as integer Id = Id - 1; Log.Output("ID of touchwrapper is : " + (Id + 1) + " , Index of number is: " + Id); respond = Dependencies.BuildVideoResonse(videoUrls[Id]); context.Logger.LogLine(JsonConvert.SerializeObject(respond)); } else if (input.Request is PlaybackControllerRequest) // Playback controller request { Log.Output("Playback Controller Request Called"); var playbackReq = input.Request as PlaybackControllerRequest; switch (playbackReq.PlaybackRequestType) { case PlaybackControllerRequestType.Next: break; case PlaybackControllerRequestType.Pause: break; case PlaybackControllerRequestType.Play: break; case PlaybackControllerRequestType.Previous: break; } respond = ResponseBuilder.AudioPlayerStop(); } // ***INTENTS*** else if (requestType == typeof(IntentRequest)) // INTENTS { var intentRequest = input.Request as IntentRequest; // Get intent request var intentName = intentRequest.Intent.Name; Log.Output("Intent Requests"); //Check request switch (intentName) { // Play Song Intent case "PlaySongIntent": Log.Output("Play a song Intent"); var songSlot = intentRequest.Intent.Slots["songName"].Value; // get slot //int songNumIndex= Dependencies.SlotConverter(songSlot); int songNumIndex = Convert.ToInt32(songSlot); songNumIndex -= 1; Log.Output("Song Slot is: " + songSlot + " , song Number index is : " + songNumIndex); if (songNumIndex != -1) // -1 = NOT FOUND { var audioRes = ResponseBuilders.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, audioUrls[songNumIndex], names[songNumIndex], null, 0); respond = audioRes; respond.Response.OutputSpeech = new PlainTextOutputSpeech { Text = "Playing the song." }; } else //Found { respond.Response.OutputSpeech = new PlainTextOutputSpeech { Text = "I did not understand which song you asked me to pplay. Could you please repeat?" }; } break; // ListSongsIntent case "ListSongsIntent": Log.Output("List Song Intent Request Called"); string text = "The ASMR songs are: "; for (int i = 0; i < names.Length; i++) { string ch = " , "; if (i == (names.Length - 1)) { ch = "."; } text += ((i + 1) + ". " + names[i] + ch); } text += " Which song do you want me to play? Say \"Alexa, play song 1 \"."; Reprompt reprompt = new Reprompt("Which song should I play?"); respond = ResponseBuilder.Ask(text, reprompt); break; // Help Intent case "AMAZON.HelpIntent": Log.Output("Help Intent Request Called"); respond = ResponseBuilder.Tell("You can ask me 'What is ASMR' or ask me to play one of ASMR Darling's top ten videos or ask for a list of ASMR's top ten videos"); break; //AMAZON StopIntent case "AMAZON.StopIntent": Log.Output("Stop Intent Request Called"); if (APLSupport) { // Stop when Video Present respond = Dependencies.CreateAPL(); } else { // Stop when Audio Present Reprompt re = new Reprompt("How can I help you today?"); respond = ResponseBuilder.Ask("Welcome to ASMR video. Please ask for the list of songs or ask me to play a song", re); respond.Response.Directives.Add(new StopDirective()); } break; case "AMAZON.CancelIntent": if (APLSupport) { Log.Output("---CancelIntent with video Support---"); respond = Dependencies.CreateAPL();; } else { Log.Output("Cancel Intent Request(Audio Player) Called"); Reprompt re = new Reprompt("How can I help you today?"); respond = ResponseBuilder.Ask("Welcome to ASMR video. Please ask for the list of songs or ask me to play a song", re); respond.Response.Directives.Add(new StopDirective()); } break; case "AMAZON.PauseIntent": Log.Output("Pause Intent Request Called"); respond = ResponseBuilder.AudioPlayerStop(); break; case "WhatIsASMRIntent": // What is ASMR? if (APLSupport) { Log.Output("What is ASMR Intent - VideoApp played"); respond = Dependencies.BuildVideoResonse(whatIsASMRvideo); // Return response to play Video } else { Log.Output("What is ASMR- Audio played"); respond = ResponseBuilders.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, whatIsASMRaudio, "What is ASMR?", null, 0);; } break; case "PlayVideoIntent": Log.Output("Play a Video Intent - \"Alexa play video\""); var videoSlot = intentRequest.Intent.Slots["songName"].Value; // get slot int videoNumIndex = Dependencies.SlotConverter(videoSlot); respond = Dependencies.BuildVideoResonse(videoUrls[videoNumIndex]); context.Logger.LogLine(JsonConvert.SerializeObject(respond)); break; default: Log.Output("Did not understand the intent request / Unexpected intent request"); respond = ResponseBuilder.Tell("I dont understand. Please ask me to list all songs or you can ask for help"); break; } } else { Log.Output("Unknown Request or Intent."); Log.Output(JsonConvert.SerializeObject(input)); respond = ResponseBuilder.Tell("I dont understand. Please ask me to list all songs or ask for help"); } return(respond); }
public async Task <SkillResponse> FunctionHandler(APLSkillRequest input, ILambdaContext context) { // core initialization await Core.Init(input, context); // direct request in a matching handler switch (Core.Request.GetMainRequestType()) { // handle launch reqeust case AlexaRequestType.LaunchRequest: LaunchRequestHandler launchRequestHandler = new LaunchRequestHandler(); await launchRequestHandler.HandleRequest(); break; // handle intent request case AlexaRequestType.IntentRequest: IntentReqeustHandler intentRequestHandler = new IntentReqeustHandler(); await intentRequestHandler.HandleRequest(); break; // handle audio player request case AlexaRequestType.AudioPlayerRequest: AudioPlayerRequestHandler audioPlayerRequestHandler = new AudioPlayerRequestHandler(); await audioPlayerRequestHandler.HandleRequest(); break; // handle gui event request case AlexaRequestType.AlexaRequest: AlexaRequestHandler alexaRequestHandler = new AlexaRequestHandler(); await alexaRequestHandler.HandleRequest(); break; // handle session eneded request case AlexaRequestType.SessionEndedRequest: SessionEndedRequestHandler sessionEndedRequestHandler = new SessionEndedRequestHandler(); await sessionEndedRequestHandler.HandleRequest(); break; // handle system exception request case AlexaRequestType.SystemRequest: SystemRequestHandler systemRequestHandler = new SystemRequestHandler(); await systemRequestHandler.HandleRequest(); break; // handle unknown request default: bool endSession = Core.State.UserState.NumReprompt > 5 ? true : false; Core.Logger.Write("Function.FunctionHandler()", "Request was not recognized, directing into the default case handler"); Core.Response.SetSpeech(false, endSession, SpeechTemplate.NoUnderstand); Core.State.UserState.Stage = Stage.Menu; Core.State.UserState.NumReprompt++; if (endSession) { Core.State.UserState.NumReprompt = 0; } break; } // log returning message details Core.Logger.Write("Function.FunctionHandler()", $"Response details: {JsonConvert.SerializeObject(Core.Response.GetResponse())}"); Core.Logger.Write("Function.FunctionHandler()", $"User state details: {JsonConvert.SerializeObject(Core.State)}"); // save database context then return await Core.Database.SaveState(); return(Core.Response.GetResponse()); }
/// <summary> /// Handles a signed request from Alexa. This endpoint validates the certificates coming from amazon and the skill id sent. /// </summary> /// <exception cref="Voicify.Sdk.Assistant.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="applicationId"> (optional)</param> /// <param name="applicationSecret"> (optional)</param> /// <param name="request"> (optional)</param> /// <returns>Task of SkillResponse</returns> public async System.Threading.Tasks.Task <SkillResponse> HandleSignedRequestAsync(string applicationId = null, string applicationSecret = null, APLSkillRequest request = null) { ApiResponse <SkillResponse> localVarResponse = await HandleSignedRequestAsyncWithHttpInfo(applicationId, applicationSecret, request); return(localVarResponse.Data); }