Add Instance::get_post_formats().
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
tastytea 2020-01-11 20:05:11 +01:00
parent b9bf28c264
commit a6b328c2d1
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 57 additions and 2 deletions

View File

@ -24,6 +24,7 @@
#include <string>
#include <string_view>
#include <utility>
#include <vector>
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<string> get_post_formats();
private:
const string _hostname;
const string _baseuri;
string _access_token;
uint64_t _max_chars;
string _proxy;
vector<string> _post_formats;
};
} // namespace mastodonpp

View File

@ -20,7 +20,6 @@
#include <algorithm>
#include <exception>
#include <vector>
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<string> 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