Files
blitz-tools/extractTankopedia.py
T

179 lines
6.7 KiB
Python
Raw Normal View History

2018-10-03 23:17:27 +08:00
#!/usr/bin/python3.7
2018-10-01 12:17:54 +08:00
# Extract tankopedia data in WG API JSON format from Blitz app files (Android APK unzipped)
2018-10-02 20:58:36 +08:00
import sys, argparse, json, os, inspect, aiohttp, asyncio, aiofiles, re, logging, time, xmltodict, collections
2018-10-04 11:24:24 +08:00
import blitzutils as bu
2018-10-03 23:17:27 +08:00
from blitzutils import WG
2018-10-01 12:17:54 +08:00
logging.getLogger("asyncio").setLevel(logging.DEBUG)
BLITZAPP_STRINGS='/assets/Data/Strings/en.yaml'
BLITZAPP_VEHICLES_DIR='/assets/Data/XML/item_defs/vehicles/'
BLITZAPP_VEHICLE_FILE='/list.xml'
2018-10-04 11:24:24 +08:00
wg = None
2018-10-01 12:17:54 +08:00
## main() -------------------------------------------------------------
async def main(argv):
2018-10-04 11:24:24 +08:00
global wg
2019-12-17 21:25:54 +02:00
# set the directory for the script
os.chdir(os.path.dirname(sys.argv[0]))
2018-10-01 12:17:54 +08:00
parser = argparse.ArgumentParser(description='Extract Tankopedia data from Blitz game files')
parser.add_argument('blitzAppBase', type=str, metavar="BLITZAPP_FOLDER", default=".", help='Base dir of the Blitz App files')
parser.add_argument('tanks', type=str, default='tanks.json', nargs='?', metavar="TANKS_FILE", help='File to write Tankopedia')
parser.add_argument('maps', type=str, default='maps.json', nargs='?', metavar='MAPS_FILE', help='File to write map names')
2018-10-01 12:17:54 +08:00
parser.add_argument('-d', '--debug', action='store_true', default=False, help='Debug mode')
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose mode')
args = parser.parse_args()
2018-10-04 11:24:24 +08:00
bu.setVerbose(args.verbose)
bu.setDebug(args.debug)
wg = WG()
2018-10-01 12:17:54 +08:00
tasks = []
2018-10-03 23:17:27 +08:00
for nation in wg.nations:
2018-10-01 12:17:54 +08:00
tasks.append(asyncio.create_task(extractTanks(args.blitzAppBase, nation)))
tanklist = []
for tanklist_tmp in await asyncio.gather(*tasks):
tanklist.extend(tanklist_tmp)
2018-10-02 14:40:41 +08:00
tank_strs, map_strs = await readUserStrs(args.blitzAppBase)
2019-01-29 10:35:35 +02:00
json_data = None
userStrs = {}
tanks = {}
if os.path.exists(args.tanks):
try:
async with aiofiles.open(args.tanks) as infile:
json_data = json.loads(await infile.read())
userStrs = json_data['userStr']
tanks = json_data['data']
except Exception as err:
bu.error('Unexpected error when reading file: ' + args.tanks + ' : ' + str(err))
2018-10-04 11:24:24 +08:00
async with aiofiles.open(args.tanks, 'w', encoding="utf8") as outfile:
2019-01-29 10:35:35 +02:00
new_tanks, new_userStrs = await convertTankNames(tanklist, tank_strs)
# merge old and new tankopedia
tanks.update(new_tanks)
userStrs.update(new_userStrs)
2018-10-04 11:24:24 +08:00
tankopedia = collections.OrderedDict()
2018-10-01 12:17:54 +08:00
tankopedia['status'] = 'ok'
2019-01-29 10:35:35 +02:00
tankopedia['meta'] = { "count": len(tanks) }
tankopedia['data'] = tanks
tankopedia['userStr'] = userStrs
2018-10-02 20:58:36 +08:00
await outfile.write(json.dumps(tankopedia, ensure_ascii=False, indent=4, sort_keys=False))
2018-10-02 14:40:41 +08:00
2018-10-04 11:24:24 +08:00
if args.maps != None:
2019-01-29 10:35:35 +02:00
maps = {}
if os.path.exists(args.maps):
try:
async with aiofiles.open(args.maps) as infile:
maps = json.loads(await infile.read())
except Exception as err:
bu.error('Unexpected error when reading file: ' + args.maps + ' : ' + str(err))
# merge old and new map data
maps.update(map_strs)
2018-10-04 11:24:24 +08:00
async with aiofiles.open(args.maps, 'w', encoding="utf8") as outfile:
2019-01-29 10:35:35 +02:00
await outfile.write(json.dumps(maps, ensure_ascii=False, indent=4, sort_keys=True))
2018-10-01 12:17:54 +08:00
return None
async def extractTanks(blitzAppBase : str, nation: str):
tanks = []
list_xml_file = blitzAppBase + BLITZAPP_VEHICLES_DIR + nation + BLITZAPP_VEHICLE_FILE
if not os.path.isfile(list_xml_file):
print('ERROR: cannot open ' + list_xml_file)
return None
2018-10-04 11:24:24 +08:00
bu.debug('Opening file: ' + list_xml_file + ' (Nation: ' + nation + ')')
async with aiofiles.open(list_xml_file, 'r', encoding="utf8") as f:
2018-10-01 12:17:54 +08:00
try:
tankList = xmltodict.parse(await f.read())
for data in tankList['root'].keys():
tank_xml = tankList['root'][data]
tank = {}
tank['tank_id'] = await getTankID(nation, int(tank_xml['id']))
tank['userStr'] = tank_xml['userString']
tank['nation'] = nation
tank['tier'] = int(tank_xml['level'])
#debug(tank_xml['price'])
tank['is_premium'] = issubclass(type(tank_xml['price']), dict)
tank['type'] = await getTankType(tank_xml['tags'])
tanks.append(tank)
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-01 12:17:54 +08:00
sys.exit(2)
return tanks
2018-10-02 14:40:41 +08:00
async def readUserStrs(blitzAppBase : str) -> dict:
"""Read user strings to convert map and tank names"""
tank_strs = {}
map_strs = {}
2018-10-01 12:17:54 +08:00
filename = blitzAppBase + BLITZAPP_STRINGS
2018-10-04 11:24:24 +08:00
bu.debug('Opening file: ' + filename + ' for reading UserStrings')
2018-10-01 12:17:54 +08:00
try:
async with aiofiles.open(filename, 'r', encoding="utf8") as f:
2018-10-02 14:40:41 +08:00
p_tank = re.compile('^"(#\\w+?_vehicles:.+?)": "(.+)"$')
p_map = re.compile('^"#maps:(.+?):.+?: "(.+?)"$')
2018-10-01 12:17:54 +08:00
async for l in f:
2018-10-02 14:40:41 +08:00
m = p_tank.match(l)
if m != None:
tank_strs[m.group(1)] = m.group(2)
m = p_map.match(l)
2018-10-08 00:14:08 +08:00
if m != None and m.group(2) != 'Macragge':
2018-10-02 14:40:41 +08:00
map_strs[m.group(1)] = m.group(2)
2018-10-01 12:17:54 +08:00
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-01 12:17:54 +08:00
sys.exit(1)
2018-10-02 14:40:41 +08:00
return tank_strs, map_strs
async def convertTankNames(tanklist : list, tank_strs: dict) -> dict:
"""Convert tank names for Tankopedia"""
tankopedia = {}
userStrs = {}
2018-10-04 11:24:24 +08:00
2018-10-02 14:40:41 +08:00
try:
for tank in tanklist:
tank['name'] = tank_strs[tank['userStr']]
userStrs[tank['userStr'].split(':')[1]] = tank['name']
tank.pop('userStr', None)
tankopedia[str(tank['tank_id'])] = tank
2018-10-02 20:58:36 +08:00
2018-10-04 11:24:24 +08:00
# sorting
2018-10-02 20:58:36 +08:00
tankopedia_sorted = collections.OrderedDict()
2018-10-04 11:24:24 +08:00
for tank_id in sorted(tankopedia.keys(), key=int):
2018-10-02 20:58:36 +08:00
tankopedia_sorted[str(tank_id)] = tankopedia[str(tank_id)]
2018-10-04 11:24:24 +08:00
userStrs_sorted = collections.OrderedDict()
for userStr in sorted(userStrs.keys()):
userStrs_sorted[userStr] = userStrs[userStr]
2018-10-02 14:40:41 +08:00
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-02 14:40:41 +08:00
sys.exit(1)
2018-10-04 11:24:24 +08:00
return tankopedia_sorted, userStrs_sorted
2018-10-01 12:17:54 +08:00
async def getTankID(nation: str, tankID : int) -> int:
2018-10-04 11:24:24 +08:00
return (tankID << 8) + (wg.nation_id[nation] << 4) + 1
2018-10-01 12:17:54 +08:00
async def getTankType(tagstr : str):
tags = tagstr.split(' ')
2018-10-03 23:17:27 +08:00
for t_type in wg.tank_type:
2018-10-01 12:17:54 +08:00
if tags[0] == t_type:
return t_type
return None
### main()
if __name__ == "__main__":
#asyncio.run(main(sys.argv[1:]), debug=True)
asyncio.run(main(sys.argv[1:]))