diff --git a/apiserver/apiserver/api/management/commands/run_minutely.py b/apiserver/apiserver/api/management/commands/run_minutely.py new file mode 100644 index 0000000..890b4a0 --- /dev/null +++ b/apiserver/apiserver/api/management/commands/run_minutely.py @@ -0,0 +1,20 @@ +from django.core.management.base import BaseCommand, CommandError +from django.utils.timezone import now +from apiserver.api import models, utils, utils_stats + +import time + +class Command(BaseCommand): + help = 'Tasks to run on the portal minutely.' + + + def handle(self, *args, **options): + self.stdout.write('{} - Beginning minutely tasks'.format(str(now()))) + start = time.time() + + players = utils_stats.check_minecraft_server() + self.stdout.write('Found Minecraft players: ' + str(players)) + + self.stdout.write('Completed tasks in {} s'.format( + str(time.time() - start)[:4] + )) diff --git a/apiserver/apiserver/api/utils_stats.py b/apiserver/apiserver/api/utils_stats.py index fadd271..85c85c2 100644 --- a/apiserver/apiserver/api/utils_stats.py +++ b/apiserver/apiserver/api/utils_stats.py @@ -1,8 +1,13 @@ +import logging +logger = logging.getLogger(__name__) + import time import datetime +import requests from django.core.cache import cache from django.utils.timezone import now from apiserver.api import models +from apiserver import secrets DEFAULTS = { 'last_card_change': time.time(), @@ -13,6 +18,7 @@ DEFAULTS = { 'green_count': None, 'bay_108_temp': None, 'bay_110_temp': None, + 'minecraft_players': [], } def changed_card(): @@ -49,3 +55,19 @@ def calc_member_counts(): cache.set('member_count', num_not_paused) cache.set('paused_count', num_paused) cache.set('green_count', num_current + num_prepaid) + +def check_minecraft_server(): + if secrets.MINECRAFT: + url = 'https://api.minetools.eu/ping/' + secrets.MINECRAFT + + try: + r = requests.get(url, timeout=5) + r.raise_for_status() + players = [x['name'] for x in r.json()['players']['sample']] + cache.set('minecraft_players', players) + return players + except BaseException as e: + cache.set('minecraft_players', []) + logger.error('Problem checking Minecraft: {} - {}'.format(e.__class__.__name__, str(e))) + + return [] diff --git a/apiserver/apiserver/secrets.py.example b/apiserver/apiserver/secrets.py.example index fced6cd..cc0a1af 100644 --- a/apiserver/apiserver/secrets.py.example +++ b/apiserver/apiserver/secrets.py.example @@ -36,6 +36,7 @@ DOOR_API_TOKEN = '' # Protospace general info DOOR_CODE = '' WIFI_PASS = '' +MINECRAFT = '' # Backup API tokens # These tokens allow each user to download a backup of member data.