multiplayer 2.3.0__tar.gz → 2.4.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.3.0 → multiplayer-2.4.0}/PKG-INFO +1 -1
  2. {multiplayer-2.3.0 → multiplayer-2.4.0}/pyproject.toml +1 -1
  3. {multiplayer-2.3.0 → multiplayer-2.4.0}/pyproject.toml.orig +1 -1
  4. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/client.py +15 -0
  5. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/save.py +9 -2
  6. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/server.py +266 -7
  7. {multiplayer-2.3.0 → multiplayer-2.4.0}/README.md +0 -0
  8. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/__init__.py +0 -0
  9. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/cities.csv +0 -0
  10. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/countries.csv +0 -0
  11. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/egyptian_gods.csv +0 -0
  12. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/european_kings.csv +0 -0
  13. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/european_queens.csv +0 -0
  14. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/greek_gods.csv +0 -0
  15. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/planets_moons.csv +0 -0
  16. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/rivers.csv +0 -0
  17. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/roman_gods.csv +0 -0
  18. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/data/seas_oceans.csv +0 -0
  19. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/exceptions.py +0 -0
  20. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/game.py +0 -0
  21. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/py.typed +0 -0
  22. {multiplayer-2.3.0 → multiplayer-2.4.0}/src/multiplayer/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiplayer
3
- Version: 2.3.0
3
+ Version: 2.4.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.3.0"
3
+ version = "2.4.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.3.0"
3
+ version = "2.4.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"
@@ -666,6 +666,21 @@ class GameClient:
666
666
  self.__session_player = player
667
667
  return player
668
668
 
669
+ def save_persistence(self) -> Dict[str, Any]:
670
+ """Requests an immediate persistence save on the server.
671
+
672
+ Sends a ``SERVER_PERSISTENCE_SAVE`` request to the server. The current
673
+ session must have administrator privileges.
674
+
675
+ Returns:
676
+ Dict[str, Any]: The response payload from the server.
677
+
678
+ Raises:
679
+ MultiplayerError: If the server returns an error.
680
+ ConnectionError: If the client is not connected.
681
+ """
682
+ return self.send_request("SERVER_PERSISTENCE_SAVE")
683
+
669
684
  def __enter__(self) -> "GameClient":
670
685
  """Enters the context manager, opening the connection.
671
686
 
@@ -380,13 +380,20 @@ class Save:
380
380
  deserializer = _SERIALIZERS[name][1]
381
381
  return [deserializer(data) for data in self._data[name].values()]
382
382
 
383
+ def clear(self) -> None:
384
+ """Clears the in-memory buffer without touching the save file.
385
+
386
+ The change is not persisted until :meth:`flush` is called.
387
+ """
388
+ self._data = {name: {} for name in _SUPPORTED_CLASSES}
389
+ self._server_config = {}
390
+
383
391
  def reset(self) -> None:
384
392
  """Clears the in-memory buffer and the underlying save file.
385
393
 
386
394
  The save file is rewritten with an empty but valid structure.
