Spectral/src/messageeventmodel.cpp

378 lines
13 KiB
C++
Raw Normal View History

2018-03-05 11:12:13 +00:00
#include "messageeventmodel.h"
#include <connection.h>
#include <settings.h>
#include <user.h>
#include <events/redactionevent.h>
#include <events/roomavatarevent.h>
#include <events/roommemberevent.h>
#include <events/simplestateevents.h>
2018-09-24 12:52:24 +00:00
#include <QRegExp>
#include <QtCore/QDebug>
#include <QtQml> // for qmlRegisterType()
2018-03-05 11:12:13 +00:00
#include "utils.h"
2018-09-26 23:37:09 +00:00
static QString parseAvatarUrl(QUrl url) {
return url.host() + "/" + url.path();
}
QHash<int, QByteArray> MessageEventModel::roleNames() const {
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[EventTypeRole] = "eventType";
2018-09-17 03:58:02 +00:00
roles[MessageRole] = "message";
roles[AboveEventTypeRole] = "aboveEventType";
roles[EventIdRole] = "eventId";
roles[TimeRole] = "time";
roles[AboveTimeRole] = "aboveTime";
roles[SectionRole] = "section";
roles[AboveSectionRole] = "aboveSection";
roles[AuthorRole] = "author";
roles[AboveAuthorRole] = "aboveAuthor";
roles[ContentRole] = "content";
roles[ContentTypeRole] = "contentType";
2018-08-05 16:53:22 +00:00
roles[HighlightRole] = "highlight";
roles[ReadMarkerRole] = "readMarker";
roles[SpecialMarksRole] = "marks";
roles[LongOperationRole] = "progressInfo";
2018-08-05 16:53:22 +00:00
roles[AnnotationRole] = "annotation";
roles[EventResolvedTypeRole] = "eventResolvedType";
2018-09-13 05:05:51 +00:00
roles[UserMarkerRole] = "userMarker";
return roles;
}
2018-03-15 09:10:27 +00:00
MessageEventModel::MessageEventModel(QObject *parent)
: QAbstractListModel(parent), m_currentRoom(nullptr) {
2018-08-05 16:53:22 +00:00
using namespace QMatrixClient;
qmlRegisterType<FileTransferInfo>();
qRegisterMetaType<FileTransferInfo>();
qmlRegisterUncreatableType<EventStatus>(
"Spectral", 0, 1, "EventStatus", "EventStatus is not an creatable type");
2018-03-05 11:12:13 +00:00
}
2018-08-17 04:55:57 +00:00
MessageEventModel::~MessageEventModel() {}
void MessageEventModel::setRoom(SpectralRoom *room) {
2018-07-09 02:45:26 +00:00
if (room == m_currentRoom) return;
beginResetModel();
if (m_currentRoom) {
m_currentRoom->disconnect(this);
}
m_currentRoom = room;
if (room) {
lastReadEventId = room->readMarkerEventId();
2018-08-05 16:53:22 +00:00
2018-07-09 02:45:26 +00:00
using namespace QMatrixClient;
connect(m_currentRoom, &Room::aboutToAddNewMessages, this,
[=](RoomEventsRange events) {
beginInsertRows({}, timelineBaseIndex(),
timelineBaseIndex() + int(events.size()) - 1);
2018-07-09 02:45:26 +00:00
});
connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this,
[=](RoomEventsRange events) {
2018-08-05 16:53:22 +00:00
if (rowCount() > 0)
rowBelowInserted = rowCount() - 1; // See #312
beginInsertRows({}, rowCount(),
2018-07-09 02:45:26 +00:00
rowCount() + int(events.size()) - 1);
});
connect(m_currentRoom, &Room::addedMessages, this,
[=](int lowest, int biggest) {
endInsertRows();
if (biggest < m_currentRoom->maxTimelineIndex()) {
auto rowBelowInserted = m_currentRoom->maxTimelineIndex() -
biggest + timelineBaseIndex() - 1;
refreshEventRoles(rowBelowInserted,
{AboveEventTypeRole, AboveAuthorRole,
AboveSectionRole, AboveTimeRole});
}
});
connect(m_currentRoom, &Room::pendingEventAboutToAdd, this,
[this] { beginInsertRows({}, 0, 0); });
connect(m_currentRoom, &Room::pendingEventAdded, this,
&MessageEventModel::endInsertRows);
connect(m_currentRoom, &Room::pendingEventAboutToMerge, this,
[this](RoomEvent *, int i) {
2018-08-05 16:53:22 +00:00
if (i == 0) return; // No need to move anything, just refresh
movingEvent = true;
// Reverse i because row 0 is bottommost in the model
const auto row = timelineBaseIndex() - i - 1;
Q_ASSERT(beginMoveRows({}, row, row, {}, timelineBaseIndex()));
});
connect(m_currentRoom, &Room::pendingEventMerged, this, [this] {
2018-08-05 16:53:22 +00:00
if (movingEvent) {
endMoveRows();
2018-08-05 16:53:22 +00:00
movingEvent = false;
}
refreshRow(timelineBaseIndex()); // Refresh the looks
2018-08-05 16:53:22 +00:00
if (m_currentRoom->timelineSize() > 1) // Refresh above
refreshEventRoles(timelineBaseIndex() + 1);
2018-08-05 16:53:22 +00:00
if (timelineBaseIndex() > 0) // Refresh below, see #312
refreshEventRoles(timelineBaseIndex() - 1,
{AboveEventTypeRole, AboveAuthorRole,
AboveSectionRole, AboveTimeRole});
});
connect(m_currentRoom, &Room::pendingEventChanged, this,
2018-08-05 16:53:22 +00:00
&MessageEventModel::refreshRow);
connect(m_currentRoom, &Room::pendingEventAboutToDiscard, this,
[this](int i) { beginRemoveRows({}, i, i); });
connect(m_currentRoom, &Room::pendingEventDiscarded, this,
&MessageEventModel::endRemoveRows);
2018-07-09 02:45:26 +00:00
connect(m_currentRoom, &Room::readMarkerMoved, this, [this] {
refreshEventRoles(
2018-08-06 12:13:51 +00:00
std::exchange(lastReadEventId, m_currentRoom->readMarkerEventId()),
{ReadMarkerRole});
refreshEventRoles(lastReadEventId, {ReadMarkerRole});
2018-07-09 02:45:26 +00:00
});
connect(
m_currentRoom, &Room::replacedEvent, this,
[this](const RoomEvent *newEvent) { refreshEvent(newEvent->id()); });
2018-07-09 02:45:26 +00:00
connect(m_currentRoom, &Room::fileTransferProgress, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCompleted, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferFailed, this,
&MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCancelled, this,
&MessageEventModel::refreshEvent);
2018-09-13 05:05:51 +00:00
connect(m_currentRoom, &Room::readMarkerForUserMoved, this,
[=](User *user, QString fromEventId, QString toEventId) {
2018-09-13 05:05:51 +00:00
refreshEventRoles(fromEventId, {UserMarkerRole});
refreshEventRoles(toEventId, {UserMarkerRole});
});
2018-07-09 02:45:26 +00:00
qDebug() << "Connected to room" << room->id() << "as"
<< room->localUser()->id();
} else
lastReadEventId.clear();
endResetModel();
}
int MessageEventModel::refreshEvent(const QString &eventId) {
return refreshEventRoles(eventId);
2018-07-09 02:45:26 +00:00
}
2018-03-05 11:12:13 +00:00
2018-08-05 16:53:22 +00:00
void MessageEventModel::refreshRow(int row) { refreshEventRoles(row); }
int MessageEventModel::timelineBaseIndex() const {
return m_currentRoom ? int(m_currentRoom->pendingEvents().size()) : 0;
}
void MessageEventModel::refreshEventRoles(int row, const QVector<int> &roles) {
const auto idx = index(row);
emit dataChanged(idx, idx, roles);
}
int MessageEventModel::refreshEventRoles(const QString &eventId,
const QVector<int> &roles) {
2018-07-09 02:45:26 +00:00
const auto it = m_currentRoom->findInTimeline(eventId);
2018-08-05 16:53:22 +00:00
if (it == m_currentRoom->timelineEdge()) {
qWarning() << "Trying to refresh inexistent event:" << eventId;
return -1;
2018-08-05 16:53:22 +00:00
}
const auto row =
it - m_currentRoom->messageEvents().rbegin() + timelineBaseIndex();
refreshEventRoles(row, roles);
return row;
2018-03-05 11:12:13 +00:00
}
inline bool hasValidTimestamp(const QMatrixClient::TimelineItem &ti) {
2018-07-09 02:45:26 +00:00
return ti->timestamp().isValid();
2018-03-05 11:12:13 +00:00
}
2018-07-09 02:45:26 +00:00
QDateTime MessageEventModel::makeMessageTimestamp(
const QMatrixClient::Room::rev_iter_t &baseIt) const {
const auto &timeline = m_currentRoom->messageEvents();
2018-07-09 02:45:26 +00:00
auto ts = baseIt->event()->timestamp();
if (ts.isValid()) return ts;
// The event is most likely redacted or just invalid.
// Look for the nearest date around and slap zero time to it.
using QMatrixClient::TimelineItem;
auto rit = std::find_if(baseIt, timeline.rend(), hasValidTimestamp);
if (rit != timeline.rend())
return {rit->event()->timestamp().date(), {0, 0}, Qt::LocalTime};
auto it = std::find_if(baseIt.base(), timeline.end(), hasValidTimestamp);
if (it != timeline.end())
return {it->event()->timestamp().date(), {0, 0}, Qt::LocalTime};
// What kind of room is that?..
qCritical() << "No valid timestamps in the room timeline!";
return {};
2018-03-05 11:12:13 +00:00
}
2018-08-05 16:53:22 +00:00
QString MessageEventModel::renderDate(QDateTime timestamp) const {
auto date = timestamp.toLocalTime().date();
2018-09-30 09:09:58 +00:00
if (date == QDate::currentDate()) return tr("Today");
if (date == QDate::currentDate().addDays(-1)) return tr("Yesterday");
if (date == QDate::currentDate().addDays(-2))
return tr("The day before yesterday");
if (date > QDate::currentDate().addDays(-7)) return date.toString("dddd");
2018-07-09 02:45:26 +00:00
return date.toString(Qt::DefaultLocaleShortDate);
2018-03-05 11:12:13 +00:00
}
int MessageEventModel::rowCount(const QModelIndex &parent) const {
2018-07-09 02:45:26 +00:00
if (!m_currentRoom || parent.isValid()) return 0;
return m_currentRoom->timelineSize();
2018-03-05 11:12:13 +00:00
}
QVariant MessageEventModel::data(const QModelIndex &idx, int role) const {
2018-08-05 16:53:22 +00:00
const auto row = idx.row();
if (!m_currentRoom || row < 0 ||
row >= int(m_currentRoom->pendingEvents().size()) +
m_currentRoom->timelineSize())
return {};
2018-07-09 02:45:26 +00:00
2018-08-05 16:53:22 +00:00
bool isPending = row < timelineBaseIndex();
const auto timelineIt = m_currentRoom->messageEvents().crbegin() +
2018-08-05 16:53:22 +00:00
std::max(0, row - timelineBaseIndex());
const auto pendingIt = m_currentRoom->pendingEvents().crbegin() +
std::min(row, timelineBaseIndex());
const auto &evt = isPending ? **pendingIt : **timelineIt;
2018-07-09 02:45:26 +00:00
if (role == Qt::DisplayRole) {
return utils::eventToString(evt, m_currentRoom, Qt::RichText);
2018-07-09 02:45:26 +00:00
}
2018-09-24 12:52:24 +00:00
if (role == MessageRole) {
static const QRegExp rmReplyRegExp("^> <@.*:.*> .*\n\n(.*)");
return utils::eventToString(evt, m_currentRoom)
.replace(rmReplyRegExp, "\\1");
2018-09-24 12:52:24 +00:00
}
2018-09-17 03:58:02 +00:00
2018-07-09 02:45:26 +00:00
if (role == Qt::ToolTipRole) {
return evt.originalJson();
2018-07-09 02:45:26 +00:00
}
if (role == EventTypeRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
switch (e->msgtype()) {
2018-07-09 02:45:26 +00:00
case MessageEventType::Emote:
return "emote";
case MessageEventType::Notice:
return "notice";
case MessageEventType::Image:
return "image";
2018-08-17 07:58:08 +00:00
case MessageEventType::Audio:
return "audio";
2018-07-09 02:45:26 +00:00
default:
2018-08-05 16:53:22 +00:00
return e->hasFileContent() ? "file" : "message";
2018-07-09 02:45:26 +00:00
}
}
if (evt.isStateEvent()) return "state";
2018-03-05 11:12:13 +00:00
2018-07-09 02:45:26 +00:00
return "other";
}
if (role == EventResolvedTypeRole)
return EventTypeRegistry::getMatrixType(evt.type());
2018-07-09 02:45:26 +00:00
if (role == AuthorRole) {
// FIXME: It shouldn't be User, it should be its state "as of event"
2018-08-05 16:53:22 +00:00
return QVariant::fromValue(isPending ? m_currentRoom->localUser()
: m_currentRoom->user(evt.senderId()));
2018-07-09 02:45:26 +00:00
}
if (role == ContentTypeRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
const auto &contentType = e->mimeType().name();
return contentType == "text/plain" ? QStringLiteral("text/html")
: contentType;
2018-07-09 02:45:26 +00:00
}
return QStringLiteral("text/plain");
2018-07-09 02:45:26 +00:00
}
if (role == ContentRole) {
if (evt.isRedacted()) {
auto reason = evt.redactedBecause()->reason();
return (reason.isEmpty())
? tr("Redacted")
: tr("Redacted: %1").arg(evt.redactedBecause()->reason());
2018-07-09 02:45:26 +00:00
}
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
// Cannot use e.contentJson() here because some
// EventContent classes inject values into the copy of the
// content JSON stored in EventContent::Base
return e->hasFileContent()
? QVariant::fromValue(e->content()->originalJson)
: QVariant();
};
2018-07-09 02:45:26 +00:00
}
2018-09-06 04:34:15 +00:00
if (role == HighlightRole) return m_currentRoom->isEventHighlighted(&evt);
if (role == ReadMarkerRole) return evt.id() == lastReadEventId && row > timelineBaseIndex();
2018-07-09 02:45:26 +00:00
if (role == SpecialMarksRole) {
if (isPending) return pendingIt->deliveryStatus();
2018-08-06 12:13:51 +00:00
if (is<RedactionEvent>(evt)) return EventStatus::Hidden;
2018-09-30 09:09:58 +00:00
if (evt.isRedacted()) return EventStatus::Redacted;
2018-08-06 12:13:51 +00:00
if (evt.isStateEvent() &&
static_cast<const StateEventBase &>(evt).repeatsState())
2018-08-05 16:53:22 +00:00
return EventStatus::Hidden;
2018-08-06 12:13:51 +00:00
return EventStatus::Normal;
2018-07-09 02:45:26 +00:00
}
2018-08-05 16:53:22 +00:00
if (role == EventIdRole)
return !evt.id().isEmpty() ? evt.id() : evt.transactionId();
2018-07-09 02:45:26 +00:00
if (role == LongOperationRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt))
if (e->hasFileContent())
return QVariant::fromValue(m_currentRoom->fileTransferInfo(e->id()));
2018-07-09 02:45:26 +00:00
}
2018-08-05 16:53:22 +00:00
if (role == AnnotationRole)
if (isPending) return pendingIt->annotation();
2018-08-05 16:53:22 +00:00
if (role == TimeRole || role == SectionRole) {
auto ts =
isPending ? pendingIt->lastUpdated() : makeMessageTimestamp(timelineIt);
return role == TimeRole ? QVariant(ts) : renderDate(ts);
}
2018-09-13 05:05:51 +00:00
if (role == UserMarkerRole) {
QVariantList variantList;
for (User *user : m_currentRoom->usersAtEventId(evt.id())) {
2018-09-13 05:05:51 +00:00
if (user == m_currentRoom->localUser()) continue;
variantList.append(QVariant::fromValue(user));
}
return variantList;
}
if (role == AboveEventTypeRole || role == AboveSectionRole ||
role == AboveAuthorRole || role == AboveTimeRole)
2018-08-05 16:53:22 +00:00
for (auto r = row + 1; r < rowCount(); ++r) {
auto i = index(r);
if (data(i, SpecialMarksRole) != EventStatus::Hidden) switch (role) {
case AboveEventTypeRole:
return data(i, EventTypeRole);
case AboveSectionRole:
return data(i, SectionRole);
case AboveAuthorRole:
return data(i, AuthorRole);
case AboveTimeRole:
return data(i, TimeRole);
}
}
2018-07-09 02:45:26 +00:00
2018-08-05 16:53:22 +00:00
return {};
2018-07-09 02:45:26 +00:00
}
2018-10-22 01:48:37 +00:00
int MessageEventModel::eventIDToIndex(const QString &eventID) {
2018-10-22 01:48:37 +00:00
const auto it = m_currentRoom->findInTimeline(eventID);
if (it == m_currentRoom->timelineEdge()) {
qWarning() << "Trying to find inexistent event:" << eventID;
return -1;
}
return it - m_currentRoom->messageEvents().rbegin() + timelineBaseIndex();
}