forked from 641i130/klbvfs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtools.py
345 lines (277 loc) · 17.7 KB
/
tools.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
#!/bin/env python3
#Script de pruebas y herramientas propias usadas para identificar trajes y personajes, entre otras pruebas que voy a estar haciendo
from klbvfs import *
import re
import json
###
#diccionario del id en la base de datos que hace referencia a cada personaje
names = {
1: "Honoka", 2: "Eli", 3: "Kotori", 4: "Umi", 5: "Rin", 6: "Maki", 7: "Nozomi", 8: "Hanayo", 9: "Nico",
101: "Chika", 102: "Riko", 103: "Kanan", 104: "Dia", 105: "You", 106: "Yoshiko", 107: "Hanamaru", 108: "Mary", 109: "Ruby",
201: "Ayumu", 202: "Kasumi", 203: "Shizuku", 204: "Karin", 205: "Ai", 206: "Kanata", 207: "Setsuna", 208: "Emma", 209: "Rina", 210: "Shioriko", 211: "Mia", 212: "Lanzhu"
}
#precargar diccionario
try:
json_dictionary = json.load(open('./m_dictionary.json'))
except FileNotFoundError:
print("[Warning] Necesitas extraer el m_dictionary a un archivo json (m_dictionary.json)")
pass
###
def decrypt(pack_name, head, size, key1, key2, output):
source = os.path.abspath(".")
destination = os.path.join(output, "%s_%d" % (pack_name, head))
#accede a la carpeta pkgx donde x es el primer digito del pack_name
pkgpath = os.path.join(source, "pkg" + pack_name[:1], pack_name)
key = [key1, key2, 0x3039] #el key es un array[3]
try:
pkg = codecs.open(pkgpath, mode='rb', encoding='klbvfs', errors=key) #abrir el archivo pkgx encriptado
pkg.seek(head) #ir a la posicion que indica el head
buffer = pkg.read(1024)
mimetype = magic.from_buffer(buffer, mime=True)
extension = mimetypes.guess_extension(magic.from_buffer(buffer, mime=True))
if mimetype == 'application/octet-stream':
if buffer.startswith(b'UnityFS'):
mimetype = "application/unityfs"
extension = ".unity3d"
elif buffer.startswith(b'\x89PNG'):
mimetype = "image/png"
extension = ".png"
else:
#print(buffer)
pass
key[0] = key1 # hack: reset rng state, codec has reference to this array
key[1] = key2
key[2] = 0x3039
pkg.seek(head)
print("[%s] decrypting to %s (%s)" % (destination, extension, mimetype))
if os.path.exists(destination + extension):
print("File already created - Skipping")
pass
else:
with open(destination + extension, 'wb+') as dst:
shutil.copyfileobj(pkg, dst, size)
pkg.close()
return destination + extension
except FileNotFoundError:
print("File not found!")
pass
def getDictionaryValue(dictionary_key):
filtered_json = json.dumps([element for element in json_dictionary if element['id'] == dictionary_key.split(".")[1]])
return re.sub('\W+',' ', json.loads(filtered_json)[0]["message"]).strip()
def decrypt_on(table, pack_name, output):
source = os.path.abspath(".")
destination = os.path.join(os.path.join(source, output + "/" + table), pack_name)
try:
os.makedirs(destination)
except FileExistsError:
pass
assetsdb = klb_sqlite(find_db('asset_a_en', source)).cursor()
asset_query = f"SELECT asset_path, pack_name, head, size, key1, key2 FROM {table} WHERE pack_name == '{pack_name}'"
for (asset_path, pack_name, head, size, key1, key2) in assetsdb.execute(asset_query):
result = decrypt(pack_name, head, size, key1, key2, destination)
return result
def decrypt_asset_on(table, asset_id, output):
source = os.path.abspath(".")
destination = os.path.join(source, output)
try:
os.makedirs(destination)
except FileExistsError:
pass
assetsdb = klb_sqlite(find_db('asset_a_en', source)).cursor()
asset_query = "SELECT asset_path, pack_name, head, size, key1, key2 FROM " + table + " WHERE asset_path == '" + asset_id.replace("'","''") + "'" #no tocar esto......
print(asset_query)
for (asset_path, pack_name, head, size, key1, key2) in assetsdb.execute(asset_query):
result = decrypt(pack_name, head, size, key1, key2, destination)
return result
def unpack_advscript(filepath, output):
source = os.path.abspath(".")
file = os.path.join(source, filepath)
out = os.path.join(source, output)
#LLAS LZ77 test (intento de implementacion parcial y limitada de esto: https://suyo.be/sifas/wiki/internals/advscript-format)
with open(file, "rb") as f:
f.seek(27) #saltear header
data = bytearray(f.read())
c = 0
while (data.find(b'\x80', c+1) != -1):
c = data.find(b'\x80', c+1)
offset = int(data[c+1:c+2].hex(), 16) + 1
length = int(data[c+2:c+3].hex(), 16) + 1
if (c - offset + length) < c:
value = data[c-offset: c-offset+length]
data[c:c+1] = value
data[c+length:c+length+2] = data[0:0] #mi hack para eliminar 2 bytes...
else:
value = data[c-offset: c-offset+length]
c_pos = value.find(b'\x80')
original_value = value[:c_pos]
original_value_length = len(original_value)
extra_length = length - original_value_length
buff = original_value
for i in range(extra_length-1):
buff = buff + original_value
data[c:c+1] = original_value + buff[:extra_length]
data[c+length:c+length+2] = data[0:0]
with open(out, 'wb+') as f:
f.write(data)
def unpack_character(character_id, output):
source = os.path.abspath(".")
destination = os.path.join(os.path.join(source, output), names[int(character_id)])
try:
os.makedirs(destination)
except FileExistsError:
pass
masterdb = klb_sqlite(find_db('masterdata', source)).cursor()
assetsdb = klb_sqlite(find_db('asset_a_en', source)).cursor()
master_query = "select id, member_m_id, name, thumbnail_image_asset_path, model_asset_path from m_suit WHERE member_m_id == :character_id"
for (id, member_m_id, name, thumbnail_image_asset_path, model_asset_path) in masterdb.execute(master_query, {'character_id': character_id}):
item_full_name = getDictionaryValue(name)
print(f"{id} - {item_full_name} - {thumbnail_image_asset_path} - {model_asset_path}")
texture_asset_query = "select asset_path, pack_name, head, size, key1, key2 from texture WHERE asset_path == :path"
for (asset_path, pack_name, head, size, key1, key2) in assetsdb.execute(texture_asset_query, {'path': thumbnail_image_asset_path}):
destination_path = os.path.join(destination, item_full_name)
try:
os.makedirs(destination_path)
except FileExistsError:
pass
decrypt(pack_name, head, size, key1, key2, destination_path)
model_asset_query = "select DISTINCT m_asset_package_mapping.package_key, member_model.pack_name, member_model.head, member_model.size, member_model.key1, member_model.key2 from member_model INNER JOIN m_asset_package_mapping ON m_asset_package_mapping.pack_name = member_model.pack_name where m_asset_package_mapping.package_key == :package_key"
destination_path = os.path.join(destination, item_full_name + "/model")
try:
os.makedirs(destination_path)
except FileExistsError:
pass
with mp.Pool() as pool:
results = []
try:
for (package_key, pack_name, head, size, key1, key2) in assetsdb.execute(model_asset_query, {'package_key': "suit:" + str(id)}):
results.append(pool.apply_async(decrypt, (pack_name, head, size, key1, key2, destination_path)))
except Exception:
print("Error en el pool desencriptando los modelos.")
pass
for result in results:
print("[%s] done" % result.get())
def unpack_stage_from(group_id, output):
source = os.path.abspath(".")
destination = os.path.join(source, output, group_id)
try:
os.makedirs(destination)
except FileExistsError:
pass
masterdb = klb_sqlite(find_db('masterdata', source)).cursor()
assetsdb = klb_sqlite(find_db('asset_a_en', source)).cursor()
query = "SELECT DISTINCT m_live_mv.live_id, m_live_mv.live_stage_master_id, m_live_mv.live_3d_asset_master_id, m_live.name, m_live.jacket_asset_path, m_live.original_deck_name, m_live_3d_asset.timeline, m_live_3d_asset.stage_effect_asset_path, m_live_3d_asset.live_prop_skeleton_asset_path, m_live_3d_asset.shader_variant_asset_path FROM m_live_mv INNER JOIN m_live ON m_live.live_id = m_live_mv.live_id INNER JOIN m_live_3d_asset ON m_live_3d_asset.id = m_live_mv.live_3d_asset_master_id WHERE m_live.original_deck_name == 'k.m_dic_group_name_" + group_id + "' OR m_live.original_deck_name == 'k.m_dic_member_name_" + group_id + "'"
for (live_id, live_stage_master_id, live_3d_asset_master_id, name, jacket_asset_path, original_deck_name, timeline, stage_effect_asset_path, live_prop_skeleton_asset_path, shader_variant_asset_path) in masterdb.execute(query):
song_name = getDictionaryValue(name)
#print(f"{live_id} - {live_stage_master_id} - {live_3d_asset_master_id} - {song_name} - {jacket_asset_path} - {original_deck_name} - {timeline} - {stage_effect_asset_path} - {live_prop_skeleton_asset_path} - {shader_variant_asset_path}")
destination_path = os.path.join(destination, song_name)
stage_destination_path = os.path.join(destination_path, "stage_models")
chara_timeline_destination_path = os.path.join(destination_path, "live_timeline")
try:
os.makedirs(stage_destination_path)
os.makedirs(chara_timeline_destination_path)
except FileExistsError:
pass
#extraer assets independientes (timeline, stage_effect_asset_path, etc)
decrypt_asset_on("texture", jacket_asset_path, destination_path) #cover
#decrypt_asset_on("live_timeline", timeline, os.path.join(destination_path, "stage_timeline")) #deprecated
decrypt_asset_on("stage_effect", stage_effect_asset_path, os.path.join(destination_path, "stage_effects"))
#decrypt_asset_on("live_prop_skeleton", live_prop_skeleton_asset_path, os.path.join(destination_path, "live_prop_models")) #ejemplo: el megáfono de setsuna, NULL si no hay props.
#decrypt_asset_on("shader", live_prop_skeleton_asset_path, os.path.join(destination_path, "live_shader")) #NULL si no hay custom shaders
#extraer stages
stage_asset_query = "SELECT DISTINCT m_asset_package_mapping.package_key, stage.pack_name, stage.head, stage.size, stage.key1, stage.key2 from stage INNER JOIN m_asset_package_mapping ON m_asset_package_mapping.pack_name = stage.pack_name WHERE m_asset_package_mapping.package_key == :package_key"
for (package_key, pack_name, head, size, key1, key2) in assetsdb.execute(stage_asset_query, {'package_key': "live:" + str(live_3d_asset_master_id)}):
print(f"{package_key} - {pack_name} - {head} - {size} - {key1} - {key2}")
decrypt(pack_name, head, size, key1, key2, stage_destination_path)
#extraer coreografia/s (character timelines)
stage_asset_query = "SELECT DISTINCT m_asset_package_mapping.package_key, live_timeline.pack_name, live_timeline.head, live_timeline.size, live_timeline.key1, live_timeline.key2 from live_timeline INNER JOIN m_asset_package_mapping ON m_asset_package_mapping.pack_name = live_timeline.pack_name WHERE m_asset_package_mapping.package_key == :package_key"
for (package_key, pack_name, head, size, key1, key2) in assetsdb.execute(stage_asset_query, {'package_key': "live:" + str(live_3d_asset_master_id)}):
print(f"{package_key} - {pack_name} - {head} - {size} - {key1} - {key2}")
decrypt(pack_name, head, size, key1, key2, chara_timeline_destination_path)
#EXPERIMENTAL: tests (ignorar)
def tests(args):
source = os.path.abspath(".")
destination = os.path.join(args.source, args.output, "test")
group_id = "aqours"
try:
os.makedirs(destination)
except FileExistsError:
pass
masterdb = klb_sqlite(find_db('masterdata', args.source)).cursor()
assetsdb = klb_sqlite(find_db('asset_a_en', args.source)).cursor()
query = "SELECT DISTINCT m_live_mv.live_id, m_live_mv.live_stage_master_id, m_live_mv.live_3d_asset_master_id, m_live.name, m_live.jacket_asset_path, m_live.original_deck_name, m_live_3d_asset.timeline, m_live_3d_asset.stage_effect_asset_path, m_live_3d_asset.live_prop_skeleton_asset_path, m_live_3d_asset.shader_variant_asset_path FROM m_live_mv INNER JOIN m_live ON m_live.live_id = m_live_mv.live_id INNER JOIN m_live_3d_asset ON m_live_3d_asset.id = m_live_mv.live_3d_asset_master_id WHERE m_live.original_deck_name == 'k.m_dic_group_name_" + group_id + "' OR m_live.original_deck_name == 'k.m_dic_member_name_" + group_id + "'"
for (live_id, live_stage_master_id, live_3d_asset_master_id, name, jacket_asset_path, original_deck_name, timeline, stage_effect_asset_path, live_prop_skeleton_asset_path, shader_variant_asset_path) in masterdb.execute(query):
song_name = getDictionaryValue(name)
#print(f"{live_id} - {live_stage_master_id} - {live_3d_asset_master_id} - {song_name} - {jacket_asset_path} - {original_deck_name} - {timeline} - {stage_effect_asset_path} - {live_prop_skeleton_asset_path} - {shader_variant_asset_path}")
destination_path = os.path.join(destination, song_name)
stage_destination_path = os.path.join(destination_path, "stage_models")
chara_timeline_destination_path = os.path.join(destination_path, "live_timeline")
try:
os.makedirs(stage_destination_path)
os.makedirs(chara_timeline_destination_path)
except FileExistsError:
pass
#extraer assets independientes (timeline, stage_effect_asset_path, etc)
decrypt_asset_on("texture", jacket_asset_path, destination_path) #cover
#decrypt_asset_on("live_timeline", timeline, os.path.join(destination_path, "stage_timeline")) #deprecated
decrypt_asset_on("stage_effect", stage_effect_asset_path, os.path.join(destination_path, "stage_effects"))
#decrypt_asset_on("live_prop_skeleton", live_prop_skeleton_asset_path, os.path.join(destination_path, "live_prop_models")) #ejemplo: el megáfono de setsuna, NULL si no hay props.
#decrypt_asset_on("shader", live_prop_skeleton_asset_path, os.path.join(destination_path, "live_shader")) #NULL si no hay custom shaders
#extraer stages
stage_asset_query = "SELECT DISTINCT m_asset_package_mapping.package_key, stage.pack_name, stage.head, stage.size, stage.key1, stage.key2 from stage INNER JOIN m_asset_package_mapping ON m_asset_package_mapping.pack_name = stage.pack_name WHERE m_asset_package_mapping.package_key == :package_key"
for (package_key, pack_name, head, size, key1, key2) in assetsdb.execute(stage_asset_query, {'package_key': "live:" + str(live_3d_asset_master_id)}):
print(f"{package_key} - {pack_name} - {head} - {size} - {key1} - {key2}")
decrypt(pack_name, head, size, key1, key2, stage_destination_path)
#extraer coreografia/s (character timelines)
stage_asset_query = "SELECT DISTINCT m_asset_package_mapping.package_key, live_timeline.pack_name, live_timeline.head, live_timeline.size, live_timeline.key1, live_timeline.key2 from live_timeline INNER JOIN m_asset_package_mapping ON m_asset_package_mapping.pack_name = live_timeline.pack_name WHERE m_asset_package_mapping.package_key == :package_key"
for (package_key, pack_name, head, size, key1, key2) in assetsdb.execute(stage_asset_query, {'package_key': "live:" + str(live_3d_asset_master_id)}):
print(f"{package_key} - {pack_name} - {head} - {size} - {key1} - {key2}")
decrypt(pack_name, head, size, key1, key2, chara_timeline_destination_path)
#UTILIDAD: desenpaqueta un advscript a texto plano
def advscript_unpack(args):
advfile = decrypt_on("adv_script", args.pack_name, args.output)
unpack_advscript(advfile, advfile + "_unpacked.txt")
#UTILIDAD: extrae un pack especifico en una tabla EJEMPLO: d member_model 108mqo
def decrypt_element(args):
decrypt_on(args.table, args.pack_name, args.output)
#UTILIDAD: extrae todos los trajes de x personaje, junto con un thumbnail EJEMPLO: chu 101 modelos_extraidos
def chara_unpack(args):
unpack_character(args.character_id, args.output)
#UTILIDAD: extrae todos los escenarios (3D) donde participan, x personaje/generacion/subunidad
#GROUP_ID: muse, aqours, niji, lili_white, printemps, bibi, cyaron, azalea, guilty_kiss, diver_diva, azuna, qu4rtz, r3birth, [character_id para los solos EN 3D]
def stage_unpack(args):
unpack_stage_from(args.group_id, args.output)
#################
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Script de pruebas y herramientas propias')
sub = parser.add_subparsers()
test_help = 'codigo experimental'
test = sub.add_parser('test', aliases=['tst'], help=test_help)
test.add_argument('source', nargs='?', help=test_help, default='.')
test.add_argument('output', nargs='?', help=test_help, default='test')
test.set_defaults(func=tests)
chu_help = 'charaunpack character_id'
chu = sub.add_parser('charaunpack', aliases=['chu'], help=chu_help)
chu.add_argument('character_id', nargs='?', help=chu_help, default='1')
chu.add_argument('output', nargs='?', help=chu_help, default='unpacked_character')
chu.set_defaults(func=chara_unpack)
lvu_help = 'liveunpack group_id'
lvu = sub.add_parser('liveunpack', aliases=['lvu'], help=lvu_help)
lvu.add_argument('group_id', nargs='?', help=lvu_help, default='muse')
lvu.add_argument('output', nargs='?', help=lvu_help, default='unpacked_stages')
lvu.set_defaults(func=stage_unpack)
dcr_help = 'decrypt table pack_name output'
dcr = sub.add_parser('decrypt', aliases=['d'], help=dcr_help)
dcr.add_argument('table', nargs='?', help=dcr_help, default='textures')
dcr.add_argument('pack_name', nargs='?', help=dcr_help, default='none')
dcr.add_argument('output', nargs='?', help=dcr_help, default='decrypted_output')
dcr.set_defaults(func=decrypt_element)
adv_help = 'advunpack pack_name output'
adv = sub.add_parser('advunpack', aliases=['advu'], help=adv_help)
adv.add_argument('pack_name', nargs='?', help=adv_help, default='none')
adv.add_argument('output', nargs='?', help=adv_help, default='decrypted_output')
adv.set_defaults(func=advscript_unpack)
args = parser.parse_args(sys.argv[1:])
if 'func' not in args:
parser.parse_args(['-h'])
args.func(args)