Make "recent_messages" network request safe in case the channel is closed when the request finished

This commit is contained in:
Rasmus Karlsson 2018-10-13 14:45:51 +02:00
parent b5c7c8ff26
commit 1422201570

View file

@ -29,8 +29,7 @@
namespace chatterino { namespace chatterino {
namespace { namespace {
auto parseRecentMessages(const QJsonObject &jsonRoot, auto parseRecentMessages(const QJsonObject &jsonRoot, ChannelPtr channel)
TwitchChannel &channel)
{ {
QJsonArray jsonMessages = jsonRoot.value("messages").toArray(); QJsonArray jsonMessages = jsonRoot.value("messages").toArray();
std::vector<MessagePtr> messages; std::vector<MessagePtr> messages;
@ -46,7 +45,7 @@ namespace {
assert(privMsg); assert(privMsg);
MessageParseArgs args; MessageParseArgs args;
TwitchMessageBuilder builder(&channel, privMsg, args); TwitchMessageBuilder builder(channel.get(), privMsg, args);
if (!builder.isIgnored()) { if (!builder.isIgnored()) {
messages.push_back(builder.build()); messages.push_back(builder.build());
} }
@ -546,13 +545,13 @@ void TwitchChannel::loadRecentMessages()
// can't be concurrent right now due to SignalVector // can't be concurrent right now due to SignalVector
// request.setExecuteConcurrently(true); // request.setExecuteConcurrently(true);
request.onSuccess([that = this](auto result) -> Outcome { request.onSuccess([weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto messages = parseRecentMessages(result.parseJson(), *that); auto shared = weak.lock();
if (!shared) return Failure;
// postToThread([that, weak = weakOf<Channel>(that), auto messages = parseRecentMessages(result.parseJson(), shared);
// messages = std::move(messages)]() mutable {
that->addMessagesAtStart(messages); shared->addMessagesAtStart(messages);
// });
return Success; return Success;
}); });