| 1 | #include "mtx/events/spaces.hpp" |
|---|---|
| 2 | |
| 3 | #include <string> |
| 4 | |
| 5 | #include <nlohmann/json.hpp> |
| 6 | |
| 7 | namespace mtx { |
| 8 | namespace events { |
| 9 | namespace state { |
| 10 | namespace space { |
| 11 | |
| 12 | void |
| 13 | from_json(const nlohmann::json &obj, Parent &parent) |
| 14 | { |
| 15 | if (obj.contains(key: "canonical") && obj.at(key: "canonical").is_boolean()) |
| 16 | parent.canonical = obj.at(key: "canonical").get<bool>(); |
| 17 | if (obj.contains(key: "via") && obj.at(key: "via").is_array() && !obj.at(key: "via").empty()) |
| 18 | parent.via = obj.at(key: "via").get<std::vector<std::string>>(); |
| 19 | } |
| 20 | |
| 21 | void |
| 22 | to_json(nlohmann::json &obj, const Parent &parent) |
| 23 | { |
| 24 | obj = nlohmann::json::object(); |
| 25 | |
| 26 | // event without via is invalid. |
| 27 | if (!parent.via.has_value() || parent.via.value().empty()) |
| 28 | return; |
| 29 | |
| 30 | obj["via"] = parent.via.value(); |
| 31 | |
| 32 | if (parent.canonical) |
| 33 | obj["canonical"] = true; |
| 34 | } |
| 35 | |
| 36 | static bool |
| 37 | is_valid_order_str(std::string_view order) |
| 38 | { |
| 39 | if (order.size() > 50) |
| 40 | return false; |
| 41 | |
| 42 | for (auto c : order) |
| 43 | if (c < '\x20' || c > '\x7E') |
| 44 | return false; |
| 45 | |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | void |
| 50 | from_json(const nlohmann::json &obj, Child &child) |
| 51 | { |
| 52 | if (obj.contains(key: "via") && obj.at(key: "via").is_array() && !obj.at(key: "via").empty()) |
| 53 | child.via = obj.at(key: "via").get<std::vector<std::string>>(); |
| 54 | |
| 55 | if (obj.contains(key: "order") && obj.at(key: "order").is_string() && |
| 56 | is_valid_order_str(order: obj.at(key: "order").get<std::string>())) |
| 57 | child.order = obj.at(key: "order").get<std::string>(); |
| 58 | |
| 59 | child.suggested = obj.value(key: "suggested", default_value: false); |
| 60 | } |
| 61 | |
| 62 | void |
| 63 | to_json(nlohmann::json &obj, const Child &child) |
| 64 | { |
| 65 | obj = nlohmann::json::object(); |
| 66 | |
| 67 | // event without via is invalid. |
| 68 | if (!child.via.has_value() || child.via.value().empty()) |
| 69 | return; |
| 70 | |
| 71 | obj["via"] = child.via.value(); |
| 72 | |
| 73 | if (child.order && is_valid_order_str(order: child.order.value())) |
| 74 | obj["order"] = child.order.value(); |
| 75 | |
| 76 | if (child.suggested) |
| 77 | obj["suggested"] = true; |
| 78 | } |
| 79 | } |
| 80 | } // namespace state |
| 81 | } // namespace events |
| 82 | } // namespace mtx |
| 83 |