Now fetching some of our Sound Graph DLL function pointers.
3 This Source Code Form is subject to the terms of the Mozilla Public
4 License, v. 2.0. If a copy of the MPL was not distributed with this
5 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 Copyright (C) 2012 Prince Samuel <prince.samuel@gmail.com>
8 Copyright (C) 2012 Michael Möller <mmoeller@openhardwaremonitor.org>
14 using System.Drawing.Imaging;
17 using System.Reflection;
19 using System.Threading;
20 using OpenHardwareMonitor.GUI;
21 using OpenHardwareMonitor.Hardware;
23 namespace OpenHardwareMonitor.Utilities {
25 public class HttpServer {
26 private HttpListener listener;
27 private int listenerPort, nodeCount;
28 private Thread listenerThread;
31 public HttpServer(Node node, int port) {
39 listener = new HttpListener();
40 } catch (PlatformNotSupportedException) {
45 public bool PlatformNotSupported {
47 return listener == null;
51 public Boolean StartHTTPListener() {
52 if (PlatformNotSupported)
56 if (listener.IsListening)
59 string prefix = "http://+:" + listenerPort + "/";
60 listener.Prefixes.Clear();
61 listener.Prefixes.Add(prefix);
64 if (listenerThread == null) {
65 listenerThread = new Thread(HandleRequests);
66 listenerThread.Start();
75 public Boolean StopHTTPListener() {
76 if (PlatformNotSupported)
80 listenerThread.Abort();
82 listenerThread = null;
83 } catch (HttpListenerException) {
84 } catch (ThreadAbortException) {
85 } catch (NullReferenceException) {
91 private void HandleRequests() {
93 while (listener.IsListening) {
94 var context = listener.BeginGetContext(
95 new AsyncCallback(ListenerCallback), listener);
96 context.AsyncWaitHandle.WaitOne();
100 private void ListenerCallback(IAsyncResult result) {
101 HttpListener listener = (HttpListener)result.AsyncState;
102 if (listener == null || !listener.IsListening)
105 // Call EndGetContext to complete the asynchronous operation.
106 HttpListenerContext context;
108 context = listener.EndGetContext(result);
109 } catch (Exception) {
113 HttpListenerRequest request = context.Request;
115 var requestedFile = request.RawUrl.Substring(1);
116 if (requestedFile == "data.json") {
117 SendJSON(context.Response);
121 if (requestedFile.Contains("images_icon")) {
122 ServeResourceImage(context.Response,
123 requestedFile.Replace("images_icon/", ""));
127 // default file to be served
128 if (string.IsNullOrEmpty(requestedFile))
129 requestedFile = "index.html";
131 string[] splits = requestedFile.Split('.');
132 string ext = splits[splits.Length - 1];
133 ServeResourceFile(context.Response,
134 "Web." + requestedFile.Replace('/', '.'), ext);
137 private void ServeResourceFile(HttpListenerResponse response, string name,
140 // resource names do not support the hyphen
141 name = "OpenHardwareMonitor.Resources." +
142 name.Replace("custom-theme", "custom_theme");
145 Assembly.GetExecutingAssembly().GetManifestResourceNames();
146 for (int i = 0; i < names.Length; i++) {
147 if (names[i].Replace('\\', '.') == name) {
148 using (Stream stream = Assembly.GetExecutingAssembly().
149 GetManifestResourceStream(names[i])) {
150 response.ContentType = GetcontentType("." + ext);
151 response.ContentLength64 = stream.Length;
152 byte[] buffer = new byte[512 * 1024];
155 Stream output = response.OutputStream;
156 while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
157 output.Write(buffer, 0, len);
160 } catch (HttpListenerException) {
168 response.StatusCode = 404;
172 private void ServeResourceImage(HttpListenerResponse response, string name) {
173 name = "OpenHardwareMonitor.Resources." + name;
176 Assembly.GetExecutingAssembly().GetManifestResourceNames();
177 for (int i = 0; i < names.Length; i++) {
178 if (names[i].Replace('\\', '.') == name) {
179 using (Stream stream = Assembly.GetExecutingAssembly().
180 GetManifestResourceStream(names[i])) {
182 Image image = Image.FromStream(stream);
183 response.ContentType = "image/png";
185 Stream output = response.OutputStream;
186 using (MemoryStream ms = new MemoryStream()) {
187 image.Save(ms, ImageFormat.Png);
191 } catch (HttpListenerException) {
200 response.StatusCode = 404;
204 private void SendJSON(HttpListenerResponse response) {
206 string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": [";
208 JSON += GenerateJSON(root);
210 JSON += ", \"Min\": \"Min\"";
211 JSON += ", \"Value\": \"Value\"";
212 JSON += ", \"Max\": \"Max\"";
213 JSON += ", \"ImageURL\": \"\"";
216 var responseContent = JSON;
217 byte[] buffer = Encoding.UTF8.GetBytes(responseContent);
219 response.AddHeader("Cache-Control", "no-cache");
221 response.ContentLength64 = buffer.Length;
222 response.ContentType = "application/json";
225 Stream output = response.OutputStream;
226 output.Write(buffer, 0, buffer.Length);
228 } catch (HttpListenerException) {
234 private string GenerateJSON(Node n) {
235 string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text
236 + "\", \"Children\": [";
239 foreach (Node child in n.Nodes)
240 JSON += GenerateJSON(child) + ", ";
241 if (JSON.EndsWith(", "))
242 JSON = JSON.Remove(JSON.LastIndexOf(","));
245 if (n is SensorNode) {
246 JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\"";
247 JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\"";
248 JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\"";
249 JSON += ", \"ImageURL\": \"images/transparent.png\"";
250 } else if (n is HardwareNode) {
251 JSON += ", \"Min\": \"\"";
252 JSON += ", \"Value\": \"\"";
253 JSON += ", \"Max\": \"\"";
254 JSON += ", \"ImageURL\": \"images_icon/" +
255 GetHardwareImageFile((HardwareNode)n) + "\"";
256 } else if (n is TypeNode) {
257 JSON += ", \"Min\": \"\"";
258 JSON += ", \"Value\": \"\"";
259 JSON += ", \"Max\": \"\"";
260 JSON += ", \"ImageURL\": \"images_icon/" +
261 GetTypeImageFile((TypeNode)n) + "\"";
263 JSON += ", \"Min\": \"\"";
264 JSON += ", \"Value\": \"\"";
265 JSON += ", \"Max\": \"\"";
266 JSON += ", \"ImageURL\": \"images_icon/computer.png\"";
273 private static void ReturnFile(HttpListenerContext context, string filePath)
275 context.Response.ContentType =
276 GetcontentType(Path.GetExtension(filePath));
277 const int bufferSize = 1024 * 512; //512KB
278 var buffer = new byte[bufferSize];
279 using (var fs = File.OpenRead(filePath)) {
281 context.Response.ContentLength64 = fs.Length;
283 while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
284 context.Response.OutputStream.Write(buffer, 0, read);
287 context.Response.OutputStream.Close();
290 private static string GetcontentType(string extension) {
292 case ".avi": return "video/x-msvideo";
293 case ".css": return "text/css";
294 case ".doc": return "application/msword";
295 case ".gif": return "image/gif";
297 case ".html": return "text/html";
299 case ".jpeg": return "image/jpeg";
300 case ".js": return "application/x-javascript";
301 case ".mp3": return "audio/mpeg";
302 case ".png": return "image/png";
303 case ".pdf": return "application/pdf";
304 case ".ppt": return "application/vnd.ms-powerpoint";
305 case ".zip": return "application/zip";
306 case ".txt": return "text/plain";
307 default: return "application/octet-stream";
311 private static string GetHardwareImageFile(HardwareNode hn) {
313 switch (hn.Hardware.HardwareType) {
314 case HardwareType.CPU:
316 case HardwareType.GpuNvidia:
318 case HardwareType.GpuAti:
320 case HardwareType.HDD:
322 case HardwareType.Heatmaster:
324 case HardwareType.Mainboard:
325 return "mainboard.png";
326 case HardwareType.SuperIO:
328 case HardwareType.TBalancer:
330 case HardwareType.RAM:
338 private static string GetTypeImageFile(TypeNode tn) {
340 switch (tn.SensorType) {
341 case SensorType.Voltage:
342 return "voltage.png";
343 case SensorType.Clock:
345 case SensorType.Load:
347 case SensorType.Temperature:
348 return "temperature.png";
351 case SensorType.Flow:
353 case SensorType.Control:
354 return "control.png";
355 case SensorType.Level:
357 case SensorType.Power:
365 public int ListenerPort {
366 get { return listenerPort; }
367 set { listenerPort = value; }
371 if (PlatformNotSupported)
379 if (PlatformNotSupported)