387
395
  """
388
- self._data = {name: {} for name in _SUPPORTED_CLASSES}
389
- self._server_config = {}
396
+ self.clear()
390
397
  self.flush()
391
398
 
392
399
  def save_server_config(self, config: Dict[str, Any]) -> None:
@@ -65,6 +65,7 @@ DEFAULT_PORT = 65432
65
65
  DEFAULT_MULTICAST_GROUP = "239.255.0.1"
66
66
  DEFAULT_MULTICAST_PORT = 65434
67
67
  DEFAULT_GC_PERIODICITY = 900
68
+ DEFAULT_PERSISTENCE_PERIODICITY = 0
68
69
  DEFAULT_TLS_DOMAIN = "localhost"
69
70
 
70
71
  # Default persistence paths used when none is provided by the caller.
@@ -268,6 +269,7 @@ class GameServer:
268
269
  "PLAYER_LIST_ALL": AccessLevel.ADMIN,
269
270
  "GAME_CREATE": AccessLevel.BASE,
270
271
  "GAME_LIST": AccessLevel.BASE,
272
+ "GAME_PARTICIPANTS_LIST": AccessLevel.BASE,
271
273
  "GAME_JOIN": AccessLevel.BASE,
272
274
  "GAME_LEAVE": AccessLevel.BASE,
273
275
  "GAME_CONTROL": AccessLevel.BASE,
@@ -311,6 +313,7 @@ class GameServer:
311
313
  "PLAYER_LIST_ALL": "PLAYER_LIST_ALL_RESPONSE",
312
314
  "GAME_CREATE": "GAME_CREATE_RESPONSE",
313
315
  "GAME_LIST": "GAME_LIST_RESPONSE",
316
+ "GAME_PARTICIPANTS_LIST": "GAME_PARTICIPANTS_LIST_RESPONSE",
314
317
  "GAME_JOIN": "GAME_JOIN_RESPONSE",
315
318
  "GAME_LEAVE": "GAME_LEAVE_RESPONSE",
316
319
  "GAME_CONTROL": "GAME_CONTROL_RESPONSE",
@@ -355,6 +358,7 @@ class GameServer:
355
358
  multicast_port: int = DEFAULT_MULTICAST_PORT,
356
359
  persistence_mode: Optional[SaveFormat] = None,
357
360
  persistence_path: Optional[Path] = None,
361
+ persistence_periodicity: int = DEFAULT_PERSISTENCE_PERIODICITY,
358
362
  garbage_collection_periodicity: int = DEFAULT_GC_PERIODICITY,
359
363
  ):
360
364
  """Initializes a new multiplayer game server.
@@ -375,6 +379,8 @@ class GameServer:
375
379
  multicast_port (int): UDP multicast port for discovery.
376
380
  persistence_mode (SaveFormat | None): Persistence storage format.
377
381
  persistence_path (Path | None): Path to the persistence file.
382
+ persistence_periodicity (int): Seconds between cyclic persistence
383
+ saves (0 to disable periodic saving).
378
384
  garbage_collection_periodicity (int): Seconds between orphan player
379
385
  garbage collections.
380
386
 
@@ -390,6 +396,12 @@ class GameServer:
390
396
  raise ValueError("The unencrypted port must differ from the main port.")
391
397
  if not isinstance(multicast_port, int) or not 1 <= multicast_port <= 65535:
392
398
  raise ValueError(f"Invalid multicast port: {multicast_port}")
399
+ if (
400
+ not isinstance(persistence_periodicity, int)
401
+ or isinstance(persistence_periodicity, bool)
402
+ or persistence_periodicity < 0
403
+ ):
404
+ raise ValueError(f"Invalid persistence periodicity: {persistence_periodicity}")
393
405
  if use_tls and not tls_self_signed and (tls_cert_path is None or tls_key_path is None):
