The Battle for Wesnoth  1.15.0-dev
lobby_data.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2009 - 2018 by Tomasz Sniatowski <kailoran@gmail.com>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
16 
17 #include "config.hpp"
19 #include "preferences/game.hpp"
21 #include "filesystem.hpp"
22 #include "font/pango/escape.hpp"
23 #include "formatter.hpp"
24 #include "formula/string_utils.hpp"
25 #include "game_config_manager.hpp"
26 #include "gettext.hpp"
27 #include "lexical_cast.hpp"
28 #include "log.hpp"
29 #include "map/map.hpp"
30 #include "map/exception.hpp"
31 #include "terrain/type_data.hpp"
32 #include "wml_exception.hpp"
33 #include "game_version.hpp"
34 
35 #include <iterator>
36 
37 #include <boost/algorithm/string.hpp>
38 
39 static lg::log_domain log_config("config");
40 #define ERR_CF LOG_STREAM(err, log_config)
41 static lg::log_domain log_engine("engine");
42 #define WRN_NG LOG_STREAM(warn, log_engine)
43 
44 static lg::log_domain log_lobby("lobby");
45 #define DBG_LB LOG_STREAM(info, log_lobby)
46 #define LOG_LB LOG_STREAM(info, log_lobby)
47 #define ERR_LB LOG_STREAM(err, log_lobby)
48 
49 namespace mp {
50 
52  const std::string& user,
53  const std::string& message)
54  : timestamp(timestamp), user(user), message(message)
55 {
56 }
57 
59 {
60 }
61 
62 void chat_session::add_message(const std::time_t& timestamp,
63  const std::string& user,
64  const std::string& message)
65 {
66  history_.emplace_back(timestamp, user, message);
67 }
68 
69 
70 void chat_session::add_message(const std::string& user, const std::string& message)
71 {
72  add_message(std::time(nullptr), user, message);
73 }
74 
76 {
77  history_.clear();
78 }
79 
80 room_info::room_info(const std::string& name) : name_(name), members_(), log_()
81 {
82 }
83 
84 bool room_info::is_member(const std::string& user) const
85 {
86  return members_.find(user) != members_.end();
87 }
88 
89 void room_info::add_member(const std::string& user)
90 {
91  members_.insert(user);
92 }
93 
94 void room_info::remove_member(const std::string& user)
95 {
96  members_.erase(user);
97 }
98 
100 {
101  members_.clear();
102  for(const auto & m : data.child_range("member"))
103  {
104  members_.insert(m["name"]);
105  }
106 }
107 
109  : name(c["name"])
110  , game_id(c["game_id"])
111  , relation(ME)
112  , state(game_id == 0 ? LOBBY : GAME)
113  , registered(c["registered"].to_bool())
114  , observing(c["status"] == "observing")
115 {
116  update_relation();
117 }
118 
119 void user_info::update_state(int selected_game_id,
120  const room_info* current_room /*= nullptr*/)
121 {
122  if(game_id != 0) {
123  if(game_id == selected_game_id) {
124  state = SEL_GAME;
125  } else {
126  state = GAME;
127  }
128  } else {
129  if(current_room != nullptr && current_room->is_member(name)) {
130  state = SEL_ROOM;
131  } else {
132  state = LOBBY;
133  }
134  }
135  update_relation();
136 }
137 
139 {
140  if(name == preferences::login()) {
141  relation = ME;
142  } else if(preferences::is_ignored(name)) {
143  relation = IGNORED;
144  } else if(preferences::is_friend(name)) {
145  relation = FRIEND;
146  } else {
147  relation = NEUTRAL;
148  }
149 }
150 
151 bool user_info::operator<(const user_info& b) const
152 {
153  return relation < b.relation || (relation == b.relation && translation::icompare(name, b.name) < 0);
154 }
155 
156 namespace
157 {
158 const std::string& spaced_em_dash()
159 {
160  static const std::string res = " " + font::unicode_em_dash + " ";
161  return res;
162 }
163 
164 std::string make_game_type_marker(std::string text, bool color_for_missing)
165 {
166  if(color_for_missing) {
167  return formatter() << "<b><span color='#f00'>[" << text << "]</span></b> ";
168  } else {
169  return formatter() << "<b>[" << text << "]</b> ";
170  }
171 }
172 
173 } // end anon namespace
174 
175 game_info::game_info(const config& game, const std::vector<std::string>& installed_addons)
176  : id(game["id"])
177  , map_data(game["map_data"])
178  , name(font::escape_text(game["name"]))
179  , scenario()
180  , remote_scenario(false)
181  , map_info()
182  , map_size_info()
183  , era()
184  , gold(game["mp_village_gold"])
185  , support(game["mp_village_support"])
186  , xp(game["experience_modifier"].str() + "%")
187  , vision()
188  , status()
189  , time_limit()
190  , vacant_slots()
191  , current_turn(0)
192  , reloaded(game["savegame"].to_bool())
193  , started(false)
194  , fog(game["mp_fog"].to_bool())
195  , shroud(game["mp_shroud"].to_bool())
196  , observers(game["observer"].to_bool(true))
197  , shuffle_sides(game["shuffle_sides"].to_bool(true))
198  , use_map_settings(game["mp_use_map_settings"].to_bool())
199  , registered_users_only(game["registered_users_only"].to_bool())
200  , verified(true)
201  , password_required(game["password"].to_bool())
202  , have_era(true)
203  , have_all_mods(true)
204  , has_friends(false)
205  , has_ignored(false)
206  , display_status(NEW)
207  , required_addons()
208  , addons_outcome(SATISFIED)
209 {
211 
212  // Parse the list of addons required to join this game.
213  for(const config& addon : game.child_range("addon")) {
214  if(addon.has_attribute("id")) {
215  if(std::find(installed_addons.begin(), installed_addons.end(), addon["id"].str()) == installed_addons.end()) {
216  required_addon r;
217  r.addon_id = addon["id"].str();
219 
220  // Use addon name if provided, else fall back on the addon id.
221  if(addon.has_attribute("name")) {
222  r.message = VGETTEXT("Missing addon: $name", {{"name", addon["name"].str()}});
223  } else {
224  r.message = VGETTEXT("Missing addon: $id", {{"id", addon["id"].str()}});
225  }
226 
227  required_addons.push_back(std::move(r));
228 
229  if(addons_outcome == SATISFIED) {
231  }
232  }
233  }
234  }
235 
236  if(!game["mp_era"].empty()) {
237  const config& era_cfg = game_config.find_child("era", "id", game["mp_era"]);
238  const bool require = game["require_era"].to_bool(true);
239  if(era_cfg) {
240  era = era_cfg["name"].str();
241 
242  if(require) {
243  ADDON_REQ result = check_addon_version_compatibility(era_cfg, game);
244  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
245  }
246  } else {
247  have_era = !require;
248  era = game["mp_era_name"].str();
249  verified = false;
250 
251  if(!have_era) {
253  }
254  }
255  } else {
256  era = _("Unknown era");
257  verified = false;
258  }
259 
260  std::stringstream info_stream;
261  info_stream << era;
262 
263  for(const config& cfg : game.child_range("modification")) {
264  mod_info.emplace_back(cfg["name"].str(), true);
265  info_stream << ' ' << mod_info.back().first;
266 
267  if(cfg["require_modification"].to_bool(false)) {
268  if(const config& mod = game_config.find_child("modification", "id", cfg["id"])) {
269  ADDON_REQ result = check_addon_version_compatibility(mod, game);
270  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
271  } else {
272  have_all_mods = false;
273  mod_info.back().second = false;
274 
276  }
277  }
278  }
279 
280  std::sort(mod_info.begin(), mod_info.end(), [](const auto& lhs, const auto& rhs) {
281  return translation::icompare(lhs.first, rhs.first) < 0;
282  });
283 
284  info_stream << ' ';
285 
286  if(map_data.empty()) {
287  map_data = filesystem::read_map(game["mp_scenario"]);
288  }
289 
290  if(map_data.empty()) {
291  info_stream << " — ??×??";
292  } else {
293  try {
294  gamemap map(std::make_shared<terrain_type_data>(game_config), map_data);
295  std::ostringstream msi;
296  msi << map.w() << font::unicode_multiplication_sign << map.h();
297  map_size_info = msi.str();
298  info_stream << spaced_em_dash() << map_size_info;
299  } catch(const incorrect_map_format_error&) {
300  verified = false;
301  } catch(const wml_exception& e) {
302  ERR_CF << "map could not be loaded: " << e.dev_message << '\n';
303  verified = false;
304  }
305  }
306 
307  info_stream << " ";
308 
309  //
310  // Check scenarios and campaigns
311  //
312  if(!game["mp_scenario"].empty() && game["mp_campaign"].empty()) {
313  // Check if it's a multiplayer scenario
314  const config* level_cfg = &game_config.find_child("multiplayer", "id", game["mp_scenario"]);
315  const bool require = game["require_scenario"].to_bool(false);
316 
317  // Check if it's a user map
318  if(!*level_cfg) {
319  level_cfg = &game_config.find_child("generic_multiplayer", "id", game["mp_scenario"]);
320  }
321 
322  if(*level_cfg) {
323  scenario = formatter() << make_game_type_marker(_("scenario_abbreviation^S"), false) << (*level_cfg)["name"].str();
324  info_stream << scenario;
325 
326  // Reloaded games do not match the original scenario hash, so it makes no sense
327  // to test them, since they always would appear as remote scenarios
328  if(!reloaded) {
329  if(const config& hashes = game_config.child("multiplayer_hashes")) {
330  std::string hash = game["hash"];
331  bool hash_found = false;
332  for(const auto & i : hashes.attribute_range()) {
333  if(i.first == game["mp_scenario"] && i.second == hash) {
334  hash_found = true;
335  break;
336  }
337  }
338 
339  if(!hash_found) {
340  remote_scenario = true;
341  info_stream << spaced_em_dash();
342  info_stream << _("Remote scenario");
343  verified = false;
344  }
345  }
346  }
347 
348  if(require) {
349  ADDON_REQ result = check_addon_version_compatibility((*level_cfg), game);
350  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
351  }
352  } else {
353  if(require) {
354  addons_outcome = std::max(addons_outcome, NEED_DOWNLOAD); // Elevate to most severe error level encountered so far
355  }
356  scenario = formatter() << make_game_type_marker(_("scenario_abbreviation^S"), true) << game["mp_scenario_name"].str();
357  info_stream << scenario;
358  verified = false;
359  }
360  } else if(!game["mp_campaign"].empty()) {
361  if(const config& campaign_cfg = game_config.find_child("campaign", "id", game["mp_campaign"])) {
362  std::stringstream campaign_text;
363  campaign_text
364  << make_game_type_marker(_("campaign_abbreviation^C"), false)
365  << campaign_cfg["name"] << spaced_em_dash()
366  << game["mp_scenario_name"];
367 
368  // Difficulty
369  config difficulties = gui2::dialogs::generate_difficulty_config(campaign_cfg);
370  for(const config& difficulty : difficulties.child_range("difficulty")) {
371  if(difficulty["define"] == game["difficulty_define"]) {
372  campaign_text << spaced_em_dash() << difficulty["description"];
373 
374  break;
375  }
376  }
377 
378  scenario = campaign_text.str();
379  info_stream << campaign_text.rdbuf();
380 
381  // TODO: should we have this?
382  //if(game["require_scenario"].to_bool(false)) {
383  ADDON_REQ result = check_addon_version_compatibility(campaign_cfg, game);
384  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
385  //}
386  } else {
387  scenario = formatter() << make_game_type_marker(_("campaign_abbreviation^C"), true) << game["mp_campaign_name"].str();
388  info_stream << scenario;
389  verified = false;
390  }
391  } else {
392  scenario = _("Unknown scenario");
393  info_stream << scenario;
394  verified = false;
395  }
396 
397  // Remove any newlines that might have been in game titles
398  boost::replace_all(scenario, "\n", " " + font::unicode_em_dash + " ");
399 
400  if(reloaded) {
401  info_stream << spaced_em_dash();
402  info_stream << _("Reloaded game");
403  verified = false;
404  }
405 
406  // These should always be present in the data the server sends, but may or may not be empty.
407  // I'm just using child_or_empty here to preempt any cases where they might not be included.
408  const config& s = game.child_or_empty("slot_data");
409  const config& t = game.child_or_empty("turn_data");
410 
411  if(!s.empty()) {
412  started = false;
413 
414  vacant_slots = s["vacant"].to_unsigned();
415 
416  if(vacant_slots > 0) {
417  status = formatter() << _n("Vacant Slot:", "Vacant Slots:", vacant_slots) << " " << vacant_slots << "/" << s["max"];
418  } else {
419  status = _("mp_game_available_slots^Full");
420  }
421  }
422 
423  if(!t.empty()) {
424  started = true;
425 
426  current_turn = t["current"].to_unsigned();
427  const int max_turns = t["max"].to_int();
428 
429  if(max_turns > -1) {
430  status = formatter() << _("Turn") << " " << t["current"] << "/" << max_turns;
431  } else {
432  status = formatter() << _("Turn") << " " << t["current"];
433  }
434  }
435 
436  if(fog) {
437  vision = _("Fog");
438  if(shroud) {
439  vision += "/";
440  vision += _("Shroud");
441  }
442  } else if(shroud) {
443  vision = _("Shroud");
444  } else {
445  vision = _("vision^none");
446  }
447 
448  if(game["mp_countdown"].to_bool()) {
450  << game["mp_countdown_init_time"].str() << "+"
451  << game["mp_countdown_turn_bonus"].str() << "/"
452  << game["mp_countdown_action_bonus"].str();
453  } else {
454  time_limit = _("time limit^none");
455  }
456 
457  map_info = info_stream.str();
458 }
459 
461 {
462  if(!local_item.has_attribute("addon_id") || !local_item.has_attribute("addon_version")) {
463  return SATISFIED;
464  }
465 
466  if(const config& game_req = game.find_child("addon", "id", local_item["addon_id"])) {
467  required_addon r {local_item["addon_id"].str(), SATISFIED, ""};
468 
469  // Local version
470  const version_info local_ver(local_item["addon_version"].str());
471  version_info local_min_ver(local_item.has_attribute("addon_min_version") ? local_item["addon_min_version"] : local_item["addon_version"]);
472 
473  // If the UMC didn't specify last compatible version, assume no backwards compatibility.
474  // Also apply some sanity checking regarding min version; if the min ver doesn't make sense, ignore it.
475  local_min_ver = std::min(local_min_ver, local_ver);
476 
477  // Remote version
478  const version_info remote_ver(game_req["version"].str());
479  version_info remote_min_ver(game_req.has_attribute("min_version") ? game_req["min_version"] : game_req["version"]);
480 
481  remote_min_ver = std::min(remote_min_ver, remote_ver);
482 
483  // Check if the host is too out of date to play.
484  if(local_min_ver > remote_ver) {
485  DBG_LB << "r.outcome = CANNOT_SATISFY for item='" << local_item["id"]
486  << "' addon='" << local_item["addon_id"]
487  << "' addon_min_version='" << local_item["addon_min_version"]
488  << "' addon_min_version_parsed='" << local_min_ver.str()
489  << "' addon_version='" << local_item["addon_version"]
490  << "' remote_ver='" << remote_ver.str()
491  << "'\n";
492  r.outcome = CANNOT_SATISFY;
493 
494  r.message = VGETTEXT("The host's version of <i>$addon</i> is incompatible. They have version <b>$host_ver</b> while you have version <b>$local_ver</b>.", {
495  {"addon", local_item["addon_title"].str()},
496  {"host_ver", remote_ver.str()},
497  {"local_ver", local_ver.str()}
498  });
499 
500  required_addons.push_back(r);
501  return r.outcome;
502  }
503 
504  // Check if our version is too out of date to play.
505  if(remote_min_ver > local_ver) {
506  r.outcome = NEED_DOWNLOAD;
507 
508  r.message = VGETTEXT("Your version of <i>$addon</i> is incompatible. You have version <b>$local_ver</b> while the host has version <b>$host_ver</b>.", {
509  {"addon", local_item["addon_title"].str()},
510  {"host_ver", remote_ver.str()},
511  {"local_ver", local_ver.str()}
512  });
513 
514  required_addons.push_back(r);
515  return r.outcome;
516  }
517  }
518 
519  return SATISFIED;
520 }
521 
523 {
524  return !started && vacant_slots > 0;
525 }
526 
528 {
530 }
531 
533 {
534  switch(display_status) {
535  case game_info::CLEAN:
536  return "clean";
537  case game_info::NEW:
538  return "new";
539  case game_info::DELETED:
540  return "deleted";
541  case game_info::UPDATED:
542  return "updated";
543  default:
544  ERR_CF << "BAD display_status " << display_status << " in game " << id << "\n";
545  return "?";
546  }
547 }
548 
549 bool game_info::match_string_filter(const std::string& filter) const
550 {
551  const std::string& s1 = name;
552  const std::string& s2 = map_info;
553  return std::search(s1.begin(), s1.end(), filter.begin(), filter.end(),
554  chars_equal_insensitive) != s1.end()
555  || std::search(s2.begin(), s2.end(), filter.begin(), filter.end(),
556  chars_equal_insensitive) != s2.end();
557 }
558 
559 }
std::string scenario
Definition: lobby_data.hpp:148
std::string map_size_info
Definition: lobby_data.hpp:151
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:423
void add_message(const std::time_t &timestamp, const std::string &user, const std::string &message)
Definition: lobby_data.cpp:62
int h() const
Effective map height.
Definition: map.hpp:116
ADDON_REQ addons_outcome
Definition: lobby_data.hpp:199
std::string status
Definition: lobby_data.hpp:161
std::string era()
Definition: game.cpp:696
#define ERR_CF
Definition: lobby_data.cpp:40
Interfaces for manipulating version numbers of engine, add-ons, etc.
std::vector< std::pair< std::string, bool > > mod_info
List of modification names and whether they&#39;re installed or not.
Definition: lobby_data.hpp:155
bool is_authenticated()
Definition: game.cpp:182
Collection of helper functions relating to Pango formatting.
unsigned int current_turn
Definition: lobby_data.hpp:165
std::deque< chat_message > history_
Definition: lobby_data.hpp:61
config & find_child(config_key_type key, const std::string &name, const std::string &value)
Returns the first child of tag key with a name attribute containing value.
Definition: config.cpp:789
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
New lexcical_cast header.
bool has_attribute(config_key_type key) const
Definition: config.cpp:217
user_state state
Definition: lobby_data.hpp:130
child_itors child_range(config_key_type key)
Definition: config.cpp:366
bool shuffle_sides()
Definition: game.cpp:471
std::set< std::string > members_
Definition: lobby_data.hpp:96
std::string map_info
Definition: lobby_data.hpp:150
bool chars_equal_insensitive(char a, char b)
Definition: general.hpp:21
bool remote_scenario
Definition: lobby_data.hpp:149
Definitions for the interface to Wesnoth Markup Language (WML).
std::string name
Definition: lobby_data.hpp:147
std::string time_limit
Definition: lobby_data.hpp:162
#define b
static lg::log_domain log_lobby("lobby")
bool fog()
Definition: game.cpp:536
Pubic entry points for the MP workflow.
Definition: lobby_data.cpp:49
static game_config_manager * get()
user_info(const config &c)
Definition: lobby_data.cpp:108
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:89
chat_message(const std::time_t &timestamp, const std::string &user, const std::string &message)
Create a chat message.
Definition: lobby_data.cpp:51
bool is_friend(const std::string &nick)
Definition: game.cpp:290
const t_string id
const t_string name
std::ostringstream wrapper.
Definition: formatter.hpp:38
#define DBG_LB
Definition: lobby_data.cpp:45
std::string vision
Definition: lobby_data.hpp:160
const std::string unicode_multiplication_sign
Definition: constants.cpp:41
Encapsulates the map of the game.
Definition: map.hpp:36
static UNUSEDNOWARN std::string _n(const char *str1, const char *str2, int n)
Definition: gettext.hpp:93
static lg::log_domain log_config("config")
std::string map_data
Definition: lobby_data.hpp:146
std::vector< std::string > installed_addons()
Retrieves the names of all installed add-ons.
Definition: manager.cpp:146
bool is_member(const std::string &user) const
Definition: lobby_data.cpp:84
bool registered_users_only()
Definition: game.cpp:461
bool is_ignored(const std::string &nick)
Definition: game.cpp:303
std::string read_map(const std::string &name)
Helper class, don&#39;t construct this directly.
std::string login()
std::string name
Definition: lobby_data.hpp:127
std::string dev_message
The message for developers telling which problem was triggered, this shouldn&#39;t be translated...
bool shroud()
Definition: game.cpp:546
int w() const
Effective map width.
Definition: map.hpp:113
std::string escape_text(const std::string &text)
Escapes the pango markup characters in a text.
Definition: escape.hpp:32
const char * display_status_string() const
Definition: lobby_data.cpp:532
std::size_t i
Definition: function.cpp:933
static lg::log_domain log_engine("engine")
config generate_difficulty_config(const config &source)
Helper function to convert old difficulty markup.
Game configuration data as global variables.
Definition: build_info.cpp:46
static map_location::DIRECTION s
ADDON_REQ check_addon_version_compatibility(const config &local_item, const config &game)
Definition: lobby_data.cpp:460
bool use_map_settings()
Definition: game.cpp:489
This class represents the information a client has about a room.
Definition: lobby_data.hpp:67
Declarations for File-IO.
bool can_observe() const
Definition: lobby_data.cpp:527
static int sort(lua_State *L)
Definition: ltablib.cpp:411
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
Represents version numbers.
std::string era
Definition: lobby_data.hpp:152
This class represents the information a client has about another player.
Definition: lobby_data.hpp:104
void update_state(int selected_game_id, const room_info *current_room=nullptr)
Definition: lobby_data.cpp:119
room_info(const std::string &name)
Definition: lobby_data.cpp:80
double t
Definition: astarsearch.cpp:63
static bool timestamp
Definition: log.cpp:45
int icompare(const std::string &s1, const std::string &s2)
Case-insensitive lexicographical comparison.
Definition: gettext.cpp:476
std::size_t vacant_slots
Definition: lobby_data.hpp:163
const std::string unicode_em_dash
Definition: constants.cpp:39
void remove_member(const std::string &user)
Definition: lobby_data.cpp:94
Standard logging facilities (interface).
std::string str() const
Serializes the version number into string form.
game_display_status display_status
Definition: lobby_data.hpp:188
std::vector< required_addon > required_addons
Definition: lobby_data.hpp:198
void update_relation()
Definition: lobby_data.cpp:138
#define e
game_info(const config &c, const std::vector< std::string > &installed_addons)
Definition: lobby_data.cpp:175
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:456
user_relation relation
Definition: lobby_data.hpp:129
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
bool can_join() const
Definition: lobby_data.cpp:522
mock_char c
bool operator<(const user_info &b) const
Definition: lobby_data.cpp:151
std::string str() const
Definition: formatter.hpp:60
bool empty() const
Definition: config.cpp:837
const config & game_config() const
void process_room_members(const config &data)
Definition: lobby_data.cpp:99
bool match_string_filter(const std::string &filter) const
Definition: lobby_data.cpp:549
const std::string & name() const
Definition: lobby_data.hpp:72
void add_member(const std::string &user)
Definition: lobby_data.cpp:89