GlobalLobbyClient.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. Settings configID = settings.write["lobby"]["accountID"];
  67. configID->String() = json["accountID"].String();
  68. Settings configName = settings.write["lobby"]["displayName"];
  69. configName->String() = json["displayName"].String();
  70. Settings configCookie = settings.write["lobby"]["accountCookie"];
  71. configCookie->String() = json["accountCookie"].String();
  72. }
  73. sendClientLogin();
  74. }
  75. void GlobalLobbyClient::receiveOperationFailed(const JsonNode & json)
  76. {
  77. auto loginWindowPtr = loginWindow.lock();
  78. if(loginWindowPtr)
  79. loginWindowPtr->onConnectionFailed(json["reason"].String());
  80. // TODO: handle errors in lobby menu
  81. }
  82. void GlobalLobbyClient::receiveClientLoginSuccess(const JsonNode & json)
  83. {
  84. {
  85. Settings configCookie = settings.write["lobby"]["accountCookie"];
  86. configCookie->String() = json["accountCookie"].String();
  87. Settings configName = settings.write["lobby"]["displayName"];
  88. configName->String() = json["displayName"].String();
  89. }
  90. auto loginWindowPtr = loginWindow.lock();
  91. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  92. throw std::runtime_error("lobby connection finished without active login window!");
  93. loginWindowPtr->onLoginSuccess();
  94. }
  95. void GlobalLobbyClient::receiveChatHistory(const JsonNode & json)
  96. {
  97. std::string channelType = json["channelType"].String();
  98. std::string channelName = json["channelName"].String();
  99. std::string channelKey = channelType + '_' + channelName;
  100. // create empty entry, potentially replacing any pre-existing data
  101. chatHistory[channelKey] = {};
  102. auto lobbyWindowPtr = lobbyWindow.lock();
  103. for(const auto & entry : json["messages"].Vector())
  104. {
  105. GlobalLobbyChannelMessage message;
  106. message.accountID = entry["accountID"].String();
  107. message.displayName = entry["displayName"].String();
  108. message.messageText = entry["messageText"].String();
  109. std::chrono::seconds ageSeconds (entry["ageSeconds"].Integer());
  110. message.timeFormatted = TextOperations::getCurrentFormattedTimeLocal(-ageSeconds);
  111. chatHistory[channelKey].push_back(message);
  112. if(lobbyWindowPtr)
  113. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  114. }
  115. }
  116. void GlobalLobbyClient::receiveChatMessage(const JsonNode & json)
  117. {
  118. GlobalLobbyChannelMessage message;
  119. message.accountID = json["accountID"].String();
  120. message.displayName = json["displayName"].String();
  121. message.messageText = json["messageText"].String();
  122. message.timeFormatted = TextOperations::getCurrentFormattedTimeLocal();
  123. std::string channelType = json["channelType"].String();
  124. std::string channelName = json["channelName"].String();
  125. std::string channelKey = channelType + '_' + channelName;
  126. chatHistory[channelKey].push_back(message);
  127. auto lobbyWindowPtr = lobbyWindow.lock();
  128. if(lobbyWindowPtr)
  129. lobbyWindowPtr->onGameChatMessage(message.displayName, message.messageText, message.timeFormatted, channelType, channelName);
  130. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  131. }
  132. void GlobalLobbyClient::receiveActiveAccounts(const JsonNode & json)
  133. {
  134. activeAccounts.clear();
  135. for(const auto & jsonEntry : json["accounts"].Vector())
  136. {
  137. GlobalLobbyAccount account;
  138. account.accountID = jsonEntry["accountID"].String();
  139. account.displayName = jsonEntry["displayName"].String();
  140. account.status = jsonEntry["status"].String();
  141. activeAccounts.push_back(account);
  142. }
  143. auto lobbyWindowPtr = lobbyWindow.lock();
  144. if(lobbyWindowPtr)
  145. lobbyWindowPtr->onActiveAccounts(activeAccounts);
  146. }
  147. void GlobalLobbyClient::receiveActiveGameRooms(const JsonNode & json)
  148. {
  149. activeRooms.clear();
  150. for(const auto & jsonEntry : json["gameRooms"].Vector())
  151. {
  152. GlobalLobbyRoom room;
  153. room.gameRoomID = jsonEntry["gameRoomID"].String();
  154. room.hostAccountID = jsonEntry["hostAccountID"].String();
  155. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  156. room.description = jsonEntry["description"].String();
  157. room.statusID = jsonEntry["status"].String();
  158. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  159. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  160. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  161. {
  162. GlobalLobbyAccount account;
  163. account.accountID = jsonParticipant["accountID"].String();
  164. account.displayName = jsonParticipant["displayName"].String();
  165. room.participants.push_back(account);
  166. }
  167. room.playerLimit = jsonEntry["playerLimit"].Integer();
  168. activeRooms.push_back(room);
  169. }
  170. auto lobbyWindowPtr = lobbyWindow.lock();
  171. if(lobbyWindowPtr)
  172. lobbyWindowPtr->onActiveRooms(activeRooms);
  173. }
  174. void GlobalLobbyClient::receiveMatchesHistory(const JsonNode & json)
  175. {
  176. matchesHistory.clear();
  177. for(const auto & jsonEntry : json["matchesHistory"].Vector())
  178. {
  179. GlobalLobbyRoom room;
  180. room.gameRoomID = jsonEntry["gameRoomID"].String();
  181. room.hostAccountID = jsonEntry["hostAccountID"].String();
  182. room.hostAccountDisplayName = jsonEntry["hostAccountDisplayName"].String();
  183. room.description = jsonEntry["description"].String();
  184. room.statusID = jsonEntry["status"].String();
  185. std::chrono::seconds ageSeconds (jsonEntry["ageSeconds"].Integer());
  186. room.startDateFormatted = TextOperations::getCurrentFormattedDateTimeLocal(-ageSeconds);
  187. for(const auto & jsonParticipant : jsonEntry["participants"].Vector())
  188. {
  189. GlobalLobbyAccount account;
  190. account.accountID = jsonParticipant["accountID"].String();
  191. account.displayName = jsonParticipant["displayName"].String();
  192. room.participants.push_back(account);
  193. }
  194. room.playerLimit = jsonEntry["playerLimit"].Integer();
  195. matchesHistory.push_back(room);
  196. }
  197. auto lobbyWindowPtr = lobbyWindow.lock();
  198. if(lobbyWindowPtr)
  199. lobbyWindowPtr->onMatchesHistory(matchesHistory);
  200. }
  201. void GlobalLobbyClient::receiveInviteReceived(const JsonNode & json)
  202. {
  203. auto lobbyWindowPtr = lobbyWindow.lock();
  204. std::string gameRoomID = json["gameRoomID"].String();
  205. std::string accountID = json["accountID"].String();
  206. activeInvites.insert(gameRoomID);
  207. if(lobbyWindowPtr)
  208. {
  209. std::string message = MetaString::createFromTextID("vcmi.lobby.invite.notification").toString();
  210. std::string time = TextOperations::getCurrentFormattedTimeLocal();
  211. lobbyWindowPtr->onGameChatMessage("System", message, time, "player", accountID);
  212. lobbyWindowPtr->onInviteReceived(gameRoomID);
  213. }
  214. CCS->soundh->playSound(AudioPath::builtin("CHAT"));
  215. }
  216. void GlobalLobbyClient::receiveJoinRoomSuccess(const JsonNode & json)
  217. {
  218. if (json["proxyMode"].Bool())
  219. {
  220. CSH->resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOBBY_GUEST, {});
  221. CSH->loadMode = ELoadMode::MULTI;
  222. std::string hostname = settings["lobby"]["hostname"].String();
  223. uint16_t port = settings["lobby"]["port"].Integer();
  224. CSH->connectToServer(hostname, port);
  225. }
  226. // NOTE: must be set after CSH->resetStateForLobby call
  227. currentGameRoomUUID = json["gameRoomID"].String();
  228. }
  229. void GlobalLobbyClient::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & connection)
  230. {
  231. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  232. networkConnection = connection;
  233. auto loginWindowPtr = loginWindow.lock();
  234. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  235. throw std::runtime_error("lobby connection established without active login window!");
  236. loginWindowPtr->onConnectionSuccess();
  237. }
  238. void GlobalLobbyClient::sendClientRegister(const std::string & accountName)
  239. {
  240. JsonNode toSend;
  241. toSend["type"].String() = "clientRegister";
  242. toSend["displayName"].String() = accountName;
  243. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  244. toSend["version"].String() = VCMI_VERSION_STRING;
  245. sendMessage(toSend);
  246. }
  247. void GlobalLobbyClient::sendClientLogin()
  248. {
  249. JsonNode toSend;
  250. toSend["type"].String() = "clientLogin";
  251. toSend["accountID"] = settings["lobby"]["accountID"];
  252. toSend["accountCookie"] = settings["lobby"]["accountCookie"];
  253. toSend["language"].String() = CGI->generaltexth->getPreferredLanguage();
  254. toSend["version"].String() = VCMI_VERSION_STRING;
  255. sendMessage(toSend);
  256. }
  257. void GlobalLobbyClient::onConnectionFailed(const std::string & errorMessage)
  258. {
  259. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  260. auto loginWindowPtr = loginWindow.lock();
  261. if(!loginWindowPtr || !GH.windows().topWindow<GlobalLobbyLoginWindow>())
  262. throw std::runtime_error("lobby connection failed without active login window!");
  263. logGlobal->warn("Connection to game lobby failed! Reason: %s", errorMessage);
  264. loginWindowPtr->onConnectionFailed(errorMessage);
  265. }
  266. void GlobalLobbyClient::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  267. {
  268. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  269. assert(connection == networkConnection);
  270. networkConnection.reset();
  271. while (!GH.windows().findWindows<GlobalLobbyWindow>().empty())
  272. {
  273. // if global lobby is open, pop all dialogs on top of it as well as lobby itself
  274. GH.windows().popWindows(1);
  275. }
  276. CInfoWindow::showInfoDialog("Connection to game lobby was lost!", {});
  277. }
  278. void GlobalLobbyClient::sendMessage(const JsonNode & data)
  279. {
  280. assert(JsonUtils::validate(data, "vcmi:lobbyProtocol/" + data["type"].String(), data["type"].String() + " pack"));
  281. networkConnection->sendPacket(data.toBytes());
  282. }
  283. void GlobalLobbyClient::sendOpenRoom(const std::string & mode, int playerLimit)
  284. {
  285. JsonNode toSend;
  286. toSend["type"].String() = "activateGameRoom";
  287. toSend["hostAccountID"] = settings["lobby"]["accountID"];
  288. toSend["roomType"].String() = mode;
  289. toSend["playerLimit"].Integer() = playerLimit;
  290. sendMessage(toSend);
  291. }
  292. void GlobalLobbyClient::connect()
  293. {
  294. std::string hostname = settings["lobby"]["hostname"].String();
  295. uint16_t port = settings["lobby"]["port"].Integer();
  296. CSH->getNetworkHandler().connectToRemote(*this, hostname, port);
  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 (isConnected())
  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::sendProxyConnectionLogin(const NetworkConnectionPtr & netConnection)
  377. {
  378. JsonNode toSend;
  379. toSend["type"].String() = "clientProxyLogin";
  380. toSend["accountID"] = settings["lobby"]["accountID"];
  381. toSend["accountCookie"] = settings["lobby"]["accountCookie"];
  382. toSend["gameRoomID"].String() = currentGameRoomUUID;
  383. assert(JsonUtils::validate(toSend, "vcmi:lobbyProtocol/" + toSend["type"].String(), toSend["type"].String() + " pack"));
  384. netConnection->sendPacket(toSend.toBytes());
  385. }
  386. void GlobalLobbyClient::resetMatchState()
  387. {
  388. currentGameRoomUUID.clear();
  389. }
  390. void GlobalLobbyClient::sendMatchChatMessage(const std::string & messageText)
  391. {
  392. if (!isConnected())
  393. return; // we are not playing with lobby
  394. if (currentGameRoomUUID.empty())
  395. return; // we are not playing through lobby
  396. JsonNode toSend;
  397. toSend["type"].String() = "sendChatMessage";
  398. toSend["channelType"].String() = "match";
  399. toSend["channelName"].String() = currentGameRoomUUID;
  400. toSend["messageText"].String() = messageText;
  401. CSH->getGlobalLobby().sendMessage(toSend);
  402. }
  403. bool GlobalLobbyClient::isInvitedToRoom(const std::string & gameRoomID)
  404. {
  405. return activeInvites.count(gameRoomID) > 0;
  406. }