-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdater.py
3924 lines (3779 loc) · 196 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
from __future__ import annotations
from typing import Any, Callable
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import asyncio
import aiohttp
import os
import sys
import re
import time
import json
import string
import html
import traceback
import signal
import argparse
# Handle tasks
class TaskManager():
CONCURRENT = 90
def __init__(self : TaskManager, updater : Updater) -> None:
self.debug : bool = False
self.is_running : bool = False
self.updater : Updater = updater
self.queues : tuple[asyncio.Queue, ...] = (asyncio.Queue(), asyncio.Queue(), asyncio.Queue(), asyncio.Queue(), asyncio.Queue())
self.running : list[asyncio.Task] = []
self.total : int = 0
self.finished : int = 0
self.print_flag : bool = False
self.elapsed : float = 0
self.return_state : bool = True
self.written_len : int = 0
# reinitialize variables
def reset(self : TaskManager) -> None:
self.total = 0
self.finished = 0
self.is_running = False
self.print_flag = False
# add a task to one queue
def add(self : TaskManager, awaitable : Callable, *, parameters : tuple[Any, ...]|None = None, priority : int = -1) -> None:
if parameters is not None and not(isinstance(parameters, tuple)):
raise Exception("Invalid parameters")
if priority < 0 or priority >= len(self.queues):
priority = len(self.queues) - 1
self.queues[priority].put_nowait(Task.make(awaitable, parameters))
self.total += 1
# return True if all queues are empty
def queues_are_empty(self : TaskManager) -> bool:
for q in self.queues:
if not q.empty():
return False
return True
# run tasks in queue
async def run(self : TaskManager, *, skip : int = 0) -> None:
if self.is_running:
self.print("ERROR: run() is already running, ignoring...)")
return
self.is_running = True
start_time : float = time.time()
self.elapsed : float = start_time
to_sleep : bool = False
i : int
# loop
while len(self.running) > 0 or not self.queues_are_empty():
# remove from queue and run
for i in range(len(self.queues)):
while len(self.running) < self.CONCURRENT and not self.queues[i].empty():
try:
t : Task = await self.queues[i].get()
if skip <= 0:
if t.parameters is not None:
self.running.append(asyncio.create_task(t.awaitable(*t.parameters)))
else:
self.running.append(asyncio.create_task(t.awaitable()))
else:
skip -= 1
except Exception as e:
self.print("Can't start task, the following exception occured:")
self.print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
self.finished += 1
self.return_state = False
break
# check process flags
await self.updater.process_flags()
# remove completed tasks
i = 0
prev : int = self.finished
while i < len(self.running):
if self.running[i].done():
try:
self.running[i].result()
except Exception as e:
self.return_state = False
self.print("The following exception occured:")
self.print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
self.finished += 1
self.running.pop(i)
else:
i += 1
# update status
if prev != self.finished:
self.update_progress()
to_sleep = False
else:
to_sleep = True
# ... and sleep if we haven't finished tasks
if to_sleep:
await asyncio.sleep(0.1)
# if ALL tasks are done, check flags
if len(self.running) == 0 and self.queues_are_empty():
await self.updater.process_flags()
self.print("Complete")
# finished
diff : float = time.time() - start_time # elapsed time
# format to H:M:S
elapsed_s : int = int(diff)
h : int = elapsed_s // 3600 # hours
m : int = (elapsed_s % 3600) // 60 # minutes
s : int = elapsed_s % 60 # seconds
strings : list[str] = ["Run time: "]
if h > 0:
strings.append(str(h).zfill(2))
strings.append('h')
if m > 0:
strings.append(str(m).zfill(2))
strings.append('m')
strings.append(str(s).zfill(2))
strings.append('s')
self.reset()
print("".join(strings))
# start to run queued tasks
async def start(self : TaskManager) -> bool:
if self.is_running or self.queues_are_empty(): # return if already running or no tasks pending
return False
self.return_state = True
asyncio.create_task(self.run())
await asyncio.sleep(5)
while self.is_running:
await asyncio.sleep(1)
return self.return_state
# update the progression string and save if we've run for over 1h
def update_progress(self : TaskManager) -> None:
self.print_progress()
if time.time() - self.elapsed >= 3600:
if self.updater.modified:
self.print("Progress: {} / {} Tasks, autosaving...".format(self.finished, self.total))
self.updater.save()
self.updater.save_resume()
self.elapsed = time.time()
# print the progression string
def print_progress(self : TaskManager) -> None:
if self.running and self.total > 0:
if self.print_flag:
sys.stdout.write("\r")
if self.written_len > 0:
sys.stdout.write((" " * self.written_len) + "\r")
else:
self.print_flag = True
if self.debug:
self.written_len = sys.stdout.write("P:{}/{} | R:{} | Q:{} {} {} {} {}".format(self.finished, self.total, len(self.running), self.queues[0].qsize(), self.queues[1].qsize(), self.queues[2].qsize(), self.queues[3].qsize(), self.queues[4].qsize()))
else:
self.written_len = sys.stdout.write("Progress: {} / {} Tasks".format(self.finished, self.total))
sys.stdout.flush()
# print whatever you want, to use instead of print to handle the \r
def print(self : TaskManager, *args) -> None:
if self.print_flag:
self.print_flag = False
sys.stdout.write("\r")
if self.written_len > 0:
sys.stdout.write((" " * self.written_len) + "\r")
print(*args)
self.print_progress()
# called when CTRL+C is used
def interrupt(self : TaskManager, *args) -> None:
if self.total <= 0 or self.finished >= self.total:
return
if self.print_flag:
self.print_flag = False
sys.stdout.write("\r")
if self.written_len > 0:
sys.stdout.write((" " * self.written_len) + "\r")
print("Process PAUSED")
print("{} / {} Tasks completed".format(self.finished, self.total))
print("{} Tasks running".format(len(self.running)))
for i in range(len(self.queues)):
print("Tasks in queue lv{}: {}".format(i, self.queues[i].qsize()))
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...")
self.updater.save_resume()
os._exit(0)
case _:
print("Process RESUMING...")
break
# A queued task
@dataclass(frozen=True, slots=True)
class Task():
awaitable : Callable
parameters : tuple[Any, ...]|None
@classmethod
def make(cls : Task, awaitable : Callable, parameters : tuple[Any, ...]|None) -> Task:
return cls(awaitable, parameters)
@dataclass(slots=True)
class TaskStatus():
index : int
max_index : int
err : int
max_err : int
running : int
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
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
@property
def finished(self : TaskStatus) -> bool:
return self.running <= 0
@dataclass(slots=True)
class Flags():
_d_ : dict[str, int]
def __init__(self : Flags) -> None:
self._d_ = {}
def set(self : Flags, name : str) -> None:
self._d_[name] = 1
def check(self : Flags, name : str) -> bool:
return self._d_.get(name, 0) != 0
class Updater():
### CONSTANT
VERSION = '3.14'
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'
SAVE_VERSION = 1
# limit
MAX_NEW = 100 # changelog limit
HTTP_CONN_LIMIT = 80
LOOKUP_TYPES = ['characters', 'summons', 'weapons', 'job', 'skins', 'npcs']
UPDATABLE = set(["characters", "enemies", "summons", "skins", "weapons", "partners", 'npcs', "background", "job"])
# 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
ADD_FATE = 12
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
# fate update
FATE_CONTENT = 0
FATE_UNCAP_CONTENT = 1
FATE_TRANSCENDENCE_CONTENT = 2
FATE_OTHER_CONTENT = 3
FATE_LINK = 4
# buff suffix list
BUFF_LIST_EXTENDED = ["", "_1", "_2", "_10", "_11", "_101", "_110", "_111", "_20", "_30", "1", "_1_1", "_2_1", "_0_10", "_1_10", "_1_20", "_2_10"]
BUFF_LIST = BUFF_LIST_EXTENDED.copy()
BUFF_LIST.pop(BUFF_LIST.index("1"))
# 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
CHAPTER_REGEX = re.compile("Chapter (\\d+)(-(\\d+))?")
# others
QUEUE_KEY = ['uncap_queue']
STRING_CHAR = string.ascii_lowercase + string.digits
def __init__(self : Updater):
# load constants
try:
with open("json/manual_constants.json", mode="r", encoding="utf-8") as f:
data : dict[str, Any] = json.load(f)
k : str
for k, v in data.items():
setattr(self, k, v)
# extra, SCENE_BUBBLE_FILTER for performance
setattr(self, 'SCENE_BUBBLE_FILTER', set([k[1:] for k in self.SCENE_SUFFIXES["default"]["end"] if len(k) > 0]))
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__)))
os._exit(0)
# other init
self.client : aiohttp.ClientSession|None = None # the http client
self.flags : Flags = Flags() # to contain and manage various flag values
self.http_sem : asyncio.Semaphore = asyncio.Semaphore(self.HTTP_CONN_LIMIT) # http semaphor to limit http connections
self.tasks : TaskManager = TaskManager(self) # the task manager
self.use_wiki : bool = False # flag to see if the wiki usable
self.update_changelog : bool = True # flag to enable or disable the generation of changelog.json
self.use_resume : bool = True # flag to use the resume file
self.ignore_file_count : bool = False # flag to control the count_file function behavior
self.data : dict[str, Any] = { # data structure
"version":self.SAVE_VERSION,
"uncap_queue":[],
"valentines":[],
"characters":{},
"partners":{},
"summons":{},
"weapons":{},
"enemies":{},
"skins":{},
"job":{},
"job_wpn":{},
"job_key":{},
'npcs':{},
"background":{},
"title":{},
"suptix":{},
"lookup":{},
'events':{},
"skills":{},
"subskills":{},
'buffs':{},
'eventthumb':{},
"story":{},
"fate":{},
"premium":{},
"npc_replace":{}
}
self.load() # load self.data NOW
self.modified : bool = False # if set to true, data.json will be written on the next call of save()
self.resume : dict[str, Any] = {} # list of items completed (for the resume file)
self.stat_string : str|None = None # set and updated by make_stats
self.addition : dict[str, Any] = {} # new elements for changelog.json
self.updated_elements = set() # set of elements ran through update_element()
self.job_list : dict[str, str]|None = None # job dictionary of id string pair
self.scene_strings : None|tuple[dict, dict] = None # scene string containers
# sound strings containers
self.sound_base_strings : list[str, list[str], int, int, int] = []
self.sound_other_strings : list[str, list[str], int, int, int] = []
### 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)
try:
with open('json/manual_npc_replace.json', mode='r', encoding='utf-8') as f:
data : dict[str, str] = json.load(f)
if not isinstance(data, dict):
raise Exception("Not a dictionary")
if self.data["npc_replace"] != data:
self.data["npc_replace"] = data
self.modified = True
except Exception as e:
self.tasks.print("Failed to import manual_npc_replace.json")
self.tasks.print("Exception:", e)
# 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"] = self.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
# remove dupes from queues
for k in self.QUEUE_KEY:
self.data[k] = list(set(self.data[k]))
self.data[k].sort()
# 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('"{}":\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')
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('"{}":'.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
stat : str|None
existing : dict[str, 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)
existing = {}
e : Any
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: # update new content
k : str
v : Any
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 : list[Any] = [[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: # 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__)))
# Generic GET request function
async def get(self : Updater, url : str) -> Any:
async with self.http_sem:
response : aiohttp.HTTPResponse = await self.client.get(url, headers={'connection':'keep-alive'})
async with response:
if response.status != 200:
raise Exception("HTTP error {}".format(response.status))
return await response.content.read()
# Same as GET but for gbf.wiki
async def get_wiki(self : Updater, url : str, *, get_json : bool = False) -> Any:
async with self.http_sem:
response : aiohttp.HTTPResponse = await self.client.get(url, headers={'User-Agent':self.USER_AGENT}, timeout=10)
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 : Updater, url : str) -> Any:
async with self.http_sem:
response : aiohttp.HTTPResponse = await self.client.head(url, headers={'connection':'keep-alive'})
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 : Updater, url : str):
try:
return await self.head(url)
except:
return None
# Extract json data from a GBF animation manifest file
async def processManifest(self, file : str, verify_file : bool = False) -> list:
# request the file
manifest = (await self.get(self.MANIFEST + file + ".js")).decode('utf-8')
# fine start and end of object part
st = manifest.find('manifest:') + len('manifest:')
ed = manifest.find(']', st) + 1
# format and load as json
data : dict[str, str] = json.loads(manifest[st:ed].replace('Game.imgUri+', '').replace('src:', '"src":').replace('type:', '"type":').replace('id:', '"id":'))
# list image srcs
res : list[str] = [src for l in data if (src := l['src'].split('?')[0].split('/')[-1])]
# check if at least one file is accessible
if verify_file:
path : list[str] = [self.IMG, "sp/cjs/", ""]
for k in res:
path[2] = k
try:
await self.head("".join(path))
return res
except:
pass
raise Exception("Invalid Spritesheets")
return res
# test if the wiki is usable
async def test_wiki(self : Updater) -> bool:
try:
t : str = (await self.get_wiki("https://gbf.wiki")).decode('utf-8') # request main page
if "<p id='status'>50" in t or 'gbf.wiki unavailable' in t: # check if down
return False
return True
except: # bad request or cloudflare = down/not usable
return False
### Main #################################################################################################################
# called by -run
async def run(self : Updater) -> None:
self.flags.set("run_process")
i : int
j : int
r : int
ts : TaskStatus
# jobs
if self.job_list is not None:
jkeys = [k for k in list(self.job_list.keys()) if (k not in self.data['job'] or self.data['job'][k] == 0)]
for k in jkeys:
self.tasks.add(self.update_job, parameters=(k))
# skills
ts = TaskStatus(10000, 12)
highest : int = 0
try:
highest = max([int(k) for k in self.data["skills"]])
except:
pass
for i in range(10):
self.tasks.add(self.search_skill, parameters=(ts, highest))
# buffs
for i in range(10):
for j in range(4):
ts = TaskStatus(i*1000+250*(j+1), 15, start=i*1000+250*j)
n : int
for n in range(3):
self.tasks.add(self.search_buff, parameters=(ts, ))
# npc
ts = TaskStatus(10000, 90)
for i in range(20):
self.tasks.add(self.search_generic, parameters=(ts, 'npcs', "399{}000", 4, [
"img/sp/quest/scene/character/body/{}.png",
"img/sp/quest/scene/character/body/{}_shadow.png",
"img/sp/quest/scene/character/body/{}_a.png",
"img/sp/raid/navi_face/{}.png",
"img/sp/assets/npc/b/{}_01.png",
"sound/voice/{}_v_001.mp3",
"sound/voice/{}_boss_v_1.mp3"
]))
# special npc
ts = TaskStatus(10000, 2)
for i in range(10):
self.tasks.add(self.search_generic, parameters=(ts, 'npcs', "305{}000", 4, ["img/sp/quest/scene/character/body/{}.png"]))
#rarity of various stuff
for r in range(1, 5):
# weapons
for j in range(10):
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'weapons', "10"+str(r)+"0{}".format(j) + "{}00", 3, ["img/sp/assets/weapon/m/{}.jpg"]))
# summons
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'summons', "20"+str(r)+"0{}000", 3, ["img/sp/assets/summon/m/{}.jpg"]))
if r > 1:
# characters
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'characters', "30"+str(r)+"0{}000", 3, ["img/sp/assets/npc/m/{}_01.jpg"]))
# partners
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'partners', "38"+str(r)+"0{}000", 3, [
"img/sp/assets/npc/raid_normal/{}_01.jpg",
"js/model/manifest/phit_{}.js",
"js/model/manifest/nsp_{}_01.js"
]))
# other partners
for r in range(8, 10):
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'partners', "38"+str(r)+"0{}000", 3, [
"img/sp/assets/npc/raid_normal/{}_01.jpg",
"js/model/manifest/phit_{}.js",
"js/model/manifest/nsp_{}_01.js"
]))
# skins
ts = TaskStatus(1000, 20)
for i in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'skins', "3710{}000", 3, ["js/model/manifest/npc_{}_01.js"]))
# enemies
main : int
sub : int
for main in range(1, 10):
for sub in range(1, 4):
ts = TaskStatus(1000, 40)
prefix : str = str(main) + str(sub)
for i in range(10):
self.tasks.add(self.search_enemy, parameters=(ts, prefix))
# backgrounds
# event & common
ev : str
for ev in ["event_{}", "common_{}"]:
ts = TaskStatus(1000, 10)
for j in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'background', ev, 3 if ev.startswith("common_") else 1, ["img/sp/raid/bg/{}.jpg"]))
# main
ts = TaskStatus(1000, 10)
for j in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'background', "main_{}", 1, ["img/sp/guild/custom/bg/{}.png"]))
# others
ss : str
for ss in ["ra", "rb", "rc"]:
ts = TaskStatus(1000, 50)
for j in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'background', "{}"+ss, 1, ["img/sp/raid/bg/{}_1.jpg"]))
bgt : tuple[str, str]
for bgt in [("e", ""), ("e", "r"), ("f", ""), ("f", "r"), ("f", "ra"), ("f", "rb"), ("f", "rc"), ("e", "r_3_a"), ("e", "r_4_a")]:
ts = TaskStatus(1000, 50)
for j in range(5):
self.tasks.add(self.search_generic, parameters=(ts, 'background', bgt[0]+"{}"+bgt[1], 3, ["img/sp/raid/bg/{}_1.jpg"]))
# titles
ts = TaskStatus(1000, 5)
for i in range(3):
self.tasks.add(self.search_generic, parameters=(ts, 'title', "{}", 1, ["img/sp/top/bg/bg_{}.jpg"]))
# subskills
ts = TaskStatus(1000, 5)
for i in range(3):
self.tasks.add(self.search_generic, parameters=(ts, 'subskills', "{}", 1, ["img/sp/assets/item/ability/s/{}_1.jpg"]))
# suptix
ts = TaskStatus(1000, 15)
for i in range(3):
self.tasks.add(self.search_generic, parameters=(ts, 'suptix', "{}", 1, ["img/sp/gacha/campaign/surprise/top_{}.jpg"]))
# start the tasks
await self.tasks.start()
# generic search for assets
async def search_generic(self : Updater, ts : TaskStatus, index : str, file : str, zfill : int, paths : list[str]) -> None:
while not ts.complete:
i : int = ts.get_next_index()
f : str = file.format(str(i).zfill(zfill)) # while the letter f is used to signify the file, it's also the id used in the index
if f in self.data[index]: # if indexed
if self.data[index][f] == 0 and index in self.UPDATABLE: # set to update if no data and it's updatable
self.tasks.print("In need of update:", f, "for index:", index)
self.tasks.add(self.update_element, parameters=(f, index), priority=3)
ts.good()
else:
j : int
path : str
for j, path in enumerate(paths): # request for each path
try:
await self.head(self.ENDPOINT + path.format(f))
ts.good()
self.tasks.print("Found:", f, "for index:", index)
self.data[index][f] = 0 # set data to 0 (until it's updated)
if index in self.ADD_SINGLE_ASSET: # these index don't have changelog ID
self.addition[index+":"+f] = index
self.modified = True
self.tasks.add(self.update_element, parameters=(f, index), priority=3) # call update task for that element
break
except: # request failed
if j == len(paths) - 1: # if it was the last path
ts.bad()
# Search for enemies
async def search_enemy(self : Updater, ts : TaskStatus, prefix : str) -> None:
while not ts.complete:
i : int = ts.get_next_index()
fi : str = prefix + str(i).zfill(4)
found : bool = False
for n in range(1, 4):
sfi : str = fi + str(n)
if sfi in self.data['enemies']:
if self.data['enemies'][sfi] == 0:
self.tasks.print("In need of update:", sfi, "for index:", 'enemies')
self.tasks.add(self.update_element, parameters=(sfi, 'enemies'), priority=3)
found = True
else:
#Note: 6200483, 6099502 and possibly more got no icons and raid_appear must be checked instead
try:
await self.head(self.ENDPOINT + "img/sp/assets/enemy/s/{}.png".format(sfi))
self.tasks.print("Found:", sfi, "for index:", 'enemies')
self.data['enemies'][sfi] = 0 # set data to 0 (until it's updated)
self.modified = True
self.tasks.add(self.update_element, parameters=(sfi, 'enemies'), priority=3) # call update task for that element
found = True
except: # request failed
pass
if found:
ts.good()
else:
ts.bad()
# Search for new skills
async def search_skill(self, ts : TaskStatus, highest : int) -> None: # skill search
# highest is the highest registered id
# it's used to keep going if we know there are further ID to be found later
# this way, is there are large gaps of unused skills, we can still keep going
while not ts.complete:
i : int = ts.get_next_index()
fi = str(i).zfill(4) # formatted id
if fi in self.data["skills"]: # already indexed
ts.good()
else:
found : bool = False
s : str
for s in ["_1.png", "_2.png", "_3.png", "_4.png", "_5.png", ".png"]: # request for each (we only need one good one), ".png" is last because it's rarely used nowadays
try:
headers : Any = 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()
ts.good()
found = True
self.data["skills"][fi] = [[str(i) + s.split('.')[0]]]
self.addition[fi] = self.ADD_SKILL
self.modified = True
break
except:
pass
if not found and i > highest:
ts.bad()
# Search for new buffs
async def search_buff(self, ts : TaskStatus) -> None:
while not ts.complete:
i : int = ts.get_next_index()
fi : str = str(i).zfill(4) # formatted id
if fi in self.data['buffs']: # already indexed
if self.data['buffs'][fi] == 0:
self.prepare_update_buff(fi, priority=3) # call update task for that element
ts.good()
continue
found : bool = False
slist : list[str] = self.BUFF_LIST_EXTENDED if i >= 1000 else self.BUFF_LIST
path : list[str] = [self.IMG, "sp/ui/icon/status/x64/status_", str(i), "", ".png"]
for s in slist:
path[3] = s
try:
await self.request_buff("".join(path))
self.data['buffs'][fi] = [[path[2]], [s]]
found = True
break
except:
pass
if found:
ts.good()
self.tasks.print("Found:", fi, "for index:", "buffs")
self.prepare_update_buff(fi, priority=3) # call update task for that element
else:
ts.bad()
# Prepare the update_buff tasks
def prepare_update_buff(self : Updater, element_id : str, *, priority : int = -1) -> None:
i : int = int(element_id)
fi : str = str(i)
if self.data['buffs'].get(element_id, 0) == 0: # init array
self.data['buffs'][element_id] = [[], []]
known : set[str] = set(self.data['buffs'].get(element_id, [[], []])[1])
path : list[str] = [self.IMG, "sp/ui/icon/status/x64/status_", fi, "", ".png"]
ts : TaskStatus = TaskStatus(1, 1, running=6)
# add tasks to verify variations
for mode in range(6):
if (mode == 0 and "" in known) or (mode == 2 and i < 1000): # skip these if the condition matches
ts.finish()
continue
self.tasks.add(self.update_buff, parameters=(mode, ts, path, element_id, fi, known), priority=priority)
# Subroutine of prepare_update_buff to check for varitions
# Mode control which variation to check
# Mode 0 is only if "" is not in known files, Mode 2 is only for IDs lesser than 1000
async def update_buff(self : Updater, mode : int, ts : TaskStatus, path : list[str], element_id : str, fi : str, known : set[str]) -> None:
err : int = 0
n : int = 0
m : int
match mode:
case 0:
# default
path[3] = ""
try:
await self.request_buff("".join(path))
known.add("")
except:
pass
case 1:
# _1, _2...
while err < 3 and n < 10:
path[3] = "_" + str(n)
if path[3] in known:
err = 0
else:
try:
await self.request_buff("".join(path))
known.add("_" + str(n))
err = 0
except:
err += 1
n += 1
case 2:
# 1, 2...
while err < 3:
path[3] = str(n)
if path[3] in known:
err = 0
else:
try:
await self.request_buff("".join(path))
known.add(str(n))
err = 0
except:
err += 1
n += 1
case 3:
errlimit : int = 10 if element_id in ["3000", "1008"] else 3
for x in range(1, 10):
# _10, _11, _20, _30...
n = 10 * x
m = n + 10
err = 0
while err < errlimit and n < m:
path[3] = "_" + str(n)
if path[3] in known:
err = 0
else:
try:
await self.request_buff("".join(path))
known.add("_" + str(n))