Geoffrey-Django/GeoffreyApp/api/views.py

89 lines
2.7 KiB
Python

from django.views.generic import View
from django.http import JsonResponse
from django.conf import settings
import traceback
import sys
from GeoffreyApp.api.commands import RequestTypes
import GeoffreyApp.api.commands as commands
from GeoffreyApp.api.key import check_request_for_key, check_key
from GeoffreyApp.errors import *
from GeoffreyApp.models import PermissionLevel
def run_command(request, command_name, req_type, key):
params = request.dict()
params.pop("api")
command_name = command_name.lower()
try:
if command_name in commands.command_dict[req_type]:
command = commands.command_dict[req_type][command_name]
if key.has_command_permission(command.permission_level):
response = command.func(**params)
else:
response = {}
else:
raise CommandNotFound
except Exception as e:
response = {"error": e.__class__.__name__, "error_message": str(e)}
if getattr(settings, "DEBUG", False):
traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
return JsonResponse(response, safe=False)
def get_commands(key):
command_list = []
for request in commands.command_dict:
for command_name in commands.command_dict[request]:
command = commands.command_dict[request][command_name]
json = command.json
if key.has_command_permission(command.permission_level):
command_list.append(json)
return command_list
class CommandAPI(View):
def get(self, request, command):
get = request.GET
key = check_request_for_key(get)
if key is not None:
if command.lower() == "commands":
return JsonResponse(get_commands(key), safe=False)
else:
return run_command(get, command, RequestTypes.GET, key)
return JsonResponse({})
def post(self, request, command):
post = request.POST
key = check_request_for_key(post)
if key is not None:
return run_command(post, command, RequestTypes.POST, key)
else:
return JsonResponse({})
class SettingsAPI(View):
def get(self, request):
key = check_request_for_key(request.GET)
if key.has_command_permission(PermissionLevel.PLAYER):
response = {
"BOT_PREFIX": getattr(settings, 'GEOFFREY_BOT_PREFIX', '?'),
"ERROR_USERS": getattr(settings, 'GEOFFREY_BOT_ERROR_USERS', []),
"MOD_RANKS": getattr(settings, 'GEOFFREY_BOT_MOD_RANK', []),
"STATUS": getattr(settings, 'GEOFFREY_BOT_STATUS', 'sed')
}
else:
response = {}
return JsonResponse(response)