diff --git a/src/core/discussion.h b/src/core/discussion.h index 0811e02b..9c7a8c05 100644 --- a/src/core/discussion.h +++ b/src/core/discussion.h @@ -1,76 +1,75 @@ /* Copyright (c) 2019-2020 Laurent Montel This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef DISCUSSION_H #define DISCUSSION_H #include "libruqola_private_export.h" -#include #include class LIBRUQOLACORE_TESTS_EXPORT Discussion { Q_GADGET public: Discussion(); Q_REQUIRED_RESULT QString description() const; void setDescription(const QString &description); Q_REQUIRED_RESULT QString parentRoomId() const; void setParentRoomId(const QString &parentRoomId); Q_REQUIRED_RESULT int numberMessages() const; void setNumberMessages(int numberMessages); Q_REQUIRED_RESULT qint64 lastMessage() const; void setLastMessage(const qint64 &lastMessage); Q_REQUIRED_RESULT bool operator ==(const Discussion &other) const; Discussion &operator =(const Discussion &other) = default; void parseDiscussion(const QJsonObject &o); Q_REQUIRED_RESULT QString discussionRoomId() const; void setDiscussionRoomId(const QString &discussionRoomId); Q_REQUIRED_RESULT QString lastMessageDisplay() const; Q_REQUIRED_RESULT qint64 timeStamp() const; void setTimeStamp(const qint64 &timeStamp); Q_REQUIRED_RESULT QString timeStampDisplay() const; Q_REQUIRED_RESULT QString fname() const; void setFname(const QString &fname); private: QString mDescription; QString mParentRoomId; QString mDiscussionRoomId; QString mLastMessageDateTimeStr; QString mTimeStampDateTimeStr; QString mFname; int mNumberMessages = 0; qint64 mLastMessage = -1; qint64 mTimeStamp = -1; }; LIBRUQOLACORE_EXPORT QDebug operator <<(QDebug d, const Discussion &t); Q_DECLARE_METATYPE(Discussion) Q_DECLARE_TYPEINFO(Discussion, Q_MOVABLE_TYPE); #endif // DISCUSSION_H diff --git a/src/core/emoticons/unicodeemoticon.cpp b/src/core/emoticons/unicodeemoticon.cpp index 502dd573..a7e5c35a 100644 --- a/src/core/emoticons/unicodeemoticon.cpp +++ b/src/core/emoticons/unicodeemoticon.cpp @@ -1,162 +1,161 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "emoticons/unicodeemoticon.h" #include -#include #include UnicodeEmoticon::UnicodeEmoticon() { } bool UnicodeEmoticon::isValid() const { return !mIdentifier.isEmpty() && !mUnicode.isEmpty(); } QString UnicodeEmoticon::identifier() const { return mIdentifier; } void UnicodeEmoticon::setIdentifier(const QString &name) { mIdentifier = name; } QString UnicodeEmoticon::unicode() const { return mUnicode; } QString UnicodeEmoticon::unicodeDisplay() const { if (!mUnicode.isEmpty()) { if (mCachedHtml.isEmpty()) { mCachedHtml = QStringLiteral("%1").arg(mUnicode); } } return mCachedHtml; } //Code from fairchat //Reimplement it ? QString UnicodeEmoticon::escapeUnicodeEmoji(const QString &pString) { QString retString; if (pString.contains(QLatin1Char('-'))) { const QStringList parts = pString.split(QLatin1Char('-')); for (const auto &item : parts) { int part; std::stringstream ss; ss << std::hex << item.toStdString(); ss >> part; if (part >= 0x10000 && part <= 0x10FFFF) { const int hi = ((part - 0x10000) / 0x400) + 0xD800; const int lo = ((part - 0x10000) % 0x400) + 0xDC00; retString += QChar(hi); retString += QChar(lo); } else { retString = QChar(part); } } } else { int part; std::stringstream ss; ss << std::hex << pString.toStdString(); ss >> part; if (part >= 0x10000 && part <= 0x10FFFF) { const int hi = ((part - 0x10000) / 0x400) + 0xD800; const int lo = ((part - 0x10000) % 0x400) + 0xDC00; retString += QChar(hi); retString += QChar(lo); } else { retString = QChar(part); } } return retString; } QString UnicodeEmoticon::key() const { return mKey; } void UnicodeEmoticon::setKey(const QString &key) { mKey = key; } int UnicodeEmoticon::order() const { return mOrder; } void UnicodeEmoticon::setOrder(int order) { mOrder = order; } void UnicodeEmoticon::setUnicode(const QString &unicode) { mUnicode = escapeUnicodeEmoji(unicode); } QString UnicodeEmoticon::category() const { return mCategory; } void UnicodeEmoticon::setCategory(const QString &category) { mCategory = category; } QStringList UnicodeEmoticon::aliases() const { return mAliases; } void UnicodeEmoticon::setAliases(const QStringList &aliases) { mAliases = aliases; } bool UnicodeEmoticon::hasEmoji(const QString &identifier) const { return (mIdentifier == identifier) || mAliases.contains(identifier); } QDebug operator <<(QDebug d, const UnicodeEmoticon &t) { d << "Identifier : " << t.identifier(); d << "Unicode: " << t.unicode(); d << "Category: " << t.category(); d << "Aliases: " << t.aliases(); d << "Order: " << t.order(); d << "Key:" << t.key(); return d; } diff --git a/src/core/emoticons/unicodeemoticon.h b/src/core/emoticons/unicodeemoticon.h index 55349caa..6f6b28c9 100644 --- a/src/core/emoticons/unicodeemoticon.h +++ b/src/core/emoticons/unicodeemoticon.h @@ -1,71 +1,70 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef UNICODEEMOTICON_H #define UNICODEEMOTICON_H -#include #include #include #include "libruqolacore_export.h" class LIBRUQOLACORE_EXPORT UnicodeEmoticon { Q_GADGET public: UnicodeEmoticon(); Q_REQUIRED_RESULT QString identifier() const; void setIdentifier(const QString &identifier); Q_REQUIRED_RESULT QString unicode() const; Q_REQUIRED_RESULT QString unicodeDisplay() const; void setUnicode(const QString &unicode); Q_REQUIRED_RESULT QString category() const; void setCategory(const QString &category); Q_REQUIRED_RESULT QStringList aliases() const; void setAliases(const QStringList &aliases); Q_REQUIRED_RESULT bool hasEmoji(const QString &identifier) const; Q_REQUIRED_RESULT bool isValid() const; Q_REQUIRED_RESULT int order() const; void setOrder(int order); Q_REQUIRED_RESULT QString key() const; void setKey(const QString &key); private: QStringList mAliases; QString escapeUnicodeEmoji(const QString &pString); QString mIdentifier; QString mUnicode; QString mCategory; QString mKey; mutable QString mCachedHtml; int mOrder = -1; }; Q_DECLARE_METATYPE(UnicodeEmoticon) LIBRUQOLACORE_EXPORT QDebug operator <<(QDebug d, const UnicodeEmoticon &t); #endif // UNICODEEMOTICON_H diff --git a/src/core/messages/messagetranslation.cpp b/src/core/messages/messagetranslation.cpp index 81273e6b..0cddaae2 100644 --- a/src/core/messages/messagetranslation.cpp +++ b/src/core/messages/messagetranslation.cpp @@ -1,63 +1,62 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagetranslation.h" #include -#include MessageTranslation::MessageTranslation() { } QDebug operator <<(QDebug d, const MessageTranslation &t) { d << " translate string " << t.translatedString(); return d; } void MessageTranslation::parse(const QJsonObject &obj) { mTranslatedString.clear(); const QJsonObject languageObject = obj[QLatin1String("translations")].toObject(); const QStringList keys = languageObject.keys(); for (const QString &lang : keys) { mTranslatedString.insert(lang, languageObject.value(lang).toString()); } //qDebug() << " void MessageTranslation::parse(const QJsonObject &obj)"< MessageTranslation::translatedString() const { return mTranslatedString; } void MessageTranslation::setTranslatedString(const QMap &translatedString) { mTranslatedString = translatedString; } QString MessageTranslation::translatedStringFromLanguage(const QString &lang) { return mTranslatedString.value(lang); } diff --git a/src/core/model/notificationdesktopdurationpreferencemodel.h b/src/core/model/notificationdesktopdurationpreferencemodel.h index 10a7a3dc..d28b176e 100644 --- a/src/core/model/notificationdesktopdurationpreferencemodel.h +++ b/src/core/model/notificationdesktopdurationpreferencemodel.h @@ -1,66 +1,65 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef NOTIFICATIONDESKTOPDURATIONPREFERENCEMODEL_H #define NOTIFICATIONDESKTOPDURATIONPREFERENCEMODEL_H #include #include "libruqolacore_export.h" -#include struct NotificationDesktopDurationPreferenceInfo { QString displayText; QString preference; }; class LIBRUQOLACORE_EXPORT NotificationDesktopDurationPreferenceModel : public QAbstractListModel { Q_OBJECT public: enum NotificationPreferenceRoles { NotificationPreferenceI18n = Qt::UserRole + 1, NotificationPreference }; Q_ENUM(NotificationPreferenceRoles) explicit NotificationDesktopDurationPreferenceModel(QObject *parent = nullptr); ~NotificationDesktopDurationPreferenceModel() override; Q_REQUIRED_RESULT int rowCount(const QModelIndex &parent = QModelIndex()) const override; Q_REQUIRED_RESULT QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; Q_REQUIRED_RESULT QHash roleNames() const override; Q_INVOKABLE Q_REQUIRED_RESULT int setCurrentNotificationPreference(const QString &preference); Q_INVOKABLE Q_REQUIRED_RESULT QString currentPreference(int index) const; Q_SIGNALS: void currentNotificationPreferenceChanged(); private: Q_DISABLE_COPY(NotificationDesktopDurationPreferenceModel) void fillModel(); QVector mNotificationDestktopDurationPreferenceList; int mCurrentPreference = 0; }; #endif // NOTIFICATIONDESKTOPDURATIONPREFERENCEMODEL_H diff --git a/src/core/model/notificationdesktopsoundpreferencemodel.h b/src/core/model/notificationdesktopsoundpreferencemodel.h index 2e7e1b03..6982542a 100644 --- a/src/core/model/notificationdesktopsoundpreferencemodel.h +++ b/src/core/model/notificationdesktopsoundpreferencemodel.h @@ -1,66 +1,65 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef NOTIFICATIONDESKTOPSOUNDPREFERENCEMODEL_H #define NOTIFICATIONDESKTOPSOUNDPREFERENCEMODEL_H #include #include "libruqolacore_export.h" -#include struct NotificationDesktopSoundPreferenceInfo { QString displayText; QString preference; }; class LIBRUQOLACORE_EXPORT NotificationDesktopSoundPreferenceModel : public QAbstractListModel { Q_OBJECT public: enum NotificationPreferenceRoles { NotificationPreferenceI18n = Qt::UserRole + 1, NotificationPreference }; Q_ENUM(NotificationPreferenceRoles) explicit NotificationDesktopSoundPreferenceModel(QObject *parent = nullptr); ~NotificationDesktopSoundPreferenceModel() override; Q_REQUIRED_RESULT int rowCount(const QModelIndex &parent = QModelIndex()) const override; Q_REQUIRED_RESULT QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; Q_REQUIRED_RESULT QHash roleNames() const override; Q_INVOKABLE Q_REQUIRED_RESULT int setCurrentNotificationPreference(const QString &preference); Q_INVOKABLE Q_REQUIRED_RESULT QString currentPreference(int index) const; Q_SIGNALS: void currentNotificationPreferenceChanged(); private: Q_DISABLE_COPY(NotificationDesktopSoundPreferenceModel) void fillModel(); QVector mNotificationDestktopSoundPreferenceList; int mCurrentPreference = 0; }; #endif // NOTIFICATIONDESKTOPSOUNDPREFERENCEMODEL_H diff --git a/src/core/model/notificationpreferencemodel.cpp b/src/core/model/notificationpreferencemodel.cpp index dde82172..59c691a0 100644 --- a/src/core/model/notificationpreferencemodel.cpp +++ b/src/core/model/notificationpreferencemodel.cpp @@ -1,114 +1,113 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "notificationpreferencemodel.h" #include -#include NotificationPreferenceModel::NotificationPreferenceModel(QObject *parent) : QAbstractListModel(parent) { fillModel(); } NotificationPreferenceModel::~NotificationPreferenceModel() { } int NotificationPreferenceModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return mNotificationPreferenceList.count(); } QVariant NotificationPreferenceModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= mNotificationPreferenceList.count()) { return {}; } NotificationPreferenceInfo preferenceInfo = mNotificationPreferenceList.at(index.row()); switch (role) { case Qt::DisplayRole: case NotificationPreferenceI18n: return preferenceInfo.displayText; case NotificationPreference: return preferenceInfo.preference; } return {}; } QHash NotificationPreferenceModel::roleNames() const { QHash roles; roles[NotificationPreferenceI18n] = QByteArrayLiteral("preferencei18n"); roles[NotificationPreference] = QByteArrayLiteral("preference"); return roles; } void NotificationPreferenceModel::fillModel() { mNotificationPreferenceList.reserve(4); { NotificationPreferenceInfo preferenceInfo; preferenceInfo.displayText = i18n("Default"); preferenceInfo.preference = QStringLiteral("default"); mNotificationPreferenceList.append(preferenceInfo); } { NotificationPreferenceInfo preferenceInfo; preferenceInfo.displayText = i18n("All Messages"); preferenceInfo.preference = QStringLiteral("all"); mNotificationPreferenceList.append(preferenceInfo); } { NotificationPreferenceInfo preferenceInfo; preferenceInfo.displayText = i18n("Mentions"); preferenceInfo.preference = QStringLiteral("mentions"); mNotificationPreferenceList.append(preferenceInfo); } { NotificationPreferenceInfo preferenceInfo; preferenceInfo.displayText = i18n("Nothing"); preferenceInfo.preference = QStringLiteral("nothing"); mNotificationPreferenceList.append(preferenceInfo); } } int NotificationPreferenceModel::setCurrentNotificationPreference(const QString &preference) { int newStatusIndex = 0; for (int i = 0, total = mNotificationPreferenceList.count(); i < total; ++i) { if (mNotificationPreferenceList.at(i).preference == preference) { newStatusIndex = i; break; } } if (mCurrentPreference != newStatusIndex) { mCurrentPreference = newStatusIndex; Q_EMIT currentNotificationPreferenceChanged(); } return mCurrentPreference; } QString NotificationPreferenceModel::currentPreference(int index) const { const QString str = mNotificationPreferenceList.at(index).preference; return str; } diff --git a/src/core/model/notificationpreferencemodel.h b/src/core/model/notificationpreferencemodel.h index ce1cdb3c..55e4a6b4 100644 --- a/src/core/model/notificationpreferencemodel.h +++ b/src/core/model/notificationpreferencemodel.h @@ -1,66 +1,65 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef NOTIFICATIONPREFERENCEMODEL_H #define NOTIFICATIONPREFERENCEMODEL_H #include "libruqolacore_export.h" #include -#include struct NotificationPreferenceInfo { QString displayText; QString preference; }; class LIBRUQOLACORE_EXPORT NotificationPreferenceModel : public QAbstractListModel { Q_OBJECT public: enum NotificationPreferenceRoles { NotificationPreferenceI18n = Qt::UserRole + 1, NotificationPreference }; Q_ENUM(NotificationPreferenceRoles) explicit NotificationPreferenceModel(QObject *parent = nullptr); ~NotificationPreferenceModel() override; Q_REQUIRED_RESULT int rowCount(const QModelIndex &parent = QModelIndex()) const override; Q_REQUIRED_RESULT QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; Q_REQUIRED_RESULT QHash roleNames() const override; Q_INVOKABLE Q_REQUIRED_RESULT int setCurrentNotificationPreference(const QString &preference); Q_INVOKABLE Q_REQUIRED_RESULT QString currentPreference(int index) const; Q_SIGNALS: void currentNotificationPreferenceChanged(); private: Q_DISABLE_COPY(NotificationPreferenceModel) void fillModel(); QVector mNotificationPreferenceList; int mCurrentPreference = 0; }; #endif // NOTIFICATIONPREFERENCEMODEL_H diff --git a/src/core/model/searchmessagemodel.cpp b/src/core/model/searchmessagemodel.cpp index ed233810..fddaf9f5 100644 --- a/src/core/model/searchmessagemodel.cpp +++ b/src/core/model/searchmessagemodel.cpp @@ -1,63 +1,61 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "searchmessagemodel.h" #include "ruqola_debug.h" #include "rocketchataccount.h" #include "textconverter.h" -#include -#include #include "listmessages.h" SearchMessageModel::SearchMessageModel(const QString &roomID, RocketChatAccount *account, Room *room, QObject *parent) : MessageModel(roomID, account, room, parent) { } SearchMessageModel::~SearchMessageModel() { } void SearchMessageModel::parse(const QJsonObject &obj) { clear(); ListMessages messages; messages.parseMessages(obj, QStringLiteral("messages")); mTotal = messages.total(); for (int i = 0, total = messages.count(); i < total; ++i) { addMessage(messages.at(i)); } setStringNotFound(rowCount() == 0); } void SearchMessageModel::setStringNotFound(bool stringNotFound) { if (mStringNotFound != stringNotFound) { mStringNotFound = stringNotFound; Q_EMIT stringNotFoundChanged(); } } bool SearchMessageModel::stringNotFound() const { return mStringNotFound; } diff --git a/src/core/model/searchmessagemodel.h b/src/core/model/searchmessagemodel.h index 0bc8a8b1..38470b2e 100644 --- a/src/core/model/searchmessagemodel.h +++ b/src/core/model/searchmessagemodel.h @@ -1,49 +1,48 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SEARCHMESSAGEMODEL_H #define SEARCHMESSAGEMODEL_H -#include #include #include "libruqola_private_export.h" #include "messagemodel.h" class RocketChatAccount; class LIBRUQOLACORE_TESTS_EXPORT SearchMessageModel : public MessageModel { Q_OBJECT public: explicit SearchMessageModel(const QString &roomID = QStringLiteral("no_room"), RocketChatAccount *account = nullptr, Room *room = nullptr, QObject *parent = nullptr); ~SearchMessageModel() override; void parse(const QJsonObject &obj); Q_REQUIRED_RESULT bool stringNotFound() const; Q_SIGNALS: void listMessageTypeChanged(); void stringNotFoundChanged(); private: void checkFullList(); void setStringNotFound(bool stringNotFound); QString mRoomId; int mTotal = 0; bool mStringNotFound = false; }; #endif // SEARCHMESSAGEMODEL_H diff --git a/src/core/rocketchataccount.cpp b/src/core/rocketchataccount.cpp index d82eb512..8c0b0e9a 100644 --- a/src/core/rocketchataccount.cpp +++ b/src/core/rocketchataccount.cpp @@ -1,1956 +1,1955 @@ /* Copyright (c) 2017-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "model/messagemodel.h" #include "rocketchataccount.h" #include "model/roommodel.h" #include "roomwrapper.h" #include "typingnotification.h" #include "model/usersmodel.h" #include "ruqola_debug.h" #include "ruqola.h" #include "messagequeue.h" #include "rocketchatbackend.h" #include "model/roomfilterproxymodel.h" #include "ruqolalogger.h" #include "ruqolaserverconfig.h" #include "model/usercompletermodel.h" #include "model/usercompleterfilterproxymodel.h" #include "model/statusmodel.h" #include "utils.h" #include "rocketchatcache.h" #include "fileattachments.h" #include "emoticons/emojimanager.h" #include "model/emoticonmodel.h" #include "otrmanager.h" #include "inputtextmanager.h" #include "model/usersforroommodel.h" #include "model/filesforroommodel.h" #include "model/searchchannelfilterproxymodel.h" #include "model/searchchannelmodel.h" #include "model/loginmethodmodel.h" #include "model/inputcompletermodel.h" #include "model/searchmessagemodel.h" #include "model/searchmessagefilterproxymodel.h" #include "model/discussionsmodel.h" #include "model/threadsmodel.h" #include "model/filesforroomfilterproxymodel.h" #include "model/discussionsfilterproxymodel.h" #include "model/threadsfilterproxymodel.h" #include "model/listmessagesmodel.h" #include "model/threadmessagemodel.h" #include "model/listmessagesmodelfilterproxymodel.h" #include "model/autotranslatelanguagesmodel.h" #include "managerdatapaths.h" #include "authenticationmanager.h" #include "ddpapi/ddpclient.h" #include "discussions.h" #include "receivetypingnotificationmanager.h" #include "restapirequest.h" #include "serverconfiginfo.h" #include "listmessages.h" #include "threads.h" #include #include -#include #include #include #include #include "users/setstatusjob.h" #include "users/usersautocompletejob.h" #define USE_REASTAPI_JOB 1 RocketChatAccount::RocketChatAccount(const QString &accountFileName, QObject *parent) : QObject(parent) { mAccountRoomSettings = new AccountRoomSettings; qCDebug(RUQOLA_LOG) << " RocketChatAccount::RocketChatAccount(const QString &accountFileName, QObject *parent)"<accountName()); } mServerConfigInfo = new ServerConfigInfo(this, this); //Create it before loading settings mLoginMethodModel = new LoginMethodModel(this); mInputTextManager = new InputTextManager(this); connect(mInputTextManager, &InputTextManager::inputCompleter, this, &RocketChatAccount::inputAutocomplete); mInputThreadMessageTextManager = new InputTextManager(this); connect(mInputThreadMessageTextManager, &InputTextManager::inputCompleter, this, &RocketChatAccount::inputThreadMessageAutocomplete); mRuqolaServerConfig = new RuqolaServerConfig; mReceiveTypingNotificationManager = new ReceiveTypingNotificationManager(this); initializeAuthenticationPlugins(); mRocketChatBackend = new RocketChatBackend(this, this); mEmoticonModel = new EmoticonModel(this); //After loadSettings mEmojiManager = new EmojiManager(this); mEmojiManager->setServerUrl(mSettings->serverUrl()); mEmoticonModel->setEmoticons(mEmojiManager->unicodeEmojiList()); mOtrManager = new OtrManager(this); mRoomFilterProxyModel = new RoomFilterProxyModel(this); mUserCompleterModel = new UserCompleterModel(this); mUserCompleterFilterModelProxy = new UserCompleterFilterProxyModel(this); mUserCompleterFilterModelProxy->setSourceModel(mUserCompleterModel); mSearchChannelModel = new SearchChannelModel(this); mSearchChannelFilterProxyModel = new SearchChannelFilterProxyModel(this); mSearchChannelFilterProxyModel->setSourceModel(mSearchChannelModel); mSearchMessageModel = new SearchMessageModel(QString(), this, nullptr, this); mSearchMessageFilterProxyModel = new SearchMessageFilterProxyModel(mSearchMessageModel, this); mFilesModelForRoom = new FilesForRoomModel(this, this); mFilesModelForRoom->setObjectName(QStringLiteral("filesmodelforrooms")); mFilesForRoomFilterProxyModel = new FilesForRoomFilterProxyModel(mFilesModelForRoom, this); mFilesForRoomFilterProxyModel->setObjectName(QStringLiteral("filesforroomfiltermodelproxy")); mDiscussionsModel = new DiscussionsModel(this); mDiscussionsModel->setObjectName(QStringLiteral("discussionsmodel")); mDiscussionsFilterProxyModel = new DiscussionsFilterProxyModel(mDiscussionsModel, this); mDiscussionsFilterProxyModel->setObjectName(QStringLiteral("discussionsfilterproxymodel")); mThreadsModel = new ThreadsModel(this); mThreadsModel->setObjectName(QStringLiteral("threadsmodel")); mThreadsFilterProxyModel = new ThreadsFilterProxyModel(mThreadsModel, this); mThreadsFilterProxyModel->setObjectName(QStringLiteral("threadsfiltermodelproxy")); mThreadMessageModel = new ThreadMessageModel(QString(), this, nullptr, this); mThreadMessageModel->setObjectName(QStringLiteral("threadmessagemodel")); mListMessageModel = new ListMessagesModel(QString(), this, nullptr, this); mListMessageModel->setObjectName(QStringLiteral("listmessagemodel")); mListMessagesFilterProxyModel = new ListMessagesModelFilterProxyModel(mListMessageModel, this); mListMessagesFilterProxyModel->setObjectName(QStringLiteral("listmessagesfiltermodelproxy")); mAutoTranslateLanguagesModel = new AutotranslateLanguagesModel(this); mAutoTranslateLanguagesModel->setObjectName(QStringLiteral("autotranslatelanguagesmodel")); mStatusModel = new StatusModel(this); mRoomModel = new RoomModel(this, this); connect(mRoomModel, &RoomModel::needToUpdateNotification, this, &RocketChatAccount::slotNeedToUpdateNotification); mRoomFilterProxyModel->setSourceModel(mRoomModel); mUserModel = new UsersModel(this); connect(mUserModel, &UsersModel::userStatusChanged, this, &RocketChatAccount::userStatusChanged); mMessageQueue = new MessageQueue(this, this); //TODO fix mem leak ! mTypingNotification = new TypingNotification(this); mCache = new RocketChatCache(this, this); connect(mCache, &RocketChatCache::fileDownloaded, this, &RocketChatAccount::fileDownloaded); connect(mTypingNotification, &TypingNotification::informTypingStatus, this, &RocketChatAccount::slotInformTypingStatus); QTimer::singleShot(0, this, &RocketChatAccount::clearModels); } RocketChatAccount::~RocketChatAccount() { delete mCache; mCache = nullptr; delete mRuqolaServerConfig; delete mRuqolaLogger; delete mAccountRoomSettings; } void RocketChatAccount::removeSettings() { mSettings->removeSettings(); } void RocketChatAccount::loadSettings(const QString &accountFileName) { delete mSettings; mSettings = new RocketChatAccountSettings(accountFileName, this); connect(mSettings, &RocketChatAccountSettings::serverURLChanged, this, &RocketChatAccount::serverUrlChanged); connect(mSettings, &RocketChatAccountSettings::userIDChanged, this, &RocketChatAccount::userIDChanged); connect(mSettings, &RocketChatAccountSettings::userNameChanged, this, &RocketChatAccount::userNameChanged); connect(mSettings, &RocketChatAccountSettings::passwordChanged, this, &RocketChatAccount::passwordChanged); } void RocketChatAccount::slotNeedToUpdateNotification() { bool hasAlert = false; int nbUnread = 0; mRoomModel->getUnreadAlertFromAccount(hasAlert, nbUnread); Q_EMIT updateNotification(hasAlert, nbUnread, accountName()); } void RocketChatAccount::clearModels() { // Clear rooms data and refill it with data in the cache, if there is mRoomModel->reset(); mMessageQueue->loadCache(); //Try to send queue message mMessageQueue->processQueue(); } SearchChannelFilterProxyModel *RocketChatAccount::searchChannelFilterProxyModel() const { return mSearchChannelFilterProxyModel; } SearchChannelModel *RocketChatAccount::searchChannelModel() const { return mSearchChannelModel; } UserCompleterModel *RocketChatAccount::userCompleterModel() const { return mUserCompleterModel; } UserCompleterFilterProxyModel *RocketChatAccount::userCompleterFilterModelProxy() const { return mUserCompleterFilterModelProxy; } EmojiManager *RocketChatAccount::emojiManager() const { return mEmojiManager; } QString RocketChatAccount::userStatusIconFileName(const QString &name) { return mUserModel->userStatusIconFileName(name); } StatusModel *RocketChatAccount::statusModel() const { return mStatusModel; } RuqolaServerConfig *RocketChatAccount::ruqolaServerConfig() const { return mRuqolaServerConfig; } RuqolaLogger *RocketChatAccount::ruqolaLogger() const { return mRuqolaLogger; } RoomFilterProxyModel *RocketChatAccount::roomFilterProxyModel() const { return mRoomFilterProxyModel; } UsersForRoomFilterProxyModel *RocketChatAccount::usersForRoomFilterProxyModel(const QString &roomId) const { return mRoomModel->usersForRoomFilterProxyModel(roomId); } FilesForRoomFilterProxyModel *RocketChatAccount::filesForRoomFilterProxyModel() const { return mFilesForRoomFilterProxyModel; } RocketChatBackend *RocketChatAccount::rocketChatBackend() const { return mRocketChatBackend; } MessageQueue *RocketChatAccount::messageQueue() const { return mMessageQueue; } RocketChatAccountSettings *RocketChatAccount::settings() const { return mSettings; } void RocketChatAccount::slotInformTypingStatus(const QString &room, bool typing) { ddp()->informTypingStatus(room, typing, mSettings->userName()); } RoomModel *RocketChatAccount::roomModel() const { return mRoomModel; } UsersModel *RocketChatAccount::usersModel() const { return mUserModel; } Room *RocketChatAccount::getRoom(const QString &roomId) { return mRoomModel->findRoom(roomId); } DiscussionsFilterProxyModel *RocketChatAccount::discussionsFilterProxyModel() const { return mDiscussionsFilterProxyModel; } ThreadsFilterProxyModel *RocketChatAccount::threadsFilterProxyModel() const { return mThreadsFilterProxyModel; } RoomWrapper *RocketChatAccount::roomWrapper(const QString &roomId) { return mRoomModel->findRoomWrapper(roomId); } MessageModel *RocketChatAccount::messageModelForRoom(const QString &roomID) { return mRoomModel->messageModel(roomID); } void RocketChatAccount::changeDisplayAttachment(const QString &roomId, const QString &messageId, bool displayAttachment) { MessageModel *model = mRoomModel->messageModel(roomId); if (model) { model->changeDisplayAttachment(messageId, displayAttachment); } else { qCWarning(RUQOLA_LOG) << "impossible to find room: " << roomId; } //TODO } void RocketChatAccount::changeShowOriginalMessage(const QString &roomId, const QString &messageId, bool showOriginal) { MessageModel *model = mRoomModel->messageModel(roomId); if (model) { model->changeShowOriginalMessage(messageId, showOriginal); } else { qCWarning(RUQOLA_LOG) << "impossible to find room: " << roomId; } //TODO } QString RocketChatAccount::getUserCurrentMessage(const QString &roomId) { return mRoomModel->inputMessage(roomId); } void RocketChatAccount::setUserCurrentMessage(const QString &message, const QString &roomId) { mRoomModel->setInputMessage(roomId, message); } void RocketChatAccount::textEditing(const QString &roomId, bool clearNotification) { mTypingNotification->textNotificationChanged(roomId, clearNotification); } void RocketChatAccount::reactOnMessage(const QString &messageId, const QString &emoji, bool shouldReact) { restApi()->reactOnMessage(messageId, emoji, shouldReact); } void RocketChatAccount::replyToMessage(const QString &roomID, const QString &message, const QString &messageId) { restApi()->postMessage(roomID, message); } void RocketChatAccount::sendMessage(const QString &roomID, const QString &message) { restApi()->postMessage(roomID, message); } void RocketChatAccount::updateMessage(const QString &roomID, const QString &messageId, const QString &message) { restApi()->updateMessage(roomID, messageId, message); } void RocketChatAccount::replyOnThread(const QString &roomID, const QString &threadMessageId, const QString &message) { restApi()->sendMessage(roomID, message, QString(), threadMessageId); } QString RocketChatAccount::avatarUrlFromDirectChannel(const QString &rid) { return mCache->avatarUrl(Utils::userIdFromDirectChannel(rid, userID())); } void RocketChatAccount::deleteFileMessage(const QString &roomId, const QString &fileId, const QString &channelType) { ddp()->deleteFileMessage(roomId, fileId, channelType); } QString RocketChatAccount::avatarUrl(const QString &userId) { return mCache->avatarUrl(userId); } void RocketChatAccount::insertAvatarUrl(const QString &userId, const QUrl &url) { mCache->insertAvatarUrl(userId, url); } RocketChatRestApi::RestApiRequest *RocketChatAccount::restApi() { if (!mRestApi) { mRestApi = new RocketChatRestApi::RestApiRequest(this); connect(mRestApi, &RocketChatRestApi::RestApiRequest::setChannelJoinDone, this, &RocketChatAccount::setChannelJoinDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::missingChannelPassword, this, &RocketChatAccount::missingChannelPassword); connect(mRestApi, &RocketChatRestApi::RestApiRequest::loadEmojiCustomDone, this, &RocketChatAccount::loadEmoji); connect(mRestApi, &RocketChatRestApi::RestApiRequest::openArchivedRoom, this, &RocketChatAccount::openArchivedRoom); connect(mRestApi, &RocketChatRestApi::RestApiRequest::channelMembersDone, this, &RocketChatAccount::parseUsersForRooms); connect(mRestApi, &RocketChatRestApi::RestApiRequest::channelFilesDone, this, &RocketChatAccount::slotChannelFilesDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::channelRolesDone, this, &RocketChatAccount::slotChannelRolesDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::searchMessageDone, this, &RocketChatAccount::slotSearchMessages); connect(mRestApi, &RocketChatRestApi::RestApiRequest::failed, this, &RocketChatAccount::jobFailed); connect(mRestApi, &RocketChatRestApi::RestApiRequest::spotlightDone, this, &RocketChatAccount::slotSplotLightDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getThreadMessagesDone, this, &RocketChatAccount::slotGetThreadMessagesDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getThreadsDone, this, &RocketChatAccount::slotGetThreadsListDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getDiscussionsDone, this, &RocketChatAccount::slotGetDiscussionsListDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::channelGetAllUserMentionsDone, this, [this](const QJsonObject &obj, const QString &roomId) { slotGetListMessagesDone(obj, roomId, ListMessagesModel::ListMessageType::MentionsMessages); }); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getPinnedMessagesDone, this, [this](const QJsonObject &obj, const QString &roomId) { slotGetListMessagesDone(obj, roomId, ListMessagesModel::ListMessageType::PinnedMessages); }); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getSnippetedMessagesDone, this, [this](const QJsonObject &obj, const QString &roomId) { slotGetListMessagesDone(obj, roomId, ListMessagesModel::ListMessageType::SnipperedMessages); }); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getStarredMessagesDone, this, [this](const QJsonObject &obj, const QString &roomId) { slotGetListMessagesDone(obj, roomId, ListMessagesModel::ListMessageType::StarredMessages); }); connect(mRestApi, &RocketChatRestApi::RestApiRequest::getSupportedLanguagesDone, this, &RocketChatAccount::slotGetSupportedLanguagesDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::usersPresenceDone, this, &RocketChatAccount::slotUsersPresenceDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::usersAutocompleteDone, this, &RocketChatAccount::slotUserAutoCompleterDone); connect(mRestApi, &RocketChatRestApi::RestApiRequest::roomsAutoCompleteChannelAndPrivateDone, this, &RocketChatAccount::slotRoomsAutoCompleteChannelAndPrivateDone); mRestApi->setServerUrl(mSettings->serverUrl()); mRestApi->setRestApiLogger(mRuqolaLogger); } return mRestApi; } void RocketChatAccount::leaveRoom(const QString &roomId, const QString &channelType) { if (channelType == QLatin1Char('c')) { restApi()->leaveChannel(roomId); } else if (channelType == QLatin1Char('p')) { restApi()->leaveGroups(roomId); } else { qCWarning(RUQOLA_LOG) << " unsupport leave room for type " << channelType; } } void RocketChatAccount::hideRoom(const QString &roomId, const QString &channelType) { restApi()->closeChannel(roomId, channelType); } DDPClient *RocketChatAccount::ddp() { if (!mDdp) { mDdp = new DDPClient(this, this); connect(mDdp, &DDPClient::loginStatusChanged, this, &RocketChatAccount::loginStatusChanged); connect(mDdp, &DDPClient::connectedChanged, this, &RocketChatAccount::connectedChanged); connect(mDdp, &DDPClient::changed, this, &RocketChatAccount::changed); connect(mDdp, &DDPClient::added, this, &RocketChatAccount::added); connect(mDdp, &DDPClient::removed, this, &RocketChatAccount::removed); connect(mDdp, &DDPClient::socketError, this, &RocketChatAccount::socketError); connect(mDdp, &DDPClient::disconnectedByServer, this, &RocketChatAccount::slotDisconnectedByServer); if (mSettings) { mDdp->setServerUrl(mSettings->serverUrl()); } mDdp->start(); } return mDdp; } bool RocketChatAccount::editingMode() const { return mEditingMode; } DDPClient::LoginStatus RocketChatAccount::loginStatus() { if (mDdp) { return ddp()->loginStatus(); } else { return DDPClient::LoggedOut; } } void RocketChatAccount::tryLogin() { qCDebug(RUQOLA_LOG) << "Attempting login" << mSettings->userName() << "on" << mSettings->serverUrl(); delete mDdp; mDdp = nullptr; // This creates a new ddp() object. // DDP will automatically try to connect and login. ddp(); // In the meantime, load cache... mRoomModel->reset(); } void RocketChatAccount::logOut() { mSettings->logout(); mRoomModel->clear(); #ifdef USE_REASTAPI_JOB restApi()->logout(); #else QJsonObject user; user[QStringLiteral("username")] = mSettings->userName(); QJsonObject json; json[QStringLiteral("user")] = user; ddp()->method(QStringLiteral("logout"), QJsonDocument(json)); #endif delete mDdp; mDdp = nullptr; Q_EMIT logoutDone(accountName()); Q_EMIT loginStatusChanged(); qCDebug(RUQOLA_LOG) << "Successfully logged out!"; } void RocketChatAccount::clearAllUnreadMessages() { for (int roomIdx = 0, nRooms = mRoomModel->rowCount(); roomIdx < nRooms; ++roomIdx) { const auto roomModelIndex = mRoomModel->index(roomIdx); const auto roomId = roomModelIndex.data(RoomModel::RoomID).toString(); const bool roomHasAlert = roomModelIndex.data(RoomModel::RoomAlert).toBool(); if (roomHasAlert) { clearUnreadMessages(roomId); } } } void RocketChatAccount::clearUnreadMessages(const QString &roomId) { restApi()->markAsRead(roomId); } void RocketChatAccount::changeFavorite(const QString &roomId, bool checked) { restApi()->markAsFavorite(roomId, checked); } void RocketChatAccount::openChannel(const QString &url) { qCDebug(RUQOLA_LOG) << "opening channel" << url; restApi()->channelJoin(url, QString()); //TODO search correct room + select it. } void RocketChatAccount::setChannelJoinDone(const QString &roomId) { ddp()->subscribeRoomMessage(roomId); } void RocketChatAccount::openArchivedRoom(const QString &roomId) { //TODO } void RocketChatAccount::joinJitsiConfCall(const QString &roomId) { qCDebug(RUQOLA_LOG) << " void RocketChatAccount::joinJitsiConfCall(const QString &roomId)"<uniqueId() + roomId).toUtf8(), QCryptographicHash::Md5).toHex()); #if defined(Q_OS_IOS) || defined(Q_OS_ANDROID) const QString scheme = QStringLiteral("org.jitsi.meet://"); #else const QString scheme = QStringLiteral("https://"); #endif const QString url = scheme + mRuqolaServerConfig->jitsiMeetUrl() + QLatin1Char('/') + mRuqolaServerConfig->jitsiMeetPrefix() + hash; const QUrl clickedUrl = QUrl::fromUserInput(url); QDesktopServices::openUrl(clickedUrl); } void RocketChatAccount::eraseRoom(const QString &roomId, const QString &channelType) { if (channelType == QLatin1Char('c')) { restApi()->channelDelete(roomId); } else if (channelType == QLatin1Char('p')) { restApi()->groupDelete(roomId); } else { qCWarning(RUQOLA_LOG) << " unsupport delete for type " << channelType; } } void RocketChatAccount::openDirectChannel(const QString &username) { //Laurent for the moment I didn't find a restapi method for it //TODO verify username vs userId //#ifdef USE_REASTAPI_JOB // restApi()->openDirectMessage(username); //#else qDebug() << "Open direct conversation channel with" << username; ddp()->openDirectChannel(username); //#endif } void RocketChatAccount::createNewChannel(const QString &name, bool readOnly, bool privateRoom, const QString &userNames, bool encryptedRoom, const QString &password, bool broadcast) { //TODO use encrypted room //TODO use broadcast if (!name.trimmed().isEmpty()) { const QStringList lstUsers = userNames.split(QLatin1Char(','), QString::SkipEmptyParts); if (privateRoom) { //TODO add password ??? restApi()->createGroups(name, readOnly, lstUsers); } else { restApi()->createChannels(name, readOnly, lstUsers, password); } } else { qCDebug(RUQOLA_LOG) << "Channel name can't be empty"; } } void RocketChatAccount::joinRoom(const QString &roomId, const QString &joinCode) { restApi()->channelJoin(roomId, joinCode); } void RocketChatAccount::channelAndPrivateAutocomplete(const QString &pattern) { //TODO use restapi if (pattern.isEmpty()) { searchChannelModel()->clear(); } else { //Use restapi //Avoid to show own user #ifdef USE_REASTAPI_JOB restApi()->searchRoomUser(pattern); #else const QString addUserNameToException = userName(); ddp()->channelAndPrivateAutocomplete(pattern, addUserNameToException); #endif } } void RocketChatAccount::listEmojiCustom() { restApi()->listEmojiCustom(); } void RocketChatAccount::setDefaultStatus(User::PresenceStatus status, const QString &messageStatus) { #ifdef USE_REASTAPI_JOB RocketChatRestApi::SetStatusJob::StatusType type = RocketChatRestApi::SetStatusJob::Unknown; switch (status) { case User::PresenceStatus::PresenceOnline: type = RocketChatRestApi::SetStatusJob::OnLine; break; case User::PresenceStatus::PresenceBusy: type = RocketChatRestApi::SetStatusJob::Busy; break; case User::PresenceStatus::PresenceAway: type = RocketChatRestApi::SetStatusJob::Away; break; case User::PresenceStatus::PresenceOffline: type = RocketChatRestApi::SetStatusJob::Offline; break; case User::PresenceStatus::Unknown: type = RocketChatRestApi::SetStatusJob::Unknown; break; } restApi()->setUserStatus(userID(), type, messageStatus); #else Q_UNUSED(messageStatus); ddp()->setDefaultStatus(status); #endif } void RocketChatAccount::changeDefaultStatus(int index, const QString &messageStatus) { setDefaultStatus(mStatusModel->status(index), messageStatus); } void RocketChatAccount::loadEmoji(const QJsonObject &obj) { mEmojiManager->loadCustomEmoji(obj); } void RocketChatAccount::deleteMessage(const QString &messageId, const QString &roomId) { restApi()->deleteMessage(roomId, messageId); } void RocketChatAccount::insertCompleterUsers() { userCompleterModel()->insertUsers(rocketChatBackend()->users()); } void RocketChatAccount::userAutocomplete(const QString &searchText, const QString &exception) { if (mRuqolaServerConfig->hasAtLeastVersion(2, 4, 0)) { if (!searchText.isEmpty()) { RocketChatRestApi::UsersAutocompleteJob::UsersAutocompleterInfo info; info.pattern = searchText; info.exception = exception; userCompleterModel()->clear(); restApi()->usersAutocomplete(info); } } else { //Clear before to create new search userCompleterModel()->clear(); rocketChatBackend()->clearUsersList(); if (!searchText.isEmpty()) { //Avoid to show own user QString addUserNameToException; if (exception.isEmpty()) { addUserNameToException = userName(); } else { addUserNameToException = exception + QLatin1Char(',') + userName(); } ddp()->userAutocomplete(searchText, addUserNameToException); } } } void RocketChatAccount::membersInRoom(const QString &roomId, const QString &roomType) { restApi()->membersInRoom(roomId, roomType); } void RocketChatAccount::parseUsersForRooms(const QJsonObject &obj, const QString &roomId) { UsersForRoomModel *usersModelForRoom = roomModel()->usersModelForRoom(roomId); if (usersModelForRoom) { usersModelForRoom->parseUsersForRooms(obj, mUserModel, true); } else { qCWarning(RUQOLA_LOG) << " Impossible to find room " << roomId; } } void RocketChatAccount::loadAutoCompleteChannel(const QJsonObject &obj) { mSearchChannelModel->parseChannels(obj); } void RocketChatAccount::roomFiles(const QString &roomId, const QString &channelType) { mFilesModelForRoom->initialize(); restApi()->filesInRoom(roomId, channelType); } MessageModel *RocketChatAccount::threadMessageModel() const { return mThreadMessageModel; } ThreadsModel *RocketChatAccount::threadsModel() const { return mThreadsModel; } DiscussionsModel *RocketChatAccount::discussionsModel() const { return mDiscussionsModel; } FilesForRoomModel *RocketChatAccount::filesModelForRoom() const { return mFilesModelForRoom; } EmoticonModel *RocketChatAccount::emoticonModel() const { return mEmoticonModel; } ReceiveTypingNotificationManager *RocketChatAccount::receiveTypingNotificationManager() const { return mReceiveTypingNotificationManager; } void RocketChatAccount::slotChannelRolesDone(const QJsonObject &obj, const QString &roomId) { Room *room = mRoomModel->findRoom(roomId); if (room) { Roles r; r.parseRole(obj); room->setRolesForRooms(r); } else { qCWarning(RUQOLA_LOG) << " Impossible to find room " << roomId; } } void RocketChatAccount::slotGetThreadMessagesDone(const QJsonObject &obj, const QString &threadMessageId) { if (mThreadMessageModel->threadMessageId() != threadMessageId) { mThreadMessageModel->setThreadMessageId(threadMessageId); mThreadMessageModel->parseThreadMessages(obj); } else { mThreadMessageModel->loadMoreThreadMessages(obj); } } void RocketChatAccount::slotGetDiscussionsListDone(const QJsonObject &obj, const QString &roomId) { if (mDiscussionsModel->roomId() != roomId) { mDiscussionsModel->parseDiscussions(obj, roomId); } else { mDiscussionsModel->addMoreDiscussions(obj); } mDiscussionsModel->setLoadMoreDiscussionsInProgress(false); } void RocketChatAccount::slotGetListMessagesDone(const QJsonObject &obj, const QString &roomId, ListMessagesModel::ListMessageType type) { if (mListMessageModel->roomId() != roomId || mListMessageModel->listMessageType() != type) { mListMessageModel->setRoomId(roomId); mListMessageModel->setListMessageType(type); mListMessageModel->parseListMessages(obj); } else { mListMessageModel->loadMoreListMessages(obj); } mListMessageModel->setLoadMoreListMessagesInProgress(false); } void RocketChatAccount::slotUserAutoCompleterDone(const QJsonObject &obj) { const QVector users = User::parseUsersList(obj); mUserCompleterModel->insertUsers(users); } void RocketChatAccount::slotRoomsAutoCompleteChannelAndPrivateDone(const QJsonObject &obj) { //TODO } AccountRoomSettings *RocketChatAccount::accountRoomSettings() const { return mAccountRoomSettings; } ListMessagesModelFilterProxyModel *RocketChatAccount::listMessagesFilterProxyModel() const { return mListMessagesFilterProxyModel; } ListMessagesModel *RocketChatAccount::listMessageModel() const { return mListMessageModel; } void RocketChatAccount::slotGetThreadsListDone(const QJsonObject &obj, const QString &roomId) { if (mThreadsModel->roomId() != roomId) { mThreadsModel->parseThreads(obj, roomId); } else { mThreadsModel->addMoreThreads(obj); } mThreadsModel->setLoadMoreThreadsInProgress(false); } void RocketChatAccount::slotSplotLightDone(const QJsonObject &obj) { //qDebug() << " void RocketChatAccount::slotSplotLightDone(const QJsonObject &obj)"<roomId() != roomId) { mFilesModelForRoom->parseFileAttachments(obj, roomId); } else { mFilesModelForRoom->addMoreFileAttachments(obj); } mFilesModelForRoom->setLoadMoreFilesInProgress(false); } void RocketChatAccount::loadMoreUsersInRoom(const QString &roomId, const QString &channelType) { UsersForRoomModel *usersModelForRoom = roomModel()->usersModelForRoom(roomId); const int offset = usersModelForRoom->usersCount(); if (offset < usersModelForRoom->total()) { restApi()->membersInRoom(roomId, channelType, offset, qMin(50, usersModelForRoom->total() - offset)); } } void RocketChatAccount::getMentionsMessages(const QString &roomId) { mListMessageModel->clear(); mListMessageModel->setRoomId(roomId); restApi()->channelGetAllUserMentions(roomId); } void RocketChatAccount::getPinnedMessages(const QString &roomId) { if (hasPinnedMessagesSupport()) { mListMessageModel->clear(); mListMessageModel->setRoomId(roomId); restApi()->getPinnedMessages(roomId); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::getPinnedMessages is not supported before server 2.0.0"; } } bool RocketChatAccount::hasPinnedMessagesSupport() const { return mRuqolaServerConfig->hasAtLeastVersion(1, 4, 0); } bool RocketChatAccount::hasStarredMessagesSupport() const { return mRuqolaServerConfig->hasAtLeastVersion(2, 3, 0); } void RocketChatAccount::getStarredMessages(const QString &roomId) { if (hasStarredMessagesSupport()) { mListMessageModel->clear(); mListMessageModel->setRoomId(roomId); restApi()->getStarredMessages(roomId); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::getStarredMessages is not supported before server 2.3.0"; } } bool RocketChatAccount::hasSnippetedMessagesSupport() const { return mRuqolaServerConfig->hasAtLeastVersion(2, 3, 0); } void RocketChatAccount::getSnippetedMessages(const QString &roomId) { if (hasSnippetedMessagesSupport()) { mListMessageModel->clear(); mListMessageModel->setRoomId(roomId); restApi()->getSnippetedMessages(roomId); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::getSnippetedMessages is not supported before server 2.3.0"; } } void RocketChatAccount::loadMoreFileAttachments(const QString &roomId, const QString &channelType) { if (!mFilesModelForRoom->loadMoreFilesInProgress()) { const int offset = mFilesModelForRoom->fileAttachments()->filesCount(); if (offset < mFilesModelForRoom->fileAttachments()->total()) { mFilesModelForRoom->setLoadMoreFilesInProgress(true); restApi()->filesInRoom(roomId, channelType, offset, qMin(50, mFilesModelForRoom->fileAttachments()->total() - offset)); } } } void RocketChatAccount::loadMoreDiscussions(const QString &roomId) { if (!mDiscussionsModel->loadMoreDiscussionsInProgress()) { const int offset = mDiscussionsModel->discussions()->discussionsCount(); if (offset < mDiscussionsModel->discussions()->total()) { mDiscussionsModel->setLoadMoreDiscussionsInProgress(true); restApi()->getDiscussions(roomId, offset, qMin(50, mDiscussionsModel->discussions()->total() - offset)); } } } void RocketChatAccount::updateThreadMessageList(const Message &m) { if (mThreadMessageModel->threadMessageId() == m.threadMessageId()) { mThreadMessageModel->addMessage(m); } } void RocketChatAccount::loadMoreThreads(const QString &roomId) { if (!mThreadsModel->loadMoreThreadsInProgress()) { const int offset = mThreadsModel->threads()->threadsCount(); if (offset < mThreadsModel->threads()->total()) { restApi()->getThreadsList(roomId, offset, qMin(50, mThreadsModel->threads()->total() - offset)); } } } void RocketChatAccount::getListMessages(const QString &roomId, ListMessagesModel::ListMessageType type) { mListMessageModel->setListMessageType(type); switch (type) { case ListMessagesModel::Unknown: qCWarning(RUQOLA_LOG) << " Error when using getListMessages"; break; case ListMessagesModel::StarredMessages: if (hasStarredMessagesSupport()) { getStarredMessages(roomId); } break; case ListMessagesModel::SnipperedMessages: if (hasSnippetedMessagesSupport()) { getSnippetedMessages(roomId); } break; case ListMessagesModel::PinnedMessages: getPinnedMessages(roomId); break; case ListMessagesModel::MentionsMessages: getMentionsMessages(roomId); break; } } QUrl RocketChatAccount::urlForLink(const QString &link) const { return mCache->urlForLink(link); } void RocketChatAccount::loadMoreListMessages(const QString &roomId) { if (!mListMessageModel->loadMoreListMessagesInProgress()) { const int offset = mListMessageModel->rowCount(); if (offset < mListMessageModel->total()) { switch (mListMessageModel->listMessageType()) { case ListMessagesModel::Unknown: qCWarning(RUQOLA_LOG) << " Error when using loadMoreListMessages"; break; case ListMessagesModel::StarredMessages: if (hasStarredMessagesSupport()) { restApi()->getStarredMessages(roomId, offset, qMin(50, mListMessageModel->total() - offset)); } break; case ListMessagesModel::SnipperedMessages: if (hasSnippetedMessagesSupport()) { restApi()->getSnippetedMessages(roomId, offset, qMin(50, mListMessageModel->total() - offset)); } break; case ListMessagesModel::PinnedMessages: restApi()->getPinnedMessages(roomId, offset, qMin(50, mListMessageModel->total() - offset)); break; case ListMessagesModel::MentionsMessages: restApi()->channelGetAllUserMentions(roomId, offset, qMin(50, mListMessageModel->total() - offset)); break; } } } } void RocketChatAccount::loadThreadMessagesHistory(const QString &threadMessageId) { restApi()->getThreadMessages(threadMessageId); } void RocketChatAccount::createJitsiConfCall(const QString &roomId) { //TODO use restapi ddp()->createJitsiConfCall(roomId); joinJitsiConfCall(roomId); } void RocketChatAccount::addUserToRoom(const QString &userId, const QString &roomId, const QString &channelType) { if (channelType == QLatin1Char('c')) { restApi()->addUserInChannel(roomId, userId); } else if (channelType == QLatin1Char('p')) { restApi()->addUserInGroup(roomId, userId); } } void RocketChatAccount::clearSearchModel() { mSearchMessageModel->clear(); } void RocketChatAccount::messageSearch(const QString &pattern, const QString &rid) { if (pattern.isEmpty()) { clearSearchModel(); } else { restApi()->searchMessages(rid, pattern); } } void RocketChatAccount::slotSearchMessages(const QJsonObject &obj) { mSearchMessageModel->parse(obj); } void RocketChatAccount::starMessage(const QString &messageId, bool starred) { restApi()->starMessage(messageId, starred); } void RocketChatAccount::pinMessage(const QString &messageId, bool pinned) { restApi()->pinMessage(messageId, pinned); } void RocketChatAccount::uploadFile(const QString &roomId, const QString &description, const QString &messageText, const QUrl &fileUrl) { restApi()->uploadFile(roomId, description, messageText, fileUrl); } void RocketChatAccount::changeChannelSettings(const QString &roomId, RocketChatAccount::RoomInfoType infoType, const QVariant &newValue, const QString &channelType) { switch (infoType) { case Announcement: if (channelType == QLatin1Char('c')) { restApi()->changeChannelAnnouncement(roomId, newValue.toString()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupsAnnouncement(roomId, newValue.toString()); } else { qCWarning(RUQOLA_LOG) << " unsupport change announcement for type " << channelType; } break; case Description: if (channelType == QLatin1Char('c')) { restApi()->changeChannelDescription(roomId, newValue.toString()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupsDescription(roomId, newValue.toString()); } else { qCWarning(RUQOLA_LOG) << " unsupport change description for type " << channelType; } break; case Name: if (channelType == QLatin1Char('c')) { restApi()->changeChannelName(roomId, newValue.toString()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupName(roomId, newValue.toString()); } else { qCWarning(RUQOLA_LOG) << " unsupport change name for type " << channelType; } break; case Topic: if (channelType == QLatin1Char('c')) { restApi()->changeChannelTopic(roomId, newValue.toString()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupsTopic(roomId, newValue.toString()); } else { //TODO : change topic in direct channel qCWarning(RUQOLA_LOG) << " unsupport change topic for type " << channelType; } break; case ReadOnly: if (channelType == QLatin1Char('c')) { restApi()->changeChannelReadOnly(roomId, newValue.toBool()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupsReadOnly(roomId, newValue.toBool()); } else { qCWarning(RUQOLA_LOG) << " unsupport change readonly for type " << channelType; } break; case Archive: if (channelType == QLatin1Char('c')) { restApi()->archiveChannel(roomId, newValue.toBool()); } else if (channelType == QLatin1Char('p')) { restApi()->archiveGroups(roomId, newValue.toBool()); } else { qCWarning(RUQOLA_LOG) << " unsupport archiving for type " << channelType; } break; case RoomType: if (channelType == QLatin1Char('c')) { restApi()->setChannelType(roomId, newValue.toBool()); } else if (channelType == QLatin1Char('p')) { restApi()->setGroupType(roomId, newValue.toBool()); } else { qCWarning(RUQOLA_LOG) << " unsupport roomtype for type " << channelType; } break; case Encrypted: if (channelType == QLatin1Char('c')) { restApi()->changeChannelEncrypted(roomId, newValue.toBool()); } else if (channelType == QLatin1Char('p')) { restApi()->changeGroupsEncrypted(roomId, newValue.toBool()); } else { qCWarning(RUQOLA_LOG) << " unsupport encrypted mode for type " << channelType; } break; case Password: //FIXME channel type ??? //restApi()->setJoinCodeChannel(roomId, newValue.toString()); break; } } void RocketChatAccount::reportMessage(const QString &messageId, const QString &message) { restApi()->reportMessage(messageId, message); } void RocketChatAccount::getThreadMessages(const QString &threadMessageId) { mThreadMessageModel->clear(); restApi()->getThreadMessages(threadMessageId); } void RocketChatAccount::changeNotificationsSettings(const QString &roomId, RocketChatAccount::NotificationOptionsType notificationsType, const QVariant &newValue) { switch (notificationsType) { case DisableNotifications: restApi()->disableNotifications(roomId, newValue.toBool()); break; case HideUnreadStatus: restApi()->hideUnreadStatus(roomId, newValue.toBool()); break; case AudioNotifications: restApi()->audioNotifications(roomId, newValue.toString()); break; case DesktopNotifications: restApi()->desktopNotifications(roomId, newValue.toString()); break; case EmailNotifications: restApi()->emailNotifications(roomId, newValue.toString()); break; case MobilePushNotifications: restApi()->mobilePushNotifications(roomId, newValue.toString()); break; case UnreadAlert: restApi()->unreadAlert(roomId, newValue.toString()); break; case MuteGroupMentions: restApi()->muteGroupMentions(roomId, newValue.toBool()); break; case DesktopDurationNotifications: restApi()->desktopDurationNotifications(roomId, newValue.toInt()); break; case DesktopSoundNotifications: restApi()->desktopSoundNotifications(roomId, newValue.toString()); break; } } void RocketChatAccount::parsePublicSettings(const QJsonObject &obj) { QJsonArray configs = obj.value(QLatin1String("result")).toArray(); for (QJsonValueRef currentConfig : configs) { QJsonObject currentConfObject = currentConfig.toObject(); const QString id = currentConfObject[QStringLiteral("_id")].toString(); const QVariant value = currentConfObject[QStringLiteral("value")].toVariant(); if (id == QLatin1String("uniqueID")) { mRuqolaServerConfig->setUniqueId(value.toString()); } else if (id == QLatin1String("Jitsi_Enabled")) { mRuqolaServerConfig->setJitsiEnabled(value.toBool()); } else if (id == QLatin1String("Jitsi_Domain")) { mRuqolaServerConfig->setJitsiMeetUrl(value.toString()); } else if (id == QLatin1String("Jitsi_URL_Room_Prefix")) { mRuqolaServerConfig->setJitsiMeetPrefix(value.toString()); } else if (id == QLatin1String("FileUpload_Storage_Type")) { mRuqolaServerConfig->setFileUploadStorageType(value.toString()); } else if (id == QLatin1String("Message_AllowEditing")) { mRuqolaServerConfig->setAllowMessageEditing(value.toBool()); } else if (id == QLatin1String("Message_AllowEditing_BlockEditInMinutes")) { mRuqolaServerConfig->setBlockEditingMessageInMinutes(value.toInt()); } else if (id == QLatin1String("OTR_Enable")) { mRuqolaServerConfig->setOtrEnabled(value.toBool()); } else if (id.contains(QRegularExpression(QStringLiteral("^Accounts_OAuth_\\w+")))) { if (value.toBool()) { mRuqolaServerConfig->addOauthService(id); } } else if (id == QLatin1String("Site_Url")) { mRuqolaServerConfig->setSiteUrl(value.toString()); } else if (id == QLatin1String("Site_Name")) { mRuqolaServerConfig->setSiteName(value.toString()); } else if (id == QLatin1String("E2E_Enable")) { mRuqolaServerConfig->setEncryptionEnabled(value.toBool()); } else if (id == QLatin1String("Message_AllowPinning")) { mRuqolaServerConfig->setAllowMessagePinningEnabled(value.toBool()); } else if (id == QLatin1String("Message_AllowSnippeting")) { mRuqolaServerConfig->setAllowMessageSnippetingEnabled(value.toBool()); } else if (id == QLatin1String("Message_AllowStarring")) { mRuqolaServerConfig->setAllowMessageStarringEnabled(value.toBool()); } else if (id == QLatin1String("Message_AllowDeleting")) { mRuqolaServerConfig->setAllowMessageDeletingEnabled(value.toBool()); } else if (id == QLatin1String("Threads_enabled")) { mRuqolaServerConfig->setThreadsEnabled(value.toBool()); } else if (id == QLatin1String("Discussion_enabled")) { mRuqolaServerConfig->setDiscussionEnabled(value.toBool()); } else if (id == QLatin1String("AutoTranslate_Enabled")) { mRuqolaServerConfig->setAutoTranslateEnabled(value.toBool()); } else if (id == QLatin1String("AutoTranslate_GoogleAPIKey")) { mRuqolaServerConfig->setAutoTranslateGoogleKey(value.toString()); } else { qCDebug(RUQOLA_LOG) << "Other public settings id " << id << value; } //TODO add Accounts_AllowUserStatusMessageChange when we will have a RestAPI method for it. } fillOauthModel(); Q_EMIT publicSettingChanged(); } void RocketChatAccount::fillOauthModel() { QVector fillModel; for (int i = 0, total = mLstInfos.count(); i < total; ++i) { if (mRuqolaServerConfig->canShowOauthService(mLstInfos.at(i).oauthType())) { fillModel.append(mLstInfos.at(i)); } } mLoginMethodModel->setAuthenticationInfos(fillModel); } void RocketChatAccount::changeDefaultAuthentication(int index) { setDefaultAuthentication(mLoginMethodModel->loginType(index)); } void RocketChatAccount::setDefaultAuthentication(AuthenticationManager::OauthType type) { PluginAuthenticationInterface *interface = mLstPluginAuthenticationInterface.value(type); if (interface) { mDefaultAuthenticationInterface = interface; } else { qCWarning(RUQOLA_LOG) << "No interface defined for " << type; } } SearchMessageFilterProxyModel *RocketChatAccount::searchMessageFilterProxyModel() const { return mSearchMessageFilterProxyModel; } SearchMessageModel *RocketChatAccount::searchMessageModel() const { return mSearchMessageModel; } void RocketChatAccount::initializeAuthenticationPlugins() { //TODO change it when we change server //Clean up at the end. const QVector lstPlugins = AuthenticationManager::self()->pluginsList(); qCDebug(RUQOLA_LOG) <<" void RocketChatAccount::initializeAuthenticationPlugins()" << lstPlugins.count(); if (lstPlugins.isEmpty()) { qCWarning(RUQOLA_LOG) <<" No plugins loaded. Please verify your installation."; } mLstPluginAuthenticationInterface.clear(); mLstInfos.clear(); for (PluginAuthentication *abstractPlugin : lstPlugins) { AuthenticationInfo info; info.setIconName(abstractPlugin->iconName()); info.setName(abstractPlugin->name()); info.setOauthType(abstractPlugin->type()); if (info.isValid()) { mLstInfos.append(info); } PluginAuthenticationInterface *interface = abstractPlugin->createInterface(this); interface->setAccount(this); mRuqolaServerConfig->addRuqolaAuthenticationSupport(abstractPlugin->type()); mLstPluginAuthenticationInterface.insert(abstractPlugin->type(), interface); //For the moment initialize default interface if (abstractPlugin->type() == AuthenticationManager::OauthType::Password) { mDefaultAuthenticationInterface = interface; } qCDebug(RUQOLA_LOG) << " plugin type " << abstractPlugin->type(); } //TODO fill ??? or store QVector } PluginAuthenticationInterface *RocketChatAccount::defaultAuthenticationInterface() const { return mDefaultAuthenticationInterface; } LoginMethodModel *RocketChatAccount::loginMethodModel() const { return mLoginMethodModel; } QString RocketChatAccount::authToken() const { return settings()->authToken(); } QString RocketChatAccount::userName() const { return settings()->userName(); } void RocketChatAccount::setAccountName(const QString &accountname) { //Initialize new account room ManagerDataPaths::self()->initializeAccountPath(accountname); //qDebug() << "void RocketChatAccount::setAccountName(const QString &servername)"<accountConfigFileName(accountname)); settings()->setAccountName(accountname); } QString RocketChatAccount::accountName() const { return settings()->accountName(); } QString RocketChatAccount::userID() const { return settings()->userId(); } QString RocketChatAccount::password() const { return settings()->password(); } QString RocketChatAccount::twoFactorAuthenticationCode() const { return settings()->twoFactorAuthenticationCode(); } void RocketChatAccount::setAuthToken(const QString &token) { settings()->setAuthToken(token); } void RocketChatAccount::setPassword(const QString &password) { settings()->setPassword(password); } void RocketChatAccount::setTwoFactorAuthenticationCode(const QString &twoFactorAuthenticationCode) { settings()->setTwoFactorAuthenticationCode(twoFactorAuthenticationCode); } void RocketChatAccount::setAccountEnabled(bool enabled) { settings()->setAccountEnabled(enabled); } void RocketChatAccount::setUserName(const QString &username) { settings()->setUserName(username); } bool RocketChatAccount::accountEnabled() const { return settings()->accountEnabled(); } void RocketChatAccount::setUserID(const QString &userID) { settings()->setUserId(userID); } QString RocketChatAccount::serverUrl() const { return settings()->serverUrl(); } void RocketChatAccount::setServerUrl(const QString &serverURL) { settings()->setServerUrl(serverURL); restApi()->setServerUrl(serverURL); mEmojiManager->setServerUrl(serverURL); } QString RocketChatAccount::recordingVideoPath() const { return mCache->recordingVideoPath(accountName()); } QString RocketChatAccount::recordingImagePath() const { return mCache->recordingImagePath(accountName()); } void RocketChatAccount::downloadFile(const QString &downloadFileUrl, const QUrl &localFile) { mCache->downloadFile(downloadFileUrl, localFile, false); } QUrl RocketChatAccount::attachmentUrl(const QString &url) { return mCache->attachmentUrl(url); } void RocketChatAccount::loadHistory(const QString &roomID, const QString &channelType, bool initial) { //TODO port to restapi Q_UNUSED(channelType); MessageModel *roomModel = messageModelForRoom(roomID); if (roomModel) { //TODO add autotest for it ! QJsonArray params; params.append(QJsonValue(roomID)); // Load history const qint64 endDateTime = roomModel->lastTimestamp(); if (initial || roomModel->isEmpty()) { params.append(QJsonValue(QJsonValue::Null)); params.append(QJsonValue(50)); // Max number of messages to load; QJsonObject dateObject; //qDebug() << "roomModel->lastTimestamp()" << roomModel->lastTimestamp() << " ROOMID " << roomID; dateObject[QStringLiteral("$date")] = QJsonValue(endDateTime); params.append(dateObject); } else { const qint64 startDateTime = roomModel->generateNewStartTimeStamp(endDateTime); QJsonObject dateObjectEnd; dateObjectEnd[QStringLiteral("$date")] = QJsonValue(endDateTime); //qDebug() << " QDATE TIME END" << QDateTime::fromMSecsSinceEpoch(endDateTime) << " START " << QDateTime::fromMSecsSinceEpoch(startDateTime) << " ROOMID" << roomID; params.append(dateObjectEnd); params.append(QJsonValue(50)); // Max number of messages to load; QJsonObject dateObjectStart; //qDebug() << "roomModel->lastTimestamp()" << roomModel->lastTimestamp() << " ROOMID " << roomID; dateObjectStart[QStringLiteral("$date")] = QJsonValue(startDateTime); params.append(dateObjectStart); } ddp()->loadHistory(params); } else { qCWarning(RUQOLA_LOG) << "Room is not found " << roomID; } } void RocketChatAccount::setServerVersion(const QString &version) { qCDebug(RUQOLA_LOG) << " void RocketChatAccount::setServerVersion(const QString &version)" << version; mRuqolaServerConfig->setServerVersion(version); Q_EMIT serverVersionChanged(); } bool RocketChatAccount::needAdaptNewSubscriptionRC60() const { return mRuqolaServerConfig->needAdaptNewSubscriptionRC60(); } bool RocketChatAccount::otrEnabled() const { return mRuqolaServerConfig->otrEnabled(); } bool RocketChatAccount::encryptedEnabled() const { return mRuqolaServerConfig->encryptionEnabled(); } bool RocketChatAccount::allowMessagePinningEnabled() const { return mRuqolaServerConfig->allowMessagePinningEnabled(); } bool RocketChatAccount::allowMessageSnippetingEnabled() const { return mRuqolaServerConfig->allowMessageSnippetingEnabled(); } bool RocketChatAccount::allowMessageStarringEnabled() const { return mRuqolaServerConfig->allowMessageStarringEnabled(); } bool RocketChatAccount::allowMessageDeletingEnabled() const { return mRuqolaServerConfig->allowMessageDeletingEnabled(); } bool RocketChatAccount::threadsEnabled() const { return mRuqolaServerConfig->threadsEnabled(); } bool RocketChatAccount::autoTranslateEnabled() const { return mRuqolaServerConfig->autoTranslateEnabled(); } bool RocketChatAccount::discussionEnabled() const { return mRuqolaServerConfig->discussionEnabled(); } QString RocketChatAccount::serverVersionStr() const { return mRuqolaServerConfig->serverVersionStr(); } ServerConfigInfo *RocketChatAccount::serverConfigInfo() const { return mServerConfigInfo; } bool RocketChatAccount::jitsiEnabled() const { return mRuqolaServerConfig->jitsiEnabled(); } void RocketChatAccount::groupInfo(const QString &roomId) { restApi()->groupInfo(roomId); } void RocketChatAccount::switchEditingMode(bool b) { if (mEditingMode != b) { mEditingMode = b; Q_EMIT editingModeChanged(); } } void RocketChatAccount::setSortUnreadOnTop(bool b) { if (settings()->setShowUnreadOnTop(b)) { mRoomFilterProxyModel->invalidate(); Q_EMIT sortUnreadOnTopChanged(); } } bool RocketChatAccount::sortUnreadOnTop() const { return settings()->showUnreadOnTop(); } void RocketChatAccount::kickUser(const QString &roomId, const QString &userId, const QString &channelType) { if (channelType == QLatin1Char('c')) { restApi()->channelKick(roomId, userId); } else if (channelType == QLatin1Char('p')) { restApi()->groupKick(roomId, userId); } else { qCWarning(RUQOLA_LOG) << " unsupport kickUser room for type " << channelType; } } void RocketChatAccount::rolesInRoom(const QString &roomId, const QString &channelType) { if (channelType == QLatin1Char('c')) { restApi()->getChannelRoles(roomId); } else if (channelType == QLatin1Char('p')) { restApi()->getGroupRoles(roomId); } else if (channelType == QLatin1Char('d')) { //No a problem here. } else { qCWarning(RUQOLA_LOG) << " unsupport get roles room for type " << channelType; } } void RocketChatAccount::switchingToRoom(const QString &roomID) { clearTypingNotification(); checkInitializedRoom(roomID); } void RocketChatAccount::changeRoles(const QString &roomId, const QString &userId, const QString &channelType, RocketChatAccount::RoleType roleType) { if (channelType == QLatin1Char('c')) { switch (roleType) { case RocketChatAccount::AddOwner: restApi()->channelAddOwner(roomId, userId); break; case RocketChatAccount::AddLeader: restApi()->channelAddLeader(roomId, userId); break; case RocketChatAccount::AddModerator: restApi()->channelAddModerator(roomId, userId); break; case RocketChatAccount::RemoveOwner: restApi()->channelRemoveOwner(roomId, userId); break; case RocketChatAccount::RemoveLeader: restApi()->channelRemoveLeader(roomId, userId); break; case RocketChatAccount::RemoveModerator: restApi()->channelRemoveModerator(roomId, userId); break; } } else if (channelType == QLatin1Char('p')) { switch (roleType) { case RocketChatAccount::AddOwner: restApi()->groupAddOwner(roomId, userId); break; case RocketChatAccount::AddLeader: restApi()->groupAddLeader(roomId, userId); break; case RocketChatAccount::AddModerator: restApi()->groupAddModerator(roomId, userId); break; case RocketChatAccount::RemoveOwner: restApi()->groupRemoveOwner(roomId, userId); break; case RocketChatAccount::RemoveLeader: restApi()->groupRemoveLeader(roomId, userId); break; case RocketChatAccount::RemoveModerator: restApi()->groupRemoveModerator(roomId, userId); break; } } else { qCWarning(RUQOLA_LOG) << " unsupport changeRoles room for type " << channelType; } } void RocketChatAccount::channelInfo(const QString &roomId) { restApi()->channelInfo(roomId); } bool RocketChatAccount::allowEditingMessages() const { return mRuqolaServerConfig->allowMessageEditing(); } void RocketChatAccount::parseOtr(const QJsonArray &contents) { qCWarning(RUQOLA_LOG) << " NOT IMPLEMENTED YET"; //const Otr t = mOtrManager->parseOtr(contents); //qDebug() << " void RocketChatAccount::parseOtr(const QJsonArray &contents)"<avatarUrlFromCacheOnly(sender); //qDebug() << " iconFileName"<inputChannelAutocomplete(pattern, exceptions); break; case InputTextManager::CompletionForType::User: ddp()->inputUserAutocomplete(pattern, exceptions); break; } } void RocketChatAccount::inputThreadMessageAutocomplete(const QString &pattern, const QString &exceptions, InputTextManager::CompletionForType type) { //qDebug() << " void RocketChatAccount::inputThreadMessageAutocomplete(const QString &pattern, const QString &exceptions, InputTextManager::CompletionForType type)" << pattern; switch (type) { case InputTextManager::CompletionForType::Channel: ddp()->inputChannelAutocomplete(pattern, exceptions); break; case InputTextManager::CompletionForType::User: ddp()->inputUserAutocomplete(pattern, exceptions); break; } } AutotranslateLanguagesModel *RocketChatAccount::autoTranslateLanguagesModel() const { return mAutoTranslateLanguagesModel; } void RocketChatAccount::updateUser(const QJsonObject &object) { mUserModel->updateUser(object); } void RocketChatAccount::userStatusChanged(User *user) { if (user->userId() == userID()) { const User::PresenceStatus status = Utils::presenceStatusFromString(user->status()); statusModel()->setCurrentPresenceStatus(status); Q_EMIT userStatusUpdated(status); } mRoomModel->userStatusChanged(user); } void RocketChatAccount::ignoreUser(const QString &rid, const QString &userId, bool ignore) { restApi()->ignoreUser(rid, userId, ignore); } void RocketChatAccount::blockUser(const QString &rid, bool block) { //TODO use restapi if (rid.isEmpty()) { qCWarning(RUQOLA_LOG) << " void RocketChatAccount::blockUser EMPTY rid ! block " << block; } else { //qDebug() << " void RocketChatAccount::blockUser userId " << userId << " block " << block << " rid " << rid << " own userdId" << userID(); const QString userId = Utils::userIdFromDirectChannel(rid, userID()); if (block) { ddp()->blockUser(rid, userId); } else { ddp()->unBlockUser(rid, userId); } } } void RocketChatAccount::clearTypingNotification() { mReceiveTypingNotificationManager->clearTypingNotification(); } void RocketChatAccount::checkInitializedRoom(const QString &roomId) { Room *r = mRoomModel->findRoom(roomId); if (r && !r->wasInitialized()) { r->setWasInitialized(true); ddp()->subscribeRoomMessage(roomId); if (!r->archived()) { membersInRoom(r->roomId(), r->channelType()); rolesInRoom(r->roomId(), r->channelType()); } loadHistory(r->roomId(), QString(), true /*initial loading*/); } else if (!r) { qWarning() << " Room " << roomId << " was no found! Need to open it"; //openDirectChannel(roomId); } QMetaObject::invokeMethod(this, &RocketChatAccount::switchedRooms, Qt::QueuedConnection); } void RocketChatAccount::openDocumentation() { QDesktopServices::openUrl(QUrl(QStringLiteral("help:/"))); } void RocketChatAccount::rolesChanged(const QJsonArray &contents) { for (int i = 0; i < contents.count(); ++i) { const QJsonObject obj = contents.at(i).toObject(); const QString scope = obj[QLatin1String("scope")].toString(); Room *room = mRoomModel->findRoom(scope); if (room) { room->updateRoles(obj); } } } void RocketChatAccount::createDiscussion(const QString &parentRoomId, const QString &discussionName, const QString &replyMessage, const QString &messageId, const QStringList &users) { restApi()->createDiscussion(parentRoomId, discussionName, replyMessage, messageId, users); } void RocketChatAccount::threadsInRoom(const QString &roomId) { mThreadsModel->initialize(); restApi()->getThreadsList(roomId); } void RocketChatAccount::discussionsInRoom(const QString &roomId) { mDiscussionsModel->initialize(); restApi()->getDiscussions(roomId); } void RocketChatAccount::followMessage(const QString &messageId, bool follow) { if (follow) { restApi()->followMessage(messageId); } else { restApi()->unFollowMessage(messageId); } } void RocketChatAccount::getSupportedLanguages() { if (mRuqolaServerConfig->hasAtLeastVersion(1, 99, 0) && autoTranslateEnabled()) { restApi()->getSupportedLanguagesMessages(); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::getSupportedLanguages is not supported before server 2.0.0"; } } void RocketChatAccount::slotGetSupportedLanguagesDone(const QJsonObject &obj) { mAutoTranslateLanguagesModel->parseLanguages(obj); } void RocketChatAccount::autoTranslateSaveLanguageSettings(const QString &roomId, const QString &language) { if (mRuqolaServerConfig->hasAtLeastVersion(1, 99, 0)) { restApi()->autoTranslateSaveLanguageSettings(roomId, language); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::autoTranslateSaveLanguageSettings is not supported before server 2.0.0"; } } void RocketChatAccount::autoTranslateSaveAutoTranslateSettings(const QString &roomId, bool autoTranslate) { if (mRuqolaServerConfig->hasAtLeastVersion(1, 99, 0)) { restApi()->autoTranslateSaveAutoTranslateSettings(roomId, autoTranslate); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::autoTranslateSaveLanguageSettings is not supported before server 2.0.0"; } } void RocketChatAccount::slotUsersPresenceDone(const QJsonObject &obj) { qDebug() << " void RocketChatAccount::slotUsersPresenceDone(const QJsonObject &obj)" << obj; } void RocketChatAccount::slotDisconnectedByServer() { //Laurent: disable it for the moment otherwise when we logout we are unable to add password in login page. Need to improve it first :) return; // This happens when we didn't react to pings for a while // (e.g. while stopped in gdb, or if network went down for a bit) // Let's try connecting in again // TODO: delay this more and more like RC+ ? QTimer::singleShot(100, this, [this]() { qCDebug(RUQOLA_LOG) << "Attempting to reconnect after the server disconnected us"; // Do the parts of logOut() that don't actually try talking to the server mRoomModel->clear(); delete mDdp; mDdp = nullptr; tryLogin(); }); } void RocketChatAccount::usersPresence() { restApi()->usersPresence(); } void RocketChatAccount::customUsersStatus() { if (mRuqolaServerConfig->hasAtLeastVersion(2, 4, 0)) { restApi()->customUserStatus(); } else { qCWarning(RUQOLA_LOG) << " RocketChatAccount::customUserStatus is not supported before server 2.4.0"; } } void RocketChatAccount::initializeAccount() { listEmojiCustom(); //load when necessary //account->usersPresence(); if (mRuqolaServerConfig->autoTranslateEnabled()) { getSupportedLanguages(); } //Force set online. //TODO don't reset message status ! ddp()->setDefaultStatus(User::PresenceStatus::PresenceOnline); //customUsersStatus(); Only for test } diff --git a/src/core/rocketchatbackend.h b/src/core/rocketchatbackend.h index 4c7f0054..a19ddfd2 100644 --- a/src/core/rocketchatbackend.h +++ b/src/core/rocketchatbackend.h @@ -1,73 +1,72 @@ /* * Copyright 2016 Riccardo Iaconelli * Copyright 2018-2020 Laurent Montel * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef ROCKETCHATBACKEND_H #define ROCKETCHATBACKEND_H #include "file.h" #include "libruqolacore_export.h" #include #include -#include #include "user.h" #include "model/roommodel.h" class RocketChatAccount; class LIBRUQOLACORE_EXPORT RocketChatBackend : public QObject { Q_OBJECT public: explicit RocketChatBackend(RocketChatAccount *account, QObject *parent = nullptr); ~RocketChatBackend() override; /** * @brief Adds incoming message from server to appropriate room * * @param messages The Json containing the message */ void processIncomingMessages(const QJsonArray &messages); void clearUsersList(); Q_REQUIRED_RESULT QVector users() const; void clearFilesList(); Q_REQUIRED_RESULT QVector files() const; private: Q_DISABLE_COPY(RocketChatBackend) void slotRemoved(const QJsonObject &object); void slotAdded(const QJsonObject &object); void slotChanged(const QJsonObject &object); void slotLoginStatusChanged(); void slotConnectedChanged(); void slotUserIDChanged(); void slotGetServerInfoFailed(bool useDeprecatedVersion); void parseOwnInfoDown(const QJsonObject &replyObject); void parseServerVersionDone(const QString &version); QVector mUsers; QVector mFiles; RocketChatAccount *mRocketChatAccount = nullptr; }; #endif // ROCKETCHATBACKEND_H diff --git a/src/core/ruqolaregisterengine.h b/src/core/ruqolaregisterengine.h index bc6a374d..b4b3725c 100644 --- a/src/core/ruqolaregisterengine.h +++ b/src/core/ruqolaregisterengine.h @@ -1,37 +1,36 @@ /* Copyright (c) 2017-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef RUQOLAREGISTERENGINE_H #define RUQOLAREGISTERENGINE_H #include "libruqolacore_export.h" -#include class QQmlApplicationEngine; class LIBRUQOLACORE_EXPORT RuqolaRegisterEngine { public: RuqolaRegisterEngine(); ~RuqolaRegisterEngine(); Q_REQUIRED_RESULT bool initialize(); private: QQmlApplicationEngine *mEngine = nullptr; }; #endif // RUQOLAREGISTERENGINE_H diff --git a/src/core/textconverter.h b/src/core/textconverter.h index 87144357..4ecb5c85 100644 --- a/src/core/textconverter.h +++ b/src/core/textconverter.h @@ -1,42 +1,41 @@ /* Copyright (c) 2018-2020 Laurent Montel This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef TEXTCONVERTER_H #define TEXTCONVERTER_H #include -#include #include #include "libruqola_private_export.h" class EmojiManager; class Message; class LIBRUQOLACORE_TESTS_EXPORT TextConverter { public: explicit TextConverter(EmojiManager *emojiManager = nullptr); ~TextConverter() = default; Q_REQUIRED_RESULT QString convertMessageText(const QString &str, const QString &userName, const QVector &allMessages) const; private: EmojiManager *mEmojiManager = nullptr; }; #endif // TEXTCONVERTER_H diff --git a/src/core/user.h b/src/core/user.h index 14fb3ec5..2f4865af 100644 --- a/src/core/user.h +++ b/src/core/user.h @@ -1,84 +1,83 @@ /* Copyright (c) 2017-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef USER_H #define USER_H #include #include -#include #include "libruqolacore_export.h" class LIBRUQOLACORE_EXPORT User { Q_GADGET public: enum class PresenceStatus { PresenceOnline, PresenceBusy, PresenceAway, PresenceOffline, Unknown }; Q_ENUM(PresenceStatus) User(); ~User(); Q_REQUIRED_RESULT QString name() const; void setName(const QString &name); Q_REQUIRED_RESULT QString userId() const; void setUserId(const QString &userId); Q_REQUIRED_RESULT QString status() const; void setStatus(const QString &status); void parseUser(const QJsonObject &json); Q_REQUIRED_RESULT Q_INVOKABLE QString iconFromStatus() const; Q_REQUIRED_RESULT bool operator ==(const User &other) const; Q_REQUIRED_RESULT bool operator !=(const User &other) const; Q_REQUIRED_RESULT QString userName() const; void setUserName(const QString &userName); Q_REQUIRED_RESULT bool isValid() const; Q_REQUIRED_RESULT double utcOffset() const; void setUtcOffset(double utcOffset); Q_REQUIRED_RESULT QString statusText() const; void setStatusText(const QString &statusText); void parseUserRestApi(const QJsonObject &object); static Q_REQUIRED_RESULT QVector parseUsersList(const QJsonObject &object); private: QString mStatus = QStringLiteral("offline"); QString mUserId; QString mName; QString mUserName; QString mStatusText; double mUtcOffset = 0.0; }; LIBRUQOLACORE_EXPORT QDebug operator <<(QDebug d, const User &t); #endif // USER_H diff --git a/src/rocketchatrestapi-qt5/autotests/usersautocompletejobtest.cpp b/src/rocketchatrestapi-qt5/autotests/usersautocompletejobtest.cpp index d21d1419..d807e995 100644 --- a/src/rocketchatrestapi-qt5/autotests/usersautocompletejobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/usersautocompletejobtest.cpp @@ -1,56 +1,55 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "usersautocompletejobtest.h" #include "users/usersautocompletejob.h" #include "ruqola_restapi_helper.h" #include -#include #include QTEST_GUILESS_MAIN(UsersAutocompleteJobTest) using namespace RocketChatRestApi; UsersAutocompleteJobTest::UsersAutocompleteJobTest(QObject *parent) : QObject(parent) { } void UsersAutocompleteJobTest::shouldHaveDefaultValue() { UsersAutocompleteJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(!job.hasQueryParameterSupport()); UsersAutocompleteJob::UsersAutocompleterInfo info; QVERIFY(!info.isValid()); QVERIFY(info.pattern.isEmpty()); QVERIFY(info.exception.isEmpty()); } void UsersAutocompleteJobTest::shouldGenerateRequest() { UsersAutocompleteJob job; UsersAutocompleteJob::UsersAutocompleterInfo info; info.pattern = QStringLiteral("foo"); job.setUsersCompleterInfo(info); QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url().toString(), QStringLiteral("http://www.kde.org/api/v1/users.autocomplete?selector=%7B%22term%22: %22foo%22%7D")); } diff --git a/src/rocketchatrestapi-qt5/autotests/usersinfojobtest.cpp b/src/rocketchatrestapi-qt5/autotests/usersinfojobtest.cpp index 0f637a1f..bef7e2f7 100644 --- a/src/rocketchatrestapi-qt5/autotests/usersinfojobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/usersinfojobtest.cpp @@ -1,63 +1,62 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "usersinfojobtest.h" #include "users/usersinfojob.h" #include "ruqola_restapi_helper.h" #include -#include #include QTEST_GUILESS_MAIN(UsersInfoJobTest) using namespace RocketChatRestApi; UsersInfoJobTest::UsersInfoJobTest(QObject *parent) : QObject(parent) { } void UsersInfoJobTest::shouldHaveDefaultValue() { UsersInfoJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(job.identifier().isEmpty()); QVERIFY(!job.useUserName()); QVERIFY(!job.hasQueryParameterSupport()); } void UsersInfoJobTest::shouldGenerateRequest() { UsersInfoJob job; const QString roomId = QStringLiteral("foo1"); job.setIdentifier(roomId); QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/users.info?userId=foo1"))); } void UsersInfoJobTest::shouldGenerateRequestUsername() { UsersInfoJob job; const QString roomId = QStringLiteral("foo1"); job.setIdentifier(roomId); job.setUseUserName(true); QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/users.info?username=foo1"))); } diff --git a/src/rocketchatrestapi-qt5/autotests/userspresencejobtest.cpp b/src/rocketchatrestapi-qt5/autotests/userspresencejobtest.cpp index 73338465..c30d4784 100644 --- a/src/rocketchatrestapi-qt5/autotests/userspresencejobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/userspresencejobtest.cpp @@ -1,48 +1,47 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "userspresencejobtest.h" #include "users/userspresencejob.h" #include "ruqola_restapi_helper.h" #include -#include #include QTEST_GUILESS_MAIN(UsersPresenceJobTest) using namespace RocketChatRestApi; UsersPresenceJobTest::UsersPresenceJobTest(QObject *parent) : QObject(parent) { } void UsersPresenceJobTest::shouldHaveDefaultValue() { UsersPresenceJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(!job.hasQueryParameterSupport()); } void UsersPresenceJobTest::shouldGenerateRequest() { UsersPresenceJob job; QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/users.presence"))); } diff --git a/src/rocketchatrestapi-qt5/autotranslate/getsupportedlanguagesjob.cpp b/src/rocketchatrestapi-qt5/autotranslate/getsupportedlanguagesjob.cpp index 6c26da19..15690b76 100644 --- a/src/rocketchatrestapi-qt5/autotranslate/getsupportedlanguagesjob.cpp +++ b/src/rocketchatrestapi-qt5/autotranslate/getsupportedlanguagesjob.cpp @@ -1,92 +1,91 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "getsupportedlanguagesjob.h" #include "restapimethod.h" #include "rocketchatqtrestapi_debug.h" #include #include #include -#include using namespace RocketChatRestApi; GetSupportedLanguagesJob::GetSupportedLanguagesJob(QObject *parent) : RestApiAbstractJob(parent) { } GetSupportedLanguagesJob::~GetSupportedLanguagesJob() { } bool GetSupportedLanguagesJob::requireHttpAuthentication() const { return true; } bool GetSupportedLanguagesJob::start() { if (!canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start GetSupportedLanguagesJob"; deleteLater(); return false; } QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &GetSupportedLanguagesJob::slotGetSupportedLanguagesFinished); addLoggerInfo(QByteArrayLiteral("GetSupportedLanguagesJob: get message starting")); return true; } void GetSupportedLanguagesJob::slotGetSupportedLanguagesFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("GetSupportedLanguagesJob: success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT getSupportedLanguagesDone(replyObject); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("GetSupportedLanguagesJob: Problem when we tried to GetSupportedLanguages : ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QNetworkRequest GetSupportedLanguagesJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::AutoTranslateGetSupportedLanguages); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } bool GetSupportedLanguagesJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start GetSupportedLanguagesJob"; return false; } return true; } diff --git a/src/rocketchatrestapi-qt5/autotranslate/translatemessagejob.cpp b/src/rocketchatrestapi-qt5/autotranslate/translatemessagejob.cpp index fabb8b6f..2d923c27 100644 --- a/src/rocketchatrestapi-qt5/autotranslate/translatemessagejob.cpp +++ b/src/rocketchatrestapi-qt5/autotranslate/translatemessagejob.cpp @@ -1,130 +1,129 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "translatemessagejob.h" #include "restapimethod.h" #include "rocketchatqtrestapi_debug.h" -#include #include #include #include using namespace RocketChatRestApi; TranslateMessageJob::TranslateMessageJob(QObject *parent) : RestApiAbstractJob(parent) { } TranslateMessageJob::~TranslateMessageJob() { } bool TranslateMessageJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("TranslateMessageJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &TranslateMessageJob::slotTranslateMessageFinished); return true; } void TranslateMessageJob::slotTranslateMessageFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("TranslateMessageJob success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT translateMessageDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("TranslateMessageJob: Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString TranslateMessageJob::targetLanguage() const { return mTargetLanguage; } void TranslateMessageJob::setTargetLanguage(const QString &targetLanguage) { mTargetLanguage = targetLanguage; } QString TranslateMessageJob::messageId() const { return mMessageId; } void TranslateMessageJob::setMessageId(const QString &messageId) { mMessageId = messageId; } bool TranslateMessageJob::requireHttpAuthentication() const { return true; } bool TranslateMessageJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start TranslateMessageJob"; return false; } if (mMessageId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "TranslateMessageJob: mMessageId is empty"; return false; } if (mTargetLanguage.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "TranslateMessageJob: mTargetLanguage is empty"; return false; } return true; } QNetworkRequest TranslateMessageJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::AutoTranslateTranslateMessage); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } QJsonDocument TranslateMessageJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("messageId")] = mMessageId; jsonObj[QLatin1String("targetLanguage")] = mTargetLanguage; const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } diff --git a/src/rocketchatrestapi-qt5/autotranslate/translatesavesettingsjob.cpp b/src/rocketchatrestapi-qt5/autotranslate/translatesavesettingsjob.cpp index 3da6964f..4e2b35ff 100644 --- a/src/rocketchatrestapi-qt5/autotranslate/translatesavesettingsjob.cpp +++ b/src/rocketchatrestapi-qt5/autotranslate/translatesavesettingsjob.cpp @@ -1,165 +1,164 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "translatesavesettingsjob.h" #include "restapimethod.h" #include "rocketchatqtrestapi_debug.h" -#include #include #include #include using namespace RocketChatRestApi; TranslateSaveSettingsJob::TranslateSaveSettingsJob(QObject *parent) : RestApiAbstractJob(parent) { } TranslateSaveSettingsJob::~TranslateSaveSettingsJob() { } bool TranslateSaveSettingsJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("TranslateSaveSettingsJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &TranslateSaveSettingsJob::slotTranslateSaveSettingsFinished); return true; } void TranslateSaveSettingsJob::slotTranslateSaveSettingsFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("TranslateSaveSettingsJob success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT translateSavesettingsDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("TranslateSaveSettingsJob: Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } TranslateSaveSettingsJob::SettingType TranslateSaveSettingsJob::type() const { return mType; } void TranslateSaveSettingsJob::setType(const SettingType &type) { mType = type; } QString TranslateSaveSettingsJob::language() const { return mLanguage; } void TranslateSaveSettingsJob::setLanguage(const QString &language) { mLanguage = language; } bool TranslateSaveSettingsJob::autoTranslate() const { return mAutoTranslate; } void TranslateSaveSettingsJob::setAutoTranslate(bool autoTranslate) { mAutoTranslate = autoTranslate; } QString TranslateSaveSettingsJob::roomId() const { return mRoomId; } void TranslateSaveSettingsJob::setRoomId(const QString &roomId) { mRoomId = roomId; } bool TranslateSaveSettingsJob::requireHttpAuthentication() const { return true; } bool TranslateSaveSettingsJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start TranslateSaveSettingsJob"; return false; } if (mRoomId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "TranslateSaveSettingsJob: mRoomId is empty"; return false; } if (mType == LanguageSetting && mLanguage.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "TranslateSaveSettingsJob: mLanguage is empty"; return false; } if (mType == Underfined) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "TranslateSaveSettingsJob: mType is not defined"; return false; } return true; } QNetworkRequest TranslateSaveSettingsJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::AutoTranslateSaveSettings); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } QJsonDocument TranslateSaveSettingsJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("roomId")] = mRoomId; switch (mType) { case AutoTranslateSetting: jsonObj[QLatin1String("field")] = QStringLiteral("autoTranslate"); jsonObj[QLatin1String("value")] = mAutoTranslate; break; case LanguageSetting: jsonObj[QLatin1String("field")] = QStringLiteral("autoTranslateLanguage"); jsonObj[QLatin1String("value")] = mLanguage; break; case Underfined: break; } const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } diff --git a/src/rocketchatrestapi-qt5/channels/channelfilesjob.cpp b/src/rocketchatrestapi-qt5/channels/channelfilesjob.cpp index 05c52b2b..b7a1a56a 100644 --- a/src/rocketchatrestapi-qt5/channels/channelfilesjob.cpp +++ b/src/rocketchatrestapi-qt5/channels/channelfilesjob.cpp @@ -1,136 +1,135 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelfilesjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include #include using namespace RocketChatRestApi; ChannelFilesJob::ChannelFilesJob(QObject *parent) : ChannelBaseJob(parent) { } ChannelFilesJob::~ChannelFilesJob() { } bool ChannelFilesJob::start() { if (!canStart()) { deleteLater(); return false; } addLoggerInfo("ChannelFilesJob::start: "); QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &ChannelFilesJob::slotFilesinChannelFinished); return true; } void ChannelFilesJob::slotFilesinChannelFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("channelFilesDone success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT channelFilesDone(replyObject, roomId()); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("channelFilesDone problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } ChannelFilesJob::ChannelType ChannelFilesJob::channelType() const { return mChannelType; } void ChannelFilesJob::setChannelType(ChannelType channelType) { mChannelType = channelType; } bool ChannelFilesJob::requireHttpAuthentication() const { return true; } bool ChannelFilesJob::canStart() const { if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelFilesJob: RoomId and RoomName are empty"; return false; } if (mChannelType == ChannelFilesJob::Unknown) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelFilesJob: Channel type is unknown."; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start ChannelFilesJob job"; return false; } return true; } QNetworkRequest ChannelFilesJob::request() const { QUrl url; switch (mChannelType) { case Channel: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsFiles); break; case Groups: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::GroupsFiles); break; case Direct: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ImFiles); break; case Unknown: qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelFilesJob: Type is not defined"; break; } QUrlQuery queryUrl; generateQuery(queryUrl); addQueryParameter(queryUrl); url.setQuery(queryUrl); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } bool RocketChatRestApi::ChannelFilesJob::hasQueryParameterSupport() const { return true; } diff --git a/src/rocketchatrestapi-qt5/channels/channelinfojob.cpp b/src/rocketchatrestapi-qt5/channels/channelinfojob.cpp index e7a18cfc..4fb6e15d 100644 --- a/src/rocketchatrestapi-qt5/channels/channelinfojob.cpp +++ b/src/rocketchatrestapi-qt5/channels/channelinfojob.cpp @@ -1,102 +1,101 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelinfojob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include #include using namespace RocketChatRestApi; ChannelInfoJob::ChannelInfoJob(QObject *parent) : ChannelBaseJob(parent) { } ChannelInfoJob::~ChannelInfoJob() { } bool ChannelInfoJob::start() { if (!canStart()) { deleteLater(); return false; } addLoggerInfo("ChannelInfoJob::start: "); QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &ChannelInfoJob::slotFilesinChannelFinished); return true; } void ChannelInfoJob::slotFilesinChannelFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("channelInfoDone success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT channelInfoDone(replyObject, roomId()); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("channelInfoDone problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } bool ChannelInfoJob::requireHttpAuthentication() const { return true; } bool ChannelInfoJob::canStart() const { if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelInfoJob: RoomId and RoomName are empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start ChannelInfoJob job"; return false; } return true; } QNetworkRequest ChannelInfoJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsInfo); QUrlQuery queryUrl; generateQuery(queryUrl); url.setQuery(queryUrl); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } diff --git a/src/rocketchatrestapi-qt5/channels/channelmembersjob.cpp b/src/rocketchatrestapi-qt5/channels/channelmembersjob.cpp index 6cc652d2..5ef6b32d 100644 --- a/src/rocketchatrestapi-qt5/channels/channelmembersjob.cpp +++ b/src/rocketchatrestapi-qt5/channels/channelmembersjob.cpp @@ -1,136 +1,135 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelmembersjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include #include using namespace RocketChatRestApi; ChannelMembersJob::ChannelMembersJob(QObject *parent) : ChannelBaseJob(parent) { } ChannelMembersJob::~ChannelMembersJob() { } bool ChannelMembersJob::start() { if (!canStart()) { deleteLater(); return false; } addLoggerInfo("ChannelMembersJob::start: "); QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &ChannelMembersJob::slotChannelMembersFinished); return true; } void ChannelMembersJob::slotChannelMembersFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("channelMembersDone success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT channelMembersDone(replyObject, roomId()); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("channelMembersDone problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } ChannelMembersJob::ChannelType ChannelMembersJob::channelType() const { return mChannelType; } void ChannelMembersJob::setChannelType(ChannelType channelType) { mChannelType = channelType; } bool ChannelMembersJob::hasQueryParameterSupport() const { return true; } bool ChannelMembersJob::requireHttpAuthentication() const { return true; } bool ChannelMembersJob::canStart() const { if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelMembersJob: RoomId and RoomName are empty"; return false; } if (mChannelType == ChannelMembersJob::Unknown) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelMembersJob: Channel type is unknown."; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start ChannelMembersJob job"; return false; } return true; } QNetworkRequest ChannelMembersJob::request() const { QUrl url; switch (mChannelType) { case Channel: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsMembers); break; case Groups: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::GroupsMembers); break; case Direct: url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ImMembers); break; case Unknown: qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelMembersJob: Type is not defined"; break; } QUrlQuery queryUrl; generateQuery(queryUrl); addQueryParameter(queryUrl); url.setQuery(queryUrl); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } diff --git a/src/rocketchatrestapi-qt5/channels/channelremoveownerjob.cpp b/src/rocketchatrestapi-qt5/channels/channelremoveownerjob.cpp index b292d859..7f34abc8 100644 --- a/src/rocketchatrestapi-qt5/channels/channelremoveownerjob.cpp +++ b/src/rocketchatrestapi-qt5/channels/channelremoveownerjob.cpp @@ -1,121 +1,120 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelremoveownerjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; ChannelRemoveOwnerJob::ChannelRemoveOwnerJob(QObject *parent) : ChannelBaseJob(parent) { } ChannelRemoveOwnerJob::~ChannelRemoveOwnerJob() { } bool ChannelRemoveOwnerJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("ChannelRemoveOwnerJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &ChannelRemoveOwnerJob::slotRemoveOwnerFinished); return true; } void ChannelRemoveOwnerJob::slotRemoveOwnerFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("ChannelRemoveOwnerJob success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT removeOwnerDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("ChannelRemoveOwnerJob problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString ChannelRemoveOwnerJob::removeUserId() const { return mRemoveUserId; } void ChannelRemoveOwnerJob::setRemoveUserId(const QString &removeUserId) { mRemoveUserId = removeUserId; } bool ChannelRemoveOwnerJob::requireHttpAuthentication() const { return true; } bool ChannelRemoveOwnerJob::canStart() const { if (mRemoveUserId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelRemoveOwnerJob: remove userid is empty"; return false; } if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelRemoveOwnerJob: RoomId and RoomName are empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start ChannelRemoveOwnerJob job"; return false; } return true; } QJsonDocument ChannelRemoveOwnerJob::json() const { QJsonObject jsonObj; generateJSon(jsonObj); jsonObj[QLatin1String("userId")] = removeUserId(); const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest ChannelRemoveOwnerJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsRemoveOwner); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/channels/channelsmoderatorsjob.cpp b/src/rocketchatrestapi-qt5/channels/channelsmoderatorsjob.cpp index 0526c149..9313ea10 100644 --- a/src/rocketchatrestapi-qt5/channels/channelsmoderatorsjob.cpp +++ b/src/rocketchatrestapi-qt5/channels/channelsmoderatorsjob.cpp @@ -1,102 +1,101 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelsmoderatorsjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include #include using namespace RocketChatRestApi; ChannelsModeratorsJob::ChannelsModeratorsJob(QObject *parent) : ChannelBaseJob(parent) { } ChannelsModeratorsJob::~ChannelsModeratorsJob() { } bool ChannelsModeratorsJob::start() { if (!canStart()) { deleteLater(); return false; } addLoggerInfo("ChannelsModeratorsJob::start: "); QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &ChannelsModeratorsJob::slotFilesinChannelFinished); return true; } void ChannelsModeratorsJob::slotFilesinChannelFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("channelFilesDone success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT channelFilesDone(replyObject, roomId()); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("channelFilesDone problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } bool ChannelsModeratorsJob::requireHttpAuthentication() const { return true; } bool ChannelsModeratorsJob::canStart() const { if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "ChannelsModeratorsJob: RoomId and RoomName are empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start ChannelsModeratorsJob job"; return false; } return true; } QNetworkRequest ChannelsModeratorsJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsModerators); QUrlQuery queryUrl; generateQuery(queryUrl); url.setQuery(queryUrl); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } diff --git a/src/rocketchatrestapi-qt5/channels/setchanneltypejob.cpp b/src/rocketchatrestapi-qt5/channels/setchanneltypejob.cpp index e0ea347b..1c0f9593 100644 --- a/src/rocketchatrestapi-qt5/channels/setchanneltypejob.cpp +++ b/src/rocketchatrestapi-qt5/channels/setchanneltypejob.cpp @@ -1,130 +1,129 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "setchanneltypejob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; SetChannelTypeJob::SetChannelTypeJob(QObject *parent) : ChannelBaseJob(parent) { } SetChannelTypeJob::~SetChannelTypeJob() { } bool SetChannelTypeJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("SetChannelTypeJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &SetChannelTypeJob::slotSetGroupTypeFinished); return true; } void SetChannelTypeJob::slotSetGroupTypeFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("SetChannelTypeJob success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT setGroupTypeDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("SetChannelTypeJob problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } SetChannelTypeJob::GroupType SetChannelTypeJob::type() const { return mType; } void SetChannelTypeJob::setType(GroupType type) { mType = type; } bool SetChannelTypeJob::requireHttpAuthentication() const { return true; } bool SetChannelTypeJob::canStart() const { if (!hasRoomIdentifier()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "SetChannelTypeJob: mRoomId and RoomName are empty"; return false; } if (mType == Unknown) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "SetChannelTypeJob: type is not defined"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start SetChannelTypeJob job"; return false; } return true; } QJsonDocument SetChannelTypeJob::json() const { QJsonObject jsonObj; generateJSon(jsonObj); switch (mType) { case Public: jsonObj[QLatin1String("type")] = QStringLiteral("c"); break; case Private: jsonObj[QLatin1String("type")] = QStringLiteral("p"); break; case Unknown: break; } const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest SetChannelTypeJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ChannelsSetType); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/directmessage/createdmjob.cpp b/src/rocketchatrestapi-qt5/directmessage/createdmjob.cpp index 7d9c44ec..406bc723 100644 --- a/src/rocketchatrestapi-qt5/directmessage/createdmjob.cpp +++ b/src/rocketchatrestapi-qt5/directmessage/createdmjob.cpp @@ -1,115 +1,114 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "createdmjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; CreateDmJob::CreateDmJob(QObject *parent) : RestApiAbstractJob(parent) { } CreateDmJob::~CreateDmJob() { } bool CreateDmJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("CreateDmJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &CreateDmJob::slotCreateDmFinished); return true; } void CreateDmJob::slotCreateDmFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("Create direct message success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT createDmDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("Create direct message Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString CreateDmJob::userName() const { return mUserName; } void CreateDmJob::setUserName(const QString &userName) { mUserName = userName; } bool CreateDmJob::requireHttpAuthentication() const { return true; } bool CreateDmJob::canStart() const { if (mUserName.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "CreateDmJob: username is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start CreateDmJob job"; return false; } return true; } QJsonDocument CreateDmJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("username")] = mUserName; const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest CreateDmJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ImCreate); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/directmessage/opendmjob.cpp b/src/rocketchatrestapi-qt5/directmessage/opendmjob.cpp index 62d94134..0e316116 100644 --- a/src/rocketchatrestapi-qt5/directmessage/opendmjob.cpp +++ b/src/rocketchatrestapi-qt5/directmessage/opendmjob.cpp @@ -1,115 +1,114 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "opendmjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; OpenDmJob::OpenDmJob(QObject *parent) : RestApiAbstractJob(parent) { } OpenDmJob::~OpenDmJob() { } bool OpenDmJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("OpenDmJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &OpenDmJob::slotOpenDmFinished); return true; } void OpenDmJob::slotOpenDmFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("Create direct message success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT openDmDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("Create direct message Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString OpenDmJob::directUserId() const { return mDirectUserId; } void OpenDmJob::setDirectUserId(const QString &userId) { mDirectUserId = userId; } bool OpenDmJob::requireHttpAuthentication() const { return true; } bool OpenDmJob::canStart() const { if (mDirectUserId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "OpenDmJob: mDirectUserId is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start OpenDmJob job"; return false; } return true; } QJsonDocument OpenDmJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("userId")] = mDirectUserId; const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest OpenDmJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ImOpen); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/directmessage/settopicdmjob.cpp b/src/rocketchatrestapi-qt5/directmessage/settopicdmjob.cpp index f0385cfc..680fdb1d 100644 --- a/src/rocketchatrestapi-qt5/directmessage/settopicdmjob.cpp +++ b/src/rocketchatrestapi-qt5/directmessage/settopicdmjob.cpp @@ -1,116 +1,115 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "settopicdmjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; SetTopicDmJob::SetTopicDmJob(QObject *parent) : RestApiAbstractJob(parent) { } SetTopicDmJob::~SetTopicDmJob() { } bool SetTopicDmJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("SetTopicDmJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &SetTopicDmJob::slotSetTopicDmFinished); return true; } void SetTopicDmJob::slotSetTopicDmFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("Create direct message success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT setTopicDmDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("Create direct message Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString SetTopicDmJob::directUserId() const { return mDirectUserId; } void SetTopicDmJob::setDirectUserId(const QString &userId) { mDirectUserId = userId; } bool SetTopicDmJob::requireHttpAuthentication() const { return true; } bool SetTopicDmJob::canStart() const { if (mDirectUserId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "SetTopicDmJob: mDirectUserId is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start SetTopicDmJob job"; return false; } return true; } QJsonDocument SetTopicDmJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("userId")] = mDirectUserId; jsonObj[QLatin1String("topic")] = mTopic; const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest SetTopicDmJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ImOpen); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/e2e/fetchmykeysjob.cpp b/src/rocketchatrestapi-qt5/e2e/fetchmykeysjob.cpp index b3550ff8..81743936 100644 --- a/src/rocketchatrestapi-qt5/e2e/fetchmykeysjob.cpp +++ b/src/rocketchatrestapi-qt5/e2e/fetchmykeysjob.cpp @@ -1,91 +1,90 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "fetchmykeysjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" #include -#include #include #include using namespace RocketChatRestApi; FetchMyKeysJob::FetchMyKeysJob(QObject *parent) : RestApiAbstractJob(parent) { } FetchMyKeysJob::~FetchMyKeysJob() { } bool FetchMyKeysJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start FetchKeyChain job"; return false; } return true; } bool FetchMyKeysJob::start() { if (!canStart()) { deleteLater(); return false; } QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &FetchMyKeysJob::slotFetchMyKeys); addLoggerInfo("Start FetchMyKeysJob"); return true; } void FetchMyKeysJob::slotFetchMyKeys() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("FetchMyKeysJob: success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT fetchMyKeysDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("FetchMyKeysJob: problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QNetworkRequest FetchMyKeysJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::E2EfetchMyKeys); QNetworkRequest request(url); addAuthRawHeader(request); return request; } bool FetchMyKeysJob::requireHttpAuthentication() const { return true; } diff --git a/src/rocketchatrestapi-qt5/emoji/deleteemojicustomjob.cpp b/src/rocketchatrestapi-qt5/emoji/deleteemojicustomjob.cpp index 8fe8477b..554c3d2d 100644 --- a/src/rocketchatrestapi-qt5/emoji/deleteemojicustomjob.cpp +++ b/src/rocketchatrestapi-qt5/emoji/deleteemojicustomjob.cpp @@ -1,115 +1,114 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "deleteemojicustomjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; DeleteEmojiCustomJob::DeleteEmojiCustomJob(QObject *parent) : RestApiAbstractJob(parent) { } DeleteEmojiCustomJob::~DeleteEmojiCustomJob() { } bool DeleteEmojiCustomJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("DeleteEmojiCustomJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &DeleteEmojiCustomJob::slotDeleteEmojiFinished); return true; } void DeleteEmojiCustomJob::slotDeleteEmojiFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("DeleteEmojiCustomJob success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT removeOwnerDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("DeleteEmojiCustomJob problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QString DeleteEmojiCustomJob::emojiId() const { return mEmojiId; } void DeleteEmojiCustomJob::setEmojiId(const QString &emojiId) { mEmojiId = emojiId; } bool DeleteEmojiCustomJob::requireHttpAuthentication() const { return true; } bool DeleteEmojiCustomJob::canStart() const { if (mEmojiId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "DeleteEmojiCustomJob: remove mEmojiId is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start DeleteEmojiCustomJob job"; return false; } return true; } QJsonDocument DeleteEmojiCustomJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("emojiId")] = emojiId(); const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest DeleteEmojiCustomJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::DeleteEmojiCustom); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/groups/groupsinfojob.cpp b/src/rocketchatrestapi-qt5/groups/groupsinfojob.cpp index 2091c459..337253a8 100644 --- a/src/rocketchatrestapi-qt5/groups/groupsinfojob.cpp +++ b/src/rocketchatrestapi-qt5/groups/groupsinfojob.cpp @@ -1,112 +1,111 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "groupsinfojob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include #include using namespace RocketChatRestApi; GroupsInfoJob::GroupsInfoJob(QObject *parent) : RestApiAbstractJob(parent) { } GroupsInfoJob::~GroupsInfoJob() { } bool GroupsInfoJob::start() { if (!canStart()) { deleteLater(); return false; } addLoggerInfo("GroupsInfoJob::start: "); QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &GroupsInfoJob::slotChannelInfoFinished); return true; } void GroupsInfoJob::slotChannelInfoFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("groupInfoDone success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT channelInfoDone(replyObject, mRoomId); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("groupInfoDone problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } bool GroupsInfoJob::requireHttpAuthentication() const { return true; } bool GroupsInfoJob::canStart() const { if (mRoomId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "GroupsInfoJob: RoomId is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start GroupsInfoJob job"; return false; } return true; } QString GroupsInfoJob::roomId() const { return mRoomId; } void GroupsInfoJob::setRoomId(const QString &roomId) { mRoomId = roomId; } QNetworkRequest GroupsInfoJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::GroupsInfo); QUrlQuery queryUrl; queryUrl.addQueryItem(QStringLiteral("roomId"), mRoomId); url.setQuery(queryUrl); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } diff --git a/src/rocketchatrestapi-qt5/groups/setgrouptypejob.cpp b/src/rocketchatrestapi-qt5/groups/setgrouptypejob.cpp index d89c4f95..ae3e8320 100644 --- a/src/rocketchatrestapi-qt5/groups/setgrouptypejob.cpp +++ b/src/rocketchatrestapi-qt5/groups/setgrouptypejob.cpp @@ -1,140 +1,139 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "setgrouptypejob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" -#include #include #include #include using namespace RocketChatRestApi; SetGroupTypeJob::SetGroupTypeJob(QObject *parent) : RestApiAbstractJob(parent) { } SetGroupTypeJob::~SetGroupTypeJob() { } bool SetGroupTypeJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("SetGroupTypeJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &SetGroupTypeJob::slotSetGroupTypeFinished); return true; } void SetGroupTypeJob::slotSetGroupTypeFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("SetGroupTypeJob: Success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT setGroupTypeDone(); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("SetGroupTypeJob: Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } SetGroupTypeJob::GroupType SetGroupTypeJob::type() const { return mType; } void SetGroupTypeJob::setType(GroupType type) { mType = type; } QString SetGroupTypeJob::roomId() const { return mRoomId; } void SetGroupTypeJob::setRoomId(const QString &roomId) { mRoomId = roomId; } bool SetGroupTypeJob::requireHttpAuthentication() const { return true; } bool SetGroupTypeJob::canStart() const { if (mRoomId.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "SetGroupTypeJob: mRoomId is empty"; return false; } if (mType == Unknown) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "SetGroupTypeJob: type is not defined"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start SetGroupTypeJob job"; return false; } return true; } QJsonDocument SetGroupTypeJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("roomId")] = roomId(); switch (mType) { case Public: jsonObj[QLatin1String("type")] = QStringLiteral("c"); break; case Private: jsonObj[QLatin1String("type")] = QStringLiteral("p"); break; case Unknown: break; } const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } QNetworkRequest SetGroupTypeJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::GroupsSetType); QNetworkRequest request(url); addAuthRawHeader(request); addRequestAttribute(request); return request; } diff --git a/src/rocketchatrestapi-qt5/users/forgotpasswordjob.cpp b/src/rocketchatrestapi-qt5/users/forgotpasswordjob.cpp index ffcd4e13..b9b8e49b 100644 --- a/src/rocketchatrestapi-qt5/users/forgotpasswordjob.cpp +++ b/src/rocketchatrestapi-qt5/users/forgotpasswordjob.cpp @@ -1,106 +1,105 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "forgotpasswordjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" #include -#include #include #include using namespace RocketChatRestApi; ForgotPasswordJob::ForgotPasswordJob(QObject *parent) : RestApiAbstractJob(parent) { } ForgotPasswordJob::~ForgotPasswordJob() { } bool ForgotPasswordJob::canStart() const { if (mEmail.isEmpty()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Avatar email is empty"; return false; } if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start getavatar job"; return false; } return true; } bool ForgotPasswordJob::start() { if (!canStart()) { deleteLater(); return false; } const QByteArray baPostData = json().toJson(QJsonDocument::Compact); addLoggerInfo("ForgotPasswordJob::start: " + baPostData); QNetworkReply *reply = mNetworkAccessManager->post(request(), baPostData); connect(reply, &QNetworkReply::finished, this, &ForgotPasswordJob::slotForgotPassword); return true; } void ForgotPasswordJob::slotForgotPassword() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); //qCDebug(ROCKETCHATQTRESTAPI_LOG) << "RestApiRequest::parseGetAvatar: " << data << " userId "<deleteLater(); } deleteLater(); } QString ForgotPasswordJob::email() const { return mEmail; } void ForgotPasswordJob::setEmail(const QString &email) { mEmail = email; } QNetworkRequest ForgotPasswordJob::request() const { const QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::ForgotPassword); QNetworkRequest request(url); return request; } bool ForgotPasswordJob::requireHttpAuthentication() const { return false; } QJsonDocument ForgotPasswordJob::json() const { QJsonObject jsonObj; jsonObj[QLatin1String("email")] = mEmail; const QJsonDocument postData = QJsonDocument(jsonObj); return postData; } diff --git a/src/rocketchatrestapi-qt5/users/getusernamesuggestionjob.cpp b/src/rocketchatrestapi-qt5/users/getusernamesuggestionjob.cpp index 101e259d..f05ae9ae 100644 --- a/src/rocketchatrestapi-qt5/users/getusernamesuggestionjob.cpp +++ b/src/rocketchatrestapi-qt5/users/getusernamesuggestionjob.cpp @@ -1,90 +1,89 @@ /* Copyright (c) 2018-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "getusernamesuggestionjob.h" #include "rocketchatqtrestapi_debug.h" #include "restapimethod.h" #include -#include #include #include using namespace RocketChatRestApi; GetUsernameSuggestionJob::GetUsernameSuggestionJob(QObject *parent) : RestApiAbstractJob(parent) { } GetUsernameSuggestionJob::~GetUsernameSuggestionJob() { } bool GetUsernameSuggestionJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start getPresence job"; return false; } return true; } bool GetUsernameSuggestionJob::start() { if (!canStart()) { deleteLater(); return false; } QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &GetUsernameSuggestionJob::slotGetUsernameSuggestion); addLoggerInfo("GetUsernameSuggestionJob start"); return true; } void GetUsernameSuggestionJob::slotGetUsernameSuggestion() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("GetUsernameSuggestionJob: success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT getUsernameSuggestionDone(replyObject[QStringLiteral("result")].toString()); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("GetUsernameSuggestionJob problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QNetworkRequest GetUsernameSuggestionJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::UsersGetUsernameSuggestion); QNetworkRequest request(url); addAuthRawHeader(request); return request; } bool GetUsernameSuggestionJob::requireHttpAuthentication() const { return true; } diff --git a/src/rocketchatrestapi-qt5/users/userspresencejob.cpp b/src/rocketchatrestapi-qt5/users/userspresencejob.cpp index 8c82b2ed..f6907a64 100644 --- a/src/rocketchatrestapi-qt5/users/userspresencejob.cpp +++ b/src/rocketchatrestapi-qt5/users/userspresencejob.cpp @@ -1,93 +1,92 @@ /* Copyright (c) 2019-2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "userspresencejob.h" #include "restapimethod.h" #include "rocketchatqtrestapi_debug.h" #include #include -#include #include using namespace RocketChatRestApi; UsersPresenceJob::UsersPresenceJob(QObject *parent) : RestApiAbstractJob(parent) { } UsersPresenceJob::~UsersPresenceJob() { } bool UsersPresenceJob::requireHttpAuthentication() const { return true; } bool UsersPresenceJob::start() { if (!canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start userspresence job"; deleteLater(); return false; } QNetworkReply *reply = mNetworkAccessManager->get(request()); connect(reply, &QNetworkReply::finished, this, &UsersPresenceJob::slotUsersPresenceFinished); addLoggerInfo(QByteArrayLiteral("UsersPresenceJob: Ask info about me")); return true; } void UsersPresenceJob::slotUsersPresenceFinished() { auto *reply = qobject_cast(sender()); if (reply) { const QByteArray data = reply->readAll(); const QJsonDocument replyJson = QJsonDocument::fromJson(data); const QJsonObject replyObject = replyJson.object(); if (replyObject[QStringLiteral("success")].toBool()) { addLoggerInfo(QByteArrayLiteral("UsersPresenceJob: success: ") + replyJson.toJson(QJsonDocument::Indented)); Q_EMIT usersPresenceDone(replyObject); } else { emitFailedMessage(replyObject); addLoggerWarning(QByteArrayLiteral("UsersPresenceJob: Problem: ") + replyJson.toJson(QJsonDocument::Indented)); } reply->deleteLater(); } deleteLater(); } QNetworkRequest UsersPresenceJob::request() const { QUrl url = mRestApiMethod->generateUrl(RestApiUtil::RestApiUrlType::UsersPresence); QNetworkRequest request(url); addAuthRawHeader(request); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); return request; } bool UsersPresenceJob::canStart() const { if (!RestApiAbstractJob::canStart()) { qCWarning(ROCKETCHATQTRESTAPI_LOG) << "Impossible to start UsersPresenceJob job"; return false; } return true; } diff --git a/src/widgets/autotests/ruqolamainwindowtest.cpp b/src/widgets/autotests/ruqolamainwindowtest.cpp index 0bac383d..a38f564c 100644 --- a/src/widgets/autotests/ruqolamainwindowtest.cpp +++ b/src/widgets/autotests/ruqolamainwindowtest.cpp @@ -1,80 +1,79 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ruqolamainwindowtest.h" #include "ruqolamainwindow.h" -#include #include #include #include QTEST_MAIN(RuqolaMainWindowTest) RuqolaMainWindowTest::RuqolaMainWindowTest(QObject *parent) : QObject(parent) { } static void switchToMainWidget(RuqolaMainWindow &w) { auto *mStackedWidget = w.findChild(QStringLiteral("mStackedWidget")); QVERIFY(mStackedWidget); auto *mRuqolaMainWidget = mStackedWidget->findChild(QStringLiteral("mRuqolaMainWidget")); QVERIFY(mRuqolaMainWidget); mStackedWidget->setCurrentWidget(mRuqolaMainWidget); QCOMPARE(mStackedWidget->currentWidget(), mRuqolaMainWidget); } void RuqolaMainWindowTest::shouldHaveDefaultValues() { RuqolaMainWindow w; auto *mSplitter = w.findChild(QStringLiteral("mSplitter")); QVERIFY(mSplitter); switchToMainWidget(w); } void RuqolaMainWindowTest::shouldRestoreSizes() { // Save QList actualSizes; { RuqolaMainWindow w; switchToMainWidget(w); w.resize(500, 500); w.show(); auto *mSplitter = w.findChild(QStringLiteral("mSplitter")); QVERIFY(mSplitter); mSplitter->setSizes({100, 400}); actualSizes = mSplitter->sizes(); // not exactly {100, 400} but more something like {167, 308} } // Restore { RuqolaMainWindow w; switchToMainWidget(w); QCOMPARE(w.size(), QSize(500, 500)); w.show(); auto *mSplitter = w.findChild(QStringLiteral("mSplitter")); QVERIFY(mSplitter); QCOMPARE(mSplitter->sizes(), actualSizes); } } diff --git a/src/widgets/channellist/channellistview.cpp b/src/widgets/channellist/channellistview.cpp index 574ed192..18251bf9 100644 --- a/src/widgets/channellist/channellistview.cpp +++ b/src/widgets/channellist/channellistview.cpp @@ -1,163 +1,162 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channellistview.h" #include "ruqola.h" #include "ruqolawidgets_debug.h" #include "rocketchataccount.h" #include "channellistdelegate.h" #include "model/roomfilterproxymodel.h" #include #include #include -#include #include ChannelListView::ChannelListView(QWidget *parent) : QListView(parent) { auto *delegate = new ChannelListDelegate(this); setItemDelegate(delegate); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); connect(this, &ChannelListView::clicked, this, &ChannelListView::slotClicked); } ChannelListView::~ChannelListView() { } RoomFilterProxyModel *ChannelListView::model() const { return qobject_cast(QListView::model()); } void ChannelListView::setModel(QAbstractItemModel *model) { if (!qobject_cast(model)) { qCWarning(RUQOLAWIDGETS_LOG) << "Need to pass a RoomFilterProxyModel instance!"; return; } QListView::setModel(model); } void ChannelListView::slotClicked(const QModelIndex &index) { if (index.isValid()) { Q_EMIT channelSelected(index); } } void ChannelListView::contextMenuEvent(QContextMenuEvent *event) { const QModelIndex index = indexAt(event->pos()); if (!index.isValid()) { return; } QMenu menu(this); const QString roomType = index.data(RoomModel::RoomType).toString(); QAction *hideChannel = new QAction(QIcon::fromTheme(QStringLiteral("hide_table_row")), i18n("Hide Channel"), &menu); connect(hideChannel, &QAction::triggered, this, [=]() { slotHideChannel(index, roomType); }); menu.addAction(hideChannel); const bool isFavorite = index.data(RoomModel::RoomFavorite).toBool(); const QString actionFavoriteText = isFavorite ? i18n("Unset as Favorite") : i18n("Set as Favorite"); QAction *favoriteAction = new QAction(QIcon::fromTheme(QStringLiteral("favorite")), actionFavoriteText, &menu); connect(favoriteAction, &QAction::triggered, this, [=]() { slotChangeFavorite(index, isFavorite); }); menu.addAction(favoriteAction); if (roomType == QLatin1String("c") || roomType == QLatin1String("p")) { //Not direct channel auto *separator = new QAction(&menu); separator->setSeparator(true); menu.addAction(separator); QAction *quitChannel = new QAction(QIcon::fromTheme(QStringLiteral("dialog-close")), i18n("Quit Channel"), &menu); connect(quitChannel, &QAction::triggered, this, [=]() { slotLeaveChannel(index, roomType); }); menu.addAction(quitChannel); } if (!menu.actions().isEmpty()) { menu.exec(event->globalPos()); } } void ChannelListView::slotHideChannel(const QModelIndex &index, const QString &roomType) { auto *rcAccount = Ruqola::self()->rocketChatAccount(); const QString roomId = index.data(RoomModel::RoomID).toString(); rcAccount->hideRoom(roomId, roomType); } void ChannelListView::slotLeaveChannel(const QModelIndex &index, const QString &roomType) { auto *rcAccount = Ruqola::self()->rocketChatAccount(); const QString roomId = index.data(RoomModel::RoomID).toString(); rcAccount->leaveRoom(roomId, roomType); } void ChannelListView::slotChangeFavorite(const QModelIndex &index, bool isFavorite) { auto *rcAccount = Ruqola::self()->rocketChatAccount(); const QString roomId = index.data(RoomModel::RoomID).toString(); rcAccount->changeFavorite(roomId, !isFavorite); } void ChannelListView::selectChannelRequested(const QString &channelId) { if (channelId.isEmpty()) { return; } RoomFilterProxyModel *filterModel = model(); for (int roomIdx = 0, nRooms = filterModel->rowCount(); roomIdx < nRooms; ++roomIdx) { const auto roomModelIndex = filterModel->index(roomIdx, 0); const auto roomId = roomModelIndex.data(RoomModel::RoomID).toString(); if (roomId == channelId) { Q_EMIT channelSelected(roomModelIndex); selectionModel()->setCurrentIndex(filterModel->index(roomIdx, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); break; } } } bool ChannelListView::selectChannelByRoomNameRequested(const QString &selectedRoomName) { if (selectedRoomName.isEmpty()) { return false; } RoomFilterProxyModel *filterModel = model(); for (int roomIdx = 0, nRooms = filterModel->rowCount(); roomIdx < nRooms; ++roomIdx) { const auto roomModelIndex = filterModel->index(roomIdx, 0); const auto roomName = roomModelIndex.data(RoomModel::RoomName).toString(); if (roomName == selectedRoomName) { Q_EMIT channelSelected(roomModelIndex); selectionModel()->setCurrentIndex(filterModel->index(roomIdx, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); return true; } } return false; } diff --git a/src/widgets/channellist/channellistwidget.cpp b/src/widgets/channellist/channellistwidget.cpp index 5a033019..2f30f5bf 100644 --- a/src/widgets/channellist/channellistwidget.cpp +++ b/src/widgets/channellist/channellistwidget.cpp @@ -1,225 +1,224 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channellistview.h" #include "channellistwidget.h" #include "statuscombobox.h" #include "dialogs/modifystatusdialog.h" #include "model/statusmodel.h" #include "model/roomfilterproxymodel.h" #include "ruqola.h" #include "rocketchataccount.h" #include "ruqolautils.h" #include #include #include #include #include #include -#include #include ChannelListWidget::ChannelListWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainlayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mSearchRoom = new QLineEdit(this); // dummy action just for getting the icon) mSearchRoom->addAction(QIcon::fromTheme(QStringLiteral("view-filter")), QLineEdit::LeadingPosition); mSearchRoom->setObjectName(QStringLiteral("mSearchRoom")); mSearchRoom->setPlaceholderText(i18n("Search Rooms (CTRL + K)")); mSearchRoom->setClearButtonEnabled(true); mSearchRoom->installEventFilter(this); mainLayout->addWidget(mSearchRoom); connect(mSearchRoom, &QLineEdit::textChanged, this, &ChannelListWidget::slotSearchRoomTextChanged); mChannelView = new ChannelListView(this); mChannelView->setObjectName(QStringLiteral("mChannelView")); mainLayout->addWidget(mChannelView); connect(mChannelView, &ChannelListView::channelSelected, this, &ChannelListWidget::channelSelected); auto *statusComboBoxLayout = new QHBoxLayout; mainLayout->addLayout(statusComboBoxLayout); QLabel *label = new QLabel(i18n("Status:"), this); label->setObjectName(QStringLiteral("label")); statusComboBoxLayout->addWidget(label); mStatusComboBox = new StatusCombobox(true, this); mStatusComboBox->setObjectName(QStringLiteral("mStatusComboBox")); statusComboBoxLayout->addWidget(mStatusComboBox); connect(mStatusComboBox, QOverload::of(&StatusCombobox::currentIndexChanged), this, &ChannelListWidget::slotStatusChanged); //BEGIN: Actions auto searchRoomAction = new QAction(i18n("Search Rooms"), this); searchRoomAction->setShortcut(Qt::CTRL + Qt::Key_K); connect(searchRoomAction, &QAction::triggered, this, [this]() { mSearchRoom->setFocus(); }); addAction(searchRoomAction); // TODO: Add to MainWindow's action collection instead? //END: Actions } ChannelListWidget::~ChannelListWidget() { } void ChannelListWidget::clearFilterChannel() { if (auto *model = mChannelView->model()) { model->setFilterString(QString()); mSearchRoom->clear(); } } void ChannelListWidget::setCurrentRocketChatAccount(RocketChatAccount *account) { clearFilterChannel(); if (mCurrentRocketChatAccount) { disconnect(mCurrentRocketChatAccount, nullptr, this, nullptr); } mCurrentRocketChatAccount = account; connect(mCurrentRocketChatAccount, &RocketChatAccount::userStatusUpdated, this, &ChannelListWidget::setUserStatusUpdated); connect(mCurrentRocketChatAccount, &RocketChatAccount::openLinkRequested, this, &ChannelListWidget::slotOpenLinkRequested); mChannelView->setModel(mCurrentRocketChatAccount->roomFilterProxyModel()); } ChannelListView *ChannelListWidget::channelListView() const { return mChannelView; } QString ChannelListWidget::currentSelectedRoom() const { if (mChannelView->selectionModel()) { //For autotest const QModelIndex selectedIndex = mChannelView->selectionModel()->currentIndex(); if (selectedIndex.isValid()) { return selectedIndex.data(Qt::DisplayRole).toString(); } } return QString(); } bool ChannelListWidget::eventFilter(QObject *object, QEvent *event) { if (object == mSearchRoom && event->type() == QEvent::KeyPress) { const auto *model = mChannelView->model(); const auto *keyEvent = static_cast(event); const int keyValue = keyEvent->key(); if (keyValue == Qt::Key_Return || keyValue == Qt::Key_Enter) { const auto selectedIndex = mChannelView->selectionModel()->currentIndex(); if (selectedIndex.isValid()) { Q_EMIT channelSelected(selectedIndex); mSearchRoom->setText({}); } } else if (keyValue == Qt::Key_Up || keyValue == Qt::Key_Down) { const QModelIndex currentIndex = mChannelView->selectionModel()->currentIndex(); int selectRow = -1; if (keyValue == Qt::Key_Up) { if (!currentIndex.isValid()) { selectRow = model->rowCount() - 1; } else if (currentIndex.row()-1 >= 0) { selectRow = currentIndex.row() - 1; } } else { // Qt::Key_Down if (!currentIndex.isValid()) { selectRow = 0; } else if (currentIndex.row()+1 < model->rowCount()) { selectRow = currentIndex.row() + 1; } } if (selectRow != -1) { mChannelView->selectionModel()->setCurrentIndex(model->index(selectRow, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } return true; // eat event } } return QWidget::eventFilter(object, event); } void ChannelListWidget::setUserStatusUpdated(User::PresenceStatus status) { mStatusComboBox->setStatus(status); } void ChannelListWidget::slotStatusChanged() { User::PresenceStatus status = mStatusComboBox->status(); QString messageStatus; if (status == User::PresenceStatus::Unknown) { QPointer dlg = new ModifyStatusDialog(this); dlg->setMessageStatus(Ruqola::self()->rocketChatAccount()->statusModel()->currentStatusInfo().displayText); dlg->setStatus(Ruqola::self()->rocketChatAccount()->statusModel()->currentStatusInfo().status); if (dlg->exec()) { messageStatus = dlg->messageStatus(); status = dlg->status(); delete dlg; } else { mStatusComboBox->setStatus(Ruqola::self()->rocketChatAccount()->statusModel()->currentUserStatus()); delete dlg; return; } } Ruqola::self()->rocketChatAccount()->setDefaultStatus(status, messageStatus); } void ChannelListWidget::slotSearchRoomTextChanged() { mChannelView->model()->setFilterString(mSearchRoom->text()); } void ChannelListWidget::slotOpenLinkRequested(const QString &link) { if (link.startsWith(QLatin1String("ruqola:"))) { const QString roomOrUser = RuqolaUtils::self()->extractRoomUserFromUrl(link); const QModelIndex selectedIndex = mChannelView->selectionModel()->currentIndex(); if (selectedIndex.isValid()) { const QString currentRoomId = selectedIndex.data(RoomModel::RoomName).toString(); if (roomOrUser == currentRoomId) { return; } } if (link.startsWith(QLatin1String("ruqola:/room/"))) { if (!mChannelView->selectChannelByRoomNameRequested(roomOrUser)) { mCurrentRocketChatAccount->openChannel(roomOrUser); } } else if (link.startsWith(QLatin1String("ruqola:/user/"))) { if (!mChannelView->selectChannelByRoomNameRequested(roomOrUser)) { if (roomOrUser != mCurrentRocketChatAccount->userName()) { mCurrentRocketChatAccount->openDirectChannel(roomOrUser); } } } else if (link == QLatin1String("ruqola:/jitsicall/")) { const QModelIndex selectedIndex = mChannelView->selectionModel()->currentIndex(); if (selectedIndex.isValid()) { const QString roomId = selectedIndex.data(RoomModel::RoomID).toString(); mCurrentRocketChatAccount->joinJitsiConfCall(roomId); } } } else { RuqolaUtils::self()->openUrl(link); } } diff --git a/src/widgets/common/authenticationcombobox.cpp b/src/widgets/common/authenticationcombobox.cpp index 14a7990d..602344cd 100644 --- a/src/widgets/common/authenticationcombobox.cpp +++ b/src/widgets/common/authenticationcombobox.cpp @@ -1,44 +1,43 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "authenticationcombobox.h" #include "ruqola.h" #include "model/loginmethodmodel.h" #include "rocketchataccount.h" -#include AuthenticationComboBox::AuthenticationComboBox(QWidget *parent) : QComboBox(parent) { initialize(); } AuthenticationComboBox::~AuthenticationComboBox() { } void AuthenticationComboBox::initialize() { const QVector authenticationInfos = Ruqola::self()->rocketChatAccount()->loginMethodModel()->authentications(); for (const AuthenticationInfo &info : authenticationInfos) { addItem(QIcon::fromTheme(info.iconName()), info.name(), QVariant::fromValue(info.oauthType())); } } diff --git a/src/widgets/common/completionlineedit.cpp b/src/widgets/common/completionlineedit.cpp index 24162ff4..571220a5 100644 --- a/src/widgets/common/completionlineedit.cpp +++ b/src/widgets/common/completionlineedit.cpp @@ -1,55 +1,49 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "completionlineedit.h" #include "completionlistview.h" #include "rocketchataccount.h" #include "ruqola.h" -#include -#include -#include -#include #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -#include -#include #endif CompletionLineEdit::CompletionLineEdit(QWidget *parent) : QLineEdit(parent) { setClearButtonEnabled(true); mCompletionListView = new CompletionListView; mCompletionListView->setTextWidget(this); connect(mCompletionListView, &CompletionListView::complete, this, &CompletionLineEdit::complete); } CompletionLineEdit::~CompletionLineEdit() { delete mCompletionListView; } void CompletionLineEdit::setCompletionModel(QAbstractItemModel *model) { mCompletionListView->setModel(model); } diff --git a/src/widgets/common/completiontextedit.cpp b/src/widgets/common/completiontextedit.cpp index 7f3171db..e1afe9ac 100644 --- a/src/widgets/common/completiontextedit.cpp +++ b/src/widgets/common/completiontextedit.cpp @@ -1,56 +1,50 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "completiontextedit.h" #include "completionlistview.h" #include "rocketchataccount.h" #include "ruqola.h" -#include -#include -#include -#include #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -#include -#include #endif CompletionTextEdit::CompletionTextEdit(QWidget *parent) : KTextEdit(parent) { // TODO how to reimplement this in QTextEdit? //setClearButtonEnabled(true); mCompletionListView = new CompletionListView; mCompletionListView->setTextWidget(this); connect(mCompletionListView, &CompletionListView::complete, this, &CompletionTextEdit::complete); } CompletionTextEdit::~CompletionTextEdit() { delete mCompletionListView; } void CompletionTextEdit::setCompletionModel(QAbstractItemModel *model) { mCompletionListView->setModel(model); } diff --git a/src/widgets/configuredialog/accountserverlistwidget.cpp b/src/widgets/configuredialog/accountserverlistwidget.cpp index 81cdf428..0aefc139 100644 --- a/src/widgets/configuredialog/accountserverlistwidget.cpp +++ b/src/widgets/configuredialog/accountserverlistwidget.cpp @@ -1,151 +1,150 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "accountserverlistwidget.h" #include "ruqola.h" #include "accountmanager.h" #include "rocketchataccount.h" #include "dialogs/createnewaccountdialog.h" #include "model/rocketchataccountmodel.h" -#include #include #include AccountServerListWidget::AccountServerListWidget(QWidget *parent) : QListWidget(parent) { connect(this, &AccountServerListWidget::itemDoubleClicked, this, &AccountServerListWidget::modifyAccountConfig); } AccountServerListWidget::~AccountServerListWidget() { } void AccountServerListWidget::load() { RocketChatAccountModel *model = Ruqola::self()->accountManager()->rocketChatAccountModel(); const int accountNumber = model->accountNumber(); for (int i = 0; i < accountNumber; ++i) { auto *item = new AccountServerListWidgetItem(this); CreateNewAccountDialog::AccountInfo info; info.accountName = model->account(i)->accountName(); info.serverName = model->account(i)->serverUrl(); info.userName = model->account(i)->userName(); item->setAccountInfo(info); item->setNewAccount(false); item->setCheckState(model->account(i)->accountEnabled() ? Qt::Checked : Qt::Unchecked); } } void AccountServerListWidget::save() { //First remove account for (const QString &accountName : qAsConst(mListRemovedAccount)) { Ruqola::self()->accountManager()->removeAccount(accountName); } //Add account or modify it for (int i = 0; i < count(); ++i) { QListWidgetItem *it = item(i); auto *serverListItem = static_cast(it); const CreateNewAccountDialog::AccountInfo info = serverListItem->accountInfo(); if (serverListItem->newAccount()) { Ruqola::self()->accountManager()->addAccount(info.accountName, info.userName, info.serverName, serverListItem->checkState() == Qt::Checked); } else { Ruqola::self()->accountManager()->modifyAccount(info.accountName, info.userName, info.serverName, serverListItem->checkState() == Qt::Checked); } } } void AccountServerListWidget::modifyAccountConfig() { QListWidgetItem *item = currentItem(); if (!item) { return; } auto *serverListItem = static_cast(item); QPointer dlg = new CreateNewAccountDialog(this); dlg->setAccountInfo(serverListItem->accountInfo()); if (dlg->exec()) { const CreateNewAccountDialog::AccountInfo info = dlg->accountInfo(); serverListItem->setAccountInfo(info); } } void AccountServerListWidget::deleteAccountConfig(QListWidgetItem *item) { mListRemovedAccount.append(item->text()); } void AccountServerListWidget::addAccountConfig() { QPointer dlg = new CreateNewAccountDialog(this); if (dlg->exec()) { CreateNewAccountDialog::AccountInfo info = dlg->accountInfo(); QStringList accountList; for (int i = 0; i < count(); ++i) { QListWidgetItem *it = item(i); accountList << it->text(); } QString newAccountName = info.accountName; int i = 1; while (accountList.contains(newAccountName)) { newAccountName = QStringLiteral("%1_%2").arg(newAccountName).arg(i); } info.accountName = newAccountName; auto *accountServeritem = new AccountServerListWidgetItem(this); accountServeritem->setCheckState(Qt::Checked); accountServeritem->setAccountInfo(info); accountServeritem->setNewAccount(true); } delete dlg; } AccountServerListWidgetItem::AccountServerListWidgetItem(QListWidget *parent) : QListWidgetItem(parent) { } AccountServerListWidgetItem::~AccountServerListWidgetItem() { } CreateNewAccountDialog::AccountInfo AccountServerListWidgetItem::accountInfo() const { return mInfo; } void AccountServerListWidgetItem::setAccountInfo(const CreateNewAccountDialog::AccountInfo &info) { mInfo = info; setText(info.accountName); } bool AccountServerListWidgetItem::newAccount() const { return mNewAccount; } void AccountServerListWidgetItem::setNewAccount(bool newAccount) { mNewAccount = newAccount; } diff --git a/src/widgets/configuredialog/autotests/configuresettingsdialogtest.cpp b/src/widgets/configuredialog/autotests/configuresettingsdialogtest.cpp index b3726bbc..f42706fe 100644 --- a/src/widgets/configuredialog/autotests/configuresettingsdialogtest.cpp +++ b/src/widgets/configuredialog/autotests/configuresettingsdialogtest.cpp @@ -1,38 +1,37 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "configuresettingsdialogtest.h" #include "configuredialog/configuresettingsdialog.h" -#include #include #include QTEST_MAIN(ConfigureSettingsDialogTest) ConfigureSettingsDialogTest::ConfigureSettingsDialogTest(QObject *parent) : QObject(parent) { QStandardPaths::setTestModeEnabled(true); } void ConfigureSettingsDialogTest::shouldHaveDefaultValues() { ConfigureSettingsDialog w; QVERIFY(!w.windowTitle().isEmpty()); } diff --git a/src/widgets/configuredialog/configureaccountwidget.cpp b/src/widgets/configuredialog/configureaccountwidget.cpp index aa74173d..275bfad9 100644 --- a/src/widgets/configuredialog/configureaccountwidget.cpp +++ b/src/widgets/configuredialog/configureaccountwidget.cpp @@ -1,50 +1,49 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "configureaccountserverwidget.h" #include "configureaccountwidget.h" #include -#include ConfigureAccountWidget::ConfigureAccountWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mConfigureAccountServerWidget = new ConfigureAccountServerWidget(this); mConfigureAccountServerWidget->setObjectName(QStringLiteral("mConfigureAccountServerWidget")); mainLayout->addWidget(mConfigureAccountServerWidget); } ConfigureAccountWidget::~ConfigureAccountWidget() { } void ConfigureAccountWidget::save() { mConfigureAccountServerWidget->save(); } void ConfigureAccountWidget::load() { mConfigureAccountServerWidget->load(); } diff --git a/src/widgets/configuredialog/configuresettingsdialog.cpp b/src/widgets/configuredialog/configuresettingsdialog.cpp index 2a2cbe8b..d3d53791 100644 --- a/src/widgets/configuredialog/configuresettingsdialog.cpp +++ b/src/widgets/configuredialog/configuresettingsdialog.cpp @@ -1,111 +1,110 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "configuresettingsdialog.h" #include "configureaccountwidget.h" #include "configurespellcheckingwidget.h" -#include #include #include #include #include #include #include #if HAVE_KUSERFEEDBACK #include "configureuserfeedbackwidget.h" #endif namespace { const char myConfigGroupName[] = "ConfigureSettingsDialog"; } ConfigureSettingsDialog::ConfigureSettingsDialog(QWidget *parent) : KPageDialog(parent) { setWindowTitle(i18nc("@title:window", "Configure Ruqola")); setFaceType(KPageDialog::List); buttonBox()->setStandardButtons(QDialogButtonBox::Ok| QDialogButtonBox::Cancel); const QString accountPageName = i18nc("@title Preferences page name", "Account"); mConfigureAccountWidget = new ConfigureAccountWidget(this); mConfigureAccountWidgetPage = new KPageWidgetItem(mConfigureAccountWidget, accountPageName); mConfigureAccountWidgetPage->setIcon(QIcon::fromTheme(QStringLiteral("network-workgroup"))); addPage(mConfigureAccountWidgetPage); const QString spellCheckingPageName = i18nc("@title Preferences page name", "Spell Checking"); mConfigureSpellCheckingWidget = new ConfigureSpellCheckingWidget(this); mConfigureSpellCheckingWidgetPage = new KPageWidgetItem(mConfigureSpellCheckingWidget, spellCheckingPageName); mConfigureSpellCheckingWidgetPage->setIcon(QIcon::fromTheme(QStringLiteral("tools-check-spelling"))); addPage(mConfigureSpellCheckingWidgetPage); #if HAVE_KUSERFEEDBACK const QString userFeedBackPageName = i18nc("@title Preferences page name", "User Feedback"); mConfigureUserFeedBackWidget = new ConfigureUserFeedbackWidget(this); mConfigureUserFeedBackWidgetPage = new KPageWidgetItem(mConfigureUserFeedBackWidget, userFeedBackPageName); mConfigureUserFeedBackWidgetPage->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-locale"))); addPage(mConfigureUserFeedBackWidgetPage); #endif connect(buttonBox()->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &ConfigureSettingsDialog::slotAccepted); connect(buttonBox()->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &ConfigureSettingsDialog::reject); readConfig(); load(); } ConfigureSettingsDialog::~ConfigureSettingsDialog() { writeConfig(); } void ConfigureSettingsDialog::readConfig() { KConfigGroup group(KSharedConfig::openConfig(), myConfigGroupName); const QSize sizeDialog = group.readEntry("Size", QSize(800, 600)); if (sizeDialog.isValid()) { resize(sizeDialog); } } void ConfigureSettingsDialog::writeConfig() { KConfigGroup group(KSharedConfig::openConfig(), myConfigGroupName); group.writeEntry("Size", size()); } void ConfigureSettingsDialog::slotAccepted() { mConfigureAccountWidget->save(); mConfigureSpellCheckingWidget->save(); #if HAVE_KUSERFEEDBACK mConfigureUserFeedBackWidget->save(); #endif } void ConfigureSettingsDialog::load() { mConfigureAccountWidget->load(); mConfigureSpellCheckingWidget->load(); #if HAVE_KUSERFEEDBACK mConfigureUserFeedBackWidget->load(); #endif } diff --git a/src/widgets/dialogs/adduserscompletionlineedit.cpp b/src/widgets/dialogs/adduserscompletionlineedit.cpp index d95ccf12..65572139 100644 --- a/src/widgets/dialogs/adduserscompletionlineedit.cpp +++ b/src/widgets/dialogs/adduserscompletionlineedit.cpp @@ -1,60 +1,59 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "adduserscompletionlineedit.h" #include "model/usercompleterfilterproxymodel.h" #include "ruqola.h" #include "rocketchataccount.h" #include "model/usercompletermodel.h" #include "common/completionlistview.h" -#include AddUsersCompletionLineEdit::AddUsersCompletionLineEdit(QWidget *parent) : CompletionLineEdit(parent) { connect(this, &QLineEdit::textChanged, this, &AddUsersCompletionLineEdit::slotTextChanged); setCompletionModel(Ruqola::self()->rocketChatAccount()->userCompleterFilterModelProxy()); connect(this, &AddUsersCompletionLineEdit::complete, this, &AddUsersCompletionLineEdit::slotComplete); } AddUsersCompletionLineEdit::~AddUsersCompletionLineEdit() { } void AddUsersCompletionLineEdit::slotTextChanged(const QString &text) { auto *rcAccount = Ruqola::self()->rocketChatAccount(); //Take text from ',' rcAccount->userAutocomplete(text, QString()); } void AddUsersCompletionLineEdit::slotComplete(const QModelIndex &index) { const QString completerName = index.data(UserCompleterModel::UserName).toString(); mCompletionListView->hide(); disconnect(this, &QLineEdit::textChanged, this, &AddUsersCompletionLineEdit::slotTextChanged); QString newText = completerName; if (!text().isEmpty()) { newText.prepend(QLatin1Char(',')); } insert(newText); connect(this, &QLineEdit::textChanged, this, &AddUsersCompletionLineEdit::slotTextChanged); } diff --git a/src/widgets/dialogs/addusersinroomwidget.cpp b/src/widgets/dialogs/addusersinroomwidget.cpp index a0761248..dd9bedd9 100644 --- a/src/widgets/dialogs/addusersinroomwidget.cpp +++ b/src/widgets/dialogs/addusersinroomwidget.cpp @@ -1,51 +1,49 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "adduserscompletionlineedit.h" #include "addusersinroomwidget.h" -#include -#include #include #include AddUsersInRoomWidget::AddUsersInRoomWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mSearchUserLineEdit = new AddUsersCompletionLineEdit(this); mSearchUserLineEdit->setObjectName(QStringLiteral("mSearchUserLineEdit")); mSearchUserLineEdit->setPlaceholderText(i18n("Search Users...")); connect(mSearchUserLineEdit, &AddUsersCompletionLineEdit::textChanged, this, &AddUsersInRoomWidget::slotSearchMessageTextChanged); mainLayout->addWidget(mSearchUserLineEdit); mainLayout->addStretch(1); } AddUsersInRoomWidget::~AddUsersInRoomWidget() { } void AddUsersInRoomWidget::slotSearchMessageTextChanged(const QString &str) { Q_EMIT updateOkButton(!str.trimmed().isEmpty()); } diff --git a/src/widgets/dialogs/autotests/channelinfowidgettest.cpp b/src/widgets/dialogs/autotests/channelinfowidgettest.cpp index 66f8ad7f..87aa07b9 100644 --- a/src/widgets/dialogs/autotests/channelinfowidgettest.cpp +++ b/src/widgets/dialogs/autotests/channelinfowidgettest.cpp @@ -1,114 +1,113 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelinfowidgettest.h" #include "dialogs/channelinfowidget.h" -#include #include #include #include #include #include #include #include QTEST_MAIN(ChannelInfoWidgetTest) ChannelInfoWidgetTest::ChannelInfoWidgetTest(QObject *parent) : QObject(parent) { } void ChannelInfoWidgetTest::shouldHaveDefaultValues() { ChannelInfoWidget w; auto *mainLayout = w.findChild(QStringLiteral("mainLayout")); QVERIFY(mainLayout); QCOMPARE(mainLayout->contentsMargins(), QMargins(0, 0, 0, 0)); auto *mStackedWidget = w.findChild(QStringLiteral("mStackedWidget")); QVERIFY(mStackedWidget); //Editable channel auto *mEditableChannel = w.findChild(QStringLiteral("mEditableChannel")); QVERIFY(mEditableChannel); auto *layout = mEditableChannel->findChild(QStringLiteral("layout")); QVERIFY(layout); QCOMPARE(layout->contentsMargins(), QMargins(0, 0, 0, 0)); auto *mComment = mEditableChannel->findChild(QStringLiteral("mComment")); QVERIFY(mComment); auto *mAnnouncement = mEditableChannel->findChild(QStringLiteral("mAnnouncement")); QVERIFY(mAnnouncement); auto *mDescription = mEditableChannel->findChild(QStringLiteral("mDescription")); QVERIFY(mDescription); auto *mPasswordLineEdit = mEditableChannel->findChild(QStringLiteral("mPasswordLineEdit")); QVERIFY(mPasswordLineEdit); auto *mArchive = mEditableChannel->findChild(QStringLiteral("mArchive")); QVERIFY(mArchive); QVERIFY(mArchive->text().isEmpty()); auto *mReadOnly = mEditableChannel->findChild(QStringLiteral("mReadOnly")); QVERIFY(mReadOnly); QVERIFY(mReadOnly->text().isEmpty()); auto *mPrivate = mEditableChannel->findChild(QStringLiteral("mPrivate")); QVERIFY(mPrivate); QVERIFY(mPrivate->text().isEmpty()); auto *mDeleteChannel = mEditableChannel->findChild(QStringLiteral("mDeleteChannel")); QVERIFY(mDeleteChannel); QVERIFY(!mDeleteChannel->text().isEmpty()); //ReadOnly Channel auto *mReadOnlyChannel = w.findChild(QStringLiteral("mReadOnlyChannel")); QVERIFY(mReadOnlyChannel); auto *layoutreadonly = mReadOnlyChannel->findChild(QStringLiteral("layoutReadOnly")); QVERIFY(layoutreadonly); QCOMPARE(layoutreadonly->contentsMargins(), QMargins(0, 0, 0, 0)); auto *mNameReadOnly = mReadOnlyChannel->findChild(QStringLiteral("mNameReadOnly")); QVERIFY(mNameReadOnly); QVERIFY(mNameReadOnly->text().isEmpty()); QCOMPARE(mNameReadOnly->textInteractionFlags(), Qt::TextBrowserInteraction); QCOMPARE(mNameReadOnly->textFormat(), Qt::RichText); auto *mCommentReadOnly = mReadOnlyChannel->findChild(QStringLiteral("mCommentReadOnly")); QVERIFY(mCommentReadOnly); QVERIFY(mCommentReadOnly->text().isEmpty()); QCOMPARE(mCommentReadOnly->textFormat(), Qt::RichText); QCOMPARE(mCommentReadOnly->textInteractionFlags(), Qt::TextBrowserInteraction); auto *mAnnouncementReadOnly = mReadOnlyChannel->findChild(QStringLiteral("mAnnouncementReadOnly")); QVERIFY(mAnnouncementReadOnly); QVERIFY(mAnnouncementReadOnly->text().isEmpty()); QCOMPARE(mAnnouncementReadOnly->textFormat(), Qt::RichText); QCOMPARE(mAnnouncementReadOnly->textInteractionFlags(), Qt::TextBrowserInteraction); auto *mDescriptionReadOnly = mReadOnlyChannel->findChild(QStringLiteral("mDescriptionReadOnly")); QVERIFY(mDescriptionReadOnly); QCOMPARE(mDescriptionReadOnly->textFormat(), Qt::RichText); QVERIFY(mDescriptionReadOnly->text().isEmpty()); QCOMPARE(mDescriptionReadOnly->textInteractionFlags(), Qt::TextBrowserInteraction); } diff --git a/src/widgets/dialogs/channelinfodialog.cpp b/src/widgets/dialogs/channelinfodialog.cpp index 760b3554..5076f35f 100644 --- a/src/widgets/dialogs/channelinfodialog.cpp +++ b/src/widgets/dialogs/channelinfodialog.cpp @@ -1,56 +1,55 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelinfodialog.h" #include "channelinfowidget.h" #include "roomwrapper.h" #include #include #include -#include ChannelInfoDialog::ChannelInfoDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(i18nc("@title:window", "Channel Info")); auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mChannelInfoWidget = new ChannelInfoWidget(this); mChannelInfoWidget->setObjectName(QStringLiteral("mChannelInfoWidget")); mainLayout->addWidget(mChannelInfoWidget); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close, this); connect(buttonBox, &QDialogButtonBox::rejected, this, &ChannelInfoDialog::reject); mainLayout->addWidget(buttonBox); resize(600, 400); connect(mChannelInfoWidget, &ChannelInfoWidget::channelDeleted, this, &ChannelInfoDialog::close); } ChannelInfoDialog::~ChannelInfoDialog() { } void ChannelInfoDialog::setRoomWrapper(RoomWrapper *roomWrapper) { setWindowTitle(i18nc("@title:window", "Channel Info about %1", roomWrapper->name())); mChannelInfoWidget->setRoomWrapper(roomWrapper); } diff --git a/src/widgets/dialogs/channelinfowidget.cpp b/src/widgets/dialogs/channelinfowidget.cpp index 176ab213..f512bb78 100644 --- a/src/widgets/dialogs/channelinfowidget.cpp +++ b/src/widgets/dialogs/channelinfowidget.cpp @@ -1,326 +1,327 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelinfowidget.h" #include "roomwrapper.h" #include "ruqola.h" #include "rocketchataccount.h" #include #include #include #include #include #include #include #include #include #include #include #include +#include ChannelInfoWidget::ChannelInfoWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mStackedWidget = new QStackedWidget(this); mStackedWidget->setObjectName(QStringLiteral("mStackedWidget")); mainLayout->addWidget(mStackedWidget); //Editable channel mEditableChannel = new QWidget(this); mEditableChannel->setObjectName(QStringLiteral("mEditableChannel")); mStackedWidget->addWidget(mEditableChannel); auto *layout = new QFormLayout(mEditableChannel); layout->setObjectName(QStringLiteral("layout")); layout->setContentsMargins(0, 0, 0, 0); QString str = i18n("Name:"); mName = new ChangeTextWidget(this); mName->setObjectName(QStringLiteral("mName")); connect(mName, &ChangeTextWidget::textChanged, this, [this](const QString &name) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Name, name, mRoomWrapper->channelType()); }); mName->setLabelText(str); layout->addRow(str, mName); mComment = new ChangeTextWidget(this); mComment->setObjectName(QStringLiteral("mComment")); str = i18n("Comment:"); mComment->setLabelText(str); layout->addRow(str, mComment); connect(mComment, &ChangeTextWidget::textChanged, this, [this](const QString &name) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Topic, name, mRoomWrapper->channelType()); }); mAnnouncement = new ChangeTextWidget(this); mAnnouncement->setObjectName(QStringLiteral("mAnnouncement")); connect(mAnnouncement, &ChangeTextWidget::textChanged, this, [this](const QString &name) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Announcement, name, mRoomWrapper->channelType()); }); str = i18n("Announcement:"); mAnnouncement->setLabelText(str); layout->addRow(str, mAnnouncement); mDescription = new ChangeTextWidget(this); mDescription->setObjectName(QStringLiteral("mDescription")); connect(mDescription, &ChangeTextWidget::textChanged, this, [this](const QString &name) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Description, name, mRoomWrapper->channelType()); }); str = i18n("Description:"); mDescription->setLabelText(str); layout->addRow(str, mDescription); mPasswordLineEdit = new KPasswordLineEdit(this); mPasswordLineEdit->setObjectName(QStringLiteral("mPasswordLineEdit")); layout->addRow(i18n("Password:"), mPasswordLineEdit); connect(mPasswordLineEdit, &KPasswordLineEdit::passwordChanged, this, [this](const QString &password) { //Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Password, password, mRoomWrapper->channelType()); }); mReadOnly = new QCheckBox(this); mReadOnly->setObjectName(QStringLiteral("mReadOnly")); layout->addRow(i18n("ReadOnly:"), mReadOnly); connect(mReadOnly, &QCheckBox::clicked, this, [this](bool checked) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::ReadOnly, checked, mRoomWrapper->channelType()); }); mArchive = new QCheckBox(this); mArchive->setObjectName(QStringLiteral("mArchive")); layout->addRow(i18n("Archive:"), mArchive); connect(mArchive, &QCheckBox::clicked, this, [this](bool checked) { const QString text = checked ? i18n("Do you want to archive this room?") : i18n("Do you want to unarchive this room?"); const QString title = checked ? i18n("Archive Channel") : i18n("Unarchive Channel"); if (KMessageBox::Yes == KMessageBox::questionYesNo(this, text, title)) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Archive, checked, mRoomWrapper->channelType()); } }); mPrivate = new QCheckBox(this); mPrivate->setObjectName(QStringLiteral("mPrivate")); layout->addRow(i18n("Private:"), mPrivate); connect(mPrivate, &QCheckBox::clicked, this, [this](bool checked) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::RoomType, checked, mRoomWrapper->channelType()); }); //TODO add encrypted too! mDeleteChannel = new QPushButton(QIcon::fromTheme(QStringLiteral("edit-delete-shred")), i18n("Delete"), this); mDeleteChannel->setObjectName(QStringLiteral("mDeleteChannel")); layout->addRow(QStringLiteral(" "), mDeleteChannel); connect(mDeleteChannel, &QPushButton::clicked, this, [this]() { if (KMessageBox::Yes == KMessageBox::questionYesNo(this, i18n("Do you want to delete this room?"), i18n("Delete Room"))) { Ruqola::self()->rocketChatAccount()->eraseRoom(mRoomWrapper->roomId(), mRoomWrapper->channelType()); Q_EMIT channelDeleted(); } }); //ReadOnly Channel mReadOnlyChannel = new QWidget(this); mReadOnlyChannel->setObjectName(QStringLiteral("mReadOnlyChannel")); mStackedWidget->addWidget(mReadOnlyChannel); auto *layoutReadOnly = new QFormLayout(mReadOnlyChannel); layoutReadOnly->setObjectName(QStringLiteral("layoutReadOnly")); layoutReadOnly->setContentsMargins(0, 0, 0, 0); mNameReadOnly = new QLabel(this); mNameReadOnly->setTextFormat(Qt::RichText); mNameReadOnly->setObjectName(QStringLiteral("mNameReadOnly")); mNameReadOnly->setTextInteractionFlags(Qt::TextBrowserInteraction); mNameReadOnly->setOpenExternalLinks(true); mNameReadOnly->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); layoutReadOnly->addRow(i18n("Name:"), mNameReadOnly); mCommentReadOnly = new QLabel(this); mCommentReadOnly->setTextFormat(Qt::RichText); mCommentReadOnly->setObjectName(QStringLiteral("mCommentReadOnly")); mCommentReadOnly->setTextInteractionFlags(Qt::TextBrowserInteraction); mCommentReadOnly->setOpenExternalLinks(true); mCommentReadOnly->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); layoutReadOnly->addRow(i18n("Comment:"), mCommentReadOnly); mAnnouncementReadOnly = new QLabel(this); mAnnouncementReadOnly->setTextFormat(Qt::RichText); mAnnouncementReadOnly->setObjectName(QStringLiteral("mAnnouncementReadOnly")); mAnnouncementReadOnly->setTextInteractionFlags(Qt::TextBrowserInteraction); mAnnouncementReadOnly->setOpenExternalLinks(true); mAnnouncementReadOnly->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); layoutReadOnly->addRow(i18n("Announcement:"), mAnnouncementReadOnly); mDescriptionReadOnly = new QLabel(this); mDescriptionReadOnly->setTextFormat(Qt::RichText); mDescriptionReadOnly->setObjectName(QStringLiteral("mDescriptionReadOnly")); mDescriptionReadOnly->setTextInteractionFlags(Qt::TextBrowserInteraction); mDescriptionReadOnly->setOpenExternalLinks(true); mDescriptionReadOnly->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); layoutReadOnly->addRow(i18n("Description:"), mDescriptionReadOnly); } ChannelInfoWidget::~ChannelInfoWidget() { } void ChannelInfoWidget::setRoomWrapper(RoomWrapper *roomWrapper) { mRoomWrapper = roomWrapper; if (mRoomWrapper->canBeModify()) { mStackedWidget->setCurrentWidget(mEditableChannel); updateEditableChannelInfo(); connectReadOnlyWidget(); } else { mStackedWidget->setCurrentWidget(mReadOnlyChannel); updateReadOnlyChannelInfo(); connectReadOnlyWidget(); } } void ChannelInfoWidget::updateReadOnlyChannelInfo() { mNameReadOnly->setText(mRoomWrapper->name()); mCommentReadOnly->setText(mRoomWrapper->topic()); mAnnouncementReadOnly->setText(mRoomWrapper->announcement()); mDescriptionReadOnly->setText(mRoomWrapper->description()); } void ChannelInfoWidget::updateEditableChannelInfo() { mName->setText(mRoomWrapper->name()); mComment->setText(mRoomWrapper->topic()); mAnnouncement->setText(mRoomWrapper->announcement()); mDescription->setText(mRoomWrapper->description()); mReadOnly->setChecked(mRoomWrapper->readOnly()); mArchive->setChecked(mRoomWrapper->archived()); mPrivate->setChecked(mRoomWrapper->channelType() == QStringLiteral("p")); joinCodeChanged(); } void ChannelInfoWidget::joinCodeChanged() { mPasswordLineEdit->lineEdit()->setPlaceholderText(mRoomWrapper->joinCodeRequired() ? i18n("This Room has a password") : i18n("Add password")); } void ChannelInfoWidget::connectReadOnlyWidget() { connect(mRoomWrapper, &RoomWrapper::announcementChanged, this, [this]() { mAnnouncementReadOnly->setText(mRoomWrapper->announcement()); }); connect(mRoomWrapper, &RoomWrapper::topicChanged, this, [this]() { mCommentReadOnly->setText(mRoomWrapper->topic()); }); connect(mRoomWrapper, &RoomWrapper::nameChanged, this, [this]() { mNameReadOnly->setText(mRoomWrapper->name()); }); connect(mRoomWrapper, &RoomWrapper::descriptionChanged, this, [this]() { mDescriptionReadOnly->setText(mRoomWrapper->description()); }); } void ChannelInfoWidget::connectEditableWidget() { connect(mRoomWrapper, &RoomWrapper::announcementChanged, this, [this]() { mAnnouncement->setText(mRoomWrapper->announcement()); }); connect(mRoomWrapper, &RoomWrapper::topicChanged, this, [this]() { mComment->setText(mRoomWrapper->topic()); }); connect(mRoomWrapper, &RoomWrapper::nameChanged, this, [this]() { mName->setText(mRoomWrapper->name()); }); connect(mRoomWrapper, &RoomWrapper::descriptionChanged, this, [this]() { mDescription->setText(mRoomWrapper->description()); }); connect(mRoomWrapper, &RoomWrapper::readOnlyChanged, this, [this]() { mReadOnly->setChecked(mRoomWrapper->readOnly()); }); connect(mRoomWrapper, &RoomWrapper::archivedChanged, this, [this]() { mArchive->setChecked(mRoomWrapper->archived()); }); connect(mRoomWrapper, &RoomWrapper::joinCodeRequiredChanged, this, [this]() { joinCodeChanged(); }); connect(mRoomWrapper, &RoomWrapper::channelTypeChanged, this, [this]() { mPrivate->setChecked(mRoomWrapper->channelType() == QStringLiteral("p")); }); //TODO react when we change settings connect(mReadOnly, &QCheckBox::clicked, this, [this](bool checked) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::ReadOnly, checked, mRoomWrapper->channelType()); }); connect(mArchive, &QCheckBox::clicked, this, [this](bool checked) { if (KMessageBox::Yes == KMessageBox::questionYesNo(this, checked ? i18n("Do you want to archive this room?") : i18n("Do you want to unarchive this room?"), i18n("Archive room"))) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::Archive, checked, mRoomWrapper->channelType()); } }); connect(mPrivate, &QCheckBox::clicked, this, [this](bool checked) { Ruqola::self()->rocketChatAccount()->changeChannelSettings(mRoomWrapper->roomId(), RocketChatAccount::RoomType, checked, mRoomWrapper->channelType()); }); } ChangeTextWidget::ChangeTextWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mLabel = new QLabel(this); mLabel->setObjectName(QStringLiteral("mLabel")); mLabel->setWordWrap(true); mLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); mLabel->setOpenExternalLinks(true); mLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); mainLayout->addWidget(mLabel); mChangeTextToolButton = new QToolButton(this); mChangeTextToolButton->setIcon(QIcon::fromTheme(QStringLiteral("document-edit"))); mChangeTextToolButton->setObjectName(QStringLiteral("mChangeTextToolButton")); mainLayout->addWidget(mChangeTextToolButton); connect(mChangeTextToolButton, &QToolButton::clicked, this, [this]() { //Convert html to text. Otherwise we will have html tag QString text = mLabel->text(); QTextDocument doc; doc.setHtml(text); text = doc.toPlainText(); const QString result = QInputDialog::getText(this, i18n("Change Text"), mLabelText, QLineEdit::Normal, text); if (!result.trimmed().isEmpty()) { if (result != text) { Q_EMIT textChanged(result); } } }); } ChangeTextWidget::~ChangeTextWidget() { } void ChangeTextWidget::setText(const QString &str) { mLabel->setText(str); } void ChangeTextWidget::setLabelText(const QString &str) { mLabelText = str; } diff --git a/src/widgets/dialogs/channelpasswordwidget.cpp b/src/widgets/dialogs/channelpasswordwidget.cpp index 004f4410..069d792f 100644 --- a/src/widgets/dialogs/channelpasswordwidget.cpp +++ b/src/widgets/dialogs/channelpasswordwidget.cpp @@ -1,50 +1,50 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "channelpasswordwidget.h" -#include #include #include +#include #include ChannelPasswordWidget::ChannelPasswordWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); QLabel *label = new QLabel(i18n("Channel Password:"), this); label->setObjectName(QStringLiteral("label")); mainLayout->addWidget(label); mPasswordLineEdit = new KPasswordLineEdit(this); mPasswordLineEdit->setObjectName(QStringLiteral("mPasswordLineEdit")); mainLayout->addWidget(mPasswordLineEdit); } ChannelPasswordWidget::~ChannelPasswordWidget() { } QString ChannelPasswordWidget::password() const { return mPasswordLineEdit->password(); } diff --git a/src/widgets/dialogs/createnewaccountwidget.cpp b/src/widgets/dialogs/createnewaccountwidget.cpp index 5bf51514..9032e792 100644 --- a/src/widgets/dialogs/createnewaccountwidget.cpp +++ b/src/widgets/dialogs/createnewaccountwidget.cpp @@ -1,98 +1,97 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "createnewaccountwidget.h" #include #include -#include #include CreateNewAccountWidget::CreateNewAccountWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QFormLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mAccountName = new QLineEdit(this); mAccountName->setObjectName(QStringLiteral("mAccountName")); mAccountName->setClearButtonEnabled(true); mainLayout->addRow(i18n("Account Name:"), mAccountName); mServerName = new QLineEdit(this); mServerName->setObjectName(QStringLiteral("mServerName")); mServerName->setClearButtonEnabled(true); mainLayout->addRow(i18n("Server Name:"), mServerName); mUserName = new QLineEdit(this); mUserName->setObjectName(QStringLiteral("mUserName")); mUserName->setClearButtonEnabled(true); mainLayout->addRow(i18n("User Name:"), mUserName); connect(mUserName, &QLineEdit::textChanged, this, &CreateNewAccountWidget::slotChangeOkButtonEnabled); connect(mServerName, &QLineEdit::textChanged, this, &CreateNewAccountWidget::slotChangeOkButtonEnabled); connect(mAccountName, &QLineEdit::textChanged, this, &CreateNewAccountWidget::slotChangeOkButtonEnabled); //TODO add support for two factor ? } CreateNewAccountWidget::~CreateNewAccountWidget() { } QString CreateNewAccountWidget::accountName() const { return mAccountName->text().trimmed(); } QString CreateNewAccountWidget::serverName() const { return mServerName->text().trimmed(); } void CreateNewAccountWidget::setAccountName(const QString &name) { mAccountName->setText(name); mAccountName->setReadOnly(true); } void CreateNewAccountWidget::setUserName(const QString &username) { mUserName->setText(username); } void CreateNewAccountWidget::setServerName(const QString &servername) { mServerName->setText(servername); } QString CreateNewAccountWidget::userName() const { return mUserName->text().trimmed(); } void CreateNewAccountWidget::slotChangeOkButtonEnabled() { Q_EMIT updateOkButton(!mAccountName->text().trimmed().isEmpty() && !mServerName->text().trimmed().isEmpty() && !mUserName->text().trimmed().isEmpty()); } diff --git a/src/widgets/dialogs/reportmessagewidget.cpp b/src/widgets/dialogs/reportmessagewidget.cpp index 7a0e6b01..2b7383cc 100644 --- a/src/widgets/dialogs/reportmessagewidget.cpp +++ b/src/widgets/dialogs/reportmessagewidget.cpp @@ -1,57 +1,57 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "reportmessagewidget.h" -#include #include #include +#include #include ReportMessageWidget::ReportMessageWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); QLabel *lab = new QLabel(i18n("Message:"), this); lab->setObjectName(QStringLiteral("label")); mainLayout->addWidget(lab); mMessageLineEdit = new QLineEdit(this); mMessageLineEdit->setObjectName(QStringLiteral("mMessageLineEdit")); mMessageLineEdit->setClearButtonEnabled(true); mMessageLineEdit->setPlaceholderText(i18n("Why you signal this message?")); mainLayout->addWidget(mMessageLineEdit); connect(mMessageLineEdit, &QLineEdit::textChanged, this, [this]() { Q_EMIT updateOkButton(!mMessageLineEdit->text().trimmed().isEmpty()); }); } ReportMessageWidget::~ReportMessageWidget() { } QString ReportMessageWidget::message() const { return mMessageLineEdit->text(); } diff --git a/src/widgets/dialogs/searchmessagewidget.cpp b/src/widgets/dialogs/searchmessagewidget.cpp index ba0abc37..c47aa647 100644 --- a/src/widgets/dialogs/searchmessagewidget.cpp +++ b/src/widgets/dialogs/searchmessagewidget.cpp @@ -1,70 +1,69 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ruqola.h" #include "rocketchataccount.h" #include "searchmessagewidget.h" #include "room/messagelistview.h" #include "model/searchmessagefilterproxymodel.h" #include #include -#include #include SearchMessageWidget::SearchMessageWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mSearchLineEdit = new KLineEdit(this); mSearchLineEdit->setObjectName(QStringLiteral("mSearchLineEdit")); mSearchLineEdit->setClearButtonEnabled(true); mSearchLineEdit->setTrapReturnKey(true); mSearchLineEdit->setPlaceholderText(i18n("Search Word... (You can use regular expression as /^text$/i)")); mainLayout->addWidget(mSearchLineEdit); mResultListWidget = new MessageListView(this); mResultListWidget->setMode(MessageListView::Mode::Viewing); mResultListWidget->setObjectName(QStringLiteral("mResultListWidget")); mainLayout->addWidget(mResultListWidget); connect(mSearchLineEdit, &QLineEdit::returnPressed, this, &SearchMessageWidget::slotSearchMessages); mResultListWidget->setModel(Ruqola::self()->rocketChatAccount()->searchMessageFilterProxyModel()); } SearchMessageWidget::~SearchMessageWidget() { } void SearchMessageWidget::slotSearchMessages() { Ruqola::self()->rocketChatAccount()->messageSearch(mSearchLineEdit->text(), mRoomId); } QString SearchMessageWidget::roomId() const { return mRoomId; } void SearchMessageWidget::setRoomId(const QString &roomId) { mRoomId = roomId; } diff --git a/src/widgets/dialogs/showlistmessagebasedialog.cpp b/src/widgets/dialogs/showlistmessagebasedialog.cpp index d6442b38..869f8daf 100644 --- a/src/widgets/dialogs/showlistmessagebasedialog.cpp +++ b/src/widgets/dialogs/showlistmessagebasedialog.cpp @@ -1,73 +1,72 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "showlistmessagebasedialog.h" #include "showlistmessagebasewidget.h" #include "ruqolawidgets_debug.h" #include "ruqola.h" #include "rocketchataccount.h" #include -#include #include ShowListMessageBaseDialog::ShowListMessageBaseDialog(QWidget *parent) : QDialog(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mShowListMessage = new ShowListMessageBaseWidget(this); mShowListMessage->setObjectName(QStringLiteral("mShowListMessage")); mainLayout->addWidget(mShowListMessage); QDialogButtonBox *button = new QDialogButtonBox(QDialogButtonBox::Close, this); button->setObjectName(QStringLiteral("button")); mainLayout->addWidget(button); connect(button, &QDialogButtonBox::rejected, this, &ShowListMessageBaseDialog::reject); connect(mShowListMessage, &ShowListMessageBaseWidget::loadMoreElements, this, &ShowListMessageBaseDialog::slotLoadMoreMessages); } ShowListMessageBaseDialog::~ShowListMessageBaseDialog() { } void ShowListMessageBaseDialog::slotLoadMoreMessages() { if (mRoomId.isEmpty()) { qCWarning(RUQOLAWIDGETS_LOG) << "RoomId is empty. It's a bug"; return; } Ruqola::self()->rocketChatAccount()->loadMoreListMessages(roomId()); } void ShowListMessageBaseDialog::setModel(ListMessagesModelFilterProxyModel *model) { mShowListMessage->setModel(model); } void ShowListMessageBaseDialog::setRoomId(const QString &roomId) { mRoomId = roomId; } QString ShowListMessageBaseDialog::roomId() const { return mRoomId; } diff --git a/src/widgets/dialogs/takevideomessagewidget.cpp b/src/widgets/dialogs/takevideomessagewidget.cpp index 3fd4f95d..b58e168f 100644 --- a/src/widgets/dialogs/takevideomessagewidget.cpp +++ b/src/widgets/dialogs/takevideomessagewidget.cpp @@ -1,34 +1,31 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "takevideomessagewidget.h" -#include -#include -#include TakeVideoMessageWidget::TakeVideoMessageWidget(QWidget *parent) : QWidget(parent) { } TakeVideoMessageWidget::~TakeVideoMessageWidget() { } diff --git a/src/widgets/room/messagedelegatehelperreactions.cpp b/src/widgets/room/messagedelegatehelperreactions.cpp index e7828148..2f2f0ac0 100644 --- a/src/widgets/room/messagedelegatehelperreactions.cpp +++ b/src/widgets/room/messagedelegatehelperreactions.cpp @@ -1,163 +1,161 @@ /* Copyright (c) 2020 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagedelegatehelperreactions.h" #include #include "rocketchataccount.h" #include "ruqola.h" #include "ruqolautils.h" #include "emoticons/emojimanager.h" #include "emoticons/unicodeemoticon.h" #include -#include -#include #include #include #include #include constexpr const qreal margin = 8; MessageDelegateHelperReactions::MessageDelegateHelperReactions() : mEmojiFont(QStringLiteral("NotoColorEmoji")) { } QVector MessageDelegateHelperReactions::layoutReactions(const QVector &reactions, const QRect &reactionsRect, const QStyleOptionViewItem &option) const { QVector layouts; layouts.reserve(reactions.count()); auto *emojiManager = Ruqola::self()->rocketChatAccount()->emojiManager(); QFontMetricsF emojiFontMetrics(mEmojiFont); const qreal smallMargin = margin/2.0; qreal x = reactionsRect.x(); for (const Reaction &reaction : reactions) { ReactionLayout layout; layout.emojiString = emojiManager->unicodeEmoticonForEmoji(reaction.reactionName()).unicode(); qreal emojiWidth; if (layout.emojiString.isEmpty()) { layout.emojiString = reaction.reactionName(); // ugly fallback: ":1md" emojiWidth = option.fontMetrics.horizontalAdvance(layout.emojiString) + smallMargin; layout.useEmojiFont = false; } else { emojiWidth = emojiFontMetrics.horizontalAdvance(layout.emojiString); layout.useEmojiFont = true; } layout.countStr = QString::number(reaction.count()); const int countWidth = option.fontMetrics.horizontalAdvance(layout.countStr) + smallMargin; layout.reactionRect = QRectF(x, reactionsRect.y(), emojiWidth + countWidth + margin, reactionsRect.height()); layout.emojiOffset = smallMargin + 1; layout.countRect = layout.reactionRect.adjusted(layout.emojiOffset + emojiWidth, smallMargin, 0, 0); layout.reaction = reaction; layouts.append(layout); x += layout.reactionRect.width() + margin; } return layouts; } void MessageDelegateHelperReactions::draw(QPainter *painter, const QRect &reactionsRect, const QModelIndex &index, const QStyleOptionViewItem &option) const { const Message *message = index.data(MessageModel::MessagePointer).value(); const QVector reactions = message->reactions().reactions(); if (reactions.isEmpty()) { return; } const QVector layouts = layoutReactions(reactions, reactionsRect, option); const QPen origPen = painter->pen(); const QBrush origBrush = painter->brush(); const QPen buttonPen(option.palette.color(QPalette::Highlight).darker()); QColor backgroundColor = option.palette.color(QPalette::Highlight); backgroundColor.setAlpha(60); const QBrush buttonBrush(backgroundColor); const qreal smallMargin = 4; for (const ReactionLayout &reactionLayout : layouts) { if (!reactionLayout.emojiString.isEmpty()) { const QRectF reactionRect = reactionLayout.reactionRect; // Rounded rect painter->setPen(buttonPen); painter->setBrush(buttonBrush); painter->drawRoundedRect(reactionRect, 5, 5); painter->setBrush(origBrush); painter->setPen(origPen); // Emoji if (reactionLayout.useEmojiFont) { painter->setFont(mEmojiFont); } painter->drawText(reactionRect.adjusted(reactionLayout.emojiOffset, smallMargin, 0, 0), reactionLayout.emojiString); // Count painter->setFont(option.font); painter->drawText(reactionLayout.countRect, reactionLayout.countStr); } } } QSize MessageDelegateHelperReactions::sizeHint(const QModelIndex &index, int maxWidth, const QStyleOptionViewItem &option) const { const Message *message = index.data(MessageModel::MessagePointer).value(); int reactionsHeight = 0; const QVector reactions = message->reactions().reactions(); if (!reactions.isEmpty()) { QFontMetrics emojiFontMetrics(mEmojiFont); reactionsHeight = qMax(emojiFontMetrics.height(), option.fontMetrics.height()) + margin; } return QSize(maxWidth, reactionsHeight); } bool MessageDelegateHelperReactions::handleMouseEvent(QMouseEvent *mouseEvent, const QRect &reactionsRect, const QStyleOptionViewItem &option, const Message *message) { if (mouseEvent->type() == QEvent::MouseButtonRelease) { const QPoint pos = mouseEvent->pos(); const QVector reactions = layoutReactions(message->reactions().reactions(), reactionsRect, option); for (const ReactionLayout &reactionLayout : reactions) { if (reactionLayout.reactionRect.contains(pos)) { const Reaction &reaction = reactionLayout.reaction; auto *rcAccount = Ruqola::self()->rocketChatAccount(); const bool doAdd = !reaction.userNames().contains(rcAccount->userName()); rcAccount->reactOnMessage(message->messageId(), reaction.reactionName(), doAdd); return true; } } } return false; } bool MessageDelegateHelperReactions::handleHelpEvent(QHelpEvent *helpEvent, QWidget *view, const QRect &reactionsRect, const QStyleOptionViewItem &option, const Message *message) { const QVector reactions = layoutReactions(message->reactions().reactions(), reactionsRect, option); for (const ReactionLayout &reactionLayout : reactions) { if (reactionLayout.reactionRect.contains(helpEvent->pos())) { const Reaction &reaction = reactionLayout.reaction; const QString tooltip = reaction.convertedUsersNameAtToolTip(); QToolTip::showText(helpEvent->globalPos(), tooltip, view); return true; } } return false; } diff --git a/src/widgets/room/messagetextedit.cpp b/src/widgets/room/messagetextedit.cpp index 93aa2bc4..cff35780 100644 --- a/src/widgets/room/messagetextedit.cpp +++ b/src/widgets/room/messagetextedit.cpp @@ -1,130 +1,125 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagetextedit.h" #include "rocketchataccount.h" #include "model/inputcompletermodel.h" #include "common/completionlistview.h" #include "ruqola.h" #include #include -#include -#include -#include #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -#include -#include #endif MessageTextEdit::MessageTextEdit(QWidget *parent) : CompletionTextEdit(parent) { connect(this, &QTextEdit::textChanged, this, &MessageTextEdit::slotTextChanged); setCompletionModel(Ruqola::self()->rocketChatAccount()->inputTextManager()->inputCompleterModel()); connect(this, &MessageTextEdit::complete, this, &MessageTextEdit::slotComplete); setAcceptRichText(false); connect(document()->documentLayout(), &QAbstractTextDocumentLayout::documentSizeChanged, this, &QWidget::updateGeometry); } MessageTextEdit::~MessageTextEdit() { disconnect(this, &QTextEdit::textChanged, this, &MessageTextEdit::slotTextChanged); } void MessageTextEdit::insert(const QString &text) { textCursor().insertText(text); } QString MessageTextEdit::text() const { return toPlainText(); } QSize MessageTextEdit::sizeHint() const { const QSize docSize = document()->size().toSize(); const int margin = int(document()->documentMargin()); return QSize(docSize.width() + margin, qMin(300, docSize.height()) + margin); } QSize MessageTextEdit::minimumSizeHint() const { return sizeHint(); } void MessageTextEdit::keyPressEvent(QKeyEvent *e) { const int key = e->key(); if (key == Qt::Key_Return || key == Qt::Key_Enter) { if ((key == Qt::Key_Enter && (e->modifiers() == Qt::KeypadModifier)) || !e->modifiers()) { Q_EMIT sendMessage(text()); clear(); } else { textCursor().insertBlock(); ensureCursorVisible(); } e->accept(); return; } else if (key == Qt::Key_Up || key == Qt::Key_Down) { if (document()->lineCount() > 1) { CompletionTextEdit::keyPressEvent(e); return; } } e->ignore(); // Check if the listview or room widget want to handle the key (e.g Esc, PageUp) Q_EMIT keyPressed(e); if (e->isAccepted()) { return; } CompletionTextEdit::keyPressEvent(e); } void MessageTextEdit::slotTextChanged() { auto *rcAccount = Ruqola::self()->rocketChatAccount(); rcAccount->inputTextManager()->setInputTextChanged(text(), textCursor().position()); Q_EMIT textEditing(document()->isEmpty()); } void MessageTextEdit::slotComplete(const QModelIndex &index) { const QString completerName = index.data(InputCompleterModel::CompleterName).toString(); auto *inputTextManager = Ruqola::self()->rocketChatAccount()->inputTextManager(); QTextCursor cursor = textCursor(); int textPos = cursor.position(); const QString newText = inputTextManager->applyCompletion(completerName + QLatin1Char(' '), text(), &textPos); mCompletionListView->hide(); disconnect(this, &QTextEdit::textChanged, this, &MessageTextEdit::slotTextChanged); setPlainText(newText); connect(this, &QTextEdit::textChanged, this, &MessageTextEdit::slotTextChanged); cursor.setPosition(textPos); setTextCursor(cursor); } diff --git a/src/widgets/room/readonlylineeditwidget.cpp b/src/widgets/room/readonlylineeditwidget.cpp index edeec3e0..96ed3b2e 100644 --- a/src/widgets/room/readonlylineeditwidget.cpp +++ b/src/widgets/room/readonlylineeditwidget.cpp @@ -1,48 +1,47 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "readonlylineeditwidget.h" #include #include -#include ReadOnlyLineEditWidget::ReadOnlyLineEditWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mLabel = new QLabel(this); mLabel->setObjectName(QStringLiteral("label")); mainLayout->addWidget(mLabel); QFont font = mLabel->font(); font.setBold(true); font.setItalic(true); mLabel->setFont(font); } ReadOnlyLineEditWidget::~ReadOnlyLineEditWidget() { } void ReadOnlyLineEditWidget::setMessage(const QString &str) { mLabel->setText(str); } diff --git a/src/widgets/room/roomheaderwidget.cpp b/src/widgets/room/roomheaderwidget.cpp index b9b456ff..baab1f6c 100644 --- a/src/widgets/room/roomheaderwidget.cpp +++ b/src/widgets/room/roomheaderwidget.cpp @@ -1,144 +1,143 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "roomheaderwidget.h" #include "ruqolawidgets_debug.h" #include -#include #include #include RoomHeaderWidget::RoomHeaderWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); auto *headerLayout = new QHBoxLayout; headerLayout->setObjectName(QStringLiteral("headerLayout")); headerLayout->setContentsMargins(0, 0, 0, 0); mainLayout->addLayout(headerLayout); mFavoriteButton = new QToolButton(this); mFavoriteButton->setObjectName(QStringLiteral("mFavoriteButton")); mFavoriteButton->setIcon(QIcon::fromTheme(QStringLiteral("favorite"))); mFavoriteButton->setCheckable(true); headerLayout->addWidget(mFavoriteButton, Qt::AlignTop); connect(mFavoriteButton, &QToolButton::clicked, this, &RoomHeaderWidget::favoriteChanged); mDiscussionBackButton = new QToolButton(this); mDiscussionBackButton->setObjectName(QStringLiteral("mDiscussionBackButton")); mDiscussionBackButton->setIcon(QIcon::fromTheme(QStringLiteral("draw-arrow-back"))); mDiscussionBackButton->setCheckable(false); headerLayout->addWidget(mDiscussionBackButton, Qt::AlignTop); connect(mDiscussionBackButton, &QToolButton::clicked, this, &RoomHeaderWidget::goBackToRoom); mDiscussionBackButton->setVisible(false); mEncryptedButton = new QToolButton(this); mEncryptedButton->setObjectName(QStringLiteral("mEncryptedButton")); mEncryptedButton->setIcon(QIcon::fromTheme(QStringLiteral("encrypted"))); mEncryptedButton->setCheckable(true); mEncryptedButton->setVisible(false); headerLayout->addWidget(mEncryptedButton, Qt::AlignTop); connect(mEncryptedButton, &QToolButton::clicked, this, &RoomHeaderWidget::encryptedChanged); auto *infoLayout = new QVBoxLayout; infoLayout->setObjectName(QStringLiteral("infoLayout")); infoLayout->setContentsMargins(0, 0, 0, 0); headerLayout->addLayout(infoLayout); mRoomName = new QLabel(this); mRoomName->setObjectName(QStringLiteral("mRoomName")); mRoomName->setTextInteractionFlags(Qt::TextBrowserInteraction); infoLayout->addWidget(mRoomName); mRoomName->setVisible(false); mTopic = new QLabel(this); mTopic->setObjectName(QStringLiteral("mTopic")); infoLayout->addWidget(mTopic); mTopic->setWordWrap(true); mTopic->setOpenExternalLinks(true); mTopic->setTextInteractionFlags(Qt::TextBrowserInteraction); mTopic->setTextFormat(Qt::RichText); mTopic->setVisible(false); mAnnouncement = new QLabel(this); mAnnouncement->setObjectName(QStringLiteral("mAnnouncement")); mAnnouncement->setWordWrap(true); mAnnouncement->setTextFormat(Qt::RichText); infoLayout->addWidget(mAnnouncement); mAnnouncement->setOpenExternalLinks(true); mAnnouncement->setTextInteractionFlags(Qt::TextBrowserInteraction); mAnnouncement->setVisible(false); mDescription = new QLabel(this); mDescription->setObjectName(QStringLiteral("mDescription")); mDescription->setTextFormat(Qt::RichText); mDescription->setWordWrap(true); infoLayout->addWidget(mDescription); mDescription->setOpenExternalLinks(true); mDescription->setTextInteractionFlags(Qt::TextBrowserInteraction); mDescription->setVisible(false); } RoomHeaderWidget::~RoomHeaderWidget() { } void RoomHeaderWidget::setRoomName(const QString &name) { mRoomName->setText(name); mRoomName->setVisible(!name.isEmpty()); } QString RoomHeaderWidget::roomName() const { return mRoomName->text(); } void RoomHeaderWidget::setRoomAnnouncement(const QString &name) { mAnnouncement->setText(name); mAnnouncement->setVisible(!name.isEmpty()); } void RoomHeaderWidget::setRoomTopic(const QString &name) { mTopic->setText(name); mTopic->setVisible(!name.isEmpty()); } void RoomHeaderWidget::setFavoriteStatus(bool b) { mFavoriteButton->setChecked(b); } void RoomHeaderWidget::setEncypted(bool b) { mEncryptedButton->setChecked(b); mEncryptedButton->setVisible(b); } void RoomHeaderWidget::setIsDiscussion(bool isDiscussion) { mFavoriteButton->setVisible(!isDiscussion); mDiscussionBackButton->setVisible(isDiscussion); } diff --git a/src/widgets/room/roomwidget.cpp b/src/widgets/room/roomwidget.cpp index 98ac4d47..0d9f1a97 100644 --- a/src/widgets/room/roomwidget.cpp +++ b/src/widgets/room/roomwidget.cpp @@ -1,294 +1,291 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "roomwidget.h" #include "roomheaderwidget.h" #include "messagelistview.h" #include "messagelinewidget.h" #include "ruqola.h" #include "rocketchataccount.h" #include "roomwrapper.h" #include "readonlylineeditwidget.h" #include "messagetextedit.h" #include "ruqolawidgets_debug.h" #include "model/roommodel.h" #include "dialogs/createnewdiscussiondialog.h" -#include - +#include #include -#include -#include #include #include #include RoomWidget::RoomWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QVBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainLayout")); mainLayout->setContentsMargins(0, 0, 0, 0); mRoomHeaderWidget = new RoomHeaderWidget(this); mRoomHeaderWidget->setObjectName(QStringLiteral("mRoomHeaderWidget")); mainLayout->addWidget(mRoomHeaderWidget); mMessageListView = new MessageListView(this); mMessageListView->setObjectName(QStringLiteral("mMessageListView")); mainLayout->addWidget(mMessageListView, 1); mStackedWidget = new QStackedWidget(this); mStackedWidget->setObjectName(QStringLiteral("mStackedWidget")); mainLayout->addWidget(mStackedWidget); mMessageLineWidget = new MessageLineWidget(this); mMessageLineWidget->setObjectName(QStringLiteral("mMessageLineWidget")); mStackedWidget->addWidget(mMessageLineWidget); mReadOnlyLineEditWidget = new ReadOnlyLineEditWidget(this); mReadOnlyLineEditWidget->setObjectName(QStringLiteral("mReadOnlyLineEditWidget")); mStackedWidget->addWidget(mReadOnlyLineEditWidget); mStackedWidget->setCurrentWidget(mMessageLineWidget); connect(this, &RoomWidget::channelSelected, this, &RoomWidget::setChannelSelected); connect(mMessageLineWidget, &MessageLineWidget::sendMessage, this, &RoomWidget::slotSendMessage); connect(mMessageLineWidget, &MessageLineWidget::sendFile, this, &RoomWidget::slotSendFile); connect(mMessageLineWidget, &MessageLineWidget::textEditing, this, &RoomWidget::slotTextEditing); connect(mMessageLineWidget->messageTextEdit(), &MessageTextEdit::keyPressed, this, &RoomWidget::keyPressedInLineEdit); connect(mRoomHeaderWidget, &RoomHeaderWidget::favoriteChanged, this, &RoomWidget::slotChangeFavorite); connect(mRoomHeaderWidget, &RoomHeaderWidget::encryptedChanged, this, &RoomWidget::slotEncryptedChanged); connect(mRoomHeaderWidget, &RoomHeaderWidget::goBackToRoom, this, &RoomWidget::slotGoBackToRoom); connect(mMessageListView, &MessageListView::editMessageRequested, this, &RoomWidget::slotEditMessage); connect(mMessageListView, &MessageListView::createNewDiscussion, this, &RoomWidget::slotCreateNewDiscussion); setAcceptDrops(true); } RoomWidget::~RoomWidget() { delete mRoomWrapper; } void RoomWidget::slotCreateNewDiscussion(const QString &messageId, const QString &originalMessage) { QPointer dlg = new CreateNewDiscussionDialog(this); dlg->setDiscussionName(originalMessage); dlg->setChannelName(mRoomHeaderWidget->roomName()); if (dlg->exec()) { auto *rcAccount = Ruqola::self()->rocketChatAccount(); const CreateNewDiscussionDialog::NewDiscussionInfo info = dlg->newDiscussionInfo(); rcAccount->createDiscussion(mRoomId, info.discussionName, info.message, messageId, info.users); } delete dlg; } void RoomWidget::slotTextEditing(bool clearNotification) { mCurrentRocketChatAccount->textEditing(mRoomId, clearNotification); } void RoomWidget::slotSendFile(const UploadFileDialog::UploadFileInfo &uploadFileInfo) { mCurrentRocketChatAccount->uploadFile(mRoomId, uploadFileInfo.description, QString(), uploadFileInfo.fileUrl); } void RoomWidget::slotSendMessage(const QString &msg) { if (mMessageIdBeingEdited.isEmpty()) { mCurrentRocketChatAccount->sendMessage(mRoomId, msg); } else { mCurrentRocketChatAccount->updateMessage(mRoomId, mMessageIdBeingEdited, msg); mMessageIdBeingEdited.clear(); } mMessageLineWidget->setMode(MessageLineWidget::EditingMode::NewMessage); } void RoomWidget::slotEditMessage(const QString &messageId, const QString &text) { mMessageIdBeingEdited = messageId; mMessageLineWidget->setMode(MessageLineWidget::EditingMode::EditMessage); mMessageLineWidget->setText(text); mMessageLineWidget->setFocus(); } void RoomWidget::dragEnterEvent(QDragEnterEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasUrls()) { event->accept(); } } void RoomWidget::dropEvent(QDropEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasUrls()) { const QList urls = mimeData->urls(); for (const QUrl &url : urls) { if (url.isLocalFile()) { QPointer dlg = new UploadFileDialog(this); dlg->setFileUrl(url); if (dlg->exec()) { const UploadFileDialog::UploadFileInfo uploadFileInfo = dlg->fileInfo(); slotSendFile(uploadFileInfo); } } } } } void RoomWidget::setChannelSelected(const QModelIndex &index) { if (mMessageLineWidget->text().isEmpty()) { mCurrentRocketChatAccount->accountRoomSettings()->remove(mRoomId); } else { AccountRoomSettings::PendingTypedInfo info; info.text = mMessageLineWidget->text(); info.messageIdBeingEdited = mMessageIdBeingEdited; mCurrentRocketChatAccount->accountRoomSettings()->add(mRoomId, info); } const QString roomId = index.data(RoomModel::RoomID).toString(); setRoomId(roomId); setRoomType(index.data(RoomModel::RoomType).toString()); const AccountRoomSettings::PendingTypedInfo currentPendingInfo = mCurrentRocketChatAccount->accountRoomSettings()->value(roomId); mMessageLineWidget->setText(currentPendingInfo.text); mMessageIdBeingEdited = currentPendingInfo.messageIdBeingEdited; mMessageLineWidget->setMode(mMessageIdBeingEdited.isEmpty() ? MessageLineWidget::EditingMode::NewMessage : MessageLineWidget::EditingMode::EditMessage); mMessageLineWidget->setFocus(); } void RoomWidget::updateRoomHeader() { if (mRoomWrapper) { mRoomHeaderWidget->setRoomName(mRoomWrapper->displayRoomName()); mRoomHeaderWidget->setRoomAnnouncement(mRoomWrapper->announcement()); mRoomHeaderWidget->setRoomTopic(mRoomWrapper->topic()); mRoomHeaderWidget->setFavoriteStatus(mRoomWrapper->favorite()); mRoomHeaderWidget->setEncypted(mRoomWrapper->encrypted()); mRoomHeaderWidget->setIsDiscussion(mRoomWrapper->isDiscussionRoom()); //TODO Description ? if (mRoomWrapper->roomMessageInfo().isEmpty()) { mStackedWidget->setCurrentWidget(mMessageLineWidget); } else { mStackedWidget->setCurrentWidget(mReadOnlyLineEditWidget); mReadOnlyLineEditWidget->setMessage(mRoomWrapper->roomMessageInfo()); } } } QString RoomWidget::roomId() const { return mRoomId; } void RoomWidget::setRoomType(const QString &roomType) { mRoomType = roomType; } RoomWrapper *RoomWidget::roomWrapper() const { return mRoomWrapper; } void RoomWidget::setRoomId(const QString &roomId) { mRoomId = roomId; delete mRoomWrapper; mRoomWrapper = mCurrentRocketChatAccount->roomWrapper(mRoomId); connectRoomWrapper(); mMessageListView->setChannelSelected(roomId); } void RoomWidget::connectRoomWrapper() { if (mRoomWrapper) { connect(mRoomWrapper, &RoomWrapper::announcementChanged, this, [this]() { mRoomHeaderWidget->setRoomAnnouncement(mRoomWrapper->announcement()); }); connect(mRoomWrapper, &RoomWrapper::topicChanged, this, [this]() { mRoomHeaderWidget->setRoomTopic(mRoomWrapper->topic()); }); connect(mRoomWrapper, &RoomWrapper::nameChanged, this, [this]() { mRoomHeaderWidget->setRoomName(mRoomWrapper->displayRoomName()); }); connect(mRoomWrapper, &RoomWrapper::favoriteChanged, this, [this]() { mRoomHeaderWidget->setFavoriteStatus(mRoomWrapper->favorite()); }); connect(mRoomWrapper, &RoomWrapper::encryptedChanged, this, [this]() { mRoomHeaderWidget->setEncypted(mRoomWrapper->encrypted()); }); } updateRoomHeader(); } void RoomWidget::slotClearNotification() { mCurrentRocketChatAccount->clearUnreadMessages(mRoomId); } void RoomWidget::slotEncryptedChanged(bool b) { qCWarning(RUQOLAWIDGETS_LOG) << "change encrypted not supported yet"; //TODO mCurrentRocketChatAccount->slot } void RoomWidget::slotChangeFavorite(bool b) { mCurrentRocketChatAccount->changeFavorite(mRoomId, b); } void RoomWidget::keyPressedInLineEdit(QKeyEvent *ev) { if (ev->key() == Qt::Key_Escape) { if (!mMessageIdBeingEdited.isEmpty()) { mMessageIdBeingEdited.clear(); mMessageLineWidget->setText(QString()); } else { slotClearNotification(); } ev->accept(); } else { mMessageListView->handleKeyPressEvent(ev); } } QString RoomWidget::roomType() const { return mRoomType; } void RoomWidget::setCurrentRocketChatAccount(RocketChatAccount *account) { mCurrentRocketChatAccount = account; mMessageLineWidget->setCurrentRocketChatAccount(account); mRoomId.clear(); //Clear it otherwise if we switch between two account with same roomId (as "GENERAL") we will see incorrect room. } void RoomWidget::slotGoBackToRoom() { Q_EMIT selectChannelRequested(mRoomWrapper->parentRid()); } diff --git a/src/widgets/room/roomwidget.h b/src/widgets/room/roomwidget.h index 0e1ea502..dda8d78c 100644 --- a/src/widgets/room/roomwidget.h +++ b/src/widgets/room/roomwidget.h @@ -1,90 +1,89 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ROOMWIDGET_H #define ROOMWIDGET_H -#include #include #include #include "dialogs/uploadfiledialog.h" #include "libruqolawidgets_private_export.h" class RoomHeaderWidget; class MessageListView; class MessageLineWidget; class RoomWrapper; class ReadOnlyLineEditWidget; class QStackedWidget; class RocketChatAccount; class LIBRUQOLAWIDGETS_TESTS_EXPORT RoomWidget : public QWidget { Q_OBJECT public: explicit RoomWidget(QWidget *parent = nullptr); ~RoomWidget() override; Q_REQUIRED_RESULT QString roomId() const; void setRoomId(const QString &roomId); void setCurrentRocketChatAccount(RocketChatAccount *account); Q_REQUIRED_RESULT QString roomType() const; RoomWrapper *roomWrapper() const; Q_SIGNALS: void channelSelected(const QModelIndex &index); void selectChannelRequested(const QString &channelId); protected: void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; private: void setChannelSelected(const QModelIndex &index); void slotSendMessage(const QString &msg); void slotEditMessage(const QString &messageId, const QString &text); void slotClearNotification(); void slotSendFile(const UploadFileDialog::UploadFileInfo &uploadFileInfo); void updateRoomHeader(); void connectRoomWrapper(); void slotChangeFavorite(bool b); void keyPressedInLineEdit(QKeyEvent *ev); void setRoomType(const QString &roomType); void slotEncryptedChanged(bool b); void slotTextEditing(bool clearNotification); void slotGoBackToRoom(); void slotCreateNewDiscussion(const QString &messageId, const QString &originalMessage); QString mRoomId; QString mRoomType; QString mMessageIdBeingEdited; RoomHeaderWidget *mRoomHeaderWidget = nullptr; MessageListView *mMessageListView = nullptr; MessageLineWidget *mMessageLineWidget = nullptr; RoomWrapper *mRoomWrapper = nullptr; QStackedWidget *mStackedWidget = nullptr; ReadOnlyLineEditWidget *mReadOnlyLineEditWidget = nullptr; QPointer mCurrentRocketChatAccount; }; #endif // ROOMWIDGET_H diff --git a/src/widgets/ruqolacentralwidget.cpp b/src/widgets/ruqolacentralwidget.cpp index 878799a0..42a12988 100644 --- a/src/widgets/ruqolacentralwidget.cpp +++ b/src/widgets/ruqolacentralwidget.cpp @@ -1,110 +1,110 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ruqolacentralwidget.h" #include "ruqolaloginwidget.h" #include "ruqolamainwidget.h" #include "ruqola.h" #include "rocketchataccount.h" -#include #include #include #include +#include RuqolaCentralWidget::RuqolaCentralWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainlayout")); mStackedWidget = new QStackedWidget(this); mStackedWidget->setObjectName(QStringLiteral("mStackedWidget")); mainLayout->addWidget(mStackedWidget); mRuqolaMainWidget = new RuqolaMainWidget(this); mRuqolaMainWidget->setObjectName(QStringLiteral("mRuqolaMainWidget")); mStackedWidget->addWidget(mRuqolaMainWidget); mRuqolaLoginWidget = new RuqolaLoginWidget(this); mRuqolaLoginWidget->setObjectName(QStringLiteral("mRuqolaLoginWidget")); mStackedWidget->addWidget(mRuqolaLoginWidget); mStackedWidget->setCurrentWidget(mRuqolaLoginWidget); connect(mRuqolaMainWidget, &RuqolaMainWidget::channelSelected, this, &RuqolaCentralWidget::channelSelected); } RuqolaCentralWidget::~RuqolaCentralWidget() { } void RuqolaCentralWidget::slotJobFailedInfo(const QString &messageError) { //TODO fix i18n KMessageBox::error(this, messageError, i18n("Job Failed")); } void RuqolaCentralWidget::slotSocketError(QAbstractSocket::SocketError error, const QString &errorString) { Q_UNUSED(error); // ## let's hope this happens while the login widget is visible, but that's quite likely // Testcase: try to connect to a server that doesn't exist mRuqolaLoginWidget->showError(errorString); } RoomWrapper *RuqolaCentralWidget::roomWrapper() const { return mRuqolaMainWidget->roomWrapper(); } QString RuqolaCentralWidget::roomId() const { return mRuqolaMainWidget->roomId(); } QString RuqolaCentralWidget::roomType() const { return mRuqolaMainWidget->roomType(); } void RuqolaCentralWidget::setCurrentRocketChatAccount(RocketChatAccount *account) { if (mCurrentRocketChatAccount) { disconnect(mCurrentRocketChatAccount, nullptr, this, nullptr); } mCurrentRocketChatAccount = account; connect(mCurrentRocketChatAccount, &RocketChatAccount::loginStatusChanged, this, &RuqolaCentralWidget::slotLoginStatusChanged); connect(mCurrentRocketChatAccount, &RocketChatAccount::socketError, this, &RuqolaCentralWidget::slotSocketError); connect(mCurrentRocketChatAccount, &RocketChatAccount::jobFailed, this, &RuqolaCentralWidget::slotJobFailedInfo); mRuqolaMainWidget->setCurrentRocketChatAccount(account); //Check if account is connected or not. slotLoginStatusChanged(); } void RuqolaCentralWidget::slotLoginStatusChanged() { const auto loginStatus = mCurrentRocketChatAccount->loginStatus(); mRuqolaLoginWidget->setLoginStatus(loginStatus); if (loginStatus == DDPClient::LoggedIn) { mStackedWidget->setCurrentWidget(mRuqolaMainWidget); } else { mStackedWidget->setCurrentWidget(mRuqolaLoginWidget); mRuqolaLoginWidget->initialize(); } } diff --git a/src/widgets/ruqolamainwidget.cpp b/src/widgets/ruqolamainwidget.cpp index 6a9a5bd0..e05299e7 100644 --- a/src/widgets/ruqolamainwidget.cpp +++ b/src/widgets/ruqolamainwidget.cpp @@ -1,117 +1,117 @@ /* Copyright (c) 2020 Laurent Montel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License or ( at your option ) version 3 or, at the discretion of KDE e.V. ( which shall act as a proxy as in section 14 of the GPLv3 ), 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ruqolamainwidget.h" #include "channellist/channellistwidget.h" #include "room/roomwidget.h" #include "channellist/channellistview.h" #include #include #include -#include +#include #include #include namespace { static const char myConfigGroupName[] = "RuqolaMainWidget"; } RuqolaMainWidget::RuqolaMainWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); mainLayout->setObjectName(QStringLiteral("mainlayout")); mSplitter = new QSplitter(this); mSplitter->setObjectName(QStringLiteral("mSplitter")); mSplitter->setChildrenCollapsible(false); mainLayout->addWidget(mSplitter); mChannelList = new ChannelListWidget(this); mChannelList->setObjectName(QStringLiteral("mChannelList")); mSplitter->addWidget(mChannelList); mStackedRoomWidget = new QStackedWidget(this); mStackedRoomWidget->setObjectName(QStringLiteral("mStackedRoomWidget")); mSplitter->addWidget(mStackedRoomWidget); mRoomWidget = new RoomWidget(this); mRoomWidget->setObjectName(QStringLiteral("mRoomWidget")); mStackedRoomWidget->addWidget(mRoomWidget); connect(mRoomWidget, &RoomWidget::selectChannelRequested, this, [this](const QString &channelId) { mChannelList->channelListView()->selectChannelRequested(channelId); }); mEmptyRoomWidget = new QWidget(this); mEmptyRoomWidget->setObjectName(QStringLiteral("mEmptyRoomWidget")); mStackedRoomWidget->addWidget(mEmptyRoomWidget); mStackedRoomWidget->setCurrentWidget(mEmptyRoomWidget); connect(mChannelList, &ChannelListWidget::channelSelected, this, &RuqolaMainWidget::selectChannelRoom); KConfigGroup group(KSharedConfig::openConfig(), myConfigGroupName); mSplitter->restoreState(group.readEntry("SplitterSizes", QByteArray())); //FIXME delay it until list of room are loaded. mChannelList->channelListView()->selectChannelRequested(group.readEntry("SelectedRoom", QString())); } RuqolaMainWidget::~RuqolaMainWidget() { KConfigGroup group(KSharedConfig::openConfig(), myConfigGroupName); group.writeEntry("SplitterSizes", mSplitter->saveState()); const QString selectedRoom = mChannelList->currentSelectedRoom(); if (selectedRoom.isEmpty()) { group.deleteEntry("SelectedRoom"); } else { group.writeEntry("SelectedRoom", selectedRoom); } } void RuqolaMainWidget::selectChannelRoom(const QModelIndex &index) { Q_EMIT mRoomWidget->channelSelected(index); mStackedRoomWidget->setCurrentWidget(mRoomWidget); Q_EMIT channelSelected(); } RoomWrapper *RuqolaMainWidget::roomWrapper() const { return mRoomWidget->roomWrapper(); } QString RuqolaMainWidget::roomId() const { return mRoomWidget->roomId(); } QString RuqolaMainWidget::roomType() const { return mRoomWidget->roomType(); } void RuqolaMainWidget::setCurrentRocketChatAccount(RocketChatAccount *account) { mChannelList->setCurrentRocketChatAccount(account); mRoomWidget->setCurrentRocketChatAccount(account); mStackedRoomWidget->setCurrentWidget(mEmptyRoomWidget); }