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