multiplayer 2.2.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.2.0 → multiplayer-2.4.0}/PKG-INFO +1 -1
  2. {multiplayer-2.2.0 → multiplayer-2.4.0}/pyproject.toml +1 -1
  3. {multiplayer-2.2.0 → multiplayer-2.4.0}/pyproject.toml.orig +1 -1
  4. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/client.py +15 -0
  5. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/save.py +39 -5
  6. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/server.py +383 -15
  7. {multiplayer-2.2.0 → multiplayer-2.4.0}/README.md +0 -0
  8. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/__init__.py +0 -0
  9. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/cities.csv +0 -0
  10. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/countries.csv +0 -0
  11. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/egyptian_gods.csv +0 -0
  12. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/european_kings.csv +0 -0
  13. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/european_queens.csv +0 -0
  14. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/greek_gods.csv +0 -0
  15. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/planets_moons.csv +0 -0
  16. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/rivers.csv +0 -0
  17. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/roman_gods.csv +0 -0
  18. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/data/seas_oceans.csv +0 -0
  19. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/exceptions.py +0 -0
  20. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/game.py +0 -0
  21. {multiplayer-2.2.0 → multiplayer-2.4.0}/src/multiplayer/py.typed +0 -0
  22. {multiplayer-2.2.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.2.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.2.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.2.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
 
@@ -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
@@ -367,14 +380,30 @@ class Save:
367
380
  deserializer = _SERIALIZERS[name][1]
368
381
  return [deserializer(data) for data in self._data[name].values()]
369
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
+
370
391
  def reset(self) -> None:
371
392
  """Clears the in-memory buffer and the underlying save file.
372
393
 
373
394
  The save file is rewritten with an empty but valid structure.
374
395
  """
375
- self._data = {name: {} for name in _SUPPORTED_CLASSES}
396
+ self.clear()
376
397
  self.flush()
377
398
 
399
+ def save_server_config(self, config: Dict[str, Any]) -> None:
400
+ """Stores the serializable server configuration in the save buffer."""
401
+ self._server_config = dict(config)
402
+
403
+ def load_server_config(self) -> Dict[str, Any]:
404
+ """Returns the stored server configuration, or an empty mapping."""
405
+ return dict(self._server_config)
406
+
378
407
  def flush(self) -> None:
379
408
  """Persists the in-memory buffer to the underlying save file.
380
409
 
@@ -393,8 +422,11 @@ class Save:
393
422
  SaveError: If the data cannot be written.
394
423
  """
395
424
  try:
425
+ content = dict(self._data)
426
+ if self._server_config:
427
+ content[_SERVER_CONFIG_CLASS] = self._server_config
396
428
  with self.file_path.open("w", encoding="utf-8") as handle:
397
- json.dump(self._data, handle, indent=2)
429
+ json.dump(content, handle, indent=2)
398
430
  except OSError as exc:
399
431
  logger.exception("Failed to write JSON save file.")
400
432
  raise SaveError(f"Cannot write save file: {self.file_path}") from exc
@@ -420,6 +452,8 @@ class Save:
420
452
  for name, section in self._data.items()
421
453
  for obj_id, data in section.items()
422
454
  ]
455
+ if self._server_config:
456
+ rows.append((_SERVER_CONFIG_CLASS, "server", json.dumps(self._server_config)))
423
457
  cursor.executemany(
424
458
  f"INSERT INTO {_SQLITE_TABLE} (class, id, data) VALUES (?, ?, ?)",
425
459
  rows,
@@ -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,12 +421,17 @@ 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
415
428
  )
416
- self._admin_hash: Optional[str] = None
417
429
  self.user_registration_enabled: bool = True
430
+ self.orphan_games_allowed: bool = True
431
+ self.unauthenticated_game_creation_allowed: bool = True
432
+ self.unauthenticated_player_join_allowed: bool = True
433
+ self.unauthenticated_observer_join_allowed: bool = True
434
+ self.participants_visible_to_all: bool = False
418
435
  self.hidden: bool = False
419
436
 
420
437
  # Persistence configuration.
