private void ProcessGETRequest(IDataProducer body, HttpRequestHead head, IHttpResponseDelegate response) { var qs = head.QueryString.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split(new char[] { '=' }, StringSplitOptions.None)) .ToDictionary(p => p[0], p => HttpUtility.UrlDecode(p[1])); string[] lines = qs["metrics"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(qs["metrics"])); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application-xml" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private static HttpRequestHead EchoPost(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) { headers.Headers["Content-Length"] = request.Headers["Content-Length"]; } // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); return(request); }
public void OnResponse(HttpResponseHead response) { current = new ResponseInfo() { Head = response }; }
private static void TurnOnElement(HttpRequestHead request, IHttpResponseDelegate response) { var status = new Status(); NameValueCollection parms = GetParameters(request); if (!parms.HasKeys() && parms["id"] != null && parms["time"] != null && parms["color"] != null) { HttpResponseHead headers = GetHeaders(0, HttpStatusCode.BadRequest.ToString()); response.OnResponse(headers, new BufferedProducer("")); return; } if (parms["color"].Length != 7 || !parms["color"].StartsWith("#")) { status.Message = "Invalid color. Must be Hex."; SerializeResponse(status, response); return; } Guid elementId = Guid.Empty; bool allElements = false; int seconds; if ("all".Equals(parms["id"])) { allElements = true; } else { Guid.TryParse(parms["id"], out elementId); } if (!int.TryParse(parms["time"], out seconds)) { status.Message = "Time must be numeric."; SerializeResponse(status, response); return; } Color elementColor = ColorTranslator.FromHtml(parms["color"]); //TODO the following logic for all does not properly deal with discrete color elements when turning all on //TODO they will not respond to turning on white if they are set up with a filter. //TODO enhance this to figure out what colors there are and turn them all on when we are turning all elements on. var effect = new SetLevel { TimeSpan = TimeSpan.FromSeconds(seconds), Color = elementColor, IntensityLevel = 1, TargetNodes = allElements ? VixenSystem.Nodes.GetRootNodes().ToArray() : new[] { VixenSystem.Nodes.GetElementNode(elementId) } }; Module.LiveSystemContext.Execute(new EffectNode(effect, TimeSpan.Zero)); status.Message = string.Format("{0} element(s) turned on for {1} seconds at 100% intensity.", allElements?"All":VixenSystem.Nodes.GetElementNode(elementId).Name, seconds); SerializeResponse(status, response); }
public static HttpResponseHead GetHttpResponseHead(string status = "200 OK") { var headers = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() }; return(headers); }
public void OnResponse(HttpResponseHead head, bool hasBody) { if (hasBody) { subject = new SimpleSubject( () => userCode.ConnectResponseBody(this), () => userCode.DisconnectResponseBody(this)); } responseDelegate.OnResponse(head, subject); }
public HttpResponseHead BuildHeaders() { AddHeader(HttpHeaderNames.ContentType, _contentType); AddHeader(HttpHeaderNames.ContentLength, _contentLength.ToString()); var headers = new HttpResponseHead { Status = string.Format("{0} {1}", (int)_httpStatusCode, _httpStatusCode), Headers = _headers }; return(headers); }
internal static HttpRequestHead UnsupportedOperation(HttpRequestHead request, IHttpResponseDelegate response) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(new Status { Message = "Unknown request" }); HttpResponseHead headers = GetOkHeaders(json.Length); headers.Status = HttpStatusCode.BadRequest.ToString(); response.OnResponse(headers, new BufferedProducer(json)); return(request); }
internal static HttpResponseHead GetHeaders(int contentSize, string status) { var headers = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Type", "application/json" }, { "Content-Length", contentSize.ToString() }, } }; return(headers); }
private void ProcessClientAccessPolicyRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "text/xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(SILVERLIGHT_CROSSDOMAIN).ToString() } } }; response.OnResponse(responseHead, new BufferedProducer(SILVERLIGHT_CROSSDOMAIN)); }
private void Respond(IHttpResponseDelegate response, string status) { var responseHead = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private static void NotFoundResponse(HttpRequestHead request, IHttpResponseDelegate response) { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/html" }, { "Content-Length", responseBody.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(responseBody)); }
private void ProcessCrossDomainRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "application-xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(FLASH_CROSSDOMAIN).ToString() }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(responseHead, new BufferedProducer(FLASH_CROSSDOMAIN)); }
private static void ReturnHttpMockNotFound(IHttpResponseDelegate response) { var dictionary = new Dictionary <string, string> { { HttpHeaderNames.ContentLength, "0" }, { "X-HttpMockError", "No handler found to handle request" } }; var notFoundResponse = new HttpResponseHead { Status = string.Format("{0} {1}", 404, "NotFound"), Headers = dictionary }; response.OnResponse(notFoundResponse, null); }
private void ProcessFileNotFound(IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() }, { "Access-Control-Allow-Origin", "*" } } }; response.OnResponse(headers, new BufferedProducer("not found")); }
private void ProcessOPTIONSRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" } }) }; response.OnResponse(responseHead, new EmptyResponse()); }
private void ProcessOPTIONSRequest(IDataProducer body, IHttpResponseDelegate response) { var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", "0" }, { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, OPTIONS" }, { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" } } }; response.OnResponse(responseHead, new EmptyResponse()); }
private static void GetResourceByName(string contentRequest, IHttpResponseDelegate response) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" }, { "Content-Length", "0" }, { "Cache-Control", "max-age=31536000" } } }; BufferedProducer producer = new BufferedProducer(""); if (_assembly == null) { _assembly = Assembly.GetAssembly(typeof(VixenModules.App.WebServer.HTTP.RequestDelegate)); } try { var resources = _assembly.GetManifestResourceNames(); var resourceItem = resources.FirstOrDefault(n => n.EndsWith(contentRequest, StringComparison.CurrentCultureIgnoreCase)); if (resourceItem == null) { throw new ApplicationException(string.Format("Requested Resource {0} does not exist.", contentRequest)); } using (var _Stream = _assembly.GetManifestResourceStream(resourceItem)) { var bytes = ReadFully(_Stream); headers.Headers["Content-Length"] = bytes.Length.ToString(); headers.Headers["Content-Type"] = GetContentType(contentRequest); producer = new BufferedProducer(bytes); } } catch (Exception e) { Logging.ErrorException(e.Message, e); headers.Status = "404 Not Found"; } response.OnResponse(headers, producer); }
private void Respond(HttpRequestHead head, IHttpResponseDelegate response, string status) { var responseHead = new HttpResponseHead() { Status = status, Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "0" } } ) }; response.OnResponse(responseHead, new EmptyResponse()); }
private void ProcessFileNotFound(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { _parent._systemMetrics.LogCount("listeners.http.404"); var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/plain" }, { "Content-Length", Encoding.UTF8.GetByteCount("not found").ToString() } } ) }; response.OnResponse(headers, new BufferedProducer("not found")); }
private void ProcessClientAccessPolicyRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var silverlightCrossdomain = _corsValidator.GetSilverlightCrossDomainPolicy(); var responseHead = new HttpResponseHead() { Status = "200 OK", Headers = _corsValidator.AppendCorsHeaderDictionary( head, new Dictionary <string, string> { { "Content-Type", "text/xml" }, { "Content-Length", Encoding.UTF8.GetByteCount(silverlightCrossdomain).ToString() } } ) }; response.OnResponse(responseHead, new BufferedProducer(silverlightCrossdomain)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var status = "404 Not Found"; var body = new BufferedProducer($"The resource you requested ('{request.Uri}') could not be found."); try { foreach (var route in _routes) { if (request.Path == route.Key) { body = route.Value.Execute(request.QueryString); status = "200 OK"; break; } } } catch (Exception e) { status = "500 Internal Server Error"; var responseBody = $"The resource you requested ('{request.Uri}') produced an error: {e.Message}"; body = new BufferedProducer(responseBody); } var headers = new HttpResponseHead() { Status = status, Headers = new Dictionary <string, string>() { { "Content-Type", body.MimeType }, { "Content-Length", body.Size.ToString() }, } }; response.OnResponse(headers, body); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/bufferedecho")) { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/echo")) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) { headers.Headers["Content-Length"] = request.Headers["Content-Length"]; } // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { #if DEBUG var logger = ApplicationManager.GetInstance().GetLogger(); logger.WriteDebug($"HTTP request {request.Path}"); logger.WriteDebug($"QueryString: {request.QueryString}"); logger.WriteDebug($"IP: {request.IPAddress}"); #endif NameValueCollection querySet = new NameValueCollection(); if (request.QueryString != null) { querySet = System.Web.HttpUtility.ParseQueryString(request.QueryString); } querySet.Set("IP", request.IPAddress); try { request.Path = String.IsNullOrEmpty(request.Path) ? "/" : request.Path; SharedLibrary.HttpResponse requestedPage = WebService.GetPage(request.Path, querySet, request.Headers); bool binaryContent = requestedPage.BinaryContent != null; if (requestedPage.content != null && requestedPage.content.GetType() != typeof(string)) #if !DEBUG { requestedPage.content = Newtonsoft.Json.JsonConvert.SerializeObject(requestedPage.content); } #else { requestedPage.content = Newtonsoft.Json.JsonConvert.SerializeObject(requestedPage.content, Newtonsoft.Json.Formatting.Indented); } #endif string maxAge = requestedPage.contentType == "application/json" ? "0" : "21600"; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", requestedPage.contentType }, { "Content-Length", binaryContent ? requestedPage.BinaryContent.Length.ToString() : requestedPage.content.ToString().Length.ToString() }, { "Access-Control-Allow-Origin", "*" }, { "Cache-Control", $"public,max-age={maxAge}" } } }; foreach (var key in requestedPage.additionalHeaders.Keys) { headers.Headers.Add(key, requestedPage.additionalHeaders[key]); } if (!binaryContent) { response.OnResponse(headers, new BufferedProducer((string)requestedPage.content)); } else { response.OnResponse(headers, new BufferedProducer(requestedPage.BinaryContent)); } } catch (Exception e) { if (e.GetType() == typeof(FormatException)) { ApplicationManager.GetInstance().Logger.WriteWarning("Request parameter data format was incorrect"); ApplicationManager.GetInstance().Logger.WriteDebug($"Request Path {request.Path}"); ApplicationManager.GetInstance().Logger.WriteDebug($"Request Query String {request.QueryString}"); response.OnResponse(new HttpResponseHead() { Status = "400 Bad Request", Headers = new Dictionary <string, string>() { { "Content-Type", "text/html" }, { "Content-Length", "0" }, } }, new BufferedProducer("")); } else { ApplicationManager.GetInstance().Logger.WriteError($"Webfront error during request"); ApplicationManager.GetInstance().Logger.WriteDebug($"Message: {e.Message}"); ApplicationManager.GetInstance().Logger.WriteDebug($"Stack Trace: {e.StackTrace}"); response.OnResponse(new HttpResponseHead() { Status = "500 Internal Server Error", Headers = new Dictionary <string, string>() { { "Content-Type", "text/html" }, { "Content-Length", "0" }, } }, new BufferedProducer("")); } } }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/next")) { // when you subscribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. bool ret = MainWindow.Next(); var body = ret ? "Successfully skipped." : "You have to wait for 20 seconds to skip again."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/pause")) { MainWindow.Pause(); var body = "Paused."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/play")) { MainWindow.Play(); var body = "Playing."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/toggleplaypause")) { var body = ""; if (MainWindow._player.Playing) { body = "Paused."; } else { body = "Playing."; } MainWindow.PlayPauseToggle(); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/like")) { MainWindow.Like(); var body = "Like"; if (MainWindow.GetCurrentSong().Loved) { body = "Liked"; } var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/dislike")) { MainWindow.Dislike(); var body = "Disliked."; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/currentsong")) { Song s = MainWindow.GetCurrentSong(); var body = JsonConvert.SerializeObject(s); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Method.ToUpperInvariant() == "GET" && request.Uri.StartsWith("/connect")) { var body = "true"; var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
public void OnResponse(HttpResponseHead head, IDataProducer body) { Head = head; Body = body; }