GlobalLobbyClient.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*
  2. * GlobalLobbyClient.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "GlobalLobbyClient.h"
  12. #include "GlobalLobbyLoginWindow.h"
  13. #include "GlobalLobbyWindow.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../gui/WindowHandler.h"
  16. #include "../windows/InfoWindows.h"
  17. #include "../CServerHandler.h"
  18. #include "../mainmenu/CMainMenu.h"
  19. #include "../CGameInfo.h"
  20. #include "../../lib/CConfigHandler.h"
  21. #include "../../lib/MetaString.h"
  22. #include "../../lib/json/JsonUtils.h"
  23. #include "../../lib/TextOperations.h"
  24. #include "../../lib/CGeneralTextHandler.h"
  25. GlobalLobbyClient::GlobalLobbyClient() = default;
  26. GlobalLobbyClient::~GlobalLobbyClient() = default;
  27. static std::string getCurrentTimeFormatted(int timeOffsetSeconds = 0)
  28. {
  29. // FIXME: better/unified way to format date
  30. auto timeNowChrono = std::chrono::system_clock::now();
  31. timeNowChrono += std::chrono::seconds(timeOffsetSeconds);
  32. return TextOperations::getFormattedTimeLocal(std::chrono::system_clock::to_time_t(timeNowChrono));
  33. }
  34. void GlobalLobbyClient::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  35. {
  36. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  37. JsonNode json(message.data(), message.size());
  38. if(json["type"].String() == "accountCreated")
  39. return receiveAccountCreated(json);
  40. if(json["type"].String() == "operationFailed")
  41. return receiveOperationFailed(json);
  42. if(json["type"].String() == "clientLoginSuccess")
  43. return receiveClientLoginSuccess(json);
  44. if(json["type"].String() == "chatHistory")
  45. return receiveChatHistory(json);
  46. if(json["type"].String() == "chatMessage")
  47. return receiveChatMessage(json);
  48. if(json["type"].String() == "activeAccounts")
  49. return receiveActiveAccounts(json);
  50. if(json["type"].String() == "activeGameRooms")
  51. return receiveActiveGameRooms(json);
  52. if(json["type"].String() == "joinRoomSuccess")
  53. return receiveJoinRoomSuccess(json);
  54. if(json["type"].String() == "inviteReceived")
  55. return receiveInviteReceived(json);
  56. logGlobal->error("Received unexpected message from lobby server: %s", json["type"].String());
  57. }
  58. void GlobalLobbyClient::receiveAccountCreated(const JsonNode & json)
  59. {
  60. auto loginWindowPtr = loginWindow.lock();
  61. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  62. throw std::runtime_error("lobby connection finished without active login window!");
  63. {
  64. Settings configID = settings.write["lobby"]["accountID"];
  65. configID->String() = json["accountID"].String();
  66. Settings configName = settings.write["lobby"]["displayName"];
  67. configName->String() = json["displayName"].String();
  68. Settings configCookie = settings.write["lobby"]["accountCookie"];
  69. configCookie->String() = json["accountCookie"].String();
  70. }
  71. sendClientLogin();
  72. }
  73. void GlobalLobbyClient::receiveOperationFailed(const JsonNode & json)
  74. {
  75. auto loginWindowPtr = loginWindow.lock();
  76. if(loginWindowPtr)
  77. loginWindowPtr->onConnectionFailed(json["reason"].String());
  78. // TODO: handle errors in lobby menu
  79. }
  80. void GlobalLobbyClient::receiveClientLoginSuccess(const JsonNode & json)
  81. {
  82. {
  83. Settings configCookie = settings.write["lobby"]["accountCookie"];
  84. configCookie->String() = json["accountCookie"].String();
  85. Settings configName = settings.write["lobby"]["displayName"];
  86. configName->String() = json["displayName"].String();
  87. }
  88. auto loginWindowPtr = loginWindow.lock();
  89. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  90. throw std::runtime_error("lobby connection finished without active login window!");
  91. loginWindowPtr->onLoginSuccess();
  92. }
  93. void GlobalLobbyClient::receiveChatHistory(const JsonNode & json)
  94. {
  95. for(const auto & entry : json["messages"].Vector())
  96. {
  97. std::string accountID = entry["accountID"].String();
  98. std::string displayName = entry["displayName"].String();
  99. std::string messageText = entry["messageText"].String();
  100. int ageSeconds = entry["ageSeconds"].Integer();
  101. std::string timeFormatted = getCurrentTimeFormatted(-ageSeconds);
  102. auto lobbyWindowPtr = lobbyWindow.lock();
  103. if(lobbyWindowPtr)
  104. lobbyWindowPtr->onGameChatMessage(displayName, messageText, timeFormatted);
  105. }
  106. }
  107. void GlobalLobbyClient::receiveChatMessage(const JsonNode & json)
  108. {
  109. std::string accountID = json["accountID"].String();
  110. std::string displayName = json["displayName"].String();
  111. std::string messageText = json["messageText"].String();
  112. std::string timeFormatted = getCurrentTimeFormatted();
  113. auto lobbyWindowPtr = lobbyWindow.lock();
  114. if(lobbyWindowPtr)
  115. lobbyWindowPtr->onGameChatMessage(displayName, messageText, timeFormatted);
  116. }
  117. void GlobalLobbyClient::receiveActiveAccounts(const JsonNode & json)
  118. {
  119. activeAccounts.clear();
  120. for (auto const & jsonEntry : json["accounts"].Vector())
  121. {
  122. GlobalLobbyAccount account;
  123. account.accountID = jsonEntry["accountID"].String();
  124. account.displayName = jsonEntry["displayName"].String();
  125. account.status = jsonEntry["status"].String();
  126. activeAccounts.push_back(account);
  127. }
  128. auto lobbyWindowPtr = lobbyWindow.lock();
  129. if(lobbyWindowPtr)
  130. lobbyWindowPtr->onActiveAccounts(activeAccounts);
  131. }
  132. void GlobalLobbyClient::receiveActiveGameRooms(const JsonNode & json)
  133. {
  134. activeRooms.clear();
  135. for (auto const & jsonEntry : json["gameRooms"].Vector())
  136. {
  137. GlobalLobbyRoom room;
  138. room.gameRoomID = jsonEntry["gameRoomID"].String();
  139. room.hostAccountID = jsonEntry["hostAccountID"].String();
  140. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  141. room.description = jsonEntry["description"].String();
  142. room.playersCount = jsonEntry["playersCount"].Integer();
  143. room.playerLimit = jsonEntry["playerLimit"].Integer();
  144. activeRooms.push_back(room);
  145. }
  146. auto lobbyWindowPtr = lobbyWindow.lock();
  147. if(lobbyWindowPtr)
  148. lobbyWindowPtr->onActiveRooms(activeRooms);
  149. }
  150. void GlobalLobbyClient::receiveInviteReceived(const JsonNode & json)
  151. {
  152. assert(0); //TODO
  153. }
  154. void GlobalLobbyClient::receiveJoinRoomSuccess(const JsonNode & json)
  155. {
  156. Settings configRoom = settings.write["lobby"]["roomID"];
  157. configRoom->String() = json["gameRoomID"].String();
  158. if (json["proxyMode"].Bool())
  159. {
  160. CSH->resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOBBY_GUEST, {});
  161. CSH->loadMode = ELoadMode::MULTI;
  162. std::string hostname = settings["lobby"]["hostname"].String();
  163. int16_t port = settings["lobby"]["port"].Integer();
  164. CSH->connectToServer(hostname, port);
  165. }
  166. }
  167. void GlobalLobbyClient::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & connection)
  168. {
  169. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  170. networkConnection = connection;
  171. auto loginWindowPtr = loginWindow.lock();
  172. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  173. throw std::runtime_error("lobby connection established without active login window!");
  174. loginWindowPtr->onConnectionSuccess();
  175. }
  176. void GlobalLobbyClient::sendClientRegister(const std::string & accountName)
  177. {
  178. JsonNode toSend;
  179. toSend["type"].String() = "clientRegister";
  180. toSend["displayName"].String() = accountName;
  181. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  182. toSend["version"].String() = VCMI_VERSION_STRING;
  183. sendMessage(toSend);
  184. }
  185. void GlobalLobbyClient::sendClientLogin()
  186. {
  187. JsonNode toSend;
  188. toSend["type"].String() = "clientLogin";
  189. toSend["accountID"] = settings["lobby"]["accountID"];
  190. toSend["accountCookie"] = settings["lobby"]["accountCookie"];
  191. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  192. toSend["version"].String() = VCMI_VERSION_STRING;
  193. sendMessage(toSend);
  194. }
  195. void GlobalLobbyClient::onConnectionFailed(const std::string & errorMessage)
  196. {
  197. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  198. auto loginWindowPtr = loginWindow.lock();
  199. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  200. throw std::runtime_error("lobby connection failed without active login window!");
  201. logGlobal->warn("Connection to game lobby failed! Reason: %s", errorMessage);
  202. loginWindowPtr->onConnectionFailed(errorMessage);
  203. }
  204. void GlobalLobbyClient::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  205. {
  206. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  207. assert(connection == networkConnection);
  208. networkConnection.reset();
  209. while (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  210. {
  211. // if global lobby is open, pop all dialogs on top of it as well as lobby itself
  212. GH.windows().popWindows(1);
  213. }
  214. CInfoWindow::showInfoDialog("Connection to game lobby was lost!", {});
  215. }
  216. void GlobalLobbyClient::sendMessage(const JsonNode & data)
  217. {
  218. assert(JsonUtils::validate(data, "vcmi:lobbyProtocol/" + data["type"].String(), data["type"].String() + " pack"));
  219. networkConnection->sendPacket(data.toBytes());
  220. }
  221. void GlobalLobbyClient::sendOpenRoom(const std::string & mode, int playerLimit)
  222. {
  223. JsonNode toSend;
  224. toSend["type"].String() = "activateGameRoom";
  225. toSend["hostAccountID"] = settings["lobby"]["accountID"];
  226. toSend["roomType"].String() = mode;
  227. toSend["playerLimit"].Integer() = playerLimit;
  228. sendMessage(toSend);
  229. }
  230. void GlobalLobbyClient::connect()
  231. {
  232. std::string hostname = settings["lobby"]["hostname"].String();
  233. int16_t port = settings["lobby"]["port"].Integer();
  234. CSH->getNetworkHandler().connectToRemote(*this, hostname, port);
  235. }
  236. bool GlobalLobbyClient::isConnected() const
  237. {
  238. return networkConnection != nullptr;
  239. }
  240. std::shared_ptr<GlobalLobbyLoginWindow> GlobalLobbyClient::createLoginWindow()
  241. {
  242. auto loginWindowPtr = loginWindow.lock();
  243. if(loginWindowPtr)
  244. return loginWindowPtr;
  245. auto loginWindowNew = std::make_shared<GlobalLobbyLoginWindow>();
  246. loginWindow = loginWindowNew;
  247. return loginWindowNew;
  248. }
  249. std::shared_ptr<GlobalLobbyWindow> GlobalLobbyClient::createLobbyWindow()
  250. {
  251. auto lobbyWindowPtr = lobbyWindow.lock();
  252. if(lobbyWindowPtr)
  253. return lobbyWindowPtr;
  254. lobbyWindowPtr = std::make_shared<GlobalLobbyWindow>();
  255. lobbyWindow = lobbyWindowPtr;
  256. lobbyWindowLock = lobbyWindowPtr;
  257. return lobbyWindowPtr;
  258. }
  259. const std::vector<GlobalLobbyAccount> & GlobalLobbyClient::getActiveAccounts() const
  260. {
  261. return activeAccounts;
  262. }
  263. const std::vector<GlobalLobbyRoom> & GlobalLobbyClient::getActiveRooms() const
  264. {
  265. return activeRooms;
  266. }
  267. void GlobalLobbyClient::activateInterface()
  268. {
  269. if (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  270. return;
  271. if (!GH.windows().findWindows<GlobalLobbyLoginWindow>().empty())
  272. return;
  273. if (isConnected())
  274. GH.windows().pushWindow(createLobbyWindow());
  275. else
  276. GH.windows().pushWindow(createLoginWindow());
  277. }
  278. void GlobalLobbyClient::sendProxyConnectionLogin(const NetworkConnectionPtr & netConnection)
  279. {
  280. JsonNode toSend;
  281. toSend["type"].String() = "clientProxyLogin";
  282. toSend["accountID"] = settings["lobby"]["accountID"];
  283. toSend["accountCookie"] = settings["lobby"]["accountCookie"];
  284. toSend["gameRoomID"] = settings["lobby"]["roomID"];
  285. assert(JsonUtils::validate(toSend, "vcmi:lobbyProtocol/" + toSend["type"].String(), toSend["type"].String() + " pack"));
  286. netConnection->sendPacket(toSend.toBytes());
  287. }