GlobalLobbyClient.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 "GlobalLobbyInviteWindow.h"
  13. #include "GlobalLobbyLoginWindow.h"
  14. #include "GlobalLobbyWindow.h"
  15. #include "../CGameInfo.h"
  16. #include "../CMusicHandler.h"
  17. #include "../CServerHandler.h"
  18. #include "../gui/CGuiHandler.h"
  19. #include "../gui/WindowHandler.h"
  20. #include "../mainmenu/CMainMenu.h"
  21. #include "../windows/InfoWindows.h"
  22. #include "../../lib/CConfigHandler.h"
  23. #include "../../lib/MetaString.h"
  24. #include "../../lib/json/JsonUtils.h"
  25. #include "../../lib/TextOperations.h"
  26. #include "../../lib/CGeneralTextHandler.h"
  27. GlobalLobbyClient::GlobalLobbyClient()
  28. {
  29. activeChannels.emplace_back("english");
  30. if (CGI->generaltexth->getPreferredLanguage() != "english")
  31. activeChannels.emplace_back(CGI->generaltexth->getPreferredLanguage());
  32. }
  33. GlobalLobbyClient::~GlobalLobbyClient() = default;
  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. if(json["type"].String() == "matchesHistory")
  57. return receiveMatchesHistory(json);
  58. logGlobal->error("Received unexpected message from lobby server: %s", json["type"].String());
  59. }
  60. void GlobalLobbyClient::receiveAccountCreated(const JsonNode & json)
  61. {
  62. auto loginWindowPtr = loginWindow.lock();
  63. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  64. throw std::runtime_error("lobby connection finished without active login window!");
  65. {
  66. setAccountID(json["accountID"].String());
  67. setAccountDisplayName(json["displayName"].String());
  68. setAccountCookie(json["accountCookie"].String());
  69. }
  70. sendClientLogin();
  71. }
  72. void GlobalLobbyClient::receiveOperationFailed(const JsonNode & json)
  73. {
  74. auto loginWindowPtr = loginWindow.lock();
  75. if(loginWindowPtr)
  76. loginWindowPtr->onConnectionFailed(json["reason"].String());
  77. logGlobal->warn("Operation failed! Reason: %s", json["reason"].String());
  78. // TODO: handle errors in lobby menu
  79. }
  80. void GlobalLobbyClient::receiveClientLoginSuccess(const JsonNode & json)
  81. {
  82. accountLoggedIn = true;
  83. setAccountDisplayName(json["displayName"].String());
  84. setAccountCookie(json["accountCookie"].String());
  85. auto loginWindowPtr = loginWindow.lock();
  86. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  87. throw std::runtime_error("lobby connection finished without active login window!");
  88. loginWindowPtr->onLoginSuccess();
  89. }
  90. void GlobalLobbyClient::receiveChatHistory(const JsonNode & json)
  91. {
  92. std::string channelType = json["channelType"].String();
  93. std::string channelName = json["channelName"].String();
  94. std::string channelKey = channelType + '_' + channelName;
  95. // create empty entry, potentially replacing any pre-existing data
  96. chatHistory[channelKey] = {};
  97. auto lobbyWindowPtr = lobbyWindow.lock();
  98. for(const auto & entry : json["messages"].Vector())
  99. {
  100. GlobalLobbyChannelMessage message;
  101. message.accountID = entry["accountID"].String();
  102. message.displayName = entry["displayName"].String();
  103. message.messageText = entry["messageText"].String();
  104. std::chrono::seconds ageSeconds (entry["ageSeconds"].Integer());
  105. message.timeFormatted = TextOperations::getCurrentFormattedTimeLocal(-ageSeconds);
  106. chatHistory[channelKey].push_back(message);
  107. if(lobbyWindowPtr && lobbyWindowPtr->isChannelOpen(channelType, channelName))
  108. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  109. }
  110. if(lobbyWindowPtr && lobbyWindowPtr->isChannelOpen(channelType, channelName))
  111. lobbyWindowPtr->refreshChatText();
  112. }
  113. void GlobalLobbyClient::receiveChatMessage(const JsonNode & json)
  114. {
  115. GlobalLobbyChannelMessage message;
  116. message.accountID = json["accountID"].String();
  117. message.displayName = json["displayName"].String();
  118. message.messageText = json["messageText"].String();
  119. message.timeFormatted = TextOperations::getCurrentFormattedTimeLocal();
  120. std::string channelType = json["channelType"].String();
  121. std::string channelName = json["channelName"].String();
  122. std::string channelKey = channelType + '_' + channelName;
  123. chatHistory[channelKey].push_back(message);
  124. auto lobbyWindowPtr = lobbyWindow.lock();
  125. if(lobbyWindowPtr)
  126. {
  127. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  128. lobbyWindowPtr->refreshChatText();
  129. if(channelType == "player" || lobbyWindowPtr->isChannelOpen(channelType, channelName))
  130. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  131. }
  132. }
  133. void GlobalLobbyClient::receiveActiveAccounts(const JsonNode & json)
  134. {
  135. activeAccounts.clear();
  136. for(const auto & jsonEntry : json["accounts"].Vector())
  137. {
  138. GlobalLobbyAccount account;
  139. account.accountID = jsonEntry["accountID"].String();
  140. account.displayName = jsonEntry["displayName"].String();
  141. account.status = jsonEntry["status"].String();
  142. activeAccounts.push_back(account);
  143. }
  144. auto lobbyWindowPtr = lobbyWindow.lock();
  145. if(lobbyWindowPtr)
  146. lobbyWindowPtr->onActiveAccounts(activeAccounts);
  147. }
  148. void GlobalLobbyClient::receiveActiveGameRooms(const JsonNode & json)
  149. {
  150. activeRooms.clear();
  151. for(const auto & jsonEntry : json["gameRooms"].Vector())
  152. {
  153. GlobalLobbyRoom room;
  154. room.gameRoomID = jsonEntry["gameRoomID"].String();
  155. room.hostAccountID = jsonEntry["hostAccountID"].String();
  156. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  157. room.description = jsonEntry["description"].String();
  158. room.statusID = jsonEntry["status"].String();
  159. room.gameVersion = jsonEntry["version"].String();
  160. room.modList = ModVerificationInfo::jsonDeserializeList(jsonEntry["mods"]);
  161. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  162. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  163. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  164. {
  165. GlobalLobbyAccount account;
  166. account.accountID = jsonParticipant["accountID"].String();
  167. account.displayName = jsonParticipant["displayName"].String();
  168. room.participants.push_back(account);
  169. }
  170. for(const auto & jsonParticipant : jsonEntry["invited"].Vector())
  171. {
  172. GlobalLobbyAccount account;
  173. account.accountID = jsonParticipant["accountID"].String();
  174. account.displayName = jsonParticipant["displayName"].String();
  175. room.invited.push_back(account);
  176. }
  177. room.playerLimit = jsonEntry["playerLimit"].Integer();
  178. activeRooms.push_back(room);
  179. }
  180. auto lobbyWindowPtr = lobbyWindow.lock();
  181. if(lobbyWindowPtr)
  182. lobbyWindowPtr->onActiveRooms(activeRooms);
  183. }
  184. void GlobalLobbyClient::receiveMatchesHistory(const JsonNode & json)
  185. {
  186. matchesHistory.clear();
  187. for(const auto & jsonEntry : json["matchesHistory"].Vector())
  188. {
  189. GlobalLobbyRoom room;
  190. room.gameRoomID = jsonEntry["gameRoomID"].String();
  191. room.hostAccountID = jsonEntry["hostAccountID"].String();
  192. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  193. room.description = jsonEntry["description"].String();
  194. room.statusID = jsonEntry["status"].String();
  195. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  196. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  197. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  198. {
  199. GlobalLobbyAccount account;
  200. account.accountID = jsonParticipant["accountID"].String();
  201. account.displayName = jsonParticipant["displayName"].String();
  202. room.participants.push_back(account);
  203. }
  204. room.playerLimit = jsonEntry["playerLimit"].Integer();
  205. matchesHistory.push_back(room);
  206. }
  207. auto lobbyWindowPtr = lobbyWindow.lock();
  208. if(lobbyWindowPtr)
  209. lobbyWindowPtr->onMatchesHistory(matchesHistory);
  210. }
  211. void GlobalLobbyClient::receiveInviteReceived(const JsonNode & json)
  212. {
  213. auto lobbyWindowPtr = lobbyWindow.lock();
  214. std::string gameRoomID = json["gameRoomID"].String();
  215. std::string accountID = json["accountID"].String();
  216. activeInvites.insert(gameRoomID);
  217. if(lobbyWindowPtr)
  218. {
  219. std::string message = MetaString::createFromTextID("vcmi.lobby.invite.notification").toString();
  220. std::string time = TextOperations::getCurrentFormattedTimeLocal();
  221. lobbyWindowPtr->onGameChatMessage("System", message, time, "player", accountID);
  222. lobbyWindowPtr->onInviteReceived(gameRoomID);
  223. lobbyWindowPtr->refreshChatText();
  224. }
  225. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  226. }
  227. void GlobalLobbyClient::receiveJoinRoomSuccess(const JsonNode & json)
  228. {
  229. if (json["proxyMode"].Bool())
  230. {
  231. CSH->resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOBBY_GUEST, { CSH->getGlobalLobby().getAccountDisplayName() });
  232. CSH->loadMode = ELoadMode::MULTI;
  233. std::string hostname = getServerHost();
  234. uint16_t port = getServerPort();
  235. CSH->connectToServer(hostname, port);
  236. }
  237. // NOTE: must be set after CSH->resetStateForLobby call
  238. currentGameRoomUUID = json["gameRoomID"].String();
  239. }
  240. void GlobalLobbyClient::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & connection)
  241. {
  242. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  243. networkConnection = connection;
  244. auto loginWindowPtr = loginWindow.lock();
  245. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  246. throw std::runtime_error("lobby connection established without active login window!");
  247. loginWindowPtr->onConnectionSuccess();
  248. }
  249. void GlobalLobbyClient::sendClientRegister(const std::string & accountName)
  250. {
  251. JsonNode toSend;
  252. toSend["type"].String() = "clientRegister";
  253. toSend["displayName"].String() = accountName;
  254. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  255. toSend["version"].String() = VCMI_VERSION_STRING;
  256. sendMessage(toSend);
  257. }
  258. void GlobalLobbyClient::sendClientLogin()
  259. {
  260. JsonNode toSend;
  261. toSend["type"].String() = "clientLogin";
  262. toSend["accountID"].String() = getAccountID();
  263. toSend["accountCookie"].String() = getAccountCookie();
  264. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  265. toSend["version"].String() = VCMI_VERSION_STRING;
  266. sendMessage(toSend);
  267. }
  268. void GlobalLobbyClient::onConnectionFailed(const std::string & errorMessage)
  269. {
  270. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  271. auto loginWindowPtr = loginWindow.lock();
  272. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  273. throw std::runtime_error("lobby connection failed without active login window!");
  274. logGlobal->warn("Connection to game lobby failed! Reason: %s", errorMessage);
  275. loginWindowPtr->onConnectionFailed(errorMessage);
  276. }
  277. void GlobalLobbyClient::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  278. {
  279. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  280. assert(connection == networkConnection);
  281. networkConnection.reset();
  282. accountLoggedIn = false;
  283. while (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  284. {
  285. // if global lobby is open, pop all dialogs on top of it as well as lobby itself
  286. GH.windows().popWindows(1);
  287. }
  288. CInfoWindow::showInfoDialog("Connection to game lobby was lost!", {});
  289. }
  290. void GlobalLobbyClient::sendMessage(const JsonNode & data)
  291. {
  292. assert(JsonUtils::validate(data, "vcmi:lobbyProtocol/" + data["type"].String(), data["type"].String() + " pack"));
  293. networkConnection->sendPacket(data.toBytes());
  294. }
  295. void GlobalLobbyClient::sendOpenRoom(const std::string & mode, int playerLimit)
  296. {
  297. JsonNode toSend;
  298. toSend["type"].String() = "activateGameRoom";
  299. toSend["hostAccountID"].String() = getAccountID();
  300. toSend["roomType"].String() = mode;
  301. toSend["playerLimit"].Integer() = playerLimit;
  302. sendMessage(toSend);
  303. }
  304. void GlobalLobbyClient::connect()
  305. {
  306. std::string hostname = getServerHost();
  307. uint16_t port = getServerPort();
  308. CSH->getNetworkHandler().connectToRemote(*this, hostname, port);
  309. }
  310. bool GlobalLobbyClient::isLoggedIn() const
  311. {
  312. return networkConnection != nullptr && accountLoggedIn;
  313. }
  314. bool GlobalLobbyClient::isConnected() const
  315. {
  316. return networkConnection != nullptr;
  317. }
  318. std::shared_ptr<GlobalLobbyLoginWindow> GlobalLobbyClient::createLoginWindow()
  319. {
  320. auto loginWindowPtr = loginWindow.lock();
  321. if(loginWindowPtr)
  322. return loginWindowPtr;
  323. auto loginWindowNew = std::make_shared<GlobalLobbyLoginWindow>();
  324. loginWindow = loginWindowNew;
  325. return loginWindowNew;
  326. }
  327. std::shared_ptr<GlobalLobbyWindow> GlobalLobbyClient::createLobbyWindow()
  328. {
  329. auto lobbyWindowPtr = lobbyWindow.lock();
  330. if(lobbyWindowPtr)
  331. return lobbyWindowPtr;
  332. lobbyWindowPtr = std::make_shared<GlobalLobbyWindow>();
  333. lobbyWindow = lobbyWindowPtr;
  334. lobbyWindowLock = lobbyWindowPtr;
  335. return lobbyWindowPtr;
  336. }
  337. const std::vector<GlobalLobbyAccount> & GlobalLobbyClient::getActiveAccounts() const
  338. {
  339. return activeAccounts;
  340. }
  341. const std::vector<GlobalLobbyRoom> & GlobalLobbyClient::getActiveRooms() const
  342. {
  343. return activeRooms;
  344. }
  345. const std::vector<std::string> & GlobalLobbyClient::getActiveChannels() const
  346. {
  347. return activeChannels;
  348. }
  349. const std::vector<GlobalLobbyRoom> & GlobalLobbyClient::getMatchesHistory() const
  350. {
  351. return matchesHistory;
  352. }
  353. const GlobalLobbyRoom & GlobalLobbyClient::getActiveRoomByName(const std::string & roomUUID) const
  354. {
  355. for (auto const & room : activeRooms)
  356. {
  357. if (room.gameRoomID == roomUUID)
  358. return room;
  359. }
  360. throw std::out_of_range("Failed to find room with UUID of " + roomUUID);
  361. }
  362. const std::vector<GlobalLobbyChannelMessage> & GlobalLobbyClient::getChannelHistory(const std::string & channelType, const std::string & channelName) const
  363. {
  364. static const std::vector<GlobalLobbyChannelMessage> emptyVector;
  365. std::string keyToTest = channelType + '_' + channelName;
  366. if (chatHistory.count(keyToTest) == 0)
  367. {
  368. if (channelType != "global")
  369. {
  370. JsonNode toSend;
  371. toSend["type"].String() = "requestChatHistory";
  372. toSend["channelType"].String() = channelType;
  373. toSend["channelName"].String() = channelName;
  374. CSH->getGlobalLobby().sendMessage(toSend);
  375. }
  376. return emptyVector;
  377. }
  378. else
  379. return chatHistory.at(keyToTest);
  380. }
  381. void GlobalLobbyClient::activateInterface()
  382. {
  383. if (GH.windows().topWindow<GlobalLobbyWindow>() != nullptr)
  384. {
  385. GH.windows().popWindows(1);
  386. return;
  387. }
  388. if (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  389. return;
  390. if (!GH.windows().findWindows<GlobalLobbyLoginWindow>().empty())
  391. return;
  392. if (isLoggedIn())
  393. GH.windows().pushWindow(createLobbyWindow());
  394. else
  395. GH.windows().pushWindow(createLoginWindow());
  396. GH.windows().topWindow<CIntObject>()->center();
  397. }
  398. void GlobalLobbyClient::activateRoomInviteInterface()
  399. {
  400. GH.windows().createAndPushWindow<GlobalLobbyInviteWindow>();
  401. }
  402. void GlobalLobbyClient::setAccountID(const std::string & accountID)
  403. {
  404. Settings configID = persistentStorage.write["lobby"][getServerHost()]["accountID"];
  405. configID->String() = accountID;
  406. }
  407. void GlobalLobbyClient::setAccountCookie(const std::string & accountCookie)
  408. {
  409. Settings configCookie = persistentStorage.write["lobby"][getServerHost()]["accountCookie"];
  410. configCookie->String() = accountCookie;
  411. }
  412. void GlobalLobbyClient::setAccountDisplayName(const std::string & accountDisplayName)
  413. {
  414. Settings configName = persistentStorage.write["lobby"][getServerHost()]["displayName"];
  415. configName->String() = accountDisplayName;
  416. }
  417. const std::string & GlobalLobbyClient::getAccountID() const
  418. {
  419. return persistentStorage["lobby"][getServerHost()]["accountID"].String();
  420. }
  421. const std::string & GlobalLobbyClient::getAccountCookie() const
  422. {
  423. return persistentStorage["lobby"][getServerHost()]["accountCookie"].String();
  424. }
  425. const std::string & GlobalLobbyClient::getAccountDisplayName() const
  426. {
  427. return persistentStorage["lobby"][getServerHost()]["displayName"].String();
  428. }
  429. const std::string & GlobalLobbyClient::getServerHost() const
  430. {
  431. return settings["lobby"]["hostname"].String();
  432. }
  433. uint16_t GlobalLobbyClient::getServerPort() const
  434. {
  435. return settings["lobby"]["port"].Integer();
  436. }
  437. void GlobalLobbyClient::sendProxyConnectionLogin(const NetworkConnectionPtr & netConnection)
  438. {
  439. JsonNode toSend;
  440. toSend["type"].String() = "clientProxyLogin";
  441. toSend["accountID"].String() = getAccountID();
  442. toSend["accountCookie"].String() = getAccountCookie();
  443. toSend["gameRoomID"].String() = currentGameRoomUUID;
  444. assert(JsonUtils::validate(toSend, "vcmi:lobbyProtocol/" + toSend["type"].String(), toSend["type"].String() + " pack"));
  445. netConnection->sendPacket(toSend.toBytes());
  446. }
  447. void GlobalLobbyClient::resetMatchState()
  448. {
  449. currentGameRoomUUID.clear();
  450. }
  451. void GlobalLobbyClient::sendMatchChatMessage(const std::string & messageText)
  452. {
  453. if (!isLoggedIn())
  454. return; // we are not playing with lobby
  455. if (currentGameRoomUUID.empty())
  456. return; // we are not playing through lobby
  457. JsonNode toSend;
  458. toSend["type"].String() = "sendChatMessage";
  459. toSend["channelType"].String() = "match";
  460. toSend["channelName"].String() = currentGameRoomUUID;
  461. toSend["messageText"].String() = messageText;
  462. assert(TextOperations::isValidUnicodeString(messageText));
  463. CSH->getGlobalLobby().sendMessage(toSend);
  464. }
  465. bool GlobalLobbyClient::isInvitedToRoom(const std::string & gameRoomID)
  466. {
  467. return activeInvites.count(gameRoomID) > 0;
  468. }