From e1aa3685747975fd5312f5b57570c166d4f57195 Mon Sep 17 00:00:00 2001 From: marty1885 Date: Sun, 23 Jul 2023 17:26:23 +0800 Subject: [PATCH] add ablity to list all users in room --- examples/messenger/main.cpp | 15 ++++++++++++++- gnunetpp/gnunetpp-messenger.cpp | 24 ++++++++++++++++++++++++ gnunetpp/gnunetpp-messenger.hpp | 9 +++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/examples/messenger/main.cpp b/examples/messenger/main.cpp index 91fedfc..35f7ece 100644 --- a/examples/messenger/main.cpp +++ b/examples/messenger/main.cpp @@ -106,8 +106,21 @@ Task<> service(const GNUNET_CONFIGURATION_Handle* cfg) shutdown(); co_return; } + else if(line == "/list") { + std::cout << "Members of room " << room_str << ":" << std::endl; + auto members = room->members(); + for(auto& contact : members) { + std::string disp_name = contact.name(); + std::string key = ""; + if(contact.key()) + key = to_string(*contact.key()); + if(disp_name.empty()) + disp_name = ""; + std::cout << "* " << disp_name << " (" << key << ")" << std::endl; + } + } // don't send empty messages - if(!line.empty()) + else if(!line.empty()) room->sendMessage(line); } } diff --git a/gnunetpp/gnunetpp-messenger.cpp b/gnunetpp/gnunetpp-messenger.cpp index ebfbfa5..80bc212 100644 --- a/gnunetpp/gnunetpp-messenger.cpp +++ b/gnunetpp/gnunetpp-messenger.cpp @@ -233,6 +233,30 @@ void Room::sendPrivateMessage(const UserSendibleMessage &value, Contact contact) GNUNET_MESSENGER_send_message(room, &msg, contact.contact); } +int Room::forEachMember(std::function cb) +{ + auto ptr = new std::function(cb); + // IMPORTANT: this method is synchronous, so we can safely delete the pointer after the call + int num_members = GNUNET_MESSENGER_iterate_members(room, + [] (void* cls, GNUNET_MESSENGER_Room* room, const GNUNET_MESSENGER_Contact* contact) -> int { + auto cb = (std::function*)cls; + (*cb)(Contact{contact}); + return GNUNET_OK; + }, ptr); + delete ptr; + return num_members; +} + +std::vector Room::members() +{ + std::vector contacts; + int n = forEachMember([&contacts] (const Contact& contact) { + contacts.push_back(contact); + }); + GNUNET_assert(n == contacts.size()); + return contacts; +} + std::string Contact::name() const { auto name = GNUNET_MESSENGER_contact_get_name(contact); diff --git a/gnunetpp/gnunetpp-messenger.hpp b/gnunetpp/gnunetpp-messenger.hpp index d9cb759..c3c9004 100644 --- a/gnunetpp/gnunetpp-messenger.hpp +++ b/gnunetpp/gnunetpp-messenger.hpp @@ -108,6 +108,15 @@ struct Room : public NonCopyable */ void setReadMessageCallback(std::function cb) { recv_cb = std::move(cb); } + /** + * @brief iterate over all members of this room + * + * @return the number of members + */ + int forEachMember(std::function cb); + + std::vector members(); + GNUNET_MESSENGER_Room* room = nullptr; std::function recv_cb; };