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 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 "wml_exception.hpp"
31 #include "version.hpp"
32 
33 #include <iterator>
34 
35 #include <boost/algorithm/string.hpp>
36 
37 static lg::log_domain log_config("config");
38 #define ERR_CF LOG_STREAM(err, log_config)
39 static lg::log_domain log_engine("engine");
40 #define WRN_NG LOG_STREAM(warn, log_engine)
41 
42 static lg::log_domain log_lobby("lobby");
43 #define DBG_LB LOG_STREAM(info, log_lobby)
44 #define LOG_LB LOG_STREAM(info, log_lobby)
45 #define ERR_LB LOG_STREAM(err, log_lobby)
46 
47 namespace mp {
48 
50  const std::string& user,
51  const std::string& message)
52  : timestamp(timestamp), user(user), message(message)
53 {
54 }
55 
57 {
58 }
59 
60 void chat_session::add_message(const std::time_t& timestamp,
61  const std::string& user,
62  const std::string& message)
63 {
64  history_.emplace_back(timestamp, user, message);
65 }
66 
67 
68 void chat_session::add_message(const std::string& user, const std::string& message)
69 {
70  add_message(std::time(nullptr), user, message);
71 }
72 
74 {
75  history_.clear();
76 }
77 
78 room_info::room_info(const std::string& name) : name_(name), members_(), log_()
79 {
80 }
81 
82 bool room_info::is_member(const std::string& user) const
83 {
84  return members_.find(user) != members_.end();
85 }
86 
87 void room_info::add_member(const std::string& user)
88 {
89  members_.insert(user);
90 }
91 
92 void room_info::remove_member(const std::string& user)
93 {
94  members_.erase(user);
95 }
96 
98 {
99  members_.clear();
100  for(const auto & m : data.child_range("member"))
101  {
102  members_.insert(m["name"]);
103  }
104 }
105 
107  : name(c["name"])
108  , game_id(c["game_id"])
109  , relation(ME)
110  , state(game_id == 0 ? LOBBY : GAME)
111  , registered(c["registered"].to_bool())
112  , observing(c["status"] == "observing")
113 {
114  update_relation();
115 }
116 
117 void user_info::update_state(int selected_game_id,
118  const room_info* current_room /*= nullptr*/)
119 {
120  if(game_id != 0) {
121  if(game_id == selected_game_id) {
122  state = SEL_GAME;
123  } else {
124  state = GAME;
125  }
126  } else {
127  if(current_room != nullptr && current_room->is_member(name)) {
128  state = SEL_ROOM;
129  } else {
130  state = LOBBY;
131  }
132  }
133  update_relation();
134 }
135 
137 {
138  if(name == preferences::login()) {
139  relation = ME;
140  } else if(preferences::is_ignored(name)) {
141  relation = IGNORED;
142  } else if(preferences::is_friend(name)) {
143  relation = FRIEND;
144  } else {
145  relation = NEUTRAL;
146  }
147 }
148 
149 bool user_info::operator<(const user_info& b) const
150 {
151  return relation < b.relation || (relation == b.relation && translation::icompare(name, b.name) < 0);
152 }
153 
154 namespace
155 {
156 const std::string& spaced_em_dash()
157 {
158  static const std::string res = " " + font::unicode_em_dash + " ";
159  return res;
160 }
161 
162 // Returns an abbreviated form of the provided string - ie, 'Ageless Era' should become 'AE'
163 std::string make_short_name(const std::string& long_name)
164 {
165  if(long_name.empty()) {
166  return "";
167  }
168 
169  std::size_t pos = 0;
170 
171  std::stringstream ss;
172  ss << long_name[pos];
173 
174  while(pos < long_name.size()) {
175  pos = long_name.find(' ', pos + 1);
176 
177  if(pos <= long_name.size() - 2) {
178  ss << long_name[pos + 1];
179  }
180  }
181 
182  return ss.str();
183 }
184 
185 std::string make_game_type_marker(std::string text, bool color_for_missing)
186 {
187  if(color_for_missing) {
188  return formatter() << "<b><span color='#f00'>[" << text << "]</span></b> ";
189  } else {
190  return formatter() << "<b>[" << text << "]</b> ";
191  }
192 }
193 
194 } // end anon namespace
195 
196 game_info::game_info(const config& game, const config& game_config, const std::vector<std::string>& installed_addons)
197  : id(game["id"])
198  , map_data(game["map_data"])
199  , name(game["name"])
200  , scenario()
201  , remote_scenario(false)
202  , map_info()
203  , map_size_info()
204  , era()
205  , era_short()
206  , gold(game["mp_village_gold"])
207  , support(game["mp_village_support"])
208  , xp(game["experience_modifier"].str() + "%")
209  , vision()
210  , status()
211  , time_limit()
212  , vacant_slots()
213  , current_turn(0)
214  , reloaded(game["savegame"].to_bool())
215  , started(false)
216  , fog(game["mp_fog"].to_bool())
217  , shroud(game["mp_shroud"].to_bool())
218  , observers(game["observer"].to_bool(true))
219  , shuffle_sides(game["shuffle_sides"].to_bool(true))
220  , use_map_settings(game["mp_use_map_settings"].to_bool())
221  , registered_users_only(game["registered_users_only"].to_bool())
222  , verified(true)
223  , password_required(game["password"].to_bool())
224  , have_era(true)
225  , have_all_mods(true)
226  , has_friends(false)
227  , has_ignored(false)
228  , display_status(NEW)
229  , required_addons()
230  , addons_outcome(SATISFIED)
231 {
232  // Parse the list of addons required to join this game.
233  for(const config& addon : game.child_range("addon")) {
234  if(addon.has_attribute("id")) {
235  if(std::find(installed_addons.begin(), installed_addons.end(), addon["id"].str()) == installed_addons.end()) {
236  required_addon r;
237  r.addon_id = addon["id"].str();
239 
240  // Use addon name if provided, else fall back on the addon id.
241  if(addon.has_attribute("name")) {
242  r.message = VGETTEXT("Missing addon: $name", {{"name", addon["name"].str()}});
243  } else {
244  r.message = VGETTEXT("Missing addon: $id", {{"id", addon["id"].str()}});
245  }
246 
247  required_addons.push_back(std::move(r));
248 
249  if(addons_outcome == SATISFIED) {
251  }
252  }
253  }
254  }
255 
256  if(!game["mp_era"].empty()) {
257  const config& era_cfg = game_config.find_child("era", "id", game["mp_era"]);
258  if(era_cfg) {
259  era = era_cfg["name"].str();
260  era_short = era_cfg["short_name"].str();
261  if(era_short.empty()) {
262  era_short = make_short_name(era);
263  }
264 
265  ADDON_REQ result = check_addon_version_compatibility(era_cfg, game);
266  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
267  } else {
268  have_era = !game["require_era"].to_bool(true);
269  era = game["mp_era_name"].str();
270  era_short = make_short_name(era);
271  verified = false;
272 
273  if(!have_era) {
275  }
276  }
277  } else {
278  era = _("Unknown era");
279  era_short = "??";
280  verified = false;
281  }
282 
283  std::stringstream info_stream;
284  info_stream << era;
285 
286  for(const config& cfg : game.child_range("modification")) {
287  mod_info.emplace_back(cfg["name"].str(), true);
288  info_stream << ' ' << mod_info.back().first;
289 
290  if(cfg["require_modification"].to_bool(false)) {
291  if(const config& mod = game_config.find_child("modification", "id", cfg["id"])) {
292  ADDON_REQ result = check_addon_version_compatibility(mod, game);
293  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
294  } else {
295  have_all_mods = false;
296  mod_info.back().second = false;
297 
299  }
300  }
301  }
302 
303  std::sort(mod_info.begin(), mod_info.end(), [](const auto& lhs, const auto& rhs) {
304  return translation::icompare(lhs.first, rhs.first) < 0;
305  });
306 
307  info_stream << ' ';
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(const incorrect_map_format_error&) {
323  verified = false;
324  } catch(const wml_exception& e) {
325  ERR_CF << "map could not be loaded: " << e.dev_message << '\n';
326  verified = false;
327  }
328  }
329 
330  info_stream << " ";
331 
332  //
333  // Check scenarios and campaigns
334  //
335  if(!game["mp_scenario"].empty() && game["mp_campaign"].empty()) {
336  // Check if it's a multiplayer scenario
337  const config* level_cfg = &game_config.find_child("multiplayer", "id", game["mp_scenario"]);
338 
339  // Check if it's a user map
340  if(!*level_cfg) {
341  level_cfg = &game_config.find_child("generic_multiplayer", "id", game["mp_scenario"]);
342  }
343 
344  if(*level_cfg) {
345  scenario = formatter() << make_game_type_marker(_("S"), false) << (*level_cfg)["name"].str();
346  info_stream << scenario;
347 
348  // Reloaded games do not match the original scenario hash, so it makes no sense
349  // to test them, since they always would appear as remote scenarios
350  if(!reloaded) {
351  if(const config& hashes = game_config.child("multiplayer_hashes")) {
352  std::string hash = game["hash"];
353  bool hash_found = false;
354  for(const auto & i : hashes.attribute_range()) {
355  if(i.first == game["mp_scenario"] && i.second == hash) {
356  hash_found = true;
357  break;
358  }
359  }
360 
361  if(!hash_found) {
362  remote_scenario = true;
363  info_stream << spaced_em_dash();
364  info_stream << _("Remote scenario");
365  verified = false;
366  }
367  }
368  }
369 
370  if((*level_cfg)["require_scenario"].to_bool(false)) {
371  ADDON_REQ result = check_addon_version_compatibility((*level_cfg), game);
372  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
373  }
374  } else {
375  scenario = formatter() << make_game_type_marker(_("S"), true) << game["mp_scenario_name"].str();
376  info_stream << scenario;
377  verified = false;
378  }
379  } else if(!game["mp_campaign"].empty()) {
380  if(const config& campaign_cfg = game_config.find_child("campaign", "id", game["mp_campaign"])) {
381  std::stringstream campaign_text;
382  campaign_text
383  << make_game_type_marker(_("C"), false)
384  << campaign_cfg["name"] << spaced_em_dash()
385  << game["mp_scenario_name"];
386 
387  // Difficulty
388  config difficulties = gui2::dialogs::generate_difficulty_config(campaign_cfg);
389  for(const config& difficulty : difficulties.child_range("difficulty")) {
390  if(difficulty["define"] == game["difficulty_define"]) {
391  campaign_text << spaced_em_dash() << difficulty["description"];
392 
393  break;
394  }
395  }
396 
397  scenario = campaign_text.str();
398  info_stream << campaign_text.rdbuf();
399 
400  // TODO: should we have this?
401  //if(game["require_scenario"].to_bool(false)) {
402  ADDON_REQ result = check_addon_version_compatibility(campaign_cfg, game);
403  addons_outcome = std::max(addons_outcome, result); // Elevate to most severe error level encountered so far
404  //}
405  } else {
406  scenario = formatter() << make_game_type_marker(_("C"), true) << game["mp_campaign_name"].str();
407  info_stream << scenario;
408  verified = false;
409  }
410  } else {
411  scenario = _("Unknown scenario");
412  info_stream << scenario;
413  verified = false;
414  }
415 
416  // Remove any newlines that might have been in game titles
417  boost::replace_all(scenario, "\n", " " + font::unicode_em_dash + " ");
418 
419  if(reloaded) {
420  info_stream << spaced_em_dash();
421  info_stream << _("Reloaded game");
422  verified = false;
423  }
424 
425  // These should always be present in the data the server sends, but may or may not be empty.
426  // I'm just using child_or_empty here to preempt any cases where they might not be included.
427  const config& s = game.child_or_empty("slot_data");
428  const config& t = game.child_or_empty("turn_data");
429 
430  if(!s.empty()) {
431  started = false;
432 
433  vacant_slots = s["vacant"].to_unsigned();
434 
435  if(vacant_slots > 0) {
436  status = formatter() << _n("Vacant Slot:", "Vacant Slots:", vacant_slots) << " " << vacant_slots << "/" << s["max"];
437  } else {
438  status = _("mp_game_available_slots^Full");
439  }
440  }
441 
442  if(!t.empty()) {
443  started = true;
444 
445  current_turn = t["current"].to_unsigned();
446  const int max_turns = t["max"].to_int();
447 
448  if(max_turns > -1) {
449  status = formatter() << _("Turn") << " " << t["current"] << "/" << max_turns;
450  } else {
451  status = formatter() << _("Turn") << " " << t["current"];
452  }
453  }
454 
455  if(fog) {
456  vision = _("Fog");
457  if(shroud) {
458  vision += "/";
459  vision += _("Shroud");
460  }
461  } else if(shroud) {
462  vision = _("Shroud");
463  } else {
464  vision = _("vision^none");
465  }
466 
467  if(game["mp_countdown"].to_bool()) {
469  << game["mp_countdown_init_time"].str() << "+"
470  << game["mp_countdown_turn_bonus"].str() << "/"
471  << game["mp_countdown_action_bonus"].str();
472  } else {
473  time_limit = _("time limit^none");
474  }
475 
476  map_info = info_stream.str();
477 }
478 
480 {
481  if(!local_item.has_attribute("addon_id") || !local_item.has_attribute("addon_version")) {
482  return SATISFIED;
483  }
484 
485  if(const config& game_req = game.find_child("addon", "id", local_item["addon_id"])) {
486  required_addon r {local_item["addon_id"].str(), SATISFIED, ""};
487 
488  // Local version
489  const version_info local_ver(local_item["addon_version"].str());
490  version_info local_min_ver(local_item.has_attribute("addon_min_version") ? local_item["addon_min_version"] : local_item["addon_version"]);
491 
492  // If the UMC didn't specify last compatible version, assume no backwards compatibility.
493  // Also apply some sanity checking regarding min version; if the min ver doesn't make sense, ignore it.
494  local_min_ver = std::min(local_min_ver, local_ver);
495 
496  // Remote version
497  const version_info remote_ver(game_req["version"].str());
498  version_info remote_min_ver(game_req.has_attribute("min_version") ? game_req["min_version"] : game_req["version"]);
499 
500  remote_min_ver = std::min(remote_min_ver, remote_ver);
501 
502  // Check if the host is too out of date to play.
503  if(local_min_ver > remote_ver) {
504  r.outcome = CANNOT_SATISFY;
505 
506  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>.", {
507  {"addon", local_item["addon_title"].str()},
508  {"host_ver", remote_ver.str()},
509  {"local_ver", local_ver.str()}
510  });
511 
512  required_addons.push_back(r);
513  return r.outcome;
514  }
515 
516  // Check if our version is too out of date to play.
517  if(remote_min_ver > local_ver) {
518  r.outcome = NEED_DOWNLOAD;
519 
520  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>.", {
521  {"addon", local_item["addon_title"].str()},
522  {"host_ver", remote_ver.str()},
523  {"local_ver", local_ver.str()}
524  });
525 
526  required_addons.push_back(r);
527  return r.outcome;
528  }
529  }
530 
531  return SATISFIED;
532 }
533 
535 {
536  return !started && vacant_slots > 0;
537 }
538 
540 {
542 }
543 
545 {
546  switch(display_status) {
547  case game_info::CLEAN:
548  return "clean";
549  case game_info::NEW:
550  return "new";
551  case game_info::DELETED:
552  return "deleted";
553  case game_info::UPDATED:
554  return "updated";
555  default:
556  ERR_CF << "BAD display_status " << display_status << " in game " << id << "\n";
557  return "?";
558  }
559 }
560 
561 bool game_info::match_string_filter(const std::string& filter) const
562 {
563  const std::string& s1 = name;
564  const std::string& s2 = map_info;
565  return std::search(s1.begin(), s1.end(), filter.begin(), filter.end(),
566  chars_equal_insensitive) != s1.end()
567  || std::search(s2.begin(), s2.end(), filter.begin(), filter.end(),
568  chars_equal_insensitive) != s2.end();
569 }
570 
571 }
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:60
int h() const
Effective map height.
Definition: map.hpp:93
ADDON_REQ addons_outcome
Definition: lobby_data.hpp:200
std::string status
Definition: lobby_data.hpp:162
std::string era()
Definition: game.cpp:699
#define ERR_CF
Definition: lobby_data.cpp:38
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:156
bool is_authenticated()
Definition: game.cpp:185
unsigned int current_turn
Definition: lobby_data.hpp:166
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:474
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:163
#define b
static lg::log_domain log_lobby("lobby")
bool fog()
Definition: game.cpp:539
Pubic entry points for the MP workflow.
Definition: lobby_data.cpp:47
user_info(const config &c)
Definition: lobby_data.cpp:106
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:49
bool is_friend(const std::string &nick)
Definition: game.cpp:293
std::ostringstream wrapper.
Definition: formatter.hpp:38
std::string vision
Definition: lobby_data.hpp:161
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:146
std::vector< std::string > installed_addons()
Retrieves the names of all installed add-ons.
Definition: manager.cpp:147
bool is_member(const std::string &user) const
Definition: lobby_data.cpp:82
bool registered_users_only()
Definition: game.cpp:464
std::string era_short
Definition: lobby_data.hpp:153
bool is_ignored(const std::string &nick)
Definition: game.cpp:306
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:549
int w() const
Effective map width.
Definition: map.hpp:90
const char * display_status_string() const
Definition: lobby_data.cpp:544
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:479
bool use_map_settings()
Definition: game.cpp:492
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:539
static int sort(lua_State *L)
Definition: ltablib.cpp:411
#define VGETTEXT(msgid,...)
Represents version numbers.
Definition: version.hpp:43
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:117
room_info(const std::string &name)
Definition: lobby_data.cpp:78
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:164
const std::string unicode_em_dash
Definition: constants.cpp:39
void remove_member(const std::string &user)
Definition: lobby_data.cpp:92
Standard logging facilities (interface).
std::string str() const
Serializes the version number into string form.
Definition: version.cpp:115
game_display_status display_status
Definition: lobby_data.hpp:189
game_info(const config &c, const config &game_config, const std::vector< std::string > &installed_addons)
Definition: lobby_data.cpp:196
std::vector< required_addon > required_addons
Definition: lobby_data.hpp:199
void update_relation()
Definition: lobby_data.cpp:136
#define e
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:534
mock_char c
Interfaces for manipulating version numbers of engine, add-ons, etc.
bool operator<(const user_info &b) const
Definition: lobby_data.cpp:149
std::string str() const
Definition: formatter.hpp:60
bool empty() const
Definition: config.cpp:837
void process_room_members(const config &data)
Definition: lobby_data.cpp:97
bool match_string_filter(const std::string &filter) const
Definition: lobby_data.cpp:561
const std::string & name() const
Definition: lobby_data.hpp:72
void add_member(const std::string &user)
Definition: lobby_data.cpp:87