void Server_Request(object sender, OnHttpRequestArgs args) { if (args.Request.Header.RequestType == "OPTIONS") { Debug.Console(2, "Asking for OPTIONS"); args.Response.Header.SetHeaderValue("Access-Control-Allow-Origin", "*"); args.Response.Header.SetHeaderValue("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS"); return; } string path = Uri.UnescapeDataString(args.Request.Path); var host = args.Request.DataConnection.RemoteEndPointAddress; //string authToken; Debug.Console(2, "HTTP Request: {2}: Path='{0}' ?'{1}'", path, args.Request.QueryString, host); // ----------------------------------- ADD AUTH HERE if (path.StartsWith("/cisco/api")) { var handler = ApiRequest; if (ApiRequest != null) { ApiRequest(this, args); } } }
internal void HandleError(OnHttpRequestArgs args, int code, string title, string message) { //#if DEBUG CloudLog.Warn("Webserver Error {0}, {1}, Path: {2}\r\n{3}", code, title, args.Request.Path, message); //#endif try { var errorTemplate = new TemplateEngine(Assembly.GetExecutingAssembly(), "WebApp.Templates.error.html", "Error" + code, false); errorTemplate.Context.Add("error_code", code.ToString()); errorTemplate.Context.Add("error_title", title); errorTemplate.Context.Add("error_message", message); errorTemplate.Context["page_style_link"] = @"<link href=""/static/lib2/css/error.css"" rel=""stylesheet"">"; args.Response.Code = code; args.Response.ResponseText = title; args.Response.Header.ContentType = "text/html"; args.Response.ContentSource = ContentSource.ContentString; args.Response.ContentString = errorTemplate.Render(); } catch (Exception e) { CloudLog.Exception(e); } try { //args.Response.FinalizeHeader(); } catch (Exception e) { CloudLog.Exception(e); } }
/// <summary> /// /// </summary> void Server_OnHttpRequest(object sender, OnHttpRequestArgs args) { var path = args.Request.Path; Debug.Console(2, "HTTP Request with path: '{0}'", args.Request.Path); if (File.Exists(FileDirectory + path)) { string filePath = path.Replace('/', '\\'); string localPath = string.Format(@"{0}{1}", FileDirectory, filePath); Debug.Console(2, "HTTP Logo Server attempting to find file: '{0}'", localPath); if (File.Exists(localPath)) { args.Response.Header.ContentType = GetContentType(new FileInfo(localPath).Extension); args.Response.ContentStream = new FileStream(localPath, FileMode.Open, FileAccess.Read); } else { Debug.Console(2, "HTTP Logo Server Cannot find file '{0}'", localPath); args.Response.ContentString = string.Format("Not found: '{0}'", filePath); args.Response.Code = 404; } } else { Debug.Console(2, "HTTP Logo Server: '{0}' does not exist", FileDirectory + path); } }
void OnReceivedData(object sender, OnHttpRequestArgs args) { Thread pThread = new Thread(ProcessData, args, Thread.eThreadStartOptions.CreateSuspended); pThread.Priority = Thread.eThreadPriority.UberPriority; pThread.Start(); }
internal Request(WebScriptingServer server, OnHttpRequestArgs context, Dictionary <string, string> pathArguments) { _time = DateTime.Now; _server = server; _context = context; //UserHostName = Dns.GetHostEntry(UserIpAddress).HostName; PathArguments = new ReadOnlyDictionary <string, string>(pathArguments); foreach (var match in from HttpHeader header in Header where header.Name == "Cookie" select Regex.Match(header.Value, @"sessionid=(\w+)") into match where match.Success select match) { _session = SessionManager.GetSession(match.Groups[1].Value); if (_session != null) { var header = _session.Validate(); if (header != null) { User = _session.User; Response.Header.AddHeader(header); } } break; } }
void ServerHttpRequestHandler(object sender, OnHttpRequestArgs e) { Trace("ServerHttpRequestHandler() received request. Path: " + e.Request.Path); SimplSharpString answer = RequestCallbackNotify(e.Request.Path); CrestronConsole.PrintLine("ANSWER: " + answer.ToString()); e.Response.ContentString = answer.ToString(); }
public void HTTPRequestEventHandler(Object sender, OnHttpRequestArgs requestArgs) { try { switch (requestArgs.Request.Header.RequestPath) { case "/alexa/": Object response = null; String message = "not handled"; try { response = HandleRequest( requestArgs.Request.Header.RequestType, requestArgs.Request.ContentString ); } catch (Exception e) { message = e.ToString(); } if (response == null) { response = new Response() { Header = new Header() { Namespace = "Alexa.ConnectedHome.Control", Name = DirectiveName.UnsupportedOperationError, PayloadVersion = "2", MessageID = Guid.NewGuid(), }, Payload = new Dictionary <string, string> { { "error", message } }, }; } requestArgs.Response.ContentString = JsonConvert.SerializeObject(response); return; default: break; } requestArgs.Response.Code = 404; requestArgs.Response.ResponseText = "File Not Found"; requestArgs.Response.ContentString = "File Not Found"; } catch (Exception e) { requestArgs.Response.Code = 500; requestArgs.Response.ResponseText = "Server Error"; requestArgs.Response.ContentString = e.ToString(); } }
void HookServer_OnHttpRequest(object sender, OnHttpRequestArgs e) { if (e.Request.Header.RequestType == "POST") { //Match valid JSON data in HTTP response Match JsonMatch = Regex.Match(e.Request.ContentString, RegexString); //Instantiate new PlexEventArgs PlexPayload = new PlexEventArgs(); //Parse JSON data and populate PlexPayload ParseJson(JsonMatch.ToString()); //Trigger PlexEvent OnPlexMediaEvent(PlexPayload); } }
void server_OnHttpRequest(object sender, OnHttpRequestArgs e) { if (!e.Request.HasContentLength) { printDebugLine("http request received from " + e.Request.DataConnection.RemoteEndPointAddress + " without content. (so I have no idea what to do with this!)"); return; } if (e.Request.Path.ToLower() != "/signalprocessor.html") { printDebugLine("http request received from " + e.Request.DataConnection.RemoteEndPointAddress + " for page " + e.Request.Path.ToLower() + " but I only have signalprocessor.html implemented"); return; } CrestronConsole.PrintLine("Incoming HTTP request from {0} requesting {1} with content: {2}", e.Request.DataConnection.RemoteEndPointAddress, e.Request.Path.ToUpper(), e.Request.ContentString); e.Response.KeepAlive = false; // Get all the variables from the request. (var=value&var2=value2) ContentVariables vars = new ContentVariables(e.Request.ContentString); if (vars.variableExists("digitaljoin") && vars.variableExists("digitalaction")) { if (digitalToPlus != null) { digitalToPlus(Convert.ToUInt16(vars.getVariable("digitaljoin")), vars.getVariable("digitalaction")); } else { printDebugLine("Delegate digitaljoin not set!"); } } if (vars.variableExists("stringjoin") && vars.variableExists("text")) { if (stringToPlus != null) { stringToPlus(Convert.ToUInt16(vars.getVariable("stringjoin")), vars.getVariable("text")); } else { printDebugLine("Delegate digitaljoin not set!"); } } }
/// <summary> /// Handles data received from IFTTT. Passes to the correct module, or provides the data back to Simpl+ if no matching modules exist. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnServerRequest(object sender, OnHttpRequestArgs args) { CrestronConsole.PrintLine("IFTTT: Received incoming message."); CrestronConsole.PrintLine(args.Request.ContentString); try { var eventData = EventData.Parse(args.Request.ContentString.Split(Separator.ToCharArray())); var mods = modules.Where((m) => m.IsEnabled && m.EventName == eventData.Name); if (mods != null && mods.Count() > 0) { foreach (var m in mods) { if (m != null) { m.ProcessEventData(eventData); } } } else { CrestronConsole.PrintLine("IFTTT: Trying to process generic event."); if (ProcessGenericEvent != null) { ProcessGenericEvent(eventData.Name, eventData.Data1, eventData.Data2, eventData.Data3, eventData.Data4, eventData.Data5, eventData.Data6, eventData.Data7, eventData.Data8, eventData.Data9, eventData.Data10); } if (GenericEventReceived != null) { GenericEventReceived(this, new EventDataReceivedEventArgs(eventData)); } } eventData = null; } catch (Exception ex) { CrestronConsole.PrintLine("IFTTT: Error occured while processing event from IFTTT."); CrestronConsole.PrintLine("Message: " + ex.Message); } }
public void HTTPRequestEventHandler(Object sender, OnHttpRequestArgs requestArgs) //requestArgs { //int bytesSent = 0; string QueryString = requestArgs.Request.Header.RequestPath; string DeviceID = ""; string DeviceValue = ""; string AuthCode = ""; string[] words; //ErrorLog.Notice(requestArgs.Request.Header.RequestType.ToString()); //IP/DeviceID/Value if (requestArgs.Request.Header.RequestType.ToString() == "GET") { //ErrorLog.Notice("QueryString = {0}\n", QueryString); if (QueryString.Contains("code")) //Need to Save this Code for Authorization Sequence { words = QueryString.Split('='); SmartThingsReceiver.AuthCode = words[1]; ErrorLog.Notice("SmartThingsReceiver Authorization Code Received {0}. Authorization will now Continue\n", AuthCode); requestArgs.Response.ContentString = "You May Now Close Your Browser, The Processor Will Finish The Authorization Sequence...Monitor Console For Status\n"; AuthenticateStep2(); //Continue Authentication Procedure } else { words = QueryString.Split('/'); DeviceID = words[1]; DeviceValue = words[2]; if (DeviceID != "" && DeviceValue != "") { SignalChangeEvents.SerialValueChange(DeviceID, DeviceValue); requestArgs.Response.ContentString = "OK"; } else { requestArgs.Response.ContentString = "Invalid Request"; } } } }
object ProcessData(object a) { OnHttpRequestArgs args = (OnHttpRequestArgs)a; try { args.Response.KeepAlive = true; #if DEBUG CrestronConsole.PrintLine("\r\n>>> CODEC EVENT to {0} from {1}", server.ServerName, args.Connection.RemoteEndPointAddress); #endif if (args.Request.Header.RequestType == "POST") { XDocument xml = XDocument.Load(new XmlReader(args.Request.ContentString)); XElement identification; string productID; if (xml.Root.HasAttributes) { XNamespace ns = xml.Root.Attribute("xmlns").Value; identification = xml.Root.Element(ns + "Identification"); productID = identification.Element(ns + "ProductID").Value; } else { identification = xml.Root.Element("Identification"); productID = identification.Element("ProductID").Value; } identification.Remove(); XElement element = xml.Root; #if DEBUG //CrestronConsole.PrintLine(element.ToString()); #endif if (Codec.LoggingEnabled) { Codec.Logger.Log("New Post from {0} at {1}{2}{3}", productID, args.Connection.RemoteEndPointAddress, CrestronEnvironment.NewLine, element.ToString()); } if (element.XName.LocalName == "Event" && element.HasElements) { foreach (XElement eventElement in element.Elements()) { switch (eventElement.XName.LocalName) { case "IncomingCallIndication": CodecIncomingCallEventArgs incomingCallArgs = new CodecIncomingCallEventArgs(); foreach (XElement e in eventElement.Elements()) { switch (e.XName.LocalName) { case "RemoteURI": incomingCallArgs.RemoteURI = e.Value; break; case "DisplayNameValue": incomingCallArgs.DisplayNameValue = e.Value; break; case "CallId": incomingCallArgs.Call = Codec.Calls.GetOrInsert(int.Parse(e.Value)); break; } } try { foreach (XElement e in this.Codec.RequestPath("Configuration/Conference/AutoAnswer").Elements()) { switch (e.XName.LocalName) { case "Delay": incomingCallArgs.AutoAnswerDelay = int.Parse(e.Value); break; case "Mode": incomingCallArgs.AutoAnswerMode = (e.Value == "On"); break; case "Mute": incomingCallArgs.AutoAnswerMute = (e.Value == "On"); break; } } } catch { ErrorLog.Error("Error getting auto answer config in Incoming Call event notification handler"); } try { if (IncomingCallEvent != null) { IncomingCallEvent(Codec, incomingCallArgs); } } catch (Exception e) { ErrorLog.Exception("Error calling IncomingCallEvent in codec", e); } break; case "UserInterface": try { foreach (XElement widget in eventElement.Element("Extensions").Elements("Widget")) { foreach (XElement action in widget.Elements("Action")) { #if DEBUG CrestronConsole.PrintLine(action.ToString()); #endif if (WidgetActionEvent != null) { WidgetActionEvent(this.Codec, new CodecUserInterfaceWidgetActionEventArgs( action.Element("WidgetId").Value, action.Element("Value").Value, (UserInterfaceActionType)Enum.Parse(typeof(UserInterfaceActionType), action.Element("Type").Value, true))); } } } } catch (Exception e) { ErrorLog.Exception("Error in codec event handler for UserInterface Widgets", e); } break; } } } else { string path = element.XName.LocalName; while (element.Elements().Count() == 1 && element.Elements().FirstOrDefault().HasElements) { element = element.Elements().FirstOrDefault(); path = string.Format("{0}/{1}", path, element.XName.LocalName); if (path == @"Status/Conference/Site") { break; } if (path == @"Status/Conference/Call") { break; } if (path == @"Status/Call") { break; } } if (element == xml.Root && element.Elements().FirstOrDefault() != null) { element = element.Elements().FirstOrDefault(); path = string.Format("{0}/{1}", path, element.XName.LocalName); } #if DEBUG CrestronConsole.PrintLine("Received {0} Update from {1} for path /{2}", xml.Root.XName.LocalName, productID, path); //ErrorLog.Notice("Received {0} Update from {1} for path /{2}", xml.Root.XName.LocalName, productID, path); //CrestronConsole.PrintLine("{0}\r\n", element.ToString()); #endif if (ReceivedData != null) { try { ReceivedData(this, new CodecFeedbackServerReceiveEventArgs(path, element)); } catch (Exception e) { ErrorLog.Exception("Error calling ReceivedData event in CodecFeedbackServer", e); } } } } else if (args.Request.Header.RequestType == "GET") { args.Response.SendError(405, "Method not allowed"); return(null); } return(null); } catch (Exception e) { ErrorLog.Exception("Exception on codec http feedback server", e); if (Codec.LoggingEnabled) { Codec.Logger.Log("ERROR processing post from {0}{1}Content:{1}{2}{1}StackTrace:{1}{3}", args.Connection.RemoteEndPointAddress, CrestronEnvironment.NewLine, args.Request.ContentString, e.StackTrace); } args.Response.SendError(500, "Internal server error"); return(null); } }
private void OnHttpRequest(object sender, OnHttpRequestArgs context) { try { var decodedPath = HttpUtility.UrlDecode(context.Request.Path); #if DEBUG var remoteAddress = context.Request.DataConnection.RemoteEndPointAddress; //var hostName = Dns.GetHostEntry(remoteAddress).HostName; Debug.WriteInfo("New WebScripting Request", "From {0}, Path \"{1}\"", remoteAddress, decodedPath); #endif foreach (var redirect in _redirects) { var pattern = redirect.Key; var match = Regex.Match(decodedPath, pattern); if (!match.Success) { continue; } #if DEBUG Debug.WriteSuccess("Redirect found!", "Pattern: \"{0}\"", pattern); #endif var queryString = context.Request.QueryString.ToString(); if (queryString.Length > 0 && !queryString.StartsWith("?")) { queryString = "?" + queryString; } context.Response.Header.AddHeader( new HttpHeader(string.Format("Location: {0}{1}", redirect.Value, queryString))); context.Response.Code = 302; //context.Response.FinalizeHeader(); return; } foreach (var handler in _handlers) { var pattern = handler.Key; var match = Regex.Match(decodedPath, pattern); if (!match.Success) { continue; } #if DEBUG Debug.WriteSuccess("Handler found!", "Pattern: \"{0}\"", pattern); #endif var loginRequired = _loginRequired[handler.Key]; try { var keyNames = _keyNames[pattern]; var args = new Dictionary <string, string>(); var index = 0; foreach (var keyName in keyNames) { if (keyName.Length > 0) { args[keyName] = match.Groups[index + 1].Value; } index++; } #if DEBUG foreach (var arg in args) { Debug.WriteInfo(" " + arg.Key, arg.Value); } #endif var request = new Request(this, context, args); var ctor = handler.Value.GetConstructor( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new CType[] { typeof(SystemBase), typeof(Request), typeof(bool) }, null); var instance = ctor.Invoke(new object[] { _system, request, loginRequired }) as BaseRequestHandler; if (instance == null) { continue; } instance.Process(); return; } catch (Exception e) { #if DEBUG CloudLog.Exception(e); #endif HandleError(context, e); return; } } #if DEBUG Debug.WriteError("No handler found for request!"); #endif HandleNotFound(context); } catch (Exception e) { HandleError(context, e); } }
void ServerHttpRequestHandler(object sender, OnHttpRequestArgs e) { Trace("ServerHttpRequestHandler() received request. Path: " + e.Request.Path); RequestCallbackNotify(e.Request.Path); }
void server_OnHttpRequest(object sender, OnHttpRequestArgs e) { try { if (e.Request.HasContentLength && e.Request.Path == "/:/timeline") { XmlDocument doc = new XmlDocument(); doc.LoadXml(e.Request.ContentString); XmlNodeList timelineList = doc.SelectNodes("MediaContainer/Timeline"); var currentType = "music"; foreach (XmlNode item in timelineList) { var type = item.Attributes["type"].Value; if (item.Attributes["state"].Value == "playing") { foreach (var sectionItem in section) { var currentItem = currentlyPlaying; if (sectionItem.Key == item.Attributes["key"].Value) { currentlyPlaying = sectionItem; if (Currentlyplaying.Type == "movie" || Currentlyplaying.Type == "episode") { currentType = "video"; } else if (Currentlyplaying.Type == "track") { currentType = "music"; } if (!isPlaying || currentItem != currentlyPlaying) { isPlaying = true; Playing(true, "playing", Name); } break; } } } if (type == currentType) { if (item.Attributes["time"] != null) { PlayProgress(this, new PlayProgressEventArgs(Convert.ToInt64(item.Attributes["time"].Value) / 1000, Name)); } if (item.Attributes["state"].Value == "paused") { isPlaying = false; Playing(false, "paused", Name); } else if (item.Attributes["state"].Value == "stopped") { if (isPlaying) { if (isPlayAll && section.Count > section.IndexOf(currentlyPlaying) + 1) { playNextItem = new CTimer(PlayNextItemCallback, this, 5000); } else if (isRepeatAll) { SelectItem(CurrentSection[0]); } else { isPlayAll = false; } isPlaying = false; PlayProgress(this, new PlayProgressEventArgs(Convert.ToInt64(currentlyPlaying.Duration) / 1000, Name)); Playing(false, "stopped", Name); } } } } } } catch (Exception ex) { ex.ToString(); } }
public void HTTPRequestEventHandler(Object sender, OnHttpRequestArgs requestArgs) //requestArgs { //int bytesSent = 0; string QueryString = requestArgs.Request.Header.RequestPath; string EventType = ""; string JoinType = ""; ushort JoinID = 0; string JoinValue = "0"; //ErrorLog.Notice(requestArgs.Request.Header.RequestType.ToString()); //IP/get|set/Digital|Analog|Serial/JoinID/Value if (requestArgs.Request.Header.RequestType.ToString() == "GET") { string[] words = QueryString.Split('/'); EventType = words[1]; JoinType = words[2]; JoinID = (ushort)Convert.ToInt32(words[3]); if(words[4] != null || words[4] != "") JoinValue = words[4]; switch (JoinType.ToUpper()) { case ("DIGITAL"): { if (EventType.ToUpper() == "SET") { SignalChangeEvents.DigitalValueChange(JoinID, (ushort)Convert.ToInt32(JoinValue)); requestArgs.Response.ContentString = "OK"; } else if (EventType.ToUpper() == "GET") { requestArgs.Response.ContentString = getDigitalSignal(JoinID).ToString(); } break; } case ("ANALOG"): { if (EventType.ToUpper() == "SET") { SignalChangeEvents.AnalogValueChange(JoinID, (ushort)Convert.ToInt32(JoinValue)); requestArgs.Response.ContentString = "OK"; } else if (EventType.ToUpper() == "GET") { requestArgs.Response.ContentString = getAnalogSignal(JoinID).ToString(); } break; } case ("SERIAL"): { if (EventType.ToUpper() == "SET") { SignalChangeEvents.SerialValueChange(JoinID, JoinValue); requestArgs.Response.ContentString = "OK"; } else if (EventType.ToUpper() == "GET") { requestArgs.Response.ContentString = getSerialSignal(JoinID).ToString(); } break; } default: { break; } } } /* if (requestArgs.Request.Header.RequestType.ToString() == "POST") { string[] words = QueryString.Split('/'); JoinType = words[1]; JoinID = (ushort)Convert.ToInt32(words[2]); JoinValue = words[3]; switch (JoinType) { case ("Digital"): { SignalChangeEvents.DigitalValueChange(JoinID,(ushort)Convert.ToInt32(JoinValue)); break; } case ("Analog"): { SignalChangeEvents.AnalogValueChange(JoinID,(ushort)Convert.ToInt32(JoinValue)); break; } case ("Serial"): { SignalChangeEvents.SerialValueChange(JoinID, JoinValue); break; } default: { break; } } } */ /* switch (requestArgs.Request.Header.RequestPath) { //"http://IP address of controller:port assigned to server" or //"http://IP address of controller:port assigned to server/home" case "/": case "/home": { var test = requestArgs.Request.QueryString.ToString(); ErrorLog.Notice(test + "\n"); //If request included data if (requestArgs.Request.HasContentLength) { //Assign amount of bytes sent to bytesSent bytesSent = requestArgs.Request.ContentLength; } if (bytesSent > 0) { String result = requestArgs.Request.ContentString; CrestronConsole.Print("Data that was received from POST request: " + result + "\r\n"); } //If the request contained no bytes else { //Set the ContentString variable as the source of data to return requestArgs.Response.ContentSource = ContentSource.ContentString; //Return the homepage requestArgs.Response.ContentString = MainPageHTML; requestArgs.Response.Header.SetHeaderValue("Content-Type", "text/html"); } break; } //http://IP address of controller:port assigned to server/secondpage case "/secondpage": { requestArgs.Response.ContentSource = ContentSource.ContentString; //Return the second page requestArgs.Response.ContentString = SecondPageHTML; requestArgs.Response.Header.SetHeaderValue("Content-Type", "text/html"); break; } //http://IP address of controller:port assigned to server/anything else default: { requestArgs.Response.ContentSource = ContentSource.ContentString; requestArgs.Response.ContentString = PageNotFoundHTML; requestArgs.Response.Header.SetHeaderValue("Content-Type", "text/html"); break; } }*/ }
internal void HandleError(OnHttpRequestArgs args, Exception e) { HandleError(args, 500, "Server Error - " + e.GetType().Name, e.Message + "\r\n" + e.StackTrace); }
internal void HandleNotFound(OnHttpRequestArgs args) { HandleError(args, 404, "Not Found", "The resource could not be found"); }
public void OnHttpRequest(object aSender, OnHttpRequestArgs ea) { AddLog(String.Format("Request to {0}", ea.Request.Header.RequestPath)); }