forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNetUtils.py
More file actions
Latest commit
534 lines (421 loc) · 18 KB
/
Copy pathNetUtils.py
File metadata and controls
534 lines (421 loc) · 18 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
from __future__ importannotations
fromcollections.abcimportMapping, Sequence
importtyping
importenum
importwarnings
fromjsonimportJSONEncoder, JSONDecoder
iftyping.TYPE_CHECKING:
fromwebsocketsimportWebSocketServerProtocolasServerConnection
fromUtilsimportByValue, Version
classHintStatus(ByValue, enum.IntEnum):
HINT_UNSPECIFIED=0
HINT_NO_PRIORITY=10
HINT_AVOID=20
HINT_PRIORITY=30
HINT_FOUND=40
classJSONMessagePart(typing.TypedDict, total=False):
text: str
# optional
type: str
color: str
# owning player for location/item
player: int
# if type == item indicates item flags
flags: int
# if type == hint_status
hint_status: HintStatus
classClientStatus(ByValue, enum.IntEnum):
CLIENT_UNKNOWN=0
CLIENT_CONNECTED=5
CLIENT_READY=10
CLIENT_PLAYING=20
CLIENT_GOAL=30
classSlotType(ByValue, enum.IntFlag):
spectator=0b00
player=0b01
group=0b10
@property
defalways_goal(self) ->bool:
"""Mark this slot as having reached its goal instantly."""
returnself.value!=0b01
classPermission(ByValue, enum.IntFlag):
disabled=0b000# 0, completely disables access
enabled=0b001# 1, allows manual use
goal=0b010# 2, allows manual use after goal completion
auto=0b110# 6, forces use after goal completion, only works for release
auto_enabled=0b111# 7, forces use after goal completion, allows manual use any time
@staticmethod
deffrom_text(text: str):
data=0
if"auto"intext:
data|=0b110
elif"goal"intext:
data|=0b010
if"enabled"intext:
data|=0b001
returnPermission(data)
classNetworkPlayer(typing.NamedTuple):
"""Represents a particular player on a particular team."""
team: int
slot: int
alias: str
name: str
classNetworkSlot(typing.NamedTuple):
"""Represents a particular slot across teams."""
name: str
game: str
type: SlotType
group_members: Sequence[int] = () # only populated if type == group
classNetworkItem(typing.NamedTuple):
item: int
location: int
player: int
""" Sending player, except in LocationInfo (from LocationScouts), where it is the receiving player. """
flags: int=0
def_scan_for_TypedTuples(obj: typing.Any) ->typing.Any:
ifisinstance(obj, tuple) andhasattr(obj, "_fields"): # NamedTuple is not actually a parent class
data=obj._asdict()
data["class"] =obj.__class__.__name__
returndata
ifisinstance(obj, (tuple, list, set, frozenset)):
returntuple(_scan_for_TypedTuples(o) foroinobj)
ifisinstance(obj, dict):
return {key: _scan_for_TypedTuples(value) forkey, valueinobj.items()}
returnobj
_base_types=str|int|bool|float|None|tuple["_base_types", ...] |dict["_base_types", "base_types"]
defconvert_to_base_types(obj: typing.Any) ->_base_types:
ifisinstance(obj, (tuple, list, set, frozenset)):
returntuple(convert_to_base_types(o) foroinobj)
elifisinstance(obj, dict):
return {convert_to_base_types(key): convert_to_base_types(value) forkey, valueinobj.items()}
elifobjisNoneortype(obj) in (str, int, float, bool):
returnobj
# unwrap simple types to their base, such as StrEnum
elifisinstance(obj, str):
returnstr(obj)
elifisinstance(obj, int):
returnint(obj)
elifisinstance(obj, float):
returnfloat(obj)
else:
raiseException(f"Cannot handle {type(obj)}")
_encode=JSONEncoder(
ensure_ascii=False,
check_circular=False,
separators=(',', ':'),
).encode
defencode(obj: typing.Any) ->str:
return_encode(_scan_for_TypedTuples(obj))
defget_any_version(data: dict) ->Version:
data= {key.lower(): valueforkey, valueindata.items()} # .NET version classes have capitalized keys
returnVersion(int(data["major"]), int(data["minor"]), int(data["build"]))
allowlist= {
"NetworkPlayer": NetworkPlayer,
"NetworkItem": NetworkItem,
"NetworkSlot": NetworkSlot
}
custom_hooks= {
"Version": get_any_version
}
def_object_hook(o: typing.Any) ->typing.Any:
ifisinstance(o, dict):
hook=custom_hooks.get(o.get("class", None), None)
ifhook:
returnhook(o)
cls=allowlist.get(o.get("class", None), None)
ifcls:
forkeyintuple(o):
ifkeynotincls._fields:
del (o[key])
returncls(**o)
returno
decode=JSONDecoder(object_hook=_object_hook).decode
classEndpoint:
__slots__= ("socket",)
socket: "ServerConnection"
def__init__(self, socket):
self.socket=socket
classHandlerMeta(type):
def__new__(mcs, name, bases, attrs):
handlers=attrs["handlers"] = {}
trigger: str="_handle_"
forbaseinbases:
handlers.update(base.handlers)
handlers.update({handler_name[len(trigger):]: methodforhandler_name, methodinattrs.items() if
handler_name.startswith(trigger)})
orig_init=attrs.get('__init__', None)
ifnotorig_init:
forbaseinbases:
orig_init=getattr(base, '__init__', None)
iforig_init:
break
def__init__(self, *args, **kwargs):
iforig_init:
orig_init(self, *args, **kwargs)
# turn functions into bound methods
self.handlers= {name: method.__get__(self, type(self)) forname, methodin
handlers.items()}
attrs['__init__'] =__init__
returnsuper(HandlerMeta, mcs).__new__(mcs, name, bases, attrs)
classJSONTypes(str, enum.Enum):
color="color"
text="text"
player_id="player_id"
player_name="player_name"
item_name="item_name"
item_id="item_id"
location_name="location_name"
location_id="location_id"
entrance_name="entrance_name"
hint_status="hint_status"
classJSONtoTextParser(metaclass=HandlerMeta):
color_codes= {
# not exact color names, close enough but decent looking
"black": "000000",
"red": "EE0000",
"green": "00FF7F",
"yellow": "FAFAD2",
"blue": "6495ED",
"magenta": "EE00EE",
"cyan": "00EEEE",
"slateblue": "6D8BE8",
"plum": "AF99EF",
"salmon": "FA8072",
"white": "FFFFFF",
"orange": "FF7700",
}
def__init__(self, ctx):
self.ctx=ctx
def__call__(self, input_object: typing.List[JSONMessagePart]) ->str:
return"".join(self.handle_node(section) forsectionininput_object)
defhandle_node(self, node: JSONMessagePart):
node_type=node.get("type", None)
handler=self.handlers.get(node_type, self.handlers["text"])
returnhandler(node)
def_handle_color(self, node: JSONMessagePart):
codes=node["color"].split(";")
buffer="".join(color_code(code) forcodeincodesifcodeincolor_codes)
returnbuffer+self._handle_text(node) +color_code("reset")
def_handle_text(self, node: JSONMessagePart):
returnnode.get("text", "")
def_handle_player_id(self, node: JSONMessagePart):
player=int(node["text"])
node["color"] ='magenta'ifself.ctx.slot_concerns_self(player) else'yellow'
node["text"] =self.ctx.player_names[player]
returnself._handle_color(node)
# for other teams, spectators etc.? Only useful if player isn't in the clientside mapping
def_handle_player_name(self, node: JSONMessagePart):
node["color"] ='yellow'
returnself._handle_color(node)
def_handle_item_name(self, node: JSONMessagePart):
flags=node.get("flags", 0)
ifflags==0:
node["color"] ='cyan'
elifflags&0b001: # advancement
node["color"] ='plum'
elifflags&0b010: # useful
node["color"] ='slateblue'
elifflags&0b100: # trap
node["color"] ='salmon'
else:
node["color"] ='cyan'
returnself._handle_color(node)
def_handle_item_id(self, node: JSONMessagePart):
item_id=int(node["text"])
node["text"] =self.ctx.item_names.lookup_in_slot(item_id, node["player"])
returnself._handle_item_name(node)
def_handle_location_name(self, node: JSONMessagePart):
node["color"] ='green'
returnself._handle_color(node)
def_handle_location_id(self, node: JSONMessagePart):
location_id=int(node["text"])
node["text"] =self.ctx.location_names.lookup_in_slot(location_id, node["player"])
returnself._handle_location_name(node)
def_handle_entrance_name(self, node: JSONMessagePart):
node["color"] ='blue'
returnself._handle_color(node)
def_handle_hint_status(self, node: JSONMessagePart):
node["color"] =status_colors.get(node["hint_status"], "red")
returnself._handle_color(node)
classRawJSONtoTextParser(JSONtoTextParser):
def_handle_color(self, node: JSONMessagePart):
returnself._handle_text(node)
color_codes= {'reset': 0, 'bold': 1, 'underline': 4, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34,
'magenta': 35, 'cyan': 36, 'white': 37, 'black_bg': 40, 'red_bg': 41, 'green_bg': 42, 'yellow_bg': 43,
'blue_bg': 44, 'magenta_bg': 45, 'cyan_bg': 46, 'white_bg': 47,
'plum': 35, 'slateblue': 34, 'salmon': 31,} # convert ui colors to terminal colors
defcolor_code(*args):
return'\033['+';'.join([str(color_codes[arg]) forarginargs]) +'m'
defcolor(text, *args):
returncolor_code(*args) +text+color_code('reset')
defadd_json_text(parts: list, text: typing.Any, **kwargs) ->None:
parts.append({"text": str(text), **kwargs})
defadd_json_item(parts: list, item_id: int, player: int=0, item_flags: int=0, **kwargs) ->None:
parts.append({"text": str(item_id), "player": player, "flags": item_flags, "type": JSONTypes.item_id, **kwargs})
defadd_json_location(parts: list, location_id: int, player: int=0, **kwargs) ->None:
parts.append({"text": str(location_id), "player": player, "type": JSONTypes.location_id, **kwargs})
status_names: typing.Dict[HintStatus, str] = {
HintStatus.HINT_FOUND: "(found)",
HintStatus.HINT_UNSPECIFIED: "(unspecified)",
HintStatus.HINT_NO_PRIORITY: "(no priority)",
HintStatus.HINT_AVOID: "(avoid)",
HintStatus.HINT_PRIORITY: "(priority)",
}
status_colors: typing.Dict[HintStatus, str] = {
HintStatus.HINT_FOUND: "green",
HintStatus.HINT_UNSPECIFIED: "white",
HintStatus.HINT_NO_PRIORITY: "slateblue",
HintStatus.HINT_AVOID: "salmon",
HintStatus.HINT_PRIORITY: "plum",
}
defadd_json_hint_status(parts: list, hint_status: HintStatus, text: typing.Optional[str] =None, **kwargs):
parts.append({"text": textiftext!=Noneelsestatus_names.get(hint_status, "(unknown)"),
"hint_status": hint_status, "type": JSONTypes.hint_status, **kwargs})
classHint(typing.NamedTuple):
receiving_player: int
finding_player: int
location: int
item: int
found: bool
entrance: str=""
item_flags: int=0
status: HintStatus=HintStatus.HINT_UNSPECIFIED
defre_check(self, ctx, team) ->Hint:
ifself.foundandself.status==HintStatus.HINT_FOUND:
returnself
found=self.locationinctx.location_checks[team, self.finding_player]
iffound:
returnself._replace(found=found, status=HintStatus.HINT_FOUND)
returnself
defre_prioritize(self, ctx, status: HintStatus) ->Hint:
ifself.foundandstatus!=HintStatus.HINT_FOUND:
status=HintStatus.HINT_FOUND
ifstatus!=self.status:
returnself._replace(status=status)
returnself
def__hash__(self):
returnhash((self.receiving_player, self.finding_player, self.location, self.item, self.entrance))
defas_network_message(self) ->dict:
parts= []
add_json_text(parts, "[Hint]: ")
add_json_text(parts, self.receiving_player, type="player_id")
add_json_text(parts, "'s ")
add_json_item(parts, self.item, self.receiving_player, self.item_flags)
add_json_text(parts, " is at ")
add_json_location(parts, self.location, self.finding_player)
add_json_text(parts, " in ")
add_json_text(parts, self.finding_player, type="player_id")
ifself.entrance:
add_json_text(parts, "'s World at ")
add_json_text(parts, self.entrance, type="entrance_name")
else:
add_json_text(parts, "'s World")
add_json_text(parts, ". ")
add_json_hint_status(parts, self.status)
return {"cmd": "PrintJSON", "data": parts, "type": "Hint",
"receiving": self.receiving_player,
"item": NetworkItem(self.item, self.location, self.finding_player, self.item_flags),
"found": self.found}
@property
deflocal(self):
returnself.receiving_player==self.finding_player
class_LocationStore(dict, typing.MutableMapping[int, typing.Dict[int, typing.Tuple[int, int, int]]]):
def__init__(self, values: typing.MutableMapping[int, typing.Dict[int, typing.Tuple[int, int, int]]]):
super().__init__(values)
ifnotself:
raiseValueError(f"Rejecting game with 0 players")
iflen(self) !=max(self):
raiseValueError("Player IDs not continuous")
iflen(self.get(0, {})):
raiseValueError("Invalid player id 0 for location")
deffind_item(self, slots: typing.Set[int], seeked_item_id: int
) ->typing.Generator[typing.Tuple[int, int, int, int, int], None, None]:
forfinding_player, check_datainself.items():
forlocation_id, (item_id, receiving_player, item_flags) incheck_data.items():
ifreceiving_playerinslotsanditem_id==seeked_item_id:
yieldfinding_player, location_id, item_id, receiving_player, item_flags
defget_for_player(self, slot: int) ->typing.Dict[int, typing.Set[int]]:
importcollections
all_locations: typing.Dict[int, typing.Set[int]] =collections.defaultdict(set)
forsource_slot, location_datainself.items():
forlocation_id, valuesinlocation_data.items():
ifvalues[1] ==slot:
all_locations[source_slot].add(location_id)
returnall_locations
defget_checked(self, state: typing.Dict[typing.Tuple[int, int], typing.Set[int]], team: int, slot: int
) ->typing.List[int]:
checked=state[team, slot]
ifnotchecked:
# This optimizes the case where everyone connects to a fresh game at the same time.
ifslotnotinself:
raiseKeyError(slot)
return []
return [location_idfor
location_idinself[slot] if
location_idinchecked]
defget_missing(self, state: typing.Dict[typing.Tuple[int, int], typing.Set[int]], team: int, slot: int
) ->typing.List[int]:
checked=state[team, slot]
ifnotchecked:
# This optimizes the case where everyone connects to a fresh game at the same time.
returnlist(self[slot])
return [location_idfor
location_idinself[slot] if
location_idnotinchecked]
defget_remaining(self, state: typing.Dict[typing.Tuple[int, int], typing.Set[int]], team: int, slot: int
) ->typing.List[typing.Tuple[int, int]]:
checked=state[team, slot]
player_locations=self[slot]
returnsorted([(player_locations[location_id][1], player_locations[location_id][0]) for
location_idinplayer_locationsif
location_idnotinchecked])
classMinimumVersions(typing.TypedDict):
server: tuple[int, int, int]
clients: dict[int, tuple[int, int, int]]
classGamesPackage(typing.TypedDict, total=False):
item_name_groups: dict[str, list[str]]
item_name_to_id: dict[str, int]
location_name_groups: dict[str, list[str]]
location_name_to_id: dict[str, int]
checksum: str
classDataPackage(typing.TypedDict):
games: dict[str, GamesPackage]
classMultiData(typing.TypedDict):
slot_data: dict[int, Mapping[str, typing.Any]]
slot_info: dict[int, NetworkSlot]
connect_names: dict[str, tuple[int, int]]
locations: dict[int, dict[int, tuple[int, int, int]]]
checks_in_area: dict[int, dict[str, int|list[int]]]
server_options: dict[str, object]
er_hint_data: dict[int, dict[int, str]]
precollected_items: dict[int, list[int]]
precollected_hints: dict[int, set[Hint]]
version: tuple[int, int, int]
tags: list[str]
minimum_versions: MinimumVersions
seed_name: str
spheres: list[dict[int, set[int]]]
datapackage: dict[str, GamesPackage]
race_mode: int
iftyping.TYPE_CHECKING: # type-check with pure python implementation until we have a typing stub
LocationStore=_LocationStore
else:
try:
from_speedupsimportLocationStore
import_speedups
importos.path
ifos.path.isfile("_speedups.pyx") andos.path.getctime(_speedups.__file__) <os.path.getctime("_speedups.pyx"):
warnings.warn(f"{_speedups.__file__} outdated! "
f"Please rebuild with `cythonize -b -i _speedups.pyx` or delete it!")
exceptImportError:
try:
importpyximport
pyximport.install()
exceptImportError:
pyximport=None
try:
from_speedupsimportLocationStore
exceptImportError:
warnings.warn("_speedups not available. Falling back to pure python LocationStore. "
"Install a matching C++ compiler for your platform to compile _speedups.")
LocationStore=_LocationStore