minecraft-monitor/convert-logs.py

63 lines
2.2 KiB
Python

from json import loads, dumps
with open('all-time.txt', 'r') as fin:
(last_t, last_ev, last_evt, last_ps) = (0, 'error', 0, [])
with open('events.json', 'w') as fout:
cur_t = 0
cur_ps = []
for line in fin:
current = loads(line)
cur_t = current['time']
cur_ps = current['players']
if last_t == 0:
(last_t, last_ev, last_evt, last_ps) = (cur_t, 'online', cur_t, cur_ps)
else:
if cur_t - last_t > 70:
if last_ev == 'online':
fout.write(dumps({'period': [last_evt, last_t], 'status': last_ev, 'players': last_ps})+'\n')
(last_ev, last_evt, last_ps) = ('unreachable', last_t, cur_ps)
else:
if last_ev != 'online':
fout.write(dumps({'period': [last_evt, last_t], 'status': last_ev})+'\n')
(last_ev, last_evt, last_ps) = ('online', last_t, last_ps)
if last_ps != cur_ps:
fout.write(dumps({'period': [last_evt, cur_t], 'status': last_ev, 'players': last_ps})+'\n')
(last_ev, last_evt, last_ps) = ('online', cur_t, cur_ps)
last_t = cur_t
with open('current-state.json', 'w') as fout:
fout.write(dumps({'period': [last_evt, last_t], 'status': 'online', 'players': last_ps}))
# scale down coordinates to dx=1 per day to prevent SVG coordinate overflows
scale = 1/60/60/24
def get_date(dtime):
return datetime.fromtimestamp(dtime).strftime('%Y-%m-%d %H:%M')
def make_line(event):
evstart = event['period'][0]
evstop = event['period'][1]
return '<line{type} x1="{start}" x2="{stop}" y1="{height}" y2="{height}"><title>{text} ({start_date}{stop_date})</title></line>'.format(
type = '' if event['status'] == 'online' else ' class="error"',
start = scale*evstart,
stop = scale*evstop,
start_date = get_date(evstart),
stop_date = get_date(evstop),
height = len(event['players']) if 'players' in event else 0,
text = ('no one' if len(event['players']) == 0 else ', '.join(event['players'])) if event['status'] == 'online' else event['status']
)
def events_to_lines():
with open('events.json', 'r') as fin:
with open('events.log', 'w') as fout:
for l in fin:
fout.write(make_line(loads(l))+'\n')