diff --git a/Basis/Api.py b/Basis/Api.py index a508701..66040b3 100644 --- a/Basis/Api.py +++ b/Basis/Api.py @@ -7,14 +7,56 @@ from Basis.Logger import logging from Basis.Constant import Version from flask import Flask, Response, request +token = '' webPath = '/' # root of api server webApi = Flask(__name__) # init flask server -def jsonResponse(data: dict) -> Response: +def jsonResponse(data: dict) -> Response: # return json mime return Response(json.dumps(data), mimetype = 'application/json') +def tokenError() -> Response: + return jsonResponse({ + 'success': False, + 'message': 'Invalid token' + }) + + +def tokenCheck() -> bool: + if token == '': return True # without token check + if request.method == 'GET': + return request.args.get('token') == token + elif request.method == 'POST': + return request.json.get('token') == token + else: + return False # polyfill + + +@webApi.route('/task', methods = ['GET']) +def getTaskList() -> Response: + if not tokenCheck(): # token check + return tokenError() + logging.critical('get task list') + return jsonResponse({}) + + +@webApi.route('/task', methods = ['POST']) +def createTask() -> Response: + if not tokenCheck(): # token check + return tokenError() + logging.critical('create task') + return jsonResponse({}) + + +@webApi.route('/task/', methods = ['GET']) +def getTaskInfo() -> Response: + if not tokenCheck(): # token check + return tokenError() + logging.critical('get task info') + return jsonResponse({}) + + @webApi.route('/version', methods = ['GET']) def getVersion() -> Response: logging.debug('get version -> %s' + Version) @@ -23,14 +65,9 @@ def getVersion() -> Response: }) -def startServer(apiPort: int = 7839, apiToken: str = '', isWsgi: bool = True) -> None: - global webApi, webPath - logging.warning( - 'API server at http://:%i/' % apiPort + (' (enable WSGI)' if isWsgi else '') - ) +def startServer(apiPort: int = 7839, apiToken: str = '') -> None: + global token + token = apiToken + logging.warning('API server at http://:%i/' % apiPort) logging.warning('API ' + ('without token' if apiToken == '' else 'token -> %s' % apiToken)) - if not isWsgi: - webApi.run(host = '0.0.0.0', port = apiPort, debug = True, threaded = True) # ordinary server (for debug) - else: - server = pywsgi.WSGIServer(('0.0.0.0', apiPort), webApi) # powered by gevent - server.serve_forever() + pywsgi.WSGIServer(('0.0.0.0', apiPort), webApi).serve_forever() # powered by gevent diff --git a/main.py b/main.py index d1eb411..ae87141 100755 --- a/main.py +++ b/main.py @@ -26,7 +26,7 @@ def daemonDnsproxy(dnsServers: list, localPort: int = 53, cacheSize: int = 41943 dnsCommand += ['--upstream', dnsServer] dnsproxy = startDnsproxy(dnsCommand) while True: - time.sleep(1) # daemon time gap + time.sleep(2) # daemon time gap if dnsproxy.poll() is not None: # unexpected exit logging.warning('dnsproxy unexpected exit') logging.debug('output of dnsproxy\n%s' % dnsproxy.stdout.read().decode('UTF-8'))