diff --git a/src/core/autotranslatelanguages.cpp b/src/core/autotranslatelanguages.cpp index 207ccaca..66fe8fcc 100644 --- a/src/core/autotranslatelanguages.cpp +++ b/src/core/autotranslatelanguages.cpp @@ -1,77 +1,78 @@ /* 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. */ #include "autotranslatelanguages.h" #include #include AutotranslateLanguages::AutotranslateLanguages() { } QVector AutotranslateLanguages::autotranslateLanguage() const { return mAutotranslateLanguages; } void AutotranslateLanguages::setAutotranslateLanguages(const QVector &autotranslateLanguage) { mAutotranslateLanguages = autotranslateLanguage; } bool AutotranslateLanguages::isEmpty() const { return mAutotranslateLanguages.isEmpty(); } int AutotranslateLanguages::count() const { return mAutotranslateLanguages.count(); } void AutotranslateLanguages::clear() { mAutotranslateLanguages.clear(); } AutotranslateLanguage AutotranslateLanguages::at(int index) const { return mAutotranslateLanguages.at(index); } void AutotranslateLanguages::parseLanguages(const QJsonObject &obj) { clear(); const QJsonArray array = obj[QLatin1String("languages")].toArray(); for (const QJsonValue ¤t : array) { const QJsonObject languageObject = current.toObject(); AutotranslateLanguage lang; lang.setLanguage(languageObject.value(QLatin1String("language")).toString()); mAutotranslateLanguages.append(lang); } } QDebug operator <<(QDebug d, const AutotranslateLanguages &t) { - for (const AutotranslateLanguage &lang : t.autotranslateLanguage()) { + const QVector autotranslateLanguages = t.autotranslateLanguage(); + for (const AutotranslateLanguage &lang : autotranslateLanguages) { d << "autotranslate :" << lang; } return d; } diff --git a/src/core/ddpapi/ddpclient.cpp b/src/core/ddpapi/ddpclient.cpp index ee6e91a4..5c8f592f 100644 --- a/src/core/ddpapi/ddpclient.cpp +++ b/src/core/ddpapi/ddpclient.cpp @@ -1,956 +1,956 @@ /* * Copyright 2016 Riccardo Iaconelli * Copyright (C) 2017-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 . * */ #include "ddpclient.h" #include "restapirequest.h" #include "utils.h" #include "ruqola_ddpapi_debug.h" #include "ruqola_ddpapi_command_debug.h" #include "rocketchatmessage.h" #include "ruqolawebsocket.h" #include "rocketchataccount.h" #include "messagequeue.h" #include "ruqolalogger.h" #include "rocketchatbackend.h" #include "plugins/pluginauthenticationinterface.h" #include #include #include #include namespace RuqolaTestWebSocket { LIBRUQOLACORE_EXPORT AbstractWebSocket *_k_ruqola_webSocket = nullptr; } void user_ignore(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("User Ignore:") + QJsonDocument(root).toJson()); } } void block_user(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Block User:") + QJsonDocument(root).toJson()); } } void unblock_user(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("UnBlock User:") + QJsonDocument(root).toJson()); } } void input_user_channel_autocomplete(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Input channel/User autocomplete:") + QJsonDocument(root).toJson()); } const QJsonObject obj = root.value(QLatin1String("result")).toObject(); account->inputTextManager()->inputTextCompleter(obj); } void process_backlog(const QJsonObject &root, RocketChatAccount *account) { const QJsonObject obj = root.value(QLatin1String("result")).toObject(); //qCDebug(RUQOLA_DDPAPI_LOG) << obj.value(QLatin1String("messages")).toArray().size(); account->rocketChatBackend()->processIncomingMessages(obj.value(QLatin1String("messages")).toArray()); } void add_user_to_room(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Add User To Room:") + QJsonDocument(root).toJson()); } } void star_message(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Star message:") + QJsonDocument(root).toJson()); } } void change_notifications_settings(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Change Notifications Settings:") + QJsonDocument(root).toJson()); } } void change_room_settings(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Change Room Settings:") + QJsonDocument(root).toJson()); } } void erase_room(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Delete Room:") + QJsonDocument(root).toJson()); } qDebug()<< "void erase_room(const QJsonObject &root, RocketChatAccount *account)"<ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Delete Message:") + QJsonDocument(root).toJson()); } } void channel_and_private_autocomplete(const QJsonObject &root, RocketChatAccount *account) { const QJsonObject obj = root.value(QLatin1String("result")).toObject(); account->loadAutoCompleteChannel(obj); if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Channel And Private AutoComplete:") + QJsonDocument(root).toJson()); } } void create_jitsi_conf_call(const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Create Jitsi Conf Call:") + QJsonDocument(root).toJson()); } } void open_direct_channel(const QJsonObject &root, RocketChatAccount *account) { const QJsonObject obj = root.value(QLatin1String("result")).toObject(); if (!obj.isEmpty()) { const QString rid = obj.value(QLatin1String("rid")).toString(); if (!rid.isEmpty()) { account->ddp()->subscribeRoomMessage(rid); } } if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Open Direct channel:") + QJsonDocument(root).toJson()); } } void join_room(const QJsonObject &obj, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Join Room :") + QJsonDocument(obj).toJson()); } } void change_default_status(const QJsonObject &obj, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Change Default Status :") + QJsonDocument(obj).toJson()); } } void empty_callback(const QJsonObject &obj, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Empty call back :") + QJsonDocument(obj).toJson()); } else { qCWarning(RUQOLA_DDPAPI_LOG) << "empty_callback "<< obj; } } void login_result(const QJsonObject &obj, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Login result: ") + QJsonDocument(obj).toJson()); } else { qCWarning(RUQOLA_DDPAPI_LOG) << "Login result: "<< obj; } const QJsonObject result = obj.value(QLatin1String("result")).toObject(); //qDebug() << " result token " << result[QStringLiteral("token")].toString(); const qint64 tokenExpires = Utils::parseDate(QStringLiteral("tokenExpires"), result); //qDebug() << " result tokenExpires " << tokenExpires; account->settings()->setExpireToken(tokenExpires); } void create_channel(const QJsonObject &root, RocketChatAccount *account) { const QJsonObject obj = root.value(QLatin1String("result")).toObject(); if (!obj.isEmpty()) { const QString rid = obj.value(QLatin1String("rid")).toString(); if (!rid.isEmpty()) { account->joinRoom(rid); } if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("create Channel :") + QJsonDocument(root).toJson()); } } } DDPClient::DDPClient(RocketChatAccount *account, QObject *parent) : QObject(parent) , m_uid(1) , m_loginStatus(NotConnected) , mRocketChatMessage(new RocketChatMessage) , mRocketChatAccount(account) { } DDPClient::~DDPClient() { disconnect(mWebSocket, &AbstractWebSocket::disconnected, this, &DDPClient::onWSclosed); mWebSocket->close(); //Don't delete socket when we use specific socket. if (!RuqolaTestWebSocket::_k_ruqola_webSocket) { delete mWebSocket; mWebSocket = nullptr; } delete mRocketChatMessage; mRocketChatMessage = nullptr; } void DDPClient::setServerUrl(const QString &url) { mUrl = url; } void DDPClient::initializeWebSocket() { mWebSocket->ignoreSslErrors(); connect(mWebSocket, &AbstractWebSocket::connected, this, &DDPClient::onWSConnected); connect(mWebSocket, &AbstractWebSocket::textMessageReceived, this, &DDPClient::onTextMessageReceived); connect(mWebSocket, &AbstractWebSocket::disconnected, this, &DDPClient::onWSclosed); connect(mWebSocket, &AbstractWebSocket::socketError, this, &DDPClient::socketError); connect(mWebSocket, &AbstractWebSocket::sslErrors, this, &DDPClient::onSslErrors); } void DDPClient::start() { if (!mWebSocket) { if (!RuqolaTestWebSocket::_k_ruqola_webSocket) { mWebSocket = new RuqolaWebSocket(mRocketChatAccount->ruqolaLogger(), this); } else { mWebSocket = RuqolaTestWebSocket::_k_ruqola_webSocket; } initializeWebSocket(); } connect(mRocketChatAccount, &RocketChatAccount::serverUrlChanged, this, &DDPClient::onServerURLChange); if (!mUrl.isEmpty()) { const QUrl serverUrl = adaptUrl(mUrl); if (!serverUrl.isValid()) { setLoginStatus(LoginFailed); } else { mWebSocket->openUrl(serverUrl); qCDebug(RUQOLA_DDPAPI_LOG) << "Trying to connect to URL" << serverUrl; } } else { qCDebug(RUQOLA_DDPAPI_LOG) << "url is empty"; } } void DDPClient::setLoginJobId(quint64 jobid) { m_loginJob = jobid; } QUrl DDPClient::adaptUrl(const QString &url) { return Utils::generateServerUrl(url); } void DDPClient::onServerURLChange() { if (mRocketChatAccount->settings()->serverUrl() != mUrl || !mWebSocket->isValid()) { if (mWebSocket->isValid()) { mWebSocket->flush(); mWebSocket->close(); } mUrl = mRocketChatAccount->settings()->serverUrl(); mWebSocket->openUrl(adaptUrl(mUrl)); connect(mWebSocket, &AbstractWebSocket::connected, this, &DDPClient::onWSConnected); qCDebug(RUQOLA_DDPAPI_LOG) << "Reconnecting" << mUrl; } } DDPClient::LoginStatus DDPClient::loginStatus() const { return m_loginStatus; } void DDPClient::setLoginStatus(DDPClient::LoginStatus l) { qCDebug(RUQOLA_DDPAPI_LOG) << "Setting login status to" << l; m_loginStatus = l; Q_EMIT loginStatusChanged(); // reset flags if (l == LoginFailed) { m_attemptedPasswordLogin = false; } } bool DDPClient::isConnected() const { return m_connected; } bool DDPClient::isLoggedIn() const { return m_loginStatus == LoggedIn; } QString DDPClient::cachePath() const { return QStandardPaths::writableLocation(QStandardPaths::CacheLocation); } QQueue > DDPClient::messageQueue() const { return m_messageQueue; } quint64 DDPClient::leaveRoom(const QString &roomID) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->leaveRoom(roomID, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::hideRoom(const QString &roomID) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->hideRoom(roomID, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::toggleFavorite(const QString &roomID, bool favorite) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->toggleFavorite(roomID, favorite, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::createChannel(const QString &name, const QStringList &userList, bool readOnly) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->createChannel(name, userList, readOnly, m_uid); return method(result, create_channel, DDPClient::Persistent); } quint64 DDPClient::setRoomName(const QString &roomId, const QString &name) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomName(roomId, name, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomTopic(const QString &roomId, const QString &topic) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomTopic(roomId, topic, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomType(const QString &roomId, bool privateChannel) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomType(roomId, privateChannel, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomEncrypted(const QString &roomId, bool encrypted) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomEncrypted(roomId, encrypted, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomDescription(const QString &roomId, const QString &description) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomDescription(roomId, description, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::archiveRoom(const QString &roomId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->archiveRoom(roomId, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomIsReadOnly(const QString &roomId, bool readOnly) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomIsReadOnly(roomId, readOnly, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::setRoomAnnouncement(const QString &roomId, const QString &announcement) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setRoomAnnouncement(roomId, announcement, m_uid); return method(result, change_room_settings, DDPClient::Persistent); } quint64 DDPClient::disableNotifications(const QString &roomId, bool disabled) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->disableNotifications(roomId, disabled, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::hideUnreadStatus(const QString &roomId, bool disabled) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->hideUnreadStatus(roomId, disabled, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::audioNotifications(const QString &roomId, const QString &value) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->audioNotifications(roomId, value, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::mobilePushNotifications(const QString &roomId, const QString &value) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->mobilePushNotifications(roomId, value, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::desktopNotifications(const QString &roomId, const QString &value) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->desktopNotifications(roomId, value, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::emailNotifications(const QString &roomId, const QString &value) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->emailNotifications(roomId, value, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } quint64 DDPClient::unreadAlert(const QString &roomId, const QString &value) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->unreadAlert(roomId, value, m_uid); return method(result, change_notifications_settings, DDPClient::Persistent); } void DDPClient::subscribeRoomMessage(const QString &roomId) { QJsonArray params; params.append(QJsonValue(roomId)); subscribe(QStringLiteral("stream-room-messages"), params); const QJsonArray params2{ - QJsonValue(QStringLiteral("%1/%2").arg(roomId).arg(QStringLiteral("deleteMessage"))), + QJsonValue(QStringLiteral("%1/%2").arg(roomId, QStringLiteral("deleteMessage"))), true }; subscribe(QStringLiteral("stream-notify-room"), params2); const QJsonArray params3{ - QJsonValue(QStringLiteral("%1/%2").arg(roomId).arg(QStringLiteral("typing"))), + QJsonValue(QStringLiteral("%1/%2").arg(roomId, QStringLiteral("typing"))), true }; subscribe(QStringLiteral("stream-notify-room"), params3); } quint64 DDPClient::eraseRoom(const QString &roomID) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->eraseRoom(roomID, m_uid); return method(result, erase_room, DDPClient::Persistent); } quint64 DDPClient::openDirectChannel(const QString &userId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->openDirectChannel(userId, m_uid); return method(result, open_direct_channel, DDPClient::Persistent); } quint64 DDPClient::setReaction(const QString &emoji, const QString &messageId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setReaction(emoji, messageId, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::createPrivateGroup(const QString &name, const QStringList &userList) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->createPrivateGroup(name, userList, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::deleteMessage(const QString &messageId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->deleteMessage(messageId, m_uid); return method(result, delete_message, DDPClient::Persistent); } quint64 DDPClient::deleteFileMessage(const QString &roomId, const QString &fileid, const QString &channelType) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->deleteFileMessage(fileid, m_uid); std::function callback = [ roomId, channelType ](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Delete Attachment File:") + QJsonDocument(root).toJson()); } else { qCDebug(RUQOLA_DDPAPI_LOG) << " parse users for room" << roomId; } account->roomFiles(roomId, channelType); }; return method(result, callback, DDPClient::Persistent); } quint64 DDPClient::joinRoom(const QString &roomId, const QString &joinCode) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->joinRoom(roomId, joinCode, m_uid); return method(result, join_room, DDPClient::Persistent); } quint64 DDPClient::setDefaultStatus(User::PresenceStatus status) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->setDefaultStatus(status, m_uid); return method(result, change_default_status, DDPClient::Persistent); } quint64 DDPClient::userAutocomplete(const QString &pattern, const QString &exception) { const quint64 subscribeId = m_uid; const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->userAutocomplete(pattern, exception, subscribeId); std::function callback = [=](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("User AutoComplete:") + QJsonDocument(root).toJson()); } else { qCDebug(RUQOLA_DDPAPI_LOG) << " User AutoComplete" << root; } account->insertCompleterUsers(); const RocketChatMessage::RocketChatMessageResult resultUnsubscribe = mRocketChatMessage->unsubscribe(subscribeId); std::function callbackUnsubscribeAutoComplete = [=](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()-> dataReceived(QByteArrayLiteral( "Unsubscribe AutoComplete:") + QJsonDocument(root).toJson()); } else { qDebug() << " Unsubscribe AutoComplete" << root; qCDebug(RUQOLA_DDPAPI_LOG) << " Unsubscribe AutoComplete" << root; } }; method(resultUnsubscribe, callbackUnsubscribeAutoComplete, DDPClient::Persistent); }; return method(result, callback, DDPClient::Persistent); } quint64 DDPClient::channelAndPrivateAutocomplete(const QString &pattern, const QString &exception) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->channelAndPrivateAutocomplete(pattern, exception, m_uid); return method(result, channel_and_private_autocomplete, DDPClient::Persistent); } quint64 DDPClient::getUsersOfRoom(const QString &roomId, bool showAll) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->getUsersOfRoom(roomId, showAll, m_uid); std::function callback = [ roomId ](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Get Users of Room:") + QJsonDocument(root).toJson()); } else { qCDebug(RUQOLA_DDPAPI_LOG) << " parse users for room" << roomId; } RocketChatRestApi::ChannelBaseJob::ChannelInfo info; info.channelInfoType = RocketChatRestApi::ChannelBaseJob::ChannelInfoType::RoomId; info.channelInfoIdentifier = roomId; account->parseUsersForRooms(root, info); }; return method(result, callback, DDPClient::Persistent); } #if 0 quint64 DDPClient::roomFiles(const QString &roomId) { const quint64 subscribeId = m_uid; const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->roomFiles(roomId, subscribeId); std::function callback = [=](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()->dataReceived(QByteArrayLiteral("Room File done:") + QJsonDocument(root).toJson()); } else { qDebug() << "Room Files " << root; qCDebug(RUQOLA_DDPAPI_LOG) << " Room Files" << root; } account->insertFilesList(roomId); const RocketChatMessage::RocketChatMessageResult resultUnsubscribe = mRocketChatMessage->unsubscribe(subscribeId); std::function callbackUnsubscribeAutoComplete = [=](const QJsonObject &root, RocketChatAccount *account) { if (account->ruqolaLogger()) { account->ruqolaLogger()-> dataReceived(QByteArrayLiteral( "Unsubscribe room files:") + QJsonDocument(root).toJson()); } else { qDebug() << " Unsubscribe room files" << root; qCDebug(RUQOLA_DDPAPI_LOG) << " Unsubscribe room files" << root; } }; method(resultUnsubscribe, callbackUnsubscribeAutoComplete, DDPClient::Persistent); }; return method(result, callback, DDPClient::Persistent); } #endif quint64 DDPClient::createJitsiConfCall(const QString &roomId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->createJitsiConfCall(roomId, m_uid); return method(result, create_jitsi_conf_call, DDPClient::Persistent); } quint64 DDPClient::clearUnreadMessages(const QString &roomID) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->readMessages(roomID, m_uid); return method(result, empty_callback, DDPClient::Persistent); } quint64 DDPClient::inputChannelAutocomplete(const QString &pattern, const QString &exceptions) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->inputChannelAutocomplete(pattern, exceptions, m_uid); return method(result, input_user_channel_autocomplete, DDPClient::Persistent); } quint64 DDPClient::inputUserAutocomplete(const QString &pattern, const QString &exceptions) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->inputUserAutocomplete(pattern, exceptions, m_uid); return method(result, input_user_channel_autocomplete, DDPClient::Persistent); } quint64 DDPClient::loginProvider(const QString &credentialToken, const QString &credentialSecret) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->loginProvider(credentialToken, credentialSecret, m_uid); return method(result, empty_callback, DDPClient::Ephemeral); } quint64 DDPClient::login(const QString &username, const QString &password) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->login(username, password, mRocketChatAccount->settings()->twoFactorAuthenticationCode(), m_uid); return method(result, login_result, DDPClient::Ephemeral); } quint64 DDPClient::addUserToRoom(const QString &username, const QString &roomId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->addUserToRoom(username, roomId, m_uid); return method(result, add_user_to_room, DDPClient::Persistent); } quint64 DDPClient::starMessage(const QString &messageId, const QString &rid, bool starred) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->starMessage(messageId, rid, starred, m_uid); return method(result, star_message, DDPClient::Persistent); } quint64 DDPClient::unBlockUser(const QString &rid, const QString &userId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->unblockUser(rid, userId, m_uid); return method(result, unblock_user, DDPClient::Persistent); } quint64 DDPClient::blockUser(const QString &rid, const QString &userId) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->blockUser(rid, userId, m_uid); return method(result, block_user, DDPClient::Persistent); } quint64 DDPClient::informTypingStatus(const QString &roomId, bool typing, const QString &userName) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->informTypingStatus(roomId, userName, typing, m_uid); qint64 bytes = mWebSocket->sendTextMessage(result.result); if (bytes < result.result.length()) { qCDebug(RUQOLA_DDPAPI_LOG) << "ERROR! I couldn't send all of my message. This is a bug! (try again)"; qCDebug(RUQOLA_DDPAPI_LOG) << mWebSocket->isValid() << mWebSocket->error() << mWebSocket->requestUrl(); } else { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "Successfully sent " << result.result; } const quint64 value = m_uid; m_uid++; return value; } quint64 DDPClient::ignoreUser(const QString &roomId, const QString &userId, bool ignore) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->ignoreUser(roomId, userId, ignore, m_uid); return method(result, user_ignore, DDPClient::Persistent); } quint64 DDPClient::method(const RocketChatMessage::RocketChatMessageResult &result, std::function callback, DDPClient::MessageType messageType) { qint64 bytes = mWebSocket->sendTextMessage(result.result); if (bytes < result.result.length()) { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "ERROR! I couldn't send all of my message. This is a bug! (try again)"; qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << mWebSocket->isValid() << mWebSocket->error() << mWebSocket->requestUrl(); if (messageType == DDPClient::Persistent) { m_messageQueue.enqueue(qMakePair(result.method, result.jsonDocument)); mRocketChatAccount->messageQueue()->processQueue(); } } else { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "Successfully sent " << result.result; } m_callbackHash[m_uid] = callback; const quint64 value = m_uid; m_uid++; return value; } quint64 DDPClient::method(const QString &m, const QJsonDocument ¶ms, DDPClient::MessageType messageType) { return method(m, params, empty_callback, messageType); } quint64 DDPClient::method(const QString &method, const QJsonDocument ¶ms, std::function callback, DDPClient::MessageType messageType) { const RocketChatMessage::RocketChatMessageResult result = mRocketChatMessage->generateMethod(method, params, m_uid); qint64 bytes = mWebSocket->sendTextMessage(result.result); if (bytes < result.result.length()) { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "ERROR! I couldn't send all of my message. This is a bug! (try again)"; qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << mWebSocket->isValid() << mWebSocket->error() << mWebSocket->requestUrl(); if (messageType == DDPClient::Persistent) { m_messageQueue.enqueue(qMakePair(result.method, result.jsonDocument)); mRocketChatAccount->messageQueue()->processQueue(); } } else { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "Successfully sent " << result.result; } m_callbackHash[m_uid] = callback; const quint64 uidCurrent = m_uid; m_uid++; return uidCurrent; } void DDPClient::subscribe(const QString &collection, const QJsonArray ¶ms) { QJsonObject json; json[QStringLiteral("msg")] = QStringLiteral("sub"); json[QStringLiteral("id")] = QString::number(m_uid); json[QStringLiteral("name")] = collection; QJsonArray newParams = params; if (mRocketChatAccount->needAdaptNewSubscriptionRC60()) { QJsonArray args; QJsonObject obj; obj[QStringLiteral("useCollection")] = false; obj[QStringLiteral("args")] = args; newParams.append(obj); } json[QStringLiteral("params")] = newParams; qint64 bytes = mWebSocket->sendTextMessage(QString::fromUtf8(QJsonDocument(json).toJson(QJsonDocument::Compact))); if (bytes < json.length()) { qCDebug(RUQOLA_DDPAPI_LOG) << "ERROR! I couldn't send all of my message. This is a bug! (try again)"; qCDebug(RUQOLA_DDPAPI_LOG) << mWebSocket->isValid() << mWebSocket->error() << mWebSocket->requestUrl(); } else { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "Successfully sent " << json; } m_uid++; } void DDPClient::onTextMessageReceived(const QString &message) { QJsonDocument response = QJsonDocument::fromJson(message.toUtf8()); if (!response.isNull() && response.isObject()) { QJsonObject root = response.object(); const QString messageType = root.value(QLatin1String("msg")).toString(); if (messageType == QLatin1String("updated")) { //nothing to do. qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << " message updated ! not implemented yet" << response; } else if (messageType == QLatin1String("result")) { quint64 id = root.value(QLatin1String("id")).toString().toULongLong(); if (m_callbackHash.contains(id)) { std::function callback = m_callbackHash.take(id); callback(root, mRocketChatAccount); } Q_EMIT result(id, QJsonDocument(root.value(QLatin1String("result")).toObject())); if (id == m_loginJob) { const QJsonObject error(root.value(QLatin1String("error")).toObject()); const QJsonValue errorValue(error.value(QLatin1String("error"))); if (errorValue.toInt() == 403) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << "Wrong password or token expired"; login(); // Let's keep trying to log in } else if (errorValue.toString() == QLatin1String("totp-required") || errorValue.toString() == QLatin1String("totp-invalid")) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << "A 2FA code or backup code is required to login"; setLoginStatus(LoginCodeRequired); } else if (!error.isEmpty()) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << error.value(QLatin1String("message")).toString(); setLoginStatus(LoginFailed); } else { const QString token = root.value(QLatin1String("result")).toObject().value(QLatin1String("token")).toString(); mRocketChatAccount->settings()->setAuthToken(token); mRocketChatAccount->restApi()->setAuthToken(token); mRocketChatAccount->restApi()->setUserId(root.value(QLatin1String("id")).toString()); setLoginStatus(DDPClient::LoggedIn); } } } else if (messageType == QLatin1String("connected")) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << " Connected!"; m_connected = true; setLoginStatus(DDPClient::LoggingIn); Q_EMIT connectedChanged(); } else if (messageType == QLatin1String("error")) { qWarning() << mRocketChatAccount->accountName() << " ERROR!!" << message; } else if (messageType == QLatin1String("ping")) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << "Ping - Pong"; pong(); } else if (messageType == QLatin1String("added")) { qCDebug(RUQOLA_DDPAPI_LOG) << mRocketChatAccount->accountName() << "ADDING element" <accountName() << "Changed element" <accountName() << "READY element" <accountName() << "REMOVED element" <accountName() << "Unsubscribe element" <accountName() << "Error unsubscribing from" << id; qWarning() << mRocketChatAccount->accountName() << "ERROR: " << errorObj[QStringLiteral("error")].toString(); qWarning() << mRocketChatAccount->accountName() << "Message: " << errorObj[QStringLiteral("message")].toString(); qWarning() << mRocketChatAccount->accountName() << "Reason: " << errorObj[QStringLiteral("reason")].toString(); qWarning() << mRocketChatAccount->accountName() << "-- Error found END --"; } } else { // The very first message we receive is {"server_id":"0"}, can't find it in the spec, just ignore it. if (messageType.isEmpty() && !root.value(QStringLiteral("server_id")).isUndefined()) { return; } qWarning() << mRocketChatAccount->accountName() << "received something unhandled:" << messageType << message; } } else { qWarning() << mRocketChatAccount->accountName() << "received something unhandled unknown " << message; } } quint64 DDPClient::loadHistory(const QJsonArray ¶ms) { return method(QStringLiteral("loadHistory"), QJsonDocument(params), process_backlog); } void DDPClient::login() { if (!mRocketChatAccount->settings()->authToken().isEmpty() && !mRocketChatAccount->settings()->tokenExpired()) { m_attemptedPasswordLogin = true; QJsonObject json; json[QStringLiteral("resume")] = mRocketChatAccount->settings()->authToken(); m_loginJob = method(QStringLiteral("login"), QJsonDocument(json)); } else if (!mRocketChatAccount->settings()->password().isEmpty()) { // If we have a password and we couldn't log in, let's stop here if (m_attemptedPasswordLogin) { setLoginStatus(LoginFailed); return; } m_attemptedPasswordLogin = true; //m_loginJob = login(mRocketChatAccount->settings()->userName(), mRocketChatAccount->settings()->password()); if (mRocketChatAccount->defaultAuthenticationInterface()) { mRocketChatAccount->defaultAuthenticationInterface()->login(); } else { qCWarning(RUQOLA_DDPAPI_LOG) <<"No plugins loaded. Please verify your installation."; setLoginStatus(FailedToLoginPluginProblem); } } else { setLoginStatus(LoginFailed); } } void DDPClient::onWSConnected() { qCDebug(RUQOLA_DDPAPI_LOG) << "Websocket connected at URL" << mUrl; QJsonArray supportedVersions; supportedVersions.append(QLatin1String("1")); QJsonObject protocol; protocol[QStringLiteral("msg")] = QStringLiteral("connect"); protocol[QStringLiteral("version")] = QStringLiteral("1"); protocol[QStringLiteral("support")] = supportedVersions; QByteArray serialize = QJsonDocument(protocol).toJson(QJsonDocument::Compact); qint64 bytes = mWebSocket->sendTextMessage(QString::fromUtf8(serialize)); if (bytes < serialize.length()) { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "onWSConnected: ERROR! I couldn't send all of my message. This is a bug! (try again)"; qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << mWebSocket->isValid() << mWebSocket->error() << mWebSocket->requestUrl(); } else { qCDebug(RUQOLA_DDPAPI_COMMAND_LOG) << "Successfully sent " << serialize; } } void DDPClient::onSslErrors(const QList &errors) { qCDebug(RUQOLA_DDPAPI_LOG) << "SSL error" << errors.count(); for (const QSslError &err : errors) { qCDebug(RUQOLA_DDPAPI_LOG) << "error ssl type:" << err.errorString(); } mWebSocket->ignoreSslErrors(); } void DDPClient::onWSclosed() { const bool normalClose = mWebSocket->closeCode() == QWebSocketProtocol::CloseCodeNormal; if (!normalClose) { qCWarning(RUQOLA_DDPAPI_LOG) << "WebSocket CLOSED" << mWebSocket->closeReason() << mWebSocket->error() << mWebSocket->closeCode(); } setLoginStatus(NotConnected); if (normalClose) { Q_EMIT disconnectedByServer(); } } void DDPClient::pong() { QJsonObject pong; pong[QStringLiteral("msg")] = QStringLiteral("pong"); mWebSocket->sendBinaryMessage(QJsonDocument(pong).toJson(QJsonDocument::Compact)); } void DDPClient::executeSubsCallBack(const QJsonObject &root) { const QJsonArray subs = root[QStringLiteral("subs")].toArray(); if (!subs.isEmpty()) { const quint64 id = subs.at(0).toString().toULongLong(); if (m_callbackHash.contains(id)) { std::function callback = m_callbackHash.take(id); callback(root, mRocketChatAccount); } } else { qCWarning(RUQOLA_DDPAPI_LOG) << "Problem with subs json " << root; } } diff --git a/src/core/emoticons/emoji.cpp b/src/core/emoticons/emoji.cpp index 3d85cb0d..a606fd14 100644 --- a/src/core/emoticons/emoji.cpp +++ b/src/core/emoticons/emoji.cpp @@ -1,196 +1,196 @@ /* 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 "emoticons/emoji.h" #include "utils.h" #include #include Emoji::Emoji() { } Emoji::~Emoji() { } bool Emoji::hasEmoji(const QString &identifier) const { return (mEmojiIdentifier == identifier) || mAliases.contains(identifier); } qint64 Emoji::updatedAt() const { return mUpdatedAt; } void Emoji::setUpdatedAt(const qint64 &updatedAt) { mUpdatedAt = updatedAt; } bool Emoji::isAnimatedImage() const { return mExtension == QLatin1String("gif"); } void Emoji::parseEmoji(const QJsonObject &emoji) { mIdentifier = emoji.value(QLatin1String("_id")).toString(); mExtension = emoji.value(QLatin1String("extension")).toString(); mName = emoji.value(QLatin1String("name")).toString(); mEmojiIdentifier = QLatin1Char(':') + mName + QLatin1Char(':'); mUpdatedAt = Utils::parseIsoDate(QStringLiteral("_updatedAt"), emoji); const QJsonArray array = emoji.value(QLatin1String("aliases")).toArray(); const int arrayCount = array.count(); QStringList lst; lst.reserve(arrayCount); for (int i = 0; i < arrayCount; ++i) { lst.append(QLatin1Char(':') + array.at(i).toString() + QLatin1Char(':')); } mAliases = lst; } bool Emoji::isValid() const { //Add more check ? return !mIdentifier.isEmpty() && !mName.isEmpty(); } QString Emoji::emojiUrl(const QString &serverUrl) const { QString url = serverUrl + emojiFileName(); // ???? http ? not https ??? if (!url.startsWith(QLatin1String("http://")) && !url.startsWith(QLatin1String("https://"))) { url.prepend(QLatin1String("http://")); } return url; } QString Emoji::emojiFileName() const { - return QStringLiteral("/emoji-custom/%1.%2").arg(mName).arg(mExtension); + return QStringLiteral("/emoji-custom/%1.%2").arg(mName, mExtension); } QString Emoji::generateAnimatedUrlFromCustomEmoji(const QString &serverUrl) { if (mCachedHtml.isEmpty()) { const QString url = emojiUrl(serverUrl); //https://rocket.chat/docs/developer-guides/realtime-api/method-calls/list-custom-emoji/#list-custom-emoji //http://yourhost.com/emoji-custom/Emoji%20Name.png //TODO customize size. mCachedHtml = url; } return mCachedHtml; } QString Emoji::generateHtmlFromCustomEmoji(const QString &serverUrl) { if (mCachedHtml.isEmpty()) { const QString url = emojiUrl(serverUrl); //https://rocket.chat/docs/developer-guides/realtime-api/method-calls/list-custom-emoji/#list-custom-emoji //http://yourhost.com/emoji-custom/Emoji%20Name.png //TODO customize size. mCachedHtml = QStringLiteral("").arg(url); } return mCachedHtml; } void Emoji::clearCachedHtml() { mCachedHtml.clear(); } QStringList Emoji::aliases() const { return mAliases; } void Emoji::setAliases(const QStringList &aliases) { mAliases = aliases; } QString Emoji::emojiIdentifier() const { return mEmojiIdentifier; } void Emoji::setEmojiIdentifier(const QString &emojiIdentifier) { mEmojiIdentifier = emojiIdentifier; } QString Emoji::cachedHtml() const { return mCachedHtml; } QString Emoji::identifier() const { return mIdentifier; } void Emoji::setIdentifier(const QString &identifier) { mIdentifier = identifier; } QString Emoji::extension() const { return mExtension; } void Emoji::setExtension(const QString &extension) { mExtension = extension; } void Emoji::setName(const QString &name) { mName = name; } QString Emoji::name() const { return mName; } bool Emoji::operator==(const Emoji &other) const { return (mName == other.name()) && (mExtension == other.extension()) && (mIdentifier == other.identifier()) && (mAliases == other.aliases()) && (mEmojiIdentifier == other.emojiIdentifier()) && (mUpdatedAt == other.updatedAt()); } QDebug operator <<(QDebug d, const Emoji &t) { d << "Name: " << t.name() << " "; d << "Identifier: " << t.identifier() << " "; d << "extension: " << t.extension() << " "; d << "aliases: " << t.aliases() << " "; d << "UpdatedAt: " << t.updatedAt() << " "; d << "EmojiIdentifier: " << t.emojiIdentifier(); return d; } diff --git a/src/core/messages/messageattachment.cpp b/src/core/messages/messageattachment.cpp index a60236cf..cfea72e7 100644 --- a/src/core/messages/messageattachment.cpp +++ b/src/core/messages/messageattachment.cpp @@ -1,209 +1,209 @@ /* 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 "messageattachment.h" #include #include MessageAttachment::MessageAttachment() { } QJsonObject MessageAttachment::serialize(const MessageAttachment &message) { QJsonObject obj; obj[QStringLiteral("description")] = message.description(); obj[QStringLiteral("title")] = message.title(); obj[QStringLiteral("url")] = message.link(); const QString authorname = message.authorName(); if (!authorname.isEmpty()) { obj[QStringLiteral("authorname")] = authorname; } const QString mimeType = message.mimeType(); if (!mimeType.isEmpty()) { obj[QStringLiteral("mimetype")] = mimeType; } if ((message.imageHeight() != -1) && (message.imageWidth() != -1)) { obj[QStringLiteral("image_height")] = message.imageHeight(); obj[QStringLiteral("image_width")] = message.imageWidth(); } const QString color = message.color(); if (!color.isEmpty()) { obj[QStringLiteral("color")] = color; } return obj; } MessageAttachment MessageAttachment::fromJSon(const QJsonObject &o) { MessageAttachment att; att.setDescription(o.value(QLatin1String("description")).toString()); att.setTitle(o.value(QLatin1String("title")).toString()); att.setLink(o.value(QLatin1String("url")).toString()); att.setAuthorName(o.value(QLatin1String("authorname")).toString()); att.setMimeType(o.value(QLatin1String("mimetype")).toString()); const QJsonValue valHeight = o.value(QLatin1String("image_height")); if (!valHeight.isUndefined()) { att.setImageHeight(valHeight.toInt()); } const QJsonValue valWidth = o.value(QLatin1String("image_width")); if (!valWidth.isUndefined()) { att.setImageWidth(valWidth.toInt()); } att.setColor(o.value(QLatin1String("color")).toString()); return att; } int MessageAttachment::imageWidth() const { return mImageWidth; } void MessageAttachment::setImageWidth(int imageWidth) { mImageWidth = imageWidth; } int MessageAttachment::imageHeight() const { return mImageHeight; } void MessageAttachment::setImageHeight(int imageHeight) { mImageHeight = imageHeight; } QString MessageAttachment::color() const { return mColor; } void MessageAttachment::setColor(const QString &color) { mColor = color; } QString MessageAttachment::authorName() const { return mAuthorName; } void MessageAttachment::setAuthorName(const QString &authorName) { mAuthorName = authorName; } bool MessageAttachment::isEmpty() const { return mLink.isEmpty(); } bool MessageAttachment::canDownloadAttachment() const { //Improve it ! if (mLink.startsWith(QLatin1String("http://")) || mLink.startsWith(QLatin1String("https://"))) { return false; } return true; } QString MessageAttachment::imageTitle() const { - return QStringLiteral("%1 %2").arg(i18n("File Uploaded:")).arg(title()); + return QStringLiteral("%1 %2").arg(i18n("File Uploaded:"), title()); } QString MessageAttachment::mimeType() const { return mMimeType; } void MessageAttachment::setMimeType(const QString &type) { mMimeType = type; mIsAnimatedImage = (mMimeType == QLatin1String("image/gif")); } bool MessageAttachment::isAnimatedImage() const { return mIsAnimatedImage; } QString MessageAttachment::displayTitle() const { if (canDownloadAttachment()) { return i18n("File Uploaded: %1", title()); } - return QStringLiteral("%2").arg(link()).arg(title()); + return QStringLiteral("%2").arg(link(), title()); } QString MessageAttachment::description() const { return mDescription; } void MessageAttachment::setDescription(const QString &description) { mDescription = description; } QString MessageAttachment::title() const { return mTitle; } void MessageAttachment::setTitle(const QString &title) { mTitle = title; } QString MessageAttachment::link() const { return mLink; } void MessageAttachment::setLink(const QString &link) { mLink = link; } bool MessageAttachment::operator==(const MessageAttachment &other) const { return (mDescription == other.description()) && (mTitle == other.title()) && (mLink == other.link()) && (mColor == other.color()) && (mImageHeight == other.imageHeight()) && (mImageWidth == other.imageWidth()) && (mAuthorName == other.authorName()) && (mMimeType == other.mimeType()); } QDebug operator <<(QDebug d, const MessageAttachment &t) { d << "Title : " << t.title(); d << "Description: " << t.description(); d << "Link: " << t.link(); d << "image dimension: width: " << t.imageWidth() << " height: " << t.imageHeight(); d << "color: " << t.color(); d << "authorname: " << t.authorName(); d << "mimeType: " << t.mimeType(); return d; } diff --git a/src/rocketchatrestapi-qt5/autotests/roomstartdiscussionjobtest.cpp b/src/rocketchatrestapi-qt5/autotests/roomstartdiscussionjobtest.cpp index 4859a4f5..15308936 100644 --- a/src/rocketchatrestapi-qt5/autotests/roomstartdiscussionjobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/roomstartdiscussionjobtest.cpp @@ -1,96 +1,96 @@ /* 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 "roomstartdiscussionjobtest.h" #include "rooms/roomstartdiscussionjob.h" #include "ruqola_restapi_helper.h" #include #include QTEST_GUILESS_MAIN(RoomStartDiscussionJobTest) using namespace RocketChatRestApi; RoomStartDiscussionJobTest::RoomStartDiscussionJobTest(QObject *parent) : QObject(parent) { } void RoomStartDiscussionJobTest::shouldHaveDefaultValue() { RoomStartDiscussionJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(job.parentRoomId().isEmpty()); QVERIFY(job.parentMessageId().isEmpty()); QVERIFY(job.discussionName().isEmpty()); QVERIFY(job.replyMessage().isEmpty()); QVERIFY(job.users().isEmpty()); QVERIFY(!job.hasQueryParameterSupport()); } void RoomStartDiscussionJobTest::shouldGenerateRequest() { RoomStartDiscussionJob job; QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/rooms.createDiscussion"))); QCOMPARE(request.header(QNetworkRequest::ContentTypeHeader).toString(), QStringLiteral("application/json")); } void RoomStartDiscussionJobTest::shouldGenerateJson() { RoomStartDiscussionJob job; const QString pRid = QStringLiteral("foo1"); job.setParentRoomId(pRid); const QString discussionName = QStringLiteral("bla"); job.setDiscussionName(discussionName); - QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"prid\":\"%1\",\"t_name\":\"%2\"}").arg(pRid).arg(discussionName).toLatin1()); + QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"prid\":\"%1\",\"t_name\":\"%2\"}").arg(pRid, discussionName).toLatin1()); const QString replyMessage = QStringLiteral("Bli"); job.setReplyMessage(replyMessage); - QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"prid\":\"%1\",\"reply\":\"%2\",\"t_name\":\"%3\"}").arg(pRid).arg(replyMessage).arg(discussionName).toLatin1()); + QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"prid\":\"%1\",\"reply\":\"%2\",\"t_name\":\"%3\"}").arg(pRid, replyMessage, discussionName).toLatin1()); const QStringList users{QStringLiteral("aaa"), QStringLiteral("bbb"), QStringLiteral("ddd")}; job.setUsers(users); QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"prid\":\"%1\",\"reply\":\"%2\",\"t_name\":\"%3\",\"users\":[\"aaa\",\"bbb\",\"ddd\"]}") - .arg(pRid).arg(replyMessage).arg(discussionName).arg(QStringLiteral("bla")).toLatin1()); + .arg(pRid, replyMessage, discussionName, QStringLiteral("bla")).toLatin1()); } void RoomStartDiscussionJobTest::shouldNotStarting() { RoomStartDiscussionJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); QNetworkAccessManager mNetworkAccessManager; job.setNetworkAccessManager(&mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); const QString pRid = QStringLiteral("foo1"); job.setParentRoomId(pRid); QVERIFY(!job.canStart()); const QString discussionName = QStringLiteral("bla"); job.setDiscussionName(discussionName); QVERIFY(job.canStart()); } diff --git a/src/rocketchatrestapi-qt5/autotests/syncthreadmessagesjobtest.cpp b/src/rocketchatrestapi-qt5/autotests/syncthreadmessagesjobtest.cpp index 85f4b0ae..d96cbdb5 100644 --- a/src/rocketchatrestapi-qt5/autotests/syncthreadmessagesjobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/syncthreadmessagesjobtest.cpp @@ -1,85 +1,85 @@ /* 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 "syncthreadmessagesjobtest.h" #include "chat/syncthreadmessagesjob.h" #include "ruqola_restapi_helper.h" #include QTEST_GUILESS_MAIN(SyncThreadMessagesJobTest) using namespace RocketChatRestApi; SyncThreadMessagesJobTest::SyncThreadMessagesJobTest(QObject *parent) : QObject(parent) { } void SyncThreadMessagesJobTest::shouldHaveDefaultValue() { SyncThreadMessagesJob job; QVERIFY(!job.restApiMethod()); QVERIFY(!job.networkAccessManager()); QVERIFY(!job.start()); QVERIFY(job.threadMessageId().isEmpty()); QVERIFY(job.timeStamp().isEmpty()); QVERIFY(job.requireHttpAuthentication()); QVERIFY(!job.restApiLogger()); QVERIFY(!job.hasQueryParameterSupport()); } void SyncThreadMessagesJobTest::shouldGenerateRequest() { SyncThreadMessagesJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); const QString threadMessageId = QStringLiteral("bla"); job.setThreadMessageId(threadMessageId); const QString timestamp = QStringLiteral("blu"); job.setTimeStamp(timestamp); const QNetworkRequest request = job.request(); - QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/chat.syncThreadMessages?tmid=%1&updatedSince=%2").arg(threadMessageId).arg(timestamp))); + QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/chat.syncThreadMessages?tmid=%1&updatedSince=%2").arg(threadMessageId, timestamp))); } void SyncThreadMessagesJobTest::shouldNotStarting() { SyncThreadMessagesJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); QNetworkAccessManager mNetworkAccessManager; job.setNetworkAccessManager(&mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); const QString threadMessageId = QStringLiteral("foo1"); job.setThreadMessageId(threadMessageId); QVERIFY(!job.canStart()); const QString timestamp = QStringLiteral("blu"); job.setTimeStamp(timestamp); QVERIFY(job.canStart()); } diff --git a/src/rocketchatrestapi-qt5/autotests/translatemessagejobtest.cpp b/src/rocketchatrestapi-qt5/autotests/translatemessagejobtest.cpp index 11f376ba..531d3afd 100644 --- a/src/rocketchatrestapi-qt5/autotests/translatemessagejobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/translatemessagejobtest.cpp @@ -1,85 +1,85 @@ /* 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 "translatemessagejobtest.h" #include "autotranslate/translatemessagejob.h" #include "ruqola_restapi_helper.h" #include #include QTEST_GUILESS_MAIN(TranslateMessageJobTest) using namespace RocketChatRestApi; TranslateMessageJobTest::TranslateMessageJobTest(QObject *parent) : QObject(parent) { } void TranslateMessageJobTest::shouldHaveDefaultValue() { TranslateMessageJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(job.messageId().isEmpty()); QVERIFY(job.targetLanguage().isEmpty()); QVERIFY(!job.hasQueryParameterSupport()); } void TranslateMessageJobTest::shouldGenerateRequest() { TranslateMessageJob job; QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/autotranslate.translateMessage"))); QCOMPARE(request.header(QNetworkRequest::ContentTypeHeader).toString(), QStringLiteral("application/json")); } void TranslateMessageJobTest::shouldGenerateJson() { TranslateMessageJob job; const QString messageId = QStringLiteral("foo1"); job.setMessageId(messageId); const QString targetLanguage = QStringLiteral("bla"); job.setTargetLanguage(targetLanguage); - QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"messageId\":\"%1\",\"targetLanguage\":\"%2\"}").arg(messageId).arg(targetLanguage).toLatin1()); + QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"messageId\":\"%1\",\"targetLanguage\":\"%2\"}").arg(messageId, targetLanguage).toLatin1()); } void TranslateMessageJobTest::shouldNotStarting() { TranslateMessageJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); QNetworkAccessManager mNetworkAccessManager; job.setNetworkAccessManager(&mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); const QString messageId = QStringLiteral("foo1"); job.setMessageId(messageId); QVERIFY(!job.canStart()); const QString targetLanguage = QStringLiteral("bla"); job.setTargetLanguage(targetLanguage); QVERIFY(job.canStart()); } diff --git a/src/rocketchatrestapi-qt5/autotests/translatesavesettingsjobtest.cpp b/src/rocketchatrestapi-qt5/autotests/translatesavesettingsjobtest.cpp index 3054ace2..4d4130e6 100644 --- a/src/rocketchatrestapi-qt5/autotests/translatesavesettingsjobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/translatesavesettingsjobtest.cpp @@ -1,101 +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 "translatesavesettingsjobtest.h" #include "autotranslate/translatesavesettingsjob.h" #include "ruqola_restapi_helper.h" #include #include QTEST_GUILESS_MAIN(TranslateSaveSettingsJobTest) using namespace RocketChatRestApi; TranslateSaveSettingsJobTest::TranslateSaveSettingsJobTest(QObject *parent) : QObject(parent) { } void TranslateSaveSettingsJobTest::shouldHaveDefaultValue() { TranslateSaveSettingsJob job; verifyDefaultValue(&job); QVERIFY(job.requireHttpAuthentication()); QVERIFY(job.roomId().isEmpty()); QVERIFY(job.language().isEmpty()); QCOMPARE(job.type(), TranslateSaveSettingsJob::Underfined); QVERIFY(!job.autoTranslate()); QVERIFY(!job.hasQueryParameterSupport()); } void TranslateSaveSettingsJobTest::shouldGenerateRequest() { TranslateSaveSettingsJob job; QNetworkRequest request = QNetworkRequest(QUrl()); verifyAuthentication(&job, request); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/autotranslate.saveSettings"))); QCOMPARE(request.header(QNetworkRequest::ContentTypeHeader).toString(), QStringLiteral("application/json")); } void TranslateSaveSettingsJobTest::shouldGenerateJson() { TranslateSaveSettingsJob job; const QString roomId = QStringLiteral("foo1"); job.setRoomId(roomId); const QString targetLanguage = QStringLiteral("bla"); job.setLanguage(targetLanguage); TranslateSaveSettingsJob::SettingType type = TranslateSaveSettingsJob::AutoTranslateSetting; job.setType(type); bool autoTranslate = true; job.setAutoTranslate(autoTranslate); - QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"field\":\"%1\",\"roomId\":\"%2\",\"value\":true}").arg(QStringLiteral("autoTranslate")).arg(roomId).toLatin1()); + QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"field\":\"%1\",\"roomId\":\"%2\",\"value\":true}").arg(QStringLiteral("autoTranslate"), roomId).toLatin1()); type = TranslateSaveSettingsJob::LanguageSetting; job.setType(type); - QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"field\":\"%1\",\"roomId\":\"%2\",\"value\":\"%3\"}").arg(QStringLiteral("autoTranslateLanguage")).arg(roomId).arg(targetLanguage).toLatin1()); + QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"field\":\"%1\",\"roomId\":\"%2\",\"value\":\"%3\"}").arg(QStringLiteral("autoTranslateLanguage"), roomId, targetLanguage).toLatin1()); } void TranslateSaveSettingsJobTest::shouldNotStarting() { TranslateSaveSettingsJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); QNetworkAccessManager mNetworkAccessManager; job.setNetworkAccessManager(&mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); TranslateSaveSettingsJob::SettingType type = TranslateSaveSettingsJob::AutoTranslateSetting; job.setType(type); const QString roomId = QStringLiteral("foo1"); job.setRoomId(roomId); QVERIFY(job.canStart()); type = TranslateSaveSettingsJob::LanguageSetting; job.setType(type); QVERIFY(!job.canStart()); const QString targetLanguage = QStringLiteral("bla"); job.setLanguage(targetLanguage); QVERIFY(job.canStart()); } diff --git a/src/rocketchatrestapi-qt5/autotests/twitterauthjobtest.cpp b/src/rocketchatrestapi-qt5/autotests/twitterauthjobtest.cpp index ff3d53f2..2e450c4f 100644 --- a/src/rocketchatrestapi-qt5/autotests/twitterauthjobtest.cpp +++ b/src/rocketchatrestapi-qt5/autotests/twitterauthjobtest.cpp @@ -1,114 +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 "twitterauthjobtest.h" #include "authentication/twitterauthjob.h" #include "ruqola_restapi_helper.h" #include #include QTEST_GUILESS_MAIN(TwitterAuthJobTest) using namespace RocketChatRestApi; TwitterAuthJobTest::TwitterAuthJobTest(QObject *parent) : QObject(parent) { } void TwitterAuthJobTest::shouldHaveDefaultValue() { TwitterAuthJob job; verifyDefaultValue(&job); QVERIFY(!job.requireHttpAuthentication()); QVERIFY(job.secret().isEmpty()); QVERIFY(job.accessToken().isEmpty()); QCOMPARE(job.expireTokenInSeconds(), -1); QVERIFY(!job.hasQueryParameterSupport()); } void TwitterAuthJobTest::shouldGenerateRequest() { TwitterAuthJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); const QNetworkRequest request = job.request(); QCOMPARE(request.url(), QUrl(QStringLiteral("http://www.kde.org/api/v1/login"))); QCOMPARE(request.header(QNetworkRequest::ContentTypeHeader).toString(), QStringLiteral("application/json")); } void TwitterAuthJobTest::shouldGenerateJson() { TwitterAuthJob job; const QString secret = QStringLiteral("secret:"); job.setSecret(secret); const QString accessToken = QStringLiteral("accessToken"); job.setAccessToken(accessToken); const QString appId = QStringLiteral("appid"); job.setAppId(appId); const QString appSecret = QStringLiteral("appSecret"); job.setAppSecret(appSecret); const int expireToken = 300; job.setExpireTokenInSeconds(expireToken); QCOMPARE(job.json().toJson(QJsonDocument::Compact), QStringLiteral("{\"accessToken\":\"%1\",\"accessTokenSecret\":\"%2\",\"appId\":\"%3\",\"appSecret\":\"%4\",\"expiresIn\":300,\"serviceName\":\"twitter\"}") - .arg(accessToken, secret, appId).arg(appSecret).toLatin1()); + .arg(accessToken, secret, appId, appSecret).toLatin1()); } void TwitterAuthJobTest::shouldNotStarting() { TwitterAuthJob job; RestApiMethod method; method.setServerUrl(QStringLiteral("http://www.kde.org")); job.setRestApiMethod(&method); QNetworkAccessManager mNetworkAccessManager; job.setNetworkAccessManager(&mNetworkAccessManager); QVERIFY(!job.canStart()); const QString auth = QStringLiteral("foo"); const QString userId = QStringLiteral("foo"); job.setAuthToken(auth); QVERIFY(!job.canStart()); job.setUserId(userId); QVERIFY(!job.canStart()); const QString secret = QStringLiteral("secret:"); job.setSecret(secret); QVERIFY(!job.canStart()); const QString accessToken = QStringLiteral("accessToken"); job.setAccessToken(accessToken); QVERIFY(!job.canStart()); const int expireToken = 300; job.setExpireTokenInSeconds(expireToken); QVERIFY(!job.canStart()); const QString appId = QStringLiteral("appid"); job.setAppId(appId); QVERIFY(!job.canStart()); const QString appSecret = QStringLiteral("appSecret"); job.setAppSecret(appSecret); QVERIFY(job.canStart()); }