394
406
  raise ValueError(
395
407
  "TLS is enabled without self-signed certificate: both "
@@ -409,6 +421,7 @@ class GameServer:
409
421
  self.multicast_group: str = multicast_group
410
422
  self.multicast_port: int = multicast_port
411
423
  self.garbage_collection_periodicity: int = garbage_collection_periodicity
424
+ self.persistence_periodicity: int = persistence_periodicity
412
425
 
413
426
  self._server_hash: Optional[str] = (
414
427
  bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() if password else None
@@ -418,6 +431,7 @@ class GameServer:
418
431
  self.unauthenticated_game_creation_allowed: bool = True
419
432
  self.unauthenticated_player_join_allowed: bool = True
420
433
  self.unauthenticated_observer_join_allowed: bool = True
434
+ self.participants_visible_to_all: bool = False
421
435
  self.hidden: bool = False
422
436
 
423
437
  # Persistence configuration.
@@ -442,6 +456,7 @@ class GameServer:
442
456
  self._game_custom_state: Dict[str, Dict[str, Any]] = {}
443
457
  self._game_roles: Dict[str, Dict[str, str]] = {}
444
458
  self._game_creator_session: Dict[str, str] = {}
459
+ self._game_creator_user: Dict[str, str] = {}
445
460
  self._audit_log: List[Dict[str, Any]] = []
446
461
 
447
462
  # Runtime state.
@@ -450,6 +465,7 @@ class GameServer:
450
465
  self._unencrypted_server: Optional[asyncio.AbstractServer] = None
451
466
  self._discovery_transport: Optional[asyncio.DatagramTransport] = None
452
467
  self._gc_task: Optional[asyncio.Task] = None
468
+ self._persistence_task: Optional[asyncio.Task] = None
453
469
  self._running: bool = False
454
470
  self._start_time: float = 0.0
455
471
  self._actual_port: int = port
@@ -520,6 +536,8 @@ class GameServer:
520
536
  self._running = True
521
537
  self._start_time = time.monotonic()
522
538
  self._gc_task = asyncio.ensure_future(self._garbage_collection_loop())
539
+ if self.persistence_periodicity > 0:
540
+ self._persistence_task = asyncio.ensure_future(self._persistence_loop())
523
541
  logger.info("Server '%s' started on %s:%s", self.name, self.host, self._actual_port)
524
542
 
525
543
  async def stop(self) -> None:
@@ -540,6 +558,14 @@ class GameServer:
540
558
  pass
541
559
  self._gc_task = None
542
560
 
561
+ if self._persistence_task is not None:
562
+ self._persistence_task.cancel()
563
+ try:
564
+ await self._persistence_task
565
+ except asyncio.CancelledError:
566
+ pass
567
+ self._persistence_task = None
568
+
543
569
  await self._broadcast_shutdown()
544
570
 
545
571
  for session in list(self._sessions.values()):
@@ -569,6 +595,13 @@ class GameServer:
569
595
  await self.stop()
570
596
  await self.start()
571
597
 
598
+ def save_persistence(self) -> None:
599
+ """Immediately saves persistent server data.
600
+
601
+ This method has no effect if persistence is not enabled.
602
+ """
603
+ self._save_persistence()
604
+
572
605
  def _build_tls_context(self) -> ssl.SSLContext:
573
606
  """Builds the TLS 1.3 context used to secure the main TCP port.
574
607
 
@@ -709,31 +742,100 @@ class GameServer:
709
742
  "unauthenticated_game_creation_allowed",
710
743
  "unauthenticated_player_join_allowed",
711
744
  "unauthenticated_observer_join_allowed",
745
+ "participants_visible_to_all",
712
746
  "hidden",
713
747
  ):
714
748
  if isinstance(config.get(field), bool):
715
749
  setattr(self, field, config[field])
750
+ if (
751
+ isinstance(config.get("persistence_periodicity"), int)
752
+ and not isinstance(config.get("persistence_periodicity"), bool)
753
+ and config["persistence_periodicity"] >= 0
754
+ ):
755
+ self.persistence_periodicity = config["persistence_periodicity"]
716
756
  if isinstance(config.get("server_hash"), str) or config.get("server_hash") is None:
717
757
  self._server_hash = config.get("server_hash")
718
758
  for game in self._save.load(Game):
719
759
  self._games[game.ID] = game
720
760
  for group in self._save.load(GameGroup):
761
+ self._share_group_games(group)
721
762
  self._groups[group.ID] = group
722
763
  for player in self._save.load(Player):
723
764
  self._players[player.ID] = player
724
765
  for user in self._save.load(User):
725
766
  self._users[user.username] = user
726
767
  self._players[user.player.ID] = user.player
768
+ self._restore_game_participants()
769
+ creators = config.get("game_creators")
770
+ if isinstance(creators, dict):
771
+ self._game_creator_user = {
772
+ game_id: username
773
+ for game_id, username in creators.items()
774
+ if game_id in self._games and username in self._users
775
+ }
727
776
  except MultiplayerError:
728
777
  logger.exception("Failed to load persistent data.")
729
778
 
779
+ def _restore_game_participants(self) -> None:
780
+ """Rebuilds the participants of the games restored from the save file.
781
+
782
+ A save file stores a copy of every player and observer of a game, so
783
+ each copy is replaced by the player of the same ID known by the
784
+ server, keeping the order of the players, which gives the turns. Only
785
+ the players of a user account are kept: a guest player belonged to a
786
+ session that no longer exists. The role of each kept participant is
787
+ recorded, so that it can be listed, leave the game or be kicked.
788
+ """
789
+ persistent_ids = self._persistent_player_ids()
790
+ for game in self._games.values():
791
+ roles: Dict[str, str] = {}
792
+ players: List[Player] = []
793
+ observers: List[Player] = []
794
+ for copies, kept, role in (
795
+ (game.players, players, "PLAYER"),
796
+ (game.observers, observers, "OBSERVER"),
797
+ ):
798
+ for copy in copies:
799
+ player = self._players.get(copy.ID)
800
+ if player is None or player.ID not in persistent_ids or player.ID in roles:
801
+ continue
802
+ kept.append(player)
803
+ roles[player.ID] = role
804
+ # The restored lists are replaced in place, as the save layer does:
805
+ # joining again would check the passwords and the capacities.
806
+ game._players = players
807
+ game._observers = observers
808
+ self._game_roles[game.ID] = roles
809
+
810
+ def _share_group_games(self, group: GameGroup) -> None:
811
+ """Makes a restored group hold the games known by the server.
812
+
813
+ A save file stores a full copy of every game of a group, so a restored
814
+ group holds game instances distinct from the ones of ``self._games``:
815
+ joining, leaving or controlling a game would then never be reflected
816
+ in the listing of its group. Each copy is replaced by the game of the
817
+ same ID, keeping the order of the games. A game only known through its
818
+ group is registered on the server.
819
+
820
+ Args:
821
+ group (GameGroup): The group restored from the save file.
822
+ """
823
+ for copy in group.games:
824
+ group.remove_game(copy.ID)
825
+ group.add_game(self._games.setdefault(copy.ID, copy))
826
+
730
827
  def _save_persistence(self) -> None:
731
- """Persists the in-memory domain objects when persistence is enabled."""
828
+ """Persists the in-memory domain objects when persistence is enabled.
829
+
830
+ The save buffer is cleared first so that objects deleted from the
831
+ server are also removed from the save file.
832
+ """
732
833
  if self.persistence_mode is None or self.persistence_path is None:
733
834
  return
734
835
  try:
735
836
  if self._save is None:
736
837
  self._save = Save(self.persistence_path, self.persistence_mode)
838
+ self._save.clear()
737
839
  for game in self._games.values():
738
840
  self._save.save(game)
739
841
  for group in self._groups.values():
@@ -749,8 +851,15 @@ class GameServer:
749
851
  "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
750
852
  "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
751
853
  "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
854
+ "participants_visible_to_all": self.participants_visible_to_all,
752
855
  "hidden": self.hidden,
856
+ "persistence_periodicity": self.persistence_periodicity,
753
857
  "server_hash": self._server_hash,
858
+ "game_creators": {
859
+ game_id: username
860
+ for game_id, username in self._game_creator_user.items()
861
+ if game_id in self._games
862
+ },
754
863
  })
755
864
  self._save.flush()
756
865
  except MultiplayerError:
@@ -1029,7 +1138,12 @@ class GameServer:
1029
1138
  pass
1030
1139
 
1031
1140
  def _remove_session_players_from_game(self, session: ClientSession, game_id: str) -> None:
1032
- """Removes every session player from a game on disconnection.
1141
+ """Removes the guest players of a session from a game on disconnection.
1142
+
1143
+ A guest player only exists for the session that created it, so it
1144
+ leaves its games with the connection. The player of a user account
1145
+ stays in its games: the user finds them again from any later session,
1146
+ including after a restart of a server with persistence enabled.
1033
1147
 
1034
1148
  Args:
1035
1149
  session (ClientSession): The disconnecting session.
@@ -1039,8 +1153,9 @@ class GameServer:
1039
1153
  if game is None:
1040
1154
  return
1041
1155
  roles = self._game_roles.get(game_id, {})
1156
+ persistent_ids = self._persistent_player_ids()
1042
1157
  for player_id in list(session.players):
1043
- if player_id not in roles:
1158
+ if player_id not in roles or player_id in persistent_ids:
1044
1159
  continue
1045
1160
  try:
1046
1161
  if roles[player_id] == "OBSERVER":
@@ -1052,6 +1167,33 @@ class GameServer:
1052
1167
  roles.pop(player_id, None)
1053
1168
  session.joined_games.discard(game_id)
1054
1169
 
1170
+ def _persistent_player_ids(self) -> Set[str]:
1171
+ """Returns the IDs of the players linked to a user account.
1172
+
1173
+ Returns:
1174
+ Set[str]: The IDs of the persistent players.
1175
+ """
1176
+ return {user.player.ID for user in self._users.values()}
1177
+
1178
+ def _remove_player_from_games(self, player_id: str) -> None:
1179
+ """Removes a player from every game it takes part in.
1180
+
1181
+ Args:
1182
+ player_id (str): The ID of the player to remove.
1183
+ """
1184
+ for game_id, roles in self._game_roles.items():
1185
+ role = roles.pop(player_id, None)
1186
+ game = self._games.get(game_id)
1187
+ if role is None or game is None:
1188
+ continue
1189
+ try:
1190
+ if role == "OBSERVER":
1191
+ game.remove_observer(player_id)
1192
+ else:
1193
+ game.remove_player(player_id)
1194
+ except PlayerNotFoundInGameError:
1195
+ pass
1196
+
1055
1197
  # ------------------------------------------------------------------ #
1056
1198
  # Broadcasting and notifications
1057
1199
  # ------------------------------------------------------------------ #
@@ -1116,6 +1258,16 @@ class GameServer:
1116
1258
  break
1117
1259
  self._collect_orphan_players()
1118
1260
 
1261
+ async def _persistence_loop(self) -> None:
1262
+ """Periodically saves server data when persistence is enabled."""
1263
+ while self._running:
1264
+ try:
1265
+ await asyncio.sleep(self.persistence_periodicity)
1266
+ except asyncio.CancelledError:
1267
+ break
1268
+ if self._running and self.persistence_mode is not None:
1269
+ self._save_persistence()
1270
+
1119
1271
  def _collect_orphan_players(self) -> None:
1120
1272
  """Removes players that are neither linked to a user nor to a session."""
1121
1273
  linked_to_user = {user.player.ID for user in self._users.values()}
@@ -1190,6 +1342,13 @@ class GameServer:
1190
1342
  session.access_level = _ROLE_TO_ACCESS.get(user.role, AccessLevel.PLAYER)
1191
1343
  session.players[user.player.ID] = user.player
1192
1344
  self._players[user.player.ID] = user.player
1345
+ # The player of the account stays in its games between connections:
1346
+ # the session takes them back, to be notified of their updates.
1347
+ session.joined_games.update(
1348
+ game_id
1349
+ for game_id, roles in self._game_roles.items()
1350
+ if user.player.ID in roles
1351
+ )
1193
1352
  return "AUTH_RESPONSE", {
1194
1353
  "success": True,
1195
1354
  "access_level": session.access_level.name,
@@ -1521,6 +1680,12 @@ class GameServer:
1521
1680
  }
1522
1681
  self._users.pop(username, None)
1523
1682
  self._players.pop(user.player.ID, None)
1683
+ # The player of an account outlives its connections in its games, so
1684
+ # it must leave them with the account.
1685
+ self._remove_player_from_games(user.player.ID)
1686
+ for game_id, creator in list(self._game_creator_user.items()):
1687
+ if creator == username:
1688
+ self._game_creator_user.pop(game_id, None)
1524
1689
  User._existing_usernames.discard(username)
1525
1690
  self._audit("USER_DELETE", session, username)
1526
1691
  return "USER_DELETE_RESPONSE", {
@@ -1712,6 +1877,8 @@ class GameServer:
1712
1877
  self._game_roles[game.ID] = {}
1713
1878
  self._game_custom_state[game.ID] = {}
1714
1879
  self._game_creator_session[game.ID] = session.session_id
1880
+ if session.user is not None:
1881
+ self._game_creator_user[game.ID] = session.user.username
1715
1882
  if group is not None:
1716
1883
  group.add_game(game)
1717
1884
  return "GAME_CREATE_RESPONSE", {
@@ -1754,6 +1921,71 @@ class GameServer:
1754
1921
  games = [self._game_summary(game) for game in self._games.values()]
1755
1922
  return "GAME_LIST_RESPONSE", {"success": True, "games": games}
1756
1923
 
1924
+ def _handle_game_participants_list(
1925
+ self, session: ClientSession, payload: Dict[str, Any]
1926
+ ) -> Tuple[str, Dict[str, Any]]:
1927
+ """Handles a ``GAME_PARTICIPANTS_LIST`` request.
1928
+
1929
+ The participants of a game are visible to every client when the
1930
+ ``participants_visible_to_all`` setting is enabled. Otherwise, only a
1931
+ server administrator, an administrator of a group holding the game,
1932
+ and the creator of the game may read them.
1933
+
1934
+ Args:
1935
+ session (ClientSession): The originating session.
1936
+ payload (Dict[str, Any]): The request payload.
1937
+
1938
+ Returns:
1939
+ Tuple[str, Dict[str, Any]]: The response type and payload.
1940
+ """
1941
+ game = self._games.get(payload.get("game_id"))
1942
+ if game is None:
1943
+ return "GAME_PARTICIPANTS_LIST_RESPONSE", {
1944
+ "success": False,
1945
+ "error_code": "GAME_NOT_FOUND",
1946
+ "message": "Game not found.",
1947
+ }
1948
+ if not (
1949
+ self.participants_visible_to_all
1950
+ or self._can_control_game(session, game.ID)
1951
+ or self._is_game_creator(session, game.ID)
1952
+ ):
1953
+ return "GAME_PARTICIPANTS_LIST_RESPONSE", {
1954
+ "success": False,
1955
+ "error_code": "INSUFFICIENT_PERMISSIONS",
1956
+ "message": "The participants of this game are not visible.",
1957
+ }
1958
+ participants = []
1959
+ for player_id, role in self._game_roles.get(game.ID, {}).items():
1960
+ player = self._players.get(player_id)
1961
+ if player is None:
1962
+ continue
1963
+ participants.append({"player_id": player.ID, "name": player.name, "role": role})
1964
+ return "GAME_PARTICIPANTS_LIST_RESPONSE", {
1965
+ "success": True,
1966
+ "game_id": game.ID,
1967
+ "participants": participants,
1968
+ }
1969
+
1970
+ def _is_game_creator(self, session: ClientSession, game_id: str) -> bool:
1971
+ """Checks whether a session created a given game.
1972
+
1973
+ A game is attributed to the session which created it and, when that
1974
+ session was authenticated, to its user, so that the user is still
1975
+ recognized as the creator from another session.
1976
+
1977
+ Args:
1978
+ session (ClientSession): The originating session.
1979
+ game_id (str): The game ID concerned.
1980
+
1981
+ Returns:
1982
+ bool: ``True`` if the session or its user created the game.
1983
+ """
1984
+ if self._game_creator_session.get(game_id) == session.session_id:
1985
+ return True
1986
+ creator = self._game_creator_user.get(game_id)
1987
+ return creator is not None and session.user is not None and session.user.username == creator
1988
+
1757
1989
  async def _handle_game_join(
1758
1990
  self, session: ClientSession, payload: Dict[str, Any]
1759
1991
  ) -> Tuple[str, Dict[str, Any]]:
@@ -1965,10 +2197,10 @@ class GameServer:
1965
2197
  game_id (str): The game ID concerned.
1966
2198
 
1967
2199
  Returns:
1968
- bool: ``True`` if the session created the game or has sufficient
1969
- administrative rights.
2200
+ bool: ``True`` if the session or its user created the game, or if
2201
+ the session has sufficient administrative rights.
1970
2202
  """
1971
- if self._game_creator_session.get(game_id) == session.session_id:
2203
+ if self._is_game_creator(session, game_id):
1972
2204
  return True
1973
2205
  if session.access_level >= AccessLevel.ADMIN:
1974
2206
  return True
@@ -2719,7 +2951,9 @@ class GameServer:
2719
2951
  "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
2720
2952
  "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
2721
2953
  "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
2954
+ "participants_visible_to_all": self.participants_visible_to_all,
2722
2955
  "hidden": self.hidden,
2956
+ "persistence_periodicity": self.persistence_periodicity,
2723
2957
  "server_password_set": self._server_hash is not None,
2724
2958
  },
2725
2959
  }