@@ -439,6 +456,7 @@ class GameServer:
439
456
  self._game_custom_state: Dict[str, Dict[str, Any]] = {}
440
457
  self._game_roles: Dict[str, Dict[str, str]] = {}
441
458
  self._game_creator_session: Dict[str, str] = {}
459
+ self._game_creator_user: Dict[str, str] = {}
442
460
  self._audit_log: List[Dict[str, Any]] = []
443
461
 
444
462
  # Runtime state.
@@ -447,6 +465,7 @@ class GameServer:
447
465
  self._unencrypted_server: Optional[asyncio.AbstractServer] = None
448
466
  self._discovery_transport: Optional[asyncio.DatagramTransport] = None
449
467
  self._gc_task: Optional[asyncio.Task] = None
468
+ self._persistence_task: Optional[asyncio.Task] = None
450
469
  self._running: bool = False
451
470
  self._start_time: float = 0.0
452
471
  self._actual_port: int = port
@@ -517,6 +536,8 @@ class GameServer:
517
536
  self._running = True
518
537
  self._start_time = time.monotonic()
519
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())
520
541
  logger.info("Server '%s' started on %s:%s", self.name, self.host, self._actual_port)
521
542
 
522
543
  async def stop(self) -> None:
@@ -537,6 +558,14 @@ class GameServer:
537
558
  pass
538
559
  self._gc_task = None
539
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
+
540
569
  await self._broadcast_shutdown()
541
570
 
542
571
  for session in list(self._sessions.values()):
@@ -566,6 +595,13 @@ class GameServer:
566
595
  await self.stop()
567
596
  await self.start()
568
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
+
569
605
  def _build_tls_context(self) -> ssl.SSLContext:
570
606
  """Builds the TLS 1.3 context used to secure the main TCP port.
571
607
 
@@ -697,25 +733,109 @@ class GameServer:
697
733
  self.persistence_path.parent.mkdir(parents=True, exist_ok=True)
698
734
  try:
699
735
  self._save = Save(self.persistence_path, self.persistence_mode)
736
+ config = self._save.load_server_config()
737
+ if isinstance(config.get("name"), str):
738
+ self.name = config["name"]
739
+ for field in (
740
+ "user_registration_enabled",
741
+ "orphan_games_allowed",
742
+ "unauthenticated_game_creation_allowed",
743
+ "unauthenticated_player_join_allowed",
744
+ "unauthenticated_observer_join_allowed",
745
+ "participants_visible_to_all",
746
+ "hidden",
747
+ ):
748
+ if isinstance(config.get(field), bool):
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"]
756
+ if isinstance(config.get("server_hash"), str) or config.get("server_hash") is None:
757
+ self._server_hash = config.get("server_hash")
700
758
  for game in self._save.load(Game):
701
759
  self._games[game.ID] = game
702
760
  for group in self._save.load(GameGroup):
761
+ self._share_group_games(group)
703
762
  self._groups[group.ID] = group
704
763
  for player in self._save.load(Player):
705
764
  self._players[player.ID] = player
706
765
  for user in self._save.load(User):
707
766
  self._users[user.username] = user
708
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
+ }
709
776
  except MultiplayerError:
710
777
  logger.exception("Failed to load persistent data.")
711
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
+
712
827
  def _save_persistence(self) -> None:
713
- """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
+ """
714
833
  if self.persistence_mode is None or self.persistence_path is None:
715
834
  return
716
835
  try:
717
836
  if self._save is None:
718
837
  self._save = Save(self.persistence_path, self.persistence_mode)
838
+ self._save.clear()
719
839
  for game in self._games.values():
720
840
  self._save.save(game)
721
841
  for group in self._groups.values():
@@ -724,6 +844,23 @@ class GameServer:
724
844
  self._save.save(player)
725
845
  for user in self._users.values():
726
846
  self._save.save(user)
847
+ self._save.save_server_config({
848
+ "name": self.name,
849
+ "user_registration_enabled": self.user_registration_enabled,
850
+ "orphan_games_allowed": self.orphan_games_allowed,
851
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
852
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
853
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
854
+ "participants_visible_to_all": self.participants_visible_to_all,
855
+ "hidden": self.hidden,
856
+ "persistence_periodicity": self.persistence_periodicity,
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
+ },
863
+ })
727
864
  self._save.flush()
728
865
  except MultiplayerError:
729
866
  logger.exception("Failed to persist data.")
@@ -1001,7 +1138,12 @@ class GameServer:
1001
1138
  pass
1002
1139
 
1003
1140
  def _remove_session_players_from_game(self, session: ClientSession, game_id: str) -> None:
1004
- """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.
1005
1147
 
