Query max_toot_chars the first time get_max_chars() is called.

This commit is contained in:
tastytea 2020-01-06 09:31:05 +01:00
parent 6663cca653
commit 0638f8fe9a
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 39 additions and 31 deletions

View File

@ -94,10 +94,7 @@ public:
* @since 0.1.0
*/
[[nodiscard]]
inline uint64_t get_max_chars() const
{
return _max_chars;
}
uint64_t get_max_chars();
private:
const string _hostname;

View File

@ -27,40 +27,51 @@ Instance::Instance(const string_view &hostname, const string_view &access_token)
: _hostname{hostname}
, _baseuri{"https://" + _hostname}
, _access_token{access_token}
, _max_chars{500}
, _max_chars{0}
{}
uint64_t Instance::get_max_chars()
{
try
{
debuglog << "Querying " << _hostname << " for max_toot_chars…\n";
const auto answer{make_request(http_method::GET,
_baseuri + "/api/v1/instance")};
if (!answer)
{
return;
}
constexpr uint64_t default_max_chars{500};
_max_chars = [&answer]
if (_max_chars == 0)
{
try
{
auto &body{answer.body};
size_t pos_start{body.find("max_toot_chars")};
if (pos_start == string::npos)
debuglog << "Querying " << _hostname << " for max_toot_chars…\n";
const auto answer{make_request(http_method::GET,
_baseuri + "/api/v1/instance")};
if (!answer)
{
debuglog << "max_toot_chars not found.\n";
return static_cast<uint64_t>(500);
debuglog << "Could not get instance info.\n";
return default_max_chars;
}
pos_start = body.find(':', pos_start) + 1;
const size_t pos_end{body.find(',', pos_start)};
const auto max_toot_chars{body.substr(pos_start,
pos_end - pos_start)};
return static_cast<uint64_t>(stoull(max_toot_chars));
}();
debuglog << "Set _max_chars to: " << _max_chars << '\n';
}
catch (const std::exception &e)
{
debuglog << "Unexpected exception: " << e.what() << '\n';
_max_chars = [&answer]
{
auto &body{answer.body};
size_t pos_start{body.find("max_toot_chars")};
if (pos_start == string::npos)
{
debuglog << "max_toot_chars not found.\n";
return default_max_chars;
}
pos_start = body.find(':', pos_start) + 1;
const size_t pos_end{body.find(',', pos_start)};
const auto max_toot_chars{body.substr(pos_start,
pos_end - pos_start)};
return static_cast<uint64_t>(stoull(max_toot_chars));
}();
debuglog << "Set _max_chars to: " << _max_chars << '\n';
}
catch (const std::exception &e)
{
debuglog << "Unexpected exception: " << e.what() << '\n';
}
}
return _max_chars;
}
} // namespace mastodonpp