diff --git a/views/base.py b/views/base.py index b51ff81c..a4513b4e 100644 --- a/views/base.py +++ b/views/base.py @@ -19,7 +19,10 @@ def set_default_headers(self): def prepare(self): if self.request.headers.get('Content-Type', '').startswith('application/json'): - self.json_args = json.loads(self.request.body) + try: + self.json_args = json.loads(self.request.body) + except json.JSONDecodeError: + self.json_args = None else: self.json_args = None diff --git a/views/config.py b/views/config.py index 81a756e7..b512bc29 100644 --- a/views/config.py +++ b/views/config.py @@ -1,30 +1,35 @@ # -*- coding: utf-8 -*- +import json import uuid import views.base from typing import * -configs: Dict[str, dict] = {} +MAX_CONFIG_SIZE = 100 * 1024 -ALLOWED_FIELDS = ( - 'showDanmaku', 'showGift', 'mergeSimilarDanmaku', 'minGiftPrice', 'maxSpeed', - 'maxNumber', 'blockGiftDanmaku', 'blockLevel', 'blockNewbie', 'blockNotMobileVerified', - 'blockKeywords', 'blockUsers', 'blockMedalLevel', 'css' -) +configs: Dict[str, dict] = {} # noinspection PyAbstractClass class ConfigsHandler(views.base.ApiHandler): async def post(self): + if not isinstance(self.json_args, dict): + self.set_status(400) + return + + config = self.json_args config_id = str(uuid.uuid4()) - config = { - name: self.json_args[name] for name in ALLOWED_FIELDS - } config['id'] = config_id + config_str = json.dumps(config) + if len(config_str) > MAX_CONFIG_SIZE: + self.set_status(413) + return + configs[config_id] = config + self.write(config_str) self.set_status(201) - self.write(config) + self.set_header('Content-Type', 'application/json; charset=UTF-8') if len(configs) > 10000: for _, key in zip(range(100), configs): @@ -34,13 +39,23 @@ async def post(self): # noinspection PyAbstractClass class ConfigHandler(views.base.ApiHandler): async def put(self, config_id): - config = configs.get(config_id, None) - if config is None: + if config_id not in configs: self.set_status(404) return - for name in ALLOWED_FIELDS: - config[name] = self.json_args[name] - self.write(config) + if not isinstance(self.json_args, dict): + self.set_status(400) + return + + config = self.json_args + config['id'] = config_id + config_str = json.dumps(config) + if len(config_str) > MAX_CONFIG_SIZE: + self.set_status(413) + return + + configs[config_id] = config + self.write(config_str) + self.set_header('Content-Type', 'application/json; charset=UTF-8') async def get(self, config_id): config = configs.get(config_id, None)