1006
1148
  Args:
1007
1149
  session (ClientSession): The disconnecting session.
@@ -1011,8 +1153,9 @@ class GameServer:
1011
1153
  if game is None:
1012
1154
  return
1013
1155
  roles = self._game_roles.get(game_id, {})
1156
+ persistent_ids = self._persistent_player_ids()
1014
1157
  for player_id in list(session.players):
1015
- if player_id not in roles:
1158
+ if player_id not in roles or player_id in persistent_ids:
1016
1159
  continue
1017
1160
  try:
1018
1161
  if roles[player_id] == "OBSERVER":
@@ -1024,6 +1167,33 @@ class GameServer:
1024
1167
  roles.pop(player_id, None)
1025
1168
  session.joined_games.discard(game_id)
1026
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
+
1027
1197
  # ------------------------------------------------------------------ #
1028
1198
  # Broadcasting and notifications
1029
1199
  # ------------------------------------------------------------------ #
@@ -1088,6 +1258,16 @@ class GameServer:
1088
1258
  break
1089
1259
  self._collect_orphan_players()
1090
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
+
1091
1271
  def _collect_orphan_players(self) -> None:
1092
1272
  """Removes players that are neither linked to a user nor to a session."""
1093
1273
  linked_to_user = {user.player.ID for user in self._users.values()}
@@ -1162,6 +1342,13 @@ class GameServer:
1162
1342
  session.access_level = _ROLE_TO_ACCESS.get(user.role, AccessLevel.PLAYER)
1163
1343
  session.players[user.player.ID] = user.player
1164
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
+ )
1165
1352
  return "AUTH_RESPONSE", {
1166
1353
  "success": True,
1167
1354
  "access_level": session.access_level.name,
@@ -1493,6 +1680,12 @@ class GameServer:
1493
1680
  }
1494
1681
  self._users.pop(username, None)
1495
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)
1496
1689
  User._existing_usernames.discard(username)
1497
1690
  self._audit("USER_DELETE", session, username)
1498
1691
  return "USER_DELETE_RESPONSE", {
@@ -1644,8 +1837,20 @@ class GameServer:
1644
1837
  "error_code": "INVALID_DATA",
1645
1838
  "message": "A game name is required.",
1646
1839
  }
1840
+ if session.user is None and not self.unauthenticated_game_creation_allowed:
1841
+ return "GAME_CREATE_RESPONSE", {
1842
+ "success": False,
1843
+ "error_code": "AUTHENTICATION_REQUIRED",
1844
+ "message": "An authenticated user is required to create a game.",
1845
+ }
1647
1846
  group_id = payload.get("group_id")
1648
1847
  group = None
1848
+ if group_id is None and not self.orphan_games_allowed:
1849
+ return "GAME_CREATE_RESPONSE", {
1850
+ "success": False,
1851
+ "error_code": "ORPHAN_GAMES_DISABLED",
1852
+ "message": "Creating a game without a group is disabled.",
1853
+ }
1649
1854
  if group_id is not None:
1650
1855
  group = self._groups.get(group_id)
1651
1856
  if group is None:
@@ -1672,6 +1877,8 @@ class GameServer:
1672
1877
  self._game_roles[game.ID] = {}
1673
1878
  self._game_custom_state[game.ID] = {}
1674
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
1675
1882
  if group is not None:
1676
1883
  group.add_game(game)
