From 86b8d6fc6264134f52b827ea0b20c46578836b77 Mon Sep 17 00:00:00 2001 From: Philipp Grathwohl Date: Sat, 19 Feb 2022 11:33:11 +0000 Subject: [PATCH] Allow specifying config path on start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bitte geben Sie eine Commit-Beschreibung für Ihre Änderungen ein. Zeilen, --- cbpi/cli.py | 213 ++++----------------- cbpi/configFolder.py | 117 +++++++++++ cbpi/controller/basic_controller2.py | 2 +- cbpi/controller/config_controller.py | 4 +- cbpi/controller/dashboard_controller.py | 10 +- cbpi/controller/fermentation_controller.py | 6 +- cbpi/controller/recipe_controller.py | 16 +- cbpi/controller/step_controller.py | 4 +- cbpi/controller/system_controller.py | 4 +- cbpi/controller/upload_controller.py | 24 +-- cbpi/craftbeerpi.py | 7 +- cbpi/http_endpoints/http_dashboard.py | 2 +- run.py | 2 +- 13 files changed, 191 insertions(+), 220 deletions(-) create mode 100644 cbpi/configFolder.py diff --git a/cbpi/cli.py b/cbpi/cli.py index 043b73a..61a43aa 100644 --- a/cbpi/cli.py +++ b/cbpi/cli.py @@ -1,93 +1,27 @@ -import argparse -import datetime import logging -import subprocess -import sys -import re import requests import yaml +from cbpi.configFolder import ConfigFolder from cbpi.utils.utils import load_config from zipfile import ZipFile from cbpi.craftbeerpi import CraftBeerPi import os -import platform import pathlib import pkgutil import shutil import yaml import click from subprocess import call -import zipfile from colorama import Fore, Back, Style -from importlib import import_module import importlib -from jinja2 import Template -from importlib_metadata import metadata, version +from importlib_metadata import metadata from tabulate import tabulate from PyInquirer import prompt, print_json -def create_config_file(): - if os.path.exists(os.path.join(".", 'config', "config.yaml")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "config.yaml") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "actor.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "actor.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "sensor.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "sensor.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "kettle.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "kettle.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "fermenter_data.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "fermenter_data.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "step_data.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "step_data.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "config.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "config.json") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "dashboard", "cbpi_dashboard_1.json")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "dashboard", "cbpi_dashboard_1.json") - destfile = os.path.join(".", "config", "dashboard") - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "carftbeerpi.service")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "craftbeerpi.service") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - if os.path.exists(os.path.join(".", 'config', "chromium.desktop")) is False: - srcfile = os.path.join(os.path.dirname(__file__), "config", "chromium.desktop") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - - print("Config Folder created") - - -def create_home_folder_structure(): +def create_home_folder_structure(configFolder): pathlib.Path(os.path.join(".", 'logs/sensors')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config/dashboard')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config/dashboard/widgets')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config/recipes')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config/fermenterrecipes')).mkdir(parents=True, exist_ok=True) - pathlib.Path(os.path.join(".", 'config/upload')).mkdir(parents=True, exist_ok=True) + + configFolder.create_folders() print("Folder created") @@ -108,79 +42,6 @@ def list_one_wire(): except Exception as e: print(e) -def copy_splash(): - srcfile = os.path.join(".", "config", "splash.png") - destfile = os.path.join(".", 'config') - shutil.copy(srcfile, destfile) - print("Splash Srceen created") - -def recursive_chown(path, owner, group): - for dirpath, dirnames, filenames in os.walk(path): - shutil.chown(dirpath, owner, group) - for filename in filenames: - shutil.chown(os.path.join(dirpath, filename), owner, group) - -def check_for_setup(): - if os.path.exists(os.path.join(".", "config", "config.yaml")) is False: - print("***************************************************") - print("CraftBeerPi Config File not found: %s" % os.path.join(".", "config", "config.yaml")) - print("Please run 'cbpi setup' before starting the server ") - print("***************************************************") - return False - if os.path.exists(os.path.join(".", "config", "upload")) is False: - print("***************************************************") - print("CraftBeerPi upload folder not found: %s" % os.path.join(".", "config/upload")) - print("Please run 'cbpi setup' before starting the server ") - print("***************************************************") - return False -# if os.path.exists(os.path.join(".", "config", "fermenterrecipes")) is False: -# print("***************************************************") -# print("CraftBeerPi fermenterrecipes folder not found: %s" % os.path.join(".", "config/fermenterrecipes")) -# print("Please run 'cbpi setup' before starting the server ") -# print("***************************************************") -# return False - backupfile = os.path.join(".", "restored_config.zip") - if os.path.exists(os.path.join(backupfile)) is True: - print("***************************************************") - print("Found backup of config. Starting restore") - required_content=['dashboard/', 'recipes/', 'upload/', 'config.json', 'config.yaml'] - zip=zipfile.ZipFile(backupfile) - zip_content_list = zip.namelist() - zip_content = True - print("Checking content of zip file") - for content in required_content: - try: - check = zip_content_list.index(content) - except: - zip_content = False - - if zip_content == True: - print("Found correct content. Starting Restore process") - output_path = pathlib.Path(os.path.join(".", 'config')) - system = platform.system() - print(system) - if system != "Windows": - owner = output_path.owner() - group = output_path.group() - print("Removing old config folder") - shutil.rmtree(output_path, ignore_errors=True) - print("Extracting zip file to config folder") - zip.extractall(output_path) - zip.close() - if system != "Windows": - print(f"Changing owner and group of config folder recursively to {owner}:{group}") - recursive_chown(output_path, owner, group) - print("Removing backup file") - os.remove(backupfile) - else: - print("Wrong Content in zip file. No restore possible") - print("Removing zip file") - os.remove(backupfile) - print("***************************************************") - - return True - else: - return True def plugins_list(): result = [] @@ -202,11 +63,9 @@ def plugins_list(): except Exception as e: print(e) print(Fore.LIGHTGREEN_EX, tabulate(result, headers="keys"), Style.RESET_ALL) - def plugin_create(): - print("Plugin Creation") print("") @@ -264,7 +123,6 @@ def plugin_create(): with open(os.path.join(".", name, name, "config.yaml"), "w") as fh: fh.write(outputText) - print("") print("") print("Plugin {}{}{} created! ".format(Fore.LIGHTGREEN_EX, name, Style.RESET_ALL) ) @@ -274,28 +132,31 @@ def plugin_create(): print("Happy developing! Cheers") print("") print("") - @click.group() -def main(): +@click.pass_context +@click.option('--config-folder-path', '-c', default="./config", type=click.Path(), help="Specify where the config folder is located. Defaults to './config'.") +def main(context, config_folder_path): print("---------------------") print("Welcome to CBPi") print("---------------------") level = logging.INFO logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') + context.obj = ConfigFolder(config_folder_path) pass -@click.command() -def setup(): +@main.command() +@click.pass_context +def setup(context): '''Create Config folder''' print("Setting up CraftBeerPi") - create_home_folder_structure() - create_config_file() + create_home_folder_structure(context.obj) + context.obj.create_config_file() -@click.command() +@main.command() @click.option('--list', is_flag=True, help="List all 1Wire Devices") @click.option('--setup', is_flag=True, help="Setup 1Wire on Raspberry Pi") def onewire(list, setup): @@ -306,34 +167,35 @@ def onewire(list, setup): list_one_wire() - -@click.command() -def start(): +@main.command() +@click.pass_context +def start(context): '''Lets go brewing''' - if check_for_setup() is False: + if context.obj.check_for_setup() is False: return print("Starting up CraftBeerPi ...") - cbpi = CraftBeerPi() + cbpi = CraftBeerPi(context.obj) cbpi.start() -@click.command() -def plugins(): +@main.command() +@click.pass_context +def plugins(context): '''List active plugins''' plugins_list() return - - @click.command() def create(): '''Create New Plugin''' plugin_create() -@click.command() + +@main.command() @click.argument('name') -def autostart(name): +@click.pass_context +def autostart(context, name): '''(on|off|status) Enable or disable autostart''' if(name == "status"): if os.path.exists(os.path.join("/etc/systemd/system","craftbeerpi.service")) is True: @@ -344,7 +206,7 @@ def autostart(name): print("Add craftbeerpi.service to systemd") try: if os.path.exists(os.path.join("/etc/systemd/system","craftbeerpi.service")) is False: - srcfile = os.path.join(".", "config", "craftbeerpi.service") + srcfile = context.obj.get_file_path("craftbeerpi.service") destfile = os.path.join("/etc/systemd/system") shutil.copy(srcfile, destfile) print("Copied craftbeerpi.service to /etc/systemd/system") @@ -379,13 +241,12 @@ def autostart(name): print(e) return return - - -@click.command() +@main.command() @click.argument('name') -def chromium(name): +@click.pass_context +def chromium(context, name): '''(on|off|status) Enable or disable Kiosk mode''' if(name == "status"): if os.path.exists(os.path.join("/etc/xdg/autostart/","chromium.desktop")) is True: @@ -396,7 +257,7 @@ def chromium(name): print("Add chromium.desktop to /etc/xdg/autostart/") try: if os.path.exists(os.path.join("/etc/xdg/autostart/","chromium.desktop")) is False: - srcfile = os.path.join(".", "config", "chromium.desktop") + srcfile = context.obj.get_file_path("chromium.desktop") destfile = os.path.join("/etc/xdg/autostart/") shutil.copy(srcfile, destfile) print("Copied chromium.desktop to /etc/xdg/autostart/") @@ -417,12 +278,4 @@ def chromium(name): except Exception as e: print(e) return - return - -main.add_command(setup) -main.add_command(start) -main.add_command(autostart) -main.add_command(chromium) -main.add_command(plugins) -main.add_command(onewire) -main.add_command(create) + return \ No newline at end of file diff --git a/cbpi/configFolder.py b/cbpi/configFolder.py new file mode 100644 index 0000000..699f6c4 --- /dev/null +++ b/cbpi/configFolder.py @@ -0,0 +1,117 @@ +import os +import pathlib +import platform +import shutil +import zipfile + + +class ConfigFolder: + def __init__(self, configFolderPath): + self._rawPath = configFolderPath + + def config_file_exists(self, path): + return os.path.exists(self.get_file_path(path)) + + def get_file_path(self, file): + return os.path.join(self._rawPath, file) + + def get_upload_file(self, file): + return os.path.join(self._rawPath, 'upload', file) + + def get_recipe_file_by_id(self, recipe_id): + return os.path.join(self._rawPath, 'recipes', "{}.yaml".format(recipe_id)) + + def check_for_setup(self): + if self.config_file_exists("config.yaml") is False: + print("***************************************************") + print("CraftBeerPi Config File not found: %s" % self.get_file_path("config.yaml")) + print("Please run 'cbpi setup' before starting the server ") + print("***************************************************") + return False + if self.config_file_exists("upload") is False: + print("***************************************************") + print("CraftBeerPi upload folder not found: %s" % self.get_file_path("upload")) + print("Please run 'cbpi setup' before starting the server ") + print("***************************************************") + return False + # if os.path.exists(os.path.join(".", "config", "fermenterrecipes")) is False: + # print("***************************************************") + # print("CraftBeerPi fermenterrecipes folder not found: %s" % os.path.join(".", "config/fermenterrecipes")) + # print("Please run 'cbpi setup' before starting the server ") + # print("***************************************************") + # return False + backupfile = os.path.join(".", "restored_config.zip") + if os.path.exists(os.path.join(backupfile)) is True: + print("***************************************************") + print("Found backup of config. Starting restore") + required_content=['dashboard/', 'recipes/', 'upload/', 'config.json', 'config.yaml'] + zip=zipfile.ZipFile(backupfile) + zip_content_list = zip.namelist() + zip_content = True + print("Checking content of zip file") + for content in required_content: + try: + check = zip_content_list.index(content) + except: + zip_content = False + + if zip_content == True: + print("Found correct content. Starting Restore process") + output_path = pathlib.Path(self._rawPath) + system = platform.system() + print(system) + if system != "Windows": + owner = output_path.owner() + group = output_path.group() + print("Removing old config folder") + shutil.rmtree(output_path, ignore_errors=True) + print("Extracting zip file to config folder") + zip.extractall(output_path) + zip.close() + if system != "Windows": + print(f"Changing owner and group of config folder recursively to {owner}:{group}") + self.recursive_chown(output_path, owner, group) + print("Removing backup file") + os.remove(backupfile) + else: + print("Wrong Content in zip file. No restore possible") + print("Removing zip file") + os.remove(backupfile) + print("***************************************************") + + def copyDefaultFileIfNotExists(self, file): + if self.config_file_exists(file) is False: + srcfile = os.path.join(os.path.dirname(__file__), "config", file) + destfile = os.path.join(self._rawPath, file) + shutil.copy(srcfile, destfile) + + def create_config_file(self): + self.copyDefaultFileIfNotExists("config.yaml") + self.copyDefaultFileIfNotExists("actor.json") + self.copyDefaultFileIfNotExists("sensor.json") + self.copyDefaultFileIfNotExists("kettle.json") + self.copyDefaultFileIfNotExists("fermenter_data.json") + self.copyDefaultFileIfNotExists("step_data.json") + self.copyDefaultFileIfNotExists("config.json") + self.copyDefaultFileIfNotExists("craftbeerpi.service") + self.copyDefaultFileIfNotExists("chromium.desktop") + + if os.path.exists(os.path.join(self._rawPath, "dashboard", "cbpi_dashboard_1.json")) is False: + srcfile = os.path.join(os.path.dirname(__file__), "config", "dashboard", "cbpi_dashboard_1.json") + destfile = os.path.join(self._rawPath, "dashboard") + shutil.copy(srcfile, destfile) + + print("Config Folder created") + + + def create_folders(self): + pathlib.Path(self._rawPath).mkdir(parents=True, exist_ok=True) + pathlib.Path(os.path.join(self._rawPath, 'dashboard', 'widgets')).mkdir(parents=True, exist_ok=True) + pathlib.Path(os.path.join(self._rawPath, 'recipes')).mkdir(parents=True, exist_ok=True) + pathlib.Path(os.path.join(self._rawPath, 'upload')).mkdir(parents=True, exist_ok=True) + + def recursive_chown(path, owner, group): + for dirpath, dirnames, filenames in os.walk(path): + shutil.chown(dirpath, owner, group) + for filename in filenames: + shutil.chown(os.path.join(dirpath, filename), owner, group) \ No newline at end of file diff --git a/cbpi/controller/basic_controller2.py b/cbpi/controller/basic_controller2.py index 990f54e..c3207dc 100644 --- a/cbpi/controller/basic_controller2.py +++ b/cbpi/controller/basic_controller2.py @@ -23,7 +23,7 @@ class BasicController: self.data = [] self.autostart = True #self._loop = asyncio.get_event_loop() - self.path = os.path.join(".", 'config', file) + self.path = self.cbpi.config_folder.get_file_path(file) self.cbpi.app.on_cleanup.append(self.shutdown) async def init(self): diff --git a/cbpi/controller/config_controller.py b/cbpi/controller/config_controller.py index 65d0298..4afaa0b 100644 --- a/cbpi/controller/config_controller.py +++ b/cbpi/controller/config_controller.py @@ -14,8 +14,8 @@ class ConfigController: self.logger = logging.getLogger(__name__) self.cbpi = cbpi self.cbpi.register(self) - self.path = os.path.join(".", 'config', "config.json") - self.path_static = os.path.join(".", 'config', "config.yaml") + self.path = cbpi.config_folder.get_file_path("config.json") + self.path_static = cbpi.config_folder.get_file_path("config.yaml") def get_state(self): diff --git a/cbpi/controller/dashboard_controller.py b/cbpi/controller/dashboard_controller.py index 73bd064..228839c 100644 --- a/cbpi/controller/dashboard_controller.py +++ b/cbpi/controller/dashboard_controller.py @@ -18,14 +18,14 @@ class DashboardController: self.logger = logging.getLogger(__name__) self.cbpi.register(self) - self.path = os.path.join(".", 'config', "cbpi_dashboard_1.json") + self.path = cbpi.config_folder.get_file_path("cbpi_dashboard_1.json") async def init(self): pass async def get_content(self, dashboard_id): try: - self.path = os.path.join(".", 'config', "cbpi_dashboard_"+ str(dashboard_id) +".json") + self.path = self.cbpi.config_folder.get_file_path("cbpi_dashboard_"+ str(dashboard_id) +".json") logging.info(self.path) with open(self.path) as json_file: data = json.load(json_file) @@ -35,21 +35,21 @@ class DashboardController: async def add_content(self, dashboard_id, data): print(data) - self.path = os.path.join(".", 'config', "cbpi_dashboard_" + str(dashboard_id)+ ".json") + self.path = self.cbpi.config_folder.get_file_path("cbpi_dashboard_" + str(dashboard_id)+ ".json") with open(self.path, 'w') as outfile: json.dump(data, outfile, indent=4, sort_keys=True) self.cbpi.notify(title="Dashboard {}".format(dashboard_id), message="Saved Successfully", type=NotificationType.SUCCESS) return {"status": "OK"} async def delete_content(self, dashboard_id): - self.path = os.path.join(".", 'config', "cbpi_dashboard_"+ str(dashboard_id)+ ".json") + self.path = self.cbpi.config_folder.get_file_path("cbpi_dashboard_"+ str(dashboard_id)+ ".json") if os.path.exists(self.path): os.remove(self.path) self.cbpi.notify(title="Dashboard {}".format(dashboard_id), message="Deleted Successfully", type=NotificationType.SUCCESS) async def get_custom_widgets(self): - path = os.path.join(".", 'config', "dashboard", "widgets") + path = os.path.join(self.cbpi.config_folder.get_file_path("dashboard"), "widgets") onlyfiles = [os.path.splitext(f)[0] for f in sorted(listdir(path)) if isfile(join(path, f)) and f.endswith(".svg")] return onlyfiles diff --git a/cbpi/controller/fermentation_controller.py b/cbpi/controller/fermentation_controller.py index 96b2f49..6e29a58 100644 --- a/cbpi/controller/fermentation_controller.py +++ b/cbpi/controller/fermentation_controller.py @@ -22,7 +22,7 @@ class FermentationController: self.update_key = "fermenterupdate" self.cbpi = cbpi self.logger = logging.getLogger(__name__) - self.path = os.path.join(".", 'config', "fermenter_data.json") + self.path = self.cbpi.config_folder.get_file_path("fermenter_data.json") self.data = [] self.types = {} self.steptypes = {} @@ -35,13 +35,13 @@ class FermentationController: pass def check_fermenter_file(self): - if os.path.exists(os.path.join(".", 'config', "fermenter_data.json")) is False: + if os.path.exists(self.cbpi.config_folder.get_file_path("fermenter_data.json")) is False: logging.info("INIT fermenter_data.json file") data = { "data": [ ] } - destfile = os.path.join(".", 'config', "fermenter_data.json") + destfile = self.cbpi.config_folder.get_file_path("fermenter_data.json") json.dump(data,open(destfile,'w'),indent=4, sort_keys=True) pathlib.Path(os.path.join(".", 'config/fermenterrecipes')).mkdir(parents=True, exist_ok=True) diff --git a/cbpi/controller/recipe_controller.py b/cbpi/controller/recipe_controller.py index d668291..c3fbe51 100644 --- a/cbpi/controller/recipe_controller.py +++ b/cbpi/controller/recipe_controller.py @@ -29,26 +29,26 @@ class RecipeController: async def create(self, name): id = shortuuid.uuid() - path = os.path.join(".", 'config', "recipes", "{}.yaml".format(id)) + path = self.cbpi.config_folder.get_recipe_file_by_id(id) data = dict(basic=dict(name=name, author=self.cbpi.config.get("AUTHOR", "John Doe")), steps=[]) with open(path, "w") as file: yaml.dump(data, file) return id async def save(self, name, data): - path = os.path.join(".", 'config', "recipes", "{}.yaml".format(name)) + path = self.cbpi.config_folder.get_recipe_file_by_id(name) logging.info(data) with open(path, "w") as file: yaml.dump(data, file, indent=4, sort_keys=True) async def get_recipes(self): - path = os.path.join(".", 'config', "recipes") + path = self.cbpi.config_folder.get_file_path("recipes") onlyfiles = [os.path.splitext(f)[0] for f in listdir(path) if isfile(join(path, f)) and f.endswith(".yaml")] result = [] for filename in onlyfiles: - recipe_path = os.path.join(".", 'config', "recipes", "%s.yaml" % filename) + recipe_path = self.cbpi.config_folder.get_recipe_file_by_id(filename) with open(recipe_path) as file: data = yaml.load(file, Loader=yaml.FullLoader) dataset = data["basic"] @@ -58,25 +58,25 @@ class RecipeController: async def get_by_name(self, name): - recipe_path = os.path.join(".", 'config', "recipes", "%s.yaml" % name) + recipe_path = self.cbpi.config_folder.get_recipe_file_by_id(name) with open(recipe_path) as file: return yaml.load(file, Loader=yaml.FullLoader) async def remove(self, name): - path = os.path.join(".", 'config', "recipes", "{}.yaml".format(name)) + path = self.cbpi.config_folder.get_recipe_file_by_id(name) os.remove(path) async def brew(self, name): - recipe_path = os.path.join(".", 'config', "recipes", "%s.yaml" % name) + recipe_path = self.cbpi.config_folder.get_recipe_file_by_id(name) with open(recipe_path) as file: data = yaml.load(file, Loader=yaml.FullLoader) await self.cbpi.step.load_recipe(data) async def clone(self, id, new_name): - recipe_path = os.path.join(".", 'config', "recipes", "%s.yaml" % id) + recipe_path = self.cbpi.config_folder.get_recipe_file_by_id(id) with open(recipe_path) as file: data = yaml.load(file, Loader=yaml.FullLoader) data["basic"]["name"] = new_name diff --git a/cbpi/controller/step_controller.py b/cbpi/controller/step_controller.py index 8f9294e..892f46b 100644 --- a/cbpi/controller/step_controller.py +++ b/cbpi/controller/step_controller.py @@ -19,7 +19,7 @@ class StepController: def __init__(self, cbpi): self.cbpi = cbpi self.logger = logging.getLogger(__name__) - self.path = os.path.join(".", 'config', "step_data.json") + self.path = self.cbpi.config_folder.get_file_path("step_data.json") #self._loop = asyncio.get_event_loop() self.basic_data = {} self.step = None @@ -324,7 +324,7 @@ class StepController: async def savetobook(self): name = shortuuid.uuid() - path = os.path.join(".", 'config', "recipes", "{}.yaml".format(name)) + path = os.path.join(self.cbpi.config_folder.get_file_path("recipes"), "{}.yaml".format(name)) data = dict(basic=self.basic_data, steps=list(map(lambda item: item.to_dict(), self.profile))) with open(path, "w") as file: yaml.dump(data, file) diff --git a/cbpi/controller/system_controller.py b/cbpi/controller/system_controller.py index 59a6eae..8c211fc 100644 --- a/cbpi/controller/system_controller.py +++ b/cbpi/controller/system_controller.py @@ -38,7 +38,7 @@ class SystemController: async def backupConfig(self): output_filename = "cbpi4_config" - dir_name = pathlib.Path(os.path.join(".", 'config')) + dir_name = pathlib.Path(self.cbpi.config_folder.get_file_path('')) shutil.make_archive(output_filename, 'zip', dir_name) async def downloadlog(self, logtime): @@ -153,7 +153,7 @@ class SystemController: try: content = svg_file.read().decode('utf-8','replace') if svg_file and self.allowed_file(filename, 'svg'): - self.path = os.path.join(".","config","dashboard","widgets", filename) + self.path = os.path.join(self.cbpi.config_folder.get_file_path("dashboard"),"widgets", filename) logging.info(self.path) f=open(self.path, "w") diff --git a/cbpi/controller/upload_controller.py b/cbpi/controller/upload_controller.py index c7db2bb..2d21de0 100644 --- a/cbpi/controller/upload_controller.py +++ b/cbpi/controller/upload_controller.py @@ -32,7 +32,7 @@ class UploadController: async def get_kbh_recipes(self): try: - path = os.path.join(".", 'config', "upload", "kbh.db") + path = self.cbpi.config_folder.get_upload_file("kbh.db") conn = sqlite3.connect(path) c = conn.cursor() c.execute('SELECT ID, Sudname, Status FROM Sud') @@ -47,7 +47,7 @@ class UploadController: async def get_xml_recipes(self): try: - path = os.path.join(".", 'config', "upload", "beer.xml") + path = self.cbpi.config_folder.get_upload_file("beer.xml") e = xml.etree.ElementTree.parse(path).getroot() result =[] counter = 1 @@ -61,7 +61,7 @@ class UploadController: async def get_json_recipes(self): try: - path = os.path.join(".", 'config', "upload", "mmum.json") + path = self.cbpi.config_folder.get_upload_file("mmum.json") e = json.load(open(path)) result =[] result.append({'value': str(1), 'label': e['Name']}) @@ -123,7 +123,7 @@ class UploadController: try: beer_xml = recipe_file.read().decode('utf-8','replace') if recipe_file and self.allowed_file(filename, 'xml'): - self.path = os.path.join(".", 'config', "upload", "beer.xml") + self.path = self.cbpi.config_folder.get_upload_file("beer.xml") f = open(self.path, "w") f.write(beer_xml) @@ -137,7 +137,7 @@ class UploadController: try: mmum_json = recipe_file.read().decode('utf-8','replace') if recipe_file and self.allowed_file(filename, 'json'): - self.path = os.path.join(".", 'config', "upload", "mmum.json") + self.path = self.cbpi.config_folder.get_upload_file("mmum.json") f = open(self.path, "w") f.write(mmum_json) @@ -151,7 +151,7 @@ class UploadController: try: content = recipe_file.read() if recipe_file and self.allowed_file(filename, 'sqlite'): - self.path = os.path.join(".", 'config', "upload", "kbh.db") + self.path = self.cbpi.config_folder.get_upload_file("kbh.db") f=open(self.path, "wb") f.write(content) @@ -168,7 +168,7 @@ class UploadController: config = self.get_config_values() if self.kettle is not None: # load beerxml file located in upload folder - self.path = os.path.join(".", 'config', "upload", "kbh.db") + self.path = self.cbpi.config_folder.get_upload_file("kbh.db") if os.path.exists(self.path) is False: self.cbpi.notify("File Not Found", "Please upload a kbh V2 databsel file", NotificationType.ERROR) @@ -318,7 +318,7 @@ class UploadController: self.cbpi.notify('Recipe Upload', 'No default Kettle defined. Please specify default Kettle in settings', NotificationType.ERROR) def findMax(self, string): - self.path = os.path.join(".", 'config', "upload", "mmum.json") + self.path = self.cbpi.config_folder.get_upload_file("mmum.json") e = json.load(open(self.path)) for idx in range(1,20): search_string = string.replace("%%",str(idx)) @@ -328,7 +328,7 @@ class UploadController: return i def getJsonMashin(self, id): - self.path = os.path.join(".", 'config', "upload", "mmum.json") + self.path = self.cbpi.config_folder.get_upload_file("mmum.json") e = json.load(open(self.path)) return float(e['Infusion_Einmaischtemperatur']) @@ -337,7 +337,7 @@ class UploadController: if self.kettle is not None: # load mmum-json file located in upload folder - self.path = os.path.join(".", 'config', "upload", "mmum.json") + self.path = self.cbpi.config_folder.get_upload_file("mmum.json") if os.path.exists(self.path) is False: self.cbpi.notify("File Not Found", "Please upload a MMuM-JSON File", NotificationType.ERROR) @@ -551,7 +551,7 @@ class UploadController: if self.kettle is not None: # load beerxml file located in upload folder - self.path = os.path.join(".", 'config', "upload", "beer.xml") + self.path = self.cbpi.config_folder.get_upload_file("beer.xml") if os.path.exists(self.path) is False: self.cbpi.notify("File Not Found", "Please upload a Beer.xml File", NotificationType.ERROR) @@ -692,7 +692,7 @@ class UploadController: temp = round(9.0 / 5.0 * float(e.find("STEP_TEMP").text) + 32, 2) steps.append({"name": e.find("NAME").text, "temp": temp, "timer": float(e.find("STEP_TIME").text)}) elif recipe_type == "json": - self.path = os.path.join(".", 'config', "upload", "mmum.json") + self.path = self.cbpi.config_folder.get_upload_file("mmum.json") e = json.load(open(self.path)) for idx in range(1,self.findMax("Infusion_Rastzeit%%")): if self.cbpi.config.get("TEMP_UNIT", "C") == "C": diff --git a/cbpi/craftbeerpi.py b/cbpi/craftbeerpi.py index b9ba484..b5efa61 100644 --- a/cbpi/craftbeerpi.py +++ b/cbpi/craftbeerpi.py @@ -86,7 +86,7 @@ async def error_middleware(request, handler): class CraftBeerPi: - def __init__(self): + def __init__(self, configFolder): operationsystem= sys.platform if operationsystem.startswith('win'): @@ -96,8 +96,9 @@ class CraftBeerPi: self.version = __version__ self.codename = __codename__ - - self.static_config = load_config(os.path.join(".", 'config', "config.yaml")) + + self.config_folder = configFolder + self.static_config = load_config(configFolder.get_file_path("config.yaml")) logger.info("Init CraftBeerPI") diff --git a/cbpi/http_endpoints/http_dashboard.py b/cbpi/http_endpoints/http_dashboard.py index 2865191..53d5d8a 100644 --- a/cbpi/http_endpoints/http_dashboard.py +++ b/cbpi/http_endpoints/http_dashboard.py @@ -12,7 +12,7 @@ class DashBoardHttpEndpoints: def __init__(self, cbpi): self.cbpi = cbpi self.controller = cbpi.dashboard - self.cbpi.register(self, "/dashboard", os.path.join(".","config", "dashboard", "widgets")) + self.cbpi.register(self, "/dashboard", os.path.join(cbpi.config_folder.get_file_path("dashboard"), "widgets")) @request_mapping(path="/{id:\d+}/content", auth_required=False) diff --git a/run.py b/run.py index db3291c..940b73e 100644 --- a/run.py +++ b/run.py @@ -1,3 +1,3 @@ from cbpi.cli import main -main() \ No newline at end of file +main(auto_envvar_prefix='CBPI') \ No newline at end of file