From f6be15fa59979672fb6ef0b71b8f75dd65bda086 Mon Sep 17 00:00:00 2001 From: Nyo Date: Thu, 2 Jun 2016 22:33:39 +0200 Subject: [PATCH] .BANCHO. Add api handlers --- constants/exceptions.py | 3 ++ handlers/apiIsOnlineHandler.py | 35 ++++++++++++++ handlers/apiOnlineUsersHandler.py | 23 +++++++++ handlers/apiServerStatusHandler.py | 23 +++++++++ handlers/ciTriggerHandler.py | 39 +++++++++++++++ pep.py | 78 +++++------------------------- 6 files changed, 134 insertions(+), 67 deletions(-) create mode 100644 handlers/apiIsOnlineHandler.py create mode 100644 handlers/apiOnlineUsersHandler.py create mode 100644 handlers/apiServerStatusHandler.py create mode 100644 handlers/ciTriggerHandler.py diff --git a/constants/exceptions.py b/constants/exceptions.py index 1b05ca6..d5bb386 100644 --- a/constants/exceptions.py +++ b/constants/exceptions.py @@ -59,3 +59,6 @@ class banchoRestartingException(Exception): class apiException(Exception): pass + +class invalidArgumentsException(Exception): + pass diff --git a/handlers/apiIsOnlineHandler.py b/handlers/apiIsOnlineHandler.py new file mode 100644 index 0000000..cb3f08f --- /dev/null +++ b/handlers/apiIsOnlineHandler.py @@ -0,0 +1,35 @@ +from helpers import requestHelper +from constants import exceptions +import json +from objects import glob + +class handler(requestHelper.asyncRequestHandler): + def asyncGet(self): + statusCode = 400 + data = {"message": "unknown error"} + try: + # Check arguments + if requestHelper.checkArguments(self.request.arguments, ["u"]) == False: + raise exceptions.invalidArgumentsException() + + # Get online staus + username = self.get_argument("u") + if username == None: + data["result"] = False + else: + data["result"] = True if glob.tokens.getTokenFromUsername(username) != None else False + + # Status code and message + statusCode = 200 + data["message"] = "ok" + except exceptions.invalidArgumentsException: + statusCode = 400 + data["message"] = "missing required arguments" + finally: + # Add status code to data + data["status"] = statusCode + + # Send response + self.clear() + self.set_status(statusCode) + self.finish(json.dumps(data)) diff --git a/handlers/apiOnlineUsersHandler.py b/handlers/apiOnlineUsersHandler.py new file mode 100644 index 0000000..bdaedc4 --- /dev/null +++ b/handlers/apiOnlineUsersHandler.py @@ -0,0 +1,23 @@ +from helpers import requestHelper +import json +from objects import glob + +class handler(requestHelper.asyncRequestHandler): + def asyncGet(self): + statusCode = 400 + data = {"message": "unknown error"} + try: + # Get online users count + data["result"] = len(glob.tokens.tokens) + + # Status code and message + statusCode = 200 + data["message"] = "ok" + finally: + # Add status code to data + data["status"] = statusCode + + # Send response + self.clear() + self.set_status(statusCode) + self.finish(json.dumps(data)) diff --git a/handlers/apiServerStatusHandler.py b/handlers/apiServerStatusHandler.py new file mode 100644 index 0000000..db06ef0 --- /dev/null +++ b/handlers/apiServerStatusHandler.py @@ -0,0 +1,23 @@ +from helpers import requestHelper +import json +from objects import glob + +class handler(requestHelper.asyncRequestHandler): + def asyncGet(self): + statusCode = 400 + data = {"message": "unknown error"} + try: + # Get online users count + data["result"] = -1 if glob.restarting == True else 1 + + # Status code and message + statusCode = 200 + data["message"] = "ok" + finally: + # Add status code to data + data["status"] = statusCode + + # Send response + self.clear() + self.set_status(statusCode) + self.finish(json.dumps(data)) diff --git a/handlers/ciTriggerHandler.py b/handlers/ciTriggerHandler.py new file mode 100644 index 0000000..ee4f83a --- /dev/null +++ b/handlers/ciTriggerHandler.py @@ -0,0 +1,39 @@ +from helpers import requestHelper +from constants import exceptions +import json +from objects import glob +from helpers import consoleHelper +from constants import bcolors +from helpers import systemHelper + +class handler(requestHelper.asyncRequestHandler): + def asyncGet(self): + statusCode = 400 + data = {"message": "unknown error"} + try: + # Check arguments + if requestHelper.checkArguments(self.request.arguments, ["k"]) == False: + raise exceptions.invalidArgumentsException() + + # Check ci key + key = self.get_argument("k") + if key is None or key != glob.conf.config["ci"]["key"]: + raise exceptions.invalidArgumentsException() + + consoleHelper.printColored("[!] Ci event triggered!!", bcolors.PINK) + systemHelper.scheduleShutdown(5, False, "A new Bancho update is available and the server will be restarted in 5 seconds. Thank you for your patience.") + + # Status code and message + statusCode = 200 + data["message"] = "ok" + except exceptions.invalidArgumentsException: + statusCode = 400 + data["message"] = "invalid ci key" + finally: + # Add status code to data + data["status"] = statusCode + + # Send response + self.clear() + self.set_status(statusCode) + self.finish(json.dumps(data)) diff --git a/pep.py b/pep.py index a2122f4..ce002bc 100644 --- a/pep.py +++ b/pep.py @@ -16,81 +16,25 @@ from helpers import discordBotHelper from objects import glob from objects import fokabot from objects import banchoConfig -from handlers import mainHandler from helpers import consoleHelper from helpers import databaseHelperNew from helpers import generalFunctions +from handlers import mainHandler +from handlers import apiIsOnlineHandler +from handlers import apiOnlineUsersHandler +from handlers import apiServerStatusHandler +from handlers import ciTriggerHandler + def make_app(): return tornado.web.Application([ - (r"/", mainHandler.handler) + (r"/", mainHandler.handler), + (r"/api/v1/isOnline", apiIsOnlineHandler.handler), + (r"/api/v1/onlineUsers", apiOnlineUsersHandler.handler), + (r"/api/v1/serverStatus", apiServerStatusHandler.handler), + (r"/api/v1/ciTrigger", ciTriggerHandler.handler), ]) -# Ci trigger -'''@app.route("/ci-trigger") -@app.route("/api/ci-trigger") -def ciTrigger(): - # Ci restart trigger - - # Get ket from GET - key = flask.request.args.get('k') - - # Get request ip - requestIP = flask.request.headers.get('X-Real-IP') - if requestIP == None: - requestIP = flask.request.remote_addr - - # Check key - if key is None or key != glob.conf.config["ci"]["key"]: - consoleHelper.printColored("[!] Invalid ci trigger from {}".format(requestIP), bcolors.RED) - return flask.jsonify({"response" : "-1"}) - - # Ci event triggered, schedule server shutdown - consoleHelper.printColored("[!] Ci event triggered from {}".format(requestIP), bcolors.PINK) - systemHelper.scheduleShutdown(5, False, "A new Bancho update is available and the server will be restarted in 5 seconds. Thank you for your patience.") - - return flask.jsonify({"response" : 1}) - - -@app.route("/api/server-status") -def serverStatus(): - # Server status api - # 1: Online - # -1: Restarting - return flask.jsonify({ - "response" : 200, - "status" : -1 if glob.restarting == True else 1 - }) - -@app.route("/api/v1/isOnline") -def apiIsOnline(): - username = request.args.get("u") - if username == None: - result = False - else: - token = glob.tokens.getTokenFromUsername(username) - result = True if token != None else False - return flask.jsonify({ - "result": result - }) - -@app.route("/api/v1/onlineUsers") -def apiOnlineUsers(): - return flask.jsonify({ - "result": len(glob.tokens.tokens) - }) - -# Main bancho server -@app.route("/", methods=['GET', 'POST']) -def banchoServer(): - if flask.request.method == 'POST': - - - else: - # Not a POST request, send html page - return responseHelper.HTMLResponse()''' - - if __name__ == "__main__": # Server start consoleHelper.printServerStartHeader(True)