2019-05-16 01:17:06 +02:00
|
|
|
import asyncio
|
|
|
|
from aiohttp import web
|
|
|
|
|
2019-05-19 08:25:15 +02:00
|
|
|
import server.database as db
|
2019-05-16 05:32:29 +02:00
|
|
|
|
|
|
|
ERRORS = {
|
|
|
|
'INVALID_PARAMS': {'code': -32602, 'message': 'Invalid parameters'},
|
|
|
|
'INTERNAL': {'code': -32603, 'message': 'An internal error'},
|
|
|
|
'UNKNOWN': {'code': -1, 'message': 'An unknown or very miscellaneous error'},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
class CommentServer:
|
2019-05-16 01:17:06 +02:00
|
|
|
def __init__(self, port=2903):
|
|
|
|
self.port = port
|
|
|
|
self.app = web.Application(debug=True)
|
|
|
|
self.app.add_routes([web.post('/api', self.api)])
|
|
|
|
self.runner = None
|
|
|
|
self.server = None
|
|
|
|
|
|
|
|
methods = {
|
2019-05-16 05:32:29 +02:00
|
|
|
'get_claim_comments': db.get_claim_comments,
|
|
|
|
'get_comment_ids': db.get_comment_ids,
|
2019-05-19 00:51:44 +02:00
|
|
|
'get_comments_by_id': db.get_comments_by_id,
|
2019-05-16 05:32:29 +02:00
|
|
|
'create_comment': db.create_comment,
|
2019-05-16 01:17:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
def process_json(self, body) -> dict:
|
|
|
|
response = {'jsonrpc': '2.0', 'id': body['id']}
|
|
|
|
if body['method'] in self.methods:
|
|
|
|
params = body.get('params', {})
|
|
|
|
result = self.methods[body['method']](self, **params)
|
|
|
|
if type(result) is dict and 'error' in result:
|
|
|
|
response['error'] = result['error']
|
|
|
|
else:
|
|
|
|
response['result'] = result
|
|
|
|
else:
|
2019-05-16 05:32:29 +02:00
|
|
|
response['error'] = ERRORS['UNKNOWN']
|
2019-05-16 01:17:06 +02:00
|
|
|
return response
|
|
|
|
|
|
|
|
async def _start(self):
|
|
|
|
self.runner = web.AppRunner(self.app)
|
|
|
|
await self.runner.setup()
|
|
|
|
self.server = web.TCPSite(self.runner, 'localhost', self.port)
|
|
|
|
await self.server.start()
|
|
|
|
|
|
|
|
async def _stop(self):
|
|
|
|
await self.runner.cleanup()
|
|
|
|
|
|
|
|
async def run(self, max_timeout=3600):
|
|
|
|
try:
|
|
|
|
await self._start()
|
|
|
|
await asyncio.sleep(max_timeout)
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
await self._stop()
|
|
|
|
|
|
|
|
async def api(self, request):
|
|
|
|
body = await request.json()
|
|
|
|
if type(body) is list or type(body) is dict:
|
|
|
|
if type(body) is list:
|
|
|
|
response = [self.process_json(part) for part in body]
|
|
|
|
else:
|
|
|
|
response = self.process_json(body)
|
|
|
|
return web.json_response(response)
|
|
|
|
else:
|
2019-05-16 05:32:29 +02:00
|
|
|
return web.json_response({'error': ERRORS['UNKNOWN']})
|
2019-05-16 01:17:06 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2019-05-16 05:32:29 +02:00
|
|
|
app = CommentServer()
|
2019-05-16 01:17:06 +02:00
|
|
|
asyncio.run(app.run())
|