@@ -2800,6 +3034,16 @@ class GameServer:
2800
3034
  }
2801
3035
  self.unauthenticated_observer_join_allowed = value
2802
3036
  updated.append("unauthenticated_observer_join_allowed")
3037
+ if "participants_visible_to_all" in payload:
3038
+ value = payload["participants_visible_to_all"]
3039
+ if not isinstance(value, bool):
3040
+ return "SERVER_CONFIG_SET_RESPONSE", {
3041
+ "success": False,
3042
+ "error_code": "INVALID_DATA",
3043
+ "message": "participants_visible_to_all must be a boolean.",
3044
+ }
3045
+ self.participants_visible_to_all = value
3046
+ updated.append("participants_visible_to_all")
2803
3047
  if "hidden" in payload:
2804
3048
  value = payload["hidden"]
2805
3049
  if not isinstance(value, bool):
@@ -2810,6 +3054,21 @@ class GameServer:
2810
3054
  }
2811
3055
  self.hidden = value
2812
3056
  updated.append("hidden")
3057
+ if "persistence_periodicity" in payload:
3058
+ value = payload["persistence_periodicity"]
3059
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
3060
+ return "SERVER_CONFIG_SET_RESPONSE", {
3061
+ "success": False,
3062
+ "error_code": "INVALID_DATA",
3063
+ "message": "persistence_periodicity must be a non-negative integer.",
3064
+ }
3065
+ self.persistence_periodicity = value
3066
+ updated.append("persistence_periodicity")
3067
+ if self._persistence_task is not None:
3068
+ self._persistence_task.cancel()
3069
+ self._persistence_task = None
3070
+ if self._running and self.persistence_periodicity > 0:
3071
+ self._persistence_task = asyncio.ensure_future(self._persistence_loop())
2813
3072
  if isinstance(payload.get("server_password"), str):
2814
3073
  self._server_hash = bcrypt.hashpw(
2815
3074
  payload["server_password"].encode(), bcrypt.gensalt()
@@ -2865,7 +3124,7 @@ class GameServer:
2865
3124
  "error_code": "PERSISTENCE_ERROR",
2866
3125
  "message": "Persistence is disabled.",
2867
3126
  }
2868
- self._save_persistence()
3127
+ self.save_persistence()
2869
3128
  self._audit("SERVER_PERSISTENCE_SAVE", session, "server")
2870
3129
  return "SERVER_PERSISTENCE_SAVE_RESPONSE", {
2871
3130
  "success": True,
File without changes