public string Fetch(FetchParams fp) { if (File.Exists("/var/www/html/nodemap.json")) { Log.Instance.Write("Fetching from text file"); return(File.ReadAllText("/var/www/html/nodemap.json")); } ulong limit = fp.Time - (86400 * fp.Limit); StringBuilder sb = new StringBuilder(); sb.AppendLine("["); SubmitParams[] n = nodeMap.Values.ToArray(); for (int i = 0; i < n.Length; i++) { if (n[i].LastAccessTime >= limit) { if (i < n.Length - 1) { sb.AppendLine(NodeMapEntryToJson(n[i]) + ","); } else { sb.AppendLine(NodeMapEntryToJson(n[i])); } } } sb.AppendLine("]"); return(sb.ToString()); }
private void HandleRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; response.ContentType = "application/json"; string text; using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { text = reader.ReadToEnd(); } string method = request.Url.Segments[1]; dynamic json = JObject.Parse(text); Log.Instance.Write($"Received new request: {json.method}"); switch (json.method.Value) { case "submit": { SubmitParams sp = JsonConvert.DeserializeObject <RpcRequest <SubmitParams> >(text).Params; bool ne = false; bool ok = dataStore.Add(sp, out ne); if (ok) { if (ne) { MapDataChanged?.Invoke(); } } string result = ok ? RESULT_OK : RESULT_BAD; response.OutputStream.Write(Encoding.ASCII.GetBytes(result)); context.Response.Close(); } break; case "fetch": { FetchParams fp = JsonConvert.DeserializeObject <RpcRequest <FetchParams> >(text).Params; response.OutputStream.Write(Encoding.ASCII.GetBytes(dataStore.Fetch(fp))); context.Response.Close(); } break; case "prune": { PruneParams pp = JsonConvert.DeserializeObject <RpcRequest <PruneParams> >(text).Params; if (string.IsNullOrEmpty(pp.Key)) { Log.Instance.Write(Log_Severity.Warning, "No access key provided"); return; } if (!Config.AllowedKeys.Contains(pp.Key)) { Log.Instance.Write(Log_Severity.Warning, "Invalid access key"); return; } int pc = 0; bool ok = dataStore.Prune(pp, out pc); if (ok && !pp.DryRun) { if (pc > 0) { MapDataChanged?.Invoke(); } } string result = ok ? RESULT_OK : RESULT_BAD; response.OutputStream.Write(Encoding.ASCII.GetBytes(result)); context.Response.Close(); } break; case "save": { Task.Run(() => { new ObjectSerializer().Serialize(dataStore, "NodeMap.xml"); Log.Instance.Write("Node map data saved"); Log.Instance.Write("Saving node map data to json"); File.WriteAllText("/var/www/html/nodemap.json", $"{{\"status\":\"OK\",\"result\":{dataStore.FetchAll()}}}\r\n"); }); } break; default: Log.Instance.Write($"Invalid request: {json.Method}"); break; } }