.BANCHO. Add api handlers

This commit is contained in:
Nyo 2016-06-02 22:33:39 +02:00
parent 15933ce962
commit f6be15fa59
6 changed files with 134 additions and 67 deletions

View File

@ -59,3 +59,6 @@ class banchoRestartingException(Exception):
class apiException(Exception):
pass
class invalidArgumentsException(Exception):
pass

View File

@ -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))

View File

@ -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))

View File

@ -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))

View File

@ -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))

78
pep.py
View File

@ -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)