1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

Merge pull request #5688

Mick Sayson (3):
      feat(offlinemsg): Force offline messages to always be enabled
      refactor(offlinemsg): Decouple OfflineMsgEngine from other components
      feat(offlinemsg): Enable offline messages with no history
This commit is contained in:
Anthony Bilinski 2019-06-09 01:37:26 -07:00
commit 8568a14c93
No known key found for this signature in database
GPG Key ID: 2AA8E0DA1B31FB3C
14 changed files with 401 additions and 122 deletions

View File

@ -27,6 +27,7 @@ auto_test(net toxmedata)
auto_test(net bsu)
auto_test(persistence paths)
auto_test(persistence dbschema)
auto_test(persistence offlinemsgengine)
if (UNIX)
auto_test(platform posixsignalnotifier)

View File

@ -21,10 +21,12 @@
#ifndef CORE_HPP
#define CORE_HPP
#include "groupid.h"
#include "icorefriendmessagesender.h"
#include "receiptnum.h"
#include "toxfile.h"
#include "toxid.h"
#include "toxpk.h"
#include "groupid.h"
#include "src/util/strongtype.h"
#include "src/model/status.h"
@ -47,10 +49,8 @@ class Profile;
class Core;
using ToxCorePtr = std::unique_ptr<Core>;
using ReceiptNum = NamedType<uint32_t, struct ReceiptNumTag>;
Q_DECLARE_METATYPE(ReceiptNum);
class Core : public QObject
class Core : public QObject, public ICoreFriendMessageSender
{
Q_OBJECT
public:
@ -114,11 +114,11 @@ public slots:
void setUsername(const QString& username);
void setStatusMessage(const QString& message);
bool sendMessage(uint32_t friendId, const QString& message, ReceiptNum& receipt);
bool sendMessage(uint32_t friendId, const QString& message, ReceiptNum& receipt) override;
void sendGroupMessage(int groupId, const QString& message);
void sendGroupAction(int groupId, const QString& message);
void changeGroupTitle(int groupId, const QString& title);
bool sendAction(uint32_t friendId, const QString& action, ReceiptNum& receipt);
bool sendAction(uint32_t friendId, const QString& action, ReceiptNum& receipt) override;
void sendTyping(uint32_t friendId, bool typing);
void setNospam(uint32_t nospam);

View File

@ -0,0 +1,36 @@
/*
Copyright © 2019 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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 3 of the License, or
(at your option) any later version.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ICORE_FRIEND_MESSAGE_SENDER_H
#define ICORE_FRIEND_MESSAGE_SENDER_H
#include "receiptnum.h"
#include <QString>
#include <cstdint>
class ICoreFriendMessageSender
{
public:
virtual bool sendAction(uint32_t friendId, const QString& action, ReceiptNum& receipt) = 0;
virtual bool sendMessage(uint32_t friendId, const QString& message, ReceiptNum& receipt) = 0;
};
#endif /* ICORE_FRIEND_MESSAGE_SENDER_H */

31
src/core/receiptnum.h Normal file
View File

@ -0,0 +1,31 @@
/*
Copyright © 2019 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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 3 of the License, or
(at your option) any later version.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RECEIPT_NUM_H
#define RECEIPT_NUM_H
#include "src/util/strongtype.h"
#include <QMetaType>
#include <cstdint>
using ReceiptNum = NamedType<uint32_t, struct ReceiptNumTag>;
Q_DECLARE_METATYPE(ReceiptNum);
#endif /* RECEIPT_NUM_H */

33
src/model/message.h Normal file
View File

@ -0,0 +1,33 @@
/*
Copyright © 2019 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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 3 of the License, or
(at your option) any later version.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MESSAGE_H
#define MESSAGE_H
#include <QDateTime>
#include <QString>
struct Message
{
bool isAction;
QString content;
QDateTime timestamp;
};
#endif /*MESSAGE_H*/

View File

@ -28,11 +28,11 @@
#include <QCoreApplication>
#include <chrono>
OfflineMsgEngine::OfflineMsgEngine(Friend* frnd)
OfflineMsgEngine::OfflineMsgEngine(Friend* frnd, ICoreFriendMessageSender* messageSender)
: mutex(QMutex::Recursive)
, f(frnd)
{
}
, messageSender(messageSender)
{}
/**
* @brief Notification that the message is now delivered.
@ -59,18 +59,10 @@ void OfflineMsgEngine::onReceiptReceived(ReceiptNum receipt)
* @param[in] messageID database RowId of the message, used to eventually mark messages as received in history
* @param[in] msg chat message line in the chatlog, used to eventually set the message's receieved timestamp
*/
void OfflineMsgEngine::addSavedMessage(RowId messageID, ChatMessage::Ptr chatMessage)
void OfflineMsgEngine::addUnsentMessage(Message const& message, CompletionFn completionCallback)
{
QMutexLocker ml(&mutex);
assert([&](){
for (const auto& message : unsentSavedMessages) {
if (message.rowId == messageID) {
return false;
}
}
return true;
}());
unsentSavedMessages.append(Message{chatMessage, messageID, std::chrono::steady_clock::now()});
unsentMessages.append(OfflineMessage{message, std::chrono::steady_clock::now(), completionCallback});
}
/**
@ -83,11 +75,12 @@ void OfflineMsgEngine::addSavedMessage(RowId messageID, ChatMessage::Ptr chatMes
* @param[in] messageID database RowId of the message, used to eventually mark messages as received in history
* @param[in] msg chat message line in the chatlog, used to eventually set the message's receieved timestamp
*/
void OfflineMsgEngine::addSentSavedMessage(ReceiptNum receipt, RowId messageID, ChatMessage::Ptr chatMessage)
void OfflineMsgEngine::addSentMessage(ReceiptNum receipt, Message const& message,
CompletionFn completionCallback)
{
QMutexLocker ml(&mutex);
assert(!sentSavedMessages.contains(receipt));
sentSavedMessages.insert(receipt, {chatMessage, messageID, std::chrono::steady_clock::now()});
assert(!sentMessages.contains(receipt));
sentMessages.insert(receipt, {message, std::chrono::steady_clock::now(), completionCallback});
checkForCompleteMessages(receipt);
}
@ -98,37 +91,35 @@ void OfflineMsgEngine::deliverOfflineMsgs()
{
QMutexLocker ml(&mutex);
if (!Settings::getInstance().getFauxOfflineMessaging()) {
return;
}
if (!f->isOnline()) {
return;
}
if (sentSavedMessages.empty() && unsentSavedMessages.empty()) {
if (sentMessages.empty() && unsentMessages.empty()) {
return;
}
QVector<Message> messages = sentSavedMessages.values().toVector() + unsentSavedMessages;
QVector<OfflineMessage> messages = sentMessages.values().toVector() + unsentMessages;
// order messages by authorship time to resend in same order as they were written
qSort(messages.begin(), messages.end(), [](const Message& lhs, const Message& rhs){ return lhs.authorshipTime < rhs.authorshipTime; });
qSort(messages.begin(), messages.end(), [](const OfflineMessage& lhs, const OfflineMessage& rhs) {
return lhs.authorshipTime < rhs.authorshipTime;
});
removeAllMessages();
for (const auto& message : messages) {
QString messageText = message.chatMessage->toString();
QString messageText = message.message.content;
ReceiptNum receipt;
bool messageSent{false};
if (message.chatMessage->isAction()) {
messageSent = Core::getInstance()->sendAction(f->getId(), messageText, receipt);
if (message.message.isAction) {
messageSent = messageSender->sendAction(f->getId(), messageText, receipt);
} else {
messageSent = Core::getInstance()->sendMessage(f->getId(), messageText, receipt);
messageSent = messageSender->sendMessage(f->getId(), messageText, receipt);
}
if (messageSent) {
addSentSavedMessage(receipt, message.rowId, message.chatMessage);
addSentMessage(receipt, message.message, message.completionFn);
} else {
qCritical() << "deliverOfflineMsgs failed to send message";
addSavedMessage(message.rowId, message.chatMessage);
addUnsentMessage(message.message, message.completionFn);
}
}
}
@ -140,38 +131,23 @@ void OfflineMsgEngine::removeAllMessages()
{
QMutexLocker ml(&mutex);
receivedReceipts.clear();
sentSavedMessages.clear();
unsentSavedMessages.clear();
sentMessages.clear();
unsentMessages.clear();
}
void OfflineMsgEngine::completeMessage(QMap<ReceiptNum, Message>::iterator msgIt)
void OfflineMsgEngine::completeMessage(QMap<ReceiptNum, OfflineMessage>::iterator msgIt)
{
Profile* const profile = Nexus::getProfile();
if (profile->isHistoryEnabled()) {
profile->getHistory()->markAsSent(msgIt->rowId);
}
if (QThread::currentThread() == QCoreApplication::instance()->thread()) {
updateTimestamp(msgIt->chatMessage);
} else {
QMetaObject::invokeMethod(this, "updateTimestamp", Qt::BlockingQueuedConnection, Q_ARG(ChatMessage::Ptr, msgIt->chatMessage));
}
sentSavedMessages.erase(msgIt);
msgIt->completionFn();
sentMessages.erase(msgIt);
receivedReceipts.removeOne(msgIt.key());
}
void OfflineMsgEngine::checkForCompleteMessages(ReceiptNum receipt)
{
auto msgIt = sentSavedMessages.find(receipt);
auto msgIt = sentMessages.find(receipt);
const bool receiptReceived = receivedReceipts.contains(receipt);
if (!receiptReceived || msgIt == sentSavedMessages.end()) {
if (!receiptReceived || msgIt == sentMessages.end()) {
return;
}
assert(!unsentSavedMessages.contains(*msgIt));
completeMessage(msgIt);
}
void OfflineMsgEngine::updateTimestamp(ChatMessage::Ptr msg)
{
msg->markAsSent(QDateTime::currentDateTime());
}

View File

@ -22,6 +22,7 @@
#include "src/chatlog/chatmessage.h"
#include "src/core/core.h"
#include "src/model/message.h"
#include "src/persistence/db/rawdatabase.h"
#include <QDateTime>
#include <QMap>
@ -31,14 +32,17 @@
#include <chrono>
class Friend;
class ICoreFriendMessageSender;
class OfflineMsgEngine : public QObject
{
Q_OBJECT
public:
explicit OfflineMsgEngine(Friend*);
void addSavedMessage(RowId messageID, ChatMessage::Ptr msg);
void addSentSavedMessage(ReceiptNum receipt, RowId messageID, ChatMessage::Ptr msg);
explicit OfflineMsgEngine(Friend* f, ICoreFriendMessageSender* messageSender);
using CompletionFn = std::function<void()>;
void addUnsentMessage(Message const& message, CompletionFn completionCallback);
void addSentMessage(ReceiptNum receipt, Message const& message, CompletionFn completionCallback);
void deliverOfflineMsgs();
public slots:
@ -46,28 +50,25 @@ public slots:
void onReceiptReceived(ReceiptNum receipt);
private:
struct Message
struct OfflineMessage
{
bool operator==(const Message& rhs) const { return rhs.rowId == rowId; }
ChatMessage::Ptr chatMessage;
RowId rowId;
Message message;
std::chrono::time_point<std::chrono::steady_clock> authorshipTime;
CompletionFn completionFn;
};
private slots:
void completeMessage(QMap<ReceiptNum, Message>::iterator msgIt);
private slots:
void updateTimestamp(ChatMessage::Ptr msg);
void completeMessage(QMap<ReceiptNum, OfflineMessage>::iterator msgIt);
private:
void checkForCompleteMessages(ReceiptNum receipt);
QMutex mutex;
const Friend* f;
ICoreFriendMessageSender* messageSender;
QVector<ReceiptNum> receivedReceipts;
QMap<ReceiptNum, Message> sentSavedMessages;
QVector<Message> unsentSavedMessages;
QMap<ReceiptNum, OfflineMessage> sentMessages;
QVector<OfflineMessage> unsentMessages;
};
#endif // OFFLINEMSGENGINE_H

View File

@ -156,7 +156,6 @@ void Settings::loadGlobal()
notifySound = s.value("notifySound", true).toBool(); // note: notifySound and busySound UI elements are now under UI settings
notifyHide = s.value("notifyHide", false).toBool();
busySound = s.value("busySound", false).toBool(); // page, but kept under General in settings file to be backwards compatible
fauxOfflineMessaging = s.value("fauxOfflineMessaging", true).toBool();
autoSaveEnabled = s.value("autoSaveEnabled", false).toBool();
globalAutoAcceptDir = s.value("globalAutoAcceptDir",
QStandardPaths::locate(QStandardPaths::HomeLocation, QString(),
@ -438,7 +437,6 @@ void Settings::saveGlobal()
s.setValue("notifySound", notifySound);
s.setValue("notifyHide", notifyHide);
s.setValue("busySound", busySound);
s.setValue("fauxOfflineMessaging", fauxOfflineMessaging);
s.setValue("autoSaveEnabled", autoSaveEnabled);
s.setValue("autoAcceptMaxSize", static_cast<qlonglong>(autoAcceptMaxSize));
s.setValue("globalAutoAcceptDir", globalAutoAcceptDir);
@ -2080,22 +2078,6 @@ void Settings::removeFriendSettings(const ToxPk& id)
friendLst.remove(id.getByteArray());
}
bool Settings::getFauxOfflineMessaging() const
{
QMutexLocker locker{&bigLock};
return fauxOfflineMessaging;
}
void Settings::setFauxOfflineMessaging(bool value)
{
QMutexLocker locker{&bigLock};
if (value != fauxOfflineMessaging) {
fauxOfflineMessaging = value;
emit fauxOfflineMessagingChanged(fauxOfflineMessaging);
}
}
bool Settings::getCompactLayout() const
{
QMutexLocker locker{&bigLock};

View File

@ -226,7 +226,6 @@ signals:
void dateFormatChanged(const QString& format);
void statusChangeNotificationEnabledChanged(bool enabled);
void spellCheckingEnabledChanged(bool enabled);
void fauxOfflineMessagingChanged(bool enabled);
// Privacy
void typingNotificationChanged(bool enabled);
@ -520,9 +519,6 @@ public:
SIGNAL_IMPL(Settings, autoAcceptDirChanged, const ToxPk& id, const QString& dir)
SIGNAL_IMPL(Settings, contactNoteChanged, const ToxPk& id, const QString& note)
bool getFauxOfflineMessaging() const;
void setFauxOfflineMessaging(bool value);
bool getCompactLayout() const;
void setCompactLayout(bool compact);
@ -604,7 +600,6 @@ private:
bool dontShowDhtDialog;
bool autoLogin;
bool fauxOfflineMessaging;
bool compactLayout;
FriendListSortingMode sortingMode;
bool groupchatPosition;

View File

@ -102,6 +102,30 @@ namespace
return cD + res.sprintf("%02ds", seconds);
}
void completeMessage(ChatMessage::Ptr ma, RowId rowId)
{
auto profile = Nexus::getProfile();
if (profile->isHistoryEnabled()) {
profile->getHistory()->markAsSent(rowId);
}
// force execution on the gui thread
QTimer::singleShot(0, QCoreApplication::instance(), [ma] {
ma->markAsSent(QDateTime::currentDateTime());
});
}
struct CompleteMessageFunctor
{
void operator()() const
{
completeMessage(ma, rowId);
}
ChatMessage::Ptr ma;
RowId rowId;
};
} // namespace
ChatForm::ChatForm(Friend* chatFriend, History* history)
@ -122,7 +146,7 @@ ChatForm::ChatForm(Friend* chatFriend, History* history)
statusMessageLabel->setTextFormat(Qt::PlainText);
statusMessageLabel->setContextMenuPolicy(Qt::CustomContextMenu);
offlineEngine = new OfflineMsgEngine(f);
offlineEngine = new OfflineMsgEngine(f, Core::getInstance());
typingTimer.setSingleShot(true);
@ -922,20 +946,26 @@ void ChatForm::sendLoadedMessage(ChatMessage::Ptr chatMsg, MessageMetadata const
ReceiptNum receipt;
bool messageSent{false};
QString stringMsg = chatMsg->toString();
if (f->isOnline()) {
Core* core = Core::getInstance();
uint32_t friendId = f->getId();
QString stringMsg = chatMsg->toString();
messageSent = metadata.isAction ? core->sendAction(friendId, stringMsg, receipt)
: core->sendMessage(friendId, stringMsg, receipt);
if (!messageSent) {
qWarning() << "Failed to send loaded message, adding to offline messaging";
}
}
auto onCompletion = CompleteMessageFunctor{};
onCompletion.ma = chatMsg;
onCompletion.rowId = metadata.id;
auto modelMsg = Message{metadata.isAction, stringMsg, QDateTime::currentDateTime()};
if (messageSent) {
getOfflineMsgEngine()->addSentSavedMessage(receipt, metadata.id, chatMsg);
getOfflineMsgEngine()->addSentMessage(receipt, modelMsg, onCompletion);
} else {
getOfflineMsgEngine()->addSavedMessage(metadata.id, chatMsg);
getOfflineMsgEngine()->addUnsentMessage(modelMsg, onCompletion);
}
}
@ -1139,23 +1169,40 @@ void ChatForm::SendMessageStr(QString msg)
ChatMessage::Ptr ma = createSelfMessage(part, timestamp, isAction, false);
Message modelMsg{isAction, part, timestamp};
if (history && Settings::getInstance().getEnableLogging()) {
auto* offMsgEngine = getOfflineMsgEngine();
QString selfPk = Core::getInstance()->getSelfId().toString();
QString pk = f->getPublicKey().toString();
QString name = Core::getInstance()->getUsername();
bool isSent = !Settings::getInstance().getFauxOfflineMessaging();
bool const isSent = false; // This forces history to add it to the offline messages table
// Use functor to avoid having to declare a lambda in a lambda
CompleteMessageFunctor onCompletion;
onCompletion.ma = ma;
history->addNewMessage(pk, historyPart, selfPk, timestamp, isSent, name,
[messageSent, offMsgEngine, receipt, ma](RowId id) {
if (messageSent) {
offMsgEngine->addSentSavedMessage(receipt, id, ma);
} else {
offMsgEngine->addSavedMessage(id, ma);
}
[messageSent, offMsgEngine, receipt, modelMsg,
onCompletion](RowId id) mutable {
onCompletion.rowId = id;
if (messageSent) {
offMsgEngine->addSentMessage(receipt, modelMsg,
onCompletion);
} else {
offMsgEngine->addUnsentMessage(modelMsg, onCompletion);
}
});
} else {
// TODO: Make faux-offline messaging work partially with the history disabled
ma->markAsSent(QDateTime::currentDateTime());
if (messageSent) {
offlineEngine->addSentMessage(receipt, modelMsg,
[ma] { ma->markAsSent(QDateTime::currentDateTime()); });
} else {
offlineEngine->addUnsentMessage(modelMsg, [ma] {
ma->markAsSent(QDateTime::currentDateTime());
});
}
}
// set last message only when sending it

View File

@ -144,7 +144,6 @@ GeneralForm::GeneralForm(SettingsWidget* myParent)
bodyUI->closeToTray->setEnabled(showSystemTray);
bodyUI->statusChanges->setChecked(s.getStatusChangeNotificationEnabled());
bodyUI->cbFauxOfflineMessaging->setChecked(s.getFauxOfflineMessaging());
bodyUI->autoAwaySpinBox->setValue(s.getAutoAwayTime());
bodyUI->autoSaveFilesDir->setText(s.getGlobalAutoAcceptDir());
@ -217,11 +216,6 @@ void GeneralForm::on_statusChanges_stateChanged()
Settings::getInstance().setStatusChangeNotificationEnabled(bodyUI->statusChanges->isChecked());
}
void GeneralForm::on_cbFauxOfflineMessaging_stateChanged()
{
Settings::getInstance().setFauxOfflineMessaging(bodyUI->cbFauxOfflineMessaging->isChecked());
}
void GeneralForm::on_autoAwaySpinBox_editingFinished()
{
int minutes = bodyUI->autoAwaySpinBox->value();

View File

@ -50,8 +50,6 @@ private slots:
void on_autoAwaySpinBox_editingFinished();
void on_minimizeToTray_stateChanged();
void on_statusChanges_stateChanged();
void on_cbFauxOfflineMessaging_stateChanged();
void on_autoacceptFiles_stateChanged();
void on_maxAutoAcceptSizeMB_editingFinished();
void on_autoSaveFilesDir_clicked();

View File

@ -222,13 +222,6 @@ instead of closing itself.</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="cbFauxOfflineMessaging">
<property name="text">
<string>Faux offline messaging</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
@ -371,7 +364,6 @@ instead of closing itself.</string>
<tabstop>minimizeToTray</tabstop>
<tabstop>closeToTray</tabstop>
<tabstop>statusChanges</tabstop>
<tabstop>cbFauxOfflineMessaging</tabstop>
<tabstop>autoAwaySpinBox</tabstop>
<tabstop>autoSaveFilesDir</tabstop>
<tabstop>autoacceptFiles</tabstop>

View File

@ -0,0 +1,193 @@
/*
Copyright © 2019 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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 3 of the License, or
(at your option) any later version.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "src/core/core.h"
#include "src/model/friend.h"
#include "src/persistence/offlinemsgengine.h"
#include <QtTest/QtTest>
struct MockFriendMessageSender : public QObject, public ICoreFriendMessageSender
{
Q_OBJECT
public:
MockFriendMessageSender(Friend* f)
: f(f){};
bool sendAction(uint32_t friendId, const QString& action, ReceiptNum& receipt) override
{
return false;
}
bool sendMessage(uint32_t friendId, const QString& message, ReceiptNum& receipt) override
{
if (f->isOnline()) {
receipt.get() = receiptNum++;
if (!dropReceipts) {
msgs.push_back(message);
emit receiptReceived(receipt);
}
numMessagesSent++;
} else {
numMessagesFailed++;
}
return f->isOnline();
}
signals:
void receiptReceived(ReceiptNum receipt);
public:
Friend* f;
bool dropReceipts = false;
size_t numMessagesSent = 0;
size_t numMessagesFailed = 0;
int receiptNum = 0;
std::vector<QString> msgs;
};
class TestOfflineMsgEngine : public QObject
{
Q_OBJECT
private slots:
void testReceiptResolution();
void testOfflineFriend();
void testSentUnsentCoordination();
void testCallback();
};
class OfflineMsgEngineFixture
{
public:
OfflineMsgEngineFixture()
: f(0, ToxPk(QByteArray(32, 0)))
, friendMessageSender(&f)
, offlineMsgEngine(&f, &friendMessageSender)
{
f.setStatus(Status::Status::Online);
QObject::connect(&friendMessageSender, &MockFriendMessageSender::receiptReceived,
&offlineMsgEngine, &OfflineMsgEngine::onReceiptReceived);
}
Friend f;
MockFriendMessageSender friendMessageSender;
OfflineMsgEngine offlineMsgEngine;
};
void completionFn() {}
void TestOfflineMsgEngine::testReceiptResolution()
{
OfflineMsgEngineFixture fixture;
Message msg{false, QString(), QDateTime()};
ReceiptNum receipt;
fixture.friendMessageSender.sendMessage(0, msg.content, receipt);
fixture.offlineMsgEngine.addSentMessage(receipt, msg, completionFn);
// We should have no offline messages to deliver if we resolved our receipt
// correctly
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
QVERIFY(fixture.friendMessageSender.numMessagesSent == 1);
// If we drop receipts we should keep trying to send messages every time we
// "deliverOfflineMsgs"
fixture.friendMessageSender.dropReceipts = true;
fixture.friendMessageSender.sendMessage(0, msg.content, receipt);
fixture.offlineMsgEngine.addSentMessage(receipt, msg, completionFn);
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
QVERIFY(fixture.friendMessageSender.numMessagesSent == 5);
// And once we stop dropping and try one more time we should run out of
// messages to send again
fixture.friendMessageSender.dropReceipts = false;
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
fixture.offlineMsgEngine.deliverOfflineMsgs();
QVERIFY(fixture.friendMessageSender.numMessagesSent == 6);
}
void TestOfflineMsgEngine::testOfflineFriend()
{
OfflineMsgEngineFixture fixture;
Message msg{false, QString(), QDateTime()};
fixture.f.setStatus(Status::Status::Offline);
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.f.setStatus(Status::Status::Online);
fixture.offlineMsgEngine.deliverOfflineMsgs();
QVERIFY(fixture.friendMessageSender.numMessagesFailed == 0);
QVERIFY(fixture.friendMessageSender.numMessagesSent == 5);
}
void TestOfflineMsgEngine::testSentUnsentCoordination()
{
OfflineMsgEngineFixture fixture;
Message msg{false, QString("a"), QDateTime()};
ReceiptNum receipt;
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
msg.content = "b";
fixture.friendMessageSender.dropReceipts = true;
fixture.friendMessageSender.sendMessage(0, msg.content, receipt);
fixture.friendMessageSender.dropReceipts = false;
fixture.offlineMsgEngine.addSentMessage(receipt, msg, completionFn);
msg.content = "c";
fixture.offlineMsgEngine.addUnsentMessage(msg, completionFn);
fixture.offlineMsgEngine.deliverOfflineMsgs();
auto expectedResponseOrder = std::vector<QString>{"a", "b", "c"};
QVERIFY(fixture.friendMessageSender.msgs == expectedResponseOrder);
}
void TestOfflineMsgEngine::testCallback()
{
OfflineMsgEngineFixture fixture;
size_t numCallbacks = 0;
auto callback = [&numCallbacks] { numCallbacks++; };
Message msg{false, QString(), QDateTime()};
ReceiptNum receipt;
fixture.friendMessageSender.sendMessage(0, msg.content, receipt);
fixture.offlineMsgEngine.addSentMessage(receipt, msg, callback);
fixture.offlineMsgEngine.addUnsentMessage(msg, callback);
fixture.offlineMsgEngine.deliverOfflineMsgs();
QVERIFY(numCallbacks == 2);
}
QTEST_GUILESS_MAIN(TestOfflineMsgEngine)
#include "offlinemsgengine_test.moc"