forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMultiServer.py
More file actions
Latest commit
2775 lines (2404 loc) · 126 KB
/
Copy pathMultiServer.py
File metadata and controls
2775 lines (2404 loc) · 126 KB
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ importannotations
importargparse
importasyncio
importcollections
importcontextlib
importcopy
importdatetime
importfunctools
importhashlib
importinspect
importitertools
importlogging
importmath
importoperator
importpickle
importrandom
importshlex
importthreading
importtime
importtyping
importweakref
importzlib
fromsignalimportSIGINT, SIGTERM, signal
importModuleUpdate
ModuleUpdate.update()
iftyping.TYPE_CHECKING:
importssl
fromNetUtilsimportServerConnection
importcolorama
importwebsockets
fromwebsockets.extensions.permessage_deflateimportPerMessageDeflate, ServerPerMessageDeflateFactory
try:
# ponyorm is a requirement for webhost, not default server, so may not be importable
frompony.orm.dbapiproviderimportOperationalError
exceptImportError:
OperationalError=ConnectionError
importNetUtils
importUtils
fromUtilsimportversion_tuple, restricted_loads, Version, async_start, get_intended_text
fromNetUtilsimportEndpoint, ClientStatus, NetworkItem, decode, encode, NetworkPlayer, Permission, NetworkSlot, \
SlotType, LocationStore, MultiData, Hint, HintStatus
fromBaseClassesimportItemClassification
min_client_version=Version(0, 5, 0)
colorama.just_fix_windows_console()
no_version=Version(0, 0, 0)
assertisinstance(no_version, tuple) # assert immutable
server_per_message_deflate_factory=ServerPerMessageDeflateFactory(
server_max_window_bits=11,
client_max_window_bits=11,
compress_settings={"memLevel": 4},
)
defremove_from_list(container, value):
try:
container.remove(value)
exceptValueError:
pass
returncontainer
defpop_from_container(container, value):
ifisinstance(container, list) andisinstance(value, int) andlen(container) <=value:
returncontainer
ifisinstance(container, dict) andvaluenotincontainer:
returncontainer
try:
container.pop(value)
exceptValueError:
pass
returncontainer
defupdate_container_unique(container, entries):
ifisinstance(container, list):
existing_container_as_set=set(container)
container.extend([entryforentryinentriesifentrynotinexisting_container_as_set])
else:
container.update(entries)
returncontainer
defqueue_gc():
importgc
fromthreadingimportThread
gc_thread: typing.Optional[Thread] =getattr(queue_gc, "_thread", None)
defasync_collect():
time.sleep(2)
setattr(queue_gc, "_thread", None)
gc.collect()
ifnotgc_thread:
gc_thread=Thread(target=async_collect)
setattr(queue_gc, "_thread", gc_thread)
gc_thread.start()
# functions callable on storable data on the server by clients
modify_functions= {
# generic:
"replace": lambdaold, new: new,
"default": lambdaold, new: old,
# numeric:
"add": operator.add, # add together two objects, using python's "+" operator (works on strings and lists as append)
"mul": operator.mul,
"pow": operator.pow,
"mod": operator.mod,
"floor": lambdavalue, _: math.floor(value),
"ceil": lambdavalue, _: math.ceil(value),
"max": max,
"min": min,
# bitwise:
"xor": operator.xor,
"or": operator.or_,
"and": operator.and_,
"left_shift": operator.lshift,
"right_shift": operator.rshift,
# lists/dicts:
"remove": remove_from_list,
"pop": pop_from_container,
"update": update_container_unique,
}
defget_saving_second(seed_name: str, interval: int=60) ->int:
# save at expected times so other systems using savegame can expect it
# represents the target second of the auto_save_interval at which to save
returnint(hashlib.sha256(seed_name.encode()).hexdigest(), 16) %interval
classClient(Endpoint):
__slots__= (
"__weakref__",
"version",
"auth",
"team",
"slot",
"send_index",
"tags",
"messageprocessor",
"ctx",
"remote_items",
"remote_start_inventory",
"no_items",
"no_locations",
"no_text",
)
version: Version
auth: bool
team: int|None
slot: int|None
send_index: int
tags: list[str]
messageprocessor: ClientMessageProcessor
ctx: weakref.ref[Context]
remote_items: bool
remote_start_inventory: bool
no_items: bool
no_locations: bool
no_text: bool
def__init__(self, socket: "ServerConnection", ctx: Context) ->None:
super().__init__(socket)
self.version=no_version
self.auth=False
self.team=None
self.slot=None
self.send_index=0
self.tags= []
self.messageprocessor=client_message_processor(ctx, self)
self.ctx=weakref.ref(ctx)
self.remote_items=False
self.remote_start_inventory=False
self.no_items=False
self.no_locations=False
self.no_text=False
@property
defitems_handling(self):
ifself.no_items:
return0
return1+ (self.remote_items<<1) + (self.remote_start_inventory<<2)
@items_handling.setter
defitems_handling(self, value: int):
ifnot (value&0b001) and (value&0b110):
raiseValueError("Invalid flag combination")
self.no_items=not (value&0b001)
self.remote_items=bool(value&0b010)
self.remote_start_inventory=bool(value&0b100)
@property
defname(self) ->str:
ctx=self.ctx()
ifctx:
returnctx.player_names[self.team, self.slot]
return"Deallocated"
team_slot=typing.Tuple[int, int]
classContext:
dumper=staticmethod(encode)
loader=staticmethod(decode)
simple_options= {"hint_cost": int,
"location_check_points": int,
"server_password": str,
"password": str,
"release_mode": str,
"remaining_mode": str,
"collect_mode": str,
"countdown_mode": str,
"item_cheat": bool,
"compatibility": int}
# team -> slot id -> list of clients authenticated to slot.
clients: typing.Dict[int, typing.Dict[int, typing.List[Client]]]
endpoints: list[Client]
locations: LocationStore# typing.Dict[int, typing.Dict[int, typing.Tuple[int, int, int]]]
location_checks: typing.Dict[typing.Tuple[int, int], typing.Set[int]]
hints_used: typing.Dict[typing.Tuple[int, int], int]
groups: typing.Dict[int, typing.Set[int]]
save_version=2
stored_data: typing.Dict[str, object]
read_data: typing.Dict[str, object]
stored_data_notification_clients: typing.Dict[str, typing.Set[Client]]
slot_info: typing.Dict[int, NetworkSlot]
generator_version=Version(0, 0, 0)
checksums: typing.Dict[str, str]
item_names: typing.Dict[str, typing.Dict[int, str]]
item_name_groups: typing.Dict[str, typing.Dict[str, typing.Set[str]]]
location_names: typing.Dict[str, typing.Dict[int, str]]
location_name_groups: typing.Dict[str, typing.Dict[str, typing.Set[str]]]
all_item_and_group_names: typing.Dict[str, typing.Set[str]]
all_location_and_group_names: typing.Dict[str, typing.Set[str]]
non_hintable_names: typing.Dict[str, typing.AbstractSet[str]]
spheres: typing.List[typing.Dict[int, typing.Set[int]]]
""" each sphere is { player: { location_id, ... } } """
logger: logging.Logger
def__init__(self, host: str, port: int, server_password: str, password: str, location_check_points: int,
hint_cost: int, item_cheat: bool, release_mode: str="disabled", collect_mode="disabled",
countdown_mode: str="auto", remaining_mode: str="disabled", auto_shutdown: typing.SupportsFloat=0,
compatibility: int=2, log_network: bool=False, logger: logging.Logger=logging.getLogger()):
self.logger=logger
super(Context, self).__init__()
self.slot_info= {}
self.log_network=log_network
self.endpoints= []
self.clients= {}
self.compatibility: int=compatibility
self.shutdown_task=None
self.data_filename=None
self.save_filename=None
self.saving=False
self.player_names: typing.Dict[team_slot, str] = {}
self.player_name_lookup: typing.Dict[str, team_slot] = {}
self.connect_names= {} # names of slots clients can connect to
self.allow_releases= {}
self.host=host
self.port=port
self.server_password=server_password
self.password=password
self.server=None
self.countdown_timer=0
self.received_items= {}
self.start_inventory= {}
self.name_aliases: typing.Dict[team_slot, str] = {}
self.location_checks=collections.defaultdict(set)
self.hint_cost=hint_cost
self.location_check_points=location_check_points
self.hints_used=collections.defaultdict(int)
self.hints: typing.Dict[team_slot, typing.Set[Hint]] =collections.defaultdict(set)
self.release_mode: str=release_mode
self.remaining_mode: str=remaining_mode
self.collect_mode: str=collect_mode
self.countdown_mode: str=countdown_mode
self.item_cheat=item_cheat
self.exit_event=asyncio.Event()
self.client_activity_timers: typing.Dict[
team_slot, datetime.datetime] = {} # datetime of last new item check
self.client_connection_timers: typing.Dict[
team_slot, datetime.datetime] = {} # datetime of last connection
self.client_game_state: typing.Dict[team_slot, int] =collections.defaultdict(int)
self.er_hint_data: typing.Dict[int, typing.Dict[int, str]] = {}
self.auto_shutdown=auto_shutdown
self.commandprocessor=ServerCommandProcessor(self)
self.embedded_blacklist= {"host", "port"}
self.client_ids: typing.Dict[typing.Tuple[int, int], datetime.datetime] = {}
self.auto_save_interval=60# in seconds
self.auto_saver_thread: typing.Optional[threading.Thread] =None
self.save_dirty=False
self.tags= ['AP']
self.games: typing.Dict[int, str] = {}
self.minimum_client_versions: typing.Dict[int, Version] = {}
self.seed_name=""
self.groups= {}
self.group_collected: typing.Dict[int, typing.Set[int]] = {}
self.random=random.Random()
self.stored_data= {}
self.stored_data_notification_clients=collections.defaultdict(weakref.WeakSet)
self.read_data= {}
self.spheres= []
# init empty to satisfy linter, I suppose
self.gamespackage= {}
self.checksums= {}
self.item_name_groups= {}
self.location_name_groups= {}
self.all_item_and_group_names= {}
self.all_location_and_group_names= {}
self.item_names=collections.defaultdict(
lambda: Utils.KeyedDefaultDict(lambdacode: f'Unknown item (ID:{code})'))
self.location_names=collections.defaultdict(
lambda: Utils.KeyedDefaultDict(lambdacode: f'Unknown location (ID:{code})'))
self.non_hintable_names=collections.defaultdict(frozenset)
self._load_game_data()
# Data package retrieval
def_load_game_data(self):
importworlds
self.gamespackage=worlds.network_data_package["games"]
self.item_name_groups= {world_name: world.item_name_groupsforworld_name, worldin
worlds.AutoWorldRegister.world_types.items()}
self.location_name_groups= {world_name: world.location_name_groupsforworld_name, worldin
worlds.AutoWorldRegister.world_types.items()}
forworld_name, worldinworlds.AutoWorldRegister.world_types.items():
self.non_hintable_names[world_name] =world.hint_blacklist
forgame_packageinself.gamespackage.values():
# remove groups from data sent to clients
delgame_package["item_name_groups"]
delgame_package["location_name_groups"]
def_init_game_data(self):
forgame_name, game_packageinself.gamespackage.items():
if"checksum"ingame_package:
self.checksums[game_name] =game_package["checksum"]
foritem_name, item_idingame_package["item_name_to_id"].items():
self.item_names[game_name][item_id] =item_name
forlocation_name, location_idingame_package["location_name_to_id"].items():
self.location_names[game_name][location_id] =location_name
self.all_item_and_group_names[game_name] = \
set(game_package["item_name_to_id"]) |set(self.item_name_groups[game_name])
self.all_location_and_group_names[game_name] = \
set(game_package["location_name_to_id"]) |set(self.location_name_groups.get(game_name, []))
archipelago_item_names=self.item_names["Archipelago"]
archipelago_location_names=self.location_names["Archipelago"]
forgamein [game_nameforgame_nameinself.gamespackageifgame_name!="Archipelago"]:
# Add Archipelago items and locations to each data package.
self.item_names[game].update(archipelago_item_names)
self.location_names[game].update(archipelago_location_names)
defitem_names_for_game(self, game: str) ->typing.Optional[typing.Dict[str, int]]:
returnself.gamespackage[game]["item_name_to_id"] ifgameinself.gamespackageelseNone
deflocation_names_for_game(self, game: str) ->typing.Optional[typing.Dict[str, int]]:
returnself.gamespackage[game]["location_name_to_id"] ifgameinself.gamespackageelseNone
# General networking
asyncdefsend_msgs(self, endpoint: Endpoint, msgs: typing.Iterable[dict]) ->bool:
ifnotendpoint.socketornotendpoint.socket.open:
returnFalse
msg=self.dumper(msgs)
try:
awaitendpoint.socket.send(msg)
exceptwebsockets.ConnectionClosed:
self.logger.exception(f"Exception during send_msgs, could not send {msg}")
awaitself.disconnect(endpoint)
returnFalse
else:
ifself.log_network:
self.logger.info(f"Outgoing message: {msg}")
returnTrue
asyncdefsend_encoded_msgs(self, endpoint: Endpoint, msg: str) ->bool:
ifnotendpoint.socketornotendpoint.socket.open:
returnFalse
try:
awaitendpoint.socket.send(msg)
exceptwebsockets.ConnectionClosed:
self.logger.exception("Exception during send_encoded_msgs")
awaitself.disconnect(endpoint)
returnFalse
else:
ifself.log_network:
self.logger.info(f"Outgoing message: {msg}")
returnTrue
asyncdefbroadcast_send_encoded_msgs(self, endpoints: typing.Iterable[Endpoint], msg: str) ->bool:
sockets= []
forendpointinendpoints:
ifendpoint.socketandendpoint.socket.open:
sockets.append(endpoint.socket)
try:
websockets.broadcast(sockets, msg)
exceptRuntimeError:
self.logger.exception("Exception during broadcast_send_encoded_msgs")
returnFalse
else:
ifself.log_network:
self.logger.info(f"Outgoing broadcast: {msg}")
returnTrue
defbroadcast_all(self, msgs: typing.List[dict]):
msg_is_text=all(msg["cmd"] =="PrintJSON"formsginmsgs)
data=self.dumper(msgs)
endpoints= (
endpoint
forendpointinself.endpoints
ifendpoint.authandnot (msg_is_textandendpoint.no_text)
)
async_start(self.broadcast_send_encoded_msgs(endpoints, data))
defbroadcast_text_all(self, text: str, additional_arguments: dict= {}):
self.logger.info("Notice (all): %s"%text)
self.broadcast_all([{**{"cmd": "PrintJSON", "data": [{ "text": text }]}, **additional_arguments}])
defbroadcast_team(self, team: int, msgs: typing.List[dict]):
msg_is_text=all(msg["cmd"] =="PrintJSON"formsginmsgs)
data=self.dumper(msgs)
endpoints= (
endpoint
forendpointinitertools.chain.from_iterable(self.clients[team].values())
ifnot (msg_is_textandendpoint.no_text)
)
async_start(self.broadcast_send_encoded_msgs(endpoints, data))
defbroadcast(self, endpoints: typing.Iterable[Client], msgs: typing.List[dict]):
msgs=self.dumper(msgs)
async_start(self.broadcast_send_encoded_msgs(endpoints, msgs))
asyncdefdisconnect(self, endpoint: Client):
ifendpointinself.endpoints:
self.endpoints.remove(endpoint)
ifendpoint.slotandendpointinself.clients[endpoint.team][endpoint.slot]:
self.clients[endpoint.team][endpoint.slot].remove(endpoint)
awaiton_client_disconnected(self, endpoint)
defnotify_client(self, client: Client, text: str, additional_arguments: dict= {}):
ifnotclient.authorclient.no_text:
return
self.logger.info("Notice (Player %s in team %d): %s"% (client.name, client.team+1, text))
async_start(self.send_msgs(client, [{"cmd": "PrintJSON", "data": [{ "text": text }], **additional_arguments}]))
defnotify_client_multiple(self, client: Client, texts: typing.List[str], additional_arguments: dict= {}):
ifnotclient.authorclient.no_text:
return
async_start(self.send_msgs(client,
[{"cmd": "PrintJSON", "data": [{ "text": text }], **additional_arguments}
fortextintexts]))
# loading
defload(self, multidatapath: str, use_embedded_server_options: bool=False):
ifmultidatapath.lower().endswith(".zip"):
importzipfile
withzipfile.ZipFile(multidatapath) aszf:
forfileinzf.namelist():
iffile.endswith(".archipelago"):
data=zf.read(file)
break
else:
raiseException("No .archipelago found in archive.")
else:
withopen(multidatapath, 'rb') asf:
data=f.read()
self._load(self.decompress(data), {}, use_embedded_server_options)
self.data_filename=multidatapath
@staticmethod
defdecompress(data: bytes) ->dict:
format_version=data[0]
ifformat_version>3:
raiseUtils.VersionException("Incompatible multidata.")
returnrestricted_loads(zlib.decompress(data[1:]))
def_load(self, decoded_obj: MultiData, game_data_packages: typing.Dict[str, typing.Any],
use_embedded_server_options: bool):
self.read_data= {}
# there might be a better place to put this.
race_mode=decoded_obj.get("race_mode", 0)
self.read_data["race_mode"] =lambda: race_mode
mdata_ver=decoded_obj["minimum_versions"]["server"]
ifmdata_ver>version_tuple:
raiseRuntimeError(f"Supplied Multidata (.archipelago) requires a server of at least version {mdata_ver}, "
f"however this server is of version {version_tuple}")
self.generator_version=Version(*decoded_obj["version"])
clients_ver=decoded_obj["minimum_versions"].get("clients", {})
self.minimum_client_versions= {}
ifself.generator_version<Version(0, 6, 2):
min_version=Version(0, 1, 6)
else:
min_version=min_client_version
forplayer, versioninclients_ver.items():
self.minimum_client_versions[player] =max(Version(*version), min_version)
self.slot_info=decoded_obj["slot_info"]
self.games= {slot: slot_info.gameforslot, slot_infoinself.slot_info.items()}
self.groups= {slot: set(slot_info.group_members) forslot, slot_infoinself.slot_info.items()
ifslot_info.type==SlotType.group}
self.clients= {0: {}}
slot_info: NetworkSlot
slot_id: int
team_0=self.clients[0]
forslot_id, slot_infoinself.slot_info.items():
team_0[slot_id] = []
self.player_names[0, slot_id] =slot_info.name
self.player_name_lookup[slot_info.name] =0, slot_id
self.read_data[f"hints_{0}_{slot_id}"] =lambdalocal_team=0, local_player=slot_id: \
list(self.get_rechecked_hints(local_team, local_player))
self.read_data[f"client_status_{0}_{slot_id}"] =lambdalocal_team=0, local_player=slot_id: \
self.client_game_state[local_team, local_player]
self.seed_name=decoded_obj["seed_name"]
self.random.seed(self.seed_name)
self.connect_names=decoded_obj['connect_names']
self.locations=LocationStore(decoded_obj.pop("locations")) # pre-emptively free memory
self.slot_data=decoded_obj['slot_data']
forslot, datainself.slot_data.items():
self.read_data[f"slot_data_{slot}"] =lambdadata=data: data
self.er_hint_data= {int(player): {int(address): nameforaddress, nameinloc_data.items()}
forplayer, loc_dataindecoded_obj["er_hint_data"].items()}
# load start inventory:
forslot, item_codesindecoded_obj["precollected_items"].items():
self.start_inventory[slot] = [NetworkItem(item_code, -2, 0) foritem_codeinitem_codes]
forslot, hintsindecoded_obj["precollected_hints"].items():
self.hints[0, slot].update(hints)
# declare slots that aren't players as done
forslot, slot_infoinself.slot_info.items():
ifslot_info.type.always_goal:
forteaminself.clients:
self.client_game_state[team, slot] =ClientStatus.CLIENT_GOAL
ifuse_embedded_server_options:
server_options=decoded_obj.get("server_options", {})
self._set_options(server_options)
# embedded data package
forgame_name, dataindecoded_obj.get("datapackage", {}).items():
ifgame_nameingame_data_packages:
data=game_data_packages[game_name]
self.logger.info(f"Loading embedded data package for game {game_name}")
self.gamespackage[game_name] =data
self.item_name_groups[game_name] =data["item_name_groups"]
if"location_name_groups"indata:
self.location_name_groups[game_name] =data["location_name_groups"]
deldata["location_name_groups"]
deldata["item_name_groups"] # remove from data package, but keep in self.item_name_groups
self._init_game_data()
forgame_name, datainself.item_name_groups.items():
self.read_data[f"item_name_groups_{game_name}"] =lambdalgame=game_name: self.item_name_groups[lgame]
forgame_name, datainself.location_name_groups.items():
self.read_data[f"location_name_groups_{game_name}"] =lambdalgame=game_name: self.location_name_groups[lgame]
# sorted access spheres
self.spheres=decoded_obj.get("spheres", [])
# saving
defsave(self, now=False) ->bool:
ifself.saving:
ifnow:
self.save_dirty=False
returnself._save()
self.save_dirty=True
returnTrue
returnFalse
def_save(self, exit_save: bool=False) ->bool:
try:
# Does not use Utils.restricted_dumps because we'd rather make a save than not make one
encoded_save=pickle.dumps(self.get_save())
withopen(self.save_filename, "wb") asf:
f.write(zlib.compress(encoded_save))
exceptExceptionase:
self.logger.exception(e)
returnFalse
else:
returnTrue
definit_save(self, enabled: bool=True):
self.saving=enabled
ifself.saving:
ifnotself.save_filename:
importos
name, ext=os.path.splitext(self.data_filename)
self.save_filename=name+'.apsave'ifext.lower() in ('.archipelago', '.zip') \
elseself.data_filename+'_'+'apsave'
try:
withopen(self.save_filename, 'rb') asf:
save_data=restricted_loads(zlib.decompress(f.read()))
self.set_save(save_data)
exceptFileNotFoundError:
self.logger.error('No save data found, starting a new game')
exceptExceptionase:
self.logger.exception(e)
self._start_async_saving()
def_start_async_saving(self, atexit_save: bool=True):
ifnotself.auto_saver_thread:
defsave_regularly():
# time.time() is platform dependent, so using the expensive datetime method instead
defget_datetime_second():
now=datetime.datetime.now()
returnnow.second+now.microsecond*0.000001
second=get_saving_second(self.seed_name, self.auto_save_interval)
whilenotself.exit_event.is_set():
try:
next_wakeup= (second-get_datetime_second()) %self.auto_save_interval
time.sleep(max(1.0, next_wakeup))
ifself.save_dirty:
self.logger.debug("Saving via thread.")
self._save()
exceptOperationalErrorase:
self.logger.exception(e)
self.logger.info(f"Saving failed. Retry in {self.auto_save_interval} seconds.")
else:
self.save_dirty=False
ifnotatexit_save: # if atexit is used, that keeps a reference anyway
queue_gc()
self.auto_saver_thread=threading.Thread(target=save_regularly, daemon=True)
self.auto_saver_thread.start()
ifatexit_save:
importatexit
atexit.register(self._save, True) # make sure we save on exit too
defget_save(self) ->dict:
self.recheck_hints()
d= {
"version": self.save_version,
"connect_names": self.connect_names,
"received_items": self.received_items,
"hints_used": dict(self.hints_used),
"hints": dict(self.hints),
"location_checks": dict(self.location_checks),
"name_aliases": self.name_aliases,
"client_game_state": dict(self.client_game_state),
"client_activity_timers": tuple(
(key, value.timestamp()) forkey, valueinself.client_activity_timers.items()),
"client_connection_timers": tuple(
(key, value.timestamp()) forkey, valueinself.client_connection_timers.items()),
"random_state": self.random.getstate(),
"group_collected": dict(self.group_collected),
"stored_data": self.stored_data,
"game_options": {"hint_cost": self.hint_cost, "location_check_points": self.location_check_points,
"server_password": self.server_password, "password": self.password,
"release_mode": self.release_mode,
"remaining_mode": self.remaining_mode, "collect_mode": self.collect_mode,
"countdown_mode": self.countdown_mode,
"item_cheat": self.item_cheat, "compatibility": self.compatibility}
}
returnd
defset_save(self, savedata: dict):
ifself.connect_names!=savedata["connect_names"]:
raiseException("This savegame does not appear to match the loaded multiworld.")
ifsavedata["version"] >self.save_version:
raiseException("This savegame is newer than the server.")
self.received_items=savedata["received_items"]
self.hints_used.update(savedata["hints_used"])
self.hints.update(savedata["hints"])
self.name_aliases.update(savedata["name_aliases"])
self.client_game_state.update(savedata["client_game_state"])
self.client_connection_timers.update(
{tuple(key): datetime.datetime.fromtimestamp(value, datetime.timezone.utc) forkey, value
insavedata["client_connection_timers"]})
self.client_activity_timers.update(
{tuple(key): datetime.datetime.fromtimestamp(value, datetime.timezone.utc) forkey, value
insavedata["client_activity_timers"]})
self.location_checks.update(savedata["location_checks"])
self.random.setstate(savedata["random_state"])
if"game_options"insavedata:
self.hint_cost=savedata["game_options"]["hint_cost"]
self.location_check_points=savedata["game_options"]["location_check_points"]
self.server_password=savedata["game_options"]["server_password"]
self.password=savedata["game_options"]["password"]
self.release_mode=savedata["game_options"]["release_mode"]
self.remaining_mode=savedata["game_options"]["remaining_mode"]
self.collect_mode=savedata["game_options"]["collect_mode"]
self.countdown_mode=savedata["game_options"].get("countdown_mode", self.countdown_mode)
self.item_cheat=savedata["game_options"]["item_cheat"]
self.compatibility=savedata["game_options"]["compatibility"]
if"group_collected"insavedata:
self.group_collected=savedata["group_collected"]
if"stored_data"insavedata:
self.stored_data=savedata["stored_data"]
# count items and slots from lists for items_handling = remote
self.logger.info(
f'Loaded save file with {sum([len(v) fork, vinself.received_items.items() ifk[2]])} received items '
f'for {sum(k[2] forkinself.received_items)} players')
# rest
defget_hint_cost(self, slot):
ifself.hint_cost:
returnmax(1, int(self.hint_cost*0.01*len(self.locations[slot])))
return0
defrecheck_hints(self, team: typing.Optional[int] =None, slot: typing.Optional[int] =None,
changed: typing.Optional[typing.Set[team_slot]] =None) ->None:
"""Refreshes the hints for the specified team/slot. Providing 'None' for either team or slot
will refresh all teams or all slots respectively. If a set is passed for 'changed', each (team,slot)
pair that has at least one hint modified will be added to the set.
"""
forhint_team, hint_slotinself.hints:
ifteam!=hint_teamandteamisnotNone:
continue# Check specified team only, all if team is None
ifslot!=hint_slotandslotisnotNone:
continue# Check specified slot only, all if slot is None
new_hints: typing.Set[Hint] =set()
forhintinself.hints[hint_team, hint_slot]:
new_hint=hint.re_check(self, hint_team)
new_hints.add(new_hint)
ifhint==new_hint:
continue
forplayerinself.slot_set(hint.receiving_player) | {hint.finding_player}:
ifchangedisnotNone:
changed.add((hint_team,player))
ifslotisnotNoneandslot!=player:
self.replace_hint(hint_team, player, hint, new_hint)
self.hints[hint_team, hint_slot] =new_hints
defget_rechecked_hints(self, team: int, slot: int):
self.recheck_hints(team, slot)
returnself.hints[team, slot]
defget_sphere(self, player: int, location_id: int) ->int:
"""Get sphere of a location, -1 if spheres are not available."""
ifself.spheres:
fori, sphereinenumerate(self.spheres):
iflocation_idinsphere.get(player, set()):
returni
raiseKeyError(f"No Sphere found for location ID {location_id} belonging to player {player}. "
f"Location or player may not exist.")
return-1
defget_players_package(self):
return [NetworkPlayer(t, p, self.get_aliased_name(t, p), n) for (t, p), ninself.player_names.items()]
defslot_set(self, slot) ->typing.Set[int]:
"""Returns the slot IDs that concern that slot,
as in expands groups out and returns back the input for solo."""
returnself.groups.get(slot, {slot})
def_set_options(self, server_options: dict):
forkey, valueinserver_options.items():
data_type=self.simple_options.get(key, None)
ifdata_typeisnotNone:
ifvaluenotin {False, True, None}: # some can be boolean OR text, such as password
try:
value=data_type(value)
exceptExceptionase:
try:
raiseException(f"Could not set server option {key}, skipping.") frome
exceptExceptionase:
self.logger.exception(e)
self.logger.debug(f"Setting server option {key} to {value} from supplied multidata")
setattr(self, key, value)
elifkey=="disable_item_cheat":
self.item_cheat=notbool(value)
else:
self.logger.debug(f"Unrecognized server option {key}")
defget_aliased_name(self, team: int, slot: int):
if (team, slot) inself.name_aliases:
returnf"{self.name_aliases[team, slot]} ({self.player_names[team, slot]})"
else:
returnself.player_names[team, slot]
defnotify_hints(self, team: int, hints: typing.List[Hint], only_new: bool=False,
persist_even_if_found: bool=False, recipients: typing.Sequence[int] =None):
"""Send and remember hints."""
ifonly_new:
hints= [hintforhintinhintsifhintnotinself.hints[team, hint.finding_player]]
ifnothints:
return
new_hint_events: typing.Set[int] =set()
concerns=collections.defaultdict(list)
forhintinsorted(hints, key=operator.attrgetter('found'), reverse=True):
data= (hint, hint.as_network_message())
forplayerinself.slot_set(hint.receiving_player):
concerns[player].append(data)
ifnothint.localanddatanotinconcerns[hint.finding_player]:
concerns[hint.finding_player].append(data)
# For !hint use cases, only hints that were not already found at the time of creation should be remembered
# For LocationScouts use-cases, all hints should be remembered
ifnothint.foundorpersist_even_if_found:
# since hints are bidirectional, finding player and receiving player,
# we can check once if hint already exists
ifhintnotinself.hints[team, hint.finding_player]:
self.hints[team, hint.finding_player].add(hint)
new_hint_events.add(hint.finding_player)
forplayerinself.slot_set(hint.receiving_player):
self.hints[team, player].add(hint)
new_hint_events.add(player)
self.logger.info("Notice (Team #%d): %s"% (team+1, format_hint(self, team, hint)))
forslotinnew_hint_events:
self.on_new_hint(team, slot)
forslot, hint_datainconcerns.items():
ifrecipientsisNoneorslotinrecipients:
clients=filter(lambdac: notc.no_text, self.clients[team].get(slot, []))
ifnotclients:
continue
client_hints= [datum[1] fordatuminsorted(hint_data, key=lambdax: x[0].finding_player!=slot)]
forclientinclients:
async_start(self.send_msgs(client, client_hints))
defget_hint(self, team: int, finding_player: int, seeked_location: int) ->typing.Optional[Hint]:
forhintinself.hints[team, finding_player]:
ifhint.location==seeked_locationandhint.finding_player==finding_player:
returnhint
returnNone
defreplace_hint(self, team: int, slot: int, old_hint: Hint, new_hint: Hint) ->None:
ifold_hintinself.hints[team, slot]:
self.hints[team, slot].remove(old_hint)
self.hints[team, slot].add(new_hint)
# "events"
defon_goal_achieved(self, client: Client):
finished_msg=f'{self.get_aliased_name(client.team, client.slot)} (Team #{client.team+1})' \
f' has completed their goal.'
self.broadcast_text_all(finished_msg, {"type": "Goal", "team": client.team, "slot": client.slot})
if"auto"inself.collect_mode:
collect_player(self, client.team, client.slot)
if"auto"inself.release_mode:
release_player(self, client.team, client.slot)
self.save() # save goal completion flag
defon_new_hint(self, team: int, slot: int):
self.on_changed_hints(team, slot)
self.broadcast(self.clients[team][slot], [{
"cmd": "RoomUpdate",
"hint_points": get_slot_points(self, team, slot)
}])
defon_changed_hints(self, team: int, slot: int):
key: str=f"_read_hints_{team}_{slot}"
targets: typing.Set[Client] =set(self.stored_data_notification_clients[key])
iftargets:
self.broadcast(targets, [{"cmd": "SetReply", "key": key, "value": self.hints[team, slot]}])
defon_client_status_change(self, team: int, slot: int):
key: str=f"_read_client_status_{team}_{slot}"
targets: typing.Set[Client] =set(self.stored_data_notification_clients[key])
iftargets:
self.broadcast(targets, [{"cmd": "SetReply", "key": key, "value": self.client_game_state[team, slot]}])
defupdate_aliases(ctx: Context, team: int):
cmd=ctx.dumper([{"cmd": "RoomUpdate",
"players": ctx.get_players_package()}])
forclientsinctx.clients[team].values():
forclientinclients:
async_start(ctx.send_encoded_msgs(client, cmd))
asyncdefserver(websocket: "ServerConnection", path: str="/", ctx: Context=None) ->None:
client=Client(websocket, ctx)
ctx.endpoints.append(client)
try:
ifctx.log_network:
ctx.logger.info("Incoming connection")
awaiton_client_connected(ctx, client)
ifctx.log_network:
ctx.logger.info("Sent Room Info")
asyncfordatainwebsocket:
ifctx.log_network:
ctx.logger.info(f"Incoming message: {data}")
formsgindecode(data):
awaitprocess_client_cmd(ctx, client, msg)
exceptExceptionase:
ifnotisinstance(e, websockets.WebSocketException):
ctx.logger.exception(e)
finally:
ifctx.log_network:
ctx.logger.info("Disconnected")
awaitctx.disconnect(client)
asyncdefon_client_connected(ctx: Context, client: Client):
games= {ctx.games[x] forxinrange(1, len(ctx.games) +1)}
games.add("Archipelago")
awaitctx.send_msgs(client, [{
'cmd': 'RoomInfo',
'password': bool(ctx.password),
'games': games,
# tags are for additional features in the communication.
# Name them by feature or fork, as you feel is appropriate.
'tags': ctx.tags,
'version': version_tuple,
'generator_version': ctx.generator_version,
'permissions': get_permissions(ctx),
'hint_cost': ctx.hint_cost,
'location_check_points': ctx.location_check_points,
'datapackage_checksums': {game: game_data["checksum"] forgame, game_data
inctx.gamespackage.items() ifgameingamesand"checksum"ingame_data},
'seed_name': ctx.seed_name,
'time': time.time(),
}])
defget_permissions(ctx) ->typing.Dict[str, Permission]:
return {
"release": Permission.from_text(ctx.release_mode),
"remaining": Permission.from_text(ctx.remaining_mode),
"collect": Permission.from_text(ctx.collect_mode)
}
asyncdefon_client_disconnected(ctx: Context, client: Client):
ifclient.auth:
awaiton_client_left(ctx, client)
_non_game_messages= {"HintGame": "hinting", "Tracker": "tracking", "TextOnly": "viewing"}
""" { tag: ui_message } """
asyncdefon_client_joined(ctx: Context, client: Client):
ifctx.client_game_state[client.team, client.slot] ==ClientStatus.CLIENT_UNKNOWN:
update_client_status(ctx, client, ClientStatus.CLIENT_CONNECTED)
version_str='.'.join(str(x) forxinclient.version)
fortag, verbin_non_game_messages.items():
iftaginclient.tags:
final_verb=verb
break
else:
final_verb="playing"
ctx.broadcast_text_all(
f"{ctx.get_aliased_name(client.team, client.slot)} (Team #{client.team+1}) "
f"{final_verb}{ctx.games[client.slot]} has joined. "
f"Client({version_str}), {client.tags}.",
{"type": "Join", "team": client.team, "slot": client.slot, "tags": client.tags})
ctx.notify_client(client, "Now that you are connected, "
"you can use !help to list commands to run via the server. "
"If your client supports it, "
"you may have additional local commands you can list with /help.",
{"type": "Tutorial"})
ifnotany(isinstance(extension, PerMessageDeflate) forextensioninclient.socket.extensions):
ctx.notify_client(client, "Warning: your client does not support compressed websocket connections! "
"It may stop working in the future. If you are a player, please report this to the "
"client's developer.")
ctx.client_connection_timers[client.team, client.slot] =datetime.datetime.now(datetime.timezone.utc)
asyncdefon_client_left(ctx: Context, client: Client):
iflen(ctx.clients[client.team][client.slot]) <1:
update_client_status(ctx, client, ClientStatus.CLIENT_UNKNOWN)
ctx.client_connection_timers[client.team, client.slot] =datetime.datetime.now(datetime.timezone.utc)
version_str='.'.join(str(x) forxinclient.version)
fortag, verbin_non_game_messages.items():
iftaginclient.tags:
final_verb=f"stopped {verb}"
break
else: