2021-02-16 20:37:51 +01:00
|
|
|
from cbpi.api.dataclasses import Config
|
2018-12-29 00:27:19 +01:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
|
2019-01-05 20:43:48 +01:00
|
|
|
from cbpi.api.config import ConfigType
|
|
|
|
from cbpi.utils import load_config
|
2021-02-16 20:37:51 +01:00
|
|
|
import json
|
2018-11-18 15:40:10 +01:00
|
|
|
|
2019-07-27 21:08:19 +02:00
|
|
|
class ConfigController:
|
2021-02-16 20:37:51 +01:00
|
|
|
|
2018-11-18 15:40:10 +01:00
|
|
|
|
|
|
|
def __init__(self, cbpi):
|
2018-12-29 00:27:19 +01:00
|
|
|
self.cache = {}
|
|
|
|
self.logger = logging.getLogger(__name__)
|
2018-11-18 15:40:10 +01:00
|
|
|
self.cbpi = cbpi
|
2019-01-02 21:20:44 +01:00
|
|
|
self.cbpi.register(self)
|
2021-02-16 20:37:51 +01:00
|
|
|
self.path = os.path.join(".", 'config', "config.json")
|
2021-02-19 22:24:15 +01:00
|
|
|
self.path_static = os.path.join(".", 'config', "config.yaml")
|
2019-01-07 22:05:52 +01:00
|
|
|
|
|
|
|
def get_state(self):
|
2021-02-16 20:37:51 +01:00
|
|
|
|
|
|
|
result = {}
|
|
|
|
for key, value in self.cache.items():
|
|
|
|
result[key] = value.to_dict()
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
2019-01-07 22:05:52 +01:00
|
|
|
|
2018-12-29 00:27:19 +01:00
|
|
|
async def init(self):
|
2021-02-19 22:24:15 +01:00
|
|
|
self.static = load_config(self.path_static)
|
2021-02-16 20:37:51 +01:00
|
|
|
with open(self.path) as json_file:
|
|
|
|
data = json.load(json_file)
|
|
|
|
for key, value in data.items():
|
|
|
|
self.cache[key] = Config(name=value.get("name"), value=value.get("value"), description=value.get("description"), type=ConfigType(value.get("type", "string")), options=value.get("options", None) )
|
2018-12-29 00:27:19 +01:00
|
|
|
|
2018-12-31 00:22:00 +01:00
|
|
|
def get(self, name, default=None):
|
2019-07-27 21:08:19 +02:00
|
|
|
self.logger.debug("GET CONFIG VALUE %s (default %s)" % (name, default))
|
2018-12-29 00:27:19 +01:00
|
|
|
if name in self.cache and self.cache[name].value is not None:
|
|
|
|
return self.cache[name].value
|
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
|
|
|
async def set(self, name, value):
|
|
|
|
if name in self.cache:
|
2021-02-16 20:37:51 +01:00
|
|
|
|
2018-12-29 00:27:19 +01:00
|
|
|
self.cache[name].value = value
|
2021-02-16 20:37:51 +01:00
|
|
|
|
|
|
|
data = {}
|
|
|
|
for key, value in self.cache.items():
|
|
|
|
data[key] = value.to_dict()
|
|
|
|
with open(self.path, "w") as file:
|
|
|
|
json.dump(data, file, indent=4, sort_keys=True)
|
2018-12-29 00:27:19 +01:00
|
|
|
|
|
|
|
async def add(self, name, value, type: ConfigType, description, options=None):
|
2021-02-16 20:37:51 +01:00
|
|
|
self.cache[name] = Config(name,value,description,type,options)
|
|
|
|
data = {}
|
|
|
|
for key, value in self.cache.items():
|
|
|
|
data[key] = value.to_dict()
|
|
|
|
with open(self.path, "w") as file:
|
|
|
|
json.dump(data, file, indent=4, sort_keys=True)
|