from django.views.generic import View from django.http import JsonResponse from django.conf import settings import GeoffreyApp.api.commands as commands from GeoffreyApp.errors import * from GeoffreyApp.models import APIToken def check_token(request, **kwargs): if "api" in request: key = request["api"] if APIToken.objects.filter(key=key, **kwargs).exists(): return True return False def run_command(request, command, req_type): command = command.lower() try: if command in commands.command_dict[req_type]: params = request.dict() params.pop("api") response = commands.command_dict[req_type][command]["func"](**params) else: raise CommandNotFound except Exception as e: response = {"error": e.__class__.__name__, "error_message": str(e)} return JsonResponse(response, safe=False) class CommandAPI(View): def get(self, request, command): get = request.GET if check_token(get, commands_perm=True): if command.lower() == "commands": return JsonResponse(command.commands_dict) else: return run_command(get, command, "GET") else: return JsonResponse({}) def post(self, request, command): post = request.POST if check_token(post, commands_perm=True): return run_command(post, command, "POST") else: return JsonResponse({}) def delete(self, request, command): delete = request.DELETE if check_token(delete, commands_perm=True): return run_command(delete, command, "DELETE") else: return JsonResponse({}) class SettingsAPI(View): def get(self, request): response = { "BOT_PREFIX": getattr(settings, 'BOT_PREFIX', '?'), "ERROR_USERS": getattr(settings, 'ERROR_USERS', []), "MOD_RANK": getattr(settings, 'MOD_RANK', []), "DEFAULT_STATUS": getattr(settings, 'DEFAULT_STATUS', 'sed') } return JsonResponse(response)