Do not crash with malformed visitors.json files

If the visitors.json file does not contain a valid JSON file, reset
it, and act as if it was empty.
pull/35/head
Marcos Marado 2020-10-03 17:28:10 +01:00
parent f243391418
commit acea6018a6
1 changed files with 18 additions and 14 deletions

View File

@ -229,20 +229,24 @@ class Plant(object):
visitors_this_check = [] visitors_this_check = []
if os.path.isfile(visitor_filepath): if os.path.isfile(visitor_filepath):
with open(visitor_filepath, 'r') as visitor_file: with open(visitor_filepath, 'r') as visitor_file:
data = json.load(visitor_file) try:
if data: data = json.load(visitor_file)
for element in data: if data:
if element['user'] not in self.visitors: for element in data:
self.visitors.append(element['user']) if element['user'] not in self.visitors:
if element['user'] not in visitors_this_check: self.visitors.append(element['user'])
visitors_this_check.append(element['user']) if element['user'] not in visitors_this_check:
# prevent users from manually setting watered_time in the future visitors_this_check.append(element['user'])
if element['timestamp'] <= int(time.time()): # prevent users from manually setting watered_time in the future
guest_timestamps.append(element['timestamp']) if element['timestamp'] <= int(time.time()):
try: guest_timestamps.append(element['timestamp'])
self.update_visitor_db(visitors_this_check) try:
except: self.update_visitor_db(visitors_this_check)
pass except:
pass
with open(visitor_filepath, 'w') as visitor_file:
visitor_file.write('[]')
except:
with open(visitor_filepath, 'w') as visitor_file: with open(visitor_filepath, 'w') as visitor_file:
visitor_file.write('[]') visitor_file.write('[]')
else: else: