multiplayer 2.2.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. {multiplayer-2.2.0 → multiplayer-2.3.0}/PKG-INFO +1 -1
  2. {multiplayer-2.2.0 → multiplayer-2.3.0}/pyproject.toml +1 -1
  3. {multiplayer-2.2.0 → multiplayer-2.3.0}/pyproject.toml.orig +1 -1
  4. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/save.py +31 -4
  5. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/server.py +117 -8
  6. {multiplayer-2.2.0 → multiplayer-2.3.0}/README.md +0 -0
  7. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/__init__.py +0 -0
  8. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/client.py +0 -0
  9. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/cities.csv +0 -0
  10. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/countries.csv +0 -0
  11. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/egyptian_gods.csv +0 -0
  12. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/european_kings.csv +0 -0
  13. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/european_queens.csv +0 -0
  14. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/greek_gods.csv +0 -0
  15. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/planets_moons.csv +0 -0
  16. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/rivers.csv +0 -0
  17. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/roman_gods.csv +0 -0
  18. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/data/seas_oceans.csv +0 -0
  19. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/exceptions.py +0 -0
  20. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/game.py +0 -0
  21. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/py.typed +0 -0
  22. {multiplayer-2.2.0 → multiplayer-2.3.0}/src/multiplayer/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiplayer
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: Library that allows you to manage multiple players, locally, on a network, or on the Internet.
5
5
  Author: devfred78
6
6
  Author-email: devfred78 <devfred78@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "multiplayer"
3
- version = "2.2.0"
3
+ version = "2.3.0"
4
4
  description = "Library that allows you to manage multiple players, locally, on a network, or on the Internet."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "multiplayer"
3
- version = "2.2.0"
3
+ version = "2.3.0"
4
4
  description = "Library that allows you to manage multiple players, locally, on a network, or on the Internet."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -32,6 +32,7 @@ _SUPPORTED_CLASSES: Dict[str, type] = {
32
32
 
33
33
  # Name of the table used for the SQLite storage format.
34
34
  _SQLITE_TABLE = "objects"
35
+ _SERVER_CONFIG_CLASS = "__server_config__"
35
36
 
36
37
 
37
38
  def _player_to_dict(player: Player) -> Dict[str, Any]:
@@ -246,6 +247,7 @@ class Save:
246
247
  self._data: Dict[str, Dict[str, Dict[str, Any]]] = {
247
248
  name: {} for name in _SUPPORTED_CLASSES
248
249
  }
250
+ self._server_config: Dict[str, Any] = {}
249
251
 
250
252
  if self.file_path.exists():
251
253
  self._load_file()
@@ -295,7 +297,8 @@ class Save:
295
297
  logger.exception("Failed to read JSON save file.")
296
298
  raise SaveError(f"Cannot read save file: {self.file_path}") from exc
297
299
 
298
- if not isinstance(content, dict) or set(content) != set(_SUPPORTED_CLASSES):
300
+ expected = set(_SUPPORTED_CLASSES)
301
+ if not isinstance(content, dict) or not expected.issubset(content) or set(content) - expected - {_SERVER_CONFIG_CLASS}:
299
302
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
300
303
 
301
304
  for name in _SUPPORTED_CLASSES:
@@ -303,6 +306,10 @@ class Save:
303
306
  if not isinstance(section, dict):
304
307
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
305
308
  self._data[name] = dict(section)
309
+ config = content.get(_SERVER_CONFIG_CLASS, {})
310
+ if not isinstance(config, dict):
311
+ raise SaveError(f"Incompatible save file structure: {self.file_path}")
312
+ self._server_config = dict(config)
306
313
 
307
314
  def _load_sqlite(self) -> None:
308
315
  """Loads the in-memory buffer from an SQLite save file.
@@ -324,9 +331,15 @@ class Save:
324
331
 
325
332
  cursor.execute(f"SELECT class, id, data FROM {_SQLITE_TABLE}")
326
333
  for class_name, obj_id, raw in cursor.fetchall():
327
- if class_name not in _SUPPORTED_CLASSES:
334
+ if class_name not in _SUPPORTED_CLASSES and class_name != _SERVER_CONFIG_CLASS:
328
335
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
329
- self._data[class_name][obj_id] = json.loads(raw)
336
+ data = json.loads(raw)
337
+ if class_name == _SERVER_CONFIG_CLASS:
338
+ if not isinstance(data, dict):
339
+ raise SaveError(f"Incompatible save file structure: {self.file_path}")
340
+ self._server_config = data
341
+ else:
342
+ self._data[class_name][obj_id] = data
330
343
  except sqlite3.DatabaseError as exc:
331
344
  logger.exception("Failed to read SQLite save file.")
332
345
  raise SaveError(f"Cannot read save file: {self.file_path}") from exc
@@ -373,8 +386,17 @@ class Save:
373
386
  The save file is rewritten with an empty but valid structure.
374
387
  """
375
388
  self._data = {name: {} for name in _SUPPORTED_CLASSES}
389
+ self._server_config = {}
376
390
  self.flush()
377
391
 
392
+ def save_server_config(self, config: Dict[str, Any]) -> None:
393
+ """Stores the serializable server configuration in the save buffer."""
394
+ self._server_config = dict(config)
395
+
396
+ def load_server_config(self) -> Dict[str, Any]:
397
+ """Returns the stored server configuration, or an empty mapping."""
398
+ return dict(self._server_config)
399
+
378
400
  def flush(self) -> None:
379
401
  """Persists the in-memory buffer to the underlying save file.
380
402
 
@@ -393,8 +415,11 @@ class Save:
393
415
  SaveError: If the data cannot be written.
394
416
  """
395
417
  try:
418
+ content = dict(self._data)
419
+ if self._server_config:
420
+ content[_SERVER_CONFIG_CLASS] = self._server_config
396
421
  with self.file_path.open("w", encoding="utf-8") as handle:
397
- json.dump(self._data, handle, indent=2)
422
+ json.dump(content, handle, indent=2)
398
423
  except OSError as exc:
399
424
  logger.exception("Failed to write JSON save file.")
400
425
  raise SaveError(f"Cannot write save file: {self.file_path}") from exc
@@ -420,6 +445,8 @@ class Save:
420
445
  for name, section in self._data.items()
421
446
  for obj_id, data in section.items()
422
447
  ]
448
+ if self._server_config:
449
+ rows.append((_SERVER_CONFIG_CLASS, "server", json.dumps(self._server_config)))
423
450
  cursor.executemany(
424
451
  f"INSERT INTO {_SQLITE_TABLE} (class, id, data) VALUES (?, ?, ?)",
425
452
  rows,
@@ -413,8 +413,11 @@ class GameServer:
413
413
  self._server_hash: Optional[str] = (
414
414
  bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() if password else None
415
415
  )
416
- self._admin_hash: Optional[str] = None
417
416
  self.user_registration_enabled: bool = True
417
+ self.orphan_games_allowed: bool = True
418
+ self.unauthenticated_game_creation_allowed: bool = True
419
+ self.unauthenticated_player_join_allowed: bool = True
420
+ self.unauthenticated_observer_join_allowed: bool = True
418
421
  self.hidden: bool = False
419
422
 
420
423
  # Persistence configuration.
@@ -697,6 +700,21 @@ class GameServer:
697
700
  self.persistence_path.parent.mkdir(parents=True, exist_ok=True)
698
701
  try:
699
702
  self._save = Save(self.persistence_path, self.persistence_mode)
703
+ config = self._save.load_server_config()
704
+ if isinstance(config.get("name"), str):
705
+ self.name = config["name"]
706
+ for field in (
707
+ "user_registration_enabled",
708
+ "orphan_games_allowed",
709
+ "unauthenticated_game_creation_allowed",
710
+ "unauthenticated_player_join_allowed",
711
+ "unauthenticated_observer_join_allowed",
712
+ "hidden",
713
+ ):
714
+ if isinstance(config.get(field), bool):
715
+ setattr(self, field, config[field])
716
+ if isinstance(config.get("server_hash"), str) or config.get("server_hash") is None:
717
+ self._server_hash = config.get("server_hash")
700
718
  for game in self._save.load(Game):
701
719
  self._games[game.ID] = game
702
720
  for group in self._save.load(GameGroup):
@@ -724,6 +742,16 @@ class GameServer:
724
742
  self._save.save(player)
725
743
  for user in self._users.values():
726
744
  self._save.save(user)
745
+ self._save.save_server_config({
746
+ "name": self.name,
747
+ "user_registration_enabled": self.user_registration_enabled,
748
+ "orphan_games_allowed": self.orphan_games_allowed,
749
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
750
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
751
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
752
+ "hidden": self.hidden,
753
+ "server_hash": self._server_hash,
754
+ })
727
755
  self._save.flush()
728
756
  except MultiplayerError:
729
757
  logger.exception("Failed to persist data.")
@@ -1644,8 +1672,20 @@ class GameServer:
1644
1672
  "error_code": "INVALID_DATA",
1645
1673
  "message": "A game name is required.",
1646
1674
  }
1675
+ if session.user is None and not self.unauthenticated_game_creation_allowed:
1676
+ return "GAME_CREATE_RESPONSE", {
1677
+ "success": False,
1678
+ "error_code": "AUTHENTICATION_REQUIRED",
1679
+ "message": "An authenticated user is required to create a game.",
1680
+ }
1647
1681
  group_id = payload.get("group_id")
1648
1682
  group = None
1683
+ if group_id is None and not self.orphan_games_allowed:
1684
+ return "GAME_CREATE_RESPONSE", {
1685
+ "success": False,
1686
+ "error_code": "ORPHAN_GAMES_DISABLED",
1687
+ "message": "Creating a game without a group is disabled.",
1688
+ }
1649
1689
  if group_id is not None:
1650
1690
  group = self._groups.get(group_id)
1651
1691
  if group is None:
@@ -1701,7 +1741,10 @@ class GameServer:
1701
1741
  "error_code": "GROUP_NOT_FOUND",
1702
1742
  "message": "Group not found.",
1703
1743
  }
1704
- if not self._authorize_group(session, group, payload.get("group_password")):
1744
+ if (
1745
+ not self._can_admin_group(session, group.ID)
1746
+ and not self._authorize_group(session, group, payload.get("group_password"))
1747
+ ):
1705
1748
  return "GAME_LIST_RESPONSE", {
1706
1749
  "success": False, "error_code": "INVALID_GROUP_PASSWORD",
1707
1750
  "message": "Invalid group password.",
@@ -1746,6 +1789,18 @@ class GameServer:
1746
1789
  "error_code": "INVALID_ACTION",
1747
1790
  "message": "Invalid role.",
1748
1791
  }
1792
+ if role == "PLAYER" and session.user is None and not self.unauthenticated_player_join_allowed:
1793
+ return "GAME_JOIN_RESPONSE", {
1794
+ "success": False,
1795
+ "error_code": "AUTHENTICATION_REQUIRED",
1796
+ "message": "An authenticated user is required to join as a player.",
1797
+ }
1798
+ if role == "OBSERVER" and session.user is None and not self.unauthenticated_observer_join_allowed:
1799
+ return "GAME_JOIN_RESPONSE", {
1800
+ "success": False,
1801
+ "error_code": "AUTHENTICATION_REQUIRED",
1802
+ "message": "An authenticated user is required to join as an observer.",
1803
+ }
1749
1804
  player = self._resolve_player(session, payload.get("player_id"))
1750
1805
  if player is None:
1751
1806
  return "GAME_JOIN_RESPONSE", {
@@ -2660,9 +2715,12 @@ class GameServer:
2660
2715
  "success": True,
2661
2716
  "config": {
2662
2717
  "user_registration_enabled": self.user_registration_enabled,
2718
+ "orphan_games_allowed": self.orphan_games_allowed,
2719
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
2720
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
2721
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
2663
2722
  "hidden": self.hidden,
2664
2723
  "server_password_set": self._server_hash is not None,
2665
- "admin_password_set": self._admin_hash is not None,
2666
2724
  },
2667
2725
  }
2668
2726
 
@@ -2679,6 +2737,19 @@ class GameServer:
2679
2737
  Tuple[str, Dict[str, Any]]: The response type and payload.
