forked from rconroy293/mtga-log-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17lands.py
More file actions
1696 lines (1459 loc) · 60.4 KB
/
Copy path17lands.py
File metadata and controls
1696 lines (1459 loc) · 60.4 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
"""
Follows along a Magic Arena log, parses the messages, and passes along
the parsed data to an API endpoint.
Licensed under GNU GPL v3.0 (see included LICENSE).
This MTGA log follower is unofficial Fan Content permitted under the Fan
Content Policy. Not approved/endorsed by Wizards. Portions of the
materials used are property of Wizards of the Coast. (C) Wizards of the
Coast LLC. See https://company.wizards.com/fancontentpolicy for more
details.
"""
import argparse
import copy
import datetime
import json
import getpass
import itertools
import os
import os.path
import pathlib
import re
import subprocess
import sys
import time
import traceback
import uuid
from typing import Any, Dict
from collections import defaultdict
import dateutil.parser
import seventeenlands.api_client
import seventeenlands.logging_utils
logger = seventeenlands.logging_utils.get_logger("17Lands")
CLIENT_VERSION = "0.1.43.p"
UPDATE_CHECK_INTERVAL = datetime.timedelta(hours=1)
UPDATE_PROMPT_FREQUENCY = 24
TOKEN_ENTRY_TITLE = "MTGA Log Client Token"
TOKEN_ENTRY_MESSAGE = "Please enter your client token from 17lands.com/account: "
TOKEN_MISSING_TITLE = "Error: Client Token Needed"
TOKEN_MISSING_MESSAGE = (
"Error: The program cannot continue without specifying a client token. Exiting."
)
TOKEN_INVALID_MESSAGE = "That token is invalid. Please specify a valid client token. See 17lands.com/getting_started for more details."
FILE_UPDATED_FORCE_REFRESH_SECONDS = 60
OSX_LOG_ROOT = os.path.join("Library", "Logs")
WINDOWS_LOG_ROOT = os.path.join(
"users",
getpass.getuser(),
"AppData",
"LocalLow",
)
STEAM_LOG_ROOT = os.path.join(
"steamapps",
"compatdata",
"2141910",
"pfx",
"drive_c",
"users",
"steamuser",
"AppData",
"LocalLow",
)
LOG_INTERMEDIATE = os.path.join("Wizards Of The Coast", "MTGA")
CURRENT_LOG = "Player.log"
PREVIOUS_LOG = "Player-prev.log"
CURRENT_LOG_PATH = os.path.join(LOG_INTERMEDIATE, CURRENT_LOG)
PREVIOUS_LOG_PATH = os.path.join(LOG_INTERMEDIATE, PREVIOUS_LOG)
POSSIBLE_ROOTS = (
# OSX
os.path.join(os.path.expanduser("~"), OSX_LOG_ROOT),
# Steam
os.path.join(
os.path.expanduser("~"),
".steam",
"steam",
STEAM_LOG_ROOT,
),
os.path.join(
os.path.expanduser("~"),
".local",
"share",
"Steam",
STEAM_LOG_ROOT,
),
# Windows
os.path.join("C:/", WINDOWS_LOG_ROOT),
os.path.join("D:/", WINDOWS_LOG_ROOT),
# Lutris
os.path.join(
os.path.expanduser("~"),
"Games",
"magic-the-gathering-arena",
"drive_c",
WINDOWS_LOG_ROOT,
),
# Wine
os.path.join(
os.environ.get(
"WINEPREFIX",
os.path.join(os.path.expanduser("~"), ".wine"),
),
"drive_c",
WINDOWS_LOG_ROOT,
),
)
POSSIBLE_CURRENT_FILEPATHS = list(
map(
lambda root_and_path: os.path.join(*root_and_path),
itertools.product(POSSIBLE_ROOTS, (CURRENT_LOG_PATH,)),
)
)
POSSIBLE_PREVIOUS_FILEPATHS = list(
map(
lambda root_and_path: os.path.join(*root_and_path),
itertools.product(POSSIBLE_ROOTS, (PREVIOUS_LOG_PATH,)),
)
)
CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".mtga_follower.ini")
LOG_START_REGEX_TIMED = re.compile(
r"^\[(UnityCrossThreadLogger|Client GRE)\](\d[\d:/ .-]+(AM|PM)?)"
)
LOG_START_REGEX_UNTIMED = re.compile(r"^\[(UnityCrossThreadLogger|Client GRE)\]")
TIMESTAMP_REGEX = re.compile("^([\\d/.-]+[ T][\\d]+:[\\d]+:[\\d]+( AM| PM)?)")
STRIPPED_TIMESTAMP_REGEX = re.compile("^(.*?)[: /]*$")
JSON_START_REGEX = re.compile(r"[\[\{]")
ACCOUNT_INFO_REGEX = re.compile(
r".*Updated account\. DisplayName:(.*), AccountID:(.*), Token:.*"
)
LOGIN_REGEX = re.compile(r".*Logged in successfully\. Display Name:(.*)")
MATCH_ACCOUNT_INFO_REGEX = re.compile(r".*: ((\w+) to Match|Match to (\w+)):")
SLEEP_TIME = 0.5
TIME_FORMATS = (
"%Y-%m-%d %I:%M:%S %p",
"%Y-%m-%d %H:%M:%S",
"%m/%d/%Y %I:%M:%S %p",
"%m/%d/%Y %H:%M:%S",
"%Y/%m/%d %I:%M:%S %p",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %I:%M:%S %p",
"%d/%m/%Y %H:%M:%S",
"%d/%m/%Y %I:%M:%S %p",
"%d.%m.%Y %H:%M:%S",
"%d.%m.%Y %I:%M:%S %p",
)
OUTPUT_TIME_FORMAT = "%Y%m%d%H%M%S"
MAX_MILLISECONDS_SINCE_EPOCH = int(1000 * datetime.datetime(3000, 1, 1).timestamp())
_ERROR_LINES_RECENCY = 10
def extract_time(time_str):
"""
Convert a time string in various formats to a datetime.
:param time_str: The string to convert.
:returns: The resulting datetime object.
:raises ValueError: Raises an exception if it cannot interpret the string.
"""
time_str = STRIPPED_TIMESTAMP_REGEX.match(time_str).group(1)
if ": " in time_str:
time_str = time_str.split(": ")[0]
for possible_format in TIME_FORMATS:
try:
return datetime.datetime.strptime(time_str, possible_format)
except ValueError:
pass
raise ValueError(f'Unsupported time format: "{time_str}"')
def json_value_matches(expectation, path, blob):
"""
Check if the value nested at a given path in a JSON blob matches the expected value.
:param expectation: The value to check against.
:param path: A list of keys for the nested value.
:param blob: The JSON blob to check in.
:returns: Whether or not the value exists at the given path and it matches expectation.
"""
for p in path:
if p in blob:
blob = blob[p]
else:
return False
return blob == expectation
def get_rank_string(rank_class, level, percentile, place, step):
"""
Convert the components of rank into a serializable value for recording
:param rank_class: Class (e.g. Bronze, Mythic)
:param level: Level within the class
:param percentile: Percentile (within Mythic)
:param place: Leaderboard place (within Mythic)
:param step: Step towards next level
:returns: Serialized rank string (e.g. "Gold-3-0.0-0-2")
"""
return "-".join(str(x) for x in [rank_class, level, percentile, place, step])
def contains_log_key(key: str, full_log: str) -> bool:
"""
Check if the given key exists in the log string. The key is checked both with and without
underscores to handle different Arena log formats.
:param key: The key to check for.
:param full_log: The string to check in.
:returns: Whether or not the key exists in the log string.
"""
return key in full_log or key.replace("_", "") in full_log
class Follower:
"""Follows along a log, parses the messages, and passes along the parsed data to the API endpoint."""
def __init__(self, token, host):
self.host = host
self.token = token
self.json_decoder = json.JSONDecoder()
self._api_client = seventeenlands.api_client.ApiClient(host=host)
self._reinitialize()
def _reinitialize(self):
self.buffer = []
self.cur_log_time = datetime.datetime.fromtimestamp(0)
self.last_utc_time = datetime.datetime.fromtimestamp(0)
self.last_event_time = None
self.last_raw_time = ""
self.disconnected_user = None
self.disconnected_screen_name = None
self.disconnected_full_screen_name = None
self.disconnected_rank = None
self.cur_user = None
self.cur_draft_event = None
self.cur_rank_data = None
self.cur_opponent_level = None
self.cur_opponent_match_id = None
self.current_match_id = None
self.current_event_id = None
self.starting_team_id = None
self.seat_id = None
self.turn_count = 0
self.current_game_maindeck = None
self.current_game_sideboard = None
self.game_service_metadata = None
self.game_client_metadata = None
self.objects_by_owner = defaultdict(dict)
self.opening_hand_count_by_seat = defaultdict(int)
self.opening_hand = defaultdict(list)
self.drawn_hands = defaultdict(list)
self.drawn_cards_by_instance_id = defaultdict(dict)
self.cards_in_hand = defaultdict(list)
self.user_screen_name = None
self.full_screen_name = None
self.screen_names = defaultdict(lambda: "")
self.game_history_events = []
self.pending_game_submission = {}
self.pending_game_result = {}
self.pending_match_result = {}
self.last_blob = ""
self.current_debug_blob = ""
self.recent_lines = []
self.__clear_match_data()
def _add_base_api_data(self, blob):
return {
"token": self.token,
"client_version": CLIENT_VERSION,
"player_id": self.cur_user,
"time": self.cur_log_time.isoformat(),
"utc_time": self.last_utc_time.isoformat(),
"event_time": self.last_event_time,
"raw_time": self.last_raw_time,
**blob,
}
def parse_log(self, filename, follow):
"""
Parse messages from a log file and pass the data along to the API endpoint.
:param filename: The filename for the log file to parse.
:param follow: Whether or not to continue looking for updates to the file after parsing
all the initial lines.
"""
while True:
self._reinitialize()
last_read_time = time.time()
last_file_size = 0
try:
with open(filename, errors="replace") as f:
while True:
line = f.readline()
file_size = pathlib.Path(filename).stat().st_size
if line:
self.__append_line(line)
last_read_time = time.time()
last_file_size = file_size
else:
self.__handle_complete_log_entry()
last_modified_time = os.stat(filename).st_mtime
if file_size < last_file_size:
logger.info(
f"Starting from beginning of file as file is smaller than before (previous = {last_file_size}; current = {file_size})"
)
break
elif (
last_modified_time
> last_read_time + FILE_UPDATED_FORCE_REFRESH_SECONDS
):
logger.info(
f"Starting from beginning of file as file has been updated much more recently than the last read (previous = {last_read_time}; current = {last_modified_time})"
)
break
elif follow:
time.sleep(SLEEP_TIME)
else:
break
except FileNotFoundError:
time.sleep(SLEEP_TIME)
except Exception as e:
self._log_error(
message=f"Error parsing log: {e}",
error=e,
stacktrace=traceback.format_exc(),
)
if not follow:
logger.info("Done processing file.")
break
def _log_error(self, message: str, error: Exception, stacktrace: str):
logger.error(message)
self._api_client.submit_error_info(
self._add_base_api_data(
{
"blob": self.current_debug_blob,
"recent_lines": self.recent_lines,
"stacktrace": traceback.format_exc(),
}
)
)
def __check_detailed_logs(self, line):
if line.startswith("DETAILED LOGS: DISABLED"):
logger.warning("Detailed logs are disabled in MTGA.")
show_message(
title="MTGA Logging Disabled (17Lands)",
message=(
"17Lands needs detailed logging enabled in MTGA. To enable this, click the "
'gear at the top right of MTGA, then "View Account" (at the bottom), then '
'check "Detailed Logs", then restart MTGA.'
),
)
elif line.startswith("DETAILED LOGS: ENABLED"):
logger.info("Detailed logs enabled in MTGA.")
def __append_line(self, line):
"""Add a complete line (not necessarily a complete message) from the log."""
if len(self.recent_lines) >= _ERROR_LINES_RECENCY:
self.recent_lines.pop(0)
self.recent_lines.append(line)
self.__check_detailed_logs(line)
self.__maybe_handle_account_info(line)
timestamp_match = TIMESTAMP_REGEX.match(line)
if timestamp_match:
self.last_raw_time = timestamp_match.group(1)
self.cur_log_time = extract_time(self.last_raw_time)
match = LOG_START_REGEX_UNTIMED.match(line)
if match:
self.__handle_complete_log_entry()
timed_match = LOG_START_REGEX_TIMED.match(line)
if timed_match:
self.last_raw_time = timed_match.group(2)
self.cur_log_time = extract_time(self.last_raw_time)
self.buffer.append(line[timed_match.end() :])
else:
self.buffer.append(line[match.end() :])
else:
self.buffer.append(line)
def __handle_complete_log_entry(self):
"""Mark the current log message complete. Should be called when waiting for more log messages."""
if len(self.buffer) == 0:
return
if self.cur_log_time is None:
self.buffer = []
return
full_log = "".join(self.buffer)
self.current_debug_blob = full_log
if full_log != self.last_blob:
try:
self.__handle_blob(full_log)
except Exception as e:
self._log_error(
message=f"Error {e} while processing {full_log}",
error=e,
stacktrace=traceback.format_exc(),
)
self.last_blob = full_log
else:
logger.info(f"Skipping repeated complete log entry: {full_log}")
self.buffer = []
# self.cur_log_time = None
def __maybe_get_utc_timestamp(self, blob):
timestamp = None
if "timestamp" in blob:
timestamp = blob["timestamp"]
elif "timestamp" in blob.get("payloadObject", {}):
timestamp = blob["payloadObject"]["timestamp"]
elif "timestamp" in blob.get("params", {}).get("payloadObject", {}):
timestamp = blob["params"]["payloadObject"]["timestamp"]
if timestamp is None:
return None
try:
timestamp_value = int(timestamp)
if timestamp_value < MAX_MILLISECONDS_SINCE_EPOCH:
return datetime.datetime.fromtimestamp(timestamp_value * 0.001)
else:
seconds_since_year_1 = timestamp_value / 10000000
return datetime.datetime.fromordinal(1) + datetime.timedelta(
seconds=seconds_since_year_1
)
except ValueError:
return dateutil.parser.isoparse(timestamp)
def __maybe_get_event_time(self, blob):
return blob.get("EventTime")
def __handle_blob(self, full_log):
"""Attempt to parse a complete log message and send the data if relevant."""
match = JSON_START_REGEX.search(full_log)
if not match:
return
try:
json_obj, end = self.json_decoder.raw_decode(full_log, match.start())
except json.JSONDecodeError as e:
logger.debug(
f"Ran into error {e} when parsing at {self.cur_log_time}. Data was: {full_log}"
)
return
json_obj = self.__extract_payload(json_obj)
if type(json_obj) != dict:
return
try:
maybe_time = self.__maybe_get_utc_timestamp(json_obj)
if maybe_time is not None:
self.last_utc_time = maybe_time
except:
pass
try:
maybe_time = self.__maybe_get_event_time(json_obj)
if maybe_time is not None:
self.last_event_time = maybe_time
except:
pass
if json_value_matches(
"Client.Connected", ["params", "messageName"], json_obj
): # Doesn't exist any more
self.__handle_login(json_obj)
elif (
contains_log_key(key="Event_Join", full_log=full_log)
and "EventName" in json_obj
):
self.__handle_joined_pod(json_obj)
elif (
contains_log_key(key="Event_Join", full_log=full_log)
and "Course" in json_obj
):
self.__handle_joined_event_response(json_obj)
elif "DraftStatus" in json_obj:
self.__handle_bot_draft_pack(json_obj)
elif (
contains_log_key(key="BotDraft_DraftPick", full_log=full_log)
and "PickInfo" in json_obj
):
self.__handle_bot_draft_pick(json_obj["PickInfo"])
elif (
contains_log_key(key="LogBusinessEvents", full_log=full_log)
and "PickGrpId" in json_obj
):
self.__handle_human_draft_combined(json_obj)
elif (
contains_log_key(key="LogBusinessEvents", full_log=full_log)
and "WinningType" in json_obj
):
self.__handle_log_business_game_end(json_obj)
elif "Draft.Notify " in full_log and "method" not in json_obj:
self.__handle_human_draft_pack(json_obj)
elif (
contains_log_key(key="Event_SetDeck", full_log=full_log)
and "EventName" in json_obj
):
self.__handle_deck_submission(json_obj)
elif (
contains_log_key(key="Event_GetCourses", full_log=full_log)
and "Courses" in json_obj
):
self.__handle_ongoing_events(json_obj)
elif (
contains_log_key(key="Event_ClaimPrize", full_log=full_log)
and "EventName" in json_obj
):
self.__handle_claim_prize(json_obj)
elif (
contains_log_key(key="Draft_CompleteDraft", full_log=full_log)
and "DraftId" in json_obj
):
self.__handle_event_course(json_obj)
elif "authenticateResponse" in json_obj:
self.__update_screen_name(json_obj["authenticateResponse"]["screenName"])
elif "matchGameRoomStateChangedEvent" in json_obj:
self.__handle_match_state_changed(json_obj)
elif (
"greToClientEvent" in json_obj
and "greToClientMessages" in json_obj["greToClientEvent"]
):
try:
for message in json_obj["greToClientEvent"]["greToClientMessages"]:
self.__handle_gre_to_client_message(message, maybe_time)
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE to client messages from {json_obj}",
error=e,
stacktrace=traceback.format_exc(),
)
elif json_value_matches(
"ClientToMatchServiceMessageType_ClientToGREMessage",
["clientToMatchServiceMessageType"],
json_obj,
):
self.__handle_client_to_gre_message(json_obj.get("payload", {}), maybe_time)
elif json_value_matches(
"ClientToMatchServiceMessageType_ClientToGREUIMessage",
["clientToMatchServiceMessageType"],
json_obj,
):
self.__handle_client_to_gre_ui_message(
json_obj.get("payload", {}), maybe_time
)
elif (
contains_log_key(key="Rank_GetCombinedRankInfo", full_log=full_log)
and "limitedSeasonOrdinal" in json_obj
):
self.__handle_self_rank_info(json_obj)
elif (
" PlayerInventory.GetPlayerCardsV3 " in full_log
and "method" not in json_obj
): # Doesn't exist any more
self.__handle_collection(json_obj)
elif "DTO_InventoryInfo" in json_obj:
self.__handle_inventory(json_obj["DTO_InventoryInfo"])
elif "NodeStates" in json_obj and "RewardTierUpgrade" in json_obj["NodeStates"]:
self.__handle_player_progress(json_obj)
elif "FrontDoorConnection.Close " in full_log:
self.__reset_current_user()
elif "Reconnect result : Connected" in full_log:
self.__handle_reconnect_result()
elif "Reconnect result : Connected" in full_log:
self.__handle_reconnect_result()
def __try_decode(self, blob, key):
try:
json_obj, _ = self.json_decoder.raw_decode(blob[key])
return json_obj
except Exception:
return blob[key]
def __extract_payload(self, blob):
if type(blob) != dict:
return blob
if "clientToMatchServiceMessageType" in blob:
return blob
for key in ("payload", "Payload", "request"):
if key in blob:
# Some messages are recursively serialized
return self.__extract_payload(self.__try_decode(blob, key))
return blob
def __update_screen_name(self, screen_name):
try:
if self.user_screen_name == screen_name:
return
self.user_screen_name = screen_name
user_info = {
"player_id": self.cur_user,
"screen_name": self.user_screen_name,
"full_screen_name": self.full_screen_name,
}
logger.info(f"Updating user info: {user_info}")
self._api_client.submit_user(self._add_base_api_data(user_info))
except Exception as e:
self._log_error(
message=f"Error {e} parsing screen name from {screen_name}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_match_state_changed(self, blob):
game_room_info = blob.get("matchGameRoomStateChangedEvent", {}).get(
"gameRoomInfo", {}
)
game_room_config = game_room_info.get("gameRoomConfig", {})
updated_match_id = game_room_config.get("matchId")
updated_event_id = game_room_config.get("eventId")
if "reservedPlayers" in game_room_config:
oppo_player_id = ""
for player in game_room_config["reservedPlayers"]:
self.screen_names[player["systemSeatId"]] = player["playerName"].split(
"#"
)[0]
# Backfill the current user's screen name when possible
if player["userId"] == self.cur_user:
self.__update_screen_name(player["playerName"])
updated_event_id = player.get("eventId", updated_event_id)
else:
oppo_player_id = player["userId"]
if oppo_player_id and "clientMetadata" in game_room_config:
metadata = game_room_config["clientMetadata"]
self.cur_opponent_level = get_rank_string(
rank_class=metadata.get(f"{oppo_player_id}_RankClass"),
level=metadata.get(f"{oppo_player_id}_RankTier"),
percentile=metadata.get(f"{oppo_player_id}_LeaderboardPercentile"),
place=metadata.get(f"{oppo_player_id}_LeaderboardPlacement"),
step=None,
)
self.cur_opponent_match_id = game_room_config.get("matchId")
logger.info(
f"Parsed opponent rank info as limited {self.cur_opponent_level} in match {self.cur_opponent_match_id}"
)
if updated_match_id and updated_event_id:
self.current_match_id = updated_match_id
self.current_event_id = updated_event_id
if "serviceMetadata" in game_room_config:
self.game_service_metadata = game_room_config["serviceMetadata"]
if "clientMetadata" in game_room_config:
self.game_client_metadata = game_room_config["clientMetadata"]
if "finalMatchResult" in game_room_info:
results = game_room_info["finalMatchResult"].get("resultList", [])
if results:
if self.__enqueue_game_data():
self.__enqueue_game_results(
results, match_game_room_state_changed_obj=blob
)
self.__clear_match_data(submit_pending_game=True)
def _add_to_game_history(self, message_blob, timestamp):
self.game_history_events.append(
{
"_timestamp": None if timestamp is None else timestamp.isoformat(),
**message_blob,
}
)
def __handle_gre_to_client_message(self, message_blob, timestamp):
"""Handle messages in the 'greToClientEvent' field."""
# Add to game history before processing the message, since we may submit the game right away.
if message_blob["type"] in [
"GREMessageType_QueuedGameStateMessage",
"GREMessageType_GameStateMessage",
]:
self._add_to_game_history(message_blob, timestamp)
elif (
message_blob["type"] == "GREMessageType_UIMessage"
and "onChat" in message_blob["uiMessage"]
):
self._add_to_game_history(message_blob, timestamp)
if message_blob["type"] == "GREMessageType_ConnectResp":
self.__handle_gre_connect_response(message_blob)
elif message_blob["type"] == "GREMessageType_EdictalMessage":
self.__handle_gre_edictal_message(message_blob, timestamp)
elif message_blob["type"] == "GREMessageType_GameStateMessage":
try:
system_seat_ids = message_blob.get("systemSeatIds", [])
if len(system_seat_ids) > 0:
self.seat_id = system_seat_ids[0]
game_state_message = message_blob.get("gameStateMessage", {})
if "gameInfo" in game_state_message:
game_info = game_state_message["gameInfo"]
if (
game_info.get("matchID", self.current_match_id)
!= self.current_match_id
):
self.current_match_id = game_info["matchID"]
self.current_event_id = None
turn_info = game_state_message.get("turnInfo", {})
players = game_state_message.get("players", [])
if turn_info.get("turnNumber"):
self.turn_count = turn_info.get("turnNumber")
else:
turns_sum = sum(p.get("turnNumber", 0) for p in players)
self.turn_count = max(self.turn_count, turns_sum)
for game_object in game_state_message.get("gameObjects", []):
if game_object["type"] not in (
"GameObjectType_Card",
"GameObjectType_SplitCard",
):
continue
owner = game_object["ownerSeatId"]
instance_id = game_object["instanceId"]
card_id = game_object["overlayGrpId"]
self.objects_by_owner[owner][instance_id] = card_id
for zone in game_state_message.get("zones", []):
if zone["type"] == "ZoneType_Hand":
owner = zone["ownerSeatId"]
player_objects = self.objects_by_owner[owner]
hand_card_ids = zone.get("objectInstanceIds", [])
self.cards_in_hand[owner] = [
player_objects.get(instance_id)
for instance_id in hand_card_ids
if instance_id
]
for instance_id in hand_card_ids:
card_id = player_objects.get(instance_id)
if instance_id is not None and card_id is not None:
self.drawn_cards_by_instance_id[owner][instance_id] = (
card_id
)
players_deciding_hand = {
(p["systemSeatNumber"], p.get("mulliganCount", 0))
for p in players
if p.get("pendingMessageType") == "ClientMessageType_MulliganResp"
}
for player_id, mulligan_count in players_deciding_hand:
if self.starting_team_id is None:
self.starting_team_id = turn_info.get("activePlayer")
self.opening_hand_count_by_seat[player_id] += 1
if mulligan_count == len(self.drawn_hands[player_id]):
self.drawn_hands[player_id].append(
self.cards_in_hand[player_id].copy()
)
if len(self.opening_hand) == 0 and (
"Phase_Beginning",
"Step_Upkeep",
1,
) == (
turn_info.get("phase"),
turn_info.get("step"),
turn_info.get("turnNumber"),
):
for owner, hand in self.cards_in_hand.items():
self.opening_hand[owner] = hand.copy()
self.__maybe_handle_game_over_stage(game_state_message)
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE message from {message_blob}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_gre_connect_response(self, blob):
try:
deck_info = blob.get("connectResp", {}).get("deckMessage", {})
self.current_game_maindeck = deck_info.pop("deckCards", [])
self.current_game_sideboard = deck_info.pop("sideboardCards", [])
self.current_game_additional_deck_info = deck_info
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE connect response from {blob}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_client_to_gre_message(self, payload, timestamp):
try:
if payload["type"] == "ClientMessageType_SelectNResp":
self._add_to_game_history(payload, timestamp)
if payload["type"] == "ClientMessageType_SubmitDeckResp":
try:
self.__clear_game_data()
deck_info = payload["submitDeckResp"]["deck"]
self.current_game_maindeck = deck_info.pop("deckCards", [])
self.current_game_sideboard = deck_info.pop("sideboardCards", [])
self.current_game_additional_deck_info = deck_info
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE deck submission from {payload}",
error=e,
stacktrace=traceback.format_exc(),
)
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE to client messages from {payload}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_client_to_gre_ui_message(self, payload, timestamp):
try:
if "onChat" in payload["uiMessage"]:
self._add_to_game_history(payload, timestamp)
except Exception as e:
self._log_error(
message=f"Error {e} parsing GRE to client UI messages from {payload}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_gre_edictal_message(self, payload, timestamp):
try:
edictMessage = payload.get("edictalMessage", {}).get("edictMessage", {})
return self.__handle_client_to_gre_message(
edictMessage, timestamp=timestamp
)
except Exception as e:
self._log_error(
message=f"Error {e} parsing edictal message from {payload}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_log_business_game_end(self, payload):
try:
if self.starting_team_id is None:
self.starting_team_id = payload.get("StartingTeamId")
if self.__enqueue_game_data():
self.pending_game_result = {
"game_end_payload": payload,
"game_number": payload.get("GameNumber"),
"won": self.seat_id == payload.get("WinningTeamId"),
"win_type": payload.get("WinningType"),
"game_end_reason": payload.get("WinningReason"),
}
logger.info(
f"Added pending game result via LogBusinessEvents {self.pending_game_result}"
)
except Exception as e:
self._log_error(
message=f"Error {e} parsing game end from LogBusinessEvents: {payload}",
error=e,
stacktrace=traceback.format_exc(),
)
def __maybe_handle_game_over_stage(self, game_state_message):
game_info = game_state_message.get("gameInfo", {})
if game_info.get("stage") != "GameStage_GameOver":
return
results = game_info.get("results")
if results:
if self.__enqueue_game_data():
self.__enqueue_game_results(results)
def __maybe_submit_pending_game(self):
if self.pending_game_submission and self.pending_game_result:
full_game = {
**self.pending_game_result,
**self.pending_match_result,
**self.pending_game_submission,
}
logger.info(f"Submitting queued game result")
self._api_client.submit_game_result(self._add_base_api_data(full_game))
self.pending_game_submission = {}
self.__clear_game_data()
def __clear_game_data(self, submit_pending_game=True):
if submit_pending_game:
self.__maybe_submit_pending_game()
self.turn_count = 0
self.objects_by_owner.clear()
self.opening_hand_count_by_seat.clear()
self.opening_hand.clear()
self.drawn_hands.clear()
self.drawn_cards_by_instance_id.clear()
self.starting_team_id = None
self.game_history_events.clear()
self.current_game_maindeck = None
self.current_game_sideboard = None
self.current_game_additional_deck_info = None
self.game_service_metadata = None
self.game_client_metadata = None
self.pending_game_result = {}
self.pending_match_result = {}
def __clear_match_data(self, submit_pending_game=False):
self.screen_names.clear()
self.current_match_id = None
self.current_event_id = None
self.seat_id = None
self.__clear_game_data(submit_pending_game=submit_pending_game)
def __maybe_handle_account_info(self, line):
match = ACCOUNT_INFO_REGEX.match(line)
if match:
screen_name = match.group(1)
self.cur_user = match.group(2)
self.__update_screen_name(screen_name)
return
match = MATCH_ACCOUNT_INFO_REGEX.match(line)
if match:
self.cur_user = match.group(2) or match.group(3)
return
match = LOGIN_REGEX.match(line)
if match:
self.full_screen_name = match.group(1)
def __handle_ongoing_events(self, json_obj):
"""Handle 'Event_GetCourses' messages."""
try:
event = {
"courses": json_obj["Courses"],
}
logger.info(f"Updated ongoing events")
self._api_client.submit_ongoing_events(self._add_base_api_data(event))
except Exception as e:
self._log_error(
message=f"Error {e} parsing ongoing event from {json_obj}",
error=e,
stacktrace=traceback.format_exc(),
)
def __handle_claim_prize(self, json_obj):
"""Handle 'Event_ClaimPrize' messages."""
try:
event = {
"event_name": json_obj["EventName"],
}
logger.info(f"Event ended: {event}")
self._api_client.submit_event_ended(self._add_base_api_data(event))
except Exception as e:
self._log_error(