From a53140890d1a4686eefebef7e11b5a0f4a45da07 Mon Sep 17 00:00:00 2001 From: DankParrot Date: Fri, 31 Jul 2020 17:56:35 -0700 Subject: [PATCH] Implement ServerStatus with rapidjson --- src/ServerStatus.h | 63 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/src/ServerStatus.h b/src/ServerStatus.h index 2fa8c91..9f50569 100644 --- a/src/ServerStatus.h +++ b/src/ServerStatus.h @@ -1,15 +1,18 @@ #pragma once -#include -#include +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" -using string = std::string; -using stringstream = std::stringstream; +#include namespace Feather { class ServerStatus { + using string = std::string; + string cachedJSON; + public: // Version string versionName = "1.16.1"; @@ -22,17 +25,51 @@ namespace Feather // Description string descriptionText = ""; - string GetServerStatusJSON() + const string &GetServerStatusJSON(bool forceUpdate = false) { - // TODO: PLACEHOLDER for real JSON - stringstream j; - j << "{"; - j << "\"version\":{\"name\":\"" << versionName << "\",\"protocol\":" << protocol << "},"; - j << "\"players\":{\"max\":" << maxPlayers << ",\"online\":" << numPlayers << ",\"sample\":[]},"; - j << "\"description\": {\"text\":\"" << descriptionText << "\"}"; - j << "}"; + using namespace rapidjson; - return j.str(); + if (cachedJSON.length() > 0 && !forceUpdate) return cachedJSON; + + Document doc; + doc.SetObject(); + + auto &alloc = doc.GetAllocator(); + + Value version(kObjectType); + { + Value name; + name.SetString(versionName.c_str(), versionName.length()); + version.AddMember("name", name, alloc); + version.AddMember("protocol", protocol, alloc); + } + doc.AddMember("version", version, alloc); + + Value players(kObjectType); + { + players.AddMember("max", maxPlayers, alloc); + players.AddMember("online", numPlayers, alloc); + Value sample(kArrayType); + players.AddMember("sample", sample, alloc); + } + doc.AddMember("players", players, alloc); + + // TODO: use chat object + Value description(kObjectType); + { + Value text; + text.SetString(descriptionText.c_str(), descriptionText.length()); + description.AddMember("text", text, alloc); + } + doc.AddMember("description", description, alloc); + + StringBuffer buf; + Writer writer(buf); + doc.Accept(writer); + + cachedJSON.assign(buf.GetString(), buf.GetLength()); + + return cachedJSON; } }; }