From fd92236ab368e1f538c95233e8cec17c12c783e0 Mon Sep 17 00:00:00 2001 From: Chukwudi Nwutobo Date: Mon, 3 Jan 2022 11:51:31 +0100 Subject: [PATCH] Some fixes --- resources/qml/ArchivedChatPage.qml | 9 +- resources/qml/AuthenticationPage.qml | 41 ++++-- resources/qml/MainPage.qml | 13 +- resources/qml/MessagePage.qml | 8 +- resources/qml/components/AboutDialog.qml | 2 +- resources/qml/components/ChatItem.qml | 2 +- resources/qml/components/MessageBubble.qml | 2 +- resources/qml/main.qml | 4 +- src/ChatModel.cpp | 45 +++--- src/ChatModel.hpp | 10 +- src/Stores.cpp | 108 ++++++++------ src/Stores.hpp | 18 ++- src/TdApi.cpp | 163 +++++++++------------ src/TdApi.hpp | 5 - src/Utils.cpp | 8 +- 15 files changed, 231 insertions(+), 207 deletions(-) diff --git a/resources/qml/ArchivedChatPage.qml b/resources/qml/ArchivedChatPage.qml index 50022ae..8d6a3bf 100644 --- a/resources/qml/ArchivedChatPage.qml +++ b/resources/qml/ArchivedChatPage.qml @@ -40,8 +40,8 @@ Page { BusyIndicator { anchors.centerIn: listView - running: populateTimer.running - visible: populateTimer.running + running: populateTimer.running || myChatModel.loading + visible: running platformStyle: BusyIndicatorStyle { size: "large" } } @@ -49,7 +49,10 @@ Page { id: myChatModel chatList: TdApi.ChatListArchive - Component.onCompleted: populateTimer.restart() + onLoadingChanged: { + if (!loading) + populateTimer.restart() + } } ContextMenu { diff --git a/resources/qml/AuthenticationPage.qml b/resources/qml/AuthenticationPage.qml index 0c40dea..d842194 100644 --- a/resources/qml/AuthenticationPage.qml +++ b/resources/qml/AuthenticationPage.qml @@ -18,6 +18,8 @@ Sheet { property alias __nextTypeString: nextTypeLabel.text property int __length + property bool loading: false + rejectButtonText: "Cancel" state: "Phone" @@ -102,7 +104,7 @@ Sheet { Button { anchors.horizontalCenter: parent.horizontalCenter - enabled: !tdapi.busy + enabled: !sheet.loading text: qsTr("Next") width: parent.width / 2 @@ -111,11 +113,13 @@ Sheet { onClicked: { if (phoneNumber.text.length > 0) { tdapi.setPhoneNumber(countryCodeButton.text + phoneNumber.text) + + sheet.loading = true; } } BusyIndicator { - visible: tdapi.busy + visible: sheet.loading running: visible anchors.centerIn: parent } @@ -160,7 +164,7 @@ Sheet { Button { anchors.horizontalCenter: parent.horizontalCenter - enabled: !tdapi.busy + enabled: !sheet.loading text: qsTr("Next") width: parent.width / 2 @@ -171,7 +175,7 @@ Sheet { } BusyIndicator { - visible: tdapi.busy + visible: sheet.loading running: visible anchors.centerIn: parent } @@ -278,7 +282,7 @@ Sheet { Button { anchors.horizontalCenter: parent.horizontalCenter - enabled: !tdapi.busy + enabled: !sheet.loading text: qsTr("Next") width: parent.width / 2 @@ -291,7 +295,7 @@ Sheet { } BusyIndicator { - visible: tdapi.busy + visible: sheet.loading running: visible anchors.centerIn: parent } @@ -345,7 +349,7 @@ Sheet { Button { anchors.horizontalCenter: parent.horizontalCenter - enabled: !tdapi.busy + enabled: !sheet.loading width: parent.width / 2 text: qsTr("Done") @@ -356,7 +360,7 @@ Sheet { } BusyIndicator { - visible: tdapi.busy + visible: sheet.loading running: visible anchors.centerIn: parent } @@ -427,16 +431,22 @@ Sheet { __isNextTypeSms = codeInfo.isNextTypeSms __length = codeInfo.length + + sheet.loading = false } onRegistrationRequested: { state = "Registration"; termsOfServiceString = termsOfService.text + + sheet.loading = false } onPasswordRequested: { state = "Password" passwordHint = passwordInfo.passwordHint + + sheet.loading = false } onIsAuthorizedChanged: { @@ -445,10 +455,23 @@ Sheet { } } + Timer { + id: loadingTimer + + interval: 10000 + repeat: false + onTriggered: { sheet.loading = false; } + } + + onLoadingChanged: { + if (loading) + loadingTimer.restart() + } + onTimeoutChanged: { codeExpireTimer.start() codeTimeText.text = Utils.formatTime(timeout / 1000) } - onRejected: tdapi.busy = false + onRejected: sheet.loading = false } diff --git a/resources/qml/MainPage.qml b/resources/qml/MainPage.qml index 96f9945..199fae2 100644 --- a/resources/qml/MainPage.qml +++ b/resources/qml/MainPage.qml @@ -79,13 +79,13 @@ Page { font.pixelSize: 60 color: "gray" text: qsTr("NoChats") - visible: myChatModel.count === 0 && !populateTimer.running && tdapi.isAuthorized + visible: myChatModel.count === 0 && !populateTimer.running && !myChatModel.loading } BusyIndicator { anchors.centerIn: listView - running: populateTimer.running - visible: populateTimer.running + running: populateTimer.running || myChatModel.loading + visible: running platformStyle: BusyIndicatorStyle { size: "large" } } @@ -174,7 +174,10 @@ Page { id: myChatModel chatList: TdApi.ChatListMain - onChatListChanged: { populateTimer.restart() } + onLoadingChanged: { + if (!loading) + populateTimer.restart() + } } ContextMenu { @@ -197,7 +200,7 @@ Page { onIsAuthorizedChanged: { if (tdapi.isAuthorized) - populateTimer.restart() + myChatModel.refresh() } } diff --git a/resources/qml/MessagePage.qml b/resources/qml/MessagePage.qml index 06f7d60..365d61a 100644 --- a/resources/qml/MessagePage.qml +++ b/resources/qml/MessagePage.qml @@ -6,7 +6,7 @@ import "components" Page { id: root - property variant chat: null + property string chatId: "" property string messageThreadId: "" property string replyToMessageId: "" @@ -81,7 +81,7 @@ Page { height: 50 width: 50 - source: chat.photo ? "image://telegram/" + chat.photo.small.local.path : "image://theme/icon-l-content-avatar-placeholder" + source: myMessageModel.chat.photo ? "image://telegram/" + myMessageModel.chat.photo.small.local.path : "image://theme/icon-l-content-avatar-placeholder" MouseArea { anchors.fill: parent @@ -360,10 +360,10 @@ Page { text: message } } - tdapi.sendMessage(chat.id, messageThreadId, replyToMessageId, options, replyMarkup, inputMessageContent) + tdapi.sendMessage(myMessageModel.chat.id, messageThreadId, replyToMessageId, options, replyMarkup, inputMessageContent) } } - Component.onCompleted: myMessageModel.openChat(chat.id) + Component.onCompleted: myMessageModel.openChat(chatId) Component.onDestruction: myMessageModel.closeChat() } diff --git a/resources/qml/components/AboutDialog.qml b/resources/qml/components/AboutDialog.qml index d57206d..1a91080 100644 --- a/resources/qml/components/AboutDialog.qml +++ b/resources/qml/components/AboutDialog.qml @@ -58,7 +58,7 @@ Dialog { wrapMode: Text.WordWrap horizontalAlignment: Text.AlignHCenter color: "white" - text: "Copyright \u00a9 2021 Chukwudi Nwutobo
Contact: nwutobo@outlook.com" + text: "Copyright \u00a9 2022 Chukwudi Nwutobo
Contact: nwutobo@outlook.com" onLinkActivated: Qt.openUrlExternally(link) } } diff --git a/resources/qml/components/ChatItem.qml b/resources/qml/components/ChatItem.qml index 2166bf8..c03e420 100644 --- a/resources/qml/components/ChatItem.qml +++ b/resources/qml/components/ChatItem.qml @@ -133,7 +133,7 @@ Item { anchors.fill: parent onClicked: { - pageStack.push(Qt.createComponent("qrc:/qml/MessagePage.qml"), { chat: myChatModel.get(index) }) + pageStack.push(Qt.createComponent("qrc:/qml/MessagePage.qml"), { chatId: myChatModel.get(index).id }) } onPressAndHold: root.pressAndHold() } diff --git a/resources/qml/components/MessageBubble.qml b/resources/qml/components/MessageBubble.qml index 9b5bbed..adb9229 100644 --- a/resources/qml/components/MessageBubble.qml +++ b/resources/qml/components/MessageBubble.qml @@ -84,7 +84,7 @@ Item { color: isOutgoing ? "black" : "white" font.pixelSize: 16 font.weight: Font.Light - horizontalAlignment: isOutgoing ? Text.AlignLeft : Text.AlignRight + horizontalAlignment: isServiceMessage ? Text.AlignHCenter : isOutgoing ? Text.AlignLeft : Text.AlignRight visible: !isServiceMessage } diff --git a/resources/qml/main.qml b/resources/qml/main.qml index df554c9..7d610fd 100644 --- a/resources/qml/main.qml +++ b/resources/qml/main.qml @@ -18,11 +18,9 @@ PageStackWindow { Connections { target: tdapi onError: { - banner.text = data.message - if (data.code !== "404") { + banner.text = data.message banner.show() - console.log(data.message, data.code) } } } diff --git a/src/ChatModel.cpp b/src/ChatModel.cpp index d11dd47..97c1c69 100644 --- a/src/ChatModel.cpp +++ b/src/ChatModel.cpp @@ -5,31 +5,35 @@ #include -#include - #include ChatModel::ChatModel(QObject *parent) : QAbstractListModel(parent) , m_sortTimer(new QTimer(this)) + , m_loadingTimer(new QTimer(this)) { connect(TdApi::getInstance().chatStore, SIGNAL(updateChatItem(qint64)), SLOT(handleChatItem(qint64))); connect(TdApi::getInstance().chatStore, SIGNAL(updateChatPosition(qint64)), SLOT(handleChatPosition(qint64))); + connect(&TdApi::getInstance(), SIGNAL(error(const QVariantMap &)), SLOT(handleError(const QVariantMap &))); - connect(this, SIGNAL(chatListChanged()), SLOT(refresh())); - connect(m_sortTimer, SIGNAL(timeout()), SLOT(sortChats())); + connect(this, SIGNAL(chatListChanged()), this, SLOT(refresh())); + + connect(m_sortTimer, SIGNAL(timeout()), this, SLOT(sortChats())); + connect(m_loadingTimer, SIGNAL(timeout()), this, SLOT(loadChats())); + m_sortTimer->setInterval(1000); m_sortTimer->setSingleShot(true); + m_loadingTimer->setInterval(500); + setRoleNames(roleNames()); - loadChats(); } ChatModel::~ChatModel() { - if (m_sortTimer) - delete m_sortTimer; + delete m_sortTimer; + delete m_loadingTimer; } int ChatModel::rowCount(const QModelIndex &parent) const @@ -53,9 +57,6 @@ void ChatModel::fetchMore(const QModelIndex &parent) if (parent.isValid()) return; - if (m_loading) - loadChats(); - const int remainder = m_chatIds.size() - m_count; const auto itemsToFetch = qMin(ChatSliceLimit, remainder); @@ -68,8 +69,6 @@ void ChatModel::fetchMore(const QModelIndex &parent) endInsertRows(); - populate(); - emit countChanged(); } @@ -229,14 +228,19 @@ void ChatModel::populate() if (!chat.value("photo").isNull() && !chatPhoto.value("small").toMap().value("local").toMap().value("is_downloading_completed").toBool()) { - TdApi::getInstance().downloadFile(chatPhoto.value("small").toMap().value("id").toInt(), 1, 0, 0, false); + QVariantMap result; + result.insert("@type", "downloadFile"); + result.insert("file_id", chatPhoto.value("small").toMap().value("id").toInt()); + result.insert("priority", 1); + + TdApi::getInstance().sendRequest(result); } } } sortChats(); - if (m_count == 0 && !m_chatIds.isEmpty()) + if (!m_chatIds.isEmpty()) fetchMore(); } @@ -256,7 +260,8 @@ void ChatModel::refresh() m_loading = true; clear(); - loadChats(); + + m_loadingTimer->start(); emit loadingChanged(); } @@ -279,16 +284,10 @@ void ChatModel::handleChatItem(qint64 chatId) auto index = std::distance(m_chatIds.begin(), it); QModelIndex modelIndex = createIndex(static_cast(index), 0); - qDebug() << chatId; - emit dataChanged(modelIndex, modelIndex); } } -void ChatModel::handleChatPhoto(int fileId) -{ -} - void ChatModel::handleChatPosition(qint64 chatId) { auto it = std::ranges::find_if(m_chatIds, [chatId](qint64 id) { return id == chatId; }); @@ -303,9 +302,11 @@ void ChatModel::handleChatPosition(qint64 chatId) void ChatModel::handleError(const QVariantMap &error) { - if (error.value("@extra").toString() == "load_chats_error" && error.value("@extra").toInt() == 404) + if (error.value("@extra").toByteArray() == "load_chats_error" && error.value("code").toInt() == 404) { m_loading = false; + m_loadingTimer->stop(); + emit loadingChanged(); } } diff --git a/src/ChatModel.hpp b/src/ChatModel.hpp index e51903f..bce9bb6 100644 --- a/src/ChatModel.hpp +++ b/src/ChatModel.hpp @@ -63,18 +63,19 @@ class ChatModel : public QAbstractListModel public slots: void populate(); - void clear(); void refresh(); - void sortChats(); private slots: + void loadChats(); + void sortChats(); + void handleChatItem(qint64 chatId); - void handleChatPhoto(int fileId); void handleChatPosition(qint64 chatId); void handleError(const QVariantMap &error); + private: - void loadChats(); + void clear(); bool m_loading{true}; @@ -84,6 +85,7 @@ private slots: TdApi::ChatList m_chatList{TdApi::ChatListMain}; QTimer *m_sortTimer; + QTimer *m_loadingTimer; QVector m_chatIds; diff --git a/src/Stores.cpp b/src/Stores.cpp index 5e1f278..381e50c 100644 --- a/src/Stores.cpp +++ b/src/Stores.cpp @@ -14,16 +14,20 @@ void BasicGroupStore::initialize(TdApi *controller) QVariantMap BasicGroupStore::get(qint64 groupId) const { - if (m_basicGroup.contains(groupId)) - return m_basicGroup.value(groupId); + if (auto it = m_basicGroup.find(groupId); it != m_basicGroup.end()) + { + return it->second; + } return {}; } QVariantMap BasicGroupStore::getFullInfo(qint64 groupId) const { - if (m_fullInfo.contains(groupId)) - return m_fullInfo.value(groupId); + if (auto it = m_fullInfo.find(groupId); it != m_fullInfo.end()) + { + return it->second; + } return {}; } @@ -32,12 +36,12 @@ void BasicGroupStore::handleUpdateBasicGroup(const QVariantMap &basicGroup) { auto groupId = basicGroup.value("id").toLongLong(); - m_basicGroup.insert(groupId, basicGroup); + m_basicGroup.emplace(groupId, basicGroup); } void BasicGroupStore::handleUpdateBasicGroupFullInfo(qint64 basicGroupId, const QVariantMap &basicGroupFullInfo) { - m_fullInfo.insert(basicGroupId, basicGroupFullInfo); + m_fullInfo.emplace(basicGroupId, basicGroupFullInfo); } void ChatStore::initialize(TdApi *controller) @@ -68,27 +72,33 @@ void ChatStore::initialize(TdApi *controller) QList ChatStore::getIds() const noexcept { - return m_chats.keys(); + QList result; + result.reserve(m_chats.size()); + + std::ranges::transform(m_chats, std::back_inserter(result), [](const auto &value) { return value.first; }); + return result; } QVariantMap ChatStore::get(qint64 chatId) const { - if (m_chats.contains(chatId)) - return m_chats.value(chatId); + if (auto it = m_chats.find(chatId); it != m_chats.end()) + { + return it->second; + } return {}; } void ChatStore::handleNewChat(const QVariantMap &chat) { - m_chats.insert(chat.value("id").toLongLong(), chat); + m_chats.emplace(chat.value("id").toLongLong(), chat); } void ChatStore::handleChatTitle(qint64 chatId, const QString &title) { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("title", title); + it->second.insert("title", title); emit updateChatItem(chatId); } @@ -98,7 +108,7 @@ void ChatStore::handleChatPhoto(qint64 chatId, const QVariantMap &photo) { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("photo", photo); + it->second.insert("photo", photo); emit updateChatItem(chatId); } @@ -108,7 +118,7 @@ void ChatStore::handleChatPermissions(qint64 chatId, const QVariantMap &permissi { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("permissions", permissions); + it->second.insert("permissions", permissions); emit updateChatItem(chatId); } @@ -118,7 +128,7 @@ void ChatStore::handleChatLastMessage(qint64 chatId, const QVariantMap &lastMess { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("last_message", lastMessage); + it->second.insert("last_message", lastMessage); if (not positions.isEmpty()) emit updateChatPosition(chatId); @@ -138,7 +148,7 @@ void ChatStore::handleChatIsMarkedAsUnread(qint64 chatId, bool isMarkedAsUnread) { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("is_marked_as_unread", isMarkedAsUnread); + it->second.insert("is_marked_as_unread", isMarkedAsUnread); emit updateChatItem(chatId); } @@ -148,7 +158,7 @@ void ChatStore::handleChatIsBlocked(qint64 chatId, bool isBlocked) { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("is_blocked", isBlocked); + it->second.insert("is_blocked", isBlocked); emit updateChatItem(chatId); } @@ -158,7 +168,7 @@ void ChatStore::handleChatHasScheduledMessages(qint64 chatId, bool hasScheduledM { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("has_scheduled_messages", hasScheduledMessages); + it->second.insert("has_scheduled_messages", hasScheduledMessages); emit updateChatItem(chatId); } @@ -168,7 +178,7 @@ void ChatStore::handleChatDefaultDisableNotification(qint64 chatId, bool default { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("default_disable_notification", defaultDisableNotification); + it->second.insert("default_disable_notification", defaultDisableNotification); emit updateChatItem(chatId); } @@ -178,8 +188,8 @@ void ChatStore::handleChatReadInbox(qint64 chatId, qint64 lastReadInboxMessageId { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("last_read_inbox_message_id", lastReadInboxMessageId); - it->insert("unread_count", unreadCount); + it->second.insert("last_read_inbox_message_id", lastReadInboxMessageId); + it->second.insert("unread_count", unreadCount); emit updateChatItem(chatId); } @@ -189,7 +199,7 @@ void ChatStore::handleChatReadOutbox(qint64 chatId, qint64 lastReadOutboxMessage { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("last_read_outbox_message_id", lastReadOutboxMessageId); + it->second.insert("last_read_outbox_message_id", lastReadOutboxMessageId); emit updateChatItem(chatId); } @@ -199,7 +209,7 @@ void ChatStore::handleChatUnreadMentionCount(qint64 chatId, int unreadMentionCou { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("unread_mention_count", unreadMentionCount); + it->second.insert("unread_mention_count", unreadMentionCount); emit updateChatItem(chatId); } @@ -209,7 +219,7 @@ void ChatStore::handleChatNotificationSettings(qint64 chatId, const QVariantMap { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("notification_settings", notificationSettings); + it->second.insert("notification_settings", notificationSettings); emit updateChatItem(chatId); } @@ -219,7 +229,7 @@ void ChatStore::handleChatActionBar(qint64 chatId, const QVariantMap &actionBar) { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("action_bar", actionBar); + it->second.insert("action_bar", actionBar); emit updateChatItem(chatId); } @@ -229,7 +239,7 @@ void ChatStore::handleChatReplyMarkup(qint64 chatId, qint64 replyMarkupMessageId { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("reply_markup_message_id", replyMarkupMessageId); + it->second.insert("reply_markup_message_id", replyMarkupMessageId); emit updateChatItem(chatId); } @@ -239,7 +249,7 @@ void ChatStore::handleChatDraftMessage(qint64 chatId, const QVariantMap &draftMe { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - it->insert("draft_message", draftMessage); + it->second.insert("draft_message", draftMessage); if (not positions.isEmpty()) emit updateChatPosition(chatId); @@ -254,7 +264,7 @@ void ChatStore::setChatPositions(qint64 chatId, const QVariantList &positions) n { if (auto it = m_chats.find(chatId); it != m_chats.end()) { - QVariantList result(it->value("positions").toList()); + QVariantList result(it->second.value("positions").toList()); std::ranges::for_each(positions, [&result](const auto &position) { result.erase(std::remove_if(result.begin(), result.end(), @@ -267,7 +277,7 @@ void ChatStore::setChatPositions(qint64 chatId, const QVariantList &positions) n result.append(position); }); - it->insert("positions", QVariantList() << result); + it->second.insert("positions", QVariantList() << result); } } @@ -278,15 +288,17 @@ void FileStore::initialize(TdApi *controller) QVariantMap FileStore::get(int fileId) const { - if (m_files.contains(fileId)) - return m_files.value(fileId); + if (auto it = m_files.find(fileId); it != m_files.end()) + { + return it->second; + } return {}; } void FileStore::handleUpdateFile(const QVariantMap &file) { - m_files.insert(file.value("id").toInt(), file); + m_files.emplace(file.value("id").toInt(), file); } void OptionStore::initialize(TdApi *controller) @@ -317,28 +329,32 @@ void SupergroupStore::initialize(TdApi *controller) QVariantMap SupergroupStore::get(qint64 groupId) const { - if (m_supergroup.contains(groupId)) - return m_supergroup.value(groupId); + if (auto it = m_supergroup.find(groupId); it != m_supergroup.end()) + { + return it->second; + } return {}; } QVariantMap SupergroupStore::getFullInfo(qint64 groupId) const { - if (m_fullInfo.contains(groupId)) - return m_fullInfo.value(groupId); + if (auto it = m_fullInfo.find(groupId); it != m_fullInfo.end()) + { + return it->second; + } return {}; } void SupergroupStore::handleUpdateSupergroup(const QVariantMap &supergroup) { - m_supergroup.insert(supergroup.value("id").toLongLong(), supergroup); + m_supergroup.emplace(supergroup.value("id").toLongLong(), supergroup); } void SupergroupStore::handleUpdateSupergroupFullInfo(qint64 supergroupId, const QVariantMap &supergroupFullInfo) { - m_fullInfo.insert(supergroupId, supergroupFullInfo); + m_fullInfo.emplace(supergroupId, supergroupFullInfo); } void UserStore::initialize(TdApi *controller) @@ -360,16 +376,20 @@ qint64 UserStore::getMyId() const QVariantMap UserStore::get(qint64 userId) const { - if (m_users.contains(userId)) - return m_users.value(userId); + if (auto it = m_users.find(userId); it != m_users.end()) + { + return it->second; + } return {}; } QVariantMap UserStore::getFullInfo(qint64 userId) const { - if (m_fullInfo.contains(userId)) - return m_fullInfo.value(userId); + if (auto it = m_fullInfo.find(userId); it != m_fullInfo.end()) + { + return it->second; + } return {}; } @@ -377,17 +397,17 @@ QVariantMap UserStore::getFullInfo(qint64 userId) const void UserStore::handleUpdateUserStatus(qint64 userId, const QVariantMap &status) { if (auto it = m_users.find(userId); it != m_users.end()) - it->insert("status", status); + it->second.insert("status", status); } void UserStore::handleUpdateUser(const QVariantMap &user) { auto userId = user.value("id").toLongLong(); - m_users.insert(userId, user); + m_users.emplace(userId, user); } void UserStore::handleUpdateUserFullInfo(qint64 userId, const QVariantMap &userFullInfo) { - m_fullInfo.insert(userId, userFullInfo); + m_fullInfo.emplace(userId, userFullInfo); } diff --git a/src/Stores.hpp b/src/Stores.hpp index 06e1e89..cd6aa3a 100644 --- a/src/Stores.hpp +++ b/src/Stores.hpp @@ -3,6 +3,8 @@ #include #include +#include + class TdApi; class Store : public QObject @@ -32,8 +34,8 @@ private slots: void handleUpdateBasicGroupFullInfo(qint64 basicGroupId, const QVariantMap &basicGroupFullInfo); private: - QHash m_basicGroup; - QHash m_fullInfo; + std::unordered_map m_basicGroup; + std::unordered_map m_fullInfo; }; class ChatStore : public Store @@ -73,7 +75,7 @@ private slots: private: void setChatPositions(qint64 chatId, const QVariantList &positions) noexcept; - QHash m_chats; + std::unordered_map m_chats; }; class FileStore : public Store @@ -89,7 +91,7 @@ private slots: void handleUpdateFile(const QVariantMap &file); private: - QHash m_files; + std::unordered_map m_files; }; class OptionStore : public Store @@ -123,8 +125,8 @@ private slots: void handleUpdateSupergroupFullInfo(qint64 supergroupId, const QVariantMap &supergroupFullInfo); private: - QHash m_supergroup; - QHash m_fullInfo; + std::unordered_map m_supergroup; + std::unordered_map m_fullInfo; }; class UserStore : public Store @@ -144,6 +146,6 @@ private slots: void handleUpdateUserFullInfo(qint64 userId, const QVariantMap &userFullInfo); private: - QHash m_users; - QHash m_fullInfo; + std::unordered_map m_users; + std::unordered_map m_fullInfo; }; diff --git a/src/TdApi.cpp b/src/TdApi.cpp index aca295b..46dcd7f 100644 --- a/src/TdApi.cpp +++ b/src/TdApi.cpp @@ -149,11 +149,6 @@ void TdApi::log(const QVariantMap &js) noexcept qDebug() << json.dump(2).c_str(); } -bool TdApi::busy() const noexcept -{ - return m_busy; -} - bool TdApi::isAuthorized() const noexcept { return m_isAuthorized; @@ -274,7 +269,6 @@ void TdApi::createNewSecretChat(qint32 userId) void TdApi::createNewSupergroupChat(const QString &title, bool isChannel, const QString &description, const QVariantMap &location) { - // clang-format off QVariantMap result; result.insert("@type", "createNewSupergroupChat"); result.insert("title", title); @@ -282,7 +276,6 @@ void TdApi::createNewSupergroupChat(const QString &title, bool isChannel, const result.insert("description", description); result.insert("location", location); - // clang-format on sendRequest(result); } @@ -910,105 +903,89 @@ void TdApi::handleAuthorizationState(const QVariantMap &data) auto authorizationState = data.value("authorization_state").toMap(); auto authorizationStateType = authorizationState.value("@type").toByteArray(); - if (authorizationStateType == "authorizationStateWaitTdlibParameters") - { - QVariantMap parameters; - parameters.insert("database_directory", QString(QDir::homePath() % DatabaseDirectory)); - parameters.insert("use_file_database", true); - parameters.insert("use_chat_info_database", true); - parameters.insert("use_message_database", true); - parameters.insert("use_secret_chats", true); - parameters.insert("api_id", ApiId); - parameters.insert("api_hash", ApiHash); - parameters.insert("system_language_code", SystemLanguageCode); - parameters.insert("device_model", DeviceModel); - parameters.insert("system_version", SystemVersion); - parameters.insert("application_version", AppVersion); - - QVariantMap result; - result.insert("@type", "setTdlibParameters"); - result.insert("parameters", parameters); - - sendRequest(result); - } - - if (authorizationStateType == "authorizationStateWaitEncryptionKey") - { - td_send(clientId, R"({"@type":"checkDatabaseEncryptionKey","encryption_key":""})"); - } - - if (authorizationStateType == "authorizationStateReady") - { - m_isAuthorized = true; - emit isAuthorizedChanged(); - - QVariantMap result; - result.insert("@type", "loadChats"); - result.insert("chat_list", {}); - result.insert("limit", ChatSliceLimit); - - TdApi::getInstance().sendRequest(result); - } - if (authorizationStateType == "authorizationStateClosed") - { - m_worker.request_stop(); - } - - if (authorizationStateType == "authorizationStateWaitCode") + switch (fnv::hashRuntime(authorizationStateType.constData())) { - const auto codeInfo = authorizationState.value("code_info").toMap(); - - QVariantMap result; - result.insert("subtitle", authentication_code_subtitle(codeInfo)); - result.insert("title", authentication_code_title(codeInfo)); - result.insert("length", authentication_code_length(codeInfo)); - - result.insert("isNextTypeSms", authentication_code_is_next_type_sms(codeInfo)); - result.insert("nextTypeString", authentication_code_next_type_string(codeInfo)); + case fnv::hash("authorizationStateWaitTdlibParameters"): { + QVariantMap parameters; + parameters.insert("database_directory", QString(QDir::homePath() % DatabaseDirectory)); + parameters.insert("use_file_database", true); + parameters.insert("use_chat_info_database", true); + parameters.insert("use_message_database", true); + parameters.insert("use_secret_chats", true); + parameters.insert("api_id", ApiId); + parameters.insert("api_hash", ApiHash); + parameters.insert("system_language_code", SystemLanguageCode); + parameters.insert("device_model", DeviceModel); + parameters.insert("system_version", SystemVersion); + parameters.insert("application_version", AppVersion); + + QVariantMap result; + result.insert("@type", "setTdlibParameters"); + result.insert("parameters", parameters); + + sendRequest(result); + break; + } + case fnv::hash("authorizationStateWaitEncryptionKey"): { + td_send(clientId, R"({"@type":"checkDatabaseEncryptionKey","encryption_key":""})"); + break; + } + case fnv::hash("authorizationStateWaitCode"): { + const auto codeInfo = authorizationState.value("code_info").toMap(); - result.insert("timeout", codeInfo.value("timeout").toInt()); + QVariantMap result; + result.insert("subtitle", authentication_code_subtitle(codeInfo)); + result.insert("title", authentication_code_title(codeInfo)); + result.insert("length", authentication_code_length(codeInfo)); - setBusy(false); + result.insert("isNextTypeSms", authentication_code_is_next_type_sms(codeInfo)); + result.insert("nextTypeString", authentication_code_next_type_string(codeInfo)); - emit codeRequested(result); - } + result.insert("timeout", codeInfo.value("timeout").toInt()); - if (authorizationStateType == "authorizationStateWaitPassword") - { - const auto password = authorizationState.value("password").toMap(); + emit codeRequested(result); + break; + } + case fnv::hash("authorizationStateWaitPassword"): { + const auto password = authorizationState.value("password").toMap(); - QVariantMap result; - result.insert("passwordHint", password.value("password_hint").toString()); - result.insert("hasRecoveryEmailAddress", password.value("has_recovery_email_address").toBool()); - result.insert("recoveryEmailAddressPattern", password.value("recovery_email_address_pattern").toString()); + QVariantMap result; + result.insert("passwordHint", password.value("password_hint").toString()); + result.insert("hasRecoveryEmailAddress", password.value("has_recovery_email_address").toBool()); + result.insert("recoveryEmailAddressPattern", password.value("recovery_email_address_pattern").toString()); - setBusy(false); + emit passwordRequested(result); + break; + } + case fnv::hash("authorizationStateWaitRegistration"): { + const auto termsOfService = authorizationState.value("terms_of_service").toMap(); - emit passwordRequested(result); - } + QVariantMap result; + result.insert("text", termsOfService.value("text").toMap().value("text").toString()); + result.insert("minUserAge", termsOfService.value("min_user_age").toInt()); + result.insert("showPopup", termsOfService.value("show_popup").toBool()); - if (authorizationStateType == "authorizationStateWaitRegistration") - { - const auto termsOfService = authorizationState.value("terms_of_service").toMap(); + emit registrationRequested(result); + break; + } + case fnv::hash("authorizationStateReady"): { + QVariantMap result; + result.insert("@type", "loadChats"); + result.insert("chat_list", {}); + result.insert("limit", ChatSliceLimit); - QVariantMap result; - result.insert("text", termsOfService.value("text").toMap().value("text").toString()); - result.insert("minUserAge", termsOfService.value("min_user_age").toInt()); - result.insert("showPopup", termsOfService.value("show_popup").toBool()); + TdApi::getInstance().sendRequest(result); - setBusy(false); + m_isAuthorized = true; - emit registrationRequested(result); + emit isAuthorizedChanged(); + break; + } + case fnv::hash("authorizationStateClosed"): { + m_worker.request_stop(); + break; + } } emit updateAuthorizationState(authorizationState); } - -void TdApi::setBusy(bool busy) -{ - if (m_busy == busy) - return; - - m_busy = busy; - emit busyChanged(); -} diff --git a/src/TdApi.hpp b/src/TdApi.hpp index f9cad5d..3ac913c 100644 --- a/src/TdApi.hpp +++ b/src/TdApi.hpp @@ -10,7 +10,6 @@ class TdApi : public QObject { Q_OBJECT Q_ENUMS(ChatList) - Q_PROPERTY(bool busy READ busy WRITE setBusy NOTIFY busyChanged) Q_PROPERTY(bool isAuthorized READ isAuthorized NOTIFY isAuthorizedChanged) std::vector> stores; @@ -34,7 +33,6 @@ class TdApi : public QObject Q_INVOKABLE void sendRequest(const QVariantMap &js); Q_INVOKABLE void log(const QVariantMap &js) noexcept; - [[nodiscard]] bool busy() const noexcept; [[nodiscard]] bool isAuthorized() const noexcept; Q_INVOKABLE void checkCode(const QString &code) noexcept; @@ -95,7 +93,6 @@ public slots: void passwordRequested(const QVariant &passwordInfo); void registrationRequested(const QVariant &termsOfService); - void busyChanged(); void isAuthorizedChanged(); void updateAuthorizationState(const QVariantMap &authorizationState); @@ -181,7 +178,6 @@ public slots: void initEvents(); void handleAuthorizationState(const QVariantMap &data); - void setBusy(bool busy); template requires std::is_base_of_v T &emplace() @@ -195,7 +191,6 @@ public slots: std::jthread m_worker; - bool m_busy{false}; bool m_isAuthorized{false}; std::unordered_map> m_events; diff --git a/src/Utils.cpp b/src/Utils.cpp index 5612d08..4ae2cbc 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -377,7 +377,7 @@ int Utils::getChatMuteFor(qint64 chatId) QString Utils::getServiceMessageContent(const QVariantMap &message) { auto ttl = message.value("ttl").toInt(); - auto sender = message.value("sender").toMap(); + auto sender = message.value("sender_id").toMap(); auto content = message.value("content").toMap(); auto isOutgoing = message.value("is_outgoing").toBool(); @@ -707,7 +707,7 @@ QString Utils::getUserShortName(qint64 userId) noexcept QString Utils::getTitle(const QVariantMap &message) noexcept { - auto sender = message.value("sender").toMap(); + auto sender = message.value("sender_id").toMap(); auto senderType = sender.value("@type").toByteArray(); if (senderType == "messageSenderUser") @@ -739,7 +739,7 @@ QString Utils::getMessageDate(const QVariantMap &message) noexcept QString Utils::getContent(const QVariantMap &message) noexcept { auto content = message.value("content").toMap(); - auto sender = message.value("sender").toMap(); + auto sender = message.value("sender_id").toMap(); auto textOneLine = [](QString text) { auto result = std::move(text); @@ -925,7 +925,7 @@ QString Utils::getMessageSenderName(const QVariantMap &message) noexcept if (isServiceMessage(message)) return QString(); - auto sender = message.value("sender").toMap(); + auto sender = message.value("sender_id").toMap(); auto chat = TdApi::getInstance().chatStore->get(message.value("chat_id").toLongLong());