stats.json fix with auto backup

This commit is contained in:
Ayush Saini 2022-05-08 15:27:08 +05:30
parent a2c7b303d0
commit db5782b6f1

View file

@ -19,6 +19,7 @@ from ba._activitytypes import *
import urllib.request
import custom_hooks
import datetime
# variables
our_settings = setting.get_settings_data()
# where our stats file and pretty html output will go
@ -66,12 +67,18 @@ statsDefault={
# useful functions
seasonStartDate = None
import shutil, os
def get_all_stats():
global seasonStartDate
if os.path.exists(statsfile):
renameFile = False
with open(statsfile, 'r', encoding='utf8') as f:
try:
jsonData = json.loads(f.read())
except:
f=open(statsfile+".backup",encoding='utf-8')
jsonData=json.load(f)
try:
stats = jsonData["stats"]
@ -87,30 +94,33 @@ def get_all_stats():
else:
return {}
def backupStatsFile():
shutil.copy(statsfile, statsfile.replace(".json", "") + str(seasonStartDate) + ".json")
def dump_stats(s: dict):
global seasonStartDate
if seasonStartDate == None:
seasonStartDate = datetime.datetime.now()
s = {"startDate": seasonStartDate.strftime("%d-%m-%Y"), "stats": s}
if os.path.exists(statsfile):
shutil.copyfile(statsfile,statsfile+".backup")
with open(statsfile, 'w', encoding='utf8') as f:
f.write(json.dumps(s, indent=4, ensure_ascii=False))
f.close()
else: print('Stats file not found!')
else:
print('Stats file not found!')
def get_stats_by_id(ID: str):
a = get_all_stats()
if ID in a:
return a[ID]
else:
return None
def refreshStats():
# lastly, write a pretty html version.
# our stats url could point at something like this...
@ -153,7 +163,8 @@ def refreshStats():
if damage_data and aid in damage_data:
dmg = damage_data[aid]
dmg = str(str(dmg).split('.')[0] + '.' + str(dmg).split('.')[1][:3])
else: dmg = 0
else:
dmg = 0
_ranks.append(aid)
@ -182,7 +193,6 @@ def refreshStats():
# </body>
# </html>''')
# f.close()
global ranks
ranks = _ranks
@ -193,6 +203,7 @@ def refreshStats():
from playersData import pdata
pdata.update_toppers(toppersIDs)
def update(score_set):
"""
Given a Session's ScoreSet, tallies per-account kills
@ -201,7 +212,6 @@ def update(score_set):
"""
# look at score-set entries to tally per-account kills for this round
account_kills = {}
account_deaths = {}
account_scores = {}
@ -224,6 +234,7 @@ def update(score_set):
if account_scores:
UpdateThread(account_kills, account_deaths, account_scores).start()
class UpdateThread(threading.Thread):
def __init__(self, account_kills, account_deaths, account_scores):
threading.Thread.__init__(self)
@ -248,8 +259,6 @@ class UpdateThread(threading.Thread):
# though it may be smart to refresh it periodically since
# it may change)
stats[account_id] = {'rank': 0,
'name': "deafult name",
'scores': 0,
@ -295,6 +304,7 @@ class UpdateThread(threading.Thread):
# print(f"Added {str(len(self._account_kills))} account's stats entries. || {str(update_time)}")
refreshStats()
def getRank(acc_id):
global ranks
if ranks == []:
@ -303,7 +313,6 @@ def getRank(acc_id):
return ranks.index(acc_id) + 1
def updateTop3Names(ids):
global top3Name
names = []
@ -320,4 +329,3 @@ def updateTop3Names(ids):
top3Name = names