GlobalLobbyClient.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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)
  108. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  109. }
  110. }
  111. void GlobalLobbyClient::receiveChatMessage(const JsonNode & json)
  112. {
  113. GlobalLobbyChannelMessage message;
  114. message.accountID = json["accountID"].String();
  115. message.displayName = json["displayName"].String();
  116. message.messageText = json["messageText"].String();
  117. message.timeFormatted = TextOperations::getCurrentFormattedTimeLocal();
  118. std::string channelType = json["channelType"].String();
  119. std::string channelName = json["channelName"].String();
  120. std::string channelKey = channelType + '_' + channelName;
  121. chatHistory[channelKey].push_back(message);
  122. auto lobbyWindowPtr = lobbyWindow.lock();
  123. if(lobbyWindowPtr)
  124. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  125. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  126. }
  127. void GlobalLobbyClient::receiveActiveAccounts(const JsonNode & json)
  128. {
  129. activeAccounts.clear();
  130. for(const auto & jsonEntry : json["accounts"].Vector())
  131. {
  132. GlobalLobbyAccount account;
  133. account.accountID = jsonEntry["accountID"].String();
  134. account.displayName = jsonEntry["displayName"].String();
  135. account.status = jsonEntry["status"].String();
  136. activeAccounts.push_back(account);
  137. }
  138. auto lobbyWindowPtr = lobbyWindow.lock();
  139. if(lobbyWindowPtr)
  140. lobbyWindowPtr->onActiveAccounts(activeAccounts);
  141. }
  142. void GlobalLobbyClient::receiveActiveGameRooms(const JsonNode & json)
  143. {
  144. activeRooms.clear();
  145. for(const auto & jsonEntry : json["gameRooms"].Vector())
  146. {
  147. GlobalLobbyRoom room;
  148. room.gameRoomID = jsonEntry["gameRoomID"].String();
  149. room.hostAccountID = jsonEntry["hostAccountID"].String();
  150. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  151. room.description = jsonEntry["description"].String();
  152. room.statusID = jsonEntry["status"].String();
  153. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  154. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  155. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  156. {
  157. GlobalLobbyAccount account;
  158. account.accountID = jsonParticipant["accountID"].String();
  159. account.displayName = jsonParticipant["displayName"].String();
  160. room.participants.push_back(account);
  161. }
  162. room.playerLimit = jsonEntry["playerLimit"].Integer();
  163. activeRooms.push_back(room);
  164. }
  165. auto lobbyWindowPtr = lobbyWindow.lock();
  166. if(lobbyWindowPtr)
  167. lobbyWindowPtr->onActiveRooms(activeRooms);
  168. }
  169. void GlobalLobbyClient::receiveMatchesHistory(const JsonNode & json)
  170. {
  171. matchesHistory.clear();
  172. for(const auto & jsonEntry : json["matchesHistory"].Vector())
  173. {
  174. GlobalLobbyRoom room;
  175. room.gameRoomID = jsonEntry["gameRoomID"].String();
  176. room.hostAccountID = jsonEntry["hostAccountID"].String();
  177. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  178. room.description = jsonEntry["description"].String();
  179. room.statusID = jsonEntry["status"].String();
  180. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  181. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  182. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  183. {
  184. GlobalLobbyAccount account;
  185. account.accountID = jsonParticipant["accountID"].String();
  186. account.displayName = jsonParticipant["displayName"].String();
  187. room.participants.push_back(account);
  188. }
  189. room.playerLimit = jsonEntry["playerLimit"].Integer();
  190. matchesHistory.push_back(room);
  191. }
  192. auto lobbyWindowPtr = lobbyWindow.lock();
  193. if(lobbyWindowPtr)
  194. lobbyWindowPtr->onMatchesHistory(matchesHistory);
  195. }
  196. void GlobalLobbyClient::receiveInviteReceived(const JsonNode & json)
  197. {
  198. auto lobbyWindowPtr = lobbyWindow.lock();
  199. std::string gameRoomID = json["gameRoomID"].String();
  200. std::string accountID = json["accountID"].String();
  201. activeInvites.insert(gameRoomID);
  202. if(lobbyWindowPtr)
  203. {
  204. std::string message = MetaString::createFromTextID("vcmi.lobby.invite.notification").toString();
  205. std::string time = TextOperations::getCurrentFormattedTimeLocal();
  206. lobbyWindowPtr->onGameChatMessage("System", message, time, "player", accountID);
  207. lobbyWindowPtr->onInviteReceived(gameRoomID);
  208. }
  209. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  210. }
  211. void GlobalLobbyClient::receiveJoinRoomSuccess(const JsonNode & json)
  212. {
  213. if (json["proxyMode"].Bool())
  214. {
  215. CSH->resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOBBY_GUEST, {});
  216. CSH->loadMode = ELoadMode::MULTI;
  217. std::string hostname = getServerHost();
  218. uint16_t port = getServerPort();
  219. CSH->connectToServer(hostname, port);
  220. }
  221. // NOTE: must be set after CSH->resetStateForLobby call
  222. currentGameRoomUUID = json["gameRoomID"].String();
  223. }
  224. void GlobalLobbyClient::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & connection)
  225. {
  226. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  227. networkConnection = connection;
  228. auto loginWindowPtr = loginWindow.lock();
  229. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  230. throw std::runtime_error("lobby connection established without active login window!");
  231. loginWindowPtr->onConnectionSuccess();
  232. }
  233. void GlobalLobbyClient::sendClientRegister(const std::string & accountName)
  234. {
  235. JsonNode toSend;
  236. toSend["type"].String() = "clientRegister";
  237. toSend["displayName"].String() = accountName;
  238. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  239. toSend["version"].String() = VCMI_VERSION_STRING;
  240. sendMessage(toSend);
  241. }
  242. void GlobalLobbyClient::sendClientLogin()
  243. {
  244. JsonNode toSend;
  245. toSend["type"].String() = "clientLogin";
  246. toSend["accountID"].String() = getAccountID();
  247. toSend["accountCookie"].String() = getAccountCookie();
  248. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  249. toSend["version"].String() = VCMI_VERSION_STRING;
  250. sendMessage(toSend);
  251. }
  252. void GlobalLobbyClient::onConnectionFailed(const std::string & errorMessage)
  253. {
  254. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  255. auto loginWindowPtr = loginWindow.lock();
  256. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  257. throw std::runtime_error("lobby connection failed without active login window!");
  258. logGlobal->warn("Connection to game lobby failed! Reason: %s", errorMessage);
  259. loginWindowPtr->onConnectionFailed(errorMessage);
  260. }
  261. void GlobalLobbyClient::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  262. {
  263. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  264. assert(connection == networkConnection);
  265. networkConnection.reset();
  266. accountLoggedIn = false;
  267. while (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  268. {
  269. // if global lobby is open, pop all dialogs on top of it as well as lobby itself
  270. GH.windows().popWindows(1);
  271. }
  272. CInfoWindow::showInfoDialog("Connection to game lobby was lost!", {});
  273. }
  274. void GlobalLobbyClient::sendMessage(const JsonNode & data)
  275. {
  276. assert(JsonUtils::validate(data, "vcmi:lobbyProtocol/" + data["type"].String(), data["type"].String() + " pack"));
  277. networkConnection->sendPacket(data.toBytes());
  278. }
  279. void GlobalLobbyClient::sendOpenRoom(const std::string & mode, int playerLimit)
  280. {
  281. JsonNode toSend;
  282. toSend["type"].String() = "activateGameRoom";
  283. toSend["hostAccountID"].String() = getAccountID();
  284. toSend["roomType"].String() = mode;
  285. toSend["playerLimit"].Integer() = playerLimit;
  286. sendMessage(toSend);
  287. }
  288. void GlobalLobbyClient::connect()
  289. {
  290. std::string hostname = getServerHost();
  291. uint16_t port = getServerPort();
  292. CSH->getNetworkHandler().connectToRemote(*this, hostname, port);
  293. }
  294. bool GlobalLobbyClient::isLoggedIn() const
  295. {
  296. return networkConnection != nullptr && accountLoggedIn;
  297. }
  298. bool GlobalLobbyClient::isConnected() const
  299. {
  300. return networkConnection != nullptr;
  301. }
  302. std::shared_ptr<GlobalLobbyLoginWindow> GlobalLobbyClient::createLoginWindow()
  303. {
  304. auto loginWindowPtr = loginWindow.lock();
  305. if(loginWindowPtr)
  306. return loginWindowPtr;
  307. auto loginWindowNew = std::make_shared<GlobalLobbyLoginWindow>();
  308. loginWindow = loginWindowNew;
  309. return loginWindowNew;
  310. }
  311. std::shared_ptr<GlobalLobbyWindow> GlobalLobbyClient::createLobbyWindow()
  312. {
  313. auto lobbyWindowPtr = lobbyWindow.lock();
  314. if(lobbyWindowPtr)
  315. return lobbyWindowPtr;
  316. lobbyWindowPtr = std::make_shared<GlobalLobbyWindow>();
  317. lobbyWindow = lobbyWindowPtr;
  318. lobbyWindowLock = lobbyWindowPtr;
  319. return lobbyWindowPtr;
  320. }
  321. const std::vector<GlobalLobbyAccount> & GlobalLobbyClient::getActiveAccounts() const
  322. {
  323. return activeAccounts;
  324. }
  325. const std::vector<GlobalLobbyRoom> & GlobalLobbyClient::getActiveRooms() const
  326. {
  327. return activeRooms;
  328. }
  329. const std::vector<std::string> & GlobalLobbyClient::getActiveChannels() const
  330. {
  331. return activeChannels;
  332. }
  333. const std::vector<GlobalLobbyRoom> & GlobalLobbyClient::getMatchesHistory() const
  334. {
  335. return matchesHistory;
  336. }
  337. const std::vector<GlobalLobbyChannelMessage> & GlobalLobbyClient::getChannelHistory(const std::string & channelType, const std::string & channelName) const
  338. {
  339. static const std::vector<GlobalLobbyChannelMessage> emptyVector;
  340. std::string keyToTest = channelType + '_' + channelName;
  341. if (chatHistory.count(keyToTest) == 0)
  342. {
  343. if (channelType != "global")
  344. {
  345. JsonNode toSend;
  346. toSend["type"].String() = "requestChatHistory";
  347. toSend["channelType"].String() = channelType;
  348. toSend["channelName"].String() = channelName;
  349. CSH->getGlobalLobby().sendMessage(toSend);
  350. }
  351. return emptyVector;
  352. }
  353. else
  354. return chatHistory.at(keyToTest);
  355. }
  356. void GlobalLobbyClient::activateInterface()
  357. {
  358. if (GH.windows().topWindow<GlobalLobbyWindow>() != nullptr)
  359. {
  360. GH.windows().popWindows(1);
  361. return;
  362. }
  363. if (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  364. return;
  365. if (!GH.windows().findWindows<GlobalLobbyLoginWindow>().empty())
  366. return;
  367. if (isLoggedIn())
  368. GH.windows().pushWindow(createLobbyWindow());
  369. else
  370. GH.windows().pushWindow(createLoginWindow());
  371. }
  372. void GlobalLobbyClient::activateRoomInviteInterface()
  373. {
  374. GH.windows().createAndPushWindow<GlobalLobbyInviteWindow>();
  375. }
  376. void GlobalLobbyClient::setAccountID(const std::string & accountID)
  377. {
  378. Settings configID = persistentStorage.write["lobby"][getServerHost()]["accountID"];
  379. configID->String() = accountID;
  380. }
  381. void GlobalLobbyClient::setAccountCookie(const std::string & accountCookie)
  382. {
  383. Settings configCookie = persistentStorage.write["lobby"][getServerHost()]["accountCookie"];
  384. configCookie->String() = accountCookie;
  385. }
  386. void GlobalLobbyClient::setAccountDisplayName(const std::string & accountDisplayName)
  387. {
  388. Settings configName = persistentStorage.write["lobby"][getServerHost()]["displayName"];
  389. configName->String() = accountDisplayName;
  390. }
  391. const std::string & GlobalLobbyClient::getAccountID() const
  392. {
  393. return persistentStorage["lobby"][getServerHost()]["accountID"].String();
  394. }
  395. const std::string & GlobalLobbyClient::getAccountCookie() const
  396. {
  397. return persistentStorage["lobby"][getServerHost()]["accountCookie"].String();
  398. }
  399. const std::string & GlobalLobbyClient::getAccountDisplayName() const
  400. {
  401. return persistentStorage["lobby"][getServerHost()]["displayName"].String();
  402. }
  403. const std::string & GlobalLobbyClient::getServerHost() const
  404. {
  405. return settings["lobby"]["hostname"].String();
  406. }
  407. uint16_t GlobalLobbyClient::getServerPort() const
  408. {
  409. return settings["lobby"]["port"].Integer();
  410. }
  411. void GlobalLobbyClient::sendProxyConnectionLogin(const NetworkConnectionPtr & netConnection)
  412. {
  413. JsonNode toSend;
  414. toSend["type"].String() = "clientProxyLogin";
  415. toSend["accountID"].String() = getAccountID();
  416. toSend["accountCookie"].String() = getAccountCookie();
  417. toSend["gameRoomID"].String() = currentGameRoomUUID;
  418. assert(JsonUtils::validate(toSend, "vcmi:lobbyProtocol/" + toSend["type"].String(), toSend["type"].String() + " pack"));
  419. netConnection->sendPacket(toSend.toBytes());
  420. }
  421. void GlobalLobbyClient::resetMatchState()
  422. {
  423. currentGameRoomUUID.clear();
  424. }
  425. void GlobalLobbyClient::sendMatchChatMessage(const std::string & messageText)
  426. {
  427. if (!isLoggedIn())
  428. return; // we are not playing with lobby
  429. if (currentGameRoomUUID.empty())
  430. return; // we are not playing through lobby
  431. JsonNode toSend;
  432. toSend["type"].String() = "sendChatMessage";
  433. toSend["channelType"].String() = "match";
  434. toSend["channelName"].String() = currentGameRoomUUID;
  435. toSend["messageText"].String() = messageText;
  436. assert(TextOperations::isValidUnicodeString(messageText));
  437. CSH->getGlobalLobby().sendMessage(toSend);
  438. }
  439. bool GlobalLobbyClient::isInvitedToRoom(const std::string & gameRoomID)
  440. {
  441. return activeInvites.count(gameRoomID) > 0;
  442. }