mc-server-manager/shared-utils/source/shared_utils/server_status.d

99 lines
3.2 KiB
D
Raw Normal View History

module shared_utils.server_status;
import std.json;
import std.algorithm;
import std.array;
/**
* A struct containing basic information about a single Minecraft server.
*/
struct ServerStatus {
/// A unique identifier for the server, defined by the agent's "servers.json" file.
const string identifier = null;
/// The human-readable name of the server.
const string name = null;
/// A description for the server.
const string description = null;
/// Whether the server is online.
const bool online = false;
/// The number of players online.
const int playersOnline = 0;
/// The maximum number of players that the server allows.
const int maxPlayers = 0;
/// A list of names of all players that are online.
const string[] playerNames = [];
/**
* Converts this status to a JSON object.
* Returns: The JSON object.
*/
JSONValue toJsonObject() const {
JSONValue obj = JSONValue.emptyObject;
obj.object["identifier"] = JSONValue(identifier);
obj.object["name"] = JSONValue(name);
obj.object["description"] = JSONValue(description);
obj.object["online"] = JSONValue(online);
obj.object["playersOnline"] = JSONValue(playersOnline);
obj.object["maxPlayers"] = JSONValue(maxPlayers);
obj.object["playerNames"] = JSONValue.emptyArray;
foreach (playerName; playerNames) {
obj.object["playerNames"].array ~= JSONValue(playerName);
}
return obj;
}
/**
* Converts this status to a JSON string.
* Returns: The JSON string.
*/
string toJsonString() const {
JSONValue obj = toJsonObject();
return obj.toJSON();
}
/**
* Parses a status from a JSON object. Throws a JSONException in case of
* errors in the provided data.
* Params:
* obj = The JSON object.
* Returns: The server status.
*/
static ServerStatus fromJsonObject(JSONValue obj) {
if (obj.type != JSONType.OBJECT) throw new JSONException("JSON value is not an object.");
return ServerStatus(
obj.object["identifier"].str,
obj.object["name"].str,
obj.object["description"].str,
obj.object["online"].boolean,
cast(int) obj.object["playersOnline"].integer,
cast(int) obj.object["maxPlayers"].integer,
obj.object["playerNames"].array().map!(node => node.str).array
);
}
}
/**
* Serializes a list of server statuses into a single JSON array.
* Params:
* statuses = The statuses to serialize.
* Returns: The JSON array.
*/
JSONValue serializeServerStatuses(in ServerStatus[] statuses) {
JSONValue arr = JSONValue.emptyArray;
foreach (s; statuses) {
arr.array ~= s.toJsonObject();
}
return arr;
}
/**
* Deserializes a list of server statuses from a JSON array.
* Params:
* arr = The JSON array.
* Returns: The list of server statuses.
*/
ServerStatus[] deserializeServerStatuses(in JSONValue arr) {
if (arr.type != JSONType.ARRAY) throw new JSONException("JSON value is not an array.");
return arr.array().map!(obj => ServerStatus.fromJsonObject(obj)).array;
}