nheko/src/timeline/ReactionsModel.cpp

96 lines
3.0 KiB
C++
Raw Normal View History

2020-05-04 13:14:54 +02:00
#include "ReactionsModel.h"
#include <MatrixClient.h>
#include "Logging.h"
QHash<int, QByteArray>
ReactionsModel::roleNames() const
{
return {
{Key, "key"},
{Count, "counter"},
{Users, "users"},
{SelfReacted, "selfReacted"},
};
}
int
ReactionsModel::rowCount(const QModelIndex &) const
{
return static_cast<int>(reactions.size());
}
QVariant
ReactionsModel::data(const QModelIndex &index, int role) const
{
const int i = index.row();
if (i < 0 || i >= static_cast<int>(reactions.size()))
return {};
switch (role) {
case Key:
return QString::fromStdString(reactions[i].key);
case Count:
return static_cast<int>(reactions[i].reactions.size());
case Users: {
QString users;
2020-05-06 11:15:45 +02:00
bool first = true;
for (const auto &[event_id, reaction] : reactions[i].reactions) {
if (!first)
2020-05-04 13:14:54 +02:00
users += ", ";
2020-05-06 11:15:45 +02:00
else
first = false;
users += QString::fromStdString(reaction.sender);
2020-05-04 13:14:54 +02:00
}
return users;
}
case SelfReacted:
for (const auto &reaction : reactions[i].reactions)
2020-05-06 11:15:45 +02:00
if (reaction.second.sender == http::client()->user_id().to_string())
2020-05-04 13:14:54 +02:00
return true;
return false;
default:
return {};
}
}
void
ReactionsModel::addReaction(const mtx::events::RoomEvent<mtx::events::msg::Reaction> &reaction)
{
int idx = 0;
for (auto &storedReactions : reactions) {
if (storedReactions.key == reaction.content.relates_to.key) {
2020-05-06 11:15:45 +02:00
storedReactions.reactions[reaction.event_id] = reaction;
2020-05-04 13:14:54 +02:00
emit dataChanged(index(idx, 0), index(idx, 0));
return;
}
idx++;
}
beginInsertRows(QModelIndex(), idx, idx);
2020-05-06 11:15:45 +02:00
reactions.push_back(
KeyReaction{reaction.content.relates_to.key, {{reaction.event_id, reaction}}});
2020-05-04 13:14:54 +02:00
endInsertRows();
}
void
ReactionsModel::removeReaction(const mtx::events::RoomEvent<mtx::events::msg::Reaction> &reaction)
{
int idx = 0;
for (auto &storedReactions : reactions) {
if (storedReactions.key == reaction.content.relates_to.key) {
2020-05-06 11:15:45 +02:00
storedReactions.reactions.erase(reaction.event_id);
2020-05-04 13:14:54 +02:00
if (storedReactions.reactions.size() == 0) {
beginRemoveRows(QModelIndex(), idx, idx);
reactions.erase(reactions.begin() + idx);
endRemoveRows();
} else
emit dataChanged(index(idx, 0), index(idx, 0));
return;
}
idx++;
}
}