diff --git a/include/instance.hpp b/include/instance.hpp index 7b90c84..527483f 100644 --- a/include/instance.hpp +++ b/include/instance.hpp @@ -24,6 +24,7 @@ #include #include #include +#include namespace mastodonpp { @@ -32,6 +33,7 @@ using std::uint64_t; using std::string; using std::string_view; using std::move; +using std::vector; /*! * @brief Holds the access data of an instance. @@ -151,12 +153,26 @@ public: [[nodiscard]] answer_type get_nodeinfo(); + /*! + * @brief Returns the allowed mime types for statuses. + * + * Extracts `metadata.postFormats` from NodeInfo. If none can be found, + * returns `{"text/plain"}`. + * + * After the first call, the value is saved internally. Subsequent calls + * return the saved value. + * + * @since 0.3.0 + */ + vector get_post_formats(); + private: const string _hostname; const string _baseuri; string _access_token; uint64_t _max_chars; string _proxy; + vector _post_formats; }; } // namespace mastodonpp diff --git a/src/instance.cpp b/src/instance.cpp index 1c7491c..f80e430 100644 --- a/src/instance.cpp +++ b/src/instance.cpp @@ -20,7 +20,6 @@ #include #include -#include namespace mastodonpp { @@ -28,7 +27,6 @@ namespace mastodonpp using std::sort; using std::stoull; using std::exception; -using std::vector; Instance::Instance(const string_view hostname, const string_view access_token) : _hostname{hostname} @@ -108,4 +106,45 @@ answer_type Instance::get_nodeinfo() return make_request(http_method::GET, hrefs.back(), {}); } +vector Instance::get_post_formats() +{ + constexpr auto default_value{"text/plain"}; + + if (!_post_formats.empty()) + { + return _post_formats; + } + + debuglog << "Querying " << _hostname << " for postFormats…\n"; + const auto answer{get_nodeinfo()}; + if (!answer) + { + debuglog << "Couldn't get NodeInfo.\n"; + _post_formats = {default_value}; + return _post_formats; + } + + constexpr string_view searchstring{R"("postFormats":[)"}; + auto pos{answer.body.find(searchstring)}; + if (pos == string::npos) + { + debuglog << "Couldn't find metadata.postFormats.\n"; + _post_formats = {default_value}; + return _post_formats; + } + pos += searchstring.size(); + auto endpos{answer.body.find("],", pos)}; + string formats{answer.body.substr(pos, endpos - pos)}; + debuglog << "Extracted postFormats: " << formats << '\n'; + + while ((pos = formats.find('"', 1)) != string::npos) + { + _post_formats.push_back(formats.substr(1, pos - 1)); + formats.erase(0, pos + 2); // 2 is the length of: ", + debuglog << "Found postFormat: " << _post_formats.back() << '\n'; + } + + return _post_formats; +} + } // namespace mastodonpp