Whitespace

This commit is contained in:
Jylpah authored and jylpah committed 2023-09-10 17:47:13 +03:00
1 parent 3f4e9c42d1
commit d4a35e6e8d
2 files changed
+121 -99

No files matched your search

+88 -82
View File
@@ -100,7 +100,7 @@ class ThrottledClientSession(aiohttp.ClientSession):
def get_stats_str(self) -> str: def get_stats_str(self) -> str:
"""Print session statistics""" """Print session statistics"""
return f"rate limit: {str(self.rate_limit if self.rate_limit != None else '-')} \ return f"rate limit: {str(self.rate_limit if self.rate_limit is not None else '-')} \
rate: {0:.1f}.format(self.get_rate()) requests: {str(self._count)}" rate: {0:.1f}.format(self.get_rate()) requests: {str(self._count)}"
@@ -203,7 +203,7 @@ class AsyncLogger():
async def open(self, logfn: str = None): async def open(self, logfn: str = None):
"""Set logging to file""" """Set logging to file"""
if logfn == None: if logfn is None:
logfn = 'LOG_' + _randomword(6) + '.log' logfn = 'LOG_' + _randomword(6) + '.log'
try: try:
self._file = await aiofiles.open(logfn, mode='a') self._file = await aiofiles.open(logfn, mode='a')
@@ -216,7 +216,7 @@ class AsyncLogger():
async def logger(self): async def logger(self):
"""Async file logger""" """Async file logger"""
if self._file == None: if self._file is None:
error('No log file defined') error('No log file defined')
return False return False
while True: while True:
@@ -306,7 +306,7 @@ async def set_file_logging(logfn=None, add_timestamp=False):
"""Set logging to file""" """Set logging to file"""
global LOG, LOGGER global LOG, LOGGER
LOG = True LOG = True
if logfn == None: if logfn is None:
logfn = 'LOG_' + _randomword(6) logfn = 'LOG_' + _randomword(6)
else: else:
dateTimeObj = datetime.now() dateTimeObj = datetime.now()
@@ -382,7 +382,9 @@ def get_class_from_frame(fr):
return None return None
def _print_log_msg(prefix = 'LOG', msg = '', exception = None, id = None, print_msg : bool = True): def _print_log_msg(prefix: str = 'LOG', msg:str = '',
exception: Exception | None = None,
id: int|None = None, print_msg : bool = True):
# Use empty prefix to determine standard verbose messages # Use empty prefix to determine standard verbose messages
if not (print_msg or LOG): if not (print_msg or LOG):
return False return False
@@ -392,20 +394,20 @@ def _print_log_msg(prefix = 'LOG', msg = '', exception = None, id = None, print_
calframe = inspect.getouterframes(curframe) calframe = inspect.getouterframes(curframe)
class_name = get_class_from_frame(curframe) class_name = get_class_from_frame(curframe)
caller = calframe[2].function caller = calframe[2].function
if class_name != None: if class_name is not None:
prefix = prefix + ': ' + class_name + '.' + caller prefix = f'{prefix}: {class_name}.{caller}'
else: else:
prefix = prefix + ': ' + caller prefix = prefix + ': ' + caller
prefix = prefix + '(): ' prefix = prefix + '(): '
if id != None: if id is not None:
prefix = prefix + '[' + str(id) + ']: ' prefix = f'{prefix} [ {id}]: '
exception_msg = '' exception_msg = ''
if (exception != None) and isinstance(exception, Exception): if (exception is not None) and isinstance(exception, Exception):
exception_msg = ' : Exception: ' + str(type(exception)) + ' : ' + str(exception) exception_msg = f' : Exception: {type(exception)} : {exception}'
msg = prefix + msg + exception_msg msg = f'{prefix}{msg}{exception_msg}'
if print_msg: if print_msg:
print(msg) print(msg)
retval = True retval = True
@@ -414,8 +416,8 @@ def _print_log_msg(prefix = 'LOG', msg = '', exception = None, id = None, print_
return retval return retval
def _log_msg(msg =''): def _log_msg(msg :str=''):
if LOG and (LOGGER != None): if LOG and (LOGGER is not None):
LOGGER.log(msg) LOGGER.log(msg)
return True return True
return False return False
@@ -438,11 +440,11 @@ def get_progress_step():
def set_progress_bar(heading: str, max_value: int, step: int = None, slow: bool = False, id: str = None): def set_progress_bar(heading: str, max_value: int, step: int = None, slow: bool = False, id: str = None):
global _progress_obj, _progress_N, _progress_i, _progress_id global _progress_obj, _progress_N, _progress_i, _progress_id
_progress_id = id _progress_id = id
if step == None: if step is None:
_progress_N = int(max_value / 1000) if (max_value > 1000) else 2 _progress_N = int(max_value / 1000) if (max_value > 1000) else 2
else: else:
_progress_N = step _progress_N = step
if _progress_obj != None: if _progress_obj is not None:
finish_progress_bar() finish_progress_bar()
if slow: if slow:
_progress_obj = SlowBar(heading, max=max_value) _progress_obj = SlowBar(heading, max=max_value)
@@ -457,10 +459,10 @@ def set_progress_bar(heading: str, max_value: int, step: int = None, slow: bool
def set_counter(heading: str, step = None): def set_counter(heading: str, step = None):
global _progress_obj, _progress_i global _progress_obj, _progress_i
_progress_i = 0 _progress_i = 0
if _progress_obj != None: if _progress_obj is not None:
finish_progress_bar() finish_progress_bar()
_progress_obj = Counter(heading + ': ') _progress_obj = Counter(heading + ': ')
if step != None: if step is not None:
set_progress_step(step) set_progress_step(step)
return return
@@ -472,7 +474,7 @@ def print_progress(force = False, id : str = None) -> bool:
_progress_i += 1 _progress_i += 1
if ((_progress_i % _progress_N) == 0): if ((_progress_i % _progress_N) == 0):
if (_log_level > SILENT) and ( force or (_log_level < DEBUG ) ): if (_log_level > SILENT) and ( force or (_log_level < DEBUG ) ):
if (_progress_obj != None): if (_progress_obj is not None):
if (_progress_id == id): if (_progress_id == id):
_progress_obj.next(_progress_N) _progress_obj.next(_progress_N)
return True return True
@@ -489,7 +491,7 @@ def finish_progress_bar():
global _progress_obj global _progress_obj
# print_nl = True # print_nl = True
if _progress_obj != None: if _progress_obj is not None:
# if isinstance(_progress_obj, Counter): # if isinstance(_progress_obj, Counter):
# print_nl = False # print_nl = False
_progress_obj.finish() _progress_obj.finish()
@@ -574,7 +576,7 @@ async def open_JSON(filename: str, chk_JSON_func = None) -> dict:
try: try:
async with aiofiles.open(filename) as fp: async with aiofiles.open(filename) as fp:
json_data = json.loads(await fp.read()) json_data = json.loads(await fp.read())
if (chk_JSON_func == None): if (chk_JSON_func is None):
debug("JSON file content not checked: " + filename) debug("JSON file content not checked: " + filename)
return json_data return json_data
elif chk_JSON_func(json_data): elif chk_JSON_func(json_data):
@@ -589,10 +591,10 @@ async def open_JSON(filename: str, chk_JSON_func = None) -> dict:
async def get_url_JSON(session: aiohttp.ClientSession, url: str, chk_JSON_func = None, max_tries = MAX_RETRIES) -> dict: async def get_url_JSON(session: aiohttp.ClientSession, url: str, chk_JSON_func = None, max_tries = MAX_RETRIES) -> dict:
"""Retrieve (GET) an URL and return JSON object""" """Retrieve (GET) an URL and return JSON object"""
if session == None: if session is None:
error('Session must be initialized first') error('Session must be initialized first')
sys.exit(1) sys.exit(1)
if url == None: if url is None:
return None return None
# To avoid excessive use of servers # To avoid excessive use of servers
@@ -602,7 +604,7 @@ async def get_url_JSON(session: aiohttp.ClientSession, url: str, chk_JSON_func =
if resp.status == 200: if resp.status == 200:
debug('HTTP request OK') debug('HTTP request OK')
json_resp = await resp.json() json_resp = await resp.json()
if (chk_JSON_func == None) or chk_JSON_func(json_resp): if (chk_JSON_func is None) or chk_JSON_func(json_resp):
# debug("Received valid JSON: " + str(json_resp)) # debug("Received valid JSON: " + str(json_resp))
return json_resp return json_resp
# Sometimes WG API returns JSON error even a retry gives valid JSON # Sometimes WG API returns JSON error even a retry gives valid JSON
@@ -644,14 +646,18 @@ def bld_dict_hierarcy(d : dict, key : str, value) -> dict:
return None return None
def get_JSON_keypath(keypath: str, key: str): def get_JSON_keypath(keypath: str, key: str):
if keypath == None: if keypath is None:
return key return key
else: else:
return '.'.join([keypath, key]) return '.'.join([keypath, key])
def get_JSON_value(json, key : str = None, keys : list = None, keypath = None): def get_JSON_value(json, key : str | None = None, keys : list | None = None,
if (keys == None) and (key != None): keypath : str | None = None):
if (keys is None):
if key is not None:
keys = key.split('.') keys = key.split('.')
else:
return json
if len(keys) == 0: if len(keys) == 0:
return json return json
key = keys.pop(0) key = keys.pop(0)
@@ -874,7 +880,7 @@ class WG:
WG.tanks = self.tanks WG.tanks = self.tanks
self.global_rate_limit = global_rate_limit self.global_rate_limit = global_rate_limit
if (maps_fn != None): if (maps_fn is not None):
if os.path.exists(maps_fn) and os.path.isfile(maps_fn): if os.path.exists(maps_fn) and os.path.isfile(maps_fn):
try: try:
with open(maps_fn, 'rt', encoding='utf8') as f: with open(maps_fn, 'rt', encoding='utf8') as f:
@@ -883,7 +889,7 @@ class WG:
error('Could not read maps file: ' + maps_fn + '\n' + str(err)) error('Could not read maps file: ' + maps_fn + '\n' + str(err))
else: else:
verbose('Could not find maps file: ' + maps_fn) verbose('Could not find maps file: ' + maps_fn)
if self.WG_app_id != None: if self.WG_app_id is not None:
headers = {'Accept-Encoding': 'gzip, deflate'} headers = {'Accept-Encoding': 'gzip, deflate'}
if self.global_rate_limit: if self.global_rate_limit:
self.session = ThrottledClientSession(rate_limit=rate_limit, headers=headers) self.session = ThrottledClientSession(rate_limit=rate_limit, headers=headers)
@@ -912,7 +918,7 @@ class WG:
async def close(self): async def close(self):
# close stats queue # close stats queue
try: try:
if self.statsQ != None: if self.statsQ is not None:
debug('WG.close(): Waiting for statsQ to finish') debug('WG.close(): Waiting for statsQ to finish')
await self.statsQ.join() await self.statsQ.join()
debug('WG.close(): statsQ finished') debug('WG.close(): statsQ finished')
@@ -921,13 +927,13 @@ class WG:
await self.stat_saver_task await self.stat_saver_task
# close cacheDB # close cacheDB
if self.cache != None: if self.cache is not None:
# prune old cache records # prune old cache records
await self.cleanup_cache() await self.cleanup_cache()
await self.cache.commit() await self.cache.commit()
await self.cache.close() await self.cache.close()
if self.session != None: if self.session is not None:
if self.global_rate_limit: if self.global_rate_limit:
await self.session.close() await self.session.close()
else: else:
@@ -981,7 +987,7 @@ class WG:
@classmethod @classmethod
def chk_JSON(cls, json_obj, check = None) -> bool: def chk_JSON(cls, json_obj, check = None) -> bool:
try: try:
if (check == None): if (check is None):
# nothing to check # nothing to check
return True return True
if (check == 'tank_stats'): if (check == 'tank_stats'):
@@ -1016,16 +1022,16 @@ class WG:
@classmethod @classmethod
def chk_JSON_status(cls, json_resp: dict) -> bool: def chk_JSON_status(cls, json_resp: dict) -> bool:
try: try:
if (json_resp == None) or ('status' not in json_resp) or (json_resp['status'] == None): if (json_resp is None) or ('status' not in json_resp) or (json_resp['status'] is None):
return False return False
elif (json_resp['status'] == 'ok') and ('data' in json_resp): elif (json_resp['status'] == 'ok') and ('data' in json_resp):
return True return True
elif json_resp['status'] == 'error': elif json_resp['status'] == 'error':
if ('error' in json_resp): if ('error' in json_resp):
error_msg = 'Received an error' error_msg = 'Received an error'
if ('message' in json_resp['error']) and (json_resp['error']['message'] != None): if ('message' in json_resp['error']) and (json_resp['error']['message'] is not None):
error_msg = error_msg + ': ' + json_resp['error']['message'] error_msg = error_msg + ': ' + json_resp['error']['message']
if ('value' in json_resp['error']) and (json_resp['error']['value'] != None): if ('value' in json_resp['error']) and (json_resp['error']['value'] is not None):
error_msg = error_msg + ' Value: ' + json_resp['error']['value'] error_msg = error_msg + ' Value: ' + json_resp['error']['value']
debug(error_msg) debug(error_msg)
return False return False
@@ -1084,7 +1090,7 @@ class WG:
try: try:
if cls.chk_JSON_status(json_resp): if cls.chk_JSON_status(json_resp):
for acc in json_resp['data']: for acc in json_resp['data']:
if json_resp['data'][acc] != None: if json_resp['data'][acc] is not None:
return True return True
except KeyError as err: except KeyError as err:
error('Key not found', err) error('Key not found', err)
@@ -1110,7 +1116,7 @@ class WG:
# Methods -------------------------------------------------- # Methods --------------------------------------------------
def load_tanks(self, tankopedia_fn: str): def load_tanks(self, tankopedia_fn: str):
"""Load tanks from tankopedia JSON""" """Load tanks from tankopedia JSON"""
if tankopedia_fn == None: if tankopedia_fn is None:
return False return False
try: try:
with open(tankopedia_fn, 'rt', encoding='utf8') as f: with open(tankopedia_fn, 'rt', encoding='utf8') as f:
@@ -1118,7 +1124,7 @@ class WG:
self.tanks['tankStr'] = dict() self.tanks['tankStr'] = dict()
p = re.compile('.+_short$') p = re.compile('.+_short$')
for usr_str in self.tanks['userStr']: for usr_str in self.tanks['userStr']:
if p.match(usr_str) == None: if p.match(usr_str) is None:
self.tanks['tankStr'][self.tanks['userStr'][usr_str]] = usr_str self.tanks['tankStr'][self.tanks['userStr'][usr_str]] = usr_str
self.tanks_by_tier = dict() self.tanks_by_tier = dict()
for tier in range(1,11): for tier in range(1,11):
@@ -1179,11 +1185,11 @@ class WG:
def get_url_clan_info(self, server: str, clan_id: int) -> str: def get_url_clan_info(self, server: str, clan_id: int) -> str:
try: try:
if server == None: if server is None:
return None return None
return self.URL_WG_SERVER[server] + self.URL_WG_CLAN_INFO + self.WG_app_id + '&clan_id=' + str(clan_id) return self.URL_WG_SERVER[server] + self.URL_WG_CLAN_INFO + self.WG_app_id + '&clan_id=' + str(clan_id)
except Exception as err: except Exception as err:
if (server == None) or (server.lower() not in WG.ACCOUNT_ID_SERVER.keys()): if (server is None) or (server.lower() not in WG.ACCOUNT_ID_SERVER.keys()):
error('No server name or invalid server name given: ' + server if (server != None) else '') error('No server name or invalid server name given: ' + server if (server != None) else '')
error('Available servers: ' + ', '.join(WG.ACCOUNT_ID_SERVER.keys())) error('Available servers: ' + ', '.join(WG.ACCOUNT_ID_SERVER.keys()))
error(exception=err) error(exception=err)
@@ -1196,15 +1202,15 @@ class WG:
def get_url_player_tanks_stats(self, account_id: int, tank_ids: list = [], fields: list = []) -> str: def get_url_player_tanks_stats(self, account_id: int, tank_ids: list = [], fields: list = []) -> str:
server = self.get_server(account_id) server = self.get_server(account_id)
if server == None: if server is None:
return None return None
if (tank_ids != None) and (len(tank_ids) > 0): if (tank_ids is not None) and (len(tank_ids) > 0):
tank_id_str= '&tank_id=' + '%2C'.join([ str(x) for x in tank_ids]) tank_id_str= '&tank_id=' + '%2C'.join([ str(x) for x in tank_ids])
else: else:
# emtpy tank-id list returns all the player's tanks # emtpy tank-id list returns all the player's tanks
tank_id_str = '' tank_id_str = ''
if (fields != None) and (len(fields) > 0): if (fields is not None) and (len(fields) > 0):
field_str = '&fields=' + '%2C'.join(fields) field_str = '&fields=' + '%2C'.join(fields)
else: else:
# return all the fields # return all the fields
@@ -1216,9 +1222,9 @@ class WG:
def get_url_player_stats(self, account_id, fields) -> str: def get_url_player_stats(self, account_id, fields) -> str:
try: try:
server = self.get_server(account_id) server = self.get_server(account_id)
if server == None: if server is None:
return None return None
if (fields != None) and (len(fields) > 0): if (fields is not None) and (len(fields) > 0):
field_str = '&fields=' + '%2C'.join(fields) field_str = '&fields=' + '%2C'.join(fields)
else: else:
# return all the fields # return all the fields
@@ -1226,7 +1232,7 @@ class WG:
return self.URL_WG_SERVER[server] + self.URL_WG_PLAYER_STATS + self.WG_app_id + '&account_id=' + str(account_id) + field_str return self.URL_WG_SERVER[server] + self.URL_WG_PLAYER_STATS + self.WG_app_id + '&account_id=' + str(account_id) + field_str
except Exception as err: except Exception as err:
if (server == None): if (server is None):
error('Invalid account_id') error('Invalid account_id')
error(exception=err) error(exception=err)
return None return None
@@ -1237,10 +1243,10 @@ class WG:
# assumming that all account_ids are from the same server. This has to be taken care. # assumming that all account_ids are from the same server. This has to be taken care.
server = self.get_server(account_ids[0]) server = self.get_server(account_ids[0])
if server == None: if server is None:
return None return None
account_ids_str = '%2C'.join(str(id) for id in account_ids) account_ids_str = '%2C'.join(str(id) for id in account_ids)
if (fields != None) and (len(fields) > 0): if (fields is not None) and (len(fields) > 0):
field_str = '&fields=' + '%2C'.join(fields) field_str = '&fields=' + '%2C'.join(fields)
else: else:
# return all the fields # return all the fields
@@ -1248,7 +1254,7 @@ class WG:
return self.URL_WG_SERVER[server] + self.URL_WG_PLAYER_ACHIEVEMENTS + self.WG_app_id + '&account_id=' + account_ids_str + field_str return self.URL_WG_SERVER[server] + self.URL_WG_PLAYER_ACHIEVEMENTS + self.WG_app_id + '&account_id=' + account_ids_str + field_str
except Exception as err: except Exception as err:
if (server == None): if (server is None):
error('Invalid account_id') error('Invalid account_id')
error(exception=err) error(exception=err)
return None return None
@@ -1258,9 +1264,9 @@ class WG:
try: try:
return self.URL_WG_SERVER[server] + self.URL_WG_ACCOUNT_ID + self.WG_app_id + '&search=' + urllib.parse.quote(nickname) return self.URL_WG_SERVER[server] + self.URL_WG_ACCOUNT_ID + self.WG_app_id + '&search=' + urllib.parse.quote(nickname)
except Exception as err: except Exception as err:
if nickname == None or len(nickname) == 0: if nickname is None or len(nickname) == 0:
error('No nickname given') error('No nickname given')
if (server == None) or (server.lower() not in WG.ACCOUNT_ID_SERVER.keys()): if (server is None) or (server.lower() not in WG.ACCOUNT_ID_SERVER.keys()):
error('No server name or invalid server name given: ' + server if (server != None) else '') error('No server name or invalid server name given: ' + server if (server != None) else '')
error('Available servers: ' + ', '.join(WG.ACCOUNT_ID_SERVER.keys())) error('Available servers: ' + ', '.join(WG.ACCOUNT_ID_SERVER.keys()))
error(exception=err) error(exception=err)
@@ -1308,7 +1314,7 @@ class WG:
nick, server = nickname.split('@') nick, server = nickname.split('@')
debug(nick + ' @ '+ server) debug(nick + ' @ '+ server)
server = server.lower() server = server.lower()
if nick == None or server == None: if nick is None or server is None:
raise ValueError('Invalid nickname given: ' + nickname) raise ValueError('Invalid nickname given: ' + nickname)
url = self.get_url_account_id(nick, server) url = self.get_url_account_id(nick, server)
@@ -1331,7 +1337,7 @@ class WG:
# try cached stats first: # try cached stats first:
if cache: if cache:
stats = await self.get_cached_tank_stats(account_id, tank_ids, fields) stats = await self.get_cached_tank_stats(account_id, tank_ids, fields)
if stats != None: if stats is not None:
return stats return stats
if cache_only: if cache_only:
return None return None
@@ -1339,7 +1345,7 @@ class WG:
# Cached stats not found, fetching new ones # Cached stats not found, fetching new ones
url = self.get_url_player_tanks_stats(account_id, tank_ids, fields) url = self.get_url_player_tanks_stats(account_id, tank_ids, fields)
json_data = await self.get_url_JSON(url, self.chk_JSON_status) json_data = await self.get_url_JSON(url, self.chk_JSON_status)
if json_data != None: if json_data is not None:
# debug('JSON Response received: ' + str(json_data)) # debug('JSON Response received: ' + str(json_data))
stats = json_data['data'][str(account_id)] stats = json_data['data'][str(account_id)]
if cache: if cache:
@@ -1372,7 +1378,7 @@ class WG:
# Cached stats not found, fetching new ones # Cached stats not found, fetching new ones
url = self.get_url_player_stats(account_id, fields) url = self.get_url_player_stats(account_id, fields)
json_data = await self.get_url_JSON(url, self.chk_JSON_status) json_data = await self.get_url_JSON(url, self.chk_JSON_status)
if json_data != None: if json_data is not None:
# debug('JSON Response received: ' + str(json_data)) # debug('JSON Response received: ' + str(json_data))
stats = json_data['data'][str(account_id)] stats = json_data['data'][str(account_id)]
if cache: if cache:
@@ -1410,7 +1416,7 @@ class WG:
# Cached stats not found, fetching new ones # Cached stats not found, fetching new ones
url = self.get_url_player_achievements(list(account_ids), fields) url = self.get_url_player_achievements(list(account_ids), fields)
json_data = await self.get_url_JSON(url, self.chk_JSON_status) json_data = await self.get_url_JSON(url, self.chk_JSON_status)
if (json_data != None) and ('data' in json_data): if (json_data is not None) and ('data' in json_data):
# debug('JSON Response received: ' + str(json_data)) # debug('JSON Response received: ' + str(json_data))
for account_id in json_data['data'].keys(): for account_id in json_data['data'].keys():
stats[account_id] = json_data['data'][account_id] stats[account_id] = json_data['data'][account_id]
@@ -1424,7 +1430,7 @@ class WG:
def merge_player_stats(self, stats1: dict, stats2: dict) -> dict: def merge_player_stats(self, stats1: dict, stats2: dict) -> dict:
try: try:
if stats2 == None: return stats1 if stats2 is None: return stats1
for keyA in stats2: for keyA in stats2:
if keyA not in stats1: if keyA not in stats1:
stats1[keyA] = stats2[keyA] stats1[keyA] = stats2[keyA]
@@ -1438,7 +1444,7 @@ class WG:
def get_tank_data(self, tank_id: int, field: str): def get_tank_data(self, tank_id: int, field: str):
if self.tanks == None: if self.tanks is None:
return None return None
try: try:
return self.tanks['data'][str(tank_id)][field] return self.tanks['data'][str(tank_id)][field]
@@ -1524,7 +1530,7 @@ class WG:
async def save_stats(self, statsType: str, key: list, stats: list): async def save_stats(self, statsType: str, key: list, stats: list):
"""Save stats to a async queue to be saved by the stat_saver -task""" """Save stats to a async queue to be saved by the stat_saver -task"""
if self.statsQ == None: if self.statsQ is None:
return False return False
else: else:
await self.statsQ.put([ statsType, key, stats, NOW() ]) await self.statsQ.put([ statsType, key, stats, NOW() ])
@@ -1558,7 +1564,7 @@ class WG:
async def stat_saver(self): async def stat_saver(self):
"""Async task for saving stats into cache in background""" """Async task for saving stats into cache in background"""
if self.statsQ == None: if self.statsQ is None:
error('No statsQ defined') error('No statsQ defined')
return None return None
try: try:
@@ -1612,12 +1618,12 @@ class WG:
async def cleanup_cache(self, grace_time = CACHE_GRACE_TIME): async def cleanup_cache(self, grace_time = CACHE_GRACE_TIME):
"""Clean old cache records""" """Clean old cache records"""
if self.cache == None: if self.cache is None:
debug('No active cache') debug('No active cache')
return None return None
for table in WG.SQL_TABLES: for table in WG.SQL_TABLES:
async with self.cache.execute(WG.SQL_CHECK_TABLE_EXITS, (table,)) as cursor: async with self.cache.execute(WG.SQL_CHECK_TABLE_EXITS, (table,)) as cursor:
if (await cursor.fetchone()) != None: if (await cursor.fetchone()) is not None:
debug('Pruning cache table: ' + table) debug('Pruning cache table: ' + table)
await self.cache.execute(WG.SQL_PRUNE_CACHE.format(table, NOW() - grace_time)) await self.cache.execute(WG.SQL_PRUNE_CACHE.format(table, NOW() - grace_time))
await self.cache.commit() await self.cache.commit()
@@ -1631,7 +1637,7 @@ class WG:
try: try:
account_id = key[0] account_id = key[0]
tank_ids = set(key[1]) tank_ids = set(key[1])
if stats_data != None: if stats_data is not None:
for stat in stats_data: for stat in stats_data:
tank_id = stat['tank_id'] tank_id = stat['tank_id']
await self.cache.execute(WG.SQL_TANK_STATS_UPDATE, (account_id, tank_id, update_time, json.dumps(stat))) await self.cache.execute(WG.SQL_TANK_STATS_UPDATE, (account_id, tank_id, update_time, json.dumps(stat)))
@@ -1653,7 +1659,7 @@ class WG:
try: try:
account_id = key[0] account_id = key[0]
if stats_data != None: if stats_data is not None:
await self.cache.execute(WG.SQL_PLAYER_STATS_UPDATE, (account_id, update_time, json.dumps(stats_data))) await self.cache.execute(WG.SQL_PLAYER_STATS_UPDATE, (account_id, update_time, json.dumps(stats_data)))
else: else:
await self.cache.execute(WG.SQL_PLAYER_STATS_UPDATE, (account_id, update_time, None)) await self.cache.execute(WG.SQL_PLAYER_STATS_UPDATE, (account_id, update_time, None))
@@ -1671,7 +1677,7 @@ class WG:
try: try:
account_id = key[0] account_id = key[0]
if stats_data != None: if stats_data is not None:
await self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_UPDATE, (account_id, update_time, json.dumps(stats_data))) await self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_UPDATE, (account_id, update_time, json.dumps(stats_data)))
else: else:
await self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_UPDATE, (account_id, update_time, None)) await self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_UPDATE, (account_id, update_time, None))
@@ -1689,7 +1695,7 @@ class WG:
try: try:
# test for cacheDB existence # test for cacheDB existence
debug('Trying cached stats first') debug('Trying cached stats first')
if self.cache == None: if self.cache is None:
debug('No cache DB') debug('No cache DB')
return None return None
@@ -1703,7 +1709,7 @@ class WG:
tank_ids = set(tank_ids) tank_ids = set(tank_ids)
async for row in cursor: async for row in cursor:
# debug('account_id: ' + str(account_id) + ': 1') # debug('account_id: ' + str(account_id) + ': 1')
if row[3] == None: if row[3] is None:
# None/null stats found in cache # None/null stats found in cache
# i.e. stats have been requested, but not returned from WG API # i.e. stats have been requested, but not returned from WG API
tank_ids.remove(row[1]) tank_ids.remove(row[1])
@@ -1728,20 +1734,20 @@ class WG:
try: try:
# test for cacheDB existence # test for cacheDB existence
debug('Trying cached stats first') debug('Trying cached stats first')
if self.cache == None: if self.cache is None:
# debug('No cache DB') # debug('No cache DB')
raise StatsNotFound('No cache DB in use') raise StatsNotFound('No cache DB in use')
async with self.cache.execute(WG.SQL_PLAYER_STATS_CACHED, [account_id, NOW() - WG.CACHE_GRACE_TIME] ) as cursor: async with self.cache.execute(WG.SQL_PLAYER_STATS_CACHED, [account_id, NOW() - WG.CACHE_GRACE_TIME] ) as cursor:
row = await cursor.fetchone() row = await cursor.fetchone()
# debug('account_id: ' + str(account_id) + ': 1') # debug('account_id: ' + str(account_id) + ': 1')
if row == None: if row is None:
# no cached stats found, marked with an empty array # no cached stats found, marked with an empty array
# debug('No cached stats found') # debug('No cached stats found')
raise StatsNotFound('No cached stats found') raise StatsNotFound('No cached stats found')
debug('Cached stats found') debug('Cached stats found')
if row[2] == None: if row[2] is None:
# None/null stats found in cache # None/null stats found in cache
# i.e. stats have been requested, but not returned from WG API # i.e. stats have been requested, but not returned from WG API
return None return None
@@ -1760,20 +1766,20 @@ class WG:
try: try:
# test for cacheDB existence # test for cacheDB existence
debug('Trying cached stats first') debug('Trying cached stats first')
if self.cache == None: if self.cache is None:
# debug('No cache DB') # debug('No cache DB')
raise StatsNotFound('No cache DB in use') raise StatsNotFound('No cache DB in use')
async with self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_CACHED, [account_id, NOW() - WG.CACHE_GRACE_TIME] ) as cursor: async with self.cache.execute(WG.SQL_PLAYER_ACHIEVEMENTS_CACHED, [account_id, NOW() - WG.CACHE_GRACE_TIME] ) as cursor:
row = await cursor.fetchone() row = await cursor.fetchone()
# debug('account_id: ' + str(account_id) + ': 1') # debug('account_id: ' + str(account_id) + ': 1')
if row == None: if row is None:
# no cached stats found, marked with an empty array # no cached stats found, marked with an empty array
# debug('No cached stats found') # debug('No cached stats found')
raise StatsNotFound('No cached stats found') raise StatsNotFound('No cached stats found')
debug('Cached stats found') debug('Cached stats found')
if row[2] == None: if row[2] is None:
# None/null stats found in cache # None/null stats found in cache
# i.e. stats have been requested, but not returned from WG API # i.e. stats have been requested, but not returned from WG API
return None return None
@@ -1876,7 +1882,7 @@ class WoTinspector:
async def post_replay(self, data, filename = 'Replay', account_id = 0, title = 'Replay', priv = False, N = None): async def post_replay(self, data, filename = 'Replay', account_id = 0, title = 'Replay', priv = False, N = None):
try: try:
N = N if N != None else self.REPLAY_N N = N if N is not None else self.REPLAY_N
self.REPLAY_N += 1 self.REPLAY_N += 1
hash = hashlib.md5() hash = hashlib.md5()
@@ -1885,7 +1891,7 @@ class WoTinspector:
## Testing if the replay has already been posted ## Testing if the replay has already been posted
json_resp = await self.get_replay_JSON(replay_id) json_resp = await self.get_replay_JSON(replay_id)
if json_resp != None: if json_resp is not None:
debug('Already uploaded: ' + title, id=N) debug('Already uploaded: ' + title, id=N)
return json_resp return json_resp
@@ -1981,7 +1987,7 @@ class WoTinspector:
""""Check String for being a valid JSON file""" """"Check String for being a valid JSON file"""
try: try:
if ('status' in json_resp) and json_resp['status'] == 'ok' and \ if ('status' in json_resp) and json_resp['status'] == 'ok' and \
(get_JSON_value(json_resp, key='data.summary.exp_base') != None) : (get_JSON_value(json_resp, key='data.summary.exp_base') is not None) :
debug("JSON check OK") debug("JSON check OK")
return True return True
except KeyError as err: except KeyError as err:
@@ -2008,7 +2014,7 @@ class BlitzStars:
self.session = ThrottledClientSession(rate_limit=rate_limit, headers=headers) self.session = ThrottledClientSession(rate_limit=rate_limit, headers=headers)
async def close(self): async def close(self):
if self.session != None: if self.session is not None:
await self.session.close() await self.session.close()
@@ -2066,7 +2072,7 @@ class BlitzStars:
async def tank_stats2WG(cls, BS_tank_stats: list) -> list: async def tank_stats2WG(cls, BS_tank_stats: list) -> list:
"""Convert BlitzStars player tank stats to WG API format""" """Convert BlitzStars player tank stats to WG API format"""
try: try:
if BS_tank_stats == None: if BS_tank_stats is None:
return None return None
WG_tank_stats = [] WG_tank_stats = []
for stat in BS_tank_stats: for stat in BS_tank_stats:
@@ -2108,7 +2114,7 @@ class BlitzStars:
# Cached stats not found, fetching new ones # Cached stats not found, fetching new ones
url = self.get_url_player_stats(account_id) url = self.get_url_player_stats(account_id)
stats = await get_url_JSON(self.session, url, self.chk_JSON_player_stats) stats = await get_url_JSON(self.session, url, self.chk_JSON_player_stats)
if stats != None: if stats is not None:
# debug('JSON Response received: ' + str(json_data)) # debug('JSON Response received: ' + str(json_data))
if cache: if cache:
error('CACHE NOT IMPLEMENTED YET FOR BlitzStars()') error('CACHE NOT IMPLEMENTED YET FOR BlitzStars()')
@@ -2139,13 +2145,13 @@ class BlitzStars:
try: try:
# Cached stats not found, fetching new ones # Cached stats not found, fetching new ones
if tank_id == None: if tank_id is None:
# get stats for all the player's tanks # get stats for all the player's tanks
url = self.get_url_player_tanks_stats(account_id) url = self.get_url_player_tanks_stats(account_id)
else: else:
url = self.get_url_player_tank_stats(account_id, tank_id) url = self.get_url_player_tank_stats(account_id, tank_id)
stats = await get_url_JSON(self.session, url, self.chk_JSON_tank_stats) stats = await get_url_JSON(self.session, url, self.chk_JSON_tank_stats)
if stats != None: if stats is not None:
# debug('JSON Response received: ' + str(json_data)) # debug('JSON Response received: ' + str(json_data))
if cache: if cache:
error('CACHE NOT IMPLEMENTED YET FOR BlitzStars()') error('CACHE NOT IMPLEMENTED YET FOR BlitzStars()')
+33 -17
View File
@@ -4,7 +4,11 @@
# Extract tankopedia data in WG API JSON format from Blitz app files (Android APK unzipped) # Extract tankopedia data in WG API JSON format from Blitz app files (Android APK unzipped)
from os import path from os import path
import sys, argparse, json, os, inspect, aiohttp, asyncio, aiofiles, re, logging, time, xmltodict, collections, configparser import aiofiles # type: ignore
import xmltodict # type: ignore
from asyncio import set_event_loop_policy, run, create_task, get_event_loop_policy
import sys, argparse, json, os, inspect, asyncio, re, logging, time, configparser
from collections import OrderedDict
import blitzutils as bu import blitzutils as bu
from blitzutils import WG from blitzutils import WG
@@ -18,10 +22,10 @@ BLITZAPP_STRINGS='Data/Strings/en.yaml'
BLITZAPP_VEHICLES_DIR='Data/XML/item_defs/vehicles/' BLITZAPP_VEHICLES_DIR='Data/XML/item_defs/vehicles/'
BLITZAPP_VEHICLE_FILE='list.xml' BLITZAPP_VEHICLE_FILE='list.xml'
wg = None wg : WG | None = None
## main() ------------------------------------------------------------- ## main() -------------------------------------------------------------
async def main(argv): async def main(argv: list[str]) -> None:
global wg global wg
# set the directory for the script # set the directory for the script
os.chdir(os.path.dirname(sys.argv[0])) os.chdir(os.path.dirname(sys.argv[0]))
@@ -79,7 +83,7 @@ async def main(argv):
# merge old and new tankopedia # merge old and new tankopedia
tanks.update(new_tanks) tanks.update(new_tanks)
userStrs.update(new_userStrs) userStrs.update(new_userStrs)
tankopedia = collections.OrderedDict() tankopedia : OrderedDict[str, str| int | dict ]= OrderedDict()
tankopedia['status'] = 'ok' tankopedia['status'] = 'ok'
tankopedia['meta'] = { "count": len(tanks) } tankopedia['meta'] = { "count": len(tanks) }
tankopedia['data'] = bu.sort_dict(tanks, number=True) tankopedia['data'] = bu.sort_dict(tanks, number=True)
@@ -88,7 +92,7 @@ async def main(argv):
bu.verbose_std('New tankopedia \'' + args.tanks + '\' contains ' + str(len(userStrs)) + ' tank strings') bu.verbose_std('New tankopedia \'' + args.tanks + '\' contains ' + str(len(userStrs)) + ' tank strings')
await outfile.write(json.dumps(tankopedia, ensure_ascii=False, indent=4, sort_keys=False)) await outfile.write(json.dumps(tankopedia, ensure_ascii=False, indent=4, sort_keys=False))
if args.maps != None: if args.maps is not None:
maps = {} maps = {}
if os.path.exists(args.maps): if os.path.exists(args.maps):
try: try:
@@ -120,7 +124,7 @@ async def extract_tanks(blitz_app_base : str, nation: str):
tankList = xmltodict.parse(await f.read()) tankList = xmltodict.parse(await f.read())
for data in tankList['root'].keys(): for data in tankList['root'].keys():
tank_xml = tankList['root'][data] tank_xml = tankList['root'][data]
tank = dict() tank : dict[str, bool | int | str]= dict()
tank['is_premium'] = issubclass(type(tank_xml['price']), dict) tank['is_premium'] = issubclass(type(tank_xml['price']), dict)
tank['nation'] = nation tank['nation'] = nation
tank['tank_id'] = get_tank_id(nation, int(tank_xml['id'])) tank['tank_id'] = get_tank_id(nation, int(tank_xml['id']))
@@ -134,7 +138,7 @@ async def extract_tanks(blitz_app_base : str, nation: str):
sys.exit(2) sys.exit(2)
return tanks return tanks
async def read_user_strs(blitz_app_base : str) -> dict: async def read_user_strs(blitz_app_base : str) -> tuple[dict, dict]:
"""Read user strings to convert map and tank names""" """Read user strings to convert map and tank names"""
tank_strs = {} tank_strs = {}
map_strs = {} map_strs = {}
@@ -147,11 +151,11 @@ async def read_user_strs(blitz_app_base : str) -> dict:
async for l in f: async for l in f:
m = p_tank.match(l) m = p_tank.match(l)
if m != None: if m is not None:
tank_strs[m.group(1)] = m.group(2) tank_strs[m.group(1)] = m.group(2)
m = p_map.match(l) m = p_map.match(l)
if m != None and m.group(2) != 'Macragge': if m is not None and m.group(2) != 'Macragge':
map_strs[m.group(1)] = m.group(2) map_strs[m.group(1)] = m.group(2)
except Exception as err: except Exception as err:
@@ -160,20 +164,30 @@ async def read_user_strs(blitz_app_base : str) -> dict:
return tank_strs, map_strs return tank_strs, map_strs
async def convert_tank_names(tanklist : list, tank_strs: dict) -> dict: async def convert_tank_names(tanklist : list, tank_strs: dict) -> tuple[dict, dict]:
"""Convert tank names for Tankopedia""" """Convert tank names for Tankopedia"""
tankopedia = {} tankopedia = {}
userStrs = {} userStrs = {}
bu.debug(f'tank_strs:')
for key, value in tank_strs.items():
bu.debug(f'{key}: {value}')
bu.debug('---------')
try: try:
for tank in tanklist: for tank in tanklist:
try:
bu.debug(f'tank: {tank}')
if tank['userStr'] in tank_strs:
tank['name'] = tank_strs[tank['userStr']] tank['name'] = tank_strs[tank['userStr']]
#userStrs[tank['userStr'].split(':')[1]] = tank['name'] else:
tank['name'] = tank['userStr'].split(':')[1]
tank.pop('userStr', None) tank.pop('userStr', None)
tank_tmp = collections.OrderedDict() tank_tmp = OrderedDict()
for key in sorted(tank.keys()): for key in sorted(tank.keys()):
tank_tmp[key] = tank[key] tank_tmp[key] = tank[key]
tankopedia[str(tank['tank_id'])] = tank_tmp tankopedia[str(tank['tank_id'])] = tank_tmp
except:
bu.error(f'Could not process tank: {tank}')
for tank_str in tank_strs: for tank_str in tank_strs:
skip = False skip = False
@@ -191,11 +205,11 @@ async def convert_tank_names(tanklist : list, tank_strs: dict) -> dict:
userStrs[key] = tank_strs[tank_str] userStrs[key] = tank_strs[tank_str]
# sorting # sorting
tankopedia_sorted = collections.OrderedDict() tankopedia_sorted = OrderedDict()
for tank_id in sorted(tankopedia.keys(), key=int): for tank_id in sorted(tankopedia.keys(), key=int):
tankopedia_sorted[str(tank_id)] = tankopedia[str(tank_id)] tankopedia_sorted[str(tank_id)] = tankopedia[str(tank_id)]
userStrs_sorted = collections.OrderedDict() userStrs_sorted = OrderedDict()
for userStr in sorted(userStrs.keys()): for userStr in sorted(userStrs.keys()):
userStrs_sorted[userStr] = userStrs[userStr] userStrs_sorted[userStr] = userStrs[userStr]
# bu.debug('Tank strings: ' + str(len(userStrs_sorted))) # bu.debug('Tank strings: ' + str(len(userStrs_sorted)))
@@ -208,10 +222,12 @@ async def convert_tank_names(tanklist : list, tank_strs: dict) -> dict:
def get_tank_id(nation: str, tank_id : int) -> int: def get_tank_id(nation: str, tank_id : int) -> int:
assert wg is not None, "wg has to be set"
return (tank_id << 8) + (wg.NATION_ID[nation] << 4) + 1 return (tank_id << 8) + (wg.NATION_ID[nation] << 4) + 1
def get_tank_type(tagstr : str): def get_tank_type(tagstr : str):
assert wg is not None, "wg has to be set"
tags = tagstr.split(' ') tags = tagstr.split(' ')
for t_type in wg.TANK_TYPE: for t_type in wg.TANK_TYPE:
if tags[0] == t_type: if tags[0] == t_type:
@@ -227,7 +243,7 @@ if __name__ == "__main__":
except ImportError: except ImportError:
pass pass
else: else:
if not isinstance(asyncio.get_event_loop_policy(), WindowsSelectorEventLoopPolicy): if not isinstance(get_event_loop_policy(), WindowsSelectorEventLoopPolicy):
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) set_event_loop_policy(WindowsSelectorEventLoopPolicy())
#asyncio.run(main(sys.argv[1:]), debug=True) #asyncio.run(main(sys.argv[1:]), debug=True)
asyncio.run(main(sys.argv[1:])) run(main(sys.argv[1:]))