-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupdater.py
More file actions
1878 lines (1806 loc) · 84.6 KB
/
updater.py
File metadata and controls
1878 lines (1806 loc) · 84.6 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__ import annotations
from typing import Any, Callable
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone, UTC
import asyncio
from pyreqwest.client import ClientBuilder, Client
import os
import sys
import re
import time
import json
from pathlib import Path
import traceback
import signal
import argparse
from tqdm import tqdm
### CONSTANT
VERSION = '5.15'
CONCURRENT_TASKS = 100
MAX_REQUEST = 60
BASE_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36'
SAVE_VERSION = 1
# addition type
ADD_JOB = 0
ADD_WEAP = 1
ADD_SUMM = 2
ADD_CHAR = 3
ADD_BOSS = 4
ADD_NPC = 5
ADD_PARTNER = 6
ADD_EVENT = 7
ADD_SKILL = 8
ADD_BUFF = 9
ADD_BG = 10
ADD_STORY0 = 11
ADD_FATE = 12
ADD_SHIELD = 13
ADD_MANATURA = 14
ADD_STORY1 = 15
# CDN endpoints
ENDPOINT = "https://prd-game-a-granbluefantasy.akamaized.net/assets_en/"
JS = ENDPOINT + "js/"
MANIFEST = JS + "model/manifest/"
CJS = JS + "cjs/"
IMG = ENDPOINT + "img/"
SOUND = ENDPOINT + "sound/"
VOICE = SOUND + "voice/"
# MC classes
CLASS = [
"csr_sw_{}_01", # sword
"gzk_kn_{}_01", # dagger
"aps_sp_{}_01", # spear
"bsk_ax_{}_01", # axe
"wrk_wa_{}_01", # staff
"rlc_gu_{}_01", # gun
"ogr_me_{}_01", # melee
"rbn_bw_{}_01", # bow
"els_mc_{}_01", # harp
"kng_kt_{}_01" # katana
]
CLASS_DEFAULT_WEAPON = {
"sw": "1010000000",
"kn": "1010100000",
"sp": "1010200000",
"ax": "1010300000",
"wa": "1010400000",
"gu": "1010500000",
"me": "1010600000",
"bw": "1010700000",
"mc": "1010800000",
"kt": "1010900000"
}
# for mp3 download
MP3_SEARCH = re.compile('"[a-zA-Z0-9_\\/]+\\.mp3"')
# dynamic constants
STYLE_CHARACTER : list[str] = []
NO_CHARGE_ATTACK : set[str] = set()
PATCHES : dict[str, list[str]] = {}
ID_SUBSTITUTE : dict[str, str] = {}
SHARED_SUMMONS : list[list[str]] = []
UNIQUE_SKIN : list[str] = []
CLASS_LIST : dict[str, list[str]] = {}
CLASS_WEAPON_LIST : dict[str, str] = {}
ORIGIN_CLASSES : list[str] = []
SUMMON_CLASS : str = ""
# load dynamic constants
try:
with open("json/manual_constants.json", mode="r", encoding="utf-8") as f:
globals().update(json.load(f)) # add to global scope
del f
except Exception as e:
print("Failed to load and set json/manual_constants.json")
print("Please fix the file content and try again")
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
raise Exception("Failed to load GBFAP Constants")
NO_CHARGE_ATTACK = set(NO_CHARGE_ATTACK)
# Handle tasks
@dataclass(slots=True)
class TaskManager():
is_running : bool
updater : Updater
queues : tuple[deque, ...]
workers : list[asyncio.Task]
work_available : asyncio.Event
all_done : asyncio.Event
total : int
finished : int
print_flag : bool
elapsed : float
pbar : tqdm|None
def __init__(self : TaskManager, updater : Updater) -> None:
self.is_running = False
self.updater = updater
self.queues = tuple(deque() for _ in range(5))
self.workers = []
self.work_available = asyncio.Event()
self.all_done = asyncio.Event()
self.total = 0
self.finished = 0
self.print_flag = False
self.elapsed = 0
self.pbar = None
# add a task to one queue
def add(self : TaskManager, awaitable : Callable, *, parameters : tuple[Any, ...]|None = None, priority : int = -1) -> None:
if priority < -1 or priority >= len(self.queues):
priority = - 1
self.queues[priority].append(
Task(
priority,
awaitable,
parameters or ()
)
)
self.total += 1
self.work_available.set()
async def _worker(self):
try:
task : Task|None
while True:
# wait for tasks to be available
await self.work_available.wait()
# get one (in order of queue priority)
task = None
for q in self.queues:
if q:
task = q.popleft()
break
if not task:
# if not, reset flag
self.work_available.clear()
continue
try:
# execute
await task.awaitable(*task.parameters)
except Exception as e:
self.print("The following exception occured:")
self.print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
finally:
self.finished += 1
if self.total != self.pbar.total:
self.pbar.total = self.total
self.pbar.update(1)
if self.finished >= self.total:
self.all_done.set()
except asyncio.CancelledError:
return
# run the tasks
async def run(self : TaskManager) -> None:
if self.is_running:
return
self.is_running = True
self.all_done.clear()
# start the workers pool
self.workers = [asyncio.create_task(self._worker()) for _ in range(CONCURRENT_TASKS)]
# set progress bar
if self.pbar is not None:
self.pbar.close()
self.pbar = tqdm(
total=self.total,
unit=" Task",
unit_scale=True,
unit_divisor=1000,
mininterval=2,
bar_format='{percentage:3.1f}%|{bar}{r_bar}'
)
try:
# wait until done
await self.all_done.wait()
finally:
# clean up
for w in self.workers:
w.cancel()
await asyncio.gather(*self.workers, return_exceptions=True)
self.pbar.close()
self.pbar = None
self.is_running = False
self.print("Complete")
# start to run queued tasks
async def start(self : TaskManager) -> bool:
if self.is_running: # return if already running or no tasks pending
return False
await self.run()
return True
def autosave(self : TaskManager) -> None:
if self.updater.modified:
self.print(f"Progress: {self.finished} / {self.total} Tasks, autosaving...")
self.updater.save()
self.updater.save_resume()
self.elapsed = time.time()
# print whatever you want, to use instead of print to handle the \r
def print(self : TaskManager, *args) -> None:
if self.pbar is not None:
self.pbar.write(" ".join(map(str, args)))
self.pbar.refresh()
else:
print(*args)
# called when CTRL+C is used
def interrupt(self : TaskManager, *args) -> None:
if self.total <= 0 or self.finished >= self.total:
return
print("\nProcess PAUSED")
print(f"{self.finished} / {self.total} Tasks completed")
if self.updater.modified:
print("Pending Data is waiting to be saved")
print("Type 'help' for a command list, or a command to execute, anything else to resume")
while True:
s = input(":").lower().split(' ')
match s[0]:
case 'help':
print("save - call the save() function")
print("exit - force exit the process, changes won't be saved, but resume file will be updated if used")
print("peek - check the content of data.json. Take two parameters: the index to look at and an id")
print("tchange - toggle update_changelog setting")
case 'save':
if not self.updater.modified:
print("No changes waiting to be saved")
else:
self.updater.save()
self.updater.save_resume()
case 'peek':
if len(s) < 3:
print("missing 1 parameter: ID")
elif len(s) < 2:
print("missing 2 parameters: index, ID")
else:
try:
d : Any = self.data[s[1]][s[2]]
print(s[1], '-', s[2])
print(d)
except Exception as e:
print("Can't read", s[1], '-', s[2])
print(e)
case 'tchange':
self.updater.update_changelog = not self.updater.update_changelog
print("changelog.json updated list WILL be modified" if self.updater.update_changelog else "changelog.json updated list won't be modified")
case 'exit':
print("Exiting...")
os._exit(0)
case _:
print("Process RESUMING...")
break
if self.pbar is not None:
self.pbar.refresh()
# A queued task
@dataclass(slots=True, order=True)
class Task:
priority: int
awaitable: Callable = field(compare=False)
parameters: tuple[Any, ...] = field(compare=False)
@dataclass(slots=True)
class TaskStatus():
index : int
max_index : int
err : int
max_err : int
running : int
_finished_event : asyncio.Event
def __init__(self : TaskStatus, max_index : int, max_err : int, *, start : int = 0, running : int = 0):
self.index = start
self.max_index = max_index
self.err = 0
self.max_err = max_err
self.running = running
self._finished_event = asyncio.Event()
def get_next_index(self : TaskStatus) -> int:
i : int = self.index
self.index += 1
return i
def good(self : TaskStatus) -> None:
self.err = 0
def bad(self : TaskStatus) -> None:
self.err += 1
@property
def complete(self : TaskStatus) -> bool:
return self.err >= self.max_err or self.index >= self.max_index
def finish(self : TaskStatus) -> None:
self.running -= 1
if self.running <= 0:
self._finished_event.set()
@property
def finished(self : TaskStatus) -> bool:
return self.running <= 0
async def wait_finish(self : TaskStatus) -> None:
if self.running > 0:
await self._finished_event.wait()
@dataclass(slots=True)
class Updater():
# other init
client : Client|None
http_limit : asyncio.Semaphore
tasks : TaskManager
update_changelog : bool
data : dict[str, Any]
modified : bool
addition : set[tuple[str, int|str]]
updated_elements : set[str]
gbfal : dict[str, Any]|None
def __init__(self : Updater):
# other init
self.client = None # the http client
self.http_limit = asyncio.Semaphore(MAX_REQUEST)
self.tasks = TaskManager(self) # the task manager
self.update_changelog = True # flag to enable or disable the generation of changelog.json
self.data = { # data structure
"version":SAVE_VERSION,
"characters":{},
"partners":{},
"summons":{},
"weapons":{},
"enemies":{},
"skins":{},
"job":{},
"background":{},
"mypage_bg":{},
"lookup":{},
"mypage":{},
"styles":{},
"mypage_styles":{}
}
self.modified = False # if set to true, data.json will be written on the next call of save()
self.addition = set() # new elements for changelog.json
self.updated_elements = set() # set of elements ran through update_element()
self.gbfal = None # storage for optional gbfal data
### Utility #################################################################################################################
# Load data.json
def load(self : Updater) -> None:
try:
# load file
with open('json/data.json', mode='r', encoding='utf-8') as f:
data : dict[str, Any] = json.load(f)
if not isinstance(data, dict):
return
# update if old version
data = self.retrocompatibility(data)
# load only expected keys
k : str
for k in self.data:
if k in data:
self.data[k] = data[k]
except OSError as e:
self.tasks.print(e)
if input("Continue anyway? (type 'y' to continue):").lower() != 'y':
os._exit(0)
except Exception as e:
self.tasks.print("The following error occured while loading data.json:")
self.tasks.print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
self.tasks.print(e)
os._exit(0)
# make older data.json compatible with newer versions
def retrocompatibility(self : Updater, data : dict[str, Any]) -> dict[str, Any]:
version = data.get("version", 0)
if version == 0:
self.tasks.print("This version is unsupported and might not work properly")
data["version"] = SAVE_VERSION
return data
# Save data.json and changelog.json (only if self.modified is True)
def save(self : Updater) -> None:
try:
if self.modified:
self.modified = False
# json.dump isn't used to keep the file small AND easily editable by hand
with open('json/data.json', mode='w', encoding='utf-8') as outfile:
# custom json indentation
outfile.write("{\n")
keys : list[str] = list(self.data.keys())
k : str
v : Any
for k, v in self.data.items():
outfile.write(f'"{k}":\n')
if isinstance(v, int): # INT
outfile.write(f'{v}\n')
if k != keys[-1]:
outfile.write(",")
outfile.write("\n")
elif isinstance(v, list): # LIST
outfile.write('[\n')
d : Any
for d in v:
json.dump(d, outfile, separators=(',', ':'), ensure_ascii=False)
if d is not v[-1]:
outfile.write(",")
outfile.write("\n")
outfile.write("]")
if k != keys[-1]:
outfile.write(",")
outfile.write("\n")
elif isinstance(v, dict): # DICT
outfile.write('{\n')
last : list[str] = list(v.keys())
if len(last) > 0:
last = last[-1]
i : int
d : Any
for i, d in v.items():
outfile.write(f'"{i}":')
json.dump(d, outfile, separators=(',', ':'), ensure_ascii=False)
if i != last:
outfile.write(",")
outfile.write("\n")
outfile.write("}")
if k != keys[-1]:
outfile.write(",")
outfile.write("\n")
outfile.write("}")
# changelog.json
stat : str|None
new : dict[str, list[Any]]
issues : list[str]
help : bool
try: # load its content
with open('json/changelog.json', mode='r', encoding='utf-8') as f:
data = json.load(f)
stat = data.get('stat', None)
issues = data.get('issues', [])
help = data.get('help', False)
new = data.get('new', {})
except:
new = {}
stat = None
issues = []
help = False
if self.update_changelog and len(self.addition) > 0: # update new content
# get date of today
now : str = datetime.now(UTC).strftime('%Y-%m-%d')
if now in new: # if date present
existing : set[tuple[str, int|str]] = {(e[0], e[1]) for e in new[now]} # get old data
for el in self.addition:
if el not in existing:
new[now].append(list(el))
else:
new[now] = [list(el) for el in self.addition] # else just set new data
# sort keys
keys : list[str]= list(new.keys())
keys.sort(reverse=True)
if len(keys) > 5: # and remove oldest
keys = keys[:5]
new = {k:new[k] for k in keys}
# sort updated one
new[now] = sorted(new[now], key=lambda x: (0 if isinstance(x[1], int) else 1, x[1], x[0]), reverse=True)
# clear self.addition
self.addition = set()
with open('json/changelog.json', mode='w', encoding='utf-8') as outfile: # the timestamp is upated below
json.dump({'timestamp':int(datetime.now(timezone.utc).timestamp()*1000), 'new':new, 'stat':stat, 'issues':issues, 'help':help}, outfile, indent=2, separators=(',', ':'), ensure_ascii=False)
if self.update_changelog:
self.tasks.print("data.json and changelog.json updated")
else:
self.tasks.print("data.json updated")
except Exception as e:
self.tasks.print(e)
self.tasks.print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
def add(self : Updater, element_id : str, element_type : int|str) -> None:
self.addition.add((element_id, element_type))
# Generic GET request function
async def get(self : Updater, url : str) -> Any:
async with self.http_limit:
response = (
await self.client.get(url)
.header("Accept-Encoding", "gzip")
.build()
.send()
)
if response.status != 200:
raise Exception(f"HTTP error {response.status}")
return (await response.bytes()).to_bytes()
# Generic HEAD request function
async def head(self : Updater, url : str) -> Any:
async with self.http_limit:
response = (
await self.client.head(url)
.build()
.send()
)
if response.status != 200:
raise Exception(f"HTTP error {response.status}")
return response.headers
async def head_manifest(self : Updater, js : str) -> None:
await self.head(MANIFEST + js + ".js")
# format a traceback
def trbk(self : Updater, e : Exception) -> str:
return "".join(traceback.format_exception(type(e), e, e.__traceback__))
def fetch_gbfal_data(self : Updater) -> None:
try:
# background import
if len(self.data["background"]) != len(self.gbfal["background"]):
self.data["background"] = self.gbfal["background"]
self.modified = True
self.tasks.print("New backgrounds imported from GBFAL")
if len(self.data["mypage_bg"]) != len(self.gbfal["mypage_bg"]):
self.data["mypage_bg"] = self.gbfal["mypage_bg"]
self.modified = True
self.tasks.print("New mypage backgrounds imported from GBFAL")
# class import
count : int = 0
for k, jd in self.gbfal["job"].items():
if k not in CLASS_LIST and k not in self.data["job"]:
CLASS_LIST[k] = self.gbfal['job'][k][6] # add mh
for x, v in self.gbfal['job_wpn'].items():
if v == k:
CLASS_WEAPON_LIST[k] = x # add class weapon
for i in range(len(CLASS_LIST[k])): # add missing classes
CLASS_LIST[k] = x + "_" + CLASS_LIST[k]
count += 1
else:
# mypage section
if len(jd[13]) > 0 and k not in self.data["mypage"]:
self.tasks.add(self.update_mypage, parameters=(k,))
self.tasks.print("New mypage animation found in GBFAL:", k)
if count > 0:
self.tasks.print("Found", count, "new classes in GBFAL")
# uncap check
table : dict[str, int] = {}
count = 0
for k, v in self.gbfal['characters'].items():
if isinstance(v, list):
max_uncap = 0
for e in v[6]: # seventh index for general ids
try:
u = int(e.split('_')[1])
if u < 10 and u > max_uncap: # store the highest uncap
max_uncap = u
except:
pass
if "_st2" in e: # check if it's a style
if k not in self.data["styles"]:
self.tasks.add(self.update_character, parameters=(k, "_st2"))
count += 1
if max_uncap > 0: # add to table if not 0
table[k] = max_uncap
# mypage section
if len(v[9]) > 0 and k not in self.data["mypage"]:
self.tasks.add(self.update_mypage, parameters=(k,))
self.tasks.print("New mypage animation found in GBFAL:", k)
for k, v in self.gbfal['summons'].items(): # do the same for summons
if isinstance(v, list):
max_uncap = 0
for e in v[0]: # first index for general ids
try:
u = int(e.split('_')[1])
except:
u = 1
if u < 10 and u > max_uncap:
max_uncap = u
if max_uncap > 0:
table[k] = max_uncap
# mypage section
if len(v[3]) > 0 and k not in self.data["mypage"]:
self.tasks.add(self.update_mypage, parameters=(k,))
self.tasks.print("New mypage animation found in GBFAL:", k)
for t in ("characters", "summons"):
for k, v in self.data[t].items(): # now go over our items and our uncap table and comapre
if k in table:
if 'v' in v:
max_uncap = 0
if k[0] == '3': # character
for e in v['v']:
u = 0
match e[0].split('★')[0]:
case '0':
u = 1
case '4':
u = 2
case '5':
u = 3
case '6':
u = 4
if u < 10 and u > max_uncap:
max_uncap = u
if table[k] > max_uncap:
self.tasks.add(self.update_character, parameters=(k,))
count += 1
elif k[0] == '2': # summon
for e in v['v']:
u = 0
match e[0].split('★')[0]:
case '3':
u = 1
case '4':
u = 2
case '5':
u = 3
case '6':
u = 4
if u < 10 and u > max_uncap:
max_uncap = u
if table[k] > max_uncap:
self.tasks.add(self.update_summon, parameters=(k,))
count += 1
else: # failsafe
continue
if count > 0:
self.tasks.print(count, "possible uncap/style(s) found in GBFAL")
# enemy appear
for k in self.data["enemies"]:
if k in self.gbfal["enemies"]:
if len(self.gbfal["enemies"][k][2]) > 0: # index 2
# add 'ra' list if missing
if "ra" not in self.data["enemies"][k]:
self.data["enemies"][k]["ra"] = []
modified = False
for f in self.gbfal["enemies"][k][2]:
parts = f.split(".png", 1)[0].split("_")
if len(parts) == 3:
appear = "_".join(parts)
if appear not in self.data["enemies"][k]["ra"]:
self.data["enemies"][k]["ra"].append(appear)
modified = True
elif len(parts) > 3:
if parts[3] in ("1", "2", "3", "4", "5", "6", "7", "8", "9", "shade"):
appear = "_".join(parts[:4])
if appear not in self.data["enemies"][k]["ra"]:
self.data["enemies"][k]["ra"].append(appear)
modified = True
if modified:
self.data["enemies"][k]["ra"].sort()
self.add(k, ADD_BOSS)
self.modified = True
except Exception as e:
self.tasks.print("Failed to fetch GBFAL data:\n", self.trbk(e))
def import_gbfal_lookup(self : Updater) -> None:
try:
if self.data["lookup"] != self.gbfal["lookup"]:
self.data["lookup"] = self.gbfal["lookup"]
self.modified = True
except Exception as e:
self.tasks.print("Failed to import GBFAL lookup:\n", self.trbk(e))
### Main #################################################################################################################
# called by -run
async def run(self : Updater) -> None:
# classes
self.tasks.add(self.check_classes)
#rarity of various stuff
for r in range(1, 5):
# weapons
for j in range(10):
ts = TaskStatus(1000, 15)
for i in range(5):
self.tasks.add(self.update_element, parameters=(ts, 'weapons', str(r)+"0"+str(j)))
# summons
ts = TaskStatus(1000, 15)
for i in range(5):
self.tasks.add(self.update_element, parameters=(ts, 'summons', str(r)))
if r > 1:
# characters
ts = TaskStatus(1000, 15)
for i in range(5):
self.tasks.add(self.update_element, parameters=(ts, 'characters', str(r)))
# skins
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.update_element, parameters=(ts, 'skins'))
# enemies
main : int
sub : int
for main in range(1, 10):
for sub in range(1, 4):
ts = TaskStatus(10000, 40)
prefix : str = str(main) + str(sub)
for i in range(10):
self.tasks.add(self.update_element, parameters=(ts, 'enemies', prefix))
# start the tasks
await self.tasks.start()
### Update #################################################################################################################
# Attempt to update all given element ids
async def update_all(self : Updater, elements : list[str]) -> None:
element_id : str
for element_id in elements:
if len(element_id) >= 10:
match element_id[:2]:
case "30"|"37"|"38":
try:
main, style = element_id.split("_", 1)
style = "_" + style
except:
main = element_id
style = ""
self.tasks.add(self.update_character, parameters=(main, style))
case "20":
self.tasks.add(self.update_summon, parameters=(element_id.split("_", 1)[0],))
case "10":
self.tasks.add(self.update_weapon, parameters=(element_id.split("_", 1)[0],))
elif len(element_id) >= 7:
self.tasks.add(self.update_enemy, parameters=(element_id,))
elif len(element_id) == 6:
self.tasks.add(self.update_class, parameters=(element_id,))
await self.tasks.start()
# run subroutine
async def update_element(self : Updater, ts : TaskStatus, target : str, extra : str = "") -> None:
match target:
case "characters":
while not ts.complete:
i : int = ts.get_next_index()
element_id : str = f"30{extra}0{i:03}000"
if (element_id in self.data[target]
or await self.update_character(element_id)):
ts.good()
else:
ts.bad()
case "skins":
while not ts.complete:
i : int = ts.get_next_index()
element_id : str = f"3710{i:03}000"
if (element_id in self.data[target]
or await self.update_character(element_id)):
ts.good()
else:
ts.bad()
case "summons":
while not ts.complete:
i : int = ts.get_next_index()
element_id : str = f"20{extra}0{i:03}000"
if (element_id in self.data[target]
or await self.update_summon(element_id)):
ts.good()
else:
ts.bad()
case "weapons":
while not ts.complete:
i : int = ts.get_next_index()
element_id : str = f"10{extra}{i:03}00"
if (element_id in self.data[target]
or await self.update_weapon(element_id)):
ts.good()
else:
ts.bad()
case "enemies":
while not ts.complete:
i : int = ts.get_next_index()
found : bool = False
for j in range(1, 4):
element_id : str = f"{extra}{i:04}{j}"
if (element_id in self.data[target]
or await self.update_enemy(element_id)):
found = True
if found:
ts.good()
else:
ts.bad()
async def update_mypage(self : Updater, element_id : str, style : str = "") -> bool:
try:
add_type = None
if len(element_id) == 10: # summons/characters
match element_id[:2]:
case "20":
suffixes = [style, "_02"+style, "_03"+style, "_04"+style, "_05"+style]
add_type = ADD_SUMM
case "30"|"37":
suffixes = await self.get_mypage_list(element_id, style)
add_type = ADD_CHAR
case _:
self.tasks.print("Unsupported ID " + element_id + " for update_mypage")
return False
elif len(element_id) == 6: # classes
suffixes = []
ci : str = CLASS_LIST[element_id][0].split("_")[1]
for g in range(0, 2):
suffixes.append(f"_{ci}_{g}_01")
add_type = ADD_JOB
else:
self.tasks.print("Unsupported ID " + element_id + " for update_mypage")
return False
character_data = {"v":[]}
for uncap in suffixes:
try:
f : str = "mypage_" + element_id + uncap
await self.head_manifest(f)
character_data["v"].append(
[
(
(
"Style "
if style != ""
else ""
) + str(len(character_data["v"]) + 1)
),
f,
None,
None,
[]
]
)
except:
pass
if len(character_data["v"]) == 0:
return False
index = "mypage" if style == "" else "mypage_styles"
if str(character_data) != str(self.data[index].get(element_id, None)):
self.data[index][element_id] = character_data
self.modified = True
if add_type is not None:
self.add(element_id, add_type)
self.tasks.print("Updated", element_id, "for", index)
return True
except Exception as e:
self.tasks.print(f"Exception for id: {element_id}, with style: {style}\n{self.trbk(e)}")
return False
# search for existing mypage arts
async def get_mypage_list(self : Updater, element_id : str, style : str) -> list[str]:
suffixes : list[str] = []
i : int
for i in (0, 80, 90):
j : int
for j in range(1, 10):
uncap : str = str(i + j).zfill(2)
found : bool = False
task_params : list = []
for n in ("", "_01"): # null (lyria...)
for g in ("", "_0", "_1"): # gender
for m in ("", "_101", "_102", "_103", "_104"): # multi
task_params.append((element_id, "_{}{}{}{}{}".format(uncap, style, g, m, n)))
futures = await asyncio.gather(*[self.get_mypage_list_sub(*p) for p in task_params])
for future in futures:
if future is not None:
suffixes.append(future)
found = True
if not found:
break
return suffixes
async def get_mypage_list_sub(self : Updater, element_id : str, suffix : str) -> str|None:
try:
await self.head(IMG + f"sp/assets/npc/my/{element_id}{suffix}.png")
return suffix
except:
return None
# custom sort for the version sorting of characters
def name_sort(self : Updater, name : str):
parts : list[str] = name.split(' ')
star : int
if "Style" in name:
p : list[str] = name.split("Style")
if p[1].strip() == "":
p[1] = "1"
star = int(p[1])
else:
star = int(parts[0].replace('★', ''))
name_order : int = 0
if len(parts) > 1:
if parts[1] == 'Gran':
name_order = 1
elif parts[1] == 'Djeeta':
name_order = 2
version_letter = ''
if len(parts) > 2:
version_letter = parts[-1]
return (star, name_order, version_letter)
async def update_character(self : Updater, element_id : str, style : str = "") -> bool:
try:
if element_id + style in self.updated_elements:
return False
self.updated_elements.add(element_id + style)
is_partner : bool = element_id.startswith("38")
is_special_partner : bool = element_id.startswith("388")
if is_partner and element_id.startswith("389"):
return await self.update_partner_main_character(element_id)
is_skin : bool = element_id.startswith("37")
try:
if is_partner:
await self.head(IMG + f"/sp/assets/npc/raid_normal/{element_id}_01.jpg")
else:
await self.head(IMG + f"/sp/assets/npc/m/{element_id}_01.jpg")
except:
return False
if not is_partner and not is_skin and style == "":
try:
await self.head(IMG + f"/sp/assets/npc/m/{element_id}_01_st2.jpg")
self.tasks.add(self.update_character, parameters=(element_id, "_st2"))
except:
pass
tid = ID_SUBSTITUTE.get(element_id, element_id) # fix for bobobo skin
versions = {}
genders = {}
gender_ougis = {}
mortals = {}
phits = {}
nsp = {}
for uncap in range(1, 6):
su = str(uncap).zfill(2) # uncap string, i.e. 01, 02, etc...
found = False
for gender in ("", "_0", "_1"): # gender check (vgrim, catura, etc..)
for ftype in ("", "_s2"): # version (s2 is newer)
for form in ("", "_f1", "_f2", "_f"): # alternate stance/form (rosetta, nicholas, etc...)
full_id : str = f"{tid}_{su}{style}{gender}{form}{ftype}"
try:
fn = "npc_" + full_id # create full filename
await self.head_manifest(fn) # check if exists, exception is raised otherwise
vs = su + gender + ftype + form
versions[vs] = fn # add in found versions
if gender != "":
genders[vs] = gender # add in gender versions
# get cjs
data = (await self.get(CJS + fn + ".js")).decode('utf-8') # retrieve the content for the following
if vs not in mortals: # for characters such as lina
for m in ('mortal_A', 'mortal_B', 'mortal_C', 'mortal_D', 'mortal_E', 'mortal_F', 'mortal_G', 'mortal_H', 'mortal_I', 'mortal_K'):
if m in data: # we check which mortal (i.e. ougi) is found in the file, as some don't have the mortal_A
mortals[vs] = m
break
if form == "":
found = True
try: # check attacks
fn = f"phit_{full_id}".replace("_01", "")
await self.head_manifest(fn)
phits[vs] = fn
except:
try: # check simpler attack if not found
fn = f"phit_{tid}_{su}{style}".replace("_01", "")
await self.head_manifest(fn)
phits[vs] = fn
except: # if still not found, retrieve from lower uncaps
for sub_uncap in range(uncap-1, 0, -1):
ssu = str(sub_uncap).zfill(2)
for k in phits:
if k.startswith(ssu):
phits[vs] = phits[k]
break
if vs in phits:
break
if vs not in phits: # if STILL not found, apply patch if any
if tid in PATCHES and PATCHES[tid][1] != "":
phits[vs] = PATCHES[tid][1].replace('UU', su).replace('FF', form)
else: # else use default axe animation
phits[vs] = 'phit_ax_0001'
if full_id not in NO_CHARGE_ATTACK:
for s in ("", "_s2", "_s3"): # check ougi
for g in (("", "_0") if gender == "" else (gender,)): # and gender
tasks = []
for m in ("", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_h", "_i", "_j"): # and variations for multiple ougi like shiva grand
tasks.append(self.update_character_sub(f"nsp_{tid}_{su}{style}{g}{form}{s}{m}"))
tmp = []
for r in await asyncio.gather(*tasks):
if r is not None:
tmp.append(r)