| 1 | #include "mtx/responses/media.hpp" |
| 2 | |
| 3 | #include <nlohmann/json.hpp> |
| 4 | #include <type_traits> |
| 5 | |
| 6 | using json = nlohmann::json; |
| 7 | |
| 8 | namespace mtx { |
| 9 | namespace responses { |
| 10 | |
| 11 | void |
| 12 | from_json(const json &obj, ContentURI &res) |
| 13 | { |
| 14 | res.content_uri = obj.at("content_uri").get<std::string>(); |
| 15 | } |
| 16 | |
| 17 | template<typename T> |
| 18 | static void |
| 19 | extractOptionalAttribute(const json &obj, const char *name, std::optional<T> &out) |
| 20 | { |
| 21 | if (obj.contains(name)) { |
| 22 | const auto &field = obj.at(name); |
| 23 | // Matrix's OpenGraph proxying does not standardize numbers to be actual json numbers, they |
| 24 | // can be (and, at least on synapse, sometimes are) strings |
| 25 | if constexpr (std::is_same_v<T, std::int32_t>) { |
| 26 | if (field.type() == json::value_t::string) { |
| 27 | out = static_cast<T>(std::stol(field.get<std::string>())); |
| 28 | return; |
| 29 | } |
| 30 | } |
| 31 | out = field.get<T>(); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | void |
| 36 | from_json(const json &obj, URLPreview &res) |
| 37 | { |
| 38 | res.title = obj.at("og:title").get<std::string>(); |
| 39 | res.url = obj.at("og:url").get<std::string>(); |
| 40 | extractOptionalAttribute(obj, "og:site_name", res.site_name); |
| 41 | extractOptionalAttribute(obj, "og:description", res.description); |
| 42 | |
| 43 | extractOptionalAttribute(obj, "og:image:type", res.image.type); |
| 44 | extractOptionalAttribute(obj, "og:image:width", res.image.width); |
| 45 | extractOptionalAttribute(obj, "og:image:height", res.image.height); |
| 46 | extractOptionalAttribute(obj, "og:image:alt", res.image.alt); |
| 47 | |
| 48 | res.image.size = obj.at("matrix:image:size").get<std::uint64_t>(); |
| 49 | res.image.url = obj.at("og:image").get<std::string>(); |
| 50 | } |
| 51 | } |
| 52 | } |