80 lines
2.1 KiB
Python
80 lines
2.1 KiB
Python
# kappa123/server/runs.py
|
|
|
|
import os
|
|
import requests
|
|
import simplejson as json
|
|
import arrow
|
|
|
|
import logging
|
|
|
|
CACHE_AGE_MAX = 600
|
|
CACHE_LOCATION='/tmp/runs.json'
|
|
TRACKER_URL='https://gamesdonequick.com/tracker/search/?type=run&event=22'
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class KappaException(Exception):
|
|
pass
|
|
class GDQException(Exception):
|
|
pass
|
|
|
|
def inject_run_class(runs, selected_runs):
|
|
output = list()
|
|
for run in runs:
|
|
# munge run
|
|
output.append(run)
|
|
return output
|
|
|
|
|
|
def fetch_or_cache_runs():
|
|
if os.path.isfile(CACHE_LOCATION):
|
|
ctime = os.stat(CACHE_LOCATION).st_ctime
|
|
arw = arrow.get(ctime)
|
|
age = (arrow.now() - arw).seconds
|
|
|
|
if age > CACHE_AGE_MAX:
|
|
return fetch_runs()
|
|
else:
|
|
return transform_runs(load_run_cache())
|
|
else:
|
|
return fetch_runs()
|
|
|
|
|
|
def load_run_cache():
|
|
if os.path.isfile(CACHE_LOCATION):
|
|
with open(CACHE_LOCATION, 'r') as f:
|
|
string = f.read()
|
|
return json.loads(string)
|
|
else:
|
|
raise KappaException("GDQ Tracker Appears to be down, and I don't have a saved copy. Try again later.")
|
|
|
|
|
|
def fetch_runs():
|
|
try:
|
|
logger.warn("Re-fetching cache")
|
|
r = requests.get(TRACKER_URL, timeout=5)
|
|
if r.status_code != 200:
|
|
raise GDQException("GDQ not returning 200")
|
|
output = r.json()
|
|
with open(CACHE_LOCATION, 'w') as f:
|
|
f.write(r.text)
|
|
return transform_runs(output)
|
|
except (GDQException, requests.exceptions.ReadTimeout):
|
|
return transform_runs(load_run_cache())
|
|
|
|
def transform_runs(raw_data):
|
|
"""Transform a JSON list of GDQ runs from their site in to simplified dict for rendering here."""
|
|
output = list()
|
|
for run in raw_data:
|
|
run = run['fields']
|
|
d = {
|
|
'time': arrow.get(run['starttime']).to('America/Chicago').format('MMM DD HH:mm:ss'),
|
|
'estimate': run['run_time'],
|
|
'name': run['name'],
|
|
'category': run['category'],
|
|
'runners': run['deprecated_runners'], #lol
|
|
'order': run['order']
|
|
}
|
|
output.append(d)
|
|
return output
|