1677
1884
  return "GAME_CREATE_RESPONSE", {
@@ -1701,7 +1908,10 @@ class GameServer:
1701
1908
  "error_code": "GROUP_NOT_FOUND",
1702
1909
  "message": "Group not found.",
1703
1910
  }
1704
- if not self._authorize_group(session, group, payload.get("group_password")):
1911
+ if (
1912
+ not self._can_admin_group(session, group.ID)
1913
+ and not self._authorize_group(session, group, payload.get("group_password"))
1914
+ ):
1705
1915
  return "GAME_LIST_RESPONSE", {
1706
1916
  "success": False, "error_code": "INVALID_GROUP_PASSWORD",
1707
1917
  "message": "Invalid group password.",
@@ -1711,6 +1921,71 @@ class GameServer:
1711
1921
  games = [self._game_summary(game) for game in self._games.values()]
1712
1922
  return "GAME_LIST_RESPONSE", {"success": True, "games": games}
1713
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
+
1714
1989
  async def _handle_game_join(
1715
1990
  self, session: ClientSession, payload: Dict[str, Any]
1716
1991
  ) -> Tuple[str, Dict[str, Any]]:
@@ -1746,6 +2021,18 @@ class GameServer:
1746
2021
  "error_code": "INVALID_ACTION",
1747
2022
  "message": "Invalid role.",
1748
2023
  }
2024
+ if role == "PLAYER" and session.user is None and not self.unauthenticated_player_join_allowed:
2025
+ return "GAME_JOIN_RESPONSE", {
2026
+ "success": False,
2027
+ "error_code": "AUTHENTICATION_REQUIRED",
2028
+ "message": "An authenticated user is required to join as a player.",
2029
+ }
2030
+ if role == "OBSERVER" and session.user is None and not self.unauthenticated_observer_join_allowed:
2031
+ return "GAME_JOIN_RESPONSE", {
2032
+ "success": False,
2033
+ "error_code": "AUTHENTICATION_REQUIRED",
2034
+ "message": "An authenticated user is required to join as an observer.",
2035
+ }
1749
2036
  player = self._resolve_player(session, payload.get("player_id"))
1750
2037
  if player is None:
1751
2038
  return "GAME_JOIN_RESPONSE", {
@@ -1910,10 +2197,10 @@ class GameServer:
1910
2197
  game_id (str): The game ID concerned.
1911
2198
 
1912
2199
  Returns:
1913
- bool: ``True`` if the session created the game or has sufficient
1914
- administrative rights.
2200
+ bool: ``True`` if the session or its user created the game, or if
2201
+ the session has sufficient administrative rights.
1915
2202
  """
1916
- if self._game_creator_session.get(game_id) == session.session_id:
2203
+ if self._is_game_creator(session, game_id):
1917
2204
  return True
1918
2205
  if session.access_level >= AccessLevel.ADMIN:
1919
2206
  return True
@@ -2660,9 +2947,14 @@ class GameServer:
2660
2947
  "success": True,
2661
2948
  "config": {
2662
2949
  "user_registration_enabled": self.user_registration_enabled,
2950
+ "orphan_games_allowed": self.orphan_games_allowed,
2951
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
2952
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
2953
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
2954
+ "participants_visible_to_all": self.participants_visible_to_all,
2663
2955
  "hidden": self.hidden,
2956
+ "persistence_periodicity": self.persistence_periodicity,
2664
2957
  "server_password_set": self._server_hash is not None,
2665
- "admin_password_set": self._admin_hash is not None,
2666
2958
  },
2667
2959
  }
2668
2960
 
@@ -2679,6 +2971,19 @@ class GameServer:
2679
2971
  Tuple[str, Dict[str, Any]]: The response type and payload.
2680
2972
  """
2681
2973
  updated: List[str] = []
2974
+ if "name" in payload:
2975
+ value = payload["name"]
2976
+ if not isinstance(value, str):
2977
+ return "SERVER_CONFIG_SET_RESPONSE", {
2978
+ "success": False,
2979
+ "error_code": "INVALID_DATA",
2980
+ "message": "name must be a string.",
2981
+ }
2982
+ if value != self.name:
2983
+ self.name = value
2984
+ updated.append("name")
2985
+ for client in list(self._sessions.values()):
2986
+ self._close_session(client)
2682
2987
  if "user_registration_enabled" in payload:
2683
2988
  value = payload["user_registration_enabled"]
2684
2989
  if not isinstance(value, bool):
@@ -2689,6 +2994,56 @@ class GameServer:
2689
2994
  }
