Geoffrey-Django/GeoffreyApp/api/views.py

89 lines
2.7 KiB
Python
Raw Normal View History

from django.views.generic import View
from django.http import JsonResponse
2018-12-02 02:17:19 +00:00
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
2018-12-17 16:02:43 +00:00
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)}
2019-01-31 23:10:28 +00:00
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(request)
if key is not None:
return run_command(post, command, RequestTypes.POST, key)
else:
return JsonResponse({})
2018-12-02 02:17:19 +00:00
class SettingsAPI(View):
2018-12-08 21:37:00 +00:00
def get(self, request):
key = check_request_for_key(request.GET)
if key.has_command_permission(PermissionLevel.PLAYER):
2019-01-01 16:18:15 +00:00
response = {
"BOT_PREFIX": getattr(settings, 'GEOFFREY_BOT_PREFIX', '?'),
"ERROR_USERS": getattr(settings, 'GEOFFREY_BOT_ERROR_USERS', []),
2019-01-01 16:18:15 +00:00
"MOD_RANKS": getattr(settings, 'GEOFFREY_BOT_MOD_RANK', []),
"STATUS": getattr(settings, 'GEOFFREY_BOT_STATUS', 'sed')
}
else:
response = {}
2018-12-02 02:17:19 +00:00
return JsonResponse(response)