From dcfe0a5febb252e3a4f40c1b25765740a269467f Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Wed, 6 Jul 2022 02:20:39 +0200 Subject: [PATCH 01/15] network: Add initial files and enet dependency --- .gitmodules | 3 + externals/CMakeLists.txt | 4 + externals/enet | 1 + src/CMakeLists.txt | 1 + src/network/CMakeLists.txt | 16 + src/network/network.cpp | 50 ++ src/network/network.h | 25 + src/network/packet.cpp | 263 +++++++++ src/network/packet.h | 166 ++++++ src/network/room.cpp | 1111 +++++++++++++++++++++++++++++++++++ src/network/room.h | 173 ++++++ src/network/room_member.cpp | 694 ++++++++++++++++++++++ src/network/room_member.h | 327 +++++++++++ src/network/verify_user.cpp | 18 + src/network/verify_user.h | 46 ++ 15 files changed, 2898 insertions(+) create mode 160000 externals/enet create mode 100644 src/network/CMakeLists.txt create mode 100644 src/network/network.cpp create mode 100644 src/network/network.h create mode 100644 src/network/packet.cpp create mode 100644 src/network/packet.h create mode 100644 src/network/room.cpp create mode 100644 src/network/room.h create mode 100644 src/network/room_member.cpp create mode 100644 src/network/room_member.h create mode 100644 src/network/verify_user.cpp create mode 100644 src/network/verify_user.h diff --git a/.gitmodules b/.gitmodules index 3c0d15951d..d8e04923ad 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ +[submodule "enet"] + path = externals/enet + url = https://github.com/lsalzman/enet.git [submodule "inih"] path = externals/inih/inih url = https://github.com/benhoyt/inih.git diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt index bd01f4c4db..b4570bb697 100644 --- a/externals/CMakeLists.txt +++ b/externals/CMakeLists.txt @@ -73,6 +73,10 @@ if (YUZU_USE_EXTERNAL_SDL2) add_library(SDL2 ALIAS SDL2-static) endif() +# ENet +add_subdirectory(enet) +target_include_directories(enet INTERFACE ./enet/include) + # Cubeb if(ENABLE_CUBEB) set(BUILD_TESTS OFF CACHE BOOL "") diff --git a/externals/enet b/externals/enet new file mode 160000 index 0000000000..39a72ab199 --- /dev/null +++ b/externals/enet @@ -0,0 +1 @@ +Subproject commit 39a72ab1990014eb399cee9d538fd529df99c6a0 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 39ae573b26..9367f67c10 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -156,6 +156,7 @@ add_subdirectory(common) add_subdirectory(core) add_subdirectory(audio_core) add_subdirectory(video_core) +add_subdirectory(network) add_subdirectory(input_common) add_subdirectory(shader_recompiler) diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt new file mode 100644 index 0000000000..382a69e2f7 --- /dev/null +++ b/src/network/CMakeLists.txt @@ -0,0 +1,16 @@ +add_library(network STATIC + network.cpp + network.h + packet.cpp + packet.h + room.cpp + room.h + room_member.cpp + room_member.h + verify_user.cpp + verify_user.h +) + +create_target_directory_groups(network) + +target_link_libraries(network PRIVATE common enet Boost::boost) diff --git a/src/network/network.cpp b/src/network/network.cpp new file mode 100644 index 0000000000..51b5d6a9fa --- /dev/null +++ b/src/network/network.cpp @@ -0,0 +1,50 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "common/assert.h" +#include "common/logging/log.h" +#include "enet/enet.h" +#include "network/network.h" + +namespace Network { + +static std::shared_ptr g_room_member; ///< RoomMember (Client) for network games +static std::shared_ptr g_room; ///< Room (Server) for network games +// TODO(B3N30): Put these globals into a networking class + +bool Init() { + if (enet_initialize() != 0) { + LOG_ERROR(Network, "Error initalizing ENet"); + return false; + } + g_room = std::make_shared(); + g_room_member = std::make_shared(); + LOG_DEBUG(Network, "initialized OK"); + return true; +} + +std::weak_ptr GetRoom() { + return g_room; +} + +std::weak_ptr GetRoomMember() { + return g_room_member; +} + +void Shutdown() { + if (g_room_member) { + if (g_room_member->IsConnected()) + g_room_member->Leave(); + g_room_member.reset(); + } + if (g_room) { + if (g_room->GetState() == Room::State::Open) + g_room->Destroy(); + g_room.reset(); + } + enet_deinitialize(); + LOG_DEBUG(Network, "shutdown OK"); +} + +} // namespace Network diff --git a/src/network/network.h b/src/network/network.h new file mode 100644 index 0000000000..6d002d693f --- /dev/null +++ b/src/network/network.h @@ -0,0 +1,25 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include "network/room.h" +#include "network/room_member.h" + +namespace Network { + +/// Initializes and registers the network device, the room, and the room member. +bool Init(); + +/// Returns a pointer to the room handle +std::weak_ptr GetRoom(); + +/// Returns a pointer to the room member handle +std::weak_ptr GetRoomMember(); + +/// Unregisters the network device, the room, and the room member and shut them down. +void Shutdown(); + +} // namespace Network diff --git a/src/network/packet.cpp b/src/network/packet.cpp new file mode 100644 index 0000000000..8fc5feabd4 --- /dev/null +++ b/src/network/packet.cpp @@ -0,0 +1,263 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#ifdef _WIN32 +#include +#else +#include +#endif +#include +#include +#include "network/packet.h" + +namespace Network { + +#ifndef htonll +u64 htonll(u64 x) { + return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32)); +} +#endif + +#ifndef ntohll +u64 ntohll(u64 x) { + return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32)); +} +#endif + +void Packet::Append(const void* in_data, std::size_t size_in_bytes) { + if (in_data && (size_in_bytes > 0)) { + std::size_t start = data.size(); + data.resize(start + size_in_bytes); + std::memcpy(&data[start], in_data, size_in_bytes); + } +} + +void Packet::Read(void* out_data, std::size_t size_in_bytes) { + if (out_data && CheckSize(size_in_bytes)) { + std::memcpy(out_data, &data[read_pos], size_in_bytes); + read_pos += size_in_bytes; + } +} + +void Packet::Clear() { + data.clear(); + read_pos = 0; + is_valid = true; +} + +const void* Packet::GetData() const { + return !data.empty() ? &data[0] : nullptr; +} + +void Packet::IgnoreBytes(u32 length) { + read_pos += length; +} + +std::size_t Packet::GetDataSize() const { + return data.size(); +} + +bool Packet::EndOfPacket() const { + return read_pos >= data.size(); +} + +Packet::operator bool() const { + return is_valid; +} + +Packet& Packet::operator>>(bool& out_data) { + u8 value; + if (*this >> value) { + out_data = (value != 0); + } + return *this; +} + +Packet& Packet::operator>>(s8& out_data) { + Read(&out_data, sizeof(out_data)); + return *this; +} + +Packet& Packet::operator>>(u8& out_data) { + Read(&out_data, sizeof(out_data)); + return *this; +} + +Packet& Packet::operator>>(s16& out_data) { + s16 value; + Read(&value, sizeof(value)); + out_data = ntohs(value); + return *this; +} + +Packet& Packet::operator>>(u16& out_data) { + u16 value; + Read(&value, sizeof(value)); + out_data = ntohs(value); + return *this; +} + +Packet& Packet::operator>>(s32& out_data) { + s32 value; + Read(&value, sizeof(value)); + out_data = ntohl(value); + return *this; +} + +Packet& Packet::operator>>(u32& out_data) { + u32 value; + Read(&value, sizeof(value)); + out_data = ntohl(value); + return *this; +} + +Packet& Packet::operator>>(s64& out_data) { + s64 value; + Read(&value, sizeof(value)); + out_data = ntohll(value); + return *this; +} + +Packet& Packet::operator>>(u64& out_data) { + u64 value; + Read(&value, sizeof(value)); + out_data = ntohll(value); + return *this; +} + +Packet& Packet::operator>>(float& out_data) { + Read(&out_data, sizeof(out_data)); + return *this; +} + +Packet& Packet::operator>>(double& out_data) { + Read(&out_data, sizeof(out_data)); + return *this; +} + +Packet& Packet::operator>>(char* out_data) { + // First extract string length + u32 length = 0; + *this >> length; + + if ((length > 0) && CheckSize(length)) { + // Then extract characters + std::memcpy(out_data, &data[read_pos], length); + out_data[length] = '\0'; + + // Update reading position + read_pos += length; + } + + return *this; +} + +Packet& Packet::operator>>(std::string& out_data) { + // First extract string length + u32 length = 0; + *this >> length; + + out_data.clear(); + if ((length > 0) && CheckSize(length)) { + // Then extract characters + out_data.assign(&data[read_pos], length); + + // Update reading position + read_pos += length; + } + + return *this; +} + +Packet& Packet::operator<<(bool in_data) { + *this << static_cast(in_data); + return *this; +} + +Packet& Packet::operator<<(s8 in_data) { + Append(&in_data, sizeof(in_data)); + return *this; +} + +Packet& Packet::operator<<(u8 in_data) { + Append(&in_data, sizeof(in_data)); + return *this; +} + +Packet& Packet::operator<<(s16 in_data) { + s16 toWrite = htons(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(u16 in_data) { + u16 toWrite = htons(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(s32 in_data) { + s32 toWrite = htonl(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(u32 in_data) { + u32 toWrite = htonl(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(s64 in_data) { + s64 toWrite = htonll(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(u64 in_data) { + u64 toWrite = htonll(in_data); + Append(&toWrite, sizeof(toWrite)); + return *this; +} + +Packet& Packet::operator<<(float in_data) { + Append(&in_data, sizeof(in_data)); + return *this; +} + +Packet& Packet::operator<<(double in_data) { + Append(&in_data, sizeof(in_data)); + return *this; +} + +Packet& Packet::operator<<(const char* in_data) { + // First insert string length + u32 length = static_cast(std::strlen(in_data)); + *this << length; + + // Then insert characters + Append(in_data, length * sizeof(char)); + + return *this; +} + +Packet& Packet::operator<<(const std::string& in_data) { + // First insert string length + u32 length = static_cast(in_data.size()); + *this << length; + + // Then insert characters + if (length > 0) + Append(in_data.c_str(), length * sizeof(std::string::value_type)); + + return *this; +} + +bool Packet::CheckSize(std::size_t size) { + is_valid = is_valid && (read_pos + size <= data.size()); + + return is_valid; +} + +} // namespace Network diff --git a/src/network/packet.h b/src/network/packet.h new file mode 100644 index 0000000000..7bdc3da958 --- /dev/null +++ b/src/network/packet.h @@ -0,0 +1,166 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include "common/common_types.h" + +namespace Network { + +/// A class that serializes data for network transfer. It also handles endianess +class Packet { +public: + Packet() = default; + ~Packet() = default; + + /** + * Append data to the end of the packet + * @param data Pointer to the sequence of bytes to append + * @param size_in_bytes Number of bytes to append + */ + void Append(const void* data, std::size_t size_in_bytes); + + /** + * Reads data from the current read position of the packet + * @param out_data Pointer where the data should get written to + * @param size_in_bytes Number of bytes to read + */ + void Read(void* out_data, std::size_t size_in_bytes); + + /** + * Clear the packet + * After calling Clear, the packet is empty. + */ + void Clear(); + + /** + * Ignores bytes while reading + * @param length THe number of bytes to ignore + */ + void IgnoreBytes(u32 length); + + /** + * Get a pointer to the data contained in the packet + * @return Pointer to the data + */ + const void* GetData() const; + + /** + * This function returns the number of bytes pointed to by + * what getData returns. + * @return Data size, in bytes + */ + std::size_t GetDataSize() const; + + /** + * This function is useful to know if there is some data + * left to be read, without actually reading it. + * @return True if all data was read, false otherwise + */ + bool EndOfPacket() const; + + explicit operator bool() const; + + /// Overloads of operator >> to read data from the packet + Packet& operator>>(bool& out_data); + Packet& operator>>(s8& out_data); + Packet& operator>>(u8& out_data); + Packet& operator>>(s16& out_data); + Packet& operator>>(u16& out_data); + Packet& operator>>(s32& out_data); + Packet& operator>>(u32& out_data); + Packet& operator>>(s64& out_data); + Packet& operator>>(u64& out_data); + Packet& operator>>(float& out_data); + Packet& operator>>(double& out_data); + Packet& operator>>(char* out_data); + Packet& operator>>(std::string& out_data); + template + Packet& operator>>(std::vector& out_data); + template + Packet& operator>>(std::array& out_data); + + /// Overloads of operator << to write data into the packet + Packet& operator<<(bool in_data); + Packet& operator<<(s8 in_data); + Packet& operator<<(u8 in_data); + Packet& operator<<(s16 in_data); + Packet& operator<<(u16 in_data); + Packet& operator<<(s32 in_data); + Packet& operator<<(u32 in_data); + Packet& operator<<(s64 in_data); + Packet& operator<<(u64 in_data); + Packet& operator<<(float in_data); + Packet& operator<<(double in_data); + Packet& operator<<(const char* in_data); + Packet& operator<<(const std::string& in_data); + template + Packet& operator<<(const std::vector& in_data); + template + Packet& operator<<(const std::array& data); + +private: + /** + * Check if the packet can extract a given number of bytes + * This function updates accordingly the state of the packet. + * @param size Size to check + * @return True if size bytes can be read from the packet + */ + bool CheckSize(std::size_t size); + + // Member data + std::vector data; ///< Data stored in the packet + std::size_t read_pos = 0; ///< Current reading position in the packet + bool is_valid = true; ///< Reading state of the packet +}; + +template +Packet& Packet::operator>>(std::vector& out_data) { + // First extract the size + u32 size = 0; + *this >> size; + out_data.resize(size); + + // Then extract the data + for (std::size_t i = 0; i < out_data.size(); ++i) { + T character; + *this >> character; + out_data[i] = character; + } + return *this; +} + +template +Packet& Packet::operator>>(std::array& out_data) { + for (std::size_t i = 0; i < out_data.size(); ++i) { + T character; + *this >> character; + out_data[i] = character; + } + return *this; +} + +template +Packet& Packet::operator<<(const std::vector& in_data) { + // First insert the size + *this << static_cast(in_data.size()); + + // Then insert the data + for (std::size_t i = 0; i < in_data.size(); ++i) { + *this << in_data[i]; + } + return *this; +} + +template +Packet& Packet::operator<<(const std::array& in_data) { + for (std::size_t i = 0; i < in_data.size(); ++i) { + *this << in_data[i]; + } + return *this; +} + +} // namespace Network diff --git a/src/network/room.cpp b/src/network/room.cpp new file mode 100644 index 0000000000..cd0c0ebc49 --- /dev/null +++ b/src/network/room.cpp @@ -0,0 +1,1111 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "enet/enet.h" +#include "network/packet.h" +#include "network/room.h" +#include "network/verify_user.h" + +namespace Network { + +class Room::RoomImpl { +public: + // This MAC address is used to generate a 'Nintendo' like Mac address. + const MacAddress NintendoOUI; + std::mt19937 random_gen; ///< Random number generator. Used for GenerateMacAddress + + ENetHost* server = nullptr; ///< Network interface. + + std::atomic state{State::Closed}; ///< Current state of the room. + RoomInformation room_information; ///< Information about this room. + + std::string verify_UID; ///< A GUID which may be used for verfication. + mutable std::mutex verify_UID_mutex; ///< Mutex for verify_UID + + std::string password; ///< The password required to connect to this room. + + struct Member { + std::string nickname; ///< The nickname of the member. + std::string console_id_hash; ///< A hash of the console ID of the member. + GameInfo game_info; ///< The current game of the member + MacAddress mac_address; ///< The assigned mac address of the member. + /// Data of the user, often including authenticated forum username. + VerifyUser::UserData user_data; + ENetPeer* peer; ///< The remote peer. + }; + using MemberList = std::vector; + MemberList members; ///< Information about the members of this room + mutable std::mutex member_mutex; ///< Mutex for locking the members list + /// This should be a std::shared_mutex as soon as C++17 is supported + + UsernameBanList username_ban_list; ///< List of banned usernames + IPBanList ip_ban_list; ///< List of banned IP addresses + mutable std::mutex ban_list_mutex; ///< Mutex for the ban lists + + RoomImpl() + : NintendoOUI{0x00, 0x1F, 0x32, 0x00, 0x00, 0x00}, random_gen(std::random_device()()) {} + + /// Thread that receives and dispatches network packets + std::unique_ptr room_thread; + + /// Verification backend of the room + std::unique_ptr verify_backend; + + /// Thread function that will receive and dispatch messages until the room is destroyed. + void ServerLoop(); + void StartLoop(); + + /** + * Parses and answers a room join request from a client. + * Validates the uniqueness of the username and assigns the MAC address + * that the client will use for the remainder of the connection. + */ + void HandleJoinRequest(const ENetEvent* event); + + /** + * Parses and answers a kick request from a client. + * Validates the permissions and that the given user exists and then kicks the member. + */ + void HandleModKickPacket(const ENetEvent* event); + + /** + * Parses and answers a ban request from a client. + * Validates the permissions and bans the user (by forum username or IP). + */ + void HandleModBanPacket(const ENetEvent* event); + + /** + * Parses and answers a unban request from a client. + * Validates the permissions and unbans the address. + */ + void HandleModUnbanPacket(const ENetEvent* event); + + /** + * Parses and answers a get ban list request from a client. + * Validates the permissions and returns the ban list. + */ + void HandleModGetBanListPacket(const ENetEvent* event); + + /** + * Returns whether the nickname is valid, ie. isn't already taken by someone else in the room. + */ + bool IsValidNickname(const std::string& nickname) const; + + /** + * Returns whether the MAC address is valid, ie. isn't already taken by someone else in the + * room. + */ + bool IsValidMacAddress(const MacAddress& address) const; + + /** + * Returns whether the console ID (hash) is valid, ie. isn't already taken by someone else in + * the room. + */ + bool IsValidConsoleId(const std::string& console_id_hash) const; + + /** + * Returns whether a user has mod permissions. + */ + bool HasModPermission(const ENetPeer* client) const; + + /** + * Sends a ID_ROOM_IS_FULL message telling the client that the room is full. + */ + void SendRoomIsFull(ENetPeer* client); + + /** + * Sends a ID_ROOM_NAME_COLLISION message telling the client that the name is invalid. + */ + void SendNameCollision(ENetPeer* client); + + /** + * Sends a ID_ROOM_MAC_COLLISION message telling the client that the MAC is invalid. + */ + void SendMacCollision(ENetPeer* client); + + /** + * Sends a IdConsoleIdCollison message telling the client that another member with the same + * console ID exists. + */ + void SendConsoleIdCollision(ENetPeer* client); + + /** + * Sends a ID_ROOM_VERSION_MISMATCH message telling the client that the version is invalid. + */ + void SendVersionMismatch(ENetPeer* client); + + /** + * Sends a ID_ROOM_WRONG_PASSWORD message telling the client that the password is wrong. + */ + void SendWrongPassword(ENetPeer* client); + + /** + * Notifies the member that its connection attempt was successful, + * and it is now part of the room. + */ + void SendJoinSuccess(ENetPeer* client, MacAddress mac_address); + + /** + * Notifies the member that its connection attempt was successful, + * and it is now part of the room, and it has been granted mod permissions. + */ + void SendJoinSuccessAsMod(ENetPeer* client, MacAddress mac_address); + + /** + * Sends a IdHostKicked message telling the client that they have been kicked. + */ + void SendUserKicked(ENetPeer* client); + + /** + * Sends a IdHostBanned message telling the client that they have been banned. + */ + void SendUserBanned(ENetPeer* client); + + /** + * Sends a IdModPermissionDenied message telling the client that they do not have mod + * permission. + */ + void SendModPermissionDenied(ENetPeer* client); + + /** + * Sends a IdModNoSuchUser message telling the client that the given user could not be found. + */ + void SendModNoSuchUser(ENetPeer* client); + + /** + * Sends the ban list in response to a client's request for getting ban list. + */ + void SendModBanListResponse(ENetPeer* client); + + /** + * Notifies the members that the room is closed, + */ + void SendCloseMessage(); + + /** + * Sends a system message to all the connected clients. + */ + void SendStatusMessage(StatusMessageTypes type, const std::string& nickname, + const std::string& username, const std::string& ip); + + /** + * Sends the information about the room, along with the list of members + * to every connected client in the room. + * The packet has the structure: + * ID_ROOM_INFORMATION + * room_name + * room_description + * member_slots: The max number of clients allowed in this room + * uid + * port + * num_members: the number of currently joined clients + * This is followed by the following three values for each member: + * nickname of that member + * mac_address of that member + * game_name of that member + */ + void BroadcastRoomInformation(); + + /** + * Generates a free MAC address to assign to a new client. + * The first 3 bytes are the NintendoOUI 0x00, 0x1F, 0x32 + */ + MacAddress GenerateMacAddress(); + + /** + * Broadcasts this packet to all members except the sender. + * @param event The ENet event containing the data + */ + void HandleWifiPacket(const ENetEvent* event); + + /** + * Extracts a chat entry from a received ENet packet and adds it to the chat queue. + * @param event The ENet event that was received. + */ + void HandleChatPacket(const ENetEvent* event); + + /** + * Extracts the game name from a received ENet packet and broadcasts it. + * @param event The ENet event that was received. + */ + void HandleGameNamePacket(const ENetEvent* event); + + /** + * Removes the client from the members list if it was in it and announces the change + * to all other clients. + */ + void HandleClientDisconnection(ENetPeer* client); +}; + +// RoomImpl +void Room::RoomImpl::ServerLoop() { + while (state != State::Closed) { + ENetEvent event; + if (enet_host_service(server, &event, 50) > 0) { + switch (event.type) { + case ENET_EVENT_TYPE_RECEIVE: + switch (event.packet->data[0]) { + case IdJoinRequest: + HandleJoinRequest(&event); + break; + case IdSetGameInfo: + HandleGameNamePacket(&event); + break; + case IdWifiPacket: + HandleWifiPacket(&event); + break; + case IdChatMessage: + HandleChatPacket(&event); + break; + // Moderation + case IdModKick: + HandleModKickPacket(&event); + break; + case IdModBan: + HandleModBanPacket(&event); + break; + case IdModUnban: + HandleModUnbanPacket(&event); + break; + case IdModGetBanList: + HandleModGetBanListPacket(&event); + break; + } + enet_packet_destroy(event.packet); + break; + case ENET_EVENT_TYPE_DISCONNECT: + HandleClientDisconnection(event.peer); + break; + case ENET_EVENT_TYPE_NONE: + case ENET_EVENT_TYPE_CONNECT: + break; + } + } + } + // Close the connection to all members: + SendCloseMessage(); +} + +void Room::RoomImpl::StartLoop() { + room_thread = std::make_unique(&Room::RoomImpl::ServerLoop, this); +} + +void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { + { + std::lock_guard lock(member_mutex); + if (members.size() >= room_information.member_slots) { + SendRoomIsFull(event->peer); + return; + } + } + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + std::string nickname; + packet >> nickname; + + std::string console_id_hash; + packet >> console_id_hash; + + MacAddress preferred_mac; + packet >> preferred_mac; + + u32 client_version; + packet >> client_version; + + std::string pass; + packet >> pass; + + std::string token; + packet >> token; + + if (pass != password) { + SendWrongPassword(event->peer); + return; + } + + if (!IsValidNickname(nickname)) { + SendNameCollision(event->peer); + return; + } + + if (preferred_mac != NoPreferredMac) { + // Verify if the preferred mac is available + if (!IsValidMacAddress(preferred_mac)) { + SendMacCollision(event->peer); + return; + } + } else { + // Assign a MAC address of this client automatically + preferred_mac = GenerateMacAddress(); + } + + if (!IsValidConsoleId(console_id_hash)) { + SendConsoleIdCollision(event->peer); + return; + } + + if (client_version != network_version) { + SendVersionMismatch(event->peer); + return; + } + + // At this point the client is ready to be added to the room. + Member member{}; + member.mac_address = preferred_mac; + member.console_id_hash = console_id_hash; + member.nickname = nickname; + member.peer = event->peer; + + std::string uid; + { + std::lock_guard lock(verify_UID_mutex); + uid = verify_UID; + } + member.user_data = verify_backend->LoadUserData(uid, token); + + std::string ip; + { + std::lock_guard lock(ban_list_mutex); + + // Check username ban + if (!member.user_data.username.empty() && + std::find(username_ban_list.begin(), username_ban_list.end(), + member.user_data.username) != username_ban_list.end()) { + + SendUserBanned(event->peer); + return; + } + + // Check IP ban + char ip_raw[256]; + enet_address_get_host_ip(&event->peer->address, ip_raw, sizeof(ip_raw) - 1); + ip = ip_raw; + + if (std::find(ip_ban_list.begin(), ip_ban_list.end(), ip) != ip_ban_list.end()) { + SendUserBanned(event->peer); + return; + } + } + + // Notify everyone that the user has joined. + SendStatusMessage(IdMemberJoin, member.nickname, member.user_data.username, ip); + + { + std::lock_guard lock(member_mutex); + members.push_back(std::move(member)); + } + + // Notify everyone that the room information has changed. + BroadcastRoomInformation(); + if (HasModPermission(event->peer)) { + SendJoinSuccessAsMod(event->peer, preferred_mac); + } else { + SendJoinSuccess(event->peer, preferred_mac); + } +} + +void Room::RoomImpl::HandleModKickPacket(const ENetEvent* event) { + if (!HasModPermission(event->peer)) { + SendModPermissionDenied(event->peer); + return; + } + + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + std::string nickname; + packet >> nickname; + + std::string username, ip; + { + std::lock_guard lock(member_mutex); + const auto target_member = + std::find_if(members.begin(), members.end(), + [&nickname](const auto& member) { return member.nickname == nickname; }); + if (target_member == members.end()) { + SendModNoSuchUser(event->peer); + return; + } + + // Notify the kicked member + SendUserKicked(target_member->peer); + + username = target_member->user_data.username; + + char ip_raw[256]; + enet_address_get_host_ip(&target_member->peer->address, ip_raw, sizeof(ip_raw) - 1); + ip = ip_raw; + + enet_peer_disconnect(target_member->peer, 0); + members.erase(target_member); + } + + // Announce the change to all clients. + SendStatusMessage(IdMemberKicked, nickname, username, ip); + BroadcastRoomInformation(); +} + +void Room::RoomImpl::HandleModBanPacket(const ENetEvent* event) { + if (!HasModPermission(event->peer)) { + SendModPermissionDenied(event->peer); + return; + } + + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + std::string nickname; + packet >> nickname; + + std::string username, ip; + { + std::lock_guard lock(member_mutex); + const auto target_member = + std::find_if(members.begin(), members.end(), + [&nickname](const auto& member) { return member.nickname == nickname; }); + if (target_member == members.end()) { + SendModNoSuchUser(event->peer); + return; + } + + // Notify the banned member + SendUserBanned(target_member->peer); + + nickname = target_member->nickname; + username = target_member->user_data.username; + + char ip_raw[256]; + enet_address_get_host_ip(&target_member->peer->address, ip_raw, sizeof(ip_raw) - 1); + ip = ip_raw; + + enet_peer_disconnect(target_member->peer, 0); + members.erase(target_member); + } + + { + std::lock_guard lock(ban_list_mutex); + + if (!username.empty()) { + // Ban the forum username + if (std::find(username_ban_list.begin(), username_ban_list.end(), username) == + username_ban_list.end()) { + + username_ban_list.emplace_back(username); + } + } + + // Ban the member's IP as well + if (std::find(ip_ban_list.begin(), ip_ban_list.end(), ip) == ip_ban_list.end()) { + ip_ban_list.emplace_back(ip); + } + } + + // Announce the change to all clients. + SendStatusMessage(IdMemberBanned, nickname, username, ip); + BroadcastRoomInformation(); +} + +void Room::RoomImpl::HandleModUnbanPacket(const ENetEvent* event) { + if (!HasModPermission(event->peer)) { + SendModPermissionDenied(event->peer); + return; + } + + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + std::string address; + packet >> address; + + bool unbanned = false; + { + std::lock_guard lock(ban_list_mutex); + + auto it = std::find(username_ban_list.begin(), username_ban_list.end(), address); + if (it != username_ban_list.end()) { + unbanned = true; + username_ban_list.erase(it); + } + + it = std::find(ip_ban_list.begin(), ip_ban_list.end(), address); + if (it != ip_ban_list.end()) { + unbanned = true; + ip_ban_list.erase(it); + } + } + + if (unbanned) { + SendStatusMessage(IdAddressUnbanned, address, "", ""); + } else { + SendModNoSuchUser(event->peer); + } +} + +void Room::RoomImpl::HandleModGetBanListPacket(const ENetEvent* event) { + if (!HasModPermission(event->peer)) { + SendModPermissionDenied(event->peer); + return; + } + + SendModBanListResponse(event->peer); +} + +bool Room::RoomImpl::IsValidNickname(const std::string& nickname) const { + // A nickname is valid if it matches the regex and is not already taken by anybody else in the + // room. + const std::regex nickname_regex("^[ a-zA-Z0-9._-]{4,20}$"); + if (!std::regex_match(nickname, nickname_regex)) + return false; + + std::lock_guard lock(member_mutex); + return std::all_of(members.begin(), members.end(), + [&nickname](const auto& member) { return member.nickname != nickname; }); +} + +bool Room::RoomImpl::IsValidMacAddress(const MacAddress& address) const { + // A MAC address is valid if it is not already taken by anybody else in the room. + std::lock_guard lock(member_mutex); + return std::all_of(members.begin(), members.end(), + [&address](const auto& member) { return member.mac_address != address; }); +} + +bool Room::RoomImpl::IsValidConsoleId(const std::string& console_id_hash) const { + // A Console ID is valid if it is not already taken by anybody else in the room. + std::lock_guard lock(member_mutex); + return std::all_of(members.begin(), members.end(), [&console_id_hash](const auto& member) { + return member.console_id_hash != console_id_hash; + }); +} + +bool Room::RoomImpl::HasModPermission(const ENetPeer* client) const { + std::lock_guard lock(member_mutex); + const auto sending_member = + std::find_if(members.begin(), members.end(), + [client](const auto& member) { return member.peer == client; }); + if (sending_member == members.end()) { + return false; + } + if (room_information.enable_citra_mods && + sending_member->user_data.moderator) { // Community moderator + + return true; + } + if (!room_information.host_username.empty() && + sending_member->user_data.username == room_information.host_username) { // Room host + + return true; + } + return false; +} + +void Room::RoomImpl::SendNameCollision(ENetPeer* client) { + Packet packet; + packet << static_cast(IdNameCollision); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendMacCollision(ENetPeer* client) { + Packet packet; + packet << static_cast(IdMacCollision); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendConsoleIdCollision(ENetPeer* client) { + Packet packet; + packet << static_cast(IdConsoleIdCollision); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendWrongPassword(ENetPeer* client) { + Packet packet; + packet << static_cast(IdWrongPassword); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendRoomIsFull(ENetPeer* client) { + Packet packet; + packet << static_cast(IdRoomIsFull); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) { + Packet packet; + packet << static_cast(IdVersionMismatch); + packet << network_version; + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) { + Packet packet; + packet << static_cast(IdJoinSuccess); + packet << mac_address; + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendJoinSuccessAsMod(ENetPeer* client, MacAddress mac_address) { + Packet packet; + packet << static_cast(IdJoinSuccessAsMod); + packet << mac_address; + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendUserKicked(ENetPeer* client) { + Packet packet; + packet << static_cast(IdHostKicked); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendUserBanned(ENetPeer* client) { + Packet packet; + packet << static_cast(IdHostBanned); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendModPermissionDenied(ENetPeer* client) { + Packet packet; + packet << static_cast(IdModPermissionDenied); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendModNoSuchUser(ENetPeer* client) { + Packet packet; + packet << static_cast(IdModNoSuchUser); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendModBanListResponse(ENetPeer* client) { + Packet packet; + packet << static_cast(IdModBanListResponse); + { + std::lock_guard lock(ban_list_mutex); + packet << username_ban_list; + packet << ip_ban_list; + } + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendCloseMessage() { + Packet packet; + packet << static_cast(IdCloseRoom); + std::lock_guard lock(member_mutex); + if (!members.empty()) { + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + for (auto& member : members) { + enet_peer_send(member.peer, 0, enet_packet); + } + } + enet_host_flush(server); + for (auto& member : members) { + enet_peer_disconnect(member.peer, 0); + } +} + +void Room::RoomImpl::SendStatusMessage(StatusMessageTypes type, const std::string& nickname, + const std::string& username, const std::string& ip) { + Packet packet; + packet << static_cast(IdStatusMessage); + packet << static_cast(type); + packet << nickname; + packet << username; + std::lock_guard lock(member_mutex); + if (!members.empty()) { + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + for (auto& member : members) { + enet_peer_send(member.peer, 0, enet_packet); + } + } + enet_host_flush(server); + + const std::string display_name = + username.empty() ? nickname : fmt::format("{} ({})", nickname, username); + + switch (type) { + case IdMemberJoin: + LOG_INFO(Network, "[{}] {} has joined.", ip, display_name); + break; + case IdMemberLeave: + LOG_INFO(Network, "[{}] {} has left.", ip, display_name); + break; + case IdMemberKicked: + LOG_INFO(Network, "[{}] {} has been kicked.", ip, display_name); + break; + case IdMemberBanned: + LOG_INFO(Network, "[{}] {} has been banned.", ip, display_name); + break; + case IdAddressUnbanned: + LOG_INFO(Network, "{} has been unbanned.", display_name); + break; + } +} + +void Room::RoomImpl::BroadcastRoomInformation() { + Packet packet; + packet << static_cast(IdRoomInformation); + packet << room_information.name; + packet << room_information.description; + packet << room_information.member_slots; + packet << room_information.port; + packet << room_information.preferred_game; + packet << room_information.host_username; + + packet << static_cast(members.size()); + { + std::lock_guard lock(member_mutex); + for (const auto& member : members) { + packet << member.nickname; + packet << member.mac_address; + packet << member.game_info.name; + packet << member.game_info.id; + packet << member.user_data.username; + packet << member.user_data.display_name; + packet << member.user_data.avatar_url; + } + } + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_host_broadcast(server, 0, enet_packet); + enet_host_flush(server); +} + +MacAddress Room::RoomImpl::GenerateMacAddress() { + MacAddress result_mac = + NintendoOUI; // The first three bytes of each MAC address will be the NintendoOUI + std::uniform_int_distribution<> dis(0x00, 0xFF); // Random byte between 0 and 0xFF + do { + for (std::size_t i = 3; i < result_mac.size(); ++i) { + result_mac[i] = dis(random_gen); + } + } while (!IsValidMacAddress(result_mac)); + return result_mac; +} + +void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + in_packet.IgnoreBytes(sizeof(u8)); // Message type + in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Type + in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Channel + in_packet.IgnoreBytes(sizeof(MacAddress)); // WifiPacket Transmitter Address + MacAddress destination_address; + in_packet >> destination_address; + + Packet out_packet; + out_packet.Append(event->packet->data, event->packet->dataLength); + ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + + if (destination_address == BroadcastMac) { // Send the data to everyone except the sender + std::lock_guard lock(member_mutex); + bool sent_packet = false; + for (const auto& member : members) { + if (member.peer != event->peer) { + sent_packet = true; + enet_peer_send(member.peer, 0, enet_packet); + } + } + + if (!sent_packet) { + enet_packet_destroy(enet_packet); + } + } else { // Send the data only to the destination client + std::lock_guard lock(member_mutex); + auto member = std::find_if(members.begin(), members.end(), + [destination_address](const Member& member) -> bool { + return member.mac_address == destination_address; + }); + if (member != members.end()) { + enet_peer_send(member->peer, 0, enet_packet); + } else { + LOG_ERROR(Network, + "Attempting to send to unknown MAC address: " + "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", + destination_address[0], destination_address[1], destination_address[2], + destination_address[3], destination_address[4], destination_address[5]); + enet_packet_destroy(enet_packet); + } + } + enet_host_flush(server); +} + +void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + + in_packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + std::string message; + in_packet >> message; + auto CompareNetworkAddress = [event](const Member member) -> bool { + return member.peer == event->peer; + }; + + std::lock_guard lock(member_mutex); + const auto sending_member = std::find_if(members.begin(), members.end(), CompareNetworkAddress); + if (sending_member == members.end()) { + return; // Received a chat message from a unknown sender + } + + // Limit the size of chat messages to MaxMessageSize + message.resize(std::min(static_cast(message.size()), MaxMessageSize)); + + Packet out_packet; + out_packet << static_cast(IdChatMessage); + out_packet << sending_member->nickname; + out_packet << sending_member->user_data.username; + out_packet << message; + + ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + bool sent_packet = false; + for (const auto& member : members) { + if (member.peer != event->peer) { + sent_packet = true; + enet_peer_send(member.peer, 0, enet_packet); + } + } + + if (!sent_packet) { + enet_packet_destroy(enet_packet); + } + + enet_host_flush(server); + + if (sending_member->user_data.username.empty()) { + LOG_INFO(Network, "{}: {}", sending_member->nickname, message); + } else { + LOG_INFO(Network, "{} ({}): {}", sending_member->nickname, + sending_member->user_data.username, message); + } +} + +void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + + in_packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + GameInfo game_info; + in_packet >> game_info.name; + in_packet >> game_info.id; + + { + std::lock_guard lock(member_mutex); + auto member = + std::find_if(members.begin(), members.end(), [event](const Member& member) -> bool { + return member.peer == event->peer; + }); + if (member != members.end()) { + member->game_info = game_info; + + const std::string display_name = + member->user_data.username.empty() + ? member->nickname + : fmt::format("{} ({})", member->nickname, member->user_data.username); + + if (game_info.name.empty()) { + LOG_INFO(Network, "{} is not playing", display_name); + } else { + LOG_INFO(Network, "{} is playing {}", display_name, game_info.name); + } + } + } + BroadcastRoomInformation(); +} + +void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) { + // Remove the client from the members list. + std::string nickname, username, ip; + { + std::lock_guard lock(member_mutex); + auto member = std::find_if(members.begin(), members.end(), [client](const Member& member) { + return member.peer == client; + }); + if (member != members.end()) { + nickname = member->nickname; + username = member->user_data.username; + + char ip_raw[256]; + enet_address_get_host_ip(&member->peer->address, ip_raw, sizeof(ip_raw) - 1); + ip = ip_raw; + + members.erase(member); + } + } + + // Announce the change to all clients. + enet_peer_disconnect(client, 0); + if (!nickname.empty()) + SendStatusMessage(IdMemberLeave, nickname, username, ip); + BroadcastRoomInformation(); +} + +// Room +Room::Room() : room_impl{std::make_unique()} {} + +Room::~Room() = default; + +bool Room::Create(const std::string& name, const std::string& description, + const std::string& server_address, u16 server_port, const std::string& password, + const u32 max_connections, const std::string& host_username, + const std::string& preferred_game, u64 preferred_game_id, + std::unique_ptr verify_backend, + const Room::BanList& ban_list, bool enable_citra_mods) { + ENetAddress address; + address.host = ENET_HOST_ANY; + if (!server_address.empty()) { + enet_address_set_host(&address, server_address.c_str()); + } + address.port = server_port; + + // In order to send the room is full message to the connecting client, we need to leave one + // slot open so enet won't reject the incoming connection without telling us + room_impl->server = enet_host_create(&address, max_connections + 1, NumChannels, 0, 0); + if (!room_impl->server) { + return false; + } + room_impl->state = State::Open; + + room_impl->room_information.name = name; + room_impl->room_information.description = description; + room_impl->room_information.member_slots = max_connections; + room_impl->room_information.port = server_port; + room_impl->room_information.preferred_game = preferred_game; + room_impl->room_information.preferred_game_id = preferred_game_id; + room_impl->room_information.host_username = host_username; + room_impl->room_information.enable_citra_mods = enable_citra_mods; + room_impl->password = password; + room_impl->verify_backend = std::move(verify_backend); + room_impl->username_ban_list = ban_list.first; + room_impl->ip_ban_list = ban_list.second; + + room_impl->StartLoop(); + return true; +} + +Room::State Room::GetState() const { + return room_impl->state; +} + +const RoomInformation& Room::GetRoomInformation() const { + return room_impl->room_information; +} + +std::string Room::GetVerifyUID() const { + std::lock_guard lock(room_impl->verify_UID_mutex); + return room_impl->verify_UID; +} + +Room::BanList Room::GetBanList() const { + std::lock_guard lock(room_impl->ban_list_mutex); + return {room_impl->username_ban_list, room_impl->ip_ban_list}; +} + +std::vector Room::GetRoomMemberList() const { + std::vector member_list; + std::lock_guard lock(room_impl->member_mutex); + for (const auto& member_impl : room_impl->members) { + Member member; + member.nickname = member_impl.nickname; + member.username = member_impl.user_data.username; + member.display_name = member_impl.user_data.display_name; + member.avatar_url = member_impl.user_data.avatar_url; + member.mac_address = member_impl.mac_address; + member.game_info = member_impl.game_info; + member_list.push_back(member); + } + return member_list; +} + +bool Room::HasPassword() const { + return !room_impl->password.empty(); +} + +void Room::SetVerifyUID(const std::string& uid) { + std::lock_guard lock(room_impl->verify_UID_mutex); + room_impl->verify_UID = uid; +} + +void Room::Destroy() { + room_impl->state = State::Closed; + room_impl->room_thread->join(); + room_impl->room_thread.reset(); + + if (room_impl->server) { + enet_host_destroy(room_impl->server); + } + room_impl->room_information = {}; + room_impl->server = nullptr; + { + std::lock_guard lock(room_impl->member_mutex); + room_impl->members.clear(); + } + room_impl->room_information.member_slots = 0; + room_impl->room_information.name.clear(); +} + +} // namespace Network diff --git a/src/network/room.h b/src/network/room.h new file mode 100644 index 0000000000..a679848370 --- /dev/null +++ b/src/network/room.h @@ -0,0 +1,173 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include "common/common_types.h" +#include "network/verify_user.h" + +namespace Network { + +constexpr u32 network_version = 4; ///< The version of this Room and RoomMember + +constexpr u16 DefaultRoomPort = 24872; + +constexpr u32 MaxMessageSize = 500; + +/// Maximum number of concurrent connections allowed to this room. +static constexpr u32 MaxConcurrentConnections = 254; + +constexpr std::size_t NumChannels = 1; // Number of channels used for the connection + +struct RoomInformation { + std::string name; ///< Name of the server + std::string description; ///< Server description + u32 member_slots; ///< Maximum number of members in this room + u16 port; ///< The port of this room + std::string preferred_game; ///< Game to advertise that you want to play + u64 preferred_game_id; ///< Title ID for the advertised game + std::string host_username; ///< Forum username of the host + bool enable_citra_mods; ///< Allow Citra Moderators to moderate on this room +}; + +struct GameInfo { + std::string name{""}; + u64 id{0}; +}; + +using MacAddress = std::array; +/// A special MAC address that tells the room we're joining to assign us a MAC address +/// automatically. +constexpr MacAddress NoPreferredMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + +// 802.11 broadcast MAC address +constexpr MacAddress BroadcastMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + +// The different types of messages that can be sent. The first byte of each packet defines the type +enum RoomMessageTypes : u8 { + IdJoinRequest = 1, + IdJoinSuccess, + IdRoomInformation, + IdSetGameInfo, + IdWifiPacket, + IdChatMessage, + IdNameCollision, + IdMacCollision, + IdVersionMismatch, + IdWrongPassword, + IdCloseRoom, + IdRoomIsFull, + IdConsoleIdCollision, + IdStatusMessage, + IdHostKicked, + IdHostBanned, + /// Moderation requests + IdModKick, + IdModBan, + IdModUnban, + IdModGetBanList, + // Moderation responses + IdModBanListResponse, + IdModPermissionDenied, + IdModNoSuchUser, + IdJoinSuccessAsMod, +}; + +/// Types of system status messages +enum StatusMessageTypes : u8 { + IdMemberJoin = 1, ///< Member joining + IdMemberLeave, ///< Member leaving + IdMemberKicked, ///< A member is kicked from the room + IdMemberBanned, ///< A member is banned from the room + IdAddressUnbanned, ///< A username / ip address is unbanned from the room +}; + +/// This is what a server [person creating a server] would use. +class Room final { +public: + enum class State : u8 { + Open, ///< The room is open and ready to accept connections. + Closed, ///< The room is not opened and can not accept connections. + }; + + struct Member { + std::string nickname; ///< The nickname of the member. + std::string username; ///< The web services username of the member. Can be empty. + std::string display_name; ///< The web services display name of the member. Can be empty. + std::string avatar_url; ///< Url to the member's avatar. Can be empty. + GameInfo game_info; ///< The current game of the member + MacAddress mac_address; ///< The assigned mac address of the member. + }; + + Room(); + ~Room(); + + /** + * Gets the current state of the room. + */ + State GetState() const; + + /** + * Gets the room information of the room. + */ + const RoomInformation& GetRoomInformation() const; + + /** + * Gets the verify UID of this room. + */ + std::string GetVerifyUID() const; + + /** + * Gets a list of the mbmers connected to the room. + */ + std::vector GetRoomMemberList() const; + + /** + * Checks if the room is password protected + */ + bool HasPassword() const; + + using UsernameBanList = std::vector; + using IPBanList = std::vector; + + using BanList = std::pair; + + /** + * Creates the socket for this room. Will bind to default address if + * server is empty string. + */ + bool Create(const std::string& name, const std::string& description = "", + const std::string& server = "", u16 server_port = DefaultRoomPort, + const std::string& password = "", + const u32 max_connections = MaxConcurrentConnections, + const std::string& host_username = "", const std::string& preferred_game = "", + u64 preferred_game_id = 0, + std::unique_ptr verify_backend = nullptr, + const BanList& ban_list = {}, bool enable_citra_mods = false); + + /** + * Sets the verification GUID of the room. + */ + void SetVerifyUID(const std::string& uid); + + /** + * Gets the ban list (including banned forum usernames and IPs) of the room. + */ + BanList GetBanList() const; + + /** + * Destroys the socket + */ + void Destroy(); + +private: + class RoomImpl; + std::unique_ptr room_impl; +}; + +} // namespace Network diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp new file mode 100644 index 0000000000..e430040271 --- /dev/null +++ b/src/network/room_member.cpp @@ -0,0 +1,694 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include "common/assert.h" +#include "enet/enet.h" +#include "network/packet.h" +#include "network/room_member.h" + +namespace Network { + +constexpr u32 ConnectionTimeoutMs = 5000; + +class RoomMember::RoomMemberImpl { +public: + ENetHost* client = nullptr; ///< ENet network interface. + ENetPeer* server = nullptr; ///< The server peer the client is connected to + + /// Information about the clients connected to the same room as us. + MemberList member_information; + /// Information about the room we're connected to. + RoomInformation room_information; + + /// The current game name, id and version + GameInfo current_game_info; + + std::atomic state{State::Idle}; ///< Current state of the RoomMember. + void SetState(const State new_state); + void SetError(const Error new_error); + bool IsConnected() const; + + std::string nickname; ///< The nickname of this member. + + std::string username; ///< The username of this member. + mutable std::mutex username_mutex; ///< Mutex for locking username. + + MacAddress mac_address; ///< The mac_address of this member. + + std::mutex network_mutex; ///< Mutex that controls access to the `client` variable. + /// Thread that receives and dispatches network packets + std::unique_ptr loop_thread; + std::mutex send_list_mutex; ///< Mutex that controls access to the `send_list` variable. + std::list send_list; ///< A list that stores all packets to send the async + + template + using CallbackSet = std::set>; + std::mutex callback_mutex; ///< The mutex used for handling callbacks + + class Callbacks { + public: + template + CallbackSet& Get(); + + private: + CallbackSet callback_set_wifi_packet; + CallbackSet callback_set_chat_messages; + CallbackSet callback_set_status_messages; + CallbackSet callback_set_room_information; + CallbackSet callback_set_state; + CallbackSet callback_set_error; + CallbackSet callback_set_ban_list; + }; + Callbacks callbacks; ///< All CallbackSets to all events + + void MemberLoop(); + + void StartLoop(); + + /** + * Sends data to the room. It will be send on channel 0 with flag RELIABLE + * @param packet The data to send + */ + void Send(Packet&& packet); + + /** + * Sends a request to the server, asking for permission to join a room with the specified + * nickname and preferred mac. + * @params nickname The desired nickname. + * @params console_id_hash A hash of the Console ID. + * @params preferred_mac The preferred MAC address to use in the room, the NoPreferredMac tells + * @params password The password for the room + * the server to assign one for us. + */ + void SendJoinRequest(const std::string& nickname, const std::string& console_id_hash, + const MacAddress& preferred_mac = NoPreferredMac, + const std::string& password = "", const std::string& token = ""); + + /** + * Extracts a MAC Address from a received ENet packet. + * @param event The ENet event that was received. + */ + void HandleJoinPacket(const ENetEvent* event); + /** + * Extracts RoomInformation and MemberInformation from a received ENet packet. + * @param event The ENet event that was received. + */ + void HandleRoomInformationPacket(const ENetEvent* event); + + /** + * Extracts a WifiPacket from a received ENet packet. + * @param event The ENet event that was received. + */ + void HandleWifiPackets(const ENetEvent* event); + + /** + * Extracts a chat entry from a received ENet packet and adds it to the chat queue. + * @param event The ENet event that was received. + */ + void HandleChatPacket(const ENetEvent* event); + + /** + * Extracts a system message entry from a received ENet packet and adds it to the system message + * queue. + * @param event The ENet event that was received. + */ + void HandleStatusMessagePacket(const ENetEvent* event); + + /** + * Extracts a ban list request response from a received ENet packet. + * @param event The ENet event that was received. + */ + void HandleModBanListResponsePacket(const ENetEvent* event); + + /** + * Disconnects the RoomMember from the Room + */ + void Disconnect(); + + template + void Invoke(const T& data); + + template + CallbackHandle Bind(std::function callback); +}; + +// RoomMemberImpl +void RoomMember::RoomMemberImpl::SetState(const State new_state) { + if (state != new_state) { + state = new_state; + Invoke(state); + } +} + +void RoomMember::RoomMemberImpl::SetError(const Error new_error) { + Invoke(new_error); +} + +bool RoomMember::RoomMemberImpl::IsConnected() const { + return state == State::Joining || state == State::Joined || state == State::Moderator; +} + +void RoomMember::RoomMemberImpl::MemberLoop() { + // Receive packets while the connection is open + while (IsConnected()) { + std::lock_guard lock(network_mutex); + ENetEvent event; + if (enet_host_service(client, &event, 100) > 0) { + switch (event.type) { + case ENET_EVENT_TYPE_RECEIVE: + switch (event.packet->data[0]) { + case IdWifiPacket: + HandleWifiPackets(&event); + break; + case IdChatMessage: + HandleChatPacket(&event); + break; + case IdStatusMessage: + HandleStatusMessagePacket(&event); + break; + case IdRoomInformation: + HandleRoomInformationPacket(&event); + break; + case IdJoinSuccess: + case IdJoinSuccessAsMod: + // The join request was successful, we are now in the room. + // If we joined successfully, there must be at least one client in the room: us. + ASSERT_MSG(member_information.size() > 0, + "We have not yet received member information."); + HandleJoinPacket(&event); // Get the MAC Address for the client + if (event.packet->data[0] == IdJoinSuccessAsMod) { + SetState(State::Moderator); + } else { + SetState(State::Joined); + } + break; + case IdModBanListResponse: + HandleModBanListResponsePacket(&event); + break; + case IdRoomIsFull: + SetState(State::Idle); + SetError(Error::RoomIsFull); + break; + case IdNameCollision: + SetState(State::Idle); + SetError(Error::NameCollision); + break; + case IdMacCollision: + SetState(State::Idle); + SetError(Error::MacCollision); + break; + case IdConsoleIdCollision: + SetState(State::Idle); + SetError(Error::ConsoleIdCollision); + break; + case IdVersionMismatch: + SetState(State::Idle); + SetError(Error::WrongVersion); + break; + case IdWrongPassword: + SetState(State::Idle); + SetError(Error::WrongPassword); + break; + case IdCloseRoom: + SetState(State::Idle); + SetError(Error::LostConnection); + break; + case IdHostKicked: + SetState(State::Idle); + SetError(Error::HostKicked); + break; + case IdHostBanned: + SetState(State::Idle); + SetError(Error::HostBanned); + break; + case IdModPermissionDenied: + SetError(Error::PermissionDenied); + break; + case IdModNoSuchUser: + SetError(Error::NoSuchUser); + break; + } + enet_packet_destroy(event.packet); + break; + case ENET_EVENT_TYPE_DISCONNECT: + if (state == State::Joined || state == State::Moderator) { + SetState(State::Idle); + SetError(Error::LostConnection); + } + break; + case ENET_EVENT_TYPE_NONE: + break; + case ENET_EVENT_TYPE_CONNECT: + // The ENET_EVENT_TYPE_CONNECT event can not possibly happen here because we're + // already connected + ASSERT_MSG(false, "Received unexpected connect event while already connected"); + break; + } + } + { + std::lock_guard lock(send_list_mutex); + for (const auto& packet : send_list) { + ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(server, 0, enetPacket); + } + enet_host_flush(client); + send_list.clear(); + } + } + Disconnect(); +}; + +void RoomMember::RoomMemberImpl::StartLoop() { + loop_thread = std::make_unique(&RoomMember::RoomMemberImpl::MemberLoop, this); +} + +void RoomMember::RoomMemberImpl::Send(Packet&& packet) { + std::lock_guard lock(send_list_mutex); + send_list.push_back(std::move(packet)); +} + +void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname, + const std::string& console_id_hash, + const MacAddress& preferred_mac, + const std::string& password, + const std::string& token) { + Packet packet; + packet << static_cast(IdJoinRequest); + packet << nickname; + packet << console_id_hash; + packet << preferred_mac; + packet << network_version; + packet << password; + packet << token; + Send(std::move(packet)); +} + +void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + RoomInformation info{}; + packet >> info.name; + packet >> info.description; + packet >> info.member_slots; + packet >> info.port; + packet >> info.preferred_game; + packet >> info.host_username; + room_information.name = info.name; + room_information.description = info.description; + room_information.member_slots = info.member_slots; + room_information.port = info.port; + room_information.preferred_game = info.preferred_game; + room_information.host_username = info.host_username; + + u32 num_members; + packet >> num_members; + member_information.resize(num_members); + + for (auto& member : member_information) { + packet >> member.nickname; + packet >> member.mac_address; + packet >> member.game_info.name; + packet >> member.game_info.id; + packet >> member.username; + packet >> member.display_name; + packet >> member.avatar_url; + + { + std::lock_guard lock(username_mutex); + if (member.nickname == nickname) { + username = member.username; + } + } + } + Invoke(room_information); +} + +void RoomMember::RoomMemberImpl::HandleJoinPacket(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + // Parse the MAC Address from the packet + packet >> mac_address; +} + +void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) { + WifiPacket wifi_packet{}; + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); // Ignore the message type + + // Parse the WifiPacket from the packet + u8 frame_type; + packet >> frame_type; + WifiPacket::PacketType type = static_cast(frame_type); + + wifi_packet.type = type; + packet >> wifi_packet.channel; + packet >> wifi_packet.transmitter_address; + packet >> wifi_packet.destination_address; + packet >> wifi_packet.data; + + Invoke(wifi_packet); +} + +void RoomMember::RoomMemberImpl::HandleChatPacket(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); + + ChatEntry chat_entry{}; + packet >> chat_entry.nickname; + packet >> chat_entry.username; + packet >> chat_entry.message; + Invoke(chat_entry); +} + +void RoomMember::RoomMemberImpl::HandleStatusMessagePacket(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); + + StatusMessageEntry status_message_entry{}; + u8 type{}; + packet >> type; + status_message_entry.type = static_cast(type); + packet >> status_message_entry.nickname; + packet >> status_message_entry.username; + Invoke(status_message_entry); +} + +void RoomMember::RoomMemberImpl::HandleModBanListResponsePacket(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + + // Ignore the first byte, which is the message id. + packet.IgnoreBytes(sizeof(u8)); + + Room::BanList ban_list = {}; + packet >> ban_list.first; + packet >> ban_list.second; + Invoke(ban_list); +} + +void RoomMember::RoomMemberImpl::Disconnect() { + member_information.clear(); + room_information.member_slots = 0; + room_information.name.clear(); + + if (!server) + return; + enet_peer_disconnect(server, 0); + + ENetEvent event; + while (enet_host_service(client, &event, ConnectionTimeoutMs) > 0) { + switch (event.type) { + case ENET_EVENT_TYPE_RECEIVE: + enet_packet_destroy(event.packet); // Ignore all incoming data + break; + case ENET_EVENT_TYPE_DISCONNECT: + server = nullptr; + return; + case ENET_EVENT_TYPE_NONE: + case ENET_EVENT_TYPE_CONNECT: + break; + } + } + // didn't disconnect gracefully force disconnect + enet_peer_reset(server); + server = nullptr; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_wifi_packet; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& +RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_state; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& +RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_error; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& +RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_room_information; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_chat_messages; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& +RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_status_messages; +} + +template <> +RoomMember::RoomMemberImpl::CallbackSet& +RoomMember::RoomMemberImpl::Callbacks::Get() { + return callback_set_ban_list; +} + +template +void RoomMember::RoomMemberImpl::Invoke(const T& data) { + std::lock_guard lock(callback_mutex); + CallbackSet callback_set = callbacks.Get(); + for (auto const& callback : callback_set) + (*callback)(data); +} + +template +RoomMember::CallbackHandle RoomMember::RoomMemberImpl::Bind( + std::function callback) { + std::lock_guard lock(callback_mutex); + CallbackHandle handle; + handle = std::make_shared>(callback); + callbacks.Get().insert(handle); + return handle; +} + +// RoomMember +RoomMember::RoomMember() : room_member_impl{std::make_unique()} {} + +RoomMember::~RoomMember() { + ASSERT_MSG(!IsConnected(), "RoomMember is being destroyed while connected"); + if (room_member_impl->loop_thread) { + Leave(); + } +} + +RoomMember::State RoomMember::GetState() const { + return room_member_impl->state; +} + +const RoomMember::MemberList& RoomMember::GetMemberInformation() const { + return room_member_impl->member_information; +} + +const std::string& RoomMember::GetNickname() const { + return room_member_impl->nickname; +} + +const std::string& RoomMember::GetUsername() const { + std::lock_guard lock(room_member_impl->username_mutex); + return room_member_impl->username; +} + +const MacAddress& RoomMember::GetMacAddress() const { + ASSERT_MSG(IsConnected(), "Tried to get MAC address while not connected"); + return room_member_impl->mac_address; +} + +RoomInformation RoomMember::GetRoomInformation() const { + return room_member_impl->room_information; +} + +void RoomMember::Join(const std::string& nick, const std::string& console_id_hash, + const char* server_addr, u16 server_port, u16 client_port, + const MacAddress& preferred_mac, const std::string& password, + const std::string& token) { + // If the member is connected, kill the connection first + if (room_member_impl->loop_thread && room_member_impl->loop_thread->joinable()) { + Leave(); + } + // If the thread isn't running but the ptr still exists, reset it + else if (room_member_impl->loop_thread) { + room_member_impl->loop_thread.reset(); + } + + if (!room_member_impl->client) { + room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0); + ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client"); + } + + room_member_impl->SetState(State::Joining); + + ENetAddress address{}; + enet_address_set_host(&address, server_addr); + address.port = server_port; + room_member_impl->server = + enet_host_connect(room_member_impl->client, &address, NumChannels, 0); + + if (!room_member_impl->server) { + room_member_impl->SetState(State::Idle); + room_member_impl->SetError(Error::UnknownError); + return; + } + + ENetEvent event{}; + int net = enet_host_service(room_member_impl->client, &event, ConnectionTimeoutMs); + if (net > 0 && event.type == ENET_EVENT_TYPE_CONNECT) { + room_member_impl->nickname = nick; + room_member_impl->StartLoop(); + room_member_impl->SendJoinRequest(nick, console_id_hash, preferred_mac, password, token); + SendGameInfo(room_member_impl->current_game_info); + } else { + enet_peer_disconnect(room_member_impl->server, 0); + room_member_impl->SetState(State::Idle); + room_member_impl->SetError(Error::CouldNotConnect); + } +} + +bool RoomMember::IsConnected() const { + return room_member_impl->IsConnected(); +} + +void RoomMember::SendWifiPacket(const WifiPacket& wifi_packet) { + Packet packet; + packet << static_cast(IdWifiPacket); + packet << static_cast(wifi_packet.type); + packet << wifi_packet.channel; + packet << wifi_packet.transmitter_address; + packet << wifi_packet.destination_address; + packet << wifi_packet.data; + room_member_impl->Send(std::move(packet)); +} + +void RoomMember::SendChatMessage(const std::string& message) { + Packet packet; + packet << static_cast(IdChatMessage); + packet << message; + room_member_impl->Send(std::move(packet)); +} + +void RoomMember::SendGameInfo(const GameInfo& game_info) { + room_member_impl->current_game_info = game_info; + if (!IsConnected()) + return; + + Packet packet; + packet << static_cast(IdSetGameInfo); + packet << game_info.name; + packet << game_info.id; + room_member_impl->Send(std::move(packet)); +} + +void RoomMember::SendModerationRequest(RoomMessageTypes type, const std::string& nickname) { + ASSERT_MSG(type == IdModKick || type == IdModBan || type == IdModUnban, + "type is not a moderation request"); + if (!IsConnected()) + return; + + Packet packet; + packet << static_cast(type); + packet << nickname; + room_member_impl->Send(std::move(packet)); +} + +void RoomMember::RequestBanList() { + if (!IsConnected()) + return; + + Packet packet; + packet << static_cast(IdModGetBanList); + room_member_impl->Send(std::move(packet)); +} + +RoomMember::CallbackHandle RoomMember::BindOnStateChanged( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnError( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnWifiPacketReceived( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnRoomInformationChanged( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnChatMessageRecieved( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnStatusMessageReceived( + std::function callback) { + return room_member_impl->Bind(callback); +} + +RoomMember::CallbackHandle RoomMember::BindOnBanListReceived( + std::function callback) { + return room_member_impl->Bind(callback); +} + +template +void RoomMember::Unbind(CallbackHandle handle) { + std::lock_guard lock(room_member_impl->callback_mutex); + room_member_impl->callbacks.Get().erase(handle); +} + +void RoomMember::Leave() { + room_member_impl->SetState(State::Idle); + room_member_impl->loop_thread->join(); + room_member_impl->loop_thread.reset(); + + enet_host_destroy(room_member_impl->client); + room_member_impl->client = nullptr; +} + +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); +template void RoomMember::Unbind(CallbackHandle); + +} // namespace Network diff --git a/src/network/room_member.h b/src/network/room_member.h new file mode 100644 index 0000000000..ee1c921d46 --- /dev/null +++ b/src/network/room_member.h @@ -0,0 +1,327 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "network/room.h" + +namespace Network { + +/// Information about the received WiFi packets. +/// Acts as our own 802.11 header. +struct WifiPacket { + enum class PacketType : u8 { + Beacon, + Data, + Authentication, + AssociationResponse, + Deauthentication, + NodeMap + }; + PacketType type; ///< The type of 802.11 frame. + std::vector data; ///< Raw 802.11 frame data, starting at the management frame header + /// for management frames. + MacAddress transmitter_address; ///< Mac address of the transmitter. + MacAddress destination_address; ///< Mac address of the receiver. + u8 channel; ///< WiFi channel where this frame was transmitted. + +private: + template + void serialize(Archive& ar, const unsigned int) { + ar& type; + ar& data; + ar& transmitter_address; + ar& destination_address; + ar& channel; + } + friend class boost::serialization::access; +}; + +/// Represents a chat message. +struct ChatEntry { + std::string nickname; ///< Nickname of the client who sent this message. + /// Web services username of the client who sent this message, can be empty. + std::string username; + std::string message; ///< Body of the message. +}; + +/// Represents a system status message. +struct StatusMessageEntry { + StatusMessageTypes type; ///< Type of the message + /// Subject of the message. i.e. the user who is joining/leaving/being banned, etc. + std::string nickname; + std::string username; +}; + +/** + * This is what a client [person joining a server] would use. + * It also has to be used if you host a game yourself (You'd create both, a Room and a + * RoomMembership for yourself) + */ +class RoomMember final { +public: + enum class State : u8 { + Uninitialized, ///< Not initialized + Idle, ///< Default state (i.e. not connected) + Joining, ///< The client is attempting to join a room. + Joined, ///< The client is connected to the room and is ready to send/receive packets. + Moderator, ///< The client is connnected to the room and is granted mod permissions. + }; + + enum class Error : u8 { + // Reasons why connection was closed + LostConnection, ///< Connection closed + HostKicked, ///< Kicked by the host + + // Reasons why connection was rejected + UnknownError, ///< Some error [permissions to network device missing or something] + NameCollision, ///< Somebody is already using this name + MacCollision, ///< Somebody is already using that mac-address + ConsoleIdCollision, ///< Somebody in the room has the same Console ID + WrongVersion, ///< The room version is not the same as for this RoomMember + WrongPassword, ///< The password doesn't match the one from the Room + CouldNotConnect, ///< The room is not responding to a connection attempt + RoomIsFull, ///< Room is already at the maximum number of players + HostBanned, ///< The user is banned by the host + + // Reasons why moderation request failed + PermissionDenied, ///< The user does not have mod permissions + NoSuchUser, ///< The nickname the user attempts to kick/ban does not exist + }; + + struct MemberInformation { + std::string nickname; ///< Nickname of the member. + std::string username; ///< The web services username of the member. Can be empty. + std::string display_name; ///< The web services display name of the member. Can be empty. + std::string avatar_url; ///< Url to the member's avatar. Can be empty. + GameInfo game_info; ///< Name of the game they're currently playing, or empty if they're + /// not playing anything. + MacAddress mac_address; ///< MAC address associated with this member. + }; + using MemberList = std::vector; + + // The handle for the callback functions + template + using CallbackHandle = std::shared_ptr>; + + /** + * Unbinds a callback function from the events. + * @param handle The connection handle to disconnect + */ + template + void Unbind(CallbackHandle handle); + + RoomMember(); + ~RoomMember(); + + /** + * Returns the status of our connection to the room. + */ + State GetState() const; + + /** + * Returns information about the members in the room we're currently connected to. + */ + const MemberList& GetMemberInformation() const; + + /** + * Returns the nickname of the RoomMember. + */ + const std::string& GetNickname() const; + + /** + * Returns the username of the RoomMember. + */ + const std::string& GetUsername() const; + + /** + * Returns the MAC address of the RoomMember. + */ + const MacAddress& GetMacAddress() const; + + /** + * Returns information about the room we're currently connected to. + */ + RoomInformation GetRoomInformation() const; + + /** + * Returns whether we're connected to a server or not. + */ + bool IsConnected() const; + + /** + * Attempts to join a room at the specified address and port, using the specified nickname. + * A console ID hash is passed in to check console ID conflicts. + * This may fail if the username or console ID is already taken. + */ + void Join(const std::string& nickname, const std::string& console_id_hash, + const char* server_addr = "127.0.0.1", u16 server_port = DefaultRoomPort, + u16 client_port = 0, const MacAddress& preferred_mac = NoPreferredMac, + const std::string& password = "", const std::string& token = ""); + + /** + * Sends a WiFi packet to the room. + * @param packet The WiFi packet to send. + */ + void SendWifiPacket(const WifiPacket& packet); + + /** + * Sends a chat message to the room. + * @param message The contents of the message. + */ + void SendChatMessage(const std::string& message); + + /** + * Sends the current game info to the room. + * @param game_info The game information. + */ + void SendGameInfo(const GameInfo& game_info); + + /** + * Sends a moderation request to the room. + * @param type Moderation request type. + * @param nickname The subject of the request. (i.e. the user you want to kick/ban) + */ + void SendModerationRequest(RoomMessageTypes type, const std::string& nickname); + + /** + * Attempts to retrieve ban list from the room. + * If success, the ban list callback would be called. Otherwise an error would be emitted. + */ + void RequestBanList(); + + /** + * Binds a function to an event that will be triggered every time the State of the member + * changed. The function wil be called every time the event is triggered. The callback function + * must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnStateChanged(std::function callback); + + /** + * Binds a function to an event that will be triggered every time an error happened. The + * function wil be called every time the event is triggered. The callback function must not bind + * or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnError(std::function callback); + + /** + * Binds a function to an event that will be triggered every time a WifiPacket is received. + * The function wil be called everytime the event is triggered. + * The callback function must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnWifiPacketReceived( + std::function callback); + + /** + * Binds a function to an event that will be triggered every time the RoomInformation changes. + * The function wil be called every time the event is triggered. + * The callback function must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnRoomInformationChanged( + std::function callback); + + /** + * Binds a function to an event that will be triggered every time a ChatMessage is received. + * The function wil be called every time the event is triggered. + * The callback function must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnChatMessageRecieved( + std::function callback); + + /** + * Binds a function to an event that will be triggered every time a StatusMessage is + * received. The function will be called every time the event is triggered. The callback + * function must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnStatusMessageReceived( + std::function callback); + + /** + * Binds a function to an event that will be triggered every time a requested ban list + * received. The function will be called every time the event is triggered. The callback + * function must not bind or unbind a function. Doing so will cause a deadlock + * @param callback The function to call + * @return A handle used for removing the function from the registered list + */ + CallbackHandle BindOnBanListReceived( + std::function callback); + + /** + * Leaves the current room. + */ + void Leave(); + +private: + class RoomMemberImpl; + std::unique_ptr room_member_impl; +}; + +inline const char* GetStateStr(const RoomMember::State& s) { + switch (s) { + case RoomMember::State::Uninitialized: + return "Uninitialized"; + case RoomMember::State::Idle: + return "Idle"; + case RoomMember::State::Joining: + return "Joining"; + case RoomMember::State::Joined: + return "Joined"; + case RoomMember::State::Moderator: + return "Moderator"; + } + return "Unknown"; +} + +inline const char* GetErrorStr(const RoomMember::Error& e) { + switch (e) { + case RoomMember::Error::LostConnection: + return "LostConnection"; + case RoomMember::Error::HostKicked: + return "HostKicked"; + case RoomMember::Error::UnknownError: + return "UnknownError"; + case RoomMember::Error::NameCollision: + return "NameCollision"; + case RoomMember::Error::MacCollision: + return "MaxCollision"; + case RoomMember::Error::ConsoleIdCollision: + return "ConsoleIdCollision"; + case RoomMember::Error::WrongVersion: + return "WrongVersion"; + case RoomMember::Error::WrongPassword: + return "WrongPassword"; + case RoomMember::Error::CouldNotConnect: + return "CouldNotConnect"; + case RoomMember::Error::RoomIsFull: + return "RoomIsFull"; + case RoomMember::Error::HostBanned: + return "HostBanned"; + case RoomMember::Error::PermissionDenied: + return "PermissionDenied"; + case RoomMember::Error::NoSuchUser: + return "NoSuchUser"; + default: + return "Unknown"; + } +} + +} // namespace Network diff --git a/src/network/verify_user.cpp b/src/network/verify_user.cpp new file mode 100644 index 0000000000..d9d98e4955 --- /dev/null +++ b/src/network/verify_user.cpp @@ -0,0 +1,18 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "network/verify_user.h" + +namespace Network::VerifyUser { + +Backend::~Backend() = default; + +NullBackend::~NullBackend() = default; + +UserData NullBackend::LoadUserData([[maybe_unused]] const std::string& verify_UID, + [[maybe_unused]] const std::string& token) { + return {}; +} + +} // namespace Network::VerifyUser diff --git a/src/network/verify_user.h b/src/network/verify_user.h new file mode 100644 index 0000000000..01b9877c86 --- /dev/null +++ b/src/network/verify_user.h @@ -0,0 +1,46 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include "common/logging/log.h" + +namespace Network::VerifyUser { + +struct UserData { + std::string username; + std::string display_name; + std::string avatar_url; + bool moderator = false; ///< Whether the user is a Citra Moderator. +}; + +/** + * A backend used for verifying users and loading user data. + */ +class Backend { +public: + virtual ~Backend(); + + /** + * Verifies the given token and loads the information into a UserData struct. + * @param verify_UID A GUID that may be used for verification. + * @param token A token that contains user data and verification data. The format and content is + * decided by backends. + */ + virtual UserData LoadUserData(const std::string& verify_UID, const std::string& token) = 0; +}; + +/** + * A null backend where the token is ignored. + * No verification is performed here and the function returns an empty UserData. + */ +class NullBackend final : public Backend { +public: + ~NullBackend(); + + UserData LoadUserData(const std::string& verify_UID, const std::string& token) override; +}; + +} // namespace Network::VerifyUser From 705f7db84dd85555a6aef1e136cf251725cef293 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Sat, 25 Dec 2021 20:27:52 +0100 Subject: [PATCH 02/15] yuzu: Add ui files for multiplayer rooms --- dist/license.md | 9 + .../colorful/icons/16x16/connected.png | Bin 0 -> 362 bytes .../icons/16x16/connected_notification.png | Bin 0 -> 607 bytes .../colorful/icons/16x16/disconnected.png | Bin 0 -> 784 bytes dist/qt_themes/colorful/style.qrc | 3 + dist/qt_themes/colorful_dark/style.qrc | 4 + dist/qt_themes/default/default.qrc | 4 + .../default/icons/16x16/connected.png | Bin 0 -> 269 bytes .../icons/16x16/connected_notification.png | Bin 0 -> 517 bytes .../default/icons/16x16/disconnected.png | Bin 0 -> 306 bytes .../default/icons/48x48/no_avatar.png | Bin 0 -> 588 bytes .../qdarkstyle/icons/16x16/connected.png | Bin 0 -> 397 bytes .../icons/16x16/connected_notification.png | Bin 0 -> 526 bytes .../qdarkstyle/icons/16x16/disconnected.png | Bin 0 -> 444 bytes .../qdarkstyle/icons/48x48/no_avatar.png | Bin 0 -> 708 bytes dist/qt_themes/qdarkstyle/style.qrc | 4 + externals/cpp-jwt | 1 + src/common/CMakeLists.txt | 1 + src/common/announce_multiplayer_room.h | 138 +++++ src/core/CMakeLists.txt | 14 +- src/core/announce_multiplayer_session.cpp | 165 ++++++ src/core/announce_multiplayer_session.h | 96 ++++ src/core/core.cpp | 17 +- src/core/hle/service/nifm/nifm.cpp | 4 +- src/core/hle/service/sockets/bsd.cpp | 4 +- src/core/hle/service/sockets/bsd.h | 2 +- .../hle/service/sockets/sockets_translate.cpp | 2 +- .../hle/service/sockets/sockets_translate.h | 2 +- .../{network => internal_network}/network.cpp | 6 +- .../{network => internal_network}/network.h | 0 .../network_interface.cpp | 2 +- .../network_interface.h | 0 .../{network => internal_network}/sockets.h | 3 +- src/network/room.cpp | 8 +- src/network/room.h | 4 +- src/network/room_member.cpp | 25 +- src/network/verify_user.h | 2 +- src/tests/CMakeLists.txt | 2 +- .../{network => internal_network}/network.cpp | 4 +- src/web_service/CMakeLists.txt | 4 +- src/web_service/announce_room_json.cpp | 157 ++++++ src/web_service/announce_room_json.h | 46 ++ src/yuzu/CMakeLists.txt | 28 +- src/yuzu/configuration/config.cpp | 79 +++ src/yuzu/configuration/config.h | 2 + src/yuzu/configuration/configure_dialog.cpp | 8 +- src/yuzu/configuration/configure_dialog.h | 3 +- src/yuzu/configuration/configure_network.cpp | 2 +- src/yuzu/configuration/configure_web.cpp | 5 + src/yuzu/configuration/configure_web.h | 1 + src/yuzu/configuration/configure_web.ui | 10 + src/yuzu/game_list.cpp | 6 + src/yuzu/game_list.h | 8 + src/yuzu/main.cpp | 39 +- src/yuzu/main.h | 5 + src/yuzu/main.ui | 52 ++ src/yuzu/multiplayer/chat_room.cpp | 490 ++++++++++++++++++ src/yuzu/multiplayer/chat_room.h | 74 +++ src/yuzu/multiplayer/chat_room.ui | 59 +++ src/yuzu/multiplayer/client_room.cpp | 115 ++++ src/yuzu/multiplayer/client_room.h | 39 ++ src/yuzu/multiplayer/client_room.ui | 80 +++ src/yuzu/multiplayer/direct_connect.cpp | 129 +++++ src/yuzu/multiplayer/direct_connect.h | 43 ++ src/yuzu/multiplayer/direct_connect.ui | 168 ++++++ src/yuzu/multiplayer/host_room.cpp | 237 +++++++++ src/yuzu/multiplayer/host_room.h | 74 +++ src/yuzu/multiplayer/host_room.ui | 207 ++++++++ src/yuzu/multiplayer/lobby.cpp | 360 +++++++++++++ src/yuzu/multiplayer/lobby.h | 127 +++++ src/yuzu/multiplayer/lobby.ui | 123 +++++ src/yuzu/multiplayer/lobby_p.h | 239 +++++++++ src/yuzu/multiplayer/message.cpp | 79 +++ src/yuzu/multiplayer/message.h | 65 +++ src/yuzu/multiplayer/moderation_dialog.cpp | 113 ++++ src/yuzu/multiplayer/moderation_dialog.h | 42 ++ src/yuzu/multiplayer/moderation_dialog.ui | 84 +++ src/yuzu/multiplayer/state.cpp | 299 +++++++++++ src/yuzu/multiplayer/state.h | 92 ++++ src/yuzu/multiplayer/validation.h | 49 ++ src/yuzu/uisettings.h | 13 + src/yuzu/util/clickable_label.cpp | 12 + src/yuzu/util/clickable_label.h | 22 + src/yuzu_cmd/yuzu.cpp | 158 ++++++ 84 files changed, 4524 insertions(+), 49 deletions(-) create mode 100644 dist/qt_themes/colorful/icons/16x16/connected.png create mode 100644 dist/qt_themes/colorful/icons/16x16/connected_notification.png create mode 100644 dist/qt_themes/colorful/icons/16x16/disconnected.png create mode 100644 dist/qt_themes/default/icons/16x16/connected.png create mode 100644 dist/qt_themes/default/icons/16x16/connected_notification.png create mode 100644 dist/qt_themes/default/icons/16x16/disconnected.png create mode 100644 dist/qt_themes/default/icons/48x48/no_avatar.png create mode 100644 dist/qt_themes/qdarkstyle/icons/16x16/connected.png create mode 100644 dist/qt_themes/qdarkstyle/icons/16x16/connected_notification.png create mode 100644 dist/qt_themes/qdarkstyle/icons/16x16/disconnected.png create mode 100644 dist/qt_themes/qdarkstyle/icons/48x48/no_avatar.png create mode 160000 externals/cpp-jwt create mode 100644 src/common/announce_multiplayer_room.h create mode 100644 src/core/announce_multiplayer_session.cpp create mode 100644 src/core/announce_multiplayer_session.h rename src/core/{network => internal_network}/network.cpp (99%) rename src/core/{network => internal_network}/network.h (100%) rename src/core/{network => internal_network}/network_interface.cpp (99%) rename src/core/{network => internal_network}/network_interface.h (100%) rename src/core/{network => internal_network}/sockets.h (97%) rename src/tests/core/{network => internal_network}/network.cpp (90%) create mode 100644 src/web_service/announce_room_json.cpp create mode 100644 src/web_service/announce_room_json.h create mode 100644 src/yuzu/multiplayer/chat_room.cpp create mode 100644 src/yuzu/multiplayer/chat_room.h create mode 100644 src/yuzu/multiplayer/chat_room.ui create mode 100644 src/yuzu/multiplayer/client_room.cpp create mode 100644 src/yuzu/multiplayer/client_room.h create mode 100644 src/yuzu/multiplayer/client_room.ui create mode 100644 src/yuzu/multiplayer/direct_connect.cpp create mode 100644 src/yuzu/multiplayer/direct_connect.h create mode 100644 src/yuzu/multiplayer/direct_connect.ui create mode 100644 src/yuzu/multiplayer/host_room.cpp create mode 100644 src/yuzu/multiplayer/host_room.h create mode 100644 src/yuzu/multiplayer/host_room.ui create mode 100644 src/yuzu/multiplayer/lobby.cpp create mode 100644 src/yuzu/multiplayer/lobby.h create mode 100644 src/yuzu/multiplayer/lobby.ui create mode 100644 src/yuzu/multiplayer/lobby_p.h create mode 100644 src/yuzu/multiplayer/message.cpp create mode 100644 src/yuzu/multiplayer/message.h create mode 100644 src/yuzu/multiplayer/moderation_dialog.cpp create mode 100644 src/yuzu/multiplayer/moderation_dialog.h create mode 100644 src/yuzu/multiplayer/moderation_dialog.ui create mode 100644 src/yuzu/multiplayer/state.cpp create mode 100644 src/yuzu/multiplayer/state.h create mode 100644 src/yuzu/multiplayer/validation.h create mode 100644 src/yuzu/util/clickable_label.cpp create mode 100644 src/yuzu/util/clickable_label.h diff --git a/dist/license.md b/dist/license.md index 7bdebfec1f..c5ebe9c003 100644 --- a/dist/license.md +++ b/dist/license.md @@ -3,6 +3,9 @@ The icons in this folder and its subfolders have the following licenses: Icon Name | License | Origin/Author --- | --- | --- qt_themes/default/icons/16x16/checked.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/default/icons/16x16/connected.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/default/icons/16x16/connected_notification.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/default/icons/16x16/disconnected.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/16x16/failed.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/16x16/lock.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/16x16/view-refresh.png | Apache 2.0 | https://material.io @@ -10,18 +13,24 @@ qt_themes/default/icons/256x256/plus_folder.png | CC BY-ND 3.0 | https://icons8. qt_themes/default/icons/48x48/bad_folder.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/48x48/chip.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/48x48/folder.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/default/icons/48x48/no_avatar.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/48x48/plus.png | CC0 1.0 | Designed by BreadFish64 from the Citra team qt_themes/default/icons/48x48/sd_card.png | CC BY-ND 3.0 | https://icons8.com qt_themes/default/icons/48x48/star.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/qdarkstyle/icons/16x16/connected.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/qdarkstyle/icons/16x16/connected_notification.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/16x16/lock.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/16x16/view-refresh.png | Apache 2.0 | https://material.io qt_themes/qdarkstyle/icons/256x256/plus_folder.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/48x48/bad_folder.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/48x48/chip.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/48x48/folder.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/qdarkstyle/icons/48x48/no_avatar.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/48x48/plus.png | CC0 1.0 | Designed by BreadFish64 from the Citra team qt_themes/qdarkstyle/icons/48x48/sd_card.png | CC BY-ND 3.0 | https://icons8.com qt_themes/qdarkstyle/icons/48x48/star.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/colorful/icons/16x16/connected.png | CC BY-ND 3.0 | https://icons8.com +qt_themes/colorful/icons/16x16/connected_notification.png | CC BY-ND 3.0 | https://icons8.com qt_themes/colorful/icons/16x16/lock.png | CC BY-ND 3.0 | https://icons8.com qt_themes/colorful/icons/16x16/view-refresh.png | Apache 2.0 | https://material.io qt_themes/colorful/icons/256x256/plus_folder.png | CC BY-ND 3.0 | https://icons8.com diff --git a/dist/qt_themes/colorful/icons/16x16/connected.png b/dist/qt_themes/colorful/icons/16x16/connected.png new file mode 100644 index 0000000000000000000000000000000000000000..d6052f1a09a9a828bf8d43ad1827d4d9d9cbae0f GIT binary patch literal 362 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBugD~Uq{1quc!T+8vjv*HQ$r4owhbC=p{o8&0tK-fV$N!7I zG75{Wk2Xy_x$CCz^fmhIm;O7pIV>$~UU0|jc-Os|kq&3=6=xmz@v22N`_uxjg657l zK`STRITf1dYARnXzHVnz%7Op?j%KGjO-*Ef=z4Y2!JVP;O`o&4nm=o8Um(r&<$utM zpf?GRCYAmx4Sx2X_vGqd?TH*0tQ9I(1o>RpUa?m2%z2>1TX%C75w(D&HyAH45$5j4PH{Kc+44&>bodk5m->}@RC7fLxAcI z#!1f(d3s;Z@QK)^x266fTk#5$LAl}+;~l5Q zvTbMg9^UuieCIpx-&Ifi=FyAs#93blXAAVk6T1cLkfNhvWKhv_s&Zmhz^+*5hT57% zOF_;n8U!$wS#BAtE4F_}x9_uN3h#||R;qIF^}7#eT+d|uz94mKnfhXH31H9huIfo8 zi^zay+&fR64K1E@-JxlR%=;^#xv6PIV?+G_s+UCMg=h4^)8}bd)f^GE)~e{qV!srN z3)gS0wp1Shp|S7zWIB^sFUGWeiInyCIgX))T9mw`_&DPPf>r?`06RRtwXvb@^0G)- zvhTjLk|#o z6b%F40BRWfRG*xU)HfORdVHeMwzg(YsI)*YB#UnSgU(w<`ka z({=BSp$~)N!i*09^m-ixwy0%@^JLsMc);uRIsiZ) zuLI9}Ao~5H-7!{nzHnbt1h`(`n!P@CZF^;XOBDdj2{VlYef>Elg$2zM_TEx)f%gM| zUZ=yD!}+%K$gbM}Kq7aFCTBFu)Nxkps?w_aZPdD~J>>xKvH4(vCB=E_n|RDx~z-v`(u{Ck(>^ z0K?FTjg5ud&4Z?C%4}L$RQtHS76>VRIGUfI`z*_{6mBpK4XsuKH!pyuX^Kna4xOuM z+^h(UdmYV_Q&T;Qn}iUk)hg+yeWcSi;>fQo&hJ(N2*<9-;|zukPUl1ymtfdJ7=}o) zEICHUE|eYJU8xid7X<*9>zeX|uHNTr)5hE=LNY|r-*L8JZ`1$60Pq`<)BU@nD5;_V O0000 icons/index.theme + icons/16x16/connected.png + icons/16x16/connected_notification.png + icons/16x16/disconnected.png icons/16x16/lock.png icons/48x48/bad_folder.png icons/48x48/chip.png diff --git a/dist/qt_themes/colorful_dark/style.qrc b/dist/qt_themes/colorful_dark/style.qrc index 0abcb4e83d..602c71b328 100644 --- a/dist/qt_themes/colorful_dark/style.qrc +++ b/dist/qt_themes/colorful_dark/style.qrc @@ -1,11 +1,15 @@ + ../colorful/icons/16x16/connected.png + ../colorful/icons/16x16/connected_notification.png + ../colorful/icons/16x16/disconnected.png icons/index.theme icons/16x16/lock.png icons/16x16/view-refresh.png ../colorful/icons/48x48/bad_folder.png ../colorful/icons/48x48/chip.png ../colorful/icons/48x48/folder.png + ../qdarkstyle/icons/48x48/no_avatar.png ../colorful/icons/48x48/plus.png ../colorful/icons/48x48/sd_card.png ../colorful/icons/256x256/plus_folder.png diff --git a/dist/qt_themes/default/default.qrc b/dist/qt_themes/default/default.qrc index b195747a37..41842e5d83 100644 --- a/dist/qt_themes/default/default.qrc +++ b/dist/qt_themes/default/default.qrc @@ -4,10 +4,14 @@ icons/16x16/checked.png icons/16x16/failed.png icons/16x16/lock.png + icons/16x16/connected.png + icons/16x16/disconnected.png + icons/16x16/connected_notification.png icons/16x16/view-refresh.png icons/48x48/bad_folder.png icons/48x48/chip.png icons/48x48/folder.png + icons/48x48/no_avatar.png icons/48x48/plus.png icons/48x48/sd_card.png icons/48x48/star.png diff --git a/dist/qt_themes/default/icons/16x16/connected.png b/dist/qt_themes/default/icons/16x16/connected.png new file mode 100644 index 0000000000000000000000000000000000000000..afa7973948c2fd69a5b838ebc993a4a618e20e31 GIT binary patch literal 269 zcmV+o0rLKdP)wVS)a5(TtL3F*6^H+fmi83={^g~HAo7u1ZbyiW#=5CU=?7R{1!Zbe$F9tyMfYy zZs6*qt^z68Vfj6G&{i5N*B8S8soODKE0Ee2()LDxTpa4zWdu+_YwLCwvHtx4JVP#E TIr_f000000NkvXXu0mjf{AX#) literal 0 HcmV?d00001 diff --git a/dist/qt_themes/default/icons/16x16/connected_notification.png b/dist/qt_themes/default/icons/16x16/connected_notification.png new file mode 100644 index 0000000000000000000000000000000000000000..e64901378b000db1871d03db88af5f06c454cb01 GIT binary patch literal 517 zcmV+g0{Z=lP)=oH5kv??W6KBf~W^uD5aJbuU z?1_l^zTebLSsabzI+llOtNV%$o|VX}coVWS{*HQ<)uxI9Ck6S4=9S_D*7>#60 zKOeWZFLYif{X3q+e8sGmn$7ygk(FzSW2Em%_GsHe=P~>O_ZNK92NF;*00000NkvXX Hu0mjf^1s=j literal 0 HcmV?d00001 diff --git a/dist/qt_themes/default/icons/16x16/disconnected.png b/dist/qt_themes/default/icons/16x16/disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..835b1f0d6b5ceeb11e9a2b7d68c61521aef7bcb8 GIT binary patch literal 306 zcmV-20nPr2P)au7)Yo#YK5^hRAPlWv+5i9m07*qoM6N<$ Ef=+yWl>h($ literal 0 HcmV?d00001 diff --git a/dist/qt_themes/default/icons/48x48/no_avatar.png b/dist/qt_themes/default/icons/48x48/no_avatar.png new file mode 100644 index 0000000000000000000000000000000000000000..d4bf82026a63d3498c57615ed744ef6ad1a11db4 GIT binary patch literal 588 zcmV-S0<-;zP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0pUqRK~!i%?bts^ z)L|UQ@k_%$K?EW+2x>Uh5Tcv9ID|t(AUGrhij56zIR}A+gAO9Jr08b!2O=6m2Zt72 zf~GJKrJ<=1OR>`Tcl&XCxO<+v^S%%9d&6t}-N*C({O&2_<>l49c1+H(cMu9ry_~F2o$%>&5}pz)}{_h$OO) zLp8FLVI))R7uq*mL^55%F4S1%5t8c`j-du;eT4mvPO?u>qqAIZpUbrkH99NlKOp2k za39IG12sD9A(E^gf1yTa*^%P~B-H@+pav_?k;D;W4;B&f%onro4Lgyj`$wvsFyF>I zR5HBScRWES&NX|c9^fm~kZReX?+f&yrr8^A68lgOTx)jR_zGR9Iy?7YgLmcf a6$)pIccPOKD6@6|0000Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0U}96K~y+TrIbBN z15p%(2ThUA!elK%1O;&sLOKPvAQqN^S%76$5m9U;Tacs`0+KRKh!$yP^1YdppLy@j zBbpBm?{V)rhhg%Q973Mw%`D4aP+z0Jqmp;@i!L;dL#Tnd!+DKbUdg3waWGz?Z^8u% zk9EdN@ZV$lKwY#fE2=PmlHCTw9lAj?WlY$Q6tTfDbS3CER>p3rhz*9WjL|aY6GcK; zx)-~7C$0pUWy~HGtHREG#M9EY#VX_e#&N7@6_#hEEo8S0El^vr5SHi4nW$v_WT|2y zEKe}ain4kx)4O#2)N;bb8 r=102j2jPKV@-HZOM*IDr)RH7C%sED}gz8E800000NkvXXu0mjf2Q8tG literal 0 HcmV?d00001 diff --git a/dist/qt_themes/qdarkstyle/icons/16x16/connected_notification.png b/dist/qt_themes/qdarkstyle/icons/16x16/connected_notification.png new file mode 100644 index 0000000000000000000000000000000000000000..7cd8b9d2930d99340778360c68bf28923a66609c GIT binary patch literal 526 zcmV+p0`dKcP)2WpUc5F_z--H^xh8V++PPa z33XEKY?gdgT~jBj|8aa2I1da0uYrTWBVZ~bo|TbKsi966PC1e~wUOg4^}G7fa*Xuu zD}ChCz!%^SaA1RG7s}j2{h+R>H`N~{31-R!rn93J^+qAGq+VB#t4(!Zk5kRaL%_XE zZwD|7j010%$4)l2G8(}uq%QEa{|BSMKwqd&%+I&Gt@=}pSAmByUBvjj+&Xa?AhHBA zg=3C-cdUL$odY1E5y>+Kw}I7x%KDK!!OK4KI`Cf7rGGvQYAIF5bAb`SY)*g}wJhau z3ikh)8lzs_F#r7`PS@PYUsN&*fWd_-?rE zoG=u!$6)85fB0bU!s5G7mw@{bF;~)+PNPxVI=FT#;4H+?AU)r`u=oPtH#>3~=2X*b QzyJUM07*qoM6N<$g7iq=m;e9( literal 0 HcmV?d00001 diff --git a/dist/qt_themes/qdarkstyle/icons/16x16/disconnected.png b/dist/qt_themes/qdarkstyle/icons/16x16/disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..fc5f23894e4aedae7a49981f68ba017a177b065b GIT binary patch literal 444 zcmV;t0YmPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0Z~arK~y+Tm6X3q z!(bG}BM3T)4oat1>3fJGI5_zRqJs}n!QHVSy7&}|Z{Q;C6&zcsljtHSLgMcv$HI{dexom*ghNEXcBKF-_BL>^@v~d;_m6`5%aP;4{rR@W0^`{D7O5#ex19(LFqb zU&V+JY)3s}}a0Qf@czHi&OA^DY-4`2a_->y&b9cID?Mf&*K<#kR|Tpm5}?1j7X4 z4jjTqBrVk)Us_UtgqE$`6a4DQ_TU|*mQ&iX713e2_G4@Sa=K!0vPRIeRkTiGreO$! zH&MmZ!_eyCMZY6~+NXx$F1sZT1bRk;ysHB8+LJc+0^2+Y(KXbspbuX?;02!GhRfCj m8qQ()KfzyOz?{P=kt9FFYiX8^{jL1~0000Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0$E8!K~!i%?U+4C z98nlWS0ieKAc&Ach>BHGNYF0YqzD!%gn)&DplF%GF4lqk-Z(wLx~!5;{cLSkWI zlQe-;q9BTeRU~K>b=Nb#TM5I?JlFRgG6yc>;`{D*#@}Uf85tR+rBEo;=kxg?@`?Q5 z^-r#wvA0p3&g6)M?Qe5o~yzyh)l{YEq|GP zp&CCRQH#Wx@ktM}>#Fht4n0Q24sIagsp{Or@@ctPLr0hD+{5w(d00b7zv|q>@^A96 zhK@efxrhCqjfOqkK)34L!}1Av+=Z8_a}PH#Bnc~+KjBiTI`<&ZYEtG4KGTZ(fhEyH-1lVHtS&9|Mh|_zk~Xa@4Rn`LI!F%8s{4gK5zC}e3ii-fP0^yM zb_;utiTz_oI-;NTRa55&_MejuDW!w?0aN1_ZeW|F|4YTtA9Z*KmtJWlgMntv1_3?` qQcDIioeb>+lqIQUWMn)Xa=B}!H(avGT(DUH0000 icons/index.theme + icons/16x16/connected.png + icons/16x16/disconnected.png + icons/16x16/connected_notification.png icons/16x16/lock.png icons/16x16/view-refresh.png icons/48x48/bad_folder.png icons/48x48/chip.png icons/48x48/folder.png + icons/48x48/no_avatar.png icons/48x48/plus.png icons/48x48/sd_card.png icons/48x48/star.png diff --git a/externals/cpp-jwt b/externals/cpp-jwt new file mode 160000 index 0000000000..e12ef06218 --- /dev/null +++ b/externals/cpp-jwt @@ -0,0 +1 @@ +Subproject commit e12ef06218596b52d9b5d6e1639484866a8e7067 diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index d574e4b792..05fdfea829 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -41,6 +41,7 @@ add_custom_command(OUTPUT scm_rev.cpp add_library(common STATIC algorithm.h alignment.h + announce_multiplayer_room.h assert.cpp assert.h atomic_helpers.h diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h new file mode 100644 index 0000000000..5ca5893ef0 --- /dev/null +++ b/src/common/announce_multiplayer_room.h @@ -0,0 +1,138 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include "common/common_types.h" +#include "web_service/web_result.h" + +namespace AnnounceMultiplayerRoom { + +using MacAddress = std::array; + +struct Room { + struct Member { + std::string username; + std::string nickname; + std::string avatar_url; + MacAddress mac_address; + std::string game_name; + u64 game_id; + }; + std::string id; + std::string verify_UID; ///< UID used for verification + std::string name; + std::string description; + std::string owner; + std::string ip; + u16 port; + u32 max_player; + u32 net_version; + bool has_password; + std::string preferred_game; + u64 preferred_game_id; + + std::vector members; +}; +using RoomList = std::vector; + +/** + * A AnnounceMultiplayerRoom interface class. A backend to submit/get to/from a web service should + * implement this interface. + */ +class Backend { +public: + virtual ~Backend() = default; + + /** + * Sets the Information that gets used for the announce + * @param uid The Id of the room + * @param name The name of the room + * @param description The room description + * @param port The port of the room + * @param net_version The version of the libNetwork that gets used + * @param has_password True if the room is passowrd protected + * @param preferred_game The preferred game of the room + * @param preferred_game_id The title id of the preferred game + */ + virtual void SetRoomInformation(const std::string& name, const std::string& description, + const u16 port, const u32 max_player, const u32 net_version, + const bool has_password, const std::string& preferred_game, + const u64 preferred_game_id) = 0; + /** + * Adds a player information to the data that gets announced + * @param nickname The nickname of the player + * @param mac_address The MAC Address of the player + * @param game_id The title id of the game the player plays + * @param game_name The name of the game the player plays + */ + virtual void AddPlayer(const std::string& username, const std::string& nickname, + const std::string& avatar_url, const MacAddress& mac_address, + const u64 game_id, const std::string& game_name) = 0; + + /** + * Updates the data in the announce service. Re-register the room when required. + * @result The result of the update attempt + */ + virtual WebService::WebResult Update() = 0; + + /** + * Registers the data in the announce service + * @result The result of the register attempt. When the result code is Success, A global Guid of + * the room which may be used for verification will be in the result's returned_data. + */ + virtual WebService::WebResult Register() = 0; + + /** + * Empties the stored players + */ + virtual void ClearPlayers() = 0; + + /** + * Get the room information from the announce service + * @result A list of all rooms the announce service has + */ + virtual RoomList GetRoomList() = 0; + + /** + * Sends a delete message to the announce service + */ + virtual void Delete() = 0; +}; + +/** + * Empty implementation of AnnounceMultiplayerRoom interface that drops all data. Used when a + * functional backend implementation is not available. + */ +class NullBackend : public Backend { +public: + ~NullBackend() = default; + void SetRoomInformation(const std::string& /*name*/, const std::string& /*description*/, + const u16 /*port*/, const u32 /*max_player*/, const u32 /*net_version*/, + const bool /*has_password*/, const std::string& /*preferred_game*/, + const u64 /*preferred_game_id*/) override {} + void AddPlayer(const std::string& /*username*/, const std::string& /*nickname*/, + const std::string& /*avatar_url*/, const MacAddress& /*mac_address*/, + const u64 /*game_id*/, const std::string& /*game_name*/) override {} + WebService::WebResult Update() override { + return WebService::WebResult{WebService::WebResult::Code::NoWebservice, + "WebService is missing"}; + } + WebService::WebResult Register() override { + return WebService::WebResult{WebService::WebResult::Code::NoWebservice, + "WebService is missing"}; + } + void ClearPlayers() override {} + RoomList GetRoomList() override { + return RoomList{}; + } + + void Delete() override {} +}; + +} // namespace AnnounceMultiplayerRoom diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 32cc2f3920..48f5c1ee0a 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -1,4 +1,6 @@ add_library(core STATIC + announce_multiplayer_session.cpp + announce_multiplayer_session.h arm/arm_interface.h arm/arm_interface.cpp arm/cpu_interrupt_handler.cpp @@ -741,11 +743,11 @@ add_library(core STATIC memory/dmnt_cheat_vm.h memory.cpp memory.h - network/network.cpp - network/network.h - network/network_interface.cpp - network/network_interface.h - network/sockets.h + internal_network/network.cpp + internal_network/network.h + internal_network/network_interface.cpp + internal_network/network_interface.h + internal_network/sockets.h perf_stats.cpp perf_stats.h reporter.cpp @@ -780,7 +782,7 @@ endif() create_target_directory_groups(core) -target_link_libraries(core PUBLIC common PRIVATE audio_core video_core) +target_link_libraries(core PUBLIC common PRIVATE audio_core network video_core) target_link_libraries(core PUBLIC Boost::boost PRIVATE fmt::fmt nlohmann_json::nlohmann_json mbedtls Opus::Opus) if (MINGW) target_link_libraries(core PRIVATE ${MSWSOCK_LIBRARY}) diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp new file mode 100644 index 0000000000..a680ad202e --- /dev/null +++ b/src/core/announce_multiplayer_session.cpp @@ -0,0 +1,165 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include "announce_multiplayer_session.h" +#include "common/announce_multiplayer_room.h" +#include "common/assert.h" +#include "common/settings.h" +#include "network/network.h" + +#ifdef ENABLE_WEB_SERVICE +#include "web_service/announce_room_json.h" +#endif + +namespace Core { + +// Time between room is announced to web_service +static constexpr std::chrono::seconds announce_time_interval(15); + +AnnounceMultiplayerSession::AnnounceMultiplayerSession() { +#ifdef ENABLE_WEB_SERVICE + backend = std::make_unique(Settings::values.web_api_url.GetValue(), + Settings::values.yuzu_username.GetValue(), + Settings::values.yuzu_token.GetValue()); +#else + backend = std::make_unique(); +#endif +} + +WebService::WebResult AnnounceMultiplayerSession::Register() { + std::shared_ptr room = Network::GetRoom().lock(); + if (!room) { + return WebService::WebResult{WebService::WebResult::Code::LibError, + "Network is not initialized"}; + } + if (room->GetState() != Network::Room::State::Open) { + return WebService::WebResult{WebService::WebResult::Code::LibError, "Room is not open"}; + } + UpdateBackendData(room); + WebService::WebResult result = backend->Register(); + if (result.result_code != WebService::WebResult::Code::Success) { + return result; + } + LOG_INFO(WebService, "Room has been registered"); + room->SetVerifyUID(result.returned_data); + registered = true; + return WebService::WebResult{WebService::WebResult::Code::Success}; +} + +void AnnounceMultiplayerSession::Start() { + if (announce_multiplayer_thread) { + Stop(); + } + shutdown_event.Reset(); + announce_multiplayer_thread = + std::make_unique(&AnnounceMultiplayerSession::AnnounceMultiplayerLoop, this); +} + +void AnnounceMultiplayerSession::Stop() { + if (announce_multiplayer_thread) { + shutdown_event.Set(); + announce_multiplayer_thread->join(); + announce_multiplayer_thread.reset(); + backend->Delete(); + registered = false; + } +} + +AnnounceMultiplayerSession::CallbackHandle AnnounceMultiplayerSession::BindErrorCallback( + std::function function) { + std::lock_guard lock(callback_mutex); + auto handle = std::make_shared>(function); + error_callbacks.insert(handle); + return handle; +} + +void AnnounceMultiplayerSession::UnbindErrorCallback(CallbackHandle handle) { + std::lock_guard lock(callback_mutex); + error_callbacks.erase(handle); +} + +AnnounceMultiplayerSession::~AnnounceMultiplayerSession() { + Stop(); +} + +void AnnounceMultiplayerSession::UpdateBackendData(std::shared_ptr room) { + Network::RoomInformation room_information = room->GetRoomInformation(); + std::vector memberlist = room->GetRoomMemberList(); + backend->SetRoomInformation( + room_information.name, room_information.description, room_information.port, + room_information.member_slots, Network::network_version, room->HasPassword(), + room_information.preferred_game, room_information.preferred_game_id); + backend->ClearPlayers(); + for (const auto& member : memberlist) { + backend->AddPlayer(member.username, member.nickname, member.avatar_url, member.mac_address, + member.game_info.id, member.game_info.name); + } +} + +void AnnounceMultiplayerSession::AnnounceMultiplayerLoop() { + // Invokes all current bound error callbacks. + const auto ErrorCallback = [this](WebService::WebResult result) { + std::lock_guard lock(callback_mutex); + for (auto callback : error_callbacks) { + (*callback)(result); + } + }; + + if (!registered) { + WebService::WebResult result = Register(); + if (result.result_code != WebService::WebResult::Code::Success) { + ErrorCallback(result); + return; + } + } + + auto update_time = std::chrono::steady_clock::now(); + std::future future; + while (!shutdown_event.WaitUntil(update_time)) { + update_time += announce_time_interval; + std::shared_ptr room = Network::GetRoom().lock(); + if (!room) { + break; + } + if (room->GetState() != Network::Room::State::Open) { + break; + } + UpdateBackendData(room); + WebService::WebResult result = backend->Update(); + if (result.result_code != WebService::WebResult::Code::Success) { + ErrorCallback(result); + } + if (result.result_string == "404") { + registered = false; + // Needs to register the room again + WebService::WebResult register_result = Register(); + if (register_result.result_code != WebService::WebResult::Code::Success) { + ErrorCallback(register_result); + } + } + } +} + +AnnounceMultiplayerRoom::RoomList AnnounceMultiplayerSession::GetRoomList() { + return backend->GetRoomList(); +} + +bool AnnounceMultiplayerSession::IsRunning() const { + return announce_multiplayer_thread != nullptr; +} + +void AnnounceMultiplayerSession::UpdateCredentials() { + ASSERT_MSG(!IsRunning(), "Credentials can only be updated when session is not running"); + +#ifdef ENABLE_WEB_SERVICE + backend = std::make_unique(Settings::values.web_api_url.GetValue(), + Settings::values.yuzu_username.GetValue(), + Settings::values.yuzu_token.GetValue()); +#endif +} + +} // namespace Core diff --git a/src/core/announce_multiplayer_session.h b/src/core/announce_multiplayer_session.h new file mode 100644 index 0000000000..2aaf550177 --- /dev/null +++ b/src/core/announce_multiplayer_session.h @@ -0,0 +1,96 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "common/announce_multiplayer_room.h" +#include "common/common_types.h" +#include "common/thread.h" + +namespace Network { +class Room; +} + +namespace Core { + +/** + * Instruments AnnounceMultiplayerRoom::Backend. + * Creates a thread that regularly updates the room information and submits them + * An async get of room information is also possible + */ +class AnnounceMultiplayerSession { +public: + using CallbackHandle = std::shared_ptr>; + AnnounceMultiplayerSession(); + ~AnnounceMultiplayerSession(); + + /** + * Allows to bind a function that will get called if the announce encounters an error + * @param function The function that gets called + * @return A handle that can be used the unbind the function + */ + CallbackHandle BindErrorCallback(std::function function); + + /** + * Unbind a function from the error callbacks + * @param handle The handle for the function that should get unbind + */ + void UnbindErrorCallback(CallbackHandle handle); + + /** + * Registers a room to web services + * @return The result of the registration attempt. + */ + WebService::WebResult Register(); + + /** + * Starts the announce of a room to web services + */ + void Start(); + + /** + * Stops the announce to web services + */ + void Stop(); + + /** + * Returns a list of all room information the backend got + * @param func A function that gets executed when the async get finished, e.g. a signal + * @return a list of rooms received from the web service + */ + AnnounceMultiplayerRoom::RoomList GetRoomList(); + + /** + * Whether the announce session is still running + */ + bool IsRunning() const; + + /** + * Recreates the backend, updating the credentials. + * This can only be used when the announce session is not running. + */ + void UpdateCredentials(); + +private: + Common::Event shutdown_event; + std::mutex callback_mutex; + std::set error_callbacks; + std::unique_ptr announce_multiplayer_thread; + + /// Backend interface that logs fields + std::unique_ptr backend; + + std::atomic_bool registered = false; ///< Whether the room has been registered + + void UpdateBackendData(std::shared_ptr room); + void AnnounceMultiplayerLoop(); +}; + +} // namespace Core diff --git a/src/core/core.cpp b/src/core/core.cpp index 0ede0d85c0..5df32c1e7d 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -43,14 +43,15 @@ #include "core/hle/service/service.h" #include "core/hle/service/sm/sm.h" #include "core/hle/service/time/time_manager.h" +#include "core/internal_network/network.h" #include "core/loader/loader.h" #include "core/memory.h" #include "core/memory/cheat_engine.h" -#include "core/network/network.h" #include "core/perf_stats.h" #include "core/reporter.h" #include "core/telemetry_session.h" #include "core/tools/freezer.h" +#include "network/network.h" #include "video_core/renderer_base.h" #include "video_core/video_core.h" @@ -315,6 +316,15 @@ struct System::Impl { GetAndResetPerfStats(); perf_stats->BeginSystemFrame(); + std::string name = "Unknown Game"; + const Loader::ResultStatus res{app_loader->ReadTitle(name)}; + if (auto room_member = Network::GetRoomMember().lock()) { + Network::GameInfo game_info; + game_info.name = name; + game_info.id = program_id; + room_member->SendGameInfo(game_info); + } + status = SystemResultStatus::Success; return status; } @@ -362,6 +372,11 @@ struct System::Impl { memory.Reset(); applet_manager.ClearAll(); + if (auto room_member = Network::GetRoomMember().lock()) { + Network::GameInfo game_info{}; + room_member->SendGameInfo(game_info); + } + LOG_DEBUG(Core, "Shutdown OK"); } diff --git a/src/core/hle/service/nifm/nifm.cpp b/src/core/hle/service/nifm/nifm.cpp index 7055ea93e7..2889973e46 100644 --- a/src/core/hle/service/nifm/nifm.cpp +++ b/src/core/hle/service/nifm/nifm.cpp @@ -18,8 +18,8 @@ namespace { } // Anonymous namespace -#include "core/network/network.h" -#include "core/network/network_interface.h" +#include "core/internal_network/network.h" +#include "core/internal_network/network_interface.h" namespace Service::NIFM { diff --git a/src/core/hle/service/sockets/bsd.cpp b/src/core/hle/service/sockets/bsd.cpp index 3e9dc4a139..c7194731ed 100644 --- a/src/core/hle/service/sockets/bsd.cpp +++ b/src/core/hle/service/sockets/bsd.cpp @@ -13,8 +13,8 @@ #include "core/hle/kernel/k_thread.h" #include "core/hle/service/sockets/bsd.h" #include "core/hle/service/sockets/sockets_translate.h" -#include "core/network/network.h" -#include "core/network/sockets.h" +#include "core/internal_network/network.h" +#include "core/internal_network/sockets.h" namespace Service::Sockets { diff --git a/src/core/hle/service/sockets/bsd.h b/src/core/hle/service/sockets/bsd.h index fed740d878..9ea36428d6 100644 --- a/src/core/hle/service/sockets/bsd.h +++ b/src/core/hle/service/sockets/bsd.h @@ -16,7 +16,7 @@ class System; namespace Network { class Socket; -} +} // namespace Network namespace Service::Sockets { diff --git a/src/core/hle/service/sockets/sockets_translate.cpp b/src/core/hle/service/sockets/sockets_translate.cpp index 9c0936d973..2db10ec810 100644 --- a/src/core/hle/service/sockets/sockets_translate.cpp +++ b/src/core/hle/service/sockets/sockets_translate.cpp @@ -7,7 +7,7 @@ #include "common/common_types.h" #include "core/hle/service/sockets/sockets.h" #include "core/hle/service/sockets/sockets_translate.h" -#include "core/network/network.h" +#include "core/internal_network/network.h" namespace Service::Sockets { diff --git a/src/core/hle/service/sockets/sockets_translate.h b/src/core/hle/service/sockets/sockets_translate.h index 5e9809add2..c93291d3ee 100644 --- a/src/core/hle/service/sockets/sockets_translate.h +++ b/src/core/hle/service/sockets/sockets_translate.h @@ -7,7 +7,7 @@ #include "common/common_types.h" #include "core/hle/service/sockets/sockets.h" -#include "core/network/network.h" +#include "core/internal_network/network.h" namespace Service::Sockets { diff --git a/src/core/network/network.cpp b/src/core/internal_network/network.cpp similarity index 99% rename from src/core/network/network.cpp rename to src/core/internal_network/network.cpp index fdafbea923..36c43cc8ff 100644 --- a/src/core/network/network.cpp +++ b/src/core/internal_network/network.cpp @@ -29,9 +29,9 @@ #include "common/common_types.h" #include "common/logging/log.h" #include "common/settings.h" -#include "core/network/network.h" -#include "core/network/network_interface.h" -#include "core/network/sockets.h" +#include "core/internal_network/network.h" +#include "core/internal_network/network_interface.h" +#include "core/internal_network/sockets.h" namespace Network { diff --git a/src/core/network/network.h b/src/core/internal_network/network.h similarity index 100% rename from src/core/network/network.h rename to src/core/internal_network/network.h diff --git a/src/core/network/network_interface.cpp b/src/core/internal_network/network_interface.cpp similarity index 99% rename from src/core/network/network_interface.cpp rename to src/core/internal_network/network_interface.cpp index 15ecc6abf5..0f0a661606 100644 --- a/src/core/network/network_interface.cpp +++ b/src/core/internal_network/network_interface.cpp @@ -11,7 +11,7 @@ #include "common/logging/log.h" #include "common/settings.h" #include "common/string_util.h" -#include "core/network/network_interface.h" +#include "core/internal_network/network_interface.h" #ifdef _WIN32 #include diff --git a/src/core/network/network_interface.h b/src/core/internal_network/network_interface.h similarity index 100% rename from src/core/network/network_interface.h rename to src/core/internal_network/network_interface.h diff --git a/src/core/network/sockets.h b/src/core/internal_network/sockets.h similarity index 97% rename from src/core/network/sockets.h rename to src/core/internal_network/sockets.h index f889159f5f..77e27e9280 100644 --- a/src/core/network/sockets.h +++ b/src/core/internal_network/sockets.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include @@ -12,7 +13,7 @@ #endif #include "common/common_types.h" -#include "core/network/network.h" +#include "core/internal_network/network.h" // TODO: C++20 Replace std::vector usages with std::span diff --git a/src/network/room.cpp b/src/network/room.cpp index cd0c0ebc49..5288671469 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -251,7 +251,7 @@ public: void Room::RoomImpl::ServerLoop() { while (state != State::Closed) { ENetEvent event; - if (enet_host_service(server, &event, 50) > 0) { + if (enet_host_service(server, &event, 16) > 0) { switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: switch (event.packet->data[0]) { @@ -599,7 +599,7 @@ bool Room::RoomImpl::HasModPermission(const ENetPeer* client) const { if (sending_member == members.end()) { return false; } - if (room_information.enable_citra_mods && + if (room_information.enable_yuzu_mods && sending_member->user_data.moderator) { // Community moderator return true; @@ -1014,7 +1014,7 @@ bool Room::Create(const std::string& name, const std::string& description, const u32 max_connections, const std::string& host_username, const std::string& preferred_game, u64 preferred_game_id, std::unique_ptr verify_backend, - const Room::BanList& ban_list, bool enable_citra_mods) { + const Room::BanList& ban_list, bool enable_yuzu_mods) { ENetAddress address; address.host = ENET_HOST_ANY; if (!server_address.empty()) { @@ -1037,7 +1037,7 @@ bool Room::Create(const std::string& name, const std::string& description, room_impl->room_information.preferred_game = preferred_game; room_impl->room_information.preferred_game_id = preferred_game_id; room_impl->room_information.host_username = host_username; - room_impl->room_information.enable_citra_mods = enable_citra_mods; + room_impl->room_information.enable_yuzu_mods = enable_yuzu_mods; room_impl->password = password; room_impl->verify_backend = std::move(verify_backend); room_impl->username_ban_list = ban_list.first; diff --git a/src/network/room.h b/src/network/room.h index a679848370..5d4371c166 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -32,7 +32,7 @@ struct RoomInformation { std::string preferred_game; ///< Game to advertise that you want to play u64 preferred_game_id; ///< Title ID for the advertised game std::string host_username; ///< Forum username of the host - bool enable_citra_mods; ///< Allow Citra Moderators to moderate on this room + bool enable_yuzu_mods; ///< Allow yuzu Moderators to moderate on this room }; struct GameInfo { @@ -148,7 +148,7 @@ public: const std::string& host_username = "", const std::string& preferred_game = "", u64 preferred_game_id = 0, std::unique_ptr verify_backend = nullptr, - const BanList& ban_list = {}, bool enable_citra_mods = false); + const BanList& ban_list = {}, bool enable_yuzu_mods = false); /** * Sets the verification GUID of the room. diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index e430040271..d6ace9b39d 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -86,7 +86,7 @@ public: * @params password The password for the room * the server to assign one for us. */ - void SendJoinRequest(const std::string& nickname, const std::string& console_id_hash, + void SendJoinRequest(const std::string& nickname_, const std::string& console_id_hash, const MacAddress& preferred_mac = NoPreferredMac, const std::string& password = "", const std::string& token = ""); @@ -159,7 +159,7 @@ void RoomMember::RoomMemberImpl::MemberLoop() { while (IsConnected()) { std::lock_guard lock(network_mutex); ENetEvent event; - if (enet_host_service(client, &event, 100) > 0) { + if (enet_host_service(client, &event, 16) > 0) { switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: switch (event.packet->data[0]) { @@ -251,16 +251,17 @@ void RoomMember::RoomMemberImpl::MemberLoop() { break; } } + std::list packets; { - std::lock_guard lock(send_list_mutex); - for (const auto& packet : send_list) { - ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(), - ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(server, 0, enetPacket); - } - enet_host_flush(client); - send_list.clear(); + std::lock_guard send_lock(send_list_mutex); + packets.swap(send_list); } + for (const auto& packet : packets) { + ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(server, 0, enetPacket); + } + enet_host_flush(client); } Disconnect(); }; @@ -274,14 +275,14 @@ void RoomMember::RoomMemberImpl::Send(Packet&& packet) { send_list.push_back(std::move(packet)); } -void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname, +void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname_, const std::string& console_id_hash, const MacAddress& preferred_mac, const std::string& password, const std::string& token) { Packet packet; packet << static_cast(IdJoinRequest); - packet << nickname; + packet << nickname_; packet << console_id_hash; packet << preferred_mac; packet << network_version; diff --git a/src/network/verify_user.h b/src/network/verify_user.h index 01b9877c86..5c3852d4aa 100644 --- a/src/network/verify_user.h +++ b/src/network/verify_user.h @@ -13,7 +13,7 @@ struct UserData { std::string username; std::string display_name; std::string avatar_url; - bool moderator = false; ///< Whether the user is a Citra Moderator. + bool moderator = false; ///< Whether the user is a yuzu Moderator. }; /** diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index a69ccb2644..fbbcf673ac 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -7,7 +7,7 @@ add_executable(tests common/ring_buffer.cpp common/unique_function.cpp core/core_timing.cpp - core/network/network.cpp + core/internal_network/network.cpp tests.cpp video_core/buffer_base.cpp input_common/calibration_configuration_job.cpp diff --git a/src/tests/core/network/network.cpp b/src/tests/core/internal_network/network.cpp similarity index 90% rename from src/tests/core/network/network.cpp rename to src/tests/core/internal_network/network.cpp index 1bbb8372fb..164b0ff245 100644 --- a/src/tests/core/network/network.cpp +++ b/src/tests/core/internal_network/network.cpp @@ -3,8 +3,8 @@ #include -#include "core/network/network.h" -#include "core/network/sockets.h" +#include "core/internal_network/network.h" +#include "core/internal_network/sockets.h" TEST_CASE("Network::Errors", "[core]") { Network::NetworkInstance network_instance; // initialize network diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt index ae85a72ea0..aff81f26d8 100644 --- a/src/web_service/CMakeLists.txt +++ b/src/web_service/CMakeLists.txt @@ -1,4 +1,6 @@ add_library(web_service STATIC + announce_room_json.cpp + announce_room_json.h telemetry_json.cpp telemetry_json.h verify_login.cpp @@ -9,4 +11,4 @@ add_library(web_service STATIC ) create_target_directory_groups(web_service) -target_link_libraries(web_service PRIVATE common nlohmann_json::nlohmann_json httplib) +target_link_libraries(web_service PRIVATE common network nlohmann_json::nlohmann_json httplib) diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp new file mode 100644 index 0000000000..31804d2b1c --- /dev/null +++ b/src/web_service/announce_room_json.cpp @@ -0,0 +1,157 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include "common/detached_tasks.h" +#include "common/logging/log.h" +#include "web_service/announce_room_json.h" +#include "web_service/web_backend.h" + +namespace AnnounceMultiplayerRoom { + +void to_json(nlohmann::json& json, const Room::Member& member) { + if (!member.username.empty()) { + json["username"] = member.username; + } + json["nickname"] = member.nickname; + if (!member.avatar_url.empty()) { + json["avatarUrl"] = member.avatar_url; + } + json["gameName"] = member.game_name; + json["gameId"] = member.game_id; +} + +void from_json(const nlohmann::json& json, Room::Member& member) { + member.nickname = json.at("nickname").get(); + member.game_name = json.at("gameName").get(); + member.game_id = json.at("gameId").get(); + try { + member.username = json.at("username").get(); + member.avatar_url = json.at("avatarUrl").get(); + } catch (const nlohmann::detail::out_of_range&) { + member.username = member.avatar_url = ""; + LOG_DEBUG(Network, "Member \'{}\' isn't authenticated", member.nickname); + } +} + +void to_json(nlohmann::json& json, const Room& room) { + json["port"] = room.port; + json["name"] = room.name; + if (!room.description.empty()) { + json["description"] = room.description; + } + json["preferredGameName"] = room.preferred_game; + json["preferredGameId"] = room.preferred_game_id; + json["maxPlayers"] = room.max_player; + json["netVersion"] = room.net_version; + json["hasPassword"] = room.has_password; + if (room.members.size() > 0) { + nlohmann::json member_json = room.members; + json["players"] = member_json; + } +} + +void from_json(const nlohmann::json& json, Room& room) { + room.verify_UID = json.at("externalGuid").get(); + room.ip = json.at("address").get(); + room.name = json.at("name").get(); + try { + room.description = json.at("description").get(); + } catch (const nlohmann::detail::out_of_range&) { + room.description = ""; + LOG_DEBUG(Network, "Room \'{}\' doesn't contain a description", room.name); + } + room.owner = json.at("owner").get(); + room.port = json.at("port").get(); + room.preferred_game = json.at("preferredGameName").get(); + room.preferred_game_id = json.at("preferredGameId").get(); + room.max_player = json.at("maxPlayers").get(); + room.net_version = json.at("netVersion").get(); + room.has_password = json.at("hasPassword").get(); + try { + room.members = json.at("players").get>(); + } catch (const nlohmann::detail::out_of_range& e) { + LOG_DEBUG(Network, "Out of range {}", e.what()); + } +} + +} // namespace AnnounceMultiplayerRoom + +namespace WebService { + +void RoomJson::SetRoomInformation(const std::string& name, const std::string& description, + const u16 port, const u32 max_player, const u32 net_version, + const bool has_password, const std::string& preferred_game, + const u64 preferred_game_id) { + room.name = name; + room.description = description; + room.port = port; + room.max_player = max_player; + room.net_version = net_version; + room.has_password = has_password; + room.preferred_game = preferred_game; + room.preferred_game_id = preferred_game_id; +} +void RoomJson::AddPlayer(const std::string& username_, const std::string& nickname_, + const std::string& avatar_url, + const AnnounceMultiplayerRoom::MacAddress& mac_address, const u64 game_id, + const std::string& game_name) { + AnnounceMultiplayerRoom::Room::Member member; + member.username = username_; + member.nickname = nickname_; + member.avatar_url = avatar_url; + member.mac_address = mac_address; + member.game_id = game_id; + member.game_name = game_name; + room.members.push_back(member); +} + +WebService::WebResult RoomJson::Update() { + if (room_id.empty()) { + LOG_ERROR(WebService, "Room must be registered to be updated"); + return WebService::WebResult{WebService::WebResult::Code::LibError, + "Room is not registered"}; + } + nlohmann::json json{{"players", room.members}}; + return client.PostJson(fmt::format("/lobby/{}", room_id), json.dump(), false); +} + +WebService::WebResult RoomJson::Register() { + nlohmann::json json = room; + auto result = client.PostJson("/lobby", json.dump(), false); + if (result.result_code != WebService::WebResult::Code::Success) { + return result; + } + auto reply_json = nlohmann::json::parse(result.returned_data); + room = reply_json.get(); + room_id = reply_json.at("id").get(); + return WebService::WebResult{WebService::WebResult::Code::Success, "", room.verify_UID}; +} + +void RoomJson::ClearPlayers() { + room.members.clear(); +} + +AnnounceMultiplayerRoom::RoomList RoomJson::GetRoomList() { + auto reply = client.GetJson("/lobby", true).returned_data; + if (reply.empty()) { + return {}; + } + return nlohmann::json::parse(reply).at("rooms").get(); +} + +void RoomJson::Delete() { + if (room_id.empty()) { + LOG_ERROR(WebService, "Room must be registered to be deleted"); + return; + } + Common::DetachedTasks::AddTask( + [host{this->host}, username{this->username}, token{this->token}, room_id{this->room_id}]() { + // create a new client here because the this->client might be destroyed. + Client{host, username, token}.DeleteJson(fmt::format("/lobby/{}", room_id), "", false); + }); +} + +} // namespace WebService diff --git a/src/web_service/announce_room_json.h b/src/web_service/announce_room_json.h new file mode 100644 index 0000000000..ac02af5b17 --- /dev/null +++ b/src/web_service/announce_room_json.h @@ -0,0 +1,46 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include "common/announce_multiplayer_room.h" +#include "web_service/web_backend.h" + +namespace WebService { + +/** + * Implementation of AnnounceMultiplayerRoom::Backend that (de)serializes room information into/from + * JSON, and submits/gets it to/from the yuzu web service + */ +class RoomJson : public AnnounceMultiplayerRoom::Backend { +public: + RoomJson(const std::string& host, const std::string& username, const std::string& token) + : client(host, username, token), host(host), username(username), token(token) {} + ~RoomJson() = default; + void SetRoomInformation(const std::string& name, const std::string& description, const u16 port, + const u32 max_player, const u32 net_version, const bool has_password, + const std::string& preferred_game, + const u64 preferred_game_id) override; + void AddPlayer(const std::string& username_, const std::string& nickname_, + const std::string& avatar_url, + const AnnounceMultiplayerRoom::MacAddress& mac_address, const u64 game_id, + const std::string& game_name) override; + WebResult Update() override; + WebResult Register() override; + void ClearPlayers() override; + AnnounceMultiplayerRoom::RoomList GetRoomList() override; + void Delete() override; + +private: + AnnounceMultiplayerRoom::Room room; + Client client; + std::string host; + std::string username; + std::string token; + std::string room_id; +}; + +} // namespace WebService diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt index 57e0e70253..f3cad8f311 100644 --- a/src/yuzu/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -156,10 +156,36 @@ add_executable(yuzu main.cpp main.h main.ui + multiplayer/chat_room.cpp + multiplayer/chat_room.h + multiplayer/chat_room.ui + multiplayer/client_room.h + multiplayer/client_room.cpp + multiplayer/client_room.ui + multiplayer/direct_connect.cpp + multiplayer/direct_connect.h + multiplayer/direct_connect.ui + multiplayer/host_room.cpp + multiplayer/host_room.h + multiplayer/host_room.ui + multiplayer/lobby.cpp + multiplayer/lobby.h + multiplayer/lobby.ui + multiplayer/lobby_p.h + multiplayer/message.cpp + multiplayer/message.h + multiplayer/moderation_dialog.cpp + multiplayer/moderation_dialog.h + multiplayer/moderation_dialog.ui + multiplayer/state.cpp + multiplayer/state.h + multiplayer/validation.h startup_checks.cpp startup_checks.h uisettings.cpp uisettings.h + util/clickable_label.cpp + util/clickable_label.h util/controller_navigation.cpp util/controller_navigation.h util/limitable_input_dialog.cpp @@ -256,7 +282,7 @@ endif() create_target_directory_groups(yuzu) -target_link_libraries(yuzu PRIVATE common core input_common video_core) +target_link_libraries(yuzu PRIVATE common core input_common network video_core) target_link_libraries(yuzu PRIVATE Boost::boost glad Qt::Widgets Qt::Multimedia) target_link_libraries(yuzu PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp index c841843f00..7c11e2c034 100644 --- a/src/yuzu/configuration/config.cpp +++ b/src/yuzu/configuration/config.cpp @@ -11,6 +11,7 @@ #include "core/hle/service/acc/profile_manager.h" #include "core/hle/service/hid/controllers/npad.h" #include "input_common/main.h" +#include "network/network.h" #include "yuzu/configuration/config.h" namespace FS = Common::FS; @@ -584,6 +585,48 @@ void Config::ReadMiscellaneousValues() { qt_config->endGroup(); } +void Config::ReadMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + UISettings::values.nickname = ReadSetting(QStringLiteral("nickname"), QString{}).toString(); + UISettings::values.ip = ReadSetting(QStringLiteral("ip"), QString{}).toString(); + UISettings::values.port = + ReadSetting(QStringLiteral("port"), Network::DefaultRoomPort).toString(); + UISettings::values.room_nickname = + ReadSetting(QStringLiteral("room_nickname"), QString{}).toString(); + UISettings::values.room_name = ReadSetting(QStringLiteral("room_name"), QString{}).toString(); + UISettings::values.room_port = + ReadSetting(QStringLiteral("room_port"), QStringLiteral("24872")).toString(); + bool ok; + UISettings::values.host_type = ReadSetting(QStringLiteral("host_type"), 0).toUInt(&ok); + if (!ok) { + UISettings::values.host_type = 0; + } + UISettings::values.max_player = ReadSetting(QStringLiteral("max_player"), 8).toUInt(); + UISettings::values.game_id = ReadSetting(QStringLiteral("game_id"), 0).toULongLong(); + UISettings::values.room_description = + ReadSetting(QStringLiteral("room_description"), QString{}).toString(); + // Read ban list back + int size = qt_config->beginReadArray(QStringLiteral("username_ban_list")); + UISettings::values.ban_list.first.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.ban_list.first[i] = + ReadSetting(QStringLiteral("username")).toString().toStdString(); + } + qt_config->endArray(); + size = qt_config->beginReadArray(QStringLiteral("ip_ban_list")); + UISettings::values.ban_list.second.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.ban_list.second[i] = + ReadSetting(QStringLiteral("ip")).toString().toStdString(); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + void Config::ReadPathValues() { qt_config->beginGroup(QStringLiteral("Paths")); @@ -794,6 +837,7 @@ void Config::ReadUIValues() { ReadPathValues(); ReadScreenshotValues(); ReadShortcutValues(); + ReadMultiplayerValues(); ReadBasicSetting(UISettings::values.single_window_mode); ReadBasicSetting(UISettings::values.fullscreen); @@ -1161,6 +1205,40 @@ void Config::SaveMiscellaneousValues() { qt_config->endGroup(); } +void Config::SaveMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + WriteSetting(QStringLiteral("nickname"), UISettings::values.nickname, QString{}); + WriteSetting(QStringLiteral("ip"), UISettings::values.ip, QString{}); + WriteSetting(QStringLiteral("port"), UISettings::values.port, Network::DefaultRoomPort); + WriteSetting(QStringLiteral("room_nickname"), UISettings::values.room_nickname, QString{}); + WriteSetting(QStringLiteral("room_name"), UISettings::values.room_name, QString{}); + WriteSetting(QStringLiteral("room_port"), UISettings::values.room_port, + QStringLiteral("24872")); + WriteSetting(QStringLiteral("host_type"), UISettings::values.host_type, 0); + WriteSetting(QStringLiteral("max_player"), UISettings::values.max_player, 8); + WriteSetting(QStringLiteral("game_id"), UISettings::values.game_id, 0); + WriteSetting(QStringLiteral("room_description"), UISettings::values.room_description, + QString{}); + // Write ban list + qt_config->beginWriteArray(QStringLiteral("username_ban_list")); + for (std::size_t i = 0; i < UISettings::values.ban_list.first.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("username"), + QString::fromStdString(UISettings::values.ban_list.first[i])); + } + qt_config->endArray(); + qt_config->beginWriteArray(QStringLiteral("ip_ban_list")); + for (std::size_t i = 0; i < UISettings::values.ban_list.second.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("ip"), + QString::fromStdString(UISettings::values.ban_list.second[i])); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + void Config::SavePathValues() { qt_config->beginGroup(QStringLiteral("Paths")); @@ -1347,6 +1425,7 @@ void Config::SaveUIValues() { SavePathValues(); SaveScreenshotValues(); SaveShortcutValues(); + SaveMultiplayerValues(); WriteBasicSetting(UISettings::values.single_window_mode); WriteBasicSetting(UISettings::values.fullscreen); diff --git a/src/yuzu/configuration/config.h b/src/yuzu/configuration/config.h index a71eabe8ea..937b2d95bf 100644 --- a/src/yuzu/configuration/config.h +++ b/src/yuzu/configuration/config.h @@ -89,6 +89,7 @@ private: void ReadUIGamelistValues(); void ReadUILayoutValues(); void ReadWebServiceValues(); + void ReadMultiplayerValues(); void SaveValues(); void SavePlayerValue(std::size_t player_index); @@ -118,6 +119,7 @@ private: void SaveUIGamelistValues(); void SaveUILayoutValues(); void SaveWebServiceValues(); + void SaveMultiplayerValues(); /** * Reads a setting from the qt_config. diff --git a/src/yuzu/configuration/configure_dialog.cpp b/src/yuzu/configuration/configure_dialog.cpp index e99657bd6a..92ef4467bd 100644 --- a/src/yuzu/configuration/configure_dialog.cpp +++ b/src/yuzu/configuration/configure_dialog.cpp @@ -29,9 +29,10 @@ ConfigureDialog::ConfigureDialog(QWidget* parent, HotkeyRegistry& registry_, InputCommon::InputSubsystem* input_subsystem, - Core::System& system_) - : QDialog(parent), ui{std::make_unique()}, registry{registry_}, - system{system_}, audio_tab{std::make_unique(system_, this)}, + Core::System& system_, bool enable_web_config) + : QDialog(parent), ui{std::make_unique()}, + registry(registry_), system{system_}, audio_tab{std::make_unique(system_, + this)}, cpu_tab{std::make_unique(system_, this)}, debug_tab_tab{std::make_unique(system_, this)}, filesystem_tab{std::make_unique(this)}, @@ -64,6 +65,7 @@ ConfigureDialog::ConfigureDialog(QWidget* parent, HotkeyRegistry& registry_, ui->tabWidget->addTab(ui_tab.get(), tr("Game List")); ui->tabWidget->addTab(web_tab.get(), tr("Web")); + web_tab->SetWebServiceConfigEnabled(enable_web_config); hotkeys_tab->Populate(registry); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); diff --git a/src/yuzu/configuration/configure_dialog.h b/src/yuzu/configuration/configure_dialog.h index 12cf25daf2..cec1610ad6 100644 --- a/src/yuzu/configuration/configure_dialog.h +++ b/src/yuzu/configuration/configure_dialog.h @@ -41,7 +41,8 @@ class ConfigureDialog : public QDialog { public: explicit ConfigureDialog(QWidget* parent, HotkeyRegistry& registry_, - InputCommon::InputSubsystem* input_subsystem, Core::System& system_); + InputCommon::InputSubsystem* input_subsystem, Core::System& system_, + bool enable_web_config = true); ~ConfigureDialog() override; void ApplyConfiguration(); diff --git a/src/yuzu/configuration/configure_network.cpp b/src/yuzu/configuration/configure_network.cpp index 8ed08fa6a8..ba1986eb1b 100644 --- a/src/yuzu/configuration/configure_network.cpp +++ b/src/yuzu/configuration/configure_network.cpp @@ -4,7 +4,7 @@ #include #include "common/settings.h" #include "core/core.h" -#include "core/network/network_interface.h" +#include "core/internal_network/network_interface.h" #include "ui_configure_network.h" #include "yuzu/configuration/configure_network.h" diff --git a/src/yuzu/configuration/configure_web.cpp b/src/yuzu/configuration/configure_web.cpp index d779251b42..ff4bf44f44 100644 --- a/src/yuzu/configuration/configure_web.cpp +++ b/src/yuzu/configuration/configure_web.cpp @@ -169,3 +169,8 @@ void ConfigureWeb::OnLoginVerified() { "correctly, and that your internet connection is working.")); } } + +void ConfigureWeb::SetWebServiceConfigEnabled(bool enabled) { + ui->label_disable_info->setVisible(!enabled); + ui->groupBoxWebConfig->setEnabled(enabled); +} diff --git a/src/yuzu/configuration/configure_web.h b/src/yuzu/configuration/configure_web.h index 9054711ea3..041b511498 100644 --- a/src/yuzu/configuration/configure_web.h +++ b/src/yuzu/configuration/configure_web.h @@ -20,6 +20,7 @@ public: ~ConfigureWeb() override; void ApplyConfiguration(); + void SetWebServiceConfigEnabled(bool enabled); private: void changeEvent(QEvent* event) override; diff --git a/src/yuzu/configuration/configure_web.ui b/src/yuzu/configuration/configure_web.ui index 35b4274b0a..3ac3864bea 100644 --- a/src/yuzu/configuration/configure_web.ui +++ b/src/yuzu/configuration/configure_web.ui @@ -112,6 +112,16 @@ + + + + Web Service configuration can only be changed when a public room isn't being hosted. + + + true + + + diff --git a/src/yuzu/game_list.cpp b/src/yuzu/game_list.cpp index 05d309827f..5bcf582bf6 100644 --- a/src/yuzu/game_list.cpp +++ b/src/yuzu/game_list.cpp @@ -499,6 +499,8 @@ void GameList::DonePopulating(const QStringList& watch_list) { } item_model->sort(tree_view->header()->sortIndicatorSection(), tree_view->header()->sortIndicatorOrder()); + + emit PopulatingCompleted(); } void GameList::PopupContextMenu(const QPoint& menu_location) { @@ -752,6 +754,10 @@ void GameList::LoadCompatibilityList() { } } +QStandardItemModel* GameList::GetModel() const { + return item_model; +} + void GameList::PopulateAsync(QVector& game_dirs) { tree_view->setEnabled(false); diff --git a/src/yuzu/game_list.h b/src/yuzu/game_list.h index bc36d015a9..9605985cc1 100644 --- a/src/yuzu/game_list.h +++ b/src/yuzu/game_list.h @@ -16,9 +16,14 @@ #include #include "common/common_types.h" +#include "core/core.h" #include "uisettings.h" #include "yuzu/compatibility_list.h" +namespace Core { +class System; +} + class ControllerNavigation; class GameListWorker; class GameListSearchField; @@ -84,6 +89,8 @@ public: void SaveInterfaceLayout(); void LoadInterfaceLayout(); + QStandardItemModel* GetModel() const; + /// Disables events from the emulated controller void UnloadController(); @@ -108,6 +115,7 @@ signals: void OpenDirectory(const QString& directory); void AddDirectory(); void ShowList(bool show); + void PopulatingCompleted(); private slots: void OnItemExpanded(const QModelIndex& item); diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index 2814548eb9..5d81326739 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -32,6 +32,7 @@ #include "core/hle/service/am/applet_ae.h" #include "core/hle/service/am/applet_oe.h" #include "core/hle/service/am/applets/applets.h" +#include "yuzu/multiplayer/state.h" #include "yuzu/util/controller_navigation.h" // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows @@ -132,6 +133,7 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual #include "yuzu/main.h" #include "yuzu/startup_checks.h" #include "yuzu/uisettings.h" +#include "yuzu/util/clickable_label.h" using namespace Common::Literals; @@ -271,6 +273,8 @@ GMainWindow::GMainWindow(bool has_broken_vulkan) SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); discord_rpc->Update(); + Network::Init(); + RegisterMetaTypes(); InitializeWidgets(); @@ -459,6 +463,7 @@ GMainWindow::~GMainWindow() { if (render_window->parent() == nullptr) { delete render_window; } + Network::Shutdown(); } void GMainWindow::RegisterMetaTypes() { @@ -822,6 +827,10 @@ void GMainWindow::InitializeWidgets() { } }); + multiplayer_state = new MultiplayerState(this, game_list->GetModel(), ui->action_Leave_Room, + ui->action_Show_Room); + multiplayer_state->setVisible(false); + // Create status bar message_label = new QLabel(); // Configured separately for left alignment @@ -854,6 +863,9 @@ void GMainWindow::InitializeWidgets() { statusBar()->addPermanentWidget(label); } + statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0); + statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0); + tas_label = new QLabel(); tas_label->setObjectName(QStringLiteral("TASlabel")); tas_label->setFocusPolicy(Qt::NoFocus); @@ -1163,6 +1175,8 @@ void GMainWindow::ConnectWidgetEvents() { connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this, &GMainWindow::OnGameListAddDirectory); connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList); + connect(game_list, &GameList::PopulatingCompleted, + [this] { multiplayer_state->UpdateGameList(game_list->GetModel()); }); connect(game_list, &GameList::OpenPerGameGeneralRequested, this, &GMainWindow::OnGameListOpenPerGameProperties); @@ -1180,6 +1194,9 @@ void GMainWindow::ConnectWidgetEvents() { connect(this, &GMainWindow::EmulationStopping, this, &GMainWindow::SoftwareKeyboardExit); connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar); + + connect(this, &GMainWindow::UpdateThemedIcons, multiplayer_state, + &MultiplayerState::UpdateThemedIcons); } void GMainWindow::ConnectMenuEvents() { @@ -1223,6 +1240,18 @@ void GMainWindow::ConnectMenuEvents() { ui->action_Reset_Window_Size_900, ui->action_Reset_Window_Size_1080}); + // Multiplayer + connect(ui->action_View_Lobby, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnViewLobby); + connect(ui->action_Start_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnCreateRoom); + connect(ui->action_Leave_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnCloseRoom); + connect(ui->action_Connect_To_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnDirectConnectToRoom); + connect(ui->action_Show_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnOpenNetworkRoom); + // Tools connect_menu(ui->action_Rederive, std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning)); @@ -2783,7 +2812,8 @@ void GMainWindow::OnConfigure() { const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue(); Settings::SetConfiguringGlobal(true); - ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), *system); + ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), *system, + !multiplayer_state->IsHostingPublicRoom()); connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this, &GMainWindow::OnLanguageChanged); @@ -2840,6 +2870,11 @@ void GMainWindow::OnConfigure() { if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) { SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); } + + if (!multiplayer_state->IsHostingPublicRoom()) { + multiplayer_state->UpdateCredentials(); + } + emit UpdateThemedIcons(); const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false); @@ -3660,6 +3695,7 @@ void GMainWindow::closeEvent(QCloseEvent* event) { } render_window->close(); + multiplayer_state->Close(); QWidget::closeEvent(event); } @@ -3856,6 +3892,7 @@ void GMainWindow::OnLanguageChanged(const QString& locale) { UISettings::values.language = locale; LoadTranslation(); ui->retranslateUi(this); + multiplayer_state->retranslateUi(); UpdateWindowTitle(); } diff --git a/src/yuzu/main.h b/src/yuzu/main.h index 27204f5a2c..8d5c1398f0 100644 --- a/src/yuzu/main.h +++ b/src/yuzu/main.h @@ -11,6 +11,7 @@ #include #include +#include "common/announce_multiplayer_room.h" #include "common/common_types.h" #include "yuzu/compatibility_list.h" #include "yuzu/hotkeys.h" @@ -22,6 +23,7 @@ #endif class Config; +class ClickableLabel; class EmuThread; class GameList; class GImageInfo; @@ -31,6 +33,7 @@ class MicroProfileDialog; class ProfilerWidget; class ControllerDialog; class QLabel; +class MultiplayerState; class QPushButton; class QProgressDialog; class WaitTreeWidget; @@ -200,6 +203,8 @@ private: void ConnectMenuEvents(); void UpdateMenuState(); + MultiplayerState* multiplayer_state = nullptr; + void PreventOSSleep(); void AllowOSSleep(); diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui index 6ab95b9a5d..60a8deab1c 100644 --- a/src/yuzu/main.ui +++ b/src/yuzu/main.ui @@ -120,6 +120,20 @@ + + + true + + + Multiplayer + + + + + + + + &Tools @@ -154,6 +168,7 @@ + @@ -245,6 +260,43 @@ Show Status Bar + + + true + + + Browse Public Game Lobby + + + + + true + + + Create Room + + + + + false + + + Leave Room + + + + + Direct Connect to Room + + + + + false + + + Show Current Room + + true diff --git a/src/yuzu/multiplayer/chat_room.cpp b/src/yuzu/multiplayer/chat_room.cpp new file mode 100644 index 0000000000..6dd4bc36d6 --- /dev/null +++ b/src/yuzu/multiplayer/chat_room.cpp @@ -0,0 +1,490 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "core/announce_multiplayer_session.h" +#include "ui_chat_room.h" +#include "yuzu/game_list_p.h" +#include "yuzu/multiplayer/chat_room.h" +#include "yuzu/multiplayer/message.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/web_backend.h" +#endif + +class ChatMessage { +public: + explicit ChatMessage(const Network::ChatEntry& chat, QTime ts = {}) { + /// Convert the time to their default locale defined format + QLocale locale; + timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat); + nickname = QString::fromStdString(chat.nickname); + username = QString::fromStdString(chat.username); + message = QString::fromStdString(chat.message); + + // Check for user pings + QString cur_nickname, cur_username; + if (auto room = Network::GetRoomMember().lock()) { + cur_nickname = QString::fromStdString(room->GetNickname()); + cur_username = QString::fromStdString(room->GetUsername()); + } + + // Handle pings at the beginning and end of message + QString fixed_message = QStringLiteral(" %1 ").arg(message); + if (fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_nickname)) || + (!cur_username.isEmpty() && + fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_username)))) { + + contains_ping = true; + } else { + contains_ping = false; + } + } + + bool ContainsPing() const { + return contains_ping; + } + + /// Format the message using the players color + QString GetPlayerChatMessage(u16 player) const { + auto color = player_color[player % 16]; + QString name; + if (username.isEmpty() || username == nickname) { + name = nickname; + } else { + name = QStringLiteral("%1 (%2)").arg(nickname, username); + } + + QString style, text_color; + if (ContainsPing()) { + // Add a background color to these messages + style = QStringLiteral("background-color: %1").arg(QString::fromStdString(ping_color)); + // Add a font color + text_color = QStringLiteral("color='#000000'"); + } + + return QStringLiteral("[%1] <%3> %6") + .arg(timestamp, QString::fromStdString(color), name.toHtmlEscaped(), style, text_color, + message.toHtmlEscaped()); + } + +private: + static constexpr std::array player_color = { + {"#0000FF", "#FF0000", "#8A2BE2", "#FF69B4", "#1E90FF", "#008000", "#00FF7F", "#B22222", + "#DAA520", "#FF4500", "#2E8B57", "#5F9EA0", "#D2691E", "#9ACD32", "#FF7F50", "FFFF00"}}; + static constexpr char ping_color[] = "#FFFF00"; + + QString timestamp; + QString nickname; + QString username; + QString message; + bool contains_ping; +}; + +class StatusMessage { +public: + explicit StatusMessage(const QString& msg, QTime ts = {}) { + /// Convert the time to their default locale defined format + QLocale locale; + timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat); + message = msg; + } + + QString GetSystemChatMessage() const { + return QStringLiteral("[%1] * %3") + .arg(timestamp, QString::fromStdString(system_color), message); + } + +private: + static constexpr const char system_color[] = "#FF8C00"; + QString timestamp; + QString message; +}; + +class PlayerListItem : public QStandardItem { +public: + static const int NicknameRole = Qt::UserRole + 1; + static const int UsernameRole = Qt::UserRole + 2; + static const int AvatarUrlRole = Qt::UserRole + 3; + static const int GameNameRole = Qt::UserRole + 4; + + PlayerListItem() = default; + explicit PlayerListItem(const std::string& nickname, const std::string& username, + const std::string& avatar_url, const std::string& game_name) { + setEditable(false); + setData(QString::fromStdString(nickname), NicknameRole); + setData(QString::fromStdString(username), UsernameRole); + setData(QString::fromStdString(avatar_url), AvatarUrlRole); + if (game_name.empty()) { + setData(QObject::tr("Not playing a game"), GameNameRole); + } else { + setData(QString::fromStdString(game_name), GameNameRole); + } + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return QStandardItem::data(role); + } + QString name; + const QString nickname = data(NicknameRole).toString(); + const QString username = data(UsernameRole).toString(); + if (username.isEmpty() || username == nickname) { + name = nickname; + } else { + name = QStringLiteral("%1 (%2)").arg(nickname, username); + } + return QStringLiteral("%1\n %2").arg(name, data(GameNameRole).toString()); + } +}; + +ChatRoom::ChatRoom(QWidget* parent) : QWidget(parent), ui(std::make_unique()) { + ui->setupUi(this); + + // set the item_model for player_view + + player_list = new QStandardItemModel(ui->player_view); + ui->player_view->setModel(player_list); + ui->player_view->setContextMenuPolicy(Qt::CustomContextMenu); + // set a header to make it look better though there is only one column + player_list->insertColumns(0, 1); + player_list->setHeaderData(0, Qt::Horizontal, tr("Members")); + + ui->chat_history->document()->setMaximumBlockCount(max_chat_lines); + + // register the network structs to use in slots and signals + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + + // setup the callbacks for network updates + if (auto member = Network::GetRoomMember().lock()) { + member->BindOnChatMessageRecieved( + [this](const Network::ChatEntry& chat) { emit ChatReceived(chat); }); + member->BindOnStatusMessageReceived( + [this](const Network::StatusMessageEntry& status_message) { + emit StatusMessageReceived(status_message); + }); + connect(this, &ChatRoom::ChatReceived, this, &ChatRoom::OnChatReceive); + connect(this, &ChatRoom::StatusMessageReceived, this, &ChatRoom::OnStatusMessageReceive); + } else { + // TODO (jroweboy) network was not initialized? + } + + // Connect all the widgets to the appropriate events + connect(ui->player_view, &QTreeView::customContextMenuRequested, this, + &ChatRoom::PopupContextMenu); + connect(ui->chat_message, &QLineEdit::returnPressed, this, &ChatRoom::OnSendChat); + connect(ui->chat_message, &QLineEdit::textChanged, this, &ChatRoom::OnChatTextChanged); + connect(ui->send_message, &QPushButton::clicked, this, &ChatRoom::OnSendChat); +} + +ChatRoom::~ChatRoom() = default; + +void ChatRoom::SetModPerms(bool is_mod) { + has_mod_perms = is_mod; +} + +void ChatRoom::RetranslateUi() { + ui->retranslateUi(this); +} + +void ChatRoom::Clear() { + ui->chat_history->clear(); + block_list.clear(); +} + +void ChatRoom::AppendStatusMessage(const QString& msg) { + ui->chat_history->append(StatusMessage(msg).GetSystemChatMessage()); +} + +void ChatRoom::AppendChatMessage(const QString& msg) { + ui->chat_history->append(msg); +} + +void ChatRoom::SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname) { + if (auto room = Network::GetRoomMember().lock()) { + auto members = room->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&nickname](const Network::RoomMember::MemberInformation& member) { + return member.nickname == nickname; + }); + if (it == members.end()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::NO_SUCH_USER); + return; + } + room->SendModerationRequest(type, nickname); + } +} + +bool ChatRoom::ValidateMessage(const std::string& msg) { + return !msg.empty(); +} + +void ChatRoom::OnRoomUpdate(const Network::RoomInformation& info) { + // TODO(B3N30): change title + if (auto room_member = Network::GetRoomMember().lock()) { + SetPlayerList(room_member->GetMemberInformation()); + } +} + +void ChatRoom::Disable() { + ui->send_message->setDisabled(true); + ui->chat_message->setDisabled(true); +} + +void ChatRoom::Enable() { + ui->send_message->setEnabled(true); + ui->chat_message->setEnabled(true); +} + +void ChatRoom::OnChatReceive(const Network::ChatEntry& chat) { + if (!ValidateMessage(chat.message)) { + return; + } + if (auto room = Network::GetRoomMember().lock()) { + // get the id of the player + auto members = room->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&chat](const Network::RoomMember::MemberInformation& member) { + return member.nickname == chat.nickname && + member.username == chat.username; + }); + if (it == members.end()) { + LOG_INFO(Network, "Chat message received from unknown player. Ignoring it."); + return; + } + if (block_list.count(chat.nickname)) { + LOG_INFO(Network, "Chat message received from blocked player {}. Ignoring it.", + chat.nickname); + return; + } + auto player = std::distance(members.begin(), it); + ChatMessage m(chat); + if (m.ContainsPing()) { + emit UserPinged(); + } + AppendChatMessage(m.GetPlayerChatMessage(player)); + } +} + +void ChatRoom::OnStatusMessageReceive(const Network::StatusMessageEntry& status_message) { + QString name; + if (status_message.username.empty() || status_message.username == status_message.nickname) { + name = QString::fromStdString(status_message.nickname); + } else { + name = QStringLiteral("%1 (%2)").arg(QString::fromStdString(status_message.nickname), + QString::fromStdString(status_message.username)); + } + QString message; + switch (status_message.type) { + case Network::IdMemberJoin: + message = tr("%1 has joined").arg(name); + break; + case Network::IdMemberLeave: + message = tr("%1 has left").arg(name); + break; + case Network::IdMemberKicked: + message = tr("%1 has been kicked").arg(name); + break; + case Network::IdMemberBanned: + message = tr("%1 has been banned").arg(name); + break; + case Network::IdAddressUnbanned: + message = tr("%1 has been unbanned").arg(name); + break; + } + if (!message.isEmpty()) + AppendStatusMessage(message); +} + +void ChatRoom::OnSendChat() { + if (auto room = Network::GetRoomMember().lock()) { + if (room->GetState() != Network::RoomMember::State::Joined && + room->GetState() != Network::RoomMember::State::Moderator) { + + return; + } + auto message = ui->chat_message->text().toStdString(); + if (!ValidateMessage(message)) { + return; + } + auto nick = room->GetNickname(); + auto username = room->GetUsername(); + Network::ChatEntry chat{nick, username, message}; + + auto members = room->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&chat](const Network::RoomMember::MemberInformation& member) { + return member.nickname == chat.nickname && + member.username == chat.username; + }); + if (it == members.end()) { + LOG_INFO(Network, "Cannot find self in the player list when sending a message."); + } + auto player = std::distance(members.begin(), it); + ChatMessage m(chat); + room->SendChatMessage(message); + AppendChatMessage(m.GetPlayerChatMessage(player)); + ui->chat_message->clear(); + } +} + +void ChatRoom::UpdateIconDisplay() { + for (int row = 0; row < player_list->invisibleRootItem()->rowCount(); ++row) { + QStandardItem* item = player_list->invisibleRootItem()->child(row); + const std::string avatar_url = + item->data(PlayerListItem::AvatarUrlRole).toString().toStdString(); + if (icon_cache.count(avatar_url)) { + item->setData(icon_cache.at(avatar_url), Qt::DecorationRole); + } else { + item->setData(QIcon::fromTheme(QStringLiteral("no_avatar")).pixmap(48), + Qt::DecorationRole); + } + } +} + +void ChatRoom::SetPlayerList(const Network::RoomMember::MemberList& member_list) { + // TODO(B3N30): Remember which row is selected + player_list->removeRows(0, player_list->rowCount()); + for (const auto& member : member_list) { + if (member.nickname.empty()) + continue; + QStandardItem* name_item = new PlayerListItem(member.nickname, member.username, + member.avatar_url, member.game_info.name); + +#ifdef ENABLE_WEB_SERVICE + if (!icon_cache.count(member.avatar_url) && !member.avatar_url.empty()) { + // Start a request to get the member's avatar + const QUrl url(QString::fromStdString(member.avatar_url)); + QFuture future = QtConcurrent::run([url] { + WebService::Client client( + QStringLiteral("%1://%2").arg(url.scheme(), url.host()).toStdString(), "", ""); + auto result = client.GetImage(url.path().toStdString(), true); + if (result.returned_data.empty()) { + LOG_ERROR(WebService, "Failed to get avatar"); + } + return result.returned_data; + }); + auto* future_watcher = new QFutureWatcher(this); + connect(future_watcher, &QFutureWatcher::finished, this, + [this, future_watcher, avatar_url = member.avatar_url] { + const std::string result = future_watcher->result(); + if (result.empty()) + return; + QPixmap pixmap; + if (!pixmap.loadFromData(reinterpret_cast(result.data()), + result.size())) + return; + icon_cache[avatar_url] = + pixmap.scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + // Update all the displayed icons with the new icon_cache + UpdateIconDisplay(); + }); + future_watcher->setFuture(future); + } +#endif + + player_list->invisibleRootItem()->appendRow(name_item); + } + UpdateIconDisplay(); + // TODO(B3N30): Restore row selection +} + +void ChatRoom::OnChatTextChanged() { + if (ui->chat_message->text().length() > static_cast(Network::MaxMessageSize)) + ui->chat_message->setText( + ui->chat_message->text().left(static_cast(Network::MaxMessageSize))); +} + +void ChatRoom::PopupContextMenu(const QPoint& menu_location) { + QModelIndex item = ui->player_view->indexAt(menu_location); + if (!item.isValid()) + return; + + std::string nickname = + player_list->item(item.row())->data(PlayerListItem::NicknameRole).toString().toStdString(); + + QMenu context_menu; + + QString username = player_list->item(item.row())->data(PlayerListItem::UsernameRole).toString(); + if (!username.isEmpty()) { + QAction* view_profile_action = context_menu.addAction(tr("View Profile")); + connect(view_profile_action, &QAction::triggered, [username] { + QDesktopServices::openUrl( + QUrl(QStringLiteral("https://community.citra-emu.org/u/%1").arg(username))); + }); + } + + std::string cur_nickname; + if (auto room = Network::GetRoomMember().lock()) { + cur_nickname = room->GetNickname(); + } + + if (nickname != cur_nickname) { // You can't block yourself + QAction* block_action = context_menu.addAction(tr("Block Player")); + + block_action->setCheckable(true); + block_action->setChecked(block_list.count(nickname) > 0); + + connect(block_action, &QAction::triggered, [this, nickname] { + if (block_list.count(nickname)) { + block_list.erase(nickname); + } else { + QMessageBox::StandardButton result = QMessageBox::question( + this, tr("Block Player"), + tr("When you block a player, you will no longer receive chat messages from " + "them.

Are you sure you would like to block %1?") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + block_list.emplace(nickname); + } + }); + } + + if (has_mod_perms && nickname != cur_nickname) { // You can't kick or ban yourself + context_menu.addSeparator(); + + QAction* kick_action = context_menu.addAction(tr("Kick")); + QAction* ban_action = context_menu.addAction(tr("Ban")); + + connect(kick_action, &QAction::triggered, [this, nickname] { + QMessageBox::StandardButton result = + QMessageBox::question(this, tr("Kick Player"), + tr("Are you sure you would like to kick %1?") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + SendModerationRequest(Network::IdModKick, nickname); + }); + connect(ban_action, &QAction::triggered, [this, nickname] { + QMessageBox::StandardButton result = QMessageBox::question( + this, tr("Ban Player"), + tr("Are you sure you would like to kick and ban %1?\n\nThis would " + "ban both their forum username and their IP address.") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + SendModerationRequest(Network::IdModBan, nickname); + }); + } + + context_menu.exec(ui->player_view->viewport()->mapToGlobal(menu_location)); +} diff --git a/src/yuzu/multiplayer/chat_room.h b/src/yuzu/multiplayer/chat_room.h new file mode 100644 index 0000000000..a810377f7a --- /dev/null +++ b/src/yuzu/multiplayer/chat_room.h @@ -0,0 +1,74 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "network/network.h" + +namespace Ui { +class ChatRoom; +} + +namespace Core { +class AnnounceMultiplayerSession; +} + +class ConnectionError; +class ComboBoxProxyModel; + +class ChatMessage; + +class ChatRoom : public QWidget { + Q_OBJECT + +public: + explicit ChatRoom(QWidget* parent); + void RetranslateUi(); + void SetPlayerList(const Network::RoomMember::MemberList& member_list); + void Clear(); + void AppendStatusMessage(const QString& msg); + ~ChatRoom(); + + void SetModPerms(bool is_mod); + void UpdateIconDisplay(); + +public slots: + void OnRoomUpdate(const Network::RoomInformation& info); + void OnChatReceive(const Network::ChatEntry&); + void OnStatusMessageReceive(const Network::StatusMessageEntry&); + void OnSendChat(); + void OnChatTextChanged(); + void PopupContextMenu(const QPoint& menu_location); + void Disable(); + void Enable(); + +signals: + void ChatReceived(const Network::ChatEntry&); + void StatusMessageReceived(const Network::StatusMessageEntry&); + void UserPinged(); + +private: + static constexpr u32 max_chat_lines = 1000; + void AppendChatMessage(const QString&); + bool ValidateMessage(const std::string&); + void SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname); + + bool has_mod_perms = false; + QStandardItemModel* player_list; + std::unique_ptr ui; + std::unordered_set block_list; + std::unordered_map icon_cache; +}; + +Q_DECLARE_METATYPE(Network::ChatEntry); +Q_DECLARE_METATYPE(Network::StatusMessageEntry); +Q_DECLARE_METATYPE(Network::RoomInformation); +Q_DECLARE_METATYPE(Network::RoomMember::State); +Q_DECLARE_METATYPE(Network::RoomMember::Error); diff --git a/src/yuzu/multiplayer/chat_room.ui b/src/yuzu/multiplayer/chat_room.ui new file mode 100644 index 0000000000..f2b31b5da1 --- /dev/null +++ b/src/yuzu/multiplayer/chat_room.ui @@ -0,0 +1,59 @@ + + + ChatRoom + + + + 0 + 0 + 807 + 432 + + + + Room Window + + + + + + + + + + + false + + + true + + + Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + + + + + + + Send Chat Message + + + + + + + Send Message + + + + + + + + + + + + diff --git a/src/yuzu/multiplayer/client_room.cpp b/src/yuzu/multiplayer/client_room.cpp new file mode 100644 index 0000000000..7b2e16e06e --- /dev/null +++ b/src/yuzu/multiplayer/client_room.cpp @@ -0,0 +1,115 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "core/announce_multiplayer_session.h" +#include "ui_client_room.h" +#include "yuzu/game_list_p.h" +#include "yuzu/multiplayer/client_room.h" +#include "yuzu/multiplayer/message.h" +#include "yuzu/multiplayer/moderation_dialog.h" +#include "yuzu/multiplayer/state.h" + +ClientRoomWindow::ClientRoomWindow(QWidget* parent) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()) { + ui->setupUi(this); + + // setup the callbacks for network updates + if (auto member = Network::GetRoomMember().lock()) { + member->BindOnRoomInformationChanged( + [this](const Network::RoomInformation& info) { emit RoomInformationChanged(info); }); + member->BindOnStateChanged( + [this](const Network::RoomMember::State& state) { emit StateChanged(state); }); + + connect(this, &ClientRoomWindow::RoomInformationChanged, this, + &ClientRoomWindow::OnRoomUpdate); + connect(this, &ClientRoomWindow::StateChanged, this, &::ClientRoomWindow::OnStateChange); + // Update the state + OnStateChange(member->GetState()); + } else { + // TODO (jroweboy) network was not initialized? + } + + connect(ui->disconnect, &QPushButton::clicked, this, &ClientRoomWindow::Disconnect); + ui->disconnect->setDefault(false); + ui->disconnect->setAutoDefault(false); + connect(ui->moderation, &QPushButton::clicked, [this] { + ModerationDialog dialog(this); + dialog.exec(); + }); + ui->moderation->setDefault(false); + ui->moderation->setAutoDefault(false); + connect(ui->chat, &ChatRoom::UserPinged, this, &ClientRoomWindow::ShowNotification); + UpdateView(); +} + +ClientRoomWindow::~ClientRoomWindow() = default; + +void ClientRoomWindow::SetModPerms(bool is_mod) { + ui->chat->SetModPerms(is_mod); + ui->moderation->setVisible(is_mod); + ui->moderation->setDefault(false); + ui->moderation->setAutoDefault(false); +} + +void ClientRoomWindow::RetranslateUi() { + ui->retranslateUi(this); + ui->chat->RetranslateUi(); +} + +void ClientRoomWindow::OnRoomUpdate(const Network::RoomInformation& info) { + UpdateView(); +} + +void ClientRoomWindow::OnStateChange(const Network::RoomMember::State& state) { + if (state == Network::RoomMember::State::Joined || + state == Network::RoomMember::State::Moderator) { + + ui->chat->Clear(); + ui->chat->AppendStatusMessage(tr("Connected")); + SetModPerms(state == Network::RoomMember::State::Moderator); + } + UpdateView(); +} + +void ClientRoomWindow::Disconnect() { + auto parent = static_cast(parentWidget()); + if (parent->OnCloseRoom()) { + ui->chat->AppendStatusMessage(tr("Disconnected")); + close(); + } +} + +void ClientRoomWindow::UpdateView() { + if (auto member = Network::GetRoomMember().lock()) { + if (member->IsConnected()) { + ui->chat->Enable(); + ui->disconnect->setEnabled(true); + auto memberlist = member->GetMemberInformation(); + ui->chat->SetPlayerList(memberlist); + const auto information = member->GetRoomInformation(); + setWindowTitle(QString(tr("%1 (%2/%3 members) - connected")) + .arg(QString::fromStdString(information.name)) + .arg(memberlist.size()) + .arg(information.member_slots)); + ui->description->setText(QString::fromStdString(information.description)); + return; + } + } + // TODO(B3N30): can't get RoomMember*, show error and close window + close(); +} + +void ClientRoomWindow::UpdateIconDisplay() { + ui->chat->UpdateIconDisplay(); +} diff --git a/src/yuzu/multiplayer/client_room.h b/src/yuzu/multiplayer/client_room.h new file mode 100644 index 0000000000..607b4073d0 --- /dev/null +++ b/src/yuzu/multiplayer/client_room.h @@ -0,0 +1,39 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "yuzu/multiplayer/chat_room.h" + +namespace Ui { +class ClientRoom; +} + +class ClientRoomWindow : public QDialog { + Q_OBJECT + +public: + explicit ClientRoomWindow(QWidget* parent); + ~ClientRoomWindow(); + + void RetranslateUi(); + void UpdateIconDisplay(); + +public slots: + void OnRoomUpdate(const Network::RoomInformation&); + void OnStateChange(const Network::RoomMember::State&); + +signals: + void RoomInformationChanged(const Network::RoomInformation&); + void StateChanged(const Network::RoomMember::State&); + void ShowNotification(); + +private: + void Disconnect(); + void UpdateView(); + void SetModPerms(bool is_mod); + + QStandardItemModel* player_list; + std::unique_ptr ui; +}; diff --git a/src/yuzu/multiplayer/client_room.ui b/src/yuzu/multiplayer/client_room.ui new file mode 100644 index 0000000000..97e88b502d --- /dev/null +++ b/src/yuzu/multiplayer/client_room.ui @@ -0,0 +1,80 @@ + + + ClientRoom + + + + 0 + 0 + 807 + 432 + + + + Room Window + + + + + + + + 0 + + + + + Room Description + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Moderation... + + + false + + + + + + + Leave Room + + + + + + + + + + + + + + + ChatRoom + QWidget +
multiplayer/chat_room.h
+ 1 +
+
+ + +
diff --git a/src/yuzu/multiplayer/direct_connect.cpp b/src/yuzu/multiplayer/direct_connect.cpp new file mode 100644 index 0000000000..27741d657f --- /dev/null +++ b/src/yuzu/multiplayer/direct_connect.cpp @@ -0,0 +1,129 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include +#include "common/settings.h" +#include "network/network.h" +#include "ui_direct_connect.h" +#include "yuzu/main.h" +#include "yuzu/multiplayer/client_room.h" +#include "yuzu/multiplayer/direct_connect.h" +#include "yuzu/multiplayer/message.h" +#include "yuzu/multiplayer/state.h" +#include "yuzu/multiplayer/validation.h" +#include "yuzu/uisettings.h" + +enum class ConnectionType : u8 { TraversalServer, IP }; + +DirectConnectWindow::DirectConnectWindow(QWidget* parent) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()) { + + ui->setupUi(this); + + // setup the watcher for background connections + watcher = new QFutureWatcher; + connect(watcher, &QFutureWatcher::finished, this, &DirectConnectWindow::OnConnection); + + ui->nickname->setValidator(validation.GetNickname()); + ui->nickname->setText(UISettings::values.nickname); + if (ui->nickname->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { + // Use yuzu Web Service user name as nickname by default + ui->nickname->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); + } + ui->ip->setValidator(validation.GetIP()); + ui->ip->setText(UISettings::values.ip); + ui->port->setValidator(validation.GetPort()); + ui->port->setText(UISettings::values.port); + + // TODO(jroweboy): Show or hide the connection options based on the current value of the combo + // box. Add this back in when the traversal server support is added. + connect(ui->connect, &QPushButton::clicked, this, &DirectConnectWindow::Connect); +} + +DirectConnectWindow::~DirectConnectWindow() = default; + +void DirectConnectWindow::RetranslateUi() { + ui->retranslateUi(this); +} + +void DirectConnectWindow::Connect() { + if (!ui->nickname->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + if (const auto member = Network::GetRoomMember().lock()) { + // Prevent the user from trying to join a room while they are already joining. + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + // And ask if they want to leave the room if they are already in one. + if (!NetworkMessage::WarnDisconnect()) { + return; + } + } + } + switch (static_cast(ui->connection_type->currentIndex())) { + case ConnectionType::TraversalServer: + break; + case ConnectionType::IP: + if (!ui->ip->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::IP_ADDRESS_NOT_VALID); + return; + } + if (!ui->port->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID); + return; + } + break; + } + + // Store settings + UISettings::values.nickname = ui->nickname->text(); + UISettings::values.ip = ui->ip->text(); + UISettings::values.port = (ui->port->isModified() && !ui->port->text().isEmpty()) + ? ui->port->text() + : UISettings::values.port; + + // attempt to connect in a different thread + QFuture f = QtConcurrent::run([&] { + if (auto room_member = Network::GetRoomMember().lock()) { + auto port = UISettings::values.port.toUInt(); + room_member->Join(ui->nickname->text().toStdString(), "", + ui->ip->text().toStdString().c_str(), port, 0, + Network::NoPreferredMac, ui->password->text().toStdString().c_str()); + } + }); + watcher->setFuture(f); + // and disable widgets and display a connecting while we wait + BeginConnecting(); +} + +void DirectConnectWindow::BeginConnecting() { + ui->connect->setEnabled(false); + ui->connect->setText(tr("Connecting")); +} + +void DirectConnectWindow::EndConnecting() { + ui->connect->setEnabled(true); + ui->connect->setText(tr("Connect")); +} + +void DirectConnectWindow::OnConnection() { + EndConnecting(); + + if (auto room_member = Network::GetRoomMember().lock()) { + if (room_member->GetState() == Network::RoomMember::State::Joined || + room_member->GetState() == Network::RoomMember::State::Moderator) { + + close(); + } + } +} diff --git a/src/yuzu/multiplayer/direct_connect.h b/src/yuzu/multiplayer/direct_connect.h new file mode 100644 index 0000000000..e38961ed04 --- /dev/null +++ b/src/yuzu/multiplayer/direct_connect.h @@ -0,0 +1,43 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include "yuzu/multiplayer/validation.h" + +namespace Ui { +class DirectConnect; +} + +class DirectConnectWindow : public QDialog { + Q_OBJECT + +public: + explicit DirectConnectWindow(QWidget* parent = nullptr); + ~DirectConnectWindow(); + + void RetranslateUi(); + +signals: + /** + * Signalled by this widget when it is closing itself and destroying any state such as + * connections that it might have. + */ + void Closed(); + +private slots: + void OnConnection(); + +private: + void Connect(); + void BeginConnecting(); + void EndConnecting(); + + QFutureWatcher* watcher; + std::unique_ptr ui; + Validation validation; +}; diff --git a/src/yuzu/multiplayer/direct_connect.ui b/src/yuzu/multiplayer/direct_connect.ui new file mode 100644 index 0000000000..681b6bf69d --- /dev/null +++ b/src/yuzu/multiplayer/direct_connect.ui @@ -0,0 +1,168 @@ + + + DirectConnect + + + + 0 + 0 + 455 + 161 + + + + Direct Connect + + + + + + + + + + 0 + + + 0 + + + + + + IP Address + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + + + IP + + + + + + + <html><head/><body><p>IPv4 address of the host</p></body></html> + + + 16 + + + + + + + Port + + + + + + + <html><head/><body><p>Port number the host is listening on</p></body></html> + + + 5 + + + 24872 + + + + + + + + + + + + + + Nickname + + + + + + + 20 + + + + + + + Password + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 20 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Connect + + + + + + + + + + + + diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp new file mode 100644 index 0000000000..1b73e2bec5 --- /dev/null +++ b/src/yuzu/multiplayer/host_room.cpp @@ -0,0 +1,237 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "common/settings.h" +#include "core/announce_multiplayer_session.h" +#include "ui_host_room.h" +#include "yuzu/game_list_p.h" +#include "yuzu/main.h" +#include "yuzu/multiplayer/host_room.h" +#include "yuzu/multiplayer/message.h" +#include "yuzu/multiplayer/state.h" +#include "yuzu/multiplayer/validation.h" +#include "yuzu/uisettings.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/verify_user_jwt.h" +#endif + +HostRoomWindow::HostRoomWindow(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), announce_multiplayer_session(session) { + ui->setupUi(this); + + // set up validation for all of the fields + ui->room_name->setValidator(validation.GetRoomName()); + ui->username->setValidator(validation.GetNickname()); + ui->port->setValidator(validation.GetPort()); + ui->port->setPlaceholderText(QString::number(Network::DefaultRoomPort)); + + // Create a proxy to the game list to display the list of preferred games + game_list = new QStandardItemModel; + UpdateGameList(list); + + proxy = new ComboBoxProxyModel; + proxy->setSourceModel(game_list); + proxy->sort(0, Qt::AscendingOrder); + ui->game_list->setModel(proxy); + + // Connect all the widgets to the appropriate events + connect(ui->host, &QPushButton::clicked, this, &HostRoomWindow::Host); + + // Restore the settings: + ui->username->setText(UISettings::values.room_nickname); + if (ui->username->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { + // Use yuzu Web Service user name as nickname by default + ui->username->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); + } + ui->room_name->setText(UISettings::values.room_name); + ui->port->setText(UISettings::values.room_port); + ui->max_player->setValue(UISettings::values.max_player); + int index = UISettings::values.host_type; + if (index < ui->host_type->count()) { + ui->host_type->setCurrentIndex(index); + } + index = ui->game_list->findData(UISettings::values.game_id, GameListItemPath::ProgramIdRole); + if (index != -1) { + ui->game_list->setCurrentIndex(index); + } + ui->room_description->setText(UISettings::values.room_description); +} + +HostRoomWindow::~HostRoomWindow() = default; + +void HostRoomWindow::UpdateGameList(QStandardItemModel* list) { + game_list->clear(); + for (int i = 0; i < list->rowCount(); i++) { + auto parent = list->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + game_list->appendRow(parent->child(j)->clone()); + } + } +} + +void HostRoomWindow::RetranslateUi() { + ui->retranslateUi(this); +} + +std::unique_ptr HostRoomWindow::CreateVerifyBackend( + bool use_validation) const { + std::unique_ptr verify_backend; + if (use_validation) { +#ifdef ENABLE_WEB_SERVICE + verify_backend = std::make_unique(Settings::values.web_api_url); +#else + verify_backend = std::make_unique(); +#endif + } else { + verify_backend = std::make_unique(); + } + return verify_backend; +} + +void HostRoomWindow::Host() { + if (!ui->username->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + if (!ui->room_name->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::ROOMNAME_NOT_VALID); + return; + } + if (!ui->port->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID); + return; + } + if (ui->game_list->currentIndex() == -1) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::GAME_NOT_SELECTED); + return; + } + if (auto member = Network::GetRoomMember().lock()) { + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + auto parent = static_cast(parentWidget()); + if (!parent->OnCloseRoom()) { + close(); + return; + } + } + ui->host->setDisabled(true); + + auto game_name = ui->game_list->currentData(Qt::DisplayRole).toString(); + auto game_id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong(); + auto port = ui->port->isModified() ? ui->port->text().toInt() : Network::DefaultRoomPort; + auto password = ui->password->text().toStdString(); + const bool is_public = ui->host_type->currentIndex() == 0; + Network::Room::BanList ban_list{}; + if (ui->load_ban_list->isChecked()) { + ban_list = UISettings::values.ban_list; + } + if (auto room = Network::GetRoom().lock()) { + bool created = room->Create( + ui->room_name->text().toStdString(), + ui->room_description->toPlainText().toStdString(), "", port, password, + ui->max_player->value(), Settings::values.yuzu_username.GetValue(), + game_name.toStdString(), game_id, CreateVerifyBackend(is_public), ban_list); + if (!created) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::COULD_NOT_CREATE_ROOM); + LOG_ERROR(Network, "Could not create room!"); + ui->host->setEnabled(true); + return; + } + } + // Start the announce session if they chose Public + if (is_public) { + if (auto session = announce_multiplayer_session.lock()) { + // Register the room first to ensure verify_UID is present when we connect + WebService::WebResult result = session->Register(); + if (result.result_code != WebService::WebResult::Code::Success) { + QMessageBox::warning( + this, tr("Error"), + tr("Failed to announce the room to the public lobby. In order to host a " + "room publicly, you must have a valid yuzu account configured in " + "Emulation -> Configure -> Web. If you do not want to publish a room in " + "the public lobby, then select Unlisted instead.\nDebug Message: ") + + QString::fromStdString(result.result_string), + QMessageBox::Ok); + ui->host->setEnabled(true); + if (auto room = Network::GetRoom().lock()) { + room->Destroy(); + } + return; + } + session->Start(); + } else { + LOG_ERROR(Network, "Starting announce session failed"); + } + } + std::string token; +#ifdef ENABLE_WEB_SERVICE + if (is_public) { + WebService::Client client(Settings::values.web_api_url, Settings::values.yuzu_username, + Settings::values.yuzu_token); + if (auto room = Network::GetRoom().lock()) { + token = client.GetExternalJWT(room->GetVerifyUID()).returned_data; + } + if (token.empty()) { + LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); + } else { + LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size()); + } + } +#endif + // TODO: Check what to do with this + member->Join(ui->username->text().toStdString(), "", "127.0.0.1", port, 0, + Network::NoPreferredMac, password, token); + + // Store settings + UISettings::values.room_nickname = ui->username->text(); + UISettings::values.room_name = ui->room_name->text(); + UISettings::values.game_id = + ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong(); + UISettings::values.max_player = ui->max_player->value(); + + UISettings::values.host_type = ui->host_type->currentIndex(); + UISettings::values.room_port = (ui->port->isModified() && !ui->port->text().isEmpty()) + ? ui->port->text() + : QString::number(Network::DefaultRoomPort); + UISettings::values.room_description = ui->room_description->toPlainText(); + ui->host->setEnabled(true); + close(); + } +} + +QVariant ComboBoxProxyModel::data(const QModelIndex& idx, int role) const { + if (role != Qt::DisplayRole) { + auto val = QSortFilterProxyModel::data(idx, role); + // If its the icon, shrink it to 16x16 + if (role == Qt::DecorationRole) + val = val.value().scaled(16, 16, Qt::KeepAspectRatio); + return val; + } + std::string filename; + Common::SplitPath( + QSortFilterProxyModel::data(idx, GameListItemPath::FullPathRole).toString().toStdString(), + nullptr, &filename, nullptr); + QString title = QSortFilterProxyModel::data(idx, GameListItemPath::TitleRole).toString(); + return title.isEmpty() ? QString::fromStdString(filename) : title; +} + +bool ComboBoxProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { + auto leftData = left.data(GameListItemPath::TitleRole).toString(); + auto rightData = right.data(GameListItemPath::TitleRole).toString(); + return leftData.compare(rightData) < 0; +} diff --git a/src/yuzu/multiplayer/host_room.h b/src/yuzu/multiplayer/host_room.h new file mode 100644 index 0000000000..d84f93ffde --- /dev/null +++ b/src/yuzu/multiplayer/host_room.h @@ -0,0 +1,74 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include +#include "network/network.h" +#include "yuzu/multiplayer/chat_room.h" +#include "yuzu/multiplayer/validation.h" + +namespace Ui { +class HostRoom; +} + +namespace Core { +class AnnounceMultiplayerSession; +} + +class ConnectionError; +class ComboBoxProxyModel; + +class ChatMessage; + +namespace Network::VerifyUser { +class Backend; +}; + +class HostRoomWindow : public QDialog { + Q_OBJECT + +public: + explicit HostRoomWindow(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session); + ~HostRoomWindow(); + + /** + * Updates the dialog with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* list); + void RetranslateUi(); + +private: + void Host(); + std::unique_ptr CreateVerifyBackend(bool use_validation) const; + + std::unique_ptr ui; + std::weak_ptr announce_multiplayer_session; + QStandardItemModel* game_list; + ComboBoxProxyModel* proxy; + Validation validation; +}; + +/** + * Proxy Model for the game list combo box so we can reuse the game list model while still + * displaying the fields slightly differently + */ +class ComboBoxProxyModel : public QSortFilterProxyModel { + Q_OBJECT + +public: + int columnCount(const QModelIndex& idx) const override { + return 1; + } + + QVariant data(const QModelIndex& idx, int role) const override; + + bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; +}; diff --git a/src/yuzu/multiplayer/host_room.ui b/src/yuzu/multiplayer/host_room.ui new file mode 100644 index 0000000000..d54cf49c65 --- /dev/null +++ b/src/yuzu/multiplayer/host_room.ui @@ -0,0 +1,207 @@ + + + HostRoom + + + + 0 + 0 + 607 + 211 + + + + Create Room + + + + + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + Room Name + + + + + + + 50 + + + + + + + Preferred Game + + + + + + + + + + Max Players + + + + + + + 2 + + + 16 + + + 8 + + + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Username + + + + + + + QLineEdit::PasswordEchoOnEdit + + + (Leave blank for open game) + + + + + + + Qt::ImhDigitsOnly + + + 5 + + + + + + + Password + + + + + + + Port + + + + + + + + + + + + + + Room Description + + + + + + + + + + + + + + Load Previous Ban List + + + true + + + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + Public + + + + + Unlisted + + + + + + + + Host Room + + + + + + + + + + diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp new file mode 100644 index 0000000000..fcaa7b517f --- /dev/null +++ b/src/yuzu/multiplayer/lobby.cpp @@ -0,0 +1,360 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include "common/logging/log.h" +#include "common/settings.h" +#include "network/network.h" +#include "ui_lobby.h" +#include "yuzu/game_list_p.h" +#include "yuzu/main.h" +#include "yuzu/multiplayer/client_room.h" +#include "yuzu/multiplayer/lobby.h" +#include "yuzu/multiplayer/lobby_p.h" +#include "yuzu/multiplayer/message.h" +#include "yuzu/multiplayer/state.h" +#include "yuzu/multiplayer/validation.h" +#include "yuzu/uisettings.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/web_backend.h" +#endif + +Lobby::Lobby(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), announce_multiplayer_session(session) { + ui->setupUi(this); + + // setup the watcher for background connections + watcher = new QFutureWatcher; + + model = new QStandardItemModel(ui->room_list); + + // Create a proxy to the game list to get the list of games owned + game_list = new QStandardItemModel; + UpdateGameList(list); + + proxy = new LobbyFilterProxyModel(this, game_list); + proxy->setSourceModel(model); + proxy->setDynamicSortFilter(true); + proxy->setFilterCaseSensitivity(Qt::CaseInsensitive); + proxy->setSortLocaleAware(true); + ui->room_list->setModel(proxy); + ui->room_list->header()->setSectionResizeMode(QHeaderView::Interactive); + ui->room_list->header()->stretchLastSection(); + ui->room_list->setAlternatingRowColors(true); + ui->room_list->setSelectionMode(QHeaderView::SingleSelection); + ui->room_list->setSelectionBehavior(QHeaderView::SelectRows); + ui->room_list->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + ui->room_list->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + ui->room_list->setSortingEnabled(true); + ui->room_list->setEditTriggers(QHeaderView::NoEditTriggers); + ui->room_list->setExpandsOnDoubleClick(false); + ui->room_list->setContextMenuPolicy(Qt::CustomContextMenu); + + ui->nickname->setValidator(validation.GetNickname()); + ui->nickname->setText(UISettings::values.nickname); + if (ui->nickname->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { + // Use yuzu Web Service user name as nickname by default + ui->nickname->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); + } + + // UI Buttons + connect(ui->refresh_list, &QPushButton::clicked, this, &Lobby::RefreshLobby); + connect(ui->games_owned, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterOwned); + connect(ui->hide_full, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterFull); + connect(ui->search, &QLineEdit::textChanged, proxy, &LobbyFilterProxyModel::SetFilterSearch); + connect(ui->room_list, &QTreeView::doubleClicked, this, &Lobby::OnJoinRoom); + connect(ui->room_list, &QTreeView::clicked, this, &Lobby::OnExpandRoom); + + // Actions + connect(&room_list_watcher, &QFutureWatcher::finished, this, + &Lobby::OnRefreshLobby); + + // manually start a refresh when the window is opening + // TODO(jroweboy): if this refresh is slow for people with bad internet, then don't do it as + // part of the constructor, but offload the refresh until after the window shown. perhaps emit a + // refreshroomlist signal from places that open the lobby + RefreshLobby(); +} + +Lobby::~Lobby() = default; + +void Lobby::UpdateGameList(QStandardItemModel* list) { + game_list->clear(); + for (int i = 0; i < list->rowCount(); i++) { + auto parent = list->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + game_list->appendRow(parent->child(j)->clone()); + } + } + if (proxy) + proxy->UpdateGameList(game_list); +} + +void Lobby::RetranslateUi() { + ui->retranslateUi(this); +} + +QString Lobby::PasswordPrompt() { + bool ok; + const QString text = + QInputDialog::getText(this, tr("Password Required to Join"), tr("Password:"), + QLineEdit::Password, QString(), &ok); + return ok ? text : QString(); +} + +void Lobby::OnExpandRoom(const QModelIndex& index) { + QModelIndex member_index = proxy->index(index.row(), Column::MEMBER); + auto member_list = proxy->data(member_index, LobbyItemMemberList::MemberListRole).toList(); +} + +void Lobby::OnJoinRoom(const QModelIndex& source) { + if (const auto member = Network::GetRoomMember().lock()) { + // Prevent the user from trying to join a room while they are already joining. + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + // And ask if they want to leave the room if they are already in one. + if (!NetworkMessage::WarnDisconnect()) { + return; + } + } + } + QModelIndex index = source; + // If the user double clicks on a child row (aka the player list) then use the parent instead + if (source.parent() != QModelIndex()) { + index = source.parent(); + } + if (!ui->nickname->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + + // Get a password to pass if the room is password protected + QModelIndex password_index = proxy->index(index.row(), Column::ROOM_NAME); + bool has_password = proxy->data(password_index, LobbyItemName::PasswordRole).toBool(); + const std::string password = has_password ? PasswordPrompt().toStdString() : ""; + if (has_password && password.empty()) { + return; + } + + QModelIndex connection_index = proxy->index(index.row(), Column::HOST); + const std::string nickname = ui->nickname->text().toStdString(); + const std::string ip = + proxy->data(connection_index, LobbyItemHost::HostIPRole).toString().toStdString(); + int port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt(); + const std::string verify_UID = + proxy->data(connection_index, LobbyItemHost::HostVerifyUIDRole).toString().toStdString(); + + // attempt to connect in a different thread + QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_UID] { + std::string token; +#ifdef ENABLE_WEB_SERVICE + if (!Settings::values.yuzu_username.empty() && !Settings::values.yuzu_token.empty()) { + WebService::Client client(Settings::values.web_api_url, Settings::values.yuzu_username, + Settings::values.yuzu_token); + token = client.GetExternalJWT(verify_UID).returned_data; + if (token.empty()) { + LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); + } else { + LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size()); + } + } +#endif + if (auto room_member = Network::GetRoomMember().lock()) { + room_member->Join(nickname, "", ip.c_str(), port, 0, Network::NoPreferredMac, password, + token); + } + }); + watcher->setFuture(f); + + // TODO(jroweboy): disable widgets and display a connecting while we wait + + // Save settings + UISettings::values.nickname = ui->nickname->text(); + UISettings::values.ip = proxy->data(connection_index, LobbyItemHost::HostIPRole).toString(); + UISettings::values.port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toString(); +} + +void Lobby::ResetModel() { + model->clear(); + model->insertColumns(0, Column::TOTAL); + model->setHeaderData(Column::EXPAND, Qt::Horizontal, QString(), Qt::DisplayRole); + model->setHeaderData(Column::ROOM_NAME, Qt::Horizontal, tr("Room Name"), Qt::DisplayRole); + model->setHeaderData(Column::GAME_NAME, Qt::Horizontal, tr("Preferred Game"), Qt::DisplayRole); + model->setHeaderData(Column::HOST, Qt::Horizontal, tr("Host"), Qt::DisplayRole); + model->setHeaderData(Column::MEMBER, Qt::Horizontal, tr("Players"), Qt::DisplayRole); +} + +void Lobby::RefreshLobby() { + if (auto session = announce_multiplayer_session.lock()) { + ResetModel(); + ui->refresh_list->setEnabled(false); + ui->refresh_list->setText(tr("Refreshing")); + room_list_watcher.setFuture( + QtConcurrent::run([session]() { return session->GetRoomList(); })); + } else { + // TODO(jroweboy): Display an error box about announce couldn't be started + } +} + +void Lobby::OnRefreshLobby() { + AnnounceMultiplayerRoom::RoomList new_room_list = room_list_watcher.result(); + for (auto room : new_room_list) { + // find the icon for the game if this person owns that game. + QPixmap smdh_icon; + for (int r = 0; r < game_list->rowCount(); ++r) { + auto index = game_list->index(r, 0); + auto game_id = game_list->data(index, GameListItemPath::ProgramIdRole).toULongLong(); + if (game_id != 0 && room.preferred_game_id == game_id) { + smdh_icon = game_list->data(index, Qt::DecorationRole).value(); + } + } + + QList members; + for (auto member : room.members) { + QVariant var; + var.setValue(LobbyMember{QString::fromStdString(member.username), + QString::fromStdString(member.nickname), member.game_id, + QString::fromStdString(member.game_name)}); + members.append(var); + } + + auto first_item = new LobbyItem(); + auto row = QList({ + first_item, + new LobbyItemName(room.has_password, QString::fromStdString(room.name)), + new LobbyItemGame(room.preferred_game_id, QString::fromStdString(room.preferred_game), + smdh_icon), + new LobbyItemHost(QString::fromStdString(room.owner), QString::fromStdString(room.ip), + room.port, QString::fromStdString(room.verify_UID)), + new LobbyItemMemberList(members, room.max_player), + }); + model->appendRow(row); + // To make the rows expandable, add the member data as a child of the first column of the + // rows with people in them and have qt set them to colspan after the model is finished + // resetting + if (!room.description.empty()) { + first_item->appendRow( + new LobbyItemDescription(QString::fromStdString(room.description))); + } + if (!room.members.empty()) { + first_item->appendRow(new LobbyItemExpandedMemberList(members)); + } + } + + // Reenable the refresh button and resize the columns + ui->refresh_list->setEnabled(true); + ui->refresh_list->setText(tr("Refresh List")); + ui->room_list->header()->stretchLastSection(); + for (int i = 0; i < Column::TOTAL - 1; ++i) { + ui->room_list->resizeColumnToContents(i); + } + + // Set the member list child items to span all columns + for (int i = 0; i < proxy->rowCount(); i++) { + auto parent = model->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + ui->room_list->setFirstColumnSpanned(j, proxy->index(i, 0), true); + } + } +} + +LobbyFilterProxyModel::LobbyFilterProxyModel(QWidget* parent, QStandardItemModel* list) + : QSortFilterProxyModel(parent), game_list(list) {} + +void LobbyFilterProxyModel::UpdateGameList(QStandardItemModel* list) { + game_list = list; +} + +bool LobbyFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { + // Prioritize filters by fastest to compute + + // pass over any child rows (aka row that shows the players in the room) + if (sourceParent != QModelIndex()) { + return true; + } + + // filter by filled rooms + if (filter_full) { + QModelIndex member_list = sourceModel()->index(sourceRow, Column::MEMBER, sourceParent); + int player_count = + sourceModel()->data(member_list, LobbyItemMemberList::MemberListRole).toList().size(); + int max_players = + sourceModel()->data(member_list, LobbyItemMemberList::MaxPlayerRole).toInt(); + if (player_count >= max_players) { + return false; + } + } + + // filter by search parameters + if (!filter_search.isEmpty()) { + QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent); + QModelIndex room_name = sourceModel()->index(sourceRow, Column::ROOM_NAME, sourceParent); + QModelIndex host_name = sourceModel()->index(sourceRow, Column::HOST, sourceParent); + bool preferred_game_match = sourceModel() + ->data(game_name, LobbyItemGame::GameNameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + bool room_name_match = sourceModel() + ->data(room_name, LobbyItemName::NameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + bool username_match = sourceModel() + ->data(host_name, LobbyItemHost::HostUsernameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + if (!preferred_game_match && !room_name_match && !username_match) { + return false; + } + } + + // filter by game owned + if (filter_owned) { + QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent); + QList owned_games; + for (int r = 0; r < game_list->rowCount(); ++r) { + owned_games.append(QModelIndex(game_list->index(r, 0))); + } + auto current_id = sourceModel()->data(game_name, LobbyItemGame::TitleIDRole).toLongLong(); + if (current_id == 0) { + // TODO(jroweboy): homebrew often doesn't have a game id and this hides them + return false; + } + bool owned = false; + for (const auto& game : owned_games) { + auto game_id = game_list->data(game, GameListItemPath::ProgramIdRole).toLongLong(); + if (current_id == game_id) { + owned = true; + } + } + if (!owned) { + return false; + } + } + + return true; +} + +void LobbyFilterProxyModel::sort(int column, Qt::SortOrder order) { + sourceModel()->sort(column, order); +} + +void LobbyFilterProxyModel::SetFilterOwned(bool filter) { + filter_owned = filter; + invalidate(); +} + +void LobbyFilterProxyModel::SetFilterFull(bool filter) { + filter_full = filter; + invalidate(); +} + +void LobbyFilterProxyModel::SetFilterSearch(const QString& filter) { + filter_search = filter; + invalidate(); +} diff --git a/src/yuzu/multiplayer/lobby.h b/src/yuzu/multiplayer/lobby.h new file mode 100644 index 0000000000..aea4a0e4e4 --- /dev/null +++ b/src/yuzu/multiplayer/lobby.h @@ -0,0 +1,127 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include +#include "common/announce_multiplayer_room.h" +#include "core/announce_multiplayer_session.h" +#include "network/network.h" +#include "yuzu/multiplayer/validation.h" + +namespace Ui { +class Lobby; +} + +class LobbyModel; +class LobbyFilterProxyModel; + +/** + * Listing of all public games pulled from services. The lobby should be simple enough for users to + * find the game they want to play, and join it. + */ +class Lobby : public QDialog { + Q_OBJECT + +public: + explicit Lobby(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session); + ~Lobby() override; + + /** + * Updates the lobby with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* list); + void RetranslateUi(); + +public slots: + /** + * Begin the process to pull the latest room list from web services. After the listing is + * returned from web services, `LobbyRefreshed` will be signalled + */ + void RefreshLobby(); + +private slots: + /** + * Pulls the list of rooms from network and fills out the lobby model with the results + */ + void OnRefreshLobby(); + + /** + * Handler for single clicking on a room in the list. Expands the treeitem to show player + * information for the people in the room + * + * index - The row of the proxy model that the user wants to join. + */ + void OnExpandRoom(const QModelIndex&); + + /** + * Handler for double clicking on a room in the list. Gathers the host ip and port and attempts + * to connect. Will also prompt for a password in case one is required. + * + * index - The row of the proxy model that the user wants to join. + */ + void OnJoinRoom(const QModelIndex&); + +signals: + void StateChanged(const Network::RoomMember::State&); + +private: + /** + * Removes all entries in the Lobby before refreshing. + */ + void ResetModel(); + + /** + * Prompts for a password. Returns an empty QString if the user either did not provide a + * password or if the user closed the window. + */ + QString PasswordPrompt(); + + std::unique_ptr ui; + + QStandardItemModel* model{}; + QStandardItemModel* game_list{}; + LobbyFilterProxyModel* proxy{}; + + QFutureWatcher room_list_watcher; + std::weak_ptr announce_multiplayer_session; + QFutureWatcher* watcher; + Validation validation; +}; + +/** + * Proxy Model for filtering the lobby + */ +class LobbyFilterProxyModel : public QSortFilterProxyModel { + Q_OBJECT; + +public: + explicit LobbyFilterProxyModel(QWidget* parent, QStandardItemModel* list); + + /** + * Updates the filter with a new game list model. + * This model should be the processed one created by the Lobby. + */ + void UpdateGameList(QStandardItemModel* list); + + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; + void sort(int column, Qt::SortOrder order) override; + +public slots: + void SetFilterOwned(bool); + void SetFilterFull(bool); + void SetFilterSearch(const QString&); + +private: + QStandardItemModel* game_list; + bool filter_owned = false; + bool filter_full = false; + QString filter_search; +}; diff --git a/src/yuzu/multiplayer/lobby.ui b/src/yuzu/multiplayer/lobby.ui new file mode 100644 index 0000000000..4c9901c9af --- /dev/null +++ b/src/yuzu/multiplayer/lobby.ui @@ -0,0 +1,123 @@ + + + Lobby + + + + 0 + 0 + 903 + 487 + + + + Public Room Browser + + + + + + 3 + + + + + 6 + + + + + + + Nickname + + + + + + + Nickname + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Filters + + + + + + + Search + + + true + + + + + + + Games I Own + + + + + + + Hide Full Rooms + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Refresh Lobby + + + + + + + + + + + + + + + + + + + + diff --git a/src/yuzu/multiplayer/lobby_p.h b/src/yuzu/multiplayer/lobby_p.h new file mode 100644 index 0000000000..749ca627f2 --- /dev/null +++ b/src/yuzu/multiplayer/lobby_p.h @@ -0,0 +1,239 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include +#include "common/common_types.h" + +namespace Column { +enum List { + EXPAND, + ROOM_NAME, + GAME_NAME, + HOST, + MEMBER, + TOTAL, +}; +} + +class LobbyItem : public QStandardItem { +public: + LobbyItem() = default; + explicit LobbyItem(const QString& string) : QStandardItem(string) {} + virtual ~LobbyItem() override = default; +}; + +class LobbyItemName : public LobbyItem { +public: + static const int NameRole = Qt::UserRole + 1; + static const int PasswordRole = Qt::UserRole + 2; + + LobbyItemName() = default; + explicit LobbyItemName(bool has_password, QString name) : LobbyItem() { + setData(name, NameRole); + setData(has_password, PasswordRole); + } + + QVariant data(int role) const override { + if (role == Qt::DecorationRole) { + bool has_password = data(PasswordRole).toBool(); + return has_password ? QIcon::fromTheme(QStringLiteral("lock")).pixmap(16) : QIcon(); + } + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(NameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(NameRole).toString().localeAwareCompare(other.data(NameRole).toString()) < 0; + } +}; + +class LobbyItemDescription : public LobbyItem { +public: + static const int DescriptionRole = Qt::UserRole + 1; + + LobbyItemDescription() = default; + explicit LobbyItemDescription(QString description) { + setData(description, DescriptionRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + auto description = data(DescriptionRole).toString(); + description.prepend(QStringLiteral("Description: ")); + return description; + } + + bool operator<(const QStandardItem& other) const override { + return data(DescriptionRole) + .toString() + .localeAwareCompare(other.data(DescriptionRole).toString()) < 0; + } +}; + +class LobbyItemGame : public LobbyItem { +public: + static const int TitleIDRole = Qt::UserRole + 1; + static const int GameNameRole = Qt::UserRole + 2; + static const int GameIconRole = Qt::UserRole + 3; + + LobbyItemGame() = default; + explicit LobbyItemGame(u64 title_id, QString game_name, QPixmap smdh_icon) { + setData(static_cast(title_id), TitleIDRole); + setData(game_name, GameNameRole); + if (!smdh_icon.isNull()) { + setData(smdh_icon, GameIconRole); + } + } + + QVariant data(int role) const override { + if (role == Qt::DecorationRole) { + auto val = data(GameIconRole); + if (val.isValid()) { + val = val.value().scaled(16, 16, Qt::KeepAspectRatio); + } + return val; + } else if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(GameNameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(GameNameRole) + .toString() + .localeAwareCompare(other.data(GameNameRole).toString()) < 0; + } +}; + +class LobbyItemHost : public LobbyItem { +public: + static const int HostUsernameRole = Qt::UserRole + 1; + static const int HostIPRole = Qt::UserRole + 2; + static const int HostPortRole = Qt::UserRole + 3; + static const int HostVerifyUIDRole = Qt::UserRole + 4; + + LobbyItemHost() = default; + explicit LobbyItemHost(QString username, QString ip, u16 port, QString verify_UID) { + setData(username, HostUsernameRole); + setData(ip, HostIPRole); + setData(port, HostPortRole); + setData(verify_UID, HostVerifyUIDRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(HostUsernameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(HostUsernameRole) + .toString() + .localeAwareCompare(other.data(HostUsernameRole).toString()) < 0; + } +}; + +class LobbyMember { +public: + LobbyMember() = default; + LobbyMember(const LobbyMember& other) = default; + explicit LobbyMember(QString username, QString nickname, u64 title_id, QString game_name) + : username(std::move(username)), nickname(std::move(nickname)), title_id(title_id), + game_name(std::move(game_name)) {} + ~LobbyMember() = default; + + QString GetName() const { + if (username.isEmpty() || username == nickname) { + return nickname; + } else { + return QStringLiteral("%1 (%2)").arg(nickname, username); + } + } + u64 GetTitleId() const { + return title_id; + } + QString GetGameName() const { + return game_name; + } + +private: + QString username; + QString nickname; + u64 title_id; + QString game_name; +}; + +Q_DECLARE_METATYPE(LobbyMember); + +class LobbyItemMemberList : public LobbyItem { +public: + static const int MemberListRole = Qt::UserRole + 1; + static const int MaxPlayerRole = Qt::UserRole + 2; + + LobbyItemMemberList() = default; + explicit LobbyItemMemberList(QList members, u32 max_players) { + setData(members, MemberListRole); + setData(max_players, MaxPlayerRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + auto members = data(MemberListRole).toList(); + return QStringLiteral("%1 / %2").arg(QString::number(members.size()), + data(MaxPlayerRole).toString()); + } + + bool operator<(const QStandardItem& other) const override { + // sort by rooms that have the most players + int left_members = data(MemberListRole).toList().size(); + int right_members = other.data(MemberListRole).toList().size(); + return left_members < right_members; + } +}; + +/** + * Member information for when a lobby is expanded in the UI + */ +class LobbyItemExpandedMemberList : public LobbyItem { +public: + static const int MemberListRole = Qt::UserRole + 1; + + LobbyItemExpandedMemberList() = default; + explicit LobbyItemExpandedMemberList(QList members) { + setData(members, MemberListRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + auto members = data(MemberListRole).toList(); + QString out; + bool first = true; + for (const auto& member : members) { + if (!first) + out.append(QStringLiteral("\n")); + const auto& m = member.value(); + if (m.GetGameName().isEmpty()) { + out += QString(QObject::tr("%1 is not playing a game")).arg(m.GetName()); + } else { + out += QString(QObject::tr("%1 is playing %2")).arg(m.GetName(), m.GetGameName()); + } + first = false; + } + return out; + } +}; diff --git a/src/yuzu/multiplayer/message.cpp b/src/yuzu/multiplayer/message.cpp new file mode 100644 index 0000000000..458f1e7d1f --- /dev/null +++ b/src/yuzu/multiplayer/message.cpp @@ -0,0 +1,79 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include + +#include "yuzu/multiplayer/message.h" + +namespace NetworkMessage { +const ConnectionError ErrorManager::USERNAME_NOT_VALID( + QT_TR_NOOP("Username is not valid. Must be 4 to 20 alphanumeric characters.")); +const ConnectionError ErrorManager::ROOMNAME_NOT_VALID( + QT_TR_NOOP("Room name is not valid. Must be 4 to 20 alphanumeric characters.")); +const ConnectionError ErrorManager::USERNAME_NOT_VALID_SERVER( + QT_TR_NOOP("Username is already in use or not valid. Please choose another.")); +const ConnectionError ErrorManager::IP_ADDRESS_NOT_VALID( + QT_TR_NOOP("IP is not a valid IPv4 address.")); +const ConnectionError ErrorManager::PORT_NOT_VALID( + QT_TR_NOOP("Port must be a number between 0 to 65535.")); +const ConnectionError ErrorManager::GAME_NOT_SELECTED(QT_TR_NOOP( + "You must choose a Preferred Game to host a room. If you do not have any games in your game " + "list yet, add a game folder by clicking on the plus icon in the game list.")); +const ConnectionError ErrorManager::NO_INTERNET( + QT_TR_NOOP("Unable to find an internet connection. Check your internet settings.")); +const ConnectionError ErrorManager::UNABLE_TO_CONNECT( + QT_TR_NOOP("Unable to connect to the host. Verify that the connection settings are correct. If " + "you still cannot connect, contact the room host and verify that the host is " + "properly configured with the external port forwarded.")); +const ConnectionError ErrorManager::ROOM_IS_FULL( + QT_TR_NOOP("Unable to connect to the room because it is already full.")); +const ConnectionError ErrorManager::COULD_NOT_CREATE_ROOM( + QT_TR_NOOP("Creating a room failed. Please retry. Restarting yuzu might be necessary.")); +const ConnectionError ErrorManager::HOST_BANNED( + QT_TR_NOOP("The host of the room has banned you. Speak with the host to unban you " + "or try a different room.")); +const ConnectionError ErrorManager::WRONG_VERSION( + QT_TR_NOOP("Version mismatch! Please update to the latest version of yuzu. If the problem " + "persists, contact the room host and ask them to update the server.")); +const ConnectionError ErrorManager::WRONG_PASSWORD(QT_TR_NOOP("Incorrect password.")); +const ConnectionError ErrorManager::GENERIC_ERROR(QT_TR_NOOP( + "An unknown error occurred. If this error continues to occur, please open an issue")); +const ConnectionError ErrorManager::LOST_CONNECTION( + QT_TR_NOOP("Connection to room lost. Try to reconnect.")); +const ConnectionError ErrorManager::HOST_KICKED( + QT_TR_NOOP("You have been kicked by the room host.")); +const ConnectionError ErrorManager::MAC_COLLISION( + QT_TR_NOOP("MAC address is already in use. Please choose another.")); +const ConnectionError ErrorManager::CONSOLE_ID_COLLISION(QT_TR_NOOP( + "Your Console ID conflicted with someone else's in the room.\n\nPlease go to Emulation " + "> Configure > System to regenerate your Console ID.")); +const ConnectionError ErrorManager::PERMISSION_DENIED( + QT_TR_NOOP("You do not have enough permission to perform this action.")); +const ConnectionError ErrorManager::NO_SUCH_USER(QT_TR_NOOP( + "The user you are trying to kick/ban could not be found.\nThey may have left the room.")); + +static bool WarnMessage(const std::string& title, const std::string& text) { + return QMessageBox::Ok == QMessageBox::warning(nullptr, QObject::tr(title.c_str()), + QObject::tr(text.c_str()), + QMessageBox::Ok | QMessageBox::Cancel); +} + +void ErrorManager::ShowError(const ConnectionError& e) { + QMessageBox::critical(nullptr, tr("Error"), tr(e.GetString().c_str())); +} + +bool WarnCloseRoom() { + return WarnMessage( + QT_TR_NOOP("Leave Room"), + QT_TR_NOOP("You are about to close the room. Any network connections will be closed.")); +} + +bool WarnDisconnect() { + return WarnMessage( + QT_TR_NOOP("Disconnect"), + QT_TR_NOOP("You are about to leave the room. Any network connections will be closed.")); +} + +} // namespace NetworkMessage diff --git a/src/yuzu/multiplayer/message.h b/src/yuzu/multiplayer/message.h new file mode 100644 index 0000000000..49a31997dd --- /dev/null +++ b/src/yuzu/multiplayer/message.h @@ -0,0 +1,65 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include + +namespace NetworkMessage { + +class ConnectionError { + +public: + explicit ConnectionError(std::string str) : err(std::move(str)) {} + const std::string& GetString() const { + return err; + } + +private: + std::string err; +}; + +class ErrorManager : QObject { + Q_OBJECT +public: + /// When the nickname is considered invalid by the client + static const ConnectionError USERNAME_NOT_VALID; + static const ConnectionError ROOMNAME_NOT_VALID; + /// When the nickname is considered invalid by the room server + static const ConnectionError USERNAME_NOT_VALID_SERVER; + static const ConnectionError IP_ADDRESS_NOT_VALID; + static const ConnectionError PORT_NOT_VALID; + static const ConnectionError GAME_NOT_SELECTED; + static const ConnectionError NO_INTERNET; + static const ConnectionError UNABLE_TO_CONNECT; + static const ConnectionError ROOM_IS_FULL; + static const ConnectionError COULD_NOT_CREATE_ROOM; + static const ConnectionError HOST_BANNED; + static const ConnectionError WRONG_VERSION; + static const ConnectionError WRONG_PASSWORD; + static const ConnectionError GENERIC_ERROR; + static const ConnectionError LOST_CONNECTION; + static const ConnectionError HOST_KICKED; + static const ConnectionError MAC_COLLISION; + static const ConnectionError CONSOLE_ID_COLLISION; + static const ConnectionError PERMISSION_DENIED; + static const ConnectionError NO_SUCH_USER; + /** + * Shows a standard QMessageBox with a error message + */ + static void ShowError(const ConnectionError& e); +}; +/** + * Show a standard QMessageBox with a warning message about leaving the room + * return true if the user wants to close the network connection + */ +bool WarnCloseRoom(); + +/** + * Show a standard QMessageBox with a warning message about disconnecting from the room + * return true if the user wants to disconnect + */ +bool WarnDisconnect(); + +} // namespace NetworkMessage diff --git a/src/yuzu/multiplayer/moderation_dialog.cpp b/src/yuzu/multiplayer/moderation_dialog.cpp new file mode 100644 index 0000000000..e97f30ee5a --- /dev/null +++ b/src/yuzu/multiplayer/moderation_dialog.cpp @@ -0,0 +1,113 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include "network/network.h" +#include "network/room_member.h" +#include "ui_moderation_dialog.h" +#include "yuzu/multiplayer/moderation_dialog.h" + +namespace Column { +enum { + SUBJECT, + TYPE, + COUNT, +}; +} + +ModerationDialog::ModerationDialog(QWidget* parent) + : QDialog(parent), ui(std::make_unique()) { + ui->setupUi(this); + + qRegisterMetaType(); + + if (auto member = Network::GetRoomMember().lock()) { + callback_handle_status_message = member->BindOnStatusMessageReceived( + [this](const Network::StatusMessageEntry& status_message) { + emit StatusMessageReceived(status_message); + }); + connect(this, &ModerationDialog::StatusMessageReceived, this, + &ModerationDialog::OnStatusMessageReceived); + callback_handle_ban_list = member->BindOnBanListReceived( + [this](const Network::Room::BanList& ban_list) { emit BanListReceived(ban_list); }); + connect(this, &ModerationDialog::BanListReceived, this, &ModerationDialog::PopulateBanList); + } + + // Initialize the UI + model = new QStandardItemModel(ui->ban_list_view); + model->insertColumns(0, Column::COUNT); + model->setHeaderData(Column::SUBJECT, Qt::Horizontal, tr("Subject")); + model->setHeaderData(Column::TYPE, Qt::Horizontal, tr("Type")); + + ui->ban_list_view->setModel(model); + + // Load the ban list in background + LoadBanList(); + + connect(ui->refresh, &QPushButton::clicked, this, [this] { LoadBanList(); }); + connect(ui->unban, &QPushButton::clicked, this, [this] { + auto index = ui->ban_list_view->currentIndex(); + SendUnbanRequest(model->item(index.row(), 0)->text()); + }); + connect(ui->ban_list_view, &QTreeView::clicked, [this] { ui->unban->setEnabled(true); }); +} + +ModerationDialog::~ModerationDialog() { + if (callback_handle_status_message) { + if (auto room = Network::GetRoomMember().lock()) { + room->Unbind(callback_handle_status_message); + } + } + + if (callback_handle_ban_list) { + if (auto room = Network::GetRoomMember().lock()) { + room->Unbind(callback_handle_ban_list); + } + } +} + +void ModerationDialog::LoadBanList() { + if (auto room = Network::GetRoomMember().lock()) { + ui->refresh->setEnabled(false); + ui->refresh->setText(tr("Refreshing")); + ui->unban->setEnabled(false); + room->RequestBanList(); + } +} + +void ModerationDialog::PopulateBanList(const Network::Room::BanList& ban_list) { + model->removeRows(0, model->rowCount()); + for (const auto& username : ban_list.first) { + QStandardItem* subject_item = new QStandardItem(QString::fromStdString(username)); + QStandardItem* type_item = new QStandardItem(tr("Forum Username")); + model->invisibleRootItem()->appendRow({subject_item, type_item}); + } + for (const auto& ip : ban_list.second) { + QStandardItem* subject_item = new QStandardItem(QString::fromStdString(ip)); + QStandardItem* type_item = new QStandardItem(tr("IP Address")); + model->invisibleRootItem()->appendRow({subject_item, type_item}); + } + for (int i = 0; i < Column::COUNT - 1; ++i) { + ui->ban_list_view->resizeColumnToContents(i); + } + ui->refresh->setEnabled(true); + ui->refresh->setText(tr("Refresh")); + ui->unban->setEnabled(false); +} + +void ModerationDialog::SendUnbanRequest(const QString& subject) { + if (auto room = Network::GetRoomMember().lock()) { + room->SendModerationRequest(Network::IdModUnban, subject.toStdString()); + } +} + +void ModerationDialog::OnStatusMessageReceived(const Network::StatusMessageEntry& status_message) { + if (status_message.type != Network::IdMemberBanned && + status_message.type != Network::IdAddressUnbanned) + return; + + // Update the ban list for ban/unban + LoadBanList(); +} diff --git a/src/yuzu/multiplayer/moderation_dialog.h b/src/yuzu/multiplayer/moderation_dialog.h new file mode 100644 index 0000000000..d10083d5b8 --- /dev/null +++ b/src/yuzu/multiplayer/moderation_dialog.h @@ -0,0 +1,42 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include +#include "network/room.h" +#include "network/room_member.h" + +namespace Ui { +class ModerationDialog; +} + +class QStandardItemModel; + +class ModerationDialog : public QDialog { + Q_OBJECT + +public: + explicit ModerationDialog(QWidget* parent = nullptr); + ~ModerationDialog(); + +signals: + void StatusMessageReceived(const Network::StatusMessageEntry&); + void BanListReceived(const Network::Room::BanList&); + +private: + void LoadBanList(); + void PopulateBanList(const Network::Room::BanList& ban_list); + void SendUnbanRequest(const QString& subject); + void OnStatusMessageReceived(const Network::StatusMessageEntry& status_message); + + std::unique_ptr ui; + QStandardItemModel* model; + Network::RoomMember::CallbackHandle callback_handle_status_message; + Network::RoomMember::CallbackHandle callback_handle_ban_list; +}; + +Q_DECLARE_METATYPE(Network::Room::BanList); diff --git a/src/yuzu/multiplayer/moderation_dialog.ui b/src/yuzu/multiplayer/moderation_dialog.ui new file mode 100644 index 0000000000..808d994142 --- /dev/null +++ b/src/yuzu/multiplayer/moderation_dialog.ui @@ -0,0 +1,84 @@ + + + ModerationDialog + + + Moderation + + + + 0 + 0 + 500 + 300 + + + + + + + Ban List + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Refreshing + + + false + + + + + + + Unban + + + false + + + + + + + + + + + + + + + QDialogButtonBox::Ok + + + + + + + + buttonBox + accepted() + ModerationDialog + accept() + + + + diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp new file mode 100644 index 0000000000..b2aaed9828 --- /dev/null +++ b/src/yuzu/multiplayer/state.cpp @@ -0,0 +1,299 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include +#include +#include +#include "common/announce_multiplayer_room.h" +#include "common/logging/log.h" +#include "yuzu/game_list.h" +#include "yuzu/multiplayer/client_room.h" +#include "yuzu/multiplayer/direct_connect.h" +#include "yuzu/multiplayer/host_room.h" +#include "yuzu/multiplayer/lobby.h" +#include "yuzu/multiplayer/message.h" +#include "yuzu/multiplayer/state.h" +#include "yuzu/uisettings.h" +#include "yuzu/util/clickable_label.h" + +MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_list_model, + QAction* leave_room, QAction* show_room) + : QWidget(parent), game_list_model(game_list_model), leave_room(leave_room), + show_room(show_room) { + if (auto member = Network::GetRoomMember().lock()) { + // register the network structs to use in slots and signals + state_callback_handle = member->BindOnStateChanged( + [this](const Network::RoomMember::State& state) { emit NetworkStateChanged(state); }); + connect(this, &MultiplayerState::NetworkStateChanged, this, + &MultiplayerState::OnNetworkStateChanged); + error_callback_handle = member->BindOnError( + [this](const Network::RoomMember::Error& error) { emit NetworkError(error); }); + connect(this, &MultiplayerState::NetworkError, this, &MultiplayerState::OnNetworkError); + } + + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + announce_multiplayer_session = std::make_shared(); + announce_multiplayer_session->BindErrorCallback( + [this](const WebService::WebResult& result) { emit AnnounceFailed(result); }); + connect(this, &MultiplayerState::AnnounceFailed, this, &MultiplayerState::OnAnnounceFailed); + + status_text = new ClickableLabel(this); + status_icon = new ClickableLabel(this); + status_text->setToolTip(tr("Current connection status")); + status_text->setText(tr("Not Connected. Click here to find a room!")); + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + + connect(status_text, &ClickableLabel::clicked, this, &MultiplayerState::OnOpenNetworkRoom); + connect(status_icon, &ClickableLabel::clicked, this, &MultiplayerState::OnOpenNetworkRoom); + + connect(static_cast(QApplication::instance()), &QApplication::focusChanged, this, + [this](QWidget* /*old*/, QWidget* now) { + if (client_room && client_room->isAncestorOf(now)) { + HideNotification(); + } + }); +} + +MultiplayerState::~MultiplayerState() { + if (state_callback_handle) { + if (auto member = Network::GetRoomMember().lock()) { + member->Unbind(state_callback_handle); + } + } + + if (error_callback_handle) { + if (auto member = Network::GetRoomMember().lock()) { + member->Unbind(error_callback_handle); + } + } +} + +void MultiplayerState::Close() { + if (host_room) + host_room->close(); + if (direct_connect) + direct_connect->close(); + if (client_room) + client_room->close(); + if (lobby) + lobby->close(); +} + +void MultiplayerState::retranslateUi() { + status_text->setToolTip(tr("Current connection status")); + + if (current_state == Network::RoomMember::State::Uninitialized) { + status_text->setText(tr("Not Connected. Click here to find a room!")); + } else if (current_state == Network::RoomMember::State::Joined || + current_state == Network::RoomMember::State::Moderator) { + + status_text->setText(tr("Connected")); + } else { + status_text->setText(tr("Not Connected")); + } + + if (lobby) + lobby->RetranslateUi(); + if (host_room) + host_room->RetranslateUi(); + if (client_room) + client_room->RetranslateUi(); + if (direct_connect) + direct_connect->RetranslateUi(); +} + +void MultiplayerState::OnNetworkStateChanged(const Network::RoomMember::State& state) { + LOG_DEBUG(Frontend, "Network State: {}", Network::GetStateStr(state)); + if (state == Network::RoomMember::State::Joined || + state == Network::RoomMember::State::Moderator) { + + OnOpenNetworkRoom(); + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected")).pixmap(16)); + status_text->setText(tr("Connected")); + leave_room->setEnabled(true); + show_room->setEnabled(true); + } else { + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + status_text->setText(tr("Not Connected")); + leave_room->setEnabled(false); + show_room->setEnabled(false); + } + + current_state = state; +} + +void MultiplayerState::OnNetworkError(const Network::RoomMember::Error& error) { + LOG_DEBUG(Frontend, "Network Error: {}", Network::GetErrorStr(error)); + switch (error) { + case Network::RoomMember::Error::LostConnection: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::LOST_CONNECTION); + break; + case Network::RoomMember::Error::HostKicked: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::HOST_KICKED); + break; + case Network::RoomMember::Error::CouldNotConnect: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::UNABLE_TO_CONNECT); + break; + case Network::RoomMember::Error::NameCollision: + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::USERNAME_NOT_VALID_SERVER); + break; + case Network::RoomMember::Error::MacCollision: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::MAC_COLLISION); + break; + case Network::RoomMember::Error::ConsoleIdCollision: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::CONSOLE_ID_COLLISION); + break; + case Network::RoomMember::Error::RoomIsFull: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::ROOM_IS_FULL); + break; + case Network::RoomMember::Error::WrongPassword: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::WRONG_PASSWORD); + break; + case Network::RoomMember::Error::WrongVersion: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::WRONG_VERSION); + break; + case Network::RoomMember::Error::HostBanned: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::HOST_BANNED); + break; + case Network::RoomMember::Error::UnknownError: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::UNABLE_TO_CONNECT); + break; + case Network::RoomMember::Error::PermissionDenied: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PERMISSION_DENIED); + break; + case Network::RoomMember::Error::NoSuchUser: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::NO_SUCH_USER); + break; + } +} + +void MultiplayerState::OnAnnounceFailed(const WebService::WebResult& result) { + announce_multiplayer_session->Stop(); + QMessageBox::warning(this, tr("Error"), + tr("Failed to update the room information. Please check your Internet " + "connection and try hosting the room again.\nDebug Message: ") + + QString::fromStdString(result.result_string), + QMessageBox::Ok); +} + +void MultiplayerState::UpdateThemedIcons() { + if (show_notification) { + status_icon->setPixmap( + QIcon::fromTheme(QStringLiteral("connected_notification")).pixmap(16)); + } else if (current_state == Network::RoomMember::State::Joined || + current_state == Network::RoomMember::State::Moderator) { + + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected")).pixmap(16)); + } else { + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + } + if (client_room) + client_room->UpdateIconDisplay(); +} + +static void BringWidgetToFront(QWidget* widget) { + widget->show(); + widget->activateWindow(); + widget->raise(); +} + +void MultiplayerState::OnViewLobby() { + if (lobby == nullptr) { + lobby = new Lobby(this, game_list_model, announce_multiplayer_session); + } + BringWidgetToFront(lobby); +} + +void MultiplayerState::OnCreateRoom() { + if (host_room == nullptr) { + host_room = new HostRoomWindow(this, game_list_model, announce_multiplayer_session); + } + BringWidgetToFront(host_room); +} + +bool MultiplayerState::OnCloseRoom() { + if (!NetworkMessage::WarnCloseRoom()) + return false; + if (auto room = Network::GetRoom().lock()) { + // if you are in a room, leave it + if (auto member = Network::GetRoomMember().lock()) { + member->Leave(); + LOG_DEBUG(Frontend, "Left the room (as a client)"); + } + + // if you are hosting a room, also stop hosting + if (room->GetState() != Network::Room::State::Open) { + return true; + } + // Save ban list + UISettings::values.ban_list = std::move(room->GetBanList()); + + room->Destroy(); + announce_multiplayer_session->Stop(); + LOG_DEBUG(Frontend, "Closed the room (as a server)"); + } + return true; +} + +void MultiplayerState::ShowNotification() { + if (client_room && client_room->isAncestorOf(QApplication::focusWidget())) + return; // Do not show notification if the chat window currently has focus + show_notification = true; + QApplication::alert(nullptr); + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected_notification")).pixmap(16)); + status_text->setText(tr("New Messages Received")); +} + +void MultiplayerState::HideNotification() { + show_notification = false; + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected")).pixmap(16)); + status_text->setText(tr("Connected")); +} + +void MultiplayerState::OnOpenNetworkRoom() { + if (auto member = Network::GetRoomMember().lock()) { + if (member->IsConnected()) { + if (client_room == nullptr) { + client_room = new ClientRoomWindow(this); + connect(client_room, &ClientRoomWindow::ShowNotification, this, + &MultiplayerState::ShowNotification); + } + BringWidgetToFront(client_room); + return; + } + } + // If the user is not a member of a room, show the lobby instead. + // This is currently only used on the clickable label in the status bar + OnViewLobby(); +} + +void MultiplayerState::OnDirectConnectToRoom() { + if (direct_connect == nullptr) { + direct_connect = new DirectConnectWindow(this); + } + BringWidgetToFront(direct_connect); +} + +bool MultiplayerState::IsHostingPublicRoom() const { + return announce_multiplayer_session->IsRunning(); +} + +void MultiplayerState::UpdateCredentials() { + announce_multiplayer_session->UpdateCredentials(); +} + +void MultiplayerState::UpdateGameList(QStandardItemModel* game_list) { + game_list_model = game_list; + if (lobby) { + lobby->UpdateGameList(game_list); + } + if (host_room) { + host_room->UpdateGameList(game_list); + } +} diff --git a/src/yuzu/multiplayer/state.h b/src/yuzu/multiplayer/state.h new file mode 100644 index 0000000000..414454acb9 --- /dev/null +++ b/src/yuzu/multiplayer/state.h @@ -0,0 +1,92 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include "core/announce_multiplayer_session.h" +#include "network/network.h" + +class QStandardItemModel; +class Lobby; +class HostRoomWindow; +class ClientRoomWindow; +class DirectConnectWindow; +class ClickableLabel; + +class MultiplayerState : public QWidget { + Q_OBJECT; + +public: + explicit MultiplayerState(QWidget* parent, QStandardItemModel* game_list, QAction* leave_room, + QAction* show_room); + ~MultiplayerState(); + + /** + * Close all open multiplayer related dialogs + */ + void Close(); + + ClickableLabel* GetStatusText() const { + return status_text; + } + + ClickableLabel* GetStatusIcon() const { + return status_icon; + } + + void retranslateUi(); + + /** + * Whether a public room is being hosted or not. + * When this is true, Web Services configuration should be disabled. + */ + bool IsHostingPublicRoom() const; + + void UpdateCredentials(); + + /** + * Updates the multiplayer dialogs with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* game_list); + +public slots: + void OnNetworkStateChanged(const Network::RoomMember::State& state); + void OnNetworkError(const Network::RoomMember::Error& error); + void OnViewLobby(); + void OnCreateRoom(); + bool OnCloseRoom(); + void OnOpenNetworkRoom(); + void OnDirectConnectToRoom(); + void OnAnnounceFailed(const WebService::WebResult&); + void UpdateThemedIcons(); + void ShowNotification(); + void HideNotification(); + +signals: + void NetworkStateChanged(const Network::RoomMember::State&); + void NetworkError(const Network::RoomMember::Error&); + void AnnounceFailed(const WebService::WebResult&); + +private: + Lobby* lobby = nullptr; + HostRoomWindow* host_room = nullptr; + ClientRoomWindow* client_room = nullptr; + DirectConnectWindow* direct_connect = nullptr; + ClickableLabel* status_icon = nullptr; + ClickableLabel* status_text = nullptr; + QStandardItemModel* game_list_model = nullptr; + QAction* leave_room; + QAction* show_room; + std::shared_ptr announce_multiplayer_session; + Network::RoomMember::State current_state = Network::RoomMember::State::Uninitialized; + bool has_mod_perms = false; + Network::RoomMember::CallbackHandle state_callback_handle; + Network::RoomMember::CallbackHandle error_callback_handle; + + bool show_notification = false; +}; + +Q_DECLARE_METATYPE(WebService::WebResult); diff --git a/src/yuzu/multiplayer/validation.h b/src/yuzu/multiplayer/validation.h new file mode 100644 index 0000000000..1c215a1909 --- /dev/null +++ b/src/yuzu/multiplayer/validation.h @@ -0,0 +1,49 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include +#include + +class Validation { +public: + Validation() + : room_name(room_name_regex), nickname(nickname_regex), ip(ip_regex), port(0, 65535) {} + + ~Validation() = default; + + const QValidator* GetRoomName() const { + return &room_name; + } + const QValidator* GetNickname() const { + return &nickname; + } + const QValidator* GetIP() const { + return &ip; + } + const QValidator* GetPort() const { + return &port; + } + +private: + /// room name can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20 + QRegExp room_name_regex = QRegExp(QStringLiteral("^[a-zA-Z0-9._- ]{4,20}$")); + QRegExpValidator room_name; + + /// nickname can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20 + QRegExp nickname_regex = QRegExp(QStringLiteral("^[a-zA-Z0-9._- ]{4,20}$")); + QRegExpValidator nickname; + + /// ipv4 address only + // TODO remove this when we support hostnames in direct connect + QRegExp ip_regex = QRegExp(QStringLiteral( + "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|" + "2[0-4][0-9]|25[0-5])")); + QRegExpValidator ip; + + /// port must be between 0 and 65535 + QIntValidator port; +}; diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h index 2f6948243d..aca1a28e1d 100644 --- a/src/yuzu/uisettings.h +++ b/src/yuzu/uisettings.h @@ -102,6 +102,19 @@ struct Values { Settings::Setting callout_flags{0, "calloutFlags"}; + // multiplayer settings + QString nickname; + QString ip; + QString port; + QString room_nickname; + QString room_name; + quint32 max_player; + QString room_port; + uint host_type; + qulonglong game_id; + QString room_description; + std::pair, std::vector> ban_list; + // logging Settings::Setting show_console{false, "showConsole"}; diff --git a/src/yuzu/util/clickable_label.cpp b/src/yuzu/util/clickable_label.cpp new file mode 100644 index 0000000000..5bde838ca4 --- /dev/null +++ b/src/yuzu/util/clickable_label.cpp @@ -0,0 +1,12 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "yuzu/util/clickable_label.h" + +ClickableLabel::ClickableLabel(QWidget* parent, [[maybe_unused]] Qt::WindowFlags f) + : QLabel(parent) {} + +void ClickableLabel::mouseReleaseEvent([[maybe_unused]] QMouseEvent* event) { + emit clicked(); +} diff --git a/src/yuzu/util/clickable_label.h b/src/yuzu/util/clickable_label.h new file mode 100644 index 0000000000..3c65a74bec --- /dev/null +++ b/src/yuzu/util/clickable_label.h @@ -0,0 +1,22 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include + +class ClickableLabel : public QLabel { + Q_OBJECT + +public: + explicit ClickableLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + ~ClickableLabel() = default; + +signals: + void clicked(); + +protected: + void mouseReleaseEvent(QMouseEvent* event); +}; diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp index cb301e78b1..0194940be4 100644 --- a/src/yuzu_cmd/yuzu.cpp +++ b/src/yuzu_cmd/yuzu.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -29,6 +30,7 @@ #include "core/loader/loader.h" #include "core/telemetry_session.h" #include "input_common/main.h" +#include "network/network.h" #include "video_core/renderer_base.h" #include "yuzu_cmd/config.h" #include "yuzu_cmd/emu_window/emu_window_sdl2.h" @@ -60,6 +62,8 @@ __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; static void PrintHelp(const char* argv0) { std::cout << "Usage: " << argv0 << " [options] \n" + "-m, --multiplayer=nick:password@address:port" + " Nickname, password, address and port for multiplayer\n" "-f, --fullscreen Start in fullscreen mode\n" "-h, --help Display this help and exit\n" "-v, --version Output version information and exit\n" @@ -71,6 +75,107 @@ static void PrintVersion() { std::cout << "yuzu " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl; } +static void OnStateChanged(const Network::RoomMember::State& state) { + switch (state) { + case Network::RoomMember::State::Idle: + LOG_DEBUG(Network, "Network is idle"); + break; + case Network::RoomMember::State::Joining: + LOG_DEBUG(Network, "Connection sequence to room started"); + break; + case Network::RoomMember::State::Joined: + LOG_DEBUG(Network, "Successfully joined to the room"); + break; + case Network::RoomMember::State::Moderator: + LOG_DEBUG(Network, "Successfully joined the room as a moderator"); + break; + default: + break; + } +} + +static void OnNetworkError(const Network::RoomMember::Error& error) { + switch (error) { + case Network::RoomMember::Error::LostConnection: + LOG_DEBUG(Network, "Lost connection to the room"); + break; + case Network::RoomMember::Error::CouldNotConnect: + LOG_ERROR(Network, "Error: Could not connect"); + exit(1); + break; + case Network::RoomMember::Error::NameCollision: + LOG_ERROR( + Network, + "You tried to use the same nickname as another user that is connected to the Room"); + exit(1); + break; + case Network::RoomMember::Error::MacCollision: + LOG_ERROR(Network, "You tried to use the same MAC-Address as another user that is " + "connected to the Room"); + exit(1); + break; + case Network::RoomMember::Error::ConsoleIdCollision: + LOG_ERROR(Network, "Your Console ID conflicted with someone else in the Room"); + exit(1); + break; + case Network::RoomMember::Error::WrongPassword: + LOG_ERROR(Network, "Room replied with: Wrong password"); + exit(1); + break; + case Network::RoomMember::Error::WrongVersion: + LOG_ERROR(Network, + "You are using a different version than the room you are trying to connect to"); + exit(1); + break; + case Network::RoomMember::Error::RoomIsFull: + LOG_ERROR(Network, "The room is full"); + exit(1); + break; + case Network::RoomMember::Error::HostKicked: + LOG_ERROR(Network, "You have been kicked by the host"); + break; + case Network::RoomMember::Error::HostBanned: + LOG_ERROR(Network, "You have been banned by the host"); + break; + case Network::RoomMember::Error::UnknownError: + LOG_ERROR(Network, "UnknownError"); + break; + case Network::RoomMember::Error::PermissionDenied: + LOG_ERROR(Network, "PermissionDenied"); + break; + case Network::RoomMember::Error::NoSuchUser: + LOG_ERROR(Network, "NoSuchUser"); + break; + } +} + +static void OnMessageReceived(const Network::ChatEntry& msg) { + std::cout << std::endl << msg.nickname << ": " << msg.message << std::endl << std::endl; +} + +static void OnStatusMessageReceived(const Network::StatusMessageEntry& msg) { + std::string message; + switch (msg.type) { + case Network::IdMemberJoin: + message = fmt::format("{} has joined", msg.nickname); + break; + case Network::IdMemberLeave: + message = fmt::format("{} has left", msg.nickname); + break; + case Network::IdMemberKicked: + message = fmt::format("{} has been kicked", msg.nickname); + break; + case Network::IdMemberBanned: + message = fmt::format("{} has been banned", msg.nickname); + break; + case Network::IdAddressUnbanned: + message = fmt::format("{} has been unbanned", msg.nickname); + break; + } + if (!message.empty()) + std::cout << std::endl << "* " << message << std::endl << std::endl; +} + /// Application entry point int main(int argc, char** argv) { Common::Log::Initialize(); @@ -92,10 +197,16 @@ int main(int argc, char** argv) { std::optional config_path; std::string program_args; + bool use_multiplayer = false; bool fullscreen = false; + std::string nickname{}; + std::string password{}; + std::string address{}; + u16 port = Network::DefaultRoomPort; static struct option long_options[] = { // clang-format off + {"multiplayer", required_argument, 0, 'm'}, {"fullscreen", no_argument, 0, 'f'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, @@ -109,6 +220,38 @@ int main(int argc, char** argv) { int arg = getopt_long(argc, argv, "g:fhvp::c:", long_options, &option_index); if (arg != -1) { switch (static_cast(arg)) { + case 'm': { + use_multiplayer = true; + const std::string str_arg(optarg); + // regex to check if the format is nickname:password@ip:port + // with optional :password + const std::regex re("^([^:]+)(?::(.+))?@([^:]+)(?::([0-9]+))?$"); + if (!std::regex_match(str_arg, re)) { + std::cout << "Wrong format for option --multiplayer\n"; + PrintHelp(argv[0]); + return 0; + } + + std::smatch match; + std::regex_search(str_arg, match, re); + ASSERT(match.size() == 5); + nickname = match[1]; + password = match[2]; + address = match[3]; + if (!match[4].str().empty()) + port = std::stoi(match[4]); + std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$"); + if (!std::regex_match(nickname, nickname_re)) { + std::cout + << "Nickname is not valid. Must be 4 to 20 alphanumeric characters.\n"; + return 0; + } + if (address.empty()) { + std::cout << "Address to room must not be empty.\n"; + return 0; + } + break; + } case 'f': fullscreen = true; LOG_INFO(Frontend, "Starting in fullscreen mode..."); @@ -215,6 +358,21 @@ int main(int argc, char** argv) { system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL"); + if (use_multiplayer) { + if (auto member = Network::GetRoomMember().lock()) { + member->BindOnChatMessageRecieved(OnMessageReceived); + member->BindOnStatusMessageReceived(OnStatusMessageReceived); + member->BindOnStateChanged(OnStateChanged); + member->BindOnError(OnNetworkError); + LOG_DEBUG(Network, "Start connection to {}:{} with nickname {}", address, port, + nickname); + member->Join(nickname, "", address.c_str(), port, 0, Network::NoPreferredMac, password); + } else { + LOG_ERROR(Network, "Could not access RoomMember"); + return 0; + } + } + // Core is loaded, start the GPU (makes the GPU contexts current to this thread) system.GPU().Start(); system.GetCpuManager().OnGpuReady(); From 1b36542be23ad6c09864d862ad7b61d5db3185c6 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Wed, 6 Jul 2022 04:19:18 +0200 Subject: [PATCH 03/15] yuzu: Hide multiplayer button and room status --- src/yuzu/main.cpp | 5 +++-- src/yuzu/main.ui | 14 -------------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index 5d81326739..f1cc910c04 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -863,8 +863,9 @@ void GMainWindow::InitializeWidgets() { statusBar()->addPermanentWidget(label); } - statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0); - statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0); + // TODO (flTobi): Add the widget when multiplayer is fully implemented + // statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0); + // statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0); tas_label = new QLabel(); tas_label->setObjectName(QStringLiteral("TASlabel")); diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui index 60a8deab1c..cdf31b417d 100644 --- a/src/yuzu/main.ui +++ b/src/yuzu/main.ui @@ -120,20 +120,6 @@ - - - true - - - Multiplayer - - - - - - - - &Tools From 7c3d241f0d03304df2c4d4449c2c8f1f9c7a16d3 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Thu, 7 Jul 2022 04:12:12 +0200 Subject: [PATCH 04/15] common, core: fix -Wmissing-field-initializers --- src/common/announce_multiplayer_room.h | 4 ++-- src/core/announce_multiplayer_session.cpp | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h index 5ca5893ef0..8773ce4dbb 100644 --- a/src/common/announce_multiplayer_room.h +++ b/src/common/announce_multiplayer_room.h @@ -121,11 +121,11 @@ public: const u64 /*game_id*/, const std::string& /*game_name*/) override {} WebService::WebResult Update() override { return WebService::WebResult{WebService::WebResult::Code::NoWebservice, - "WebService is missing"}; + "WebService is missing", ""}; } WebService::WebResult Register() override { return WebService::WebResult{WebService::WebResult::Code::NoWebservice, - "WebService is missing"}; + "WebService is missing", ""}; } void ClearPlayers() override {} RoomList GetRoomList() override { diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp index a680ad202e..aeca87aaca 100644 --- a/src/core/announce_multiplayer_session.cpp +++ b/src/core/announce_multiplayer_session.cpp @@ -34,10 +34,10 @@ WebService::WebResult AnnounceMultiplayerSession::Register() { std::shared_ptr room = Network::GetRoom().lock(); if (!room) { return WebService::WebResult{WebService::WebResult::Code::LibError, - "Network is not initialized"}; + "Network is not initialized", ""}; } if (room->GetState() != Network::Room::State::Open) { - return WebService::WebResult{WebService::WebResult::Code::LibError, "Room is not open"}; + return WebService::WebResult{WebService::WebResult::Code::LibError, "Room is not open", ""}; } UpdateBackendData(room); WebService::WebResult result = backend->Register(); @@ -47,7 +47,7 @@ WebService::WebResult AnnounceMultiplayerSession::Register() { LOG_INFO(WebService, "Room has been registered"); room->SetVerifyUID(result.returned_data); registered = true; - return WebService::WebResult{WebService::WebResult::Code::Success}; + return WebService::WebResult{WebService::WebResult::Code::Success, "", ""}; } void AnnounceMultiplayerSession::Start() { From 7fbd2916a17763b93a8401ba0d560000d56b48cf Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Thu, 7 Jul 2022 16:54:20 +0200 Subject: [PATCH 05/15] core: Fix -Wunused-variable --- src/core/core.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/core.cpp b/src/core/core.cpp index 5df32c1e7d..98fe6d39cc 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -317,7 +317,9 @@ struct System::Impl { perf_stats->BeginSystemFrame(); std::string name = "Unknown Game"; - const Loader::ResultStatus res{app_loader->ReadTitle(name)}; + if (app_loader->ReadTitle(name) != Loader::ResultStatus::Success) { + LOG_ERROR(Core, "Failed to read title for ROM (Error {})", load_result); + } if (auto room_member = Network::GetRoomMember().lock()) { Network::GameInfo game_info; game_info.name = name; From ee5cb9c7b9a5416ae30cdf1e7ecb492ae9b75fc9 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Fri, 8 Jul 2022 04:23:16 +0200 Subject: [PATCH 06/15] web_service: Fix -Wmissing-field-initializers --- src/web_service/announce_room_json.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 31804d2b1c..32249f28e9 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -112,7 +112,7 @@ WebService::WebResult RoomJson::Update() { if (room_id.empty()) { LOG_ERROR(WebService, "Room must be registered to be updated"); return WebService::WebResult{WebService::WebResult::Code::LibError, - "Room is not registered"}; + "Room is not registered", ""}; } nlohmann::json json{{"players", room.members}}; return client.PostJson(fmt::format("/lobby/{}", room_id), json.dump(), false); From ec407bd3f1988c6f5d147307c662703c7bc94751 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Mon, 11 Jul 2022 20:40:57 +0200 Subject: [PATCH 07/15] Fix compilation on linux gcc --- src/network/packet.cpp | 18 +++++++++--------- src/network/room.cpp | 19 ++++++++++--------- src/web_service/announce_room_json.cpp | 8 ++++---- src/web_service/announce_room_json.h | 4 ++-- src/yuzu/multiplayer/lobby_p.h | 6 +++--- src/yuzu/multiplayer/state.cpp | 8 ++++---- 6 files changed, 32 insertions(+), 31 deletions(-) diff --git a/src/network/packet.cpp b/src/network/packet.cpp index 8fc5feabd4..a3c1e16440 100644 --- a/src/network/packet.cpp +++ b/src/network/packet.cpp @@ -14,13 +14,13 @@ namespace Network { #ifndef htonll -u64 htonll(u64 x) { +static u64 htonll(u64 x) { return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32)); } #endif #ifndef ntohll -u64 ntohll(u64 x) { +static u64 ntohll(u64 x) { return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32)); } #endif @@ -67,7 +67,7 @@ Packet::operator bool() const { } Packet& Packet::operator>>(bool& out_data) { - u8 value; + u8 value{}; if (*this >> value) { out_data = (value != 0); } @@ -85,42 +85,42 @@ Packet& Packet::operator>>(u8& out_data) { } Packet& Packet::operator>>(s16& out_data) { - s16 value; + s16 value{}; Read(&value, sizeof(value)); out_data = ntohs(value); return *this; } Packet& Packet::operator>>(u16& out_data) { - u16 value; + u16 value{}; Read(&value, sizeof(value)); out_data = ntohs(value); return *this; } Packet& Packet::operator>>(s32& out_data) { - s32 value; + s32 value{}; Read(&value, sizeof(value)); out_data = ntohl(value); return *this; } Packet& Packet::operator>>(u32& out_data) { - u32 value; + u32 value{}; Read(&value, sizeof(value)); out_data = ntohl(value); return *this; } Packet& Packet::operator>>(s64& out_data) { - s64 value; + s64 value{}; Read(&value, sizeof(value)); out_data = ntohll(value); return *this; } Packet& Packet::operator>>(u64& out_data) { - u64 value; + u64 value{}; Read(&value, sizeof(value)); out_data = ntohll(value); return *this; diff --git a/src/network/room.cpp b/src/network/room.cpp index 5288671469..b82a757491 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -877,8 +877,8 @@ void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) { } else { // Send the data only to the destination client std::lock_guard lock(member_mutex); auto member = std::find_if(members.begin(), members.end(), - [destination_address](const Member& member) -> bool { - return member.mac_address == destination_address; + [destination_address](const Member& member_entry) -> bool { + return member_entry.mac_address == destination_address; }); if (member != members.end()) { enet_peer_send(member->peer, 0, enet_packet); @@ -955,10 +955,10 @@ void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) { { std::lock_guard lock(member_mutex); - auto member = - std::find_if(members.begin(), members.end(), [event](const Member& member) -> bool { - return member.peer == event->peer; - }); + auto member = std::find_if(members.begin(), members.end(), + [event](const Member& member_entry) -> bool { + return member_entry.peer == event->peer; + }); if (member != members.end()) { member->game_info = game_info; @@ -982,9 +982,10 @@ void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) { std::string nickname, username, ip; { std::lock_guard lock(member_mutex); - auto member = std::find_if(members.begin(), members.end(), [client](const Member& member) { - return member.peer == client; - }); + auto member = + std::find_if(members.begin(), members.end(), [client](const Member& member_entry) { + return member_entry.peer == client; + }); if (member != members.end()) { nickname = member->nickname; username = member->user_data.username; diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 32249f28e9..984a59f777 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -11,7 +11,7 @@ namespace AnnounceMultiplayerRoom { -void to_json(nlohmann::json& json, const Room::Member& member) { +static void to_json(nlohmann::json& json, const Room::Member& member) { if (!member.username.empty()) { json["username"] = member.username; } @@ -23,7 +23,7 @@ void to_json(nlohmann::json& json, const Room::Member& member) { json["gameId"] = member.game_id; } -void from_json(const nlohmann::json& json, Room::Member& member) { +static void from_json(const nlohmann::json& json, Room::Member& member) { member.nickname = json.at("nickname").get(); member.game_name = json.at("gameName").get(); member.game_id = json.at("gameId").get(); @@ -36,7 +36,7 @@ void from_json(const nlohmann::json& json, Room::Member& member) { } } -void to_json(nlohmann::json& json, const Room& room) { +static void to_json(nlohmann::json& json, const Room& room) { json["port"] = room.port; json["name"] = room.name; if (!room.description.empty()) { @@ -53,7 +53,7 @@ void to_json(nlohmann::json& json, const Room& room) { } } -void from_json(const nlohmann::json& json, Room& room) { +static void from_json(const nlohmann::json& json, Room& room) { room.verify_UID = json.at("externalGuid").get(); room.ip = json.at("address").get(); room.name = json.at("name").get(); diff --git a/src/web_service/announce_room_json.h b/src/web_service/announce_room_json.h index ac02af5b17..f65c93214a 100644 --- a/src/web_service/announce_room_json.h +++ b/src/web_service/announce_room_json.h @@ -17,8 +17,8 @@ namespace WebService { */ class RoomJson : public AnnounceMultiplayerRoom::Backend { public: - RoomJson(const std::string& host, const std::string& username, const std::string& token) - : client(host, username, token), host(host), username(username), token(token) {} + RoomJson(const std::string& host_, const std::string& username_, const std::string& token_) + : client(host_, username_, token_), host(host_), username(username_), token(token_) {} ~RoomJson() = default; void SetRoomInformation(const std::string& name, const std::string& description, const u16 port, const u32 max_player, const u32 net_version, const bool has_password, diff --git a/src/yuzu/multiplayer/lobby_p.h b/src/yuzu/multiplayer/lobby_p.h index 749ca627f2..afb8b99dc0 100644 --- a/src/yuzu/multiplayer/lobby_p.h +++ b/src/yuzu/multiplayer/lobby_p.h @@ -148,9 +148,9 @@ class LobbyMember { public: LobbyMember() = default; LobbyMember(const LobbyMember& other) = default; - explicit LobbyMember(QString username, QString nickname, u64 title_id, QString game_name) - : username(std::move(username)), nickname(std::move(nickname)), title_id(title_id), - game_name(std::move(game_name)) {} + explicit LobbyMember(QString username_, QString nickname_, u64 title_id_, QString game_name_) + : username(std::move(username_)), nickname(std::move(nickname_)), title_id(title_id_), + game_name(std::move(game_name_)) {} ~LobbyMember() = default; QString GetName() const { diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index b2aaed9828..e96b03e5df 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -19,10 +19,10 @@ #include "yuzu/uisettings.h" #include "yuzu/util/clickable_label.h" -MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_list_model, - QAction* leave_room, QAction* show_room) - : QWidget(parent), game_list_model(game_list_model), leave_room(leave_room), - show_room(show_room) { +MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_list_model_, + QAction* leave_room_, QAction* show_room_) + : QWidget(parent), game_list_model(game_list_model_), leave_room(leave_room_), + show_room(show_room_) { if (auto member = Network::GetRoomMember().lock()) { // register the network structs to use in slots and signals state_callback_handle = member->BindOnStateChanged( From 6c8e45618578de1406c0bf4a7f976bd4903c339c Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Fri, 15 Jul 2022 19:45:35 +0200 Subject: [PATCH 08/15] Address first part of review comments --- .gitmodules | 3 + externals/CMakeLists.txt | 5 + src/core/CMakeLists.txt | 10 +- src/input_common/helpers/udp_protocol.h | 2 +- src/network/room.h | 2 +- src/web_service/CMakeLists.txt | 4 +- src/web_service/verify_user_jwt.cpp | 60 ++++++++++ src/web_service/verify_user_jwt.h | 25 ++++ src/yuzu/CMakeLists.txt | 4 + src/yuzu/configuration/config.cpp | 148 ++++++++++++------------ src/yuzu/multiplayer/chat_room.cpp | 2 +- src/yuzu/multiplayer/direct_connect.cpp | 20 ++-- src/yuzu/multiplayer/host_room.cpp | 45 +++---- src/yuzu/multiplayer/lobby.cpp | 18 +-- src/yuzu/multiplayer/state.cpp | 2 +- src/yuzu/uisettings.h | 22 ++-- 16 files changed, 239 insertions(+), 133 deletions(-) create mode 100644 src/web_service/verify_user_jwt.cpp create mode 100644 src/web_service/verify_user_jwt.h diff --git a/.gitmodules b/.gitmodules index d8e04923ad..26c6735cd9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -46,3 +46,6 @@ [submodule "vcpkg"] path = externals/vcpkg url = https://github.com/Microsoft/vcpkg.git +[submodule "cpp-jwt"] + path = externals/cpp-jwt + url = https://github.com/arun11299/cpp-jwt.git diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt index b4570bb697..5b74a17731 100644 --- a/externals/CMakeLists.txt +++ b/externals/CMakeLists.txt @@ -116,6 +116,11 @@ if (ENABLE_WEB_SERVICE) if (WIN32) target_link_libraries(httplib INTERFACE crypt32 cryptui ws2_32) endif() + + # cpp-jwt + add_library(cpp-jwt INTERFACE) + target_include_directories(cpp-jwt INTERFACE ./cpp-jwt/include) + target_compile_definitions(cpp-jwt INTERFACE CPP_JWT_USE_VENDORED_NLOHMANN_JSON) endif() # Opus diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 48f5c1ee0a..c1cc62a456 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -716,6 +716,11 @@ add_library(core STATIC hle/service/vi/vi_u.h hle/service/wlan/wlan.cpp hle/service/wlan/wlan.h + internal_network/network.cpp + internal_network/network.h + internal_network/network_interface.cpp + internal_network/network_interface.h + internal_network/sockets.h loader/deconstructed_rom_directory.cpp loader/deconstructed_rom_directory.h loader/elf.cpp @@ -743,11 +748,6 @@ add_library(core STATIC memory/dmnt_cheat_vm.h memory.cpp memory.h - internal_network/network.cpp - internal_network/network.h - internal_network/network_interface.cpp - internal_network/network_interface.h - internal_network/sockets.h perf_stats.cpp perf_stats.h reporter.cpp diff --git a/src/input_common/helpers/udp_protocol.h b/src/input_common/helpers/udp_protocol.h index 597f51cd37..889693e731 100644 --- a/src/input_common/helpers/udp_protocol.h +++ b/src/input_common/helpers/udp_protocol.h @@ -85,7 +85,7 @@ enum RegisterFlags : u8 { struct Version {}; /** * Requests the server to send information about what controllers are plugged into the ports - * In citra's case, we only have one controller, so for simplicity's sake, we can just send a + * In yuzu's case, we only have one controller, so for simplicity's sake, we can just send a * request explicitly for the first controller port and leave it at that. In the future it would be * nice to make this configurable */ diff --git a/src/network/room.h b/src/network/room.h index 5d4371c166..df2253bf81 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -13,7 +13,7 @@ namespace Network { -constexpr u32 network_version = 4; ///< The version of this Room and RoomMember +constexpr u32 network_version = 1; ///< The version of this Room and RoomMember constexpr u16 DefaultRoomPort = 24872; diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt index aff81f26d8..753fb6e7ac 100644 --- a/src/web_service/CMakeLists.txt +++ b/src/web_service/CMakeLists.txt @@ -5,10 +5,12 @@ add_library(web_service STATIC telemetry_json.h verify_login.cpp verify_login.h + verify_user_jwt.cpp + verify_user_jwt.h web_backend.cpp web_backend.h web_result.h ) create_target_directory_groups(web_service) -target_link_libraries(web_service PRIVATE common network nlohmann_json::nlohmann_json httplib) +target_link_libraries(web_service PRIVATE common network nlohmann_json::nlohmann_json httplib cpp-jwt) diff --git a/src/web_service/verify_user_jwt.cpp b/src/web_service/verify_user_jwt.cpp new file mode 100644 index 0000000000..78fe7bed5a --- /dev/null +++ b/src/web_service/verify_user_jwt.cpp @@ -0,0 +1,60 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include +#include +#include "common/logging/log.h" +#include "web_service/verify_user_jwt.h" +#include "web_service/web_backend.h" +#include "web_service/web_result.h" + +namespace WebService { + +static std::string public_key; +std::string GetPublicKey(const std::string& host) { + if (public_key.empty()) { + Client client(host, "", ""); // no need for credentials here + public_key = client.GetPlain("/jwt/external/key.pem", true).returned_data; + if (public_key.empty()) { + LOG_ERROR(WebService, "Could not fetch external JWT public key, verification may fail"); + } else { + LOG_INFO(WebService, "Fetched external JWT public key (size={})", public_key.size()); + } + } + return public_key; +} + +VerifyUserJWT::VerifyUserJWT(const std::string& host) : pub_key(GetPublicKey(host)) {} + +Network::VerifyUser::UserData VerifyUserJWT::LoadUserData(const std::string& verify_UID, + const std::string& token) { + const std::string audience = fmt::format("external-{}", verify_UID); + using namespace jwt::params; + std::error_code error; + auto decoded = + jwt::decode(token, algorithms({"rs256"}), error, secret(pub_key), issuer("yuzu-core"), + aud(audience), validate_iat(true), validate_jti(true)); + if (error) { + LOG_INFO(WebService, "Verification failed: category={}, code={}, message={}", + error.category().name(), error.value(), error.message()); + return {}; + } + Network::VerifyUser::UserData user_data{}; + if (decoded.payload().has_claim("username")) { + user_data.username = decoded.payload().get_claim_value("username"); + } + if (decoded.payload().has_claim("displayName")) { + user_data.display_name = decoded.payload().get_claim_value("displayName"); + } + if (decoded.payload().has_claim("avatarUrl")) { + user_data.avatar_url = decoded.payload().get_claim_value("avatarUrl"); + } + if (decoded.payload().has_claim("roles")) { + auto roles = decoded.payload().get_claim_value>("roles"); + user_data.moderator = std::find(roles.begin(), roles.end(), "moderator") != roles.end(); + } + return user_data; +} + +} // namespace WebService diff --git a/src/web_service/verify_user_jwt.h b/src/web_service/verify_user_jwt.h new file mode 100644 index 0000000000..826e01eed7 --- /dev/null +++ b/src/web_service/verify_user_jwt.h @@ -0,0 +1,25 @@ +// Copyright 2018 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include +#include "network/verify_user.h" +#include "web_service/web_backend.h" + +namespace WebService { + +class VerifyUserJWT final : public Network::VerifyUser::Backend { +public: + VerifyUserJWT(const std::string& host); + ~VerifyUserJWT() = default; + + Network::VerifyUser::UserData LoadUserData(const std::string& verify_UID, + const std::string& token) override; + +private: + std::string pub_key; +}; + +} // namespace WebService diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt index f3cad8f311..66873143e3 100644 --- a/src/yuzu/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -326,6 +326,10 @@ if (USE_DISCORD_PRESENCE) target_compile_definitions(yuzu PRIVATE -DUSE_DISCORD_PRESENCE) endif() +if (ENABLE_WEB_SERVICE) + target_compile_definitions(yuzu PRIVATE -DENABLE_WEB_SERVICE) +endif() + if (YUZU_USE_QT_WEB_ENGINE) target_link_libraries(yuzu PRIVATE Qt::WebEngineCore Qt::WebEngineWidgets) target_compile_definitions(yuzu PRIVATE -DYUZU_USE_QT_WEB_ENGINE) diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp index 7c11e2c034..3b22102a80 100644 --- a/src/yuzu/configuration/config.cpp +++ b/src/yuzu/configuration/config.cpp @@ -585,48 +585,6 @@ void Config::ReadMiscellaneousValues() { qt_config->endGroup(); } -void Config::ReadMultiplayerValues() { - qt_config->beginGroup(QStringLiteral("Multiplayer")); - - UISettings::values.nickname = ReadSetting(QStringLiteral("nickname"), QString{}).toString(); - UISettings::values.ip = ReadSetting(QStringLiteral("ip"), QString{}).toString(); - UISettings::values.port = - ReadSetting(QStringLiteral("port"), Network::DefaultRoomPort).toString(); - UISettings::values.room_nickname = - ReadSetting(QStringLiteral("room_nickname"), QString{}).toString(); - UISettings::values.room_name = ReadSetting(QStringLiteral("room_name"), QString{}).toString(); - UISettings::values.room_port = - ReadSetting(QStringLiteral("room_port"), QStringLiteral("24872")).toString(); - bool ok; - UISettings::values.host_type = ReadSetting(QStringLiteral("host_type"), 0).toUInt(&ok); - if (!ok) { - UISettings::values.host_type = 0; - } - UISettings::values.max_player = ReadSetting(QStringLiteral("max_player"), 8).toUInt(); - UISettings::values.game_id = ReadSetting(QStringLiteral("game_id"), 0).toULongLong(); - UISettings::values.room_description = - ReadSetting(QStringLiteral("room_description"), QString{}).toString(); - // Read ban list back - int size = qt_config->beginReadArray(QStringLiteral("username_ban_list")); - UISettings::values.ban_list.first.resize(size); - for (int i = 0; i < size; ++i) { - qt_config->setArrayIndex(i); - UISettings::values.ban_list.first[i] = - ReadSetting(QStringLiteral("username")).toString().toStdString(); - } - qt_config->endArray(); - size = qt_config->beginReadArray(QStringLiteral("ip_ban_list")); - UISettings::values.ban_list.second.resize(size); - for (int i = 0; i < size; ++i) { - qt_config->setArrayIndex(i); - UISettings::values.ban_list.second[i] = - ReadSetting(QStringLiteral("ip")).toString().toStdString(); - } - qt_config->endArray(); - - qt_config->endGroup(); -} - void Config::ReadPathValues() { qt_config->beginGroup(QStringLiteral("Paths")); @@ -904,6 +862,42 @@ void Config::ReadWebServiceValues() { qt_config->endGroup(); } +void Config::ReadMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + ReadBasicSetting(UISettings::values.multiplayer_nickname); + ReadBasicSetting(UISettings::values.multiplayer_ip); + ReadBasicSetting(UISettings::values.multiplayer_port); + ReadBasicSetting(UISettings::values.multiplayer_room_nickname); + ReadBasicSetting(UISettings::values.multiplayer_room_name); + ReadBasicSetting(UISettings::values.multiplayer_room_port); + ReadBasicSetting(UISettings::values.multiplayer_host_type); + ReadBasicSetting(UISettings::values.multiplayer_port); + ReadBasicSetting(UISettings::values.multiplayer_max_player); + ReadBasicSetting(UISettings::values.multiplayer_game_id); + ReadBasicSetting(UISettings::values.multiplayer_room_description); + + // Read ban list back + int size = qt_config->beginReadArray(QStringLiteral("username_ban_list")); + UISettings::values.multiplayer_ban_list.first.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.multiplayer_ban_list.first[i] = + ReadSetting(QStringLiteral("username")).toString().toStdString(); + } + qt_config->endArray(); + size = qt_config->beginReadArray(QStringLiteral("ip_ban_list")); + UISettings::values.multiplayer_ban_list.second.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.multiplayer_ban_list.second[i] = + ReadSetting(QStringLiteral("ip")).toString().toStdString(); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + void Config::ReadValues() { if (global) { ReadControlValues(); @@ -920,6 +914,7 @@ void Config::ReadValues() { ReadRendererValues(); ReadAudioValues(); ReadSystemValues(); + ReadMultiplayerValues(); } void Config::SavePlayerValue(std::size_t player_index) { @@ -1069,6 +1064,7 @@ void Config::SaveValues() { SaveRendererValues(); SaveAudioValues(); SaveSystemValues(); + SaveMultiplayerValues(); } void Config::SaveAudioValues() { @@ -1205,40 +1201,6 @@ void Config::SaveMiscellaneousValues() { qt_config->endGroup(); } -void Config::SaveMultiplayerValues() { - qt_config->beginGroup(QStringLiteral("Multiplayer")); - - WriteSetting(QStringLiteral("nickname"), UISettings::values.nickname, QString{}); - WriteSetting(QStringLiteral("ip"), UISettings::values.ip, QString{}); - WriteSetting(QStringLiteral("port"), UISettings::values.port, Network::DefaultRoomPort); - WriteSetting(QStringLiteral("room_nickname"), UISettings::values.room_nickname, QString{}); - WriteSetting(QStringLiteral("room_name"), UISettings::values.room_name, QString{}); - WriteSetting(QStringLiteral("room_port"), UISettings::values.room_port, - QStringLiteral("24872")); - WriteSetting(QStringLiteral("host_type"), UISettings::values.host_type, 0); - WriteSetting(QStringLiteral("max_player"), UISettings::values.max_player, 8); - WriteSetting(QStringLiteral("game_id"), UISettings::values.game_id, 0); - WriteSetting(QStringLiteral("room_description"), UISettings::values.room_description, - QString{}); - // Write ban list - qt_config->beginWriteArray(QStringLiteral("username_ban_list")); - for (std::size_t i = 0; i < UISettings::values.ban_list.first.size(); ++i) { - qt_config->setArrayIndex(static_cast(i)); - WriteSetting(QStringLiteral("username"), - QString::fromStdString(UISettings::values.ban_list.first[i])); - } - qt_config->endArray(); - qt_config->beginWriteArray(QStringLiteral("ip_ban_list")); - for (std::size_t i = 0; i < UISettings::values.ban_list.second.size(); ++i) { - qt_config->setArrayIndex(static_cast(i)); - WriteSetting(QStringLiteral("ip"), - QString::fromStdString(UISettings::values.ban_list.second[i])); - } - qt_config->endArray(); - - qt_config->endGroup(); -} - void Config::SavePathValues() { qt_config->beginGroup(QStringLiteral("Paths")); @@ -1490,6 +1452,40 @@ void Config::SaveWebServiceValues() { qt_config->endGroup(); } +void Config::SaveMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + WriteBasicSetting(UISettings::values.multiplayer_nickname); + WriteBasicSetting(UISettings::values.multiplayer_ip); + WriteBasicSetting(UISettings::values.multiplayer_port); + WriteBasicSetting(UISettings::values.multiplayer_room_nickname); + WriteBasicSetting(UISettings::values.multiplayer_room_name); + WriteBasicSetting(UISettings::values.multiplayer_room_port); + WriteBasicSetting(UISettings::values.multiplayer_host_type); + WriteBasicSetting(UISettings::values.multiplayer_port); + WriteBasicSetting(UISettings::values.multiplayer_max_player); + WriteBasicSetting(UISettings::values.multiplayer_game_id); + WriteBasicSetting(UISettings::values.multiplayer_room_description); + + // Write ban list + qt_config->beginWriteArray(QStringLiteral("username_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.first.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("username"), + QString::fromStdString(UISettings::values.multiplayer_ban_list.first[i])); + } + qt_config->endArray(); + qt_config->beginWriteArray(QStringLiteral("ip_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.second.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("ip"), + QString::fromStdString(UISettings::values.multiplayer_ban_list.second[i])); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + QVariant Config::ReadSetting(const QString& name) const { return qt_config->value(name); } diff --git a/src/yuzu/multiplayer/chat_room.cpp b/src/yuzu/multiplayer/chat_room.cpp index 6dd4bc36d6..7048ee1fce 100644 --- a/src/yuzu/multiplayer/chat_room.cpp +++ b/src/yuzu/multiplayer/chat_room.cpp @@ -390,7 +390,7 @@ void ChatRoom::SetPlayerList(const Network::RoomMember::MemberList& member_list) return; QPixmap pixmap; if (!pixmap.loadFromData(reinterpret_cast(result.data()), - result.size())) + static_cast(result.size()))) return; icon_cache[avatar_url] = pixmap.scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); diff --git a/src/yuzu/multiplayer/direct_connect.cpp b/src/yuzu/multiplayer/direct_connect.cpp index 27741d657f..837baf85cc 100644 --- a/src/yuzu/multiplayer/direct_connect.cpp +++ b/src/yuzu/multiplayer/direct_connect.cpp @@ -32,15 +32,15 @@ DirectConnectWindow::DirectConnectWindow(QWidget* parent) connect(watcher, &QFutureWatcher::finished, this, &DirectConnectWindow::OnConnection); ui->nickname->setValidator(validation.GetNickname()); - ui->nickname->setText(UISettings::values.nickname); + ui->nickname->setText(UISettings::values.multiplayer_nickname.GetValue()); if (ui->nickname->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { // Use yuzu Web Service user name as nickname by default ui->nickname->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); } ui->ip->setValidator(validation.GetIP()); - ui->ip->setText(UISettings::values.ip); + ui->ip->setText(UISettings::values.multiplayer_ip.GetValue()); ui->port->setValidator(validation.GetPort()); - ui->port->setText(UISettings::values.port); + ui->port->setText(QString::number(UISettings::values.multiplayer_port.GetValue())); // TODO(jroweboy): Show or hide the connection options based on the current value of the combo // box. Add this back in when the traversal server support is added. @@ -86,16 +86,18 @@ void DirectConnectWindow::Connect() { } // Store settings - UISettings::values.nickname = ui->nickname->text(); - UISettings::values.ip = ui->ip->text(); - UISettings::values.port = (ui->port->isModified() && !ui->port->text().isEmpty()) - ? ui->port->text() - : UISettings::values.port; + UISettings::values.multiplayer_nickname = ui->nickname->text(); + UISettings::values.multiplayer_ip = ui->ip->text(); + if (ui->port->isModified() && !ui->port->text().isEmpty()) { + UISettings::values.multiplayer_port = ui->port->text().toInt(); + } else { + UISettings::values.multiplayer_port = UISettings::values.multiplayer_port.GetDefault(); + } // attempt to connect in a different thread QFuture f = QtConcurrent::run([&] { if (auto room_member = Network::GetRoomMember().lock()) { - auto port = UISettings::values.port.toUInt(); + auto port = UISettings::values.multiplayer_port.GetValue(); room_member->Join(ui->nickname->text().toStdString(), "", ui->ip->text().toStdString().c_str(), port, 0, Network::NoPreferredMac, ui->password->text().toStdString().c_str()); diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp index 1b73e2bec5..5470b8b86e 100644 --- a/src/yuzu/multiplayer/host_room.cpp +++ b/src/yuzu/multiplayer/host_room.cpp @@ -51,23 +51,24 @@ HostRoomWindow::HostRoomWindow(QWidget* parent, QStandardItemModel* list, connect(ui->host, &QPushButton::clicked, this, &HostRoomWindow::Host); // Restore the settings: - ui->username->setText(UISettings::values.room_nickname); + ui->username->setText(UISettings::values.multiplayer_room_nickname.GetValue()); if (ui->username->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { // Use yuzu Web Service user name as nickname by default ui->username->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); } - ui->room_name->setText(UISettings::values.room_name); - ui->port->setText(UISettings::values.room_port); - ui->max_player->setValue(UISettings::values.max_player); - int index = UISettings::values.host_type; + ui->room_name->setText(UISettings::values.multiplayer_room_name.GetValue()); + ui->port->setText(QString::number(UISettings::values.multiplayer_room_port.GetValue())); + ui->max_player->setValue(UISettings::values.multiplayer_max_player.GetValue()); + int index = UISettings::values.multiplayer_host_type.GetValue(); if (index < ui->host_type->count()) { ui->host_type->setCurrentIndex(index); } - index = ui->game_list->findData(UISettings::values.game_id, GameListItemPath::ProgramIdRole); + index = ui->game_list->findData(UISettings::values.multiplayer_game_id.GetValue(), + GameListItemPath::ProgramIdRole); if (index != -1) { ui->game_list->setCurrentIndex(index); } - ui->room_description->setText(UISettings::values.room_description); + ui->room_description->setText(UISettings::values.multiplayer_room_description.GetValue()); } HostRoomWindow::~HostRoomWindow() = default; @@ -91,7 +92,8 @@ std::unique_ptr HostRoomWindow::CreateVerifyBacken std::unique_ptr verify_backend; if (use_validation) { #ifdef ENABLE_WEB_SERVICE - verify_backend = std::make_unique(Settings::values.web_api_url); + verify_backend = + std::make_unique(Settings::values.web_api_url.GetValue()); #else verify_backend = std::make_unique(); #endif @@ -137,7 +139,7 @@ void HostRoomWindow::Host() { const bool is_public = ui->host_type->currentIndex() == 0; Network::Room::BanList ban_list{}; if (ui->load_ban_list->isChecked()) { - ban_list = UISettings::values.ban_list; + ban_list = UISettings::values.multiplayer_ban_list; } if (auto room = Network::GetRoom().lock()) { bool created = room->Create( @@ -181,8 +183,9 @@ void HostRoomWindow::Host() { std::string token; #ifdef ENABLE_WEB_SERVICE if (is_public) { - WebService::Client client(Settings::values.web_api_url, Settings::values.yuzu_username, - Settings::values.yuzu_token); + WebService::Client client(Settings::values.web_api_url.GetValue(), + Settings::values.yuzu_username.GetValue(), + Settings::values.yuzu_token.GetValue()); if (auto room = Network::GetRoom().lock()) { token = client.GetExternalJWT(room->GetVerifyUID()).returned_data; } @@ -198,17 +201,19 @@ void HostRoomWindow::Host() { Network::NoPreferredMac, password, token); // Store settings - UISettings::values.room_nickname = ui->username->text(); - UISettings::values.room_name = ui->room_name->text(); - UISettings::values.game_id = + UISettings::values.multiplayer_room_nickname = ui->username->text(); + UISettings::values.multiplayer_room_name = ui->room_name->text(); + UISettings::values.multiplayer_game_id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong(); - UISettings::values.max_player = ui->max_player->value(); + UISettings::values.multiplayer_max_player = ui->max_player->value(); - UISettings::values.host_type = ui->host_type->currentIndex(); - UISettings::values.room_port = (ui->port->isModified() && !ui->port->text().isEmpty()) - ? ui->port->text() - : QString::number(Network::DefaultRoomPort); - UISettings::values.room_description = ui->room_description->toPlainText(); + UISettings::values.multiplayer_host_type = ui->host_type->currentIndex(); + if (ui->port->isModified() && !ui->port->text().isEmpty()) { + UISettings::values.multiplayer_room_port = ui->port->text().toInt(); + } else { + UISettings::values.multiplayer_room_port = Network::DefaultRoomPort; + } + UISettings::values.multiplayer_room_description = ui->room_description->toPlainText(); ui->host->setEnabled(true); close(); } diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index fcaa7b517f..364b4605e6 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -56,7 +56,7 @@ Lobby::Lobby(QWidget* parent, QStandardItemModel* list, ui->room_list->setContextMenuPolicy(Qt::CustomContextMenu); ui->nickname->setValidator(validation.GetNickname()); - ui->nickname->setText(UISettings::values.nickname); + ui->nickname->setText(UISettings::values.multiplayer_nickname.GetValue()); if (ui->nickname->text().isEmpty() && !Settings::values.yuzu_username.GetValue().empty()) { // Use yuzu Web Service user name as nickname by default ui->nickname->setText(QString::fromStdString(Settings::values.yuzu_username.GetValue())); @@ -154,9 +154,11 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_UID] { std::string token; #ifdef ENABLE_WEB_SERVICE - if (!Settings::values.yuzu_username.empty() && !Settings::values.yuzu_token.empty()) { - WebService::Client client(Settings::values.web_api_url, Settings::values.yuzu_username, - Settings::values.yuzu_token); + if (!Settings::values.yuzu_username.GetValue().empty() && + !Settings::values.yuzu_token.GetValue().empty()) { + WebService::Client client(Settings::values.web_api_url.GetValue(), + Settings::values.yuzu_username.GetValue(), + Settings::values.yuzu_token.GetValue()); token = client.GetExternalJWT(verify_UID).returned_data; if (token.empty()) { LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); @@ -175,9 +177,11 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { // TODO(jroweboy): disable widgets and display a connecting while we wait // Save settings - UISettings::values.nickname = ui->nickname->text(); - UISettings::values.ip = proxy->data(connection_index, LobbyItemHost::HostIPRole).toString(); - UISettings::values.port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toString(); + UISettings::values.multiplayer_nickname = ui->nickname->text(); + UISettings::values.multiplayer_ip = + proxy->data(connection_index, LobbyItemHost::HostIPRole).toString(); + UISettings::values.multiplayer_port = + proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt(); } void Lobby::ResetModel() { diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index e96b03e5df..ee138739b2 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -232,7 +232,7 @@ bool MultiplayerState::OnCloseRoom() { return true; } // Save ban list - UISettings::values.ban_list = std::move(room->GetBanList()); + UISettings::values.multiplayer_ban_list = std::move(room->GetBanList()); room->Destroy(); announce_multiplayer_session->Stop(); diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h index aca1a28e1d..83a6cffa3e 100644 --- a/src/yuzu/uisettings.h +++ b/src/yuzu/uisettings.h @@ -103,17 +103,17 @@ struct Values { Settings::Setting callout_flags{0, "calloutFlags"}; // multiplayer settings - QString nickname; - QString ip; - QString port; - QString room_nickname; - QString room_name; - quint32 max_player; - QString room_port; - uint host_type; - qulonglong game_id; - QString room_description; - std::pair, std::vector> ban_list; + Settings::Setting multiplayer_nickname{QStringLiteral("yuzu"), "nickname"}; + Settings::Setting multiplayer_ip{{}, "ip"}; + Settings::SwitchableSetting multiplayer_port{24872, 0, 65535, "port"}; + Settings::Setting multiplayer_room_nickname{{}, "room_nickname"}; + Settings::Setting multiplayer_room_name{{}, "room_name"}; + Settings::SwitchableSetting multiplayer_max_player{8, 0, 8, "max_player"}; + Settings::SwitchableSetting multiplayer_room_port{24872, 0, 65535, "room_port"}; + Settings::SwitchableSetting multiplayer_host_type{0, 0, 1, "host_type"}; + Settings::Setting multiplayer_game_id{{}, "game_id"}; + Settings::Setting multiplayer_room_description{{}, "room_description"}; + std::pair, std::vector> multiplayer_ban_list; // logging Settings::Setting show_console{false, "showConsole"}; From 4b404191cf054ec3206676f1fccc452bc0a0e223 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Fri, 15 Jul 2022 21:11:09 +0200 Subject: [PATCH 09/15] Address second part of review comments --- src/common/announce_multiplayer_room.h | 51 +++++++++++-------- src/core/announce_multiplayer_session.cpp | 5 +- src/network/room.cpp | 7 +-- src/network/room.h | 32 +++--------- src/network/room_member.h | 4 ++ src/web_service/announce_room_json.cpp | 62 ++++++++++------------- src/web_service/announce_room_json.h | 5 +- src/web_service/verify_user_jwt.cpp | 10 +++- src/yuzu/multiplayer/lobby.cpp | 19 +++---- 9 files changed, 92 insertions(+), 103 deletions(-) diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h index 8773ce4dbb..2ff38b6cfc 100644 --- a/src/common/announce_multiplayer_room.h +++ b/src/common/announce_multiplayer_room.h @@ -15,27 +15,40 @@ namespace AnnounceMultiplayerRoom { using MacAddress = std::array; +struct Member { + std::string username; + std::string nickname; + std::string display_name; + std::string avatar_url; + MacAddress mac_address; + std::string game_name; + u64 game_id; +}; + +struct RoomInformation { + std::string name; ///< Name of the server + std::string description; ///< Server description + u32 member_slots; ///< Maximum number of members in this room + u16 port; ///< The port of this room + std::string preferred_game; ///< Game to advertise that you want to play + u64 preferred_game_id; ///< Title ID for the advertised game + std::string host_username; ///< Forum username of the host + bool enable_yuzu_mods; ///< Allow yuzu Moderators to moderate on this room +}; + +struct GameInfo { + std::string name{""}; + u64 id{0}; +}; + struct Room { - struct Member { - std::string username; - std::string nickname; - std::string avatar_url; - MacAddress mac_address; - std::string game_name; - u64 game_id; - }; + RoomInformation information; + std::string id; std::string verify_UID; ///< UID used for verification - std::string name; - std::string description; - std::string owner; std::string ip; - u16 port; - u32 max_player; u32 net_version; bool has_password; - std::string preferred_game; - u64 preferred_game_id; std::vector members; }; @@ -71,9 +84,7 @@ public: * @param game_id The title id of the game the player plays * @param game_name The name of the game the player plays */ - virtual void AddPlayer(const std::string& username, const std::string& nickname, - const std::string& avatar_url, const MacAddress& mac_address, - const u64 game_id, const std::string& game_name) = 0; + virtual void AddPlayer(const Member& member) = 0; /** * Updates the data in the announce service. Re-register the room when required. @@ -116,9 +127,7 @@ public: const u16 /*port*/, const u32 /*max_player*/, const u32 /*net_version*/, const bool /*has_password*/, const std::string& /*preferred_game*/, const u64 /*preferred_game_id*/) override {} - void AddPlayer(const std::string& /*username*/, const std::string& /*nickname*/, - const std::string& /*avatar_url*/, const MacAddress& /*mac_address*/, - const u64 /*game_id*/, const std::string& /*game_name*/) override {} + void AddPlayer(const Member& /*member*/) override {} WebService::WebResult Update() override { return WebService::WebResult{WebService::WebResult::Code::NoWebservice, "WebService is missing", ""}; diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp index aeca87aaca..f8aa9bb0b2 100644 --- a/src/core/announce_multiplayer_session.cpp +++ b/src/core/announce_multiplayer_session.cpp @@ -88,15 +88,14 @@ AnnounceMultiplayerSession::~AnnounceMultiplayerSession() { void AnnounceMultiplayerSession::UpdateBackendData(std::shared_ptr room) { Network::RoomInformation room_information = room->GetRoomInformation(); - std::vector memberlist = room->GetRoomMemberList(); + std::vector memberlist = room->GetRoomMemberList(); backend->SetRoomInformation( room_information.name, room_information.description, room_information.port, room_information.member_slots, Network::network_version, room->HasPassword(), room_information.preferred_game, room_information.preferred_game_id); backend->ClearPlayers(); for (const auto& member : memberlist) { - backend->AddPlayer(member.username, member.nickname, member.avatar_url, member.mac_address, - member.game_info.id, member.game_info.name); + backend->AddPlayer(member); } } diff --git a/src/network/room.cpp b/src/network/room.cpp index b82a757491..fe55d194c4 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -1066,8 +1066,8 @@ Room::BanList Room::GetBanList() const { return {room_impl->username_ban_list, room_impl->ip_ban_list}; } -std::vector Room::GetRoomMemberList() const { - std::vector member_list; +std::vector Room::GetRoomMemberList() const { + std::vector member_list; std::lock_guard lock(room_impl->member_mutex); for (const auto& member_impl : room_impl->members) { Member member; @@ -1076,7 +1076,8 @@ std::vector Room::GetRoomMemberList() const { member.display_name = member_impl.user_data.display_name; member.avatar_url = member_impl.user_data.avatar_url; member.mac_address = member_impl.mac_address; - member.game_info = member_impl.game_info; + member.game_name = member_impl.game_info.name; + member.game_id = member_impl.game_info.id; member_list.push_back(member); } return member_list; diff --git a/src/network/room.h b/src/network/room.h index df2253bf81..f282a5ac32 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -8,11 +8,17 @@ #include #include #include +#include "common/announce_multiplayer_room.h" #include "common/common_types.h" #include "network/verify_user.h" namespace Network { +using AnnounceMultiplayerRoom::GameInfo; +using AnnounceMultiplayerRoom::MacAddress; +using AnnounceMultiplayerRoom::Member; +using AnnounceMultiplayerRoom::RoomInformation; + constexpr u32 network_version = 1; ///< The version of this Room and RoomMember constexpr u16 DefaultRoomPort = 24872; @@ -24,23 +30,6 @@ static constexpr u32 MaxConcurrentConnections = 254; constexpr std::size_t NumChannels = 1; // Number of channels used for the connection -struct RoomInformation { - std::string name; ///< Name of the server - std::string description; ///< Server description - u32 member_slots; ///< Maximum number of members in this room - u16 port; ///< The port of this room - std::string preferred_game; ///< Game to advertise that you want to play - u64 preferred_game_id; ///< Title ID for the advertised game - std::string host_username; ///< Forum username of the host - bool enable_yuzu_mods; ///< Allow yuzu Moderators to moderate on this room -}; - -struct GameInfo { - std::string name{""}; - u64 id{0}; -}; - -using MacAddress = std::array; /// A special MAC address that tells the room we're joining to assign us a MAC address /// automatically. constexpr MacAddress NoPreferredMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; @@ -95,15 +84,6 @@ public: Closed, ///< The room is not opened and can not accept connections. }; - struct Member { - std::string nickname; ///< The nickname of the member. - std::string username; ///< The web services username of the member. Can be empty. - std::string display_name; ///< The web services display name of the member. Can be empty. - std::string avatar_url; ///< Url to the member's avatar. Can be empty. - GameInfo game_info; ///< The current game of the member - MacAddress mac_address; ///< The assigned mac address of the member. - }; - Room(); ~Room(); diff --git a/src/network/room_member.h b/src/network/room_member.h index ee1c921d46..c835ba8635 100644 --- a/src/network/room_member.h +++ b/src/network/room_member.h @@ -9,11 +9,15 @@ #include #include #include +#include "common/announce_multiplayer_room.h" #include "common/common_types.h" #include "network/room.h" namespace Network { +using AnnounceMultiplayerRoom::GameInfo; +using AnnounceMultiplayerRoom::RoomInformation; + /// Information about the received WiFi packets. /// Acts as our own 802.11 header. struct WifiPacket { diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 984a59f777..84220b851a 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -11,7 +11,7 @@ namespace AnnounceMultiplayerRoom { -static void to_json(nlohmann::json& json, const Room::Member& member) { +static void to_json(nlohmann::json& json, const Member& member) { if (!member.username.empty()) { json["username"] = member.username; } @@ -23,7 +23,7 @@ static void to_json(nlohmann::json& json, const Room::Member& member) { json["gameId"] = member.game_id; } -static void from_json(const nlohmann::json& json, Room::Member& member) { +static void from_json(const nlohmann::json& json, Member& member) { member.nickname = json.at("nickname").get(); member.game_name = json.at("gameName").get(); member.game_id = json.at("gameId").get(); @@ -37,14 +37,14 @@ static void from_json(const nlohmann::json& json, Room::Member& member) { } static void to_json(nlohmann::json& json, const Room& room) { - json["port"] = room.port; - json["name"] = room.name; - if (!room.description.empty()) { - json["description"] = room.description; + json["port"] = room.information.port; + json["name"] = room.information.name; + if (!room.information.description.empty()) { + json["description"] = room.information.description; } - json["preferredGameName"] = room.preferred_game; - json["preferredGameId"] = room.preferred_game_id; - json["maxPlayers"] = room.max_player; + json["preferredGameName"] = room.information.preferred_game; + json["preferredGameId"] = room.information.preferred_game_id; + json["maxPlayers"] = room.information.member_slots; json["netVersion"] = room.net_version; json["hasPassword"] = room.has_password; if (room.members.size() > 0) { @@ -56,22 +56,22 @@ static void to_json(nlohmann::json& json, const Room& room) { static void from_json(const nlohmann::json& json, Room& room) { room.verify_UID = json.at("externalGuid").get(); room.ip = json.at("address").get(); - room.name = json.at("name").get(); + room.information.name = json.at("name").get(); try { - room.description = json.at("description").get(); + room.information.description = json.at("description").get(); } catch (const nlohmann::detail::out_of_range&) { - room.description = ""; - LOG_DEBUG(Network, "Room \'{}\' doesn't contain a description", room.name); + room.information.description = ""; + LOG_DEBUG(Network, "Room \'{}\' doesn't contain a description", room.information.name); } - room.owner = json.at("owner").get(); - room.port = json.at("port").get(); - room.preferred_game = json.at("preferredGameName").get(); - room.preferred_game_id = json.at("preferredGameId").get(); - room.max_player = json.at("maxPlayers").get(); + room.information.host_username = json.at("owner").get(); + room.information.port = json.at("port").get(); + room.information.preferred_game = json.at("preferredGameName").get(); + room.information.preferred_game_id = json.at("preferredGameId").get(); + room.information.member_slots = json.at("maxPlayers").get(); room.net_version = json.at("netVersion").get(); room.has_password = json.at("hasPassword").get(); try { - room.members = json.at("players").get>(); + room.members = json.at("players").get>(); } catch (const nlohmann::detail::out_of_range& e) { LOG_DEBUG(Network, "Out of range {}", e.what()); } @@ -85,26 +85,16 @@ void RoomJson::SetRoomInformation(const std::string& name, const std::string& de const u16 port, const u32 max_player, const u32 net_version, const bool has_password, const std::string& preferred_game, const u64 preferred_game_id) { - room.name = name; - room.description = description; - room.port = port; - room.max_player = max_player; + room.information.name = name; + room.information.description = description; + room.information.port = port; + room.information.member_slots = max_player; room.net_version = net_version; room.has_password = has_password; - room.preferred_game = preferred_game; - room.preferred_game_id = preferred_game_id; + room.information.preferred_game = preferred_game; + room.information.preferred_game_id = preferred_game_id; } -void RoomJson::AddPlayer(const std::string& username_, const std::string& nickname_, - const std::string& avatar_url, - const AnnounceMultiplayerRoom::MacAddress& mac_address, const u64 game_id, - const std::string& game_name) { - AnnounceMultiplayerRoom::Room::Member member; - member.username = username_; - member.nickname = nickname_; - member.avatar_url = avatar_url; - member.mac_address = mac_address; - member.game_id = game_id; - member.game_name = game_name; +void RoomJson::AddPlayer(const AnnounceMultiplayerRoom::Member& member) { room.members.push_back(member); } diff --git a/src/web_service/announce_room_json.h b/src/web_service/announce_room_json.h index f65c93214a..811c76fbd2 100644 --- a/src/web_service/announce_room_json.h +++ b/src/web_service/announce_room_json.h @@ -24,10 +24,7 @@ public: const u32 max_player, const u32 net_version, const bool has_password, const std::string& preferred_game, const u64 preferred_game_id) override; - void AddPlayer(const std::string& username_, const std::string& nickname_, - const std::string& avatar_url, - const AnnounceMultiplayerRoom::MacAddress& mac_address, const u64 game_id, - const std::string& game_name) override; + void AddPlayer(const AnnounceMultiplayerRoom::Member& member) override; WebResult Update() override; WebResult Register() override; void ClearPlayers() override; diff --git a/src/web_service/verify_user_jwt.cpp b/src/web_service/verify_user_jwt.cpp index 78fe7bed5a..3133dcbe26 100644 --- a/src/web_service/verify_user_jwt.cpp +++ b/src/web_service/verify_user_jwt.cpp @@ -2,8 +2,16 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wimplicit-fallthrough" +#endif #include +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#include #include "common/logging/log.h" #include "web_service/verify_user_jwt.h" #include "web_service/web_backend.h" diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index 364b4605e6..6cc5f8f7eb 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -214,7 +214,7 @@ void Lobby::OnRefreshLobby() { for (int r = 0; r < game_list->rowCount(); ++r) { auto index = game_list->index(r, 0); auto game_id = game_list->data(index, GameListItemPath::ProgramIdRole).toULongLong(); - if (game_id != 0 && room.preferred_game_id == game_id) { + if (game_id != 0 && room.information.preferred_game_id == game_id) { smdh_icon = game_list->data(index, Qt::DecorationRole).value(); } } @@ -231,20 +231,21 @@ void Lobby::OnRefreshLobby() { auto first_item = new LobbyItem(); auto row = QList({ first_item, - new LobbyItemName(room.has_password, QString::fromStdString(room.name)), - new LobbyItemGame(room.preferred_game_id, QString::fromStdString(room.preferred_game), - smdh_icon), - new LobbyItemHost(QString::fromStdString(room.owner), QString::fromStdString(room.ip), - room.port, QString::fromStdString(room.verify_UID)), - new LobbyItemMemberList(members, room.max_player), + new LobbyItemName(room.has_password, QString::fromStdString(room.information.name)), + new LobbyItemGame(room.information.preferred_game_id, + QString::fromStdString(room.information.preferred_game), smdh_icon), + new LobbyItemHost(QString::fromStdString(room.information.host_username), + QString::fromStdString(room.ip), room.information.port, + QString::fromStdString(room.verify_UID)), + new LobbyItemMemberList(members, room.information.member_slots), }); model->appendRow(row); // To make the rows expandable, add the member data as a child of the first column of the // rows with people in them and have qt set them to colspan after the model is finished // resetting - if (!room.description.empty()) { + if (!room.information.description.empty()) { first_item->appendRow( - new LobbyItemDescription(QString::fromStdString(room.description))); + new LobbyItemDescription(QString::fromStdString(room.information.description))); } if (!room.members.empty()) { first_item->appendRow(new LobbyItemExpandedMemberList(members)); From 899c8bb33094f43fbd8df9afb4ca84718ebac87e Mon Sep 17 00:00:00 2001 From: german77 Date: Sun, 17 Jul 2022 22:53:44 -0500 Subject: [PATCH 10/15] common: multiplayer: Use GameInfo type --- src/common/announce_multiplayer_room.h | 35 +++++++++++------------ src/core/announce_multiplayer_session.cpp | 8 +++--- src/network/room.cpp | 8 ++---- src/network/room.h | 3 +- src/network/room_member.cpp | 2 +- src/web_service/announce_room_json.cpp | 21 +++++++------- src/web_service/announce_room_json.h | 3 +- src/web_service/verify_user_jwt.h | 2 ++ src/yuzu/multiplayer/host_room.cpp | 21 ++++++++------ src/yuzu/multiplayer/lobby.cpp | 11 +++---- src/yuzu/uisettings.h | 8 +++--- 11 files changed, 60 insertions(+), 62 deletions(-) diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h index 2ff38b6cfc..a9e2f89b7a 100644 --- a/src/common/announce_multiplayer_room.h +++ b/src/common/announce_multiplayer_room.h @@ -15,30 +15,28 @@ namespace AnnounceMultiplayerRoom { using MacAddress = std::array; +struct GameInfo { + std::string name{""}; + u64 id{0}; +}; + struct Member { std::string username; std::string nickname; std::string display_name; std::string avatar_url; MacAddress mac_address; - std::string game_name; - u64 game_id; + GameInfo game; }; struct RoomInformation { - std::string name; ///< Name of the server - std::string description; ///< Server description - u32 member_slots; ///< Maximum number of members in this room - u16 port; ///< The port of this room - std::string preferred_game; ///< Game to advertise that you want to play - u64 preferred_game_id; ///< Title ID for the advertised game - std::string host_username; ///< Forum username of the host - bool enable_yuzu_mods; ///< Allow yuzu Moderators to moderate on this room -}; - -struct GameInfo { - std::string name{""}; - u64 id{0}; + std::string name; ///< Name of the server + std::string description; ///< Server description + u32 member_slots; ///< Maximum number of members in this room + u16 port; ///< The port of this room + GameInfo preferred_game; ///< Game to advertise that you want to play + std::string host_username; ///< Forum username of the host + bool enable_yuzu_mods; ///< Allow yuzu Moderators to moderate on this room }; struct Room { @@ -75,8 +73,7 @@ public: */ virtual void SetRoomInformation(const std::string& name, const std::string& description, const u16 port, const u32 max_player, const u32 net_version, - const bool has_password, const std::string& preferred_game, - const u64 preferred_game_id) = 0; + const bool has_password, const GameInfo& preferred_game) = 0; /** * Adds a player information to the data that gets announced * @param nickname The nickname of the player @@ -125,8 +122,8 @@ public: ~NullBackend() = default; void SetRoomInformation(const std::string& /*name*/, const std::string& /*description*/, const u16 /*port*/, const u32 /*max_player*/, const u32 /*net_version*/, - const bool /*has_password*/, const std::string& /*preferred_game*/, - const u64 /*preferred_game_id*/) override {} + const bool /*has_password*/, + const GameInfo& /*preferred_game*/) override {} void AddPlayer(const Member& /*member*/) override {} WebService::WebResult Update() override { return WebService::WebResult{WebService::WebResult::Code::NoWebservice, diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp index f8aa9bb0b2..db9eaeac83 100644 --- a/src/core/announce_multiplayer_session.cpp +++ b/src/core/announce_multiplayer_session.cpp @@ -89,10 +89,10 @@ AnnounceMultiplayerSession::~AnnounceMultiplayerSession() { void AnnounceMultiplayerSession::UpdateBackendData(std::shared_ptr room) { Network::RoomInformation room_information = room->GetRoomInformation(); std::vector memberlist = room->GetRoomMemberList(); - backend->SetRoomInformation( - room_information.name, room_information.description, room_information.port, - room_information.member_slots, Network::network_version, room->HasPassword(), - room_information.preferred_game, room_information.preferred_game_id); + backend->SetRoomInformation(room_information.name, room_information.description, + room_information.port, room_information.member_slots, + Network::network_version, room->HasPassword(), + room_information.preferred_game); backend->ClearPlayers(); for (const auto& member : memberlist) { backend->AddPlayer(member); diff --git a/src/network/room.cpp b/src/network/room.cpp index fe55d194c4..22491b2996 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -811,7 +811,7 @@ void Room::RoomImpl::BroadcastRoomInformation() { packet << room_information.description; packet << room_information.member_slots; packet << room_information.port; - packet << room_information.preferred_game; + packet << room_information.preferred_game.name; packet << room_information.host_username; packet << static_cast(members.size()); @@ -1013,7 +1013,7 @@ Room::~Room() = default; bool Room::Create(const std::string& name, const std::string& description, const std::string& server_address, u16 server_port, const std::string& password, const u32 max_connections, const std::string& host_username, - const std::string& preferred_game, u64 preferred_game_id, + const GameInfo preferred_game, std::unique_ptr verify_backend, const Room::BanList& ban_list, bool enable_yuzu_mods) { ENetAddress address; @@ -1036,7 +1036,6 @@ bool Room::Create(const std::string& name, const std::string& description, room_impl->room_information.member_slots = max_connections; room_impl->room_information.port = server_port; room_impl->room_information.preferred_game = preferred_game; - room_impl->room_information.preferred_game_id = preferred_game_id; room_impl->room_information.host_username = host_username; room_impl->room_information.enable_yuzu_mods = enable_yuzu_mods; room_impl->password = password; @@ -1076,8 +1075,7 @@ std::vector Room::GetRoomMemberList() const { member.display_name = member_impl.user_data.display_name; member.avatar_url = member_impl.user_data.avatar_url; member.mac_address = member_impl.mac_address; - member.game_name = member_impl.game_info.name; - member.game_id = member_impl.game_info.id; + member.game = member_impl.game_info; member_list.push_back(member); } return member_list; diff --git a/src/network/room.h b/src/network/room.h index f282a5ac32..90a82563f2 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -125,8 +125,7 @@ public: const std::string& server = "", u16 server_port = DefaultRoomPort, const std::string& password = "", const u32 max_connections = MaxConcurrentConnections, - const std::string& host_username = "", const std::string& preferred_game = "", - u64 preferred_game_id = 0, + const std::string& host_username = "", const GameInfo = {}, std::unique_ptr verify_backend = nullptr, const BanList& ban_list = {}, bool enable_yuzu_mods = false); diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index d6ace9b39d..11a2e276ea 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -303,7 +303,7 @@ void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* ev packet >> info.description; packet >> info.member_slots; packet >> info.port; - packet >> info.preferred_game; + packet >> info.preferred_game.name; packet >> info.host_username; room_information.name = info.name; room_information.description = info.description; diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 84220b851a..082bebaa92 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -19,14 +19,14 @@ static void to_json(nlohmann::json& json, const Member& member) { if (!member.avatar_url.empty()) { json["avatarUrl"] = member.avatar_url; } - json["gameName"] = member.game_name; - json["gameId"] = member.game_id; + json["gameName"] = member.game.name; + json["gameId"] = member.game.id; } static void from_json(const nlohmann::json& json, Member& member) { member.nickname = json.at("nickname").get(); - member.game_name = json.at("gameName").get(); - member.game_id = json.at("gameId").get(); + member.game.name = json.at("gameName").get(); + member.game.id = json.at("gameId").get(); try { member.username = json.at("username").get(); member.avatar_url = json.at("avatarUrl").get(); @@ -42,8 +42,8 @@ static void to_json(nlohmann::json& json, const Room& room) { if (!room.information.description.empty()) { json["description"] = room.information.description; } - json["preferredGameName"] = room.information.preferred_game; - json["preferredGameId"] = room.information.preferred_game_id; + json["preferredGameName"] = room.information.preferred_game.name; + json["preferredGameId"] = room.information.preferred_game.id; json["maxPlayers"] = room.information.member_slots; json["netVersion"] = room.net_version; json["hasPassword"] = room.has_password; @@ -65,8 +65,8 @@ static void from_json(const nlohmann::json& json, Room& room) { } room.information.host_username = json.at("owner").get(); room.information.port = json.at("port").get(); - room.information.preferred_game = json.at("preferredGameName").get(); - room.information.preferred_game_id = json.at("preferredGameId").get(); + room.information.preferred_game.name = json.at("preferredGameName").get(); + room.information.preferred_game.id = json.at("preferredGameId").get(); room.information.member_slots = json.at("maxPlayers").get(); room.net_version = json.at("netVersion").get(); room.has_password = json.at("hasPassword").get(); @@ -83,8 +83,8 @@ namespace WebService { void RoomJson::SetRoomInformation(const std::string& name, const std::string& description, const u16 port, const u32 max_player, const u32 net_version, - const bool has_password, const std::string& preferred_game, - const u64 preferred_game_id) { + const bool has_password, + const AnnounceMultiplayerRoom::GameInfo& preferred_game) { room.information.name = name; room.information.description = description; room.information.port = port; @@ -92,7 +92,6 @@ void RoomJson::SetRoomInformation(const std::string& name, const std::string& de room.net_version = net_version; room.has_password = has_password; room.information.preferred_game = preferred_game; - room.information.preferred_game_id = preferred_game_id; } void RoomJson::AddPlayer(const AnnounceMultiplayerRoom::Member& member) { room.members.push_back(member); diff --git a/src/web_service/announce_room_json.h b/src/web_service/announce_room_json.h index 811c76fbd2..24ec29c65e 100644 --- a/src/web_service/announce_room_json.h +++ b/src/web_service/announce_room_json.h @@ -22,8 +22,7 @@ public: ~RoomJson() = default; void SetRoomInformation(const std::string& name, const std::string& description, const u16 port, const u32 max_player, const u32 net_version, const bool has_password, - const std::string& preferred_game, - const u64 preferred_game_id) override; + const AnnounceMultiplayerRoom::GameInfo& preferred_game) override; void AddPlayer(const AnnounceMultiplayerRoom::Member& member) override; WebResult Update() override; WebResult Register() override; diff --git a/src/web_service/verify_user_jwt.h b/src/web_service/verify_user_jwt.h index 826e01eed7..6db74c2089 100644 --- a/src/web_service/verify_user_jwt.h +++ b/src/web_service/verify_user_jwt.h @@ -10,6 +10,8 @@ namespace WebService { +std::string GetPublicKey(const std::string& host); + class VerifyUserJWT final : public Network::VerifyUser::Backend { public: VerifyUserJWT(const std::string& host); diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp index 5470b8b86e..053e22fe4b 100644 --- a/src/yuzu/multiplayer/host_room.cpp +++ b/src/yuzu/multiplayer/host_room.cpp @@ -132,21 +132,24 @@ void HostRoomWindow::Host() { } ui->host->setDisabled(true); - auto game_name = ui->game_list->currentData(Qt::DisplayRole).toString(); - auto game_id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong(); - auto port = ui->port->isModified() ? ui->port->text().toInt() : Network::DefaultRoomPort; - auto password = ui->password->text().toStdString(); + const AnnounceMultiplayerRoom::GameInfo game{ + .name = ui->game_list->currentData(Qt::DisplayRole).toString().toStdString(), + .id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toULongLong(), + }; + const auto port = + ui->port->isModified() ? ui->port->text().toInt() : Network::DefaultRoomPort; + const auto password = ui->password->text().toStdString(); const bool is_public = ui->host_type->currentIndex() == 0; Network::Room::BanList ban_list{}; if (ui->load_ban_list->isChecked()) { ban_list = UISettings::values.multiplayer_ban_list; } if (auto room = Network::GetRoom().lock()) { - bool created = room->Create( - ui->room_name->text().toStdString(), - ui->room_description->toPlainText().toStdString(), "", port, password, - ui->max_player->value(), Settings::values.yuzu_username.GetValue(), - game_name.toStdString(), game_id, CreateVerifyBackend(is_public), ban_list); + const bool created = + room->Create(ui->room_name->text().toStdString(), + ui->room_description->toPlainText().toStdString(), "", port, password, + ui->max_player->value(), Settings::values.yuzu_username.GetValue(), + game, CreateVerifyBackend(is_public), ban_list); if (!created) { NetworkMessage::ErrorManager::ShowError( NetworkMessage::ErrorManager::COULD_NOT_CREATE_ROOM); diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index 6cc5f8f7eb..1b6b782d99 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -214,7 +214,7 @@ void Lobby::OnRefreshLobby() { for (int r = 0; r < game_list->rowCount(); ++r) { auto index = game_list->index(r, 0); auto game_id = game_list->data(index, GameListItemPath::ProgramIdRole).toULongLong(); - if (game_id != 0 && room.information.preferred_game_id == game_id) { + if (game_id != 0 && room.information.preferred_game.id == game_id) { smdh_icon = game_list->data(index, Qt::DecorationRole).value(); } } @@ -223,8 +223,8 @@ void Lobby::OnRefreshLobby() { for (auto member : room.members) { QVariant var; var.setValue(LobbyMember{QString::fromStdString(member.username), - QString::fromStdString(member.nickname), member.game_id, - QString::fromStdString(member.game_name)}); + QString::fromStdString(member.nickname), member.game.id, + QString::fromStdString(member.game.name)}); members.append(var); } @@ -232,8 +232,9 @@ void Lobby::OnRefreshLobby() { auto row = QList({ first_item, new LobbyItemName(room.has_password, QString::fromStdString(room.information.name)), - new LobbyItemGame(room.information.preferred_game_id, - QString::fromStdString(room.information.preferred_game), smdh_icon), + new LobbyItemGame(room.information.preferred_game.id, + QString::fromStdString(room.information.preferred_game.name), + smdh_icon), new LobbyItemHost(QString::fromStdString(room.information.host_username), QString::fromStdString(room.ip), room.information.port, QString::fromStdString(room.verify_UID)), diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h index 83a6cffa3e..6cd4d6cb2e 100644 --- a/src/yuzu/uisettings.h +++ b/src/yuzu/uisettings.h @@ -105,12 +105,12 @@ struct Values { // multiplayer settings Settings::Setting multiplayer_nickname{QStringLiteral("yuzu"), "nickname"}; Settings::Setting multiplayer_ip{{}, "ip"}; - Settings::SwitchableSetting multiplayer_port{24872, 0, 65535, "port"}; + Settings::SwitchableSetting multiplayer_port{24872, 0, 65535, "port"}; Settings::Setting multiplayer_room_nickname{{}, "room_nickname"}; Settings::Setting multiplayer_room_name{{}, "room_name"}; - Settings::SwitchableSetting multiplayer_max_player{8, 0, 8, "max_player"}; - Settings::SwitchableSetting multiplayer_room_port{24872, 0, 65535, "room_port"}; - Settings::SwitchableSetting multiplayer_host_type{0, 0, 1, "host_type"}; + Settings::SwitchableSetting multiplayer_max_player{8, 0, 8, "max_player"}; + Settings::SwitchableSetting multiplayer_room_port{24872, 0, 65535, "room_port"}; + Settings::SwitchableSetting multiplayer_host_type{0, 0, 1, "host_type"}; Settings::Setting multiplayer_game_id{{}, "game_id"}; Settings::Setting multiplayer_room_description{{}, "room_description"}; std::pair, std::vector> multiplayer_ban_list; From 7d82e57b91dee30e0fe6fed36550ea7cc9eb778e Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Fri, 22 Jul 2022 16:31:13 +0200 Subject: [PATCH 11/15] network: Move global state into a seperate class Co-Authored-By: Narr the Reg <5944268+german77@users.noreply.github.com> --- src/core/announce_multiplayer_session.cpp | 7 ++-- src/core/announce_multiplayer_session.h | 11 +++-- src/core/core.cpp | 16 ++++++-- src/core/core.h | 10 +++++ src/network/network.cpp | 15 +++---- src/network/network.h | 25 +++++++---- src/yuzu/main.cpp | 6 +-- src/yuzu/multiplayer/chat_room.cpp | 48 +++++++++++----------- src/yuzu/multiplayer/chat_room.h | 2 + src/yuzu/multiplayer/client_room.cpp | 11 ++--- src/yuzu/multiplayer/client_room.h | 3 +- src/yuzu/multiplayer/direct_connect.cpp | 10 ++--- src/yuzu/multiplayer/direct_connect.h | 3 +- src/yuzu/multiplayer/host_room.cpp | 14 ++++--- src/yuzu/multiplayer/host_room.h | 4 +- src/yuzu/multiplayer/lobby.cpp | 12 +++--- src/yuzu/multiplayer/lobby.h | 4 +- src/yuzu/multiplayer/moderation_dialog.cpp | 14 +++---- src/yuzu/multiplayer/moderation_dialog.h | 4 +- src/yuzu/multiplayer/state.cpp | 28 +++++++------ src/yuzu/multiplayer/state.h | 3 +- 21 files changed, 152 insertions(+), 98 deletions(-) diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp index db9eaeac83..8f96b4ee87 100644 --- a/src/core/announce_multiplayer_session.cpp +++ b/src/core/announce_multiplayer_session.cpp @@ -20,7 +20,8 @@ namespace Core { // Time between room is announced to web_service static constexpr std::chrono::seconds announce_time_interval(15); -AnnounceMultiplayerSession::AnnounceMultiplayerSession() { +AnnounceMultiplayerSession::AnnounceMultiplayerSession(Network::RoomNetwork& room_network_) + : room_network{room_network_} { #ifdef ENABLE_WEB_SERVICE backend = std::make_unique(Settings::values.web_api_url.GetValue(), Settings::values.yuzu_username.GetValue(), @@ -31,7 +32,7 @@ AnnounceMultiplayerSession::AnnounceMultiplayerSession() { } WebService::WebResult AnnounceMultiplayerSession::Register() { - std::shared_ptr room = Network::GetRoom().lock(); + std::shared_ptr room = room_network.GetRoom().lock(); if (!room) { return WebService::WebResult{WebService::WebResult::Code::LibError, "Network is not initialized", ""}; @@ -120,7 +121,7 @@ void AnnounceMultiplayerSession::AnnounceMultiplayerLoop() { std::future future; while (!shutdown_event.WaitUntil(update_time)) { update_time += announce_time_interval; - std::shared_ptr room = Network::GetRoom().lock(); + std::shared_ptr room = room_network.GetRoom().lock(); if (!room) { break; } diff --git a/src/core/announce_multiplayer_session.h b/src/core/announce_multiplayer_session.h index 2aaf550177..5da3c1f8d0 100644 --- a/src/core/announce_multiplayer_session.h +++ b/src/core/announce_multiplayer_session.h @@ -16,7 +16,8 @@ namespace Network { class Room; -} +class RoomNetwork; +} // namespace Network namespace Core { @@ -28,7 +29,7 @@ namespace Core { class AnnounceMultiplayerSession { public: using CallbackHandle = std::shared_ptr>; - AnnounceMultiplayerSession(); + AnnounceMultiplayerSession(Network::RoomNetwork& room_network_); ~AnnounceMultiplayerSession(); /** @@ -79,6 +80,9 @@ public: void UpdateCredentials(); private: + void UpdateBackendData(std::shared_ptr room); + void AnnounceMultiplayerLoop(); + Common::Event shutdown_event; std::mutex callback_mutex; std::set error_callbacks; @@ -89,8 +93,7 @@ private: std::atomic_bool registered = false; ///< Whether the room has been registered - void UpdateBackendData(std::shared_ptr room); - void AnnounceMultiplayerLoop(); + Network::RoomNetwork& room_network; }; } // namespace Core diff --git a/src/core/core.cpp b/src/core/core.cpp index 98fe6d39cc..95791a07f1 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -131,7 +131,7 @@ FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs, struct System::Impl { explicit Impl(System& system) - : kernel{system}, fs_controller{system}, memory{system}, hid_core{}, + : kernel{system}, fs_controller{system}, memory{system}, hid_core{}, room_network{}, cpu_manager{system}, reporter{system}, applet_manager{system}, time_manager{system} {} SystemResultStatus Run() { @@ -320,7 +320,7 @@ struct System::Impl { if (app_loader->ReadTitle(name) != Loader::ResultStatus::Success) { LOG_ERROR(Core, "Failed to read title for ROM (Error {})", load_result); } - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network.GetRoomMember().lock()) { Network::GameInfo game_info; game_info.name = name; game_info.id = program_id; @@ -374,7 +374,7 @@ struct System::Impl { memory.Reset(); applet_manager.ClearAll(); - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network.GetRoomMember().lock()) { Network::GameInfo game_info{}; room_member->SendGameInfo(game_info); } @@ -451,6 +451,8 @@ struct System::Impl { std::unique_ptr audio_core; Core::Memory::Memory memory; Core::HID::HIDCore hid_core; + Network::RoomNetwork room_network; + CpuManager cpu_manager; std::atomic_bool is_powered_on{}; bool exit_lock = false; @@ -896,6 +898,14 @@ const Core::Debugger& System::GetDebugger() const { return *impl->debugger; } +Network::RoomNetwork& System::GetRoomNetwork() { + return impl->room_network; +} + +const Network::RoomNetwork& System::GetRoomNetwork() const { + return impl->room_network; +} + void System::RegisterExecuteProgramCallback(ExecuteProgramCallback&& callback) { impl->execute_program_callback = std::move(callback); } diff --git a/src/core/core.h b/src/core/core.h index a49d1214b7..13122dd619 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -97,6 +97,10 @@ namespace Core::HID { class HIDCore; } +namespace Network { +class RoomNetwork; +} + namespace Core { class ARM_Interface; @@ -379,6 +383,12 @@ public: [[nodiscard]] Core::Debugger& GetDebugger(); [[nodiscard]] const Core::Debugger& GetDebugger() const; + /// Gets a mutable reference to the Room Network. + [[nodiscard]] Network::RoomNetwork& GetRoomNetwork(); + + /// Gets an immutable reference to the Room Network. + [[nodiscard]] const Network::RoomNetwork& GetRoomNetwork() const; + void SetExitLock(bool locked); [[nodiscard]] bool GetExitLock() const; diff --git a/src/network/network.cpp b/src/network/network.cpp index 51b5d6a9fa..e1401a4031 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -9,11 +9,12 @@ namespace Network { -static std::shared_ptr g_room_member; ///< RoomMember (Client) for network games -static std::shared_ptr g_room; ///< Room (Server) for network games -// TODO(B3N30): Put these globals into a networking class +RoomNetwork::RoomNetwork() { + g_room = std::make_shared(); + g_room_member = std::make_shared(); +} -bool Init() { +bool RoomNetwork::Init() { if (enet_initialize() != 0) { LOG_ERROR(Network, "Error initalizing ENet"); return false; @@ -24,15 +25,15 @@ bool Init() { return true; } -std::weak_ptr GetRoom() { +std::weak_ptr RoomNetwork::GetRoom() { return g_room; } -std::weak_ptr GetRoomMember() { +std::weak_ptr RoomNetwork::GetRoomMember() { return g_room_member; } -void Shutdown() { +void RoomNetwork::Shutdown() { if (g_room_member) { if (g_room_member->IsConnected()) g_room_member->Leave(); diff --git a/src/network/network.h b/src/network/network.h index 6d002d693f..74eb42bf5c 100644 --- a/src/network/network.h +++ b/src/network/network.h @@ -10,16 +10,25 @@ namespace Network { -/// Initializes and registers the network device, the room, and the room member. -bool Init(); +class RoomNetwork { +public: + RoomNetwork(); -/// Returns a pointer to the room handle -std::weak_ptr GetRoom(); + /// Initializes and registers the network device, the room, and the room member. + bool Init(); -/// Returns a pointer to the room member handle -std::weak_ptr GetRoomMember(); + /// Returns a pointer to the room handle + std::weak_ptr GetRoom(); -/// Unregisters the network device, the room, and the room member and shut them down. -void Shutdown(); + /// Returns a pointer to the room member handle + std::weak_ptr GetRoomMember(); + + /// Unregisters the network device, the room, and the room member and shut them down. + void Shutdown(); + +private: + std::shared_ptr g_room_member; ///< RoomMember (Client) for network games + std::shared_ptr g_room; ///< Room (Server) for network games +}; } // namespace Network diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index f1cc910c04..e56fcabffb 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -273,7 +273,7 @@ GMainWindow::GMainWindow(bool has_broken_vulkan) SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); discord_rpc->Update(); - Network::Init(); + system->GetRoomNetwork().Init(); RegisterMetaTypes(); @@ -463,7 +463,7 @@ GMainWindow::~GMainWindow() { if (render_window->parent() == nullptr) { delete render_window; } - Network::Shutdown(); + system->GetRoomNetwork().Shutdown(); } void GMainWindow::RegisterMetaTypes() { @@ -828,7 +828,7 @@ void GMainWindow::InitializeWidgets() { }); multiplayer_state = new MultiplayerState(this, game_list->GetModel(), ui->action_Leave_Room, - ui->action_Show_Room); + ui->action_Show_Room, system->GetRoomNetwork()); multiplayer_state->setVisible(false); // Create status bar diff --git a/src/yuzu/multiplayer/chat_room.cpp b/src/yuzu/multiplayer/chat_room.cpp index 7048ee1fce..9f2c57eee3 100644 --- a/src/yuzu/multiplayer/chat_room.cpp +++ b/src/yuzu/multiplayer/chat_room.cpp @@ -28,7 +28,8 @@ class ChatMessage { public: - explicit ChatMessage(const Network::ChatEntry& chat, QTime ts = {}) { + explicit ChatMessage(const Network::ChatEntry& chat, Network::RoomNetwork& room_network, + QTime ts = {}) { /// Convert the time to their default locale defined format QLocale locale; timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat); @@ -38,7 +39,7 @@ public: // Check for user pings QString cur_nickname, cur_username; - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network.GetRoomMember().lock()) { cur_nickname = QString::fromStdString(room->GetNickname()); cur_username = QString::fromStdString(room->GetUsername()); } @@ -173,20 +174,6 @@ ChatRoom::ChatRoom(QWidget* parent) : QWidget(parent), ui(std::make_unique(); qRegisterMetaType(); - // setup the callbacks for network updates - if (auto member = Network::GetRoomMember().lock()) { - member->BindOnChatMessageRecieved( - [this](const Network::ChatEntry& chat) { emit ChatReceived(chat); }); - member->BindOnStatusMessageReceived( - [this](const Network::StatusMessageEntry& status_message) { - emit StatusMessageReceived(status_message); - }); - connect(this, &ChatRoom::ChatReceived, this, &ChatRoom::OnChatReceive); - connect(this, &ChatRoom::StatusMessageReceived, this, &ChatRoom::OnStatusMessageReceive); - } else { - // TODO (jroweboy) network was not initialized? - } - // Connect all the widgets to the appropriate events connect(ui->player_view, &QTreeView::customContextMenuRequested, this, &ChatRoom::PopupContextMenu); @@ -197,6 +184,21 @@ ChatRoom::ChatRoom(QWidget* parent) : QWidget(parent), ui(std::make_uniqueGetRoomMember().lock()) { + member->BindOnChatMessageRecieved( + [this](const Network::ChatEntry& chat) { emit ChatReceived(chat); }); + member->BindOnStatusMessageReceived( + [this](const Network::StatusMessageEntry& status_message) { + emit StatusMessageReceived(status_message); + }); + connect(this, &ChatRoom::ChatReceived, this, &ChatRoom::OnChatReceive); + connect(this, &ChatRoom::StatusMessageReceived, this, &ChatRoom::OnStatusMessageReceive); + } +} + void ChatRoom::SetModPerms(bool is_mod) { has_mod_perms = is_mod; } @@ -219,7 +221,7 @@ void ChatRoom::AppendChatMessage(const QString& msg) { } void ChatRoom::SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname) { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network->GetRoomMember().lock()) { auto members = room->GetMemberInformation(); auto it = std::find_if(members.begin(), members.end(), [&nickname](const Network::RoomMember::MemberInformation& member) { @@ -239,7 +241,7 @@ bool ChatRoom::ValidateMessage(const std::string& msg) { void ChatRoom::OnRoomUpdate(const Network::RoomInformation& info) { // TODO(B3N30): change title - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network->GetRoomMember().lock()) { SetPlayerList(room_member->GetMemberInformation()); } } @@ -258,7 +260,7 @@ void ChatRoom::OnChatReceive(const Network::ChatEntry& chat) { if (!ValidateMessage(chat.message)) { return; } - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network->GetRoomMember().lock()) { // get the id of the player auto members = room->GetMemberInformation(); auto it = std::find_if(members.begin(), members.end(), @@ -276,7 +278,7 @@ void ChatRoom::OnChatReceive(const Network::ChatEntry& chat) { return; } auto player = std::distance(members.begin(), it); - ChatMessage m(chat); + ChatMessage m(chat, *room_network); if (m.ContainsPing()) { emit UserPinged(); } @@ -315,7 +317,7 @@ void ChatRoom::OnStatusMessageReceive(const Network::StatusMessageEntry& status_ } void ChatRoom::OnSendChat() { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network->GetRoomMember().lock()) { if (room->GetState() != Network::RoomMember::State::Joined && room->GetState() != Network::RoomMember::State::Moderator) { @@ -339,7 +341,7 @@ void ChatRoom::OnSendChat() { LOG_INFO(Network, "Cannot find self in the player list when sending a message."); } auto player = std::distance(members.begin(), it); - ChatMessage m(chat); + ChatMessage m(chat, *room_network); room->SendChatMessage(message); AppendChatMessage(m.GetPlayerChatMessage(player)); ui->chat_message->clear(); @@ -433,7 +435,7 @@ void ChatRoom::PopupContextMenu(const QPoint& menu_location) { } std::string cur_nickname; - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network->GetRoomMember().lock()) { cur_nickname = room->GetNickname(); } diff --git a/src/yuzu/multiplayer/chat_room.h b/src/yuzu/multiplayer/chat_room.h index a810377f7a..9179d16fbb 100644 --- a/src/yuzu/multiplayer/chat_room.h +++ b/src/yuzu/multiplayer/chat_room.h @@ -30,6 +30,7 @@ class ChatRoom : public QWidget { public: explicit ChatRoom(QWidget* parent); + void Initialize(Network::RoomNetwork* room_network); void RetranslateUi(); void SetPlayerList(const Network::RoomMember::MemberList& member_list); void Clear(); @@ -65,6 +66,7 @@ private: std::unique_ptr ui; std::unordered_set block_list; std::unordered_map icon_cache; + Network::RoomNetwork* room_network; }; Q_DECLARE_METATYPE(Network::ChatEntry); diff --git a/src/yuzu/multiplayer/client_room.cpp b/src/yuzu/multiplayer/client_room.cpp index 7b2e16e06e..9bef9bdfcd 100644 --- a/src/yuzu/multiplayer/client_room.cpp +++ b/src/yuzu/multiplayer/client_room.cpp @@ -19,13 +19,14 @@ #include "yuzu/multiplayer/moderation_dialog.h" #include "yuzu/multiplayer/state.h" -ClientRoomWindow::ClientRoomWindow(QWidget* parent) +ClientRoomWindow::ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), - ui(std::make_unique()) { + ui(std::make_unique()), room_network{room_network_} { ui->setupUi(this); + ui->chat->Initialize(&room_network); // setup the callbacks for network updates - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { member->BindOnRoomInformationChanged( [this](const Network::RoomInformation& info) { emit RoomInformationChanged(info); }); member->BindOnStateChanged( @@ -44,7 +45,7 @@ ClientRoomWindow::ClientRoomWindow(QWidget* parent) ui->disconnect->setDefault(false); ui->disconnect->setAutoDefault(false); connect(ui->moderation, &QPushButton::clicked, [this] { - ModerationDialog dialog(this); + ModerationDialog dialog(room_network, this); dialog.exec(); }); ui->moderation->setDefault(false); @@ -91,7 +92,7 @@ void ClientRoomWindow::Disconnect() { } void ClientRoomWindow::UpdateView() { - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { if (member->IsConnected()) { ui->chat->Enable(); ui->disconnect->setEnabled(true); diff --git a/src/yuzu/multiplayer/client_room.h b/src/yuzu/multiplayer/client_room.h index 607b4073d0..6303b2595f 100644 --- a/src/yuzu/multiplayer/client_room.h +++ b/src/yuzu/multiplayer/client_room.h @@ -14,7 +14,7 @@ class ClientRoomWindow : public QDialog { Q_OBJECT public: - explicit ClientRoomWindow(QWidget* parent); + explicit ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_); ~ClientRoomWindow(); void RetranslateUi(); @@ -36,4 +36,5 @@ private: QStandardItemModel* player_list; std::unique_ptr ui; + Network::RoomNetwork& room_network; }; diff --git a/src/yuzu/multiplayer/direct_connect.cpp b/src/yuzu/multiplayer/direct_connect.cpp index 837baf85cc..360d66beae 100644 --- a/src/yuzu/multiplayer/direct_connect.cpp +++ b/src/yuzu/multiplayer/direct_connect.cpp @@ -21,9 +21,9 @@ enum class ConnectionType : u8 { TraversalServer, IP }; -DirectConnectWindow::DirectConnectWindow(QWidget* parent) +DirectConnectWindow::DirectConnectWindow(Network::RoomNetwork& room_network_, QWidget* parent) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), - ui(std::make_unique()) { + ui(std::make_unique()), room_network{room_network_} { ui->setupUi(this); @@ -58,7 +58,7 @@ void DirectConnectWindow::Connect() { NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); return; } - if (const auto member = Network::GetRoomMember().lock()) { + if (const auto member = room_network.GetRoomMember().lock()) { // Prevent the user from trying to join a room while they are already joining. if (member->GetState() == Network::RoomMember::State::Joining) { return; @@ -96,7 +96,7 @@ void DirectConnectWindow::Connect() { // attempt to connect in a different thread QFuture f = QtConcurrent::run([&] { - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network.GetRoomMember().lock()) { auto port = UISettings::values.multiplayer_port.GetValue(); room_member->Join(ui->nickname->text().toStdString(), "", ui->ip->text().toStdString().c_str(), port, 0, @@ -121,7 +121,7 @@ void DirectConnectWindow::EndConnecting() { void DirectConnectWindow::OnConnection() { EndConnecting(); - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network.GetRoomMember().lock()) { if (room_member->GetState() == Network::RoomMember::State::Joined || room_member->GetState() == Network::RoomMember::State::Moderator) { diff --git a/src/yuzu/multiplayer/direct_connect.h b/src/yuzu/multiplayer/direct_connect.h index e38961ed04..719030d29c 100644 --- a/src/yuzu/multiplayer/direct_connect.h +++ b/src/yuzu/multiplayer/direct_connect.h @@ -17,7 +17,7 @@ class DirectConnectWindow : public QDialog { Q_OBJECT public: - explicit DirectConnectWindow(QWidget* parent = nullptr); + explicit DirectConnectWindow(Network::RoomNetwork& room_network_, QWidget* parent = nullptr); ~DirectConnectWindow(); void RetranslateUi(); @@ -40,4 +40,5 @@ private: QFutureWatcher* watcher; std::unique_ptr ui; Validation validation; + Network::RoomNetwork& room_network; }; diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp index 053e22fe4b..a48077544d 100644 --- a/src/yuzu/multiplayer/host_room.cpp +++ b/src/yuzu/multiplayer/host_room.cpp @@ -27,9 +27,11 @@ #endif HostRoomWindow::HostRoomWindow(QWidget* parent, QStandardItemModel* list, - std::shared_ptr session) + std::shared_ptr session, + Network::RoomNetwork& room_network_) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), - ui(std::make_unique()), announce_multiplayer_session(session) { + ui(std::make_unique()), + announce_multiplayer_session(session), room_network{room_network_} { ui->setupUi(this); // set up validation for all of the fields @@ -120,7 +122,7 @@ void HostRoomWindow::Host() { NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::GAME_NOT_SELECTED); return; } - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { if (member->GetState() == Network::RoomMember::State::Joining) { return; } else if (member->IsConnected()) { @@ -144,7 +146,7 @@ void HostRoomWindow::Host() { if (ui->load_ban_list->isChecked()) { ban_list = UISettings::values.multiplayer_ban_list; } - if (auto room = Network::GetRoom().lock()) { + if (auto room = room_network.GetRoom().lock()) { const bool created = room->Create(ui->room_name->text().toStdString(), ui->room_description->toPlainText().toStdString(), "", port, password, @@ -173,7 +175,7 @@ void HostRoomWindow::Host() { QString::fromStdString(result.result_string), QMessageBox::Ok); ui->host->setEnabled(true); - if (auto room = Network::GetRoom().lock()) { + if (auto room = room_network.GetRoom().lock()) { room->Destroy(); } return; @@ -189,7 +191,7 @@ void HostRoomWindow::Host() { WebService::Client client(Settings::values.web_api_url.GetValue(), Settings::values.yuzu_username.GetValue(), Settings::values.yuzu_token.GetValue()); - if (auto room = Network::GetRoom().lock()) { + if (auto room = room_network.GetRoom().lock()) { token = client.GetExternalJWT(room->GetVerifyUID()).returned_data; } if (token.empty()) { diff --git a/src/yuzu/multiplayer/host_room.h b/src/yuzu/multiplayer/host_room.h index d84f93ffde..98a56458f9 100644 --- a/src/yuzu/multiplayer/host_room.h +++ b/src/yuzu/multiplayer/host_room.h @@ -35,7 +35,8 @@ class HostRoomWindow : public QDialog { public: explicit HostRoomWindow(QWidget* parent, QStandardItemModel* list, - std::shared_ptr session); + std::shared_ptr session, + Network::RoomNetwork& room_network_); ~HostRoomWindow(); /** @@ -54,6 +55,7 @@ private: QStandardItemModel* game_list; ComboBoxProxyModel* proxy; Validation validation; + Network::RoomNetwork& room_network; }; /** diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index 1b6b782d99..0c6648ab5d 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -23,9 +23,11 @@ #endif Lobby::Lobby(QWidget* parent, QStandardItemModel* list, - std::shared_ptr session) + std::shared_ptr session, + Network::RoomNetwork& room_network_) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), - ui(std::make_unique()), announce_multiplayer_session(session) { + ui(std::make_unique()), + announce_multiplayer_session(session), room_network{room_network_} { ui->setupUi(this); // setup the watcher for background connections @@ -113,7 +115,7 @@ void Lobby::OnExpandRoom(const QModelIndex& index) { } void Lobby::OnJoinRoom(const QModelIndex& source) { - if (const auto member = Network::GetRoomMember().lock()) { + if (const auto member = room_network.GetRoomMember().lock()) { // Prevent the user from trying to join a room while they are already joining. if (member->GetState() == Network::RoomMember::State::Joining) { return; @@ -151,7 +153,7 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { proxy->data(connection_index, LobbyItemHost::HostVerifyUIDRole).toString().toStdString(); // attempt to connect in a different thread - QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_UID] { + QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_UID, this] { std::string token; #ifdef ENABLE_WEB_SERVICE if (!Settings::values.yuzu_username.GetValue().empty() && @@ -167,7 +169,7 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { } } #endif - if (auto room_member = Network::GetRoomMember().lock()) { + if (auto room_member = room_network.GetRoomMember().lock()) { room_member->Join(nickname, "", ip.c_str(), port, 0, Network::NoPreferredMac, password, token); } diff --git a/src/yuzu/multiplayer/lobby.h b/src/yuzu/multiplayer/lobby.h index aea4a0e4e4..ec6ec26628 100644 --- a/src/yuzu/multiplayer/lobby.h +++ b/src/yuzu/multiplayer/lobby.h @@ -30,7 +30,8 @@ class Lobby : public QDialog { public: explicit Lobby(QWidget* parent, QStandardItemModel* list, - std::shared_ptr session); + std::shared_ptr session, + Network::RoomNetwork& room_network_); ~Lobby() override; /** @@ -94,6 +95,7 @@ private: std::weak_ptr announce_multiplayer_session; QFutureWatcher* watcher; Validation validation; + Network::RoomNetwork& room_network; }; /** diff --git a/src/yuzu/multiplayer/moderation_dialog.cpp b/src/yuzu/multiplayer/moderation_dialog.cpp index e97f30ee5a..fc3f36c57e 100644 --- a/src/yuzu/multiplayer/moderation_dialog.cpp +++ b/src/yuzu/multiplayer/moderation_dialog.cpp @@ -17,13 +17,13 @@ enum { }; } -ModerationDialog::ModerationDialog(QWidget* parent) - : QDialog(parent), ui(std::make_unique()) { +ModerationDialog::ModerationDialog(Network::RoomNetwork& room_network_, QWidget* parent) + : QDialog(parent), ui(std::make_unique()), room_network{room_network_} { ui->setupUi(this); qRegisterMetaType(); - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { callback_handle_status_message = member->BindOnStatusMessageReceived( [this](const Network::StatusMessageEntry& status_message) { emit StatusMessageReceived(status_message); @@ -56,20 +56,20 @@ ModerationDialog::ModerationDialog(QWidget* parent) ModerationDialog::~ModerationDialog() { if (callback_handle_status_message) { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network.GetRoomMember().lock()) { room->Unbind(callback_handle_status_message); } } if (callback_handle_ban_list) { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network.GetRoomMember().lock()) { room->Unbind(callback_handle_ban_list); } } } void ModerationDialog::LoadBanList() { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network.GetRoomMember().lock()) { ui->refresh->setEnabled(false); ui->refresh->setText(tr("Refreshing")); ui->unban->setEnabled(false); @@ -98,7 +98,7 @@ void ModerationDialog::PopulateBanList(const Network::Room::BanList& ban_list) { } void ModerationDialog::SendUnbanRequest(const QString& subject) { - if (auto room = Network::GetRoomMember().lock()) { + if (auto room = room_network.GetRoomMember().lock()) { room->SendModerationRequest(Network::IdModUnban, subject.toStdString()); } } diff --git a/src/yuzu/multiplayer/moderation_dialog.h b/src/yuzu/multiplayer/moderation_dialog.h index d10083d5b8..8adec0cd89 100644 --- a/src/yuzu/multiplayer/moderation_dialog.h +++ b/src/yuzu/multiplayer/moderation_dialog.h @@ -20,7 +20,7 @@ class ModerationDialog : public QDialog { Q_OBJECT public: - explicit ModerationDialog(QWidget* parent = nullptr); + explicit ModerationDialog(Network::RoomNetwork& room_network_, QWidget* parent = nullptr); ~ModerationDialog(); signals: @@ -37,6 +37,8 @@ private: QStandardItemModel* model; Network::RoomMember::CallbackHandle callback_handle_status_message; Network::RoomMember::CallbackHandle callback_handle_ban_list; + + Network::RoomNetwork& room_network; }; Q_DECLARE_METATYPE(Network::Room::BanList); diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index ee138739b2..de25225dda 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -20,10 +20,11 @@ #include "yuzu/util/clickable_label.h" MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_list_model_, - QAction* leave_room_, QAction* show_room_) + QAction* leave_room_, QAction* show_room_, + Network::RoomNetwork& room_network_) : QWidget(parent), game_list_model(game_list_model_), leave_room(leave_room_), - show_room(show_room_) { - if (auto member = Network::GetRoomMember().lock()) { + show_room(show_room_), room_network{room_network_} { + if (auto member = room_network.GetRoomMember().lock()) { // register the network structs to use in slots and signals state_callback_handle = member->BindOnStateChanged( [this](const Network::RoomMember::State& state) { emit NetworkStateChanged(state); }); @@ -37,7 +38,7 @@ MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_lis qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); - announce_multiplayer_session = std::make_shared(); + announce_multiplayer_session = std::make_shared(room_network); announce_multiplayer_session->BindErrorCallback( [this](const WebService::WebResult& result) { emit AnnounceFailed(result); }); connect(this, &MultiplayerState::AnnounceFailed, this, &MultiplayerState::OnAnnounceFailed); @@ -61,13 +62,13 @@ MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_lis MultiplayerState::~MultiplayerState() { if (state_callback_handle) { - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { member->Unbind(state_callback_handle); } } if (error_callback_handle) { - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { member->Unbind(error_callback_handle); } } @@ -205,14 +206,15 @@ static void BringWidgetToFront(QWidget* widget) { void MultiplayerState::OnViewLobby() { if (lobby == nullptr) { - lobby = new Lobby(this, game_list_model, announce_multiplayer_session); + lobby = new Lobby(this, game_list_model, announce_multiplayer_session, room_network); } BringWidgetToFront(lobby); } void MultiplayerState::OnCreateRoom() { if (host_room == nullptr) { - host_room = new HostRoomWindow(this, game_list_model, announce_multiplayer_session); + host_room = + new HostRoomWindow(this, game_list_model, announce_multiplayer_session, room_network); } BringWidgetToFront(host_room); } @@ -220,9 +222,9 @@ void MultiplayerState::OnCreateRoom() { bool MultiplayerState::OnCloseRoom() { if (!NetworkMessage::WarnCloseRoom()) return false; - if (auto room = Network::GetRoom().lock()) { + if (auto room = room_network.GetRoom().lock()) { // if you are in a room, leave it - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { member->Leave(); LOG_DEBUG(Frontend, "Left the room (as a client)"); } @@ -257,10 +259,10 @@ void MultiplayerState::HideNotification() { } void MultiplayerState::OnOpenNetworkRoom() { - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = room_network.GetRoomMember().lock()) { if (member->IsConnected()) { if (client_room == nullptr) { - client_room = new ClientRoomWindow(this); + client_room = new ClientRoomWindow(this, room_network); connect(client_room, &ClientRoomWindow::ShowNotification, this, &MultiplayerState::ShowNotification); } @@ -275,7 +277,7 @@ void MultiplayerState::OnOpenNetworkRoom() { void MultiplayerState::OnDirectConnectToRoom() { if (direct_connect == nullptr) { - direct_connect = new DirectConnectWindow(this); + direct_connect = new DirectConnectWindow(room_network, this); } BringWidgetToFront(direct_connect); } diff --git a/src/yuzu/multiplayer/state.h b/src/yuzu/multiplayer/state.h index 414454acb9..bdd5cc954e 100644 --- a/src/yuzu/multiplayer/state.h +++ b/src/yuzu/multiplayer/state.h @@ -20,7 +20,7 @@ class MultiplayerState : public QWidget { public: explicit MultiplayerState(QWidget* parent, QStandardItemModel* game_list, QAction* leave_room, - QAction* show_room); + QAction* show_room, Network::RoomNetwork& room_network_); ~MultiplayerState(); /** @@ -87,6 +87,7 @@ private: Network::RoomMember::CallbackHandle error_callback_handle; bool show_notification = false; + Network::RoomNetwork& room_network; }; Q_DECLARE_METATYPE(WebService::WebResult); From 6b5667dfa55c2c0c9537a2f46537158e316d0508 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Sat, 23 Jul 2022 19:28:19 +0200 Subject: [PATCH 12/15] yuzu_cmd: Fix compilation --- src/network/room_member.h | 12 ------------ src/yuzu_cmd/yuzu.cpp | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/src/network/room_member.h b/src/network/room_member.h index c835ba8635..8d6254023e 100644 --- a/src/network/room_member.h +++ b/src/network/room_member.h @@ -8,7 +8,6 @@ #include #include #include -#include #include "common/announce_multiplayer_room.h" #include "common/common_types.h" #include "network/room.h" @@ -35,17 +34,6 @@ struct WifiPacket { MacAddress transmitter_address; ///< Mac address of the transmitter. MacAddress destination_address; ///< Mac address of the receiver. u8 channel; ///< WiFi channel where this frame was transmitted. - -private: - template - void serialize(Archive& ar, const unsigned int) { - ar& type; - ar& data; - ar& transmitter_address; - ar& destination_address; - ar& channel; - } - friend class boost::serialization::access; }; /// Represents a chat message. diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp index 0194940be4..e10d3f5b43 100644 --- a/src/yuzu_cmd/yuzu.cpp +++ b/src/yuzu_cmd/yuzu.cpp @@ -359,7 +359,7 @@ int main(int argc, char** argv) { system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL"); if (use_multiplayer) { - if (auto member = Network::GetRoomMember().lock()) { + if (auto member = system.GetRoomNetwork().GetRoomMember().lock()) { member->BindOnChatMessageRecieved(OnMessageReceived); member->BindOnStatusMessageReceived(OnStatusMessageReceived); member->BindOnStateChanged(OnStateChanged); From 6a2dcc8b3d4ed0940e33d60fee701bcdb063eb6b Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Mon, 25 Jul 2022 17:08:20 +0200 Subject: [PATCH 13/15] network, yuzu: Improve variable naming and style consistency --- src/common/announce_multiplayer_room.h | 2 +- src/network/network.cpp | 28 +++++++++++++------------- src/network/network.h | 4 ++-- src/network/room.cpp | 16 +++++++-------- src/network/room_member.cpp | 6 ++++-- src/network/verify_user.cpp | 2 +- src/network/verify_user.h | 6 +++--- src/web_service/announce_room_json.cpp | 4 ++-- src/web_service/verify_user_jwt.cpp | 4 ++-- src/web_service/verify_user_jwt.h | 2 +- src/yuzu/multiplayer/host_room.cpp | 2 +- src/yuzu/multiplayer/lobby.cpp | 8 ++++---- src/yuzu/multiplayer/lobby_p.h | 4 ++-- src/yuzu/multiplayer/state.cpp | 12 +++++++---- 14 files changed, 53 insertions(+), 47 deletions(-) diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h index a9e2f89b7a..11a80aa8ee 100644 --- a/src/common/announce_multiplayer_room.h +++ b/src/common/announce_multiplayer_room.h @@ -43,7 +43,7 @@ struct Room { RoomInformation information; std::string id; - std::string verify_UID; ///< UID used for verification + std::string verify_uid; ///< UID used for verification std::string ip; u32 net_version; bool has_password; diff --git a/src/network/network.cpp b/src/network/network.cpp index e1401a4031..36b70c36f2 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -10,8 +10,8 @@ namespace Network { RoomNetwork::RoomNetwork() { - g_room = std::make_shared(); - g_room_member = std::make_shared(); + m_room = std::make_shared(); + m_room_member = std::make_shared(); } bool RoomNetwork::Init() { @@ -19,30 +19,30 @@ bool RoomNetwork::Init() { LOG_ERROR(Network, "Error initalizing ENet"); return false; } - g_room = std::make_shared(); - g_room_member = std::make_shared(); + m_room = std::make_shared(); + m_room_member = std::make_shared(); LOG_DEBUG(Network, "initialized OK"); return true; } std::weak_ptr RoomNetwork::GetRoom() { - return g_room; + return m_room; } std::weak_ptr RoomNetwork::GetRoomMember() { - return g_room_member; + return m_room_member; } void RoomNetwork::Shutdown() { - if (g_room_member) { - if (g_room_member->IsConnected()) - g_room_member->Leave(); - g_room_member.reset(); + if (m_room_member) { + if (m_room_member->IsConnected()) + m_room_member->Leave(); + m_room_member.reset(); } - if (g_room) { - if (g_room->GetState() == Room::State::Open) - g_room->Destroy(); - g_room.reset(); + if (m_room) { + if (m_room->GetState() == Room::State::Open) + m_room->Destroy(); + m_room.reset(); } enet_deinitialize(); LOG_DEBUG(Network, "shutdown OK"); diff --git a/src/network/network.h b/src/network/network.h index 74eb42bf5c..a38f040293 100644 --- a/src/network/network.h +++ b/src/network/network.h @@ -27,8 +27,8 @@ public: void Shutdown(); private: - std::shared_ptr g_room_member; ///< RoomMember (Client) for network games - std::shared_ptr g_room; ///< Room (Server) for network games + std::shared_ptr m_room_member; ///< RoomMember (Client) for network games + std::shared_ptr m_room; ///< Room (Server) for network games }; } // namespace Network diff --git a/src/network/room.cpp b/src/network/room.cpp index 22491b2996..b22c5fb89c 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -29,8 +29,8 @@ public: std::atomic state{State::Closed}; ///< Current state of the room. RoomInformation room_information; ///< Information about this room. - std::string verify_UID; ///< A GUID which may be used for verfication. - mutable std::mutex verify_UID_mutex; ///< Mutex for verify_UID + std::string verify_uid; ///< A GUID which may be used for verfication. + mutable std::mutex verify_uid_mutex; ///< Mutex for verify_uid std::string password; ///< The password required to connect to this room. @@ -369,8 +369,8 @@ void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { std::string uid; { - std::lock_guard lock(verify_UID_mutex); - uid = verify_UID; + std::lock_guard lock(verify_uid_mutex); + uid = verify_uid; } member.user_data = verify_backend->LoadUserData(uid, token); @@ -1056,8 +1056,8 @@ const RoomInformation& Room::GetRoomInformation() const { } std::string Room::GetVerifyUID() const { - std::lock_guard lock(room_impl->verify_UID_mutex); - return room_impl->verify_UID; + std::lock_guard lock(room_impl->verify_uid_mutex); + return room_impl->verify_uid; } Room::BanList Room::GetBanList() const { @@ -1086,8 +1086,8 @@ bool Room::HasPassword() const { } void Room::SetVerifyUID(const std::string& uid) { - std::lock_guard lock(room_impl->verify_UID_mutex); - room_impl->verify_UID = uid; + std::lock_guard lock(room_impl->verify_uid_mutex); + room_impl->verify_uid = uid; } void Room::Destroy() { diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index 11a2e276ea..d8cb327210 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -416,8 +416,9 @@ void RoomMember::RoomMemberImpl::Disconnect() { room_information.member_slots = 0; room_information.name.clear(); - if (!server) + if (!server) { return; + } enet_peer_disconnect(server, 0); ENetEvent event; @@ -483,8 +484,9 @@ template void RoomMember::RoomMemberImpl::Invoke(const T& data) { std::lock_guard lock(callback_mutex); CallbackSet callback_set = callbacks.Get(); - for (auto const& callback : callback_set) + for (auto const& callback : callback_set) { (*callback)(data); + } } template diff --git a/src/network/verify_user.cpp b/src/network/verify_user.cpp index d9d98e4955..51094e9bc4 100644 --- a/src/network/verify_user.cpp +++ b/src/network/verify_user.cpp @@ -10,7 +10,7 @@ Backend::~Backend() = default; NullBackend::~NullBackend() = default; -UserData NullBackend::LoadUserData([[maybe_unused]] const std::string& verify_UID, +UserData NullBackend::LoadUserData([[maybe_unused]] const std::string& verify_uid, [[maybe_unused]] const std::string& token) { return {}; } diff --git a/src/network/verify_user.h b/src/network/verify_user.h index 5c3852d4aa..ddae67e99a 100644 --- a/src/network/verify_user.h +++ b/src/network/verify_user.h @@ -25,11 +25,11 @@ public: /** * Verifies the given token and loads the information into a UserData struct. - * @param verify_UID A GUID that may be used for verification. + * @param verify_uid A GUID that may be used for verification. * @param token A token that contains user data and verification data. The format and content is * decided by backends. */ - virtual UserData LoadUserData(const std::string& verify_UID, const std::string& token) = 0; + virtual UserData LoadUserData(const std::string& verify_uid, const std::string& token) = 0; }; /** @@ -40,7 +40,7 @@ class NullBackend final : public Backend { public: ~NullBackend(); - UserData LoadUserData(const std::string& verify_UID, const std::string& token) override; + UserData LoadUserData(const std::string& verify_uid, const std::string& token) override; }; } // namespace Network::VerifyUser diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 082bebaa92..0aae8e2155 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -54,7 +54,7 @@ static void to_json(nlohmann::json& json, const Room& room) { } static void from_json(const nlohmann::json& json, Room& room) { - room.verify_UID = json.at("externalGuid").get(); + room.verify_uid = json.at("externalGuid").get(); room.ip = json.at("address").get(); room.information.name = json.at("name").get(); try { @@ -116,7 +116,7 @@ WebService::WebResult RoomJson::Register() { auto reply_json = nlohmann::json::parse(result.returned_data); room = reply_json.get(); room_id = reply_json.at("id").get(); - return WebService::WebResult{WebService::WebResult::Code::Success, "", room.verify_UID}; + return WebService::WebResult{WebService::WebResult::Code::Success, "", room.verify_uid}; } void RoomJson::ClearPlayers() { diff --git a/src/web_service/verify_user_jwt.cpp b/src/web_service/verify_user_jwt.cpp index 3133dcbe26..2f294d378a 100644 --- a/src/web_service/verify_user_jwt.cpp +++ b/src/web_service/verify_user_jwt.cpp @@ -35,9 +35,9 @@ std::string GetPublicKey(const std::string& host) { VerifyUserJWT::VerifyUserJWT(const std::string& host) : pub_key(GetPublicKey(host)) {} -Network::VerifyUser::UserData VerifyUserJWT::LoadUserData(const std::string& verify_UID, +Network::VerifyUser::UserData VerifyUserJWT::LoadUserData(const std::string& verify_uid, const std::string& token) { - const std::string audience = fmt::format("external-{}", verify_UID); + const std::string audience = fmt::format("external-{}", verify_uid); using namespace jwt::params; std::error_code error; auto decoded = diff --git a/src/web_service/verify_user_jwt.h b/src/web_service/verify_user_jwt.h index 6db74c2089..ec3cc29043 100644 --- a/src/web_service/verify_user_jwt.h +++ b/src/web_service/verify_user_jwt.h @@ -17,7 +17,7 @@ public: VerifyUserJWT(const std::string& host); ~VerifyUserJWT() = default; - Network::VerifyUser::UserData LoadUserData(const std::string& verify_UID, + Network::VerifyUser::UserData LoadUserData(const std::string& verify_uid, const std::string& token) override; private: diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp index a48077544d..f59c6a28d5 100644 --- a/src/yuzu/multiplayer/host_room.cpp +++ b/src/yuzu/multiplayer/host_room.cpp @@ -163,7 +163,7 @@ void HostRoomWindow::Host() { // Start the announce session if they chose Public if (is_public) { if (auto session = announce_multiplayer_session.lock()) { - // Register the room first to ensure verify_UID is present when we connect + // Register the room first to ensure verify_uid is present when we connect WebService::WebResult result = session->Register(); if (result.result_code != WebService::WebResult::Code::Success) { QMessageBox::warning( diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index 0c6648ab5d..6daef97129 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -149,11 +149,11 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { const std::string ip = proxy->data(connection_index, LobbyItemHost::HostIPRole).toString().toStdString(); int port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt(); - const std::string verify_UID = + const std::string verify_uid = proxy->data(connection_index, LobbyItemHost::HostVerifyUIDRole).toString().toStdString(); // attempt to connect in a different thread - QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_UID, this] { + QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_uid, this] { std::string token; #ifdef ENABLE_WEB_SERVICE if (!Settings::values.yuzu_username.GetValue().empty() && @@ -161,7 +161,7 @@ void Lobby::OnJoinRoom(const QModelIndex& source) { WebService::Client client(Settings::values.web_api_url.GetValue(), Settings::values.yuzu_username.GetValue(), Settings::values.yuzu_token.GetValue()); - token = client.GetExternalJWT(verify_UID).returned_data; + token = client.GetExternalJWT(verify_uid).returned_data; if (token.empty()) { LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); } else { @@ -239,7 +239,7 @@ void Lobby::OnRefreshLobby() { smdh_icon), new LobbyItemHost(QString::fromStdString(room.information.host_username), QString::fromStdString(room.ip), room.information.port, - QString::fromStdString(room.verify_UID)), + QString::fromStdString(room.verify_uid)), new LobbyItemMemberList(members, room.information.member_slots), }); model->appendRow(row); diff --git a/src/yuzu/multiplayer/lobby_p.h b/src/yuzu/multiplayer/lobby_p.h index afb8b99dc0..bb2de4af31 100644 --- a/src/yuzu/multiplayer/lobby_p.h +++ b/src/yuzu/multiplayer/lobby_p.h @@ -123,11 +123,11 @@ public: static const int HostVerifyUIDRole = Qt::UserRole + 4; LobbyItemHost() = default; - explicit LobbyItemHost(QString username, QString ip, u16 port, QString verify_UID) { + explicit LobbyItemHost(QString username, QString ip, u16 port, QString verify_uid) { setData(username, HostUsernameRole); setData(ip, HostIPRole); setData(port, HostPortRole); - setData(verify_UID, HostVerifyUIDRole); + setData(verify_uid, HostVerifyUIDRole); } QVariant data(int role) const override { diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index de25225dda..661a32b3e5 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -98,14 +98,18 @@ void MultiplayerState::retranslateUi() { status_text->setText(tr("Not Connected")); } - if (lobby) + if (lobby) { lobby->RetranslateUi(); - if (host_room) + } + if (host_room) { host_room->RetranslateUi(); - if (client_room) + } + if (client_room) { client_room->RetranslateUi(); - if (direct_connect) + } + if (direct_connect) { direct_connect->RetranslateUi(); + } } void MultiplayerState::OnNetworkStateChanged(const Network::RoomMember::State& state) { From 61ce57b5242984c297283de5868ea4938391a911 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Mon, 25 Jul 2022 17:18:30 +0200 Subject: [PATCH 14/15] network, yuzu: Make copyright headers SPDX-compliant --- src/common/announce_multiplayer_room.h | 5 ++--- src/core/announce_multiplayer_session.cpp | 5 ++--- src/core/announce_multiplayer_session.h | 5 ++--- src/network/network.cpp | 5 ++--- src/network/network.h | 5 ++--- src/network/packet.cpp | 5 ++--- src/network/packet.h | 5 ++--- src/network/room.cpp | 5 ++--- src/network/room.h | 5 ++--- src/network/room_member.cpp | 5 ++--- src/network/room_member.h | 5 ++--- src/network/verify_user.cpp | 5 ++--- src/network/verify_user.h | 5 ++--- src/web_service/announce_room_json.cpp | 5 ++--- src/web_service/announce_room_json.h | 5 ++--- src/web_service/verify_user_jwt.cpp | 5 ++--- src/web_service/verify_user_jwt.h | 5 ++--- src/yuzu/multiplayer/chat_room.cpp | 5 ++--- src/yuzu/multiplayer/chat_room.h | 5 ++--- src/yuzu/multiplayer/client_room.cpp | 5 ++--- src/yuzu/multiplayer/client_room.h | 5 ++--- src/yuzu/multiplayer/direct_connect.cpp | 5 ++--- src/yuzu/multiplayer/direct_connect.h | 5 ++--- src/yuzu/multiplayer/host_room.cpp | 5 ++--- src/yuzu/multiplayer/host_room.h | 5 ++--- src/yuzu/multiplayer/lobby.cpp | 5 ++--- src/yuzu/multiplayer/lobby.h | 5 ++--- src/yuzu/multiplayer/lobby_p.h | 5 ++--- src/yuzu/multiplayer/message.cpp | 5 ++--- src/yuzu/multiplayer/message.h | 5 ++--- src/yuzu/multiplayer/moderation_dialog.cpp | 5 ++--- src/yuzu/multiplayer/moderation_dialog.h | 5 ++--- src/yuzu/multiplayer/state.cpp | 5 ++--- src/yuzu/multiplayer/state.h | 5 ++--- src/yuzu/multiplayer/validation.h | 5 ++--- src/yuzu/util/clickable_label.cpp | 5 ++--- src/yuzu/util/clickable_label.h | 5 ++--- 37 files changed, 74 insertions(+), 111 deletions(-) diff --git a/src/common/announce_multiplayer_room.h b/src/common/announce_multiplayer_room.h index 11a80aa8ee..0ad9da2be9 100644 --- a/src/common/announce_multiplayer_room.h +++ b/src/common/announce_multiplayer_room.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/core/announce_multiplayer_session.cpp b/src/core/announce_multiplayer_session.cpp index 8f96b4ee87..d73a488cf2 100644 --- a/src/core/announce_multiplayer_session.cpp +++ b/src/core/announce_multiplayer_session.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/core/announce_multiplayer_session.h b/src/core/announce_multiplayer_session.h index 5da3c1f8d0..db790f7d2d 100644 --- a/src/core/announce_multiplayer_session.h +++ b/src/core/announce_multiplayer_session.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/network/network.cpp b/src/network/network.cpp index 36b70c36f2..0841e41347 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include "common/assert.h" #include "common/logging/log.h" diff --git a/src/network/network.h b/src/network/network.h index a38f040293..e4de207b27 100644 --- a/src/network/network.h +++ b/src/network/network.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/network/packet.cpp b/src/network/packet.cpp index a3c1e16440..d6c8dc6463 100644 --- a/src/network/packet.cpp +++ b/src/network/packet.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #ifdef _WIN32 #include diff --git a/src/network/packet.h b/src/network/packet.h index 7bdc3da958..aa9fa39e2d 100644 --- a/src/network/packet.h +++ b/src/network/packet.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/network/room.cpp b/src/network/room.cpp index b22c5fb89c..d5f0bb723d 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/network/room.h b/src/network/room.h index 90a82563f2..6f7e3b5b53 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index d8cb327210..38a6f6bfd7 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/network/room_member.h b/src/network/room_member.h index 8d6254023e..bbb7d13d4c 100644 --- a/src/network/room_member.h +++ b/src/network/room_member.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/network/verify_user.cpp b/src/network/verify_user.cpp index 51094e9bc4..f84cfe59b6 100644 --- a/src/network/verify_user.cpp +++ b/src/network/verify_user.cpp @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include "network/verify_user.h" diff --git a/src/network/verify_user.h b/src/network/verify_user.h index ddae67e99a..6fc64d8a3e 100644 --- a/src/network/verify_user.h +++ b/src/network/verify_user.h @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/web_service/announce_room_json.cpp b/src/web_service/announce_room_json.cpp index 0aae8e2155..4c3195efda 100644 --- a/src/web_service/announce_room_json.cpp +++ b/src/web_service/announce_room_json.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/web_service/announce_room_json.h b/src/web_service/announce_room_json.h index 24ec29c65e..32c08858dd 100644 --- a/src/web_service/announce_room_json.h +++ b/src/web_service/announce_room_json.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/web_service/verify_user_jwt.cpp b/src/web_service/verify_user_jwt.cpp index 2f294d378a..3bff46f0ac 100644 --- a/src/web_service/verify_user_jwt.cpp +++ b/src/web_service/verify_user_jwt.cpp @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push diff --git a/src/web_service/verify_user_jwt.h b/src/web_service/verify_user_jwt.h index ec3cc29043..27b0a100c6 100644 --- a/src/web_service/verify_user_jwt.h +++ b/src/web_service/verify_user_jwt.h @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/chat_room.cpp b/src/yuzu/multiplayer/chat_room.cpp index 9f2c57eee3..5837b36ab5 100644 --- a/src/yuzu/multiplayer/chat_room.cpp +++ b/src/yuzu/multiplayer/chat_room.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/chat_room.h b/src/yuzu/multiplayer/chat_room.h index 9179d16fbb..01c70fad07 100644 --- a/src/yuzu/multiplayer/chat_room.h +++ b/src/yuzu/multiplayer/chat_room.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/client_room.cpp b/src/yuzu/multiplayer/client_room.cpp index 9bef9bdfcd..a9859ed702 100644 --- a/src/yuzu/multiplayer/client_room.cpp +++ b/src/yuzu/multiplayer/client_room.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/client_room.h b/src/yuzu/multiplayer/client_room.h index 6303b2595f..f338e3c592 100644 --- a/src/yuzu/multiplayer/client_room.h +++ b/src/yuzu/multiplayer/client_room.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/direct_connect.cpp b/src/yuzu/multiplayer/direct_connect.cpp index 360d66beae..9000c45312 100644 --- a/src/yuzu/multiplayer/direct_connect.cpp +++ b/src/yuzu/multiplayer/direct_connect.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/direct_connect.h b/src/yuzu/multiplayer/direct_connect.h index 719030d29c..4e10430532 100644 --- a/src/yuzu/multiplayer/direct_connect.h +++ b/src/yuzu/multiplayer/direct_connect.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/host_room.cpp b/src/yuzu/multiplayer/host_room.cpp index f59c6a28d5..cb9464b2bc 100644 --- a/src/yuzu/multiplayer/host_room.cpp +++ b/src/yuzu/multiplayer/host_room.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/host_room.h b/src/yuzu/multiplayer/host_room.h index 98a56458f9..a968042d03 100644 --- a/src/yuzu/multiplayer/host_room.h +++ b/src/yuzu/multiplayer/host_room.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/lobby.cpp b/src/yuzu/multiplayer/lobby.cpp index 6daef97129..23c2f21ab0 100644 --- a/src/yuzu/multiplayer/lobby.cpp +++ b/src/yuzu/multiplayer/lobby.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/lobby.h b/src/yuzu/multiplayer/lobby.h index ec6ec26628..82744ca945 100644 --- a/src/yuzu/multiplayer/lobby.h +++ b/src/yuzu/multiplayer/lobby.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/lobby_p.h b/src/yuzu/multiplayer/lobby_p.h index bb2de4af31..8071cede4d 100644 --- a/src/yuzu/multiplayer/lobby_p.h +++ b/src/yuzu/multiplayer/lobby_p.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/message.cpp b/src/yuzu/multiplayer/message.cpp index 458f1e7d1f..76ec276ad7 100644 --- a/src/yuzu/multiplayer/message.cpp +++ b/src/yuzu/multiplayer/message.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/message.h b/src/yuzu/multiplayer/message.h index 49a31997dd..eb5c8d1be5 100644 --- a/src/yuzu/multiplayer/message.h +++ b/src/yuzu/multiplayer/message.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/moderation_dialog.cpp b/src/yuzu/multiplayer/moderation_dialog.cpp index fc3f36c57e..c9b8ed397a 100644 --- a/src/yuzu/multiplayer/moderation_dialog.cpp +++ b/src/yuzu/multiplayer/moderation_dialog.cpp @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/moderation_dialog.h b/src/yuzu/multiplayer/moderation_dialog.h index 8adec0cd89..e9e5daff79 100644 --- a/src/yuzu/multiplayer/moderation_dialog.h +++ b/src/yuzu/multiplayer/moderation_dialog.h @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index 661a32b3e5..015c59788a 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include #include diff --git a/src/yuzu/multiplayer/state.h b/src/yuzu/multiplayer/state.h index bdd5cc954e..9c60712d51 100644 --- a/src/yuzu/multiplayer/state.h +++ b/src/yuzu/multiplayer/state.h @@ -1,6 +1,5 @@ -// Copyright 2018 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/multiplayer/validation.h b/src/yuzu/multiplayer/validation.h index 1c215a1909..7d48e589d4 100644 --- a/src/yuzu/multiplayer/validation.h +++ b/src/yuzu/multiplayer/validation.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once diff --git a/src/yuzu/util/clickable_label.cpp b/src/yuzu/util/clickable_label.cpp index 5bde838ca4..89d14190ac 100644 --- a/src/yuzu/util/clickable_label.cpp +++ b/src/yuzu/util/clickable_label.cpp @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #include "yuzu/util/clickable_label.h" diff --git a/src/yuzu/util/clickable_label.h b/src/yuzu/util/clickable_label.h index 3c65a74bec..4fe7441506 100644 --- a/src/yuzu/util/clickable_label.h +++ b/src/yuzu/util/clickable_label.h @@ -1,6 +1,5 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later #pragma once From a41baaa181f30229d3552caa69135be978c1ddb5 Mon Sep 17 00:00:00 2001 From: FearlessTobi Date: Mon, 25 Jul 2022 19:16:59 +0200 Subject: [PATCH 15/15] network: Address review comments --- src/network/packet.cpp | 64 +++++++-------- src/network/packet.h | 84 ++++++++++---------- src/network/room.cpp | 140 ++++++++++++++++----------------- src/network/room_member.cpp | 98 +++++++++++------------ src/yuzu/multiplayer/state.cpp | 12 ++- 5 files changed, 201 insertions(+), 197 deletions(-) diff --git a/src/network/packet.cpp b/src/network/packet.cpp index d6c8dc6463..0e22f1eb4d 100644 --- a/src/network/packet.cpp +++ b/src/network/packet.cpp @@ -65,80 +65,80 @@ Packet::operator bool() const { return is_valid; } -Packet& Packet::operator>>(bool& out_data) { +Packet& Packet::Read(bool& out_data) { u8 value{}; - if (*this >> value) { + if (Read(value)) { out_data = (value != 0); } return *this; } -Packet& Packet::operator>>(s8& out_data) { +Packet& Packet::Read(s8& out_data) { Read(&out_data, sizeof(out_data)); return *this; } -Packet& Packet::operator>>(u8& out_data) { +Packet& Packet::Read(u8& out_data) { Read(&out_data, sizeof(out_data)); return *this; } -Packet& Packet::operator>>(s16& out_data) { +Packet& Packet::Read(s16& out_data) { s16 value{}; Read(&value, sizeof(value)); out_data = ntohs(value); return *this; } -Packet& Packet::operator>>(u16& out_data) { +Packet& Packet::Read(u16& out_data) { u16 value{}; Read(&value, sizeof(value)); out_data = ntohs(value); return *this; } -Packet& Packet::operator>>(s32& out_data) { +Packet& Packet::Read(s32& out_data) { s32 value{}; Read(&value, sizeof(value)); out_data = ntohl(value); return *this; } -Packet& Packet::operator>>(u32& out_data) { +Packet& Packet::Read(u32& out_data) { u32 value{}; Read(&value, sizeof(value)); out_data = ntohl(value); return *this; } -Packet& Packet::operator>>(s64& out_data) { +Packet& Packet::Read(s64& out_data) { s64 value{}; Read(&value, sizeof(value)); out_data = ntohll(value); return *this; } -Packet& Packet::operator>>(u64& out_data) { +Packet& Packet::Read(u64& out_data) { u64 value{}; Read(&value, sizeof(value)); out_data = ntohll(value); return *this; } -Packet& Packet::operator>>(float& out_data) { +Packet& Packet::Read(float& out_data) { Read(&out_data, sizeof(out_data)); return *this; } -Packet& Packet::operator>>(double& out_data) { +Packet& Packet::Read(double& out_data) { Read(&out_data, sizeof(out_data)); return *this; } -Packet& Packet::operator>>(char* out_data) { +Packet& Packet::Read(char* out_data) { // First extract string length u32 length = 0; - *this >> length; + Read(length); if ((length > 0) && CheckSize(length)) { // Then extract characters @@ -152,10 +152,10 @@ Packet& Packet::operator>>(char* out_data) { return *this; } -Packet& Packet::operator>>(std::string& out_data) { +Packet& Packet::Read(std::string& out_data) { // First extract string length u32 length = 0; - *this >> length; + Read(length); out_data.clear(); if ((length > 0) && CheckSize(length)) { @@ -169,71 +169,71 @@ Packet& Packet::operator>>(std::string& out_data) { return *this; } -Packet& Packet::operator<<(bool in_data) { - *this << static_cast(in_data); +Packet& Packet::Write(bool in_data) { + Write(static_cast(in_data)); return *this; } -Packet& Packet::operator<<(s8 in_data) { +Packet& Packet::Write(s8 in_data) { Append(&in_data, sizeof(in_data)); return *this; } -Packet& Packet::operator<<(u8 in_data) { +Packet& Packet::Write(u8 in_data) { Append(&in_data, sizeof(in_data)); return *this; } -Packet& Packet::operator<<(s16 in_data) { +Packet& Packet::Write(s16 in_data) { s16 toWrite = htons(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(u16 in_data) { +Packet& Packet::Write(u16 in_data) { u16 toWrite = htons(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(s32 in_data) { +Packet& Packet::Write(s32 in_data) { s32 toWrite = htonl(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(u32 in_data) { +Packet& Packet::Write(u32 in_data) { u32 toWrite = htonl(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(s64 in_data) { +Packet& Packet::Write(s64 in_data) { s64 toWrite = htonll(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(u64 in_data) { +Packet& Packet::Write(u64 in_data) { u64 toWrite = htonll(in_data); Append(&toWrite, sizeof(toWrite)); return *this; } -Packet& Packet::operator<<(float in_data) { +Packet& Packet::Write(float in_data) { Append(&in_data, sizeof(in_data)); return *this; } -Packet& Packet::operator<<(double in_data) { +Packet& Packet::Write(double in_data) { Append(&in_data, sizeof(in_data)); return *this; } -Packet& Packet::operator<<(const char* in_data) { +Packet& Packet::Write(const char* in_data) { // First insert string length u32 length = static_cast(std::strlen(in_data)); - *this << length; + Write(length); // Then insert characters Append(in_data, length * sizeof(char)); @@ -241,10 +241,10 @@ Packet& Packet::operator<<(const char* in_data) { return *this; } -Packet& Packet::operator<<(const std::string& in_data) { +Packet& Packet::Write(const std::string& in_data) { // First insert string length u32 length = static_cast(in_data.size()); - *this << length; + Write(length); // Then insert characters if (length > 0) diff --git a/src/network/packet.h b/src/network/packet.h index aa9fa39e2d..e69217488c 100644 --- a/src/network/packet.h +++ b/src/network/packet.h @@ -63,43 +63,43 @@ public: explicit operator bool() const; - /// Overloads of operator >> to read data from the packet - Packet& operator>>(bool& out_data); - Packet& operator>>(s8& out_data); - Packet& operator>>(u8& out_data); - Packet& operator>>(s16& out_data); - Packet& operator>>(u16& out_data); - Packet& operator>>(s32& out_data); - Packet& operator>>(u32& out_data); - Packet& operator>>(s64& out_data); - Packet& operator>>(u64& out_data); - Packet& operator>>(float& out_data); - Packet& operator>>(double& out_data); - Packet& operator>>(char* out_data); - Packet& operator>>(std::string& out_data); + /// Overloads of read function to read data from the packet + Packet& Read(bool& out_data); + Packet& Read(s8& out_data); + Packet& Read(u8& out_data); + Packet& Read(s16& out_data); + Packet& Read(u16& out_data); + Packet& Read(s32& out_data); + Packet& Read(u32& out_data); + Packet& Read(s64& out_data); + Packet& Read(u64& out_data); + Packet& Read(float& out_data); + Packet& Read(double& out_data); + Packet& Read(char* out_data); + Packet& Read(std::string& out_data); template - Packet& operator>>(std::vector& out_data); + Packet& Read(std::vector& out_data); template - Packet& operator>>(std::array& out_data); + Packet& Read(std::array& out_data); - /// Overloads of operator << to write data into the packet - Packet& operator<<(bool in_data); - Packet& operator<<(s8 in_data); - Packet& operator<<(u8 in_data); - Packet& operator<<(s16 in_data); - Packet& operator<<(u16 in_data); - Packet& operator<<(s32 in_data); - Packet& operator<<(u32 in_data); - Packet& operator<<(s64 in_data); - Packet& operator<<(u64 in_data); - Packet& operator<<(float in_data); - Packet& operator<<(double in_data); - Packet& operator<<(const char* in_data); - Packet& operator<<(const std::string& in_data); + /// Overloads of write function to write data into the packet + Packet& Write(bool in_data); + Packet& Write(s8 in_data); + Packet& Write(u8 in_data); + Packet& Write(s16 in_data); + Packet& Write(u16 in_data); + Packet& Write(s32 in_data); + Packet& Write(u32 in_data); + Packet& Write(s64 in_data); + Packet& Write(u64 in_data); + Packet& Write(float in_data); + Packet& Write(double in_data); + Packet& Write(const char* in_data); + Packet& Write(const std::string& in_data); template - Packet& operator<<(const std::vector& in_data); + Packet& Write(const std::vector& in_data); template - Packet& operator<<(const std::array& data); + Packet& Write(const std::array& data); private: /** @@ -117,47 +117,47 @@ private: }; template -Packet& Packet::operator>>(std::vector& out_data) { +Packet& Packet::Read(std::vector& out_data) { // First extract the size u32 size = 0; - *this >> size; + Read(size); out_data.resize(size); // Then extract the data for (std::size_t i = 0; i < out_data.size(); ++i) { T character; - *this >> character; + Read(character); out_data[i] = character; } return *this; } template -Packet& Packet::operator>>(std::array& out_data) { +Packet& Packet::Read(std::array& out_data) { for (std::size_t i = 0; i < out_data.size(); ++i) { T character; - *this >> character; + Read(character); out_data[i] = character; } return *this; } template -Packet& Packet::operator<<(const std::vector& in_data) { +Packet& Packet::Write(const std::vector& in_data) { // First insert the size - *this << static_cast(in_data.size()); + Write(static_cast(in_data.size())); // Then insert the data for (std::size_t i = 0; i < in_data.size(); ++i) { - *this << in_data[i]; + Write(in_data[i]); } return *this; } template -Packet& Packet::operator<<(const std::array& in_data) { +Packet& Packet::Write(const std::array& in_data) { for (std::size_t i = 0; i < in_data.size(); ++i) { - *this << in_data[i]; + Write(in_data[i]); } return *this; } diff --git a/src/network/room.cpp b/src/network/room.cpp index d5f0bb723d..3fc3a0383c 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include "common/logging/log.h" @@ -43,9 +44,8 @@ public: ENetPeer* peer; ///< The remote peer. }; using MemberList = std::vector; - MemberList members; ///< Information about the members of this room - mutable std::mutex member_mutex; ///< Mutex for locking the members list - /// This should be a std::shared_mutex as soon as C++17 is supported + MemberList members; ///< Information about the members of this room + mutable std::shared_mutex member_mutex; ///< Mutex for locking the members list UsernameBanList username_ban_list; ///< List of banned usernames IPBanList ip_ban_list; ///< List of banned IP addresses @@ -311,22 +311,22 @@ void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { packet.Append(event->packet->data, event->packet->dataLength); packet.IgnoreBytes(sizeof(u8)); // Ignore the message type std::string nickname; - packet >> nickname; + packet.Read(nickname); std::string console_id_hash; - packet >> console_id_hash; + packet.Read(console_id_hash); MacAddress preferred_mac; - packet >> preferred_mac; + packet.Read(preferred_mac); u32 client_version; - packet >> client_version; + packet.Read(client_version); std::string pass; - packet >> pass; + packet.Read(pass); std::string token; - packet >> token; + packet.Read(token); if (pass != password) { SendWrongPassword(event->peer); @@ -387,9 +387,9 @@ void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { } // Check IP ban - char ip_raw[256]; - enet_address_get_host_ip(&event->peer->address, ip_raw, sizeof(ip_raw) - 1); - ip = ip_raw; + std::array ip_raw{}; + enet_address_get_host_ip(&event->peer->address, ip_raw.data(), sizeof(ip_raw) - 1); + ip = ip_raw.data(); if (std::find(ip_ban_list.begin(), ip_ban_list.end(), ip) != ip_ban_list.end()) { SendUserBanned(event->peer); @@ -425,7 +425,7 @@ void Room::RoomImpl::HandleModKickPacket(const ENetEvent* event) { packet.IgnoreBytes(sizeof(u8)); // Ignore the message type std::string nickname; - packet >> nickname; + packet.Read(nickname); std::string username, ip; { @@ -443,9 +443,9 @@ void Room::RoomImpl::HandleModKickPacket(const ENetEvent* event) { username = target_member->user_data.username; - char ip_raw[256]; - enet_address_get_host_ip(&target_member->peer->address, ip_raw, sizeof(ip_raw) - 1); - ip = ip_raw; + std::array ip_raw{}; + enet_address_get_host_ip(&target_member->peer->address, ip_raw.data(), sizeof(ip_raw) - 1); + ip = ip_raw.data(); enet_peer_disconnect(target_member->peer, 0); members.erase(target_member); @@ -467,7 +467,7 @@ void Room::RoomImpl::HandleModBanPacket(const ENetEvent* event) { packet.IgnoreBytes(sizeof(u8)); // Ignore the message type std::string nickname; - packet >> nickname; + packet.Read(nickname); std::string username, ip; { @@ -486,9 +486,9 @@ void Room::RoomImpl::HandleModBanPacket(const ENetEvent* event) { nickname = target_member->nickname; username = target_member->user_data.username; - char ip_raw[256]; - enet_address_get_host_ip(&target_member->peer->address, ip_raw, sizeof(ip_raw) - 1); - ip = ip_raw; + std::array ip_raw{}; + enet_address_get_host_ip(&target_member->peer->address, ip_raw.data(), sizeof(ip_raw) - 1); + ip = ip_raw.data(); enet_peer_disconnect(target_member->peer, 0); members.erase(target_member); @@ -528,7 +528,7 @@ void Room::RoomImpl::HandleModUnbanPacket(const ENetEvent* event) { packet.IgnoreBytes(sizeof(u8)); // Ignore the message type std::string address; - packet >> address; + packet.Read(address); bool unbanned = false; { @@ -613,7 +613,7 @@ bool Room::RoomImpl::HasModPermission(const ENetPeer* client) const { void Room::RoomImpl::SendNameCollision(ENetPeer* client) { Packet packet; - packet << static_cast(IdNameCollision); + packet.Write(static_cast(IdNameCollision)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -623,7 +623,7 @@ void Room::RoomImpl::SendNameCollision(ENetPeer* client) { void Room::RoomImpl::SendMacCollision(ENetPeer* client) { Packet packet; - packet << static_cast(IdMacCollision); + packet.Write(static_cast(IdMacCollision)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -633,7 +633,7 @@ void Room::RoomImpl::SendMacCollision(ENetPeer* client) { void Room::RoomImpl::SendConsoleIdCollision(ENetPeer* client) { Packet packet; - packet << static_cast(IdConsoleIdCollision); + packet.Write(static_cast(IdConsoleIdCollision)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -643,7 +643,7 @@ void Room::RoomImpl::SendConsoleIdCollision(ENetPeer* client) { void Room::RoomImpl::SendWrongPassword(ENetPeer* client) { Packet packet; - packet << static_cast(IdWrongPassword); + packet.Write(static_cast(IdWrongPassword)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -653,7 +653,7 @@ void Room::RoomImpl::SendWrongPassword(ENetPeer* client) { void Room::RoomImpl::SendRoomIsFull(ENetPeer* client) { Packet packet; - packet << static_cast(IdRoomIsFull); + packet.Write(static_cast(IdRoomIsFull)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -663,8 +663,8 @@ void Room::RoomImpl::SendRoomIsFull(ENetPeer* client) { void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) { Packet packet; - packet << static_cast(IdVersionMismatch); - packet << network_version; + packet.Write(static_cast(IdVersionMismatch)); + packet.Write(network_version); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -674,8 +674,8 @@ void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) { void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) { Packet packet; - packet << static_cast(IdJoinSuccess); - packet << mac_address; + packet.Write(static_cast(IdJoinSuccess)); + packet.Write(mac_address); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(client, 0, enet_packet); @@ -684,8 +684,8 @@ void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) { void Room::RoomImpl::SendJoinSuccessAsMod(ENetPeer* client, MacAddress mac_address) { Packet packet; - packet << static_cast(IdJoinSuccessAsMod); - packet << mac_address; + packet.Write(static_cast(IdJoinSuccessAsMod)); + packet.Write(mac_address); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(client, 0, enet_packet); @@ -694,7 +694,7 @@ void Room::RoomImpl::SendJoinSuccessAsMod(ENetPeer* client, MacAddress mac_addre void Room::RoomImpl::SendUserKicked(ENetPeer* client) { Packet packet; - packet << static_cast(IdHostKicked); + packet.Write(static_cast(IdHostKicked)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -704,7 +704,7 @@ void Room::RoomImpl::SendUserKicked(ENetPeer* client) { void Room::RoomImpl::SendUserBanned(ENetPeer* client) { Packet packet; - packet << static_cast(IdHostBanned); + packet.Write(static_cast(IdHostBanned)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -714,7 +714,7 @@ void Room::RoomImpl::SendUserBanned(ENetPeer* client) { void Room::RoomImpl::SendModPermissionDenied(ENetPeer* client) { Packet packet; - packet << static_cast(IdModPermissionDenied); + packet.Write(static_cast(IdModPermissionDenied)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -724,7 +724,7 @@ void Room::RoomImpl::SendModPermissionDenied(ENetPeer* client) { void Room::RoomImpl::SendModNoSuchUser(ENetPeer* client) { Packet packet; - packet << static_cast(IdModNoSuchUser); + packet.Write(static_cast(IdModNoSuchUser)); ENetPacket* enet_packet = enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -734,11 +734,11 @@ void Room::RoomImpl::SendModNoSuchUser(ENetPeer* client) { void Room::RoomImpl::SendModBanListResponse(ENetPeer* client) { Packet packet; - packet << static_cast(IdModBanListResponse); + packet.Write(static_cast(IdModBanListResponse)); { std::lock_guard lock(ban_list_mutex); - packet << username_ban_list; - packet << ip_ban_list; + packet.Write(username_ban_list); + packet.Write(ip_ban_list); } ENetPacket* enet_packet = @@ -749,7 +749,7 @@ void Room::RoomImpl::SendModBanListResponse(ENetPeer* client) { void Room::RoomImpl::SendCloseMessage() { Packet packet; - packet << static_cast(IdCloseRoom); + packet.Write(static_cast(IdCloseRoom)); std::lock_guard lock(member_mutex); if (!members.empty()) { ENetPacket* enet_packet = @@ -767,10 +767,10 @@ void Room::RoomImpl::SendCloseMessage() { void Room::RoomImpl::SendStatusMessage(StatusMessageTypes type, const std::string& nickname, const std::string& username, const std::string& ip) { Packet packet; - packet << static_cast(IdStatusMessage); - packet << static_cast(type); - packet << nickname; - packet << username; + packet.Write(static_cast(IdStatusMessage)); + packet.Write(static_cast(type)); + packet.Write(nickname); + packet.Write(username); std::lock_guard lock(member_mutex); if (!members.empty()) { ENetPacket* enet_packet = @@ -805,25 +805,25 @@ void Room::RoomImpl::SendStatusMessage(StatusMessageTypes type, const std::strin void Room::RoomImpl::BroadcastRoomInformation() { Packet packet; - packet << static_cast(IdRoomInformation); - packet << room_information.name; - packet << room_information.description; - packet << room_information.member_slots; - packet << room_information.port; - packet << room_information.preferred_game.name; - packet << room_information.host_username; + packet.Write(static_cast(IdRoomInformation)); + packet.Write(room_information.name); + packet.Write(room_information.description); + packet.Write(room_information.member_slots); + packet.Write(room_information.port); + packet.Write(room_information.preferred_game.name); + packet.Write(room_information.host_username); - packet << static_cast(members.size()); + packet.Write(static_cast(members.size())); { std::lock_guard lock(member_mutex); for (const auto& member : members) { - packet << member.nickname; - packet << member.mac_address; - packet << member.game_info.name; - packet << member.game_info.id; - packet << member.user_data.username; - packet << member.user_data.display_name; - packet << member.user_data.avatar_url; + packet.Write(member.nickname); + packet.Write(member.mac_address); + packet.Write(member.game_info.name); + packet.Write(member.game_info.id); + packet.Write(member.user_data.username); + packet.Write(member.user_data.display_name); + packet.Write(member.user_data.avatar_url); } } @@ -853,7 +853,7 @@ void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) { in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Channel in_packet.IgnoreBytes(sizeof(MacAddress)); // WifiPacket Transmitter Address MacAddress destination_address; - in_packet >> destination_address; + in_packet.Read(destination_address); Packet out_packet; out_packet.Append(event->packet->data, event->packet->dataLength); @@ -899,7 +899,7 @@ void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) { in_packet.IgnoreBytes(sizeof(u8)); // Ignore the message type std::string message; - in_packet >> message; + in_packet.Read(message); auto CompareNetworkAddress = [event](const Member member) -> bool { return member.peer == event->peer; }; @@ -914,10 +914,10 @@ void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) { message.resize(std::min(static_cast(message.size()), MaxMessageSize)); Packet out_packet; - out_packet << static_cast(IdChatMessage); - out_packet << sending_member->nickname; - out_packet << sending_member->user_data.username; - out_packet << message; + out_packet.Write(static_cast(IdChatMessage)); + out_packet.Write(sending_member->nickname); + out_packet.Write(sending_member->user_data.username); + out_packet.Write(message); ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); @@ -949,8 +949,8 @@ void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) { in_packet.IgnoreBytes(sizeof(u8)); // Ignore the message type GameInfo game_info; - in_packet >> game_info.name; - in_packet >> game_info.id; + in_packet.Read(game_info.name); + in_packet.Read(game_info.id); { std::lock_guard lock(member_mutex); @@ -989,9 +989,9 @@ void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) { nickname = member->nickname; username = member->user_data.username; - char ip_raw[256]; - enet_address_get_host_ip(&member->peer->address, ip_raw, sizeof(ip_raw) - 1); - ip = ip_raw; + std::array ip_raw{}; + enet_address_get_host_ip(&member->peer->address, ip_raw.data(), sizeof(ip_raw) - 1); + ip = ip_raw.data(); members.erase(member); } diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index 38a6f6bfd7..e4f823e981 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -280,13 +280,13 @@ void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname_, const std::string& password, const std::string& token) { Packet packet; - packet << static_cast(IdJoinRequest); - packet << nickname_; - packet << console_id_hash; - packet << preferred_mac; - packet << network_version; - packet << password; - packet << token; + packet.Write(static_cast(IdJoinRequest)); + packet.Write(nickname_); + packet.Write(console_id_hash); + packet.Write(preferred_mac); + packet.Write(network_version); + packet.Write(password); + packet.Write(token); Send(std::move(packet)); } @@ -298,12 +298,12 @@ void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* ev packet.IgnoreBytes(sizeof(u8)); // Ignore the message type RoomInformation info{}; - packet >> info.name; - packet >> info.description; - packet >> info.member_slots; - packet >> info.port; - packet >> info.preferred_game.name; - packet >> info.host_username; + packet.Read(info.name); + packet.Read(info.description); + packet.Read(info.member_slots); + packet.Read(info.port); + packet.Read(info.preferred_game.name); + packet.Read(info.host_username); room_information.name = info.name; room_information.description = info.description; room_information.member_slots = info.member_slots; @@ -312,17 +312,17 @@ void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* ev room_information.host_username = info.host_username; u32 num_members; - packet >> num_members; + packet.Read(num_members); member_information.resize(num_members); for (auto& member : member_information) { - packet >> member.nickname; - packet >> member.mac_address; - packet >> member.game_info.name; - packet >> member.game_info.id; - packet >> member.username; - packet >> member.display_name; - packet >> member.avatar_url; + packet.Read(member.nickname); + packet.Read(member.mac_address); + packet.Read(member.game_info.name); + packet.Read(member.game_info.id); + packet.Read(member.username); + packet.Read(member.display_name); + packet.Read(member.avatar_url); { std::lock_guard lock(username_mutex); @@ -342,7 +342,7 @@ void RoomMember::RoomMemberImpl::HandleJoinPacket(const ENetEvent* event) { packet.IgnoreBytes(sizeof(u8)); // Ignore the message type // Parse the MAC Address from the packet - packet >> mac_address; + packet.Read(mac_address); } void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) { @@ -355,14 +355,14 @@ void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) { // Parse the WifiPacket from the packet u8 frame_type; - packet >> frame_type; + packet.Read(frame_type); WifiPacket::PacketType type = static_cast(frame_type); wifi_packet.type = type; - packet >> wifi_packet.channel; - packet >> wifi_packet.transmitter_address; - packet >> wifi_packet.destination_address; - packet >> wifi_packet.data; + packet.Read(wifi_packet.channel); + packet.Read(wifi_packet.transmitter_address); + packet.Read(wifi_packet.destination_address); + packet.Read(wifi_packet.data); Invoke(wifi_packet); } @@ -375,9 +375,9 @@ void RoomMember::RoomMemberImpl::HandleChatPacket(const ENetEvent* event) { packet.IgnoreBytes(sizeof(u8)); ChatEntry chat_entry{}; - packet >> chat_entry.nickname; - packet >> chat_entry.username; - packet >> chat_entry.message; + packet.Read(chat_entry.nickname); + packet.Read(chat_entry.username); + packet.Read(chat_entry.message); Invoke(chat_entry); } @@ -390,10 +390,10 @@ void RoomMember::RoomMemberImpl::HandleStatusMessagePacket(const ENetEvent* even StatusMessageEntry status_message_entry{}; u8 type{}; - packet >> type; + packet.Read(type); status_message_entry.type = static_cast(type); - packet >> status_message_entry.nickname; - packet >> status_message_entry.username; + packet.Read(status_message_entry.nickname); + packet.Read(status_message_entry.username); Invoke(status_message_entry); } @@ -405,8 +405,8 @@ void RoomMember::RoomMemberImpl::HandleModBanListResponsePacket(const ENetEvent* packet.IgnoreBytes(sizeof(u8)); Room::BanList ban_list = {}; - packet >> ban_list.first; - packet >> ban_list.second; + packet.Read(ban_list.first); + packet.Read(ban_list.second); Invoke(ban_list); } @@ -586,19 +586,19 @@ bool RoomMember::IsConnected() const { void RoomMember::SendWifiPacket(const WifiPacket& wifi_packet) { Packet packet; - packet << static_cast(IdWifiPacket); - packet << static_cast(wifi_packet.type); - packet << wifi_packet.channel; - packet << wifi_packet.transmitter_address; - packet << wifi_packet.destination_address; - packet << wifi_packet.data; + packet.Write(static_cast(IdWifiPacket)); + packet.Write(static_cast(wifi_packet.type)); + packet.Write(wifi_packet.channel); + packet.Write(wifi_packet.transmitter_address); + packet.Write(wifi_packet.destination_address); + packet.Write(wifi_packet.data); room_member_impl->Send(std::move(packet)); } void RoomMember::SendChatMessage(const std::string& message) { Packet packet; - packet << static_cast(IdChatMessage); - packet << message; + packet.Write(static_cast(IdChatMessage)); + packet.Write(message); room_member_impl->Send(std::move(packet)); } @@ -608,9 +608,9 @@ void RoomMember::SendGameInfo(const GameInfo& game_info) { return; Packet packet; - packet << static_cast(IdSetGameInfo); - packet << game_info.name; - packet << game_info.id; + packet.Write(static_cast(IdSetGameInfo)); + packet.Write(game_info.name); + packet.Write(game_info.id); room_member_impl->Send(std::move(packet)); } @@ -621,8 +621,8 @@ void RoomMember::SendModerationRequest(RoomMessageTypes type, const std::string& return; Packet packet; - packet << static_cast(type); - packet << nickname; + packet.Write(static_cast(type)); + packet.Write(nickname); room_member_impl->Send(std::move(packet)); } @@ -631,7 +631,7 @@ void RoomMember::RequestBanList() { return; Packet packet; - packet << static_cast(IdModGetBanList); + packet.Write(static_cast(IdModGetBanList)); room_member_impl->Send(std::move(packet)); } diff --git a/src/yuzu/multiplayer/state.cpp b/src/yuzu/multiplayer/state.cpp index 015c59788a..4149b52321 100644 --- a/src/yuzu/multiplayer/state.cpp +++ b/src/yuzu/multiplayer/state.cpp @@ -74,14 +74,18 @@ MultiplayerState::~MultiplayerState() { } void MultiplayerState::Close() { - if (host_room) + if (host_room) { host_room->close(); - if (direct_connect) + } + if (direct_connect) { direct_connect->close(); - if (client_room) + } + if (client_room) { client_room->close(); - if (lobby) + } + if (lobby) { lobby->close(); + } } void MultiplayerState::retranslateUi() {