1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
|
/// The server-side game: connections, sessions, secrets and the command
/// execution path (PLAN.md sections 3.3–3.6).
///
/// One [GameServer] serves one game (the reference app's deployment model).
/// It is the conceptual successor of the reference app's `Server extends
/// GameServer`: same concepts — monotonic command index, full-state push on
/// every action, full resync on reconnect, ping — native to WebSocket, and
/// with the server as the only executor (clients send input only).
library;
import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:logging/logging.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:x_haven_server/core/commands/add_character_command.dart';
import 'package:x_haven_server/core/commands/command_registry.dart';
import 'package:x_haven_server/core/commands/track_standees_command.dart';
import 'package:x_haven_server/core/enums.dart';
import 'package:x_haven_server/core/game_methods.dart';
import 'package:x_haven_server/core/service_locator.dart';
import 'package:x_haven_server/core/settings.dart';
import 'package:x_haven_server/core/state/game_state.dart';
import 'protocol.dart';
import 'seat_store.dart';
import 'sessions.dart';
import 'visibility.dart';
final _log = Logger('GameServer');
/// One live connection: the channel, its session, and activity tracking.
class _Connection {
_Connection(this.channel, this.session) : lastActivityAt = DateTime.now();
final WebSocketChannel channel;
final SessionRecord session;
/// Last time anything was received on this connection (connect time
/// initially). The heartbeat sweep closes connections quiet longer than
/// the server's dead timeout.
DateTime lastActivityAt;
/// Whether the `hello` handshake completed.
bool handshaken = false;
/// Whether this connection has been detached (idempotent-cleanup guard).
bool closed = false;
void send(Map<String, dynamic> message) =>
channel.sink.add(jsonEncode(message));
}
/// The game server bound to one [GameState].
class GameServer {
GameServer({
required GameState gameState,
required SessionManager sessions,
required SeatStore seatStore,
Duration heartbeatInterval = const Duration(seconds: 20),
Duration deadTimeout = const Duration(seconds: 90),
}) : _gameState = gameState,
_sessions = sessions,
_seatStore = seatStore,
_deadTimeout = deadTimeout {
// The action handler's broadcast hook: after every action/undo/redo the
// index, description and event arrive here; the per-connection state
// push happens in [_onAction].
gameState.onAction = _onAction;
_restoreSeats();
_heartbeat = Timer.periodic(heartbeatInterval, (_) => _sweepDeadConnections());
}
final GameState _gameState;
final SessionManager _sessions;
final SeatStore _seatStore;
final Duration _deadTimeout;
final Map<String, List<_Connection>> _connections = {};
late final Timer _heartbeat;
SessionManager get sessions => _sessions;
GameState get gameState => _gameState;
/// Number of live connections (diagnostics/tests).
int get connectionCount =>
_connections.values.fold<int>(0, (sum, list) => sum + list.length);
/// Attaches a live WebSocket channel.
///
/// [cookieSessionId] comes from the `x-haven-session` cookie (or the
/// `?session=` query parameter) of the upgrade request; null (or unknown)
/// mints a new session.
void attach(WebSocketChannel channel, {String? cookieSessionId}) {
final session = _sessions.resolve(cookieSessionId);
final connection = _Connection(channel, session);
_connections.putIfAbsent(session.id, () => []).add(connection);
_log.info(
'session ${session.id} connected '
'($connectionCount connection(s) live)',
);
channel.stream.listen(
(Object? raw) {
connection.lastActivityAt = DateTime.now();
_onMessage(connection, raw);
},
onDone: () => _detach(connection),
onError: (Object error) {
_log.warning('session ${session.id} connection error: $error');
_detach(connection);
},
);
}
/// Stops the heartbeat sweep. Does not close connections — the caller
/// closes them (e.g. when the HTTP server shuts down, or to simulate a
/// crash in tests).
void dispose() {
_heartbeat.cancel();
}
// --- connection lifecycle -------------------------------------------------
void _detach(_Connection connection) {
if (connection.closed) return;
connection.closed = true;
final list = _connections[connection.session.id];
list?.remove(connection);
if (list != null && list.isEmpty) {
_connections.remove(connection.session.id);
_onSessionDisconnected(connection.session);
}
}
/// The session's last connection is gone: its characters become unclaimed
/// (PLAN.md section 3.3), the seat table is persisted, and the `seats`
/// broadcast goes out so every screen can update its inputs.
void _onSessionDisconnected(SessionRecord session) {
_log.info('session ${session.id} left');
final released = _sessions.release(session.id);
if (released.isNotEmpty) {
_log.info('session ${session.id} released seats: $released');
_persistSeats();
}
_broadcastSeats();
}
/// Closes connections quiet longer than [_deadTimeout] (half-open
/// connections the OS never reported). The sweep is the safety net; normal
/// disconnects are handled by the socket's done/error events.
void _sweepDeadConnections() {
final now = DateTime.now();
for (final connection in _activeConnections().toList()) {
final quietFor = now.difference(connection.lastActivityAt);
if (quietFor > _deadTimeout) {
_log.info(
'closing dead connection for session ${connection.session.id} '
'(no activity for ${quietFor.inSeconds}s)',
);
unawaited(connection.channel.sink.close());
// onDone fires → _detach runs the seat release + broadcast.
}
}
}
List<_Connection> _activeConnections() {
final result = <_Connection>[];
for (final list in _connections.values) {
result.addAll(list);
}
return result;
}
// --- message dispatch -----------------------------------------------------
void _onMessage(_Connection connection, Object? raw) {
final String? text = _coerceText(raw);
if (text == null) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'expected a UTF-8 JSON message',
),
);
return;
}
final Map<String, dynamic>? message = _decodeMessage(text);
if (message == null) {
connection.send(
Protocol.errorMessage(Protocol.errBadRequest, 'malformed JSON'),
);
return;
}
final type = message['t'];
switch (type) {
case Protocol.hello:
_handleHello(connection, message);
case Protocol.ping:
// Allowed before the handshake — a keepalive is harmless.
connection.send(Protocol.pongMessage());
case Protocol.claim:
_handleClaim(connection, message);
case Protocol.cmd:
_handleCmd(connection, message);
case Protocol.undo:
_handleUndoRedo(connection, undo: true);
case Protocol.redo:
_handleUndoRedo(connection, undo: false);
case Protocol.setSetting:
_handleSetSetting(connection, message);
case Protocol.save:
_handleSave(connection, message);
case Protocol.loadSave:
_handleLoadSave(connection, message);
case Protocol.deleteSave:
_handleDeleteSave(connection, message);
case Protocol.saveCharacter:
_handleSaveCharacter(connection, message);
case Protocol.loadCharacterSave:
_handleLoadCharacterSave(connection, message);
case Protocol.deleteCharacterSave:
_handleDeleteCharacterSave(connection, message);
default:
connection.send(
Protocol.errorMessage(
Protocol.errUnknownMessage,
'unknown message type: $type',
),
);
}
}
String? _coerceText(Object? raw) {
if (raw is String) return raw;
if (raw is List<int>) return utf8.decode(raw, allowMalformed: true);
return null;
}
Map<String, dynamic>? _decodeMessage(String text) {
try {
final dynamic decoded = jsonDecode(text);
return decoded is Map<String, dynamic> ? decoded : null;
} catch (_) {
return null;
}
}
void _notHandshaken(_Connection connection) {
connection.send(
Protocol.errorMessage(Protocol.errBadRequest, 'send hello first'),
);
}
/// The handshake: checks the protocol version, then answers with a full
/// `welcome` (current state, role, seats). Re-sending `hello` re-answers
/// with a fresh `welcome` — the client's resync tool.
void _handleHello(_Connection connection, Map<String, dynamic> message) {
final version = message['v'];
if (version is! int || version != Protocol.version) {
connection.send(
Protocol.errorMessage(
Protocol.errProtocol,
'protocol version mismatch: client $version, '
'server ${Protocol.version}. Please update.',
),
);
unawaited(connection.channel.sink.close());
return;
}
connection.handshaken = true;
connection.send(_welcomeFor(connection));
}
Map<String, dynamic> _welcomeFor(_Connection connection) {
final session = connection.session;
return Protocol.welcomeMessage(
session: session.id,
role: session.role,
index: _gameState.commandIndex,
description: _currentDescription(),
event: null,
state: _serializeFor(connection),
seats: _sessions.seatsForState(_gameState),
settings: _settings().forClient(),
historyLength: _gameState.commandDescriptions.length,
redoDescription: _redoDescription(),
undoDescription: _undoDescription(),
);
}
/// The description of the action at the current index (null at the
/// baseline), for the client's undo label.
String? _currentDescription() {
final index = _gameState.commandIndex;
final descriptions = _gameState.commandDescriptions;
if (index < 0 || index >= descriptions.length) return null;
return descriptions[index];
}
/// The description of the next action (null when nothing can be redone),
/// for the client's `Redo: …` label.
String? _redoDescription() {
final index = _gameState.commandIndex + 1;
final descriptions = _gameState.commandDescriptions;
if (index < 0 || index >= descriptions.length) return null;
return descriptions[index];
}
/// The description of the action at the current index — what an undo would
/// undo (null at the baseline), for the client's `Undo: …` label. The
/// reference app's `MainMenuViewModel.undoDescription` getter, ported.
String? _undoDescription() => _currentDescription();
// --- claims ---------------------------------------------------------------
/// `{t: claim, characterId}` — any session may claim an unclaimed
/// character; that is also how a session becomes a player.
void _handleClaim(_Connection connection, Map<String, dynamic> message) {
if (!connection.handshaken) {
_notHandshaken(connection);
return;
}
final characterId = message['characterId'];
if (characterId is! String || characterId.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'claim requires a non-empty "characterId" string',
),
);
return;
}
final character = _gameState.currentList.firstWhereOrNull(
(item) => item is Character && item.id == characterId,
);
if (character == null) {
connection.send(
Protocol.errorMessage(
Protocol.errRejected,
'no character with id "$characterId" in the current list',
),
);
return;
}
final session = connection.session;
final owner = _sessions.ownerOf(characterId);
if (owner != null && owner.id != session.id) {
connection.send(
Protocol.errorMessage(
Protocol.errRejected,
'character "$characterId" is already claimed',
),
);
return;
}
if (owner == null) {
_sessions.assign(session, characterId);
_persistSeats();
}
_broadcastSeats();
}
// --- command execution path ------------------------------------------------
/// `{t: cmd, name, args}` — role check → game-rule guard → args
/// validation (registry) → execute → per-connection `update` broadcast
/// (via the action handler hook) → seat sync.
///
/// A rejected command answers the sender with an `error` only — no
/// broadcast, no index change.
void _handleCmd(_Connection connection, Map<String, dynamic> message) {
if (!connection.handshaken) {
_notHandshaken(connection);
return;
}
final name = message['name'];
if (name is! String || name.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'cmd requires a non-empty "name" string',
),
);
return;
}
final rawArgs = message['args'];
if (rawArgs != null && rawArgs is! Map) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'cmd "args" must be an object',
),
);
return;
}
final args =
rawArgs is Map<String, dynamic>
? rawArgs
: const <String, dynamic>{};
final session = connection.session;
// Role gate: spectators cannot run commands — except `addCharacter`,
// which is the way a session becomes a player (the session that adds a
// character owns it, PLAN.md section 3.3).
if (!session.isPlayer && name != 'addCharacter') {
connection.send(
Protocol.errorMessage(
Protocol.errForbidden,
'spectators cannot run commands — claim a character first',
),
);
return;
}
final String? guardMessage = _guard(name);
if (guardMessage != null) {
connection.send(Protocol.errorMessage(Protocol.errRejected, guardMessage));
return;
}
final Command command;
try {
command = buildCommand(name, args, _gameState);
} on CommandRegistryError catch (error) {
connection.send(Protocol.errorMessage(Protocol.errRejected, error.message));
return;
}
try {
_gameState.action(command);
} on Exception catch (error) {
_log.warning('command "$name" failed during execution: $error');
connection.send(
Protocol.errorMessage(Protocol.errRejected, 'command "$name" failed: $error'),
);
return;
}
// Seat bookkeeping: a newly added character belongs to the session that
// added it.
if (name == 'addCharacter') {
final character = (command as AddCharacterCommand).character;
if (character != null) {
_sessions.assign(session, character.id);
_persistSeats();
_broadcastSeats();
}
}
// Other actions may have removed characters (undo, removeCharacter,
// loadSave) — prune stale seats and broadcast if anything changed.
_syncSeats();
}
/// The preconditions the reference app enforced in its UI (the
/// `runDrawOrNextRoundAction` gate): commands whose `execute()` would run
/// outside their round phase are rejected here. This is the server-side
/// replacement for the reference app's 300 ms draw-button lockout —
/// sequential server execution makes a second draw deterministically
/// lose, and the loser gets a clear `error`.
String? _guard(String name) {
if (name == 'draw') {
if (_gameState.roundState != RoundState.chooseInitiative) {
return 'the round has already been drawn';
}
if (_gameState.currentList.isEmpty) {
return 'add characters before drawing';
}
if (!GameMethods.canDraw()) {
return 'player initiative values must be set before drawing';
}
}
if (name == 'nextRound') {
if (_gameState.roundState != RoundState.playTurns) {
return 'the round has not started yet';
}
}
return null;
}
void _handleUndoRedo(_Connection connection, {required bool undo}) {
if (!_requirePlayer(connection, 'undo or redo')) return;
if (undo) {
_gameState.undo();
} else {
_gameState.redo();
}
}
// --- Phase 6: settings and multi-save --------------------------------------
/// The server-side settings (the game-relevant half of the reference
/// app's `Settings`; Phase 6 split, PLAN.md section 4).
Settings _settings() => getIt<Settings>();
/// The locales the client may select (the reference app's `supportedLocales`
/// plus `zh_Hant`, which the gen-l10n arb set covers).
static const List<String> _kSettableLocales = [
'en', 'de', 'es', 'fr', 'ko', 'pl', 'ru', 'th', 'zh', 'zh_Hant',
];
/// Gate for player-only messages (undo/redo, settings, saves): answers the
/// sender with a clear `error` when the session has no seat.
bool _requirePlayer(_Connection connection, String what) {
if (!connection.handshaken) {
_notHandshaken(connection);
return false;
}
if (!connection.session.isPlayer) {
connection.send(
Protocol.errorMessage(
Protocol.errForbidden,
'spectators cannot $what — claim a character first',
),
);
return false;
}
return true;
}
/// `{t: setSetting, name, value}` — one server-side (game-relevant) setting
/// (Phase 6). Persisted immediately and broadcast to every screen, since
/// the setting changes game behaviour for everyone (e.g. standee tracking,
/// the loot deck, reminders).
///
/// `noStandees` additionally runs `TrackStandeesCommand` (the reference
/// app's settings menu does the same — the command itself writes the
/// setting and adjusts the already-added monsters' standees).
void _handleSetSetting(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'change settings')) return;
final name = message['name'];
final value = message['value'];
if (name is! String || name.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'setSetting requires a non-empty "name" string',
),
);
return;
}
final s = _settings();
var ok = true;
switch (name) {
case 'noInit':
ok = value is bool && (s.noInit = value);
case 'noStandees':
ok = value is bool && (s.noStandees = value);
case 'randomStandees':
ok = value is bool && (s.randomStandees = value);
case 'expireConditions':
ok = value is bool && (s.expireConditions = value);
case 'autoAddStandees':
ok = value is bool && (s.autoAddStandees = value);
case 'autoAddSpawns':
ok = value is bool && (s.autoAddSpawns = value);
case 'hideLootDeck':
ok = value is bool && (s.hideLootDeck = value);
case 'showBattleGoalReminder':
ok = value is bool && (s.showBattleGoalReminder = value);
case 'showReminders':
ok = value is bool && (s.showReminders = value);
case 'showAmdDeck':
ok = value is bool && (s.showAmdDeck = value);
case 'fhHazTerrainCalcInOGGloom':
ok = value is bool && (s.fhHazTerrainCalcInOGGloom = value);
case 'style':
ok = value is int && value >= 0 && value < Style.values.length;
if (ok) s.style = Style.values[value];
case 'locale':
ok = value is String && _kSettableLocales.contains(value);
if (ok) s.locale = value;
default:
ok = false;
}
if (!ok) {
connection.send(
Protocol.errorMessage(
Protocol.errRejected,
'invalid setting "$name" (value $value)',
),
);
return;
}
if (name == 'noStandees') {
// The reference toggles this through the command so the standing
// monsters' standees are adjusted; the command writes the setting
// itself (track = !noStandees), so the value survives the execute.
_gameState.action(
TrackStandeesCommand(!s.noStandees, gameState: _gameState, settings: s),
);
}
s.saveToDisk();
_broadcastSettings();
}
/// `{t: save, name}` — snapshot the current game state under [name]
/// (multi-save; the content lives only on the server).
void _handleSave(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'save game states')) return;
final name = _nonEmptyName(connection, message, 'save');
if (name == null) return;
_settings().saveState(name);
_broadcastSettings();
}
/// `{t: loadSave, name}` — runs `LoadSaveCommand` (an undoable action, so
/// the index advances and every screen receives the loaded state).
void _handleLoadSave(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'load save states')) return;
final name = _nonEmptyName(connection, message, 'loadSave');
if (name == null) return;
final s = _settings();
if (!s.saves.containsKey(name)) {
connection.send(
Protocol.errorMessage(Protocol.errRejected, 'no save named "$name"'),
);
return;
}
s.loadSave(name);
// The loaded state may contain different characters — prune stale seats.
_syncSeats();
}
/// `{t: deleteSave, name}`.
void _handleDeleteSave(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'delete save states')) return;
final name = _nonEmptyName(connection, message, 'deleteSave');
if (name == null) return;
_settings().deleteSave(name);
_broadcastSettings();
}
/// `{t: saveCharacter, name, characterId}` — snapshot one character's
/// state (the reference `saveCharacterState`).
void _handleSaveCharacter(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'save characters')) return;
final name = _nonEmptyName(connection, message, 'saveCharacter');
if (name == null) return;
final characterId = message['characterId'];
if (characterId is! String || characterId.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'saveCharacter requires a non-empty "characterId" string',
),
);
return;
}
final item = _gameState.currentList.firstWhereOrNull(
(item) => item is Character && item.id == characterId,
);
final character = item is Character ? item : null;
if (character == null) {
connection.send(
Protocol.errorMessage(
Protocol.errRejected,
'no character with id "$characterId" in the current list',
),
);
return;
}
_settings().saveCharacterState(name, character);
_broadcastSettings();
}
/// `{t: loadCharacterSave, saveId}` — runs `LoadCharacterSaveCommand`
/// (undoable). [saveId] is the `"$name\n${characterId}"` key.
void _handleLoadCharacterSave(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'load character saves')) return;
final saveId = message['saveId'];
if (saveId is! String || saveId.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'loadCharacterSave requires a non-empty "saveId" string',
),
);
return;
}
final s = _settings();
if (!s.characterSaves.containsKey(saveId)) {
connection.send(
Protocol.errorMessage(
Protocol.errRejected,
'no character save with id "$saveId"',
),
);
return;
}
s.loadCharacterSave(saveId);
_syncSeats();
}
/// `{t: deleteCharacterSave, saveId}`.
void _handleDeleteCharacterSave(_Connection connection, Map<String, dynamic> message) {
if (!_requirePlayer(connection, 'delete character saves')) return;
final saveId = message['saveId'];
if (saveId is! String || saveId.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'deleteCharacterSave requires a non-empty "saveId" string',
),
);
return;
}
_settings().deleteCharacterSave(saveId);
_broadcastSettings();
}
/// The `"name"` field of a save message, with the bad-request answer sent
/// when it is missing/wrong-typed (returns null in that case).
String? _nonEmptyName(
_Connection connection,
Map<String, dynamic> message,
String verb,
) {
final name = message['name'];
if (name is! String || name.isEmpty) {
connection.send(
Protocol.errorMessage(
Protocol.errBadRequest,
'$verb requires a non-empty "name" string',
),
);
return null;
}
return name;
}
/// Broadcasts the current settings payload to every connection (after a
/// setting change or a save-list change).
void _broadcastSettings() {
final payload = _settings().forClient();
for (final connection in _activeConnections()) {
connection.send(Protocol.settingsMessage(payload));
}
}
// --- broadcasts -----------------------------------------------------------
/// The action handler's hook (set in the constructor): after every
/// action/undo/redo, push the new index + description + event plus a
/// full state snapshot serialized for each connection.
void _onAction(int index, String description, String eventJson) {
final Object? event = _decodeEvent(eventJson);
for (final connection in _activeConnections()) {
connection.send(
Protocol.updateMessage(
index: index,
description: description,
event: event,
state: _serializeFor(connection),
historyLength: _gameState.commandDescriptions.length,
redoDescription: _redoDescription(),
undoDescription: _undoDescription(),
),
);
}
}
Object? _decodeEvent(String eventJson) {
try {
return jsonDecode(eventJson);
} catch (_) {
return const {'type': 'none'};
}
}
Map<String, dynamic> _serializeFor(_Connection connection) =>
serializeState(
_gameState,
SessionContext(
sessionId: connection.session.id,
seats: _sessions.seats(),
),
);
/// Broadcasts the current seat table to every connection.
void _broadcastSeats() {
final seats = _sessions.seatsForState(_gameState);
for (final connection in _activeConnections()) {
connection.send(Protocol.seatsMessage(seats));
}
}
/// Prunes seats for characters no longer in the current list (undo,
/// removeCharacter, loadSave, …); persists and broadcasts when the table
/// changed.
void _syncSeats() {
final characterIds = _gameState.currentList
.whereType<Character>()
.map((c) => c.id)
.toSet();
var changed = false;
for (final session in _sessions.all) {
final stale = session.ownedCharacters
.where((id) => !characterIds.contains(id))
.toList();
if (stale.isNotEmpty) {
session.ownedCharacters.removeAll(stale);
changed = true;
}
}
if (changed) {
_persistSeats();
_broadcastSeats();
}
}
// --- seat persistence ------------------------------------------------------
void _persistSeats() {
// The store format is session id → character ids (a session may own
// several characters).
final bySession = <String, List<String>>{};
for (final entry in _sessions.seats().entries) {
bySession.putIfAbsent(entry.value, () => []).add(entry.key);
}
_seatStore.write(bySession);
}
/// At startup: restore persisted seats onto the (lazily created) session
/// records, keeping only characters that are actually in the restored
/// list.
void _restoreSeats() {
final stored = _seatStore.read();
if (stored == null || stored.isEmpty) return;
final characterIds = _gameState.currentList
.whereType<Character>()
.map((c) => c.id)
.toSet();
for (final entry in stored.entries) {
final session = _sessions.resolveOrCreate(entry.key);
for (final characterId in entry.value) {
if (characterIds.contains(characterId)) {
session.ownedCharacters.add(characterId);
}
}
}
if (stored.isNotEmpty) {
_log.info('restored seats for ${stored.length} session(s)');
}
}
}
|