private async Task ApiResponse(SimpleHttpRequest request, string target, Stream responseStream) { try { var method = target.Substring(target.LastIndexOf("/")); var responseText = string.Empty; var jsonSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; switch (method) { case "/api": //just return ok responseText = JsonConvert.SerializeObject(new { response = 1 }); break; case "/currentTrack": //return current track responseText = JsonConvert.SerializeObject(new { response = new { track = ViewModelLocator.Main.CurrentAudio, currentTime = ViewModelLocator.Main.CurrentAudioPositionSeconds, duration = ViewModelLocator.Main.CurrentAudioDuration.TotalSeconds, shuffle = ViewModelLocator.Main.Shuffle, repeat = ViewModelLocator.Main.Repeat } }, Formatting.None, jsonSettings); break; case "/isPlaying": //return isPlaying responseText = JsonConvert.SerializeObject(new { response = ViewModelLocator.Main.IsPlaying }, Formatting.None, jsonSettings); break; case "/volume": //return volume responseText = JsonConvert.SerializeObject(new { response = ViewModelLocator.Main.Volume }, Formatting.None, jsonSettings); break; } var response = new SimpleHttpResponse(); var contentType = "application/json"; var responseBytes = Encoding.UTF8.GetBytes(responseText.ToString()); response.Headers.Add("Content-Length", responseBytes.Length.ToString()); response.Headers.Add("Content-Type", contentType); responseStream.WriteText(response.ToString() + responseText); responseStream.Dispose(); } catch (Exception ex) { LoggingService.Log(ex); } }
private async Task FileResponse(SimpleHttpRequest request, string target, Stream responseStream) { var streamResourceInfo = Application.GetContentStream(new Uri("pack://application:,,,/Meridian;component/RemotePlay/web" + target)); if (streamResourceInfo != null) { try { var response = new SimpleHttpResponse(); var length = streamResourceInfo.Stream.Length; var extension = Path.GetExtension(target); var contentType = "application/" + extension; switch (extension) { case ".html": case ".htm": contentType = "text/html"; break; case ".js": contentType = "application/javascript"; break; case ".css": contentType = "text/css"; break; case ".png": contentType = "image/png"; break; case ".svg": contentType = "image/svg+xml"; break; } response.Headers.Add("Content-Length", length.ToString()); response.Headers.Add("Content-Type", contentType); var headerBytes = Encoding.UTF8.GetBytes(response.ToString()); responseStream.Write(headerBytes, 0, headerBytes.Length); streamResourceInfo.Stream.CopyTo(responseStream); await responseStream.FlushAsync(); responseStream.Close(); responseStream.Dispose(); } catch (Exception ex) { LoggingService.Log(ex); } } else { var response = new SimpleHttpResponse(); response.Status = "HTTP/1.1 404 NOT FOUND"; response.Headers.Add("Content-Length", "0"); responseStream.WriteText(response.ToString()); responseStream.Dispose(); } }