From 3d9a3ee79efbb331ad1ed28a25f470c0c22d465d Mon Sep 17 00:00:00 2001 From: user Date: Fri, 1 Mar 2024 23:32:03 +0300 Subject: [PATCH] dev@locazia: edit config manager --- app/core/models/_config.py | 46 ++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/app/core/models/_config.py b/app/core/models/_config.py index 3e3c009..19fd47c 100644 --- a/app/core/models/_config.py +++ b/app/core/models/_config.py @@ -1,32 +1,64 @@ +import string + from app.core.logger import make_log from json import loads as json_loads from json import dumps as json_dumps +from random import choice +from subprocess import Popen, PIPE class ConfigFile: def __init__(self, filepath: str): self.filepath = filepath + self.values + + @property + def values(self): with open(self.filepath, 'r') as file: - self.values = json_loads(file.read()) + return json_loads(file.read()) assert isinstance(self.values, dict) def get(self, key, default=None): return self.values.get(key, default) - def save(self): - with open(self.filepath, 'w') as file: + def set(self, key, value): + random_part = choice(string.ascii_lowercase) + app_cached_values = self.values + app_cached_values[key] = value + with open(f"{'/'.join(self.filepath.split('/')[:-1])}/.backup_{self.filepath.split('/')[-1]}_{random_part}", 'w') as file: file.write( json_dumps( - self.values, + app_cached_values, + indent=4, + sort_keys=True + ) + ) + + with open(self.filepath, 'w') as file: + file.write( + json_dumps( + app_cached_values, indent=4, sort_keys=True ) ) - def set(self, key, value): - self.values[key] = value - self.save() make_log("ConfigFile", f"Edited {key}", level="debug") + p1 = Popen(["md5sum", self.filepath], stdout=PIPE, stderr=PIPE) + p1.wait() + out1, err1 = p1.communicate() + p2 = Popen(["md5sum", f"{'/'.join(self.filepath.split('/')[:-1])}/.backup_{self.filepath.split('/')[-1]}_{random_part}"], stdout=PIPE, stderr=PIPE) + p2.wait() + out2, err2 = p2.communicate() + if err1 or err2: + make_log("ConfigFile", f"Error when editing {key} (check md5sum): {err1} {err2}", level="error") + return self.set(key, value) + fingerprint1 = out1.split()[0].strip() + fingerprint2 = out2.split()[0].strip() + + if fingerprint1 != fingerprint2: + make_log("ConfigFile", f"Error when editing {key} (check md5sum): {fingerprint1} {fingerprint2}", level="error") + return self.set(key, value)