diff options
Diffstat (limited to 'lib/events')
-rw-r--r-- | lib/events/accountdataevents.h | 42 | ||||
-rw-r--r-- | lib/events/directchatevent.cpp | 8 | ||||
-rw-r--r-- | lib/events/directchatevent.h | 10 | ||||
-rw-r--r-- | lib/events/event.cpp | 161 | ||||
-rw-r--r-- | lib/events/event.h | 403 | ||||
-rw-r--r-- | lib/events/eventcontent.cpp | 25 | ||||
-rw-r--r-- | lib/events/eventcontent.h | 36 | ||||
-rw-r--r-- | lib/events/eventloader.h | 57 | ||||
-rw-r--r-- | lib/events/receiptevent.cpp | 11 | ||||
-rw-r--r-- | lib/events/receiptevent.h | 8 | ||||
-rw-r--r-- | lib/events/redactionevent.h | 18 | ||||
-rw-r--r-- | lib/events/roomavatarevent.h | 11 | ||||
-rw-r--r-- | lib/events/roomevent.cpp | 82 | ||||
-rw-r--r-- | lib/events/roomevent.h | 91 | ||||
-rw-r--r-- | lib/events/roommemberevent.cpp | 15 | ||||
-rw-r--r-- | lib/events/roommemberevent.h | 27 | ||||
-rw-r--r-- | lib/events/roommessageevent.cpp | 88 | ||||
-rw-r--r-- | lib/events/roommessageevent.h | 30 | ||||
-rw-r--r-- | lib/events/simplestateevents.h | 72 | ||||
-rw-r--r-- | lib/events/stateevent.cpp | 30 | ||||
-rw-r--r-- | lib/events/stateevent.h | 92 | ||||
-rw-r--r-- | lib/events/typingevent.cpp | 10 | ||||
-rw-r--r-- | lib/events/typingevent.h | 8 |
23 files changed, 795 insertions, 540 deletions
diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index 11667172..671ed776 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -22,6 +22,7 @@ #include "event.h" #include "eventcontent.h" +#include "converters.h" namespace QMatrixClient { @@ -32,7 +33,7 @@ namespace QMatrixClient { TagRecord (QString order = {}) : order(std::move(order)) { } explicit TagRecord(const QJsonValue& jv) - : order(jv.toObject().value("order").toString()) + : order(jv.toObject().value("order"_ls).toString()) { } QString order; @@ -50,28 +51,31 @@ namespace QMatrixClient using TagsMap = QHash<QString, TagRecord>; -#define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _EnumType, _ContentType, _ContentKey) \ +#define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ class _Name : public Event \ { \ public: \ - static constexpr const char* typeId() { return _TypeId; } \ - explicit _Name(const QJsonObject& obj) \ - : Event((_EnumType), obj) \ - , _content(contentJson(), QStringLiteral(#_ContentKey)) \ + using content_type = _ContentType; \ + DEFINE_EVENT_TYPEID(_TypeId, _Name) \ + explicit _Name(QJsonObject obj) \ + : Event(typeId(), std::move(obj)) \ { } \ - template <typename... Ts> \ - explicit _Name(Ts&&... contentArgs) \ - : Event(_EnumType) \ - , _content(QStringLiteral(#_ContentKey), \ - std::forward<Ts>(contentArgs)...) \ + explicit _Name(_ContentType content) \ + : Event(typeId(), matrixTypeId(), \ + QJsonObject { { QStringLiteral(#_ContentKey), \ + toJson(std::move(content)) } }) \ { } \ - const _ContentType& _ContentKey() const { return _content.value; } \ - QJsonObject toJson() const { return _content.toJson(); } \ - protected: \ - EventContent::SimpleContent<_ContentType> _content; \ - }; + auto _ContentKey() const \ + { return fromJson<content_type>(contentJson()[#_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<QString>, ignored_users) - DEFINE_SIMPLE_EVENT(TagEvent, "m.tag", EventType::Tag, TagsMap, tags) - DEFINE_SIMPLE_EVENT(ReadMarkerEvent, "m.fully_read", EventType::ReadMarker, - QString, event_id) + DEFINE_EVENTTYPE_ALIAS(Tag, TagEvent) + DEFINE_EVENTTYPE_ALIAS(ReadMarker, ReadMarkerEvent) } diff --git a/lib/events/directchatevent.cpp b/lib/events/directchatevent.cpp index 63d638a3..266d60d8 100644 --- a/lib/events/directchatevent.cpp +++ b/lib/events/directchatevent.cpp @@ -18,18 +18,14 @@ #include "directchatevent.h" -#include "converters.h" +#include <QtCore/QJsonArray> using namespace QMatrixClient; -DirectChatEvent::DirectChatEvent(const QJsonObject& obj) - : Event(Type::DirectChat, obj) -{ } - QMultiHash<QString, QString> DirectChatEvent::usersToDirectChats() const { QMultiHash<QString, QString> result; - const auto json = contentJson(); + const auto& json = contentJson(); for (auto it = json.begin(); it != json.end(); ++it) { // Beware of range-for's over temporary returned from temporary diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index bd8f2d35..7559796b 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -25,10 +25,14 @@ namespace QMatrixClient class DirectChatEvent : public Event { public: - explicit DirectChatEvent(const QJsonObject& obj); + DEFINE_EVENT_TYPEID("m.direct", DirectChatEvent) - QMultiHash<QString, QString> usersToDirectChats() const; + explicit DirectChatEvent(const QJsonObject& obj) + : Event(typeId(), obj) + { } - static constexpr const char* typeId() { return "m.direct"; } + QMultiHash<QString, QString> usersToDirectChats() const; }; + REGISTER_EVENT_TYPE(DirectChatEvent) + DEFINE_EVENTTYPE_ALIAS(DirectChat, DirectChatEvent) } diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 576e9426..44bf79a1 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -18,170 +18,51 @@ #include "event.h" -#include "roommessageevent.h" -#include "simplestateevents.h" -#include "roommemberevent.h" -#include "roomavatarevent.h" -#include "typingevent.h" -#include "receiptevent.h" -#include "accountdataevents.h" -#include "directchatevent.h" -#include "redactionevent.h" #include "logging.h" #include <QtCore/QJsonDocument> using namespace QMatrixClient; -Event::Event(Type type, const QJsonObject& rep) - : _type(type), _originalJson(rep) +event_type_t QMatrixClient::nextTypeId() { - if (!rep.contains("content") && - !rep.value("unsigned").toObject().contains("redacted_because")) - { - qCWarning(EVENTS) << "Event without 'content' node"; - qCWarning(EVENTS) << formatJson << rep; - } + static event_type_t _id = EventTypeTraits<void>::id; + return ++_id; } -Event::~Event() = default; - -QString Event::jsonType() const +Event::Event(Type type, const QJsonObject& json) + : _type(type), _json(json) { - return originalJsonObject().value("type").toString(); -} - -QByteArray Event::originalJson() const -{ - return QJsonDocument(_originalJson).toJson(); -} - -QJsonObject Event::originalJsonObject() const -{ - return _originalJson; -} - -const QJsonObject Event::contentJson() const -{ - return _originalJson["content"].toObject(); -} - -template <typename BaseEventT> -inline event_ptr_tt<BaseEventT> makeIfMatches(const QJsonObject&, const QString&) -{ - return nullptr; -} - -template <typename BaseEventT, typename EventT, typename... EventTs> -inline event_ptr_tt<BaseEventT> makeIfMatches(const QJsonObject& o, - const QString& selector) -{ - if (selector == EventT::typeId()) - return _impl::create<EventT>(o); - - return makeIfMatches<BaseEventT, EventTs...>(o, selector); -} - -template <> -EventPtr _impl::doMakeEvent<Event>(const QJsonObject& obj) -{ - // Check more specific event types first - if (auto e = doMakeEvent<RoomEvent>(obj)) - return ptrCast<Event>(move(e)); - - return makeIfMatches<Event, - TypingEvent, ReceiptEvent, TagEvent, ReadMarkerEvent, DirectChatEvent>( - obj, obj["type"].toString()); -} - -RoomEvent::RoomEvent(Event::Type type) : Event(type) { } - -RoomEvent::RoomEvent(Type type, const QJsonObject& rep) - : Event(type, rep) - , _id(rep["event_id"].toString()) -{ -// if (_id.isEmpty()) -// { -// qCWarning(EVENTS) << "Can't find event_id in a room event"; -// qCWarning(EVENTS) << formatJson << rep; -// } -// if (!rep.contains("origin_server_ts")) -// { -// qCWarning(EVENTS) << "Can't find server timestamp in a room event"; -// qCWarning(EVENTS) << formatJson << rep; -// } -// if (_senderId.isEmpty()) -// { -// qCWarning(EVENTS) << "Can't find sender in a room event"; -// qCWarning(EVENTS) << formatJson << rep; -// } - auto unsignedData = rep["unsigned"].toObject(); - auto redaction = unsignedData.value("redacted_because"); - if (redaction.isObject()) + if (!json.contains(ContentKeyL) && + !json.value(UnsignedKeyL).toObject().contains(RedactedCauseKeyL)) { - _redactedBecause = _impl::create<RedactionEvent>(redaction.toObject()); - return; + qCWarning(EVENTS) << "Event without 'content' node"; + qCWarning(EVENTS) << formatJson << json; } - - _txnId = unsignedData.value("transactionId").toString(); - if (!_txnId.isEmpty()) - qCDebug(EVENTS) << "Event transactionId:" << _txnId; -} - -RoomEvent::~RoomEvent() = default; // Let the smart pointer do its job - -QDateTime RoomEvent::timestamp() const -{ - return QMatrixClient::fromJson<QDateTime>( - originalJsonObject().value("origin_server_ts")); } -QString RoomEvent::roomId() const -{ - return originalJsonObject().value("room_id").toString(); -} - -QString RoomEvent::senderId() const -{ - return originalJsonObject().value("sender").toString(); -} +Event::Event(Type type, event_mtype_t matrixType, const QJsonObject& contentJson) + : Event(type, basicEventJson(matrixType, contentJson)) +{ } -QString RoomEvent::redactionReason() const -{ - return isRedacted() ? _redactedBecause->reason() : QString{}; -} +Event::~Event() = default; -void RoomEvent::addId(const QString& id) +QString Event::matrixType() const { - Q_ASSERT(_id.isEmpty()); Q_ASSERT(!id.isEmpty()); - _id = id; + return fullJson()[TypeKeyL].toString(); } -template <> -RoomEventPtr _impl::doMakeEvent(const QJsonObject& obj) +QByteArray Event::originalJson() const { - // Check more specific event types first - if (auto e = doMakeEvent<StateEventBase>(obj)) - return ptrCast<RoomEvent>(move(e)); - - return makeIfMatches<RoomEvent, - RoomMessageEvent, RedactionEvent>(obj, obj["type"].toString()); + return QJsonDocument(_json).toJson(); } -bool StateEventBase::repeatsState() const +const QJsonObject Event::contentJson() const { - auto contentJson = originalJsonObject().value("content"); - auto prevContentJson = originalJsonObject().value("unsigned") - .toObject().value("prev_content"); - return contentJson == prevContentJson; + return fullJson()[ContentKeyL].toObject(); } -template<> -StateEventPtr _impl::doMakeEvent<StateEventBase>(const QJsonObject& obj) +const QJsonObject Event::unsignedJson() const { - return makeIfMatches<StateEventBase, - RoomNameEvent, RoomAliasesEvent, - RoomCanonicalAliasEvent, RoomMemberEvent, RoomTopicEvent, - RoomAvatarEvent, EncryptionEvent>(obj, obj["type"].toString()); - + return fullJson()[UnsignedKeyL].toObject(); } diff --git a/lib/events/event.h b/lib/events/event.h index cbfa06ac..04384aa7 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -18,11 +18,14 @@ #pragma once -#include "converters.h" #include "util.h" +#include <QtCore/QJsonObject> + namespace QMatrixClient { + // === event_ptr_tt<> and type casting facilities === + template <typename EventT> using event_ptr_tt = std::unique_ptr<EventT>; @@ -44,252 +47,238 @@ namespace QMatrixClient return unique_ptr_cast<TargetT>(ptr); } - namespace _impl + // === Standard Matrix key names and basicEventJson() === + + static const auto TypeKey = QStringLiteral("type"); + static const auto ContentKey = QStringLiteral("content"); + static const auto EventIdKey = QStringLiteral("event_id"); + static const auto TypeKeyL = "type"_ls; + static const auto ContentKeyL = "content"_ls; + static const auto EventIdKeyL = "event_id"_ls; + static const auto UnsignedKeyL = "unsigned"_ls; + static const auto RedactedCauseKeyL = "redacted_because"_ls; + static const auto PrevContentKeyL = "prev_content"_ls; + + // Minimal correct Matrix event JSON + template <typename StrT> + inline QJsonObject basicEventJson(StrT matrixType, + const QJsonObject& content) + { + return { { TypeKey, std::forward<StrT>(matrixType) }, + { ContentKey, content } }; + } + + // === Event factory === + + using event_type_t = size_t; + using event_mtype_t = const char*; + + template <typename EventT> + struct EventTypeTraits + { + static const event_type_t id; + }; + + template <> + struct EventTypeTraits<void> + { + static constexpr event_type_t id = 0; + }; + + event_type_t nextTypeId(); + + template <typename EventT> + const event_type_t EventTypeTraits<EventT>::id = nextTypeId(); + + template <typename EventT> + inline event_type_t typeId() { return EventTypeTraits<std::decay_t<EventT>>::id; } + + inline event_type_t unknownEventTypeId() { return typeId<void>(); } + + template <typename EventT, typename... ArgTs> + inline event_ptr_tt<EventT> makeEvent(ArgTs&&... args) + { + return std::make_unique<EventT>(std::forward<ArgTs>(args)...); + } + + template <typename BaseEventT> + class EventFactory { - template <typename EventT, typename... ArgTs> - inline event_ptr_tt<EventT> create(ArgTs&&... args) - { - return std::make_unique<EventT>(std::forward<ArgTs>(args)...); - } - - template <typename EventT> - inline event_ptr_tt<EventT> doMakeEvent(const QJsonObject& obj) - { - return create<EventT>(obj); - } + public: + template <typename FnT> + static void addMethod(FnT&& method) + { + factories().emplace_back(std::forward<FnT>(method)); + } + + /** 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 <typename EventT> + static auto chainFactory() + { + addMethod(&EventT::factory_t::make); + return 0; + } + + static event_ptr_tt<BaseEventT> make(const QJsonObject& json, + const QString& matrixType) + { + for (const auto& f: factories()) + if (auto e = f(json, matrixType)) + return e; + return makeEvent<BaseEventT>(unknownEventTypeId(), json); + } + + private: + static auto& factories() + { + using inner_factory_tt = + std::function<event_ptr_tt<BaseEventT>(const QJsonObject&, + const QString&)>; + static std::vector<inner_factory_tt> _factories {}; + return _factories; + } + }; + + /** 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 <typename EventT> + inline void setupFactory() + { + EventT::factory_t::addMethod( + [] (const QJsonObject& json, const QString& jsonMatrixType) + { + return EventT::matrixTypeId() == jsonMatrixType + ? makeEvent<EventT>(json) : nullptr; + }); } + // === Event === + class Event { Q_GADGET + Q_PROPERTY(Type type READ type CONSTANT) + Q_PROPERTY(QJsonObject contentJson READ contentJson CONSTANT) public: - enum class Type : quint16 - { - Unknown = 0, - Typing, Receipt, Tag, DirectChat, ReadMarker, - RoomEventBase = 0x1000, - RoomMessage = RoomEventBase + 1, - RoomEncryptedMessage, Redaction, - RoomStateEventBase = 0x1800, - RoomName = RoomStateEventBase + 1, - RoomAliases, RoomCanonicalAlias, RoomMember, RoomTopic, - RoomAvatar, RoomEncryption, RoomCreate, RoomJoinRules, - RoomPowerLevels, - Reserved = 0x2000 - }; - - explicit Event(Type type) : _type(type) { } - Event(Type type, const QJsonObject& rep); + using Type = event_type_t; + using factory_t = EventFactory<Event>; + + explicit Event(Type type, const QJsonObject& json); + explicit Event(Type type, event_mtype_t matrixType, + const QJsonObject& contentJson = {}); Event(const Event&) = delete; + Event(Event&&) = default; + Event& operator=(const Event&) = delete; + Event& operator=(Event&&) = delete; virtual ~Event(); Type type() const { return _type; } - QString jsonType() const; - bool isStateEvent() const - { - return (quint16(_type) & 0x1800) == 0x1800; - } + QString matrixType() const; QByteArray originalJson() const; - QJsonObject originalJsonObject() const; + QJsonObject originalJsonObject() const { return fullJson(); } + + const QJsonObject& fullJson() const { return _json; } // According to the CS API spec, every event also has // a "content" object; but since its structure is different for - // different types, we're implementing it per-event type - // (and in most cases it will be a combination of other fields - // instead of "content" field). + // different types, we're implementing it per-event type. const QJsonObject contentJson() const; + const QJsonObject unsignedJson() const; + + virtual bool isStateEvent() const { return false; } - virtual QJsonObject toJson() const { Q_ASSERT(false); return {}; } + protected: + QJsonObject& editJson() { return _json; } private: Type _type; - QJsonObject _originalJson; - - REGISTER_ENUM(Type) - Q_PROPERTY(Type type READ type CONSTANT) - Q_PROPERTY(QJsonObject contentJson READ contentJson CONSTANT) + QJsonObject _json; }; - using EventType = Event::Type; using EventPtr = event_ptr_tt<Event>; - /** 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 <typename EventT> - inline event_ptr_tt<EventT> makeEvent(const QJsonObject& obj) - { - auto e = _impl::doMakeEvent<EventT>(obj); - if (!e) - e = _impl::create<EventT>(EventType::Unknown, obj); - return e; - } - - namespace _impl - { - template <> - EventPtr doMakeEvent<Event>(const QJsonObject& obj); - } - - template <typename EventT> struct FromJson<event_ptr_tt<EventT>> - { - auto operator()(const QJsonValue& jv) const - { - return makeEvent<EventT>(jv.toObject()); - } - }; - template <typename EventT> using EventsArray = std::vector<event_ptr_tt<EventT>>; using Events = EventsArray<Event>; - class RedactionEvent; + // === Macros used with 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_mtype_t matrixTypeId() { return _Id; } \ + static auto typeId() { return QMatrixClient::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) \ + namespace { \ + [[gnu::unused]] \ + static const auto _factoryAdded##_Type = ( setupFactory<_Type>(), 0); \ + } \ + // End of macro + + // This macro provides constants in EventType:: namespace for + // back-compatibility with libQMatrixClient 0.3 event type system. +#define DEFINE_EVENTTYPE_ALIAS(_Id, _Type) \ + namespace EventType \ + { \ + [[deprecated("Use typeId<>(), is<>() or visit<>()")]] \ + static const auto _Id = typeId<_Type>(); \ + } \ + // End of macro + + // === is<>() and visit<>() === - /** This class corresponds to m.room.* events */ - class RoomEvent : public Event - { - Q_GADGET - Q_PROPERTY(QString id READ id) - Q_PROPERTY(QDateTime timestamp READ timestamp 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) - public: - // RedactionEvent is an incomplete type here so we cannot inline - // constructors and destructors - explicit RoomEvent(Type type); - RoomEvent(Type type, const QJsonObject& rep); - ~RoomEvent() override; - - QString id() const { return _id; } - QDateTime timestamp() const; - QString roomId() const; - QString senderId() const; - bool isRedacted() const { return bool(_redactedBecause); } - const event_ptr_tt<RedactionEvent>& redactedBecause() const - { - return _redactedBecause; - } - QString redactionReason() const; - const QString& transactionId() const { return _txnId; } - - /** - * 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() - */ - void setTransactionId(const QString& txnId) { _txnId = 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 - */ - void addId(const QString& id); + template <typename EventT> + inline bool is(const Event& e) { return e.type() == typeId<EventT>(); } - private: - QString _id; - event_ptr_tt<RedactionEvent> _redactedBecause; - QString _txnId; - }; - using RoomEventPtr = event_ptr_tt<RoomEvent>; - using RoomEvents = EventsArray<RoomEvent>; - using RoomEventsRange = Range<RoomEvents>; + inline bool isUnknown(const Event& e) { return e.type() == unknownEventTypeId(); } - namespace _impl + template <typename FnT> + inline fn_return_t<FnT> visit(const Event& event, FnT visitor) { - template <> - RoomEventPtr doMakeEvent<RoomEvent>(const QJsonObject& obj); + using event_type = fn_arg_t<FnT>; + if (is<event_type>(event)) + return visitor(static_cast<event_type>(event)); + return fn_return_t<FnT>(); } - class StateEventBase: public RoomEvent + template <typename FnT, typename... FnTs> + inline auto visit(const Event& event, FnT visitor1, FnTs&&... visitors) { - public: - explicit StateEventBase(Type type, const QJsonObject& obj) - : RoomEvent(obj.contains("state_key") ? type : Type::Unknown, - obj) - { } - explicit StateEventBase(Type type) - : RoomEvent(type) - { } - ~StateEventBase() override = default; - - virtual bool repeatsState() const; - }; - using StateEventPtr = event_ptr_tt<StateEventBase>; - using StateEvents = EventsArray<StateEventBase>; + using event_type1 = fn_arg_t<FnT>; + if (is<event_type1>(event)) + return visitor1(static_cast<event_type1&>(event)); - namespace _impl - { - template <> - StateEventPtr doMakeEvent<StateEventBase>(const QJsonObject& obj); + return visit(event, std::forward<FnTs>(visitors)...); } - template <typename ContentT> - struct Prev + template <typename BaseEventT, typename... FnTs> + inline auto visit(const event_ptr_tt<BaseEventT>& eptr, FnTs&&... visitors) { - template <typename... ContentParamTs> - explicit Prev(const QJsonObject& unsignedJson, - ContentParamTs&&... contentParams) - : senderId(unsignedJson.value("prev_sender").toString()) - , content(unsignedJson.value("prev_content").toObject(), - std::forward<ContentParamTs>(contentParams)...) - { } - - QString senderId; - ContentT content; - }; - - template <typename ContentT> - class StateEvent: public StateEventBase - { - public: - using content_type = ContentT; - - template <typename... ContentParamTs> - explicit StateEvent(Type type, const QJsonObject& obj, - ContentParamTs&&... contentParams) - : StateEventBase(type, obj) - , _content(contentJson(), - std::forward<ContentParamTs>(contentParams)...) - { - auto unsignedData = obj.value("unsigned").toObject(); - if (unsignedData.contains("prev_content")) - _prev = std::make_unique<Prev<ContentT>>(unsignedData, - std::forward<ContentParamTs>(contentParams)...); - } - template <typename... ContentParamTs> - explicit StateEvent(Type type, ContentParamTs&&... contentParams) - : StateEventBase(type) - , _content(std::forward<ContentParamTs>(contentParams)...) - { } - - QJsonObject toJson() const override { return _content.toJson(); } - - const ContentT& content() const { return _content; } - /** @deprecated Use prevContent instead */ - const ContentT* prev_content() const { return prevContent(); } - const ContentT* prevContent() const - { return _prev ? &_prev->content : nullptr; } - QString prevSenderId() const { return _prev ? _prev->senderId : ""; } + using return_type = decltype(visit(*eptr, visitors...)); + if (eptr) + return visit(*eptr, visitors...); + return return_type(); + } - protected: - ContentT _content; - std::unique_ptr<Prev<ContentT>> _prev; - }; } // namespace QMatrixClient Q_DECLARE_METATYPE(QMatrixClient::Event*) -Q_DECLARE_METATYPE(QMatrixClient::RoomEvent*) Q_DECLARE_METATYPE(const QMatrixClient::Event*) -Q_DECLARE_METATYPE(const QMatrixClient::RoomEvent*) diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index f5974b46..a6b1c763 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -17,8 +17,8 @@ */ #include "eventcontent.h" +#include "util.h" -#include <QtCore/QUrl> #include <QtCore/QMimeDatabase> using namespace QMatrixClient::EventContent; @@ -39,9 +39,9 @@ FileInfo::FileInfo(const QUrl& u, int payloadSize, const QMimeType& mimeType, FileInfo::FileInfo(const QUrl& u, const QJsonObject& infoJson, const QString& originalFilename) : originalInfoJson(infoJson) - , mimeType(QMimeDatabase().mimeTypeForName(infoJson["mimetype"].toString())) + , mimeType(QMimeDatabase().mimeTypeForName(infoJson["mimetype"_ls].toString())) , url(u) - , payloadSize(infoJson["size"].toInt()) + , payloadSize(infoJson["size"_ls].toInt()) , originalName(originalFilename) { if (!mimeType.isValid()) @@ -51,8 +51,8 @@ FileInfo::FileInfo(const QUrl& u, const QJsonObject& infoJson, void FileInfo::fillInfoJson(QJsonObject* infoJson) const { Q_ASSERT(infoJson); - infoJson->insert("size", payloadSize); - infoJson->insert("mimetype", mimeType.name()); + infoJson->insert(QStringLiteral("size"), payloadSize); + infoJson->insert(QStringLiteral("mimetype"), mimeType.name()); } ImageInfo::ImageInfo(const QUrl& u, int fileSize, QMimeType mimeType, @@ -63,23 +63,24 @@ ImageInfo::ImageInfo(const QUrl& u, int fileSize, QMimeType mimeType, ImageInfo::ImageInfo(const QUrl& u, const QJsonObject& infoJson, const QString& originalFilename) : FileInfo(u, infoJson, originalFilename) - , imageSize(infoJson["w"].toInt(), infoJson["h"].toInt()) + , imageSize(infoJson["w"_ls].toInt(), infoJson["h"_ls].toInt()) { } void ImageInfo::fillInfoJson(QJsonObject* infoJson) const { FileInfo::fillInfoJson(infoJson); - infoJson->insert("w", imageSize.width()); - infoJson->insert("h", imageSize.height()); + infoJson->insert(QStringLiteral("w"), imageSize.width()); + infoJson->insert(QStringLiteral("h"), imageSize.height()); } Thumbnail::Thumbnail(const QJsonObject& infoJson) - : ImageInfo(infoJson["thumbnail_url"].toString(), - infoJson["thumbnail_info"].toObject()) + : ImageInfo(infoJson["thumbnail_url"_ls].toString(), + infoJson["thumbnail_info"_ls].toObject()) { } void Thumbnail::fillInfoJson(QJsonObject* infoJson) const { - infoJson->insert("thumbnail_url", url.toString()); - infoJson->insert("thumbnail_info", toInfoJson<ImageInfo>(*this)); + infoJson->insert(QStringLiteral("thumbnail_url"), url.toString()); + infoJson->insert(QStringLiteral("thumbnail_info"), + toInfoJson<ImageInfo>(*this)); } diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 9d44aec0..91d7a8c8 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -21,14 +21,11 @@ // This file contains generic event content definitions, applicable to room // message events as well as other events (e.g., avatars). -#include "converters.h" - +#include <QtCore/QJsonObject> #include <QtCore/QMimeType> #include <QtCore/QUrl> #include <QtCore/QSize> -#include <functional> - namespace QMatrixClient { namespace EventContent @@ -58,37 +55,6 @@ namespace QMatrixClient virtual void fillJson(QJsonObject* o) const = 0; }; - template <typename T = QString> - class SimpleContent: public Base - { - public: - using value_type = T; - - // The constructor is templated to enable perfect forwarding - template <typename TT> - SimpleContent(QString keyName, TT&& value) - : value(std::forward<TT>(value)), key(std::move(keyName)) - { } - SimpleContent(const QJsonObject& json, QString keyName) - : Base(json) - , value(QMatrixClient::fromJson<T>(json[keyName])) - , key(std::move(keyName)) - { } - - public: - T value; - - protected: - QString key; - - private: - void fillJson(QJsonObject* json) const override - { - Q_ASSERT(json); - json->insert(key, QMatrixClient::toJson(value)); - } - }; - // 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 diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h new file mode 100644 index 00000000..5f1e3b57 --- /dev/null +++ b/lib/events/eventloader.h @@ -0,0 +1,57 @@ +/****************************************************************************** +* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net> +* +* 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 +*/ + +#pragma once + +#include "stateevent.h" +#include "converters.h" + +namespace QMatrixClient { + /** 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 <typename BaseEventT> + inline event_ptr_tt<BaseEventT> loadEvent(const QJsonObject& fullJson) + { + return EventFactory<BaseEventT> + ::make(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 <typename BaseEventT> + inline event_ptr_tt<BaseEventT> loadEvent(const QString& matrixType, + const QJsonObject& content) + { + return EventFactory<BaseEventT> + ::make(basicEventJson(matrixType, content), matrixType); + } + + template <typename EventT> struct FromJson<event_ptr_tt<EventT>> + { + auto operator()(const QJsonValue& jv) const + { + return loadEvent<EventT>(jv.toObject()); + } + }; +} // namespace QMatrixClient diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index a12f4c05..47e1398c 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -41,11 +41,9 @@ Example of a Receipt Event: using namespace QMatrixClient; ReceiptEvent::ReceiptEvent(const QJsonObject& obj) - : Event(Type::Receipt, obj) + : Event(typeId(), obj) { - Q_ASSERT(obj["type"].toString() == typeId()); - - const QJsonObject contents = contentJson(); + const auto& contents = contentJson(); _eventsWithReceipts.reserve(contents.size()); for( auto eventIt = contents.begin(); eventIt != contents.end(); ++eventIt ) { @@ -55,14 +53,15 @@ ReceiptEvent::ReceiptEvent(const QJsonObject& obj) qCDebug(EPHEMERAL) << "ReceiptEvent content follows:\n" << contents; continue; } - const QJsonObject reads = eventIt.value().toObject().value("m.read").toObject(); + const QJsonObject reads = eventIt.value().toObject() + .value("m.read"_ls).toObject(); QVector<Receipt> receipts; receipts.reserve(reads.size()); for( auto userIt = reads.begin(); userIt != reads.end(); ++userIt ) { const QJsonObject user = userIt.value().toObject(); receipts.push_back({userIt.key(), - QMatrixClient::fromJson<QDateTime>(user["ts"])}); + fromJson<QDateTime>(user["ts"_ls])}); } _eventsWithReceipts.push_back({eventIt.key(), std::move(receipts)}); } diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index e8d3a65f..c15a01c2 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -21,6 +21,7 @@ #include "event.h" #include <QtCore/QVector> +#include <QtCore/QDateTime> namespace QMatrixClient { @@ -39,14 +40,15 @@ namespace QMatrixClient class ReceiptEvent: public Event { public: + DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) explicit ReceiptEvent(const QJsonObject& obj); - EventsWithReceipts eventsWithReceipts() const + const EventsWithReceipts& eventsWithReceipts() const { return _eventsWithReceipts; } - static constexpr const char* typeId() { return "m.receipt"; } - private: EventsWithReceipts _eventsWithReceipts; }; + REGISTER_EVENT_TYPE(ReceiptEvent) + DEFINE_EVENTTYPE_ALIAS(Receipt, ReceiptEvent) } // namespace QMatrixClient diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index dad54788..64504d57 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -25,19 +25,17 @@ namespace QMatrixClient class RedactionEvent : public RoomEvent { public: - static constexpr const char* typeId() { return "m.room.redaction"; } + DEFINE_EVENT_TYPEID("m.room.redaction", RedactionEvent) explicit RedactionEvent(const QJsonObject& obj) - : RoomEvent(Type::Redaction, obj) - , _redactedEvent(obj.value("redacts").toString()) - , _reason(contentJson().value("reason").toString()) + : RoomEvent(typeId(), obj) { } - const QString& redactedEvent() const { return _redactedEvent; } - const QString& reason() const { return _reason; } - - private: - QString _redactedEvent; - QString _reason; + QString redactedEvent() const + { return fullJson()["redacts"_ls].toString(); } + QString reason() const + { return contentJson()["reason"_ls].toString(); } }; + REGISTER_EVENT_TYPE(RedactionEvent) + DEFINE_EVENTTYPE_ALIAS(Redaction, RedactionEvent) } // namespace QMatrixClient diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index 0e44ad7c..491861b1 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -20,8 +20,6 @@ #include "event.h" -#include <utility> - #include "eventcontent.h" namespace QMatrixClient @@ -33,11 +31,12 @@ namespace QMatrixClient // without a thumbnail. But The Spec says there be thumbnails, and // we follow The Spec. public: + DEFINE_EVENT_TYPEID("m.room.avatar", RoomAvatarEvent) explicit RoomAvatarEvent(const QJsonObject& obj) - : StateEvent(Type::RoomAvatar, obj) + : StateEvent(typeId(), obj) { } - - static constexpr const char* typeId() { return "m.room.avatar"; } + QUrl url() const { return content().url; } }; - + REGISTER_EVENT_TYPE(RoomAvatarEvent) + DEFINE_EVENTTYPE_ALIAS(RoomAvatar, RoomAvatarEvent) } // namespace QMatrixClient diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp new file mode 100644 index 00000000..3d09af8a --- /dev/null +++ b/lib/events/roomevent.cpp @@ -0,0 +1,82 @@ +/****************************************************************************** +* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net> +* +* 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 +*/ + +#include "roomevent.h" + +#include "redactionevent.h" +#include "converters.h" +#include "logging.h" + +using namespace QMatrixClient; + +[[gnu::unused]] static auto roomEventTypeInitialised = + Event::factory_t::chainFactory<RoomEvent>(); + +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) +{ + const auto unsignedData = json[UnsignedKeyL].toObject(); + const auto redaction = unsignedData[RedactedCauseKeyL]; + if (redaction.isObject()) + { + _redactedBecause = makeEvent<RedactionEvent>(redaction.toObject()); + return; + } + + _txnId = unsignedData.value("transactionId"_ls).toString(); + if (!_txnId.isEmpty()) + qCDebug(EVENTS) << "Event transactionId:" << _txnId; +} + +RoomEvent::~RoomEvent() = default; // Let the smart pointer do its job + +QString RoomEvent::id() const +{ + return fullJson()[EventIdKeyL].toString(); +} + +QDateTime RoomEvent::timestamp() const +{ + return QMatrixClient::fromJson<QDateTime>(fullJson()["origin_server_ts"_ls]); +} + +QString RoomEvent::roomId() const +{ + return fullJson()["room_id"_ls].toString(); +} + +QString RoomEvent::senderId() const +{ + return fullJson()["sender"_ls].toString(); +} + +QString RoomEvent::redactionReason() const +{ + return isRedacted() ? _redactedBecause->reason() : QString{}; +} + +void RoomEvent::addId(const QString& newId) +{ + Q_ASSERT(id().isEmpty()); Q_ASSERT(!newId.isEmpty()); + editJson().insert(EventIdKey, newId); +} diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h new file mode 100644 index 00000000..d2bc6edc --- /dev/null +++ b/lib/events/roomevent.h @@ -0,0 +1,91 @@ +/****************************************************************************** +* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net> +* +* 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 +*/ + +#pragma once + +#include "event.h" + +#include <QtCore/QDateTime> + +namespace QMatrixClient { + class RedactionEvent; + + /** This class corresponds to m.room.* events */ + class RoomEvent : public Event + { + Q_GADGET + Q_PROPERTY(QString id READ id) + Q_PROPERTY(QDateTime timestamp READ timestamp 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) + public: + using factory_t = EventFactory<RoomEvent>; + + // 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); + ~RoomEvent() override; + + QString id() const; + QDateTime timestamp() const; + QString roomId() const; + QString senderId() const; + bool isRedacted() const { return bool(_redactedBecause); } + const event_ptr_tt<RedactionEvent>& redactedBecause() const + { + return _redactedBecause; + } + QString redactionReason() const; + const QString& transactionId() const { return _txnId; } + + /** + * 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() + */ + void setTransactionId(const QString& txnId) { _txnId = 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 + */ + void addId(const QString& newId); + + private: + event_ptr_tt<RedactionEvent> _redactedBecause; + QString _txnId; + }; + using RoomEventPtr = event_ptr_tt<RoomEvent>; + using RoomEvents = EventsArray<RoomEvent>; + using RoomEventsRange = Range<RoomEvents>; +} // namespace QMatrixClient +Q_DECLARE_METATYPE(QMatrixClient::RoomEvent*) +Q_DECLARE_METATYPE(const QMatrixClient::RoomEvent*) diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index 76b003c2..79e4af2d 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -18,6 +18,7 @@ #include "roommemberevent.h" +#include "converters.h" #include "logging.h" #include <array> @@ -50,10 +51,10 @@ namespace QMatrixClient } MemberEventContent::MemberEventContent(const QJsonObject& json) - : membership(fromJson<MembershipType>(json["membership"])) - , isDirect(json["is_direct"].toBool()) - , displayName(json["displayname"].toString()) - , avatarUrl(json["avatar_url"].toString()) + : membership(fromJson<MembershipType>(json["membership"_ls])) + , isDirect(json["is_direct"_ls].toBool()) + , displayName(json["displayname"_ls].toString()) + , avatarUrl(json["avatar_url"_ls].toString()) { } void MemberEventContent::fillJson(QJsonObject* o) const @@ -62,8 +63,8 @@ void MemberEventContent::fillJson(QJsonObject* o) const Q_ASSERT_X(membership != MembershipType::Undefined, __FUNCTION__, "The key 'membership' must be explicit in MemberEventContent"); if (membership != MembershipType::Undefined) - o->insert("membership", membershipStrings[membership]); - o->insert("displayname", displayName); + o->insert(QStringLiteral("membership"), membershipStrings[membership]); + o->insert(QStringLiteral("displayname"), displayName); if (avatarUrl.isValid()) - o->insert("avatar_url", avatarUrl.toString()); + o->insert(QStringLiteral("avatar_url"), avatarUrl.toString()); } diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index 8e0cc0a4..f3e4f53a 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -18,12 +18,9 @@ #pragma once -#include "event.h" - +#include "stateevent.h" #include "eventcontent.h" -#include <QtCore/QUrl> - namespace QMatrixClient { class MemberEventContent: public EventContent::Base @@ -36,6 +33,9 @@ namespace QMatrixClient : membership(mt) { } explicit MemberEventContent(const QJsonObject& json); + explicit MemberEventContent(const QJsonValue& jv) + : MemberEventContent(jv.toObject()) + { } MembershipType membership; bool isDirect = false; @@ -52,23 +52,26 @@ namespace QMatrixClient { Q_GADGET public: - static constexpr const char* typeId() { return "m.room.member"; } + DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) using MembershipType = MemberEventContent::MembershipType; - explicit RoomMemberEvent(Type type, const QJsonObject& obj) - : StateEvent(type, obj) + explicit RoomMemberEvent(const QJsonObject& obj) + : StateEvent(typeId(), obj) { } RoomMemberEvent(MemberEventContent&& c) - : StateEvent(Type::RoomMember, c) + : StateEvent(typeId(), matrixTypeId(), c.toJson()) { } - explicit RoomMemberEvent(const QJsonObject& obj) - : RoomMemberEvent(Type::RoomMember, obj) + + // This is a special constructor enabling RoomMemberEvent to be + // a base class for more specific member events. + RoomMemberEvent(Type type, const QJsonObject& fullJson) + : StateEvent(type, fullJson) { } MembershipType membership() const { return content().membership; } QString userId() const - { return originalJsonObject().value("state_key").toString(); } + { return fullJson()["state_key"_ls].toString(); } bool isDirect() const { return content().isDirect; } QString displayName() const { return content().displayName; } QUrl avatarUrl() const { return content().avatarUrl; } @@ -76,4 +79,6 @@ namespace QMatrixClient private: REGISTER_ENUM(MembershipType) }; + REGISTER_EVENT_TYPE(RoomMemberEvent) + DEFINE_EVENTTYPE_ALIAS(RoomMember, RoomMemberEvent) } // namespace QMatrixClient diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index 1a4e74bf..e07054a4 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -35,7 +35,7 @@ TypedBase* make(const QJsonObject& json) struct MsgTypeDesc { - QString jsonType; + QString matrixType; MsgType enumType; TypedBase* (*maker)(const QJsonObject&); }; @@ -56,39 +56,56 @@ QString msgTypeToJson(MsgType enumType) auto it = std::find_if(msgTypes.begin(), msgTypes.end(), [=](const MsgTypeDesc& mtd) { return mtd.enumType == enumType; }); if (it != msgTypes.end()) - return it->jsonType; + return it->matrixType; return {}; } -MsgType jsonToMsgType(const QString& jsonType) +MsgType jsonToMsgType(const QString& matrixType) { auto it = std::find_if(msgTypes.begin(), msgTypes.end(), - [=](const MsgTypeDesc& mtd) { return mtd.jsonType == jsonType; }); + [=](const MsgTypeDesc& mtd) { return mtd.matrixType == matrixType; }); if (it != msgTypes.end()) return it->enumType; return MsgType::Unknown; } +inline QJsonObject toMsgJson(const QString& plainBody, const QString& jsonMsgType, + TypedBase* content) +{ + auto json = content ? content->toJson() : QJsonObject(); + json.insert(QStringLiteral("msgtype"), jsonMsgType); + json.insert(QStringLiteral("body"), plainBody); + return json; +} + +static const auto MsgTypeKey = "msgtype"_ls; +static const auto BodyKey = "body"_ls; + +RoomMessageEvent::RoomMessageEvent(const QString& plainBody, + const QString& jsonMsgType, TypedBase* content) + : RoomEvent(typeId(), matrixTypeId(), + toMsgJson(plainBody, jsonMsgType, content)) + , _content(content) +{ } + RoomMessageEvent::RoomMessageEvent(const QString& plainBody, MsgType msgType, TypedBase* content) : RoomMessageEvent(plainBody, msgTypeToJson(msgType), content) { } RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) - : RoomEvent(Type::RoomMessage, obj), _content(nullptr) + : RoomEvent(typeId(), obj), _content(nullptr) { if (isRedacted()) return; const QJsonObject content = contentJson(); - if ( content.contains("msgtype") && content.contains("body") ) + if ( content.contains(MsgTypeKey) && content.contains(BodyKey) ) { - _plainBody = content["body"].toString(); - - _msgtype = content["msgtype"].toString(); + auto msgtype = content[MsgTypeKey].toString(); for (const auto& mt: msgTypes) - if (mt.jsonType == _msgtype) + if (mt.matrixType == msgtype) _content.reset(mt.maker(content)); if (!_content) @@ -107,13 +124,25 @@ RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) RoomMessageEvent::MsgType RoomMessageEvent::msgtype() const { - return jsonToMsgType(_msgtype); + return jsonToMsgType(rawMsgtype()); +} + +QString RoomMessageEvent::rawMsgtype() const +{ + return contentJson()[MsgTypeKey].toString(); +} + +QString RoomMessageEvent::plainBody() const +{ + return contentJson()[BodyKey].toString(); } QMimeType RoomMessageEvent::mimeType() const { - return _content ? _content->type() : - QMimeDatabase().mimeTypeForName("text/plain"); + static const auto PlainTextMimeType = + QMimeDatabase().mimeTypeForName("text/plain"); + return _content ? _content->type() : PlainTextMimeType; + ; } bool RoomMessageEvent::hasTextContent() const @@ -133,14 +162,6 @@ bool RoomMessageEvent::hasThumbnail() const return content() && content()->thumbnailInfo(); } -QJsonObject RoomMessageEvent::toJson() const -{ - QJsonObject obj = _content ? _content->toJson() : QJsonObject(); - obj.insert("msgtype", msgTypeToJson(msgtype())); - obj.insert("body", plainBody()); - return obj; -} - TextContent::TextContent(const QString& text, const QString& contentType) : mimeType(QMimeDatabase().mimeTypeForName(contentType)), body(text) { } @@ -148,26 +169,29 @@ TextContent::TextContent(const QString& text, const QString& contentType) TextContent::TextContent(const QJsonObject& json) { QMimeDatabase db; + static const auto PlainTextMimeType = db.mimeTypeForName("text/plain"); + static const auto HtmlMimeType = db.mimeTypeForName("text/html"); // Special-casing the custom matrix.org's (actually, Riot's) way // of sending HTML messages. - if (json["format"].toString() == "org.matrix.custom.html") + if (json["format"_ls].toString() == "org.matrix.custom.html") { - mimeType = db.mimeTypeForName("text/html"); - body = json["formatted_body"].toString(); + mimeType = HtmlMimeType; + body = json["formatted_body"_ls].toString(); } else { // Falling back to plain text, as there's no standard way to describe // rich text in messages. - mimeType = db.mimeTypeForName("text/plain"); - body = json["body"].toString(); + mimeType = PlainTextMimeType; + body = json[BodyKey].toString(); } } void TextContent::fillJson(QJsonObject* json) const { Q_ASSERT(json); - json->insert("format", QStringLiteral("org.matrix.custom.html")); - json->insert("formatted_body", body); + json->insert(QStringLiteral("format"), + QStringLiteral("org.matrix.custom.html")); + json->insert(QStringLiteral("formatted_body"), body); } LocationContent::LocationContent(const QString& geoUri, const ImageInfo& thumbnail) @@ -176,8 +200,8 @@ LocationContent::LocationContent(const QString& geoUri, const ImageInfo& thumbna LocationContent::LocationContent(const QJsonObject& json) : TypedBase(json) - , geoUri(json["geo_uri"].toString()) - , thumbnail(json["info"].toObject()) + , geoUri(json["geo_uri"_ls].toString()) + , thumbnail(json["info"_ls].toObject()) { } QMimeType LocationContent::type() const @@ -188,6 +212,6 @@ QMimeType LocationContent::type() const void LocationContent::fillJson(QJsonObject* o) const { Q_ASSERT(o); - o->insert("geo_uri", geoUri); - o->insert("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 075d7188..4c29a93e 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -18,8 +18,7 @@ #pragma once -#include "event.h" - +#include "roomevent.h" #include "eventcontent.h" namespace QMatrixClient @@ -37,6 +36,8 @@ namespace QMatrixClient Q_PROPERTY(QMimeType mimeType READ mimeType STORED false CONSTANT) Q_PROPERTY(EventContent::TypedBase* content READ content CONSTANT) public: + DEFINE_EVENT_TYPEID("m.room.message", RoomMessageEvent) + enum class MsgType { Text, Emote, Notice, Image, File, Location, Video, Audio, Unknown @@ -44,18 +45,15 @@ namespace QMatrixClient RoomMessageEvent(const QString& plainBody, const QString& jsonMsgType, - EventContent::TypedBase* content = nullptr) - : RoomEvent(Type::RoomMessage) - , _msgtype(jsonMsgType), _plainBody(plainBody), _content(content) - { } + EventContent::TypedBase* content = nullptr); explicit RoomMessageEvent(const QString& plainBody, MsgType msgType = MsgType::Text, EventContent::TypedBase* content = nullptr); explicit RoomMessageEvent(const QJsonObject& obj); MsgType msgtype() const; - QString rawMsgtype() const { return _msgtype; } - const QString& plainBody() const { return _plainBody; } + QString rawMsgtype() const; + QString plainBody() const; EventContent::TypedBase* content() const { return _content.data(); } QMimeType mimeType() const; @@ -63,17 +61,13 @@ namespace QMatrixClient bool hasFileContent() const; bool hasThumbnail() const; - QJsonObject toJson() const override; - - static constexpr const char* typeId() { return "m.room.message"; } - private: - QString _msgtype; - QString _plainBody; QScopedPointer<EventContent::TypedBase> _content; REGISTER_ENUM(MsgType) }; + REGISTER_EVENT_TYPE(RoomMessageEvent) + DEFINE_EVENTTYPE_ALIAS(RoomMessage, RoomMessageEvent) using MessageEventType = RoomMessageEvent::MsgType; namespace EventContent @@ -140,16 +134,16 @@ namespace QMatrixClient public: PlayableContent(const QJsonObject& json) : ContentT(json) - , duration(ContentT::originalInfoJson["duration"].toInt()) + , duration(ContentT::originalInfoJson["duration"_ls].toInt()) { } protected: void fillJson(QJsonObject* json) const override { ContentT::fillJson(json); - auto infoJson = json->take("info").toObject(); - infoJson.insert("duration", duration); - json->insert("info", infoJson); + auto infoJson = json->take("info"_ls).toObject(); + infoJson.insert(QStringLiteral("duration"), duration); + json->insert(QStringLiteral("info"), infoJson); } public: diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index d9f403e8..fa1ca8f4 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -18,36 +18,76 @@ #pragma once -#include "event.h" +#include "stateevent.h" #include "eventcontent.h" namespace QMatrixClient { -#define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _EnumType, _ContentType, _ContentKey) \ - class _Name \ - : public StateEvent<EventContent::SimpleContent<_ContentType>> \ + namespace EventContent + { + template <typename T> + class SimpleContent: public Base + { + public: + using value_type = T; + + // The constructor is templated to enable perfect forwarding + template <typename TT> + SimpleContent(QString keyName, TT&& value) + : value(std::forward<TT>(value)), key(std::move(keyName)) + { } + SimpleContent(const QJsonObject& json, QString keyName) + : Base(json) + , value(QMatrixClient::fromJson<T>(json[keyName])) + , key(std::move(keyName)) + { } + + public: + T value; + + protected: + QString key; + + private: + void fillJson(QJsonObject* json) const override + { + Q_ASSERT(json); + json->insert(key, QMatrixClient::toJson(value)); + } + }; + } // namespace EventContent + +#define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ + class _Name : public StateEvent<EventContent::SimpleContent<_ContentType>> \ { \ public: \ - static constexpr const char* typeId() { return _TypeId; } \ + using content_type = _ContentType; \ + DEFINE_EVENT_TYPEID(_TypeId, _Name) \ explicit _Name(const QJsonObject& obj) \ - : StateEvent(_EnumType, obj, QStringLiteral(#_ContentKey)) \ + : StateEvent(typeId(), obj, QStringLiteral(#_ContentKey)) \ { } \ template <typename T> \ explicit _Name(T&& value) \ - : StateEvent(_EnumType, QStringLiteral(#_ContentKey), \ + : StateEvent(typeId(), matrixTypeId(), \ + QStringLiteral(#_ContentKey), \ std::forward<T>(value)) \ { } \ - const _ContentType& _ContentKey() const { return content().value; } \ - }; + auto _ContentKey() const { return content().value; } \ + }; \ + REGISTER_EVENT_TYPE(_Name) \ + // End of macro - DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", - Event::Type::RoomName, QString, name) + DEFINE_SIMPLE_STATE_EVENT(RoomNameEvent, "m.room.name", QString, name) + DEFINE_EVENTTYPE_ALIAS(RoomName, RoomNameEvent) DEFINE_SIMPLE_STATE_EVENT(RoomAliasesEvent, "m.room.aliases", - Event::Type::RoomAliases, QStringList, aliases) + QStringList, aliases) + DEFINE_EVENTTYPE_ALIAS(RoomAliases, RoomAliasesEvent) DEFINE_SIMPLE_STATE_EVENT(RoomCanonicalAliasEvent, "m.room.canonical_alias", - Event::Type::RoomCanonicalAlias, QString, alias) - DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", - Event::Type::RoomTopic, QString, topic) + QString, alias) + DEFINE_EVENTTYPE_ALIAS(RoomCanonicalAlias, RoomCanonicalAliasEvent) + DEFINE_SIMPLE_STATE_EVENT(RoomTopicEvent, "m.room.topic", QString, topic) + DEFINE_EVENTTYPE_ALIAS(RoomTopic, RoomTopicEvent) DEFINE_SIMPLE_STATE_EVENT(EncryptionEvent, "m.room.encryption", - Event::Type::RoomEncryption, QString, algorithm) + QString, algorithm) + DEFINE_EVENTTYPE_ALIAS(RoomEncryption, EncryptionEvent) } // namespace QMatrixClient diff --git a/lib/events/stateevent.cpp b/lib/events/stateevent.cpp new file mode 100644 index 00000000..fd5d2642 --- /dev/null +++ b/lib/events/stateevent.cpp @@ -0,0 +1,30 @@ +/****************************************************************************** +* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net> +* +* 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 +*/ + +#include "stateevent.h" + +using namespace QMatrixClient; + +[[gnu::unused]] static auto stateEventTypeInitialised = + RoomEvent::factory_t::chainFactory<StateEventBase>(); + +bool StateEventBase::repeatsState() const +{ + const auto prevContentJson = unsignedJson().value(PrevContentKeyL); + return fullJson().value(ContentKeyL) == prevContentJson; +} diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h new file mode 100644 index 00000000..6032132e --- /dev/null +++ b/lib/events/stateevent.h @@ -0,0 +1,92 @@ +/****************************************************************************** +* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net> +* +* 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 +*/ + +#pragma once + +#include "roomevent.h" + +namespace QMatrixClient { + class StateEventBase: public RoomEvent + { + public: + using factory_t = EventFactory<StateEventBase>; + + using RoomEvent::RoomEvent; + ~StateEventBase() override = default; + + bool isStateEvent() const override { return true; } + virtual bool repeatsState() const; + }; + using StateEventPtr = event_ptr_tt<StateEventBase>; + using StateEvents = EventsArray<StateEventBase>; + + template <typename ContentT> + struct Prev + { + template <typename... ContentParamTs> + explicit Prev(const QJsonObject& unsignedJson, + ContentParamTs&&... contentParams) + : senderId(unsignedJson.value("prev_sender"_ls).toString()) + , content(unsignedJson.value(PrevContentKeyL).toObject(), + std::forward<ContentParamTs>(contentParams)...) + { } + + QString senderId; + ContentT content; + }; + + template <typename ContentT> + class StateEvent: public StateEventBase + { + public: + using content_type = ContentT; + + template <typename... ContentParamTs> + explicit StateEvent(Type type, const QJsonObject& fullJson, + ContentParamTs&&... contentParams) + : StateEventBase(type, fullJson) + , _content(contentJson(), + std::forward<ContentParamTs>(contentParams)...) + { + const auto& unsignedData = unsignedJson(); + if (unsignedData.contains(PrevContentKeyL)) + _prev = std::make_unique<Prev<ContentT>>(unsignedData, + std::forward<ContentParamTs>(contentParams)...); + } + template <typename... ContentParamTs> + explicit StateEvent(Type type, event_mtype_t matrixType, + ContentParamTs&&... contentParams) + : StateEventBase(type, matrixType) + , _content(std::forward<ContentParamTs>(contentParams)...) + { + editJson().insert(ContentKey, _content.toJson()); + } + + const ContentT& content() const { return _content; } + [[deprecated("Use prevContent instead")]] + const ContentT* prev_content() const { return prevContent(); } + const ContentT* prevContent() const + { return _prev ? &_prev->content : nullptr; } + QString prevSenderId() const + { return _prev ? _prev->senderId : QString(); } + + protected: + ContentT _content; + std::unique_ptr<Prev<ContentT>> _prev; + }; +} // namespace QMatrixClient diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index a4d3bae4..0d39d1be 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -18,15 +18,15 @@ #include "typingevent.h" +#include <QtCore/QJsonArray> + using namespace QMatrixClient; TypingEvent::TypingEvent(const QJsonObject& obj) - : Event(Type::Typing, obj) + : Event(typeId(), obj) { - QJsonValue result; - result= contentJson()["user_ids"]; - QJsonArray array = result.toArray(); - for( const QJsonValue& user: array ) + const auto& array = contentJson()["user_ids"_ls].toArray(); + for(const auto& user: array ) _users.push_back(user.toString()); } diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 6ccbc1c8..27b668b4 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -20,20 +20,20 @@ #include "event.h" -#include <QtCore/QStringList> - namespace QMatrixClient { class TypingEvent: public Event { public: - static constexpr const char* typeId() { return "m.typing"; } + DEFINE_EVENT_TYPEID("m.typing", TypingEvent) TypingEvent(const QJsonObject& obj); - QStringList users() const { return _users; } + const QStringList& users() const { return _users; } private: QStringList _users; }; + REGISTER_EVENT_TYPE(TypingEvent) + DEFINE_EVENTTYPE_ALIAS(Typing, TypingEvent) } // namespace QMatrixClient |