public override Dictionary<string, object> GetPageData(HttpRequest request, IDirectory directory) { Dictionary<string,object> d = new Dictionary<string,object>(); d.Add("MarqueeText", MainClass.Sanitise(MainClass.settings.GetMarqueeText())); d.Add("NotepadText", MainClass.Sanitise(MainClass.settings.GetNotepadText())); d.Add("Timeout", 10); d.Add("Fonts", new string[] {"placeholder"}); d.Add("Font", "placeholder"); d.Add("EventNameFull", MainClass.Sanitise(MainClass.settings.GetEventNameFull())); /* * d.Add("MarqueeText", Main.Sanitise(mw.MarqueeText)); d.Add("NotepadText", Main.Sanitise(mw.LanSettings.Notepad)); d.Add("Timeout", mw.LanSettings.NotepadTimeout); d.Add("Fonts", Main.Sanitise(mw.LanSettings.Fonts.ToArray())); */ //Pango.FontDescription fd = Pango.FontDescription.FromString(mw.LanSettings.NotepadFont); //d.Add("Font", Main.Sanitise(fd.Family)); // UGLY HACK ALERT // this really should be done properly, however the font size reported in the fontdescription is the wrong // unit and no suitable conversion function to points is quickly available. //try { // d.Add("FontSize", int.Parse(mw.LanSettings.NotepadFont.Remove(0,fd.Family.Length+1))); //} catch (FormatException) { // some fonts have incorrect family names for some reason, another thing to fix. d.Add("FontSize", 30); //} return d; }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); Console.WriteLine("[EXIT] Disconnecting users.."); System.Threading.Thread.Sleep(1000); foreach (KeyValuePair<Guid, User> entry in users) { try { User user = entry.Value; //Guid session = (Guid)entry.Key; if (user.Events != null) { user.Events.Network_Disconnected(this, new DisconnectedEventArgs(NetworkManager.DisconnectType.ServerInitiated, "Your deviMobile session has timed out.")); Console.WriteLine("[EXIT] Transmitted logout alert to " + user.Client.Self.FirstName + " " + user.Client.Self.LastName + ". Waiting..."); System.Threading.Thread.Sleep(1000); user.Events.deactivate(); } Console.WriteLine("[EXIT] Disconnecting " + user.Client.Self.FirstName + " " + user.Client.Self.LastName + "..."); user.Client.Network.Logout(); } catch(Exception e) { Console.WriteLine("[ERROR] " + e.Message); } } System.Threading.Thread.Sleep(1000); Console.WriteLine("[EXIT] Done."); Environment.Exit(0); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); try { Guid key = Guid.NewGuid(); StreamReader reader = new StreamReader(request.PostData); string qstring = reader.ReadToEnd(); reader.Dispose(); Dictionary<string, string> POST = deviMobile.PostDecode(qstring); User user = User.CreateUser(); //(int)POST["screenWidth"], (int)POST["screenHeight"]); lock (users) users.Add(key, user); Hashtable ret = new Hashtable(); ret.Add("id", key.ToString("D")); ret.Add("ch", user.Challenge); writer.Write(MakeJson.FromHashtable(ret)); writer.Flush(); } catch (IOException e) { writer.Write(e.Message); writer.Flush(); } }
/// <summary> /// Called when the file is requested by a client. /// </summary> /// <param name="request">The <see cref="HttpRequest"/> requesting the file.</param> /// <param name="directory">The <see cref="IDirectory"/> of the parent directory.</param> public void OnFileRequested(HttpRequest request, IDirectory directory) { ICollection dirs; ICollection files; try { dirs = directory.GetDirectories(); files = directory.GetFiles(); } catch(UnauthorizedAccessException) { throw new HttpRequestException("403"); } request.Response.BeginChunkedOutput(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); writer.WriteLine("<html>"); writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); writer.WriteLine("<head><title>Index of " + HttpWebServer.GetDirectoryPath(directory) + "</title></head>"); writer.WriteLine("<body>"); PrintBody(writer, request, directory, dirs, files); writer.WriteLine("<hr>" + request.Server.ServerName); writer.WriteLine("</body></html>"); writer.WriteLine("</body>"); writer.WriteLine("</html>"); writer.Flush(); }
internal virtual void PrintBody(StreamWriter writer, HttpRequest request, IDirectory directory, ICollection dirs, ICollection files ) { writer.WriteLine("<h2>Index of " + HttpWebServer.GetDirectoryPath(directory) + "</h2>"); if(directory.Parent != null) writer.WriteLine("<a href=\"..\">[..]</a><br>"); foreach(IDirectory dir in dirs) { //if(dir is IPhysicalResource) // if((File.GetAttributes((dir as IPhysicalResource).Path) & FileAttributes.Hidden) != 0) // continue; writer.WriteLine("<a href=\"" + UrlEncoding.Encode(dir.Name) + "/\">[" + dir.Name + "]</a><br>"); } foreach(IFile file in files) { //if(file is IPhysicalResource) // if((File.GetAttributes((file as IPhysicalResource).Path) & FileAttributes.Hidden) != 0) // continue; writer.WriteLine("<a href=\"" + UrlEncoding.Encode(file.Name) + "\">" + file.Name + "</a><br>"); } }
/// <summary> /// Called when the file is requested by a client. /// </summary> /// <param name="request">The <see cref="HttpRequest"/> requesting the file.</param> /// <param name="directory">The <see cref="IDirectory"/> of the parent directory.</param> public void OnFileRequested(HttpRequest request, IDirectory directory) { if(request.IfModifiedSince != DateTime.MinValue) { if(File.GetLastWriteTimeUtc(path) < request.IfModifiedSince) request.Response.ResponseCode = "304"; return; } if(request.IfUnmodifiedSince != DateTime.MinValue) { if(File.GetLastWriteTimeUtc(path) > request.IfUnmodifiedSince) request.Response.ResponseCode = "304"; return; } if(System.IO.Path.GetFileName(path).StartsWith(".")) { request.Response.ResponseCode = "403"; return; } try { request.Response.ResponseContent = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } catch(FileNotFoundException) { request.Response.ResponseCode = "404"; } catch(IOException e) { request.Response.ResponseCode = "500"; request.Server.Log.WriteLine(e); } }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ContentType = request.Query["type"]; this.contenttype = request.Query["type"]; request.Response.ResponseContent = new MemoryStream(); StreamWriter textWriter = new StreamWriter(request.Response.ResponseContent); textWriter.Write(request.Query["content"]); textWriter.Flush(); }
// /blink1/id -- Display blink1_id and blink1 serial numbers (if any) static string blink1Id(HttpRequest request, blinkServer bs)//example { string serial = bs.getId(); return @"{ ""blink1_id"": ""44288083" + serial + @""", ""blink1_serialnums"": [ """ + serial + @""" ], ""status"": ""blink1 id"" }"; }
public override Dictionary<string, object> GetPageData(HttpRequest request, IDirectory directory) { Dictionary<string,object> d = new Dictionary<string,object>(); // save the data back Console.WriteLine("Setting to {0}.", request.Query.Get("marqueeText")); MainClass.settings.SetMarqueeText(request.Query.Get("marqueeText")); MainClass.settings.FireSettingsChanged(); d.Add("Redirect", "index.html"); return d; }
internal override void PrintBody(StreamWriter writer, HttpRequest request, IDirectory directory, ICollection dirs, ICollection files ) { bool reverse = request.Query["desc"] != null; ResourceColumn sort = ResourceColumn.None; try { string sortString = request.Query["sort"]; if(sortString != null && sortString != string.Empty) sort = (ResourceColumn)Enum.Parse(typeof(ResourceColumn), sortString); } catch(ArgumentException) { } writer.WriteLine("<h2>Index of " + MakeLinkPath(directory, request) + "</h2>"); writer.WriteLine("<table cellspacing=\"0\">"); writer.WriteLine("<tr>"); foreach(ResourceColumn column in columns) { writer.Write(GetColumnTd(column) + "<b><a href=\"" + "." + "?sort=" + column.ToString()); if(sort == column && !reverse) writer.Write("&desc"); writer.Write("\"/>"); writer.WriteLine(column.ToString() + "</a></b></td>"); } writer.WriteLine("</tr>"); ArrayList entries = new ArrayList(dirs.Count + files.Count); foreach(IDirectory dir in dirs) entries.Add(new ResourceEntry(dir)); foreach(IFile file in files) entries.Add(new ResourceEntry(file)); if(sort != ResourceColumn.None) entries.Sort(new ResourceComparer(reverse, sort)); foreach(ResourceEntry entry in entries) entry.WriteHtml(writer, columns); writer.WriteLine("</table>"); }
// Someone wants differentorigin.kat. This exists to bypass the Same Origin Policy. // It was going to be proxy.kat, but my school's filter blocks the word "proxy." public void OnFileRequested(MiniHttpd.HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); // Work out the URL. string url = request.Query["url"]; // Make a Sytem.Net.HttpWebRequest for the URL. HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url); // If we're meant to be posting it, take the request's postdata and forward it on, // with appropriate headers. if (request.Method.ToLower() == "post") { byte[] postdata = Encoding.GetEncoding("utf8").GetBytes((new StreamReader(request.PostData)).ReadToEnd()); webrequest.ContentLength = postdata.Length; Stream poststream = webrequest.GetRequestStream(); poststream.Write(postdata, 0, postdata.Length); poststream.Close(); } // For stats/blocking/identification purposes. webrequest.UserAgent = "AjaxLife"; // Get the response back HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse(); // Read the response's headers. StreamReader responsestream = new StreamReader(response.GetResponseStream()); // Set the headers in our response, except for Transfer-Encoding (which would break things) foreach (string header in response.Headers) { if (header == "Transfer-Encoding") { continue; } request.Response.SetHeader(header, response.Headers[header]); } // Read the rest of the data string output = responsestream.ReadToEnd(); ctype = response.ContentType; // Spit out the data again. writer.Write(output); // Close everything. writer.Flush(); responsestream.Close(); response.Close(); // Voila. Proxy. }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); Guid key = Guid.NewGuid(); User user = User.CreateUser(); lock(users) users.Add(key, user); Hashtable ret = new Hashtable(); ret.Add("SessionID", key.ToString("D")); ret.Add("Challenge", user.Challenge); ret.Add("Exponent", StringHelper.BytesToHexString(AjaxLife.RSAp.Exponent)); ret.Add("Modulus", StringHelper.BytesToHexString(AjaxLife.RSAp.Modulus)); ret.Add("Grids", AjaxLife.LOGIN_SERVERS.Keys); ret.Add("DefaultGrid", AjaxLife.DEFAULT_LOGIN_SERVER); writer.Write(MakeJson.FromHashtable(ret)); writer.Flush(); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); try { Dictionary<string, object> d = GetPageData(request, directory); d.Add("Version", MainClass.Version); d.Add("GenerationTime", DateTime.Now.ToString("F")); writer.Write(template.Generate(d)); } catch (HTTPDErrorException ex) { writer.Write(ex.GenerateErrorPage()); } catch (Exception ex) { HTTPDErrorException hex = new HTTPDErrorException(String.Format("Unhandled Exception: {0}", ex.GetType().FullName), String.Format("An exception ({0}) was thrown that was not handled and turned into a HTTPDErrorException properly. It's message was: {1}", ex.GetType().FullName, ex.Message), ex); writer.Write(hex.GenerateErrorPage()); } writer.Flush(); }
string MakeLinkPath(IDirectory directory, HttpRequest request) { StringBuilder sb = new StringBuilder(); ArrayList pathList = new ArrayList(); for(IDirectory dir = directory; dir != null; dir = dir.Parent) pathList.Add(dir.Name); pathList.RemoveAt(pathList.Count-1); pathList.Reverse(); sb.Append("<a href=\"" + request.Uri.Scheme + "://" + request.Uri.Host); if(request.Uri.Port != 80) sb.Append(":" + request.Uri.Port); sb.Append("/\">"); sb.Append(request.Uri.Host + "</a>"); if(pathList.Count > 0) sb.Append(" - "); StringBuilder reassembledPath = new StringBuilder(); for(int i = 0; i < pathList.Count; i++) { string path = pathList[i] as string; sb.Append("<a href=\"/"); reassembledPath.Append(UrlEncoding.Encode(path)); reassembledPath.Append("/"); sb.Append(reassembledPath.ToString()); sb.Append("\">"); sb.Append(path); if(i < pathList.Count-1) sb.Append("</a>/"); else sb.Append("</a>"); } return sb.ToString(); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); StreamReader reader = new StreamReader(request.PostData); string post = reader.ReadToEnd(); reader.Dispose(); Dictionary<string, string> POST = AjaxLife.PostDecode(post); Hashtable hash = new Hashtable(); hash.Add("SESSION_ID", POST["sid"]); hash.Add("STATIC_ROOT", AjaxLife.STATIC_ROOT); Html.Template.Parser parser = new Html.Template.Parser(hash); writer.Write(parser.Parse(File.ReadAllText("Html/Templates/iPhone.html")));; writer.Flush(); }
internal RequestEventArgs(HttpClient client, HttpRequest request) : base(client) { this.request = request; }
// ----------------------------------------------------------------------------------------------- // color patterns url handling // // /blink1/pattern/ -- List saved color patterns static string Ublink1Pattern(HttpRequest request, Blink1Server blink1Server) { Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", "pattern results"); result.Add("patterns", blink1Server.patterns.Values); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { // Assign a MemoryStream to hold the response content. request.Response.ResponseContent = new MemoryStream(); // Create a StreamWriter to which we // can write some text, and write to it. StreamWriter writer = new StreamWriter(request.Response.ResponseContent); writer.WriteLine(GetStringResponse(request, bs)); // Don't forget to flush! writer.Flush(); }
public virtual Dictionary<string, object> GetPageData(HttpRequest request, IDirectory directory) { return null; }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); try { // Generate a new session ID. Guid key = Guid.NewGuid(); // Create a new User. User user = new User(); // Set the user session properties. user.LastRequest = DateTime.Now; user.Rotation = -Math.PI; // Generate a single-use challenge key. user.Challenge = "123"; // Add the session to the users. lock (users) users.Add(key, user); Hashtable hash = new Hashtable(); // Set up the template with useful details and the challenge and public key. hash.Add("STATIC_ROOT", deviMobile.STATIC_ROOT); hash.Add("SESSION_ID", key.ToString("D")); hash.Add("CHALLENGE", user.Challenge); // Make the grid list, ensuring the default one is selected. string grids = ""; foreach (string server in deviMobile.LOGIN_SERVERS.Keys) { grids += "<option value=\"" + System.Web.HttpUtility.HtmlAttributeEncode(server) + "\"" + (server == deviMobile.DEFAULT_LOGIN_SERVER ? " selected=\"selected\"" : "") + ">" + System.Web.HttpUtility.HtmlEncode(server) + "</option>\n"; } hash.Add("GRID_OPTIONS", grids); if (deviMobile.HANDLE_CONTENT_ENCODING) { hash.Add("ENCODING", "identity"); // S3 doesn't support Accept-Encoding, so we do it ourselves. if (request.Headers["Accept-Encoding"] != null) { string[] accept = request.Headers["Accept-Encoding"].Split(','); foreach (string encoding in accept) { string parsedencoding = encoding.Split(';')[0].Trim(); if (parsedencoding == "gzip" || parsedencoding == "*") // Should we really honour "*"? Specs aside, it's never going to be true. { hash["ENCODING"] = "gzip"; break; } } } } // Parse the template. Html.Template.Parser parser = new Html.Template.Parser(hash); writer.Write(parser.Parse(File.ReadAllText("Html/Templates/index.html"))); } catch (Exception exception) { this.contenttype = "text/plain"; writer.WriteLine("Error: " + exception.Message); } writer.Flush(); }
// /blink1/pattern/add -- Add color pattern to color pattern list static string Ublink1PatternAdd(HttpRequest request, Blink1Server blink1Server) { string pname = request.Query.Get("pname"); string patternstr = request.Query.Get("pattern"); string statusstr = "pattern add"; Blink1Pattern pattern = null; if (pname != null && patternstr != null) { pattern = new Blink1Pattern(pname); Boolean goodpattern = pattern.parsePatternStr(patternstr); if (goodpattern) { blink1Server.patterns[pname] = pattern; // NOTE: this replaces pattern if already exists } else { statusstr = "error: pattern badly formatted"; } } else { statusstr = "error: need 'pname' and 'pattern' (e.g. '2,#ff00ff,0.5,#00ff00,0.5') argument"; } blink1Server.saveSettings(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", statusstr); result.Add("pattern", pattern); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
// /blink1/input/ifttt -- Add and Start watching messages from IFTTT webservice static string Ublink1InputIfttt(HttpRequest request, Blink1Server blink1Server) { string pname = request.Query.Get("pname"); string iname = request.Query.Get("iname"); string rulename = request.Query.Get("arg1"); string test = request.Query.Get("test"); if (pname == null) pname = iname; Boolean testmode = (test == null) ? false : (test.Equals("on") || test.Equals("true")); string statusstr = "must specifiy 'iname' and 'arg1' (rulename)"; Blink1Input input = null; if (rulename != null && iname != null) { statusstr = "input ifttt"; rulename = rulename.Trim(); input = new Blink1Input(blink1Server, iname, pname, "ifttt", rulename); if (testmode) { // override periodic fetch for immediate fetch Blink1Input.getIftttResponse(false); } input.updateIftttInput(); if (!testmode) { blink1Server.inputs[iname] = input; // NOTE: this replaces input if already exists } } blink1Server.saveSettings(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", statusstr); result.Add("input", input); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); try { StreamReader reader = new StreamReader(request.PostData); string post = reader.ReadToEnd(); reader.Dispose(); // Decode the POST data. Dictionary<string,string> POST = deviMobile.PostDecode(post); Guid session = new Guid(POST["sid"]); Events eventqueue; User user; GridClient client; // Load in the session data. lock (users) { user = users[session]; eventqueue = user.Events; client = user.Client; user.LastRequest = DateTime.Now; } bool sent = false; double heading = user.Rotation; // Check once per second, timing out after 15 seconds. for (int i = 0; i < 5; ++i) { // Ugly hack - we're riding on the back of the event poll to rotate our camera. if(user.Rotation != -4) { // If we've reached π, having started at -π, we're done. Quit rotating, because it // appears to annoy people and/or make them dizzy. heading += 0.5d; if (heading > Math.PI) { // We use -4 because -4 < -π, so will never occur during normal operation. user.Rotation = -4; heading = Math.PI; // Reset the draw distance to attempt to reduce traffic. Also limits the // nearby list to people within chat range. user.Client.Self.Movement.Camera.Far = 20.0f; user.Client.Self.Movement.SendUpdate(); } else { user.Rotation = heading; } client.Self.Movement.UpdateFromHeading(heading, false); } if (eventqueue.GetEventCount() > 0) { writer.WriteLine(eventqueue.GetPendingJson(client)); sent = true; break; } else { System.Threading.Thread.Sleep(1000); } } // If nothing of interest ever came up, we just send the standard footer. if (!sent) { JsonWriter w = new JsonWriter(writer); w.WriteStartArray(); (new JsonSerializer()).Serialize(w, eventqueue.GetFooter(client)); w.WriteEndArray(); w.Flush(); } } catch (Exception e) { request.Response.ContentType = "text/plain"; writer.WriteLine(e.Message); } writer.Flush(); }
public void OnFileRequested(HttpRequest request, IDirectory directory) { request.Response.ResponseContent = new MemoryStream(); StreamWriter writer = new StreamWriter(request.Response.ResponseContent); try{ Hashtable hash = new Hashtable(); // Set up the template with useful details and the challenge and public key. hash.Add("STATIC_ROOT", AjaxLife.STATIC_ROOT); if (AjaxLife.HANDLE_CONTENT_ENCODING) { hash.Add("ENCODING", "identity"); // S3 doesn't support Accept-Encoding, so we do it ourselves. if (request.Headers["Accept-Encoding"] != null) { string[] accept = request.Headers["Accept-Encoding"].Split(','); foreach (string encoding in accept) { string parsedencoding = encoding.Split(';')[0].Trim(); if (parsedencoding == "gzip" || parsedencoding == "*") // Should we really honour "*"? Specs aside, it's never going to be true. { hash["ENCODING"] = "gzip"; break; } } } } Html.Template.Parser parser = new Html.Template.Parser(hash); writer.Write(parser.Parse(File.ReadAllText("Html/Templates/index.html"))); }catch(Exception exception){ this.contenttype = "text/plain"; writer.WriteLine("Error: " + exception.Message); } writer.Flush(); }
// --------------------------------------------------------------------------- // inputs // // /blink1/input/ -- List configured inputs, enable or disable input watching static string Ublink1Input(HttpRequest request, Blink1Server blink1Server) { string enabled = request.Query.Get("enabled"); if (enabled != null) { blink1Server.inputsEnable = (enabled.Equals("on") || enabled.Equals("true")); } Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", "input results"); result.Add("enabled", blink1Server.inputsEnable); result.Add("inputs", blink1Server.inputs.Values); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
// /blink1/pattern/stopall -- Stop all pattern playback static string Ublink1PatternStopAll(HttpRequest request, Blink1Server blink1Server) { blink1Server.stopAllPatterns(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", "all patterns stopped"); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
// /blink1/pattern/stop -- Stop a pattern playback for a given pattern static string Ublink1PatternStop(HttpRequest request, Blink1Server blink1Server) { string pname = request.Query.Get("pname"); string statusstr = "no pattern by that name"; if (pname != null) { Blink1Pattern patt = null; if (blink1Server.patterns.TryGetValue(pname, out patt)) { patt.stop(); statusstr = "pattern '" + pname + "' stopped"; } } Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", statusstr); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
internal HttpResponse(HttpRequest request) { this.request = request; outputStream = request.Client.stream; }
// /blink1/input/delall -- Remove all configured inputs static string Ublink1InputDelAll(HttpRequest request, Blink1Server blink1Server) { foreach (KeyValuePair<string, Blink1Input> kvp in blink1Server.inputs) { kvp.Value.stop(); } blink1Server.inputs.Clear(); blink1Server.saveSettings(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", "all patterns removed"); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
// /blink1/input/del -- Remove a configured input static string Ublink1InputDel(HttpRequest request, Blink1Server blink1Server) { string iname = request.Query.Get("iname"); string statusstr = "no input by that name"; Blink1Input input = null; if (iname != null) { if (blink1Server.inputs.TryGetValue(iname, out input)) { input.stop(); blink1Server.inputs.Remove(iname); statusstr = "input '" + iname + "' removed"; } } blink1Server.saveSettings(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", statusstr); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }
// /blink1/input/script -- Add and Start command-line script executer static string Ublink1InputScript(HttpRequest request, Blink1Server blink1Server) { string pname = request.Query.Get("pname"); string iname = request.Query.Get("iname"); string fpath = request.Query.Get("arg1").Trim(); string test = request.Query.Get("test"); if (pname == null) pname = iname; Boolean testmode = (test == null) ? false : (test.Equals("on") || test.Equals("true")); string statusstr = "must specifiy 'iname' and 'arg1' (script filepath)"; Blink1Input input = null; if (fpath != null && iname != null) { statusstr = "input script"; input = new Blink1Input(blink1Server, iname, pname, "script", fpath); input.updateScriptInput(); if (!testmode) { blink1Server.inputs[iname] = input; // NOTE: this replaces input if already exists } } blink1Server.saveSettings(); Dictionary<string, object> result = new Dictionary<string, object>(); result.Add("status", statusstr); result.Add("input", input); return JsonConvert.SerializeObject(result, Formatting.Indented, jsonSerializerSettings); }