refactor configcheck

- move the decission to check the config from serverside to clientside
- add confirmation for saving a faulty config
This commit is contained in:
thelastWallE 2021-11-03 11:10:14 +01:00
parent 5d9f935568
commit 3478bc06ee
4 changed files with 110 additions and 79 deletions

View File

@ -106,6 +106,7 @@ class KlipperPlugin(
] ]
def get_settings_defaults(self): def get_settings_defaults(self):
# TODO #69 put some settings on the localStorage
return dict( return dict(
connection=dict( connection=dict(
port="/tmp/printer", port="/tmp/printer",
@ -563,7 +564,7 @@ class KlipperPlugin(
def check_config(self): def check_config(self):
data = flask.request.json data = flask.request.json
data_to_check = data.get("DataToCheck", []) data_to_check = data.get("DataToCheck", [])
response = cfgUtils.check_cfg(self, data_to_check) response = cfgUtils.check_cfg_ok(self, data_to_check)
return flask.jsonify(is_syntax_ok = response) return flask.jsonify(is_syntax_ok = response)
# save a configfile # save a configfile

View File

@ -124,13 +124,6 @@ def save_cfg(self, content, filename):
filename += ".cfg" filename += ".cfg"
filepath = os.path.join(configpath, filename) filepath = os.path.join(configpath, filename)
logger.log_debug(self, "save filepath: {}".format(filepath))
check_parse = self._settings.get(["configuration", "parse_check"])
logger.log_debug(self, "check_parse on filesave: {}".format(check_parse))
if check_parse and not check_cfg(self, content):
return False
logger.log_debug(self, "Writing Klipper config to {}".format(filepath)) logger.log_debug(self, "Writing Klipper config to {}".format(filepath))
try: try:
@ -147,7 +140,7 @@ def save_cfg(self, content, filename):
copy_cfg_to_backup(self, filepath) copy_cfg_to_backup(self, filepath)
def check_cfg(self, data): def check_cfg_ok(self, data):
"""Checks the given data on parsing errors. """Checks the given data on parsing errors.
Args: Args:
@ -190,14 +183,6 @@ def show_error_message(self, error):
('Error: Invalid Klipper config file:\n' + '{}'.format(str(error))), ('Error: Invalid Klipper config file:\n' + '{}'.format(str(error))),
) )
util.send_message(
self,
type = 'PopUp',
subtype = 'warning',
title = 'Invalid Config data\n',
payload = ('\n' + str(error))
)
def is_float_ok(self, dataToValidated): def is_float_ok(self, dataToValidated):

View File

@ -252,7 +252,7 @@ $(function () {
}; };
self.saveOption = function(dir, option, value) { self.saveOption = function(dir, option, value) {
if (! (_.includes(["fontsize", "confirm_reload"], option)) ) { if (! (_.includes(["fontsize", "confirm_reload", "parse_check"], option)) ) {
return; return;
} }
@ -302,7 +302,7 @@ $(function () {
showConfirmationDialog({ showConfirmationDialog({
title: gettext("Restart Klipper?"), title: gettext("Restart Klipper?"),
html: html, html: html,
proceed: [gettext("Restart"), gettext("Restart and don't show again.")], proceed: [gettext("Restart"), gettext("Restart and don't show this again.")],
onproceed: function (idx) { onproceed: function (idx) {
if (idx > -1) { if (idx > -1) {
request(idx); request(idx);

View File

@ -44,7 +44,7 @@ $(function () {
self.checkExternChange(); self.checkExternChange();
editor.focus(); editor.focus();
self.setEditorDivSize(); self.setEditorDivSize();
} };
self.close_selection = function (index) { self.close_selection = function (index) {
switch (index) { switch (index) {
@ -58,7 +58,7 @@ $(function () {
self.saveCfg({closing: true}); self.saveCfg({closing: true});
break; break;
} }
} };
self.closeEditor = function () { self.closeEditor = function () {
self.CfgContent(editor.getValue()); self.CfgContent(editor.getValue());
@ -82,11 +82,11 @@ $(function () {
} else { } else {
editordialog.modal('hide'); editordialog.modal('hide');
} }
} };
self.addStyleAttribute = function ($element, styleAttribute) { self.addStyleAttribute = function ($element, styleAttribute) {
$element.attr('style', styleAttribute); $element.attr('style', styleAttribute);
} };
self.setEditorDivSize = function () { self.setEditorDivSize = function () {
var klipper_modal_body= $('#klipper_editor .modal-body'); var klipper_modal_body= $('#klipper_editor .modal-body');
@ -120,7 +120,7 @@ $(function () {
); );
} }
}); });
} };
self.onDataUpdaterPluginMessage = function (plugin, data) { self.onDataUpdaterPluginMessage = function (plugin, data) {
//receive from backend after a SAVE_CONFIG //receive from backend after a SAVE_CONFIG
@ -160,30 +160,55 @@ $(function () {
}); });
} }
} }
};
self.askSaveFaulty = function () {
return new Promise(function (resolve) {
var html = "<h5>" +
gettext("Your configuration seems to be faulty.") +
"</h5>";
showConfirmationDialog({
title: gettext("Save faulty Configuration?"),
html: html,
cancel: gettext("Do not save!"),
proceed: [gettext("Save anyway!"), gettext("Save anyway and don't show this again.")],
onproceed: function (idx) {
if (idx == 0) {
resolve(true);
} else {
self.klipperViewModel.saveOption("configuration", "parse_check", false);
resolve(true);
} }
},
oncancel: function () {
resolve(false);
}
});
});
};
self.checkSyntax = function () { self.checkSyntax = function () {
return new Promise((resolve, reject) => {
if (editor.session) { if (editor.session) {
self.klipperViewModel.consoleMessage("debug", "checkSyntax started"); self.klipperViewModel.consoleMessage("debug", "checkSyntax started");
OctoPrint.plugins.klipper.checkCfg(editor.session.getValue()) OctoPrint.plugins.klipper.checkCfg(editor.session.getValue())
.done(function (response) { .done(function (response) {
var msg = ""
if (response.is_syntax_ok == true) { if (response.is_syntax_ok == true) {
self.klipperViewModel.showPopUp("success", gettext("SyntaxCheck"), gettext("SyntaxCheck OK")); self.klipperViewModel.showPopUp("success", gettext("SyntaxCheck"), gettext("SyntaxCheck OK"));
self.editorFocusDelay(1000); self.editorFocusDelay(1000);
resolve(true);
} else { } else {
msg = gettext('Syntax NOK') self.editorFocusDelay(1000);
showMessageDialog( resolve(false);
msg,
{
title: gettext("SyntaxCheck"),
onclose: function () { self.editorFocusDelay(1000); }
}
);
} }
})
.fail(function () {
reject(false);
});
} else { reject(false); }
}); });
};
}; };
self.saveCfg = function (options) { self.saveCfg = function (options) {
@ -193,6 +218,7 @@ $(function () {
if (editor.session) { if (editor.session) {
self.klipperViewModel.consoleMessage("debug", "SaveCfg start"); self.klipperViewModel.consoleMessage("debug", "SaveCfg start");
var saveRequest = function () {
OctoPrint.plugins.klipper.saveCfg(editor.session.getValue(), self.CfgFilename()) OctoPrint.plugins.klipper.saveCfg(editor.session.getValue(), self.CfgFilename())
.done(function (response) { .done(function (response) {
@ -202,7 +228,7 @@ $(function () {
if (closing) { if (closing) {
editordialog.modal('hide'); editordialog.modal('hide');
} }
if (self.settings.settings.plugins.klipper.configuration.restart_onsave()==true) { if (self.settings.settings.plugins.klipper.configuration.restart_onsave() == true) {
self.klipperViewModel.requestRestart(); self.klipperViewModel.requestRestart();
} }
} else { } else {
@ -212,9 +238,34 @@ $(function () {
title: gettext("Save Config"), title: gettext("Save Config"),
onclose: function () { self.editorFocusDelay(1000); } onclose: function () { self.editorFocusDelay(1000); }
} }
) );
} }
}); });
};
if (self.settings.settings.plugins.klipper.configuration.parse_check() == true) {
self.checkSyntax().then((syntaxOK) => {
if (syntaxOK === false) {
self.askSaveFaulty().then((areWeSaving) => {
if (areWeSaving === false) {
showMessageDialog(
gettext('Faulty config not saved!'),
{
title: gettext("Save Config"),
onclose: function () { self.editorFocusDelay(1000); }
}
);
} else {
saveRequest();
}
});
} else {
saveRequest();
}
});
} else {
saveRequest();
}
} }
}; };
@ -227,11 +278,9 @@ $(function () {
self.settings.settings.plugins.klipper.configuration.fontsize(9); self.settings.settings.plugins.klipper.configuration.fontsize(9);
} }
var fontsize = self.settings.settings.plugins.klipper.configuration.fontsize() var fontsize = self.settings.settings.plugins.klipper.configuration.fontsize();
if (editor) { if (editor) {
editor.setFontSize( editor.setFontSize(fontsize);
fontsize
);
editor.resize(); editor.resize();
} }
@ -247,11 +296,9 @@ $(function () {
self.settings.settings.plugins.klipper.configuration.fontsize(20); self.settings.settings.plugins.klipper.configuration.fontsize(20);
} }
var fontsize = self.settings.settings.plugins.klipper.configuration.fontsize() var fontsize = self.settings.settings.plugins.klipper.configuration.fontsize();
if (editor) { if (editor) {
editor.setFontSize( editor.setFontSize(fontsize);
fontsize
);
editor.resize(); editor.resize();
} }
self.klipperViewModel.saveOption("configuration", "fontsize", fontsize); self.klipperViewModel.saveOption("configuration", "fontsize", fontsize);
@ -262,13 +309,12 @@ $(function () {
.done(function (response) { .done(function (response) {
self.klipperViewModel.consoleMessage("debug", "reloadFromFile done"); self.klipperViewModel.consoleMessage("debug", "reloadFromFile done");
if (response.response.text != "") { if (response.response.text != "") {
var msg = response.response.text
showMessageDialog( showMessageDialog(
msg, response.response.text,
{ {
title: gettext("Reload File") title: gettext("Reload File")
} }
) );
} else { } else {
self.klipperViewModel.showPopUp("success", gettext("Reload Config"), gettext("File reloaded.")); self.klipperViewModel.showPopUp("success", gettext("Reload Config"), gettext("File reloaded."));
self.CfgChangedExtern = false; self.CfgChangedExtern = false;
@ -281,13 +327,12 @@ $(function () {
} }
}) })
.fail(function (response) { .fail(function (response) {
var msg = response
showMessageDialog( showMessageDialog(
msg, response,
{ {
title: gettext("Reload File") title: gettext("Reload File")
} }
) );
}); });
}; };