2680
2738
  """
2681
2739
  updated: List[str] = []
2740
+ if "name" in payload:
2741
+ value = payload["name"]
2742
+ if not isinstance(value, str):
2743
+ return "SERVER_CONFIG_SET_RESPONSE", {
2744
+ "success": False,
2745
+ "error_code": "INVALID_DATA",
2746
+ "message": "name must be a string.",
2747
+ }
2748
+ if value != self.name:
2749
+ self.name = value
2750
+ updated.append("name")
2751
+ for client in list(self._sessions.values()):
2752
+ self._close_session(client)
2682
2753
  if "user_registration_enabled" in payload:
2683
2754
  value = payload["user_registration_enabled"]
2684
2755
  if not isinstance(value, bool):
@@ -2689,6 +2760,46 @@ class GameServer:
2689
2760
  }
2690
2761
  self.user_registration_enabled = value
2691
2762
  updated.append("user_registration_enabled")
2763
+ if "orphan_games_allowed" in payload:
2764
+ value = payload["orphan_games_allowed"]
2765
+ if not isinstance(value, bool):
2766
+ return "SERVER_CONFIG_SET_RESPONSE", {
2767
+ "success": False,
2768
+ "error_code": "INVALID_DATA",
2769
+ "message": "orphan_games_allowed must be a boolean.",
2770
+ }
2771
+ self.orphan_games_allowed = value
2772
+ updated.append("orphan_games_allowed")
2773
+ if "unauthenticated_game_creation_allowed" in payload:
2774
+ value = payload["unauthenticated_game_creation_allowed"]
2775
+ if not isinstance(value, bool):
2776
+ return "SERVER_CONFIG_SET_RESPONSE", {
2777
+ "success": False,
2778
+ "error_code": "INVALID_DATA",
2779
+ "message": "unauthenticated_game_creation_allowed must be a boolean.",
2780
+ }
2781
+ self.unauthenticated_game_creation_allowed = value
2782
+ updated.append("unauthenticated_game_creation_allowed")
2783
+ if "unauthenticated_player_join_allowed" in payload:
2784
+ value = payload["unauthenticated_player_join_allowed"]
2785
+ if not isinstance(value, bool):
2786
+ return "SERVER_CONFIG_SET_RESPONSE", {
2787
+ "success": False,
2788
+ "error_code": "INVALID_DATA",
2789
+ "message": "unauthenticated_player_join_allowed must be a boolean.",
2790
+ }
2791
+ self.unauthenticated_player_join_allowed = value
2792
+ updated.append("unauthenticated_player_join_allowed")
2793
+ if "unauthenticated_observer_join_allowed" in payload:
2794
+ value = payload["unauthenticated_observer_join_allowed"]
2795
+ if not isinstance(value, bool):
2796
+ return "SERVER_CONFIG_SET_RESPONSE", {
2797
+ "success": False,
2798
+ "error_code": "INVALID_DATA",
2799
+ "message": "unauthenticated_observer_join_allowed must be a boolean.",
2800
+ }
2801
+ self.unauthenticated_observer_join_allowed = value
2802
+ updated.append("unauthenticated_observer_join_allowed")
2692
2803
  if "hidden" in payload:
2693
2804
  value = payload["hidden"]
2694
2805
  if not isinstance(value, bool):
@@ -2704,11 +2815,9 @@ class GameServer:
2704
2815
  payload["server_password"].encode(), bcrypt.gensalt()
2705
2816
  ).decode()
2706
2817
  updated.append("server_password")
2707
- if isinstance(payload.get("admin_password"), str):
2708
- self._admin_hash = bcrypt.hashpw(
2709
- payload["admin_password"].encode(), bcrypt.gensalt()
2710
- ).decode()
2711
- updated.append("admin_password")
2818
+ for client in list(self._sessions.values()):
2819
+ self._close_session(client)
2820
+ self._save_persistence()
2712
2821
  self._audit("SERVER_CONFIG_SET", session, "server")
2713
2822
  return "SERVER_CONFIG_SET_RESPONSE", {
2714
2823
  "success": True,
File without changes