2690
2995
  self.user_registration_enabled = value
2691
2996
  updated.append("user_registration_enabled")
2997
+ if "orphan_games_allowed" in payload:
2998
+ value = payload["orphan_games_allowed"]
2999
+ if not isinstance(value, bool):
3000
+ return "SERVER_CONFIG_SET_RESPONSE", {
3001
+ "success": False,
3002
+ "error_code": "INVALID_DATA",
3003
+ "message": "orphan_games_allowed must be a boolean.",
3004
+ }
3005
+ self.orphan_games_allowed = value
3006
+ updated.append("orphan_games_allowed")
3007
+ if "unauthenticated_game_creation_allowed" in payload:
3008
+ value = payload["unauthenticated_game_creation_allowed"]
3009
+ if not isinstance(value, bool):
3010
+ return "SERVER_CONFIG_SET_RESPONSE", {
3011
+ "success": False,
3012
+ "error_code": "INVALID_DATA",
3013
+ "message": "unauthenticated_game_creation_allowed must be a boolean.",
3014
+ }
3015
+ self.unauthenticated_game_creation_allowed = value
3016
+ updated.append("unauthenticated_game_creation_allowed")
3017
+ if "unauthenticated_player_join_allowed" in payload:
3018
+ value = payload["unauthenticated_player_join_allowed"]
3019
+ if not isinstance(value, bool):
3020
+ return "SERVER_CONFIG_SET_RESPONSE", {
3021
+ "success": False,
3022
+ "error_code": "INVALID_DATA",
3023
+ "message": "unauthenticated_player_join_allowed must be a boolean.",
3024
+ }
3025
+ self.unauthenticated_player_join_allowed = value
3026
+ updated.append("unauthenticated_player_join_allowed")
3027
+ if "unauthenticated_observer_join_allowed" in payload:
3028
+ value = payload["unauthenticated_observer_join_allowed"]
3029
+ if not isinstance(value, bool):
3030
+ return "SERVER_CONFIG_SET_RESPONSE", {
3031
+ "success": False,
3032
+ "error_code": "INVALID_DATA",
3033
+ "message": "unauthenticated_observer_join_allowed must be a boolean.",
3034
+ }
3035
+ self.unauthenticated_observer_join_allowed = value
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")
2692
3047
  if "hidden" in payload:
2693
3048
  value = payload["hidden"]
2694
3049
  if not isinstance(value, bool):
@@ -2699,16 +3054,29 @@ class GameServer:
2699
3054
  }
2700
3055
  self.hidden = value
2701
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())
2702
3072
  if isinstance(payload.get("server_password"), str):
2703
3073
  self._server_hash = bcrypt.hashpw(
2704
3074
  payload["server_password"].encode(), bcrypt.gensalt()
2705
3075
  ).decode()
2706
3076
  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")
3077
+ for client in list(self._sessions.values()):
3078
+ self._close_session(client)
3079
+ self._save_persistence()
2712
3080
  self._audit("SERVER_CONFIG_SET", session, "server")
2713
3081
  return "SERVER_CONFIG_SET_RESPONSE", {
2714
3082
  "success": True,
@@ -2756,7 +3124,7 @@ class GameServer:
2756
3124
  "error_code": "PERSISTENCE_ERROR",
2757
3125
  "message": "Persistence is disabled.",
2758
3126
  }
2759
- self._save_persistence()
3127
+ self.save_persistence()
2760
3128
  self._audit("SERVER_PERSISTENCE_SAVE", session, "server")
2761
3129
  return "SERVER_PERSISTENCE_SAVE_RESPONSE", {
2762
3130
  "success": True,
File without changes