From 08e19449ad4e33b9ec3eb66c56501f1c4a977350 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sun, 2 Aug 2020 19:31:22 +0200 Subject: Event::dumpTo: make protected, and RoomEvent override The override adds the event's origin timestamp --- lib/events/event.h | 2 +- lib/events/roomevent.cpp | 6 ++++++ lib/events/roomevent.h | 3 +++ 3 files changed, 10 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 6c8961ad..5b9f20b7 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -270,10 +270,10 @@ public: virtual bool isStateEvent() const { return false; } virtual bool isCallEvent() const { return false; } - virtual void dumpTo(QDebug dbg) const; protected: QJsonObject& editJson() { return _json; } + virtual void dumpTo(QDebug dbg) const; private: Type _type; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index a59cd6e0..0a4332ad 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -115,6 +115,12 @@ void RoomEvent::addId(const QString& newId) Q_ASSERT(id() == newId); } +void RoomEvent::dumpTo(QDebug dbg) const +{ + Event::dumpTo(dbg); + dbg << " (made at " << originTimestamp().toString(Qt::ISODate) << ')'; +} + QJsonObject makeCallContentJson(const QString& callId, int version, QJsonObject content) { diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 621652cb..084cb524 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -87,6 +87,9 @@ public: */ void addId(const QString& newId); +protected: + void dumpTo(QDebug dbg) const override; + private: event_ptr_tt _redactedBecause; }; -- cgit v1.2.3 From 82bcc316d736bd04174876efde38827c34181c33 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Mon, 3 Aug 2020 19:10:10 +0200 Subject: Cleanup --- lib/events/roomcanonicalaliasevent.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index 5d680de7..fadfece0 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -59,12 +59,14 @@ public: : StateEvent(typeId(), obj) { } - explicit RoomCanonicalAliasEvent(const QString& canonicalAlias, const QStringList& altAliases = {}) + explicit RoomCanonicalAliasEvent(const QString& canonicalAlias, + const QStringList& altAliases = {}) : StateEvent(typeId(), matrixTypeId(), QString(), canonicalAlias, altAliases) { } - explicit RoomCanonicalAliasEvent(QString&& canonicalAlias, QStringList&& altAliases = {}) + explicit RoomCanonicalAliasEvent(QString&& canonicalAlias, + QStringList&& altAliases = {}) : StateEvent(typeId(), matrixTypeId(), QString(), std::move(canonicalAlias), std::move(altAliases)) { } -- cgit v1.2.3 From 08b9adcf611e0307daa8297205eb9ed3af66c71e Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Tue, 11 Aug 2020 22:53:58 +0200 Subject: Drop unneeded #include --- lib/events/accountdataevents.h | 1 - 1 file changed, 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index a55016d9..0f240aa1 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -18,7 +18,6 @@ #pragma once -#include "converters.h" #include "event.h" #include "eventcontent.h" -- cgit v1.2.3 From f4db6988bf2fd71f74ac851557d82c6f65cc89b1 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sun, 8 Nov 2020 18:57:44 +0100 Subject: More robust member profile data retrieval MemberEventContent: displayname and avatarUrl are now Omittables; CS API doesn't guarantee their presence (see also https://github.com/matrix-org/matrix-doc/issues/1375) but Quotient used to assume they are always there, causing #412. RoomMemberEvent: displayname() -> newDisplayName() and avatarUrl() -> newAvatarUrl(), to emphasise the actual semantics (and also the changed interface). The old signatures still work but are deprecated. Instead of roomMembername() (with weird camel-casing), three new methods in addition to safeMemberName() are introduced to Room: - memberName() - produces the "best known" display name for a given member; User::name() uses it to avoid the pitfall of #412. - disambiguatedMemberName() - this is what roomMembername() used to be; not recommended for direct use when UI is concerned. - safeMemberName() - remains as is, with the fix to the documentation that used to mislead that the function returns HTML-escaped content (it didn't, and doesn't). - htmlSafeMemberName() - does what safeMemberName() claimed to do. Respectively, memberNames() is deprecated in favor of safeMemberNames() and htmlSafeMemberNames(). The corresponding Q_PROPERTY uses safeMemberNames() now. Similar to memberName(), Room has got memberAvatarUrl() to spare User class from diving into Room state to find the member avatar URL. Closes #412. --- lib/events/roommemberevent.cpp | 28 ++++++++++++++++++---------- lib/events/roommemberevent.h | 18 +++++++++++++----- 2 files changed, 31 insertions(+), 15 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 35cbdb3a..f6b29f7f 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -50,10 +50,13 @@ using namespace Quotient; MemberEventContent::MemberEventContent(const QJsonObject& json) : membership(fromJson(json["membership"_ls])) , isDirect(json["is_direct"_ls].toBool()) - , displayName(sanitized(json["displayname"_ls].toString())) - , avatarUrl(json["avatar_url"_ls].toString()) + , displayName(fromJson>(json["displayname"_ls])) + , avatarUrl(fromJson>(json["avatar_url"_ls])) , reason(json["reason"_ls].toString()) -{} +{ + if (displayName) + displayName = sanitized(*displayName); +} void MemberEventContent::fillJson(QJsonObject* o) const { @@ -62,9 +65,10 @@ void MemberEventContent::fillJson(QJsonObject* o) const "The key 'membership' must be explicit in MemberEventContent"); if (membership != MembershipType::Undefined) o->insert(QStringLiteral("membership"), membershipStrings[membership]); - o->insert(QStringLiteral("displayname"), displayName); - if (avatarUrl.isValid()) - o->insert(QStringLiteral("avatar_url"), avatarUrl.toString()); + if (displayName) + o->insert(QStringLiteral("displayname"), *displayName); + if (avatarUrl && avatarUrl->isValid()) + o->insert(QStringLiteral("avatar_url"), avatarUrl->toString()); if (!reason.isEmpty()) o->insert(QStringLiteral("reason"), reason); } @@ -111,12 +115,16 @@ bool RoomMemberEvent::isUnban() const bool RoomMemberEvent::isRename() const { - auto prevName = prevContent() ? prevContent()->displayName : QString(); - return displayName() != prevName; + auto prevName = prevContent() && prevContent()->displayName + ? *prevContent()->displayName + : QString(); + return newDisplayName() != prevName; } bool RoomMemberEvent::isAvatarUpdate() const { - auto prevAvatarUrl = prevContent() ? prevContent()->avatarUrl : QUrl(); - return avatarUrl() != prevAvatarUrl; + auto prevAvatarUrl = prevContent() && prevContent()->avatarUrl + ? *prevContent()->avatarUrl + : QUrl(); + return newAvatarUrl() != prevAvatarUrl; } diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 783b8207..35fd69a9 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -24,7 +24,7 @@ namespace Quotient { class MemberEventContent : public EventContent::Base { public: - enum MembershipType : size_t { + enum MembershipType : unsigned char { Invite = 0, Join, Knock, @@ -38,8 +38,8 @@ public: MembershipType membership; bool isDirect = false; - QString displayName; - QUrl avatarUrl; + Omittable displayName; + Omittable avatarUrl; QString reason; protected: @@ -84,8 +84,16 @@ public: MembershipType membership() const { return content().membership; } QString userId() const { return fullJson()[StateKeyKeyL].toString(); } bool isDirect() const { return content().isDirect; } - QString displayName() const { return content().displayName; } - QUrl avatarUrl() const { return content().avatarUrl; } + Omittable newDisplayName() const { return content().displayName; } + Omittable newAvatarUrl() const { return content().avatarUrl; } + [[deprecated("Use newDisplayName() instead")]] QString displayName() const + { + return newDisplayName().value_or(QString()); + } + [[deprecated("Use newAvatarUrl() instead")]] QUrl avatarUrl() const + { + return newAvatarUrl().value_or(QUrl()); + } QString reason() const { return content().reason; } bool changesMembership() const; bool isBan() const; -- cgit v1.2.3 From b27ef93df9b5147ab03c8a255918874b9f73c201 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Tue, 10 Nov 2020 13:07:28 +0100 Subject: MembershipType: drop warning on empty values This is a usual situation when a membership type is undefined; and the current code constructs _a lot_ of stub events by loading them from empty JSON. So just silence those warnings for now. --- lib/events/roommemberevent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index f6b29f7f..be47e412 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -39,7 +39,8 @@ struct JsonConverter { if (membershipString == *it) return MembershipType(it - membershipStrings.begin()); - qCWarning(EVENTS) << "Unknown MembershipType: " << membershipString; + if (!membershipString.isEmpty()) + qCWarning(EVENTS) << "Unknown MembershipType: " << membershipString; return MembershipType::Undefined; } }; -- cgit v1.2.3 From 4cc8838c3bbe712493a4f6ddbecd0f7093e907bb Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Thu, 12 Nov 2020 18:51:35 +0100 Subject: More JSON key constants --- lib/events/event.h | 4 ++++ lib/events/roomevent.cpp | 8 ++++---- lib/events/roomkeyevent.h | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 5b9f20b7..b12dc9ad 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -59,12 +59,16 @@ static const auto TypeKey = QStringLiteral("type"); static const auto BodyKey = QStringLiteral("body"); static const auto ContentKey = QStringLiteral("content"); static const auto EventIdKey = QStringLiteral("event_id"); +static const auto SenderKey = QStringLiteral("sender"); +static const auto RoomIdKey = QStringLiteral("room_id"); static const auto UnsignedKey = QStringLiteral("unsigned"); static const auto StateKeyKey = QStringLiteral("state_key"); static const auto TypeKeyL = "type"_ls; static const auto BodyKeyL = "body"_ls; static const auto ContentKeyL = "content"_ls; static const auto EventIdKeyL = "event_id"_ls; +static const auto SenderKeyL = "sender"_ls; +static const auto RoomIdKeyL = "room_id"_ls; static const auto UnsignedKeyL = "unsigned"_ls; static const auto RedactedCauseKeyL = "redacted_because"_ls; static const auto PrevContentKeyL = "prev_content"_ls; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 0a4332ad..3d87ef18 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -51,12 +51,12 @@ QDateTime RoomEvent::originTimestamp() const QString RoomEvent::roomId() const { - return fullJson()["room_id"_ls].toString(); + return fullJson()[RoomIdKeyL].toString(); } QString RoomEvent::senderId() const { - return fullJson()["sender"_ls].toString(); + return fullJson()[SenderKeyL].toString(); } bool RoomEvent::isReplaced() const @@ -90,12 +90,12 @@ QString RoomEvent::stateKey() const void RoomEvent::setRoomId(const QString& roomId) { - editJson().insert(QStringLiteral("room_id"), roomId); + editJson().insert(RoomIdKey, roomId); } void RoomEvent::setSender(const QString& senderId) { - editJson().insert(QStringLiteral("sender"), senderId); + editJson().insert(SenderKey, senderId); } void RoomEvent::setTransactionId(const QString& txnId) diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 679cbf7c..3a781474 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -11,7 +11,7 @@ public: RoomKeyEvent(const QJsonObject& obj); QString algorithm() const { return content("algorithm"_ls); } - QString roomId() const { return content("room_id"_ls); } + QString roomId() const { return content(RoomIdKeyL); } QString sessionId() const { return content("session_id"_ls); } QString sessionKey() const { return content("session_key"_ls); } }; -- cgit v1.2.3 From 8f4c7f67930be402836ca7a6266ba4277266a12d Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sat, 14 Nov 2020 20:01:36 +0100 Subject: Drop EventFactory RoomPowerLevelsEvent is not used in csapi/ classes so the factory is of no use either. --- lib/events/roompowerlevelsevent.h | 10 ---------- 1 file changed, 10 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index f0f7207f..b832230e 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -62,15 +62,5 @@ public: private: }; -template <> -class EventFactory { -public: - static event_ptr_tt make(const QJsonObject& json, - const QString&) - { - return makeEvent(json); - } -}; - REGISTER_EVENT_TYPE(RoomPowerLevelsEvent) } // namespace Quotient -- cgit v1.2.3 From c919c021be42228ff615e581a2f80e649c992807 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sat, 14 Nov 2020 22:34:41 +0100 Subject: Cleanup --- lib/events/roomcreateevent.cpp | 4 ++-- lib/events/stateevent.h | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index c72b5bc2..0fc7d6b9 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -33,8 +33,8 @@ QString RoomCreateEvent::version() const RoomCreateEvent::Predecessor RoomCreateEvent::predecessor() const { const auto predJson = contentJson()["predecessor"_ls].toObject(); - return { fromJson(predJson["room_id"_ls]), - fromJson(predJson["event_id"_ls]) }; + return { fromJson(predJson[RoomIdKeyL]), + fromJson(predJson[EventIdKeyL]) }; } bool RoomCreateEvent::isUpgrade() const diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 710b4271..400858db 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -23,12 +23,11 @@ namespace Quotient { /// Make a minimal correct Matrix state event JSON -template -inline QJsonObject basicStateEventJson(StrT matrixType, +inline QJsonObject basicStateEventJson(const QString& matrixTypeId, const QJsonObject& content, const QString& stateKey = {}) { - return { { TypeKey, std::forward(matrixType) }, + return { { TypeKey, matrixTypeId }, { StateKeyKey, stateKey }, { ContentKey, content } }; } -- cgit v1.2.3 From 5b1bfc102fccd4e57893b34bf2b0a14ba6a9f577 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sat, 14 Nov 2020 22:35:31 +0100 Subject: Make StateEventBase Q_GADGET too To align with the two other base event classes (Event and RoomEvent). --- lib/events/stateevent.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'lib/events') diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 400858db..20a85f83 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -33,6 +33,8 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, } class StateEventBase : public RoomEvent { + Q_GADGET + Q_PROPERTY(QString stateKey READ stateKey CONSTANT) public: using factory_t = EventFactory; @@ -128,3 +130,5 @@ private: std::unique_ptr> _prev; }; } // namespace Quotient +Q_DECLARE_METATYPE(Quotient::StateEventBase*) +Q_DECLARE_METATYPE(const Quotient::StateEventBase*) -- cgit v1.2.3 From 52cab4b11bdd48cd87e04c01b12c698ec4145e6d Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sun, 15 Nov 2020 21:51:51 +0100 Subject: Cleanup across event classes In particular: removed unnecessary #includes, deprecated and no more used constructs, replaced stored members with dynamic generation from JSON (TypingEvent and, especially promising for performance, ReceiptEvent) --- lib/events/callanswerevent.cpp | 5 ----- lib/events/callhangupevent.cpp | 5 ----- lib/events/callinviteevent.cpp | 5 ----- lib/events/encryptedevent.cpp | 3 --- lib/events/encryptionevent.h | 4 +--- lib/events/event.h | 12 ------------ lib/events/reactionevent.h | 3 --- lib/events/receiptevent.cpp | 12 +++++++----- lib/events/receiptevent.h | 10 ++-------- lib/events/roomcanonicalaliasevent.h | 4 ++-- lib/events/roomevent.cpp | 5 ++--- lib/events/roomkeyevent.h | 2 +- lib/events/roommemberevent.h | 10 ++-------- lib/events/typingevent.cpp | 8 ++------ lib/events/typingevent.h | 7 ++----- 15 files changed, 21 insertions(+), 74 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index d6622b30..bf096534 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -18,11 +18,6 @@ #include "callanswerevent.h" -#include "event.h" -#include "logging.h" - -#include - /* m.call.answer { diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp index d41849c3..f2117f38 100644 --- a/lib/events/callhangupevent.cpp +++ b/lib/events/callhangupevent.cpp @@ -18,11 +18,6 @@ #include "callhangupevent.h" -#include "event.h" -#include "logging.h" - -#include - /* m.call.hangup { diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 54faac8d..63f331de 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -18,11 +18,6 @@ #include "callinviteevent.h" -#include "event.h" -#include "logging.h" - -#include - /* m.call.invite { diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index dccfa540..117aae37 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -1,9 +1,6 @@ #include "encryptedevent.h" -#include "room.h" - using namespace Quotient; -using namespace QtOlm; EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertext, const QString& senderKey) diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index cbd3ba4a..cbb6d786 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -48,6 +48,7 @@ public: DEFINE_EVENT_TYPEID("m.room.encryption", EncryptionEvent) using EncryptionType = EncryptionEventContent::EncryptionType; + Q_ENUM(EncryptionType) explicit EncryptionEvent(const QJsonObject& obj = {}) // TODO: apropriate // default value @@ -64,9 +65,6 @@ public: QString algorithm() const { return content().algorithm; } int rotationPeriodMs() const { return content().rotationPeriodMs; } int rotationPeriodMsgs() const { return content().rotationPeriodMsgs; } - -private: - Q_ENUM(EncryptionType) }; REGISTER_EVENT_TYPE(EncryptionEvent) diff --git a/lib/events/event.h b/lib/events/event.h index b12dc9ad..626a0229 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -21,10 +21,6 @@ #include "converters.h" #include "logging.h" -#ifdef ENABLE_EVENTTYPE_ALIAS -# define USE_EVENTTYPE_ALIAS 1 -#endif - namespace Quotient { // === event_ptr_tt<> and type casting facilities === @@ -45,14 +41,6 @@ inline TargetEventT* weakPtrCast(const event_ptr_tt& ptr) return static_cast(rawPtr(ptr)); } -/// Re-wrap a smart pointer to base into a smart pointer to derived -template -[[deprecated("Consider using eventCast() or visit() instead")]] -inline event_ptr_tt ptrCast(event_ptr_tt&& ptr) -{ - return std::unique_ptr(static_cast(ptr.release())); -} - // === Standard Matrix key names and basicEventJson() === static const auto TypeKey = QStringLiteral("type"); diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index 75c6528c..48b0bc6c 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -64,9 +64,6 @@ public: { return content(QStringLiteral("m.relates_to")); } - -private: - EventRelation _relation; }; REGISTER_EVENT_TYPE(ReactionEvent) diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index bf050cb2..deb3c4e8 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -40,10 +40,11 @@ Example of a Receipt Event: using namespace Quotient; -ReceiptEvent::ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) +EventsWithReceipts ReceiptEvent::eventsWithReceipts() const { + EventsWithReceipts result; const auto& contents = contentJson(); - _eventsWithReceipts.reserve(contents.size()); + result.reserve(contents.size()); for (auto eventIt = contents.begin(); eventIt != contents.end(); ++eventIt) { if (eventIt.key().isEmpty()) { qCWarning(EPHEMERAL) @@ -51,15 +52,16 @@ ReceiptEvent::ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) qCDebug(EPHEMERAL) << "ReceiptEvent content follows:\n" << contents; continue; } - const QJsonObject reads = + const auto reads = eventIt.value().toObject().value("m.read"_ls).toObject(); QVector receipts; receipts.reserve(reads.size()); for (auto userIt = reads.begin(); userIt != reads.end(); ++userIt) { - const QJsonObject user = userIt.value().toObject(); + const auto user = userIt.value().toObject(); receipts.push_back( { userIt.key(), fromJson(user["ts"_ls]) }); } - _eventsWithReceipts.push_back({ eventIt.key(), std::move(receipts) }); + result.push_back({ eventIt.key(), std::move(receipts) }); } + return result; } diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index dd54a476..b7adea44 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -37,15 +37,9 @@ using EventsWithReceipts = QVector; class ReceiptEvent : public Event { public: DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) - explicit ReceiptEvent(const QJsonObject& obj); + explicit ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) {} - const EventsWithReceipts& eventsWithReceipts() const - { - return _eventsWithReceipts; - } - -private: - EventsWithReceipts _eventsWithReceipts; + EventsWithReceipts eventsWithReceipts() const; }; REGISTER_EVENT_TYPE(ReceiptEvent) } // namespace Quotient diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index fadfece0..4a21b7cc 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -61,13 +61,13 @@ public: explicit RoomCanonicalAliasEvent(const QString& canonicalAlias, const QStringList& altAliases = {}) - : StateEvent(typeId(), matrixTypeId(), QString(), + : StateEvent(typeId(), matrixTypeId(), {}, canonicalAlias, altAliases) { } explicit RoomCanonicalAliasEvent(QString&& canonicalAlias, QStringList&& altAliases = {}) - : StateEvent(typeId(), matrixTypeId(), QString(), + : StateEvent(typeId(), matrixTypeId(), {}, std::move(canonicalAlias), std::move(altAliases)) { } diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 3d87ef18..a2dbc07d 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -34,9 +34,8 @@ RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, RoomEvent::RoomEvent(Type type, const QJsonObject& json) : Event(type, json) { - const auto unsignedData = json[UnsignedKeyL].toObject(); - const auto redaction = unsignedData[RedactedCauseKeyL]; - if (redaction.isObject()) + if (const auto redaction = unsignedJson()[RedactedCauseKeyL]; + redaction.isObject()) _redactedBecause = makeEvent(redaction.toObject()); } diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 3a781474..b8cd2eae 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -8,7 +8,7 @@ class RoomKeyEvent : public Event public: DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) - RoomKeyEvent(const QJsonObject& obj); + explicit RoomKeyEvent(const QJsonObject& obj); QString algorithm() const { return content("algorithm"_ls); } QString roomId() const { return content(RoomIdKeyL); } diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 35fd69a9..cebaaf10 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -54,13 +54,10 @@ public: DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) using MembershipType = MemberEventContent::MembershipType; + Q_ENUM(MembershipType) explicit RoomMemberEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} - [[deprecated("Use RoomMemberEvent(userId, contentArgs) instead")]] - RoomMemberEvent(MemberEventContent&& c) - : StateEvent(typeId(), matrixTypeId(), QString(), c) - {} template RoomMemberEvent(const QString& userId, ArgTs&&... contentArgs) : StateEvent(typeId(), matrixTypeId(), userId, @@ -82,7 +79,7 @@ public: {} MembershipType membership() const { return content().membership; } - QString userId() const { return fullJson()[StateKeyKeyL].toString(); } + QString userId() const { return stateKey(); } bool isDirect() const { return content().isDirect; } Omittable newDisplayName() const { return content().displayName; } Omittable newAvatarUrl() const { return content().avatarUrl; } @@ -104,9 +101,6 @@ public: bool isLeave() const; bool isRename() const; bool isAvatarUpdate() const; - -private: - Q_ENUM(MembershipType) }; template <> diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index 0c5fc6ba..e102fc79 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -18,13 +18,9 @@ #include "typingevent.h" -#include - using namespace Quotient; -TypingEvent::TypingEvent(const QJsonObject& obj) : Event(typeId(), obj) +QStringList TypingEvent::users() const { - const auto& array = contentJson()["user_ids"_ls].toArray(); - for (const auto& user : array) - _users.push_back(user.toString()); + return fromJson(contentJson()["user_ids"_ls]); } diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 1cf4e69d..97e1f9cc 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -25,12 +25,9 @@ class TypingEvent : public Event { public: DEFINE_EVENT_TYPEID("m.typing", TypingEvent) - TypingEvent(const QJsonObject& obj); + explicit TypingEvent(const QJsonObject& obj) : Event(typeId(), obj) {} - const QStringList& users() const { return _users; } - -private: - QStringList _users; + QStringList users() const; }; REGISTER_EVENT_TYPE(TypingEvent) } // namespace Quotient -- cgit v1.2.3 From dda813899fdb4a520dc83e10c17c1923712a8f7d Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Thu, 19 Nov 2020 14:56:09 +0100 Subject: Fix Q_ASSERT failure on sending messages Changes in e81117fb exposed a flaw in EncryptionEvent causing assertion failure when this event is default-initialised (i.e. no encryption). --- lib/events/encryptionevent.cpp | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 073303b0..f1bde621 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -1,21 +1,14 @@ -// -// Created by rusakov on 26/09/2017. -// Contributed by andreev on 27/06/2019. -// - #include "encryptionevent.h" -#include "converters.h" #include "e2ee.h" -#include "logging.h" #include +namespace Quotient { static const std::array encryptionStrings = { - { Quotient::MegolmV1AesSha2AlgoKey } + { MegolmV1AesSha2AlgoKey } }; -namespace Quotient { template <> struct JsonConverter { static EncryptionType load(const QJsonValue& jv) @@ -26,7 +19,8 @@ struct JsonConverter { if (encryptionString == *it) return EncryptionType(it - encryptionStrings.begin()); - qCWarning(EVENTS) << "Unknown EncryptionType: " << encryptionString; + if (!encryptionString.isEmpty()) + qCWarning(EVENTS) << "Unknown EncryptionType: " << encryptionString; return EncryptionType::Undefined; } }; @@ -35,7 +29,7 @@ struct JsonConverter { using namespace Quotient; EncryptionEventContent::EncryptionEventContent(const QJsonObject& json) - : encryption(fromJson(json["algorithm"_ls])) + : encryption(fromJson(json[AlgorithmKeyL])) , algorithm(sanitized(json[AlgorithmKeyL].toString())) , rotationPeriodMs(json[RotationPeriodMsKeyL].toInt(604800000)) , rotationPeriodMsgs(json[RotationPeriodMsgsKeyL].toInt(100)) @@ -44,9 +38,6 @@ EncryptionEventContent::EncryptionEventContent(const QJsonObject& json) void EncryptionEventContent::fillJson(QJsonObject* o) const { Q_ASSERT(o); - Q_ASSERT_X( - encryption != EncryptionType::Undefined, __FUNCTION__, - "The key 'algorithm' must be explicit in EncryptionEventContent"); if (encryption != EncryptionType::Undefined) o->insert(AlgorithmKey, algorithm); o->insert(RotationPeriodMsKey, rotationPeriodMs); -- cgit v1.2.3 From 17d6e00597fdc1c8f25808735cbc728c4a6b3506 Mon Sep 17 00:00:00 2001 From: David Faure Date: Thu, 26 Nov 2020 22:32:55 +0100 Subject: Enable QT_NO_URL_CAST_FROM_STRING and QT_STRICT_ITERATORS. * QT_NO_URL_CAST_FROM_STRING makes it clearer where QUrls are created from QStrings (which incurs a parsing cost). * QT_STRICT_ITERATORS helps detecting where begin()/end() is used instead of cbegin()/cend(). KDE developers have verified that the generated assembly code is identical. --- lib/events/eventcontent.cpp | 2 +- lib/events/eventcontent.h | 2 +- lib/events/roommemberevent.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 802d8176..0cb9e292 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -89,7 +89,7 @@ void ImageInfo::fillInfoJson(QJsonObject* infoJson) const } Thumbnail::Thumbnail(const QJsonObject& infoJson) - : ImageInfo(infoJson["thumbnail_url"_ls].toString(), + : ImageInfo(QUrl(infoJson["thumbnail_url"_ls].toString()), infoJson["thumbnail_info"_ls].toObject()) {} diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 0d4c047e..9c167d4b 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -189,7 +189,7 @@ namespace EventContent { using InfoT::InfoT; explicit UrlBasedContent(const QJsonObject& json) : TypedBase(json) - , InfoT(json["url"].toString(), json["info"].toObject(), + , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), json["filename"].toString()) { // A small hack to facilitate links creation in QML. diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index be47e412..913bde74 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -52,7 +52,7 @@ MemberEventContent::MemberEventContent(const QJsonObject& json) : membership(fromJson(json["membership"_ls])) , isDirect(json["is_direct"_ls].toBool()) , displayName(fromJson>(json["displayname"_ls])) - , avatarUrl(fromJson>(json["avatar_url"_ls])) + , avatarUrl(fromJson>(json["avatar_url"_ls])) , reason(json["reason"_ls].toString()) { if (displayName) -- cgit v1.2.3 From cd9c9296bb1ac7af7ebbbf66931e731dbf581bc8 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Sat, 26 Dec 2020 14:54:31 +0100 Subject: Port existing copyright statement to reuse using licensedigger --- lib/events/accountdataevents.h | 16 ++-------------- lib/events/callanswerevent.cpp | 16 ++-------------- lib/events/callanswerevent.h | 16 ++-------------- lib/events/callcandidatesevent.cpp | 16 ++-------------- lib/events/callcandidatesevent.h | 16 ++-------------- lib/events/callhangupevent.cpp | 16 ++-------------- lib/events/callhangupevent.h | 16 ++-------------- lib/events/callinviteevent.cpp | 16 ++-------------- lib/events/callinviteevent.h | 16 ++-------------- lib/events/directchatevent.cpp | 16 ++-------------- lib/events/directchatevent.h | 16 ++-------------- lib/events/encryptionevent.h | 16 ++-------------- lib/events/event.cpp | 16 ++-------------- lib/events/event.h | 16 ++-------------- lib/events/eventcontent.cpp | 16 ++-------------- lib/events/eventcontent.h | 16 ++-------------- lib/events/eventloader.h | 16 ++-------------- lib/events/reactionevent.cpp | 16 ++-------------- lib/events/reactionevent.h | 16 ++-------------- lib/events/receiptevent.cpp | 16 ++-------------- lib/events/receiptevent.h | 16 ++-------------- lib/events/redactionevent.h | 16 ++-------------- lib/events/roomavatarevent.h | 16 ++-------------- lib/events/roomcanonicalaliasevent.h | 16 ++-------------- lib/events/roomcreateevent.cpp | 16 ++-------------- lib/events/roomcreateevent.h | 16 ++-------------- lib/events/roomevent.cpp | 16 ++-------------- lib/events/roomevent.h | 16 ++-------------- lib/events/roommemberevent.cpp | 16 ++-------------- lib/events/roommemberevent.h | 16 ++-------------- lib/events/roommessageevent.cpp | 16 ++-------------- lib/events/roommessageevent.h | 16 ++-------------- lib/events/roomtombstoneevent.cpp | 16 ++-------------- lib/events/roomtombstoneevent.h | 16 ++-------------- lib/events/simplestateevents.h | 16 ++-------------- lib/events/stateevent.cpp | 16 ++-------------- lib/events/stateevent.h | 16 ++-------------- lib/events/typingevent.cpp | 16 ++-------------- lib/events/typingevent.h | 16 ++-------------- 39 files changed, 78 insertions(+), 546 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 0f240aa1..d0abf577 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index bf096534..f3d0a9a0 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "callanswerevent.h" diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 2709882b..d7214468 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/callcandidatesevent.cpp b/lib/events/callcandidatesevent.cpp index 24f0dd46..9b765064 100644 --- a/lib/events/callcandidatesevent.cpp +++ b/lib/events/callcandidatesevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "callcandidatesevent.h" diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index e224f048..ae3bb150 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp index f2117f38..45b84cd4 100644 --- a/lib/events/callhangupevent.cpp +++ b/lib/events/callhangupevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "callhangupevent.h" diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index 5d73fb62..432f72f5 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 63f331de..86478ada 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "callinviteevent.h" diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index b067a492..304c89ac 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2017 Marius Gripsgard * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/directchatevent.cpp b/lib/events/directchatevent.cpp index b4027e16..39d11072 100644 --- a/lib/events/directchatevent.cpp +++ b/lib/events/directchatevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "directchatevent.h" diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index bb091c5c..373e36dc 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index cbb6d786..3431ddd8 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 96e33864..6014183e 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "event.h" diff --git a/lib/events/event.h b/lib/events/event.h index 626a0229..e9d42333 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 802d8176..d7b109f7 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "eventcontent.h" diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 0d4c047e..e0e4a5db 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index ebb96441..0d95daf5 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/reactionevent.cpp b/lib/events/reactionevent.cpp index 003c8ead..9b43e372 100644 --- a/lib/events/reactionevent.cpp +++ b/lib/events/reactionevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 Kitsune Ral + * SPDX-FileCopyrightText: 2019 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "reactionevent.h" diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index 48b0bc6c..09166b24 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 Kitsune Ral + * SPDX-FileCopyrightText: 2019 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index deb3c4e8..b6f0fcdd 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2016 Felix Rohrbach + * SPDX-FileCopyrightText: 2016 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ /* diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index b7adea44..ec297a6c 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2016 Felix Rohrbach + * SPDX-FileCopyrightText: 2016 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index 3b3af18e..320db6f2 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index c2100eaa..649412e8 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index 4a21b7cc..eda94d2d 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2020 QMatrixClient project + * SPDX-FileCopyrightText: 2020 QMatrixClient project * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index 0fc7d6b9..3d9ec4a3 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 QMatrixClient project + * SPDX-FileCopyrightText: 2019 QMatrixClient project * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "roomcreateevent.h" diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 91aefe9e..8328d38a 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 QMatrixClient project + * SPDX-FileCopyrightText: 2019 QMatrixClient project * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index a2dbc07d..2b6ac2be 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "roomevent.h" diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 084cb524..3fafecfd 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index be47e412..6f5d5a52 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "roommemberevent.h" diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index cebaaf10..b7a7c9df 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 616a034f..19d460b8 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "roommessageevent.h" diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 2501d097..ebc9d564 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/roomtombstoneevent.cpp b/lib/events/roomtombstoneevent.cpp index f93eb60d..163e1d3a 100644 --- a/lib/events/roomtombstoneevent.cpp +++ b/lib/events/roomtombstoneevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 QMatrixClient project + * SPDX-FileCopyrightText: 2019 QMatrixClient project * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "roomtombstoneevent.h" diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 2c2f0663..8d50aba0 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2019 QMatrixClient project + * SPDX-FileCopyrightText: 2019 QMatrixClient project * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index cde5b0fd..58ba3b5a 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2017 Kitsune Ral + * SPDX-FileCopyrightText: 2017 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 5909e8a6..7bde12bb 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "stateevent.h" diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 20a85f83..0db37767 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2018 Kitsune Ral + * SPDX-FileCopyrightText: 2018 Kitsune Ral * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index e102fc79..7d3f71e5 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "typingevent.h" diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 97e1f9cc..8ca4f8e4 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -1,19 +1,7 @@ /****************************************************************************** - * Copyright (C) 2015 Felix Rohrbach + * SPDX-FileCopyrightText: 2015 Felix Rohrbach * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once -- cgit v1.2.3 From 78cfde52d8f3ff04a07031a87a0c7218a3b0079f Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Sun, 27 Dec 2020 18:07:30 +0100 Subject: more :) --- lib/events/encryptedevent.cpp | 4 ++++ lib/events/encryptedevent.h | 4 ++++ lib/events/redactionevent.cpp | 4 ++++ 3 files changed, 12 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 117aae37..dc9eaf2d 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// +// SPDX-License-Identifier: LGPL-2.1-or-later + #include "encryptedevent.h" using namespace Quotient; diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 235b2aa4..9de08b00 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// +// SPDX-License-Identifier: LGPL-2.1-or-later + #pragma once #include "e2ee.h" diff --git a/lib/events/redactionevent.cpp b/lib/events/redactionevent.cpp index bf467718..5889773c 100644 --- a/lib/events/redactionevent.cpp +++ b/lib/events/redactionevent.cpp @@ -1 +1,5 @@ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// +// SPDX-License-Identifier: CC0-1.0 + #include "redactionevent.h" -- cgit v1.2.3 From 639f1d482633a7adb72164c56e3b5ea429db96a5 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sun, 27 Dec 2020 23:19:12 +0100 Subject: event.h: Minor tweaks around visit<> --- lib/events/event.h | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 626a0229..309ebddf 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -298,7 +298,7 @@ using Events = EventsArray; // === is<>(), eventCast<>() and visit<>() === -template +template inline bool is(const Event& e) { return e.type() == typeId(); @@ -309,7 +309,7 @@ inline bool isUnknown(const Event& e) return e.type() == unknownEventTypeId(); } -template +template inline auto eventCast(const BasePtrT& eptr) -> decltype(static_cast(&*eptr)) { @@ -319,7 +319,7 @@ inline auto eventCast(const BasePtrT& eptr) } // A single generic catch-all visitor -template +template inline auto visit(const BaseEventT& event, FnT&& visitor) -> decltype(visitor(event)) { @@ -327,18 +327,17 @@ inline auto visit(const BaseEventT& event, FnT&& visitor) } namespace _impl { - template - constexpr auto needs_downcast() - { - return !std::is_convertible_v>; - } + template + inline constexpr auto needs_downcast = + std::is_base_of_v>> + && !std::is_same_v>>; } // A single type-specific void visitor -template -inline std::enable_if_t<_impl::needs_downcast() +template +inline auto visit(const BaseT& event, FnT&& visitor) + -> std::enable_if_t<_impl::needs_downcast && std::is_void_v>> -visit(const BaseEventT& event, FnT&& visitor) { using event_type = fn_arg_t; if (is>(event)) @@ -347,10 +346,10 @@ visit(const BaseEventT& event, FnT&& visitor) // A single type-specific non-void visitor with an optional default value // non-voidness is guarded by defaultValue type -template -inline std::enable_if_t<_impl::needs_downcast(), fn_return_t> -visit(const BaseEventT& event, FnT&& visitor, - fn_return_t&& defaultValue = {}) +template +inline auto visit(const BaseT& event, FnT&& visitor, + fn_return_t&& defaultValue = {}) + -> std::enable_if_t<_impl::needs_downcast, fn_return_t> { using event_type = fn_arg_t; if (is>(event)) @@ -359,9 +358,10 @@ visit(const BaseEventT& event, FnT&& visitor, } // A chain of 2 or more visitors -template -inline fn_return_t visit(const BaseEventT& event, FnT1&& visitor1, - FnT2&& visitor2, FnTs&&... visitors) +template +inline std::common_type_t, fn_return_t> visit( + const BaseT& event, FnT1&& visitor1, FnT2&& visitor2, + FnTs&&... visitors) { using event_type1 = fn_arg_t; if (is>(event)) @@ -374,8 +374,8 @@ inline fn_return_t visit(const BaseEventT& event, FnT1&& visitor1, // over a range of event pointers template inline auto visitEach(RangeT&& events, FnTs&&... visitors) - -> std::enable_if_t, Event>> + -> std::enable_if_t(visitors)...))>> { for (auto&& evtPtr: events) visit(*evtPtr, std::forward(visitors)...); -- cgit v1.2.3 From 7c29f33121f58a52f43fa83183eaca47fa374980 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sun, 27 Dec 2020 18:33:51 +0100 Subject: More comments/documentation Notably, recommend using loginFlowsChanged() rather than homeserverChanged() to detect when a Connection object is ready for a login sequence. Related: #427. --- lib/events/event.cpp | 3 +++ 1 file changed, 3 insertions(+) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 96e33864..7b34114d 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -61,11 +61,14 @@ QString Event::matrixType() const { return fullJson()[TypeKeyL].toString(); } QByteArray Event::originalJson() const { return QJsonDocument(_json).toJson(); } +// On const below: this is to catch accidental attempts to change event JSON +// NOLINTNEXTLINE(readability-const-return-type) const QJsonObject Event::contentJson() const { return fullJson()[ContentKeyL].toObject(); } +// NOLINTNEXTLINE(readability-const-return-type) const QJsonObject Event::unsignedJson() const { return fullJson()[UnsignedKeyL].toObject(); -- cgit v1.2.3 From e5bf7c2fa64716de0b75a67acc5f8620e8dc1704 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Mon, 28 Dec 2020 18:22:29 +0100 Subject: Add support for sticker events --- lib/events/stickerevent.cpp | 26 ++++++++++++++++++++++++++ lib/events/stickerevent.h | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 lib/events/stickerevent.cpp create mode 100644 lib/events/stickerevent.h (limited to 'lib/events') diff --git a/lib/events/stickerevent.cpp b/lib/events/stickerevent.cpp new file mode 100644 index 00000000..ea4dff3f --- /dev/null +++ b/lib/events/stickerevent.cpp @@ -0,0 +1,26 @@ +// SDPX-FileCopyrightText: 2020 Carl Schwan +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "stickerevent.h" + +using namespace Quotient; + +StickerEvent::StickerEvent(const QJsonObject &obj) + : RoomEvent(typeId(), obj) + , m_imageContent(EventContent::ImageContent(obj["content"_ls].toObject())) +{} + +QString StickerEvent::body() const +{ + return content("body"_ls); +} + +const EventContent::ImageContent &StickerEvent::image() const +{ + return m_imageContent; +} + +QUrl StickerEvent::url() const +{ + return m_imageContent.url; +} diff --git a/lib/events/stickerevent.h b/lib/events/stickerevent.h new file mode 100644 index 00000000..93671086 --- /dev/null +++ b/lib/events/stickerevent.h @@ -0,0 +1,38 @@ +// SDPX-FileCopyrightText: 2020 Carl Schwan +// SPDX-License-Identifier: LGPL-2.1-or-later + +#pragma once + +#include "roomevent.h" +#include "eventcontent.h" + +namespace Quotient { + +/// Sticker messages are specialised image messages that are displayed without +/// controls (e.g. no "download" link, or light-box view on click, as would be +/// displayed for for m.image events). +class StickerEvent : public RoomEvent +{ +public: + DEFINE_EVENT_TYPEID("m.sticker", StickerEvent) + + explicit StickerEvent(const QJsonObject &obj); + + /// \brief A textual representation or associated description of the + /// sticker image. + /// + /// This could be the alt text of the original image, or a message to + /// accompany and further describe the sticker. + QString body() const; + + /// \brief Metadata about the image referred to in url including a + /// thumbnail representation. + const EventContent::ImageContent &image() const; + + /// \brief The URL to the sticker image. This must be a valid mxc:// URI. + QUrl url() const; +private: + EventContent::ImageContent m_imageContent; +}; +REGISTER_EVENT_TYPE(StickerEvent) +} // namespace Quotient -- cgit v1.2.3 From 2174e1980fd2cf5407ba8cd7cabb85d74d242ed2 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Mon, 28 Dec 2020 18:57:07 +0100 Subject: event.h: Fix breakage of AppVeyor CI The breakage was caused by 639f1d48. --- lib/events/event.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 309ebddf..9f2f4f91 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -327,8 +327,9 @@ inline auto visit(const BaseEventT& event, FnT&& visitor) } namespace _impl { + // Using bool instead of auto below because auto apparently upsets MSVC template - inline constexpr auto needs_downcast = + inline constexpr bool needs_downcast = std::is_base_of_v>> && !std::is_same_v>>; } -- cgit v1.2.3 From 0a775d9b3209be15dea8b8915fc0a1c8e0046ba6 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Sat, 16 Jan 2021 18:19:45 +0100 Subject: Updated copyright statements upon Git audit After going through all the files and the history of commits on them it was clear that some copyright statements are obsolete (the code has been overwritten since) and some are missing. This commit tries best to remedy that, along with adding SPDX tags where they were still not used. Also, a minimal SPDX convention is documented for further contributions. Closes #426. --- lib/events/accountdataevents.h | 7 ++----- lib/events/callanswerevent.cpp | 8 +++----- lib/events/callanswerevent.h | 8 +++----- lib/events/callcandidatesevent.cpp | 8 +++----- lib/events/callcandidatesevent.h | 9 ++++----- lib/events/callhangupevent.cpp | 1 + lib/events/callhangupevent.h | 8 +++----- lib/events/callinviteevent.cpp | 8 +++----- lib/events/callinviteevent.h | 8 +++----- lib/events/directchatevent.cpp | 7 ++----- lib/events/directchatevent.h | 7 ++----- lib/events/encryptedevent.cpp | 1 - lib/events/encryptedevent.h | 1 - lib/events/encryptionevent.cpp | 4 ++++ lib/events/encryptionevent.h | 8 +++----- lib/events/event.cpp | 7 ++----- lib/events/event.h | 7 ++----- lib/events/eventcontent.cpp | 7 ++----- lib/events/eventcontent.h | 7 ++----- lib/events/eventloader.h | 7 ++----- lib/events/reactionevent.cpp | 7 ++----- lib/events/reactionevent.h | 7 ++----- lib/events/receiptevent.cpp | 7 ++----- lib/events/receiptevent.h | 7 ++----- lib/events/redactionevent.cpp | 5 ----- lib/events/redactionevent.h | 7 ++----- lib/events/roomavatarevent.h | 7 ++----- lib/events/roomcanonicalaliasevent.h | 8 +++----- lib/events/roomcreateevent.cpp | 7 ++----- lib/events/roomcreateevent.h | 7 ++----- lib/events/roomevent.cpp | 7 ++----- lib/events/roomevent.h | 7 ++----- lib/events/roomkeyevent.cpp | 3 +++ lib/events/roomkeyevent.h | 3 +++ lib/events/roommemberevent.cpp | 8 +++----- lib/events/roommemberevent.h | 9 ++++----- lib/events/roommessageevent.cpp | 9 ++++----- lib/events/roommessageevent.h | 9 ++++----- lib/events/roompowerlevelsevent.cpp | 3 +++ lib/events/roompowerlevelsevent.h | 3 +++ lib/events/roomtombstoneevent.cpp | 7 ++----- lib/events/roomtombstoneevent.h | 7 ++----- lib/events/simplestateevents.h | 7 ++----- lib/events/stateevent.cpp | 7 ++----- lib/events/stateevent.h | 7 ++----- lib/events/typingevent.cpp | 7 ++----- lib/events/typingevent.h | 7 ++----- 47 files changed, 110 insertions(+), 197 deletions(-) delete mode 100644 lib/events/redactionevent.cpp (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index d0abf577..8cea0ec8 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index f3d0a9a0..be83d9d0 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #include "callanswerevent.h" diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index d7214468..6132cb44 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/callcandidatesevent.cpp b/lib/events/callcandidatesevent.cpp index 9b765064..b87c8e9b 100644 --- a/lib/events/callcandidatesevent.cpp +++ b/lib/events/callcandidatesevent.cpp @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #include "callcandidatesevent.h" diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index ae3bb150..b9de7556 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -1,8 +1,7 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp index 45b84cd4..43bc4db0 100644 --- a/lib/events/callhangupevent.cpp +++ b/lib/events/callhangupevent.cpp @@ -1,5 +1,6 @@ /****************************************************************************** * SPDX-FileCopyrightText: 2017 Marius Gripsgard + * SPDX-FileCopyrightText: 2018 Josip Delic * * SPDX-License-Identifier: LGPL-2.1-or-later */ diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index 432f72f5..24382ac2 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 86478ada..5ea54662 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #include "callinviteevent.h" diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 304c89ac..d3454c4f 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Marius Gripsgard +// SPDX-FileCopyrightText: 2018 Josip Delic +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/directchatevent.cpp b/lib/events/directchatevent.cpp index 39d11072..0ee1f7b0 100644 --- a/lib/events/directchatevent.cpp +++ b/lib/events/directchatevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "directchatevent.h" diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index 373e36dc..e2143779 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index dc9eaf2d..0290f973 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -1,5 +1,4 @@ // SPDX-FileCopyrightText: 2019 Alexey Andreyev -// // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 9de08b00..eb7123eb 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -1,5 +1,4 @@ // SPDX-FileCopyrightText: 2019 Alexey Andreyev -// // SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index f1bde621..490a5e8a 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// SPDX-License-Identifier: LGPL-2.1-or-later + #include "encryptionevent.h" #include "e2ee.h" diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 3431ddd8..f9bbab12 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 97edb4e0..3d66ab55 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2016 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "event.h" diff --git a/lib/events/event.h b/lib/events/event.h index c5752a7a..f8f8311d 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2016 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 18b1b94b..b249b160 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "eventcontent.h" diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index e247adbf..60d1f7b7 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index 0d95daf5..978668f2 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/reactionevent.cpp b/lib/events/reactionevent.cpp index 9b43e372..b53fffd6 100644 --- a/lib/events/reactionevent.cpp +++ b/lib/events/reactionevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "reactionevent.h" diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index 09166b24..777905f2 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index b6f0fcdd..4185d92d 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2016 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later /* Example of a Receipt Event: diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index ec297a6c..4feec9ea 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2016 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/redactionevent.cpp b/lib/events/redactionevent.cpp deleted file mode 100644 index 5889773c..00000000 --- a/lib/events/redactionevent.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-FileCopyrightText: 2019 Kitsune Ral -// -// SPDX-License-Identifier: CC0-1.0 - -#include "redactionevent.h" diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index 320db6f2..ed560331 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index 649412e8..a4257895 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index eda94d2d..bb8654e5 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2020 QMatrixClient project - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2020 Ram Nad +// SPDX-FileCopyrightText: 2020 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index 3d9ec4a3..6558bade 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 QMatrixClient project - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "roomcreateevent.h" diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 8328d38a..05e623ed 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 QMatrixClient project - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 2b6ac2be..4fec9d2b 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "roomevent.h" diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 3fafecfd..fea509c0 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index 66580430..332be3f7 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// SPDX-License-Identifier: LGPL-2.1-or-later + #include "roomkeyevent.h" using namespace Quotient; diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index b8cd2eae..14e80324 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2019 Alexey Andreyev +// SPDX-License-Identifier: LGPL-2.1-or-later + #pragma once #include "event.h" diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index d093286c..9634ca3a 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -1,8 +1,6 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-FileCopyrightText: 2019 Karol Kosek +// SPDX-License-Identifier: LGPL-2.1-or-later #include "roommemberevent.h" diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index b7a7c9df..f2fbe689 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -1,8 +1,7 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2015 Felix Rohrbach +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-FileCopyrightText: 2019 Karol Kosek +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 19d460b8..14824277 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -1,8 +1,7 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2015 Felix Rohrbach +// SPDX-FileCopyrightText: 2016 Kitsune Ral +// SPDX-FileCopyrightText: 2017 Roman Plášil +// SPDX-License-Identifier: LGPL-2.1-or-later #include "roommessageevent.h" diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index ebc9d564..8303ce4e 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -1,8 +1,7 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2015 Felix Rohrbach +// SPDX-FileCopyrightText: 2016 Kitsune Ral +// SPDX-FileCopyrightText: 2017 Roman Plášil +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/roompowerlevelsevent.cpp b/lib/events/roompowerlevelsevent.cpp index 0a401752..8d262ddf 100644 --- a/lib/events/roompowerlevelsevent.cpp +++ b/lib/events/roompowerlevelsevent.cpp @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2019 Black Hat +// SPDX-License-Identifier: LGPL-2.1-or-later + #include "roompowerlevelsevent.h" #include diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index b832230e..0346fc0d 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: 2019 Black Hat +// SPDX-License-Identifier: LGPL-2.1-or-later + #pragma once #include "eventcontent.h" diff --git a/lib/events/roomtombstoneevent.cpp b/lib/events/roomtombstoneevent.cpp index 163e1d3a..080d269c 100644 --- a/lib/events/roomtombstoneevent.cpp +++ b/lib/events/roomtombstoneevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 QMatrixClient project - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "roomtombstoneevent.h" diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 8d50aba0..30e53738 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2019 QMatrixClient project - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2019 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 58ba3b5a..d6261a8f 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 7bde12bb..42fc9054 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "stateevent.h" diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 0db37767..1415f709 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2018 Kitsune Ral - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index 7d3f71e5..e97e978f 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #include "typingevent.h" diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 8ca4f8e4..7456100a 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -1,8 +1,5 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2015 Felix Rohrbach - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ +// SPDX-FileCopyrightText: 2017 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once -- cgit v1.2.3 From 17e62b85cae99d8485be44f90f0622e4ba843fa0 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Sun, 10 Jan 2021 23:26:57 +0100 Subject: Add more properties to CallCandidateEvent --- lib/events/callcandidatesevent.h | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'lib/events') diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index b9de7556..c2ccac3b 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2017 Marius Gripsgard // SPDX-FileCopyrightText: 2018 Josip Delic // SPDX-FileCopyrightText: 2018 Kitsune Ral +// SPDX-FileCopyrightText: 2020 Carl Schwan // SPDX-License-Identifier: LGPL-2.1-or-later #pragma once @@ -26,6 +27,16 @@ public: { return content("candidates"_ls); } + + QString callId() const + { + return content("call_id"); + } + + int version() const + { + return content("version"); + } }; REGISTER_EVENT_TYPE(CallCandidatesEvent) -- cgit v1.2.3 From b850edadde2299b122a5cd17da85e943430e43b7 Mon Sep 17 00:00:00 2001 From: Roland Pallai Date: Thu, 28 Jan 2021 14:58:11 +0100 Subject: Fix rich replies json format (transmit) With this patch it looks like: "m.relates_to": { "m.in_reply_to": { "event_id": "$another:event.com" } } instead of: "m.relates_to": { "event_id": "$another:event.com", "rel_type": "m.in_reply_to" }, So it fits the specification by now. https://matrix.org/docs/spec/client_server/r0.6.1#rich-replies --- lib/events/roommessageevent.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 14824277..3fccb380 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -325,7 +325,10 @@ void TextContent::fillJson(QJsonObject* json) const } if (relatesTo) { json->insert(QStringLiteral("m.relates_to"), - QJsonObject { { "rel_type", relatesTo->type }, { EventIdKey, relatesTo->eventId } }); + relatesTo->type == RelatesTo::ReplyTypeId() ? + QJsonObject { { relatesTo->type, QJsonObject{ { EventIdKey, relatesTo->eventId } } } } : + QJsonObject { { "rel_type", relatesTo->type }, { EventIdKey, relatesTo->eventId } } + ); if (relatesTo->type == RelatesTo::ReplacementTypeId()) { QJsonObject newContentJson; if (mimeType.inherits("text/html")) { -- cgit v1.2.3 From df6b2d31ec8f2f5890826719e960f450a4968f22 Mon Sep 17 00:00:00 2001 From: Roland Pallai Date: Thu, 28 Jan 2021 15:05:33 +0100 Subject: Fix rich edits (transmit) The new formatted_body was not included into new content on edit due to badly constructed json. --- lib/events/roommessageevent.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 14824277..4a733772 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -329,8 +329,8 @@ void TextContent::fillJson(QJsonObject* json) const if (relatesTo->type == RelatesTo::ReplacementTypeId()) { QJsonObject newContentJson; if (mimeType.inherits("text/html")) { - json->insert(FormatKey, HtmlContentTypeId); - json->insert(FormattedBodyKey, body); + newContentJson.insert(FormatKey, HtmlContentTypeId); + newContentJson.insert(FormattedBodyKey, body); } json->insert(QStringLiteral("m.new_content"), newContentJson); } -- cgit v1.2.3 From ec60e76d585813ea54a22b58d6fabc52f113e4b1 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 21 Feb 2021 20:47:36 +0100 Subject: Update a comment that still mentions Riot (cherry picked from commit b25785d294669f2bab7dcd1e3cd1fba61991fe46) --- lib/events/roommessageevent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index a9d9754f..31c0fd9e 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -300,7 +300,7 @@ TextContent::TextContent(const QJsonObject& json) const auto actualJson = isReplacement(relatesTo) ? json.value("m.new_content"_ls).toObject() : json; - // Special-casing the custom matrix.org's (actually, Riot's) way + // Special-casing the custom matrix.org's (actually, Element's) way // of sending HTML messages. if (actualJson["format"_ls].toString() == HtmlContentTypeId) { mimeType = HtmlMimeType; -- cgit v1.2.3 From a95d5e83b4d0ab3a9bf2adef1ae4246adc317d04 Mon Sep 17 00:00:00 2001 From: Arnav Rawat Date: Thu, 11 Mar 2021 16:09:55 -0600 Subject: Support for pinned messages Fixes issue #188 --- lib/events/simplestateevents.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index d6261a8f..f22f313d 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -71,4 +71,21 @@ public: QStringList aliases() const { return content().value; } }; REGISTER_EVENT_TYPE(RoomAliasesEvent) + +class RoomPinnedEvent + : public StateEvent> +{ +public: + DEFINE_EVENT_TYPEID("m.room.pinned_messages", RoomPinnedEvent) + + explicit RoomPinnedEvent(const QJsonObject& json) + : StateEvent(typeId(), json, QStringLiteral("pinned")) + { } + explicit RoomPinnedEvent(const QStringList& roomEvents) + : StateEvent(typeId(), matrixTypeId(), {}, + QStringLiteral("pinned"), roomEvents) + { } + QStringList pinnedEvents() const { return content().value; } +}; +REGISTER_EVENT_TYPE(RoomPinnedEvent) } // namespace Quotient -- cgit v1.2.3 From 17bf4d180297c7e87363e179b8afa79ddb15dca7 Mon Sep 17 00:00:00 2001 From: Arnav Rawat Date: Tue, 25 May 2021 14:01:51 -0500 Subject: Fixes --- lib/events/simplestateevents.h | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index f22f313d..c977cb6e 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -55,6 +55,7 @@ namespace EventContent { DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", QString, topic) +DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) class RoomAliasesEvent : public StateEvent> { @@ -71,21 +72,4 @@ public: QStringList aliases() const { return content().value; } }; REGISTER_EVENT_TYPE(RoomAliasesEvent) - -class RoomPinnedEvent - : public StateEvent> -{ -public: - DEFINE_EVENT_TYPEID("m.room.pinned_messages", RoomPinnedEvent) - - explicit RoomPinnedEvent(const QJsonObject& json) - : StateEvent(typeId(), json, QStringLiteral("pinned")) - { } - explicit RoomPinnedEvent(const QStringList& roomEvents) - : StateEvent(typeId(), matrixTypeId(), {}, - QStringLiteral("pinned"), roomEvents) - { } - QStringList pinnedEvents() const { return content().value; } -}; -REGISTER_EVENT_TYPE(RoomPinnedEvent) } // namespace Quotient -- cgit v1.2.3 From 67ea5b45701e6bd5bf244039dc60a134d67a4cab Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 13 Jun 2021 14:08:52 +0200 Subject: Disable the piece depending on Qt Multimedia for Qt 6 Waiting for the Multimedia arrival in Qt 6.2. --- lib/events/roommessageevent.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 31c0fd9e..3f6e475d 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -10,7 +10,9 @@ #include #include #include -#include +#if QT_VERSION_MAJOR < 6 +# include +#endif using namespace Quotient; using namespace EventContent; @@ -149,7 +151,11 @@ TypedBase* contentFromFile(const QFileInfo& file, bool asGenericFile) // done by starting to play the file. Left for a future implementation. if (mimeTypeName.startsWith("video/")) return new VideoContent(localUrl, file.size(), mimeType, +#if QT_VERSION_MAJOR < 6 QMediaResource(localUrl).resolution(), +#else + {}, +#endif file.fileName()); if (mimeTypeName.startsWith("audio/")) -- cgit v1.2.3 From beb3a135a336dca654d967b88ea06a7457fbbec1 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 12 Jun 2021 22:31:25 +0200 Subject: EncryptionEvent: fix "too perfect forwarding" Now that QMetaType introspects into types, it reveals hidden problems (which is very nice of it). --- lib/events/encryptionevent.h | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index f9bbab12..65ee4187 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -40,6 +40,7 @@ public: // default value : StateEvent(typeId(), obj) {} + EncryptionEvent(EncryptionEvent&&) = delete; template EncryptionEvent(ArgTs&&... contentArgs) : StateEvent(typeId(), matrixTypeId(), QString(), -- cgit v1.2.3 From 9a5fa623c17f5644da7cdb459ade86bc8e1cdbf3 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 16 Jul 2021 20:02:00 +0200 Subject: Officially drop Qt Multimedia with Qt 6 Closes #483. --- lib/events/roommessageevent.cpp | 6 ++---- lib/events/roommessageevent.h | 4 ++++ 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 3f6e475d..71f85363 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -135,6 +135,7 @@ RoomMessageEvent::RoomMessageEvent(const QString& plainBody, MsgType msgType, : RoomMessageEvent(plainBody, msgTypeToJson(msgType), content) {} +#if QT_VERSION_MAJOR < 6 TypedBase* contentFromFile(const QFileInfo& file, bool asGenericFile) { auto filePath = file.absoluteFilePath(); @@ -151,11 +152,7 @@ TypedBase* contentFromFile(const QFileInfo& file, bool asGenericFile) // done by starting to play the file. Left for a future implementation. if (mimeTypeName.startsWith("video/")) return new VideoContent(localUrl, file.size(), mimeType, -#if QT_VERSION_MAJOR < 6 QMediaResource(localUrl).resolution(), -#else - {}, -#endif file.fileName()); if (mimeTypeName.startsWith("audio/")) @@ -172,6 +169,7 @@ RoomMessageEvent::RoomMessageEvent(const QString& plainBody, : rawMsgTypeForFile(file), contentFromFile(file, asGenericFile)) {} +#endif RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj), _content(nullptr) diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 8303ce4e..7bcda2ba 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -42,8 +42,12 @@ public: explicit RoomMessageEvent(const QString& plainBody, MsgType msgType = MsgType::Text, EventContent::TypedBase* content = nullptr); +#if QT_VERSION_MAJOR < 6 + [[deprecated("Create an EventContent object on the client side" + " and pass it to other constructors")]] // explicit RoomMessageEvent(const QString& plainBody, const QFileInfo& file, bool asGenericFile = false); +#endif explicit RoomMessageEvent(const QJsonObject& obj); MsgType msgtype() const; -- cgit v1.2.3 From 004ebf8d5ba095ca1b11e30d86cedc2ff8c0cfe7 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 18 Jul 2021 18:22:28 +0200 Subject: Room::postFile(): adjust to the changed RoomMessageEvent API 9a5fa623 dropped one of RoomMessageEvent constructors for Qt 6 in order to address #483 - breaking the build with Qt 6 along the way, as Room::postFile() relied on that constructor. This commit changes Room::postFile() in turn, deprecating the current signature and adding a new one that accepts an EventContent object rather than a path to a file. In order to achieve that, FileInfo and ImageInfo classes have gained new constructors that accept QFileInfo instead of the legacy series of parameters, streamlining usage of EventContent structures. --- lib/events/eventcontent.cpp | 51 ++++++++++++++++++++++++++++++++------------ lib/events/eventcontent.h | 23 ++++++++++++-------- lib/events/roomavatarevent.h | 4 ++-- 3 files changed, 53 insertions(+), 25 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index b249b160..1f28f195 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -5,10 +5,13 @@ #include "converters.h" #include "util.h" +#include "logging.h" #include +#include using namespace Quotient::EventContent; +using std::move; QJsonObject Base::toJson() const { @@ -17,22 +20,37 @@ QJsonObject Base::toJson() const return o; } -FileInfo::FileInfo(const QUrl& u, qint64 payloadSize, const QMimeType& mimeType, - const QString& originalFilename) +FileInfo::FileInfo(const QFileInfo &fi) + : mimeType(QMimeDatabase().mimeTypeForFile(fi)) + , url(QUrl::fromLocalFile(fi.filePath())) + , payloadSize(fi.size()) + , originalName(fi.fileName()) +{ + Q_ASSERT(fi.isFile()); +} + +FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, + QString originalFilename) : mimeType(mimeType) - , url(u) + , url(move(u)) , payloadSize(payloadSize) - , originalName(originalFilename) -{} + , originalName(move(originalFilename)) +{ + if (!isValid()) + qCWarning(MESSAGES) + << "To client developers: using FileInfo(QUrl, qint64, ...) " + "constructor for non-mxc resources is deprecated since Quotient " + "0.7; for local resources, use FileInfo(QFileInfo) instead"; +} -FileInfo::FileInfo(const QUrl& u, const QJsonObject& infoJson, - const QString& originalFilename) +FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, + QString originalFilename) : originalInfoJson(infoJson) , mimeType( QMimeDatabase().mimeTypeForName(infoJson["mimetype"_ls].toString())) - , url(u) + , url(move(mxcUrl)) , payloadSize(fromJson(infoJson["size"_ls])) - , originalName(originalFilename) + , originalName(move(originalFilename)) { if (!mimeType.isValid()) mimeType = QMimeDatabase().mimeTypeForData(QByteArray()); @@ -53,14 +71,19 @@ void FileInfo::fillInfoJson(QJsonObject* infoJson) const infoJson->insert(QStringLiteral("mimetype"), mimeType.name()); } -ImageInfo::ImageInfo(const QUrl& u, qint64 fileSize, QMimeType mimeType, - const QSize& imageSize, const QString& originalFilename) - : FileInfo(u, fileSize, mimeType, originalFilename), imageSize(imageSize) +ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) + : FileInfo(fi), imageSize(imageSize) +{} + +ImageInfo::ImageInfo(const QUrl& mxcUrl, qint64 fileSize, const QMimeType& type, + QSize imageSize, const QString& originalFilename) + : FileInfo(mxcUrl, fileSize, type, originalFilename) + , imageSize(imageSize) {} -ImageInfo::ImageInfo(const QUrl& u, const QJsonObject& infoJson, +ImageInfo::ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, const QString& originalFilename) - : FileInfo(u, infoJson, originalFilename) + : FileInfo(mxcUrl, infoJson, originalFilename) , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) {} diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 60d1f7b7..78c5b287 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -10,7 +10,8 @@ #include #include #include -#include + +class QFileInfo; namespace Quotient { namespace EventContent { @@ -73,11 +74,13 @@ namespace EventContent { */ class FileInfo { public: - explicit FileInfo(const QUrl& u, qint64 payloadSize = -1, + FileInfo() = default; + explicit FileInfo(const QFileInfo& fi); + explicit FileInfo(QUrl mxcUrl, qint64 payloadSize = -1, const QMimeType& mimeType = {}, - const QString& originalFilename = {}); - FileInfo(const QUrl& u, const QJsonObject& infoJson, - const QString& originalFilename = {}); + QString originalFilename = {}); + FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, + QString originalFilename = {}); bool isValid() const; @@ -113,10 +116,12 @@ namespace EventContent { */ class ImageInfo : public FileInfo { public: - explicit ImageInfo(const QUrl& u, qint64 fileSize = -1, - QMimeType mimeType = {}, const QSize& imageSize = {}, + ImageInfo() = default; + explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); + explicit ImageInfo(const QUrl& mxcUrl, qint64 fileSize = -1, + const QMimeType& type = {}, QSize imageSize = {}, const QString& originalFilename = {}); - ImageInfo(const QUrl& u, const QJsonObject& infoJson, + ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, const QString& originalFilename = {}); void fillInfoJson(QJsonObject* infoJson) const; @@ -134,7 +139,7 @@ namespace EventContent { */ class Thumbnail : public ImageInfo { public: - Thumbnail() : ImageInfo(QUrl()) {} // To allow empty thumbnails + Thumbnail() = default; // Allow empty thumbnails Thumbnail(const QJsonObject& infoJson); Thumbnail(const ImageInfo& info) : ImageInfo(info) {} using ImageInfo::ImageInfo; diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index a4257895..3fa11a0f 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -20,12 +20,12 @@ public: : StateEvent(typeId(), matrixTypeId(), QString(), avatar) {} // A replica of EventContent::ImageInfo constructor - explicit RoomAvatarEvent(const QUrl& u, qint64 fileSize = -1, + explicit RoomAvatarEvent(const QUrl& mxcUrl, qint64 fileSize = -1, QMimeType mimeType = {}, const QSize& imageSize = {}, const QString& originalFilename = {}) : RoomAvatarEvent(EventContent::ImageContent { - u, fileSize, mimeType, imageSize, originalFilename }) + mxcUrl, fileSize, mimeType, imageSize, originalFilename }) {} QUrl url() const { return content().url; } -- cgit v1.2.3 From 86fe0a8f0682c0122439d53cc96b4b742a69ffcf Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 18 Jul 2021 18:24:39 +0200 Subject: Make EventContent::TypedBase() constructor protected TypedBase is an abstract class; constructing it doesn't make sense. But even if it were not abstract, it's not supposed to be instantiated. --- lib/events/eventcontent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 78c5b287..b3a5f280 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -153,13 +153,13 @@ namespace EventContent { class TypedBase : public Base { public: - explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} virtual QMimeType type() const = 0; virtual const FileInfo* fileInfo() const { return nullptr; } virtual FileInfo* fileInfo() { return nullptr; } virtual const Thumbnail* thumbnailInfo() const { return nullptr; } protected: + explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} using Base::Base; }; -- cgit v1.2.3 From 6d24915e4bdd56dbdace8358297ee9d2d9aa83a0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 18 Jul 2021 18:53:57 +0200 Subject: Revert previous commit Q_DECLARE_METATYPE is really unhappy about types without a public default constructor. --- lib/events/eventcontent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index b3a5f280..78c5b287 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -153,13 +153,13 @@ namespace EventContent { class TypedBase : public Base { public: + explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} virtual QMimeType type() const = 0; virtual const FileInfo* fileInfo() const { return nullptr; } virtual FileInfo* fileInfo() { return nullptr; } virtual const Thumbnail* thumbnailInfo() const { return nullptr; } protected: - explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} using Base::Base; }; -- cgit v1.2.3 From 110190d48a80a471e6d10d048602390b35e7ed07 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 18 Jul 2021 18:24:39 +0200 Subject: Re-apply the previous commit and actually fix the breakage Ok, it was stupid to delete #include in 004ebf8d and then to expect that Qt macros would still work, given that I don't use QObject. In my defense I can only say that with Qt 6 it still compiled. --- lib/events/eventcontent.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 78c5b287..1d81bd72 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -10,6 +10,7 @@ #include #include #include +#include class QFileInfo; @@ -153,13 +154,13 @@ namespace EventContent { class TypedBase : public Base { public: - explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} virtual QMimeType type() const = 0; virtual const FileInfo* fileInfo() const { return nullptr; } virtual FileInfo* fileInfo() { return nullptr; } virtual const Thumbnail* thumbnailInfo() const { return nullptr; } protected: + explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} using Base::Base; }; -- cgit v1.2.3 From c05b5c2b79f9ab301fee587ee781b9c8e18b8a2f Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 16 Jul 2021 20:03:06 +0200 Subject: MembershipType -> Membership, also used for JoinState Instead of being defined independently, JoinState now uses values from the Membership enumeration (former MemberEventContent::MembershipType) that was moved to quotient_common.h for that purpose. Both enumerations gained a Q_FLAG_NS decoration and operator<< overrides that strip "Quotient::" prefix when dumping member/join state values to the log - obviating toCString(JoinState) along the way. Quotient::MembershipType alias is deprecated from now. --- lib/events/roommemberevent.cpp | 65 +++++++++++++++++++++--------------------- lib/events/roommemberevent.h | 26 ++++++++--------- 2 files changed, 45 insertions(+), 46 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 9634ca3a..8a6bddd8 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -7,27 +7,26 @@ #include "converters.h" #include "logging.h" -#include - -static const std::array membershipStrings = { - { QStringLiteral("invite"), QStringLiteral("join"), QStringLiteral("knock"), - QStringLiteral("leave"), QStringLiteral("ban") } -}; +#include namespace Quotient { template <> -struct JsonConverter { - static MembershipType load(const QJsonValue& jv) +struct JsonConverter { + static Membership load(const QJsonValue& jv) { - const auto& membershipString = jv.toString(); - for (auto it = membershipStrings.begin(); it != membershipStrings.end(); - ++it) - if (membershipString == *it) - return MembershipType(it - membershipStrings.begin()); - - if (!membershipString.isEmpty()) - qCWarning(EVENTS) << "Unknown MembershipType: " << membershipString; - return MembershipType::Undefined; + const auto& ms = jv.toString(); + if (ms.isEmpty()) + { + qCWarning(EVENTS) << "Empty member state:" << ms; + return Membership::Invalid; + } + const auto it = + std::find(MembershipStrings.begin(), MembershipStrings.end(), ms); + if (it != MembershipStrings.end()) + return Membership(1U << (it - MembershipStrings.begin())); + + qCWarning(EVENTS) << "Unknown Membership value: " << ms; + return Membership::Invalid; } }; } // namespace Quotient @@ -35,7 +34,7 @@ struct JsonConverter { using namespace Quotient; MemberEventContent::MemberEventContent(const QJsonObject& json) - : membership(fromJson(json["membership"_ls])) + : membership(fromJson(json["membership"_ls])) , isDirect(json["is_direct"_ls].toBool()) , displayName(fromJson>(json["displayname"_ls])) , avatarUrl(fromJson>(json["avatar_url"_ls])) @@ -48,10 +47,12 @@ MemberEventContent::MemberEventContent(const QJsonObject& json) void MemberEventContent::fillJson(QJsonObject* o) const { Q_ASSERT(o); - Q_ASSERT_X(membership != MembershipType::Undefined, __FUNCTION__, - "The key 'membership' must be explicit in MemberEventContent"); - if (membership != MembershipType::Undefined) - o->insert(QStringLiteral("membership"), membershipStrings[membership]); + if (membership != Membership::Invalid) + o->insert( + QStringLiteral("membership"), + MembershipStrings[qCountTrailingZeroBits( + std::underlying_type_t(membership)) + + 1]); if (displayName) o->insert(QStringLiteral("displayname"), *displayName); if (avatarUrl && avatarUrl->isValid()) @@ -67,37 +68,37 @@ bool RoomMemberEvent::changesMembership() const bool RoomMemberEvent::isInvite() const { - return membership() == MembershipType::Invite && changesMembership(); + return membership() == Membership::Invite && changesMembership(); } bool RoomMemberEvent::isRejectedInvite() const { - return membership() == MembershipType::Leave && prevContent() - && prevContent()->membership == MembershipType::Invite; + return membership() == Membership::Leave && prevContent() + && prevContent()->membership == Membership::Invite; } bool RoomMemberEvent::isJoin() const { - return membership() == MembershipType::Join && changesMembership(); + return membership() == Membership::Join && changesMembership(); } bool RoomMemberEvent::isLeave() const { - return membership() == MembershipType::Leave && prevContent() + return membership() == Membership::Leave && prevContent() && prevContent()->membership != membership() - && prevContent()->membership != MembershipType::Ban - && prevContent()->membership != MembershipType::Invite; + && prevContent()->membership != Membership::Ban + && prevContent()->membership != Membership::Invite; } bool RoomMemberEvent::isBan() const { - return membership() == MembershipType::Ban && changesMembership(); + return membership() == Membership::Ban && changesMembership(); } bool RoomMemberEvent::isUnban() const { - return membership() == MembershipType::Leave && prevContent() - && prevContent()->membership == MembershipType::Ban; + return membership() == Membership::Leave && prevContent() + && prevContent()->membership == Membership::Ban; } bool RoomMemberEvent::isRename() const diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index f2fbe689..f3047159 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -7,23 +7,21 @@ #include "eventcontent.h" #include "stateevent.h" +#include "quotient_common.h" namespace Quotient { class MemberEventContent : public EventContent::Base { public: - enum MembershipType : unsigned char { - Invite = 0, - Join, - Knock, - Leave, - Ban, - Undefined - }; + using MembershipType + [[deprecated("Use Quotient::Membership instead")]] = Membership; - explicit MemberEventContent(MembershipType mt = Join) : membership(mt) {} + explicit MemberEventContent(Membership ms = Membership::Join) + : membership(ms) + {} explicit MemberEventContent(const QJsonObject& json); - MembershipType membership; + Membership membership; + /// (Only for invites) Whether the invite is to a direct chat bool isDirect = false; Omittable displayName; Omittable avatarUrl; @@ -33,15 +31,15 @@ protected: void fillJson(QJsonObject* o) const override; }; -using MembershipType = MemberEventContent::MembershipType; +using MembershipType [[deprecated("Use Membership instead")]] = Membership; class RoomMemberEvent : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) - using MembershipType = MemberEventContent::MembershipType; - Q_ENUM(MembershipType) + using MembershipType + [[deprecated("Use Quotient::Membership instead")]] = Membership; explicit RoomMemberEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} @@ -65,7 +63,7 @@ public: : StateEvent(type, fullJson) {} - MembershipType membership() const { return content().membership; } + Membership membership() const { return content().membership; } QString userId() const { return stateKey(); } bool isDirect() const { return content().isDirect; } Omittable newDisplayName() const { return content().displayName; } -- cgit v1.2.3 From e4a08bc431be9a2b680a4cd70f2ceda07c99b7bf Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 18 Jul 2021 20:10:35 +0200 Subject: Fix bit rot in comments --- lib/events/eventcontent.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 1d81bd72..40ec3a49 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -49,13 +49,14 @@ namespace EventContent { // but specific aggregation structure is altered. See doc comments to // each type for the list of available attributes. - // A quick classes inheritance structure follows: + // A quick classes inheritance structure follows (the definitions are + // spread across eventcontent.h and roommessageevent.h): // FileInfo - // FileContent : UrlBasedContent - // AudioContent : UrlBasedContent + // FileContent : UrlWithThumbnailContent + // AudioContent : PlayableContent> // ImageInfo : FileInfo + imageSize attribute - // ImageContent : UrlBasedContent - // VideoContent : UrlBasedContent + // ImageContent : UrlWithThumbnailContent + // VideoContent : PlayableContent> /** * A base/mixin class for structures representing an "info" object for -- cgit v1.2.3 From e0d9125de7ac132c2a54152015687abbe5e73193 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 30 Jul 2021 08:10:48 +0200 Subject: Room: drop 0.6 deprecations; deprecate RoomAliasEvent Namely memberCount(), localAliases(), remoteAliases(), timelineEdge(). --- lib/events/simplestateevents.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index d6261a8f..3bac54e6 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -56,8 +56,10 @@ namespace EventContent { DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", QString, topic) -class RoomAliasesEvent - : public StateEvent> { +class [[deprecated( + "m.room.aliases events are deprecated by the Matrix spec; use" + " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases")]] // +RoomAliasesEvent : public StateEvent> { public: DEFINE_EVENT_TYPEID("m.room.aliases", RoomAliasesEvent) explicit RoomAliasesEvent(const QJsonObject& obj) -- cgit v1.2.3 From 7ee1681d7640b7e7683f7bb40bf768704a48832c Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 30 Jul 2021 08:22:13 +0200 Subject: Clean up after the previous commit RoomAliasesEvent is no more even registered (meaning that the library will load m.room.aliases as unknown state events); quotest code updated to use historyEdge() instead of timelineEdge(). --- lib/events/simplestateevents.h | 1 - 1 file changed, 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 3bac54e6..cf1bfbba 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -72,5 +72,4 @@ public: QString server() const { return stateKey(); } QStringList aliases() const { return content().value; } }; -REGISTER_EVENT_TYPE(RoomAliasesEvent) } // namespace Quotient -- cgit v1.2.3 From ea1e849f617f62b3d209b2019e0daa3c6bed50f0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 2 Aug 2021 09:02:31 +0200 Subject: More doc-comments --- lib/events/roomevent.h | 4 ++++ lib/events/roommessageevent.h | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index fea509c0..3abd56c0 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -37,6 +37,10 @@ public: } QString roomId() const; QString senderId() const; + //! \brief Determine whether the event has been replaced + //! + //! \return true if this event has been overridden by another event + //! with `"rel_type": "m.replace"`; false otherwise bool isReplaced() const; QString replacedBy() const; bool isRedacted() const { return bool(_redactedBecause); } diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 7bcda2ba..88d3b74c 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -62,9 +62,26 @@ public: _content.data()); } QMimeType mimeType() const; + //! \brief Determine whether the message has text content + //! + //! \return true, if the message type is one of m.text, m.notice, m.emote, + //! or the message type is unspecified (in which case plainBody() + //! can still be examined); false otherwise bool hasTextContent() const; + //! \brief Determine whether the message has a file/attachment + //! + //! \return true, if the message has a data structure corresponding to + //! a file (such as m.file or m.audio); false otherwise bool hasFileContent() const; + //! \brief Determine whether the message has a thumbnail + //! + //! \return true, if the message has a data structure corresponding to + //! a thumbnail (the message type may be one for visual content, + //! such as m.image, or generic binary content, i.e. m.file); + //! false otherwise bool hasThumbnail() const; + //! \brief Obtain id of an event replaced by the current one + //! \sa RoomEvent::isReplaced, RoomEvent::replacedBy QString replacedEvent() const; static QString rawMsgTypeForUrl(const QUrl& url); -- cgit v1.2.3 From c26015503aa0fbca37abdfc4870ac94bb7befeee Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 22 Aug 2021 20:19:15 +0200 Subject: Drop other stuff deprecated pre- or early 0.6 BaseJob: StatusCode::JsonParseError Connection: resolved() and reconnected() signals; roomMap(); postReceipt() User: bridged() and rawName() ConnectionData: setHost() and setPort() StateEventBase: prev_content() --- lib/events/stateevent.h | 4 ---- 1 file changed, 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 1415f709..bc414a5f 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -100,10 +100,6 @@ public: visitor(_content); editJson()[ContentKeyL] = _content.toJson(); } - [[deprecated("Use prevContent instead")]] const ContentT* prev_content() const - { - return prevContent(); - } const ContentT* prevContent() const { return _prev ? &_prev->content : nullptr; -- cgit v1.2.3 From fd42d1dbd29800ef53ab9997c948f39a92aa8bff Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 22 Aug 2021 20:23:42 +0200 Subject: RoomEvent: drop timestamp() Use originTimestamp(); the corresponding Q_PROPERTY was not renamed (in error) so it is now. --- lib/events/roomevent.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 3abd56c0..3174764f 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -14,7 +14,9 @@ class RedactionEvent; class RoomEvent : public Event { Q_GADGET Q_PROPERTY(QString id READ id) - Q_PROPERTY(QDateTime timestamp READ timestamp CONSTANT) + //! \deprecated Use originTimestamp instead + Q_PROPERTY(QDateTime timestamp READ originTimestamp CONSTANT) + Q_PROPERTY(QDateTime originTimestamp READ originTimestamp CONSTANT) Q_PROPERTY(QString roomId READ roomId CONSTANT) Q_PROPERTY(QString senderId READ senderId CONSTANT) Q_PROPERTY(QString redactionReason READ redactionReason) @@ -32,9 +34,6 @@ public: QString id() const; QDateTime originTimestamp() const; - [[deprecated("Use originTimestamp()")]] QDateTime timestamp() const { - return originTimestamp(); - } QString roomId() const; QString senderId() const; //! \brief Determine whether the event has been replaced -- cgit v1.2.3 From 0209be8305aa38722a3d25593ae71fbb3ac05e52 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sat, 11 Sep 2021 16:18:35 +0200 Subject: Add convenience function for activating encryption and fix EncryptionEvent constructor --- lib/events/encryptionevent.cpp | 8 ++++++++ lib/events/encryptionevent.h | 4 +--- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 490a5e8a..aa05a96e 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -39,6 +39,14 @@ EncryptionEventContent::EncryptionEventContent(const QJsonObject& json) , rotationPeriodMsgs(json[RotationPeriodMsgsKeyL].toInt(100)) {} +EncryptionEventContent::EncryptionEventContent(EncryptionType et) + : encryption(et) +{ + if(encryption != Undefined) { + algorithm = encryptionStrings[encryption]; + } +} + void EncryptionEventContent::fillJson(QJsonObject* o) const { Q_ASSERT(o); diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 65ee4187..14439fcc 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -12,9 +12,7 @@ class EncryptionEventContent : public EventContent::Base { public: enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; - explicit EncryptionEventContent(EncryptionType et = Undefined) - : encryption(et) - {} + explicit EncryptionEventContent(EncryptionType et = Undefined); explicit EncryptionEventContent(const QJsonObject& json); EncryptionType encryption; -- cgit v1.2.3 From 59c9ca720093f2931c2eee1c0d5806d7e2e0c85f Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 13 Sep 2021 16:05:46 +0200 Subject: Add room types to RoomCreateEvent --- lib/events/roomcreateevent.cpp | 21 +++++++++++++++++++++ lib/events/roomcreateevent.h | 2 ++ 2 files changed, 23 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index 6558bade..ff93041c 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -5,6 +5,22 @@ using namespace Quotient; +template <> +struct Quotient::JsonConverter { + static RoomType load(const QJsonValue& jv) + { + const auto& roomTypeString = jv.toString(); + for (auto it = RoomTypeStrings.begin(); it != RoomTypeStrings.end(); + ++it) + if (roomTypeString == *it) + return RoomType(it - RoomTypeStrings.begin()); + + if (!roomTypeString.isEmpty()) + qCWarning(EVENTS) << "Unknown Room Type: " << roomTypeString; + return RoomType::Undefined; + } +}; + bool RoomCreateEvent::isFederated() const { return fromJson(contentJson()["m.federate"_ls]); @@ -26,3 +42,8 @@ bool RoomCreateEvent::isUpgrade() const { return contentJson().contains("predecessor"_ls); } + +RoomType RoomCreateEvent::roomType() const +{ + return fromJson(contentJson()["type"_ls]); +} diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 05e623ed..b3ad287c 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -4,6 +4,7 @@ #pragma once #include "stateevent.h" +#include "quotient_common.h" namespace Quotient { class RoomCreateEvent : public StateEventBase { @@ -24,6 +25,7 @@ public: QString version() const; Predecessor predecessor() const; bool isUpgrade() const; + RoomType roomType() const; }; REGISTER_EVENT_TYPE(RoomCreateEvent) } // namespace Quotient -- cgit v1.2.3 From fe9425f313e7c172095ff9355743427337b7ea78 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 13 Sep 2021 19:14:19 +0200 Subject: Add the encryptedfile to the eventcontent --- lib/events/encryptedfile.h | 88 +++++++++++++++++++++++++++++++++++++++++ lib/events/eventcontent.cpp | 20 +++++++--- lib/events/eventcontent.h | 17 ++++++-- lib/events/roomavatarevent.h | 2 +- lib/events/roommessageevent.cpp | 8 ++-- 5 files changed, 121 insertions(+), 14 deletions(-) create mode 100644 lib/events/encryptedfile.h (limited to 'lib/events') diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h new file mode 100644 index 00000000..24ac9de1 --- /dev/null +++ b/lib/events/encryptedfile.h @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// +// SPDX-License-Identifier: LGPl-2.1-or-later + +#pragma once + +#include "converters.h" + +namespace Quotient { +/** + * JSON Web Key object as specified in + * https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes + * The only currently relevant member is `k`, the rest needs to be set to the defaults specified in the spec. + */ +struct JWK +{ + Q_GADGET + Q_PROPERTY(QString kty MEMBER kty CONSTANT) + Q_PROPERTY(QStringList keyOps MEMBER keyOps CONSTANT) + Q_PROPERTY(QString alg MEMBER alg CONSTANT) + Q_PROPERTY(QString k MEMBER k CONSTANT) + Q_PROPERTY(bool ext MEMBER ext CONSTANT) + +public: + QString kty; + QStringList keyOps; + QString alg; + QString k; + bool ext; +}; + +struct EncryptedFile +{ + Q_GADGET + Q_PROPERTY(QUrl url MEMBER url CONSTANT) + Q_PROPERTY(JWK key MEMBER key CONSTANT) + Q_PROPERTY(QString iv MEMBER iv CONSTANT) + Q_PROPERTY(QHash hashes MEMBER hashes CONSTANT) + Q_PROPERTY(QString v MEMBER v CONSTANT) + +public: + QUrl url; + JWK key; + QString iv; + QHash hashes; + QString v; +}; + +template <> +struct JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const EncryptedFile& pod) + { + addParam<>(jo, QStringLiteral("url"), pod.url); + addParam<>(jo, QStringLiteral("key"), pod.key); + addParam<>(jo, QStringLiteral("iv"), pod.iv); + addParam<>(jo, QStringLiteral("hashes"), pod.hashes); + addParam<>(jo, QStringLiteral("v"), pod.v); + } + static void fillFrom(const QJsonObject& jo, EncryptedFile& pod) + { + fromJson(jo.value("url"_ls), pod.url); + fromJson(jo.value("key"_ls), pod.key); + fromJson(jo.value("iv"_ls), pod.iv); + fromJson(jo.value("hashes"_ls), pod.hashes); + fromJson(jo.value("v"_ls), pod.v); + } +}; + +template <> +struct JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const JWK& pod) + { + addParam<>(jo, QStringLiteral("kty"), pod.kty); + addParam<>(jo, QStringLiteral("key_ops"), pod.keyOps); + addParam<>(jo, QStringLiteral("alg"), pod.alg); + addParam<>(jo, QStringLiteral("k"), pod.k); + addParam<>(jo, QStringLiteral("ext"), pod.ext); + } + static void fillFrom(const QJsonObject& jo, JWK& pod) + { + fromJson(jo.value("kty"_ls), pod.kty); + fromJson(jo.value("key_ops"_ls), pod.keyOps); + fromJson(jo.value("alg"_ls), pod.alg); + fromJson(jo.value("k"_ls), pod.k); + fromJson(jo.value("ext"_ls), pod.ext); + } +}; +} // namespace Quotient diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 1f28f195..22878d4c 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -30,11 +30,12 @@ FileInfo::FileInfo(const QFileInfo &fi) } FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, - QString originalFilename) + Omittable file, QString originalFilename) : mimeType(mimeType) , url(move(u)) , payloadSize(payloadSize) , originalName(move(originalFilename)) + , file(file) { if (!isValid()) qCWarning(MESSAGES) @@ -44,6 +45,7 @@ FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, } FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, + const Omittable &file, QString originalFilename) : originalInfoJson(infoJson) , mimeType( @@ -51,7 +53,11 @@ FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, , url(move(mxcUrl)) , payloadSize(fromJson(infoJson["size"_ls])) , originalName(move(originalFilename)) + , file(file) { + if(url.isEmpty() && file.has_value()) { + url = file->url; + } if (!mimeType.isValid()) mimeType = QMimeDatabase().mimeTypeForData(QByteArray()); } @@ -76,14 +82,15 @@ ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) {} ImageInfo::ImageInfo(const QUrl& mxcUrl, qint64 fileSize, const QMimeType& type, - QSize imageSize, const QString& originalFilename) - : FileInfo(mxcUrl, fileSize, type, originalFilename) + QSize imageSize, const Omittable &file, const QString& originalFilename) + : FileInfo(mxcUrl, fileSize, type, file, originalFilename) , imageSize(imageSize) {} ImageInfo::ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, + const Omittable &file, const QString& originalFilename) - : FileInfo(mxcUrl, infoJson, originalFilename) + : FileInfo(mxcUrl, infoJson, file, originalFilename) , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) {} @@ -96,9 +103,10 @@ void ImageInfo::fillInfoJson(QJsonObject* infoJson) const infoJson->insert(QStringLiteral("h"), imageSize.height()); } -Thumbnail::Thumbnail(const QJsonObject& infoJson) +Thumbnail::Thumbnail(const QJsonObject& infoJson, const Omittable &file) : ImageInfo(QUrl(infoJson["thumbnail_url"_ls].toString()), - infoJson["thumbnail_info"_ls].toObject()) + infoJson["thumbnail_info"_ls].toObject(), + file) {} void Thumbnail::fillInfoJson(QJsonObject* infoJson) const diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 40ec3a49..f609a603 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -12,6 +12,8 @@ #include #include +#include "encryptedfile.h" + class QFileInfo; namespace Quotient { @@ -80,8 +82,10 @@ namespace EventContent { explicit FileInfo(const QFileInfo& fi); explicit FileInfo(QUrl mxcUrl, qint64 payloadSize = -1, const QMimeType& mimeType = {}, + Omittable file = none, QString originalFilename = {}); FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, + const Omittable &file, QString originalFilename = {}); bool isValid() const; @@ -103,6 +107,7 @@ namespace EventContent { QUrl url; qint64 payloadSize; QString originalName; + Omittable file = none; }; template @@ -122,8 +127,10 @@ namespace EventContent { explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); explicit ImageInfo(const QUrl& mxcUrl, qint64 fileSize = -1, const QMimeType& type = {}, QSize imageSize = {}, + const Omittable &file = none, const QString& originalFilename = {}); ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, + const Omittable &encryptedFile, const QString& originalFilename = {}); void fillInfoJson(QJsonObject* infoJson) const; @@ -142,7 +149,7 @@ namespace EventContent { class Thumbnail : public ImageInfo { public: Thumbnail() = default; // Allow empty thumbnails - Thumbnail(const QJsonObject& infoJson); + Thumbnail(const QJsonObject& infoJson, const Omittable &file = none); Thumbnail(const ImageInfo& info) : ImageInfo(info) {} using ImageInfo::ImageInfo; @@ -182,7 +189,7 @@ namespace EventContent { explicit UrlBasedContent(const QJsonObject& json) : TypedBase(json) , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), - json["filename"].toString()) + fromJson>(json["file"]), json["filename"].toString()) { // A small hack to facilitate links creation in QML. originalJson.insert("mediaId", InfoT::mediaId()); @@ -196,7 +203,11 @@ namespace EventContent { void fillJson(QJsonObject* json) const override { Q_ASSERT(json); - json->insert("url", InfoT::url.toString()); + if (!InfoT::file.has_value()) { + json->insert("url", InfoT::url.toString()); + } else { + json->insert("file", Quotient::toJson(*InfoT::file)); + } if (!InfoT::originalName.isEmpty()) json->insert("filename", InfoT::originalName); json->insert("info", toInfoJson(*this)); diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index 3fa11a0f..8618ba31 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -25,7 +25,7 @@ public: const QSize& imageSize = {}, const QString& originalFilename = {}) : RoomAvatarEvent(EventContent::ImageContent { - mxcUrl, fileSize, mimeType, imageSize, originalFilename }) + mxcUrl, fileSize, mimeType, imageSize, none, originalFilename }) {} QUrl url() const { return content().url; } diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 71f85363..9b46594e 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -145,21 +145,21 @@ TypedBase* contentFromFile(const QFileInfo& file, bool asGenericFile) auto mimeTypeName = mimeType.name(); if (mimeTypeName.startsWith("image/")) return new ImageContent(localUrl, file.size(), mimeType, - QImageReader(filePath).size(), + QImageReader(filePath).size(), none, file.fileName()); // duration can only be obtained asynchronously and can only be reliably // done by starting to play the file. Left for a future implementation. if (mimeTypeName.startsWith("video/")) return new VideoContent(localUrl, file.size(), mimeType, - QMediaResource(localUrl).resolution(), + QMediaResource(localUrl).resolution(), none, file.fileName()); if (mimeTypeName.startsWith("audio/")) - return new AudioContent(localUrl, file.size(), mimeType, + return new AudioContent(localUrl, file.size(), mimeType, none, file.fileName()); } - return new FileContent(localUrl, file.size(), mimeType, file.fileName()); + return new FileContent(localUrl, file.size(), mimeType, none, file.fileName()); } RoomMessageEvent::RoomMessageEvent(const QString& plainBody, -- cgit v1.2.3 From fc0fdf2ed6006c11ffd47675fabb1232721c5e7d Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 12 Oct 2021 09:26:09 +0200 Subject: RoomMemberEvent::is*(): fix comparison against Omittable Closes #514. --- lib/events/roommemberevent.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 8a6bddd8..469dbb32 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -103,16 +103,14 @@ bool RoomMemberEvent::isUnban() const bool RoomMemberEvent::isRename() const { - auto prevName = prevContent() && prevContent()->displayName - ? *prevContent()->displayName - : QString(); - return newDisplayName() != prevName; + return prevContent() && prevContent()->displayName + ? newDisplayName() != *prevContent()->displayName + : newDisplayName().has_value(); } bool RoomMemberEvent::isAvatarUpdate() const { - auto prevAvatarUrl = prevContent() && prevContent()->avatarUrl - ? *prevContent()->avatarUrl - : QUrl(); - return newAvatarUrl() != prevAvatarUrl; + return prevContent() && prevContent()->avatarUrl + ? newAvatarUrl() != *prevContent()->avatarUrl + : newAvatarUrl().has_value(); } -- cgit v1.2.3 From 061de37889b0fa4bf8baae1f11693950297418c5 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 8 Nov 2021 14:46:56 +0100 Subject: Q_DISABLE_MOVE/COPY_MOVE; QT_IGNORE_DEPRECATIONS DISABLE_MOVE is no more; instead, the library provides Q_DISABLE_MOVE (and also Q_DISABLE_COPY_MOVE while at it) for Qt pre-5.13 that don't have it yet. Same for QT_IGNORE_DEPRECATIONS - it only arrived in 5.15 but all the building pieces existed prior so libQuotient has it regardless of the Qt version used for building. --- lib/events/event.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index f8f8311d..78853ced 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -76,8 +76,7 @@ public: private: EventTypeRegistry() = default; - Q_DISABLE_COPY(EventTypeRegistry) - DISABLE_MOVE(EventTypeRegistry) + Q_DISABLE_COPY_MOVE(EventTypeRegistry) static EventTypeRegistry& get() { -- cgit v1.2.3 From f2bf3f203965c51824e8681427798f7a09784ce3 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 11 Nov 2021 22:18:18 +0100 Subject: Make ReceiptEvent constructible from content Makes the Room::P::toJson() code more readable. --- lib/events/receiptevent.cpp | 29 +++++++++++++++++++++++++---- lib/events/receiptevent.h | 5 +++-- 2 files changed, 28 insertions(+), 6 deletions(-) (limited to 'lib/events') diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index 4185d92d..72dbf2e3 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -25,6 +25,27 @@ Example of a Receipt Event: using namespace Quotient; +// The library loads the event-ids-to-receipts JSON map into a vector because +// map lookups are not used and vectors are massively faster. Same goes for +// de-/serialization of ReceiptsForEvent::receipts. +// (XXX: would this be generally preferred across CS API JSON maps?..) +QJsonObject toJson(const EventsWithReceipts& ewrs) +{ + QJsonObject json; + for (const auto& e : ewrs) { + QJsonObject receiptsJson; + for (const auto& r : e.receipts) + receiptsJson.insert(r.userId, + QJsonObject { { "ts"_ls, toJson(r.timestamp) } }); + json.insert(e.evtId, QJsonObject { { "m.read"_ls, receiptsJson } }); + } + return json; +} + +ReceiptEvent::ReceiptEvent(const EventsWithReceipts &ewrs) + : Event(typeId(), matrixTypeId(), toJson(ewrs)) +{} + EventsWithReceipts ReceiptEvent::eventsWithReceipts() const { EventsWithReceipts result; @@ -39,14 +60,14 @@ EventsWithReceipts ReceiptEvent::eventsWithReceipts() const } const auto reads = eventIt.value().toObject().value("m.read"_ls).toObject(); - QVector receipts; - receipts.reserve(reads.size()); + QVector usersAtEvent; + usersAtEvent.reserve(reads.size()); for (auto userIt = reads.begin(); userIt != reads.end(); ++userIt) { const auto user = userIt.value().toObject(); - receipts.push_back( + usersAtEvent.push_back( { userIt.key(), fromJson(user["ts"_ls]) }); } - result.push_back({ eventIt.key(), std::move(receipts) }); + result.push_back({ eventIt.key(), std::move(usersAtEvent) }); } return result; } diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index 4feec9ea..9683deef 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -9,19 +9,20 @@ #include namespace Quotient { -struct Receipt { +struct UserTimestamp { QString userId; QDateTime timestamp; }; struct ReceiptsForEvent { QString evtId; - QVector receipts; + QVector receipts; }; using EventsWithReceipts = QVector; class ReceiptEvent : public Event { public: DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) + explicit ReceiptEvent(const EventsWithReceipts& ewrs); explicit ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) {} EventsWithReceipts eventsWithReceipts() const; -- cgit v1.2.3 From 2d1cf137d7380a15673826bce00e71461fbc7446 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 19 Nov 2021 12:46:00 +0100 Subject: Cleanup --- lib/events/roommemberevent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 469dbb32..b0bc7bcb 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -17,7 +17,7 @@ struct JsonConverter { const auto& ms = jv.toString(); if (ms.isEmpty()) { - qCWarning(EVENTS) << "Empty member state:" << ms; + qCWarning(EVENTS) << "Empty membership state"; return Membership::Invalid; } const auto it = -- cgit v1.2.3 From f6155d62740a88b020273ba623c816f7b9805772 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 26 Nov 2021 13:44:39 +0100 Subject: Drop Q_GADGET from most uncopyable classes; other minor cleanup Q_GADGET is generally used to enable two things outside of QObject: Q_PROPERTY/Q_INVOKABLE and Q_ENUM/Q_FLAG. While the latter can be used in its own right in QML, the former requires Q_GADGET instances to be passed to QML by value, which is not really possible with uncopyable/unassignable classes. Bottom line is that Q_PROPERTY in anything derived from Quotient::Event is not viable, making Q_GADGET macro useless unless there's a Q_ENUM/Q_FLAG (as is the case with RoomMessageEvent, e.g.). --- lib/events/encryptedevent.h | 2 -- lib/events/event.h | 3 --- lib/events/roomevent.h | 41 +++++++++++++---------------------------- lib/events/roommessageevent.h | 4 ---- lib/events/stateevent.h | 2 -- 5 files changed, 13 insertions(+), 39 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index eb7123eb..598829cd 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -7,7 +7,6 @@ #include "roomevent.h" namespace Quotient { -class Room; /* * While the specification states: * @@ -27,7 +26,6 @@ class Room; * one and doesn't add new restrictions, just provides additional features. */ class EncryptedEvent : public RoomEvent { - Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.encrypted", EncryptedEvent) diff --git a/lib/events/event.h b/lib/events/event.h index 78853ced..2ed5de5d 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -195,9 +195,6 @@ inline auto registerEventType() // === Event === class Event { - Q_GADGET - Q_PROPERTY(Type type READ type CONSTANT) - Q_PROPERTY(QJsonObject contentJson READ contentJson CONSTANT) public: using Type = event_type_t; using factory_t = EventFactory; diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 3174764f..a6cd84ca 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -12,16 +12,6 @@ class RedactionEvent; /** This class corresponds to m.room.* events */ class RoomEvent : public Event { - Q_GADGET - Q_PROPERTY(QString id READ id) - //! \deprecated Use originTimestamp instead - Q_PROPERTY(QDateTime timestamp READ originTimestamp CONSTANT) - Q_PROPERTY(QDateTime originTimestamp READ originTimestamp CONSTANT) - Q_PROPERTY(QString roomId READ roomId CONSTANT) - Q_PROPERTY(QString senderId READ senderId CONSTANT) - Q_PROPERTY(QString redactionReason READ redactionReason) - Q_PROPERTY(bool isRedacted READ isRedacted) - Q_PROPERTY(QString transactionId READ transactionId WRITE setTransactionId) public: using factory_t = EventFactory; @@ -51,28 +41,23 @@ public: QString transactionId() const; QString stateKey() const; + //! \brief Fill the pending event object with the room id void setRoomId(const QString& roomId); + //! \brief Fill the pending event object with the sender id void setSender(const QString& senderId); - - /** - * Sets the transaction id for locally created events. This should be - * done before the event is exposed to any code using the respective - * Q_PROPERTY. - * - * \param txnId - transaction id, normally obtained from - * Connection::generateTxnId() - */ + //! \brief Fill the pending event object with the transaction id + //! \param txnId - transaction id, normally obtained from + //! Connection::generateTxnId() void setTransactionId(const QString& txnId); - /** - * Sets event id for locally created events - * - * When a new event is created locally, it has no server id yet. - * This function allows to add the id once the confirmation from - * the server is received. There should be no id set previously - * in the event. It's the responsibility of the code calling addId() - * to notify clients that use Q_PROPERTY(id) about its change - */ + //! \brief Add an event id to locally created events after they are sent + //! + //! When a new event is created locally, it has no id; the homeserver + //! assigns it once the event is sent. This function allows to add the id + //! once the confirmation from the server is received. There should be no id + //! set previously in the event. It's the responsibility of the code calling + //! addId() to notify clients about the change; there's no signal or + //! callback for that in RoomEvent. void addId(const QString& newId); protected: diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 88d3b74c..56597ddc 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -18,10 +18,6 @@ namespace MessageEventContent = EventContent; // Back-compatibility */ class RoomMessageEvent : public RoomEvent { Q_GADGET - Q_PROPERTY(QString msgType READ rawMsgtype CONSTANT) - Q_PROPERTY(QString plainBody READ plainBody CONSTANT) - Q_PROPERTY(QMimeType mimeType READ mimeType STORED false CONSTANT) - Q_PROPERTY(const EventContent::TypedBase* content READ content CONSTANT) public: DEFINE_EVENT_TYPEID("m.room.message", RoomMessageEvent) diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index bc414a5f..b0aa9907 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -18,8 +18,6 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, } class StateEventBase : public RoomEvent { - Q_GADGET - Q_PROPERTY(QString stateKey READ stateKey CONSTANT) public: using factory_t = EventFactory; -- cgit v1.2.3 From f4a0acf818c4c89d132b2ec96d47c5817b106149 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 26 Nov 2021 13:46:58 +0100 Subject: Drop #include "logging.h" from event.h Makes compilation a tad lighter. --- lib/events/callanswerevent.cpp | 1 + lib/events/callhangupevent.cpp | 1 + lib/events/callinviteevent.cpp | 1 + lib/events/encryptedevent.cpp | 11 ++++++++--- lib/events/encryptedevent.h | 14 ++++---------- lib/events/encryptionevent.cpp | 1 + lib/events/event.cpp | 11 ++++++++--- lib/events/event.h | 5 +++-- lib/events/reactionevent.cpp | 1 + lib/events/roomcreateevent.cpp | 1 + lib/events/roomkeyevent.cpp | 1 + 11 files changed, 30 insertions(+), 18 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index be83d9d0..24144585 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "callanswerevent.h" +#include "logging.h" /* m.call.answer diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp index 43bc4db0..537ace75 100644 --- a/lib/events/callhangupevent.cpp +++ b/lib/events/callhangupevent.cpp @@ -6,6 +6,7 @@ */ #include "callhangupevent.h" +#include "logging.h" /* m.call.hangup diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 5ea54662..ce4fb101 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "callinviteevent.h" +#include "logging.h" /* m.call.invite diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 0290f973..ebf733ac 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" +#include "logging.h" using namespace Quotient; @@ -25,8 +26,12 @@ EncryptedEvent::EncryptedEvent(QByteArray ciphertext, const QString& senderKey, }) {} -EncryptedEvent::EncryptedEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) +QString EncryptedEvent::algorithm() const { - qCDebug(E2EE) << "Encrypted event from" << senderId(); + const auto algo = content(AlgorithmKeyL); + if (!SupportedAlgorithms.contains(algo)) { + qCWarning(MAIN) << "The EncryptedEvent's algorithm" << algo + << "is not supported"; + } + return algo; } diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 598829cd..d2b71785 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -37,17 +37,11 @@ public: /* In case with Megolm, device_id and session_id are required */ explicit EncryptedEvent(QByteArray ciphertext, const QString& senderKey, const QString& deviceId, const QString& sessionId); - explicit EncryptedEvent(const QJsonObject& obj); + explicit EncryptedEvent(const QJsonObject& obj) + : RoomEvent(typeId(), obj) + {} - QString algorithm() const - { - QString algo = content(AlgorithmKeyL); - if (!SupportedAlgorithms.contains(algo)) { - qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo - << "is not supported"; - } - return algo; - } + QString algorithm() const; QByteArray ciphertext() const { return content(CiphertextKeyL).toLatin1(); diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index aa05a96e..9eb48844 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptionevent.h" +#include "logging.h" #include "e2ee.h" diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 3d66ab55..305dd454 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -9,15 +9,20 @@ using namespace Quotient; +void Quotient::logFactorySetup(event_mtype_t eventTypeId) +{ + qCDebug(EVENTS) << "Adding factory method for" << eventTypeId; +} + event_type_t EventTypeRegistry::initializeTypeId(event_mtype_t matrixTypeId) { const auto id = get().eventTypes.size(); get().eventTypes.push_back(matrixTypeId); if (strncmp(matrixTypeId, "", 1) == 0) - qDebug(EVENTS) << "Initialized unknown event type with id" << id; + qCDebug(EVENTS) << "Initialized unknown event type with id" << id; else - qDebug(EVENTS) << "Initialized event type" << matrixTypeId << "with id" - << id; + qCDebug(EVENTS) << "Initialized event type" << matrixTypeId << "with id" + << id; return id; } diff --git a/lib/events/event.h b/lib/events/event.h index 2ed5de5d..e9963eae 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -4,7 +4,6 @@ #pragma once #include "converters.h" -#include "logging.h" namespace Quotient { // === event_ptr_tt<> and type casting facilities === @@ -162,6 +161,8 @@ private: } }; +void logFactorySetup(event_mtype_t eventTypeId); + /** Add a type to its default factory * Adds a standard factory method (via makeEvent<>) for a given * type to EventT::factory_t factory class so that it can be @@ -174,7 +175,7 @@ private: template inline auto setupFactory() { - qDebug(EVENTS) << "Adding factory method for" << EventT::matrixTypeId(); + logFactorySetup(EventT::matrixTypeId()); return EventT::factory_t::addMethod([](const QJsonObject& json, const QString& jsonMatrixType) { return EventT::matrixTypeId() == jsonMatrixType ? makeEvent(json) diff --git a/lib/events/reactionevent.cpp b/lib/events/reactionevent.cpp index b53fffd6..bb62f0e0 100644 --- a/lib/events/reactionevent.cpp +++ b/lib/events/reactionevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "reactionevent.h" +#include "logging.h" using namespace Quotient; diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index ff93041c..e119696f 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "roomcreateevent.h" +#include "logging.h" using namespace Quotient; diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index 332be3f7..dbcb35bd 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "roomkeyevent.h" +#include "logging.h" using namespace Quotient; -- cgit v1.2.3 From b3d62050befbb1c526f03e4356f3263d197c45f2 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 26 Nov 2021 14:02:49 +0100 Subject: Event: deprecate originalJson[Object]() The "original JSON" wording is misleading: the returned JSON can be and is routinely edited as a part of event construction, redaction, editing. Also, originalJson() name is misleading in that it returns a stringified (in a very specific way) JSON and not an object. You have to call fullJson() to get the object, and originalJsonObject(), confusingly, returns exactly the same thing but as a value rather than as a reference. The original intention of keeping originalJsonObject() was to make it Q_INVOKABLE or use it as an accessor for a Q_PROPERTY. unfortunately, this was never really practical as discussed in the previous commit. All that implies that clients have to handle passing event JSON to QML themselves, in the form they prefer (as an object or a string). The added complexity is negligible though; on the other hand, there's added flexibility in, e.g., choosing a compact instead of default JSON layout or even generate a highlighted JSON representation. --- lib/events/event.h | 3 +++ 1 file changed, 3 insertions(+) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index e9963eae..52e3d025 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -210,7 +210,10 @@ public: Type type() const { return _type; } QString matrixType() const; + [[deprecated("Use fullJson() and stringify it with QJsonDocument::toJson() " + "or by other means")]] QByteArray originalJson() const; + [[deprecated("Use fullJson() instead")]] // QJsonObject originalJsonObject() const { return fullJson(); } const QJsonObject& fullJson() const { return _json; } -- cgit v1.2.3 From 4ba795556721a88d2ac258d9095a46de21d77011 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 26 Nov 2021 16:07:25 +0100 Subject: Revert "Drop #include "logging.h" from event.h" Doesn't really help build times, instead breaking the build on older Qt. --- lib/events/callanswerevent.cpp | 1 - lib/events/callhangupevent.cpp | 1 - lib/events/callinviteevent.cpp | 1 - lib/events/encryptedevent.cpp | 11 +++-------- lib/events/encryptedevent.h | 14 ++++++++++---- lib/events/encryptionevent.cpp | 1 - lib/events/event.cpp | 11 +++-------- lib/events/event.h | 5 ++--- lib/events/reactionevent.cpp | 1 - lib/events/roomcreateevent.cpp | 1 - lib/events/roomkeyevent.cpp | 1 - 11 files changed, 18 insertions(+), 30 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index 24144585..be83d9d0 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -3,7 +3,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "callanswerevent.h" -#include "logging.h" /* m.call.answer diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp index 537ace75..43bc4db0 100644 --- a/lib/events/callhangupevent.cpp +++ b/lib/events/callhangupevent.cpp @@ -6,7 +6,6 @@ */ #include "callhangupevent.h" -#include "logging.h" /* m.call.hangup diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index ce4fb101..5ea54662 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -3,7 +3,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "callinviteevent.h" -#include "logging.h" /* m.call.invite diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index ebf733ac..0290f973 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,7 +2,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" -#include "logging.h" using namespace Quotient; @@ -26,12 +25,8 @@ EncryptedEvent::EncryptedEvent(QByteArray ciphertext, const QString& senderKey, }) {} -QString EncryptedEvent::algorithm() const +EncryptedEvent::EncryptedEvent(const QJsonObject& obj) + : RoomEvent(typeId(), obj) { - const auto algo = content(AlgorithmKeyL); - if (!SupportedAlgorithms.contains(algo)) { - qCWarning(MAIN) << "The EncryptedEvent's algorithm" << algo - << "is not supported"; - } - return algo; + qCDebug(E2EE) << "Encrypted event from" << senderId(); } diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index d2b71785..598829cd 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -37,11 +37,17 @@ public: /* In case with Megolm, device_id and session_id are required */ explicit EncryptedEvent(QByteArray ciphertext, const QString& senderKey, const QString& deviceId, const QString& sessionId); - explicit EncryptedEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) - {} + explicit EncryptedEvent(const QJsonObject& obj); - QString algorithm() const; + QString algorithm() const + { + QString algo = content(AlgorithmKeyL); + if (!SupportedAlgorithms.contains(algo)) { + qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo + << "is not supported"; + } + return algo; + } QByteArray ciphertext() const { return content(CiphertextKeyL).toLatin1(); diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 9eb48844..aa05a96e 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -3,7 +3,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptionevent.h" -#include "logging.h" #include "e2ee.h" diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 305dd454..3d66ab55 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -9,20 +9,15 @@ using namespace Quotient; -void Quotient::logFactorySetup(event_mtype_t eventTypeId) -{ - qCDebug(EVENTS) << "Adding factory method for" << eventTypeId; -} - event_type_t EventTypeRegistry::initializeTypeId(event_mtype_t matrixTypeId) { const auto id = get().eventTypes.size(); get().eventTypes.push_back(matrixTypeId); if (strncmp(matrixTypeId, "", 1) == 0) - qCDebug(EVENTS) << "Initialized unknown event type with id" << id; + qDebug(EVENTS) << "Initialized unknown event type with id" << id; else - qCDebug(EVENTS) << "Initialized event type" << matrixTypeId << "with id" - << id; + qDebug(EVENTS) << "Initialized event type" << matrixTypeId << "with id" + << id; return id; } diff --git a/lib/events/event.h b/lib/events/event.h index 52e3d025..89efb7f8 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -4,6 +4,7 @@ #pragma once #include "converters.h" +#include "logging.h" namespace Quotient { // === event_ptr_tt<> and type casting facilities === @@ -161,8 +162,6 @@ private: } }; -void logFactorySetup(event_mtype_t eventTypeId); - /** Add a type to its default factory * Adds a standard factory method (via makeEvent<>) for a given * type to EventT::factory_t factory class so that it can be @@ -175,7 +174,7 @@ void logFactorySetup(event_mtype_t eventTypeId); template inline auto setupFactory() { - logFactorySetup(EventT::matrixTypeId()); + qDebug(EVENTS) << "Adding factory method for" << EventT::matrixTypeId(); return EventT::factory_t::addMethod([](const QJsonObject& json, const QString& jsonMatrixType) { return EventT::matrixTypeId() == jsonMatrixType ? makeEvent(json) diff --git a/lib/events/reactionevent.cpp b/lib/events/reactionevent.cpp index bb62f0e0..b53fffd6 100644 --- a/lib/events/reactionevent.cpp +++ b/lib/events/reactionevent.cpp @@ -2,7 +2,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "reactionevent.h" -#include "logging.h" using namespace Quotient; diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index e119696f..ff93041c 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -2,7 +2,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "roomcreateevent.h" -#include "logging.h" using namespace Quotient; diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index dbcb35bd..332be3f7 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -2,7 +2,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "roomkeyevent.h" -#include "logging.h" using namespace Quotient; -- cgit v1.2.3 From 0425fd280e7eee7a4c9bcf18f79910f181322c42 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 27 Nov 2021 20:14:53 +0100 Subject: Event::content() -> contentPart() There's a clash between Event::content() (a template function) and RoomMessageEvent::content() (plain member). Out of these two, the name more fits to the RME's member function - strictly speaking, Event::content() retrieves a part of content, and so is renamed. In addition, contentPart() defaults to QJsonValue now, which is pretty intuitive (the function returns values from a JSON object) and allows to implement more elaborate logic such as if (const auto v = contentPart<>("key"_ls); v.isObject()) { // foo } else if (v.isString()) { // bar } else { // boo } --- lib/events/accountdataevents.h | 2 +- lib/events/callanswerevent.h | 4 ++-- lib/events/callcandidatesevent.h | 6 +++--- lib/events/callinviteevent.h | 4 ++-- lib/events/encryptedevent.h | 12 ++++++------ lib/events/event.h | 15 +++++++++++---- lib/events/reactionevent.h | 2 +- lib/events/redactionevent.h | 2 +- lib/events/roomcreateevent.cpp | 8 ++++---- lib/events/roomevent.h | 4 ++-- lib/events/roomkeyevent.h | 8 ++++---- lib/events/roommessageevent.cpp | 4 ++-- lib/events/roomtombstoneevent.cpp | 4 ++-- lib/events/stickerevent.cpp | 2 +- lib/events/typingevent.cpp | 2 +- 15 files changed, 43 insertions(+), 36 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 8cea0ec8..7715d3b8 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -63,7 +63,7 @@ using TagsMap = QHash; {} \ auto _ContentKey() const \ { \ - return content(#_ContentKey##_ls); \ + return contentPart(#_ContentKey##_ls); \ } \ }; \ REGISTER_EVENT_TYPE(_Name) \ diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 6132cb44..4c01c941 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -19,11 +19,11 @@ public: int lifetime() const { - return content("lifetime"_ls); + return contentPart("lifetime"_ls); } // FIXME: Omittable<>? QString sdp() const { - return contentJson()["answer"_ls].toObject().value("sdp"_ls).toString(); + return contentPart("answer"_ls).value("sdp"_ls).toString(); } }; diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index c2ccac3b..74c38f2c 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -25,17 +25,17 @@ public: QJsonArray candidates() const { - return content("candidates"_ls); + return contentPart("candidates"_ls); } QString callId() const { - return content("call_id"); + return contentPart("call_id"); } int version() const { - return content("version"); + return contentPart("version"); } }; diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index d3454c4f..80b7d651 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -18,11 +18,11 @@ public: int lifetime() const { - return content("lifetime"_ls); + return contentPart("lifetime"_ls); } // FIXME: Omittable<>? QString sdp() const { - return contentJson()["offer"_ls].toObject().value("sdp"_ls).toString(); + return contentPart("offer"_ls).value("sdp"_ls).toString(); } }; diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 598829cd..de89a7c6 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -41,7 +41,7 @@ public: QString algorithm() const { - QString algo = content(AlgorithmKeyL); + QString algo = contentPart(AlgorithmKeyL); if (!SupportedAlgorithms.contains(algo)) { qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo << "is not supported"; @@ -50,17 +50,17 @@ public: } QByteArray ciphertext() const { - return content(CiphertextKeyL).toLatin1(); + return contentPart(CiphertextKeyL).toLatin1(); } QJsonObject ciphertext(const QString& identityKey) const { - return content(CiphertextKeyL).value(identityKey).toObject(); + return contentPart(CiphertextKeyL).value(identityKey).toObject(); } - QString senderKey() const { return content(SenderKeyKeyL); } + QString senderKey() const { return contentPart(SenderKeyKeyL); } /* device_id and session_id are required with Megolm */ - QString deviceId() const { return content(DeviceIdKeyL); } - QString sessionId() const { return content(SessionIdKeyL); } + QString deviceId() const { return contentPart(DeviceIdKeyL); } + QString sessionId() const { return contentPart(SessionIdKeyL); } }; REGISTER_EVENT_TYPE(EncryptedEvent) diff --git a/lib/events/event.h b/lib/events/event.h index 89efb7f8..024e45ef 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -224,18 +224,25 @@ public: const QJsonObject contentJson() const; const QJsonObject unsignedJson() const; - template - T content(const QString& key) const + template + const T contentPart(const QString& key) const { return fromJson(contentJson()[key]); } - template - T content(QLatin1String key) const + template + const T contentPart(QLatin1String key) const { return fromJson(contentJson()[key]); } + template + [[deprecated("Use contentPart() to get a part of the event content")]] // + T content(const QString& key) const + { + return contentPart(key); + } + friend QDebug operator<<(QDebug dbg, const Event& e) { QDebugStateSaver _dss { dbg }; diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index 777905f2..5a2b98c4 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -47,7 +47,7 @@ public: explicit ReactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} EventRelation relation() const { - return content(QStringLiteral("m.relates_to")); + return contentPart("m.relates_to"_ls); } }; REGISTER_EVENT_TYPE(ReactionEvent) diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index ed560331..be20bf52 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -17,7 +17,7 @@ public: { return fullJson()["redacts"_ls].toString(); } - QString reason() const { return contentJson()["reason"_ls].toString(); } + QString reason() const { return contentPart("reason"_ls); } }; REGISTER_EVENT_TYPE(RedactionEvent) } // namespace Quotient diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index ff93041c..bb6de648 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -23,17 +23,17 @@ struct Quotient::JsonConverter { bool RoomCreateEvent::isFederated() const { - return fromJson(contentJson()["m.federate"_ls]); + return contentPart("m.federate"_ls); } QString RoomCreateEvent::version() const { - return fromJson(contentJson()["room_version"_ls]); + return contentPart("room_version"_ls); } RoomCreateEvent::Predecessor RoomCreateEvent::predecessor() const { - const auto predJson = contentJson()["predecessor"_ls].toObject(); + const auto predJson = contentPart("predecessor"_ls); return { fromJson(predJson[RoomIdKeyL]), fromJson(predJson[EventIdKeyL]) }; } @@ -45,5 +45,5 @@ bool RoomCreateEvent::isUpgrade() const RoomType RoomCreateEvent::roomType() const { - return fromJson(contentJson()["type"_ls]); + return contentPart("type"_ls); } diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index a6cd84ca..7f13f6f2 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -78,8 +78,8 @@ public: ~CallEventBase() override = default; bool isCallEvent() const override { return true; } - QString callId() const { return content("call_id"_ls); } - int version() const { return content("version"_ls); } + QString callId() const { return contentPart("call_id"_ls); } + int version() const { return contentPart("version"_ls); } }; } // namespace Quotient Q_DECLARE_METATYPE(Quotient::RoomEvent*) diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 14e80324..d021fbec 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -13,10 +13,10 @@ public: explicit RoomKeyEvent(const QJsonObject& obj); - QString algorithm() const { return content("algorithm"_ls); } - QString roomId() const { return content(RoomIdKeyL); } - QString sessionId() const { return content("session_id"_ls); } - QString sessionKey() const { return content("session_key"_ls); } + QString algorithm() const { return contentPart("algorithm"_ls); } + QString roomId() const { return contentPart(RoomIdKeyL); } + QString sessionId() const { return contentPart("session_id"_ls); } + QString sessionKey() const { return contentPart("session_key"_ls); } }; REGISTER_EVENT_TYPE(RoomKeyEvent) } // namespace Quotient diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 9b46594e..2b7b4166 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -204,12 +204,12 @@ RoomMessageEvent::MsgType RoomMessageEvent::msgtype() const QString RoomMessageEvent::rawMsgtype() const { - return contentJson()[MsgTypeKeyL].toString(); + return contentPart(MsgTypeKeyL); } QString RoomMessageEvent::plainBody() const { - return contentJson()[BodyKeyL].toString(); + return contentPart(BodyKeyL); } QMimeType RoomMessageEvent::mimeType() const diff --git a/lib/events/roomtombstoneevent.cpp b/lib/events/roomtombstoneevent.cpp index 080d269c..2c3492d6 100644 --- a/lib/events/roomtombstoneevent.cpp +++ b/lib/events/roomtombstoneevent.cpp @@ -7,10 +7,10 @@ using namespace Quotient; QString RoomTombstoneEvent::serverMessage() const { - return fromJson(contentJson()["body"_ls]); + return contentPart("body"_ls); } QString RoomTombstoneEvent::successorRoomId() const { - return fromJson(contentJson()["replacement_room"_ls]); + return contentPart("replacement_room"_ls); } diff --git a/lib/events/stickerevent.cpp b/lib/events/stickerevent.cpp index ea4dff3f..628fd154 100644 --- a/lib/events/stickerevent.cpp +++ b/lib/events/stickerevent.cpp @@ -12,7 +12,7 @@ StickerEvent::StickerEvent(const QJsonObject &obj) QString StickerEvent::body() const { - return content("body"_ls); + return contentPart("body"_ls); } const EventContent::ImageContent &StickerEvent::image() const diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index e97e978f..7e5d7ee6 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -7,5 +7,5 @@ using namespace Quotient; QStringList TypingEvent::users() const { - return fromJson(contentJson()["user_ids"_ls]); + return contentPart("user_ids"_ls); } -- cgit v1.2.3 From ce4e878040946b963b30c4768847e2be24dd77fa Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 27 Nov 2021 22:53:02 +0100 Subject: basicEventJson(): dismiss with the template Given that QJsonObject only accepts QStrings in the list constructor, the template is useless cruft. --- lib/events/event.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 024e45ef..733fadd8 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -48,11 +48,10 @@ static const auto PrevContentKeyL = "prev_content"_ls; static const auto StateKeyKeyL = "state_key"_ls; /// Make a minimal correct Matrix event JSON -template -inline QJsonObject basicEventJson(StrT matrixType, const QJsonObject& content) +inline QJsonObject basicEventJson(const QString& matrixType, + const QJsonObject& content) { - return { { TypeKey, std::forward(matrixType) }, - { ContentKey, content } }; + return { { TypeKey, matrixType }, { ContentKey, content } }; } // === Event types and event types registry === -- cgit v1.2.3 From ab91944cc71a72699d0168b7c472326e59319477 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 28 Nov 2021 11:19:08 +0100 Subject: Event::unsignedPart() Similar to contentPart() - apparently there are enough places across the code that would benefit from it. --- lib/events/event.h | 21 +++++++++++---------- lib/events/roomevent.cpp | 10 +++++----- lib/events/stateevent.cpp | 10 +++++----- 3 files changed, 21 insertions(+), 20 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 733fadd8..e45fecca 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -221,18 +221,11 @@ public: // different types, we're implementing it per-event type. const QJsonObject contentJson() const; - const QJsonObject unsignedJson() const; - template - const T contentPart(const QString& key) const + template + const T contentPart(KeyT&& key) const { - return fromJson(contentJson()[key]); - } - - template - const T contentPart(QLatin1String key) const - { - return fromJson(contentJson()[key]); + return fromJson(contentJson()[std::forward(key)]); } template @@ -242,6 +235,14 @@ public: return contentPart(key); } + const QJsonObject unsignedJson() const; + + template + const T unsignedPart(KeyT&& key) const + { + return fromJson(unsignedJson()[std::forward(key)]); + } + friend QDebug operator<<(QDebug dbg, const Event& e) { QDebugStateSaver _dss { dbg }; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 4fec9d2b..fb921af6 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -19,7 +19,7 @@ RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, RoomEvent::RoomEvent(Type type, const QJsonObject& json) : Event(type, json) { - if (const auto redaction = unsignedJson()[RedactedCauseKeyL]; + if (const auto redaction = unsignedPart(RedactedCauseKeyL); redaction.isObject()) _redactedBecause = makeEvent(redaction.toObject()); } @@ -45,14 +45,14 @@ QString RoomEvent::senderId() const bool RoomEvent::isReplaced() const { - return unsignedJson()["m.relations"_ls].toObject().contains("m.replace"); + return unsignedPart("m.relations"_ls).contains("m.replace"); } QString RoomEvent::replacedBy() const { // clang-format off - return unsignedJson()["m.relations"_ls].toObject() - .value("m.replace").toObject() + return unsignedPart("m.relations"_ls) + .value("m.replace"_ls).toObject() .value(EventIdKeyL).toString(); // clang-format on } @@ -64,7 +64,7 @@ QString RoomEvent::redactionReason() const QString RoomEvent::transactionId() const { - return unsignedJson()["transaction_id"_ls].toString(); + return unsignedPart("transaction_id"_ls); } QString RoomEvent::stateKey() const diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 42fc9054..efe011a0 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -28,22 +28,22 @@ StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, bool StateEventBase::repeatsState() const { - const auto prevContentJson = unsignedJson().value(PrevContentKeyL); + const auto prevContentJson = unsignedPart(PrevContentKeyL); return fullJson().value(ContentKeyL) == prevContentJson; } QString StateEventBase::replacedState() const { - return unsignedJson().value("replaces_state"_ls).toString(); + return unsignedPart("replaces_state"_ls); } void StateEventBase::dumpTo(QDebug dbg) const { if (!stateKey().isEmpty()) dbg << '<' << stateKey() << "> "; - if (unsignedJson().contains(PrevContentKeyL)) - dbg << QJsonDocument(unsignedJson()[PrevContentKeyL].toObject()) - .toJson(QJsonDocument::Compact) + if (const auto prevContentJson = unsignedPart(PrevContentKeyL); + !prevContentJson.isEmpty()) + dbg << QJsonDocument(prevContentJson).toJson(QJsonDocument::Compact) << " -> "; RoomEvent::dumpTo(dbg); } -- cgit v1.2.3 From ca1ba482b50c41425bd0a540c7bb68406d10e552 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 28 Nov 2021 16:42:41 +0100 Subject: Don't std::move when the callee doesn't support it In both fixed cases the callee accepts a const reference, which makes std::move() useless. Static analyzers apparently missed them because the cases are inside a macro. --- lib/events/accountdataevents.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 7715d3b8..e5101d20 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -55,11 +55,11 @@ using TagsMap = QHash; public: \ using content_type = _ContentType; \ DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - explicit _Name(QJsonObject obj) : Event(typeId(), std::move(obj)) {} \ - explicit _Name(_ContentType content) \ + explicit _Name(const QJsonObject& obj) : Event(typeId(), obj) {} \ + explicit _Name(const content_type& content) \ : Event(typeId(), matrixTypeId(), \ - QJsonObject { { QStringLiteral(#_ContentKey), \ - toJson(std::move(content)) } }) \ + QJsonObject { \ + { QStringLiteral(#_ContentKey), toJson(content) } }) \ {} \ auto _ContentKey() const \ { \ -- cgit v1.2.3 From 8a769cddcd1a063dd9400518ff65c0b1f1aec1b4 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 28 Nov 2021 16:53:51 +0100 Subject: Comment on const return types in event.h Proper linters recognise that the returned types are not primitive, while people might still be confused a bit. --- lib/events/event.cpp | 3 --- lib/events/event.h | 3 +++ 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 3d66ab55..96be717c 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -46,14 +46,11 @@ QString Event::matrixType() const { return fullJson()[TypeKeyL].toString(); } QByteArray Event::originalJson() const { return QJsonDocument(_json).toJson(); } -// On const below: this is to catch accidental attempts to change event JSON -// NOLINTNEXTLINE(readability-const-return-type) const QJsonObject Event::contentJson() const { return fullJson()[ContentKeyL].toObject(); } -// NOLINTNEXTLINE(readability-const-return-type) const QJsonObject Event::unsignedJson() const { return fullJson()[UnsignedKeyL].toObject(); diff --git a/lib/events/event.h b/lib/events/event.h index e45fecca..998a386c 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -220,6 +220,9 @@ public: // a "content" object; but since its structure is different for // different types, we're implementing it per-event type. + // NB: const return types below are meant to catch accidental attempts + // to change event JSON (e.g., consider contentJson()["inexistentKey"]). + const QJsonObject contentJson() const; template -- cgit v1.2.3 From 9f71b2a79fba7c5d5ce09ebfdd482c8c470203d9 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Thu, 28 Jan 2021 21:59:20 +0100 Subject: Remove duplicated file --- lib/events/encryptedevent.h | 2 +- lib/events/encryptionevent.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index de89a7c6..1d7ea913 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -3,7 +3,7 @@ #pragma once -#include "e2ee.h" +#include "crypto/e2ee.h" #include "roomevent.h" namespace Quotient { diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index aa05a96e..d7bb953a 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -4,7 +4,7 @@ #include "encryptionevent.h" -#include "e2ee.h" +#include "crypto/e2ee.h" #include -- cgit v1.2.3 From 5f3e33e1c15be19f09d83a0d6f44d551021a9d44 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Fri, 5 Feb 2021 18:45:30 +0100 Subject: Implement key verification events --- lib/events/keyverificationevent.cpp | 193 ++++++++++++++++++++++++++++++++++++ lib/events/keyverificationevent.h | 167 +++++++++++++++++++++++++++++++ 2 files changed, 360 insertions(+) create mode 100644 lib/events/keyverificationevent.cpp create mode 100644 lib/events/keyverificationevent.h (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.cpp b/lib/events/keyverificationevent.cpp new file mode 100644 index 00000000..938b3bde --- /dev/null +++ b/lib/events/keyverificationevent.cpp @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "keyverificationevent.h" + +using namespace Quotient; + +KeyVerificationRequestEvent::KeyVerificationRequestEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationRequestEvent::fromDevice() const +{ + return contentJson()["from_device"_ls].toString(); +} + +QString KeyVerificationRequestEvent::transactionId() const +{ + return contentJson()["transaction_id"_ls].toString(); +} + +QStringList KeyVerificationRequestEvent::methods() const +{ + QStringList methods; + for (const auto &method : contentJson()["methods"].toArray()) { + methods.append(method.toString()); + } + return methods; +} + +uint64_t KeyVerificationRequestEvent::timestamp() const +{ + return contentJson()["timestamp"_ls].toDouble(); +} + +KeyVerificationStartEvent::KeyVerificationStartEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationStartEvent::fromDevice() const +{ + return contentJson()["from_device"_ls].toString(); +} + +QString KeyVerificationStartEvent::transactionId() const +{ + return contentJson()["transaction_id"_ls].toString(); +} + +QString KeyVerificationStartEvent::method() const +{ + return contentJson()["method"_ls].toString(); +} + +Omittable KeyVerificationStartEvent::nextMethod() const +{ + auto next = contentJson()["method"_ls]; + if (next.isUndefined()) { + return std::nullopt; + } + return next.toString(); +} + +QStringList KeyVerificationStartEvent::keyAgreementProtocols() const +{ + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + QStringList protocols; + for (const auto &proto : contentJson()["key_agreement_protocols"_ls].toArray()) { + protocols.append(proto.toString()); + } + return protocols; +} + +QStringList KeyVerificationStartEvent::hashes() const +{ + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + QStringList hashes; + for (const auto &hashItem : contentJson()["hashes"_ls].toArray()) { + hashes.append(hashItem.toString()); + } + return hashes; +} + +QStringList KeyVerificationStartEvent::messageAuthenticationCodes() const +{ + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + + QStringList codes; + for (const auto &code : contentJson()["message_authentication_codes"_ls].toArray()) { + codes.append(code.toString()); + } + return codes; +} + +QString KeyVerificationStartEvent::shortAuthenticationString() const +{ + return contentJson()["short_authentification_string"_ls].toString(); +} + +KeyVerificationAcceptEvent::KeyVerificationAcceptEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationAcceptEvent::transactionId() const +{ + return contentJson()["transaction_id"_ls].toString(); +} + +QString KeyVerificationAcceptEvent::method() const +{ + return contentJson()["method"_ls].toString(); +} + +QString KeyVerificationAcceptEvent::keyAgreementProtocol() const +{ + return contentJson()["key_agreement_protocol"_ls].toString(); +} + +QString KeyVerificationAcceptEvent::hashData() const +{ + return contentJson()["hash"_ls].toString(); +} + +QStringList KeyVerificationAcceptEvent::shortAuthenticationString() const +{ + QStringList strings; + for (const auto &authenticationString : contentJson()["short_authentification_string"].toArray()) { + strings.append(authenticationString.toString()); + } + return strings; +} + +QString KeyVerificationAcceptEvent::commitement() const +{ + return contentJson()["commitement"].toString(); +} + +KeyVerificationCancelEvent::KeyVerificationCancelEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationCancelEvent::transactionId() const +{ + return contentJson()["transaction_id"_ls].toString(); +} + +QString KeyVerificationCancelEvent::reason() const +{ + return contentJson()["reason"_ls].toString(); +} + +QString KeyVerificationCancelEvent::code() const +{ + return contentJson()["code"_ls].toString(); +} + +KeyVerificationKeyEvent::KeyVerificationKeyEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationKeyEvent::transactionId() const +{ + return contentJson()["transaction_id"_ls].toString(); +} + +QString KeyVerificationKeyEvent::key() const +{ + return contentJson()["key"_ls].toString(); +} + +KeyVerificationMacEvent::KeyVerificationMacEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationMacEvent::transactionId() const +{ + return contentJson()["transaction_id"].toString(); +} + +QString KeyVerificationMacEvent::keys() const +{ + return contentJson()["keys"].toString(); +} + +QHash KeyVerificationMacEvent::mac() const +{ + QHash macs; + const auto macObj = contentJson()["mac"_ls].toObject(); + for (auto mac = macObj.constBegin(); mac != macObj.constEnd(); mac++) { + macs.insert(mac.key(), mac.value().toString()); + } + return macs; +} diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h new file mode 100644 index 00000000..13e7dcdd --- /dev/null +++ b/lib/events/keyverificationevent.h @@ -0,0 +1,167 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "event.h" + +namespace Quotient { + +/// Requests a key verification with another user's devices. +/// Typically sent as a to-device event. +class KeyVerificationRequestEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.request", KeyVerificationRequestEvent) + + explicit KeyVerificationRequestEvent(const QJsonObject& obj); + + /// The device ID which is initiating the request. + QString fromDevice() const; + + /// An opaque identifier for the verification request. Must + /// be unique with respect to the devices involved. + QString transactionId() const; + + /// The verification methods supported by the sender. + QStringList methods() const; + + /// The POSIX timestamp in milliseconds for when the request was + /// made. If the request is in the future by more than 5 minutes or + /// more than 10 minutes in the past, the message should be ignored + /// by the receiver. + uint64_t timestamp() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationRequestEvent) + +/// Begins a key verification process. +class KeyVerificationStartEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.start", KeyVerificationStartEvent) + + explicit KeyVerificationStartEvent(const QJsonObject &obj); + + /// The device ID which is initiating the process. + QString fromDevice() const; + + /// An opaque identifier for the verification request. Must + /// be unique with respect to the devices involved. + QString transactionId() const; + + /// The verification method to use. + QString method() const; + + /// Optional method to use to verify the other user's key with. + Omittable nextMethod() const; + + // SAS.V1 methods + + /// The key agreement protocols the sending device understands. + /// \note Only exist if method is m.sas.v1 + QStringList keyAgreementProtocols() const; + + /// The hash methods the sending device understands. + /// \note Only exist if method is m.sas.v1 + QStringList hashes() const; + + /// The message authentication codes that the sending device understands. + /// \note Only exist if method is m.sas.v1 + QStringList messageAuthenticationCodes() const; + + /// The SAS methods the sending device (and the sending device's + /// user) understands. + /// \note Only exist if method is m.sas.v1 + QString shortAuthenticationString() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationStartEvent) + +/// Accepts a previously sent m.key.verification.start message. +/// Typically sent as a to-device event. +class KeyVerificationAcceptEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.accept", KeyVerificationAcceptEvent) + + explicit KeyVerificationAcceptEvent(const QJsonObject& obj); + + /// An opaque identifier for the verification process. + QString transactionId() const; + + /// The verification method to use. Must be 'm.sas.v1'. + QString method() const; + + /// The key agreement protocol the device is choosing to use, out of + /// the options in the m.key.verification.start message. + QString keyAgreementProtocol() const; + + /// The hash method the device is choosing to use, out of the + /// options in the m.key.verification.start message. + QString hashData() const; + + /// The message authentication code the device is choosing to use, out + /// of the options in the m.key.verification.start message. + QString messageAuthenticationCode() const; + + /// The SAS methods both devices involved in the verification process understand. + QStringList shortAuthenticationString() const; + + /// The hash (encoded as unpadded base64) of the concatenation of the + /// device's ephemeral public key (encoded as unpadded base64) and the + /// canonical JSON representation of the m.key.verification.start message. + QString commitement() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationAcceptEvent) + +class KeyVerificationCancelEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.cancel", KeyVerificationCancelEvent) + + explicit KeyVerificationCancelEvent(const QJsonObject &obj); + + /// An opaque identifier for the verification process. + QString transactionId() const; + + /// A human readable description of the code. The client should only + /// rely on this string if it does not understand the code. + QString reason() const; + + /// The error code for why the process/request was cancelled by the user. + QString code() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationCancelEvent) + +/// Sends the ephemeral public key for a device to the partner device. +/// Typically sent as a to-device event. +class KeyVerificationKeyEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.key", KeyVerificationKeyEvent) + + explicit KeyVerificationKeyEvent(const QJsonObject &obj); + + /// An opaque identifier for the verification process. + QString transactionId() const; + + /// The device's ephemeral public key, encoded as unpadded base64. + QString key() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationKeyEvent) + +/// Sends the MAC of a device's key to the partner device. +class KeyVerificationMacEvent : public Event { + Q_GADGET +public: + DEFINE_EVENT_TYPEID("m.key.verification.mac", KeyVerificationMacEvent) + + explicit KeyVerificationMacEvent(const QJsonObject &obj); + + /// An opaque identifier for the verification process. + QString transactionId() const; + + /// The device's ephemeral public key, encoded as unpadded base64. + QString keys() const; + + QHash mac() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationMacEvent) +} // namespace Quotient -- cgit v1.2.3 From 0583534d83f902235b46ef6761d6698ddb6e6aba Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Wed, 18 Aug 2021 02:00:15 +0200 Subject: Store pickling key in qtkeychain and pickle encrypted --- lib/events/eventcontent.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 22878d4c..d4cb43ff 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -75,6 +75,7 @@ void FileInfo::fillInfoJson(QJsonObject* infoJson) const infoJson->insert(QStringLiteral("size"), payloadSize); if (mimeType.isValid()) infoJson->insert(QStringLiteral("mimetype"), mimeType.name()); + //TODO add encryptedfile } ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) -- cgit v1.2.3 From 3128df9daa196b2cf3cdb8e029e22d79c397ff66 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sat, 27 Nov 2021 01:34:44 +0100 Subject: Apply even more suggestions --- lib/events/encryptedevent.cpp | 22 ++++++++++++++++++++++ lib/events/encryptedevent.h | 1 + 2 files changed, 23 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 0290f973..c9257584 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" +#include "roommessageevent.h" using namespace Quotient; @@ -30,3 +31,24 @@ EncryptedEvent::EncryptedEvent(const QJsonObject& obj) { qCDebug(E2EE) << "Encrypted event from" << senderId(); } + +RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const +{ + auto eventObject = QJsonDocument::fromJson(decrypted.toUtf8()).object(); + eventObject["event_id"] = id(); + eventObject["sender"] = senderId(); + eventObject["origin_server_ts"] = originTimestamp().toMSecsSinceEpoch(); + if(contentJson().contains("m.relates_to")) { + auto relates = contentJson()["m.relates_to"].toObject(); + auto content = eventObject["content"].toObject(); + content["m.relates_to"] = relates; + eventObject["content"] = content; + } + if(unsignedJson().contains("redacts")) { + auto redacts = unsignedJson()["redacts"].toString(); + auto unsign = eventObject["unsigned"].toObject(); + unsign["redacts"] = redacts; + eventObject["unsigned"] = unsign; + } + return makeEvent(eventObject); +} diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 1d7ea913..28398827 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -61,6 +61,7 @@ public: /* device_id and session_id are required with Megolm */ QString deviceId() const { return contentPart(DeviceIdKeyL); } QString sessionId() const { return contentPart(SessionIdKeyL); } + RoomEventPtr createDecrypted(const QString &decrypted) const; }; REGISTER_EVENT_TYPE(EncryptedEvent) -- cgit v1.2.3 From 9217026e46d7ac0d761cc5206d7ef00978558c47 Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Sun, 28 Nov 2021 20:58:38 +0100 Subject: Apply suggestions from code review Co-authored-by: Alexey Rusakov --- lib/events/encryptedevent.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index c9257584..2e0d7387 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -38,17 +38,15 @@ RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const eventObject["event_id"] = id(); eventObject["sender"] = senderId(); eventObject["origin_server_ts"] = originTimestamp().toMSecsSinceEpoch(); - if(contentJson().contains("m.relates_to")) { - auto relates = contentJson()["m.relates_to"].toObject(); + if (const auto relatesToJson = contentPart("m.relates_to"_ls); !relatesToJson.isUndefined()) { auto content = eventObject["content"].toObject(); - content["m.relates_to"] = relates; + content["m.relates_to"] = relatesToJson.toObject(); eventObject["content"] = content; } - if(unsignedJson().contains("redacts")) { - auto redacts = unsignedJson()["redacts"].toString(); + if (const auto redactsJson = unsignedPart("redacts"_ls); !redactsJson.isUndefined()) { auto unsign = eventObject["unsigned"].toObject(); - unsign["redacts"] = redacts; + unsign["redacts"] = redactsJson.toString(); eventObject["unsigned"] = unsign; } - return makeEvent(eventObject); + return loadEvent(eventObject); } -- cgit v1.2.3 From ae0ad49f36e8ba5983839581302ed16ddbd75d5f Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 2 Dec 2021 14:04:49 +0100 Subject: visit(Event, ...) -> switchOnType() It has not much to do with the Visitor design pattern; also, std::visit() has different conventions on the order of parameters. --- lib/events/event.h | 58 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 33 insertions(+), 25 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 998a386c..ce737280 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -290,7 +290,7 @@ using Events = EventsArray; } \ // End of macro -// === is<>(), eventCast<>() and visit<>() === +// === is<>(), eventCast<>() and switchOnType<>() === template inline bool is(const Event& e) @@ -312,12 +312,12 @@ inline auto eventCast(const BasePtrT& eptr) : nullptr; } -// A single generic catch-all visitor +// A trivial generic catch-all "switch" template -inline auto visit(const BaseEventT& event, FnT&& visitor) - -> decltype(visitor(event)) +inline auto switchOnType(const BaseEventT& event, FnT&& fn) + -> decltype(fn(event)) { - return visitor(event); + return fn(event); } namespace _impl { @@ -328,52 +328,60 @@ namespace _impl { && !std::is_same_v>>; } -// A single type-specific void visitor +// A trivial type-specific "switch" for a void function template -inline auto visit(const BaseT& event, FnT&& visitor) +inline auto switchOnType(const BaseT& event, FnT&& fn) -> std::enable_if_t<_impl::needs_downcast && std::is_void_v>> { using event_type = fn_arg_t; if (is>(event)) - visitor(static_cast(event)); + fn(static_cast(event)); } -// A single type-specific non-void visitor with an optional default value -// non-voidness is guarded by defaultValue type +// A trivial type-specific "switch" for non-void functions with an optional +// default value; non-voidness is guarded by defaultValue type template -inline auto visit(const BaseT& event, FnT&& visitor, - fn_return_t&& defaultValue = {}) +inline auto switchOnType(const BaseT& event, FnT&& fn, + fn_return_t&& defaultValue = {}) -> std::enable_if_t<_impl::needs_downcast, fn_return_t> { using event_type = fn_arg_t; if (is>(event)) - return visitor(static_cast(event)); - return std::forward>(defaultValue); + return fn(static_cast(event)); + return std::move(defaultValue); } -// A chain of 2 or more visitors +// A switch for a chain of 2 or more functions template -inline std::common_type_t, fn_return_t> visit( - const BaseT& event, FnT1&& visitor1, FnT2&& visitor2, - FnTs&&... visitors) +inline std::common_type_t, fn_return_t> +switchOnType(const BaseT& event, FnT1&& fn1, FnT2&& fn2, FnTs&&... fns) { using event_type1 = fn_arg_t; if (is>(event)) - return visitor1(static_cast(event)); - return visit(event, std::forward(visitor2), - std::forward(visitors)...); + return fn1(static_cast(event)); + return switchOnType(event, std::forward(fn2), + std::forward(fns)...); } -// A facility overload that calls void-returning visit() on each event +template +[[deprecated("The new name for visit() is switchOnType()")]] // +inline std::common_type_t...> +visit(const BaseT& event, FnTs&&... fns) +{ + return switchOnType(event, std::forward(fns)...); +} + + // A facility overload that calls void-returning switchOnType() on each event // over a range of event pointers +// TODO: replace with ranges::for_each once all standard libraries have it template -inline auto visitEach(RangeT&& events, FnTs&&... visitors) +inline auto visitEach(RangeT&& events, FnTs&&... fns) -> std::enable_if_t(visitors)...))>> + decltype(switchOnType(**begin(events), std::forward(fns)...))>> { for (auto&& evtPtr: events) - visit(*evtPtr, std::forward(visitors)...); + switchOnType(*evtPtr, std::forward(fns)...); } } // namespace Quotient Q_DECLARE_METATYPE(Quotient::Event*) -- cgit v1.2.3 From dc08fb9dfd474023084de9ce86f29f177ca52fdc Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 2 Dec 2021 15:24:44 +0100 Subject: Improve function_traits<>; split out from util.* Quotient::function_traits<> did not support member functions in a proper way (i.e. the way std::invoke_result<> treats them, with the function's owning class represented as the first parameter). Now that I gained the skill and understanding in function_traits<> somewhat wicked machinery, I could properly support member functions. Overloads and generic lambdas are not supported but maybe we'll get to those one day. --- lib/events/event.h | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index ce737280..4d4bb16b 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -5,6 +5,7 @@ #include "converters.h" #include "logging.h" +#include "function_traits.h" namespace Quotient { // === event_ptr_tt<> and type casting facilities === -- cgit v1.2.3 From 776d05bf98a5dd9e484d5a0e651c71fa95498689 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 3 Dec 2021 21:36:32 +0100 Subject: Cleanup; drop an unused RoomAliasesEvent constructor Also, RoomAliasesEvent is to be completely gone after 0.7. --- lib/events/accountdataevents.h | 5 ++--- lib/events/simplestateevents.h | 12 ++---------- 2 files changed, 4 insertions(+), 13 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index e5101d20..9cf77be3 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -4,7 +4,6 @@ #pragma once #include "event.h" -#include "eventcontent.h" namespace Quotient { constexpr const char* FavouriteTag = "m.favourite"; @@ -16,12 +15,12 @@ struct TagRecord { order_type order; - TagRecord(order_type order = none) : order(std::move(order)) {} + TagRecord(order_type order = none) : order(order) {} bool operator<(const TagRecord& other) const { // Per The Spec, rooms with no order should be after those with order, - // against optional<>::operator<() convention. + // against std::optional<>::operator<() convention. return order && (!other.order || *order < *other.order); } }; diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index cf1bfbba..9ce78609 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -8,8 +8,7 @@ namespace Quotient { namespace EventContent { template - class SimpleContent { - public: + struct SimpleContent { using value_type = T; // The constructor is templated to enable perfect forwarding @@ -25,11 +24,8 @@ namespace EventContent { return { { key, Quotient::toJson(value) } }; } - public: T value; - - protected: - QString key; + const QString key; }; } // namespace EventContent @@ -65,10 +61,6 @@ public: explicit RoomAliasesEvent(const QJsonObject& obj) : StateEvent(typeId(), obj, QStringLiteral("aliases")) {} - RoomAliasesEvent(const QString& server, const QStringList& aliases) - : StateEvent(typeId(), matrixTypeId(), server, - QStringLiteral("aliases"), aliases) - {} QString server() const { return stateKey(); } QStringList aliases() const { return content().value; } }; -- cgit v1.2.3 From 47bd4dfb2bc720d2b5919b93985f87d918af572a Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 7 Dec 2021 00:25:05 +0100 Subject: Port E2EE to database instead of JSON files --- lib/events/encryptedevent.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 2e0d7387..1b5e4441 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -3,6 +3,7 @@ #include "encryptedevent.h" #include "roommessageevent.h" +#include "events/eventloader.h" using namespace Quotient; -- cgit v1.2.3 From 2c6fa33ca52842e9dfba0dd3893a9d5526e10e60 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 7 Dec 2021 19:08:29 +0100 Subject: Rename "crypto" -> "e2ee" --- lib/events/encryptedevent.h | 2 +- lib/events/encryptionevent.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 28398827..4cc3bf8e 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -3,7 +3,7 @@ #pragma once -#include "crypto/e2ee.h" +#include "e2ee/e2ee.h" #include "roomevent.h" namespace Quotient { diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index d7bb953a..6272c668 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -4,7 +4,7 @@ #include "encryptionevent.h" -#include "crypto/e2ee.h" +#include "e2ee/e2ee.h" #include -- cgit v1.2.3 From a0ce17dfe793c924205b449c026f2f776b032ff3 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Wed, 8 Dec 2021 23:07:14 +0100 Subject: Store encryptedevent in decrypted roomevents --- lib/events/roomevent.cpp | 13 +++++++++++++ lib/events/roomevent.h | 4 ++++ 2 files changed, 17 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index fb921af6..b99d1381 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -126,3 +126,16 @@ CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) if (callId().isEmpty()) qCWarning(EVENTS) << id() << "is a call event with an empty call id"; } + +void RoomEvent::setOriginalEvent(event_ptr_tt originalEvent) +{ + _originalEvent = std::move(originalEvent); +} + +const QJsonObject RoomEvent::encryptedJson() const +{ + if(!_originalEvent) { + return {}; + } + return _originalEvent->fullJson(); +} diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 7f13f6f2..35527a62 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -60,11 +60,15 @@ public: //! callback for that in RoomEvent. void addId(const QString& newId); + void setOriginalEvent(event_ptr_tt originalEvent); + const QJsonObject encryptedJson() const; + protected: void dumpTo(QDebug dbg) const override; private: event_ptr_tt _redactedBecause; + event_ptr_tt _originalEvent; }; using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; -- cgit v1.2.3 From 58798ce15f0f235d64f9c34b3f8c013678ebf25f Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Thu, 9 Dec 2021 23:26:24 +0100 Subject: Ifdef all the things --- lib/events/roomevent.cpp | 2 ++ lib/events/roomevent.h | 5 +++++ 2 files changed, 7 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index b99d1381..dbce2255 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -127,6 +127,7 @@ CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) qCWarning(EVENTS) << id() << "is a call event with an empty call id"; } +#ifdef Quotient_E2EE_ENABLED void RoomEvent::setOriginalEvent(event_ptr_tt originalEvent) { _originalEvent = std::move(originalEvent); @@ -139,3 +140,4 @@ const QJsonObject RoomEvent::encryptedJson() const } return _originalEvent->fullJson(); } +#endif diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 35527a62..36b45f09 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -60,15 +60,20 @@ public: //! callback for that in RoomEvent. void addId(const QString& newId); +#ifdef Quotient_E2EE_ENABLED void setOriginalEvent(event_ptr_tt originalEvent); const QJsonObject encryptedJson() const; +#endif protected: void dumpTo(QDebug dbg) const override; private: event_ptr_tt _redactedBecause; + +#ifdef Quotient_E2EE_ENABLED event_ptr_tt _originalEvent; +#endif }; using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; -- cgit v1.2.3 From b4a6070d44140a3cbc931b18530721e31f069455 Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Fri, 10 Dec 2021 16:15:50 +0100 Subject: Apply suggestions from code review Co-authored-by: Alexey Rusakov --- lib/events/roomevent.cpp | 2 +- lib/events/roomevent.h | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index dbce2255..eb5d0485 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -128,7 +128,7 @@ CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) } #ifdef Quotient_E2EE_ENABLED -void RoomEvent::setOriginalEvent(event_ptr_tt originalEvent) +void RoomEvent::setOriginalEvent(event_ptr_tt&& originalEvent) { _originalEvent = std::move(originalEvent); } diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 36b45f09..3d46bf9b 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -61,7 +61,8 @@ public: void addId(const QString& newId); #ifdef Quotient_E2EE_ENABLED - void setOriginalEvent(event_ptr_tt originalEvent); + void setOriginalEvent(event_ptr_tt&& originalEvent); + const RoomEvent* originalEvent() { return _originalEvent.get(); } const QJsonObject encryptedJson() const; #endif -- cgit v1.2.3 From e5256e0b1e4c43ce96d99d1b82ca5d98a1baded6 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 17 Dec 2021 08:07:07 +0100 Subject: RoomMemberEvent: fix an off-by-one error Also: extended quotest to cover member renames, not just user profile renames. --- lib/events/roommemberevent.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index b0bc7bcb..3141f6b5 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -48,11 +48,9 @@ void MemberEventContent::fillJson(QJsonObject* o) const { Q_ASSERT(o); if (membership != Membership::Invalid) - o->insert( - QStringLiteral("membership"), - MembershipStrings[qCountTrailingZeroBits( - std::underlying_type_t(membership)) - + 1]); + o->insert(QStringLiteral("membership"), + MembershipStrings[qCountTrailingZeroBits( + std::underlying_type_t(membership))]); if (displayName) o->insert(QStringLiteral("displayname"), *displayName); if (avatarUrl && avatarUrl->isValid()) -- cgit v1.2.3 From b989383165b648269a231d1febadc8150676d5cf Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 21 Dec 2021 18:40:47 +0100 Subject: Don't chain RoomEvent to Event factory any more Objects derived from Event are not room events (in the spec sense) and never occur in the same arrays as room events; therefore this chaining has always been superfluous. --- lib/events/roomevent.cpp | 3 --- 1 file changed, 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index fb921af6..b728e0bf 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -9,9 +9,6 @@ using namespace Quotient; -[[maybe_unused]] static auto roomEventTypeInitialised = - Event::factory_t::chainFactory(); - RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, const QJsonObject& contentJson) : Event(type, matrixType, contentJson) -- cgit v1.2.3 From 231c4d723eb53f3ea5f641b743d198584840a963 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Dec 2021 13:44:39 +0100 Subject: Simplify the code around EventFactory<> The former code assumed that EventFactory<> is just a class-level shell for a bunch of functions and a static data member that only exists to allow specialisations to occur for the whole group together. On top of that, setupFactory() and registerEventType() strived to protect this group from double registration coming from static variables in an anonymous namespace produced by REGISTER_EVENT_TYPE. The whole thing is now de-static-ed: resolving the factory now relies on class-static Event/RoomEvent/StateEventBase::factory variables instead of factory_t type aliases; and REGISTER_EVENT_TYPE produces non-static inline variables instead, obviating the need of registerEventType/setupFactory kludge. --- lib/events/event.h | 166 +++++++++++++++++++++++-------------------- lib/events/eventloader.h | 18 ++--- lib/events/roomevent.h | 2 +- lib/events/roommemberevent.h | 32 ++++----- lib/events/stateevent.cpp | 15 ---- lib/events/stateevent.h | 18 ++++- 6 files changed, 125 insertions(+), 126 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 4d4bb16b..e786fb30 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -110,94 +110,90 @@ inline event_type_t typeId() inline event_type_t unknownEventTypeId() { return typeId(); } -// === EventFactory === +// === Event creation facilities === -/** Create an event of arbitrary type from its arguments */ +//! Create an event of arbitrary type from its arguments template inline event_ptr_tt makeEvent(ArgTs&&... args) { return std::make_unique(std::forward(args)...); } -template -class EventFactory { -public: - template - static auto addMethod(FnT&& method) - { - factories().emplace_back(std::forward(method)); - return 0; - } - - /** Chain two type factories - * Adds the factory class of EventT2 (EventT2::factory_t) to - * the list in factory class of EventT1 (EventT1::factory_t) so - * that when EventT1::factory_t::make() is invoked, types of - * EventT2 factory are looked through as well. This is used - * to include RoomEvent types into the more general Event factory, - * and state event types into the RoomEvent factory. - */ - template - static auto chainFactory() - { - return addMethod(&EventT::factory_t::make); - } - - static event_ptr_tt make(const QJsonObject& json, - const QString& matrixType) - { - for (const auto& f : factories()) - if (auto e = f(json, matrixType)) - return e; - return nullptr; - } - -private: - static auto& factories() +namespace _impl { + template + event_ptr_tt makeIfMatches(const QJsonObject& json, + const QString& matrixType) { - using inner_factory_tt = std::function( - const QJsonObject&, const QString&)>; - static std::vector _factories {}; - return _factories; + return QLatin1String(EventT::matrixTypeId()) == matrixType + ? makeEvent(json) + : nullptr; } -}; - -/** Add a type to its default factory - * Adds a standard factory method (via makeEvent<>) for a given - * type to EventT::factory_t factory class so that it can be - * created dynamically from loadEvent<>(). - * - * \tparam EventT the type to enable dynamic creation of - * \return the registered type id - * \sa loadEvent, Event::type - */ -template -inline auto setupFactory() -{ - qDebug(EVENTS) << "Adding factory method for" << EventT::matrixTypeId(); - return EventT::factory_t::addMethod([](const QJsonObject& json, - const QString& jsonMatrixType) { - return EventT::matrixTypeId() == jsonMatrixType ? makeEvent(json) - : nullptr; - }); -} -template -inline auto registerEventType() -{ - // Initialise exactly once, even if this function is called twice for - // the same type (for whatever reason - you never know the ways of - // static initialisation is done). - static const auto _ = setupFactory(); - return _; // Only to facilitate usage in static initialisation -} + //! \brief A family of event factories to create events from CS API responses + //! + //! Each of these factories, as instantiated by event base types (Event, + //! RoomEvent etc.) is capable of producing an event object derived from + //! \p BaseEventT, using the JSON payload and the event type passed to its + //! make() method. Don't use these directly to make events; use loadEvent() + //! overloads as the frontend for these. Never instantiate new factories + //! outside of base event classes. + //! \sa loadEvent, setupFactory, Event::factory, RoomEvent::factory, + //! StateEventBase::factory + template + class EventFactory + : private std::vector (*)(const QJsonObject&, + const QString&)> { + // Actual makeIfMatches specialisations will differ in the first + // template parameter but that doesn't affect the function type + public: + explicit EventFactory(const char* name = "") + : name(name) + { + static auto yetToBeConstructed = true; + Q_ASSERT(yetToBeConstructed); + if (!yetToBeConstructed) // For Release builds that pass Q_ASSERT + qCritical(EVENTS) + << "Another EventFactory for the same base type is being " + "created - event creation logic will be splintered"; + yetToBeConstructed = false; + } + EventFactory(const EventFactory&) = delete; + + //! \brief Add a method to create events of a given type + //! + //! Adds a standard factory method (makeIfMatches) for \p EventT so that + //! event objects of this type can be created dynamically by loadEvent. + //! The caller is responsible for ensuring this method is called only + //! once per type. + //! \sa makeIfMatches, loadEvent, Quotient::loadEvent + template + bool addMethod() + { + this->emplace_back(&makeIfMatches); + qDebug(EVENTS) << "Added factory method for" + << EventT::matrixTypeId() << "events;" << this->size() + << "methods in the" << name << "chain by now"; + return true; + } + + auto loadEvent(const QJsonObject& json, const QString& matrixType) + { + for (const auto& f : *this) + if (auto e = f(json, matrixType)) + return e; + return makeEvent(unknownEventTypeId(), json); + } + + const char* const name; + }; +} // namespace _impl // === Event === class Event { public: using Type = event_type_t; - using factory_t = EventFactory; + static inline _impl::EventFactory factory { "Event" }; explicit Event(Type type, const QJsonObject& json); explicit Event(Type type, event_mtype_t matrixType, @@ -272,7 +268,7 @@ template using EventsArray = std::vector>; using Events = EventsArray; -// === Macros used with event class definitions === +// === Facilities for event class definitions === // This macro should be used in a public section of an event class to // provide matrixTypeId() and typeId(). @@ -284,13 +280,27 @@ using Events = EventsArray; // This macro should be put after an event class definition (in .h or .cpp) // to enable its deserialisation from a /sync and other // polymorphic event arrays -#define REGISTER_EVENT_TYPE(_Type) \ - namespace { \ - [[maybe_unused]] static const auto _factoryAdded##_Type = \ - registerEventType<_Type>(); \ - } \ +#define REGISTER_EVENT_TYPE(_Type) \ + [[maybe_unused]] inline const auto _factoryAdded##_Type = \ + _Type::factory.addMethod<_Type>(); \ // End of macro +// === Event loading === +// (see also event_loader.h) + +//! \brief Point of customisation to dynamically load events +//! +//! The default specialisation of this calls BaseEventT::factory and if that +//! fails (i.e. returns nullptr) creates an unknown event of BaseEventT. +//! Other specialisations may reuse other factories, add validations common to +//! BaseEventT, and so on +template +event_ptr_tt doLoadEvent(const QJsonObject& json, + const QString& matrixType) +{ + return BaseEventT::factory.loadEvent(json, matrixType); +} + // === is<>(), eventCast<>() and switchOnType<>() === template diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index 978668f2..fe624d70 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -6,16 +6,6 @@ #include "stateevent.h" namespace Quotient { -namespace _impl { - template - static inline auto loadEvent(const QJsonObject& json, - const QString& matrixType) - { - if (auto e = EventFactory::make(json, matrixType)) - return e; - return makeEvent(unknownEventTypeId(), json); - } -} // namespace _impl /*! Create an event with proper type from a JSON object * @@ -26,7 +16,7 @@ namespace _impl { template inline event_ptr_tt loadEvent(const QJsonObject& fullJson) { - return _impl::loadEvent(fullJson, fullJson[TypeKeyL].toString()); + return doLoadEvent(fullJson, fullJson[TypeKeyL].toString()); } /*! Create an event from a type string and content JSON @@ -39,8 +29,8 @@ template inline event_ptr_tt loadEvent(const QString& matrixType, const QJsonObject& content) { - return _impl::loadEvent(basicEventJson(matrixType, content), - matrixType); + return doLoadEvent(basicEventJson(matrixType, content), + matrixType); } /*! Create a state event from a type string, content JSON and state key @@ -53,7 +43,7 @@ inline StateEventPtr loadStateEvent(const QString& matrixType, const QJsonObject& content, const QString& stateKey = {}) { - return _impl::loadEvent( + return doLoadEvent( basicStateEventJson(matrixType, content, stateKey), matrixType); } diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 7f13f6f2..8be58481 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -13,7 +13,7 @@ class RedactionEvent; /** This class corresponds to m.room.* events */ class RoomEvent : public Event { public: - using factory_t = EventFactory; + static inline _impl::EventFactory factory { "RoomEvent" }; // RedactionEvent is an incomplete type here so we cannot inline // constructors and destructors and we cannot use 'using'. diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index f3047159..0fb464d4 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -49,16 +49,15 @@ public: std::forward(contentArgs)...) {} - /// A special constructor to create unknown RoomMemberEvents - /** - * This is needed in order to use RoomMemberEvent as a "base event - * class" in cases like GetMembersByRoomJob when RoomMemberEvents - * (rather than RoomEvents or StateEvents) are resolved from JSON. - * For such cases loadEvent<> requires an underlying class to be - * constructible with unknownTypeId() instead of its genuine id. - * Don't use it directly. - * \sa GetMembersByRoomJob, loadEvent, unknownTypeId - */ + //! \brief A special constructor to create unknown RoomMemberEvents + //! + //! This is needed in order to use RoomMemberEvent as a "base event class" + //! in cases like GetMembersByRoomJob when RoomMemberEvents (rather than + //! RoomEvents or StateEvents) are resolved from JSON. For such cases + //! loadEvent\<> requires an underlying class to have a specialisation of + //! EventFactory\<> and be constructible with unknownTypeId() instead of + //! its genuine id. Don't use directly. + //! \sa EventFactory, loadEvent, GetMembersByRoomJob RoomMemberEvent(Type type, const QJsonObject& fullJson) : StateEvent(type, fullJson) {} @@ -89,14 +88,13 @@ public: }; template <> -class EventFactory { -public: - static event_ptr_tt make(const QJsonObject& json, - const QString&) - { +inline event_ptr_tt +doLoadEvent(const QJsonObject& json, const QString& matrixType) +{ + if (matrixType == QLatin1String(RoomMemberEvent::matrixTypeId())) return makeEvent(json); - } -}; + return makeEvent(unknownEventTypeId(), json); +} REGISTER_EVENT_TYPE(RoomMemberEvent) } // namespace Quotient diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index efe011a0..9535af56 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -5,21 +5,6 @@ using namespace Quotient; -// Aside from the normal factory to instantiate StateEventBase inheritors -// StateEventBase itself can be instantiated if there's a state_key JSON key -// but the event type is unknown. -[[maybe_unused]] static auto stateEventTypeInitialised = - RoomEvent::factory_t::addMethod( - [](const QJsonObject& json, const QString& matrixType) -> StateEventPtr { - if (!json.contains(StateKeyKeyL)) - return nullptr; - - if (auto e = StateEventBase::factory_t::make(json, matrixType)) - return e; - - return makeEvent(unknownEventTypeId(), json); - }); - StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, const QString& stateKey, const QJsonObject& contentJson) diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index b0aa9907..919e8f86 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -19,7 +19,7 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, class StateEventBase : public RoomEvent { public: - using factory_t = EventFactory; + static inline _impl::EventFactory factory { "StateEvent" }; StateEventBase(Type type, const QJsonObject& json) : RoomEvent(type, json) {} @@ -37,6 +37,22 @@ public: using StateEventPtr = event_ptr_tt; using StateEvents = EventsArray; +//! \brief Override RoomEvent factory with that from StateEventBase if JSON has +//! stateKey +//! +//! This means in particular that an event with a type known to RoomEvent but +//! having stateKey set (even to an empty value) will be treated as a state +//! event and most likely end up as unknown (consider, e.g., m.room.message +//! that has stateKey set). +template <> +inline RoomEventPtr doLoadEvent(const QJsonObject& json, + const QString& matrixType) +{ + if (json.contains(StateKeyKeyL)) + return StateEventBase::factory.loadEvent(json, matrixType); + return RoomEvent::factory.loadEvent(json, matrixType); +} + template <> inline bool is(const Event& e) { -- cgit v1.2.3 From 060af9334049c58767b6457da2d7c07fdb0d171e Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Dec 2021 16:13:02 +0100 Subject: StateEventBase: force type to unknown if stateKey is not in JSON --- lib/events/stateevent.cpp | 8 ++++++++ lib/events/stateevent.h | 3 +-- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 9535af56..e53d47d4 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -5,6 +5,14 @@ using namespace Quotient; +StateEventBase::StateEventBase(Type type, const QJsonObject& json) + : RoomEvent(json.contains(StateKeyKeyL) ? type : unknownEventTypeId(), json) +{ + if (Event::type() == unknownEventTypeId() && !json.contains(StateKeyKeyL)) + qWarning(EVENTS) << "Attempt to create a state event with no stateKey -" + "forcing the event type to unknown to avoid damage"; +} + StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, const QString& stateKey, const QJsonObject& contentJson) diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 919e8f86..c37965aa 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -21,8 +21,7 @@ class StateEventBase : public RoomEvent { public: static inline _impl::EventFactory factory { "StateEvent" }; - StateEventBase(Type type, const QJsonObject& json) : RoomEvent(type, json) - {} + StateEventBase(Type type, const QJsonObject& json); StateEventBase(Type type, event_mtype_t matrixType, const QString& stateKey = {}, const QJsonObject& contentJson = {}); -- cgit v1.2.3 From ae0180acc50de443e98bc1c59dee94f0096df2e0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 24 Dec 2021 15:40:13 +0100 Subject: Prune empty/ish call*event.cpp files --- lib/events/callcandidatesevent.cpp | 27 --------------------------- lib/events/callhangupevent.cpp | 36 ------------------------------------ lib/events/callhangupevent.h | 8 ++++++-- 3 files changed, 6 insertions(+), 65 deletions(-) delete mode 100644 lib/events/callcandidatesevent.cpp delete mode 100644 lib/events/callhangupevent.cpp (limited to 'lib/events') diff --git a/lib/events/callcandidatesevent.cpp b/lib/events/callcandidatesevent.cpp deleted file mode 100644 index b87c8e9b..00000000 --- a/lib/events/callcandidatesevent.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "callcandidatesevent.h" - -/* -m.call.candidates -{ - "age": 242352, - "content": { - "call_id": "12345", - "candidates": [ - { - "candidate": "candidate:863018703 1 udp 2122260223 10.9.64.156 -43670 typ host generation 0", "sdpMLineIndex": 0, "sdpMid": "audio" - } - ], - "version": 0 - }, - "event_id": "$WLGTSEFSEF:localhost", - "origin_server_ts": 1431961217939, - "room_id": "!Cuyf34gef24t:localhost", - "sender": "@example:localhost", - "type": "m.call.candidates" -} -*/ diff --git a/lib/events/callhangupevent.cpp b/lib/events/callhangupevent.cpp deleted file mode 100644 index 43bc4db0..00000000 --- a/lib/events/callhangupevent.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/****************************************************************************** - * SPDX-FileCopyrightText: 2017 Marius Gripsgard - * SPDX-FileCopyrightText: 2018 Josip Delic - * - * SPDX-License-Identifier: LGPL-2.1-or-later - */ - -#include "callhangupevent.h" - -/* -m.call.hangup -{ - "age": 242352, - "content": { - "call_id": "12345", - "version": 0 - }, - "event_id": "$WLGTSEFSEF:localhost", - "origin_server_ts": 1431961217939, - "room_id": "!Cuyf34gef24t:localhost", - "sender": "@example:localhost", - "type": "m.call.hangup" -} -*/ - -using namespace Quotient; - -CallHangupEvent::CallHangupEvent(const QJsonObject& obj) - : CallEventBase(typeId(), obj) -{ - qCDebug(EVENTS) << "Call Hangup event"; -} - -CallHangupEvent::CallHangupEvent(const QString& callId) - : CallEventBase(typeId(), matrixTypeId(), callId, 0) -{} diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index 24382ac2..f3f82833 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -11,8 +11,12 @@ class CallHangupEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.hangup", CallHangupEvent) - explicit CallHangupEvent(const QJsonObject& obj); - explicit CallHangupEvent(const QString& callId); + explicit CallHangupEvent(const QJsonObject& obj) + : CallEventBase(typeId(), obj) + {} + explicit CallHangupEvent(const QString& callId) + : CallEventBase(typeId(), matrixTypeId(), callId, 0) + {} }; REGISTER_EVENT_TYPE(CallHangupEvent) -- cgit v1.2.3 From 674e984e459375974f619d0e778d43a2cc928dc3 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 26 Dec 2021 09:33:14 +0100 Subject: Key* strings: drop 'static'; add 'constexpr' where ok --- lib/events/event.h | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index e786fb30..8f62872d 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -29,24 +29,24 @@ inline TargetEventT* weakPtrCast(const event_ptr_tt& ptr) // === Standard Matrix key names and basicEventJson() === -static const auto TypeKey = QStringLiteral("type"); -static const auto BodyKey = QStringLiteral("body"); -static const auto ContentKey = QStringLiteral("content"); -static const auto EventIdKey = QStringLiteral("event_id"); -static const auto SenderKey = QStringLiteral("sender"); -static const auto RoomIdKey = QStringLiteral("room_id"); -static const auto UnsignedKey = QStringLiteral("unsigned"); -static const auto StateKeyKey = QStringLiteral("state_key"); -static const auto TypeKeyL = "type"_ls; -static const auto BodyKeyL = "body"_ls; -static const auto ContentKeyL = "content"_ls; -static const auto EventIdKeyL = "event_id"_ls; -static const auto SenderKeyL = "sender"_ls; -static const auto RoomIdKeyL = "room_id"_ls; -static const auto UnsignedKeyL = "unsigned"_ls; -static const auto RedactedCauseKeyL = "redacted_because"_ls; -static const auto PrevContentKeyL = "prev_content"_ls; -static const auto StateKeyKeyL = "state_key"_ls; +constexpr auto TypeKeyL = "type"_ls; +constexpr auto BodyKeyL = "body"_ls; +constexpr auto ContentKeyL = "content"_ls; +constexpr auto EventIdKeyL = "event_id"_ls; +constexpr auto SenderKeyL = "sender"_ls; +constexpr auto RoomIdKeyL = "room_id"_ls; +constexpr auto UnsignedKeyL = "unsigned"_ls; +constexpr auto RedactedCauseKeyL = "redacted_because"_ls; +constexpr auto PrevContentKeyL = "prev_content"_ls; +constexpr auto StateKeyKeyL = "state_key"_ls; +const QString TypeKey { TypeKeyL }; +const QString BodyKey { BodyKeyL }; +const QString ContentKey { ContentKeyL }; +const QString EventIdKey { EventIdKeyL }; +const QString SenderKey { SenderKeyL }; +const QString RoomIdKey { RoomIdKeyL }; +const QString UnsignedKey { UnsignedKeyL }; +const QString StateKeyKey { StateKeyKeyL }; /// Make a minimal correct Matrix event JSON inline QJsonObject basicEventJson(const QString& matrixType, -- cgit v1.2.3 From 5f4d9ef6df492bfd91fa7c48fb4d5f8c2afc40b2 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 27 Dec 2021 20:14:07 +0100 Subject: EventFactory: remove default constructor This is a leftover from deferred `name` initialisation that wasn't needed in the end. --- lib/events/event.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 8f62872d..8347bb4f 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -146,7 +146,7 @@ namespace _impl { // Actual makeIfMatches specialisations will differ in the first // template parameter but that doesn't affect the function type public: - explicit EventFactory(const char* name = "") + explicit EventFactory(const char* name) : name(name) { static auto yetToBeConstructed = true; -- cgit v1.2.3 From 418b85c285fa0a0c196a26eef5cc0c9c3dbe20fe Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 28 Dec 2021 09:07:37 +0100 Subject: EventContent::FileInfo: default payloadSize to 0 Fixes a clang-tidy warning. --- lib/events/eventcontent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index f609a603..f6dbd4bf 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -105,7 +105,7 @@ namespace EventContent { QJsonObject originalInfoJson; QMimeType mimeType; QUrl url; - qint64 payloadSize; + qint64 payloadSize = 0; QString originalName; Omittable file = none; }; -- cgit v1.2.3 From 7350fe82953cf6274b8845a890eafb21a09b9931 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 29 Dec 2021 15:59:58 +0100 Subject: Add QUOTIENT_API throughout non-generated code This include all (hopefully) classes/structures and functions that have non-inline definitions, as well as namespaces with Q_NAMESPACE since those have non-inline (as of Qt 5.15) QMetaObject - for that a new macro, QUO_NAMESPACE, has been devised to accommodate the lack of Q_NAMESPACE_EXPORT in Qt before 5.14. --- lib/events/accountdataevents.h | 2 +- lib/events/callanswerevent.h | 3 +-- lib/events/callhangupevent.h | 2 +- lib/events/callinviteevent.h | 2 +- lib/events/directchatevent.h | 2 +- lib/events/encryptedevent.h | 2 +- lib/events/encryptionevent.h | 5 ++--- lib/events/event.h | 23 +++++++++++++---------- lib/events/eventcontent.h | 19 ++++++++++--------- lib/events/reactionevent.h | 6 +++--- lib/events/receiptevent.h | 2 +- lib/events/roomavatarevent.h | 3 ++- lib/events/roomcreateevent.h | 2 +- lib/events/roomevent.h | 4 ++-- lib/events/roomkeyevent.h | 2 +- lib/events/roommemberevent.h | 5 ++--- lib/events/roommessageevent.h | 8 ++++---- lib/events/roompowerlevelsevent.h | 8 +++----- lib/events/roomtombstoneevent.h | 2 +- lib/events/simplestateevents.h | 3 ++- lib/events/stateevent.h | 2 +- lib/events/stickerevent.h | 2 +- lib/events/typingevent.h | 2 +- 23 files changed, 56 insertions(+), 55 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 9cf77be3..c0f2202d 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -50,7 +50,7 @@ struct JsonObjectConverter { using TagsMap = QHash; #define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ - class _Name : public Event { \ + class QUOTIENT_API _Name : public Event { \ public: \ using content_type = _ContentType; \ DEFINE_EVENT_TYPEID(_TypeId, _Name) \ diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 4c01c941..8ffe60f2 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -7,7 +7,7 @@ #include "roomevent.h" namespace Quotient { -class CallAnswerEvent : public CallEventBase { +class QUOTIENT_API CallAnswerEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.answer", CallAnswerEvent) @@ -26,6 +26,5 @@ public: return contentPart("answer"_ls).value("sdp"_ls).toString(); } }; - REGISTER_EVENT_TYPE(CallAnswerEvent) } // namespace Quotient diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index f3f82833..b0017c59 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -7,7 +7,7 @@ #include "roomevent.h" namespace Quotient { -class CallHangupEvent : public CallEventBase { +class QUOTIENT_API CallHangupEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.hangup", CallHangupEvent) diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 80b7d651..47362b5c 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -7,7 +7,7 @@ #include "roomevent.h" namespace Quotient { -class CallInviteEvent : public CallEventBase { +class QUOTIENT_API CallInviteEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.invite", CallInviteEvent) diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index e2143779..2018d3d6 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -6,7 +6,7 @@ #include "event.h" namespace Quotient { -class DirectChatEvent : public Event { +class QUOTIENT_API DirectChatEvent : public Event { public: DEFINE_EVENT_TYPEID("m.direct", DirectChatEvent) diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index de89a7c6..81343a29 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -25,7 +25,7 @@ namespace Quotient { * in general. It's possible, because RoomEvent interface is similar to Event's * one and doesn't add new restrictions, just provides additional features. */ -class EncryptedEvent : public RoomEvent { +class QUOTIENT_API EncryptedEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.room.encrypted", EncryptedEvent) diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 14439fcc..dfb28b2f 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -8,7 +8,7 @@ #include "stateevent.h" namespace Quotient { -class EncryptionEventContent : public EventContent::Base { +class QUOTIENT_API EncryptionEventContent : public EventContent::Base { public: enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; @@ -26,7 +26,7 @@ protected: using EncryptionType = EncryptionEventContent::EncryptionType; -class EncryptionEvent : public StateEvent { +class QUOTIENT_API EncryptionEvent : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.encryption", EncryptionEvent) @@ -51,6 +51,5 @@ public: int rotationPeriodMs() const { return content().rotationPeriodMs; } int rotationPeriodMsgs() const { return content().rotationPeriodMsgs; } }; - REGISTER_EVENT_TYPE(EncryptionEvent) } // namespace Quotient diff --git a/lib/events/event.h b/lib/events/event.h index 8f62872d..8a0076d0 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -60,14 +60,14 @@ inline QJsonObject basicEventJson(const QString& matrixType, using event_type_t = size_t; using event_mtype_t = const char*; -class EventTypeRegistry { +class QUOTIENT_API EventTypeRegistry { public: ~EventTypeRegistry() = default; static event_type_t initializeTypeId(event_mtype_t matrixTypeId); template - static inline event_type_t initializeTypeId() + static event_type_t initializeTypeId() { return initializeTypeId(EventT::matrixTypeId()); } @@ -190,7 +190,7 @@ namespace _impl { // === Event === -class Event { +class QUOTIENT_API Event { public: using Type = event_type_t; static inline _impl::EventFactory factory { "Event" }; @@ -243,7 +243,7 @@ public: return fromJson(unsignedJson()[std::forward(key)]); } - friend QDebug operator<<(QDebug dbg, const Event& e) + friend QUOTIENT_API QDebug operator<<(QDebug dbg, const Event& e) { QDebugStateSaver _dss { dbg }; dbg.noquote().nospace() << e.matrixType() << '(' << e.type() << "): "; @@ -272,17 +272,20 @@ using Events = EventsArray; // This macro should be used in a public section of an event class to // provide matrixTypeId() and typeId(). -#define DEFINE_EVENT_TYPEID(_Id, _Type) \ - static constexpr event_mtype_t matrixTypeId() { return _Id; } \ - static auto typeId() { return Quotient::typeId<_Type>(); } \ +#define DEFINE_EVENT_TYPEID(_Id, _Type) \ + static QUOTIENT_EXPORT constexpr event_mtype_t matrixTypeId() \ + { \ + return _Id; \ + } \ + static QUOTIENT_EXPORT auto typeId() { return Quotient::typeId<_Type>(); } \ // End of macro // This macro should be put after an event class definition (in .h or .cpp) // to enable its deserialisation from a /sync and other // polymorphic event arrays -#define REGISTER_EVENT_TYPE(_Type) \ - [[maybe_unused]] inline const auto _factoryAdded##_Type = \ - _Type::factory.addMethod<_Type>(); \ +#define REGISTER_EVENT_TYPE(_Type) \ + [[maybe_unused]] QUOTIENT_API inline const auto _factoryAdded##_Type = \ + _Type::factory.addMethod<_Type>(); \ // End of macro // === Event loading === diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index f609a603..bfa7d926 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -6,14 +6,15 @@ // This file contains generic event content definitions, applicable to room // message events as well as other events (e.g., avatars). +#include "encryptedfile.h" +#include "quotient_export.h" + #include #include #include #include #include -#include "encryptedfile.h" - class QFileInfo; namespace Quotient { @@ -28,7 +29,7 @@ namespace EventContent { * assumed but not required that a content object can also be created * from plain data. */ - class Base { + class QUOTIENT_API Base { public: explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} virtual ~Base() = default; @@ -76,7 +77,7 @@ namespace EventContent { * * This class is not polymorphic. */ - class FileInfo { + class QUOTIENT_API FileInfo { public: FileInfo() = default; explicit FileInfo(const QFileInfo& fi); @@ -121,7 +122,7 @@ namespace EventContent { /** * A content info class for image content types: image, thumbnail, video */ - class ImageInfo : public FileInfo { + class QUOTIENT_API ImageInfo : public FileInfo { public: ImageInfo() = default; explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); @@ -146,7 +147,7 @@ namespace EventContent { * the JSON representation of event content; namely, * "info/thumbnail_url" and "info/thumbnail_info" fields are used. */ - class Thumbnail : public ImageInfo { + class QUOTIENT_API Thumbnail : public ImageInfo { public: Thumbnail() = default; // Allow empty thumbnails Thumbnail(const QJsonObject& infoJson, const Omittable &file = none); @@ -160,7 +161,7 @@ namespace EventContent { void fillInfoJson(QJsonObject* infoJson) const; }; - class TypedBase : public Base { + class QUOTIENT_API TypedBase : public Base { public: virtual QMimeType type() const = 0; virtual const FileInfo* fileInfo() const { return nullptr; } @@ -183,7 +184,7 @@ namespace EventContent { * \tparam InfoT base info class */ template - class UrlBasedContent : public TypedBase, public InfoT { + class QUOTIENT_API UrlBasedContent : public TypedBase, public InfoT { public: using InfoT::InfoT; explicit UrlBasedContent(const QJsonObject& json) @@ -215,7 +216,7 @@ namespace EventContent { }; template - class UrlWithThumbnailContent : public UrlBasedContent { + class QUOTIENT_API UrlWithThumbnailContent : public UrlBasedContent { public: // NB: when using inherited constructors, thumbnail has to be // initialised separately diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index 5a2b98c4..ce11eaed 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -7,7 +7,7 @@ namespace Quotient { -struct EventRelation { +struct QUOTIENT_API EventRelation { using reltypeid_t = const char*; static constexpr reltypeid_t Reply() { return "m.in_reply_to"; } static constexpr reltypeid_t Annotation() { return "m.annotation"; } @@ -31,12 +31,12 @@ struct EventRelation { } }; template <> -struct JsonObjectConverter { +struct QUOTIENT_API JsonObjectConverter { static void dumpTo(QJsonObject& jo, const EventRelation& pod); static void fillFrom(const QJsonObject& jo, EventRelation& pod); }; -class ReactionEvent : public RoomEvent { +class QUOTIENT_API ReactionEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.reaction", ReactionEvent) diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index 9683deef..5e077e47 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -19,7 +19,7 @@ struct ReceiptsForEvent { }; using EventsWithReceipts = QVector; -class ReceiptEvent : public Event { +class QUOTIENT_API ReceiptEvent : public Event { public: DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) explicit ReceiptEvent(const EventsWithReceipts& ewrs); diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index 8618ba31..c54b5801 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -7,7 +7,8 @@ #include "stateevent.h" namespace Quotient { -class RoomAvatarEvent : public StateEvent { +class QUOTIENT_API RoomAvatarEvent + : public StateEvent { // It's a bit of an overkill to use a full-fledged ImageContent // because in reality m.room.avatar usually only has a single URL, // without a thumbnail. But The Spec says there be thumbnails, and diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index b3ad287c..016855b9 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -7,7 +7,7 @@ #include "quotient_common.h" namespace Quotient { -class RoomCreateEvent : public StateEventBase { +class QUOTIENT_API RoomCreateEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.create", RoomCreateEvent) diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 8be58481..3fbb247e 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -11,7 +11,7 @@ namespace Quotient { class RedactionEvent; /** This class corresponds to m.room.* events */ -class RoomEvent : public Event { +class QUOTIENT_API RoomEvent : public Event { public: static inline _impl::EventFactory factory { "RoomEvent" }; @@ -70,7 +70,7 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; -class CallEventBase : public RoomEvent { +class QUOTIENT_API CallEventBase : public RoomEvent { public: CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, int version, const QJsonObject& contentJson = {}); diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index d021fbec..c4df7936 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -6,7 +6,7 @@ #include "event.h" namespace Quotient { -class RoomKeyEvent : public Event +class QUOTIENT_API RoomKeyEvent : public Event { public: DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 0fb464d4..5e446dbe 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -10,7 +10,7 @@ #include "quotient_common.h" namespace Quotient { -class MemberEventContent : public EventContent::Base { +class QUOTIENT_API MemberEventContent : public EventContent::Base { public: using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; @@ -33,7 +33,7 @@ protected: using MembershipType [[deprecated("Use Membership instead")]] = Membership; -class RoomMemberEvent : public StateEvent { +class QUOTIENT_API RoomMemberEvent : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) @@ -95,6 +95,5 @@ doLoadEvent(const QJsonObject& json, const QString& matrixType) return makeEvent(json); return makeEvent(unknownEventTypeId(), json); } - REGISTER_EVENT_TYPE(RoomMemberEvent) } // namespace Quotient diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 56597ddc..0c901b7a 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -16,7 +16,7 @@ namespace MessageEventContent = EventContent; // Back-compatibility /** * The event class corresponding to m.room.message events */ -class RoomMessageEvent : public RoomEvent { +class QUOTIENT_API RoomMessageEvent : public RoomEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.message", RoomMessageEvent) @@ -120,7 +120,7 @@ namespace EventContent { * Available fields: mimeType, body. The body can be either rich text * or plain text, depending on what mimeType specifies. */ - class TextContent : public TypedBase { + class QUOTIENT_API TextContent : public TypedBase { public: TextContent(QString text, const QString& contentType, Omittable relatesTo = none); @@ -149,7 +149,7 @@ namespace EventContent { * - thumbnail.mimeType * - thumbnail.imageSize */ - class LocationContent : public TypedBase { + class QUOTIENT_API LocationContent : public TypedBase { public: LocationContent(const QString& geoUri, const Thumbnail& thumbnail = {}); explicit LocationContent(const QJsonObject& json); @@ -168,7 +168,7 @@ namespace EventContent { * A base class for info types that include duration: audio and video */ template - class PlayableContent : public ContentT { + class QUOTIENT_API PlayableContent : public ContentT { public: using ContentT::ContentT; PlayableContent(const QJsonObject& json) diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index 0346fc0d..80e27048 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -7,7 +7,7 @@ #include "stateevent.h" namespace Quotient { -class PowerLevelsEventContent : public EventContent::Base { +class QUOTIENT_API PowerLevelsEventContent : public EventContent::Base { public: struct Notifications { int room; @@ -34,7 +34,8 @@ protected: void fillJson(QJsonObject* o) const override; }; -class RoomPowerLevelsEvent : public StateEvent { +class QUOTIENT_API RoomPowerLevelsEvent + : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.power_levels", RoomPowerLevelsEvent) @@ -61,9 +62,6 @@ public: int powerLevelForEvent(const QString& eventId) const; int powerLevelForState(const QString& eventId) const; int powerLevelForUser(const QString& userId) const; - -private: }; - REGISTER_EVENT_TYPE(RoomPowerLevelsEvent) } // namespace Quotient diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 30e53738..e336c448 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -6,7 +6,7 @@ #include "stateevent.h" namespace Quotient { -class RoomTombstoneEvent : public StateEventBase { +class QUOTIENT_API RoomTombstoneEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.tombstone", RoomTombstoneEvent) diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 9ce78609..d6557012 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -30,7 +30,8 @@ namespace EventContent { } // namespace EventContent #define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ValueType, _ContentKey) \ - class _Name : public StateEvent> { \ + class QUOTIENT_API _Name \ + : public StateEvent> { \ public: \ using value_type = content_type::value_type; \ DEFINE_EVENT_TYPEID(_TypeId, _Name) \ diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index c37965aa..6095d628 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -17,7 +17,7 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, { ContentKey, content } }; } -class StateEventBase : public RoomEvent { +class QUOTIENT_API StateEventBase : public RoomEvent { public: static inline _impl::EventFactory factory { "StateEvent" }; diff --git a/lib/events/stickerevent.h b/lib/events/stickerevent.h index 93671086..0957dca3 100644 --- a/lib/events/stickerevent.h +++ b/lib/events/stickerevent.h @@ -11,7 +11,7 @@ namespace Quotient { /// Sticker messages are specialised image messages that are displayed without /// controls (e.g. no "download" link, or light-box view on click, as would be /// displayed for for m.image events). -class StickerEvent : public RoomEvent +class QUOTIENT_API StickerEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.sticker", StickerEvent) diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 7456100a..522f7e42 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -6,7 +6,7 @@ #include "event.h" namespace Quotient { -class TypingEvent : public Event { +class QUOTIENT_API TypingEvent : public Event { public: DEFINE_EVENT_TYPEID("m.typing", TypingEvent) -- cgit v1.2.3 From 7eda212753057c07f429dfdfb0cf3a18312de054 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 28 Dec 2021 21:46:57 +0100 Subject: Refactor EventFactory and move it out of _impl:: Strictly speaking, EventFactory can be further instantiated if any client application figures they need a whole new base class for events and respectively a separate EventFactory specialisation for it. Where this whole commit started though was a linkage error because I did not plan to expose Quotient-specific logging categories for linkage (effectively, usage) from the client code - meanwhile the inline code of EventFactory uses qDebug(EVENTS), meaning I had to either add QUOTIENT_API to EVENTS or hide those invocations. This in turn led to trimming the EventFactory constructor back to trivial implementation and dropping the guard variable that was supposed to trace duplicate EventFactory objects for the same BaseEventT - with the reasoning that such situation is not really dangerous (unlike EventTypeRegistry double-initialisation fiasco, see #413), and at the same time it can be easily detected in the logs by duplicated factory method registration messages. And while I was at it, I replaced the meaningless bool in the return type of EventFactory<>::addMethod with the slightly more (but still barely) useful reference to the inserted factory method. One can (in theory) use it now if they need to turn some event JSON into an object of some specific event type or nullptr if the event type in the JSON payload doesn't match - but at the same rate (for now at least) one can call makeIfMatches() directly. With this commit, both Quotest and Quaternion build and link using either Clang or GCC even under -fvisibility=hidden. However, running quotest now reproduces #413, which is a matter of event typeId infrastructure refactoring, coming in further commits. --- lib/events/event.cpp | 8 +++ lib/events/event.h | 159 ++++++++++++++++++++++++------------------------ lib/events/roomevent.h | 2 +- lib/events/stateevent.h | 2 +- 4 files changed, 88 insertions(+), 83 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 96be717c..715e7da2 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -27,6 +27,14 @@ QString EventTypeRegistry::getMatrixType(event_type_t typeId) : QString(); } +void _impl::EventFactoryBase::logAddingMethod(event_mtype_t matrixType, + size_t newSize) +{ + qDebug(EVENTS) << "Adding factory method for" << matrixType << "events;" + << newSize << "methods will be in the" << name + << "chain"; +} + Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) { if (!json.contains(ContentKeyL) diff --git a/lib/events/event.h b/lib/events/event.h index 8a0076d0..0aef49f7 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -120,80 +120,93 @@ inline event_ptr_tt makeEvent(ArgTs&&... args) } namespace _impl { - template - event_ptr_tt makeIfMatches(const QJsonObject& json, - const QString& matrixType) + class QUOTIENT_API EventFactoryBase { + public: + EventFactoryBase(const EventFactoryBase&) = delete; + + protected: // This class is only to inherit from + explicit EventFactoryBase(const char* name) + : name(name) + {} + void logAddingMethod(event_mtype_t mtypeId, size_t newSize); + + private: + const char* const name; + }; +} // namespace _impl + +//! \brief A family of event factories to create events from CS API responses +//! +//! Each of these factories, as instantiated by event base types (Event, +//! RoomEvent etc.) is capable of producing an event object derived from +//! \p BaseEventT, using the JSON payload and the event type passed to its +//! make() method. Don't use these directly to make events; use loadEvent() +//! overloads as the frontend for these. Never instantiate new factories +//! outside of base event classes. +//! \sa loadEvent, setupFactory, Event::factory, RoomEvent::factory, +//! StateEventBase::factory +template +class EventFactory : public _impl::EventFactoryBase { +private: + std::vector (*)(const QJsonObject&, const QString&)> + methods {}; + + template + static event_ptr_tt makeIfMatches(const QJsonObject& json, + const QString& matrixType) { return QLatin1String(EventT::matrixTypeId()) == matrixType ? makeEvent(json) : nullptr; } - //! \brief A family of event factories to create events from CS API responses +public: + explicit EventFactory(const char* fName) + : EventFactoryBase { fName } + {} + + //! \brief Add a method to create events of a given type //! - //! Each of these factories, as instantiated by event base types (Event, - //! RoomEvent etc.) is capable of producing an event object derived from - //! \p BaseEventT, using the JSON payload and the event type passed to its - //! make() method. Don't use these directly to make events; use loadEvent() - //! overloads as the frontend for these. Never instantiate new factories - //! outside of base event classes. - //! \sa loadEvent, setupFactory, Event::factory, RoomEvent::factory, - //! StateEventBase::factory - template - class EventFactory - : private std::vector (*)(const QJsonObject&, - const QString&)> { - // Actual makeIfMatches specialisations will differ in the first - // template parameter but that doesn't affect the function type - public: - explicit EventFactory(const char* name = "") - : name(name) - { - static auto yetToBeConstructed = true; - Q_ASSERT(yetToBeConstructed); - if (!yetToBeConstructed) // For Release builds that pass Q_ASSERT - qCritical(EVENTS) - << "Another EventFactory for the same base type is being " - "created - event creation logic will be splintered"; - yetToBeConstructed = false; - } - EventFactory(const EventFactory&) = delete; - - //! \brief Add a method to create events of a given type - //! - //! Adds a standard factory method (makeIfMatches) for \p EventT so that - //! event objects of this type can be created dynamically by loadEvent. - //! The caller is responsible for ensuring this method is called only - //! once per type. - //! \sa makeIfMatches, loadEvent, Quotient::loadEvent - template - bool addMethod() - { - this->emplace_back(&makeIfMatches); - qDebug(EVENTS) << "Added factory method for" - << EventT::matrixTypeId() << "events;" << this->size() - << "methods in the" << name << "chain by now"; - return true; - } - - auto loadEvent(const QJsonObject& json, const QString& matrixType) - { - for (const auto& f : *this) - if (auto e = f(json, matrixType)) - return e; - return makeEvent(unknownEventTypeId(), json); - } + //! Adds a standard factory method (makeIfMatches) for \p EventT so that + //! event objects of this type can be created dynamically by loadEvent. + //! The caller is responsible for ensuring this method is called only + //! once per type. + //! \sa loadEvent, Quotient::loadEvent + template + const auto& addMethod() + { + logAddingMethod(EventT::matrixTypeId(), methods.size() + 1); + return methods.emplace_back(&makeIfMatches); + } - const char* const name; - }; -} // namespace _impl + auto loadEvent(const QJsonObject& json, const QString& matrixType) + { + for (const auto& f : methods) + if (auto e = f(json, matrixType)) + return e; + return makeEvent(unknownEventTypeId(), json); + } +}; + +//! \brief Point of customisation to dynamically load events +//! +//! The default specialisation of this calls BaseEventT::factory.loadEvent() +//! and if that fails (i.e. returns nullptr) creates an unknown event of +//! BaseEventT. Other specialisations may reuse other factories, add validations +//! common to BaseEventT events, and so on. +template +event_ptr_tt doLoadEvent(const QJsonObject& json, + const QString& matrixType) +{ + return BaseEventT::factory.loadEvent(json, matrixType); +} // === Event === class QUOTIENT_API Event { public: using Type = event_type_t; - static inline _impl::EventFactory factory { "Event" }; + static inline EventFactory factory { "Event" }; explicit Event(Type type, const QJsonObject& json); explicit Event(Type type, event_mtype_t matrixType, @@ -273,37 +286,21 @@ using Events = EventsArray; // This macro should be used in a public section of an event class to // provide matrixTypeId() and typeId(). #define DEFINE_EVENT_TYPEID(_Id, _Type) \ - static QUOTIENT_EXPORT constexpr event_mtype_t matrixTypeId() \ + static QUOTIENT_API constexpr event_mtype_t matrixTypeId() \ { \ return _Id; \ } \ - static QUOTIENT_EXPORT auto typeId() { return Quotient::typeId<_Type>(); } \ + static QUOTIENT_API auto typeId() { return Quotient::typeId<_Type>(); } \ // End of macro // This macro should be put after an event class definition (in .h or .cpp) // to enable its deserialisation from a /sync and other // polymorphic event arrays -#define REGISTER_EVENT_TYPE(_Type) \ - [[maybe_unused]] QUOTIENT_API inline const auto _factoryAdded##_Type = \ - _Type::factory.addMethod<_Type>(); \ +#define REGISTER_EVENT_TYPE(Type_) \ + [[maybe_unused]] QUOTIENT_API inline const auto& factoryMethodFor##Type_ = \ + Type_::factory.addMethod(); \ // End of macro -// === Event loading === -// (see also event_loader.h) - -//! \brief Point of customisation to dynamically load events -//! -//! The default specialisation of this calls BaseEventT::factory and if that -//! fails (i.e. returns nullptr) creates an unknown event of BaseEventT. -//! Other specialisations may reuse other factories, add validations common to -//! BaseEventT, and so on -template -event_ptr_tt doLoadEvent(const QJsonObject& json, - const QString& matrixType) -{ - return BaseEventT::factory.loadEvent(json, matrixType); -} - // === is<>(), eventCast<>() and switchOnType<>() === template diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 3fbb247e..dcee1170 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -13,7 +13,7 @@ class RedactionEvent; /** This class corresponds to m.room.* events */ class QUOTIENT_API RoomEvent : public Event { public: - static inline _impl::EventFactory factory { "RoomEvent" }; + static inline EventFactory factory { "RoomEvent" }; // RedactionEvent is an incomplete type here so we cannot inline // constructors and destructors and we cannot use 'using'. diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 6095d628..88da68f8 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -19,7 +19,7 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, class QUOTIENT_API StateEventBase : public RoomEvent { public: - static inline _impl::EventFactory factory { "StateEvent" }; + static inline EventFactory factory { "StateEvent" }; StateEventBase(Type type, const QJsonObject& json); StateEventBase(Type type, event_mtype_t matrixType, -- cgit v1.2.3 From 27bb7ba696ae803c6a6903f85fe14074b23b7bcc Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 28 Dec 2021 21:34:03 +0100 Subject: Use QLatin1String for event typeId's Before all, this fixes the problem with double-initialising of type ids; it could have been fixed with a smaller change but EventTypeRegistry is fairly superfluous now when inline variables are a thing and it's possible to have an extensible registry system using literally pointers to the memory that are guaranteed to be unique. That being said, event_type_t is still QLatin1String and not a bare const char* (or void*), mostly to stay on the safe side when it comes to type identities: unlike const char*, QLatin1String's are deep-compared, meaning that matching for switchOnType (former visit) occurs a bit slower now. This may change in the future; but this is the first step in getting rid of EventTypeRegistry. This change means that initializeTypeId is no more needed; also, two static member functions, typeId() and matrixTypeId(), are being replaced with a single inline static member variable, TypeId. This commit doesn't apply that transition across the event types, meaning that you'll get a pile of warnings when compiling the library. These warnings will be tackled in further commits within this branch. --- lib/events/event.cpp | 22 +++-------------- lib/events/event.h | 68 ++++++++++++++++------------------------------------ 2 files changed, 23 insertions(+), 67 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 715e7da2..4c304a3c 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -9,28 +9,12 @@ using namespace Quotient; -event_type_t EventTypeRegistry::initializeTypeId(event_mtype_t matrixTypeId) -{ - const auto id = get().eventTypes.size(); - get().eventTypes.push_back(matrixTypeId); - if (strncmp(matrixTypeId, "", 1) == 0) - qDebug(EVENTS) << "Initialized unknown event type with id" << id; - else - qDebug(EVENTS) << "Initialized event type" << matrixTypeId << "with id" - << id; - return id; -} - -QString EventTypeRegistry::getMatrixType(event_type_t typeId) -{ - return typeId < get().eventTypes.size() ? get().eventTypes[typeId] - : QString(); -} +QString EventTypeRegistry::getMatrixType(event_type_t typeId) { return typeId; } -void _impl::EventFactoryBase::logAddingMethod(event_mtype_t matrixType, +void _impl::EventFactoryBase::logAddingMethod(event_type_t TypeId, size_t newSize) { - qDebug(EVENTS) << "Adding factory method for" << matrixType << "events;" + qDebug(EVENTS) << "Adding factory method for" << TypeId << "events;" << newSize << "methods will be in the" << name << "chain"; } diff --git a/lib/events/event.h b/lib/events/event.h index 0aef49f7..47f07c1d 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -55,60 +55,32 @@ inline QJsonObject basicEventJson(const QString& matrixType, return { { TypeKey, matrixType }, { ContentKey, content } }; } -// === Event types and event types registry === +// === Event types === -using event_type_t = size_t; +using event_type_t = QLatin1String; using event_mtype_t = const char*; class QUOTIENT_API EventTypeRegistry { public: ~EventTypeRegistry() = default; - static event_type_t initializeTypeId(event_mtype_t matrixTypeId); - - template - static event_type_t initializeTypeId() - { - return initializeTypeId(EventT::matrixTypeId()); - } - + [[deprecated("event_type_t is a string now, use it directly instead")]] static QString getMatrixType(event_type_t typeId); private: EventTypeRegistry() = default; Q_DISABLE_COPY_MOVE(EventTypeRegistry) - - static EventTypeRegistry& get() - { - static EventTypeRegistry etr; - return etr; - } - - std::vector eventTypes; -}; - -template <> -inline event_type_t EventTypeRegistry::initializeTypeId() -{ - return initializeTypeId(""); -} - -template -struct EventTypeTraits { - static event_type_t id() - { - static const auto id = EventTypeRegistry::initializeTypeId(); - return id; - } }; template inline event_type_t typeId() { - return EventTypeTraits>::id(); + return std::decay_t::TypeId; } -inline event_type_t unknownEventTypeId() { return typeId(); } +constexpr inline event_type_t UnknownEventTypeId = "?"_ls; +[[deprecated("Use UnknownEventTypeId")]] +constexpr inline event_type_t unknownEventTypeId() { return UnknownEventTypeId; } // === Event creation facilities === @@ -128,7 +100,7 @@ namespace _impl { explicit EventFactoryBase(const char* name) : name(name) {} - void logAddingMethod(event_mtype_t mtypeId, size_t newSize); + void logAddingMethod(event_type_t TypeId, size_t newSize); private: const char* const name; @@ -155,9 +127,9 @@ private: static event_ptr_tt makeIfMatches(const QJsonObject& json, const QString& matrixType) { - return QLatin1String(EventT::matrixTypeId()) == matrixType - ? makeEvent(json) - : nullptr; + // If your matrix event type is not all ASCII, it's your problem + // (see https://github.com/matrix-org/matrix-doc/pull/2758) + return EventT::TypeId == matrixType ? makeEvent(json) : nullptr; } public: @@ -175,7 +147,7 @@ public: template const auto& addMethod() { - logAddingMethod(EventT::matrixTypeId(), methods.size() + 1); + logAddingMethod(EventT::TypeId, methods.size() + 1); return methods.emplace_back(&makeIfMatches); } @@ -184,7 +156,7 @@ public: for (const auto& f : methods) if (auto e = f(json, matrixType)) return e; - return makeEvent(unknownEventTypeId(), json); + return makeEvent(UnknownEventTypeId, json); } }; @@ -285,12 +257,12 @@ using Events = EventsArray; // This macro should be used in a public section of an event class to // provide matrixTypeId() and typeId(). -#define DEFINE_EVENT_TYPEID(_Id, _Type) \ - static QUOTIENT_API constexpr event_mtype_t matrixTypeId() \ - { \ - return _Id; \ - } \ - static QUOTIENT_API auto typeId() { return Quotient::typeId<_Type>(); } \ +#define DEFINE_EVENT_TYPEID(Id_, Type_) \ + static inline constexpr event_type_t TypeId = Id_##_ls; \ + [[deprecated("Use _Type::TypeId directly instead")]] \ + static constexpr event_mtype_t matrixTypeId() { return Id_; } \ + [[deprecated("Use _Type::TypeId directly instead")]] \ + static event_type_t typeId() { return TypeId; } \ // End of macro // This macro should be put after an event class definition (in .h or .cpp) @@ -311,7 +283,7 @@ inline bool is(const Event& e) inline bool isUnknown(const Event& e) { - return e.type() == unknownEventTypeId(); + return e.type() == UnknownEventTypeId; } template -- cgit v1.2.3 From 8f03628ee0e4d1d1cb4e2f237e8fa695bc2cde42 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 30 Dec 2021 15:24:58 +0100 Subject: Drop inline next to constexpr Thanks to Sonar for reminding that constexpr implies inline. --- lib/events/event.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 47f07c1d..692e88e7 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -78,9 +78,9 @@ inline event_type_t typeId() return std::decay_t::TypeId; } -constexpr inline event_type_t UnknownEventTypeId = "?"_ls; +constexpr event_type_t UnknownEventTypeId = "?"_ls; [[deprecated("Use UnknownEventTypeId")]] -constexpr inline event_type_t unknownEventTypeId() { return UnknownEventTypeId; } +constexpr event_type_t unknownEventTypeId() { return UnknownEventTypeId; } // === Event creation facilities === @@ -258,7 +258,7 @@ using Events = EventsArray; // This macro should be used in a public section of an event class to // provide matrixTypeId() and typeId(). #define DEFINE_EVENT_TYPEID(Id_, Type_) \ - static inline constexpr event_type_t TypeId = Id_##_ls; \ + static constexpr event_type_t TypeId = Id_##_ls; \ [[deprecated("Use _Type::TypeId directly instead")]] \ static constexpr event_mtype_t matrixTypeId() { return Id_; } \ [[deprecated("Use _Type::TypeId directly instead")]] \ -- cgit v1.2.3 From 22ac47b275c2bcad5b5ff3c0cc3e10f3caaeb65b Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 30 Dec 2021 15:46:11 +0100 Subject: Don't use QUOTIENT_API inside REGISTER_EVENT_TYPE On Windows QUOTIENT_API expands to different things depending on whether the library is built or used. This results in confusing statements (and MSVC erroring out on them, in some cases - see below - quite legitimately) not only when the application includes Quotient headers but also when the application defines custom events and uses REGISTER_EVENT_TYPE to make them creatable from /sync responses. To avoid repeated registration when dynamic linking is involved, EventFactory<>::addMethod() now bluntly looks up the method for this type in the vector of already registered methods. It would surely be quicker to use a static variable instead; but since the refreshed API for addMethod returns a reference to the factory method it's necessary to do this lookup anyway. Once the primary goal of this branch is achieved across platforms I might experiment with lighter ways to register factory methods; for now here's a minimal change to make the code build on Windows. --- lib/events/event.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 692e88e7..4024c6f8 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -73,7 +73,7 @@ private: }; template -inline event_type_t typeId() +constexpr event_type_t typeId() { return std::decay_t::TypeId; } @@ -147,8 +147,12 @@ public: template const auto& addMethod() { + const auto m = &makeIfMatches; + const auto it = std::find(methods.cbegin(), methods.cend(), m); + if (it != methods.cend()) + return *it; logAddingMethod(EventT::TypeId, methods.size() + 1); - return methods.emplace_back(&makeIfMatches); + return methods.emplace_back(m); } auto loadEvent(const QJsonObject& json, const QString& matrixType) @@ -268,9 +272,9 @@ using Events = EventsArray; // This macro should be put after an event class definition (in .h or .cpp) // to enable its deserialisation from a /sync and other // polymorphic event arrays -#define REGISTER_EVENT_TYPE(Type_) \ - [[maybe_unused]] QUOTIENT_API inline const auto& factoryMethodFor##Type_ = \ - Type_::factory.addMethod(); \ +#define REGISTER_EVENT_TYPE(Type_) \ + [[maybe_unused]] inline const auto& factoryMethodFor##Type_ = \ + Type_::factory.addMethod(); \ // End of macro // === is<>(), eventCast<>() and switchOnType<>() === -- cgit v1.2.3 From 874ea3fae21d6b5cab12c8e524e8b25442e4cdd5 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 30 Dec 2021 17:55:23 +0100 Subject: Fix more Sonar warnings --- lib/events/event.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 4024c6f8..f12e525e 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -120,8 +120,9 @@ namespace _impl { template class EventFactory : public _impl::EventFactoryBase { private: - std::vector (*)(const QJsonObject&, const QString&)> - methods {}; + using method_t = event_ptr_tt (*)(const QJsonObject&, + const QString&); + std::vector methods {}; template static event_ptr_tt makeIfMatches(const QJsonObject& json, -- cgit v1.2.3 From 9e3752b8333813b9f00970a1af6e7ca9087ca424 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 5 Jan 2022 14:37:07 +0100 Subject: Thumbnail: drop unneeded constructors Those are already inherited with 'using'. --- lib/events/eventcontent.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 87ea3672..de9a792b 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -149,10 +149,8 @@ namespace EventContent { */ class QUOTIENT_API Thumbnail : public ImageInfo { public: - Thumbnail() = default; // Allow empty thumbnails - Thumbnail(const QJsonObject& infoJson, const Omittable &file = none); - Thumbnail(const ImageInfo& info) : ImageInfo(info) {} using ImageInfo::ImageInfo; + Thumbnail(const QJsonObject& infoJson, const Omittable &file = none); /** * Writes thumbnail information to "thumbnail_info" subobject -- cgit v1.2.3 From 3986de7f8f1c98f952911c2f93891ea8643df62c Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 5 Jan 2022 15:08:57 +0100 Subject: Make TagRecord generally better It doesn't need all those things inside - order_type alias is no more in use; operator<() is better outside; QLatin1String is better to compare against than const char* (because const char* is assumed to be UTF-8); and TagRecord is really small so it doesn't need const& for parameters. --- lib/events/accountdataevents.h | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index c0f2202d..12f1f00b 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -4,27 +4,24 @@ #pragma once #include "event.h" +#include "util.h" namespace Quotient { -constexpr const char* FavouriteTag = "m.favourite"; -constexpr const char* LowPriorityTag = "m.lowpriority"; -constexpr const char* ServerNoticeTag = "m.server_notice"; +constexpr auto FavouriteTag [[maybe_unused]] = "m.favourite"_ls; +constexpr auto LowPriorityTag [[maybe_unused]] = "m.lowpriority"_ls; +constexpr auto ServerNoticeTag [[maybe_unused]] = "m.server_notice"_ls; struct TagRecord { - using order_type = Omittable; - - order_type order; - - TagRecord(order_type order = none) : order(order) {} - - bool operator<(const TagRecord& other) const - { - // Per The Spec, rooms with no order should be after those with order, - // against std::optional<>::operator<() convention. - return order && (!other.order || *order < *other.order); - } + Omittable order = none; }; +inline bool operator<(TagRecord lhs, TagRecord rhs) +{ + // Per The Spec, rooms with no order should be after those with order, + // against std::optional<>::operator<() convention. + return lhs.order && (!rhs.order || *lhs.order < *rhs.order); +} + template <> struct JsonObjectConverter { static void fillFrom(const QJsonObject& jo, TagRecord& rec) @@ -41,7 +38,7 @@ struct JsonObjectConverter { rec.order = none; } } - static void dumpTo(QJsonObject& jo, const TagRecord& rec) + static void dumpTo(QJsonObject& jo, TagRecord rec) { addParam(jo, QStringLiteral("order"), rec.order); } -- cgit v1.2.3 From 9351d9afcbaae0bdc8aa26f7361be1f84cac7467 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 5 Jan 2022 15:13:24 +0100 Subject: DEFINE_EVENT_TYPEID: fix up deprecation warnings --- lib/events/event.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index f12e525e..858972da 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -264,9 +264,9 @@ using Events = EventsArray; // provide matrixTypeId() and typeId(). #define DEFINE_EVENT_TYPEID(Id_, Type_) \ static constexpr event_type_t TypeId = Id_##_ls; \ - [[deprecated("Use _Type::TypeId directly instead")]] \ + [[deprecated("Use " #Type_ "::TypeId directly instead")]] \ static constexpr event_mtype_t matrixTypeId() { return Id_; } \ - [[deprecated("Use _Type::TypeId directly instead")]] \ + [[deprecated("Use " #Type_ "::TypeId directly instead")]] \ static event_type_t typeId() { return TypeId; } \ // End of macro -- cgit v1.2.3 From bd280a087ecab30f94f7937513ee298c233fcba1 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 18 Jan 2022 08:54:52 +0100 Subject: Revise inline keyword usage - Templates and constexpr imply inline - A function called from a single site better be inlined. --- lib/events/event.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 858972da..f10f6a8d 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -311,7 +311,7 @@ inline auto switchOnType(const BaseEventT& event, FnT&& fn) namespace _impl { // Using bool instead of auto below because auto apparently upsets MSVC template - inline constexpr bool needs_downcast = + constexpr bool needs_downcast = std::is_base_of_v>> && !std::is_same_v>>; } -- cgit v1.2.3 From c7907084282c7957d085acb329574ab6a7d593c8 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 18 Jan 2022 11:43:32 +0100 Subject: Move over non-interface code to QLatin1String It's better than const char* because any interaction between const char* and QString assumes that const char* contains UTF-8, which is pessimistic and therefore inefficient; at the same time: - construction of QString from QLatin1String is extremely fast (boiling down to padding null bytes) - "something"_ls is much shorter than QStringLiteral("something") - "something"_ls produces a direct pointer to the literal at compile time, using the benefits of raw string literals (deduplication, e.g.) The library API will also transition to QLatin1String where applicable, likely in 0.8. --- lib/events/roommessageevent.cpp | 64 ++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 32 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 2b7b4166..0f58d8a6 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -19,15 +19,13 @@ using namespace EventContent; using MsgType = RoomMessageEvent::MsgType; -static const auto RelatesToKeyL = "m.relates_to"_ls; -static const auto MsgTypeKeyL = "msgtype"_ls; -static const auto FormattedBodyKeyL = "formatted_body"_ls; - -static const auto TextTypeKey = "m.text"; -static const auto EmoteTypeKey = "m.emote"; -static const auto NoticeTypeKey = "m.notice"; - -static const auto HtmlContentTypeId = QStringLiteral("org.matrix.custom.html"); +static constexpr auto RelatesToKey = "m.relates_to"_ls; +static constexpr auto MsgTypeKey = "msgtype"_ls; +static constexpr auto FormattedBodyKey = "formatted_body"_ls; +static constexpr auto TextTypeKey = "m.text"_ls; +static constexpr auto EmoteTypeKey = "m.emote"_ls; +static constexpr auto NoticeTypeKey = "m.notice"_ls; +static constexpr auto HtmlContentTypeId = "org.matrix.custom.html"_ls; template TypedBase* make(const QJsonObject& json) @@ -38,13 +36,13 @@ TypedBase* make(const QJsonObject& json) template <> TypedBase* make(const QJsonObject& json) { - return json.contains(FormattedBodyKeyL) || json.contains(RelatesToKeyL) + return json.contains(FormattedBodyKey) || json.contains(RelatesToKey) ? new TextContent(json) : nullptr; } struct MsgTypeDesc { - QString matrixType; + QLatin1String matrixType; MsgType enumType; TypedBase* (*maker)(const QJsonObject&); }; @@ -53,11 +51,11 @@ const std::vector msgTypes = { { TextTypeKey, MsgType::Text, make }, { EmoteTypeKey, MsgType::Emote, make }, { NoticeTypeKey, MsgType::Notice, make }, - { QStringLiteral("m.image"), MsgType::Image, make }, - { QStringLiteral("m.file"), MsgType::File, make }, - { QStringLiteral("m.location"), MsgType::Location, make }, - { QStringLiteral("m.video"), MsgType::Video, make }, - { QStringLiteral("m.audio"), MsgType::Audio, make } + { "m.image"_ls, MsgType::Image, make }, + { "m.file"_ls, MsgType::File, make }, + { "m.location"_ls, MsgType::Location, make }, + { "m.video"_ls, MsgType::Video, make }, + { "m.audio"_ls, MsgType::Audio, make } }; QString msgTypeToJson(MsgType enumType) @@ -94,12 +92,12 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, TypedBase* content) { auto json = content ? content->toJson() : QJsonObject(); - if (json.contains(RelatesToKeyL)) { + if (json.contains(RelatesToKey)) { if (jsonMsgType != TextTypeKey && jsonMsgType != NoticeTypeKey && jsonMsgType != EmoteTypeKey) { - json.remove(RelatesToKeyL); + json.remove(RelatesToKey); qCWarning(EVENTS) - << RelatesToKeyL << "cannot be used in" << jsonMsgType + << RelatesToKey << "cannot be used in" << jsonMsgType << "messages; the relation has been stripped off"; } else { // After the above, we know for sure that the content is TextContent @@ -109,9 +107,9 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, if (textContent->relatesTo->type == RelatesTo::ReplacementTypeId()) { auto newContentJson = json.take("m.new_content"_ls).toObject(); newContentJson.insert(BodyKey, plainBody); - newContentJson.insert(MsgTypeKeyL, jsonMsgType); + newContentJson.insert(MsgTypeKey, jsonMsgType); json.insert(QStringLiteral("m.new_content"), newContentJson); - json[MsgTypeKeyL] = jsonMsgType; + json[MsgTypeKey] = jsonMsgType; json[BodyKeyL] = "* " + plainBody; return json; } @@ -177,8 +175,8 @@ RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) if (isRedacted()) return; const QJsonObject content = contentJson(); - if (content.contains(MsgTypeKeyL) && content.contains(BodyKeyL)) { - auto msgtype = content[MsgTypeKeyL].toString(); + if (content.contains(MsgTypeKey) && content.contains(BodyKeyL)) { + auto msgtype = content[MsgTypeKey].toString(); bool msgTypeFound = false; for (const auto& mt : msgTypes) if (mt.matrixType == msgtype) { @@ -204,7 +202,7 @@ RoomMessageEvent::MsgType RoomMessageEvent::msgtype() const QString RoomMessageEvent::rawMsgtype() const { - return contentPart(MsgTypeKeyL); + return contentPart(MsgTypeKey); } QString RoomMessageEvent::plainBody() const @@ -295,7 +293,7 @@ Omittable fromJson(const QJsonValue& jv) } // namespace Quotient TextContent::TextContent(const QJsonObject& json) - : relatesTo(fromJson>(json[RelatesToKeyL])) + : relatesTo(fromJson>(json[RelatesToKey])) { QMimeDatabase db; static const auto PlainTextMimeType = db.mimeTypeForName("text/plain"); @@ -308,7 +306,7 @@ TextContent::TextContent(const QJsonObject& json) // of sending HTML messages. if (actualJson["format"_ls].toString() == HtmlContentTypeId) { mimeType = HtmlMimeType; - body = actualJson[FormattedBodyKeyL].toString(); + body = actualJson[FormattedBodyKey].toString(); } else { // Falling back to plain text, as there's no standard way to describe // rich text in messages. @@ -320,7 +318,6 @@ TextContent::TextContent(const QJsonObject& json) void TextContent::fillJson(QJsonObject* json) const { static const auto FormatKey = QStringLiteral("format"); - static const auto FormattedBodyKey = QStringLiteral("formatted_body"); Q_ASSERT(json); if (mimeType.inherits("text/html")) { @@ -328,11 +325,14 @@ void TextContent::fillJson(QJsonObject* json) const json->insert(FormattedBodyKey, body); } if (relatesTo) { - json->insert(QStringLiteral("m.relates_to"), - relatesTo->type == RelatesTo::ReplyTypeId() ? - QJsonObject { { relatesTo->type, QJsonObject{ { EventIdKey, relatesTo->eventId } } } } : - QJsonObject { { "rel_type", relatesTo->type }, { EventIdKey, relatesTo->eventId } } - ); + json->insert( + QStringLiteral("m.relates_to"), + relatesTo->type == RelatesTo::ReplyTypeId() + ? QJsonObject { { relatesTo->type, + QJsonObject { + { EventIdKey, relatesTo->eventId } } } } + : QJsonObject { { "rel_type", relatesTo->type }, + { EventIdKey, relatesTo->eventId } }); if (relatesTo->type == RelatesTo::ReplacementTypeId()) { QJsonObject newContentJson; if (mimeType.inherits("text/html")) { -- cgit v1.2.3 From bf82aeea369cacfc93a0e6d6d9feb01f1f2afdb2 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 18 Jan 2022 11:43:21 +0100 Subject: Don't use 'static' on top-level/namespace scope When internal linkage is necessary, anonymous namespaces fulfil the same purpose in a better way. See also: https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static --- lib/events/roommessageevent.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 0f58d8a6..5ab0f845 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -19,13 +19,15 @@ using namespace EventContent; using MsgType = RoomMessageEvent::MsgType; -static constexpr auto RelatesToKey = "m.relates_to"_ls; -static constexpr auto MsgTypeKey = "msgtype"_ls; -static constexpr auto FormattedBodyKey = "formatted_body"_ls; -static constexpr auto TextTypeKey = "m.text"_ls; -static constexpr auto EmoteTypeKey = "m.emote"_ls; -static constexpr auto NoticeTypeKey = "m.notice"_ls; -static constexpr auto HtmlContentTypeId = "org.matrix.custom.html"_ls; +namespace { // Supporting internal definitions + +constexpr auto RelatesToKey = "m.relates_to"_ls; +constexpr auto MsgTypeKey = "msgtype"_ls; +constexpr auto FormattedBodyKey = "formatted_body"_ls; +constexpr auto TextTypeKey = "m.text"_ls; +constexpr auto EmoteTypeKey = "m.emote"_ls; +constexpr auto NoticeTypeKey = "m.notice"_ls; +constexpr auto HtmlContentTypeId = "org.matrix.custom.html"_ls; template TypedBase* make(const QJsonObject& json) @@ -87,6 +89,8 @@ inline bool isReplacement(const Omittable& rel) return rel && rel->type == RelatesTo::ReplacementTypeId(); } +} // anonymous namespace + QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, const QString& jsonMsgType, TypedBase* content) -- cgit v1.2.3 From fdff209744ac4c422f63fe2549aa0132df7e6292 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 21 Jan 2022 02:04:10 +0100 Subject: Redo EventRelation; deprecate RelatesTo RelatesTo and EventRelation have been two means to the same end in two different contexts. (Modernised) EventRelation is the one used now both for ReactionEvent and EventContent::TextContent. The modernisation mostly boils down to using inline variables instead of functions to return relation types and switching to QLatin1String from const char* (because we know exactly that those constants are Latin-1 and QLatin1String is more efficient than const char* to compare/convert to QString). --- lib/events/eventrelation.cpp | 38 ++++++++++++++++++++++++++++++ lib/events/eventrelation.h | 52 +++++++++++++++++++++++++++++++++++++++++ lib/events/reactionevent.cpp | 29 ----------------------- lib/events/reactionevent.h | 32 ++----------------------- lib/events/roommessageevent.cpp | 38 ++++++++---------------------- lib/events/roommessageevent.h | 27 +++++++++++---------- 6 files changed, 117 insertions(+), 99 deletions(-) create mode 100644 lib/events/eventrelation.cpp create mode 100644 lib/events/eventrelation.h delete mode 100644 lib/events/reactionevent.cpp (limited to 'lib/events') diff --git a/lib/events/eventrelation.cpp b/lib/events/eventrelation.cpp new file mode 100644 index 00000000..04972f45 --- /dev/null +++ b/lib/events/eventrelation.cpp @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2022 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "eventrelation.h" + +#include "../logging.h" +#include "event.h" + +using namespace Quotient; + +void JsonObjectConverter::dumpTo(QJsonObject& jo, + const EventRelation& pod) +{ + if (pod.type.isEmpty()) { + qCWarning(MAIN) << "Empty relation type; won't dump to JSON"; + return; + } + jo.insert(RelTypeKey, pod.type); + jo.insert(EventIdKey, pod.eventId); + if (pod.type == EventRelation::AnnotationType) + jo.insert(QStringLiteral("key"), pod.key); +} + +void JsonObjectConverter::fillFrom(const QJsonObject& jo, + EventRelation& pod) +{ + if (const auto replyJson = jo.value(EventRelation::ReplyType).toObject(); + !replyJson.isEmpty()) { + pod.type = EventRelation::ReplyType; + fromJson(replyJson[EventIdKeyL], pod.eventId); + } else { + // The experimental logic for generic relationships (MSC1849) + fromJson(jo[RelTypeKey], pod.type); + fromJson(jo[EventIdKeyL], pod.eventId); + if (pod.type == EventRelation::AnnotationType) + fromJson(jo["key"_ls], pod.key); + } +} diff --git a/lib/events/eventrelation.h b/lib/events/eventrelation.h new file mode 100644 index 00000000..e445ee42 --- /dev/null +++ b/lib/events/eventrelation.h @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2022 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later + +#pragma once + +#include "converters.h" + +namespace Quotient { + +[[maybe_unused]] constexpr auto RelatesToKey = "m.relates_to"_ls; +constexpr auto RelTypeKey = "rel_type"_ls; + +struct QUOTIENT_API EventRelation { + using reltypeid_t = QLatin1String; + + QString type; + QString eventId; + QString key = {}; // Only used for m.annotation for now + + static constexpr auto ReplyType = "m.in_reply_to"_ls; + static constexpr auto AnnotationType = "m.annotation"_ls; + static constexpr auto ReplacementType = "m.replace"_ls; + + static EventRelation replyTo(QString eventId) + { + return { ReplyType, std::move(eventId) }; + } + static EventRelation annotate(QString eventId, QString key) + { + return { AnnotationType, std::move(eventId), std::move(key) }; + } + static EventRelation replace(QString eventId) + { + return { ReplacementType, std::move(eventId) }; + } + + [[deprecated("Use ReplyRelation variable instead")]] + static constexpr auto Reply() { return ReplyType; } + [[deprecated("Use AnnotationRelation variable instead")]] // + static constexpr auto Annotation() { return AnnotationType; } + [[deprecated("Use ReplacementRelation variable instead")]] // + static constexpr auto Replacement() { return ReplacementType; } +}; + +template <> +struct QUOTIENT_API JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const EventRelation& pod); + static void fillFrom(const QJsonObject& jo, EventRelation& pod); +}; + +} + diff --git a/lib/events/reactionevent.cpp b/lib/events/reactionevent.cpp deleted file mode 100644 index b53fffd6..00000000 --- a/lib/events/reactionevent.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2019 Kitsune Ral -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "reactionevent.h" - -using namespace Quotient; - -void JsonObjectConverter::dumpTo( - QJsonObject& jo, const EventRelation& pod) -{ - if (pod.type.isEmpty()) { - qCWarning(MAIN) << "Empty relation type; won't dump to JSON"; - return; - } - jo.insert(QStringLiteral("rel_type"), pod.type); - jo.insert(EventIdKey, pod.eventId); - if (pod.type == EventRelation::Annotation()) - jo.insert(QStringLiteral("key"), pod.key); -} - -void JsonObjectConverter::fillFrom( - const QJsonObject& jo, EventRelation& pod) -{ - // The experimental logic for generic relationships (MSC1849) - fromJson(jo["rel_type"_ls], pod.type); - fromJson(jo[EventIdKeyL], pod.eventId); - if (pod.type == EventRelation::Annotation()) - fromJson(jo["key"_ls], pod.key); -} diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index ce11eaed..b3cb3ca7 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -4,38 +4,10 @@ #pragma once #include "roomevent.h" +#include "eventrelation.h" namespace Quotient { -struct QUOTIENT_API EventRelation { - using reltypeid_t = const char*; - static constexpr reltypeid_t Reply() { return "m.in_reply_to"; } - static constexpr reltypeid_t Annotation() { return "m.annotation"; } - static constexpr reltypeid_t Replacement() { return "m.replace"; } - - QString type; - QString eventId; - QString key = {}; // Only used for m.annotation for now - - static EventRelation replyTo(QString eventId) - { - return { Reply(), std::move(eventId) }; - } - static EventRelation annotate(QString eventId, QString key) - { - return { Annotation(), std::move(eventId), std::move(key) }; - } - static EventRelation replace(QString eventId) - { - return { Replacement(), std::move(eventId) }; - } -}; -template <> -struct QUOTIENT_API JsonObjectConverter { - static void dumpTo(QJsonObject& jo, const EventRelation& pod); - static void fillFrom(const QJsonObject& jo, EventRelation& pod); -}; - class QUOTIENT_API ReactionEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.reaction", ReactionEvent) @@ -47,7 +19,7 @@ public: explicit ReactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} EventRelation relation() const { - return contentPart("m.relates_to"_ls); + return contentPart(RelatesToKey); } }; REGISTER_EVENT_TYPE(ReactionEvent) diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 5ab0f845..c07a4f3c 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -6,6 +6,7 @@ #include "roommessageevent.h" #include "logging.h" +#include "events/eventrelation.h" #include #include @@ -20,7 +21,6 @@ using namespace EventContent; using MsgType = RoomMessageEvent::MsgType; namespace { // Supporting internal definitions - constexpr auto RelatesToKey = "m.relates_to"_ls; constexpr auto MsgTypeKey = "msgtype"_ls; constexpr auto FormattedBodyKey = "formatted_body"_ls; @@ -84,9 +84,9 @@ MsgType jsonToMsgType(const QString& matrixType) return MsgType::Unknown; } -inline bool isReplacement(const Omittable& rel) +inline bool isReplacement(const Omittable& rel) { - return rel && rel->type == RelatesTo::ReplacementTypeId(); + return rel && rel->type == EventRelation::ReplacementType; } } // anonymous namespace @@ -105,10 +105,10 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, << "messages; the relation has been stripped off"; } else { // After the above, we know for sure that the content is TextContent - // and that its RelatesTo structure is not omitted + // and that its EventRelation structure is not omitted auto* textContent = static_cast(content); Q_ASSERT(textContent && textContent->relatesTo.has_value()); - if (textContent->relatesTo->type == RelatesTo::ReplacementTypeId()) { + if (textContent->relatesTo->type == EventRelation::ReplacementType) { auto newContentJson = json.take("m.new_content"_ls).toObject(); newContentJson.insert(BodyKey, plainBody); newContentJson.insert(MsgTypeKey, jsonMsgType); @@ -269,7 +269,7 @@ QString RoomMessageEvent::rawMsgTypeForFile(const QFileInfo& fi) } TextContent::TextContent(QString text, const QString& contentType, - Omittable relatesTo) + Omittable relatesTo) : mimeType(QMimeDatabase().mimeTypeForName(contentType)) , body(std::move(text)) , relatesTo(std::move(relatesTo)) @@ -278,26 +278,8 @@ TextContent::TextContent(QString text, const QString& contentType, mimeType = QMimeDatabase().mimeTypeForName("text/html"); } -namespace Quotient { -// Overload the default fromJson<> logic that defined in converters.h -// as we want -template <> -Omittable fromJson(const QJsonValue& jv) -{ - const auto jo = jv.toObject(); - if (jo.isEmpty()) - return none; - const auto replyJson = jo.value(RelatesTo::ReplyTypeId()).toObject(); - if (!replyJson.isEmpty()) - return replyTo(fromJson(replyJson[EventIdKeyL])); - - return RelatesTo { jo.value("rel_type"_ls).toString(), - jo.value(EventIdKeyL).toString() }; -} -} // namespace Quotient - TextContent::TextContent(const QJsonObject& json) - : relatesTo(fromJson>(json[RelatesToKey])) + : relatesTo(fromJson>(json[RelatesToKey])) { QMimeDatabase db; static const auto PlainTextMimeType = db.mimeTypeForName("text/plain"); @@ -331,13 +313,13 @@ void TextContent::fillJson(QJsonObject* json) const if (relatesTo) { json->insert( QStringLiteral("m.relates_to"), - relatesTo->type == RelatesTo::ReplyTypeId() + relatesTo->type == EventRelation::ReplyType ? QJsonObject { { relatesTo->type, QJsonObject { { EventIdKey, relatesTo->eventId } } } } - : QJsonObject { { "rel_type", relatesTo->type }, + : QJsonObject { { RelTypeKey, relatesTo->type }, { EventIdKey, relatesTo->eventId } }); - if (relatesTo->type == RelatesTo::ReplacementTypeId()) { + if (relatesTo->type == EventRelation::ReplacementType) { QJsonObject newContentJson; if (mimeType.inherits("text/html")) { newContentJson.insert(FormatKey, HtmlContentTypeId); diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 0c901b7a..44ef05fb 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -6,6 +6,7 @@ #pragma once #include "eventcontent.h" +#include "eventrelation.h" #include "roomevent.h" class QFileInfo; @@ -97,23 +98,25 @@ REGISTER_EVENT_TYPE(RoomMessageEvent) using MessageEventType = RoomMessageEvent::MsgType; namespace EventContent { - // Additional event content types - struct RelatesTo { - static constexpr const char* ReplyTypeId() { return "m.in_reply_to"; } - static constexpr const char* ReplacementTypeId() { return "m.replace"; } - QString type; // The only supported relation so far - QString eventId; + struct [[deprecated("Use Quotient::EventRelation instead")]] RelatesTo + : EventRelation { + static constexpr auto ReplyTypeId() { return Reply(); } + static constexpr auto ReplacementTypeId() { return Replacement(); } }; - inline RelatesTo replyTo(QString eventId) + [[deprecated("Use EventRelation::replyTo() instead")]] + inline auto replyTo(QString eventId) { - return { RelatesTo::ReplyTypeId(), std::move(eventId) }; + return EventRelation::replyTo(std::move(eventId)); } - inline RelatesTo replacementOf(QString eventId) + [[deprecated("Use EventRelation::replace() instead")]] + inline auto replacementOf(QString eventId) { - return { RelatesTo::ReplacementTypeId(), std::move(eventId) }; + return EventRelation::replace(std::move(eventId)); } + // Additional event content types + /** * Rich text content for m.text, m.emote, m.notice * @@ -123,14 +126,14 @@ namespace EventContent { class QUOTIENT_API TextContent : public TypedBase { public: TextContent(QString text, const QString& contentType, - Omittable relatesTo = none); + Omittable relatesTo = none); explicit TextContent(const QJsonObject& json); QMimeType type() const override { return mimeType; } QMimeType mimeType; QString body; - Omittable relatesTo; + Omittable relatesTo; protected: void fillJson(QJsonObject* json) const override; -- cgit v1.2.3 From 0689028f4a0db403a55c6158e750fee3ba6c7098 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 20 Jan 2022 17:35:28 +0100 Subject: Refactor assembleContentJson() Get rid of that Q_ASSERT() in the middle that only worked in Debug builds anyway. --- lib/events/roommessageevent.cpp | 43 +++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 21 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index c07a4f3c..d63352cb 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -95,32 +95,33 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, const QString& jsonMsgType, TypedBase* content) { - auto json = content ? content->toJson() : QJsonObject(); - if (json.contains(RelatesToKey)) { + QJsonObject json; + if (content) { + // TODO: replace with content->fillJson(json) when it starts working + json = content->toJson(); if (jsonMsgType != TextTypeKey && jsonMsgType != NoticeTypeKey && jsonMsgType != EmoteTypeKey) { - json.remove(RelatesToKey); - qCWarning(EVENTS) - << RelatesToKey << "cannot be used in" << jsonMsgType - << "messages; the relation has been stripped off"; - } else { - // After the above, we know for sure that the content is TextContent - // and that its EventRelation structure is not omitted - auto* textContent = static_cast(content); - Q_ASSERT(textContent && textContent->relatesTo.has_value()); - if (textContent->relatesTo->type == EventRelation::ReplacementType) { - auto newContentJson = json.take("m.new_content"_ls).toObject(); - newContentJson.insert(BodyKey, plainBody); - newContentJson.insert(MsgTypeKey, jsonMsgType); - json.insert(QStringLiteral("m.new_content"), newContentJson); - json[MsgTypeKey] = jsonMsgType; - json[BodyKeyL] = "* " + plainBody; - return json; + if (json.contains(RelatesToKey)) { + json.remove(RelatesToKey); + qCWarning(EVENTS) + << RelatesToKey << "cannot be used in" << jsonMsgType + << "messages; the relation has been stripped off"; } + } else if (auto* textContent = static_cast(content); + textContent->relatesTo + && textContent->relatesTo->type + == EventRelation::ReplacementType) { + auto newContentJson = json.take("m.new_content"_ls).toObject(); + newContentJson.insert(BodyKey, plainBody); + newContentJson.insert(MsgTypeKey, jsonMsgType); + json.insert(QStringLiteral("m.new_content"), newContentJson); + json[MsgTypeKey] = jsonMsgType; + json[BodyKeyL] = "* " + plainBody; + return json; } } - json.insert(QStringLiteral("msgtype"), jsonMsgType); - json.insert(QStringLiteral("body"), plainBody); + json.insert(MsgTypeKey, jsonMsgType); + json.insert(BodyKey, plainBody); return json; } -- cgit v1.2.3 From cc9908e5159ed93a18eda9f9794a7c9fc7f67f27 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 23 Jan 2022 10:34:38 +0100 Subject: Fix visit() return type It's too restrictive compared to switchOnType() overloads and doesn't map to the case with a default value. --- lib/events/event.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index f10f6a8d..113fa3fa 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -354,8 +354,7 @@ switchOnType(const BaseT& event, FnT1&& fn1, FnT2&& fn2, FnTs&&... fns) template [[deprecated("The new name for visit() is switchOnType()")]] // -inline std::common_type_t...> -visit(const BaseT& event, FnTs&&... fns) +inline auto visit(const BaseT& event, FnTs&&... fns) { return switchOnType(event, std::forward(fns)...); } -- cgit v1.2.3 From 29775218e0c8b6c176015dd3128a0d545906ae6f Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 2 Dec 2021 20:54:39 +0100 Subject: Cleanup some #includes --- lib/events/eventcontent.cpp | 1 - lib/events/receiptevent.cpp | 1 - lib/events/roomevent.cpp | 1 - lib/events/roommemberevent.cpp | 1 - 4 files changed, 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 22878d4c..4ce130a6 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -4,7 +4,6 @@ #include "eventcontent.h" #include "converters.h" -#include "util.h" #include "logging.h" #include diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index 72dbf2e3..7f06d99f 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -20,7 +20,6 @@ Example of a Receipt Event: #include "receiptevent.h" -#include "converters.h" #include "logging.h" using namespace Quotient; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index b728e0bf..3502e3f7 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -3,7 +3,6 @@ #include "roomevent.h" -#include "converters.h" #include "logging.h" #include "redactionevent.h" diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 3141f6b5..b4770224 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -4,7 +4,6 @@ #include "roommemberevent.h" -#include "converters.h" #include "logging.h" #include -- cgit v1.2.3 From 08612cb253417fe70ef45a1ad08663a0745d748a Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 10 Dec 2021 19:26:23 +0100 Subject: No more default construction of events Default construction was only done to support stubbed state in Room and even that did not really use those, opting to construct an event from an empty QJsonObject instead. Now that Room doesn't have stubbed state, default constructors are even less needed. --- lib/events/encryptionevent.h | 20 ++++++++++++-------- lib/events/roomcreateevent.h | 1 - lib/events/roommemberevent.h | 10 +++------- lib/events/roompowerlevelsevent.h | 4 +++- lib/events/roomtombstoneevent.h | 1 - lib/events/simplestateevents.h | 1 - 6 files changed, 18 insertions(+), 19 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index dfb28b2f..56913393 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -12,7 +12,11 @@ class QUOTIENT_API EncryptionEventContent : public EventContent::Base { public: enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; - explicit EncryptionEventContent(EncryptionType et = Undefined); + explicit(false) EncryptionEventContent(EncryptionType et); + [[deprecated("This constructor will require explicit EncryptionType soon")]] // + explicit EncryptionEventContent() + : EncryptionEventContent(Undefined) + {} explicit EncryptionEventContent(const QJsonObject& json); EncryptionType encryption; @@ -34,15 +38,15 @@ public: using EncryptionType = EncryptionEventContent::EncryptionType; Q_ENUM(EncryptionType) - explicit EncryptionEvent(const QJsonObject& obj = {}) // TODO: apropriate - // default value + explicit EncryptionEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} - EncryptionEvent(EncryptionEvent&&) = delete; - template - EncryptionEvent(ArgTs&&... contentArgs) - : StateEvent(typeId(), matrixTypeId(), QString(), - std::forward(contentArgs)...) + [[deprecated("This constructor will require an explicit parameter soon")]] // +// explicit EncryptionEvent() +// : EncryptionEvent(QJsonObject()) +// {} + explicit EncryptionEvent(EncryptionEventContent&& content) + : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) {} EncryptionType encryption() const { return content().encryption; } diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 016855b9..989030ac 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -11,7 +11,6 @@ class QUOTIENT_API RoomCreateEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.create", RoomCreateEvent) - explicit RoomCreateEvent() : StateEventBase(typeId(), matrixTypeId()) {} explicit RoomCreateEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) {} diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 5e446dbe..3296ae22 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -15,9 +15,7 @@ public: using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; - explicit MemberEventContent(Membership ms = Membership::Join) - : membership(ms) - {} + explicit(false) MemberEventContent(Membership ms) : membership(ms) {} explicit MemberEventContent(const QJsonObject& json); Membership membership; @@ -43,10 +41,8 @@ public: explicit RoomMemberEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} - template - RoomMemberEvent(const QString& userId, ArgTs&&... contentArgs) - : StateEvent(typeId(), matrixTypeId(), userId, - std::forward(contentArgs)...) + RoomMemberEvent(const QString& userId, MemberEventContent&& content) + : StateEvent(typeId(), matrixTypeId(), userId, std::move(content)) {} //! \brief A special constructor to create unknown RoomMemberEvents diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index 80e27048..415cc814 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -36,10 +36,12 @@ protected: class QUOTIENT_API RoomPowerLevelsEvent : public StateEvent { - Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.power_levels", RoomPowerLevelsEvent) + explicit RoomPowerLevelsEvent(PowerLevelsEventContent&& content) + : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) + {} explicit RoomPowerLevelsEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index e336c448..15d26923 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -10,7 +10,6 @@ class QUOTIENT_API RoomTombstoneEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.tombstone", RoomTombstoneEvent) - explicit RoomTombstoneEvent() : StateEventBase(typeId(), matrixTypeId()) {} explicit RoomTombstoneEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) {} diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index e6c05880..9610574b 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -35,7 +35,6 @@ namespace EventContent { public: \ using value_type = content_type::value_type; \ DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - explicit _Name() : _Name(value_type()) {} \ template \ explicit _Name(T&& value) \ : StateEvent(typeId(), matrixTypeId(), QString(), \ -- cgit v1.2.3 From 1747575321cda4fc11f90c2ffb2148a69d0d9946 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 28 Jan 2022 17:08:10 +0100 Subject: QUO_IMPLICIT Because Apple Clang choked on `explicit(false)`. --- lib/events/encryptionevent.h | 3 ++- lib/events/roommemberevent.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 56913393..124ced33 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -6,13 +6,14 @@ #include "eventcontent.h" #include "stateevent.h" +#include "quotient_common.h" namespace Quotient { class QUOTIENT_API EncryptionEventContent : public EventContent::Base { public: enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; - explicit(false) EncryptionEventContent(EncryptionType et); + QUO_IMPLICIT EncryptionEventContent(EncryptionType et); [[deprecated("This constructor will require explicit EncryptionType soon")]] // explicit EncryptionEventContent() : EncryptionEventContent(Undefined) diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 3296ae22..ceb7826b 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -15,7 +15,7 @@ public: using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; - explicit(false) MemberEventContent(Membership ms) : membership(ms) {} + QUO_IMPLICIT MemberEventContent(Membership ms) : membership(ms) {} explicit MemberEventContent(const QJsonObject& json); Membership membership; -- cgit v1.2.3 From 7b5edb737522b03d4f697e0e09f1771ad5edef89 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 7 Feb 2022 21:48:07 +0100 Subject: Remove encryptionmanager and various fixes --- lib/events/encryptedfile.cpp | 27 +++++++++++++++++++++++++++ lib/events/encryptedfile.h | 6 ++++++ 2 files changed, 33 insertions(+) create mode 100644 lib/events/encryptedfile.cpp (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp new file mode 100644 index 00000000..5ec344bb --- /dev/null +++ b/lib/events/encryptedfile.cpp @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "encryptedfile.h" + +using namespace Quotient; + +QByteArray EncryptedFile::decryptFile(const QByteArray &ciphertext) const +{ + QString _key = key.k; + _key = QByteArray::fromBase64(_key.replace(QLatin1Char('_'), QLatin1Char('/')).replace(QLatin1Char('-'), QLatin1Char('+')).toLatin1()); + const auto sha256 = QByteArray::fromBase64(hashes["sha256"].toLatin1()); + if(sha256 != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { + qCWarning(E2EE) << "Hash verification failed for file"; + return QByteArray(); + } + QByteArray plaintext(ciphertext.size(), 0); + EVP_CIPHER_CTX *ctx; + int length; + ctx = EVP_CIPHER_CTX_new(); + EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const unsigned char *)_key.data(), (const unsigned char *)iv.toLatin1().data()); + EVP_DecryptUpdate(ctx, (unsigned char *)plaintext.data(), &length, (const unsigned char *)ciphertext.data(), ciphertext.size()); + EVP_DecryptFinal_ex(ctx, (unsigned char *)plaintext.data() + length, &length); + EVP_CIPHER_CTX_free(ctx); + return plaintext; +} diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 24ac9de1..f271d345 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -5,6 +5,10 @@ #pragma once #include "converters.h" +#include "logging.h" + +#include +#include namespace Quotient { /** @@ -44,6 +48,8 @@ public: QString iv; QHash hashes; QString v; + + QByteArray decryptFile(const QByteArray &ciphertext) const; }; template <> -- cgit v1.2.3 From 840aead6e77a7ab8605bd2f70820ddd2219bdad5 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 7 Feb 2022 22:04:38 +0100 Subject: Refactor KeyVerificationEvents --- lib/events/keyverificationevent.cpp | 83 ++++++++++++------------------------- 1 file changed, 27 insertions(+), 56 deletions(-) (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.cpp b/lib/events/keyverificationevent.cpp index 938b3bde..4803955d 100644 --- a/lib/events/keyverificationevent.cpp +++ b/lib/events/keyverificationevent.cpp @@ -11,26 +11,22 @@ KeyVerificationRequestEvent::KeyVerificationRequestEvent(const QJsonObject &obj) QString KeyVerificationRequestEvent::fromDevice() const { - return contentJson()["from_device"_ls].toString(); + return contentPart("from_device"_ls); } QString KeyVerificationRequestEvent::transactionId() const { - return contentJson()["transaction_id"_ls].toString(); + return contentPart("transaction_id"_ls); } QStringList KeyVerificationRequestEvent::methods() const { - QStringList methods; - for (const auto &method : contentJson()["methods"].toArray()) { - methods.append(method.toString()); - } - return methods; + return contentPart("methods"_ls); } uint64_t KeyVerificationRequestEvent::timestamp() const { - return contentJson()["timestamp"_ls].toDouble(); + return contentPart("timestamp"_ls); } KeyVerificationStartEvent::KeyVerificationStartEvent(const QJsonObject &obj) @@ -39,62 +35,46 @@ KeyVerificationStartEvent::KeyVerificationStartEvent(const QJsonObject &obj) QString KeyVerificationStartEvent::fromDevice() const { - return contentJson()["from_device"_ls].toString(); + return contentPart("from_device"_ls); } QString KeyVerificationStartEvent::transactionId() const { - return contentJson()["transaction_id"_ls].toString(); + return contentPart("transaction_id"_ls); } QString KeyVerificationStartEvent::method() const { - return contentJson()["method"_ls].toString(); + return contentPart("method"_ls); } Omittable KeyVerificationStartEvent::nextMethod() const { - auto next = contentJson()["method"_ls]; - if (next.isUndefined()) { - return std::nullopt; - } - return next.toString(); + return contentPart>("method_ls"); } QStringList KeyVerificationStartEvent::keyAgreementProtocols() const { Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - QStringList protocols; - for (const auto &proto : contentJson()["key_agreement_protocols"_ls].toArray()) { - protocols.append(proto.toString()); - } - return protocols; + return contentPart("key_agreement_protocols"_ls); } QStringList KeyVerificationStartEvent::hashes() const { Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - QStringList hashes; - for (const auto &hashItem : contentJson()["hashes"_ls].toArray()) { - hashes.append(hashItem.toString()); - } - return hashes; + return contentPart("hashes"_ls); + } QStringList KeyVerificationStartEvent::messageAuthenticationCodes() const { Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - - QStringList codes; - for (const auto &code : contentJson()["message_authentication_codes"_ls].toArray()) { - codes.append(code.toString()); - } - return codes; + return contentPart("message_authentication_codes"_ls); } QString KeyVerificationStartEvent::shortAuthenticationString() const { - return contentJson()["short_authentification_string"_ls].toString(); + return contentPart("short_authentification_string"_ls); } KeyVerificationAcceptEvent::KeyVerificationAcceptEvent(const QJsonObject &obj) @@ -103,36 +83,32 @@ KeyVerificationAcceptEvent::KeyVerificationAcceptEvent(const QJsonObject &obj) QString KeyVerificationAcceptEvent::transactionId() const { - return contentJson()["transaction_id"_ls].toString(); + return contentPart("transaction_id"_ls); } QString KeyVerificationAcceptEvent::method() const { - return contentJson()["method"_ls].toString(); + return contentPart("method"_ls); } QString KeyVerificationAcceptEvent::keyAgreementProtocol() const { - return contentJson()["key_agreement_protocol"_ls].toString(); + return contentPart("key_agreement_protocol"_ls); } QString KeyVerificationAcceptEvent::hashData() const { - return contentJson()["hash"_ls].toString(); + return contentPart("hash"_ls); } QStringList KeyVerificationAcceptEvent::shortAuthenticationString() const { - QStringList strings; - for (const auto &authenticationString : contentJson()["short_authentification_string"].toArray()) { - strings.append(authenticationString.toString()); - } - return strings; + return contentPart("short_authentification_string"_ls); } QString KeyVerificationAcceptEvent::commitement() const { - return contentJson()["commitement"].toString(); + return contentPart("commitment"_ls); } KeyVerificationCancelEvent::KeyVerificationCancelEvent(const QJsonObject &obj) @@ -141,17 +117,17 @@ KeyVerificationCancelEvent::KeyVerificationCancelEvent(const QJsonObject &obj) QString KeyVerificationCancelEvent::transactionId() const { - return contentJson()["transaction_id"_ls].toString(); + return contentPart("transaction_id"_ls); } QString KeyVerificationCancelEvent::reason() const { - return contentJson()["reason"_ls].toString(); + return contentPart("reason"_ls); } QString KeyVerificationCancelEvent::code() const { - return contentJson()["code"_ls].toString(); + return contentPart("code"_ls); } KeyVerificationKeyEvent::KeyVerificationKeyEvent(const QJsonObject &obj) @@ -160,12 +136,12 @@ KeyVerificationKeyEvent::KeyVerificationKeyEvent(const QJsonObject &obj) QString KeyVerificationKeyEvent::transactionId() const { - return contentJson()["transaction_id"_ls].toString(); + return contentPart("transaction_id"_ls); } QString KeyVerificationKeyEvent::key() const { - return contentJson()["key"_ls].toString(); + return contentPart("key"_ls); } KeyVerificationMacEvent::KeyVerificationMacEvent(const QJsonObject &obj) @@ -174,20 +150,15 @@ KeyVerificationMacEvent::KeyVerificationMacEvent(const QJsonObject &obj) QString KeyVerificationMacEvent::transactionId() const { - return contentJson()["transaction_id"].toString(); + return contentPart("transaction_id"_ls); } QString KeyVerificationMacEvent::keys() const { - return contentJson()["keys"].toString(); + return contentPart("keys"_ls); } QHash KeyVerificationMacEvent::mac() const { - QHash macs; - const auto macObj = contentJson()["mac"_ls].toObject(); - for (auto mac = macObj.constBegin(); mac != macObj.constEnd(); mac++) { - macs.insert(mac.key(), mac.value().toString()); - } - return macs; + return contentPart>("mac"_ls); } -- cgit v1.2.3 From 94f34099b8a4c8a40cc99496ceaf9ad5b285c08f Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Wed, 9 Feb 2022 22:18:42 +0100 Subject: Move includes to .cpp file --- lib/events/encryptedfile.cpp | 4 ++++ lib/events/encryptedfile.h | 4 ---- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 5ec344bb..74119127 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -3,6 +3,10 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedfile.h" +#include "logging.h" + +#include +#include using namespace Quotient; diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index f271d345..6199be8e 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -5,10 +5,6 @@ #pragma once #include "converters.h" -#include "logging.h" - -#include -#include namespace Quotient { /** -- cgit v1.2.3 From 73623b69477352f901aa0d02a667bd2438a91491 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 11 Feb 2022 14:22:57 +0100 Subject: EventRelation: defer to non-deprecated symbols --- lib/events/roommessageevent.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 44ef05fb..03a51328 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -101,8 +101,8 @@ namespace EventContent { struct [[deprecated("Use Quotient::EventRelation instead")]] RelatesTo : EventRelation { - static constexpr auto ReplyTypeId() { return Reply(); } - static constexpr auto ReplacementTypeId() { return Replacement(); } + static constexpr auto ReplyTypeId() { return ReplyType; } + static constexpr auto ReplacementTypeId() { return ReplacementType; } }; [[deprecated("Use EventRelation::replyTo() instead")]] inline auto replyTo(QString eventId) -- cgit v1.2.3 From 2cf44607cf0f057e147c2c4fe6dded6c13c58a8a Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 14 Feb 2022 14:45:38 +0100 Subject: Don't #include "logging.h" from headers Logging categories used by Quotient are not supposed to be exposed externally, which basically forbids usage of logging in header files. A more flexible solution would involve moving logging.h to private headers but Quotient doesn't have that thing yet. --- lib/events/event.h | 1 - 1 file changed, 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 113fa3fa..b6f36306 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -4,7 +4,6 @@ #pragma once #include "converters.h" -#include "logging.h" #include "function_traits.h" namespace Quotient { -- cgit v1.2.3 From 7221c10118a8895ec39ba6a78768574a4b00dfed Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 14 Feb 2022 15:41:36 +0100 Subject: Revert "Don't #include "logging.h" from headers" This reverts commit 2cf44607cf0f057e147c2c4fe6dded6c13c58a8a (that was stupid, honestly). --- lib/events/event.h | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index b6f36306..113fa3fa 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -4,6 +4,7 @@ #pragma once #include "converters.h" +#include "logging.h" #include "function_traits.h" namespace Quotient { -- cgit v1.2.3 From 34cd6a6c6dfe2981001341f39e4e1e9aaa9c8898 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 14 Feb 2022 21:46:27 +0100 Subject: Don't set lifetime as version in call invites --- lib/events/callinviteevent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 5ea54662..11d50768 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -36,7 +36,7 @@ CallInviteEvent::CallInviteEvent(const QJsonObject& obj) CallInviteEvent::CallInviteEvent(const QString& callId, const int lifetime, const QString& sdp) : CallEventBase( - typeId(), matrixTypeId(), callId, lifetime, + typeId(), matrixTypeId(), callId, 0, { { QStringLiteral("lifetime"), lifetime }, { QStringLiteral("offer"), QJsonObject { { QStringLiteral("type"), QStringLiteral("offer") }, -- cgit v1.2.3 From 52a787eefb3fb3d147648d08fc439a4b8a966fd3 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 16 Feb 2022 17:57:30 +0100 Subject: Add a few missing QUOTIENT_API stanzas Also, removed Q_GADGET macros from key verification events as those don't seem to do anything (no Q_ENUM/Q_FLAG things, namely). --- lib/events/encryptedfile.h | 2 +- lib/events/keyverificationevent.h | 16 +++++----------- 2 files changed, 6 insertions(+), 12 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 6199be8e..43bafc49 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -29,7 +29,7 @@ public: bool ext; }; -struct EncryptedFile +struct QUOTIENT_API EncryptedFile { Q_GADGET Q_PROPERTY(QUrl url MEMBER url CONSTANT) diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 13e7dcdd..497e56a2 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -7,8 +7,7 @@ namespace Quotient { /// Requests a key verification with another user's devices. /// Typically sent as a to-device event. -class KeyVerificationRequestEvent : public Event { - Q_GADGET +class QUOTIENT_API KeyVerificationRequestEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.request", KeyVerificationRequestEvent) @@ -33,8 +32,7 @@ public: REGISTER_EVENT_TYPE(KeyVerificationRequestEvent) /// Begins a key verification process. -class KeyVerificationStartEvent : public Event { - Q_GADGET +class QUOTIENT_API KeyVerificationStartEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.start", KeyVerificationStartEvent) @@ -76,8 +74,7 @@ REGISTER_EVENT_TYPE(KeyVerificationStartEvent) /// Accepts a previously sent m.key.verification.start message. /// Typically sent as a to-device event. -class KeyVerificationAcceptEvent : public Event { - Q_GADGET +class QUOTIENT_API KeyVerificationAcceptEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.accept", KeyVerificationAcceptEvent) @@ -111,8 +108,7 @@ public: }; REGISTER_EVENT_TYPE(KeyVerificationAcceptEvent) -class KeyVerificationCancelEvent : public Event { - Q_GADGET +class QUOTIENT_API KeyVerificationCancelEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.cancel", KeyVerificationCancelEvent) @@ -133,7 +129,6 @@ REGISTER_EVENT_TYPE(KeyVerificationCancelEvent) /// Sends the ephemeral public key for a device to the partner device. /// Typically sent as a to-device event. class KeyVerificationKeyEvent : public Event { - Q_GADGET public: DEFINE_EVENT_TYPEID("m.key.verification.key", KeyVerificationKeyEvent) @@ -148,8 +143,7 @@ public: REGISTER_EVENT_TYPE(KeyVerificationKeyEvent) /// Sends the MAC of a device's key to the partner device. -class KeyVerificationMacEvent : public Event { - Q_GADGET +class QUOTIENT_API KeyVerificationMacEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.mac", KeyVerificationMacEvent) -- cgit v1.2.3 From 53dfa70601b2d27a6be12d52e86af123d0b26b79 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 15 Feb 2022 20:51:32 +0100 Subject: Cleanup A note on switching to QLatin1String for JSON key constants - this is more concise and barely affects (if at all) runtime performance (padding each QChar with zeros is trivial for assignment; and comparison can be done directly with the same performance as for two QStrings). --- lib/events/encryptedevent.cpp | 13 +++++++++++++ lib/events/encryptedevent.h | 14 ++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 1b5e4441..ba4dd154 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -33,6 +33,19 @@ EncryptedEvent::EncryptedEvent(const QJsonObject& obj) qCDebug(E2EE) << "Encrypted event from" << senderId(); } +QString EncryptedEvent::algorithm() const +{ + auto algo = contentPart(AlgorithmKeyL); + static constexpr auto SupportedAlgorithms = + make_array(OlmV1Curve25519AesSha2AlgoKey, MegolmV1AesSha2AlgoKey); + if (std::find(SupportedAlgorithms.cbegin(), SupportedAlgorithms.cend(), + algo) == SupportedAlgorithms.cend()) { + qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo + << "is not supported"; + } + return algo; +} + RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const { auto eventObject = QJsonDocument::fromJson(decrypted.toUtf8()).object(); diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index c838bbd8..72efffd4 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -39,22 +39,16 @@ public: const QString& deviceId, const QString& sessionId); explicit EncryptedEvent(const QJsonObject& obj); - QString algorithm() const - { - QString algo = contentPart(AlgorithmKeyL); - if (!SupportedAlgorithms.contains(algo)) { - qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo - << "is not supported"; - } - return algo; - } + QString algorithm() const; QByteArray ciphertext() const { return contentPart(CiphertextKeyL).toLatin1(); } QJsonObject ciphertext(const QString& identityKey) const { - return contentPart(CiphertextKeyL).value(identityKey).toObject(); + return contentPart(CiphertextKeyL) + .value(identityKey) + .toObject(); } QString senderKey() const { return contentPart(SenderKeyKeyL); } -- cgit v1.2.3 From 445e34f26450cf8262a65b74e1294579d9cd56be Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sun, 13 Feb 2022 22:11:52 +0100 Subject: Fix file decryption --- lib/events/encryptedfile.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 74119127..dbb72af8 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -13,7 +13,7 @@ using namespace Quotient; QByteArray EncryptedFile::decryptFile(const QByteArray &ciphertext) const { QString _key = key.k; - _key = QByteArray::fromBase64(_key.replace(QLatin1Char('_'), QLatin1Char('/')).replace(QLatin1Char('-'), QLatin1Char('+')).toLatin1()); + auto keyBytes = QByteArray::fromBase64(_key.replace(QLatin1Char('_'), QLatin1Char('/')).replace(QLatin1Char('-'), QLatin1Char('+')).toLatin1()); const auto sha256 = QByteArray::fromBase64(hashes["sha256"].toLatin1()); if(sha256 != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { qCWarning(E2EE) << "Hash verification failed for file"; @@ -23,7 +23,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray &ciphertext) const EVP_CIPHER_CTX *ctx; int length; ctx = EVP_CIPHER_CTX_new(); - EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const unsigned char *)_key.data(), (const unsigned char *)iv.toLatin1().data()); + EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const unsigned char *)keyBytes.data(), (const unsigned char *)QByteArray::fromBase64(iv.toLatin1()).data()); EVP_DecryptUpdate(ctx, (unsigned char *)plaintext.data(), &length, (const unsigned char *)ciphertext.data(), ciphertext.size()); EVP_DecryptFinal_ex(ctx, (unsigned char *)plaintext.data() + length, &length); EVP_CIPHER_CTX_free(ctx); -- cgit v1.2.3 From 0a43c023b94e12b3130572f2dd0d6ac8bb4ed110 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 14 Feb 2022 15:25:24 +0100 Subject: isSupportedAlgorithm() That's a better primitive than just exposing SupportedAlgorithms list. --- lib/events/encryptedevent.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index ba4dd154..9d07a35f 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -35,14 +35,11 @@ EncryptedEvent::EncryptedEvent(const QJsonObject& obj) QString EncryptedEvent::algorithm() const { - auto algo = contentPart(AlgorithmKeyL); - static constexpr auto SupportedAlgorithms = - make_array(OlmV1Curve25519AesSha2AlgoKey, MegolmV1AesSha2AlgoKey); - if (std::find(SupportedAlgorithms.cbegin(), SupportedAlgorithms.cend(), - algo) == SupportedAlgorithms.cend()) { + const auto algo = contentPart(AlgorithmKeyL); + if (!isSupportedAlgorithm(algo)) qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo << "is not supported"; - } + return algo; } -- cgit v1.2.3 From b5e1fc7d8fcf9336db0dfb351403aa06dcb226a0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 16 Feb 2022 08:40:56 +0100 Subject: More cleanup, especially in EncryptedFile For EncryptedFile: - JSON converter bodies moved away to .cpp; - instead of C-style casts, reinterpret_cast is used to convert from (const) char* to (const) unsigned char*; - the size for the target plain text takes into account the case where the cipher block size can be larger than 1 (after reading https://www.openssl.org/docs/man1.1.1/man3/EVP_DecryptUpdate.html). - file decryption is wrapped in #ifdef Quotient_E2EE_ENABLED, to avoid OpenSSL linking errors when compiling without E2EE. --- lib/events/encryptedfile.cpp | 89 +++++++++++++++++++++++++++++++++++++------- lib/events/encryptedfile.h | 40 +++----------------- 2 files changed, 81 insertions(+), 48 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index dbb72af8..d4a517bd 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -5,27 +5,88 @@ #include "encryptedfile.h" #include "logging.h" +#ifdef Quotient_E2EE_ENABLED #include #include +#endif using namespace Quotient; -QByteArray EncryptedFile::decryptFile(const QByteArray &ciphertext) const +QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const { - QString _key = key.k; - auto keyBytes = QByteArray::fromBase64(_key.replace(QLatin1Char('_'), QLatin1Char('/')).replace(QLatin1Char('-'), QLatin1Char('+')).toLatin1()); +#ifdef Quotient_E2EE_ENABLED + auto _key = key.k; + const auto keyBytes = QByteArray::fromBase64( + _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); const auto sha256 = QByteArray::fromBase64(hashes["sha256"].toLatin1()); - if(sha256 != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { + if (sha256 + != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { qCWarning(E2EE) << "Hash verification failed for file"; - return QByteArray(); + return {}; } - QByteArray plaintext(ciphertext.size(), 0); - EVP_CIPHER_CTX *ctx; - int length; - ctx = EVP_CIPHER_CTX_new(); - EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, (const unsigned char *)keyBytes.data(), (const unsigned char *)QByteArray::fromBase64(iv.toLatin1()).data()); - EVP_DecryptUpdate(ctx, (unsigned char *)plaintext.data(), &length, (const unsigned char *)ciphertext.data(), ciphertext.size()); - EVP_DecryptFinal_ex(ctx, (unsigned char *)plaintext.data() + length, &length); - EVP_CIPHER_CTX_free(ctx); - return plaintext; + { + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + QByteArray plaintext(ciphertext.size() + EVP_CIPHER_CTX_block_size(ctx) + - 1, + '\0'); + EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, + reinterpret_cast( + keyBytes.data()), + reinterpret_cast( + QByteArray::fromBase64(iv.toLatin1()).data())); + EVP_DecryptUpdate( + ctx, reinterpret_cast(plaintext.data()), &length, + reinterpret_cast(ciphertext.data()), + ciphertext.size()); + EVP_DecryptFinal_ex(ctx, + reinterpret_cast(plaintext.data()) + + length, + &length); + EVP_CIPHER_CTX_free(ctx); + return plaintext; + } +#else + qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " + "cannot decrypt the file"; + return ciphertext; +#endif +} + +void JsonObjectConverter::dumpTo(QJsonObject& jo, + const EncryptedFile& pod) +{ + addParam<>(jo, QStringLiteral("url"), pod.url); + addParam<>(jo, QStringLiteral("key"), pod.key); + addParam<>(jo, QStringLiteral("iv"), pod.iv); + addParam<>(jo, QStringLiteral("hashes"), pod.hashes); + addParam<>(jo, QStringLiteral("v"), pod.v); +} + +void JsonObjectConverter::fillFrom(const QJsonObject& jo, + EncryptedFile& pod) +{ + fromJson(jo.value("url"_ls), pod.url); + fromJson(jo.value("key"_ls), pod.key); + fromJson(jo.value("iv"_ls), pod.iv); + fromJson(jo.value("hashes"_ls), pod.hashes); + fromJson(jo.value("v"_ls), pod.v); +} + +void JsonObjectConverter::dumpTo(QJsonObject &jo, const JWK &pod) +{ + addParam<>(jo, QStringLiteral("kty"), pod.kty); + addParam<>(jo, QStringLiteral("key_ops"), pod.keyOps); + addParam<>(jo, QStringLiteral("alg"), pod.alg); + addParam<>(jo, QStringLiteral("k"), pod.k); + addParam<>(jo, QStringLiteral("ext"), pod.ext); +} + +void JsonObjectConverter::fillFrom(const QJsonObject &jo, JWK &pod) +{ + fromJson(jo.value("kty"_ls), pod.kty); + fromJson(jo.value("key_ops"_ls), pod.keyOps); + fromJson(jo.value("alg"_ls), pod.alg); + fromJson(jo.value("k"_ls), pod.k); + fromJson(jo.value("ext"_ls), pod.ext); } diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 43bafc49..0558563f 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -49,42 +49,14 @@ public: }; template <> -struct JsonObjectConverter { - static void dumpTo(QJsonObject& jo, const EncryptedFile& pod) - { - addParam<>(jo, QStringLiteral("url"), pod.url); - addParam<>(jo, QStringLiteral("key"), pod.key); - addParam<>(jo, QStringLiteral("iv"), pod.iv); - addParam<>(jo, QStringLiteral("hashes"), pod.hashes); - addParam<>(jo, QStringLiteral("v"), pod.v); - } - static void fillFrom(const QJsonObject& jo, EncryptedFile& pod) - { - fromJson(jo.value("url"_ls), pod.url); - fromJson(jo.value("key"_ls), pod.key); - fromJson(jo.value("iv"_ls), pod.iv); - fromJson(jo.value("hashes"_ls), pod.hashes); - fromJson(jo.value("v"_ls), pod.v); - } +struct QUOTIENT_API JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const EncryptedFile& pod); + static void fillFrom(const QJsonObject& jo, EncryptedFile& pod); }; template <> -struct JsonObjectConverter { - static void dumpTo(QJsonObject& jo, const JWK& pod) - { - addParam<>(jo, QStringLiteral("kty"), pod.kty); - addParam<>(jo, QStringLiteral("key_ops"), pod.keyOps); - addParam<>(jo, QStringLiteral("alg"), pod.alg); - addParam<>(jo, QStringLiteral("k"), pod.k); - addParam<>(jo, QStringLiteral("ext"), pod.ext); - } - static void fillFrom(const QJsonObject& jo, JWK& pod) - { - fromJson(jo.value("kty"_ls), pod.kty); - fromJson(jo.value("key_ops"_ls), pod.keyOps); - fromJson(jo.value("alg"_ls), pod.alg); - fromJson(jo.value("k"_ls), pod.k); - fromJson(jo.value("ext"_ls), pod.ext); - } +struct QUOTIENT_API JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const JWK& pod); + static void fillFrom(const QJsonObject& jo, JWK& pod); }; } // namespace Quotient -- cgit v1.2.3 From 4f137493f026afba2299ae5b65ef6eb17939aece Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sun, 27 Feb 2022 19:15:16 +0100 Subject: Add constructor for creating roomkeyevents --- lib/events/roomkeyevent.cpp | 13 +++++++++++++ lib/events/roomkeyevent.h | 1 + 2 files changed, 14 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index 332be3f7..68962950 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -10,3 +10,16 @@ RoomKeyEvent::RoomKeyEvent(const QJsonObject &obj) : Event(typeId(), obj) if (roomId().isEmpty()) qCWarning(E2EE) << "Room key event has empty room id"; } + +RoomKeyEvent::RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString& sessionId, const QString& sessionKey, const QString& senderId) + : Event(typeId(), { + {"content", QJsonObject{ + {"algorithm", algorithm}, + {"room_id", roomId}, + {"session_id", sessionId}, + {"session_key", sessionKey}, + }}, + {"sender", senderId}, + {"type", "m.room_key"}, + }) +{} diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index c4df7936..cb3fe7e7 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -12,6 +12,7 @@ public: DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) explicit RoomKeyEvent(const QJsonObject& obj); + explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString &sessionId, const QString& sessionKey, const QString& senderId); QString algorithm() const { return contentPart("algorithm"_ls); } QString roomId() const { return contentPart(RoomIdKeyL); } -- cgit v1.2.3 From 2071f5020975bc3f5ecbb9e2444acaad8f13060a Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 8 Mar 2022 00:06:36 +0100 Subject: Implement sending encrypted files --- lib/events/encryptedfile.cpp | 26 ++++++++++++++++++++++++-- lib/events/encryptedfile.h | 1 + 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index d4a517bd..e90be428 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -8,6 +8,7 @@ #ifdef Quotient_E2EE_ENABLED #include #include +#include "e2ee/qolmutils.h" #endif using namespace Quotient; @@ -27,7 +28,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const { int length; auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray plaintext(ciphertext.size() + EVP_CIPHER_CTX_block_size(ctx) + QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, @@ -44,7 +45,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const + length, &length); EVP_CIPHER_CTX_free(ctx); - return plaintext; + return plaintext.left(ciphertext.size()); } #else qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " @@ -53,6 +54,27 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const #endif } +std::pair EncryptedFile::encryptFile(const QByteArray &plainText) +{ + QByteArray k = getRandom(32); + auto kBase64 = k.toBase64(); + QByteArray iv = getRandom(16); + JWK key = {"oct"_ls, {"encrypt"_ls, "decrypt"_ls}, "A256CTR"_ls, QString(k.toBase64()).replace(u'/', u'_').replace(u'+', u'-').left(kBase64.indexOf('=')), true}; + + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + QByteArray cipherText(plainText.size(), plainText.size() + EVP_MAX_BLOCK_LENGTH - 1); + EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); + EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); + EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); + EVP_CIPHER_CTX_free(ctx); + + auto hash = QCryptographicHash::hash(cipherText, QCryptographicHash::Sha256).toBase64(); + auto ivBase64 = iv.toBase64(); + EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; + return {file, cipherText}; +} + void JsonObjectConverter::dumpTo(QJsonObject& jo, const EncryptedFile& pod) { diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 0558563f..76aff837 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -46,6 +46,7 @@ public: QString v; QByteArray decryptFile(const QByteArray &ciphertext) const; + static std::pair encryptFile(const QByteArray &plainText); }; template <> -- cgit v1.2.3 From 7ba17e2b9b6d76aeea250f37c833ad7eed2f61da Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 8 Mar 2022 21:44:10 +0100 Subject: Properly create encrypted edits --- lib/events/encryptedevent.cpp | 7 +++++++ lib/events/encryptedevent.h | 2 ++ 2 files changed, 9 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 9d07a35f..3af3d6ff 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -61,3 +61,10 @@ RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const } return loadEvent(eventObject); } + +void EncryptedEvent::setRelation(const QJsonObject& relation) +{ + auto content = editJson()["content"_ls].toObject(); + content["m.relates_to"] = relation; + editJson()["content"] = content; +} diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 72efffd4..ddd5e415 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -56,6 +56,8 @@ public: QString deviceId() const { return contentPart(DeviceIdKeyL); } QString sessionId() const { return contentPart(SessionIdKeyL); } RoomEventPtr createDecrypted(const QString &decrypted) const; + + void setRelation(const QJsonObject& relation); }; REGISTER_EVENT_TYPE(EncryptedEvent) -- cgit v1.2.3 From 71eed90fdea8689d237da8de1bf385202b85cffd Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Thu, 10 Mar 2022 21:19:49 +0100 Subject: More work; Update olm pickle & timestamps in database; Remove TODOs --- lib/events/encryptedfile.cpp | 4 ++++ lib/events/roomevent.h | 8 ++++++++ 2 files changed, 12 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index e90be428..bb4e26c7 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -56,6 +56,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const std::pair EncryptedFile::encryptFile(const QByteArray &plainText) { +#ifdef Quotient_E2EE_ENABLED QByteArray k = getRandom(32); auto kBase64 = k.toBase64(); QByteArray iv = getRandom(16); @@ -73,6 +74,9 @@ std::pair EncryptedFile::encryptFile(const QByteArray auto ivBase64 = iv.toBase64(); EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; return {file, cipherText}; +#else + return {{}, {}}; +#endif } void JsonObjectConverter::dumpTo(QJsonObject& jo, diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index c4b0131a..a7d6c428 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -80,6 +80,14 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; +template <> +inline EventPtr doLoadEvent(const QJsonObject& json, const QString& matrixType) +{ + if (matrixType == "m.room.encrypted") + return RoomEvent::factory.loadEvent(json, matrixType); + return Event::factory.loadEvent(json, matrixType); +} + class QUOTIENT_API CallEventBase : public RoomEvent { public: CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, -- cgit v1.2.3 From 80251f1db42268be0e678543b0b054f925fbfe88 Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Thu, 10 Mar 2022 21:47:51 +0100 Subject: Update lib/events/encryptedfile.h --- lib/events/encryptedfile.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 76aff837..b2808395 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -46,7 +46,7 @@ public: QString v; QByteArray decryptFile(const QByteArray &ciphertext) const; - static std::pair encryptFile(const QByteArray &plainText); + static std::pair encryptFile(const QByteArray& plainText); }; template <> -- cgit v1.2.3 From fc3ad90a054e3c674127a0cdd385ddbb98cf2010 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Fri, 8 Apr 2022 23:23:30 +0200 Subject: Correctly load EncryptedEvents --- lib/events/roomevent.h | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index c4b0131a..a7d6c428 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -80,6 +80,14 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; +template <> +inline EventPtr doLoadEvent(const QJsonObject& json, const QString& matrixType) +{ + if (matrixType == "m.room.encrypted") + return RoomEvent::factory.loadEvent(json, matrixType); + return Event::factory.loadEvent(json, matrixType); +} + class QUOTIENT_API CallEventBase : public RoomEvent { public: CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, -- cgit v1.2.3 From 16d4f4e48304543a0ab59b235edba07f5f2c2204 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 18 Apr 2022 20:07:12 +0200 Subject: Implement key verification --- lib/events/encryptedevent.h | 2 ++ lib/events/keyverificationevent.cpp | 32 +++++++++++++++++++++++++++++++- lib/events/keyverificationevent.h | 36 ++++++++++++++++++++++++++++++++++-- lib/events/roomevent.h | 2 +- 4 files changed, 68 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index ddd5e415..bfacdec9 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -58,6 +58,8 @@ public: RoomEventPtr createDecrypted(const QString &decrypted) const; void setRelation(const QJsonObject& relation); + + bool isVerified(); }; REGISTER_EVENT_TYPE(EncryptedEvent) diff --git a/lib/events/keyverificationevent.cpp b/lib/events/keyverificationevent.cpp index 4803955d..e7f5b019 100644 --- a/lib/events/keyverificationevent.cpp +++ b/lib/events/keyverificationevent.cpp @@ -106,7 +106,7 @@ QStringList KeyVerificationAcceptEvent::shortAuthenticationString() const return contentPart("short_authentification_string"_ls); } -QString KeyVerificationAcceptEvent::commitement() const +QString KeyVerificationAcceptEvent::commitment() const { return contentPart("commitment"_ls); } @@ -162,3 +162,33 @@ QHash KeyVerificationMacEvent::mac() const { return contentPart>("mac"_ls); } + +KeyVerificationDoneEvent::KeyVerificationDoneEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{ +} + +QString KeyVerificationDoneEvent::transactionId() const +{ + return contentPart("transaction_id"_ls); +} + + +KeyVerificationReadyEvent::KeyVerificationReadyEvent(const QJsonObject &obj) + : Event(typeId(), obj) +{} + +QString KeyVerificationReadyEvent::fromDevice() const +{ + return contentPart("from_device"_ls); +} + +QString KeyVerificationReadyEvent::transactionId() const +{ + return contentPart("transaction_id"_ls); +} + +QStringList KeyVerificationReadyEvent::methods() const +{ + return contentPart("methods"_ls); +} diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 497e56a2..a9f63968 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: 2021 Carl Schwan // SPDX-License-Identifier: LGPL-2.1-or-later +#pragma once + #include "event.h" namespace Quotient { @@ -31,6 +33,24 @@ public: }; REGISTER_EVENT_TYPE(KeyVerificationRequestEvent) +class QUOTIENT_API KeyVerificationReadyEvent : public Event { +public: + DEFINE_EVENT_TYPEID("m.key.verification.ready", KeyVerificationReadyEvent) + + explicit KeyVerificationReadyEvent(const QJsonObject& obj); + + /// The device ID which is accepting the request. + QString fromDevice() const; + + /// The transaction id of the verification request + QString transactionId() const; + + /// The verification methods supported by the sender. + QStringList methods() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationReadyEvent) + + /// Begins a key verification process. class QUOTIENT_API KeyVerificationStartEvent : public Event { public: @@ -104,7 +124,7 @@ public: /// The hash (encoded as unpadded base64) of the concatenation of the /// device's ephemeral public key (encoded as unpadded base64) and the /// canonical JSON representation of the m.key.verification.start message. - QString commitement() const; + QString commitment() const; }; REGISTER_EVENT_TYPE(KeyVerificationAcceptEvent) @@ -128,7 +148,7 @@ REGISTER_EVENT_TYPE(KeyVerificationCancelEvent) /// Sends the ephemeral public key for a device to the partner device. /// Typically sent as a to-device event. -class KeyVerificationKeyEvent : public Event { +class QUOTIENT_API KeyVerificationKeyEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.key", KeyVerificationKeyEvent) @@ -158,4 +178,16 @@ public: QHash mac() const; }; REGISTER_EVENT_TYPE(KeyVerificationMacEvent) + +class QUOTIENT_API KeyVerificationDoneEvent : public Event { +public: + DEFINE_EVENT_TYPEID("m.key.verification.done", KeyVerificationRequestEvent) + + explicit KeyVerificationDoneEvent(const QJsonObject& obj); + + /// The same transactionId as before + QString transactionId() const; +}; +REGISTER_EVENT_TYPE(KeyVerificationDoneEvent) + } // namespace Quotient diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index a7d6c428..5670f55f 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -62,7 +62,7 @@ public: #ifdef Quotient_E2EE_ENABLED void setOriginalEvent(event_ptr_tt&& originalEvent); - const RoomEvent* originalEvent() { return _originalEvent.get(); } + const RoomEvent* originalEvent() const { return _originalEvent.get(); } const QJsonObject encryptedJson() const; #endif -- cgit v1.2.3 From 272cb01b05529971ea38e09bf75d8d8f194a9dd8 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Thu, 5 May 2022 14:23:14 +0200 Subject: Fix license identifier --- lib/events/encryptedfile.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 0558563f..d0c4a030 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: 2021 Carl Schwan // -// SPDX-License-Identifier: LGPl-2.1-or-later +// SPDX-License-Identifier: LGPL-2.1-or-later #pragma once -- cgit v1.2.3 From b79f67919e05698a8c3daffbe0fe53fa1ce46e54 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 8 May 2022 17:43:08 +0200 Subject: toSnakeCase and EventContent::SingleKeyValue This is a rework of EventContent::SimpleContent previously defined in simplestateevents.h. Quite a few events (and not only state events) have just a single key-value pair in their content - this structure (which is really just a template wrapper around the value) and the accompanying JsonConverter<> specialisation encapsulate the concept to streamline definition of such events. This commit only has simplestateevents.h using it; further commits will use SingleKeyValue in other places. toSnakeCase is a facility function that converts camelCase used for C++ variables into snake_case used in JSON payloads. Combined with the preprocessor trick that makes a string literal from an identifier, this allows to reduce boilerplate code that repeats the same name for fields in C++ event classes and fields in JSON. SingleKeyValue uses it, and there are other cases for it coming. --- lib/events/simplestateevents.h | 72 ++++++++++++++++-------------------------- lib/events/single_key_value.h | 27 ++++++++++++++++ 2 files changed, 55 insertions(+), 44 deletions(-) create mode 100644 lib/events/single_key_value.h (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 9610574b..33221542 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -4,63 +4,47 @@ #pragma once #include "stateevent.h" +#include "single_key_value.h" namespace Quotient { -namespace EventContent { - template - struct SimpleContent { - using value_type = T; - - // The constructor is templated to enable perfect forwarding - template - SimpleContent(QString keyName, TT&& value) - : value(std::forward(value)), key(std::move(keyName)) - {} - SimpleContent(const QJsonObject& json, QString keyName) - : value(fromJson(json[keyName])), key(std::move(keyName)) - {} - QJsonObject toJson() const - { - return { { key, Quotient::toJson(value) } }; - } - - T value; - const QString key; - }; -} // namespace EventContent - -#define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ValueType, _ContentKey) \ - class QUOTIENT_API _Name \ - : public StateEvent> { \ - public: \ - using value_type = content_type::value_type; \ - DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - template \ - explicit _Name(T&& value) \ - : StateEvent(typeId(), matrixTypeId(), QString(), \ - QStringLiteral(#_ContentKey), std::forward(value)) \ - {} \ - explicit _Name(QJsonObject obj) \ - : StateEvent(typeId(), std::move(obj), \ - QStringLiteral(#_ContentKey)) \ - {} \ - auto _ContentKey() const { return content().value; } \ - }; \ - REGISTER_EVENT_TYPE(_Name) \ +#define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ValueType, _ContentKey) \ + constexpr auto _Name##Key = #_ContentKey##_ls; \ + class QUOTIENT_API _Name \ + : public StateEvent< \ + EventContent::SingleKeyValue<_ValueType, &_Name##Key>> { \ + public: \ + using value_type = _ValueType; \ + DEFINE_EVENT_TYPEID(_TypeId, _Name) \ + template \ + explicit _Name(T&& value) \ + : StateEvent(TypeId, matrixTypeId(), QString(), \ + std::forward(value)) \ + {} \ + explicit _Name(QJsonObject obj) \ + : StateEvent(TypeId, std::move(obj)) \ + {} \ + auto _ContentKey() const { return content().value; } \ + }; \ + REGISTER_EVENT_TYPE(_Name) \ // End of macro DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", QString, topic) -DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) +DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", + QStringList, pinnedEvents) +constexpr auto RoomAliasesEventKey = "aliases"_ls; class [[deprecated( "m.room.aliases events are deprecated by the Matrix spec; use" " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases")]] // -RoomAliasesEvent : public StateEvent> { +RoomAliasesEvent + : public StateEvent< + EventContent::SingleKeyValue> +{ public: DEFINE_EVENT_TYPEID("m.room.aliases", RoomAliasesEvent) explicit RoomAliasesEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj, QStringLiteral("aliases")) + : StateEvent(typeId(), obj) {} QString server() const { return stateKey(); } QStringList aliases() const { return content().value; } diff --git a/lib/events/single_key_value.h b/lib/events/single_key_value.h new file mode 100644 index 00000000..75ca8cd2 --- /dev/null +++ b/lib/events/single_key_value.h @@ -0,0 +1,27 @@ +#pragma once + +#include "converters.h" + +namespace Quotient { + +namespace EventContent { + template + struct SingleKeyValue { + T value; + }; +} // namespace EventContent + +template +struct JsonConverter> { + using content_type = EventContent::SingleKeyValue; + static content_type load(const QJsonValue& jv) + { + return { fromJson(jv.toObject().value(JsonKey)) }; + } + static QJsonObject dump(const content_type& c) + { + return { { JsonKey, toJson(c.value) } }; + } + static inline const auto JsonKey = toSnakeCase(*KeyStr); +}; +} // namespace Quotient -- cgit v1.2.3 From b094a75f704b59f1382b6eec1f3bf0ab51fb0a85 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 4 Jan 2022 10:30:17 +0100 Subject: StateEvent: use non-member JSON converters With the reworked JsonConverter code it is possible to work uniformly with structures that have a member toJson() and a constructor converting from QJsonObject, as well as with structures that rely on an external JsonConverter specialisation. --- lib/events/eventcontent.h | 1 - lib/events/stateevent.h | 11 ++++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index de9a792b..76f20f79 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -34,7 +34,6 @@ namespace EventContent { explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} virtual ~Base() = default; - // FIXME: make toJson() from converters.* work on base classes QJsonObject toJson() const; public: diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 88da68f8..19905431 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -72,7 +72,7 @@ struct Prev { explicit Prev(const QJsonObject& unsignedJson, ContentParamTs&&... contentParams) : senderId(unsignedJson.value("prev_sender"_ls).toString()) - , content(unsignedJson.value(PrevContentKeyL).toObject(), + , content(fromJson(unsignedJson.value(PrevContentKeyL)), std::forward(contentParams)...) {} @@ -89,7 +89,8 @@ public: explicit StateEvent(Type type, const QJsonObject& fullJson, ContentParamTs&&... contentParams) : StateEventBase(type, fullJson) - , _content(contentJson(), std::forward(contentParams)...) + , _content(fromJson(contentJson()), + std::forward(contentParams)...) { const auto& unsignedData = unsignedJson(); if (unsignedData.contains(PrevContentKeyL)) @@ -101,9 +102,9 @@ public: const QString& stateKey, ContentParamTs&&... contentParams) : StateEventBase(type, matrixType, stateKey) - , _content(std::forward(contentParams)...) + , _content{std::forward(contentParams)...} { - editJson().insert(ContentKey, _content.toJson()); + editJson().insert(ContentKey, toJson(_content)); } const ContentT& content() const { return _content; } @@ -111,7 +112,7 @@ public: void editContent(VisitorT&& visitor) { visitor(_content); - editJson()[ContentKeyL] = _content.toJson(); + editJson()[ContentKeyL] = toJson(_content); } const ContentT* prevContent() const { -- cgit v1.2.3 From 09ecce1744344f1bfbacd31c8f300440a4139be4 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 4 Jan 2022 12:46:34 +0100 Subject: Cleanup; comments reformatting --- lib/events/eventcontent.cpp | 24 +++--- lib/events/eventcontent.h | 198 +++++++++++++++++++++----------------------- 2 files changed, 109 insertions(+), 113 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 9d7edf20..479d5da0 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -29,12 +29,13 @@ FileInfo::FileInfo(const QFileInfo &fi) } FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, - Omittable file, QString originalFilename) + Omittable encryptedFile, + QString originalFilename) : mimeType(mimeType) , url(move(u)) , payloadSize(payloadSize) , originalName(move(originalFilename)) - , file(file) + , file(move(encryptedFile)) { if (!isValid()) qCWarning(MESSAGES) @@ -44,7 +45,7 @@ FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, } FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, - const Omittable &file, + Omittable encryptedFile, QString originalFilename) : originalInfoJson(infoJson) , mimeType( @@ -52,7 +53,7 @@ FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, , url(move(mxcUrl)) , payloadSize(fromJson(infoJson["size"_ls])) , originalName(move(originalFilename)) - , file(file) + , file(move(encryptedFile)) { if(url.isEmpty() && file.has_value()) { url = file->url; @@ -82,15 +83,16 @@ ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) {} ImageInfo::ImageInfo(const QUrl& mxcUrl, qint64 fileSize, const QMimeType& type, - QSize imageSize, const Omittable &file, const QString& originalFilename) - : FileInfo(mxcUrl, fileSize, type, file, originalFilename) + QSize imageSize, Omittable encryptedFile, + const QString& originalFilename) + : FileInfo(mxcUrl, fileSize, type, move(encryptedFile), originalFilename) , imageSize(imageSize) {} ImageInfo::ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, - const Omittable &file, + Omittable encryptedFile, const QString& originalFilename) - : FileInfo(mxcUrl, infoJson, file, originalFilename) + : FileInfo(mxcUrl, infoJson, move(encryptedFile), originalFilename) , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) {} @@ -103,10 +105,10 @@ void ImageInfo::fillInfoJson(QJsonObject* infoJson) const infoJson->insert(QStringLiteral("h"), imageSize.height()); } -Thumbnail::Thumbnail(const QJsonObject& infoJson, const Omittable &file) +Thumbnail::Thumbnail(const QJsonObject& infoJson, + Omittable encryptedFile) : ImageInfo(QUrl(infoJson["thumbnail_url"_ls].toString()), - infoJson["thumbnail_info"_ls].toObject(), - file) + infoJson["thumbnail_info"_ls].toObject(), move(encryptedFile)) {} void Thumbnail::fillInfoJson(QJsonObject* infoJson) const diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 76f20f79..4134202a 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -19,16 +19,13 @@ class QFileInfo; namespace Quotient { namespace EventContent { - /** - * A base class for all content types that can be stored - * in a RoomMessageEvent - * - * Each content type class should have a constructor taking - * a QJsonObject and override fillJson() with an implementation - * that will fill the target QJsonObject with stored values. It is - * assumed but not required that a content object can also be created - * from plain data. - */ + //! \brief Base for all content types that can be stored in RoomMessageEvent + //! + //! Each content type class should have a constructor taking + //! a QJsonObject and override fillJson() with an implementation + //! that will fill the target QJsonObject with stored values. It is + //! assumed but not required that a content object can also be created + //! from plain data. class QUOTIENT_API Base { public: explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} @@ -60,45 +57,55 @@ namespace EventContent { // ImageContent : UrlWithThumbnailContent // VideoContent : PlayableContent> - /** - * A base/mixin class for structures representing an "info" object for - * some content types. These include most attachment types currently in - * the CS API spec. - * - * In order to use it in a content class, derive both from TypedBase - * (or Base) and from FileInfo (or its derivative, such as \p ImageInfo) - * and call fillInfoJson() to fill the "info" subobject. Make sure - * to pass an "info" part of JSON to FileInfo constructor, not the whole - * JSON content, as well as contents of "url" (or a similar key) and - * optionally "filename" node from the main JSON content. Assuming you - * don't do unusual things, you should use \p UrlBasedContent<> instead - * of doing multiple inheritance and overriding Base::fillJson() by hand. - * - * This class is not polymorphic. - */ + //! \brief Mix-in class representing `info` subobject in content JSON + //! + //! This is one of base classes for content types that deal with files or + //! URLs. It stores the file metadata attributes, such as size, MIME type + //! etc. found in the `content/info` subobject of event JSON payloads. + //! Actual content classes derive from this class _and_ TypedBase that + //! provides a polymorphic interface to access data in the mix-in. FileInfo + //! (as well as ImageInfo, that adds image size to the metadata) is NOT + //! polymorphic and is used in a non-polymorphic way to store thumbnail + //! metadata (in a separate instance), next to the metadata on the file + //! itself. + //! + //! If you need to make a new _content_ (not info) class based on files/URLs + //! take UrlBasedContent as the example, i.e.: + //! 1. Double-inherit from this class (or ImageInfo) and TypedBase. + //! 2. Provide a constructor from QJsonObject that will pass the `info` + //! subobject (not the whole content JSON) down to FileInfo/ImageInfo. + //! 3. Override fillJson() to customise the JSON export logic. Make sure + //! to call toInfoJson() from it to produce the payload for the `info` + //! subobject in the JSON payload. + //! + //! \sa ImageInfo, FileContent, ImageContent, AudioContent, VideoContent, + //! UrlBasedContent class QUOTIENT_API FileInfo { public: FileInfo() = default; + //! \brief Construct from a QFileInfo object + //! + //! \param fi a QFileInfo object referring to an existing file explicit FileInfo(const QFileInfo& fi); explicit FileInfo(QUrl mxcUrl, qint64 payloadSize = -1, const QMimeType& mimeType = {}, - Omittable file = none, + Omittable encryptedFile = none, QString originalFilename = {}); + //! \brief Construct from a JSON `info` payload + //! + //! Make sure to pass the `info` subobject of content JSON, not the + //! whole JSON content. FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, - const Omittable &file, + Omittable encryptedFile, QString originalFilename = {}); bool isValid() const; - void fillInfoJson(QJsonObject* infoJson) const; - - /** - * \brief Extract media id from the URL - * - * This can be used, e.g., to construct a QML-facing image:// - * URI as follows: - * \code "image://provider/" + info.mediaId() \endcode - */ + //! \brief Extract media id from the URL + //! + //! This can be used, e.g., to construct a QML-facing image:// + //! URI as follows: + //! \code "image://provider/" + info.mediaId() \endcode QString mediaId() const { return url.authority() + url.path(); } public: @@ -118,19 +125,17 @@ namespace EventContent { return infoJson; } - /** - * A content info class for image content types: image, thumbnail, video - */ + //! \brief A content info class for image/video content types and thumbnails class QUOTIENT_API ImageInfo : public FileInfo { public: ImageInfo() = default; explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); explicit ImageInfo(const QUrl& mxcUrl, qint64 fileSize = -1, const QMimeType& type = {}, QSize imageSize = {}, - const Omittable &file = none, + Omittable encryptedFile = none, const QString& originalFilename = {}); ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, - const Omittable &encryptedFile, + Omittable encryptedFile, const QString& originalFilename = {}); void fillInfoJson(QJsonObject* infoJson) const; @@ -139,22 +144,18 @@ namespace EventContent { QSize imageSize; }; - /** - * An auxiliary class for an info type that carries a thumbnail - * - * This class saves/loads a thumbnail to/from "info" subobject of - * the JSON representation of event content; namely, - * "info/thumbnail_url" and "info/thumbnail_info" fields are used. - */ + //! \brief An auxiliary class for an info type that carries a thumbnail + //! + //! This class saves/loads a thumbnail to/from `info` subobject of + //! the JSON representation of event content; namely, `info/thumbnail_url` + //! and `info/thumbnail_info` fields are used. class QUOTIENT_API Thumbnail : public ImageInfo { public: using ImageInfo::ImageInfo; - Thumbnail(const QJsonObject& infoJson, const Omittable &file = none); + Thumbnail(const QJsonObject& infoJson, + Omittable encryptedFile = none); - /** - * Writes thumbnail information to "thumbnail_info" subobject - * and thumbnail URL to "thumbnail_url" node inside "info". - */ + //! \brief Add thumbnail information to the passed `info` JSON object void fillInfoJson(QJsonObject* infoJson) const; }; @@ -170,18 +171,15 @@ namespace EventContent { using Base::Base; }; - /** - * A base class for content types that have a URL and additional info - * - * Types that derive from this class template take "url" and, - * optionally, "filename" values from the top-level JSON object and - * the rest of information from the "info" subobject, as defined by - * the parameter type. - * - * \tparam InfoT base info class - */ + //! \brief A template class for content types with a URL and additional info + //! + //! Types that derive from this class template take `url` and, + //! optionally, `filename` values from the top-level JSON object and + //! the rest of information from the `info` subobject, as defined by + //! the parameter type. + //! \tparam InfoT base info class - FileInfo or ImageInfo template - class QUOTIENT_API UrlBasedContent : public TypedBase, public InfoT { + class UrlBasedContent : public TypedBase, public InfoT { public: using InfoT::InfoT; explicit UrlBasedContent(const QJsonObject& json) @@ -241,43 +239,39 @@ namespace EventContent { } }; - /** - * Content class for m.image - * - * Available fields: - * - corresponding to the top-level JSON: - * - url - * - filename (extension to the spec) - * - corresponding to the "info" subobject: - * - payloadSize ("size" in JSON) - * - mimeType ("mimetype" in JSON) - * - imageSize (QSize for a combination of "h" and "w" in JSON) - * - thumbnail.url ("thumbnail_url" in JSON) - * - corresponding to the "info/thumbnail_info" subobject: contents of - * thumbnail field, in the same vein as for the main image: - * - payloadSize - * - mimeType - * - imageSize - */ - using ImageContent = UrlWithThumbnailContent; - - /** - * Content class for m.file - * - * Available fields: - * - corresponding to the top-level JSON: - * - url - * - filename - * - corresponding to the "info" subobject: - * - payloadSize ("size" in JSON) - * - mimeType ("mimetype" in JSON) - * - thumbnail.url ("thumbnail_url" in JSON) - * - corresponding to the "info/thumbnail_info" subobject: - * - thumbnail.payloadSize - * - thumbnail.mimeType - * - thumbnail.imageSize (QSize for "h" and "w" in JSON) - */ - using FileContent = UrlWithThumbnailContent; + //! \brief Content class for m.image + //! + //! Available fields: + //! - corresponding to the top-level JSON: + //! - url + //! - filename (extension to the spec) + //! - corresponding to the `info` subobject: + //! - payloadSize (`size` in JSON) + //! - mimeType (`mimetype` in JSON) + //! - imageSize (QSize for a combination of `h` and `w` in JSON) + //! - thumbnail.url (`thumbnail_url` in JSON) + //! - corresponding to the `info/thumbnail_info` subobject: contents of + //! thumbnail field, in the same vein as for the main image: + //! - payloadSize + //! - mimeType + //! - imageSize + using ImageContent = UrlBasedContent; + + //! \brief Content class for m.file + //! + //! Available fields: + //! - corresponding to the top-level JSON: + //! - url + //! - filename + //! - corresponding to the `info` subobject: + //! - payloadSize (`size` in JSON) + //! - mimeType (`mimetype` in JSON) + //! - thumbnail.url (`thumbnail_url` in JSON) + //! - corresponding to the `info/thumbnail_info` subobject: + //! - thumbnail.payloadSize + //! - thumbnail.mimeType + //! - thumbnail.imageSize (QSize for `h` and `w` in JSON) + using FileContent = UrlBasedContent; } // namespace EventContent } // namespace Quotient Q_DECLARE_METATYPE(const Quotient::EventContent::TypedBase*) -- cgit v1.2.3 From d271a171dbec4068e43e8f711d5d2e966a2072ac Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 4 Jan 2022 15:25:49 +0100 Subject: Simplify EventContent a bit Main changes: 1. Base::fillJson() gets a QJsonObject& instead of QJsonObject* - c'mon, there's nothing inherently wrong with using an lvalue reference for a read-write parameter. 2. UrlWithThumbnailContent merged into UrlBasedContent. The original UrlBasedContent was only used to produce a single class, AudioContent, and even that can logically have a thumbnail even if the spec doesn't provision that. And there's no guarantee even for visual content (ImageContent, e.g.) to have thumbnail data; the fallback is already tested. 3. toInfoJson is converted from a template to a couple of overloads that supersede fillInfoJson() member functions in FileInfo/ImageInfo. These overloads are easier on the eye; and clang-tidy no more warns about ImageInfo::fillInfoJson() shadowing FileInfo::fillInfoJson(). 4. Now that UrlWithThumbnail is gone, PlayableContent can directly derive from UrlBasedContent since both its specialisations use it. 5. Instead of FileInfo/ImageInfo, fillInfoJson() has been reinvented within UrlBasedContent so that, in particular, PlayableContent wouldn't need to extract 'info' subobject and then roll it back inside the content JSON object. --- lib/events/encryptionevent.cpp | 9 ++-- lib/events/encryptionevent.h | 2 +- lib/events/eventcontent.cpp | 36 ++++++++-------- lib/events/eventcontent.h | 84 ++++++++++++++----------------------- lib/events/roommemberevent.cpp | 11 +++-- lib/events/roommemberevent.h | 2 +- lib/events/roommessageevent.cpp | 18 ++++---- lib/events/roommessageevent.h | 29 +++++++------ lib/events/roompowerlevelsevent.cpp | 22 +++++----- lib/events/roompowerlevelsevent.h | 2 +- 10 files changed, 98 insertions(+), 117 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 6272c668..47b0a032 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -47,11 +47,10 @@ EncryptionEventContent::EncryptionEventContent(EncryptionType et) } } -void EncryptionEventContent::fillJson(QJsonObject* o) const +void EncryptionEventContent::fillJson(QJsonObject& o) const { - Q_ASSERT(o); if (encryption != EncryptionType::Undefined) - o->insert(AlgorithmKey, algorithm); - o->insert(RotationPeriodMsKey, rotationPeriodMs); - o->insert(RotationPeriodMsgsKey, rotationPeriodMsgs); + o.insert(AlgorithmKey, algorithm); + o.insert(RotationPeriodMsKey, rotationPeriodMs); + o.insert(RotationPeriodMsgsKey, rotationPeriodMsgs); } diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 124ced33..fe76b1af 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -26,7 +26,7 @@ public: int rotationPeriodMsgs; protected: - void fillJson(QJsonObject* o) const override; + void fillJson(QJsonObject& o) const override; }; using EncryptionType = EncryptionEventContent::EncryptionType; diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 479d5da0..6218e3b8 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -15,7 +15,7 @@ using std::move; QJsonObject Base::toJson() const { QJsonObject o; - fillJson(&o); + fillJson(o); return o; } @@ -68,14 +68,15 @@ bool FileInfo::isValid() const && (url.authority() + url.path()).count('/') == 1; } -void FileInfo::fillInfoJson(QJsonObject* infoJson) const +QJsonObject Quotient::EventContent::toInfoJson(const FileInfo& info) { - Q_ASSERT(infoJson); - if (payloadSize != -1) - infoJson->insert(QStringLiteral("size"), payloadSize); - if (mimeType.isValid()) - infoJson->insert(QStringLiteral("mimetype"), mimeType.name()); + QJsonObject infoJson; + if (info.payloadSize != -1) + infoJson.insert(QStringLiteral("size"), info.payloadSize); + if (info.mimeType.isValid()) + infoJson.insert(QStringLiteral("mimetype"), info.mimeType.name()); //TODO add encryptedfile + return infoJson; } ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) @@ -96,13 +97,14 @@ ImageInfo::ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) {} -void ImageInfo::fillInfoJson(QJsonObject* infoJson) const +QJsonObject Quotient::EventContent::toInfoJson(const ImageInfo& info) { - FileInfo::fillInfoJson(infoJson); - if (imageSize.width() != -1) - infoJson->insert(QStringLiteral("w"), imageSize.width()); - if (imageSize.height() != -1) - infoJson->insert(QStringLiteral("h"), imageSize.height()); + auto infoJson = toInfoJson(static_cast(info)); + if (info.imageSize.width() != -1) + infoJson.insert(QStringLiteral("w"), info.imageSize.width()); + if (info.imageSize.height() != -1) + infoJson.insert(QStringLiteral("h"), info.imageSize.height()); + return infoJson; } Thumbnail::Thumbnail(const QJsonObject& infoJson, @@ -111,11 +113,11 @@ Thumbnail::Thumbnail(const QJsonObject& infoJson, infoJson["thumbnail_info"_ls].toObject(), move(encryptedFile)) {} -void Thumbnail::fillInfoJson(QJsonObject* infoJson) const +void Thumbnail::dumpTo(QJsonObject& infoJson) const { if (url.isValid()) - infoJson->insert(QStringLiteral("thumbnail_url"), url.toString()); + infoJson.insert(QStringLiteral("thumbnail_url"), url.toString()); if (!imageSize.isEmpty()) - infoJson->insert(QStringLiteral("thumbnail_info"), - toInfoJson(*this)); + infoJson.insert(QStringLiteral("thumbnail_info"), + toInfoJson(*this)); } diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 4134202a..6aee333d 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -40,7 +40,7 @@ namespace EventContent { Base(const Base&) = default; Base(Base&&) = default; - virtual void fillJson(QJsonObject* o) const = 0; + virtual void fillJson(QJsonObject& o) const = 0; }; // The below structures fairly follow CS spec 11.2.1.6. The overall @@ -50,12 +50,14 @@ namespace EventContent { // A quick classes inheritance structure follows (the definitions are // spread across eventcontent.h and roommessageevent.h): + // UrlBasedContent : InfoT + url and thumbnail data + // PlayableContent : + duration attribute // FileInfo - // FileContent : UrlWithThumbnailContent - // AudioContent : PlayableContent> + // FileContent = UrlBasedContent + // AudioContent = PlayableContent // ImageInfo : FileInfo + imageSize attribute - // ImageContent : UrlWithThumbnailContent - // VideoContent : PlayableContent> + // ImageContent = UrlBasedContent + // VideoContent = PlayableContent //! \brief Mix-in class representing `info` subobject in content JSON //! @@ -117,13 +119,7 @@ namespace EventContent { Omittable file = none; }; - template - QJsonObject toInfoJson(const InfoT& info) - { - QJsonObject infoJson; - info.fillInfoJson(&infoJson); - return infoJson; - } + QUOTIENT_API QJsonObject toInfoJson(const FileInfo& info); //! \brief A content info class for image/video content types and thumbnails class QUOTIENT_API ImageInfo : public FileInfo { @@ -138,12 +134,12 @@ namespace EventContent { Omittable encryptedFile, const QString& originalFilename = {}); - void fillInfoJson(QJsonObject* infoJson) const; - public: QSize imageSize; }; + QUOTIENT_API QJsonObject toInfoJson(const ImageInfo& info); + //! \brief An auxiliary class for an info type that carries a thumbnail //! //! This class saves/loads a thumbnail to/from `info` subobject of @@ -156,7 +152,7 @@ namespace EventContent { Omittable encryptedFile = none); //! \brief Add thumbnail information to the passed `info` JSON object - void fillInfoJson(QJsonObject* infoJson) const; + void dumpTo(QJsonObject& infoJson) const; }; class QUOTIENT_API TypedBase : public Base { @@ -185,57 +181,41 @@ namespace EventContent { explicit UrlBasedContent(const QJsonObject& json) : TypedBase(json) , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), - fromJson>(json["file"]), json["filename"].toString()) + fromJson>(json["file"]), + json["filename"].toString()) + , thumbnail(FileInfo::originalInfoJson) { - // A small hack to facilitate links creation in QML. + // Two small hacks on originalJson to expose mediaIds to QML originalJson.insert("mediaId", InfoT::mediaId()); + originalJson.insert("thumbnailMediaId", thumbnail.mediaId()); } QMimeType type() const override { return InfoT::mimeType; } const FileInfo* fileInfo() const override { return this; } FileInfo* fileInfo() override { return this; } - - protected: - void fillJson(QJsonObject* json) const override - { - Q_ASSERT(json); - if (!InfoT::file.has_value()) { - json->insert("url", InfoT::url.toString()); - } else { - json->insert("file", Quotient::toJson(*InfoT::file)); - } - if (!InfoT::originalName.isEmpty()) - json->insert("filename", InfoT::originalName); - json->insert("info", toInfoJson(*this)); - } - }; - - template - class QUOTIENT_API UrlWithThumbnailContent : public UrlBasedContent { - public: - // NB: when using inherited constructors, thumbnail has to be - // initialised separately - using UrlBasedContent::UrlBasedContent; - explicit UrlWithThumbnailContent(const QJsonObject& json) - : UrlBasedContent(json), thumbnail(InfoT::originalInfoJson) - { - // Another small hack, to simplify making a thumbnail link - UrlBasedContent::originalJson.insert("thumbnailMediaId", - thumbnail.mediaId()); - } - const Thumbnail* thumbnailInfo() const override { return &thumbnail; } public: Thumbnail thumbnail; protected: - void fillJson(QJsonObject* json) const override + virtual void fillInfoJson(QJsonObject& infoJson [[maybe_unused]]) const + {} + + void fillJson(QJsonObject& json) const override { - UrlBasedContent::fillJson(json); - auto infoJson = json->take("info").toObject(); - thumbnail.fillInfoJson(&infoJson); - json->insert("info", infoJson); + if (!InfoT::file.has_value()) { + json.insert("url", InfoT::url.toString()); + } else { + json.insert("file", Quotient::toJson(*InfoT::file)); + } + if (!InfoT::originalName.isEmpty()) + json.insert("filename", InfoT::originalName); + auto infoJson = toInfoJson(*this); + if (thumbnail.isValid()) + thumbnail.dumpTo(infoJson); + fillInfoJson(infoJson); + json.insert("info", infoJson); } }; diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index b4770224..55da5809 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -43,19 +43,18 @@ MemberEventContent::MemberEventContent(const QJsonObject& json) displayName = sanitized(*displayName); } -void MemberEventContent::fillJson(QJsonObject* o) const +void MemberEventContent::fillJson(QJsonObject& o) const { - Q_ASSERT(o); if (membership != Membership::Invalid) - o->insert(QStringLiteral("membership"), + o.insert(QStringLiteral("membership"), MembershipStrings[qCountTrailingZeroBits( std::underlying_type_t(membership))]); if (displayName) - o->insert(QStringLiteral("displayname"), *displayName); + o.insert(QStringLiteral("displayname"), *displayName); if (avatarUrl && avatarUrl->isValid()) - o->insert(QStringLiteral("avatar_url"), avatarUrl->toString()); + o.insert(QStringLiteral("avatar_url"), avatarUrl->toString()); if (!reason.isEmpty()) - o->insert(QStringLiteral("reason"), reason); + o.insert(QStringLiteral("reason"), reason); } bool RoomMemberEvent::changesMembership() const diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index ceb7826b..afbaf825 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -26,7 +26,7 @@ public: QString reason; protected: - void fillJson(QJsonObject* o) const override; + void fillJson(QJsonObject& o) const override; }; using MembershipType [[deprecated("Use Membership instead")]] = Membership; diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index d63352cb..d9d3fbe0 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -302,17 +302,16 @@ TextContent::TextContent(const QJsonObject& json) } } -void TextContent::fillJson(QJsonObject* json) const +void TextContent::fillJson(QJsonObject &json) const { static const auto FormatKey = QStringLiteral("format"); - Q_ASSERT(json); if (mimeType.inherits("text/html")) { - json->insert(FormatKey, HtmlContentTypeId); - json->insert(FormattedBodyKey, body); + json.insert(FormatKey, HtmlContentTypeId); + json.insert(FormattedBodyKey, body); } if (relatesTo) { - json->insert( + json.insert( QStringLiteral("m.relates_to"), relatesTo->type == EventRelation::ReplyType ? QJsonObject { { relatesTo->type, @@ -326,7 +325,7 @@ void TextContent::fillJson(QJsonObject* json) const newContentJson.insert(FormatKey, HtmlContentTypeId); newContentJson.insert(FormattedBodyKey, body); } - json->insert(QStringLiteral("m.new_content"), newContentJson); + json.insert(QStringLiteral("m.new_content"), newContentJson); } } } @@ -347,9 +346,8 @@ QMimeType LocationContent::type() const return QMimeDatabase().mimeTypeForData(geoUri.toLatin1()); } -void LocationContent::fillJson(QJsonObject* o) const +void LocationContent::fillJson(QJsonObject& o) const { - Q_ASSERT(o); - o->insert(QStringLiteral("geo_uri"), geoUri); - o->insert(QStringLiteral("info"), toInfoJson(thumbnail)); + o.insert(QStringLiteral("geo_uri"), geoUri); + o.insert(QStringLiteral("info"), toInfoJson(thumbnail)); } diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 03a51328..6968ad70 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -136,7 +136,7 @@ namespace EventContent { Omittable relatesTo; protected: - void fillJson(QJsonObject* json) const override; + void fillJson(QJsonObject& json) const override; }; /** @@ -164,28 +164,25 @@ namespace EventContent { Thumbnail thumbnail; protected: - void fillJson(QJsonObject* o) const override; + void fillJson(QJsonObject& o) const override; }; /** * A base class for info types that include duration: audio and video */ - template - class QUOTIENT_API PlayableContent : public ContentT { + template + class PlayableContent : public UrlBasedContent { public: - using ContentT::ContentT; + using UrlBasedContent::UrlBasedContent; PlayableContent(const QJsonObject& json) - : ContentT(json) - , duration(ContentT::originalInfoJson["duration"_ls].toInt()) + : UrlBasedContent(json) + , duration(FileInfo::originalInfoJson["duration"_ls].toInt()) {} protected: - void fillJson(QJsonObject* json) const override + void fillInfoJson(QJsonObject& infoJson) const override { - ContentT::fillJson(json); - auto infoJson = json->take("info"_ls).toObject(); infoJson.insert(QStringLiteral("duration"), duration); - json->insert(QStringLiteral("info"), infoJson); } public: @@ -211,7 +208,7 @@ namespace EventContent { * - mimeType * - imageSize */ - using VideoContent = PlayableContent>; + using VideoContent = PlayableContent; /** * Content class for m.audio @@ -224,7 +221,13 @@ namespace EventContent { * - payloadSize ("size" in JSON) * - mimeType ("mimetype" in JSON) * - duration + * - thumbnail.url ("thumbnail_url" in JSON - extension to the spec) + * - corresponding to the "info/thumbnail_info" subobject: contents of + * thumbnail field (extension to the spec): + * - payloadSize + * - mimeType + * - imageSize */ - using AudioContent = PlayableContent>; + using AudioContent = PlayableContent; } // namespace EventContent } // namespace Quotient diff --git a/lib/events/roompowerlevelsevent.cpp b/lib/events/roompowerlevelsevent.cpp index 8d262ddf..1c87fd47 100644 --- a/lib/events/roompowerlevelsevent.cpp +++ b/lib/events/roompowerlevelsevent.cpp @@ -21,17 +21,17 @@ PowerLevelsEventContent::PowerLevelsEventContent(const QJsonObject& json) : { } -void PowerLevelsEventContent::fillJson(QJsonObject* o) const { - o->insert(QStringLiteral("invite"), invite); - o->insert(QStringLiteral("kick"), kick); - o->insert(QStringLiteral("ban"), ban); - o->insert(QStringLiteral("redact"), redact); - o->insert(QStringLiteral("events"), Quotient::toJson(events)); - o->insert(QStringLiteral("events_default"), eventsDefault); - o->insert(QStringLiteral("state_default"), stateDefault); - o->insert(QStringLiteral("users"), Quotient::toJson(users)); - o->insert(QStringLiteral("users_default"), usersDefault); - o->insert(QStringLiteral("notifications"), QJsonObject{{"room", notifications.room}}); +void PowerLevelsEventContent::fillJson(QJsonObject& o) const { + o.insert(QStringLiteral("invite"), invite); + o.insert(QStringLiteral("kick"), kick); + o.insert(QStringLiteral("ban"), ban); + o.insert(QStringLiteral("redact"), redact); + o.insert(QStringLiteral("events"), Quotient::toJson(events)); + o.insert(QStringLiteral("events_default"), eventsDefault); + o.insert(QStringLiteral("state_default"), stateDefault); + o.insert(QStringLiteral("users"), Quotient::toJson(users)); + o.insert(QStringLiteral("users_default"), usersDefault); + o.insert(QStringLiteral("notifications"), QJsonObject{{"room", notifications.room}}); } int RoomPowerLevelsEvent::powerLevelForEvent(const QString &eventId) const { diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index 415cc814..3ce83763 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -31,7 +31,7 @@ public: Notifications notifications; protected: - void fillJson(QJsonObject* o) const override; + void fillJson(QJsonObject& o) const override; }; class QUOTIENT_API RoomPowerLevelsEvent -- cgit v1.2.3 From 4070706fcc91cd46054b00c5f3a267a9d8c44fb7 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 5 Jan 2022 13:58:47 +0100 Subject: Event content: provide toJson() instead of deriving from EC::Base EventContent::Base has been made primarily for the sake of dynamic polymorphism needed within RoomMessageEvent content (arguably, it might not be really needed even there, but that's a bigger matter for another time). When that polymorphism is not needed, it's easier for reading and maintenance to have toJson() member function (or even specialise JsonConverter<> outside of the content structure) instead of deriving from EC::Base and then still having fillJson() member function. This commit removes EventContent::Base dependency where it's not beneficial. --- lib/events/encryptionevent.cpp | 4 +++- lib/events/encryptionevent.h | 8 +++----- lib/events/roommemberevent.cpp | 6 +++--- lib/events/roommemberevent.h | 7 ++----- lib/events/roompowerlevelsevent.cpp | 10 ++++++---- lib/events/roompowerlevelsevent.h | 8 ++------ 6 files changed, 19 insertions(+), 24 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 47b0a032..6e994cd4 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -47,10 +47,12 @@ EncryptionEventContent::EncryptionEventContent(EncryptionType et) } } -void EncryptionEventContent::fillJson(QJsonObject& o) const +QJsonObject EncryptionEventContent::toJson() const { + QJsonObject o; if (encryption != EncryptionType::Undefined) o.insert(AlgorithmKey, algorithm); o.insert(RotationPeriodMsKey, rotationPeriodMs); o.insert(RotationPeriodMsgsKey, rotationPeriodMsgs); + return o; } diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index fe76b1af..5b5420ec 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -4,12 +4,11 @@ #pragma once -#include "eventcontent.h" #include "stateevent.h" #include "quotient_common.h" namespace Quotient { -class QUOTIENT_API EncryptionEventContent : public EventContent::Base { +class QUOTIENT_API EncryptionEventContent { public: enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; @@ -20,13 +19,12 @@ public: {} explicit EncryptionEventContent(const QJsonObject& json); + QJsonObject toJson() const; + EncryptionType encryption; QString algorithm; int rotationPeriodMs; int rotationPeriodMsgs; - -protected: - void fillJson(QJsonObject& o) const override; }; using EncryptionType = EncryptionEventContent::EncryptionType; diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 55da5809..c3be0e00 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -4,8 +4,6 @@ #include "roommemberevent.h" -#include "logging.h" - #include namespace Quotient { @@ -43,8 +41,9 @@ MemberEventContent::MemberEventContent(const QJsonObject& json) displayName = sanitized(*displayName); } -void MemberEventContent::fillJson(QJsonObject& o) const +QJsonObject MemberEventContent::toJson() const { + QJsonObject o; if (membership != Membership::Invalid) o.insert(QStringLiteral("membership"), MembershipStrings[qCountTrailingZeroBits( @@ -55,6 +54,7 @@ void MemberEventContent::fillJson(QJsonObject& o) const o.insert(QStringLiteral("avatar_url"), avatarUrl->toString()); if (!reason.isEmpty()) o.insert(QStringLiteral("reason"), reason); + return o; } bool RoomMemberEvent::changesMembership() const diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index afbaf825..dd33ea6b 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -5,18 +5,18 @@ #pragma once -#include "eventcontent.h" #include "stateevent.h" #include "quotient_common.h" namespace Quotient { -class QUOTIENT_API MemberEventContent : public EventContent::Base { +class QUOTIENT_API MemberEventContent { public: using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; QUO_IMPLICIT MemberEventContent(Membership ms) : membership(ms) {} explicit MemberEventContent(const QJsonObject& json); + QJsonObject toJson() const; Membership membership; /// (Only for invites) Whether the invite is to a direct chat @@ -24,9 +24,6 @@ public: Omittable displayName; Omittable avatarUrl; QString reason; - -protected: - void fillJson(QJsonObject& o) const override; }; using MembershipType [[deprecated("Use Membership instead")]] = Membership; diff --git a/lib/events/roompowerlevelsevent.cpp b/lib/events/roompowerlevelsevent.cpp index 1c87fd47..84a31d55 100644 --- a/lib/events/roompowerlevelsevent.cpp +++ b/lib/events/roompowerlevelsevent.cpp @@ -3,8 +3,6 @@ #include "roompowerlevelsevent.h" -#include - using namespace Quotient; PowerLevelsEventContent::PowerLevelsEventContent(const QJsonObject& json) : @@ -21,7 +19,9 @@ PowerLevelsEventContent::PowerLevelsEventContent(const QJsonObject& json) : { } -void PowerLevelsEventContent::fillJson(QJsonObject& o) const { +QJsonObject PowerLevelsEventContent::toJson() const +{ + QJsonObject o; o.insert(QStringLiteral("invite"), invite); o.insert(QStringLiteral("kick"), kick); o.insert(QStringLiteral("ban"), ban); @@ -31,7 +31,9 @@ void PowerLevelsEventContent::fillJson(QJsonObject& o) const { o.insert(QStringLiteral("state_default"), stateDefault); o.insert(QStringLiteral("users"), Quotient::toJson(users)); o.insert(QStringLiteral("users_default"), usersDefault); - o.insert(QStringLiteral("notifications"), QJsonObject{{"room", notifications.room}}); + o.insert(QStringLiteral("notifications"), + QJsonObject { { "room", notifications.room } }); + return o; } int RoomPowerLevelsEvent::powerLevelForEvent(const QString &eventId) const { diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index 3ce83763..a1638a27 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -3,17 +3,16 @@ #pragma once -#include "eventcontent.h" #include "stateevent.h" namespace Quotient { -class QUOTIENT_API PowerLevelsEventContent : public EventContent::Base { -public: +struct QUOTIENT_API PowerLevelsEventContent { struct Notifications { int room; }; explicit PowerLevelsEventContent(const QJsonObject& json); + QJsonObject toJson() const; int invite; int kick; @@ -29,9 +28,6 @@ public: int usersDefault; Notifications notifications; - -protected: - void fillJson(QJsonObject& o) const override; }; class QUOTIENT_API RoomPowerLevelsEvent -- cgit v1.2.3 From 843f7a0ac2619a2f2863d457cdeaa03707255793 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 4 May 2022 21:12:29 +0200 Subject: basic*EventJson() -> *Event::basicJson() This makes it easier and more intuitive to build a minimal JSON payload for a given event type. A common basicJson() call point is also convenient in template contexts (see next commits). --- lib/events/event.cpp | 2 +- lib/events/event.h | 14 +++++++------- lib/events/eventloader.h | 4 ++-- lib/events/roomevent.cpp | 10 +++++----- lib/events/roomevent.h | 5 +++++ lib/events/stateevent.cpp | 2 +- lib/events/stateevent.h | 28 ++++++++++++++++++---------- 7 files changed, 39 insertions(+), 26 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 4c304a3c..1f1eebaa 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -29,7 +29,7 @@ Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) } Event::Event(Type type, event_mtype_t matrixType, const QJsonObject& contentJson) - : Event(type, basicEventJson(matrixType, contentJson)) + : Event(type, basicJson(matrixType, contentJson)) {} Event::~Event() = default; diff --git a/lib/events/event.h b/lib/events/event.h index 113fa3fa..5be2b41b 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -48,13 +48,6 @@ const QString RoomIdKey { RoomIdKeyL }; const QString UnsignedKey { UnsignedKeyL }; const QString StateKeyKey { StateKeyKeyL }; -/// Make a minimal correct Matrix event JSON -inline QJsonObject basicEventJson(const QString& matrixType, - const QJsonObject& content) -{ - return { { TypeKey, matrixType }, { ContentKey, content } }; -} - // === Event types === using event_type_t = QLatin1String; @@ -193,6 +186,13 @@ public: Event& operator=(Event&&) = delete; virtual ~Event(); + /// Make a minimal correct Matrix event JSON + static QJsonObject basicJson(const QString& matrixType, + const QJsonObject& content) + { + return { { TypeKey, matrixType }, { ContentKey, content } }; + } + Type type() const { return _type; } QString matrixType() const; [[deprecated("Use fullJson() and stringify it with QJsonDocument::toJson() " diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index fe624d70..c7b82e8e 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -29,7 +29,7 @@ template inline event_ptr_tt loadEvent(const QString& matrixType, const QJsonObject& content) { - return doLoadEvent(basicEventJson(matrixType, content), + return doLoadEvent(Event::basicJson(matrixType, content), matrixType); } @@ -44,7 +44,7 @@ inline StateEventPtr loadStateEvent(const QString& matrixType, const QString& stateKey = {}) { return doLoadEvent( - basicStateEventJson(matrixType, content, stateKey), matrixType); + StateEventBase::basicJson(matrixType, content, stateKey), matrixType); } template diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 2f482871..ebe72149 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -101,19 +101,19 @@ void RoomEvent::dumpTo(QDebug dbg) const dbg << " (made at " << originTimestamp().toString(Qt::ISODate) << ')'; } -QJsonObject makeCallContentJson(const QString& callId, int version, - QJsonObject content) +QJsonObject CallEventBase::basicJson(const QString& matrixType, + const QString& callId, int version, + QJsonObject content) { content.insert(QStringLiteral("call_id"), callId); content.insert(QStringLiteral("version"), version); - return content; + return RoomEvent::basicJson(matrixType, content); } CallEventBase::CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, int version, const QJsonObject& contentJson) - : RoomEvent(type, matrixType, - makeCallContentJson(callId, version, contentJson)) + : RoomEvent(type, basicJson(type, callId, version, contentJson)) {} CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index a7d6c428..0692ad8a 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -98,6 +98,11 @@ public: QString callId() const { return contentPart("call_id"_ls); } int version() const { return contentPart("version"_ls); } + +protected: + static QJsonObject basicJson(const QString& matrixType, + const QString& callId, int version, + QJsonObject contentJson = {}); }; } // namespace Quotient Q_DECLARE_METATYPE(Quotient::RoomEvent*) diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index e53d47d4..cdf3c449 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -16,7 +16,7 @@ StateEventBase::StateEventBase(Type type, const QJsonObject& json) StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, const QString& stateKey, const QJsonObject& contentJson) - : RoomEvent(type, basicStateEventJson(matrixType, contentJson, stateKey)) + : RoomEvent(type, basicJson(type, contentJson, stateKey)) {} bool StateEventBase::repeatsState() const diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 19905431..47bf6e59 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -7,16 +7,6 @@ namespace Quotient { -/// Make a minimal correct Matrix state event JSON -inline QJsonObject basicStateEventJson(const QString& matrixTypeId, - const QJsonObject& content, - const QString& stateKey = {}) -{ - return { { TypeKey, matrixTypeId }, - { StateKeyKey, stateKey }, - { ContentKey, content } }; -} - class QUOTIENT_API StateEventBase : public RoomEvent { public: static inline EventFactory factory { "StateEvent" }; @@ -27,6 +17,16 @@ public: const QJsonObject& contentJson = {}); ~StateEventBase() override = default; + //! Make a minimal correct Matrix state event JSON + static QJsonObject basicJson(const QString& matrixTypeId, + const QJsonObject& content, + const QString& stateKey = {}) + { + return { { TypeKey, matrixTypeId }, + { StateKeyKey, stateKey }, + { ContentKey, content } }; + } + bool isStateEvent() const override { return true; } QString replacedState() const; void dumpTo(QDebug dbg) const override; @@ -36,6 +36,14 @@ public: using StateEventPtr = event_ptr_tt; using StateEvents = EventsArray; +[[deprecated("Use StateEventBase::basicJson() instead")]] +inline QJsonObject basicStateEventJson(const QString& matrixTypeId, + const QJsonObject& content, + const QString& stateKey = {}) +{ + return StateEventBase::basicJson(matrixTypeId, content, stateKey); +} + //! \brief Override RoomEvent factory with that from StateEventBase if JSON has //! stateKey //! -- cgit v1.2.3 From 41f630cf7be6e806e498cb31711f403bf6919ff8 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 7 May 2022 19:23:18 +0200 Subject: Pass matrixType(QString), not Event::Type, to basicJson() Not that it was very important, as the two are basically the same thing (and matrixTypeId() is about to be obsoleted); but formally basicJson() is supposed to get the former, not the latter. --- lib/events/roomevent.cpp | 8 ++++---- lib/events/stateevent.cpp | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index ebe72149..707cf4fd 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -105,15 +105,15 @@ QJsonObject CallEventBase::basicJson(const QString& matrixType, const QString& callId, int version, QJsonObject content) { - content.insert(QStringLiteral("call_id"), callId); - content.insert(QStringLiteral("version"), version); - return RoomEvent::basicJson(matrixType, content); + contentJson.insert(QStringLiteral("call_id"), callId); + contentJson.insert(QStringLiteral("version"), version); + return RoomEvent::basicJson(matrixType, contentJson); } CallEventBase::CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, int version, const QJsonObject& contentJson) - : RoomEvent(type, basicJson(type, callId, version, contentJson)) + : RoomEvent(type, basicJson(matrixType, callId, version, contentJson)) {} CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index cdf3c449..0fd489d1 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -16,7 +16,7 @@ StateEventBase::StateEventBase(Type type, const QJsonObject& json) StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, const QString& stateKey, const QJsonObject& contentJson) - : RoomEvent(type, basicJson(type, contentJson, stateKey)) + : RoomEvent(type, basicJson(matrixType, contentJson, stateKey)) {} bool StateEventBase::repeatsState() const -- cgit v1.2.3 From e7a4b5a545b0f59b95ca8097009dbf6eea534db1 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 6 May 2022 22:17:55 +0200 Subject: Generalise DEFINE_SIMPLE_EVENT This macro was defined in accountdataevents.h but adding one more parameter (base class) makes it applicable to pretty much any event with the content that has one key-value pair (though state events already have a non-macro solution in the form of `StateEvent`). Now CustomEvent definition in quotest.cpp can be replaced with a single line. --- lib/events/accountdataevents.h | 31 +++++++++---------------------- lib/events/event.h | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 22 deletions(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 12f1f00b..ec2f64e3 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -46,27 +46,14 @@ struct JsonObjectConverter { using TagsMap = QHash; -#define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ - class QUOTIENT_API _Name : public Event { \ - public: \ - using content_type = _ContentType; \ - DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - explicit _Name(const QJsonObject& obj) : Event(typeId(), obj) {} \ - explicit _Name(const content_type& content) \ - : Event(typeId(), matrixTypeId(), \ - QJsonObject { \ - { QStringLiteral(#_ContentKey), toJson(content) } }) \ - {} \ - auto _ContentKey() const \ - { \ - return contentPart(#_ContentKey##_ls); \ - } \ - }; \ - REGISTER_EVENT_TYPE(_Name) \ - // End of macro - -DEFINE_SIMPLE_EVENT(TagEvent, "m.tag", TagsMap, tags) -DEFINE_SIMPLE_EVENT(ReadMarkerEvent, "m.fully_read", QString, event_id) -DEFINE_SIMPLE_EVENT(IgnoredUsersEvent, "m.ignored_user_list", QSet, +DEFINE_SIMPLE_EVENT(TagEvent, Event, "m.tag", TagsMap, tags) +DEFINE_SIMPLE_EVENT(ReadMarkerEventImpl, Event, "m.fully_read", QString, eventId) +class ReadMarkerEvent : public ReadMarkerEventImpl { +public: + using ReadMarkerEventImpl::ReadMarkerEventImpl; + [[deprecated("Use ReadMarkerEvent::eventId() instead")]] + QString event_id() const { return eventId(); } +}; +DEFINE_SIMPLE_EVENT(IgnoredUsersEvent, Event, "m.ignored_user_list", QSet, ignored_users) } // namespace Quotient diff --git a/lib/events/event.h b/lib/events/event.h index 5be2b41b..a27c0b96 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -278,6 +278,32 @@ using Events = EventsArray; Type_::factory.addMethod(); \ // End of macro +/// \brief Define a new event class with a single key-value pair in the content +/// +/// This macro defines a new event class \p Name_ derived from \p Base_, +/// with Matrix event type \p TypeId_, providing a getter named \p GetterName_ +/// for a single value of type \p ValueType_ inside the event content. +/// To retrieve the value the getter uses a JSON key name that corresponds to +/// its own (getter's) name but written in snake_case. \p GetterName_ must be +/// in camelCase, no quotes (an identifier, not a literal). +#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_) \ + class QUOTIENT_API Name_ : public Base_ { \ + public: \ + using content_type = ValueType_; \ + DEFINE_EVENT_TYPEID(TypeId_, Name_) \ + explicit Name_(const QJsonObject& obj) : Base_(TypeId, obj) {} \ + explicit Name_(const content_type& content) \ + : Name_(Base_::basicJson(TypeId, { { JsonKey, toJson(content) } })) \ + {} \ + auto GetterName_() const \ + { \ + return contentPart(JsonKey); \ + } \ + static inline const auto JsonKey = toSnakeCase(#GetterName_##_ls); \ + }; \ + REGISTER_EVENT_TYPE(Name_) \ + // End of macro + // === is<>(), eventCast<>() and switchOnType<>() === template -- cgit v1.2.3 From f4a20cc3710ee8f4b1788f73d05466aa0e660d61 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 7 May 2022 19:02:35 +0200 Subject: More cleanup --- lib/events/directchatevent.cpp | 2 -- lib/events/eventcontent.h | 2 +- lib/events/roomevent.cpp | 4 ++-- lib/events/stateevent.cpp | 4 ++-- 4 files changed, 5 insertions(+), 7 deletions(-) (limited to 'lib/events') diff --git a/lib/events/directchatevent.cpp b/lib/events/directchatevent.cpp index 0ee1f7b0..83bb1e32 100644 --- a/lib/events/directchatevent.cpp +++ b/lib/events/directchatevent.cpp @@ -3,8 +3,6 @@ #include "directchatevent.h" -#include - using namespace Quotient; QMultiHash DirectChatEvent::usersToDirectChats() const diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 6aee333d..bbd35618 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -40,7 +40,7 @@ namespace EventContent { Base(const Base&) = default; Base(Base&&) = default; - virtual void fillJson(QJsonObject& o) const = 0; + virtual void fillJson(QJsonObject&) const = 0; }; // The below structures fairly follow CS spec 11.2.1.6. The overall diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 707cf4fd..3ddf5ac4 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -103,7 +103,7 @@ void RoomEvent::dumpTo(QDebug dbg) const QJsonObject CallEventBase::basicJson(const QString& matrixType, const QString& callId, int version, - QJsonObject content) + QJsonObject contentJson) { contentJson.insert(QStringLiteral("call_id"), callId); contentJson.insert(QStringLiteral("version"), version); @@ -116,7 +116,7 @@ CallEventBase::CallEventBase(Type type, event_mtype_t matrixType, : RoomEvent(type, basicJson(matrixType, callId, version, contentJson)) {} -CallEventBase::CallEventBase(Event::Type type, const QJsonObject& json) +CallEventBase::CallEventBase(Type type, const QJsonObject& json) : RoomEvent(type, json) { if (callId().isEmpty()) diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 0fd489d1..c343e37f 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -6,9 +6,9 @@ using namespace Quotient; StateEventBase::StateEventBase(Type type, const QJsonObject& json) - : RoomEvent(json.contains(StateKeyKeyL) ? type : unknownEventTypeId(), json) + : RoomEvent(json.contains(StateKeyKeyL) ? type : UnknownEventTypeId, json) { - if (Event::type() == unknownEventTypeId() && !json.contains(StateKeyKeyL)) + if (Event::type() == UnknownEventTypeId && !json.contains(StateKeyKeyL)) qWarning(EVENTS) << "Attempt to create a state event with no stateKey -" "forcing the event type to unknown to avoid damage"; } -- cgit v1.2.3 From 4b35dfd8af196ff9e8669499ea3ed7e4127f5901 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 30 Jan 2022 15:55:06 +0100 Subject: Use std::pair instead of QPair QPair is giving way to its STL counterpart, becoming its alias in Qt 6. --- lib/events/stateevent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 47bf6e59..343e87a5 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -72,7 +72,7 @@ inline bool is(const Event& e) * \sa * https://matrix.org/docs/spec/client_server/unstable.html#types-of-room-events */ -using StateEventKey = QPair; +using StateEventKey = std::pair; template struct Prev { -- cgit v1.2.3 From c42d268db0b40cdba06381fc64a6966a72c90709 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 11 Feb 2022 22:21:25 +0100 Subject: QUO_CONTENT_GETTER To streamline adding of simple getters of content parts. --- lib/events/callanswerevent.h | 6 ++---- lib/events/callcandidatesevent.h | 17 +++-------------- lib/events/callinviteevent.h | 5 +---- lib/events/event.h | 15 +++++++++++++++ lib/events/redactionevent.h | 2 +- lib/events/roomevent.h | 4 ++-- 6 files changed, 24 insertions(+), 25 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 8ffe60f2..70292a7a 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -17,10 +17,8 @@ public: const QString& sdp); explicit CallAnswerEvent(const QString& callId, const QString& sdp); - int lifetime() const - { - return contentPart("lifetime"_ls); - } // FIXME: Omittable<>? + QUO_CONTENT_GETTER(int, lifetime) // FIXME: Omittable<>? + QString sdp() const { return contentPart("answer"_ls).value("sdp"_ls).toString(); diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index 74c38f2c..e949f722 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -23,20 +23,9 @@ public: { { QStringLiteral("candidates"), candidates } }) {} - QJsonArray candidates() const - { - return contentPart("candidates"_ls); - } - - QString callId() const - { - return contentPart("call_id"); - } - - int version() const - { - return contentPart("version"); - } + QUO_CONTENT_GETTER(QJsonArray, candidates) + QUO_CONTENT_GETTER(QString, callId) + QUO_CONTENT_GETTER(int, version) }; REGISTER_EVENT_TYPE(CallCandidatesEvent) diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 47362b5c..1b1f4f0f 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -16,10 +16,7 @@ public: explicit CallInviteEvent(const QString& callId, const int lifetime, const QString& sdp); - int lifetime() const - { - return contentPart("lifetime"_ls); - } // FIXME: Omittable<>? + QUO_CONTENT_GETTER(int, lifetime) // FIXME: Omittable<>? QString sdp() const { return contentPart("offer"_ls).value("sdp"_ls).toString(); diff --git a/lib/events/event.h b/lib/events/event.h index a27c0b96..ec21c6aa 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -258,6 +258,21 @@ template using EventsArray = std::vector>; using Events = EventsArray; +//! \brief Define an inline method obtaining a content part +//! +//! This macro adds a const method that extracts a JSON value at the key +//! toSnakeCase(PartName_) (sic) and converts it to the type +//! \p PartType_. Effectively, the generated method is an equivalent of +//! \code +//! contentPart(Quotient::toSnakeCase(#PartName_##_ls)); +//! \endcode +#define QUO_CONTENT_GETTER(PartType_, PartName_) \ + PartType_ PartName_() const \ + { \ + static const auto JsonKey = toSnakeCase(#PartName_##_ls); \ + return contentPart(JsonKey); \ + } + // === Facilities for event class definitions === // This macro should be used in a public section of an event class to diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index be20bf52..1c486a44 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -17,7 +17,7 @@ public: { return fullJson()["redacts"_ls].toString(); } - QString reason() const { return contentPart("reason"_ls); } + QUO_CONTENT_GETTER(QString, reason) }; REGISTER_EVENT_TYPE(RedactionEvent) } // namespace Quotient diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 0692ad8a..7f724689 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -96,8 +96,8 @@ public: ~CallEventBase() override = default; bool isCallEvent() const override { return true; } - QString callId() const { return contentPart("call_id"_ls); } - int version() const { return contentPart("version"_ls); } + QUO_CONTENT_GETTER(QString, callId) + QUO_CONTENT_GETTER(int, version) protected: static QJsonObject basicJson(const QString& matrixType, -- cgit v1.2.3 From b32c1c27ae412d073a7e98bdaf22678bdc66ab23 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 10 May 2022 22:56:02 +0200 Subject: CallAnswerEvent: drop lifetime See https://github.com/matrix-org/matrix-spec/pull/1054. # Conflicts: # lib/events/callanswerevent.cpp # lib/events/callanswerevent.h --- lib/events/callanswerevent.cpp | 11 ----------- lib/events/callanswerevent.h | 4 ---- 2 files changed, 15 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index be83d9d0..f75f8ad3 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -14,7 +14,6 @@ m.call.answer "type": "answer" }, "call_id": "12345", - "lifetime": 60000, "version": 0 }, "event_id": "$WLGTSEFSEF:localhost", @@ -33,16 +32,6 @@ CallAnswerEvent::CallAnswerEvent(const QJsonObject& obj) qCDebug(EVENTS) << "Call Answer event"; } -CallAnswerEvent::CallAnswerEvent(const QString& callId, const int lifetime, - const QString& sdp) - : CallEventBase( - typeId(), matrixTypeId(), callId, 0, - { { QStringLiteral("lifetime"), lifetime }, - { QStringLiteral("answer"), - QJsonObject { { QStringLiteral("type"), QStringLiteral("answer") }, - { QStringLiteral("sdp"), sdp } } } }) -{} - CallAnswerEvent::CallAnswerEvent(const QString& callId, const QString& sdp) : CallEventBase( typeId(), matrixTypeId(), callId, 0, diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 70292a7a..4d539b85 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -13,12 +13,8 @@ public: explicit CallAnswerEvent(const QJsonObject& obj); - explicit CallAnswerEvent(const QString& callId, const int lifetime, - const QString& sdp); explicit CallAnswerEvent(const QString& callId, const QString& sdp); - QUO_CONTENT_GETTER(int, lifetime) // FIXME: Omittable<>? - QString sdp() const { return contentPart("answer"_ls).value("sdp"_ls).toString(); -- cgit v1.2.3 From 572b727b22d66a79431326c924236ef431fd972b Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 14 May 2022 11:20:43 +0200 Subject: Cleanup across the board Mainly driven by clang-tidy and SonarCloud warnings (sadly, SonarCloud doesn't store historical reports so no link can be provided here). --- lib/events/callinviteevent.cpp | 2 +- lib/events/callinviteevent.h | 4 ++-- lib/events/roomkeyevent.h | 5 ++++- 3 files changed, 7 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 11d50768..2f26a1cb 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -33,7 +33,7 @@ CallInviteEvent::CallInviteEvent(const QJsonObject& obj) qCDebug(EVENTS) << "Call Invite event"; } -CallInviteEvent::CallInviteEvent(const QString& callId, const int lifetime, +CallInviteEvent::CallInviteEvent(const QString& callId, int lifetime, const QString& sdp) : CallEventBase( typeId(), matrixTypeId(), callId, 0, diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 1b1f4f0f..5b4ca0df 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -13,10 +13,10 @@ public: explicit CallInviteEvent(const QJsonObject& obj); - explicit CallInviteEvent(const QString& callId, const int lifetime, + explicit CallInviteEvent(const QString& callId, int lifetime, const QString& sdp); - QUO_CONTENT_GETTER(int, lifetime) // FIXME: Omittable<>? + QUO_CONTENT_GETTER(int, lifetime) QString sdp() const { return contentPart("offer"_ls).value("sdp"_ls).toString(); diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index c4df7936..ed4c9440 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -16,7 +16,10 @@ public: QString algorithm() const { return contentPart("algorithm"_ls); } QString roomId() const { return contentPart(RoomIdKeyL); } QString sessionId() const { return contentPart("session_id"_ls); } - QString sessionKey() const { return contentPart("session_key"_ls); } + QByteArray sessionKey() const + { + return contentPart("session_key"_ls).toLatin1(); + } }; REGISTER_EVENT_TYPE(RoomKeyEvent) } // namespace Quotient -- cgit v1.2.3 From ff54bf2d0979dc6b9b3b77bba827ae7f3baa9f58 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sun, 27 Feb 2022 19:15:16 +0100 Subject: Add constructor for creating roomkeyevents --- lib/events/roomkeyevent.cpp | 13 +++++++++++++ lib/events/roomkeyevent.h | 1 + 2 files changed, 14 insertions(+) (limited to 'lib/events') diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index 332be3f7..68962950 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -10,3 +10,16 @@ RoomKeyEvent::RoomKeyEvent(const QJsonObject &obj) : Event(typeId(), obj) if (roomId().isEmpty()) qCWarning(E2EE) << "Room key event has empty room id"; } + +RoomKeyEvent::RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString& sessionId, const QString& sessionKey, const QString& senderId) + : Event(typeId(), { + {"content", QJsonObject{ + {"algorithm", algorithm}, + {"room_id", roomId}, + {"session_id", sessionId}, + {"session_key", sessionKey}, + }}, + {"sender", senderId}, + {"type", "m.room_key"}, + }) +{} diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index ed4c9440..2bda3086 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -12,6 +12,7 @@ public: DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) explicit RoomKeyEvent(const QJsonObject& obj); + explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString &sessionId, const QString& sessionKey, const QString& senderId); QString algorithm() const { return contentPart("algorithm"_ls); } QString roomId() const { return contentPart(RoomIdKeyL); } -- cgit v1.2.3 From efa450920e5fc338e771e653ca0889e948d04ee7 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 8 Mar 2022 00:06:36 +0100 Subject: Implement sending encrypted files --- lib/events/encryptedfile.cpp | 26 ++++++++++++++++++++++++-- lib/events/encryptedfile.h | 1 + 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index d4a517bd..e90be428 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -8,6 +8,7 @@ #ifdef Quotient_E2EE_ENABLED #include #include +#include "e2ee/qolmutils.h" #endif using namespace Quotient; @@ -27,7 +28,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const { int length; auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray plaintext(ciphertext.size() + EVP_CIPHER_CTX_block_size(ctx) + QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, @@ -44,7 +45,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const + length, &length); EVP_CIPHER_CTX_free(ctx); - return plaintext; + return plaintext.left(ciphertext.size()); } #else qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " @@ -53,6 +54,27 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const #endif } +std::pair EncryptedFile::encryptFile(const QByteArray &plainText) +{ + QByteArray k = getRandom(32); + auto kBase64 = k.toBase64(); + QByteArray iv = getRandom(16); + JWK key = {"oct"_ls, {"encrypt"_ls, "decrypt"_ls}, "A256CTR"_ls, QString(k.toBase64()).replace(u'/', u'_').replace(u'+', u'-').left(kBase64.indexOf('=')), true}; + + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + QByteArray cipherText(plainText.size(), plainText.size() + EVP_MAX_BLOCK_LENGTH - 1); + EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); + EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); + EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); + EVP_CIPHER_CTX_free(ctx); + + auto hash = QCryptographicHash::hash(cipherText, QCryptographicHash::Sha256).toBase64(); + auto ivBase64 = iv.toBase64(); + EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; + return {file, cipherText}; +} + void JsonObjectConverter::dumpTo(QJsonObject& jo, const EncryptedFile& pod) { diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index d0c4a030..2ce35086 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -46,6 +46,7 @@ public: QString v; QByteArray decryptFile(const QByteArray &ciphertext) const; + static std::pair encryptFile(const QByteArray &plainText); }; template <> -- cgit v1.2.3 From fcde81c8618fbe10c1cb91c0ec6887a3df705a23 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Tue, 8 Mar 2022 21:44:10 +0100 Subject: Properly create encrypted edits --- lib/events/encryptedevent.cpp | 7 +++++++ lib/events/encryptedevent.h | 2 ++ 2 files changed, 9 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 9d07a35f..3af3d6ff 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -61,3 +61,10 @@ RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const } return loadEvent(eventObject); } + +void EncryptedEvent::setRelation(const QJsonObject& relation) +{ + auto content = editJson()["content"_ls].toObject(); + content["m.relates_to"] = relation; + editJson()["content"] = content; +} diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 72efffd4..ddd5e415 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -56,6 +56,8 @@ public: QString deviceId() const { return contentPart(DeviceIdKeyL); } QString sessionId() const { return contentPart(SessionIdKeyL); } RoomEventPtr createDecrypted(const QString &decrypted) const; + + void setRelation(const QJsonObject& relation); }; REGISTER_EVENT_TYPE(EncryptedEvent) -- cgit v1.2.3 From e437c29654e8f988ad694083401bbef23fbbcb18 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Mon, 16 May 2022 20:51:41 +0200 Subject: More work; Update olm pickle & timestamps in database; Remove TODOs --- lib/events/encryptedfile.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index e90be428..bb4e26c7 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -56,6 +56,7 @@ QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const std::pair EncryptedFile::encryptFile(const QByteArray &plainText) { +#ifdef Quotient_E2EE_ENABLED QByteArray k = getRandom(32); auto kBase64 = k.toBase64(); QByteArray iv = getRandom(16); @@ -73,6 +74,9 @@ std::pair EncryptedFile::encryptFile(const QByteArray auto ivBase64 = iv.toBase64(); EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; return {file, cipherText}; +#else + return {{}, {}}; +#endif } void JsonObjectConverter::dumpTo(QJsonObject& jo, -- cgit v1.2.3 From 1b302abce0bfd9fb62cdc721bc7300dc61b1784f Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Thu, 10 Mar 2022 21:47:51 +0100 Subject: Update lib/events/encryptedfile.h --- lib/events/encryptedfile.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h index 2ce35086..022ac91e 100644 --- a/lib/events/encryptedfile.h +++ b/lib/events/encryptedfile.h @@ -46,7 +46,7 @@ public: QString v; QByteArray decryptFile(const QByteArray &ciphertext) const; - static std::pair encryptFile(const QByteArray &plainText); + static std::pair encryptFile(const QByteArray& plainText); }; template <> -- cgit v1.2.3 From c671867a0a3e2a6ad0e7ae6e93fa09467c06188f Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Wed, 18 May 2022 22:02:50 +0200 Subject: Apply suggestions from code review Co-authored-by: Alexey Rusakov --- lib/events/encryptedfile.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index bb4e26c7..d35ee28f 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -75,7 +75,7 @@ std::pair EncryptedFile::encryptFile(const QByteArray EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; return {file, cipherText}; #else - return {{}, {}}; + return {}; #endif } -- cgit v1.2.3 From 9c4cc1b9b065765843c81a0c555b3afa5122b61e Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Wed, 18 May 2022 22:05:48 +0200 Subject: Update lib/events/encryptedevent.cpp Co-authored-by: Alexey Rusakov --- lib/events/encryptedevent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 3af3d6ff..c97ccc16 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -64,7 +64,7 @@ RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const void EncryptedEvent::setRelation(const QJsonObject& relation) { - auto content = editJson()["content"_ls].toObject(); + auto content = contentJson(); content["m.relates_to"] = relation; editJson()["content"] = content; } -- cgit v1.2.3 From a8076b9a2394150e11381dc8fc2e3af2bbd03f39 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Thu, 19 May 2022 21:58:54 +0200 Subject: Fix cipher text buffer initialization --- lib/events/encryptedfile.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index d35ee28f..9cc3a0c8 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -64,7 +64,7 @@ std::pair EncryptedFile::encryptFile(const QByteArray int length; auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray cipherText(plainText.size(), plainText.size() + EVP_MAX_BLOCK_LENGTH - 1); + QByteArray cipherText(plainText.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); -- cgit v1.2.3 From 44f34c60fe1f1dde859655bbda86221b6cec4811 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Fri, 20 May 2022 12:41:06 +0200 Subject: Truncate ciphertext buffer to actual size during file encryption The ciphertext for AES CTR is exactly as large as the plaintext (not necessarily a multiple of the blocksize!). By truncating the ciphertext, we do not send bytes that will be decrypted to gibberish. As a side node, we probably do not need to initialize the ciphertext buffer larger than the plaintext size at all, but the OpenSSL docs are a bit vague about that. --- lib/events/encryptedfile.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 9cc3a0c8..140dca7f 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -67,6 +67,7 @@ std::pair EncryptedFile::encryptFile(const QByteArray QByteArray cipherText(plainText.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); + cipherText.resize(length); EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); EVP_CIPHER_CTX_free(ctx); -- cgit v1.2.3 From 59f2b60835752fc87e75f456145d21cc5f77a433 Mon Sep 17 00:00:00 2001 From: Tobias Fella <9750016+TobiasFella@users.noreply.github.com> Date: Fri, 20 May 2022 20:33:12 +0200 Subject: Apply suggestions from code review Co-authored-by: Alexey Rusakov --- lib/events/encryptedfile.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp index 140dca7f..33ebb514 100644 --- a/lib/events/encryptedfile.cpp +++ b/lib/events/encryptedfile.cpp @@ -64,10 +64,10 @@ std::pair EncryptedFile::encryptFile(const QByteArray int length; auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray cipherText(plainText.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); + const auto blockSize = EVP_CIPHER_CTX_block_size(ctx); + QByteArray cipherText(plainText.size() + blockSize - 1, '\0'); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); - cipherText.resize(length); EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); EVP_CIPHER_CTX_free(ctx); -- cgit v1.2.3 From 0b5e72a2c6502f22a752b72b4df5fa25746fdd25 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 26 May 2022 08:51:22 +0200 Subject: Refactor EncryptedFile and EC::FileInfo::file Besides having a misleading name (and it goes back to the spec), EncryptedFile under `file` key preempts the `url` (or `thumbnail_url`) string value so only one of the two should exist. This is a case for using std::variant<> - despite its clumsy syntax, it can actually simplify and streamline code when all the necessary bits are in place (such as conversion to JSON and getting the common piece - the URL - out of it). This commit replaces `FileInfo::url` and `FileInfo::file` with a common field `source` of type `FileSourceInfo` that is an alias for a variant type covering both underlying types; and `url()` is reintroduced as a function instead, to allow simplified access to whichever URL is available inside the variant. Oh, and EncryptedFile is EncryptedFileMetadata now, to clarify that it does not represent the file payload itself but rather the data necessary to obtain that payload. --- lib/events/encryptedfile.cpp | 119 -------------------------- lib/events/encryptedfile.h | 63 -------------- lib/events/eventcontent.cpp | 68 +++++++-------- lib/events/eventcontent.h | 53 ++++++------ lib/events/filesourceinfo.cpp | 181 ++++++++++++++++++++++++++++++++++++++++ lib/events/filesourceinfo.h | 89 ++++++++++++++++++++ lib/events/roomavatarevent.h | 4 +- lib/events/roommessageevent.cpp | 8 +- lib/events/stickerevent.cpp | 2 +- 9 files changed, 335 insertions(+), 252 deletions(-) delete mode 100644 lib/events/encryptedfile.cpp delete mode 100644 lib/events/encryptedfile.h create mode 100644 lib/events/filesourceinfo.cpp create mode 100644 lib/events/filesourceinfo.h (limited to 'lib/events') diff --git a/lib/events/encryptedfile.cpp b/lib/events/encryptedfile.cpp deleted file mode 100644 index 33ebb514..00000000 --- a/lib/events/encryptedfile.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// SPDX-FileCopyrightText: 2021 Carl Schwan -// -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "encryptedfile.h" -#include "logging.h" - -#ifdef Quotient_E2EE_ENABLED -#include -#include -#include "e2ee/qolmutils.h" -#endif - -using namespace Quotient; - -QByteArray EncryptedFile::decryptFile(const QByteArray& ciphertext) const -{ -#ifdef Quotient_E2EE_ENABLED - auto _key = key.k; - const auto keyBytes = QByteArray::fromBase64( - _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); - const auto sha256 = QByteArray::fromBase64(hashes["sha256"].toLatin1()); - if (sha256 - != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { - qCWarning(E2EE) << "Hash verification failed for file"; - return {}; - } - { - int length; - auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - - 1, - '\0'); - EVP_DecryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, - reinterpret_cast( - keyBytes.data()), - reinterpret_cast( - QByteArray::fromBase64(iv.toLatin1()).data())); - EVP_DecryptUpdate( - ctx, reinterpret_cast(plaintext.data()), &length, - reinterpret_cast(ciphertext.data()), - ciphertext.size()); - EVP_DecryptFinal_ex(ctx, - reinterpret_cast(plaintext.data()) - + length, - &length); - EVP_CIPHER_CTX_free(ctx); - return plaintext.left(ciphertext.size()); - } -#else - qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " - "cannot decrypt the file"; - return ciphertext; -#endif -} - -std::pair EncryptedFile::encryptFile(const QByteArray &plainText) -{ -#ifdef Quotient_E2EE_ENABLED - QByteArray k = getRandom(32); - auto kBase64 = k.toBase64(); - QByteArray iv = getRandom(16); - JWK key = {"oct"_ls, {"encrypt"_ls, "decrypt"_ls}, "A256CTR"_ls, QString(k.toBase64()).replace(u'/', u'_').replace(u'+', u'-').left(kBase64.indexOf('=')), true}; - - int length; - auto* ctx = EVP_CIPHER_CTX_new(); - EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()),reinterpret_cast(iv.data())); - const auto blockSize = EVP_CIPHER_CTX_block_size(ctx); - QByteArray cipherText(plainText.size() + blockSize - 1, '\0'); - EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), &length, reinterpret_cast(plainText.data()), plainText.size()); - EVP_EncryptFinal_ex(ctx, reinterpret_cast(cipherText.data()) + length, &length); - EVP_CIPHER_CTX_free(ctx); - - auto hash = QCryptographicHash::hash(cipherText, QCryptographicHash::Sha256).toBase64(); - auto ivBase64 = iv.toBase64(); - EncryptedFile file = {{}, key, ivBase64.left(ivBase64.indexOf('=')), {{QStringLiteral("sha256"), hash.left(hash.indexOf('='))}}, "v2"_ls}; - return {file, cipherText}; -#else - return {}; -#endif -} - -void JsonObjectConverter::dumpTo(QJsonObject& jo, - const EncryptedFile& pod) -{ - addParam<>(jo, QStringLiteral("url"), pod.url); - addParam<>(jo, QStringLiteral("key"), pod.key); - addParam<>(jo, QStringLiteral("iv"), pod.iv); - addParam<>(jo, QStringLiteral("hashes"), pod.hashes); - addParam<>(jo, QStringLiteral("v"), pod.v); -} - -void JsonObjectConverter::fillFrom(const QJsonObject& jo, - EncryptedFile& pod) -{ - fromJson(jo.value("url"_ls), pod.url); - fromJson(jo.value("key"_ls), pod.key); - fromJson(jo.value("iv"_ls), pod.iv); - fromJson(jo.value("hashes"_ls), pod.hashes); - fromJson(jo.value("v"_ls), pod.v); -} - -void JsonObjectConverter::dumpTo(QJsonObject &jo, const JWK &pod) -{ - addParam<>(jo, QStringLiteral("kty"), pod.kty); - addParam<>(jo, QStringLiteral("key_ops"), pod.keyOps); - addParam<>(jo, QStringLiteral("alg"), pod.alg); - addParam<>(jo, QStringLiteral("k"), pod.k); - addParam<>(jo, QStringLiteral("ext"), pod.ext); -} - -void JsonObjectConverter::fillFrom(const QJsonObject &jo, JWK &pod) -{ - fromJson(jo.value("kty"_ls), pod.kty); - fromJson(jo.value("key_ops"_ls), pod.keyOps); - fromJson(jo.value("alg"_ls), pod.alg); - fromJson(jo.value("k"_ls), pod.k); - fromJson(jo.value("ext"_ls), pod.ext); -} diff --git a/lib/events/encryptedfile.h b/lib/events/encryptedfile.h deleted file mode 100644 index 022ac91e..00000000 --- a/lib/events/encryptedfile.h +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-FileCopyrightText: 2021 Carl Schwan -// -// SPDX-License-Identifier: LGPL-2.1-or-later - -#pragma once - -#include "converters.h" - -namespace Quotient { -/** - * JSON Web Key object as specified in - * https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes - * The only currently relevant member is `k`, the rest needs to be set to the defaults specified in the spec. - */ -struct JWK -{ - Q_GADGET - Q_PROPERTY(QString kty MEMBER kty CONSTANT) - Q_PROPERTY(QStringList keyOps MEMBER keyOps CONSTANT) - Q_PROPERTY(QString alg MEMBER alg CONSTANT) - Q_PROPERTY(QString k MEMBER k CONSTANT) - Q_PROPERTY(bool ext MEMBER ext CONSTANT) - -public: - QString kty; - QStringList keyOps; - QString alg; - QString k; - bool ext; -}; - -struct QUOTIENT_API EncryptedFile -{ - Q_GADGET - Q_PROPERTY(QUrl url MEMBER url CONSTANT) - Q_PROPERTY(JWK key MEMBER key CONSTANT) - Q_PROPERTY(QString iv MEMBER iv CONSTANT) - Q_PROPERTY(QHash hashes MEMBER hashes CONSTANT) - Q_PROPERTY(QString v MEMBER v CONSTANT) - -public: - QUrl url; - JWK key; - QString iv; - QHash hashes; - QString v; - - QByteArray decryptFile(const QByteArray &ciphertext) const; - static std::pair encryptFile(const QByteArray& plainText); -}; - -template <> -struct QUOTIENT_API JsonObjectConverter { - static void dumpTo(QJsonObject& jo, const EncryptedFile& pod); - static void fillFrom(const QJsonObject& jo, EncryptedFile& pod); -}; - -template <> -struct QUOTIENT_API JsonObjectConverter { - static void dumpTo(QJsonObject& jo, const JWK& pod); - static void fillFrom(const QJsonObject& jo, JWK& pod); -}; -} // namespace Quotient diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 6218e3b8..36b647cb 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -19,23 +19,21 @@ QJsonObject Base::toJson() const return o; } -FileInfo::FileInfo(const QFileInfo &fi) - : mimeType(QMimeDatabase().mimeTypeForFile(fi)) - , url(QUrl::fromLocalFile(fi.filePath())) - , payloadSize(fi.size()) - , originalName(fi.fileName()) +FileInfo::FileInfo(const QFileInfo& fi) + : source(QUrl::fromLocalFile(fi.filePath())), + mimeType(QMimeDatabase().mimeTypeForFile(fi)), + payloadSize(fi.size()), + originalName(fi.fileName()) { Q_ASSERT(fi.isFile()); } -FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, - Omittable encryptedFile, - QString originalFilename) - : mimeType(mimeType) - , url(move(u)) +FileInfo::FileInfo(FileSourceInfo sourceInfo, qint64 payloadSize, + const QMimeType& mimeType, QString originalFilename) + : source(move(sourceInfo)) + , mimeType(mimeType) , payloadSize(payloadSize) , originalName(move(originalFilename)) - , file(move(encryptedFile)) { if (!isValid()) qCWarning(MESSAGES) @@ -44,28 +42,28 @@ FileInfo::FileInfo(QUrl u, qint64 payloadSize, const QMimeType& mimeType, "0.7; for local resources, use FileInfo(QFileInfo) instead"; } -FileInfo::FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, - Omittable encryptedFile, +FileInfo::FileInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, QString originalFilename) - : originalInfoJson(infoJson) + : source(move(sourceInfo)) + , originalInfoJson(infoJson) , mimeType( QMimeDatabase().mimeTypeForName(infoJson["mimetype"_ls].toString())) - , url(move(mxcUrl)) , payloadSize(fromJson(infoJson["size"_ls])) , originalName(move(originalFilename)) - , file(move(encryptedFile)) { - if(url.isEmpty() && file.has_value()) { - url = file->url; - } if (!mimeType.isValid()) mimeType = QMimeDatabase().mimeTypeForData(QByteArray()); } bool FileInfo::isValid() const { - return url.scheme() == "mxc" - && (url.authority() + url.path()).count('/') == 1; + const auto& u = url(); + return u.scheme() == "mxc" && (u.authority() + u.path()).count('/') == 1; +} + +QUrl FileInfo::url() const +{ + return getUrlFromSourceInfo(source); } QJsonObject Quotient::EventContent::toInfoJson(const FileInfo& info) @@ -75,7 +73,6 @@ QJsonObject Quotient::EventContent::toInfoJson(const FileInfo& info) infoJson.insert(QStringLiteral("size"), info.payloadSize); if (info.mimeType.isValid()) infoJson.insert(QStringLiteral("mimetype"), info.mimeType.name()); - //TODO add encryptedfile return infoJson; } @@ -83,17 +80,16 @@ ImageInfo::ImageInfo(const QFileInfo& fi, QSize imageSize) : FileInfo(fi), imageSize(imageSize) {} -ImageInfo::ImageInfo(const QUrl& mxcUrl, qint64 fileSize, const QMimeType& type, - QSize imageSize, Omittable encryptedFile, +ImageInfo::ImageInfo(FileSourceInfo sourceInfo, qint64 fileSize, + const QMimeType& type, QSize imageSize, const QString& originalFilename) - : FileInfo(mxcUrl, fileSize, type, move(encryptedFile), originalFilename) + : FileInfo(move(sourceInfo), fileSize, type, originalFilename) , imageSize(imageSize) {} -ImageInfo::ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, - Omittable encryptedFile, +ImageInfo::ImageInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, const QString& originalFilename) - : FileInfo(mxcUrl, infoJson, move(encryptedFile), originalFilename) + : FileInfo(move(sourceInfo), infoJson, originalFilename) , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) {} @@ -107,16 +103,20 @@ QJsonObject Quotient::EventContent::toInfoJson(const ImageInfo& info) return infoJson; } -Thumbnail::Thumbnail(const QJsonObject& infoJson, - Omittable encryptedFile) +Thumbnail::Thumbnail( + const QJsonObject& infoJson, + const Omittable& encryptedFileMetadata) : ImageInfo(QUrl(infoJson["thumbnail_url"_ls].toString()), - infoJson["thumbnail_info"_ls].toObject(), move(encryptedFile)) -{} + infoJson["thumbnail_info"_ls].toObject()) +{ + if (encryptedFileMetadata) + source = *encryptedFileMetadata; +} void Thumbnail::dumpTo(QJsonObject& infoJson) const { - if (url.isValid()) - infoJson.insert(QStringLiteral("thumbnail_url"), url.toString()); + if (url().isValid()) + fillJson(infoJson, { "thumbnail_url"_ls, "thumbnail_file"_ls }, source); if (!imageSize.isEmpty()) infoJson.insert(QStringLiteral("thumbnail_info"), toInfoJson(*this)); diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index bbd35618..23281876 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -6,14 +6,14 @@ // This file contains generic event content definitions, applicable to room // message events as well as other events (e.g., avatars). -#include "encryptedfile.h" +#include "filesourceinfo.h" #include "quotient_export.h" #include +#include #include #include #include -#include class QFileInfo; @@ -50,7 +50,7 @@ namespace EventContent { // A quick classes inheritance structure follows (the definitions are // spread across eventcontent.h and roommessageevent.h): - // UrlBasedContent : InfoT + url and thumbnail data + // UrlBasedContent : InfoT + thumbnail data // PlayableContent : + duration attribute // FileInfo // FileContent = UrlBasedContent @@ -89,34 +89,32 @@ namespace EventContent { //! //! \param fi a QFileInfo object referring to an existing file explicit FileInfo(const QFileInfo& fi); - explicit FileInfo(QUrl mxcUrl, qint64 payloadSize = -1, + explicit FileInfo(FileSourceInfo sourceInfo, qint64 payloadSize = -1, const QMimeType& mimeType = {}, - Omittable encryptedFile = none, QString originalFilename = {}); //! \brief Construct from a JSON `info` payload //! //! Make sure to pass the `info` subobject of content JSON, not the //! whole JSON content. - FileInfo(QUrl mxcUrl, const QJsonObject& infoJson, - Omittable encryptedFile, + FileInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, QString originalFilename = {}); bool isValid() const; + QUrl url() const; //! \brief Extract media id from the URL //! //! This can be used, e.g., to construct a QML-facing image:// //! URI as follows: //! \code "image://provider/" + info.mediaId() \endcode - QString mediaId() const { return url.authority() + url.path(); } + QString mediaId() const { return url().authority() + url().path(); } public: + FileSourceInfo source; QJsonObject originalInfoJson; QMimeType mimeType; - QUrl url; qint64 payloadSize = 0; QString originalName; - Omittable file = none; }; QUOTIENT_API QJsonObject toInfoJson(const FileInfo& info); @@ -126,12 +124,10 @@ namespace EventContent { public: ImageInfo() = default; explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); - explicit ImageInfo(const QUrl& mxcUrl, qint64 fileSize = -1, + explicit ImageInfo(FileSourceInfo sourceInfo, qint64 fileSize = -1, const QMimeType& type = {}, QSize imageSize = {}, - Omittable encryptedFile = none, const QString& originalFilename = {}); - ImageInfo(const QUrl& mxcUrl, const QJsonObject& infoJson, - Omittable encryptedFile, + ImageInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, const QString& originalFilename = {}); public: @@ -144,12 +140,13 @@ namespace EventContent { //! //! This class saves/loads a thumbnail to/from `info` subobject of //! the JSON representation of event content; namely, `info/thumbnail_url` - //! and `info/thumbnail_info` fields are used. + //! (or, in case of an encrypted thumbnail, `info/thumbnail_file`) and + //! `info/thumbnail_info` fields are used. class QUOTIENT_API Thumbnail : public ImageInfo { public: using ImageInfo::ImageInfo; Thumbnail(const QJsonObject& infoJson, - Omittable encryptedFile = none); + const Omittable& encryptedFile = none); //! \brief Add thumbnail information to the passed `info` JSON object void dumpTo(QJsonObject& infoJson) const; @@ -169,10 +166,10 @@ namespace EventContent { //! \brief A template class for content types with a URL and additional info //! - //! Types that derive from this class template take `url` and, - //! optionally, `filename` values from the top-level JSON object and - //! the rest of information from the `info` subobject, as defined by - //! the parameter type. + //! Types that derive from this class template take `url` (or, if the file + //! is encrypted, `file`) and, optionally, `filename` values from + //! the top-level JSON object and the rest of information from the `info` + //! subobject, as defined by the parameter type. //! \tparam InfoT base info class - FileInfo or ImageInfo template class UrlBasedContent : public TypedBase, public InfoT { @@ -181,10 +178,12 @@ namespace EventContent { explicit UrlBasedContent(const QJsonObject& json) : TypedBase(json) , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), - fromJson>(json["file"]), json["filename"].toString()) , thumbnail(FileInfo::originalInfoJson) { + const auto efmJson = json.value("file"_ls).toObject(); + if (!efmJson.isEmpty()) + InfoT::source = fromJson(efmJson); // Two small hacks on originalJson to expose mediaIds to QML originalJson.insert("mediaId", InfoT::mediaId()); originalJson.insert("thumbnailMediaId", thumbnail.mediaId()); @@ -204,11 +203,7 @@ namespace EventContent { void fillJson(QJsonObject& json) const override { - if (!InfoT::file.has_value()) { - json.insert("url", InfoT::url.toString()); - } else { - json.insert("file", Quotient::toJson(*InfoT::file)); - } + Quotient::fillJson(json, { "url"_ls, "file"_ls }, InfoT::source); if (!InfoT::originalName.isEmpty()) json.insert("filename", InfoT::originalName); auto infoJson = toInfoJson(*this); @@ -223,7 +218,7 @@ namespace EventContent { //! //! Available fields: //! - corresponding to the top-level JSON: - //! - url + //! - source (corresponding to `url` or `file` in JSON) //! - filename (extension to the spec) //! - corresponding to the `info` subobject: //! - payloadSize (`size` in JSON) @@ -241,12 +236,12 @@ namespace EventContent { //! //! Available fields: //! - corresponding to the top-level JSON: - //! - url + //! - source (corresponding to `url` or `file` in JSON) //! - filename //! - corresponding to the `info` subobject: //! - payloadSize (`size` in JSON) //! - mimeType (`mimetype` in JSON) - //! - thumbnail.url (`thumbnail_url` in JSON) + //! - thumbnail.source (`thumbnail_url` or `thumbnail_file` in JSON) //! - corresponding to the `info/thumbnail_info` subobject: //! - thumbnail.payloadSize //! - thumbnail.mimeType diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp new file mode 100644 index 00000000..a64c7da8 --- /dev/null +++ b/lib/events/filesourceinfo.cpp @@ -0,0 +1,181 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "filesourceinfo.h" + +#include "logging.h" + +#ifdef Quotient_E2EE_ENABLED +# include "e2ee/qolmutils.h" + +# include + +# include +#endif + +using namespace Quotient; + +QByteArray EncryptedFileMetadata::decryptFile(const QByteArray& ciphertext) const +{ +#ifdef Quotient_E2EE_ENABLED + auto _key = key.k; + const auto keyBytes = QByteArray::fromBase64( + _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); + const auto sha256 = + QByteArray::fromBase64(hashes["sha256"_ls].toLatin1()); + if (sha256 + != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { + qCWarning(E2EE) << "Hash verification failed for file"; + return {}; + } + { + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); + EVP_DecryptInit_ex( + ctx, EVP_aes_256_ctr(), nullptr, + reinterpret_cast(keyBytes.data()), + reinterpret_cast( + QByteArray::fromBase64(iv.toLatin1()).data())); + EVP_DecryptUpdate( + ctx, reinterpret_cast(plaintext.data()), &length, + reinterpret_cast(ciphertext.data()), + ciphertext.size()); + EVP_DecryptFinal_ex(ctx, + reinterpret_cast(plaintext.data()) + + length, + &length); + EVP_CIPHER_CTX_free(ctx); + return plaintext.left(ciphertext.size()); + } +#else + qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " + "cannot decrypt the file"; + return ciphertext; +#endif +} + +std::pair EncryptedFileMetadata::encryptFile( + const QByteArray& plainText) +{ +#ifdef Quotient_E2EE_ENABLED + QByteArray k = getRandom(32); + auto kBase64 = k.toBase64(); + QByteArray iv = getRandom(16); + JWK key = { "oct"_ls, + { "encrypt"_ls, "decrypt"_ls }, + "A256CTR"_ls, + QString(k.toBase64()) + .replace(u'/', u'_') + .replace(u'+', u'-') + .left(kBase64.indexOf('=')), + true }; + + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, + reinterpret_cast(k.data()), + reinterpret_cast(iv.data())); + const auto blockSize = EVP_CIPHER_CTX_block_size(ctx); + QByteArray cipherText(plainText.size() + blockSize - 1, '\0'); + EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), + &length, + reinterpret_cast(plainText.data()), + plainText.size()); + EVP_EncryptFinal_ex(ctx, + reinterpret_cast(cipherText.data()) + + length, + &length); + EVP_CIPHER_CTX_free(ctx); + + auto hash = QCryptographicHash::hash(cipherText, QCryptographicHash::Sha256) + .toBase64(); + auto ivBase64 = iv.toBase64(); + EncryptedFileMetadata efm = { {}, + key, + ivBase64.left(ivBase64.indexOf('=')), + { { QStringLiteral("sha256"), + hash.left(hash.indexOf('=')) } }, + "v2"_ls }; + return { efm, cipherText }; +#else + return {}; +#endif +} + +void JsonObjectConverter::dumpTo(QJsonObject& jo, + const EncryptedFileMetadata& pod) +{ + addParam<>(jo, QStringLiteral("url"), pod.url); + addParam<>(jo, QStringLiteral("key"), pod.key); + addParam<>(jo, QStringLiteral("iv"), pod.iv); + addParam<>(jo, QStringLiteral("hashes"), pod.hashes); + addParam<>(jo, QStringLiteral("v"), pod.v); +} + +void JsonObjectConverter::fillFrom(const QJsonObject& jo, + EncryptedFileMetadata& pod) +{ + fromJson(jo.value("url"_ls), pod.url); + fromJson(jo.value("key"_ls), pod.key); + fromJson(jo.value("iv"_ls), pod.iv); + fromJson(jo.value("hashes"_ls), pod.hashes); + fromJson(jo.value("v"_ls), pod.v); +} + +void JsonObjectConverter::dumpTo(QJsonObject& jo, const JWK& pod) +{ + addParam<>(jo, QStringLiteral("kty"), pod.kty); + addParam<>(jo, QStringLiteral("key_ops"), pod.keyOps); + addParam<>(jo, QStringLiteral("alg"), pod.alg); + addParam<>(jo, QStringLiteral("k"), pod.k); + addParam<>(jo, QStringLiteral("ext"), pod.ext); +} + +void JsonObjectConverter::fillFrom(const QJsonObject& jo, JWK& pod) +{ + fromJson(jo.value("kty"_ls), pod.kty); + fromJson(jo.value("key_ops"_ls), pod.keyOps); + fromJson(jo.value("alg"_ls), pod.alg); + fromJson(jo.value("k"_ls), pod.k); + fromJson(jo.value("ext"_ls), pod.ext); +} + +template +struct Overloads : FunctorTs... { + using FunctorTs::operator()...; +}; + +template +Overloads(FunctorTs&&...) -> Overloads; + +QUrl Quotient::getUrlFromSourceInfo(const FileSourceInfo& fsi) +{ + return std::visit(Overloads { [](const QUrl& url) { return url; }, + [](const EncryptedFileMetadata& efm) { + return efm.url; + } }, + fsi); +} + +void Quotient::setUrlInSourceInfo(FileSourceInfo& fsi, const QUrl& newUrl) +{ + std::visit(Overloads { [&newUrl](QUrl& url) { url = newUrl; }, + [&newUrl](EncryptedFileMetadata& efm) { + efm.url = newUrl; + } }, + fsi); +} + +void Quotient::fillJson(QJsonObject& jo, + const std::array& jsonKeys, + const FileSourceInfo& fsi) +{ + // NB: Keeping variant_size_v out of the function signature for readability. + // NB2: Can't use jsonKeys directly inside static_assert as its value is + // unknown so the compiler cannot ensure size() is constexpr (go figure...) + static_assert( + std::variant_size_v == decltype(jsonKeys) {}.size()); + jo.insert(jsonKeys[fsi.index()], toJson(fsi)); +} diff --git a/lib/events/filesourceinfo.h b/lib/events/filesourceinfo.h new file mode 100644 index 00000000..885601be --- /dev/null +++ b/lib/events/filesourceinfo.h @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2021 Carl Schwan +// +// SPDX-License-Identifier: LGPL-2.1-or-later + +#pragma once + +#include "converters.h" + +#include + +namespace Quotient { +/** + * JSON Web Key object as specified in + * https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes + * The only currently relevant member is `k`, the rest needs to be set to the defaults specified in the spec. + */ +struct JWK +{ + Q_GADGET + Q_PROPERTY(QString kty MEMBER kty CONSTANT) + Q_PROPERTY(QStringList keyOps MEMBER keyOps CONSTANT) + Q_PROPERTY(QString alg MEMBER alg CONSTANT) + Q_PROPERTY(QString k MEMBER k CONSTANT) + Q_PROPERTY(bool ext MEMBER ext CONSTANT) + +public: + QString kty; + QStringList keyOps; + QString alg; + QString k; + bool ext; +}; + +struct QUOTIENT_API EncryptedFileMetadata { + Q_GADGET + Q_PROPERTY(QUrl url MEMBER url CONSTANT) + Q_PROPERTY(JWK key MEMBER key CONSTANT) + Q_PROPERTY(QString iv MEMBER iv CONSTANT) + Q_PROPERTY(QHash hashes MEMBER hashes CONSTANT) + Q_PROPERTY(QString v MEMBER v CONSTANT) + +public: + QUrl url; + JWK key; + QString iv; + QHash hashes; + QString v; + + static std::pair encryptFile( + const QByteArray& plainText); + QByteArray decryptFile(const QByteArray& ciphertext) const; +}; + +template <> +struct QUOTIENT_API JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const EncryptedFileMetadata& pod); + static void fillFrom(const QJsonObject& jo, EncryptedFileMetadata& pod); +}; + +template <> +struct QUOTIENT_API JsonObjectConverter { + static void dumpTo(QJsonObject& jo, const JWK& pod); + static void fillFrom(const QJsonObject& jo, JWK& pod); +}; + +using FileSourceInfo = std::variant; + +QUOTIENT_API QUrl getUrlFromSourceInfo(const FileSourceInfo& fsi); + +QUOTIENT_API void setUrlInSourceInfo(FileSourceInfo& fsi, const QUrl& newUrl); + +// The way FileSourceInfo is stored in JSON requires an extra parameter so +// the original template is not applicable +template <> +void fillJson(QJsonObject&, const FileSourceInfo&) = delete; + +//! \brief Export FileSourceInfo to a JSON object +//! +//! Depending on what is stored inside FileSourceInfo, this function will insert +//! - a key-to-string pair where key is taken from jsonKeys[0] and the string +//! is the URL, if FileSourceInfo stores a QUrl; +//! - a key-to-object mapping where key is taken from jsonKeys[1] and the object +//! is the result of converting EncryptedFileMetadata to JSON, +//! if FileSourceInfo stores EncryptedFileMetadata +QUOTIENT_API void fillJson(QJsonObject& jo, + const std::array& jsonKeys, + const FileSourceInfo& fsi); + +} // namespace Quotient diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index c54b5801..af291696 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -26,10 +26,10 @@ public: const QSize& imageSize = {}, const QString& originalFilename = {}) : RoomAvatarEvent(EventContent::ImageContent { - mxcUrl, fileSize, mimeType, imageSize, none, originalFilename }) + mxcUrl, fileSize, mimeType, imageSize, originalFilename }) {} - QUrl url() const { return content().url; } + QUrl url() const { return content().url(); } }; REGISTER_EVENT_TYPE(RoomAvatarEvent) } // namespace Quotient diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index d9d3fbe0..2a6ae93c 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -148,21 +148,21 @@ TypedBase* contentFromFile(const QFileInfo& file, bool asGenericFile) auto mimeTypeName = mimeType.name(); if (mimeTypeName.startsWith("image/")) return new ImageContent(localUrl, file.size(), mimeType, - QImageReader(filePath).size(), none, + QImageReader(filePath).size(), file.fileName()); // duration can only be obtained asynchronously and can only be reliably // done by starting to play the file. Left for a future implementation. if (mimeTypeName.startsWith("video/")) return new VideoContent(localUrl, file.size(), mimeType, - QMediaResource(localUrl).resolution(), none, + QMediaResource(localUrl).resolution(), file.fileName()); if (mimeTypeName.startsWith("audio/")) - return new AudioContent(localUrl, file.size(), mimeType, none, + return new AudioContent(localUrl, file.size(), mimeType, file.fileName()); } - return new FileContent(localUrl, file.size(), mimeType, none, file.fileName()); + return new FileContent(localUrl, file.size(), mimeType, file.fileName()); } RoomMessageEvent::RoomMessageEvent(const QString& plainBody, diff --git a/lib/events/stickerevent.cpp b/lib/events/stickerevent.cpp index 628fd154..6d318f0e 100644 --- a/lib/events/stickerevent.cpp +++ b/lib/events/stickerevent.cpp @@ -22,5 +22,5 @@ const EventContent::ImageContent &StickerEvent::image() const QUrl StickerEvent::url() const { - return m_imageContent.url; + return m_imageContent.url(); } -- cgit v1.2.3 From c2d87291dbf8bd240e3e96138ec52aa5da22416b Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 26 May 2022 12:50:30 +0200 Subject: Move encryptFile/decryptFile out of EncryptedFileMetadata These are not operations on EncryptedFileMetadata but rather on a combination of EncryptedFileMetadata and ciphertext. If C++ had multimethods these could be bound to such a combination. --- lib/events/filesourceinfo.cpp | 11 ++++++----- lib/events/filesourceinfo.h | 9 +++++---- 2 files changed, 11 insertions(+), 9 deletions(-) (limited to 'lib/events') diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp index a64c7da8..43e8e44c 100644 --- a/lib/events/filesourceinfo.cpp +++ b/lib/events/filesourceinfo.cpp @@ -16,14 +16,15 @@ using namespace Quotient; -QByteArray EncryptedFileMetadata::decryptFile(const QByteArray& ciphertext) const +QByteArray Quotient::decryptFile(const QByteArray& ciphertext, + const EncryptedFileMetadata& metadata) { #ifdef Quotient_E2EE_ENABLED - auto _key = key.k; + auto _key = metadata.key.k; const auto keyBytes = QByteArray::fromBase64( _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); const auto sha256 = - QByteArray::fromBase64(hashes["sha256"_ls].toLatin1()); + QByteArray::fromBase64(metadata.hashes["sha256"_ls].toLatin1()); if (sha256 != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { qCWarning(E2EE) << "Hash verification failed for file"; @@ -37,7 +38,7 @@ QByteArray EncryptedFileMetadata::decryptFile(const QByteArray& ciphertext) cons ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(keyBytes.data()), reinterpret_cast( - QByteArray::fromBase64(iv.toLatin1()).data())); + QByteArray::fromBase64(metadata.iv.toLatin1()).data())); EVP_DecryptUpdate( ctx, reinterpret_cast(plaintext.data()), &length, reinterpret_cast(ciphertext.data()), @@ -56,7 +57,7 @@ QByteArray EncryptedFileMetadata::decryptFile(const QByteArray& ciphertext) cons #endif } -std::pair EncryptedFileMetadata::encryptFile( +std::pair Quotient::encryptFile( const QByteArray& plainText) { #ifdef Quotient_E2EE_ENABLED diff --git a/lib/events/filesourceinfo.h b/lib/events/filesourceinfo.h index 885601be..8f7e3cbe 100644 --- a/lib/events/filesourceinfo.h +++ b/lib/events/filesourceinfo.h @@ -45,12 +45,13 @@ public: QString iv; QHash hashes; QString v; - - static std::pair encryptFile( - const QByteArray& plainText); - QByteArray decryptFile(const QByteArray& ciphertext) const; }; +QUOTIENT_API std::pair encryptFile( + const QByteArray& plainText); +QUOTIENT_API QByteArray decryptFile(const QByteArray& ciphertext, + const EncryptedFileMetadata& metadata); + template <> struct QUOTIENT_API JsonObjectConverter { static void dumpTo(QJsonObject& jo, const EncryptedFileMetadata& pod); -- cgit v1.2.3 From c2e9256b1c334bdadcc208429084cbc83496fb4b Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 26 May 2022 12:57:23 +0200 Subject: Cleanup and address Sonar warnings --- lib/events/eventcontent.cpp | 9 ++++---- lib/events/eventcontent.h | 6 +++--- lib/events/filesourceinfo.cpp | 49 ++++++++++++++++++++----------------------- 3 files changed, 30 insertions(+), 34 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 36b647cb..8db3b7e3 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -103,14 +103,13 @@ QJsonObject Quotient::EventContent::toInfoJson(const ImageInfo& info) return infoJson; } -Thumbnail::Thumbnail( - const QJsonObject& infoJson, - const Omittable& encryptedFileMetadata) +Thumbnail::Thumbnail(const QJsonObject& infoJson, + const Omittable& efm) : ImageInfo(QUrl(infoJson["thumbnail_url"_ls].toString()), infoJson["thumbnail_info"_ls].toObject()) { - if (encryptedFileMetadata) - source = *encryptedFileMetadata; + if (efm) + source = *efm; } void Thumbnail::dumpTo(QJsonObject& infoJson) const diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 23281876..ea240122 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -146,7 +146,7 @@ namespace EventContent { public: using ImageInfo::ImageInfo; Thumbnail(const QJsonObject& infoJson, - const Omittable& encryptedFile = none); + const Omittable& efm = none); //! \brief Add thumbnail information to the passed `info` JSON object void dumpTo(QJsonObject& infoJson) const; @@ -181,8 +181,8 @@ namespace EventContent { json["filename"].toString()) , thumbnail(FileInfo::originalInfoJson) { - const auto efmJson = json.value("file"_ls).toObject(); - if (!efmJson.isEmpty()) + if (const auto efmJson = json.value("file"_ls).toObject(); + !efmJson.isEmpty()) InfoT::source = fromJson(efmJson); // Two small hacks on originalJson to expose mediaIds to QML originalJson.insert("mediaId", InfoT::mediaId()); diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp index 43e8e44c..11f93d80 100644 --- a/lib/events/filesourceinfo.cpp +++ b/lib/events/filesourceinfo.cpp @@ -20,36 +20,33 @@ QByteArray Quotient::decryptFile(const QByteArray& ciphertext, const EncryptedFileMetadata& metadata) { #ifdef Quotient_E2EE_ENABLED - auto _key = metadata.key.k; - const auto keyBytes = QByteArray::fromBase64( - _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); - const auto sha256 = - QByteArray::fromBase64(metadata.hashes["sha256"_ls].toLatin1()); - if (sha256 + if (QByteArray::fromBase64(metadata.hashes["sha256"_ls].toLatin1()) != QCryptographicHash::hash(ciphertext, QCryptographicHash::Sha256)) { qCWarning(E2EE) << "Hash verification failed for file"; return {}; } - { - int length; - auto* ctx = EVP_CIPHER_CTX_new(); - QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); - EVP_DecryptInit_ex( - ctx, EVP_aes_256_ctr(), nullptr, - reinterpret_cast(keyBytes.data()), - reinterpret_cast( - QByteArray::fromBase64(metadata.iv.toLatin1()).data())); - EVP_DecryptUpdate( - ctx, reinterpret_cast(plaintext.data()), &length, - reinterpret_cast(ciphertext.data()), - ciphertext.size()); - EVP_DecryptFinal_ex(ctx, - reinterpret_cast(plaintext.data()) - + length, - &length); - EVP_CIPHER_CTX_free(ctx); - return plaintext.left(ciphertext.size()); - } + + auto _key = metadata.key.k; + const auto keyBytes = QByteArray::fromBase64( + _key.replace(u'_', u'/').replace(u'-', u'+').toLatin1()); + int length; + auto* ctx = EVP_CIPHER_CTX_new(); + QByteArray plaintext(ciphertext.size() + EVP_MAX_BLOCK_LENGTH - 1, '\0'); + EVP_DecryptInit_ex( + ctx, EVP_aes_256_ctr(), nullptr, + reinterpret_cast(keyBytes.data()), + reinterpret_cast( + QByteArray::fromBase64(metadata.iv.toLatin1()).data())); + EVP_DecryptUpdate(ctx, reinterpret_cast(plaintext.data()), + &length, + reinterpret_cast(ciphertext.data()), + ciphertext.size()); + EVP_DecryptFinal_ex(ctx, + reinterpret_cast(plaintext.data()) + + length, + &length); + EVP_CIPHER_CTX_free(ctx); + return plaintext.left(ciphertext.size()); #else qWarning(MAIN) << "This build of libQuotient doesn't support E2EE, " "cannot decrypt the file"; -- cgit v1.2.3 From 0f8335a32debc4c61d9fc9875c79c0ba6ba05357 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 27 May 2022 19:09:26 +0200 Subject: Move some Meg/Olm session logic from Room::Private to Connection::Private Functions (Room::Private::)createOlmSession, payloadForUserDevice and sendRoomKeyToDevices don't have a lot to do with the given Room object but deal with quite a few things stored in Connection. This commit moves them to Connection::Private, exposing sendSessionKeyToDevices (the new name for sendRoomKeyToDevices) in Connection so that Room could call it from Room::P::sendMegolmSession(). While moving these over, a few additional things were adjusted: - more functions marked as const - a few functions could be moved now from Connection to Connection::Private - false slots in Connection (such as picklingMode) are moved out of the slots block - keys.yml in Matrix CS API definitions has been adjusted to match the real structure of `/claim` response (see quotient-im/matrix-spec repo); csapi/keys.h has been regenerated accordingly. --- lib/events/roomkeyevent.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 2bda3086..3093db41 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -12,7 +12,9 @@ public: DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) explicit RoomKeyEvent(const QJsonObject& obj); - explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString &sessionId, const QString& sessionKey, const QString& senderId); + explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, + const QString& sessionId, const QString& sessionKey, + const QString& senderId); QString algorithm() const { return contentPart("algorithm"_ls); } QString roomId() const { return contentPart(RoomIdKeyL); } -- cgit v1.2.3 From 5a63f8a18645d612decdcc853335df0682c41d03 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 18 Jun 2022 21:29:27 +0200 Subject: Drop make_array(); use std::to_array() where needed make_array() has been introduced to cover for shortcomings on macOS and Windows. These shortcomings are no more there, so we can just use the standardrlibrary. --- lib/events/encryptionevent.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 6e994cd4..eb15f38e 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -9,9 +9,7 @@ #include namespace Quotient { -static const std::array encryptionStrings = { - { MegolmV1AesSha2AlgoKey } -}; +static constexpr std::array encryptionStrings { MegolmV1AesSha2AlgoKey }; template <> struct JsonConverter { -- cgit v1.2.3 From 7ef84728ab3744192583eb587a4585c576f5a176 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 18 Jun 2022 21:39:42 +0200 Subject: Move C++-only macros to util.h This pertains to QUO_IMPLICIT and DECL_DEPRECATED_ENUMERATOR - both can be used with no connection to Qt meta-type system (which is what quotient_common.h is for). --- lib/events/encryptionevent.cpp | 2 -- lib/events/encryptionevent.h | 1 - 2 files changed, 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index eb15f38e..1654d6f3 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -6,8 +6,6 @@ #include "e2ee/e2ee.h" -#include - namespace Quotient { static constexpr std::array encryptionStrings { MegolmV1AesSha2AlgoKey }; diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 5b5420ec..c73e5598 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -5,7 +5,6 @@ #pragma once #include "stateevent.h" -#include "quotient_common.h" namespace Quotient { class QUOTIENT_API EncryptionEventContent { -- cgit v1.2.3 From 34ff85b715b377c4b2a8e30b1af8327aa7928e36 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 18 Jun 2022 10:35:48 +0200 Subject: Move out Overloads to util.h ...instead of tucking the template in filesourceinfo.cpp where it surely will be forgotten. --- lib/events/filesourceinfo.cpp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) (limited to 'lib/events') diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp index 11f93d80..e8b6794b 100644 --- a/lib/events/filesourceinfo.cpp +++ b/lib/events/filesourceinfo.cpp @@ -5,6 +5,7 @@ #include "filesourceinfo.h" #include "logging.h" +#include "util.h" #ifdef Quotient_E2EE_ENABLED # include "e2ee/qolmutils.h" @@ -140,14 +141,6 @@ void JsonObjectConverter::fillFrom(const QJsonObject& jo, JWK& pod) fromJson(jo.value("ext"_ls), pod.ext); } -template -struct Overloads : FunctorTs... { - using FunctorTs::operator()...; -}; - -template -Overloads(FunctorTs&&...) -> Overloads; - QUrl Quotient::getUrlFromSourceInfo(const FileSourceInfo& fsi) { return std::visit(Overloads { [](const QUrl& url) { return url; }, -- cgit v1.2.3 From 1fa81ac5dc9259b7368e0487e0424c76bc87053e Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 21 Jun 2022 14:42:59 +0200 Subject: Fix a few clang-tidy/GCC warnings --- lib/events/accountdataevents.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index ec2f64e3..24c3353c 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -32,7 +32,7 @@ struct JsonObjectConverter { if (orderJv.isDouble()) rec.order = fromJson(orderJv); if (orderJv.isString()) { - bool ok; + bool ok = false; rec.order = orderJv.toString().toFloat(&ok); if (!ok) rec.order = none; -- cgit v1.2.3 From 6a2cec476b72d44ecf1cd05e47724d325a46f246 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Jun 2022 10:17:26 +0200 Subject: Address a few more Sonar warnings --- lib/events/eventcontent.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index ea240122..1e2f3615 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -36,6 +36,10 @@ namespace EventContent { public: QJsonObject originalJson; + // You can't assign those classes + Base& operator=(const Base&) = delete; + Base& operator=(Base&&) = delete; + protected: Base(const Base&) = default; Base(Base&&) = default; @@ -145,8 +149,8 @@ namespace EventContent { class QUOTIENT_API Thumbnail : public ImageInfo { public: using ImageInfo::ImageInfo; - Thumbnail(const QJsonObject& infoJson, - const Omittable& efm = none); + explicit Thumbnail(const QJsonObject& infoJson, + const Omittable& efm = none); //! \brief Add thumbnail information to the passed `info` JSON object void dumpTo(QJsonObject& infoJson) const; -- cgit v1.2.3 From 6a7e4f883ec22ef26c1d10ba1544b0afd1a0f4d2 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Jun 2022 20:43:04 +0200 Subject: Streamline RoomPowerLevelsEvent backoffice code Also: leave a link at the place in the spec with power level defaults to make it clear they are not invented out of thin air. --- lib/events/roompowerlevelsevent.cpp | 38 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 26 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roompowerlevelsevent.cpp b/lib/events/roompowerlevelsevent.cpp index 84a31d55..d9bd010b 100644 --- a/lib/events/roompowerlevelsevent.cpp +++ b/lib/events/roompowerlevelsevent.cpp @@ -5,6 +5,8 @@ using namespace Quotient; +// The default values used below are defined in +// https://spec.matrix.org/v1.3/client-server-api/#mroompower_levels PowerLevelsEventContent::PowerLevelsEventContent(const QJsonObject& json) : invite(json["invite"_ls].toInt(50)), kick(json["kick"_ls].toInt(50)), @@ -16,8 +18,7 @@ PowerLevelsEventContent::PowerLevelsEventContent(const QJsonObject& json) : users(fromJson>(json["users"_ls])), usersDefault(json["users_default"_ls].toInt(0)), notifications(Notifications{json["notifications"_ls].toObject()["room"_ls].toInt(50)}) -{ -} +{} QJsonObject PowerLevelsEventContent::toJson() const { @@ -36,32 +37,17 @@ QJsonObject PowerLevelsEventContent::toJson() const return o; } -int RoomPowerLevelsEvent::powerLevelForEvent(const QString &eventId) const { - auto e = events(); - - if (e.contains(eventId)) { - return e[eventId]; - } - - return eventsDefault(); +int RoomPowerLevelsEvent::powerLevelForEvent(const QString& eventId) const +{ + return events().value(eventId, eventsDefault()); } -int RoomPowerLevelsEvent::powerLevelForState(const QString &eventId) const { - auto e = events(); - - if (e.contains(eventId)) { - return e[eventId]; - } - - return stateDefault(); +int RoomPowerLevelsEvent::powerLevelForState(const QString& eventId) const +{ + return events().value(eventId, stateDefault()); } -int RoomPowerLevelsEvent::powerLevelForUser(const QString &userId) const { - auto u = users(); - - if (u.contains(userId)) { - return u[userId]; - } - - return usersDefault(); +int RoomPowerLevelsEvent::powerLevelForUser(const QString& userId) const +{ + return users().value(userId, usersDefault()); } -- cgit v1.2.3 From 19746de7426aeb67eb90e8c48448356691e270b0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 9 Jun 2022 10:19:14 +0200 Subject: Use QUO_CONTENT_GETTER In keyverificationevent.*, this massively shortens repetitive getter definitions; the remaining few non-trivial ones are moved to keyverificationevent.h, dropping the respective .cpp file and therefore the dedicated translation unit. In roomkeyevent.h, it's just shorter. --- lib/events/keyverificationevent.cpp | 164 ------------------------------------ lib/events/keyverificationevent.h | 80 +++++++++++------- lib/events/roomkeyevent.h | 6 +- 3 files changed, 54 insertions(+), 196 deletions(-) delete mode 100644 lib/events/keyverificationevent.cpp (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.cpp b/lib/events/keyverificationevent.cpp deleted file mode 100644 index 4803955d..00000000 --- a/lib/events/keyverificationevent.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// SPDX-FileCopyrightText: 2021 Carl Schwan -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "keyverificationevent.h" - -using namespace Quotient; - -KeyVerificationRequestEvent::KeyVerificationRequestEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationRequestEvent::fromDevice() const -{ - return contentPart("from_device"_ls); -} - -QString KeyVerificationRequestEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QStringList KeyVerificationRequestEvent::methods() const -{ - return contentPart("methods"_ls); -} - -uint64_t KeyVerificationRequestEvent::timestamp() const -{ - return contentPart("timestamp"_ls); -} - -KeyVerificationStartEvent::KeyVerificationStartEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationStartEvent::fromDevice() const -{ - return contentPart("from_device"_ls); -} - -QString KeyVerificationStartEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QString KeyVerificationStartEvent::method() const -{ - return contentPart("method"_ls); -} - -Omittable KeyVerificationStartEvent::nextMethod() const -{ - return contentPart>("method_ls"); -} - -QStringList KeyVerificationStartEvent::keyAgreementProtocols() const -{ - Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - return contentPart("key_agreement_protocols"_ls); -} - -QStringList KeyVerificationStartEvent::hashes() const -{ - Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - return contentPart("hashes"_ls); - -} - -QStringList KeyVerificationStartEvent::messageAuthenticationCodes() const -{ - Q_ASSERT(method() == QStringLiteral("m.sas.v1")); - return contentPart("message_authentication_codes"_ls); -} - -QString KeyVerificationStartEvent::shortAuthenticationString() const -{ - return contentPart("short_authentification_string"_ls); -} - -KeyVerificationAcceptEvent::KeyVerificationAcceptEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationAcceptEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QString KeyVerificationAcceptEvent::method() const -{ - return contentPart("method"_ls); -} - -QString KeyVerificationAcceptEvent::keyAgreementProtocol() const -{ - return contentPart("key_agreement_protocol"_ls); -} - -QString KeyVerificationAcceptEvent::hashData() const -{ - return contentPart("hash"_ls); -} - -QStringList KeyVerificationAcceptEvent::shortAuthenticationString() const -{ - return contentPart("short_authentification_string"_ls); -} - -QString KeyVerificationAcceptEvent::commitement() const -{ - return contentPart("commitment"_ls); -} - -KeyVerificationCancelEvent::KeyVerificationCancelEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationCancelEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QString KeyVerificationCancelEvent::reason() const -{ - return contentPart("reason"_ls); -} - -QString KeyVerificationCancelEvent::code() const -{ - return contentPart("code"_ls); -} - -KeyVerificationKeyEvent::KeyVerificationKeyEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationKeyEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QString KeyVerificationKeyEvent::key() const -{ - return contentPart("key"_ls); -} - -KeyVerificationMacEvent::KeyVerificationMacEvent(const QJsonObject &obj) - : Event(typeId(), obj) -{} - -QString KeyVerificationMacEvent::transactionId() const -{ - return contentPart("transaction_id"_ls); -} - -QString KeyVerificationMacEvent::keys() const -{ - return contentPart("keys"_ls); -} - -QHash KeyVerificationMacEvent::mac() const -{ - return contentPart>("mac"_ls); -} diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 497e56a2..78457e0c 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -14,20 +14,20 @@ public: explicit KeyVerificationRequestEvent(const QJsonObject& obj); /// The device ID which is initiating the request. - QString fromDevice() const; + QUO_CONTENT_GETTER(QString, fromDevice) /// An opaque identifier for the verification request. Must /// be unique with respect to the devices involved. - QString transactionId() const; + QUO_CONTENT_GETTER(QString, transactionId) /// The verification methods supported by the sender. - QStringList methods() const; + QUO_CONTENT_GETTER(QStringList, methods) /// The POSIX timestamp in milliseconds for when the request was /// made. If the request is in the future by more than 5 minutes or /// more than 10 minutes in the past, the message should be ignored /// by the receiver. - uint64_t timestamp() const; + QUO_CONTENT_GETTER(uint64_t, timestamp) }; REGISTER_EVENT_TYPE(KeyVerificationRequestEvent) @@ -39,36 +39,52 @@ public: explicit KeyVerificationStartEvent(const QJsonObject &obj); /// The device ID which is initiating the process. - QString fromDevice() const; + QUO_CONTENT_GETTER(QString, fromDevice) /// An opaque identifier for the verification request. Must /// be unique with respect to the devices involved. - QString transactionId() const; + QUO_CONTENT_GETTER(QString, transactionId) /// The verification method to use. - QString method() const; + QUO_CONTENT_GETTER(QString, method) /// Optional method to use to verify the other user's key with. - Omittable nextMethod() const; + QUO_CONTENT_GETTER(Omittable, nextMethod) // SAS.V1 methods /// The key agreement protocols the sending device understands. /// \note Only exist if method is m.sas.v1 - QStringList keyAgreementProtocols() const; + QStringList keyAgreementProtocols() const + { + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + return contentPart("key_agreement_protocols"_ls); + } /// The hash methods the sending device understands. /// \note Only exist if method is m.sas.v1 - QStringList hashes() const; + QStringList hashes() const + { + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + return contentPart("hashes"_ls); + } /// The message authentication codes that the sending device understands. /// \note Only exist if method is m.sas.v1 - QStringList messageAuthenticationCodes() const; + QStringList messageAuthenticationCodes() const + { + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + return contentPart("message_authentication_codes"_ls); + } /// The SAS methods the sending device (and the sending device's /// user) understands. /// \note Only exist if method is m.sas.v1 - QString shortAuthenticationString() const; + QString shortAuthenticationString() const + { + Q_ASSERT(method() == QStringLiteral("m.sas.v1")); + return contentPart("short_authentification_string"_ls); + } }; REGISTER_EVENT_TYPE(KeyVerificationStartEvent) @@ -81,30 +97,33 @@ public: explicit KeyVerificationAcceptEvent(const QJsonObject& obj); /// An opaque identifier for the verification process. - QString transactionId() const; + QUO_CONTENT_GETTER(QString, transactionId) /// The verification method to use. Must be 'm.sas.v1'. - QString method() const; + QUO_CONTENT_GETTER(QString, method) /// The key agreement protocol the device is choosing to use, out of /// the options in the m.key.verification.start message. - QString keyAgreementProtocol() const; + QUO_CONTENT_GETTER(QString, keyAgreementProtocol) /// The hash method the device is choosing to use, out of the /// options in the m.key.verification.start message. - QString hashData() const; + QString hashData() const + { + return contentPart("hash"_ls); + } /// The message authentication code the device is choosing to use, out /// of the options in the m.key.verification.start message. - QString messageAuthenticationCode() const; + QUO_CONTENT_GETTER(QString, messageAuthenticationCode) /// The SAS methods both devices involved in the verification process understand. - QStringList shortAuthenticationString() const; + QUO_CONTENT_GETTER(QStringList, shortAuthenticationString) /// The hash (encoded as unpadded base64) of the concatenation of the /// device's ephemeral public key (encoded as unpadded base64) and the /// canonical JSON representation of the m.key.verification.start message. - QString commitement() const; + QUO_CONTENT_GETTER(QString, commitment) }; REGISTER_EVENT_TYPE(KeyVerificationAcceptEvent) @@ -115,14 +134,14 @@ public: explicit KeyVerificationCancelEvent(const QJsonObject &obj); /// An opaque identifier for the verification process. - QString transactionId() const; + QUO_CONTENT_GETTER(QString, transactionId) /// A human readable description of the code. The client should only /// rely on this string if it does not understand the code. - QString reason() const; + QUO_CONTENT_GETTER(QString, reason) /// The error code for why the process/request was cancelled by the user. - QString code() const; + QUO_CONTENT_GETTER(QString, code) }; REGISTER_EVENT_TYPE(KeyVerificationCancelEvent) @@ -134,11 +153,11 @@ public: explicit KeyVerificationKeyEvent(const QJsonObject &obj); - /// An opaque identifier for the verification process. - QString transactionId() const; + /// An opaque identifier for the verification process. + QUO_CONTENT_GETTER(QString, transactionId) /// The device's ephemeral public key, encoded as unpadded base64. - QString key() const; + QUO_CONTENT_GETTER(QString, key) }; REGISTER_EVENT_TYPE(KeyVerificationKeyEvent) @@ -149,13 +168,16 @@ public: explicit KeyVerificationMacEvent(const QJsonObject &obj); - /// An opaque identifier for the verification process. - QString transactionId() const; + /// An opaque identifier for the verification process. + QUO_CONTENT_GETTER(QString, transactionId) /// The device's ephemeral public key, encoded as unpadded base64. - QString keys() const; + QUO_CONTENT_GETTER(QString, keys) - QHash mac() const; + QHash mac() const + { + return contentPart>("mac"_ls); + } }; REGISTER_EVENT_TYPE(KeyVerificationMacEvent) } // namespace Quotient diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 3093db41..9eb2854b 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -16,9 +16,9 @@ public: const QString& sessionId, const QString& sessionKey, const QString& senderId); - QString algorithm() const { return contentPart("algorithm"_ls); } - QString roomId() const { return contentPart(RoomIdKeyL); } - QString sessionId() const { return contentPart("session_id"_ls); } + QUO_CONTENT_GETTER(QString, algorithm) + QUO_CONTENT_GETTER(QString, roomId) + QUO_CONTENT_GETTER(QString, sessionId) QByteArray sessionKey() const { return contentPart("session_key"_ls).toLatin1(); -- cgit v1.2.3 From 143ac38aabab90b40fbe73b489b91fb159e66b6b Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 23 Jun 2022 08:34:53 +0200 Subject: Streamline Room::P::shouldRotateMegolmSession() Now there's only 1 instead of 5 lookups of the same EncryptionEvent, and the code is shorter. --- lib/events/encryptionevent.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index c73e5598..945b17e7 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -52,6 +52,8 @@ public: QString algorithm() const { return content().algorithm; } int rotationPeriodMs() const { return content().rotationPeriodMs; } int rotationPeriodMsgs() const { return content().rotationPeriodMsgs; } + + bool useEncryption() const { return !algorithm().isEmpty(); } }; REGISTER_EVENT_TYPE(EncryptionEvent) } // namespace Quotient -- cgit v1.2.3 From 8580043a64941e1c1f132737e4b50280ac17812a Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 24 Jun 2022 23:11:20 +0200 Subject: Make EventContent::Base() move constructor noexcept --- lib/events/eventcontent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 1e2f3615..7611d077 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -42,7 +42,7 @@ namespace EventContent { protected: Base(const Base&) = default; - Base(Base&&) = default; + Base(Base&&) noexcept = default; virtual void fillJson(QJsonObject&) const = 0; }; -- cgit v1.2.3 From bc8e01df4286f5f8ff9103fbebad801f355db689 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 3 Jul 2022 22:14:13 +0200 Subject: Shorten switchOnType, function_traits and connect* ...thanks to C++20 awesomeness. A notable change is that wrap_in_function() (and respectively function_traits<>::function_type) and fn_return_t alias are gone. The former are no more needed because connectUntil/connectSingleShot no more use std::function. The latter has been relatively underused and with the optimisation of switchOnType hereby, could be completely replaced with std::invoke_result_t. Rewriting connect* functions using constexpr and auto parameters made the implementation 30% more compact and much easier to understand (though still with a couple of - now thoroughly commented - tricky places). Dropping std::function<> from it may also bring some (quite modest, likely) performance benefits. --- lib/events/event.h | 64 ++++++++++++++++++------------------------------------ 1 file changed, 21 insertions(+), 43 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index ec21c6aa..a966e613 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -341,56 +341,34 @@ inline auto eventCast(const BasePtrT& eptr) : nullptr; } -// A trivial generic catch-all "switch" -template -inline auto switchOnType(const BaseEventT& event, FnT&& fn) - -> decltype(fn(event)) -{ - return fn(event); -} - namespace _impl { - // Using bool instead of auto below because auto apparently upsets MSVC - template - constexpr bool needs_downcast = - std::is_base_of_v>> - && !std::is_same_v>>; -} - -// A trivial type-specific "switch" for a void function -template -inline auto switchOnType(const BaseT& event, FnT&& fn) - -> std::enable_if_t<_impl::needs_downcast - && std::is_void_v>> -{ - using event_type = fn_arg_t; - if (is>(event)) - fn(static_cast(event)); + template + concept Invocable_With_Downcast = + std::derived_from>, BaseT>; } -// A trivial type-specific "switch" for non-void functions with an optional -// default value; non-voidness is guarded by defaultValue type -template -inline auto switchOnType(const BaseT& event, FnT&& fn, - fn_return_t&& defaultValue = {}) - -> std::enable_if_t<_impl::needs_downcast, fn_return_t> +template +inline auto switchOnType(const BaseT& event, TailT&& tail) { - using event_type = fn_arg_t; - if (is>(event)) - return fn(static_cast(event)); - return std::move(defaultValue); + if constexpr (std::is_invocable_v) { + return tail(event); + } else if constexpr (_impl::Invocable_With_Downcast) { + using event_type = fn_arg_t; + if (is>(event)) + return tail(static_cast(event)); + return std::invoke_result_t(); // Default-constructed + } else { // Treat it as a value to return + return std::forward(tail); + } } -// A switch for a chain of 2 or more functions -template -inline std::common_type_t, fn_return_t> -switchOnType(const BaseT& event, FnT1&& fn1, FnT2&& fn2, FnTs&&... fns) +template +inline auto switchOnType(const BaseT& event, FnT1&& fn1, FnTs&&... fns) { using event_type1 = fn_arg_t; if (is>(event)) - return fn1(static_cast(event)); - return switchOnType(event, std::forward(fn2), - std::forward(fns)...); + return fn1(static_cast(event)); + return switchOnType(event, std::forward(fns)...); } template @@ -405,8 +383,8 @@ inline auto visit(const BaseT& event, FnTs&&... fns) // TODO: replace with ranges::for_each once all standard libraries have it template inline auto visitEach(RangeT&& events, FnTs&&... fns) - -> std::enable_if_t(fns)...))>> + requires std::is_void_v< + decltype(switchOnType(**begin(events), std::forward(fns)...))> { for (auto&& evtPtr: events) switchOnType(*evtPtr, std::forward(fns)...); -- cgit v1.2.3 From 64948b6840032b04ef00bfe207baa29dd445d141 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 7 Jul 2022 18:32:48 +0200 Subject: Avoid std::derived_from and std::bind_front Apple Clang doesn't have those yet. --- lib/events/event.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index a966e613..05eb51e9 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -344,7 +344,7 @@ inline auto eventCast(const BasePtrT& eptr) namespace _impl { template concept Invocable_With_Downcast = - std::derived_from>, BaseT>; + std::is_base_of_v>>; } template -- cgit v1.2.3 From 2245a44aca8d51e331cf1211ff6e2b38c57e5246 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 8 Jun 2022 14:26:30 +0200 Subject: Pack up StickerEvent in the header file Dropping yet another translation unit. --- lib/events/stickerevent.cpp | 26 -------------------------- lib/events/stickerevent.h | 19 +++++++++++++++---- 2 files changed, 15 insertions(+), 30 deletions(-) delete mode 100644 lib/events/stickerevent.cpp (limited to 'lib/events') diff --git a/lib/events/stickerevent.cpp b/lib/events/stickerevent.cpp deleted file mode 100644 index 6d318f0e..00000000 --- a/lib/events/stickerevent.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// SDPX-FileCopyrightText: 2020 Carl Schwan -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "stickerevent.h" - -using namespace Quotient; - -StickerEvent::StickerEvent(const QJsonObject &obj) - : RoomEvent(typeId(), obj) - , m_imageContent(EventContent::ImageContent(obj["content"_ls].toObject())) -{} - -QString StickerEvent::body() const -{ - return contentPart("body"_ls); -} - -const EventContent::ImageContent &StickerEvent::image() const -{ - return m_imageContent; -} - -QUrl StickerEvent::url() const -{ - return m_imageContent.url(); -} diff --git a/lib/events/stickerevent.h b/lib/events/stickerevent.h index 0957dca3..e378422d 100644 --- a/lib/events/stickerevent.h +++ b/lib/events/stickerevent.h @@ -16,21 +16,32 @@ class QUOTIENT_API StickerEvent : public RoomEvent public: DEFINE_EVENT_TYPEID("m.sticker", StickerEvent) - explicit StickerEvent(const QJsonObject &obj); + explicit StickerEvent(const QJsonObject& obj) + : RoomEvent(TypeId, obj) + , m_imageContent( + EventContent::ImageContent(obj["content"_ls].toObject())) + {} /// \brief A textual representation or associated description of the /// sticker image. /// /// This could be the alt text of the original image, or a message to /// accompany and further describe the sticker. - QString body() const; + QUO_CONTENT_GETTER(QString, body) /// \brief Metadata about the image referred to in url including a /// thumbnail representation. - const EventContent::ImageContent &image() const; + const EventContent::ImageContent& image() const + { + return m_imageContent; + } /// \brief The URL to the sticker image. This must be a valid mxc:// URI. - QUrl url() const; + QUrl url() const + { + return m_imageContent.url(); + } + private: EventContent::ImageContent m_imageContent; }; -- cgit v1.2.3 From 607489a2e6a3e3238eac0178f5c7bbc70f178f46 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Jun 2022 20:43:50 +0200 Subject: Fix deprecation messages [skip ci] --- lib/events/eventrelation.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventrelation.h b/lib/events/eventrelation.h index e445ee42..2a841cf1 100644 --- a/lib/events/eventrelation.h +++ b/lib/events/eventrelation.h @@ -34,11 +34,11 @@ struct QUOTIENT_API EventRelation { return { ReplacementType, std::move(eventId) }; } - [[deprecated("Use ReplyRelation variable instead")]] + [[deprecated("Use ReplyType variable instead")]] static constexpr auto Reply() { return ReplyType; } - [[deprecated("Use AnnotationRelation variable instead")]] // + [[deprecated("Use AnnotationType variable instead")]] // static constexpr auto Annotation() { return AnnotationType; } - [[deprecated("Use ReplacementRelation variable instead")]] // + [[deprecated("Use ReplacementType variable instead")]] // static constexpr auto Replacement() { return ReplacementType; } }; -- cgit v1.2.3 From ab2d78de6a9d33e1470ae9db2ed6ed9565c817e5 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 11 Jul 2022 10:08:44 +0200 Subject: fromJson()/toJson() refactoring fromJson() is generalised to accept any JSON-like type while passing QJsonObject to JsonConverter<>::load (instead of doLoad). This allows to (still) rely on JsonConverter<> as a customisation point while providing an opportunity to overload fromJson for custom types in a pointed way (specifically, by providing the overload for `fromJson(const QJsonObject&)`), instead of having to go with full-blown JsonConverter<> specialisation. This will be used in a further commit to simplify ReceiptEvent definition. Using if constexpr in combination with constraints (`requires()`) - the first such case in Quotient codebase - allowed to put the entire logic in a single JsonConverter<>::load() body instead of having a facility JsonExporter<> class for SFINAE. Aside from that, fromJson is entirely dropped because it's not supposed to be used that way (it's no-op after all); reflecting that, Event::unsignedPart() and Event::contentPart() no more default to QJsonValue as the expected return type, you have to explicitly provide the type instead (and as one can see from the changes in the commit, it's actually better that way since it's better to validate the value inside JSON - e.g. check QString or QJsonObject for emptiness - than the QJsonValue envelope which may still wrap an empty value). toJson() is also generalised, replacing 3 functions with one that has a constexpr if to discern between two kinds of types. --- lib/events/encryptedevent.cpp | 10 ++++++---- lib/events/event.h | 4 ++-- lib/events/roomevent.cpp | 6 +++--- lib/events/stateevent.cpp | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index c97ccc16..ec00ad4c 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -49,14 +49,16 @@ RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const eventObject["event_id"] = id(); eventObject["sender"] = senderId(); eventObject["origin_server_ts"] = originTimestamp().toMSecsSinceEpoch(); - if (const auto relatesToJson = contentPart("m.relates_to"_ls); !relatesToJson.isUndefined()) { + if (const auto relatesToJson = contentPart("m.relates_to"_ls); + !relatesToJson.isEmpty()) { auto content = eventObject["content"].toObject(); - content["m.relates_to"] = relatesToJson.toObject(); + content["m.relates_to"] = relatesToJson; eventObject["content"] = content; } - if (const auto redactsJson = unsignedPart("redacts"_ls); !redactsJson.isUndefined()) { + if (const auto redactsJson = unsignedPart("redacts"_ls); + !redactsJson.isEmpty()) { auto unsign = eventObject["unsigned"].toObject(); - unsign["redacts"] = redactsJson.toString(); + unsign["redacts"] = redactsJson; eventObject["unsigned"] = unsign; } return loadEvent(eventObject); diff --git a/lib/events/event.h b/lib/events/event.h index 05eb51e9..da6cf3c7 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -212,7 +212,7 @@ public: const QJsonObject contentJson() const; - template + template const T contentPart(KeyT&& key) const { return fromJson(contentJson()[std::forward(key)]); @@ -227,7 +227,7 @@ public: const QJsonObject unsignedJson() const; - template + template const T unsignedPart(KeyT&& key) const { return fromJson(unsignedJson()[std::forward(key)]); diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 3ddf5ac4..e695e0ec 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -15,9 +15,9 @@ RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, RoomEvent::RoomEvent(Type type, const QJsonObject& json) : Event(type, json) { - if (const auto redaction = unsignedPart(RedactedCauseKeyL); - redaction.isObject()) - _redactedBecause = makeEvent(redaction.toObject()); + if (const auto redaction = unsignedPart(RedactedCauseKeyL); + !redaction.isEmpty()) + _redactedBecause = makeEvent(redaction); } RoomEvent::~RoomEvent() = default; // Let the smart pointer do its job diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index c343e37f..43dfd6e8 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -21,7 +21,7 @@ StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, bool StateEventBase::repeatsState() const { - const auto prevContentJson = unsignedPart(PrevContentKeyL); + const auto prevContentJson = unsignedPart(PrevContentKeyL); return fullJson().value(ContentKeyL) == prevContentJson; } -- cgit v1.2.3 From 44aeb57e196bcd9e041c498a212f17b0dcd1244f Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Jun 2022 02:52:35 +0200 Subject: Refactor things around EncryptionEvent[Content] EncryptionEvent was marked as Q_GADGET only for the sake of defining EncryptionType inside of it as Q_ENUM, with aliases also available under Quotient:: and EncryptionEventContent. This is a legacy from pre-Q_ENUM_NS times. However, event types are not really made to be proper Q_GADGETs: Q_GADGET implies access by value or reference but event types are uncopyable for the former and QML is ill-equipped for the latter. This commit moves EncryptionType definition to where other such enumerations reside - on the namespace level in quotient_common.h; and the other two places are now deprecated; and EncryptionEvent is no more Q_GADGET. With fromJson/toJson refactored in the previous commit there's no more need to specialise JsonConverter<>: specialising fromJson() is just enough. Moving EncryptionType to quotient_common.h exposed the clash of two Undefined enumerators (in RoomType and EncryptionType), warranting both enumerations to become scoped (which they ought to be, anyway). And while we're at it, the base type of enumerations is specified explicitly, as MSVC apparently uses a signed base type (int?) by default, unlike other compilers, and the upcoming enum converters will assume an unsigned base type. Finally, using fillFromJson() instead of fromJson() in the EncryptionEventContent constructor allowed to make default values explicit in the header file, rather than buried in the initialisation code. --- lib/events/encryptionevent.cpp | 50 ++++++++++++++++++++---------------------- lib/events/encryptionevent.h | 35 ++++++++++++----------------- 2 files changed, 38 insertions(+), 47 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 1654d6f3..8872447b 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -6,47 +6,45 @@ #include "e2ee/e2ee.h" -namespace Quotient { +using namespace Quotient; + static constexpr std::array encryptionStrings { MegolmV1AesSha2AlgoKey }; template <> -struct JsonConverter { - static EncryptionType load(const QJsonValue& jv) - { - const auto& encryptionString = jv.toString(); - for (auto it = encryptionStrings.begin(); it != encryptionStrings.end(); - ++it) - if (encryptionString == *it) - return EncryptionType(it - encryptionStrings.begin()); - - if (!encryptionString.isEmpty()) - qCWarning(EVENTS) << "Unknown EncryptionType: " << encryptionString; - return EncryptionType::Undefined; - } -}; -} // namespace Quotient - -using namespace Quotient; +EncryptionType Quotient::fromJson(const QJsonValue& jv) +{ + const auto& encryptionString = jv.toString(); + for (auto it = encryptionStrings.begin(); it != encryptionStrings.end(); + ++it) + if (encryptionString == *it) + return EncryptionType(it - encryptionStrings.begin()); + + if (!encryptionString.isEmpty()) + qCWarning(EVENTS) << "Unknown EncryptionType: " << encryptionString; + return EncryptionType::Undefined; +} EncryptionEventContent::EncryptionEventContent(const QJsonObject& json) - : encryption(fromJson(json[AlgorithmKeyL])) + : encryption(fromJson(json[AlgorithmKeyL])) , algorithm(sanitized(json[AlgorithmKeyL].toString())) - , rotationPeriodMs(json[RotationPeriodMsKeyL].toInt(604800000)) - , rotationPeriodMsgs(json[RotationPeriodMsgsKeyL].toInt(100)) -{} +{ + // NB: fillFromJson only fills the variable if the JSON key exists + fillFromJson(json[RotationPeriodMsKeyL], rotationPeriodMs); + fillFromJson(json[RotationPeriodMsgsKeyL], rotationPeriodMsgs); +} -EncryptionEventContent::EncryptionEventContent(EncryptionType et) +EncryptionEventContent::EncryptionEventContent(Quotient::EncryptionType et) : encryption(et) { - if(encryption != Undefined) { - algorithm = encryptionStrings[encryption]; + if(encryption != Quotient::EncryptionType::Undefined) { + algorithm = encryptionStrings[static_cast(encryption)]; } } QJsonObject EncryptionEventContent::toJson() const { QJsonObject o; - if (encryption != EncryptionType::Undefined) + if (encryption != Quotient::EncryptionType::Undefined) o.insert(AlgorithmKey, algorithm); o.insert(RotationPeriodMsKey, rotationPeriodMs); o.insert(RotationPeriodMsgsKey, rotationPeriodMsgs); diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 945b17e7..91452c3f 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -4,51 +4,44 @@ #pragma once +#include "quotient_common.h" #include "stateevent.h" namespace Quotient { class QUOTIENT_API EncryptionEventContent { public: - enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; + using EncryptionType + [[deprecated("Use Quotient::EncryptionType instead")]] = + Quotient::EncryptionType; - QUO_IMPLICIT EncryptionEventContent(EncryptionType et); - [[deprecated("This constructor will require explicit EncryptionType soon")]] // - explicit EncryptionEventContent() - : EncryptionEventContent(Undefined) - {} + // NOLINTNEXTLINE(google-explicit-constructor) + QUO_IMPLICIT EncryptionEventContent(Quotient::EncryptionType et); explicit EncryptionEventContent(const QJsonObject& json); QJsonObject toJson() const; - EncryptionType encryption; - QString algorithm; - int rotationPeriodMs; - int rotationPeriodMsgs; + Quotient::EncryptionType encryption; + QString algorithm {}; + int rotationPeriodMs = 604'800'000; + int rotationPeriodMsgs = 100; }; -using EncryptionType = EncryptionEventContent::EncryptionType; - class QUOTIENT_API EncryptionEvent : public StateEvent { - Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.encryption", EncryptionEvent) - using EncryptionType = EncryptionEventContent::EncryptionType; - Q_ENUM(EncryptionType) + using EncryptionType + [[deprecated("Use Quotient::EncryptionType instead")]] = + Quotient::EncryptionType; explicit EncryptionEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} - [[deprecated("This constructor will require an explicit parameter soon")]] // -// explicit EncryptionEvent() -// : EncryptionEvent(QJsonObject()) -// {} explicit EncryptionEvent(EncryptionEventContent&& content) : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) {} - EncryptionType encryption() const { return content().encryption; } - + Quotient::EncryptionType encryption() const { return content().encryption; } QString algorithm() const { return content().algorithm; } int rotationPeriodMs() const { return content().rotationPeriodMs; } int rotationPeriodMsgs() const { return content().rotationPeriodMsgs; } -- cgit v1.2.3 From 9a65bde0fa438ee4ad101b58721b77182ae1ae70 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 9 May 2022 12:02:30 +0200 Subject: Make AliasesEventContent a simple structure JSON conversions are moved out of the class, obviating the need to define the plain data constructor and gaining default-constructibility along the way - previously the default constructor was preempted by user-defined ones. --- lib/events/roomcanonicalaliasevent.h | 43 ++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 24 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index bb8654e5..e599699d 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -7,35 +7,30 @@ #include "stateevent.h" namespace Quotient { -namespace EventContent{ - class AliasesEventContent { - - public: - - template - AliasesEventContent(T1&& canonicalAlias, T2&& altAliases) - : canonicalAlias(std::forward(canonicalAlias)) - , altAliases(std::forward(altAliases)) - { } - - AliasesEventContent(const QJsonObject& json) - : canonicalAlias(fromJson(json["alias"])) - , altAliases(fromJson(json["alt_aliases"])) - { } - - auto toJson() const - { - QJsonObject jo; - addParam(jo, QStringLiteral("alias"), canonicalAlias); - addParam(jo, QStringLiteral("alt_aliases"), altAliases); - return jo; - } - +namespace EventContent { + struct AliasesEventContent { QString canonicalAlias; QStringList altAliases; }; } // namespace EventContent +template<> +inline EventContent::AliasesEventContent fromJson(const QJsonObject& jo) +{ + return EventContent::AliasesEventContent { + fromJson(jo["alias"_ls]), + fromJson(jo["alt_aliases"_ls]) + }; +} +template<> +inline auto toJson(const EventContent::AliasesEventContent& c) +{ + QJsonObject jo; + addParam(jo, QStringLiteral("alias"), c.canonicalAlias); + addParam(jo, QStringLiteral("alt_aliases"), c.altAliases); + return jo; +} + class RoomCanonicalAliasEvent : public StateEvent { public: -- cgit v1.2.3 From e7dee15531ad357bd33ac546fb1b9332a5c1260c Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 9 Jun 2022 08:40:27 +0200 Subject: converters.*: facilities to convert enums This introduces enumTo/FromJsonString() and flagTo/FromJsonString(), four facility functions to simplify conversion between C++ enums and JSON, and refactors a couple of places where it's useful. --- lib/events/roomcreateevent.cpp | 19 +++++-------------- lib/events/roommemberevent.cpp | 19 +++++-------------- 2 files changed, 10 insertions(+), 28 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomcreateevent.cpp b/lib/events/roomcreateevent.cpp index bb6de648..3b5024d5 100644 --- a/lib/events/roomcreateevent.cpp +++ b/lib/events/roomcreateevent.cpp @@ -6,20 +6,11 @@ using namespace Quotient; template <> -struct Quotient::JsonConverter { - static RoomType load(const QJsonValue& jv) - { - const auto& roomTypeString = jv.toString(); - for (auto it = RoomTypeStrings.begin(); it != RoomTypeStrings.end(); - ++it) - if (roomTypeString == *it) - return RoomType(it - RoomTypeStrings.begin()); - - if (!roomTypeString.isEmpty()) - qCWarning(EVENTS) << "Unknown Room Type: " << roomTypeString; - return RoomType::Undefined; - } -}; +RoomType Quotient::fromJson(const QJsonValue& jv) +{ + return enumFromJsonString(jv.toString(), RoomTypeStrings, + RoomType::Undefined); +} bool RoomCreateEvent::isFederated() const { diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index c3be0e00..953ff8ae 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -11,18 +11,10 @@ template <> struct JsonConverter { static Membership load(const QJsonValue& jv) { - const auto& ms = jv.toString(); - if (ms.isEmpty()) - { - qCWarning(EVENTS) << "Empty membership state"; - return Membership::Invalid; - } - const auto it = - std::find(MembershipStrings.begin(), MembershipStrings.end(), ms); - if (it != MembershipStrings.end()) - return Membership(1U << (it - MembershipStrings.begin())); - - qCWarning(EVENTS) << "Unknown Membership value: " << ms; + if (const auto& ms = jv.toString(); !ms.isEmpty()) + return flagFromJsonString(ms, MembershipStrings); + + qCWarning(EVENTS) << "Empty membership state"; return Membership::Invalid; } }; @@ -46,8 +38,7 @@ QJsonObject MemberEventContent::toJson() const QJsonObject o; if (membership != Membership::Invalid) o.insert(QStringLiteral("membership"), - MembershipStrings[qCountTrailingZeroBits( - std::underlying_type_t(membership))]); + flagToJsonString(membership, MembershipStrings)); if (displayName) o.insert(QStringLiteral("displayname"), *displayName); if (avatarUrl && avatarUrl->isValid()) -- cgit v1.2.3 From e172699e9a20737c4abb9bd96609f48e65415961 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 22 Jun 2022 13:17:22 +0200 Subject: eventcontent.h: Use C++17 nested namespaces notation --- lib/events/eventcontent.h | 464 +++++++++++++++++++++++----------------------- 1 file changed, 231 insertions(+), 233 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 7611d077..af26c0a4 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -17,240 +17,238 @@ class QFileInfo; -namespace Quotient { -namespace EventContent { - //! \brief Base for all content types that can be stored in RoomMessageEvent +namespace Quotient::EventContent { +//! \brief Base for all content types that can be stored in RoomMessageEvent +//! +//! Each content type class should have a constructor taking +//! a QJsonObject and override fillJson() with an implementation +//! that will fill the target QJsonObject with stored values. It is +//! assumed but not required that a content object can also be created +//! from plain data. +class QUOTIENT_API Base { +public: + explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} + virtual ~Base() = default; + + QJsonObject toJson() const; + +public: + QJsonObject originalJson; + + // You can't assign those classes + Base& operator=(const Base&) = delete; + Base& operator=(Base&&) = delete; + +protected: + Base(const Base&) = default; + Base(Base&&) noexcept = default; + + virtual void fillJson(QJsonObject&) const = 0; +}; + +// The below structures fairly follow CS spec 11.2.1.6. The overall +// set of attributes for each content types is a superset of the spec +// but specific aggregation structure is altered. See doc comments to +// each type for the list of available attributes. + +// A quick classes inheritance structure follows (the definitions are +// spread across eventcontent.h and roommessageevent.h): +// UrlBasedContent : InfoT + thumbnail data +// PlayableContent : + duration attribute +// FileInfo +// FileContent = UrlBasedContent +// AudioContent = PlayableContent +// ImageInfo : FileInfo + imageSize attribute +// ImageContent = UrlBasedContent +// VideoContent = PlayableContent + +//! \brief Mix-in class representing `info` subobject in content JSON +//! +//! This is one of base classes for content types that deal with files or +//! URLs. It stores the file metadata attributes, such as size, MIME type +//! etc. found in the `content/info` subobject of event JSON payloads. +//! Actual content classes derive from this class _and_ TypedBase that +//! provides a polymorphic interface to access data in the mix-in. FileInfo +//! (as well as ImageInfo, that adds image size to the metadata) is NOT +//! polymorphic and is used in a non-polymorphic way to store thumbnail +//! metadata (in a separate instance), next to the metadata on the file +//! itself. +//! +//! If you need to make a new _content_ (not info) class based on files/URLs +//! take UrlBasedContent as the example, i.e.: +//! 1. Double-inherit from this class (or ImageInfo) and TypedBase. +//! 2. Provide a constructor from QJsonObject that will pass the `info` +//! subobject (not the whole content JSON) down to FileInfo/ImageInfo. +//! 3. Override fillJson() to customise the JSON export logic. Make sure +//! to call toInfoJson() from it to produce the payload for the `info` +//! subobject in the JSON payload. +//! +//! \sa ImageInfo, FileContent, ImageContent, AudioContent, VideoContent, +//! UrlBasedContent +class QUOTIENT_API FileInfo { +public: + FileInfo() = default; + //! \brief Construct from a QFileInfo object //! - //! Each content type class should have a constructor taking - //! a QJsonObject and override fillJson() with an implementation - //! that will fill the target QJsonObject with stored values. It is - //! assumed but not required that a content object can also be created - //! from plain data. - class QUOTIENT_API Base { - public: - explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} - virtual ~Base() = default; - - QJsonObject toJson() const; - - public: - QJsonObject originalJson; - - // You can't assign those classes - Base& operator=(const Base&) = delete; - Base& operator=(Base&&) = delete; - - protected: - Base(const Base&) = default; - Base(Base&&) noexcept = default; - - virtual void fillJson(QJsonObject&) const = 0; - }; - - // The below structures fairly follow CS spec 11.2.1.6. The overall - // set of attributes for each content types is a superset of the spec - // but specific aggregation structure is altered. See doc comments to - // each type for the list of available attributes. - - // A quick classes inheritance structure follows (the definitions are - // spread across eventcontent.h and roommessageevent.h): - // UrlBasedContent : InfoT + thumbnail data - // PlayableContent : + duration attribute - // FileInfo - // FileContent = UrlBasedContent - // AudioContent = PlayableContent - // ImageInfo : FileInfo + imageSize attribute - // ImageContent = UrlBasedContent - // VideoContent = PlayableContent - - //! \brief Mix-in class representing `info` subobject in content JSON + //! \param fi a QFileInfo object referring to an existing file + explicit FileInfo(const QFileInfo& fi); + explicit FileInfo(FileSourceInfo sourceInfo, qint64 payloadSize = -1, + const QMimeType& mimeType = {}, + QString originalFilename = {}); + //! \brief Construct from a JSON `info` payload //! - //! This is one of base classes for content types that deal with files or - //! URLs. It stores the file metadata attributes, such as size, MIME type - //! etc. found in the `content/info` subobject of event JSON payloads. - //! Actual content classes derive from this class _and_ TypedBase that - //! provides a polymorphic interface to access data in the mix-in. FileInfo - //! (as well as ImageInfo, that adds image size to the metadata) is NOT - //! polymorphic and is used in a non-polymorphic way to store thumbnail - //! metadata (in a separate instance), next to the metadata on the file - //! itself. - //! - //! If you need to make a new _content_ (not info) class based on files/URLs - //! take UrlBasedContent as the example, i.e.: - //! 1. Double-inherit from this class (or ImageInfo) and TypedBase. - //! 2. Provide a constructor from QJsonObject that will pass the `info` - //! subobject (not the whole content JSON) down to FileInfo/ImageInfo. - //! 3. Override fillJson() to customise the JSON export logic. Make sure - //! to call toInfoJson() from it to produce the payload for the `info` - //! subobject in the JSON payload. - //! - //! \sa ImageInfo, FileContent, ImageContent, AudioContent, VideoContent, - //! UrlBasedContent - class QUOTIENT_API FileInfo { - public: - FileInfo() = default; - //! \brief Construct from a QFileInfo object - //! - //! \param fi a QFileInfo object referring to an existing file - explicit FileInfo(const QFileInfo& fi); - explicit FileInfo(FileSourceInfo sourceInfo, qint64 payloadSize = -1, - const QMimeType& mimeType = {}, - QString originalFilename = {}); - //! \brief Construct from a JSON `info` payload - //! - //! Make sure to pass the `info` subobject of content JSON, not the - //! whole JSON content. - FileInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, - QString originalFilename = {}); - - bool isValid() const; - QUrl url() const; - - //! \brief Extract media id from the URL - //! - //! This can be used, e.g., to construct a QML-facing image:// - //! URI as follows: - //! \code "image://provider/" + info.mediaId() \endcode - QString mediaId() const { return url().authority() + url().path(); } - - public: - FileSourceInfo source; - QJsonObject originalInfoJson; - QMimeType mimeType; - qint64 payloadSize = 0; - QString originalName; - }; - - QUOTIENT_API QJsonObject toInfoJson(const FileInfo& info); - - //! \brief A content info class for image/video content types and thumbnails - class QUOTIENT_API ImageInfo : public FileInfo { - public: - ImageInfo() = default; - explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); - explicit ImageInfo(FileSourceInfo sourceInfo, qint64 fileSize = -1, - const QMimeType& type = {}, QSize imageSize = {}, - const QString& originalFilename = {}); - ImageInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, - const QString& originalFilename = {}); - - public: - QSize imageSize; - }; - - QUOTIENT_API QJsonObject toInfoJson(const ImageInfo& info); - - //! \brief An auxiliary class for an info type that carries a thumbnail - //! - //! This class saves/loads a thumbnail to/from `info` subobject of - //! the JSON representation of event content; namely, `info/thumbnail_url` - //! (or, in case of an encrypted thumbnail, `info/thumbnail_file`) and - //! `info/thumbnail_info` fields are used. - class QUOTIENT_API Thumbnail : public ImageInfo { - public: - using ImageInfo::ImageInfo; - explicit Thumbnail(const QJsonObject& infoJson, - const Omittable& efm = none); - - //! \brief Add thumbnail information to the passed `info` JSON object - void dumpTo(QJsonObject& infoJson) const; - }; - - class QUOTIENT_API TypedBase : public Base { - public: - virtual QMimeType type() const = 0; - virtual const FileInfo* fileInfo() const { return nullptr; } - virtual FileInfo* fileInfo() { return nullptr; } - virtual const Thumbnail* thumbnailInfo() const { return nullptr; } - - protected: - explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} - using Base::Base; - }; - - //! \brief A template class for content types with a URL and additional info - //! - //! Types that derive from this class template take `url` (or, if the file - //! is encrypted, `file`) and, optionally, `filename` values from - //! the top-level JSON object and the rest of information from the `info` - //! subobject, as defined by the parameter type. - //! \tparam InfoT base info class - FileInfo or ImageInfo - template - class UrlBasedContent : public TypedBase, public InfoT { - public: - using InfoT::InfoT; - explicit UrlBasedContent(const QJsonObject& json) - : TypedBase(json) - , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), - json["filename"].toString()) - , thumbnail(FileInfo::originalInfoJson) - { - if (const auto efmJson = json.value("file"_ls).toObject(); - !efmJson.isEmpty()) - InfoT::source = fromJson(efmJson); - // Two small hacks on originalJson to expose mediaIds to QML - originalJson.insert("mediaId", InfoT::mediaId()); - originalJson.insert("thumbnailMediaId", thumbnail.mediaId()); - } - - QMimeType type() const override { return InfoT::mimeType; } - const FileInfo* fileInfo() const override { return this; } - FileInfo* fileInfo() override { return this; } - const Thumbnail* thumbnailInfo() const override { return &thumbnail; } - - public: - Thumbnail thumbnail; - - protected: - virtual void fillInfoJson(QJsonObject& infoJson [[maybe_unused]]) const - {} - - void fillJson(QJsonObject& json) const override - { - Quotient::fillJson(json, { "url"_ls, "file"_ls }, InfoT::source); - if (!InfoT::originalName.isEmpty()) - json.insert("filename", InfoT::originalName); - auto infoJson = toInfoJson(*this); - if (thumbnail.isValid()) - thumbnail.dumpTo(infoJson); - fillInfoJson(infoJson); - json.insert("info", infoJson); - } - }; - - //! \brief Content class for m.image - //! - //! Available fields: - //! - corresponding to the top-level JSON: - //! - source (corresponding to `url` or `file` in JSON) - //! - filename (extension to the spec) - //! - corresponding to the `info` subobject: - //! - payloadSize (`size` in JSON) - //! - mimeType (`mimetype` in JSON) - //! - imageSize (QSize for a combination of `h` and `w` in JSON) - //! - thumbnail.url (`thumbnail_url` in JSON) - //! - corresponding to the `info/thumbnail_info` subobject: contents of - //! thumbnail field, in the same vein as for the main image: - //! - payloadSize - //! - mimeType - //! - imageSize - using ImageContent = UrlBasedContent; - - //! \brief Content class for m.file + //! Make sure to pass the `info` subobject of content JSON, not the + //! whole JSON content. + FileInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, + QString originalFilename = {}); + + bool isValid() const; + QUrl url() const; + + //! \brief Extract media id from the URL //! - //! Available fields: - //! - corresponding to the top-level JSON: - //! - source (corresponding to `url` or `file` in JSON) - //! - filename - //! - corresponding to the `info` subobject: - //! - payloadSize (`size` in JSON) - //! - mimeType (`mimetype` in JSON) - //! - thumbnail.source (`thumbnail_url` or `thumbnail_file` in JSON) - //! - corresponding to the `info/thumbnail_info` subobject: - //! - thumbnail.payloadSize - //! - thumbnail.mimeType - //! - thumbnail.imageSize (QSize for `h` and `w` in JSON) - using FileContent = UrlBasedContent; -} // namespace EventContent -} // namespace Quotient + //! This can be used, e.g., to construct a QML-facing image:// + //! URI as follows: + //! \code "image://provider/" + info.mediaId() \endcode + QString mediaId() const { return url().authority() + url().path(); } + +public: + FileSourceInfo source; + QJsonObject originalInfoJson; + QMimeType mimeType; + qint64 payloadSize = 0; + QString originalName; +}; + +QUOTIENT_API QJsonObject toInfoJson(const FileInfo& info); + +//! \brief A content info class for image/video content types and thumbnails +class QUOTIENT_API ImageInfo : public FileInfo { +public: + ImageInfo() = default; + explicit ImageInfo(const QFileInfo& fi, QSize imageSize = {}); + explicit ImageInfo(FileSourceInfo sourceInfo, qint64 fileSize = -1, + const QMimeType& type = {}, QSize imageSize = {}, + const QString& originalFilename = {}); + ImageInfo(FileSourceInfo sourceInfo, const QJsonObject& infoJson, + const QString& originalFilename = {}); + +public: + QSize imageSize; +}; + +QUOTIENT_API QJsonObject toInfoJson(const ImageInfo& info); + +//! \brief An auxiliary class for an info type that carries a thumbnail +//! +//! This class saves/loads a thumbnail to/from `info` subobject of +//! the JSON representation of event content; namely, `info/thumbnail_url` +//! (or, in case of an encrypted thumbnail, `info/thumbnail_file`) and +//! `info/thumbnail_info` fields are used. +class QUOTIENT_API Thumbnail : public ImageInfo { +public: + using ImageInfo::ImageInfo; + explicit Thumbnail(const QJsonObject& infoJson, + const Omittable& efm = none); + + //! \brief Add thumbnail information to the passed `info` JSON object + void dumpTo(QJsonObject& infoJson) const; +}; + +class QUOTIENT_API TypedBase : public Base { +public: + virtual QMimeType type() const = 0; + virtual const FileInfo* fileInfo() const { return nullptr; } + virtual FileInfo* fileInfo() { return nullptr; } + virtual const Thumbnail* thumbnailInfo() const { return nullptr; } + +protected: + explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} + using Base::Base; +}; + +//! \brief A template class for content types with a URL and additional info +//! +//! Types that derive from this class template take `url` (or, if the file +//! is encrypted, `file`) and, optionally, `filename` values from +//! the top-level JSON object and the rest of information from the `info` +//! subobject, as defined by the parameter type. +//! \tparam InfoT base info class - FileInfo or ImageInfo +template +class UrlBasedContent : public TypedBase, public InfoT { +public: + using InfoT::InfoT; + explicit UrlBasedContent(const QJsonObject& json) + : TypedBase(json) + , InfoT(QUrl(json["url"].toString()), json["info"].toObject(), + json["filename"].toString()) + , thumbnail(FileInfo::originalInfoJson) + { + if (const auto efmJson = json.value("file"_ls).toObject(); + !efmJson.isEmpty()) + InfoT::source = fromJson(efmJson); + // Two small hacks on originalJson to expose mediaIds to QML + originalJson.insert("mediaId", InfoT::mediaId()); + originalJson.insert("thumbnailMediaId", thumbnail.mediaId()); + } + + QMimeType type() const override { return InfoT::mimeType; } + const FileInfo* fileInfo() const override { return this; } + FileInfo* fileInfo() override { return this; } + const Thumbnail* thumbnailInfo() const override { return &thumbnail; } + +public: + Thumbnail thumbnail; + +protected: + virtual void fillInfoJson(QJsonObject& infoJson [[maybe_unused]]) const + {} + + void fillJson(QJsonObject& json) const override + { + Quotient::fillJson(json, { "url"_ls, "file"_ls }, InfoT::source); + if (!InfoT::originalName.isEmpty()) + json.insert("filename", InfoT::originalName); + auto infoJson = toInfoJson(*this); + if (thumbnail.isValid()) + thumbnail.dumpTo(infoJson); + fillInfoJson(infoJson); + json.insert("info", infoJson); + } +}; + +//! \brief Content class for m.image +//! +//! Available fields: +//! - corresponding to the top-level JSON: +//! - source (corresponding to `url` or `file` in JSON) +//! - filename (extension to the spec) +//! - corresponding to the `info` subobject: +//! - payloadSize (`size` in JSON) +//! - mimeType (`mimetype` in JSON) +//! - imageSize (QSize for a combination of `h` and `w` in JSON) +//! - thumbnail.url (`thumbnail_url` in JSON) +//! - corresponding to the `info/thumbnail_info` subobject: contents of +//! thumbnail field, in the same vein as for the main image: +//! - payloadSize +//! - mimeType +//! - imageSize +using ImageContent = UrlBasedContent; + +//! \brief Content class for m.file +//! +//! Available fields: +//! - corresponding to the top-level JSON: +//! - source (corresponding to `url` or `file` in JSON) +//! - filename +//! - corresponding to the `info` subobject: +//! - payloadSize (`size` in JSON) +//! - mimeType (`mimetype` in JSON) +//! - thumbnail.source (`thumbnail_url` or `thumbnail_file` in JSON) +//! - corresponding to the `info/thumbnail_info` subobject: +//! - thumbnail.payloadSize +//! - thumbnail.mimeType +//! - thumbnail.imageSize (QSize for `h` and `w` in JSON) +using FileContent = UrlBasedContent; +} // namespace Quotient::EventContent Q_DECLARE_METATYPE(const Quotient::EventContent::TypedBase*) -- cgit v1.2.3 From a329538c617bad01ffd35a83a0b684f90993dd0d Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 26 Jul 2022 14:26:05 +0200 Subject: Add missing QUOTIENT_API pieces The upcoming event type infrastructure finally helps to detect those omissions more or less reliably (for event types only though). --- lib/events/redactionevent.h | 2 +- lib/events/roomcanonicalaliasevent.h | 2 +- lib/events/simplestateevents.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index 1c486a44..63617e54 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -6,7 +6,7 @@ #include "roomevent.h" namespace Quotient { -class RedactionEvent : public RoomEvent { +class QUOTIENT_API RedactionEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.room.redaction", RedactionEvent) diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index e599699d..60ca68ac 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -31,7 +31,7 @@ inline auto toJson(const EventContent::AliasesEventContent& c) return jo; } -class RoomCanonicalAliasEvent +class QUOTIENT_API RoomCanonicalAliasEvent : public StateEvent { public: DEFINE_EVENT_TYPEID("m.room.canonical_alias", RoomCanonicalAliasEvent) diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 33221542..43c1da69 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -34,7 +34,7 @@ DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) constexpr auto RoomAliasesEventKey = "aliases"_ls; -class [[deprecated( +class QUOTIENT_API [[deprecated( "m.room.aliases events are deprecated by the Matrix spec; use" " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases")]] // RoomAliasesEvent -- cgit v1.2.3 From d422b1fd87c48572ae1fc162ce239196e3254752 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 26 Jul 2022 16:56:41 +0200 Subject: Hopefully fix building with GCC The last commit broke it. --- lib/events/simplestateevents.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 43c1da69..c6b91931 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -34,10 +34,10 @@ DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) constexpr auto RoomAliasesEventKey = "aliases"_ls; -class QUOTIENT_API [[deprecated( +class [[deprecated( "m.room.aliases events are deprecated by the Matrix spec; use" " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases")]] // -RoomAliasesEvent +QUOTIENT_API RoomAliasesEvent : public StateEvent< EventContent::SingleKeyValue> { -- cgit v1.2.3 From 7754947d7f758ddcb31d4ff3ea79435fb1c171e9 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 26 Jul 2022 17:18:36 +0200 Subject: Another fix attempt --- lib/events/simplestateevents.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index c6b91931..46e1b3a7 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -34,13 +34,12 @@ DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) constexpr auto RoomAliasesEventKey = "aliases"_ls; -class [[deprecated( +class Q_DECL_DEPRECATED_X( "m.room.aliases events are deprecated by the Matrix spec; use" - " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases")]] // -QUOTIENT_API RoomAliasesEvent + " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases") + QUOTIENT_API RoomAliasesEvent : public StateEvent< - EventContent::SingleKeyValue> -{ + EventContent::SingleKeyValue> { public: DEFINE_EVENT_TYPEID("m.room.aliases", RoomAliasesEvent) explicit RoomAliasesEvent(const QJsonObject& obj) -- cgit v1.2.3 From 36344a6e0283f924b72cb2b25001bdf212a7e707 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 26 Jul 2022 23:06:50 +0200 Subject: ...and the definitive fix --- lib/events/simplestateevents.h | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 46e1b3a7..a8eaab56 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -34,10 +34,7 @@ DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", QStringList, pinnedEvents) constexpr auto RoomAliasesEventKey = "aliases"_ls; -class Q_DECL_DEPRECATED_X( - "m.room.aliases events are deprecated by the Matrix spec; use" - " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases") - QUOTIENT_API RoomAliasesEvent +class QUOTIENT_API RoomAliasesEvent : public StateEvent< EventContent::SingleKeyValue> { public: @@ -45,7 +42,13 @@ public: explicit RoomAliasesEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} + Q_DECL_DEPRECATED_X( + "m.room.aliases events are deprecated by the Matrix spec; use" + " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases") QString server() const { return stateKey(); } + Q_DECL_DEPRECATED_X( + "m.room.aliases events are deprecated by the Matrix spec; use" + " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases") QStringList aliases() const { return content().value; } }; } // namespace Quotient -- cgit v1.2.3 From 953d5a9d03b2a3ca439a79775a0c212965d91c20 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 29 Jul 2022 17:50:17 +0200 Subject: Moving eventCast() In a situation where you have an EventPtr that you want to place somewhere as an `event_ptr_tt` you have to carefully check that the stored event is actually of SomeMoreSpecificType and if it is, release() that event pointer, downcast, and re-wrap it into that new event_ptr_tt - or, as can be seen from the diff here, re-loadEvent() from JSON, which is simpler but inefficient. To help clients, and the library, eventCast() can now accept an rvalue smart pointer and do all the necessary things with it. --- lib/events/event.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index da6cf3c7..043d4f54 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -332,6 +332,13 @@ inline bool isUnknown(const Event& e) return e.type() == UnknownEventTypeId; } +//! \brief Cast the event pointer down in a type-safe way +//! +//! Checks that the event \p eptr points to actually is of the requested type +//! and returns a (plain) pointer to the event downcast to that type. \p eptr +//! can be either "dumb" (BaseEventT*) or "smart" (`event_ptr_tt<>`). This +//! overload doesn't affect the event ownership - if the original pointer owns +//! the event it must outlive the downcast pointer to keep it from dangling. template inline auto eventCast(const BasePtrT& eptr) -> decltype(static_cast(&*eptr)) @@ -341,6 +348,28 @@ inline auto eventCast(const BasePtrT& eptr) : nullptr; } +//! \brief Cast the event pointer down in a type-safe way, with moving +//! +//! Checks that the event \p eptr points to actually is of the requested type; +//! if (and only if) it is, releases the pointer, downcasts it to the requested +//! event type and returns a new smart pointer wrapping the downcast one. +//! Unlike the non-moving eventCast() overload, this one only accepts a smart +//! pointer, and that smart pointer should be an rvalue (either a temporary, +//! or as a result of std::move()). The ownership, respectively, is transferred +//! to the new pointer; the original smart pointer is reset to nullptr, as is +//! normal for `unique_ptr<>::release()`. +//! \note If \p eptr's event type does not match \p EventT it retains ownership +//! after calling this overload; if it is a temporary, this normally +//! leads to the event getting deleted along with the end of +//! the temporary's lifetime. +template +inline auto eventCast(event_ptr_tt&& eptr) +{ + return eptr && is>(*eptr) + ? event_ptr_tt(static_cast(eptr.release())) + : nullptr; +} + namespace _impl { template concept Invocable_With_Downcast = -- cgit v1.2.3 From d4b8f54f764bec5758c8f672d4ab05d59e02c269 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 30 Jul 2022 07:37:15 +0200 Subject: moving eventCast(): disallow passing nullptr This is aligned with the non-moving version. --- lib/events/event.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 043d4f54..b7454337 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -343,9 +343,9 @@ template inline auto eventCast(const BasePtrT& eptr) -> decltype(static_cast(&*eptr)) { - Q_ASSERT(eptr); - return is>(*eptr) ? static_cast(&*eptr) - : nullptr; + return eptr && is>(*eptr) + ? static_cast(&*eptr) + : nullptr; } //! \brief Cast the event pointer down in a type-safe way, with moving -- cgit v1.2.3 From 150df8ce08976ac7b8c25dbed1b965b7c2f65249 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 1 Aug 2022 12:11:58 +0200 Subject: Pull out common JsonConverter code to JsonObjectUnpacker --- lib/events/eventloader.h | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index c7b82e8e..7dde9786 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -48,14 +48,11 @@ inline StateEventPtr loadStateEvent(const QString& matrixType, } template -struct JsonConverter> { - static auto load(const QJsonValue& jv) +struct JsonConverter> + : JsonObjectUnpacker> { + static auto load(const QJsonObject& jo) { - return loadEvent(jv.toObject()); - } - static auto load(const QJsonDocument& jd) - { - return loadEvent(jd.object()); + return loadEvent(jo); } }; } // namespace Quotient -- cgit v1.2.3 From 88dcdd3ef0af4030a963b08bf8c5bff0784c320d Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 1 Aug 2022 13:51:58 +0200 Subject: Fix FTBFS --- lib/events/eventloader.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'lib/events') diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index 7dde9786..15271ab1 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -50,9 +50,11 @@ inline StateEventPtr loadStateEvent(const QString& matrixType, template struct JsonConverter> : JsonObjectUnpacker> { + using JsonObjectUnpacker>::load; static auto load(const QJsonObject& jo) { return loadEvent(jo); } }; + } // namespace Quotient -- cgit v1.2.3 From 3214feeb031fa231c7c42c21c53410302966e32e Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 29 Jul 2022 18:13:14 +0200 Subject: eventloader.h: use basicJson() in a uniform way There's no particular reason the order of parameters in StateEventBase::basicJson() should be as it was, and (the only) loadStateEvent() usage in room.cpp suggests the unified order is more convenient. Besides, this order is aligned with that in the StateEventBase constructor. --- lib/events/eventloader.h | 35 ++++++++++------------------------- lib/events/stateevent.cpp | 2 +- lib/events/stateevent.h | 8 ++++---- 3 files changed, 15 insertions(+), 30 deletions(-) (limited to 'lib/events') diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index 15271ab1..4c639efa 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -19,32 +19,17 @@ inline event_ptr_tt loadEvent(const QJsonObject& fullJson) return doLoadEvent(fullJson, fullJson[TypeKeyL].toString()); } -/*! Create an event from a type string and content JSON - * - * Use this factory template to resolve the C++ type from the Matrix - * type string in \p matrixType and create an event of that type that has - * its content part set to \p content. - */ -template -inline event_ptr_tt loadEvent(const QString& matrixType, - const QJsonObject& content) -{ - return doLoadEvent(Event::basicJson(matrixType, content), - matrixType); -} - -/*! Create a state event from a type string, content JSON and state key - * - * Use this factory to resolve the C++ type from the Matrix type string - * in \p matrixType and create a state event of that type with content part - * set to \p content and state key set to \p stateKey (empty by default). - */ -inline StateEventPtr loadStateEvent(const QString& matrixType, - const QJsonObject& content, - const QString& stateKey = {}) +//! \brief Create an event from a type string and content JSON +//! +//! Use this template to resolve the C++ type from the Matrix type string in +//! \p matrixType and create an event of that type by passing all parameters +//! to BaseEventT::basicJson(). +template +inline event_ptr_tt loadEvent( + const QString& matrixType, const BasicJsonParamTs&... basicJsonParams) { - return doLoadEvent( - StateEventBase::basicJson(matrixType, content, stateKey), matrixType); + return doLoadEvent( + BaseEventT::basicJson(matrixType, basicJsonParams...), matrixType); } template diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 43dfd6e8..1df24df0 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -16,7 +16,7 @@ StateEventBase::StateEventBase(Type type, const QJsonObject& json) StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, const QString& stateKey, const QJsonObject& contentJson) - : RoomEvent(type, basicJson(matrixType, contentJson, stateKey)) + : RoomEvent(type, basicJson(type, stateKey, contentJson)) {} bool StateEventBase::repeatsState() const diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 343e87a5..9f1d7118 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -19,12 +19,12 @@ public: //! Make a minimal correct Matrix state event JSON static QJsonObject basicJson(const QString& matrixTypeId, - const QJsonObject& content, - const QString& stateKey = {}) + const QString& stateKey = {}, + const QJsonObject& contentJson = {}) { return { { TypeKey, matrixTypeId }, { StateKeyKey, stateKey }, - { ContentKey, content } }; + { ContentKey, contentJson } }; } bool isStateEvent() const override { return true; } @@ -41,7 +41,7 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, const QJsonObject& content, const QString& stateKey = {}) { - return StateEventBase::basicJson(matrixTypeId, content, stateKey); + return StateEventBase::basicJson(matrixTypeId, stateKey, content); } //! \brief Override RoomEvent factory with that from StateEventBase if JSON has -- cgit v1.2.3 From 2e1f179bf75da9705963be9305ab6db34afa4d6d Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 20 Aug 2022 19:18:17 +0200 Subject: Connection::Private::assembleEncryptedContent() What was partially factored out before into encryptSessionKeyEvent() is now the complete algorithm converting any event json into encrypted content. --- lib/events/roomkeyevent.cpp | 21 +++++++++------------ lib/events/roomkeyevent.h | 3 +-- 2 files changed, 10 insertions(+), 14 deletions(-) (limited to 'lib/events') diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp index 68962950..3a8601d1 100644 --- a/lib/events/roomkeyevent.cpp +++ b/lib/events/roomkeyevent.cpp @@ -5,21 +5,18 @@ using namespace Quotient; -RoomKeyEvent::RoomKeyEvent(const QJsonObject &obj) : Event(typeId(), obj) +RoomKeyEvent::RoomKeyEvent(const QJsonObject &obj) : Event(TypeId, obj) { if (roomId().isEmpty()) qCWarning(E2EE) << "Room key event has empty room id"; } -RoomKeyEvent::RoomKeyEvent(const QString& algorithm, const QString& roomId, const QString& sessionId, const QString& sessionKey, const QString& senderId) - : Event(typeId(), { - {"content", QJsonObject{ - {"algorithm", algorithm}, - {"room_id", roomId}, - {"session_id", sessionId}, - {"session_key", sessionKey}, - }}, - {"sender", senderId}, - {"type", "m.room_key"}, - }) +RoomKeyEvent::RoomKeyEvent(const QString& algorithm, const QString& roomId, + const QString& sessionId, const QString& sessionKey) + : Event(TypeId, basicJson(TypeId, { + { "algorithm", algorithm }, + { "room_id", roomId }, + { "session_id", sessionId }, + { "session_key", sessionKey }, + })) {} diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 9eb2854b..0dfdf383 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -13,8 +13,7 @@ public: explicit RoomKeyEvent(const QJsonObject& obj); explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, - const QString& sessionId, const QString& sessionKey, - const QString& senderId); + const QString& sessionId, const QString& sessionKey); QUO_CONTENT_GETTER(QString, algorithm) QUO_CONTENT_GETTER(QString, roomId) -- cgit v1.2.3 From 376da43a29f3ebad807da2761e7a0c0b105587ec Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Thu, 25 Aug 2022 19:58:18 +0200 Subject: More code reorganisation - Common switchOnType() piece for key verification events is factored out into processIfVerificationEvent() - Bare event JSON removed from KeyVerificationSession into constructors of respective events - Connection::sendToDevice() uses assembleEncryptedContent() introduced in the previous commit - commonSupportedMethods() moved out to .cpp; error/string converters made static --- lib/events/keyverificationevent.h | 77 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 4 deletions(-) (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index cdbd5d74..f635d07b 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -18,6 +18,16 @@ public: explicit KeyVerificationRequestEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationRequestEvent(const QString& transactionId, + const QString& fromDevice, + const QStringList& methods, + const QDateTime& timestamp) + : KeyVerificationRequestEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId }, + { "from_device"_ls, fromDevice }, + { "methods"_ls, toJson(methods) }, + { "timestamp"_ls, toJson(timestamp) } })) + {} /// The device ID which is initiating the request. QUO_CONTENT_GETTER(QString, fromDevice) @@ -44,6 +54,14 @@ public: explicit KeyVerificationReadyEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationReadyEvent(const QString& transactionId, + const QString& fromDevice, + const QStringList& methods) + : KeyVerificationReadyEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId }, + { "from_device"_ls, fromDevice }, + { "methods"_ls, toJson(methods) } })) + {} /// The device ID which is accepting the request. QUO_CONTENT_GETTER(QString, fromDevice) @@ -62,9 +80,23 @@ class QUOTIENT_API KeyVerificationStartEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.start", KeyVerificationStartEvent) - explicit KeyVerificationStartEvent(const QJsonObject &obj) + explicit KeyVerificationStartEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationStartEvent(const QString& transactionId, + const QString& fromDevice) + : KeyVerificationStartEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId }, + { "from_device"_ls, fromDevice }, + { "method"_ls, SasV1Method }, + { "hashes"_ls, QJsonArray{ "sha256"_ls } }, + { "key_agreement_protocols"_ls, + QJsonArray{ "curve25519-hkdf-sha256"_ls } }, + { "message_authentication_codes"_ls, + QJsonArray{ "hkdf-hmac-sha256"_ls } }, + { "short_authentication_string"_ls, + QJsonArray{ "decimal"_ls, "emoji"_ls } } })) + {} /// The device ID which is initiating the process. QUO_CONTENT_GETTER(QString, fromDevice) @@ -125,6 +157,18 @@ public: explicit KeyVerificationAcceptEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationAcceptEvent(const QString& transactionId, + const QString& commitment) + : KeyVerificationAcceptEvent(basicJson( + TypeId, { { "transaction_id"_ls, transactionId }, + { "method"_ls, SasV1Method }, + { "key_agreement_protocol"_ls, "curve25519-hkdf-sha256" }, + { "hash"_ls, "sha256" }, + { "message_authentication_code"_ls, "hkdf-hmac-sha256" }, + { "short_authentication_string"_ls, + QJsonArray{ "decimal"_ls, "emoji"_ls, } }, + { "commitment"_ls, commitment } })) + {} /// An opaque identifier for the verification process. QUO_CONTENT_GETTER(QString, transactionId) @@ -161,9 +205,18 @@ class QUOTIENT_API KeyVerificationCancelEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.cancel", KeyVerificationCancelEvent) - explicit KeyVerificationCancelEvent(const QJsonObject &obj) + explicit KeyVerificationCancelEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationCancelEvent(const QString& transactionId, + const QString& reason) + : KeyVerificationCancelEvent( + basicJson(TypeId, { + { "transaction_id"_ls, transactionId }, + { "reason"_ls, reason }, + { "code"_ls, reason } // Not a typo + })) + {} /// An opaque identifier for the verification process. QUO_CONTENT_GETTER(QString, transactionId) @@ -183,9 +236,14 @@ class QUOTIENT_API KeyVerificationKeyEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.key", KeyVerificationKeyEvent) - explicit KeyVerificationKeyEvent(const QJsonObject &obj) + explicit KeyVerificationKeyEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationKeyEvent(const QString& transactionId, const QString& key) + : KeyVerificationKeyEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId }, + { "key"_ls, key } })) + {} /// An opaque identifier for the verification process. QUO_CONTENT_GETTER(QString, transactionId) @@ -200,9 +258,16 @@ class QUOTIENT_API KeyVerificationMacEvent : public Event { public: DEFINE_EVENT_TYPEID("m.key.verification.mac", KeyVerificationMacEvent) - explicit KeyVerificationMacEvent(const QJsonObject &obj) + explicit KeyVerificationMacEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + KeyVerificationMacEvent(const QString& transactionId, const QString& keys, + const QJsonObject& mac) + : KeyVerificationMacEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId }, + { "keys"_ls, keys }, + { "mac"_ls, mac } })) + {} /// An opaque identifier for the verification process. QUO_CONTENT_GETTER(QString, transactionId) @@ -224,6 +289,10 @@ public: explicit KeyVerificationDoneEvent(const QJsonObject& obj) : Event(TypeId, obj) {} + explicit KeyVerificationDoneEvent(const QString& transactionId) + : KeyVerificationDoneEvent( + basicJson(TypeId, { { "transaction_id"_ls, transactionId } })) + {} /// The same transactionId as before QUO_CONTENT_GETTER(QString, transactionId) -- cgit v1.2.3 From 5efbf75c8719407549e4bcfcf4c5329b37630990 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 3 Sep 2022 15:26:07 +0200 Subject: KeyVerificationDoneEvent: fix copy-pasta in DEFINE_EVENT_TYPEID --- lib/events/keyverificationevent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index f635d07b..5b587522 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -284,7 +284,7 @@ REGISTER_EVENT_TYPE(KeyVerificationMacEvent) class QUOTIENT_API KeyVerificationDoneEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.done", KeyVerificationRequestEvent) + DEFINE_EVENT_TYPEID("m.key.verification.done", KeyVerificationDoneEvent) explicit KeyVerificationDoneEvent(const QJsonObject& obj) : Event(TypeId, obj) -- cgit v1.2.3 From dbc78d185c4bafe03b458f9eeb7ef3af35ce2eb2 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 21 Jun 2022 07:33:43 +0200 Subject: SingleKeyValue: allow seamless construction from the underlying type SingleKeyValue is a tiny wrapper and supposed to be discreet. Having to explicitly (even if only with braces) construct its objects stands in the way of readability on the consuming side of the code and sometimes prevents direct initialisation of event objects without constructors getting some kind of ContentParamTs parameter pack where a single content_type argument would suffice otherwise. --- lib/events/single_key_value.h | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'lib/events') diff --git a/lib/events/single_key_value.h b/lib/events/single_key_value.h index 75ca8cd2..5edff3b1 100644 --- a/lib/events/single_key_value.h +++ b/lib/events/single_key_value.h @@ -7,6 +7,15 @@ namespace Quotient { namespace EventContent { template struct SingleKeyValue { + // NOLINTBEGIN(google-explicit-constructor): that check should learn + // about explicit(false) + QUO_IMPLICIT SingleKeyValue(const T& v = {}) + : value { v } + {} + QUO_IMPLICIT SingleKeyValue(T&& v) + : value { std::move(v) } + {} + // NOLINTEND(google-explicit-constructor) T value; }; } // namespace EventContent -- cgit v1.2.3 From a26147582ce8cbd6a5206aee4b59de98c9dfe9b6 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 27 Jul 2022 20:19:44 +0200 Subject: DEFINE_SIMPLE_EVENT: support custom JSON keys --- lib/events/accountdataevents.h | 18 +++++++++++------ lib/events/event.h | 46 ++++++++++++++++++++++-------------------- lib/events/reactionevent.h | 17 ++-------------- lib/events/typingevent.cpp | 11 ---------- lib/events/typingevent.h | 10 +-------- 5 files changed, 39 insertions(+), 63 deletions(-) delete mode 100644 lib/events/typingevent.cpp (limited to 'lib/events') diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 24c3353c..324ce449 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -4,7 +4,6 @@ #pragma once #include "event.h" -#include "util.h" namespace Quotient { constexpr auto FavouriteTag [[maybe_unused]] = "m.favourite"_ls; @@ -46,14 +45,21 @@ struct JsonObjectConverter { using TagsMap = QHash; -DEFINE_SIMPLE_EVENT(TagEvent, Event, "m.tag", TagsMap, tags) -DEFINE_SIMPLE_EVENT(ReadMarkerEventImpl, Event, "m.fully_read", QString, eventId) +DEFINE_SIMPLE_EVENT(TagEvent, Event, "m.tag", TagsMap, tags, "tags") +DEFINE_SIMPLE_EVENT(ReadMarkerEventImpl, Event, "m.fully_read", QString, + eventId, "event_id") class ReadMarkerEvent : public ReadMarkerEventImpl { public: using ReadMarkerEventImpl::ReadMarkerEventImpl; [[deprecated("Use ReadMarkerEvent::eventId() instead")]] - QString event_id() const { return eventId(); } + auto event_id() const { return eventId(); } +}; +DEFINE_SIMPLE_EVENT(IgnoredUsersEventImpl, Event, "m.ignored_user_list", + QSet, ignoredUsers, "ignored_users") +class IgnoredUsersEvent : public IgnoredUsersEventImpl { +public: + using IgnoredUsersEventImpl::IgnoredUsersEventImpl; + [[deprecated("Use IgnoredUsersEvent::ignoredUsers() instead")]] + auto ignored_users() const { return ignoredUsers(); } }; -DEFINE_SIMPLE_EVENT(IgnoredUsersEvent, Event, "m.ignored_user_list", QSet, - ignored_users) } // namespace Quotient diff --git a/lib/events/event.h b/lib/events/event.h index b7454337..711f8fd4 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -6,6 +6,7 @@ #include "converters.h" #include "logging.h" #include "function_traits.h" +#include "single_key_value.h" namespace Quotient { // === event_ptr_tt<> and type casting facilities === @@ -258,6 +259,13 @@ template using EventsArray = std::vector>; using Events = EventsArray; +#define QUO_CONTENT_GETTER_X(PartType_, PartName_, JsonKey_) \ + PartType_ PartName_() const \ + { \ + static const auto PartName_##JsonKey = JsonKey_; \ + return contentPart(PartName_##JsonKey); \ + } + //! \brief Define an inline method obtaining a content part //! //! This macro adds a const method that extracts a JSON value at the key @@ -266,12 +274,8 @@ using Events = EventsArray; //! \code //! contentPart(Quotient::toSnakeCase(#PartName_##_ls)); //! \endcode -#define QUO_CONTENT_GETTER(PartType_, PartName_) \ - PartType_ PartName_() const \ - { \ - static const auto JsonKey = toSnakeCase(#PartName_##_ls); \ - return contentPart(JsonKey); \ - } +#define QUO_CONTENT_GETTER(PartType_, PartName_) \ + QUO_CONTENT_GETTER_X(PartType_, PartName_, toSnakeCase(#PartName_##_ls)) // === Facilities for event class definitions === @@ -301,22 +305,20 @@ using Events = EventsArray; /// To retrieve the value the getter uses a JSON key name that corresponds to /// its own (getter's) name but written in snake_case. \p GetterName_ must be /// in camelCase, no quotes (an identifier, not a literal). -#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_) \ - class QUOTIENT_API Name_ : public Base_ { \ - public: \ - using content_type = ValueType_; \ - DEFINE_EVENT_TYPEID(TypeId_, Name_) \ - explicit Name_(const QJsonObject& obj) : Base_(TypeId, obj) {} \ - explicit Name_(const content_type& content) \ - : Name_(Base_::basicJson(TypeId, { { JsonKey, toJson(content) } })) \ - {} \ - auto GetterName_() const \ - { \ - return contentPart(JsonKey); \ - } \ - static inline const auto JsonKey = toSnakeCase(#GetterName_##_ls); \ - }; \ - REGISTER_EVENT_TYPE(Name_) \ +#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_, \ + JsonKey_) \ + class QUOTIENT_API Name_ : public Base_ { \ + public: \ + DEFINE_EVENT_TYPEID(TypeId_, Name_) \ + using value_type = ValueType_; \ + explicit Name_(const QJsonObject& obj) : Base_(TypeId, obj) {} \ + explicit Name_(const value_type& v) \ + : Name_(Base_::basicJson(TypeId, { { JsonKey, toJson(v) } })) \ + {} \ + QUO_CONTENT_GETTER_X(ValueType_, GetterName_, JsonKey) \ + static inline const auto JsonKey = toSnakeCase(#GetterName_##_ls); \ + }; \ + REGISTER_EVENT_TYPE(Name_) \ // End of macro // === is<>(), eventCast<>() and switchOnType<>() === diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index b3cb3ca7..8d873441 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -8,20 +8,7 @@ namespace Quotient { -class QUOTIENT_API ReactionEvent : public RoomEvent { -public: - DEFINE_EVENT_TYPEID("m.reaction", ReactionEvent) - - explicit ReactionEvent(const EventRelation& value) - : RoomEvent(typeId(), matrixTypeId(), - { { QStringLiteral("m.relates_to"), toJson(value) } }) - {} - explicit ReactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} - EventRelation relation() const - { - return contentPart(RelatesToKey); - } -}; -REGISTER_EVENT_TYPE(ReactionEvent) +DEFINE_SIMPLE_EVENT(ReactionEvent, RoomEvent, "m.reaction", EventRelation, + relation, "m.relates_to") } // namespace Quotient diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp deleted file mode 100644 index 7e5d7ee6..00000000 --- a/lib/events/typingevent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Kitsune Ral -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "typingevent.h" - -using namespace Quotient; - -QStringList TypingEvent::users() const -{ - return contentPart("user_ids"_ls); -} diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 522f7e42..b56475af 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -6,13 +6,5 @@ #include "event.h" namespace Quotient { -class QUOTIENT_API TypingEvent : public Event { -public: - DEFINE_EVENT_TYPEID("m.typing", TypingEvent) - - explicit TypingEvent(const QJsonObject& obj) : Event(typeId(), obj) {} - - QStringList users() const; -}; -REGISTER_EVENT_TYPE(TypingEvent) +DEFINE_SIMPLE_EVENT(TypingEvent, Event, "m.typing", QStringList, users, "user_ids") } // namespace Quotient -- cgit v1.2.3 From a18f505fe7ca66556d66538a7c9b9ff31d2c1b29 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 9 Aug 2022 18:42:24 +0200 Subject: EventMetaType, QUO_EVENT, QUO_BASE_EVENT The new metatype framework replaces EventFactory/DEFINE_EVENT_TYPEID/REGISTER_EVENT_TYPE; it is faster, more functional and extensible. Of note: - EventMetaType mostly reproduces the logic of EventFactory but supports custom base event types not just for loading (that part EventFactory also supported) but also for matching - previously you had to have Event::is*Event() for base type matching. Now Quotient::is() can match against both base and leaf types. - Instead of DEFINE_EVENT_TYPEID and REGISTER_EVENT_TYPE there's now a single macro, QUO_EVENT, intended for use in the way similar to Q_OBJECT. Actually, the entire framework borrows heavily from QMetaObject and Q_OBJECT. Making event types full-fledged QObjects is still not considered because half of QObject functions would not be applicable (e.g. signals/slots) while another half (in particular, using Matrix type ids to select event types) would still have to be done on top of QObject. And QML can just access events as const QJsonObjects which is arguably more lightweight as well. - QUO_BASE_EVENT is a new macro replacing EventFactory object definitions. This was necessary for the same reason why Q_OBJECT is a macro: aside from a static object definition, this macro introduces a virtual function override to resolve the metatype at runtime. This very mechanism is used to make event type matching/casting as quick as possible - QUO_BASE_EVENT and QUO_EVENT use the C++20 __VA_OPT__ feature that is only available with the new MSVC preprocessor (see https://docs.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview); the respective switch was added to CMakeLists.txt. --- lib/events/callanswerevent.h | 3 +- lib/events/callcandidatesevent.h | 4 +- lib/events/callhangupevent.h | 4 +- lib/events/callinviteevent.h | 4 +- lib/events/directchatevent.h | 3 +- lib/events/encryptedevent.h | 4 +- lib/events/encryptionevent.h | 3 +- lib/events/event.cpp | 41 +++- lib/events/event.h | 355 ++++++++++++++++++++++++----------- lib/events/keyverificationevent.h | 26 +-- lib/events/receiptevent.h | 3 +- lib/events/redactionevent.h | 3 +- lib/events/roomavatarevent.h | 3 +- lib/events/roomcanonicalaliasevent.h | 3 +- lib/events/roomcreateevent.h | 3 +- lib/events/roomevent.h | 16 +- lib/events/roomkeyevent.h | 3 +- lib/events/roommemberevent.h | 12 +- lib/events/roommessageevent.h | 4 +- lib/events/roompowerlevelsevent.h | 3 +- lib/events/roomtombstoneevent.h | 3 +- lib/events/simplestateevents.h | 5 +- lib/events/stateevent.h | 30 +-- lib/events/stickerevent.h | 3 +- 24 files changed, 325 insertions(+), 216 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 4d539b85..70ca1c7e 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -9,7 +9,7 @@ namespace Quotient { class QUOTIENT_API CallAnswerEvent : public CallEventBase { public: - DEFINE_EVENT_TYPEID("m.call.answer", CallAnswerEvent) + QUO_EVENT(CallAnswerEvent, "m.call.answer") explicit CallAnswerEvent(const QJsonObject& obj); @@ -20,5 +20,4 @@ public: return contentPart("answer"_ls).value("sdp"_ls).toString(); } }; -REGISTER_EVENT_TYPE(CallAnswerEvent) } // namespace Quotient diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index e949f722..cb96f358 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -11,7 +11,7 @@ namespace Quotient { class CallCandidatesEvent : public CallEventBase { public: - DEFINE_EVENT_TYPEID("m.call.candidates", CallCandidatesEvent) + QUO_EVENT(CallCandidatesEvent, "m.call.candidates") explicit CallCandidatesEvent(const QJsonObject& obj) : CallEventBase(typeId(), obj) @@ -27,6 +27,4 @@ public: QUO_CONTENT_GETTER(QString, callId) QUO_CONTENT_GETTER(int, version) }; - -REGISTER_EVENT_TYPE(CallCandidatesEvent) } // namespace Quotient diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index b0017c59..e4d9bb78 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -9,7 +9,7 @@ namespace Quotient { class QUOTIENT_API CallHangupEvent : public CallEventBase { public: - DEFINE_EVENT_TYPEID("m.call.hangup", CallHangupEvent) + QUO_EVENT(CallHangupEvent, "m.call.hangup") explicit CallHangupEvent(const QJsonObject& obj) : CallEventBase(typeId(), obj) @@ -18,6 +18,4 @@ public: : CallEventBase(typeId(), matrixTypeId(), callId, 0) {} }; - -REGISTER_EVENT_TYPE(CallHangupEvent) } // namespace Quotient diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 5b4ca0df..f96f416d 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -9,7 +9,7 @@ namespace Quotient { class QUOTIENT_API CallInviteEvent : public CallEventBase { public: - DEFINE_EVENT_TYPEID("m.call.invite", CallInviteEvent) + QUO_EVENT(CallInviteEvent, "m.call.invite") explicit CallInviteEvent(const QJsonObject& obj); @@ -22,6 +22,4 @@ public: return contentPart("offer"_ls).value("sdp"_ls).toString(); } }; - -REGISTER_EVENT_TYPE(CallInviteEvent) } // namespace Quotient diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index 2018d3d6..942edba4 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -8,11 +8,10 @@ namespace Quotient { class QUOTIENT_API DirectChatEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.direct", DirectChatEvent) + QUO_EVENT(DirectChatEvent, "m.direct") explicit DirectChatEvent(const QJsonObject& obj) : Event(typeId(), obj) {} QMultiHash usersToDirectChats() const; }; -REGISTER_EVENT_TYPE(DirectChatEvent) } // namespace Quotient diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index ddd5e415..22e51cb8 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -27,7 +27,7 @@ namespace Quotient { */ class QUOTIENT_API EncryptedEvent : public RoomEvent { public: - DEFINE_EVENT_TYPEID("m.room.encrypted", EncryptedEvent) + QUO_EVENT(EncryptedEvent, "m.room.encrypted") /* In case with Olm, the encrypted content of the event is * a map from the recipient Curve25519 identity key to ciphertext @@ -59,6 +59,4 @@ public: void setRelation(const QJsonObject& relation); }; -REGISTER_EVENT_TYPE(EncryptedEvent) - } // namespace Quotient diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 91452c3f..60e77451 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -28,7 +28,7 @@ public: class QUOTIENT_API EncryptionEvent : public StateEvent { public: - DEFINE_EVENT_TYPEID("m.room.encryption", EncryptionEvent) + QUO_EVENT(EncryptionEvent, "m.room.encryption") using EncryptionType [[deprecated("Use Quotient::EncryptionType instead")]] = @@ -48,5 +48,4 @@ public: bool useEncryption() const { return !algorithm().isEmpty(); } }; -REGISTER_EVENT_TYPE(EncryptionEvent) } // namespace Quotient diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 1f1eebaa..595e20a5 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -4,6 +4,7 @@ #include "event.h" #include "logging.h" +#include "stateevent.h" #include @@ -11,12 +12,38 @@ using namespace Quotient; QString EventTypeRegistry::getMatrixType(event_type_t typeId) { return typeId; } -void _impl::EventFactoryBase::logAddingMethod(event_type_t TypeId, - size_t newSize) +void AbstractEventMetaType::addDerived(AbstractEventMetaType* newType) { - qDebug(EVENTS) << "Adding factory method for" << TypeId << "events;" - << newSize << "methods will be in the" << name - << "chain"; + if (const auto existing = + std::find_if(derivedTypes.cbegin(), derivedTypes.cend(), + [&newType](const AbstractEventMetaType* t) { + return t->matrixId == newType->matrixId; + }); + existing != derivedTypes.cend()) + { + if (*existing == newType) + return; + // Two different metatype objects claim the same Matrix type id; this + // is not normal, so give as much information as possible to diagnose + if ((*existing)->className == newType->className) { + qCritical(EVENTS) + << newType->className << "claims" << newType->matrixId + << "repeatedly; check that it's exported across translation " + "units or shared objects"; + Q_ASSERT(false); // That situation is plain wrong + return; // So maybe std::terminate() even? + } + qWarning(EVENTS).nospace() + << newType->matrixId << " is already mapped to " + << (*existing)->className << " before " << newType->className + << "; unless the two have different isValid() conditions, the " + "latter class will never be used"; + } + derivedTypes.emplace_back(newType); + qDebug(EVENTS).nospace() + << newType->matrixId << " -> " << newType->className << "; " + << derivedTypes.size() << " derived type(s) registered for " + << className; } Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) @@ -48,6 +75,10 @@ const QJsonObject Event::unsignedJson() const return fullJson()[UnsignedKeyL].toObject(); } +bool Event::isStateEvent() const { return is(); } + +bool Event::isCallEvent() const { return is(); } + void Event::dumpTo(QDebug dbg) const { dbg << QJsonDocument(contentJson()).toJson(QJsonDocument::Compact); diff --git a/lib/events/event.h b/lib/events/event.h index 711f8fd4..ea827244 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -85,91 +85,167 @@ inline event_ptr_tt makeEvent(ArgTs&&... args) return std::make_unique(std::forward(args)...); } -namespace _impl { - class QUOTIENT_API EventFactoryBase { - public: - EventFactoryBase(const EventFactoryBase&) = delete; - - protected: // This class is only to inherit from - explicit EventFactoryBase(const char* name) - : name(name) - {} - void logAddingMethod(event_type_t TypeId, size_t newSize); - - private: - const char* const name; - }; -} // namespace _impl - -//! \brief A family of event factories to create events from CS API responses -//! -//! Each of these factories, as instantiated by event base types (Event, -//! RoomEvent etc.) is capable of producing an event object derived from -//! \p BaseEventT, using the JSON payload and the event type passed to its -//! make() method. Don't use these directly to make events; use loadEvent() -//! overloads as the frontend for these. Never instantiate new factories -//! outside of base event classes. -//! \sa loadEvent, setupFactory, Event::factory, RoomEvent::factory, -//! StateEventBase::factory -template -class EventFactory : public _impl::EventFactoryBase { -private: - using method_t = event_ptr_tt (*)(const QJsonObject&, - const QString&); - std::vector methods {}; +// === EventMetaType === - template - static event_ptr_tt makeIfMatches(const QJsonObject& json, - const QString& matrixType) +class Event; + +template +bool is(const Event& e); + +//! \brief The base class for event metatypes +//! +//! You should not normally have to use this directly, unless you need to devise +//! a whole new kind of event metatypes. +class QUOTIENT_API AbstractEventMetaType { +public: + // The public fields here are const and are not to be changeable anyway. + // NOLINTBEGIN(misc-non-private-member-variables-in-classes) + const char* const className; + const event_type_t matrixId; + const AbstractEventMetaType* const baseType = nullptr; + // NOLINTEND(misc-non-private-member-variables-in-classes) + + explicit AbstractEventMetaType(const char* className) + : className(className) + {} + explicit AbstractEventMetaType(const char* className, event_type_t matrixId, + AbstractEventMetaType& nearestBase) + : className(className), matrixId(matrixId), baseType(&nearestBase) { - // If your matrix event type is not all ASCII, it's your problem - // (see https://github.com/matrix-org/matrix-doc/pull/2758) - return EventT::TypeId == matrixType ? makeEvent(json) : nullptr; + nearestBase.addDerived(this); } + void addDerived(AbstractEventMetaType *newType); + + virtual ~AbstractEventMetaType() = default; + +protected: + // Allow template specialisations to call into one another + template + friend class EventMetaType; + + // The returned value indicates whether a generic object has to be created + // on the top level when `event` is empty, instead of returning nullptr + virtual bool doLoadFrom(const QJsonObject& fullJson, const QString& type, + Event*& event) const = 0; + +private: + std::vector derivedTypes{}; + Q_DISABLE_COPY_MOVE(AbstractEventMetaType) +}; + +// Any event metatype is unique (note Q_DISABLE_COPY_MOVE above) so can be +// identified by its address +inline bool operator==(const AbstractEventMetaType& lhs, + const AbstractEventMetaType& rhs) +{ + return &lhs == &rhs; +} + +//! \brief A family of event meta-types to load and match events +//! +//! TL;DR for the loadFrom() story: +//! - for base event types, use QUO_BASE_EVENT and, if you have additional +//! validation (e.g., JSON has to contain a certain key - see StateEventBase +//! for a real example), define it in the static EventT::isValid() member +//! function accepting QJsonObject and returning bool. +//! - for leaf (specific) event types - simply use QUO_EVENT and it will do +//! everything necessary, including the TypeId definition. +//! \sa QUO_EVENT, QUO_BASE_EVENT +template +class QUOTIENT_API EventMetaType : public AbstractEventMetaType { + // Above: can't constrain EventT to be EventClass because it's incomplete + // at the point of EventMetaType instantiation. public: - explicit EventFactory(const char* fName) - : EventFactoryBase { fName } - {} + using AbstractEventMetaType::AbstractEventMetaType; - //! \brief Add a method to create events of a given type + //! \brief Try to load an event from JSON, with dynamic type resolution //! - //! Adds a standard factory method (makeIfMatches) for \p EventT so that - //! event objects of this type can be created dynamically by loadEvent. - //! The caller is responsible for ensuring this method is called only - //! once per type. - //! \sa loadEvent, Quotient::loadEvent - template - const auto& addMethod() + //! The generic logic defined in this class template and invoked applies to + //! all event types defined in the library and boils down to the following: + //! 1. + //! a. If EventT has TypeId defined (which normally is a case of + //! all leaf - specific - event types, via QUO_EVENT macro) and + //! \p type doesn't exactly match it, nullptr is immediately returned. + //! b. In absence of TypeId, an event type is assumed to be a base; + //! its derivedTypes are examined, and this algorithm is applied + //! recursively on each. + //! 2. Optional validation: if EventT (or, due to the way inheritance works, + //! any of its base event types) has a static isValid() predicate and + //! the event JSON does not satisfy it, nullptr is immediately returned + //! to the upper level or to the loadFrom() caller. This is how existence + //! of `state_key` is checked in any type derived from StateEventBase. + //! 3. If step 1b above returned non-nullptr, immediately return it. + //! 4. + //! a. If EventT::isValid() or EventT::TypeId (either, or both) exist and + //! are satisfied (see steps 1a and 2 above), an object of this type + //! is created from the passed JSON and returned. In case of a base + //! event type, this will be a generic (aka "unknown") event. + //! b. If neither exists, a generic event is only created and returned + //! when on the top level (i.e., outside of recursion into + //! derivedTypes); lower levels return nullptr instead and the type + //! lookup continues. The latter is a case of a derived base event + //! metatype (e.g. RoomEvent) called from its base event metatype + //! (i.e., Event). If no matching type derived from RoomEvent is found, + //! the nested lookup returns nullptr rather than a generic RoomEvent, + //! so that other types derived from Event could be examined. + event_ptr_tt loadFrom(const QJsonObject& fullJson, + const QString& type) const { - const auto m = &makeIfMatches; - const auto it = std::find(methods.cbegin(), methods.cend(), m); - if (it != methods.cend()) - return *it; - logAddingMethod(EventT::TypeId, methods.size() + 1); - return methods.emplace_back(m); + Event* event = nullptr; + const bool goodEnough = doLoadFrom(fullJson, type, event); + if (!event && goodEnough) + return event_ptr_tt{ makeEvent(fullJson) }; + return event_ptr_tt{ static_cast(event) }; } - auto loadEvent(const QJsonObject& json, const QString& matrixType) +private: + bool doLoadFrom(const QJsonObject& fullJson, const QString& type, + Event*& event) const override + { + if constexpr (requires { EventT::TypeId; }) { + if (EventT::TypeId != type) + return false; + } else { + for (const auto& p : derivedTypes) { + p->doLoadFrom(fullJson, type, event); + if (event) { + Q_ASSERT(is(*event)); + return false; + } + } + } + if constexpr (requires { EventT::isValid; }) { + if (!EventT::isValid(fullJson)) + return false; + } else if constexpr (!requires { EventT::TypeId; }) + return true; // Create a generic event object if on the top level + event = makeEvent(fullJson); + return false; + } + static auto makeEvent(const QJsonObject& fullJson) { - for (const auto& f : methods) - if (auto e = f(json, matrixType)) - return e; - return makeEvent(UnknownEventTypeId, json); + if constexpr (requires { EventT::TypeId; }) + return new EventT(fullJson); + else + return new EventT(UnknownEventTypeId, fullJson); } }; -//! \brief Point of customisation to dynamically load events -//! -//! The default specialisation of this calls BaseEventT::factory.loadEvent() -//! and if that fails (i.e. returns nullptr) creates an unknown event of -//! BaseEventT. Other specialisations may reuse other factories, add validations -//! common to BaseEventT events, and so on. -template -event_ptr_tt doLoadEvent(const QJsonObject& json, - const QString& matrixType) +template +constexpr const auto& mostSpecificMetaType() { - return BaseEventT::factory.loadEvent(json, matrixType); + if constexpr (requires { EventT::MetaType; }) + return EventT::MetaType; + else + return EventT::BaseMetaType; +} + +template +inline event_ptr_tt doLoadEvent(const QJsonObject& json, + const QString& matrixType) +{ + return mostSpecificMetaType().loadFrom(json, matrixType); } // === Event === @@ -177,7 +253,12 @@ event_ptr_tt doLoadEvent(const QJsonObject& json, class QUOTIENT_API Event { public: using Type = event_type_t; - static inline EventFactory factory { "Event" }; + static inline EventMetaType BaseMetaType { "Event" }; + virtual const AbstractEventMetaType& metaType() const + { + return BaseMetaType; + } + explicit Event(Type type, const QJsonObject& json); explicit Event(Type type, event_mtype_t matrixType, @@ -194,8 +275,26 @@ public: return { { TypeKey, matrixType }, { ContentKey, content } }; } - Type type() const { return _type; } + //! \brief Event Matrix type, as identified by its metatype object + //! + //! For generic/unknown events it will contain a descriptive/generic string + //! defined by the respective base event type (that can be empty). + //! \sa matrixType + Type type() const { return metaType().matrixId; } + + //! \brief Exact Matrix type stored in JSON + //! + //! Coincides with the result of type() (but is slower) for events defined + //! in C++ (not necessarily in the library); for generic/unknown events + //! the returned value will be different. QString matrixType() const; + + template + bool is() const + { + return Quotient::is(*this); + } + [[deprecated("Use fullJson() and stringify it with QJsonDocument::toJson() " "or by other means")]] QByteArray originalJson() const; @@ -237,13 +336,17 @@ public: friend QUOTIENT_API QDebug operator<<(QDebug dbg, const Event& e) { QDebugStateSaver _dss { dbg }; - dbg.noquote().nospace() << e.matrixType() << '(' << e.type() << "): "; + dbg.noquote().nospace() + << e.matrixType() << '(' << e.metaType().className << "): "; e.dumpTo(dbg); return dbg; } - virtual bool isStateEvent() const { return false; } - virtual bool isCallEvent() const { return false; } + // State events are quite special in Matrix; so isStateEvent() is here, + // as an exception. For other base events, Event::is<>() and + // Quotient::is<>() should be used; don't add is* methods here + bool isStateEvent() const; + [[deprecated("Use is() instead")]] bool isCallEvent() const; protected: QJsonObject& editJson() { return _json; } @@ -259,11 +362,64 @@ template using EventsArray = std::vector>; using Events = EventsArray; +// === Facilities for event class definitions === + +//! \brief Supply event metatype information in base event types +//! +//! Use this macro in a public section of your base event class to provide +//! type identity and enable dynamic loading of generic events of that type. +//! Do _not_ add this macro if your class is an intermediate wrapper and is not +//! supposed to be instantiated on its own. Provides BaseMetaType static field +//! initialised by parameters passed to the macro, and a metaType() override +//! pointing to that BaseMetaType. +//! \sa EventMetaType, EventMetaType::SuppressLoadDerived +#define QUO_BASE_EVENT(CppType_, ...) \ + static inline EventMetaType BaseMetaType{ \ + #CppType_ __VA_OPT__(,) __VA_ARGS__ }; \ + const AbstractEventMetaType& metaType() const override \ + { \ + return BaseMetaType; \ + } \ + // End of macro + +//! Supply event metatype information in (specific) event types +//! +//! Use this macro in a public section of your event class to provide type +//! identity and enable dynamic loading of generic events of that type. +//! Do _not_ use this macro if your class is an intermediate wrapper and is not +//! supposed to be instantiated on its own. Provides MetaType static field +//! initialised as described below; a metaType() override pointing to it; and +//! the TypeId static field that is equal to MetaType.matrixId. +//! +//! The first two macro parameters are used as the first two EventMetaType +//! constructor parameters; the third EventMetaType parameter is always +//! BaseMetaType; and additional base types can be passed in extra macro +//! parameters if you need to include the same event type in more than one +//! event factory hierarchy (e.g., EncryptedEvent). +//! \sa EventMetaType +#define QUO_EVENT(CppType_, MatrixType_, ...) \ + static inline const auto& TypeId = MatrixType_##_ls; \ + static inline const EventMetaType MetaType{ \ + #CppType_, TypeId, BaseMetaType __VA_OPT__(,) __VA_ARGS__ \ + }; \ + const AbstractEventMetaType& metaType() const override \ + { \ + return MetaType; \ + } \ + [[deprecated("Use " #CppType_ "::TypeId directly instead")]] \ + static constexpr const char* matrixTypeId() { return MatrixType_; } \ + [[deprecated("Use " #CppType_ "::TypeId directly instead")]] \ + static event_type_t typeId() { return TypeId; } \ + // End of macro + +//! \deprecated This is the old name for what is now known as QUO_EVENT +#define DEFINE_EVENT_TYPEID(Type_, Id_) QUO_EVENT(Type_, Id_) + #define QUO_CONTENT_GETTER_X(PartType_, PartName_, JsonKey_) \ - PartType_ PartName_() const \ - { \ - static const auto PartName_##JsonKey = JsonKey_; \ - return contentPart(PartName_##JsonKey); \ + PartType_ PartName_() const \ + { \ + static const auto PartName_##JsonKey = JsonKey_; \ + return contentPart(PartName_##JsonKey); \ } //! \brief Define an inline method obtaining a content part @@ -277,25 +433,9 @@ using Events = EventsArray; #define QUO_CONTENT_GETTER(PartType_, PartName_) \ QUO_CONTENT_GETTER_X(PartType_, PartName_, toSnakeCase(#PartName_##_ls)) -// === Facilities for event class definitions === - -// This macro should be used in a public section of an event class to -// provide matrixTypeId() and typeId(). -#define DEFINE_EVENT_TYPEID(Id_, Type_) \ - static constexpr event_type_t TypeId = Id_##_ls; \ - [[deprecated("Use " #Type_ "::TypeId directly instead")]] \ - static constexpr event_mtype_t matrixTypeId() { return Id_; } \ - [[deprecated("Use " #Type_ "::TypeId directly instead")]] \ - static event_type_t typeId() { return TypeId; } \ - // End of macro - -// This macro should be put after an event class definition (in .h or .cpp) -// to enable its deserialisation from a /sync and other -// polymorphic event arrays -#define REGISTER_EVENT_TYPE(Type_) \ - [[maybe_unused]] inline const auto& factoryMethodFor##Type_ = \ - Type_::factory.addMethod(); \ - // End of macro +//! \deprecated This macro was used after an event class definition +//! to enable its dynamic loading; it is completely superseded by QUO_EVENT +#define REGISTER_EVENT_TYPE(Type_) /// \brief Define a new event class with a single key-value pair in the content /// @@ -309,7 +449,7 @@ using Events = EventsArray; JsonKey_) \ class QUOTIENT_API Name_ : public Base_ { \ public: \ - DEFINE_EVENT_TYPEID(TypeId_, Name_) \ + QUO_EVENT(Name_, TypeId_) \ using value_type = ValueType_; \ explicit Name_(const QJsonObject& obj) : Base_(TypeId, obj) {} \ explicit Name_(const value_type& v) \ @@ -318,7 +458,6 @@ using Events = EventsArray; QUO_CONTENT_GETTER_X(ValueType_, GetterName_, JsonKey) \ static inline const auto JsonKey = toSnakeCase(#GetterName_##_ls); \ }; \ - REGISTER_EVENT_TYPE(Name_) \ // End of macro // === is<>(), eventCast<>() and switchOnType<>() === @@ -326,12 +465,16 @@ using Events = EventsArray; template inline bool is(const Event& e) { - return e.type() == typeId(); -} - -inline bool isUnknown(const Event& e) -{ - return e.type() == UnknownEventTypeId; + if constexpr (requires { EventT::MetaType; }) { + return &e.metaType() == &EventT::MetaType; + } else { + const auto* p = &e.metaType(); + do { + if (p == &EventT::BaseMetaType) + return true; + } while ((p = p->baseType) != nullptr); + return false; + } } //! \brief Cast the event pointer down in a type-safe way diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 5b587522..5b5a518f 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -13,7 +13,7 @@ static constexpr auto SasV1Method = "m.sas.v1"_ls; /// Typically sent as a to-device event. class QUOTIENT_API KeyVerificationRequestEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.request", KeyVerificationRequestEvent) + QUO_EVENT(KeyVerificationRequestEvent, "m.key.verification.request") explicit KeyVerificationRequestEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -45,11 +45,10 @@ public: /// by the receiver. QUO_CONTENT_GETTER(QDateTime, timestamp) }; -REGISTER_EVENT_TYPE(KeyVerificationRequestEvent) class QUOTIENT_API KeyVerificationReadyEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.ready", KeyVerificationReadyEvent) + QUO_EVENT(KeyVerificationReadyEvent, "m.key.verification.ready") explicit KeyVerificationReadyEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -72,13 +71,11 @@ public: /// The verification methods supported by the sender. QUO_CONTENT_GETTER(QStringList, methods) }; -REGISTER_EVENT_TYPE(KeyVerificationReadyEvent) - /// Begins a key verification process. class QUOTIENT_API KeyVerificationStartEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.start", KeyVerificationStartEvent) + QUO_EVENT(KeyVerificationStartEvent, "m.key.verification.start") explicit KeyVerificationStartEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -146,13 +143,12 @@ public: return contentPart("short_authentification_string"_ls); } }; -REGISTER_EVENT_TYPE(KeyVerificationStartEvent) /// Accepts a previously sent m.key.verification.start message. /// Typically sent as a to-device event. class QUOTIENT_API KeyVerificationAcceptEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.accept", KeyVerificationAcceptEvent) + QUO_EVENT(KeyVerificationAcceptEvent, "m.key.verification.accept") explicit KeyVerificationAcceptEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -199,11 +195,10 @@ public: /// canonical JSON representation of the m.key.verification.start message. QUO_CONTENT_GETTER(QString, commitment) }; -REGISTER_EVENT_TYPE(KeyVerificationAcceptEvent) class QUOTIENT_API KeyVerificationCancelEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.cancel", KeyVerificationCancelEvent) + QUO_EVENT(KeyVerificationCancelEvent, "m.key.verification.cancel") explicit KeyVerificationCancelEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -228,13 +223,12 @@ public: /// The error code for why the process/request was cancelled by the user. QUO_CONTENT_GETTER(QString, code) }; -REGISTER_EVENT_TYPE(KeyVerificationCancelEvent) /// Sends the ephemeral public key for a device to the partner device. /// Typically sent as a to-device event. class QUOTIENT_API KeyVerificationKeyEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.key", KeyVerificationKeyEvent) + QUO_EVENT(KeyVerificationKeyEvent, "m.key.verification.key") explicit KeyVerificationKeyEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -251,12 +245,11 @@ public: /// The device's ephemeral public key, encoded as unpadded base64. QUO_CONTENT_GETTER(QString, key) }; -REGISTER_EVENT_TYPE(KeyVerificationKeyEvent) /// Sends the MAC of a device's key to the partner device. class QUOTIENT_API KeyVerificationMacEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.mac", KeyVerificationMacEvent) + QUO_EVENT(KeyVerificationMacEvent, "m.key.verification.mac") explicit KeyVerificationMacEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -280,11 +273,10 @@ public: return contentPart>("mac"_ls); } }; -REGISTER_EVENT_TYPE(KeyVerificationMacEvent) class QUOTIENT_API KeyVerificationDoneEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.key.verification.done", KeyVerificationDoneEvent) + QUO_EVENT(KeyVerificationDoneEvent, "m.key.verification.done") explicit KeyVerificationDoneEvent(const QJsonObject& obj) : Event(TypeId, obj) @@ -297,6 +289,4 @@ public: /// The same transactionId as before QUO_CONTENT_GETTER(QString, transactionId) }; -REGISTER_EVENT_TYPE(KeyVerificationDoneEvent) - } // namespace Quotient diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index 5e077e47..a02f4592 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -21,11 +21,10 @@ using EventsWithReceipts = QVector; class QUOTIENT_API ReceiptEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) + QUO_EVENT(ReceiptEvent, "m.receipt") explicit ReceiptEvent(const EventsWithReceipts& ewrs); explicit ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) {} EventsWithReceipts eventsWithReceipts() const; }; -REGISTER_EVENT_TYPE(ReceiptEvent) } // namespace Quotient diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index 63617e54..c193054a 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -8,7 +8,7 @@ namespace Quotient { class QUOTIENT_API RedactionEvent : public RoomEvent { public: - DEFINE_EVENT_TYPEID("m.room.redaction", RedactionEvent) + QUO_EVENT(RedactionEvent, "m.room.redaction") explicit RedactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} @@ -19,5 +19,4 @@ public: } QUO_CONTENT_GETTER(QString, reason) }; -REGISTER_EVENT_TYPE(RedactionEvent) } // namespace Quotient diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index af291696..2ebe29bf 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -14,7 +14,7 @@ class QUOTIENT_API RoomAvatarEvent // without a thumbnail. But The Spec says there be thumbnails, and // we follow The Spec. public: - DEFINE_EVENT_TYPEID("m.room.avatar", RoomAvatarEvent) + QUO_EVENT(RoomAvatarEvent, "m.room.avatar") explicit RoomAvatarEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} explicit RoomAvatarEvent(const EventContent::ImageContent& avatar) @@ -31,5 +31,4 @@ public: QUrl url() const { return content().url(); } }; -REGISTER_EVENT_TYPE(RoomAvatarEvent) } // namespace Quotient diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index 60ca68ac..e1c7888e 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -34,7 +34,7 @@ inline auto toJson(const EventContent::AliasesEventContent& c) class QUOTIENT_API RoomCanonicalAliasEvent : public StateEvent { public: - DEFINE_EVENT_TYPEID("m.room.canonical_alias", RoomCanonicalAliasEvent) + QUO_EVENT(RoomCanonicalAliasEvent, "m.room.canonical_alias") explicit RoomCanonicalAliasEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) @@ -55,5 +55,4 @@ public: QString alias() const { return content().canonicalAlias; } QStringList altAliases() const { return content().altAliases; } }; -REGISTER_EVENT_TYPE(RoomCanonicalAliasEvent) } // namespace Quotient diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 989030ac..f22752b4 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -9,7 +9,7 @@ namespace Quotient { class QUOTIENT_API RoomCreateEvent : public StateEventBase { public: - DEFINE_EVENT_TYPEID("m.room.create", RoomCreateEvent) + QUO_EVENT(RoomCreateEvent, "m.room.create") explicit RoomCreateEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) @@ -26,5 +26,4 @@ public: bool isUpgrade() const; RoomType roomType() const; }; -REGISTER_EVENT_TYPE(RoomCreateEvent) } // namespace Quotient diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 9461340b..532e72e2 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -10,10 +10,11 @@ namespace Quotient { class RedactionEvent; -/** This class corresponds to m.room.* events */ +// That check could look into Event and find most stuff already deleted... +// NOLINTNEXTLINE(cppcoreguidelines-special-member-functions) class QUOTIENT_API RoomEvent : public Event { public: - static inline EventFactory factory { "RoomEvent" }; + QUO_BASE_EVENT(RoomEvent, {}, Event::BaseMetaType) // RedactionEvent is an incomplete type here so we cannot inline // constructors and destructors and we cannot use 'using'. @@ -80,21 +81,14 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; -template <> -inline EventPtr doLoadEvent(const QJsonObject& json, const QString& matrixType) -{ - if (matrixType == "m.room.encrypted") - return RoomEvent::factory.loadEvent(json, matrixType); - return Event::factory.loadEvent(json, matrixType); -} - class QUOTIENT_API CallEventBase : public RoomEvent { public: + QUO_BASE_EVENT(CallEventBase, "m.call.*"_ls, RoomEvent::BaseMetaType) + CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, int version, const QJsonObject& contentJson = {}); CallEventBase(Type type, const QJsonObject& json); ~CallEventBase() override = default; - bool isCallEvent() const override { return true; } QUO_CONTENT_GETTER(QString, callId) QUO_CONTENT_GETTER(int, version) diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 0dfdf383..6883a2a5 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -9,7 +9,7 @@ namespace Quotient { class QUOTIENT_API RoomKeyEvent : public Event { public: - DEFINE_EVENT_TYPEID("m.room_key", RoomKeyEvent) + QUO_EVENT(RoomKeyEvent, "m.room_key") explicit RoomKeyEvent(const QJsonObject& obj); explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, @@ -23,5 +23,4 @@ public: return contentPart("session_key"_ls).toLatin1(); } }; -REGISTER_EVENT_TYPE(RoomKeyEvent) } // namespace Quotient diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index dd33ea6b..c690586e 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -31,7 +31,7 @@ using MembershipType [[deprecated("Use Membership instead")]] = Membership; class QUOTIENT_API RoomMemberEvent : public StateEvent { Q_GADGET public: - DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) + QUO_EVENT(RoomMemberEvent, "m.room.member") using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; @@ -79,14 +79,4 @@ public: bool isRename() const; bool isAvatarUpdate() const; }; - -template <> -inline event_ptr_tt -doLoadEvent(const QJsonObject& json, const QString& matrixType) -{ - if (matrixType == QLatin1String(RoomMemberEvent::matrixTypeId())) - return makeEvent(json); - return makeEvent(unknownEventTypeId(), json); -} -REGISTER_EVENT_TYPE(RoomMemberEvent) } // namespace Quotient diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 6968ad70..889fc4dc 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -20,7 +20,7 @@ namespace MessageEventContent = EventContent; // Back-compatibility class QUOTIENT_API RoomMessageEvent : public RoomEvent { Q_GADGET public: - DEFINE_EVENT_TYPEID("m.room.message", RoomMessageEvent) + QUO_EVENT(RoomMessageEvent, "m.room.message") enum class MsgType { Text, @@ -94,7 +94,7 @@ private: Q_ENUM(MsgType) }; -REGISTER_EVENT_TYPE(RoomMessageEvent) + using MessageEventType = RoomMessageEvent::MsgType; namespace EventContent { diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index a1638a27..7ac12db0 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -33,7 +33,7 @@ struct QUOTIENT_API PowerLevelsEventContent { class QUOTIENT_API RoomPowerLevelsEvent : public StateEvent { public: - DEFINE_EVENT_TYPEID("m.room.power_levels", RoomPowerLevelsEvent) + QUO_EVENT(RoomPowerLevelsEvent, "m.room.power_levels") explicit RoomPowerLevelsEvent(PowerLevelsEventContent&& content) : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) @@ -61,5 +61,4 @@ public: int powerLevelForState(const QString& eventId) const; int powerLevelForUser(const QString& userId) const; }; -REGISTER_EVENT_TYPE(RoomPowerLevelsEvent) } // namespace Quotient diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 15d26923..97586587 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -8,7 +8,7 @@ namespace Quotient { class QUOTIENT_API RoomTombstoneEvent : public StateEventBase { public: - DEFINE_EVENT_TYPEID("m.room.tombstone", RoomTombstoneEvent) + QUO_EVENT(RoomTombstoneEvent, "m.room.tombstone") explicit RoomTombstoneEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) @@ -17,5 +17,4 @@ public: QString serverMessage() const; QString successorRoomId() const; }; -REGISTER_EVENT_TYPE(RoomTombstoneEvent) } // namespace Quotient diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index a8eaab56..c79d03b0 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -14,7 +14,7 @@ namespace Quotient { EventContent::SingleKeyValue<_ValueType, &_Name##Key>> { \ public: \ using value_type = _ValueType; \ - DEFINE_EVENT_TYPEID(_TypeId, _Name) \ + QUO_EVENT(_Name, _TypeId) \ template \ explicit _Name(T&& value) \ : StateEvent(TypeId, matrixTypeId(), QString(), \ @@ -25,7 +25,6 @@ namespace Quotient { {} \ auto _ContentKey() const { return content().value; } \ }; \ - REGISTER_EVENT_TYPE(_Name) \ // End of macro DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) @@ -38,7 +37,7 @@ class QUOTIENT_API RoomAliasesEvent : public StateEvent< EventContent::SingleKeyValue> { public: - DEFINE_EVENT_TYPEID("m.room.aliases", RoomAliasesEvent) + QUO_EVENT(RoomAliasesEvent, "m.room.aliases") explicit RoomAliasesEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 9f1d7118..74876803 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -9,7 +9,12 @@ namespace Quotient { class QUOTIENT_API StateEventBase : public RoomEvent { public: - static inline EventFactory factory { "StateEvent" }; + QUO_BASE_EVENT(StateEventBase, "json.contains('state_key')"_ls, + RoomEvent::BaseMetaType) + static bool isValid(const QJsonObject& fullJson) + { + return fullJson.contains(StateKeyKeyL); + } StateEventBase(Type type, const QJsonObject& json); StateEventBase(Type type, event_mtype_t matrixType, @@ -27,7 +32,6 @@ public: { ContentKey, contentJson } }; } - bool isStateEvent() const override { return true; } QString replacedState() const; void dumpTo(QDebug dbg) const override; @@ -44,28 +48,6 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, return StateEventBase::basicJson(matrixTypeId, stateKey, content); } -//! \brief Override RoomEvent factory with that from StateEventBase if JSON has -//! stateKey -//! -//! This means in particular that an event with a type known to RoomEvent but -//! having stateKey set (even to an empty value) will be treated as a state -//! event and most likely end up as unknown (consider, e.g., m.room.message -//! that has stateKey set). -template <> -inline RoomEventPtr doLoadEvent(const QJsonObject& json, - const QString& matrixType) -{ - if (json.contains(StateKeyKeyL)) - return StateEventBase::factory.loadEvent(json, matrixType); - return RoomEvent::factory.loadEvent(json, matrixType); -} - -template <> -inline bool is(const Event& e) -{ - return e.isStateEvent(); -} - /** * A combination of event type and state key uniquely identifies a piece * of state in Matrix. diff --git a/lib/events/stickerevent.h b/lib/events/stickerevent.h index e378422d..67905481 100644 --- a/lib/events/stickerevent.h +++ b/lib/events/stickerevent.h @@ -14,7 +14,7 @@ namespace Quotient { class QUOTIENT_API StickerEvent : public RoomEvent { public: - DEFINE_EVENT_TYPEID("m.sticker", StickerEvent) + QUO_EVENT(StickerEvent, "m.sticker") explicit StickerEvent(const QJsonObject& obj) : RoomEvent(TypeId, obj) @@ -45,5 +45,4 @@ public: private: EventContent::ImageContent m_imageContent; }; -REGISTER_EVENT_TYPE(StickerEvent) } // namespace Quotient -- cgit v1.2.3 From 17cd3beaefa5501a902e08c7644e8cd97c9091a0 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Fri, 12 Aug 2022 16:46:01 +0200 Subject: Streamline event types This commit introduces a few things to further reduce the boilerplate across event type definitions: - Event type is no more separately stored in Event and therefore no more passed to base event constructors. Until the previous commit, it was used by is() to quickly match the event type; with the new event metatype class, the same is achieved even quicker by comparing metatype pointers. - EventTemplate is a generalisation of StateEvent for all event types providing common constructor signatures and content() for (most) leaf event types. StateEvent therefore has become a partial specialisation of EventTemplate for types derived from StateEventBase; as the known client code base does not use it directly, a compatibility alias is not provided. Also, DEFINE_SIMPLE_EVENT now expands into a class deriving from EventTemplate. - On top of StateEvent->EventTemplate specialisation, KeyedStateEventBase and KeylessStateEventBase types are introduced with appropriate constructor signatures (with or without state_key, respectively) to allow `using` of them from derived event types. To facilitate writing of constraints, concepts for keyed and keyless state event types are also introduced; RoomStateView, e.g., makes use of those to provide appropriate method signatures. - typeId(), unknownEventTypeId(), UnknownEventTypeId are no more provided - they weren't used throughout the known code base (Quaternion, NeoChat), and the concept of "unknown event types" is hereby eliminated entirely. - RoomKeyEvent no more accepts senderId as a parameter; it has never been a good practice as the sender is assigned by Connection anyway. --- lib/events/callanswerevent.cpp | 15 +-- lib/events/callanswerevent.h | 5 +- lib/events/callcandidatesevent.h | 9 +- lib/events/callhangupevent.h | 12 +-- lib/events/callinviteevent.cpp | 9 +- lib/events/callinviteevent.h | 5 +- lib/events/directchatevent.h | 2 +- lib/events/encryptedevent.cpp | 22 ++--- lib/events/encryptionevent.h | 10 +- lib/events/event.cpp | 7 +- lib/events/event.h | 174 +++++++++++++++++++++++------------ lib/events/eventloader.h | 40 +------- lib/events/keyverificationevent.h | 32 ++----- lib/events/receiptevent.cpp | 16 ++-- lib/events/receiptevent.h | 13 ++- lib/events/redactionevent.h | 3 +- lib/events/roomavatarevent.h | 19 +--- lib/events/roomcanonicalaliasevent.h | 20 +--- lib/events/roomcreateevent.h | 4 +- lib/events/roomevent.cpp | 17 +--- lib/events/roomevent.h | 22 +++-- lib/events/roomkeyevent.cpp | 22 ----- lib/events/roomkeyevent.h | 11 ++- lib/events/roommemberevent.h | 22 +---- lib/events/roommessageevent.cpp | 7 +- lib/events/roompowerlevelsevent.h | 9 +- lib/events/roomtombstoneevent.h | 4 +- lib/events/simplestateevents.h | 42 ++++----- lib/events/stateevent.cpp | 14 ++- lib/events/stateevent.h | 115 ++++++++++++++--------- 30 files changed, 314 insertions(+), 388 deletions(-) delete mode 100644 lib/events/roomkeyevent.cpp (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp index f75f8ad3..89dcd7fd 100644 --- a/lib/events/callanswerevent.cpp +++ b/lib/events/callanswerevent.cpp @@ -26,16 +26,9 @@ m.call.answer using namespace Quotient; -CallAnswerEvent::CallAnswerEvent(const QJsonObject& obj) - : CallEventBase(typeId(), obj) -{ - qCDebug(EVENTS) << "Call Answer event"; -} - CallAnswerEvent::CallAnswerEvent(const QString& callId, const QString& sdp) - : CallEventBase( - typeId(), matrixTypeId(), callId, 0, - { { QStringLiteral("answer"), - QJsonObject { { QStringLiteral("type"), QStringLiteral("answer") }, - { QStringLiteral("sdp"), sdp } } } }) + : EventTemplate(callId, { { QStringLiteral("answer"), + QJsonObject { { QStringLiteral("type"), + QStringLiteral("answer") }, + { QStringLiteral("sdp"), sdp } } } }) {} diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 70ca1c7e..c5ad14df 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -7,11 +7,12 @@ #include "roomevent.h" namespace Quotient { -class QUOTIENT_API CallAnswerEvent : public CallEventBase { +class QUOTIENT_API CallAnswerEvent + : public EventTemplate { public: QUO_EVENT(CallAnswerEvent, "m.call.answer") - explicit CallAnswerEvent(const QJsonObject& obj); + using EventTemplate::EventTemplate; explicit CallAnswerEvent(const QString& callId, const QString& sdp); diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index cb96f358..f5d2f815 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -9,18 +9,15 @@ #include "roomevent.h" namespace Quotient { -class CallCandidatesEvent : public CallEventBase { +class CallCandidatesEvent : public EventTemplate { public: QUO_EVENT(CallCandidatesEvent, "m.call.candidates") - explicit CallCandidatesEvent(const QJsonObject& obj) - : CallEventBase(typeId(), obj) - {} + using EventTemplate::EventTemplate; explicit CallCandidatesEvent(const QString& callId, const QJsonArray& candidates) - : CallEventBase(typeId(), matrixTypeId(), callId, 0, - { { QStringLiteral("candidates"), candidates } }) + : EventTemplate(callId, { { QStringLiteral("candidates"), candidates } }) {} QUO_CONTENT_GETTER(QJsonArray, candidates) diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index e4d9bb78..f0b131b9 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -7,15 +7,11 @@ #include "roomevent.h" namespace Quotient { -class QUOTIENT_API CallHangupEvent : public CallEventBase { +class QUOTIENT_API CallHangupEvent + : public EventTemplate { public: QUO_EVENT(CallHangupEvent, "m.call.hangup") - - explicit CallHangupEvent(const QJsonObject& obj) - : CallEventBase(typeId(), obj) - {} - explicit CallHangupEvent(const QString& callId) - : CallEventBase(typeId(), matrixTypeId(), callId, 0) - {} + using EventTemplate::EventTemplate; }; +//REGISTER_EVENT_TYPE(CallHangupEvent) } // namespace Quotient diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp index 2f26a1cb..0232275b 100644 --- a/lib/events/callinviteevent.cpp +++ b/lib/events/callinviteevent.cpp @@ -27,16 +27,9 @@ m.call.invite using namespace Quotient; -CallInviteEvent::CallInviteEvent(const QJsonObject& obj) - : CallEventBase(typeId(), obj) -{ - qCDebug(EVENTS) << "Call Invite event"; -} - CallInviteEvent::CallInviteEvent(const QString& callId, int lifetime, const QString& sdp) - : CallEventBase( - typeId(), matrixTypeId(), callId, 0, + : EventTemplate(callId, { { QStringLiteral("lifetime"), lifetime }, { QStringLiteral("offer"), QJsonObject { { QStringLiteral("type"), QStringLiteral("offer") }, diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index f96f416d..fc22f7e1 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -7,11 +7,12 @@ #include "roomevent.h" namespace Quotient { -class QUOTIENT_API CallInviteEvent : public CallEventBase { +class QUOTIENT_API CallInviteEvent + : public EventTemplate { public: QUO_EVENT(CallInviteEvent, "m.call.invite") - explicit CallInviteEvent(const QJsonObject& obj); + using EventTemplate::EventTemplate; explicit CallInviteEvent(const QString& callId, int lifetime, const QString& sdp); diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index 942edba4..0756d816 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -10,7 +10,7 @@ class QUOTIENT_API DirectChatEvent : public Event { public: QUO_EVENT(DirectChatEvent, "m.direct") - explicit DirectChatEvent(const QJsonObject& obj) : Event(typeId(), obj) {} + using Event::Event; QMultiHash usersToDirectChats() const; }; diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index ec00ad4c..c539d5b2 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,33 +2,29 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" -#include "roommessageevent.h" -#include "events/eventloader.h" using namespace Quotient; EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertext, const QString& senderKey) - : RoomEvent(typeId(), matrixTypeId(), - { { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, + : RoomEvent({ { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, { CiphertextKeyL, ciphertext }, { SenderKeyKeyL, senderKey } }) {} EncryptedEvent::EncryptedEvent(QByteArray ciphertext, const QString& senderKey, const QString& deviceId, const QString& sessionId) - : RoomEvent(typeId(), matrixTypeId(), - { - { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, - { CiphertextKeyL, QString(ciphertext) }, - { DeviceIdKeyL, deviceId }, - { SenderKeyKeyL, senderKey }, - { SessionIdKeyL, sessionId }, - }) + : RoomEvent({ + { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, + { CiphertextKeyL, QString(ciphertext) }, + { DeviceIdKeyL, deviceId }, + { SenderKeyKeyL, senderKey }, + { SessionIdKeyL, sessionId }, + }) {} EncryptedEvent::EncryptedEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) + : RoomEvent(obj) { qCDebug(E2EE) << "Encrypted event from" << senderId(); } diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 60e77451..4bf7459c 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -26,7 +26,8 @@ public: int rotationPeriodMsgs = 100; }; -class QUOTIENT_API EncryptionEvent : public StateEvent { +class QUOTIENT_API EncryptionEvent + : public KeylessStateEventBase { public: QUO_EVENT(EncryptionEvent, "m.room.encryption") @@ -34,12 +35,7 @@ public: [[deprecated("Use Quotient::EncryptionType instead")]] = Quotient::EncryptionType; - explicit EncryptionEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) - {} - explicit EncryptionEvent(EncryptionEventContent&& content) - : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) - {} + using KeylessStateEventBase::KeylessStateEventBase; Quotient::EncryptionType encryption() const { return content().encryption; } QString algorithm() const { return content().algorithm; } diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 595e20a5..2843e1dc 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -46,7 +46,8 @@ void AbstractEventMetaType::addDerived(AbstractEventMetaType* newType) << className; } -Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) +Event::Event(const QJsonObject& json) + : _json(json) { if (!json.contains(ContentKeyL) && !json.value(UnsignedKeyL).toObject().contains(RedactedCauseKeyL)) { @@ -55,10 +56,6 @@ Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) } } -Event::Event(Type type, event_mtype_t matrixType, const QJsonObject& contentJson) - : Event(type, basicJson(matrixType, contentJson)) -{} - Event::~Event() = default; QString Event::matrixType() const { return fullJson()[TypeKeyL].toString(); } diff --git a/lib/events/event.h b/lib/events/event.h index ea827244..8a8d64b0 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -9,7 +9,7 @@ #include "single_key_value.h" namespace Quotient { -// === event_ptr_tt<> and type casting facilities === +// === event_ptr_tt<> and basic type casting facilities === template using event_ptr_tt = std::unique_ptr; @@ -49,42 +49,18 @@ const QString RoomIdKey { RoomIdKeyL }; const QString UnsignedKey { UnsignedKeyL }; const QString StateKeyKey { StateKeyKeyL }; -// === Event types === - using event_type_t = QLatin1String; -using event_mtype_t = const char*; - -class QUOTIENT_API EventTypeRegistry { -public: - ~EventTypeRegistry() = default; - [[deprecated("event_type_t is a string now, use it directly instead")]] +// TODO: Remove in 0.8 +struct QUOTIENT_API EventTypeRegistry { + [[deprecated("event_type_t is a string since libQuotient 0.7, use it directly instead")]] static QString getMatrixType(event_type_t typeId); -private: - EventTypeRegistry() = default; + EventTypeRegistry() = delete; + ~EventTypeRegistry() = default; Q_DISABLE_COPY_MOVE(EventTypeRegistry) }; -template -constexpr event_type_t typeId() -{ - return std::decay_t::TypeId; -} - -constexpr event_type_t UnknownEventTypeId = "?"_ls; -[[deprecated("Use UnknownEventTypeId")]] -constexpr event_type_t unknownEventTypeId() { return UnknownEventTypeId; } - -// === Event creation facilities === - -//! Create an event of arbitrary type from its arguments -template -inline event_ptr_tt makeEvent(ArgTs&&... args) -{ - return std::make_unique(std::forward(args)...); -} - // === EventMetaType === class Event; @@ -195,7 +171,7 @@ public: Event* event = nullptr; const bool goodEnough = doLoadFrom(fullJson, type, event); if (!event && goodEnough) - return event_ptr_tt{ makeEvent(fullJson) }; + return event_ptr_tt{ new EventT(fullJson) }; return event_ptr_tt{ static_cast(event) }; } @@ -220,18 +196,20 @@ private: return false; } else if constexpr (!requires { EventT::TypeId; }) return true; // Create a generic event object if on the top level - event = makeEvent(fullJson); + event = new EventT(fullJson); return false; } - static auto makeEvent(const QJsonObject& fullJson) - { - if constexpr (requires { EventT::TypeId; }) - return new EventT(fullJson); - else - return new EventT(UnknownEventTypeId, fullJson); - } }; +// === Event creation facilities === + +//! \brief Create an event of arbitrary type from its arguments +template +inline event_ptr_tt makeEvent(ArgTs&&... args) +{ + return std::make_unique(std::forward(args)...); +} + template constexpr const auto& mostSpecificMetaType() { @@ -241,13 +219,43 @@ constexpr const auto& mostSpecificMetaType() return EventT::BaseMetaType; } -template -inline event_ptr_tt doLoadEvent(const QJsonObject& json, - const QString& matrixType) +//! \brief Create an event with proper type from a JSON object +//! +//! Use this factory template to detect the type from the JSON object +//! contents (the detected event type should derive from the template +//! parameter type) and create an event object of that type. +template +inline event_ptr_tt loadEvent(const QJsonObject& fullJson) { - return mostSpecificMetaType().loadFrom(json, matrixType); + return mostSpecificMetaType().loadFrom( + fullJson, fullJson[TypeKeyL].toString()); } +//! \brief Create an event from a type string and content JSON +//! +//! Use this template to resolve the C++ type from the Matrix type string in +//! \p matrixType and create an event of that type by passing all parameters +//! to BaseEventT::basicJson(). +template +inline event_ptr_tt loadEvent(const QString& matrixType, + const auto&... otherBasicJsonParams) +{ + return mostSpecificMetaType().loadFrom( + EventT::basicJson(matrixType, otherBasicJsonParams...), matrixType); +} + +template +struct JsonConverter> + : JsonObjectUnpacker> { + // No dump() to avoid any ambiguity on whether a given export to JSON uses + // fullJson() or only contentJson() + using JsonObjectUnpacker>::load; + static auto load(const QJsonObject& jo) + { + return loadEvent(jo); + } +}; + // === Event === class QUOTIENT_API Event { @@ -259,10 +267,8 @@ public: return BaseMetaType; } + explicit Event(const QJsonObject& json); - explicit Event(Type type, const QJsonObject& json); - explicit Event(Type type, event_mtype_t matrixType, - const QJsonObject& contentJson = {}); Q_DISABLE_COPY(Event) Event(Event&&) = default; Event& operator=(Event&&) = delete; @@ -312,6 +318,11 @@ public: const QJsonObject contentJson() const; + //! \brief Get a part of the content object, assuming a given type + //! + //! This retrieves the value under `content.` from the event JSON and + //! then converts it to \p T using fromJson(). + //! \sa contentJson, fromJson template const T contentPart(KeyT&& key) const { @@ -327,6 +338,11 @@ public: const QJsonObject unsignedJson() const; + //! \brief Get a part of the unsigned object, assuming a given type + //! + //! This retrieves the value under `unsigned.` from the event JSON and + //! then converts it to \p T using fromJson(). + //! \sa unsignedJson, fromJson template const T unsignedPart(KeyT&& key) const { @@ -353,7 +369,6 @@ protected: virtual void dumpTo(QDebug dbg) const; private: - Type _type; QJsonObject _json; }; using EventPtr = event_ptr_tt; @@ -364,6 +379,45 @@ using Events = EventsArray; // === Facilities for event class definitions === +//! \brief A template base class to derive your event type from +//! +//! This simple class template generates commonly used event constructor +//! signatures and the content() method with the appropriate return type. +//! The generic version here is only used with non-trivial \p ContentT (if you +//! don't need to create an event from its content structure, just go and derive +//! straight from the respective \p EventBaseT instead of using EventTemplate); +//! specialisations may override that and provide useful semantics even without +//! \p ContentT (see EventTemplate, e.g.). +//! +//! The template uses CRTP to pick the event type id from the actual class; +//! it will fail to compile if \p EventT doesn't provide TypeId. It also uses +//! the base event type's basicJson(); if you need extra keys to be inserted +//! you may want to bypass this template as writing the code to that effect in +//! your class will likely be clearer and more concise. +//! \sa https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern +//! \sa DEFINE_SIMPLE_EVENT +template +class EventTemplate : public BaseEventT { +public: + static_assert( + !std::is_same_v, + "If you see this, you tried to use EventTemplate with the default" + " ContentT type, which is void. This default is only used with explicit" + " specialisations (see CallEventBase, e.g.). Otherwise, if you don't" + " intend to use the content part of EventTemplate then you don't need" + " EventTemplate; just use the base event class directly"); + using content_type = ContentT; + + explicit EventTemplate(const QJsonObject& json) + : BaseEventT(json) + {} + explicit EventTemplate(const ContentT& c) + : BaseEventT(EventT::basicJson(EventT::TypeId, toJson(c))) + {} + + ContentT content() const { return fromJson(this->contentJson()); } +}; + //! \brief Supply event metatype information in base event types //! //! Use this macro in a public section of your base event class to provide @@ -445,19 +499,19 @@ using Events = EventsArray; /// To retrieve the value the getter uses a JSON key name that corresponds to /// its own (getter's) name but written in snake_case. \p GetterName_ must be /// in camelCase, no quotes (an identifier, not a literal). -#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_, \ - JsonKey_) \ - class QUOTIENT_API Name_ : public Base_ { \ - public: \ - QUO_EVENT(Name_, TypeId_) \ - using value_type = ValueType_; \ - explicit Name_(const QJsonObject& obj) : Base_(TypeId, obj) {} \ - explicit Name_(const value_type& v) \ - : Name_(Base_::basicJson(TypeId, { { JsonKey, toJson(v) } })) \ - {} \ - QUO_CONTENT_GETTER_X(ValueType_, GetterName_, JsonKey) \ - static inline const auto JsonKey = toSnakeCase(#GetterName_##_ls); \ - }; \ +#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_, \ + JsonKey_) \ + constexpr auto Name_##ContentKey = JsonKey_##_ls; \ + class QUOTIENT_API Name_ \ + : public EventTemplate< \ + Name_, Base_, \ + EventContent::SingleKeyValue> { \ + public: \ + QUO_EVENT(Name_, TypeId_) \ + using value_type = ValueType_; \ + using EventTemplate::EventTemplate; \ + QUO_CONTENT_GETTER_X(ValueType_, GetterName_, Name_##ContentKey) \ + }; \ // End of macro // === is<>(), eventCast<>() and switchOnType<>() === diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index 4c639efa..b4ac154c 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -6,40 +6,8 @@ #include "stateevent.h" namespace Quotient { - -/*! Create an event with proper type from a JSON object - * - * Use this factory template to detect the type from the JSON object - * contents (the detected event type should derive from the template - * parameter type) and create an event object of that type. - */ -template -inline event_ptr_tt loadEvent(const QJsonObject& fullJson) -{ - return doLoadEvent(fullJson, fullJson[TypeKeyL].toString()); -} - -//! \brief Create an event from a type string and content JSON -//! -//! Use this template to resolve the C++ type from the Matrix type string in -//! \p matrixType and create an event of that type by passing all parameters -//! to BaseEventT::basicJson(). -template -inline event_ptr_tt loadEvent( - const QString& matrixType, const BasicJsonParamTs&... basicJsonParams) -{ - return doLoadEvent( - BaseEventT::basicJson(matrixType, basicJsonParams...), matrixType); +struct [[deprecated( + "This header is obsolete since libQuotient 0.7; include a header with" + " the respective event type definition instead")]] EventLoaderH; +StateEventPtr eventLoaderH(EventLoaderH&); } - -template -struct JsonConverter> - : JsonObjectUnpacker> { - using JsonObjectUnpacker>::load; - static auto load(const QJsonObject& jo) - { - return loadEvent(jo); - } -}; - -} // namespace Quotient diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 5b5a518f..0ffd8b2c 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -15,9 +15,7 @@ class QUOTIENT_API KeyVerificationRequestEvent : public Event { public: QUO_EVENT(KeyVerificationRequestEvent, "m.key.verification.request") - explicit KeyVerificationRequestEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationRequestEvent(const QString& transactionId, const QString& fromDevice, const QStringList& methods, @@ -50,9 +48,7 @@ class QUOTIENT_API KeyVerificationReadyEvent : public Event { public: QUO_EVENT(KeyVerificationReadyEvent, "m.key.verification.ready") - explicit KeyVerificationReadyEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationReadyEvent(const QString& transactionId, const QString& fromDevice, const QStringList& methods) @@ -77,9 +73,7 @@ class QUOTIENT_API KeyVerificationStartEvent : public Event { public: QUO_EVENT(KeyVerificationStartEvent, "m.key.verification.start") - explicit KeyVerificationStartEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationStartEvent(const QString& transactionId, const QString& fromDevice) : KeyVerificationStartEvent( @@ -150,9 +144,7 @@ class QUOTIENT_API KeyVerificationAcceptEvent : public Event { public: QUO_EVENT(KeyVerificationAcceptEvent, "m.key.verification.accept") - explicit KeyVerificationAcceptEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationAcceptEvent(const QString& transactionId, const QString& commitment) : KeyVerificationAcceptEvent(basicJson( @@ -200,9 +192,7 @@ class QUOTIENT_API KeyVerificationCancelEvent : public Event { public: QUO_EVENT(KeyVerificationCancelEvent, "m.key.verification.cancel") - explicit KeyVerificationCancelEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationCancelEvent(const QString& transactionId, const QString& reason) : KeyVerificationCancelEvent( @@ -230,9 +220,7 @@ class QUOTIENT_API KeyVerificationKeyEvent : public Event { public: QUO_EVENT(KeyVerificationKeyEvent, "m.key.verification.key") - explicit KeyVerificationKeyEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationKeyEvent(const QString& transactionId, const QString& key) : KeyVerificationKeyEvent( basicJson(TypeId, { { "transaction_id"_ls, transactionId }, @@ -251,9 +239,7 @@ class QUOTIENT_API KeyVerificationMacEvent : public Event { public: QUO_EVENT(KeyVerificationMacEvent, "m.key.verification.mac") - explicit KeyVerificationMacEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; KeyVerificationMacEvent(const QString& transactionId, const QString& keys, const QJsonObject& mac) : KeyVerificationMacEvent( @@ -278,9 +264,7 @@ class QUOTIENT_API KeyVerificationDoneEvent : public Event { public: QUO_EVENT(KeyVerificationDoneEvent, "m.key.verification.done") - explicit KeyVerificationDoneEvent(const QJsonObject& obj) - : Event(TypeId, obj) - {} + using Event::Event; explicit KeyVerificationDoneEvent(const QString& transactionId) : KeyVerificationDoneEvent( basicJson(TypeId, { { "transaction_id"_ls, transactionId } })) diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index 7f06d99f..d8f9fa0b 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -28,7 +28,7 @@ using namespace Quotient; // map lookups are not used and vectors are massively faster. Same goes for // de-/serialization of ReceiptsForEvent::receipts. // (XXX: would this be generally preferred across CS API JSON maps?..) -QJsonObject toJson(const EventsWithReceipts& ewrs) +QJsonObject Quotient::toJson(const EventsWithReceipts& ewrs) { QJsonObject json; for (const auto& e : ewrs) { @@ -41,20 +41,16 @@ QJsonObject toJson(const EventsWithReceipts& ewrs) return json; } -ReceiptEvent::ReceiptEvent(const EventsWithReceipts &ewrs) - : Event(typeId(), matrixTypeId(), toJson(ewrs)) -{} - -EventsWithReceipts ReceiptEvent::eventsWithReceipts() const +template<> +EventsWithReceipts Quotient::fromJson(const QJsonObject& json) { EventsWithReceipts result; - const auto& contents = contentJson(); - result.reserve(contents.size()); - for (auto eventIt = contents.begin(); eventIt != contents.end(); ++eventIt) { + result.reserve(json.size()); + for (auto eventIt = json.begin(); eventIt != json.end(); ++eventIt) { if (eventIt.key().isEmpty()) { qCWarning(EPHEMERAL) << "ReceiptEvent has an empty event id, skipping"; - qCDebug(EPHEMERAL) << "ReceiptEvent content follows:\n" << contents; + qCDebug(EPHEMERAL) << "ReceiptEvent content follows:\n" << json; continue; } const auto reads = diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index a02f4592..b87e00f6 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -19,12 +19,17 @@ struct ReceiptsForEvent { }; using EventsWithReceipts = QVector; -class QUOTIENT_API ReceiptEvent : public Event { +template <> +QUOTIENT_API EventsWithReceipts fromJson(const QJsonObject& json); +QUOTIENT_API QJsonObject toJson(const EventsWithReceipts& ewrs); + +class QUOTIENT_API ReceiptEvent + : public EventTemplate { public: QUO_EVENT(ReceiptEvent, "m.receipt") - explicit ReceiptEvent(const EventsWithReceipts& ewrs); - explicit ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) {} + using EventTemplate::EventTemplate; - EventsWithReceipts eventsWithReceipts() const; + [[deprecated("Use content() instead")]] + EventsWithReceipts eventsWithReceipts() const { return content(); } }; } // namespace Quotient diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index c193054a..a2e0b73b 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -10,8 +10,7 @@ class QUOTIENT_API RedactionEvent : public RoomEvent { public: QUO_EVENT(RedactionEvent, "m.room.redaction") - explicit RedactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) - {} + using RoomEvent::RoomEvent; QString redactedEvent() const { diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index 2ebe29bf..1986f852 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -8,26 +8,15 @@ namespace Quotient { class QUOTIENT_API RoomAvatarEvent - : public StateEvent { + : public KeylessStateEventBase { // It's a bit of an overkill to use a full-fledged ImageContent // because in reality m.room.avatar usually only has a single URL, // without a thumbnail. But The Spec says there be thumbnails, and - // we follow The Spec. + // we follow The Spec (and ImageContent is very convenient to reuse here). public: QUO_EVENT(RoomAvatarEvent, "m.room.avatar") - explicit RoomAvatarEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) - {} - explicit RoomAvatarEvent(const EventContent::ImageContent& avatar) - : StateEvent(typeId(), matrixTypeId(), QString(), avatar) - {} - // A replica of EventContent::ImageInfo constructor - explicit RoomAvatarEvent(const QUrl& mxcUrl, qint64 fileSize = -1, - QMimeType mimeType = {}, - const QSize& imageSize = {}, - const QString& originalFilename = {}) - : RoomAvatarEvent(EventContent::ImageContent { - mxcUrl, fileSize, mimeType, imageSize, originalFilename }) - {} + using KeylessStateEventBase::KeylessStateEventBase; QUrl url() const { return content().url(); } }; diff --git a/lib/events/roomcanonicalaliasevent.h b/lib/events/roomcanonicalaliasevent.h index e1c7888e..c73bc92a 100644 --- a/lib/events/roomcanonicalaliasevent.h +++ b/lib/events/roomcanonicalaliasevent.h @@ -32,25 +32,11 @@ inline auto toJson(const EventContent::AliasesEventContent& c) } class QUOTIENT_API RoomCanonicalAliasEvent - : public StateEvent { + : public KeylessStateEventBase { public: QUO_EVENT(RoomCanonicalAliasEvent, "m.room.canonical_alias") - - explicit RoomCanonicalAliasEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) - { } - - explicit RoomCanonicalAliasEvent(const QString& canonicalAlias, - const QStringList& altAliases = {}) - : StateEvent(typeId(), matrixTypeId(), {}, - canonicalAlias, altAliases) - { } - - explicit RoomCanonicalAliasEvent(QString&& canonicalAlias, - QStringList&& altAliases = {}) - : StateEvent(typeId(), matrixTypeId(), {}, - std::move(canonicalAlias), std::move(altAliases)) - { } + using KeylessStateEventBase::KeylessStateEventBase; QString alias() const { return content().canonicalAlias; } QStringList altAliases() const { return content().altAliases; } diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index f22752b4..2709258f 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -11,9 +11,7 @@ class QUOTIENT_API RoomCreateEvent : public StateEventBase { public: QUO_EVENT(RoomCreateEvent, "m.room.create") - explicit RoomCreateEvent(const QJsonObject& obj) - : StateEventBase(typeId(), obj) - {} + using StateEventBase::StateEventBase; struct Predecessor { QString roomId; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index e695e0ec..bd06f5c5 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -8,12 +8,7 @@ using namespace Quotient; -RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, - const QJsonObject& contentJson) - : Event(type, matrixType, contentJson) -{} - -RoomEvent::RoomEvent(Type type, const QJsonObject& json) : Event(type, json) +RoomEvent::RoomEvent(const QJsonObject& json) : Event(json) { if (const auto redaction = unsignedPart(RedactedCauseKeyL); !redaction.isEmpty()) @@ -110,14 +105,8 @@ QJsonObject CallEventBase::basicJson(const QString& matrixType, return RoomEvent::basicJson(matrixType, contentJson); } -CallEventBase::CallEventBase(Type type, event_mtype_t matrixType, - const QString& callId, int version, - const QJsonObject& contentJson) - : RoomEvent(type, basicJson(matrixType, callId, version, contentJson)) -{} - -CallEventBase::CallEventBase(Type type, const QJsonObject& json) - : RoomEvent(type, json) +CallEventBase::CallEventBase(const QJsonObject& json) + : RoomEvent(json) { if (callId().isEmpty()) qCWarning(EVENTS) << id() << "is a call event with an empty call id"; diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 532e72e2..830f1d30 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -17,10 +17,8 @@ public: QUO_BASE_EVENT(RoomEvent, {}, Event::BaseMetaType) // RedactionEvent is an incomplete type here so we cannot inline - // constructors and destructors and we cannot use 'using'. - RoomEvent(Type type, event_mtype_t matrixType, - const QJsonObject& contentJson = {}); - RoomEvent(Type type, const QJsonObject& json); + // constructors using it and also destructors (with 'using', in particular). + explicit RoomEvent(const QJsonObject& json); ~RoomEvent() override; QString id() const; @@ -85,10 +83,7 @@ class QUOTIENT_API CallEventBase : public RoomEvent { public: QUO_BASE_EVENT(CallEventBase, "m.call.*"_ls, RoomEvent::BaseMetaType) - CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, - int version, const QJsonObject& contentJson = {}); - CallEventBase(Type type, const QJsonObject& json); - ~CallEventBase() override = default; + explicit CallEventBase(const QJsonObject& json); QUO_CONTENT_GETTER(QString, callId) QUO_CONTENT_GETTER(int, version) @@ -98,6 +93,17 @@ protected: const QString& callId, int version, QJsonObject contentJson = {}); }; + +template +class EventTemplate : public CallEventBase { +public: + using CallEventBase::CallEventBase; + explicit EventTemplate(const QString& callId, + const QJsonObject& contentJson = {}) + : EventTemplate(basicJson(EventT::TypeId, callId, 0, contentJson)) + {} +}; + } // namespace Quotient Q_DECLARE_METATYPE(Quotient::RoomEvent*) Q_DECLARE_METATYPE(const Quotient::RoomEvent*) diff --git a/lib/events/roomkeyevent.cpp b/lib/events/roomkeyevent.cpp deleted file mode 100644 index 3a8601d1..00000000 --- a/lib/events/roomkeyevent.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: 2019 Alexey Andreyev -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "roomkeyevent.h" - -using namespace Quotient; - -RoomKeyEvent::RoomKeyEvent(const QJsonObject &obj) : Event(TypeId, obj) -{ - if (roomId().isEmpty()) - qCWarning(E2EE) << "Room key event has empty room id"; -} - -RoomKeyEvent::RoomKeyEvent(const QString& algorithm, const QString& roomId, - const QString& sessionId, const QString& sessionKey) - : Event(TypeId, basicJson(TypeId, { - { "algorithm", algorithm }, - { "room_id", roomId }, - { "session_id", sessionId }, - { "session_key", sessionKey }, - })) -{} diff --git a/lib/events/roomkeyevent.h b/lib/events/roomkeyevent.h index 6883a2a5..dad5df8b 100644 --- a/lib/events/roomkeyevent.h +++ b/lib/events/roomkeyevent.h @@ -11,9 +11,16 @@ class QUOTIENT_API RoomKeyEvent : public Event public: QUO_EVENT(RoomKeyEvent, "m.room_key") - explicit RoomKeyEvent(const QJsonObject& obj); + using Event::Event; explicit RoomKeyEvent(const QString& algorithm, const QString& roomId, - const QString& sessionId, const QString& sessionKey); + const QString& sessionId, const QString& sessionKey) + : Event(basicJson(TypeId, { + { "algorithm", algorithm }, + { "room_id", roomId }, + { "session_id", sessionId }, + { "session_key", sessionKey }, + })) + {} QUO_CONTENT_GETTER(QString, algorithm) QUO_CONTENT_GETTER(QString, roomId) diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index c690586e..9f063136 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -28,7 +28,8 @@ public: using MembershipType [[deprecated("Use Membership instead")]] = Membership; -class QUOTIENT_API RoomMemberEvent : public StateEvent { +class QUOTIENT_API RoomMemberEvent + : public KeyedStateEventBase { Q_GADGET public: QUO_EVENT(RoomMemberEvent, "m.room.member") @@ -36,24 +37,7 @@ public: using MembershipType [[deprecated("Use Quotient::Membership instead")]] = Membership; - explicit RoomMemberEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) - {} - RoomMemberEvent(const QString& userId, MemberEventContent&& content) - : StateEvent(typeId(), matrixTypeId(), userId, std::move(content)) - {} - - //! \brief A special constructor to create unknown RoomMemberEvents - //! - //! This is needed in order to use RoomMemberEvent as a "base event class" - //! in cases like GetMembersByRoomJob when RoomMemberEvents (rather than - //! RoomEvents or StateEvents) are resolved from JSON. For such cases - //! loadEvent\<> requires an underlying class to have a specialisation of - //! EventFactory\<> and be constructible with unknownTypeId() instead of - //! its genuine id. Don't use directly. - //! \sa EventFactory, loadEvent, GetMembersByRoomJob - RoomMemberEvent(Type type, const QJsonObject& fullJson) - : StateEvent(type, fullJson) - {} + using KeyedStateEventBase::KeyedStateEventBase; Membership membership() const { return content().membership; } QString userId() const { return stateKey(); } diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 2a6ae93c..db5afaf1 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -128,8 +128,9 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, RoomMessageEvent::RoomMessageEvent(const QString& plainBody, const QString& jsonMsgType, TypedBase* content) - : RoomEvent(typeId(), matrixTypeId(), - assembleContentJson(plainBody, jsonMsgType, content)) + : RoomEvent(RoomEvent::basicJson(TypeId, + assembleContentJson(plainBody, jsonMsgType, + content))) , _content(content) {} @@ -175,7 +176,7 @@ RoomMessageEvent::RoomMessageEvent(const QString& plainBody, #endif RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj), _content(nullptr) + : RoomEvent(obj), _content(nullptr) { if (isRedacted()) return; diff --git a/lib/events/roompowerlevelsevent.h b/lib/events/roompowerlevelsevent.h index 7ac12db0..6150980a 100644 --- a/lib/events/roompowerlevelsevent.h +++ b/lib/events/roompowerlevelsevent.h @@ -31,16 +31,11 @@ struct QUOTIENT_API PowerLevelsEventContent { }; class QUOTIENT_API RoomPowerLevelsEvent - : public StateEvent { + : public KeylessStateEventBase { public: QUO_EVENT(RoomPowerLevelsEvent, "m.room.power_levels") - explicit RoomPowerLevelsEvent(PowerLevelsEventContent&& content) - : StateEvent(typeId(), matrixTypeId(), QString(), std::move(content)) - {} - explicit RoomPowerLevelsEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) - {} + using KeylessStateEventBase::KeylessStateEventBase; int invite() const { return content().invite; } int kick() const { return content().kick; } diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 97586587..95743e32 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -10,9 +10,7 @@ class QUOTIENT_API RoomTombstoneEvent : public StateEventBase { public: QUO_EVENT(RoomTombstoneEvent, "m.room.tombstone") - explicit RoomTombstoneEvent(const QJsonObject& obj) - : StateEventBase(typeId(), obj) - {} + using StateEventBase::StateEventBase; QString serverMessage() const; QString successorRoomId() const; diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index c79d03b0..d84dc1b1 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -7,25 +7,18 @@ #include "single_key_value.h" namespace Quotient { -#define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ValueType, _ContentKey) \ - constexpr auto _Name##Key = #_ContentKey##_ls; \ - class QUOTIENT_API _Name \ - : public StateEvent< \ - EventContent::SingleKeyValue<_ValueType, &_Name##Key>> { \ - public: \ - using value_type = _ValueType; \ - QUO_EVENT(_Name, _TypeId) \ - template \ - explicit _Name(T&& value) \ - : StateEvent(TypeId, matrixTypeId(), QString(), \ - std::forward(value)) \ - {} \ - explicit _Name(QJsonObject obj) \ - : StateEvent(TypeId, std::move(obj)) \ - {} \ - auto _ContentKey() const { return content().value; } \ - }; \ - // End of macro +#define DEFINE_SIMPLE_STATE_EVENT(Name_, TypeId_, ValueType_, ContentKey_) \ + constexpr auto Name_##Key = #ContentKey_##_ls; \ + class QUOTIENT_API Name_ \ + : public KeylessStateEventBase< \ + Name_, EventContent::SingleKeyValue> { \ + public: \ + using value_type = ValueType_; \ + QUO_EVENT(Name_, TypeId_) \ + using KeylessStateEventBase::KeylessStateEventBase; \ + auto ContentKey_() const { return content().value; } \ + }; \ +// End of macro DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", QString, topic) @@ -34,13 +27,14 @@ DEFINE_SIMPLE_STATE_EVENT(RoomPinnedEvent, "m.room.pinned_messages", constexpr auto RoomAliasesEventKey = "aliases"_ls; class QUOTIENT_API RoomAliasesEvent - : public StateEvent< - EventContent::SingleKeyValue> { + : public KeyedStateEventBase< + RoomAliasesEvent, + EventContent::SingleKeyValue> +{ public: QUO_EVENT(RoomAliasesEvent, "m.room.aliases") - explicit RoomAliasesEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) - {} + using KeyedStateEventBase::KeyedStateEventBase; + Q_DECL_DEPRECATED_X( "m.room.aliases events are deprecated by the Matrix spec; use" " RoomCanonicalAliasEvent::altAliases() to get non-authoritative aliases") diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 1df24df0..e117f8a0 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -5,18 +5,16 @@ using namespace Quotient; -StateEventBase::StateEventBase(Type type, const QJsonObject& json) - : RoomEvent(json.contains(StateKeyKeyL) ? type : UnknownEventTypeId, json) +StateEventBase::StateEventBase(const QJsonObject& json) + : RoomEvent(json) { - if (Event::type() == UnknownEventTypeId && !json.contains(StateKeyKeyL)) - qWarning(EVENTS) << "Attempt to create a state event with no stateKey -" - "forcing the event type to unknown to avoid damage"; + Q_ASSERT_X(json.contains(StateKeyKeyL), __FUNCTION__, + "Attempt to create a state event without state key"); } -StateEventBase::StateEventBase(Event::Type type, event_mtype_t matrixType, - const QString& stateKey, +StateEventBase::StateEventBase(Event::Type type, const QString& stateKey, const QJsonObject& contentJson) - : RoomEvent(type, basicJson(type, stateKey, contentJson)) + : RoomEvent(basicJson(type, stateKey, contentJson)) {} bool StateEventBase::repeatsState() const diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 74876803..911972f2 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -16,11 +16,17 @@ public: return fullJson.contains(StateKeyKeyL); } - StateEventBase(Type type, const QJsonObject& json); - StateEventBase(Type type, event_mtype_t matrixType, - const QString& stateKey = {}, - const QJsonObject& contentJson = {}); - ~StateEventBase() override = default; + //! \brief Static setting of whether a given even type uses state keys + //! + //! Most event types don't use a state key; overriding this to `true` + //! for a given type changes the calls across Quotient to include state key + //! in their signatures; otherwise, state key is still accessible but + //! constructors and calls in, e.g., RoomStateView don't include it. + static constexpr auto needsStateKey = false; + + explicit StateEventBase(const QJsonObject& json); + explicit StateEventBase(Type type, const QString& stateKey = {}, + const QJsonObject& contentJson = {}); //! Make a minimal correct Matrix state event JSON static QJsonObject basicJson(const QString& matrixTypeId, @@ -56,64 +62,85 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, */ using StateEventKey = std::pair; -template -struct Prev { - template - explicit Prev(const QJsonObject& unsignedJson, - ContentParamTs&&... contentParams) - : senderId(unsignedJson.value("prev_sender"_ls).toString()) - , content(fromJson(unsignedJson.value(PrevContentKeyL)), - std::forward(contentParams)...) - {} - - QString senderId; - ContentT content; -}; - -template -class StateEvent : public StateEventBase { +template +class EventTemplate + : public StateEventBase { public: using content_type = ContentT; + struct Prev { + explicit Prev() = default; + explicit Prev(const QJsonObject& unsignedJson) + : senderId(fromJson(unsignedJson["prev_sender"_ls])) + , content( + fromJson>(unsignedJson[PrevContentKeyL])) + {} + + QString senderId; + Omittable content; + }; + + explicit EventTemplate(const QJsonObject& fullJson) + : StateEventBase(fullJson) + , _content(fromJson(Event::contentJson())) + , _prev(unsignedJson()) + {} template - explicit StateEvent(Type type, const QJsonObject& fullJson, - ContentParamTs&&... contentParams) - : StateEventBase(type, fullJson) - , _content(fromJson(contentJson()), - std::forward(contentParams)...) - { - const auto& unsignedData = unsignedJson(); - if (unsignedData.contains(PrevContentKeyL)) - _prev = std::make_unique>( - unsignedData, std::forward(contentParams)...); - } - template - explicit StateEvent(Type type, event_mtype_t matrixType, - const QString& stateKey, - ContentParamTs&&... contentParams) - : StateEventBase(type, matrixType, stateKey) - , _content{std::forward(contentParams)...} + explicit EventTemplate(const QString& stateKey, + ContentParamTs&&... contentParams) + : StateEventBase(EventT::TypeId, stateKey) + , _content { std::forward(contentParams)... } { editJson().insert(ContentKey, toJson(_content)); } const ContentT& content() const { return _content; } + template void editContent(VisitorT&& visitor) { visitor(_content); editJson()[ContentKeyL] = toJson(_content); } - const ContentT* prevContent() const - { - return _prev ? &_prev->content : nullptr; - } - QString prevSenderId() const { return _prev ? _prev->senderId : QString(); } + const Omittable& prevContent() const { return _prev.content; } + QString prevSenderId() const { return _prev.senderId; } private: ContentT _content; - std::unique_ptr> _prev; + Prev _prev; }; + +template +class KeyedStateEventBase + : public EventTemplate { +public: + static constexpr auto needsStateKey = true; + + using EventTemplate::EventTemplate; +}; + +template +concept Keyed_State_Event = EvT::needsStateKey; + +template +class KeylessStateEventBase + : public EventTemplate { +private: + using base_type = EventTemplate; + +public: + explicit KeylessStateEventBase(const QJsonObject& fullJson) + : base_type(fullJson) + {} + template + explicit KeylessStateEventBase(ContentParamTs&&... contentParams) + : base_type(QString(), std::forward(contentParams)...) + {} +}; + +template +concept Keyless_State_Event = !EvT::needsStateKey; + } // namespace Quotient Q_DECLARE_METATYPE(Quotient::StateEventBase*) Q_DECLARE_METATYPE(const Quotient::StateEventBase*) -- cgit v1.2.3 From 3fa9afc796788e0c7f44db15c21a5ba1294d3b2d Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 25 Jul 2022 17:05:59 +0200 Subject: Remove #include "logging.h" from event.h We don't expose logging internals to the outside world. --- lib/events/encryptedevent.cpp | 1 + lib/events/encryptionevent.cpp | 1 + lib/events/event.h | 1 - lib/events/roommemberevent.cpp | 3 +-- lib/events/stateevent.cpp | 1 + 5 files changed, 4 insertions(+), 3 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index c539d5b2..e9b4a585 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" +#include "logging.h" using namespace Quotient; diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 8872447b..b1b04984 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -3,6 +3,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptionevent.h" +#include "logging.h" #include "e2ee/e2ee.h" diff --git a/lib/events/event.h b/lib/events/event.h index 8a8d64b0..4b715813 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -4,7 +4,6 @@ #pragma once #include "converters.h" -#include "logging.h" #include "function_traits.h" #include "single_key_value.h" diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 953ff8ae..4e7eae1b 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -3,8 +3,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "roommemberevent.h" - -#include +#include "logging.h" namespace Quotient { template <> diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index e117f8a0..204044bb 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "stateevent.h" +#include "logging.h" using namespace Quotient; -- cgit v1.2.3 From 80499cc7619bb857c284e6e89db728ccee9c61f6 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sat, 3 Sep 2022 19:12:42 +0200 Subject: More cleanup --- lib/events/encryptedevent.cpp | 7 ++++--- lib/events/encryptedevent.h | 7 ++++--- lib/events/event.h | 2 +- lib/events/roommessageevent.cpp | 5 ++--- 4 files changed, 11 insertions(+), 10 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index e9b4a585..94b44901 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -6,14 +6,15 @@ using namespace Quotient; -EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertext, +EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertexts, const QString& senderKey) : RoomEvent({ { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, - { CiphertextKeyL, ciphertext }, + { CiphertextKeyL, ciphertexts }, { SenderKeyKeyL, senderKey } }) {} -EncryptedEvent::EncryptedEvent(QByteArray ciphertext, const QString& senderKey, +EncryptedEvent::EncryptedEvent(const QByteArray& ciphertext, + const QString& senderKey, const QString& deviceId, const QString& sessionId) : RoomEvent({ { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 22e51cb8..02d4c7aa 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -32,11 +32,12 @@ public: /* In case with Olm, the encrypted content of the event is * a map from the recipient Curve25519 identity key to ciphertext * information */ - explicit EncryptedEvent(const QJsonObject& ciphertext, + explicit EncryptedEvent(const QJsonObject& ciphertexts, const QString& senderKey); /* In case with Megolm, device_id and session_id are required */ - explicit EncryptedEvent(QByteArray ciphertext, const QString& senderKey, - const QString& deviceId, const QString& sessionId); + explicit EncryptedEvent(const QByteArray& ciphertext, + const QString& senderKey, const QString& deviceId, + const QString& sessionId); explicit EncryptedEvent(const QJsonObject& obj); QString algorithm() const; diff --git a/lib/events/event.h b/lib/events/event.h index 4b715813..ea5a2554 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -269,7 +269,7 @@ public: explicit Event(const QJsonObject& json); Q_DISABLE_COPY(Event) - Event(Event&&) = default; + Event(Event&&) noexcept = default; Event& operator=(Event&&) = delete; virtual ~Event(); diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index db5afaf1..df4840b3 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -128,9 +128,8 @@ QJsonObject RoomMessageEvent::assembleContentJson(const QString& plainBody, RoomMessageEvent::RoomMessageEvent(const QString& plainBody, const QString& jsonMsgType, TypedBase* content) - : RoomEvent(RoomEvent::basicJson(TypeId, - assembleContentJson(plainBody, jsonMsgType, - content))) + : RoomEvent( + basicJson(TypeId, assembleContentJson(plainBody, jsonMsgType, content))) , _content(content) {} -- cgit v1.2.3 From 8e58d28ca0517aeeb43c99bd97ec9ba5ada11c95 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 1 Aug 2022 08:09:40 +0200 Subject: CallEventBase -> CallEvent; pack up all call events These are small enough to comfortably reside in a single translation unit. --- lib/events/callanswerevent.cpp | 34 -------------- lib/events/callanswerevent.h | 24 ---------- lib/events/callcandidatesevent.h | 27 ----------- lib/events/callevents.cpp | 82 +++++++++++++++++++++++++++++++++ lib/events/callevents.h | 99 ++++++++++++++++++++++++++++++++++++++++ lib/events/callhangupevent.h | 17 ------- lib/events/callinviteevent.cpp | 37 --------------- lib/events/callinviteevent.h | 26 ----------- lib/events/event.cpp | 3 +- lib/events/event.h | 8 ++-- lib/events/roomevent.cpp | 16 ------- lib/events/roomevent.h | 25 ---------- 12 files changed, 187 insertions(+), 211 deletions(-) delete mode 100644 lib/events/callanswerevent.cpp delete mode 100644 lib/events/callanswerevent.h delete mode 100644 lib/events/callcandidatesevent.h create mode 100644 lib/events/callevents.cpp create mode 100644 lib/events/callevents.h delete mode 100644 lib/events/callhangupevent.h delete mode 100644 lib/events/callinviteevent.cpp delete mode 100644 lib/events/callinviteevent.h (limited to 'lib/events') diff --git a/lib/events/callanswerevent.cpp b/lib/events/callanswerevent.cpp deleted file mode 100644 index 89dcd7fd..00000000 --- a/lib/events/callanswerevent.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "callanswerevent.h" - -/* -m.call.answer -{ - "age": 242352, - "content": { - "answer": { - "sdp": "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]", - "type": "answer" - }, - "call_id": "12345", - "version": 0 - }, - "event_id": "$WLGTSEFSEF:localhost", - "origin_server_ts": 1431961217939, - "room_id": "!Cuyf34gef24t:localhost", - "sender": "@example:localhost", - "type": "m.call.answer" -} -*/ - -using namespace Quotient; - -CallAnswerEvent::CallAnswerEvent(const QString& callId, const QString& sdp) - : EventTemplate(callId, { { QStringLiteral("answer"), - QJsonObject { { QStringLiteral("type"), - QStringLiteral("answer") }, - { QStringLiteral("sdp"), sdp } } } }) -{} diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h deleted file mode 100644 index c5ad14df..00000000 --- a/lib/events/callanswerevent.h +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#pragma once - -#include "roomevent.h" - -namespace Quotient { -class QUOTIENT_API CallAnswerEvent - : public EventTemplate { -public: - QUO_EVENT(CallAnswerEvent, "m.call.answer") - - using EventTemplate::EventTemplate; - - explicit CallAnswerEvent(const QString& callId, const QString& sdp); - - QString sdp() const - { - return contentPart("answer"_ls).value("sdp"_ls).toString(); - } -}; -} // namespace Quotient diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h deleted file mode 100644 index f5d2f815..00000000 --- a/lib/events/callcandidatesevent.h +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-FileCopyrightText: 2018 Kitsune Ral -// SPDX-FileCopyrightText: 2020 Carl Schwan -// SPDX-License-Identifier: LGPL-2.1-or-later - -#pragma once - -#include "roomevent.h" - -namespace Quotient { -class CallCandidatesEvent : public EventTemplate { -public: - QUO_EVENT(CallCandidatesEvent, "m.call.candidates") - - using EventTemplate::EventTemplate; - - explicit CallCandidatesEvent(const QString& callId, - const QJsonArray& candidates) - : EventTemplate(callId, { { QStringLiteral("candidates"), candidates } }) - {} - - QUO_CONTENT_GETTER(QJsonArray, candidates) - QUO_CONTENT_GETTER(QString, callId) - QUO_CONTENT_GETTER(int, version) -}; -} // namespace Quotient diff --git a/lib/events/callevents.cpp b/lib/events/callevents.cpp new file mode 100644 index 00000000..3873614d --- /dev/null +++ b/lib/events/callevents.cpp @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2022 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later + +#include "callevents.h" + +#include "logging.h" + +using namespace Quotient; + +QJsonObject CallEvent::basicJson(const QString& matrixType, + const QString& callId, int version, + QJsonObject contentJson) +{ + contentJson.insert(QStringLiteral("call_id"), callId); + contentJson.insert(QStringLiteral("version"), version); + return RoomEvent::basicJson(matrixType, contentJson); +} + +CallEvent::CallEvent(const QJsonObject& json) + : RoomEvent(json) +{ + if (callId().isEmpty()) + qCWarning(EVENTS) << id() << "is a call event with an empty call id"; +} + +/* +m.call.invite +{ + "age": 242352, + "content": { + "call_id": "12345", + "lifetime": 60000, + "offer": { + "sdp": "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]", + "type": "offer" + }, + "version": 0 + }, + "event_id": "$WLGTSEFSEF:localhost", + "origin_server_ts": 1431961217939, + "room_id": "!Cuyf34gef24t:localhost", + "sender": "@example:localhost", + "type": "m.call.invite" +} +*/ + +CallInviteEvent::CallInviteEvent(const QString& callId, int lifetime, + const QString& sdp) + : EventTemplate( + callId, + { { QStringLiteral("lifetime"), lifetime }, + { QStringLiteral("offer"), + QJsonObject{ { QStringLiteral("type"), QStringLiteral("offer") }, + { QStringLiteral("sdp"), sdp } } } }) +{} + +/* +m.call.answer +{ + "age": 242352, + "content": { + "answer": { + "sdp": "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]", + "type": "answer" + }, + "call_id": "12345", + "version": 0 + }, + "event_id": "$WLGTSEFSEF:localhost", + "origin_server_ts": 1431961217939, + "room_id": "!Cuyf34gef24t:localhost", + "sender": "@example:localhost", + "type": "m.call.answer" +} +*/ + +CallAnswerEvent::CallAnswerEvent(const QString& callId, const QString& sdp) + : EventTemplate(callId, { { QStringLiteral("answer"), + QJsonObject { { QStringLiteral("type"), + QStringLiteral("answer") }, + { QStringLiteral("sdp"), sdp } } } }) +{} diff --git a/lib/events/callevents.h b/lib/events/callevents.h new file mode 100644 index 00000000..6d9feae4 --- /dev/null +++ b/lib/events/callevents.h @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2022 Kitsune Ral +// SPDX-License-Identifier: LGPL-2.1-or-later + +#pragma once + +#include "roomevent.h" + +namespace Quotient { + +class QUOTIENT_API CallEvent : public RoomEvent { +public: + QUO_BASE_EVENT(CallEvent, "m.call.*"_ls, RoomEvent::BaseMetaType) + static bool matches(const QJsonObject&, const QString& mType) + { + return mType.startsWith("m.call."); + } + + explicit CallEvent(const QJsonObject& json); + + QUO_CONTENT_GETTER(QString, callId) + QUO_CONTENT_GETTER(int, version) + +protected: + static QJsonObject basicJson(const QString& matrixType, + const QString& callId, int version, + QJsonObject contentJson = {}); +}; +using CallEventBase + [[deprecated("CallEventBase is CallEvent now")]] = CallEvent; + +template +class EventTemplate : public CallEvent { +public: + using CallEvent::CallEvent; + explicit EventTemplate(const QString& callId, + const QJsonObject& contentJson = {}) + : EventTemplate(basicJson(EventT::TypeId, callId, 0, contentJson)) + {} +}; + +template +class EventTemplate + : public EventTemplate { +public: + using EventTemplate::EventTemplate; + template + explicit EventTemplate(const QString& callId, + ContentParamTs&&... contentParams) + : EventTemplate( + callId, + toJson(ContentT{ std::forward(contentParams)... })) + {} +}; + +class QUOTIENT_API CallInviteEvent + : public EventTemplate { +public: + QUO_EVENT(CallInviteEvent, "m.call.invite") + + using EventTemplate::EventTemplate; + + explicit CallInviteEvent(const QString& callId, int lifetime, + const QString& sdp); + + QUO_CONTENT_GETTER(int, lifetime) + QString sdp() const + { + return contentPart("offer"_ls).value("sdp"_ls).toString(); + } +}; + +DEFINE_SIMPLE_EVENT(CallCandidatesEvent, CallEvent, "m.call.candidates", + QJsonArray, candidates, "candidates") + +class QUOTIENT_API CallAnswerEvent + : public EventTemplate { +public: + QUO_EVENT(CallAnswerEvent, "m.call.answer") + + using EventTemplate::EventTemplate; + + explicit CallAnswerEvent(const QString& callId, const QString& sdp); + + QString sdp() const + { + return contentPart("answer"_ls).value("sdp"_ls).toString(); + } +}; + +class QUOTIENT_API CallHangupEvent + : public EventTemplate { +public: + QUO_EVENT(CallHangupEvent, "m.call.hangup") + using EventTemplate::EventTemplate; +}; + +} // namespace Quotient +Q_DECLARE_METATYPE(Quotient::CallEvent*) +Q_DECLARE_METATYPE(const Quotient::CallEvent*) diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h deleted file mode 100644 index f0b131b9..00000000 --- a/lib/events/callhangupevent.h +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#pragma once - -#include "roomevent.h" - -namespace Quotient { -class QUOTIENT_API CallHangupEvent - : public EventTemplate { -public: - QUO_EVENT(CallHangupEvent, "m.call.hangup") - using EventTemplate::EventTemplate; -}; -//REGISTER_EVENT_TYPE(CallHangupEvent) -} // namespace Quotient diff --git a/lib/events/callinviteevent.cpp b/lib/events/callinviteevent.cpp deleted file mode 100644 index 0232275b..00000000 --- a/lib/events/callinviteevent.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#include "callinviteevent.h" - -/* -m.call.invite -{ - "age": 242352, - "content": { - "call_id": "12345", - "lifetime": 60000, - "offer": { - "sdp": "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]", - "type": "offer" - }, - "version": 0 - }, - "event_id": "$WLGTSEFSEF:localhost", - "origin_server_ts": 1431961217939, - "room_id": "!Cuyf34gef24t:localhost", - "sender": "@example:localhost", - "type": "m.call.invite" -} -*/ - -using namespace Quotient; - -CallInviteEvent::CallInviteEvent(const QString& callId, int lifetime, - const QString& sdp) - : EventTemplate(callId, - { { QStringLiteral("lifetime"), lifetime }, - { QStringLiteral("offer"), - QJsonObject { { QStringLiteral("type"), QStringLiteral("offer") }, - { QStringLiteral("sdp"), sdp } } } }) -{} diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h deleted file mode 100644 index fc22f7e1..00000000 --- a/lib/events/callinviteevent.h +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: 2017 Marius Gripsgard -// SPDX-FileCopyrightText: 2018 Josip Delic -// SPDX-License-Identifier: LGPL-2.1-or-later - -#pragma once - -#include "roomevent.h" - -namespace Quotient { -class QUOTIENT_API CallInviteEvent - : public EventTemplate { -public: - QUO_EVENT(CallInviteEvent, "m.call.invite") - - using EventTemplate::EventTemplate; - - explicit CallInviteEvent(const QString& callId, int lifetime, - const QString& sdp); - - QUO_CONTENT_GETTER(int, lifetime) - QString sdp() const - { - return contentPart("offer"_ls).value("sdp"_ls).toString(); - } -}; -} // namespace Quotient diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 2843e1dc..ca751081 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -3,6 +3,7 @@ #include "event.h" +#include "callevents.h" #include "logging.h" #include "stateevent.h" @@ -74,7 +75,7 @@ const QJsonObject Event::unsignedJson() const bool Event::isStateEvent() const { return is(); } -bool Event::isCallEvent() const { return is(); } +bool Event::isCallEvent() const { return is(); } void Event::dumpTo(QDebug dbg) const { diff --git a/lib/events/event.h b/lib/events/event.h index ea5a2554..6a7acf28 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -361,7 +361,7 @@ public: // as an exception. For other base events, Event::is<>() and // Quotient::is<>() should be used; don't add is* methods here bool isStateEvent() const; - [[deprecated("Use is() instead")]] bool isCallEvent() const; + [[deprecated("Use is() instead")]] bool isCallEvent() const; protected: QJsonObject& editJson() { return _json; } @@ -386,7 +386,7 @@ using Events = EventsArray; //! don't need to create an event from its content structure, just go and derive //! straight from the respective \p EventBaseT instead of using EventTemplate); //! specialisations may override that and provide useful semantics even without -//! \p ContentT (see EventTemplate, e.g.). +//! \p ContentT (see EventTemplate, e.g.). //! //! The template uses CRTP to pick the event type id from the actual class; //! it will fail to compile if \p EventT doesn't provide TypeId. It also uses @@ -402,8 +402,8 @@ public: !std::is_same_v, "If you see this, you tried to use EventTemplate with the default" " ContentT type, which is void. This default is only used with explicit" - " specialisations (see CallEventBase, e.g.). Otherwise, if you don't" - " intend to use the content part of EventTemplate then you don't need" + " specialisations (see CallEvent, e.g.). Otherwise, if you don't intend" + " to use the content part of EventTemplate then you don't need" " EventTemplate; just use the base event class directly"); using content_type = ContentT; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index bd06f5c5..8928c81c 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -96,22 +96,6 @@ void RoomEvent::dumpTo(QDebug dbg) const dbg << " (made at " << originTimestamp().toString(Qt::ISODate) << ')'; } -QJsonObject CallEventBase::basicJson(const QString& matrixType, - const QString& callId, int version, - QJsonObject contentJson) -{ - contentJson.insert(QStringLiteral("call_id"), callId); - contentJson.insert(QStringLiteral("version"), version); - return RoomEvent::basicJson(matrixType, contentJson); -} - -CallEventBase::CallEventBase(const QJsonObject& json) - : RoomEvent(json) -{ - if (callId().isEmpty()) - qCWarning(EVENTS) << id() << "is a call event with an empty call id"; -} - #ifdef Quotient_E2EE_ENABLED void RoomEvent::setOriginalEvent(event_ptr_tt&& originalEvent) { diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 830f1d30..47b0b59d 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -79,31 +79,6 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; -class QUOTIENT_API CallEventBase : public RoomEvent { -public: - QUO_BASE_EVENT(CallEventBase, "m.call.*"_ls, RoomEvent::BaseMetaType) - - explicit CallEventBase(const QJsonObject& json); - - QUO_CONTENT_GETTER(QString, callId) - QUO_CONTENT_GETTER(int, version) - -protected: - static QJsonObject basicJson(const QString& matrixType, - const QString& callId, int version, - QJsonObject contentJson = {}); -}; - -template -class EventTemplate : public CallEventBase { -public: - using CallEventBase::CallEventBase; - explicit EventTemplate(const QString& callId, - const QJsonObject& contentJson = {}) - : EventTemplate(basicJson(EventT::TypeId, callId, 0, contentJson)) - {} -}; - } // namespace Quotient Q_DECLARE_METATYPE(Quotient::RoomEvent*) Q_DECLARE_METATYPE(const Quotient::RoomEvent*) -- cgit v1.2.3 From 575534e7cca310c6d6195ab16d482bf9dfba755e Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 1 Aug 2022 18:09:35 +0200 Subject: Disallow direct events construction from JSON Direct construction (using makeEvent() or explicitly constructing an event) from JSON may create an event that has a type conflicting with that stored in JSON. There's no such problem with loadEvent(), even though it's considerably slower. Driven by the fact that almost nowhere in the code direct construction is used on checked JSON (one test is the only valid case), this commit moves all JSON-loading constructors to the protected section, thereby disabling usage of makeEvent() in JSON-loading capacity, and switches such cases across the library to loadEvent(). --- lib/events/callevents.h | 4 ++-- lib/events/event.h | 11 +++++++++-- lib/events/roomevent.cpp | 2 +- lib/events/roomevent.h | 8 ++++---- lib/events/stateevent.h | 15 +++++++++------ 5 files changed, 25 insertions(+), 15 deletions(-) (limited to 'lib/events') diff --git a/lib/events/callevents.h b/lib/events/callevents.h index 6d9feae4..752e331d 100644 --- a/lib/events/callevents.h +++ b/lib/events/callevents.h @@ -15,12 +15,12 @@ public: return mType.startsWith("m.call."); } - explicit CallEvent(const QJsonObject& json); - QUO_CONTENT_GETTER(QString, callId) QUO_CONTENT_GETTER(int, version) protected: + explicit CallEvent(const QJsonObject& json); + static QJsonObject basicJson(const QString& matrixType, const QString& callId, int version, QJsonObject contentJson = {}); diff --git a/lib/events/event.h b/lib/events/event.h index 6a7acf28..9d7c61a9 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -203,6 +203,9 @@ private: // === Event creation facilities === //! \brief Create an event of arbitrary type from its arguments +//! +//! This should not be used to load events from JSON - use loadEvent() for that. +//! \sa loadEvent template inline event_ptr_tt makeEvent(ArgTs&&... args) { @@ -266,8 +269,6 @@ public: return BaseMetaType; } - explicit Event(const QJsonObject& json); - Q_DISABLE_COPY(Event) Event(Event&&) noexcept = default; Event& operator=(Event&&) = delete; @@ -364,6 +365,10 @@ public: [[deprecated("Use is() instead")]] bool isCallEvent() const; protected: + friend class EventMetaType; // To access the below constructor + + explicit Event(const QJsonObject& json); + QJsonObject& editJson() { return _json; } virtual void dumpTo(QDebug dbg) const; @@ -427,6 +432,7 @@ public: //! pointing to that BaseMetaType. //! \sa EventMetaType, EventMetaType::SuppressLoadDerived #define QUO_BASE_EVENT(CppType_, ...) \ + friend class EventMetaType; \ static inline EventMetaType BaseMetaType{ \ #CppType_ __VA_OPT__(,) __VA_ARGS__ }; \ const AbstractEventMetaType& metaType() const override \ @@ -452,6 +458,7 @@ public: //! \sa EventMetaType #define QUO_EVENT(CppType_, MatrixType_, ...) \ static inline const auto& TypeId = MatrixType_##_ls; \ + friend class EventMetaType; \ static inline const EventMetaType MetaType{ \ #CppType_, TypeId, BaseMetaType __VA_OPT__(,) __VA_ARGS__ \ }; \ diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index 8928c81c..e98cb591 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -12,7 +12,7 @@ RoomEvent::RoomEvent(const QJsonObject& json) : Event(json) { if (const auto redaction = unsignedPart(RedactedCauseKeyL); !redaction.isEmpty()) - _redactedBecause = makeEvent(redaction); + _redactedBecause = loadEvent(redaction); } RoomEvent::~RoomEvent() = default; // Let the smart pointer do its job diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 47b0b59d..203434f6 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -16,10 +16,7 @@ class QUOTIENT_API RoomEvent : public Event { public: QUO_BASE_EVENT(RoomEvent, {}, Event::BaseMetaType) - // RedactionEvent is an incomplete type here so we cannot inline - // constructors using it and also destructors (with 'using', in particular). - explicit RoomEvent(const QJsonObject& json); - ~RoomEvent() override; + ~RoomEvent() override; // Don't inline this - see the private section QString id() const; QDateTime originTimestamp() const; @@ -66,9 +63,12 @@ public: #endif protected: + explicit RoomEvent(const QJsonObject& json); void dumpTo(QDebug dbg) const override; private: + // RedactionEvent is an incomplete type here so we cannot inline + // constructors using it and also destructors (with 'using', in particular). event_ptr_tt _redactedBecause; #ifdef Quotient_E2EE_ENABLED diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index 911972f2..ffbce76e 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -24,7 +24,6 @@ public: //! constructors and calls in, e.g., RoomStateView don't include it. static constexpr auto needsStateKey = false; - explicit StateEventBase(const QJsonObject& json); explicit StateEventBase(Type type, const QString& stateKey = {}, const QJsonObject& contentJson = {}); @@ -39,9 +38,11 @@ public: } QString replacedState() const; - void dumpTo(QDebug dbg) const override; - virtual bool repeatsState() const; + +protected: + explicit StateEventBase(const QJsonObject& json); + void dumpTo(QDebug dbg) const override; }; using StateEventPtr = event_ptr_tt; using StateEvents = EventsArray; @@ -129,13 +130,15 @@ private: using base_type = EventTemplate; public: - explicit KeylessStateEventBase(const QJsonObject& fullJson) - : base_type(fullJson) - {} template explicit KeylessStateEventBase(ContentParamTs&&... contentParams) : base_type(QString(), std::forward(contentParams)...) {} + +protected: + explicit KeylessStateEventBase(const QJsonObject& fullJson) + : base_type(fullJson) + {} }; template -- cgit v1.2.3 From bde38f86337d6f49b34b38016ab088d2f48ec371 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 1 Aug 2022 18:09:47 +0200 Subject: concept EventClass Constrain types to derive from Event (or the chosen class), where applicable. --- lib/events/event.h | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index 9d7c61a9..d0b63085 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -64,7 +64,11 @@ struct QUOTIENT_API EventTypeRegistry { class Event; -template +// TODO: move over to std::derived_from once it's available everywhere +template +concept EventClass = std::is_base_of_v; + +template bool is(const Event& e); //! \brief The base class for event metatypes @@ -206,13 +210,13 @@ private: //! //! This should not be used to load events from JSON - use loadEvent() for that. //! \sa loadEvent -template +template inline event_ptr_tt makeEvent(ArgTs&&... args) { return std::make_unique(std::forward(args)...); } -template +template constexpr const auto& mostSpecificMetaType() { if constexpr (requires { EventT::MetaType; }) @@ -226,7 +230,7 @@ constexpr const auto& mostSpecificMetaType() //! Use this factory template to detect the type from the JSON object //! contents (the detected event type should derive from the template //! parameter type) and create an event object of that type. -template +template inline event_ptr_tt loadEvent(const QJsonObject& fullJson) { return mostSpecificMetaType().loadFrom( @@ -238,7 +242,7 @@ inline event_ptr_tt loadEvent(const QJsonObject& fullJson) //! Use this template to resolve the C++ type from the Matrix type string in //! \p matrixType and create an event of that type by passing all parameters //! to BaseEventT::basicJson(). -template +template inline event_ptr_tt loadEvent(const QString& matrixType, const auto&... otherBasicJsonParams) { @@ -246,7 +250,7 @@ inline event_ptr_tt loadEvent(const QString& matrixType, EventT::basicJson(matrixType, otherBasicJsonParams...), matrixType); } -template +template struct JsonConverter> : JsonObjectUnpacker> { // No dump() to avoid any ambiguity on whether a given export to JSON uses @@ -295,7 +299,7 @@ public: //! the returned value will be different. QString matrixType() const; - template + template bool is() const { return Quotient::is(*this); @@ -377,7 +381,7 @@ private: }; using EventPtr = event_ptr_tt; -template +template using EventsArray = std::vector>; using Events = EventsArray; @@ -400,8 +404,10 @@ using Events = EventsArray; //! your class will likely be clearer and more concise. //! \sa https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern //! \sa DEFINE_SIMPLE_EVENT -template +template class EventTemplate : public BaseEventT { + // Above: can't constrain EventT to be EventClass because it's incomplete + // by CRTP definition. public: static_assert( !std::is_same_v, @@ -522,7 +528,7 @@ public: // === is<>(), eventCast<>() and switchOnType<>() === -template +template inline bool is(const Event& e) { if constexpr (requires { EventT::MetaType; }) { @@ -544,7 +550,7 @@ inline bool is(const Event& e) //! can be either "dumb" (BaseEventT*) or "smart" (`event_ptr_tt<>`). This //! overload doesn't affect the event ownership - if the original pointer owns //! the event it must outlive the downcast pointer to keep it from dangling. -template +template inline auto eventCast(const BasePtrT& eptr) -> decltype(static_cast(&*eptr)) { @@ -567,7 +573,7 @@ inline auto eventCast(const BasePtrT& eptr) //! after calling this overload; if it is a temporary, this normally //! leads to the event getting deleted along with the end of //! the temporary's lifetime. -template +template inline auto eventCast(event_ptr_tt&& eptr) { return eptr && is>(*eptr) @@ -576,12 +582,15 @@ inline auto eventCast(event_ptr_tt&& eptr) } namespace _impl { - template - concept Invocable_With_Downcast = + template + concept Invocable_With_Downcast = requires + { + requires EventClass; std::is_base_of_v>>; + }; } -template +template inline auto switchOnType(const BaseT& event, TailT&& tail) { if constexpr (std::is_invocable_v) { @@ -596,7 +605,7 @@ inline auto switchOnType(const BaseT& event, TailT&& tail) } } -template +template inline auto switchOnType(const BaseT& event, FnT1&& fn1, FnTs&&... fns) { using event_type1 = fn_arg_t; @@ -605,7 +614,7 @@ inline auto switchOnType(const BaseT& event, FnT1&& fn1, FnTs&&... fns) return switchOnType(event, std::forward(fns)...); } -template +template [[deprecated("The new name for visit() is switchOnType()")]] // inline auto visit(const BaseT& event, FnTs&&... fns) { -- cgit v1.2.3 From 7251d6856993a08dd8ec1d4965a310e4cf8e97d3 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 10 Aug 2022 21:54:15 +0200 Subject: StateEventBase -> StateEvent Now that StateEvent name is vacated, the naming for event core classes can be completely unified: Event, RoomEvent, CallEvent, StateEvent. --- lib/events/event.cpp | 2 +- lib/events/event.h | 4 ++-- lib/events/roomcreateevent.h | 4 ++-- lib/events/roomtombstoneevent.h | 4 ++-- lib/events/stateevent.cpp | 13 ++++++------- lib/events/stateevent.h | 42 +++++++++++++++++++++-------------------- 6 files changed, 35 insertions(+), 34 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.cpp b/lib/events/event.cpp index ca751081..da7de919 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -73,7 +73,7 @@ const QJsonObject Event::unsignedJson() const return fullJson()[UnsignedKeyL].toObject(); } -bool Event::isStateEvent() const { return is(); } +bool Event::isStateEvent() const { return is(); } bool Event::isCallEvent() const { return is(); } diff --git a/lib/events/event.h b/lib/events/event.h index d0b63085..c8ef5acb 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -125,7 +125,7 @@ inline bool operator==(const AbstractEventMetaType& lhs, //! //! TL;DR for the loadFrom() story: //! - for base event types, use QUO_BASE_EVENT and, if you have additional -//! validation (e.g., JSON has to contain a certain key - see StateEventBase +//! validation (e.g., JSON has to contain a certain key - see StateEvent //! for a real example), define it in the static EventT::isValid() member //! function accepting QJsonObject and returning bool. //! - for leaf (specific) event types - simply use QUO_EVENT and it will do @@ -153,7 +153,7 @@ public: //! any of its base event types) has a static isValid() predicate and //! the event JSON does not satisfy it, nullptr is immediately returned //! to the upper level or to the loadFrom() caller. This is how existence - //! of `state_key` is checked in any type derived from StateEventBase. + //! of `state_key` is checked in any type derived from StateEvent. //! 3. If step 1b above returned non-nullptr, immediately return it. //! 4. //! a. If EventT::isValid() or EventT::TypeId (either, or both) exist and diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 2709258f..5968e187 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -7,11 +7,11 @@ #include "quotient_common.h" namespace Quotient { -class QUOTIENT_API RoomCreateEvent : public StateEventBase { +class QUOTIENT_API RoomCreateEvent : public StateEvent { public: QUO_EVENT(RoomCreateEvent, "m.room.create") - using StateEventBase::StateEventBase; + using StateEvent::StateEvent; struct Predecessor { QString roomId; diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index 95743e32..c85b4dfd 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -6,11 +6,11 @@ #include "stateevent.h" namespace Quotient { -class QUOTIENT_API RoomTombstoneEvent : public StateEventBase { +class QUOTIENT_API RoomTombstoneEvent : public StateEvent { public: QUO_EVENT(RoomTombstoneEvent, "m.room.tombstone") - using StateEventBase::StateEventBase; + using StateEvent::StateEvent; QString serverMessage() const; QString successorRoomId() const; diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp index 204044bb..72ecd5ad 100644 --- a/lib/events/stateevent.cpp +++ b/lib/events/stateevent.cpp @@ -6,30 +6,29 @@ using namespace Quotient; -StateEventBase::StateEventBase(const QJsonObject& json) +StateEvent::StateEvent(const QJsonObject& json) : RoomEvent(json) { Q_ASSERT_X(json.contains(StateKeyKeyL), __FUNCTION__, "Attempt to create a state event without state key"); } -StateEventBase::StateEventBase(Event::Type type, const QString& stateKey, +StateEvent::StateEvent(Event::Type type, const QString& stateKey, const QJsonObject& contentJson) : RoomEvent(basicJson(type, stateKey, contentJson)) {} -bool StateEventBase::repeatsState() const +bool StateEvent::repeatsState() const { - const auto prevContentJson = unsignedPart(PrevContentKeyL); - return fullJson().value(ContentKeyL) == prevContentJson; + return contentJson() == unsignedPart(PrevContentKeyL); } -QString StateEventBase::replacedState() const +QString StateEvent::replacedState() const { return unsignedPart("replaces_state"_ls); } -void StateEventBase::dumpTo(QDebug dbg) const +void StateEvent::dumpTo(QDebug dbg) const { if (!stateKey().isEmpty()) dbg << '<' << stateKey() << "> "; diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index ffbce76e..992ec2e2 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -7,10 +7,10 @@ namespace Quotient { -class QUOTIENT_API StateEventBase : public RoomEvent { +class QUOTIENT_API StateEvent : public RoomEvent { public: - QUO_BASE_EVENT(StateEventBase, "json.contains('state_key')"_ls, - RoomEvent::BaseMetaType) + QUO_BASE_EVENT(StateEvent, "json.contains('state_key')"_ls, + RoomEvent::BaseMetaType) static bool isValid(const QJsonObject& fullJson) { return fullJson.contains(StateKeyKeyL); @@ -24,8 +24,8 @@ public: //! constructors and calls in, e.g., RoomStateView don't include it. static constexpr auto needsStateKey = false; - explicit StateEventBase(Type type, const QString& stateKey = {}, - const QJsonObject& contentJson = {}); + explicit StateEvent(Type type, const QString& stateKey = {}, + const QJsonObject& contentJson = {}); //! Make a minimal correct Matrix state event JSON static QJsonObject basicJson(const QString& matrixTypeId, @@ -41,18 +41,20 @@ public: virtual bool repeatsState() const; protected: - explicit StateEventBase(const QJsonObject& json); + explicit StateEvent(const QJsonObject& json); void dumpTo(QDebug dbg) const override; }; -using StateEventPtr = event_ptr_tt; -using StateEvents = EventsArray; +using StateEventBase + [[deprecated("StateEventBase is StateEvent now")]] = StateEvent; +using StateEventPtr = event_ptr_tt; +using StateEvents = EventsArray; -[[deprecated("Use StateEventBase::basicJson() instead")]] +[[deprecated("Use StateEvent::basicJson() instead")]] inline QJsonObject basicStateEventJson(const QString& matrixTypeId, const QJsonObject& content, const QString& stateKey = {}) { - return StateEventBase::basicJson(matrixTypeId, stateKey, content); + return StateEvent::basicJson(matrixTypeId, stateKey, content); } /** @@ -64,8 +66,8 @@ inline QJsonObject basicStateEventJson(const QString& matrixTypeId, using StateEventKey = std::pair; template -class EventTemplate - : public StateEventBase { +class EventTemplate + : public StateEvent { public: using content_type = ContentT; @@ -82,14 +84,14 @@ public: }; explicit EventTemplate(const QJsonObject& fullJson) - : StateEventBase(fullJson) + : StateEvent(fullJson) , _content(fromJson(Event::contentJson())) , _prev(unsignedJson()) {} template explicit EventTemplate(const QString& stateKey, ContentParamTs&&... contentParams) - : StateEventBase(EventT::TypeId, stateKey) + : StateEvent(EventT::TypeId, stateKey) , _content { std::forward(contentParams)... } { editJson().insert(ContentKey, toJson(_content)); @@ -113,11 +115,11 @@ private: template class KeyedStateEventBase - : public EventTemplate { + : public EventTemplate { public: static constexpr auto needsStateKey = true; - using EventTemplate::EventTemplate; + using EventTemplate::EventTemplate; }; template @@ -125,9 +127,9 @@ concept Keyed_State_Event = EvT::needsStateKey; template class KeylessStateEventBase - : public EventTemplate { + : public EventTemplate { private: - using base_type = EventTemplate; + using base_type = EventTemplate; public: template @@ -145,5 +147,5 @@ template concept Keyless_State_Event = !EvT::needsStateKey; } // namespace Quotient -Q_DECLARE_METATYPE(Quotient::StateEventBase*) -Q_DECLARE_METATYPE(const Quotient::StateEventBase*) +Q_DECLARE_METATYPE(Quotient::StateEvent*) +Q_DECLARE_METATYPE(const Quotient::StateEvent*) -- cgit v1.2.3 From bd2736bc9f8b6023ecbc21d0d831856703b853db Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Tue, 21 Jun 2022 07:37:01 +0200 Subject: SingleKeyValue: use reference for template parameter I guess it was simply overlooked originally; in any case, currently used compilers deal with the reference just as fine as with the pointer. --- lib/events/event.h | 26 +++++++++++++------------- lib/events/simplestateevents.h | 24 ++++++++++++------------ lib/events/single_key_value.h | 6 +++--- 3 files changed, 28 insertions(+), 28 deletions(-) (limited to 'lib/events') diff --git a/lib/events/event.h b/lib/events/event.h index c8ef5acb..0abef1f0 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -511,19 +511,19 @@ public: /// To retrieve the value the getter uses a JSON key name that corresponds to /// its own (getter's) name but written in snake_case. \p GetterName_ must be /// in camelCase, no quotes (an identifier, not a literal). -#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_, \ - JsonKey_) \ - constexpr auto Name_##ContentKey = JsonKey_##_ls; \ - class QUOTIENT_API Name_ \ - : public EventTemplate< \ - Name_, Base_, \ - EventContent::SingleKeyValue> { \ - public: \ - QUO_EVENT(Name_, TypeId_) \ - using value_type = ValueType_; \ - using EventTemplate::EventTemplate; \ - QUO_CONTENT_GETTER_X(ValueType_, GetterName_, Name_##ContentKey) \ - }; \ +#define DEFINE_SIMPLE_EVENT(Name_, Base_, TypeId_, ValueType_, GetterName_, \ + JsonKey_) \ + constexpr auto Name_##ContentKey = JsonKey_##_ls; \ + class QUOTIENT_API Name_ \ + : public EventTemplate< \ + Name_, Base_, \ + EventContent::SingleKeyValue> { \ + public: \ + QUO_EVENT(Name_, TypeId_) \ + using value_type = ValueType_; \ + using EventTemplate::EventTemplate; \ + QUO_CONTENT_GETTER_X(ValueType_, GetterName_, Name_##ContentKey) \ + }; \ // End of macro // === is<>(), eventCast<>() and switchOnType<>() === diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index d84dc1b1..2a0d3817 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -7,17 +7,17 @@ #include "single_key_value.h" namespace Quotient { -#define DEFINE_SIMPLE_STATE_EVENT(Name_, TypeId_, ValueType_, ContentKey_) \ - constexpr auto Name_##Key = #ContentKey_##_ls; \ - class QUOTIENT_API Name_ \ - : public KeylessStateEventBase< \ - Name_, EventContent::SingleKeyValue> { \ - public: \ - using value_type = ValueType_; \ - QUO_EVENT(Name_, TypeId_) \ - using KeylessStateEventBase::KeylessStateEventBase; \ - auto ContentKey_() const { return content().value; } \ - }; \ +#define DEFINE_SIMPLE_STATE_EVENT(Name_, TypeId_, ValueType_, ContentKey_) \ + constexpr auto Name_##Key = #ContentKey_##_ls; \ + class QUOTIENT_API Name_ \ + : public KeylessStateEventBase< \ + Name_, EventContent::SingleKeyValue> { \ + public: \ + using value_type = ValueType_; \ + QUO_EVENT(Name_, TypeId_) \ + using KeylessStateEventBase::KeylessStateEventBase; \ + auto ContentKey_() const { return content().value; } \ + }; \ // End of macro DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) @@ -29,7 +29,7 @@ constexpr auto RoomAliasesEventKey = "aliases"_ls; class QUOTIENT_API RoomAliasesEvent : public KeyedStateEventBase< RoomAliasesEvent, - EventContent::SingleKeyValue> + EventContent::SingleKeyValue> { public: QUO_EVENT(RoomAliasesEvent, "m.room.aliases") diff --git a/lib/events/single_key_value.h b/lib/events/single_key_value.h index 5edff3b1..ca2bd331 100644 --- a/lib/events/single_key_value.h +++ b/lib/events/single_key_value.h @@ -5,7 +5,7 @@ namespace Quotient { namespace EventContent { - template + template struct SingleKeyValue { // NOLINTBEGIN(google-explicit-constructor): that check should learn // about explicit(false) @@ -20,7 +20,7 @@ namespace EventContent { }; } // namespace EventContent -template +template struct JsonConverter> { using content_type = EventContent::SingleKeyValue; static content_type load(const QJsonValue& jv) @@ -31,6 +31,6 @@ struct JsonConverter> { { return { { JsonKey, toJson(c.value) } }; } - static inline const auto JsonKey = toSnakeCase(*KeyStr); + static inline const auto JsonKey = toSnakeCase(KeyStr); }; } // namespace Quotient -- cgit v1.2.3 From 6abdd5358c9c5ed89cda5bc5e50a76af423b0634 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Sun, 11 Sep 2022 20:25:46 +0200 Subject: KeyVerificationEvent; KeyVerificationSession::handleEvent() Key verification events gain their own base type and KeyVerificationSession gets a single point of entry for all kinds of incoming events. This allows to drop a pile of `incoming*` signals in Connection and a stack of options inside switchOnType in processIfVerification(). KVS::handleEvent() also makes (some) allowed state transitions a bit clearer. --- lib/events/keyverificationevent.h | 74 +++++++++++++++------------------------ 1 file changed, 28 insertions(+), 46 deletions(-) (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 0ffd8b2c..0e939508 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -9,13 +9,24 @@ namespace Quotient { static constexpr auto SasV1Method = "m.sas.v1"_ls; +class QUOTIENT_API KeyVerificationEvent : public Event { +public: + QUO_BASE_EVENT(KeyVerificationEvent, "m.key.*"_ls, Event::BaseMetaType) + + using Event::Event; + + /// An opaque identifier for the verification request. Must + /// be unique with respect to the devices involved. + QUO_CONTENT_GETTER(QString, transactionId) +}; + /// Requests a key verification with another user's devices. /// Typically sent as a to-device event. -class QUOTIENT_API KeyVerificationRequestEvent : public Event { +class QUOTIENT_API KeyVerificationRequestEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationRequestEvent, "m.key.verification.request") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationRequestEvent(const QString& transactionId, const QString& fromDevice, const QStringList& methods, @@ -30,10 +41,6 @@ public: /// The device ID which is initiating the request. QUO_CONTENT_GETTER(QString, fromDevice) - /// An opaque identifier for the verification request. Must - /// be unique with respect to the devices involved. - QUO_CONTENT_GETTER(QString, transactionId) - /// The verification methods supported by the sender. QUO_CONTENT_GETTER(QStringList, methods) @@ -44,11 +51,11 @@ public: QUO_CONTENT_GETTER(QDateTime, timestamp) }; -class QUOTIENT_API KeyVerificationReadyEvent : public Event { +class QUOTIENT_API KeyVerificationReadyEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationReadyEvent, "m.key.verification.ready") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationReadyEvent(const QString& transactionId, const QString& fromDevice, const QStringList& methods) @@ -61,19 +68,16 @@ public: /// The device ID which is accepting the request. QUO_CONTENT_GETTER(QString, fromDevice) - /// The transaction id of the verification request - QUO_CONTENT_GETTER(QString, transactionId) - /// The verification methods supported by the sender. QUO_CONTENT_GETTER(QStringList, methods) }; /// Begins a key verification process. -class QUOTIENT_API KeyVerificationStartEvent : public Event { +class QUOTIENT_API KeyVerificationStartEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationStartEvent, "m.key.verification.start") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationStartEvent(const QString& transactionId, const QString& fromDevice) : KeyVerificationStartEvent( @@ -92,10 +96,6 @@ public: /// The device ID which is initiating the process. QUO_CONTENT_GETTER(QString, fromDevice) - /// An opaque identifier for the verification request. Must - /// be unique with respect to the devices involved. - QUO_CONTENT_GETTER(QString, transactionId) - /// The verification method to use. QUO_CONTENT_GETTER(QString, method) @@ -140,11 +140,11 @@ public: /// Accepts a previously sent m.key.verification.start message. /// Typically sent as a to-device event. -class QUOTIENT_API KeyVerificationAcceptEvent : public Event { +class QUOTIENT_API KeyVerificationAcceptEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationAcceptEvent, "m.key.verification.accept") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationAcceptEvent(const QString& transactionId, const QString& commitment) : KeyVerificationAcceptEvent(basicJson( @@ -158,9 +158,6 @@ public: { "commitment"_ls, commitment } })) {} - /// An opaque identifier for the verification process. - QUO_CONTENT_GETTER(QString, transactionId) - /// The verification method to use. Must be 'm.sas.v1'. QUO_CONTENT_GETTER(QString, method) @@ -170,10 +167,7 @@ public: /// The hash method the device is choosing to use, out of the /// options in the m.key.verification.start message. - QString hashData() const - { - return contentPart("hash"_ls); - } + QUO_CONTENT_GETTER_X(QString, hashData, "hash"_ls) /// The message authentication code the device is choosing to use, out /// of the options in the m.key.verification.start message. @@ -188,11 +182,11 @@ public: QUO_CONTENT_GETTER(QString, commitment) }; -class QUOTIENT_API KeyVerificationCancelEvent : public Event { +class QUOTIENT_API KeyVerificationCancelEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationCancelEvent, "m.key.verification.cancel") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationCancelEvent(const QString& transactionId, const QString& reason) : KeyVerificationCancelEvent( @@ -203,9 +197,6 @@ public: })) {} - /// An opaque identifier for the verification process. - QUO_CONTENT_GETTER(QString, transactionId) - /// A human readable description of the code. The client should only /// rely on this string if it does not understand the code. QUO_CONTENT_GETTER(QString, reason) @@ -216,30 +207,27 @@ public: /// Sends the ephemeral public key for a device to the partner device. /// Typically sent as a to-device event. -class QUOTIENT_API KeyVerificationKeyEvent : public Event { +class KeyVerificationKeyEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationKeyEvent, "m.key.verification.key") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationKeyEvent(const QString& transactionId, const QString& key) : KeyVerificationKeyEvent( basicJson(TypeId, { { "transaction_id"_ls, transactionId }, { "key"_ls, key } })) {} - /// An opaque identifier for the verification process. - QUO_CONTENT_GETTER(QString, transactionId) - /// The device's ephemeral public key, encoded as unpadded base64. QUO_CONTENT_GETTER(QString, key) }; /// Sends the MAC of a device's key to the partner device. -class QUOTIENT_API KeyVerificationMacEvent : public Event { +class QUOTIENT_API KeyVerificationMacEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationMacEvent, "m.key.verification.mac") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; KeyVerificationMacEvent(const QString& transactionId, const QString& keys, const QJsonObject& mac) : KeyVerificationMacEvent( @@ -248,9 +236,6 @@ public: { "mac"_ls, mac } })) {} - /// An opaque identifier for the verification process. - QUO_CONTENT_GETTER(QString, transactionId) - /// The device's ephemeral public key, encoded as unpadded base64. QUO_CONTENT_GETTER(QString, keys) @@ -260,17 +245,14 @@ public: } }; -class QUOTIENT_API KeyVerificationDoneEvent : public Event { +class QUOTIENT_API KeyVerificationDoneEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationDoneEvent, "m.key.verification.done") - using Event::Event; + using KeyVerificationEvent::KeyVerificationEvent; explicit KeyVerificationDoneEvent(const QString& transactionId) : KeyVerificationDoneEvent( basicJson(TypeId, { { "transaction_id"_ls, transactionId } })) {} - - /// The same transactionId as before - QUO_CONTENT_GETTER(QString, transactionId) }; } // namespace Quotient -- cgit v1.2.3 From f161519740da12c2578d6ecf79a501e10c2debae Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sat, 24 Sep 2022 11:36:44 +0200 Subject: Fix construction of EncryptedEvents The parent constructor requires full json instead of content json now --- lib/events/encryptedevent.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 94b44901..9ef3b22a 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -8,20 +8,28 @@ using namespace Quotient; EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertexts, const QString& senderKey) - : RoomEvent({ { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, - { CiphertextKeyL, ciphertexts }, - { SenderKeyKeyL, senderKey } }) + : RoomEvent({ + {"content", QJsonObject{ + { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, + { CiphertextKeyL, ciphertexts }, + { SenderKeyKeyL, senderKey } + }}, + {TypeKeyL, "m.room.encrypted"} + }) {} EncryptedEvent::EncryptedEvent(const QByteArray& ciphertext, const QString& senderKey, const QString& deviceId, const QString& sessionId) : RoomEvent({ - { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, - { CiphertextKeyL, QString(ciphertext) }, - { DeviceIdKeyL, deviceId }, - { SenderKeyKeyL, senderKey }, - { SessionIdKeyL, sessionId }, + {"content", QJsonObject{ + { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, + { CiphertextKeyL, QString(ciphertext) }, + { DeviceIdKeyL, deviceId }, + { SenderKeyKeyL, senderKey }, + { SessionIdKeyL, sessionId }, + }}, + {TypeKeyL, "m.room.encrypted"} }) {} -- cgit v1.2.3 From 4146f33bda60d04db34fbd5614439b22b5d5837f Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Sat, 24 Sep 2022 14:27:16 +0200 Subject: Use basicJson() --- lib/events/encryptedevent.cpp | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 9ef3b22a..49df25c8 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -8,29 +8,19 @@ using namespace Quotient; EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertexts, const QString& senderKey) - : RoomEvent({ - {"content", QJsonObject{ - { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, - { CiphertextKeyL, ciphertexts }, - { SenderKeyKeyL, senderKey } - }}, - {TypeKeyL, "m.room.encrypted"} - }) + : RoomEvent(basicJson(TypeId, { { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey }, + { CiphertextKeyL, ciphertexts }, + { SenderKeyKeyL, senderKey } })) {} EncryptedEvent::EncryptedEvent(const QByteArray& ciphertext, const QString& senderKey, const QString& deviceId, const QString& sessionId) - : RoomEvent({ - {"content", QJsonObject{ - { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, - { CiphertextKeyL, QString(ciphertext) }, - { DeviceIdKeyL, deviceId }, - { SenderKeyKeyL, senderKey }, - { SessionIdKeyL, sessionId }, - }}, - {TypeKeyL, "m.room.encrypted"} - }) + : RoomEvent(basicJson(TypeId, { { AlgorithmKeyL, MegolmV1AesSha2AlgoKey }, + { CiphertextKeyL, QString(ciphertext) }, + { DeviceIdKeyL, deviceId }, + { SenderKeyKeyL, senderKey }, + { SessionIdKeyL, sessionId } })) {} EncryptedEvent::EncryptedEvent(const QJsonObject& obj) -- cgit v1.2.3 From 363a7e40e8aa12cb780b076cca8db4f47b70f4fa Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Mon, 26 Sep 2022 09:44:20 +0200 Subject: Replace QOlmError with OlmErrorCode QOlmError represents a subset of OlmErrorCode, and the associated fromString() function uses undocumented strings produced inside Olm; meanwhile OlmErrorCode is documented in its own header file. Each QOlm* class now has lastErrorCode() next to lastError() (that, from now, returns a textual representation straight from Olm, not QOlmError enum). Also: including olm/error.h in e2ee/e2ee.h required some rearrangement of the code to make sure non-E2EE configuration still builds. --- lib/events/encryptedevent.cpp | 1 + lib/events/encryptedevent.h | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/encryptedevent.cpp b/lib/events/encryptedevent.cpp index 94b44901..114addb5 100644 --- a/lib/events/encryptedevent.cpp +++ b/lib/events/encryptedevent.cpp @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later #include "encryptedevent.h" +#include "e2ee/e2ee.h" #include "logging.h" using namespace Quotient; diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 02d4c7aa..e24e5745 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -3,10 +3,15 @@ #pragma once -#include "e2ee/e2ee.h" #include "roomevent.h" namespace Quotient { + +constexpr auto CiphertextKeyL = "ciphertext"_ls; +constexpr auto SenderKeyKeyL = "sender_key"_ls; +constexpr auto DeviceIdKeyL = "device_id"_ls; +constexpr auto SessionIdKeyL = "session_id"_ls; + /* * While the specification states: * -- cgit v1.2.3 From bcc05aa1d52cae2b6d8e70bb6cf04fa49904687a Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 21 Sep 2022 15:45:59 +0200 Subject: Cleanup across E2EE code Notably: - simplified unnecessarily verbose constructs; - formally aligned (no re-numeration was necessary) QOlmMessage::Type with corresponding OLM_ constants; - dropped QOlmSession::encryptMessageType() because it's very sensitive to the order of calling with QOlmSession::encrypt() (and encrypt() itself already calls it and returns the message type); - simplify the return type of pickle() calls that can only fail due to an internal error; - replace const QString& with QStringView or const QByteArray& where appropriate; - use '\0' where it was meant to be instead of '0'. --- lib/events/filesourceinfo.cpp | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) (limited to 'lib/events') diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp index e8b6794b..6abe6a08 100644 --- a/lib/events/filesourceinfo.cpp +++ b/lib/events/filesourceinfo.cpp @@ -59,19 +59,15 @@ std::pair Quotient::encryptFile( const QByteArray& plainText) { #ifdef Quotient_E2EE_ENABLED - QByteArray k = getRandom(32); - auto kBase64 = k.toBase64(); - QByteArray iv = getRandom(16); - JWK key = { "oct"_ls, - { "encrypt"_ls, "decrypt"_ls }, - "A256CTR"_ls, - QString(k.toBase64()) - .replace(u'/', u'_') - .replace(u'+', u'-') - .left(kBase64.indexOf('=')), - true }; - - int length; + auto k = getRandom(32); + auto kBase64 = k.toBase64(QByteArray::Base64UrlEncoding + | QByteArray::OmitTrailingEquals); + auto iv = getRandom(16); + JWK key = { + "oct"_ls, { "encrypt"_ls, "decrypt"_ls }, "A256CTR"_ls, kBase64, true + }; + + int length = -1; auto* ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, reinterpret_cast(k.data()), @@ -89,14 +85,11 @@ std::pair Quotient::encryptFile( EVP_CIPHER_CTX_free(ctx); auto hash = QCryptographicHash::hash(cipherText, QCryptographicHash::Sha256) - .toBase64(); - auto ivBase64 = iv.toBase64(); - EncryptedFileMetadata efm = { {}, - key, - ivBase64.left(ivBase64.indexOf('=')), - { { QStringLiteral("sha256"), - hash.left(hash.indexOf('=')) } }, - "v2"_ls }; + .toBase64(QByteArray::OmitTrailingEquals); + auto ivBase64 = iv.toBase64(QByteArray::OmitTrailingEquals); + EncryptedFileMetadata efm = { + {}, key, ivBase64, { { QStringLiteral("sha256"), hash } }, "v2"_ls + }; return { efm, cipherText }; #else return {}; -- cgit v1.2.3 From bc1ded73bedf593acda80b00eb7da32f688c4843 Mon Sep 17 00:00:00 2001 From: Alexey Rusakov Date: Wed, 21 Sep 2022 16:11:39 +0200 Subject: RandomBuffer A convenient abstraction swallowing all the type casts and, more importantly, cleanup on destruction (previous code only cleaned up the buffer upon a successful call to Olm API but not upon an error). --- lib/events/filesourceinfo.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'lib/events') diff --git a/lib/events/filesourceinfo.cpp b/lib/events/filesourceinfo.cpp index 6abe6a08..a60d86d2 100644 --- a/lib/events/filesourceinfo.cpp +++ b/lib/events/filesourceinfo.cpp @@ -59,19 +59,17 @@ std::pair Quotient::encryptFile( const QByteArray& plainText) { #ifdef Quotient_E2EE_ENABLED - auto k = getRandom(32); + auto k = RandomBuffer(32); auto kBase64 = k.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); - auto iv = getRandom(16); + auto iv = RandomBuffer(16); JWK key = { "oct"_ls, { "encrypt"_ls, "decrypt"_ls }, "A256CTR"_ls, kBase64, true }; int length = -1; auto* ctx = EVP_CIPHER_CTX_new(); - EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, - reinterpret_cast(k.data()), - reinterpret_cast(iv.data())); + EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), nullptr, k.bytes(), iv.bytes()); const auto blockSize = EVP_CIPHER_CTX_block_size(ctx); QByteArray cipherText(plainText.size() + blockSize - 1, '\0'); EVP_EncryptUpdate(ctx, reinterpret_cast(cipherText.data()), -- cgit v1.2.3 From 6824a0ab5614c5497b220eb9e18e190cd57d5710 Mon Sep 17 00:00:00 2001 From: Tobias Fella Date: Thu, 6 Oct 2022 12:27:42 +0200 Subject: Properly export KeyVerificationKeyEvent --- lib/events/keyverificationevent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/events') diff --git a/lib/events/keyverificationevent.h b/lib/events/keyverificationevent.h index 0e939508..80aebcf3 100644 --- a/lib/events/keyverificationevent.h +++ b/lib/events/keyverificationevent.h @@ -207,7 +207,7 @@ public: /// Sends the ephemeral public key for a device to the partner device. /// Typically sent as a to-device event. -class KeyVerificationKeyEvent : public KeyVerificationEvent { +class QUOTIENT_API KeyVerificationKeyEvent : public KeyVerificationEvent { public: QUO_EVENT(KeyVerificationKeyEvent, "m.key.verification.key") -- cgit v1.2.3