-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
s3s.py
executable file
·2066 lines (1758 loc) · 78.9 KB
/
s3s.py
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
#!/usr/bin/env python
# s3s (ↄ) 2022-2024 eli fessler (frozenpandaman), clovervidia
# Based on splatnet2statink (ↄ) 2017-2024 eli fessler (frozenpandaman), clovervidia
# https://github.com/frozenpandaman/s3s
# License: GPLv3
import argparse, base64, datetime, json, os, shutil, re, sys, time, uuid
from concurrent.futures import ThreadPoolExecutor
from subprocess import call
import requests, msgpack
from packaging import version
import iksm, utils
A_VERSION = "0.6.6"
DEBUG = False
os.system("") # ANSI escape setup
if sys.version_info[1] >= 7: # only works on python 3.7+
sys.stdout.reconfigure(encoding='utf-8') # note: please stop using git bash
# CONFIG.TXT CREATION
if getattr(sys, 'frozen', False): # place config.txt in same directory as script (bundled or not)
app_path = os.path.dirname(sys.executable)
elif __file__:
app_path = os.path.dirname(__file__)
config_path = os.path.join(app_path, "config.txt")
try:
config_file = open(config_path, "r")
CONFIG_DATA = json.load(config_file)
config_file.close()
except (IOError, ValueError):
print("Generating new config file.")
CONFIG_DATA = {"api_key": "", "acc_loc": "", "gtoken": "", "bullettoken": "", "session_token": "", "f_gen": "https://api.imink.app/f"}
config_file = open(config_path, "w")
config_file.seek(0)
config_file.write(json.dumps(CONFIG_DATA, indent=4, sort_keys=False, separators=(',', ': ')))
config_file.close()
config_file = open(config_path, "r")
CONFIG_DATA = json.load(config_file)
config_file.close()
# SET GLOBALS
API_KEY = CONFIG_DATA["api_key"] # for stat.ink
USER_LANG = CONFIG_DATA["acc_loc"][:5] # user input
USER_COUNTRY = CONFIG_DATA["acc_loc"][-2:] # nintendo account info
GTOKEN = CONFIG_DATA["gtoken"] # for accessing splatnet - base64 json web token
BULLETTOKEN = CONFIG_DATA["bullettoken"] # for accessing splatnet - base64
SESSION_TOKEN = CONFIG_DATA["session_token"] # for nintendo login
F_GEN_URL = CONFIG_DATA["f_gen"] # endpoint for generating f (imink API by default)
thread_pool = ThreadPoolExecutor(max_workers=2)
# SET HTTP HEADERS
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Linux; Android 14; Pixel 7a) ' \
'AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/120.0.6099.230 Mobile Safari/537.36'
APP_USER_AGENT = str(CONFIG_DATA.get("app_user_agent", DEFAULT_USER_AGENT))
def write_config(tokens):
'''Writes config file and updates the global variables.'''
config_file = open(config_path, "w")
config_file.seek(0)
config_file.write(json.dumps(tokens, indent=4, sort_keys=False, separators=(',', ': ')))
config_file.close()
config_file = open(config_path, "r")
CONFIG_DATA = json.load(config_file)
global API_KEY
API_KEY = CONFIG_DATA["api_key"]
global USER_LANG
USER_LANG = CONFIG_DATA["acc_loc"][:5]
global USER_COUNTRY
USER_COUNTRY = CONFIG_DATA["acc_loc"][-2:]
global GTOKEN
GTOKEN = CONFIG_DATA["gtoken"]
global BULLETTOKEN
BULLETTOKEN = CONFIG_DATA["bullettoken"]
global SESSION_TOKEN
SESSION_TOKEN = CONFIG_DATA["session_token"]
config_file.close()
def headbutt(forcelang=None):
'''Returns a (dynamic!) header used for GraphQL requests.'''
if forcelang:
lang = forcelang
country = forcelang[-2:]
else:
lang = USER_LANG
country = USER_COUNTRY
graphql_head = {
'Authorization': f'Bearer {BULLETTOKEN}', # update every time it's called with current global var
'Accept-Language': lang,
'User-Agent': APP_USER_AGENT,
'X-Web-View-Ver': iksm.get_web_view_ver(),
'Content-Type': 'application/json',
'Accept': '*/*',
'Origin': iksm.SPLATNET3_URL,
'X-Requested-With': 'com.nintendo.znca',
'Referer': f'{iksm.SPLATNET3_URL}?lang={lang}&na_country={country}&na_lang={lang}',
'Accept-Encoding': 'gzip, deflate'
}
return graphql_head
def prefetch_checks(printout=False):
'''Queries the SplatNet 3 homepage to check if our gtoken & bulletToken are still valid and regenerates them if not.'''
if printout:
print("Validating your tokens...", end='\r')
iksm.get_web_view_ver() # setup
if SESSION_TOKEN == "" or GTOKEN == "" or BULLETTOKEN == "":
gen_new_tokens("blank")
sha = utils.translate_rid["HomeQuery"]
test = requests.post(iksm.GRAPHQL_URL, data=utils.gen_graphql_body(sha, "naCountry", USER_COUNTRY), headers=headbutt(), cookies=dict(_gtoken=GTOKEN))
if test.status_code != 200:
if printout:
print("\n")
gen_new_tokens("expiry")
else:
if printout:
print("Validating your tokens... done.\n")
def gen_new_tokens(reason, force=False):
'''Attempts to generate new tokens when the saved ones have expired.'''
manual_entry = False
if force != True: # unless we force our way through
if reason == "blank":
print("Blank token(s). ")
elif reason == "expiry":
print("The stored tokens have expired.")
else:
print("Cannot access SplatNet 3 without having played online.")
sys.exit(0)
if SESSION_TOKEN == "":
print("Please log in to your Nintendo Account to obtain your session_token.")
new_token = iksm.log_in(A_VERSION, APP_USER_AGENT, F_GEN_URL)
if new_token is None:
print("There was a problem logging you in. Please try again later.")
elif new_token == "skip":
manual_entry = True
else:
print("\nWrote session_token to config.txt.")
CONFIG_DATA["session_token"] = new_token
write_config(CONFIG_DATA)
elif SESSION_TOKEN == "skip":
manual_entry = True
if manual_entry: # no session_token ever gets stored
print("\nYou have opted against automatic token generation and must manually input your tokens.\n")
new_gtoken, new_bullettoken = iksm.enter_tokens()
acc_lang = "en-US" # overwritten by user setting
acc_country = "US"
print("Using `US` for country by default. This can be changed in config.txt.")
else:
print("Attempting to generate new gtoken and bulletToken...")
new_gtoken, acc_name, acc_lang, acc_country = iksm.get_gtoken(F_GEN_URL, SESSION_TOKEN, A_VERSION)
new_bullettoken = iksm.get_bullet(new_gtoken, APP_USER_AGENT, acc_lang, acc_country)
CONFIG_DATA["gtoken"] = new_gtoken # valid for 6 hours
CONFIG_DATA["bullettoken"] = new_bullettoken # valid for 2 hours
global USER_LANG
if acc_lang != USER_LANG:
acc_lang = USER_LANG
CONFIG_DATA["acc_loc"] = f"{acc_lang}|{acc_country}"
write_config(CONFIG_DATA)
if new_bullettoken == "":
print("Wrote gtoken to config.txt, but could not generate bulletToken.")
print("Is SplatNet 3 undergoing maintenance?")
sys.exit(1)
if manual_entry:
print("Wrote tokens to config.txt.\n") # and updates acc_country if necessary...
else:
print(f"Wrote tokens for {acc_name} to config.txt.\n")
def fetch_json(which, separate=False, exportall=False, specific=False, numbers_only=False, printout=False, skipprefetch=False):
'''Returns results JSON from SplatNet 3, including a combined dictionary for battles + SR jobs if requested.'''
swim = SquidProgress()
if DEBUG:
print(f"* fetch_json() called with which={which}, separate={separate}, " \
f"exportall={exportall}, specific={specific}, numbers_only={numbers_only}")
if exportall and not separate:
print("* fetch_json() must be called with separate=True if using exportall.")
sys.exit(1)
if not skipprefetch:
prefetch_checks(printout)
if DEBUG:
print("* prefetch_checks() succeeded")
else:
if DEBUG:
print("* skipping prefetch_checks()")
swim()
ink_list, salmon_list = [], []
parent_files = []
queries = []
if which in ("both", "ink"):
if specific in (True, "regular"):
queries.append("RegularBattleHistoriesQuery")
if specific in (True, "anarchy"):
queries.append("BankaraBattleHistoriesQuery")
if specific in (True, "x"):
queries.append("XBattleHistoriesQuery")
if specific in (True, "challenge"):
queries.append("EventBattleHistoriesQuery")
if specific in (True, "private") and not utils.custom_key_exists("ignore_private", CONFIG_DATA):
queries.append("PrivateBattleHistoriesQuery")
if not specific: # False
if DEBUG:
print("* not specific, just looking at latest")
queries.append("LatestBattleHistoriesQuery")
else:
queries.append(None)
if which in ("both", "salmon"):
queries.append("CoopHistoryQuery")
else:
queries.append(None)
needs_sorted = False # https://ygdp.yale.edu/phenomena/needs-washed :D
for sha in queries:
if sha is not None:
if DEBUG:
print(f"* making query1 to {sha}")
lang = 'en-US' if sha == "CoopHistoryQuery" else None
sha = utils.translate_rid[sha]
battle_ids, job_ids = [], []
query1 = requests.post(iksm.GRAPHQL_URL,
data=utils.gen_graphql_body(sha),
headers=headbutt(forcelang=lang),
cookies=dict(_gtoken=GTOKEN))
query1_resp = json.loads(query1.text)
swim()
if not query1_resp.get("data"): # catch error
print("\nSomething's wrong with one of the query hashes. Ensure s3s is up-to-date, and if this message persists, please open an issue on GitHub.")
sys.exit(1)
# ink battles - latest 50 of any type
if "latestBattleHistories" in query1_resp["data"]:
for battle_group in query1_resp["data"]["latestBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"]) # don't filter out private battles here - do that in post_result()
# ink battles - latest 50 turf war
elif "regularBattleHistories" in query1_resp["data"]:
needs_sorted = True
for battle_group in query1_resp["data"]["regularBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"])
# ink battles - latest 50 anarchy battles
elif "bankaraBattleHistories" in query1_resp["data"]:
needs_sorted = True
for battle_group in query1_resp["data"]["bankaraBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"])
# ink battles - latest 50 x battles
elif "xBattleHistories" in query1_resp["data"]:
needs_sorted = True
for battle_group in query1_resp["data"]["xBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"])
# ink battles - latest 50 challenge battles
elif "eventBattleHistories" in query1_resp["data"]:
needs_sorted = True
for battle_group in query1_resp["data"]["eventBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"])
# ink battles - latest 50 private battles
elif "privateBattleHistories" in query1_resp["data"] \
and not utils.custom_key_exists("ignore_private", CONFIG_DATA):
needs_sorted = True
for battle_group in query1_resp["data"]["privateBattleHistories"]["historyGroups"]["nodes"]:
for battle in battle_group["historyDetails"]["nodes"]:
battle_ids.append(battle["id"])
# salmon run jobs - latest 50
elif "coopResult" in query1_resp["data"]:
for shift in query1_resp["data"]["coopResult"]["historyGroups"]["nodes"]:
for job in shift["historyDetails"]["nodes"]:
job_ids.append(job["id"])
if numbers_only:
ink_list.extend(battle_ids)
salmon_list.extend(job_ids)
else: # ALL DATA - TAKES A LONG TIME
ink_list.extend(thread_pool.map(fetch_detailed_result, [True]*len(battle_ids), battle_ids, [swim]*len(battle_ids)))
salmon_list.extend(thread_pool.map(fetch_detailed_result, [False]*len(job_ids), job_ids, [swim]*len(job_ids)))
if needs_sorted: # put regular/bankara/event/private in order, b/c exported in sequential chunks
try:
ink_list = [x for x in ink_list if x['data']['vsHistoryDetail'] is not None] # just in case
ink_list = sorted(ink_list, key=lambda d: d['data']['vsHistoryDetail']['playedTime'])
except:
print("(!) Exporting without sorting results.json")
try:
salmon_list = [x for x in salmon_list if x['data']['coopHistoryDetail'] is not None]
salmon_list = sorted(salmon_list, key=lambda d: d['data']['coopHistoryDetail']['playedTime'])
except:
print("(!) Exporting without sorting coop_results.json")
parent_files.append(query1_resp)
else: # sha = None (we don't want to get the specified result type)
pass
if exportall:
return parent_files, ink_list, salmon_list
else:
if separate:
return ink_list, salmon_list
else:
combined = ink_list + salmon_list
return combined
def fetch_detailed_result(is_vs_history, history_id, swim):
'''Helper function for fetch_json().'''
sha = "VsHistoryDetailQuery" if is_vs_history else "CoopHistoryDetailQuery"
varname = "vsResultId" if is_vs_history else "coopHistoryDetailId"
lang = None if is_vs_history else 'en-US'
query2 = requests.post(iksm.GRAPHQL_URL,
data=utils.gen_graphql_body(utils.translate_rid[sha], varname, history_id),
headers=headbutt(forcelang=lang),
cookies=dict(_gtoken=GTOKEN))
query2_resp = json.loads(query2.text)
swim()
return query2_resp
def populate_gear_abilities(player):
'''Returns string representing all 12 ability slots for the player's gear, for use in set_scoreboard().'''
h_main = utils.translate_gear_ability(player["headGear"]["primaryGearPower"]["image"]["url"])
h_subs = []
if len(player["headGear"]["additionalGearPowers"]) > 0:
h_subs.append(utils.translate_gear_ability(player["headGear"]["additionalGearPowers"][0]["image"]["url"]))
if len(player["headGear"]["additionalGearPowers"]) > 1:
h_subs.append(utils.translate_gear_ability(player["headGear"]["additionalGearPowers"][1]["image"]["url"]))
if len(player["headGear"]["additionalGearPowers"]) > 2:
h_subs.append(utils.translate_gear_ability(player["headGear"]["additionalGearPowers"][2]["image"]["url"]))
c_main = utils.translate_gear_ability(player["clothingGear"]["primaryGearPower"]["image"]["url"])
c_subs = []
if len(player["clothingGear"]["additionalGearPowers"]) > 0:
c_subs.append(utils.translate_gear_ability(player["clothingGear"]["additionalGearPowers"][0]["image"]["url"]))
if len(player["clothingGear"]["additionalGearPowers"]) > 1:
c_subs.append(utils.translate_gear_ability(player["clothingGear"]["additionalGearPowers"][1]["image"]["url"]))
if len(player["clothingGear"]["additionalGearPowers"]) > 2:
c_subs.append(utils.translate_gear_ability(player["clothingGear"]["additionalGearPowers"][2]["image"]["url"]))
s_main = utils.translate_gear_ability(player["shoesGear"]["primaryGearPower"]["image"]["url"])
s_subs = []
if len(player["shoesGear"]["additionalGearPowers"]) > 0:
s_subs.append(utils.translate_gear_ability(player["shoesGear"]["additionalGearPowers"][0]["image"]["url"]))
if len(player["shoesGear"]["additionalGearPowers"]) > 1:
s_subs.append(utils.translate_gear_ability(player["shoesGear"]["additionalGearPowers"][1]["image"]["url"]))
if len(player["shoesGear"]["additionalGearPowers"]) > 2:
s_subs.append(utils.translate_gear_ability(player["shoesGear"]["additionalGearPowers"][2]["image"]["url"]))
return h_main, h_subs, c_main, c_subs, s_main, s_subs
def set_scoreboard(battle, tricolor=False):
'''Returns lists of player dictionaries: our_team_players, their_team_players, and optionally third_team_players.'''
# https://github.com/fetus-hina/stat.ink/wiki/Spl3-API:-Battle-%EF%BC%8D-Post#player-structure
our_team_players, their_team_players, third_team_players = [], [], []
for i, player in enumerate(battle["myTeam"]["players"]):
p_dict = {}
p_dict["me"] = "yes" if player["isMyself"] else "no"
p_dict["name"] = player["name"]
try:
p_dict["number"] = str(player["nameId"]) # splashtag # - can contain alpha chars too... (why!!!)
except KeyError: # may not be present if first battle as "Player"
pass
p_dict["splashtag_title"] = player["byname"] # splashtag title
p_dict["weapon"] = utils.b64d(player["weapon"]["id"])
p_dict["inked"] = player["paint"]
p_dict["species"] = player["species"].lower()
p_dict["rank_in_team"] = i+1
if player.get("crown"):
p_dict["crown_type"] = "x"
if "DRAGON" in player.get("festDragonCert", ""):
if player["festDragonCert"] == "DRAGON":
p_dict["crown_type"] = "100x"
elif player["festDragonCert"] == "DOUBLE_DRAGON":
p_dict["crown_type"] = "333x"
if "result" in player and player["result"] is not None:
p_dict["kill_or_assist"] = player["result"]["kill"]
p_dict["assist"] = player["result"]["assist"]
p_dict["kill"] = p_dict["kill_or_assist"] - p_dict["assist"]
p_dict["death"] = player["result"]["death"]
p_dict["special"] = player["result"]["special"]
p_dict["signal"] = player["result"]["noroshiTry"]
p_dict["disconnected"] = "no"
p_dict["crown"] = "yes" if player.get("crown") == True else "no"
# https://github.com/fetus-hina/stat.ink/wiki/Spl3-API:-Battle-%EF%BC%8D-Post#gears-structure
gear_struct = {"headgear": {}, "clothing": {}, "shoes": {}}
h_main, h_subs, c_main, c_subs, s_main, s_subs = populate_gear_abilities(player)
gear_struct["headgear"] = {"primary_ability": h_main, "secondary_abilities": h_subs}
gear_struct["clothing"] = {"primary_ability": c_main, "secondary_abilities": c_subs}
gear_struct["shoes"] = {"primary_ability": s_main, "secondary_abilities": s_subs}
p_dict["gears"] = gear_struct
else:
p_dict["disconnected"] = "yes"
our_team_players.append(p_dict)
team_nums = [0, 1] if tricolor else [0]
for team_num in team_nums:
for i, player in enumerate(battle["otherTeams"][team_num]["players"]):
p_dict = {}
p_dict["me"] = "no"
p_dict["name"] = player["name"]
try:
p_dict["number"] = str(player["nameId"])
except:
pass
p_dict["splashtag_title"] = player["byname"]
p_dict["weapon"] = utils.b64d(player["weapon"]["id"])
p_dict["inked"] = player["paint"]
p_dict["species"] = player["species"].lower()
p_dict["rank_in_team"] = i+1
if player.get("crown"):
p_dict["crown_type"] = "x"
if "DRAGON" in player.get("festDragonCert", ""):
if player["festDragonCert"] == "DRAGON":
p_dict["crown_type"] = "100x"
elif player["festDragonCert"] == "DOUBLE_DRAGON":
p_dict["crown_type"] = "333x"
if "result" in player and player["result"] is not None:
p_dict["kill_or_assist"] = player["result"]["kill"]
p_dict["assist"] = player["result"]["assist"]
p_dict["kill"] = p_dict["kill_or_assist"] - p_dict["assist"]
p_dict["death"] = player["result"]["death"]
p_dict["special"] = player["result"]["special"]
p_dict["signal"] = player["result"]["noroshiTry"]
p_dict["disconnected"] = "no"
p_dict["crown"] = "yes" if player.get("crown") == True else "no"
gear_struct = {"headgear": {}, "clothing": {}, "shoes": {}}
h_main, h_subs, c_main, c_subs, s_main, s_subs = populate_gear_abilities(player)
gear_struct["headgear"] = {"primary_ability": h_main, "secondary_abilities": h_subs}
gear_struct["clothing"] = {"primary_ability": c_main, "secondary_abilities": c_subs}
gear_struct["shoes"] = {"primary_ability": s_main, "secondary_abilities": s_subs}
p_dict["gears"] = gear_struct
else:
p_dict["disconnected"] = "yes"
if team_num == 0:
their_team_players.append(p_dict)
elif team_num == 1:
third_team_players.append(p_dict)
if tricolor:
return our_team_players, their_team_players, third_team_players
else:
return our_team_players, their_team_players
def prepare_battle_result(battle, ismonitoring, isblackout, overview_data=None):
'''Converts the Nintendo JSON format for a battle to the stat.ink one.'''
# https://github.com/fetus-hina/stat.ink/wiki/Spl3-API:-Battle-%EF%BC%8D-Post
payload = {}
battle = battle["vsHistoryDetail"]
## UUID ##
##########
try:
full_id = utils.b64d(battle["id"])
payload["uuid"] = str(uuid.uuid5(utils.S3S_NAMESPACE, full_id[-52:])) # input format: <YYYYMMDD>T<HHMMSS>_<uuid>
except TypeError:
print("Couldn't get the battle ID. This is likely an error on Nintendo's end; running the script again may fix it. Exiting.")
print('\nDebug info:')
print(json.dumps(battle))
sys.exit(1)
## MODE ##
##########
mode = battle["vsMode"]["mode"]
if mode == "REGULAR":
payload["lobby"] = "regular"
elif mode == "BANKARA":
if battle["bankaraMatch"]["mode"] == "OPEN":
payload["lobby"] = "bankara_open"
elif battle["bankaraMatch"]["mode"] == "CHALLENGE":
payload["lobby"] = "bankara_challenge"
elif mode == "PRIVATE":
payload["lobby"] = "private"
elif mode == "FEST":
if utils.b64d(battle["vsMode"]["id"]) in (6, 8): # open or tricolor
payload["lobby"] = "splatfest_open"
elif utils.b64d(battle["vsMode"]["id"]) == 7:
payload["lobby"] = "splatfest_challenge" # pro
elif mode == "X_MATCH":
payload["lobby"] = "xmatch"
elif mode == "LEAGUE": # challenge
payload["lobby"] = "event"
## RULE ##
##########
rule = battle["vsRule"]["rule"]
if rule == "TURF_WAR":
payload["rule"] = "nawabari" # could be splatfest too
elif rule == "AREA":
payload["rule"] = "area"
elif rule == "LOFT":
payload["rule"] = "yagura"
elif rule == "GOAL":
payload["rule"] = "hoko"
elif rule == "CLAM":
payload["rule"] = "asari"
elif rule == "TRI_COLOR":
payload["rule"] = "tricolor"
## STAGE ##
###########
payload["stage"] = utils.b64d(battle["vsStage"]["id"])
## WEAPON, K/D/A/S, PLAYER & TEAM TURF INKED ##
###############################################
for i, player in enumerate(battle["myTeam"]["players"]): # specified again in set_scoreboard()
if player["isMyself"] == True:
payload["weapon"] = utils.b64d(player["weapon"]["id"])
payload["inked"] = player["paint"]
payload["species"] = player["species"].lower()
payload["rank_in_team"] = i+1
# crowns (x rank and splatfest 'dragon') set in set_scoreboard()
if player["result"] is not None: # null if player disconnect
payload["kill_or_assist"] = player["result"]["kill"]
payload["assist"] = player["result"]["assist"]
payload["kill"] = payload["kill_or_assist"] - payload["assist"]
payload["death"] = player["result"]["death"]
payload["special"] = player["result"]["special"]
payload["signal"] = player["result"]["noroshiTry"] # ultra signal attempts in tricolor TW
break
try:
our_team_inked, their_team_inked = 0, 0
for player in battle["myTeam"]["players"]:
our_team_inked += player["paint"]
for player in battle["otherTeams"][0]["players"]:
their_team_inked += player["paint"]
payload["our_team_inked"] = our_team_inked
payload["their_team_inked"] = their_team_inked
except: # one of these might be able to be null? doubtful but idk lol
pass
## RESULT ##
############
result = battle["judgement"]
if result == "WIN":
payload["result"] = "win"
elif result in ("LOSE", "DEEMED_LOSE"):
payload["result"] = "lose"
elif result == "EXEMPTED_LOSE":
payload["result"] = "exempted_lose" # doesn't count toward stats
elif result == "DRAW":
payload["result"] = "draw"
## BASIC INFO & TURF WAR ##
###########################
if rule == "TURF_WAR" or rule == "TRI_COLOR": # could be turf war
try:
payload["our_team_percent"] = float(battle["myTeam"]["result"]["paintRatio"]) * 100
payload["their_team_percent"] = float(battle["otherTeams"][0]["result"]["paintRatio"]) * 100
except: # draw - 'result' is null
pass
else: # could be a ranked mode
try:
payload["knockout"] = "no" if battle["knockout"] is None or battle["knockout"] == "NEITHER" else "yes"
payload["our_team_count"] = battle["myTeam"]["result"]["score"]
payload["their_team_count"] = battle["otherTeams"][0]["result"]["score"]
except: # draw - 'result' is null
pass
## START/END TIMES ##
#####################
payload["start_at"] = utils.epoch_time(battle["playedTime"])
payload["end_at"] = payload["start_at"] + battle["duration"]
## SCOREBOARD & COLOR ##
########################
payload["our_team_color"] = utils.convert_color(battle["myTeam"]["color"])
payload["their_team_color"] = utils.convert_color(battle["otherTeams"][0]["color"])
if rule != "TRI_COLOR":
payload["our_team_players"], payload["their_team_players"] = set_scoreboard(battle)
else:
payload["our_team_players"], payload["their_team_players"], payload["third_team_players"] = set_scoreboard(battle, tricolor=True)
payload["third_team_color"] = utils.convert_color(battle["otherTeams"][1]["color"])
## SPLATFEST ##
###############
if mode == "FEST":
# paint %ages set in 'basic info'
payload["our_team_theme"] = battle["myTeam"]["festTeamName"]
payload["their_team_theme"] = battle["otherTeams"][0]["festTeamName"]
# NORMAL (1x), DECUPLE (10x), DRAGON (100x), DOUBLE_DRAGON (333x)
times_battle = battle["festMatch"]["dragonMatchType"]
if times_battle == "DECUPLE":
payload["fest_dragon"] = "10x"
elif times_battle == "DRAGON":
payload["fest_dragon"] = "100x"
elif times_battle == "DOUBLE_DRAGON":
payload["fest_dragon"] = "333x"
elif times_battle == "CONCH_SHELL_SCRAMBLE":
payload["conch_clash"] = "1x"
elif times_battle == "CONCH_SHELL_SCRAMBLE_10":
payload["conch_clash"] = "10x"
elif times_battle == "CONCH_SHELL_SCRAMBLE_33": # presumed
payload["conch_clash"] = "33x"
payload["clout_change"] = battle["festMatch"]["contribution"]
payload["fest_power"] = battle["festMatch"]["myFestPower"] # pro only
## TRICOLOR TW ##
#################
if mode == "FEST" and rule == "TRI_COLOR":
try:
payload["third_team_percent"] = float(battle["otherTeams"][1]["result"]["paintRatio"]) * 100
except TypeError:
pass
third_team_inked = 0
for player in battle["otherTeams"][1]["players"]:
third_team_inked += player["paint"]
payload["third_team_inked"] = third_team_inked
payload["third_team_theme"] = battle["otherTeams"][1]["festTeamName"]
payload["our_team_role"] = utils.convert_tricolor_role(battle["myTeam"]["tricolorRole"])
payload["their_team_role"] = utils.convert_tricolor_role(battle["otherTeams"][0]["tricolorRole"])
payload["third_team_role"] = utils.convert_tricolor_role(battle["otherTeams"][1]["tricolorRole"])
## ANARCHY BATTLES ##
#####################
if mode == "BANKARA":
# counts & knockout set in 'basic info'
payload["rank_exp_change"] = battle["bankaraMatch"]["earnedUdemaePoint"]
try: # if playing in anarchy open with 2-4 people, after 5 calibration matches
payload["bankara_power_after"] = battle["bankaraMatch"]["bankaraPower"]["power"]
except: # could be null in historical data
pass
battle_id = base64.b64decode(battle["id"]).decode('utf-8')
battle_id_mutated = battle_id.replace("BANKARA", "RECENT") # normalize the ID, make work with -M and -r
if overview_data is None: # no passed in file with -i
overview_post = requests.post(iksm.GRAPHQL_URL,
data=utils.gen_graphql_body(utils.translate_rid["BankaraBattleHistoriesQuery"]),
headers=headbutt(),
cookies=dict(_gtoken=GTOKEN))
try:
overview_data = [json.loads(overview_post.text)] # make the request in real-time in attempt to get rank, etc.
except:
overview_data = None
print("Failed to get recent Anarchy Battles. Proceeding without information on current rank.")
if overview_data is not None:
ranked_list = []
for screen in overview_data:
if "bankaraBattleHistories" in screen["data"]:
ranked_list = screen["data"]["bankaraBattleHistories"]["historyGroups"]["nodes"]
break
elif "latestBattleHistories" in screen["data"]: # early exports used this, and no bankaraMatchChallenge below
ranked_list = screen["data"]["latestBattleHistories"]["historyGroups"]["nodes"]
break
for parent in ranked_list: # groups in overview (anarchy tab) JSON/screen
for idx, child in enumerate(parent["historyDetails"]["nodes"]):
# same battle, different screens
overview_battle_id = base64.b64decode(child["id"]).decode('utf-8')
overview_battle_id_mutated = overview_battle_id.replace("BANKARA", "RECENT")
if overview_battle_id_mutated == battle_id_mutated: # found the battle ID in the other file
full_rank = re.split('([0-9]+)', child["udemae"].lower())
was_s_plus_before = len(full_rank) > 1 # true if "before" rank is s+
payload["rank_before"] = full_rank[0]
if was_s_plus_before:
payload["rank_before_s_plus"] = int(full_rank[1])
# anarchy battle (series) - not open
if "bankaraMatchChallenge" in parent and parent["bankaraMatchChallenge"] is not None:
# rankedup = parent["bankaraMatchChallenge"]["isUdemaeUp"]
ranks = ["c-", "c", "c+", "b-", "b", "b+", "a-", "a", "a+", "s"] # s+ handled separately
# rank-up battle
if parent["bankaraMatchChallenge"]["isPromo"] == True:
payload["rank_up_battle"] = "yes"
else:
payload["rank_up_battle"] = "no"
if parent["bankaraMatchChallenge"]["udemaeAfter"] is not None:
if idx != 0:
payload["rank_after"] = payload["rank_before"]
if was_s_plus_before: # not a rank-up battle, so must be the same
payload["rank_after_s_plus"] = payload["rank_before_s_plus"]
else: # the battle where we actually ranked up
full_rank_after = re.split('([0-9]+)', parent["bankaraMatchChallenge"]["udemaeAfter"].lower())
payload["rank_after"] = full_rank_after[0]
if len(full_rank_after) > 1:
payload["rank_after_s_plus"] = int(full_rank_after[1])
if idx == 0: # for the most recent battle in the series only
# send overall win/lose count
payload["challenge_win"] = parent["bankaraMatchChallenge"]["winCount"]
payload["challenge_lose"] = parent["bankaraMatchChallenge"]["loseCount"]
# send exp change (gain)
if payload["rank_exp_change"] is None:
payload["rank_exp_change"] = parent["bankaraMatchChallenge"]["earnedUdemaePoint"]
if DEBUG:
print(f'* {battle["judgement"]} {idx}')
print(f'* rank_before: {payload["rank_before"]}')
print(f'* rank_after: {payload["rank_after"]}')
print(f'* rank up battle: {parent["bankaraMatchChallenge"]["isPromo"]}')
print(f'* is ranked up: {parent["bankaraMatchChallenge"]["isUdemaeUp"]}')
if idx == 0:
print(f'* rank_exp_change: {parent["bankaraMatchChallenge"]["earnedUdemaePoint"]}')
else:
print(f'* rank_exp_change: 0')
break # found the child ID, no need to continue
## X BATTLES ##
###############
if mode == "X_MATCH":
# counts & knockout set in 'basic info'
if battle["xMatch"]["lastXPower"] is not None:
payload["x_power_before"] = battle["xMatch"]["lastXPower"]
battle_id = base64.b64decode(battle["id"]).decode('utf-8')
battle_id_mutated = battle_id.replace("XMATCH", "RECENT")
if overview_data is None: # no passed in file with -i
overview_post = requests.post(iksm.GRAPHQL_URL,
data=utils.gen_graphql_body(utils.translate_rid["XBattleHistoriesQuery"]),
headers=headbutt(),
cookies=dict(_gtoken=GTOKEN))
try:
overview_data = [json.loads(overview_post.text)] # make the request in real-time in attempt to get rank, etc.
except:
overview_data = None
print("Failed to get recent X Battles. Proceeding without some information on X Power.")
if overview_data is not None:
x_list = []
for screen in overview_data:
if "xBattleHistories" in screen["data"]:
x_list = screen["data"]["xBattleHistories"]["historyGroups"]["nodes"]
break
for parent in x_list: # groups in overview (x tab) JSON/screen
for idx, child in enumerate(parent["historyDetails"]["nodes"]):
overview_battle_id = base64.b64decode(child["id"]).decode('utf-8')
overview_battle_id_mutated = overview_battle_id.replace("XMATCH", "RECENT")
if overview_battle_id_mutated == battle_id_mutated:
if idx == 0:
# best of 5 for getting x power at season start, best of 3 after
payload["challenge_win"] = parent["xMatchMeasurement"]["winCount"]
payload["challenge_lose"] = parent["xMatchMeasurement"]["loseCount"]
if parent["xMatchMeasurement"]["state"] == "COMPLETED":
payload["x_power_after"] = parent["xMatchMeasurement"]["xPowerAfter"]
break
## CHALLENGES ##
################
if mode == "LEAGUE":
payload["event"] = battle["leagueMatch"]["leagueMatchEvent"]["id"] # send in Base64
payload["event_power"] = battle["leagueMatch"]["myLeaguePower"]
# luckily no need to look at overview screen for any info
# to check: any ranked-specific stuff for challenges in battle.leagueMatch...?
## MEDALS ##
############
medals = []
for medal in battle["awards"]:
medals.append(medal["name"])
payload["medals"] = medals
# no way to get: level_before/after, cash_before/after
payload["automated"] = "yes" # data was not manually entered!
if isblackout:
# fix payload
for player in payload["our_team_players"]:
if player["me"] == "no": # only black out others
player["name"] = None
player["number"] = None
player["splashtag_title"] = None
for player in payload["their_team_players"]:
player["name"] = None
player["number"] = None
player["splashtag_title"] = None
if "third_team_players" in payload:
for player in payload["third_team_players"]:
player["name"] = None
player["number"] = None
player["splashtag_title"] = None
# fix battle json
for player in battle["myTeam"]["players"]:
if not player["isMyself"]: # only black out others
player["name"] = None
player["nameId"] = None
player["byname"] = None
for team in battle["otherTeams"]:
for player in team["players"]:
player["name"] = None
player["nameId"] = None
player["byname"] = None
payload["splatnet_json"] = json.dumps(battle)
return payload
def prepare_job_result(job, ismonitoring, isblackout, overview_data=None, prevresult=None):
'''Converts the Nintendo JSON format for a Salmon Run job to the stat.ink one.'''
# https://github.com/fetus-hina/stat.ink/wiki/Spl3-API:-Salmon-%EF%BC%8D-Post
payload = {}
job = job["coopHistoryDetail"]
full_id = utils.b64d(job["id"])
payload["uuid"] = str(uuid.uuid5(utils.SALMON_NAMESPACE, full_id))
job_rule = job["rule"]
if job_rule in ("PRIVATE_CUSTOM", "PRIVATE_SCENARIO"):
payload["private"] = "yes"
else:
payload["private"] = "yes" if job["jobPoint"] is None else "no"
is_private = True if payload["private"] == "yes" else False
payload["big_run"] = "yes" if job_rule == "BIG_RUN" else "no"
payload["eggstra_work"] = "yes" if job_rule == "TEAM_CONTEST" else "no"
payload["stage"] = utils.b64d(job["coopStage"]["id"])
if job_rule != "TEAM_CONTEST": # not present for overall job in eggstra work
payload["danger_rate"] = job["dangerRate"] * 100
payload["king_smell"] = job["smellMeter"]
waves_cleared = job["resultWave"] - 1 # resultWave = 0 if all normal waves cleared
max_waves = 5 if job_rule == "TEAM_CONTEST" else 3
payload["clear_waves"] = max_waves if waves_cleared == -1 else waves_cleared
if payload["clear_waves"] < 0: # player dc'd
payload["clear_waves"] = None
elif payload["clear_waves"] != max_waves: # job failure
last_wave = job["waveResults"][payload["clear_waves"]]
if last_wave["teamDeliverCount"] >= last_wave["deliverNorm"]: # delivered more than quota, but still failed
payload["fail_reason"] = "wipe_out"
# xtrawave only
# https://stat.ink/api-info/boss-salmonid3
if job["bossResult"]:
try:
payload["king_salmonid"] = utils.b64d(job["bossResult"]["boss"]["id"])
except KeyError:
print("Could not send unsupported King Salmonid data to stat.ink. You may want to delete & re-upload this job later.")
payload["clear_extra"] = "yes" if job["bossResult"]["hasDefeatBoss"] else "no"
# https://stat.ink/api-info/salmon-title3
if not is_private and job_rule != "TEAM_CONTEST": # only in regular, not private or eggstra work
payload["title_after"] = utils.b64d(job["afterGrade"]["id"])
payload["title_exp_after"] = job["afterGradePoint"]
# never sure of points gained unless first job of rot - wave 3 clear is usu. +20, but 0 if playing w/ diff-titled friends
if job.get("previousHistoryDetail") != None:
prev_job_id = job["previousHistoryDetail"]["id"]
if overview_data: # passed in a file, so no web request needed
if prevresult:
# compare stage - if different, this is the first job of a rotation, where you start at 40
if job["coopStage"]["id"] != prevresult["coopHistoryDetail"]["coopStage"]["id"]:
payload["title_before"] = payload["title_after"] # can't go up or down from just one job
payload["title_exp_before"] = 40
else:
try:
payload["title_before"] = utils.b64d(prevresult["coopHistoryDetail"]["afterGrade"]["id"])
payload["title_exp_before"] = prevresult["coopHistoryDetail"]["afterGradePoint"]
except KeyError: # prev job was private or disconnect
pass
else:
prev_job_post = requests.post(iksm.GRAPHQL_URL,
data=utils.gen_graphql_body(utils.translate_rid["CoopHistoryDetailQuery"], "coopHistoryDetailId", prev_job_id),
headers=headbutt(forcelang='en-US'),
cookies=dict(_gtoken=GTOKEN))
try:
prev_job = json.loads(prev_job_post.text)
# do stage comparison again
if job["coopStage"]["id"] != prev_job["data"]["coopHistoryDetail"]["coopStage"]["id"]:
payload["title_before"] = payload["title_after"]
payload["title_exp_before"] = 40
else:
try:
payload["title_before"] = utils.b64d(prev_job["data"]["coopHistoryDetail"]["afterGrade"]["id"])
payload["title_exp_before"] = prev_job["data"]["coopHistoryDetail"]["afterGradePoint"]
except (KeyError, TypeError): # private or disconnect, or the json was invalid (expired job >50 ago) or something
pass
except json.decoder.JSONDecodeError:
pass
geggs = 0
peggs = job["myResult"]["deliverCount"]
for player in job["memberResults"]:
peggs += player["deliverCount"]
for wave in job["waveResults"]:
geggs += wave["teamDeliverCount"] if wave["teamDeliverCount"] != None else 0
payload["golden_eggs"] = geggs
payload["power_eggs"] = peggs
if job["scale"]:
payload["gold_scale"] = job["scale"]["gold"]
payload["silver_scale"] = job["scale"]["silver"]
payload["bronze_scale"] = job["scale"]["bronze"]
payload["job_score"] = job["jobScore"] # job score
payload["job_rate"] = job["jobRate"] # pay grade
payload["job_bonus"] = job["jobBonus"] # clear bonus
payload["job_point"] = job["jobPoint"] # your points = floor((score x rate) + bonus)
# note the current bug with "bonus" lol... https://github.com/frozenpandaman/s3s/wiki/%7C-splatnet-bugs
# species sent in player struct
translate_special = { # used in players and waves below
20006: "nicedama",
20007: "hopsonar",
20009: "megaphone51",
20010: "jetpack",
20012: "kanitank",
20013: "sameride",
20014: "tripletornado",
20017: "teioika",
20018: "ultra_chakuchi"
}
players = []
players_json = [job["myResult"]]
for teammate in job["memberResults"]:
players_json.append(teammate)
for i, player in enumerate(players_json):
player_info = {}
player_info["me"] = "yes" if i == 0 else "no"
player_info["name"] = player["player"]["name"]
player_info["number"] = player["player"]["nameId"]
player_info["splashtag_title"] = player["player"]["byname"]
player_info["golden_eggs"] = player["goldenDeliverCount"]
player_info["golden_assist"] = player["goldenAssistCount"]
player_info["power_eggs"] = player["deliverCount"]
player_info["rescue"] = player["rescueCount"]
player_info["rescued"] = player["rescuedCount"]
player_info["defeat_boss"] = player["defeatEnemyCount"]
player_info["species"] = player["player"]["species"].lower()
dc_indicators = [