nheko/src/timeline/ReactionsModel.cpp

99 lines
3.2 KiB
C++
Raw Normal View History

2020-05-04 13:14:54 +02:00
#include "ReactionsModel.h"
2020-05-06 11:28:24 +02:00
#include <Cache.h>
2020-05-04 13:14:54 +02:00
#include <MatrixClient.h>
QHash<int, QByteArray>
ReactionsModel::roleNames() const
{
return {
{Key, "key"},
{Count, "counter"},
{Users, "users"},
{SelfReactedEvent, "selfReactedEvent"},
2020-05-04 13:14:54 +02:00
};
}
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;
2020-05-06 13:45:38 +02:00
for (const auto &reaction : reactions[i].reactions) {
2020-05-06 11:15:45 +02:00
if (!first)
2020-05-04 13:14:54 +02:00
users += ", ";
2020-05-06 11:15:45 +02:00
else
first = false;
2020-05-06 13:45:38 +02:00
users += QString::fromStdString(
cache::displayName(room_id_, reaction.second.sender));
2020-05-04 13:14:54 +02:00
}
return users;
}
case SelfReactedEvent:
2020-05-04 13:14:54 +02:00
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())
return QString::fromStdString(reaction.second.event_id);
return QStringLiteral("");
2020-05-04 13:14:54 +02:00
default:
return {};
}
}
void
2020-05-06 11:28:24 +02:00
ReactionsModel::addReaction(const std::string &room_id,
const mtx::events::RoomEvent<mtx::events::msg::Reaction> &reaction)
2020-05-04 13:14:54 +02:00
{
2020-05-06 11:28:24 +02:00
room_id_ = room_id;
2020-05-04 13:14:54 +02:00
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++;
}
}