-
Notifications
You must be signed in to change notification settings - Fork 1
/
updater.py
3654 lines (3527 loc) · 183 KB
/
updater.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
import asyncio
import aiohttp
import sys
import re
import json
import time
import string
import html
import os
import signal
from datetime import datetime, timezone, timedelta
import traceback
from typing import Optional, Callable, Collection, AsyncIterator, Any, Iterator, Union
# progress bar class
class Progress():
def __init__(self, parent : 'Updater', *, total : int = 9999999999999, silent : bool = True, current : int = 0) -> None: # set to silent with a high total by default
self.silent = silent
self.total = total
self.current = current - 1
self.start_time = time.time()
self.elapsed = self.start_time
self.parent = parent
self._prev_percents_ = ("", "")
if self.total > 0: self.update()
def progress2str(self) -> str: # convert the percentage to a valid string
s = "{:.2f}".format(100 * self.current / float(self.total))
if s == self._prev_percents_[0]: # use cached result if same string
return self._prev_percents_[1]
l = len(s)
while s[l-1] == '0' or s[l-1] == '.': # remove trailing 0 up to the dot (included)
l -= 1
if s[l] == '.':
break
self._prev_percents_ = (s, s[:l]) # cache the result
return s[:l]
def set(self, *, total : int = 0, silent : bool = False) -> None: # to initialize it after a task start, once we know the total
if total >= 0:
self.total = total
self.silent = silent
if not self.silent and self.total > 0:
sys.stdout.write("\rProgress: {}% ".format(self.progress2str()))
sys.stdout.flush()
def update(self) -> None: # to call to update the progress text (if not silent and not done)
if self.current < self.total:
self.current += 1
if self.parent is not None and time.time() - self.elapsed >= 3600: # 1h passed, autosave (if set)
if self.silent:
sys.stdout.write("\r")
else:
print("\rState: {}/{} - Autosaving...".format(self.current, self.total))
self.elapsed = time.time()
self.parent.save()
if not self.silent:
sys.stdout.write("\rProgress: {}% ".format(self.progress2str()))
sys.stdout.flush()
if self.current >= self.total:
diff = time.time() - self.start_time # elapsed time
# format to H:M:S
x = int((diff - int(diff)) * 100)
diff = int(diff)
h = diff // 3600
m = (diff % 3600) // 60
s = diff % 60
p = ""
if h > 0: p += str(h).zfill(2) + "h"
if m > 0 or p != "": p += str(m).zfill(2) + "m"
p += str(s).zfill(2)
if x > 0: p += "." + str(x).zfill(2)
p += "s"
print("\nRun time: {}".format(p))
def __enter__(self): # to use 'WITH'
pass
def __exit__(self, type, value, traceback):
self.update() # updated on exit
# main class
class Updater():
### CONSTANT
# limit
MAX_NEW = 80
MAX_UPDATE = 80
MAX_HTTP = 90
MAX_UPDATEALL = MAX_HTTP+10
MAX_HTTP_WIKI = 20
MAX_SCENE_CONCURRENT = 10
SOUND_CONCURRENT_PER_STEP = 4
LOOKUP_TYPES = ['characters', 'summons', 'weapons', 'job', 'skins', 'npcs']
# 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_STORY = 11
PREEMPTIVE_ADD = set(["characters", "enemies", "summons", "skins", "weapons", "partners", "npcs", "background"])
ADD_SINGLE_ASSET = ["title", "subskills", "suptix"]
# chara/skin/partner update
CHARA_SPRITE = 0
CHARA_PHIT = 1
CHARA_SP = 2
CHARA_AB_ALL = 3
CHARA_AB = 4
CHARA_GENERAL = 5
CHARA_SD = 6
CHARA_SCENE = 7
CHARA_SOUND = 8
CHARA_SPECIAL_REUSE = {"3710171000":"3710167000","3710170000":"3710167000","3710169000":"3710167000","3710168000":"3710167000"} # bobobo skins reuse bobobo data
# npc update
NPC_JOURNAL = 0
NPC_SCENE = 1
NPC_SOUND = 2
# MC update
JOB_ID = 0
JOB_ALT = 1
JOB_DETAIL = 2
JOB_DETAIL_ALT = 3
JOB_DETAIL_ALL = 4
JOB_SD = 5
JOB_MH = 6
JOB_SPRITE = 7
JOB_PHIT = 8
JOB_SP = 9
JOB_UNLOCK = 10
# summon update
SUM_GENERAL = 0
SUM_CALL = 1
SUM_DAMAGE = 2
# weapon update
WEAP_GENERAL = 0
WEAP_PHIT = 1
WEAP_SP = 2
# enemy update
BOSS_GENERAL = 0
BOSS_SPRITE = 1
BOSS_APPEAR = 2
BOSS_HIT = 3
BOSS_SP = 4
BOSS_SP_ALL = 5
# event update
EVENT_CHAPTER_COUNT = 0
EVENT_THUMB = 1
EVENT_OP = 2
EVENT_ED = 3
EVENT_INT = 4
EVENT_CHAPTER_START = 5
EVENT_MAX_CHAPTER = 20
EVENT_SKY = EVENT_CHAPTER_START+EVENT_MAX_CHAPTER
EVENT_UPDATE_COUNT = 20
# story update
STORY_CONTENT = 0
STORY_UPDATE_COUNT = 10
# common to story, event
SCENE_UPDATE_STEP = 5
# job update
MAINHAND = ['sw', 'wa', 'kn', 'me', 'bw', 'mc', 'sp', 'ax', 'gu', 'kt'] # weapon type keywords
# 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/"
# regex
ID_REGEX = re.compile("[123][07][1234]0\\d{4}00")
VERSION_REGEX = re.compile("\\/assets\\/(\d+)\\/")
CHAPTER_REGEX = re.compile("Chapter (\d+)(-(\d+))?")
# others
SAVE_VERSION = 1
LOAD_EXCLUSION = ['version']
QUEUE_KEY = ['uncap_queue', 'scene_queue', 'sound_queue']
STRING_CHAR = string.ascii_lowercase + string.digits
MISSING_EVENTS = ["201017", "211017", "221017", "231017", "241017", "200214", "210214", "220214", "230214", "240214", "200314", "210316", "220304", "220313", "230303", "230314", "240305", "240312", "201216", "211216", "221216", "231216", "241216", "200101", "210101", "220101", "230101", "240101"] + ["131201", "140330", "160430", "161031", "161227", "170501", "170801", "171129", "180301", "180310", "180403", "180428", "180503", "180603", "180623", "180801", "180813", "181214", "190310", "190427", "190801", "191004", "191222", "200222", "200331", "200801", "201209", "201215", "201222", "210222", "210303", "210310", "210331", "210801", "210824", "210917", "220105", "220222", "220520", "220813", "230105", "230209", "230222", "230331", "230429", "230616", "230813", "220307", "210303", "190307", "231215", "231224", "240107", "240222", "240331", "200304"]
SPECIAL_EVENTS = {
"221121":"221121_arcarum_maria",
"230322":"230322_arcarum_caim",
"230515":"230515_arcarum_nier",
"230607":"230607_arcarum_estarriola",
"230723":"230723_arcarum_fraux",
"230816":"230816_arcarum_lobelia",
"231007":"231007_arcarum_geisenborger",
"231114":"231114_arcarum_haaselia",
"240122":"240122_arcarum_alanaan",
"240322":"240322_arcarum_katzelia",
"241017":"20241017",
"241206":"terra_anre_feower",
"babyl0":"babeel_01",
"dread0":"dreadbarrage",
"alchm0":"kaitaku_renkin_hwop",
"sandb0":"arcarum_sandbox"
}
CUT_CONTENT = ["2040145000","2040146000","2040147000","2040148000","2040149000","2040150000","2040151000","2040152000","2040153000","2040154000","2040200000","2020001000"] # beta arcarum ids
SHARED_NAMES = [["2030081000", "2030082000", "2030083000", "2030084000"], ["2030085000", "2030086000", "2030087000", "2030088000"], ["2030089000", "2030090000", "2030091000", "2030092000"], ["2030093000", "2030094000", "2030095000", "2030096000"], ["2030097000", "2030098000", "2030099000", "2030100000"], ["2030101000", "2030102000", "2030103000", "2030104000"], ["2030105000", "2030106000", "2030107000", "2030108000"], ["2030109000", "2030110000", "2030111000", "2030112000"], ["2030113000", "2030114000", "2030115000", "2030116000"], ["2030117000", "2030118000", "2030119000", "2030120000"], ["2040236000", "2040313000", "2040145000"], ["2040237000", "2040314000", "2040146000"], ["2040238000", "2040315000", "2040147000"], ["2040239000", "2040316000", "2040148000"], ["2040240000", "2040317000", "2040149000"], ["2040241000", "2040318000", "2040150000"], ["2040242000", "2040319000", "2040151000"], ["2040243000", "2040320000", "2040152000"], ["2040244000", "2040321000", "2040153000"], ["2040245000", "2040322000", "2040154000"], ["1040019500", '1040008000', '1040008100', '1040008200', '1040008300', '1040008400'], ["1040112400", '1040107300', '1040107400', '1040107500', '1040107600', '1040107700'], ["1040213500", '1040206000', '1040206100', '1040206200', '1040206300', '1040206400'], ["1040311500", '1040304900', '1040305000', '1040305100', '1040305200', '1040305300'], ["1040416400", '1040407600', '1040407700', '1040407800', '1040407900', '1040408000'], ["1040511800", '1040505100', '1040505200', '1040505300', '1040505400', '1040505500'], ["1040612300", '1040605000', '1040605100', '1040605200', '1040605300', '1040605400'], ["1040709500", '1040704300', '1040704400', '1040704500', '1040704600', '1040704700'], ["1040811500", '1040804400', '1040804500', '1040804600', '1040804700', '1040804800'], ["1040911800", '1040905000', '1040905100', '1040905200', '1040905300', '1040905400'], ["2040306000","2040200000"]]
UNIQUE_SKIN = ["311301", "311302"]
SPECIAL_LOOKUP = { # special elements
"3020065000": "R brown poppet trial",
"3030158000": "SR blue poppet trial",
"3040097000": "SSR sierokarte trial",
"2030004000": "fire SR cut-content",
"2030014000": "dark SR cut-content",
"2020001000": "earth SR goblin cut-content",
"3040114000": "SSR cut-content",
# missing skins
"3710196000": "cassius parasol and hakama of prosperity",
"3710117000": "meteon a comet's calm",
"3710183000": "young cat black with golden eyes",
"3710184000": "young cat ginger tabby",
"3710182000": "young cat milky white shorthair",
"3710015000": "lina"
}
MALINDA = "3030093000"
PARTNER_STEP = 10
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Rosetta/Dev'
# scene string
SCENE_SUFFIXES = {
"default": {
"base": ["", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_nalhe", "_school", "_astral", "_battle", "_off", "_race", "_cavalry", "_guardian", "_cook", "_orange", "_blue", "_green", "_nude", "_mask", "_doll", "_girl", "_cow", "_two", "_three", "_2021", "_2022", "_2023", "_2024"],
"main": ["", "_a", "_b", "_c", "_d", "_e", "_f", "_g", "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9", "_10", "_up", "_laugh", "_laugh_small", "_laugh2", "_laugh3", "_laugh4", "_laugh5", "_laugh6", "_laugh7", "_laugh8", "_laugh9", "_wink", "_wink2", "_shout", "_shout2", "_shout3", "_leer", "_sad", "_sad2", "_sad3","_angry", "_angry2", "_angry3", "_angry4", "_roar", "_fear", "_fear2", "_cry", "_cry2", "_painful", "_painful2", "_painful3", "_painful4", "_shadow", "_shadow2", "_shadow3", "_light", "_close", "_serious", "_serious2", "_serious3", "_serious4", "_serious5", "_serious6", "_serious7", "_serious8", "_serious9", "_serious10", "_serious11", "_surprise", "_surprise2", "_surprise3", "_surprise4", "_think", "_think2", "_think3", "_think4", "_think5", "_serious", "_serious2", "_mood", "_mood2", "_mood3", "_despair", "_despair2", "_badmood", "_badmood2", "_ecstasy", "_ecstasy2", "_suddenly", "_suddenly2", "_speed2", "_shy", "_shy2", "_shy3", "_shy4", "_weak", "_weak2", "_sleep", "_sleepy", "_open", "_eye", "_bad", "_bad2", "_amaze", "_amaze2", "_amezed", "_joy", "_joy2", "_pride", "_pride2", "_jito", "_intrigue", "_intrigue2", "_pray", "_motivation", "_melancholy", "_concentration", "_mortifying", "_cold", "_cold2", "_cold3", "_cold4", "_weapon", "_stance", "_hood", "_letter", "_gesu", "_gesu2", "_stump", "_stump2", "_doya", "_fight", "_2021", "_2022", "_2023", "_2024", "_2025", "_all", "_all2", "_pinya", "_ef", "_ef_left", "_ef_right", "_ef2", "_body", "_front", "_head", "_up_head", "_foot", "_back", "_middle", "_middle_left", "_middle_right", "_left", "_right", "_move", "_move2", "_jump", "_small", "_big", "_pair_1", "_pair_2", "_break", "_break2", "_break3", "_ghost", "_stand", "_two", "_three", "_stand", "_eyeline"],
"unique": ["_valentine", "_valentine2", "_valentine3", "_white", "_whiteday", "_whiteday1", "_whiteday2", "_whiteday3", "_summer", "_summer2", "_halloween", "_sturm", "_rabbit"],
"end": ["", "_a", "_b", "_b1", "_b2", "_b3", "_speed", "_line", "_up", "_up_speed", "_up_damage", "_up_line", "_up2", "_up3", "_up4", "_down", "_shadow", "_shadow2", "_shadow3", "_damage", "_damage_up", "_light", "_up_light", "_light_speed", "_vanish", "_vanish1", "_vanish2", "_fadein1", "_blood", "_up_blood"]
},
"3050000000": { # lyria
"base": ["_muffler", "_swim"],
"unique": ["_jewel", "_jewel2", "_birthday", "_birthday1", "_birthday2", "_birthday3", "_birthday4", "_birthday5"]
},
"3050001000": { # vyrn
"unique": ["_birthday", "_birthday1", "_birthday2", "_birthday3", "_birthday4", "_birthday5"]
},
"3992852000": { # gold slime
"unique": ["_jewel"]
},
"3990219000": { # mc (gran)
"base": ["_dancer", "_mechanic", "_glory", "_kengo", "_monk", "_lumberjack", "_robinhood", "_horse", "_paladin", "_panakeia", "_manadiver", "_king", "_sumou", "_eternals", "_eternals2"]
},
"3990002000": { # bk
"base": ["_m"],
"main": ["_off"]
},
"3030280000": { # sr joi
"main": ["_off"]
},
"3030006000": { # sr io
"base": ["_new"]
},
"3990326000": { # veight
"base": ["_knife"]
},
"3991542000": { # rackam
"base": ["_cigarette"]
},
"3991849000": { # shadowverse cards
"unique": ["_03", "_06", "_09", "_10", "_11", "_12", "_19", "_20", "_21", "_22", "_25", "_30", "_31", "_32", "_37", "_40"]
},
"3993542000": { # marks
"unique": ["_02", "_03", "_04", "_05", "_06", "_07", "_08", "_09", "_10"]
},
"3990135000": { # thug
"base": ["_town"],
"main": ["_thug"]
},
"3990162000": { # gastalga
"main": ["_child1", "_child2"]
},
"3990465000": { # teepo
"main": ["_chara"]
},
"3992265000": { # teepo
"base": ["_helicopter"]
},
"3991666000": { # seox
"base": ["_mask", "_halfmask"]
},
"3991829000": { # anthony
"unique": ["_narrator"]
},
"3992169000": { # tsubasa
"unique": ["_skin", "_skin_01", "_skin_02", "_skin_03"]
},
"3992888000": { # makura
"unique": ["_rabbit1", "_rabbit2", "_rabbit3", "_rabbit4"]
},
"3993539000": { # miss heaty
"unique": ["_uncontroll"]
},
"3040073000": { # ferry
"unique": ["_beppo", "_beppo_jiji", "_jiji", "_foogee", "_foogee_nicola", "_nicola", "_momo"]
},
"3990454000": { # ichiro ogami
"unique": ["_split"]
}
}
SCENE_SUFFIXES["3990220000"] = SCENE_SUFFIXES["3990219000"] # djeeta = gran
SCENE_SUFFIXES["3990024000"] = SCENE_SUFFIXES["3990135000"] # thug 2 = thug
SCENE_SUFFIXES["3990031000"] = SCENE_SUFFIXES["3990135000"] # thug 3 = thug
SCENE_SUFFIXES["3992257000"] = SCENE_SUFFIXES["3992265000"] # helicopter (auguste of the dead)
SCENE_SUFFIXES["3040209000"] = SCENE_SUFFIXES["3040073000"] # ferry
SCENE_SUFFIXES["3991804000"] = SCENE_SUFFIXES["3040073000"] # ferry
SCENE_BUBBLE_FILTER = set([k[1:] for k in SCENE_SUFFIXES["default"]["end"] if len(k) > 0])
def __init__(self) -> None:
# main variables
self.update_changelog = True # flag to enable or disable the generation of changelog.json
self.debug_wpn = False # for testing
self.debug_npc_detail = False # set to true for better detection
self.data = { # data structure
"version":self.SAVE_VERSION,
"uncap_queue":[],
"scene_queue":[],
"sound_queue":[],
"valentines":[],
"characters":{},
"partners":{},
"summons":{},
"weapons":{},
"enemies":{},
"skins":{},
"job":{},
"job_wpn":{},
"job_key":{},
"npcs":{},
"background":{},
"title":{},
"suptix":{},
"lookup":{},
"events":{},
"skills":{},
"subskills":{},
"buffs":{},
"eventthumb":{},
"story":{},
"premium":{}
}
self.load() # load self.data NOW
self.modified = False # if set to true, data.json will be written on the next call of save()
self.stat_string = None # set and updated by make_stats
self.new_elements = [] # new indexed element
self.addition = {} # new elements for changelog.json
self.job_list = None
self.scene_strings = None # contains list of suffix
self.scene_strings_special = None # contains list of suffix
self.force_partner = False # set to True by -partner
self.shared_task_container = [] # used for -scene
# asyncio semaphores
self.sem = asyncio.Semaphore(self.MAX_UPDATE) # update semaphore
self.http_sem = asyncio.Semaphore(self.MAX_HTTP) # http semaphore
self.wiki_sem = asyncio.Semaphore(self.MAX_HTTP_WIKI) # wiki request semaphor
# others
self.run_count = 0
self.progress = Progress(self) # initialized with a silent progress bar
self.use_wiki = True # if True, use wiki features
self.client = None # will contain the aiohttp client. Is initialized at startup or must be initialized by a third party.
# CTRL+C signal
try: # unix
self.loop.add_signal_handler(signal.SIGINT, self.interrupt)
except: # windows
signal.signal(signal.SIGINT, self.interrupt)
def interrupt(self, signum : int, frame) -> None:
print("")
print("Process PAUSED")
if self.progress is not None and self.progress.total != 9999999999999:
print("State: {}/{}".format(self.progress.current, self.progress.total))
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")
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.modified:
print("No changes waiting to be saved")
else:
self.save()
case 'peek':
if len(s) < 3:
print("missing 1 parameter: ID")
elif len(s) < 2:
print("missing 2 parameters: index, ID")
else:
try:
d = 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.update_changelog = not self.update_changelog
print("changelog.json updated list WILL be modified" if self.update_changelog else "changelog.json updated list won't be modified")
case 'exit':
print("Exiting...")
os._exit(0)
case _:
print("Process RESUMING...")
break
### Utility #################################################################################################################
# Load data.json
def load(self) -> None:
try:
with open('json/data.json', mode='r', encoding='utf-8') as f:
data = json.load(f)
if not isinstance(data, dict): return
data = self.retrocompatibility(data)
for k in self.data:
if k in self.LOAD_EXCLUSION: continue
elif k in data: self.data[k] = data[k]
except OSError as e:
print(e)
if input("Continue anyway? (type 'y' to continue):").lower() != 'y':
os._exit(0)
except Exception as e:
print("The following error occured while loading data.json:")
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
print(e)
os._exit(0)
# make older data.json compatible with newer versions
def retrocompatibility(self, data : dict) -> dict:
#version = data.get("version", 0)
# Does nothing for now
return data
# Save data.json and changelog.json (only if self.modified is True)
def save(self) -> None:
try:
if self.modified:
self.modified = False
# data.json
for k in self.QUEUE_KEY:
self.data[k] = list(set(self.data[k]))
self.data[k].sort()
with open('json/data.json', mode='w', encoding='utf-8') as outfile:
# custom json indentation
outfile.write("{\n")
keys = list(self.data.keys())
for k, v in self.data.items():
outfile.write('"{}":\n'.format(k))
if isinstance(v, int): # INT
outfile.write('{}\n'.format(v))
if k != keys[-1]:
outfile.write(",")
outfile.write("\n")
elif isinstance(v, list): # LIST
outfile.write('[\n')
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(v.keys())
if len(last) > 0:
last = last[-1]
for i, d in v.items():
outfile.write('"{}":'.format(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
try:
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)
existing = {}
for e in data.get('new', []): # convert content to dict
existing[e[0]] = e[1]
except:
existing = {}
stat = None
issues = []
help = False
if self.update_changelog:
for k, v in self.addition.items(): # merge but put updated elements last
if k in existing: existing.pop(k)
existing[k] = v
self.addition = {} # clear self.addition
# updated new elements
new = [[k, v] for k, v in existing.items()] # convert back to list. NOTE: maybe make a cleaner way later
if len(new) > self.MAX_NEW: new = new[len(new)-self.MAX_NEW:]
# update stat
if self.stat_string is not None: stat = self.stat_string
with open('json/changelog.json', mode='w', encoding='utf-8') as outfile:
json.dump({'timestamp':int(datetime.now(timezone.utc).timestamp()*1000), 'new':new, 'stat':stat, 'issues':issues, 'help':help}, outfile)
if self.update_changelog: print("data.json and changelog.json updated")
else: print("data.json updated")
except Exception as e:
print(e)
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
# Generic GET request function
async def get(self, url : str, headers : dict = {}, timeout : Optional[int] = None, get_json : bool = False):
async with self.http_sem:
response = await self.client.get(url, headers={'connection':'keep-alive'} | headers, timeout=timeout)
async with response:
if response.status != 200: raise Exception("HTTP error {}".format(response.status))
if get_json: return await response.json()
return await response.content.read()
# Generic HEAD request function
async def head(self, url : str, headers : dict = {}):
async with self.http_sem:
response = await self.client.head(url, headers={'connection':'keep-alive'} | headers)
async with response:
if response.status != 200: raise Exception("HTTP error {}".format(response.status))
return response.headers
# wrapper of head() if the exception isn't needed (return None in case of error instead)
async def head_nx(self, url : str, headers : dict = {}):
try:
return await self.head(url, headers)
except:
return None
# another wrapper to chain requests
async def multi_head_nx(self, urls : list, headers : dict = {}):
for url in urls:
r = await self.head_nx(url, headers)
if r is not None:
return r
return None
# test if the wiki is usable
async def test_wiki(self) -> bool:
try:
t = (await self.get("https://gbf.wiki", headers={'User-Agent':self.USER_AGENT}, timeout=5)).decode('utf-8')
if "<p id='status'>50" in t or 'gbf.wiki unavailable' in t: return False
return True
except:
return False
# Create a shared container for tasks.
def newShared(self, errs : list) -> list:
errs.append([0, True, 0])
return errs[-1]
# Extract json data from a manifest file
async def processManifest(self, file : str, verify_file : bool = False) -> list:
manifest = (await self.get(self.MANIFEST + file + ".js")).decode('utf-8')
st = manifest.find('manifest:') + len('manifest:')
ed = manifest.find(']', st) + 1
data = json.loads(manifest[st:ed].replace('Game.imgUri+', '').replace('src:', '"src":').replace('type:', '"type":').replace('id:', '"id":'))
res = [src for l in data if (src := l['src'].split('?')[0].split('/')[-1])] # list all string srcs
if verify_file: # check if at least one file is visible
for k in res:
try:
await self.head(self.IMG + "sp/cjs/" + k)
return res
except:
pass
raise Exception("Invalid Spritesheets")
return res
# clean shared_task_container of completed tasks
def clean_shared_task(self) -> None:
self.shared_task_container = [t for t in self.shared_task_container if not t.done()]
# wait for all tasks in shared_task_container to be complete
async def wait_shared_task_completion(self) -> None:
while len(self.shared_task_container) > 0:
await asyncio.sleep(0.01)
self.clean_shared_task()
# wait for free space to appear in shared_task_container
async def wait_shared_task_free(self, limit : int) -> None:
while len(self.shared_task_container) >= limit:
await asyncio.sleep(0.01)
self.clean_shared_task()
# for limited queued asyncio concurrency
async def map_unordered(self, func : Callable, iterable : Union[Iterator,Collection,AsyncIterator], limit : int) -> asyncio.Task:
aws = iter(map(func, iterable))
aws_ended = False
pending = set()
while pending or not aws_ended:
while len(pending) < limit and not aws_ended:
try:
aw = next(aws)
except StopIteration:
aws_ended = True
else:
pending.add(asyncio.ensure_future(aw))
if not pending:
return
done, pending = await asyncio.wait(
pending, return_when=asyncio.FIRST_COMPLETED
)
while done:
yield done.pop()
### Run #####################################################################################################################
# Called by -run, update the indexed content
async def run(self, ids : list = []) -> None:
self.new_elements = ids
self.run_count = 0
categories = []
errs = []
job_task = 10
skill_task = 10
buff_series_task = 12
# job keys to check
if self.job_list is None:
self.job_list = await self.init_job_list()
if self.job_list is None:
print("Couldn't retrieve job list from the game")
return
jkeys = [k for k in list(self.job_list.keys()) if k not in self.data['job']]
if len(jkeys) > 0:
job_task == 0
# jobs
categories.append([])
self.newShared(errs)
for i in range(job_task):
categories[-1].append(self.search_job(i, job_task, jkeys, errs[-1]))
# skills
for i in range(skill_task):
categories.append([self.search_skill(i, skill_task)])
# buffs
for i in range(10):
for j in range(buff_series_task):
categories.append([self.search_buff(1000*i+j, buff_series_task)])
# npc
categories.append([])
self.newShared(errs)
for i in range(10): # assets
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "img/sp/quest/scene/character/body/", ".png", 70))
categories.append([])
self.newShared(errs)
for i in range(10): # assets
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "img/sp/raid/navi_face/", ".png", 50))
categories.append([])
self.newShared(errs)
for i in range(10): # assets
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "img/sp/quest/scene/character/body/", "_a.png", 50))
categories.append([])
self.newShared(errs)
for i in range(10): # assets
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "img/sp/assets/npc/b/", "_01.png", 70))
categories.append([])
self.newShared(errs)
for i in range(10): # sounds
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "sound/voice/", "_v_001.mp3", 50))
categories.append([])
self.newShared(errs)
for i in range(10): # boss sounds
categories[-1].append(self.search_generic('npcs', i, 10, errs[-1], "399{}000", 4, "sound/voice/", "_boss_v_1.mp3", 50))
# special
categories.append([])
categories[-1].append(self.search_generic('npcs', 0, 1, self.newShared(errs), "305{}000", 4, "img/sp/quest/scene/character/body/", ".png", 2))
#rarity of various stuff
for r in range(1, 5):
# weapons
for j in range(10):
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('weapons', i, 5, errs[-1], "10"+str(r)+"0{}".format(j) + "{}00", 3, "img/sp/assets/weapon/m/", ".jpg", 20))
# summons
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('summons', i, 5, errs[-1], "20"+str(r)+"0{}000", 3, "img/sp/assets/summon/m/", ".jpg", 20))
if r > 1:
# characters
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('characters', i, 5, errs[-1], "30"+str(r)+"0{}000", 3, "img/sp/assets/npc/m/", "_01.jpg", 20))
# partners
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "img/sp/assets/npc/raid_normal/", "_01.jpg", 20))
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "js/model/manifest/phit_", ".js", 20))
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "js/model/manifest/nsp_", "_01.js", 20))
# other partners
for r in range(8, 10):
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "img/sp/assets/npc/raid_normal/", "_01.jpg", 20))
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "js/model/manifest/phit_", ".js", 20))
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('partners', i, 5, errs[-1], "38"+str(r)+"0{}000", 3, "js/model/manifest/nsp_", "_01.js", 20))
# skins
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('skins', i, 5, errs[-1], "3710{}000", 3, "js/model/manifest/npc_", "_01.js", 20))
# enemies
for a in range(1, 10):
for b in range(1, 4):
for d in [1, 2, 3]:
categories.append([])
self.newShared(errs)
for i in range(5):
categories[-1].append(self.search_generic('enemies', i, 5, errs[-1], str(a) + str(b) + "{}" + str(d), 4, "img/sp/assets/enemy/s/", ".png", 50))
# backgrounds
# event & common
for i in ["event_{}", "common_{}"]:
categories.append([])
self.newShared(errs)
for j in range(5):
categories[-1].append(self.search_generic('background', j, 5, errs[-1], i, 3 if i.startswith("common_") else 1, "img/sp/raid/bg/", ".jpg", 10))
# main
categories.append([])
self.newShared(errs)
for j in range(5):
categories[-1].append(self.search_generic('background', j, 5, errs[-1], "main_{}", 1, "img/sp/guild/custom/bg/", ".png", 10))
# others
for i in ["ra", "rb", "rc"]:
categories.append([])
self.newShared(errs)
for j in range(5):
categories[-1].append(self.search_generic('background', j, 5, errs[-1], "{}"+i, 1, "img/sp/raid/bg/", "_1.jpg", 50))
break
for i in [("e", ""), ("e", "r"), ("f", ""), ("f", "r"), ("f", "ra"), ("f", "rb"), ("f", "rc"), ("e", "r_3_a"), ("e", "r_4_a")]:
categories.append([])
self.newShared(errs)
for j in range(5):
categories[-1].append(self.search_generic('background', j, 5, errs[-1], i[0]+"{}"+i[1], 3, "img/sp/raid/bg/", "_1.jpg", 50))
# titles
categories.append([])
self.newShared(errs)
for i in range(3):
categories[-1].append(self.search_generic('title', i, 3, errs[-1], "{}", 1, "img/sp/top/bg/bg_", ".jpg", 5))
# subskills
categories.append([])
self.newShared(errs)
for i in range(3):
categories[-1].append(self.search_generic('subskills', i, 3, errs[-1], "{}", 1, "img/sp/assets/item/ability/s/", "_1.jpg", 5))
# suptix
categories.append([])
self.newShared(errs)
for i in range(3):
categories[-1].append(self.search_generic('suptix', i, 3, errs[-1], "{}", 1, "img/sp/gacha/campaign/surprise/top_", ".jpg", 15))
print("Starting process...")
self.progress = Progress(self, total=len(categories), silent=False)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(self.run_category(c)) for c in categories]
for t in tasks:
t.result()
self.save()
if len(self.new_elements) > 0:
await self.manualUpdate(self.new_elements)
await self.check_msq()
await self.check_new_event()
await self.update_all_event_skycompass()
await self.update_npc_thumb()
else:
if len(self.data['uncap_queue']) > 0:
await self.manualUpdate([])
if len(self.data['scene_queue']) > 0:
await self.update_all_scene(update_pending=True)
if len(self.data['sound_queue']) > 0:
await self.update_all_sound(update_pending=True)
# run subroutine, process a category batch
async def run_category(self, coroutines : list) -> None:
with self.progress:
while True:
if self.run_count + len(coroutines) <= self.MAX_HTTP:
self.run_count += len(coroutines)
break
await asyncio.sleep(1)
try:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(coroutines[i]) for i in range(len(coroutines))]
for t in tasks:
t.result()
except Exception as e:
print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
self.run_count -= len(coroutines)
# generic asset search
async def search_generic(self, index : str, start : int, step : int, err : list, file : str, zfill : int, path : str, ext : str, maxerr : int) -> None:
i = start
is_js = ext.endswith('.js')
while err[0] < maxerr and err[1]:
f = file.format(str(i).zfill(zfill))
if f in self.data[index]:
if self.data[index][f] == 0 and (is_js or index in self.PREEMPTIVE_ADD):
self.new_elements.append(f)
err[0] = 0
await asyncio.sleep(0.02)
else:
try:
await self.head(self.ENDPOINT + path + f + ext)
err[0] = 0
self.data[index][f] = 0
if index in self.ADD_SINGLE_ASSET:
self.addition[index+":"+f] = index
self.modified = True
self.new_elements.append(f)
break
except:
err[0] += 1
if err[0] >= maxerr:
err[1] = False
return
i += step
# -run subroutine to search for new skills
async def search_skill(self, start : int, step : int) -> None: # skill search
err = 0
i = start
tmp_c = ("0" if start < 1000 else str(start)[0])
tmp = [k for k in list(self.data["skills"].keys()) if k[0] == tmp_c]
tmp.sort()
try:
highest = int(tmp[-1])
except:
highest = i - 1
tmp = None
highest = start
while err < 12:
fi = str(i).zfill(4)
if fi in self.data["skills"]:
i += step
err = 0
continue
found = False
for s in [".png", "_1.png", "_2.png", "_3.png", "_4.png", "_5.png"]:
try:
headers = await self.head(self.IMG + "sp/ui/icon/ability/m/" + str(i) + s)
if 'content-length' in headers and int(headers['content-length']) < 200: raise Exception()
found = True
err = 0
self.data["skills"][fi] = [[str(i) + s.split('.')[0]]]
self.addition[fi] = self.ADD_SKILL
self.modified = True
break
except:
pass
i += step
if not found and i > highest: err += 1
# -run subroutine to search for new buffs
async def search_buff(self, start : int, step : int, full : bool = False) -> None: # buff search
err = 0
i = start
end = (start // 1000) * 1000 + 1000
tmp_c = ("0" if start < 1000 else str(start)[0])
tmp = [k for k in list(self.data["buffs"].keys()) if k[0] == tmp_c]
tmp.sort()
try:
highest = int(tmp[-1])
except:
highest = i - 1
tmp = None
highest = start
# suffix list
slist = ["_1", "_10", "_11", "_101", "_110", "_111", "_30"] + (["1"] if start >= 1000 else []) + ["_1_1", "_2_1", "_0_10", "_1_10" "_1_20", "_2_10"]
known = set()
while err < 10 and i < end:
fi = str(i).zfill(4)
data = [[], []]
if not full:
if fi in self.data["buffs"]:
i += step
err = 0
continue
else:
try:
data[0] = self.data["buffs"][fi][0].copy()
data[1] = self.data["buffs"][fi][1].copy()
known = set(data[1])
if '_' not in data[0] and len(data[0]) < 5:
known.add("")
except:
known = set()
found = False
modified = False
# check no suffix
try:
if len(data[0]) == 0 or (len(data[0]) > 0 and data[0][0] != str(i)):
headers = await self.head(self.IMG + "sp/ui/icon/status/x64/status_" + str(i) + ".png")
if 'content-length' in headers and int(headers['content-length']) < 150: raise Exception()
data[0] = [str(i)]
modified = True
found = True
except:
pass
# check suffixes
for s in slist:
try:
if s not in known:
headers = await self.head(self.IMG + "sp/ui/icon/status/x64/status_" + str(i) + s + ".png")
if 'content-length' in headers and int(headers['content-length']) < 150: raise Exception()
if len(data[0]) == 0:
data[0] = [str(i)+s]
if s != "":
data[1].append(s)
modified = True
found = True
except:
pass
if not found:
if i > highest:
err += 1
else:
err = 0
if modified:
try:
if len(data[1]) != len(self.data["buffs"][fi][1]):
self.addition[fi] = self.ADD_BUFF
except:
self.addition[fi] = self.ADD_BUFF
self.data["buffs"][fi] = data
self.modified = True
i += step
### Job #####################################################################################################################
# To be called once when needed
async def init_job_list(self) -> dict:
print("Initializing job list...")
# existing classes
try: job_list = (await self.get(self.JS + "constant/job.js")).decode('utf-8') # contain a list of all classes. it misses the id of the outfits however.
except Exception as ee:
print(ee)
return
a = job_list.find("var a={")
if a == -1: return
a+=len("var a={")
b = job_list.find("};", a)
if b == -b: return
job_list = job_list[a:b].split(',')
temp = {}
for j in job_list:
e = j.split(':')
temp[e[1]] = set()
for c in e[0].replace('_', ''):
temp[e[1]].add(c)
temp[e[1]] = "".join(list(temp[e[1]])).lower()
job_list = temp
# old skins
for e in [("125001","snt"), ("165001","stf"), ("185001", "idl")]:
job_list[e[0]] = e[1]
# new skins
async with asyncio.TaskGroup() as tg:
tasks = []
for i in range(31, 41):
for j in range(0, 20):
if str(i * 100 + j)+"01" in job_list: continue
tasks.append(tg.create_task(self.init_job_list_sub(str(i * 100 + j)+"01")))
for t in tasks:
r = t.result()
if r is not None: