From 939d9585b4355f897cfd4eb8dea6ff10bc9442f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 22 Feb 2022 18:08:41 +0100 Subject: [PATCH 01/11] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Get=20rid=20of=20som?= =?UTF-8?q?e=20data=20duplication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ...and a TODO --- src/octoprint/printer/standard.py | 72 +++++++++-------------------- src/octoprint/server/api/printer.py | 3 +- 2 files changed, 24 insertions(+), 51 deletions(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index be41a65f4..e011044ee 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -56,16 +56,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._fileManager = fileManager self._printerProfileManager = printerProfileManager - # state - # TODO do we really need to hold the temperature here? - self._temp = None - self._bedTemp = None - self._chamberTemp = None - self._targetTemp = None - self._targetBedTemp = None - self._targetChamberTemp = None - self._custom = None - self._temps = DataHistory( cutoff=settings().getInt(["temperature", "cutoff"]) * 60 ) @@ -843,43 +833,21 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): else: offsets = {} - result = {} - if self._temp is not None: - for tool in self._temp.keys(): - result["tool%d" % tool] = { - "actual": self._temp[tool][0], - "target": self._temp[tool][1], - "offset": offsets[tool] - if tool in offsets and offsets[tool] is not None - else 0, - } - if self._bedTemp is not None: - result["bed"] = { - "actual": self._bedTemp[0], - "target": self._bedTemp[1], - "offset": offsets["bed"] - if "bed" in offsets and offsets["bed"] is not None - else 0, - } - if self._chamberTemp is not None: - result["chamber"] = { - "actual": self._chamberTemp[0], - "target": self._chamberTemp[1], - "offset": offsets["chamber"] - if "chamber" in offsets and offsets["chamber"] is not None - else 0, - } - if self._custom is not None: - for custom_key in self._custom.keys(): - result[custom_key] = { - "actual": self._custom[custom_key][0], - "target": self._custom[custom_key][1], - } + last = self._temps.last + if last is None: + return {} - return result + return { + key: { + "actual": value["actual"], + "target": value["target"], + "offset": offsets[key] if offsets.get(key) is not None else 0, + } + for key, value in last.items() + } def get_temperature_history(self, *args, **kwargs): - return self._temps + return list(self._temps) def get_current_connection(self, *args, **kwargs): if self._comm is None: @@ -1229,11 +1197,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._temps.append(data) - self._temp = tools - self._bedTemp = bed - self._chamberTemp = chamber - self._custom = custom - self._stateMonitor.add_temperature(self._dict(**data)) def _validateJob(self, filename, sd): @@ -2097,3 +2060,14 @@ class DataHistory(InvariantContainer): return [item for item in data if item["time"] >= now - cutoff] InvariantContainer.__init__(self, guarantee_invariant=data_invariant) + self._last = None + + @property + def last(self): + return self._last + + def append(self, item): + try: + return super().append(item) + finally: + self._last = self._data[-1] if len(self._data) else None diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index b892df317..d92f7bb93 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -463,13 +463,12 @@ def _get_temperature_data(preprocessor): tempData = printer.get_current_temperatures() if "history" in request.values and request.values["history"] in valid_boolean_trues: - tempHistory = printer.get_temperature_history() + history = printer.get_temperature_history() limit = 300 if "limit" in request.values and str(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) - history = list(tempHistory) limit = min(limit, len(history)) tempData.update( From a02dc82fb583f2f59d27332506b8a139c97e7f4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 23 Feb 2022 16:41:17 +0100 Subject: [PATCH 02/11] =?UTF-8?q?=E2=9C=85=20Switch=20SettingsTest=20to=20?= =?UTF-8?q?use=20overlay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/settings/_files/defaults.yaml | 7 +- tests/settings/_files/overlay.yaml | 6 + tests/settings/test_settings.py | 191 +++++++++------------------- 3 files changed, 65 insertions(+), 139 deletions(-) create mode 100644 tests/settings/_files/overlay.yaml diff --git a/tests/settings/_files/defaults.yaml b/tests/settings/_files/defaults.yaml index 1c7eff302..2c79ede4a 100644 --- a/tests/settings/_files/defaults.yaml +++ b/tests/settings/_files/defaults.yaml @@ -13,9 +13,4 @@ serial: server: host: 0.0.0.0 port: 5000 -devel: - virtualPrinter: - enabled: false - sendWait: true - waitInterval: 1.0 - repetierStyleResends: false +devel: {} diff --git a/tests/settings/_files/overlay.yaml b/tests/settings/_files/overlay.yaml new file mode 100644 index 000000000..6c6f86b13 --- /dev/null +++ b/tests/settings/_files/overlay.yaml @@ -0,0 +1,6 @@ +devel: + virtualPrinter: + enabled: false + sendWait: true + waitInterval: 1.0 + repetierStyleResends: false diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index a9e45ec55..105810198 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -36,16 +36,21 @@ class SettingsTest(unittest.TestCase): def setUp(self): self.base_path = os.path.join(os.path.dirname(__file__), "_files") self.config_path = os.path.realpath(os.path.join(self.base_path, "config.yaml")) + self.overlay_path = os.path.realpath(os.path.join(self.base_path, "overlay.yaml")) self.defaults_path = os.path.realpath( os.path.join(self.base_path, "defaults.yaml") ) self.config = self._load_yaml(self.config_path) + self.overlay = self._load_yaml(self.overlay_path) self.defaults = self._load_yaml(self.defaults_path) from octoprint.util import dict_merge - self.expected_effective = dict_merge(self.defaults, self.config) + self.expected_effective = dict_merge( + dict_merge(self.defaults, self.overlay), self.config + ) + self.expected_effective[octoprint.settings.Settings.OVERLAY_KEY] = "overlay" def test_basedir_initialization(self): with self.mocked_basedir() as basedir: @@ -209,100 +214,71 @@ class SettingsTest(unittest.TestCase): ##~~ test getters def test_get(self): - with self.mocked_config(): + with self.settings() as settings: expected_api_key = "test" - settings = octoprint.settings.Settings() - api_key = settings.get(["api", "key"]) self.assertIsNotNone(api_key) self.assertEqual(api_key, expected_api_key) def test_get_int(self): - with self.mocked_config(): + with self.settings() as settings: expected_server_port = 8080 - settings = octoprint.settings.Settings() - server_port = settings.get(["server", "port"]) self.assertIsNotNone(server_port) self.assertEqual(server_port, expected_server_port) def test_get_int_converted(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.getInt(["serial", "timeout", "connection"]) - self.assertEqual(5, value) def test_get_int_invalid(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.getInt(["server", "host"]) - self.assertIsNone(value) def test_get_float(self): - with self.mocked_config(): + with self.settings() as settings: expected_serial_timeout = 1.0 - settings = octoprint.settings.Settings() - serial_timeout = settings.get(["serial", "timeout", "detection"]) self.assertIsNotNone(serial_timeout) self.assertEqual(serial_timeout, expected_serial_timeout) def test_get_float_converted(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.getFloat(["serial", "timeout", "connection"]) - self.assertEqual(5.0, value) def test_get_float_invalid(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.getFloat(["server", "host"]) - self.assertIsNone(value) def test_get_boolean(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.get(["devel", "virtualPrinter", "enabled"]) - self.assertTrue(value) def test_get_list(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: data = settings.get(["serial", "additionalPorts"]) - self.assertEqual(len(data), 2) self.assertListEqual(["/dev/portA", "/dev/portB"], data) def test_get_map(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: data = settings.get(["devel", "virtualPrinter"]) - self.assertDictEqual({"enabled": True}, data) self.assertEqual(len(data), 1) def test_get_map_merged(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: data = settings.get(["devel", "virtualPrinter"], merged=True) self.assertGreater(len(data), 1) @@ -311,9 +287,7 @@ class SettingsTest(unittest.TestCase): self.assertEqual(test_dict, test_data) def test_get_multiple(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: data = settings.get(["serial", ["timeout", "additionalPorts"]]) self.assertIsInstance(data, list) @@ -323,9 +297,7 @@ class SettingsTest(unittest.TestCase): self.assertIsInstance(data[1], list) def test_get_multiple_asdict(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: data = settings.get(["serial", ["timeout", "additionalPorts"]], asdict=True) self.assertIsInstance(data, dict) @@ -335,17 +307,13 @@ class SettingsTest(unittest.TestCase): self.assertTrue("additionalPorts" in data) def test_get_invalid(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: value = settings.get(["i", "do", "not", "exist"]) self.assertIsNone(value) def test_get_invalid_error(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: try: settings.get(["i", "do", "not", "exist"], error_on_path=True) self.fail("Expected NoSuchSettingsPath") @@ -353,9 +321,7 @@ class SettingsTest(unittest.TestCase): pass def test_get_custom_config(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: server_port = settings.getInt( ["server", "port"], config={"server": {"port": 9090}} ) @@ -363,9 +329,7 @@ class SettingsTest(unittest.TestCase): self.assertEqual(9090, server_port) def test_get_custom_defaults(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: api_enabled = settings.getBoolean( ["api", "enabled"], defaults={"api": {"enabled": False}} ) @@ -373,8 +337,7 @@ class SettingsTest(unittest.TestCase): self.assertFalse(api_enabled) def test_get_empty_path(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() + with self.settings() as settings: self.assertIsNone(settings.get([])) try: @@ -386,60 +349,40 @@ class SettingsTest(unittest.TestCase): ##~~ test setters def test_set(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.set(["server", "host"], "127.0.0.1") - self.assertEqual("127.0.0.1", settings._config["server"]["host"]) def test_set_int(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setInt(["server", "port"], 8181) - self.assertEqual(8181, settings._config["server"]["port"]) def test_set_int_convert(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setInt(["server", "port"], "8181") - self.assertEqual(8181, settings._config["server"]["port"]) def test_set_float(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setFloat(["serial", "timeout", "detection"], 1.2) - self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"]) def test_set_float_convert(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setFloat(["serial", "timeout", "detection"], "1.2") - self.assertEqual(1.2, settings._config["serial"]["timeout"]["detection"]) def test_set_boolean(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setBoolean(["devel", "virtualPrinter", "sendWait"], False) - self.assertEqual( False, settings._config["devel"]["virtualPrinter"]["sendWait"] ) @ddt.data("1", "yes", "true", "TrUe", "y", "Y", "YES") def test_set_boolean_convert_string_true(self, value): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setBoolean( ["devel", "virtualPrinter", "repetierStyleResends"], value ) @@ -450,17 +393,13 @@ class SettingsTest(unittest.TestCase): @ddt.data("0", "no", "false", ["some", "list"], {"a": "dictionary"}, lambda: None) def test_set_boolean_convert_any_false(self, value): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: settings.setBoolean(["api", "enabled"], value) self.assertEqual(False, settings._config["api"]["enabled"]) def test_set_default(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: self.assertEqual(8080, settings._config["server"]["port"]) settings.set(["server", "port"], 5000) @@ -469,9 +408,7 @@ class SettingsTest(unittest.TestCase): self.assertEqual(5000, settings.get(["server", "port"])) def test_set_none(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: self.assertTrue("port" in settings._config["server"]) settings.set(["server", "port"], None) @@ -482,9 +419,7 @@ class SettingsTest(unittest.TestCase): [], ["api", "lock"], ["api", "lock", "door"], ["serial", "additionalPorts", "key"] ) def test_set_invalid(self, path): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: try: settings.set(path, "value", error_on_path=True) self.fail("Expected NoSuchSettingsPath") @@ -494,9 +429,7 @@ class SettingsTest(unittest.TestCase): ##~~ test remove def test_remove(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: self.assertTrue("port" in settings._config["server"]) settings.remove(["server", "port"]) @@ -508,9 +441,7 @@ class SettingsTest(unittest.TestCase): @ddt.data([], ["server", "lock"], ["serial", "additionalPorts", "key"]) def test_remove_invalid(self, path): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: try: settings.remove(path, error_on_path=True) self.fail("Expected NoSuchSettingsPath") @@ -520,62 +451,53 @@ class SettingsTest(unittest.TestCase): ##~~ test has def test_has(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() - + with self.settings() as settings: self.assertTrue(settings.has(["api", "key"])) self.assertFalse(settings.has(["api", "lock"])) ##~~ test properties def test_effective(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() + with self.settings() as settings: effective = settings.effective - self.assertDictEqual(self.expected_effective, effective) def test_effective_hash(self): - with self.mocked_config(): + with self.settings() as settings: hash = hashlib.md5() hash.update(yaml.safe_dump(self.expected_effective).encode("utf-8")) expected_effective_hash = hash.hexdigest() print(yaml.safe_dump(self.expected_effective)) - settings = octoprint.settings.Settings() effective_hash = settings.effective_hash print(yaml.safe_dump(settings.effective)) self.assertEqual(expected_effective_hash, effective_hash) def test_config_hash(self): - with self.mocked_config(): + with self.settings() as settings: hash = hashlib.md5() hash.update(yaml.safe_dump(self.config).encode("utf-8")) expected_config_hash = hash.hexdigest() - settings = octoprint.settings.Settings() config_hash = settings.config_hash self.assertEqual(expected_config_hash, config_hash) def test_last_modified(self): - with self.mocked_config() as paths: - basedir, configfile = paths - settings = octoprint.settings.Settings() - + with self.settings() as settings: + configfile = settings._configfile last_modified = os.stat(configfile).st_mtime self.assertEqual(settings.last_modified, last_modified) ##~~ test preprocessors def test_get_preprocessor(self): - with self.mocked_config(): + with self.settings() as settings: config = {} defaults = {"test": "some string"} preprocessors = {"test": lambda x: x.upper()} - settings = octoprint.settings.Settings() value = settings.get( ["test"], config=config, defaults=defaults, preprocessors=preprocessors ) @@ -583,12 +505,11 @@ class SettingsTest(unittest.TestCase): self.assertEqual("SOME STRING", value) def test_set_preprocessor(self): - with self.mocked_config(): + with self.settings() as settings: config = {} defaults = {"foo": {"bar": "fnord"}} preprocessors = {"foo": {"bar": lambda x: x.upper()}} - settings = octoprint.settings.Settings() settings.set( ["foo", "bar"], "value", @@ -600,9 +521,8 @@ class SettingsTest(unittest.TestCase): self.assertEqual("VALUE", config["foo"]["bar"]) def test_set_external_modification(self): - with self.mocked_config() as paths: - basedir, configfile = paths - settings = octoprint.settings.Settings() + with self.settings() as settings: + configfile = settings._configfile # Make sure the config files last modified time changes time.sleep(1.0) @@ -624,9 +544,8 @@ class SettingsTest(unittest.TestCase): ##~~ test save def test_save(self): - with self.mocked_config() as paths: - basedir, config_path = paths - settings = octoprint.settings.Settings() + with self.settings() as settings: + config_path = settings._configfile # current modification date of config.yaml current_modified = os.stat(config_path).st_mtime @@ -645,8 +564,7 @@ class SettingsTest(unittest.TestCase): self.assertNotEqual(current_modified, os.stat(config_path).st_mtime) def test_save_unmodified(self): - with self.mocked_config(): - settings = octoprint.settings.Settings() + with self.settings() as settings: last_modified = settings.last_modified # sleep a bit to make sure we do have a change in the timestamp @@ -686,10 +604,17 @@ class SettingsTest(unittest.TestCase): shutil.copy(self.config_path, fresh_config_path) try: octoprint.settings.default_settings = self.defaults - yield basedir, fresh_config_path + yield finally: octoprint.settings.default_settings = orig_defaults + @contextlib.contextmanager + def settings(self): + with self.mocked_config(): + settings = octoprint.settings.Settings() + settings.add_overlay(self.overlay, key="overlay") + yield settings + @ddt.ddt class HelpersTest(unittest.TestCase): From 770131e1d88d573af12ad5419746e6f4dbdf8fe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 23 Feb 2022 17:10:00 +0100 Subject: [PATCH 03/11] =?UTF-8?q?=E2=9C=85=20Add=20more=20chainmap=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/settings.py | 3 +- tests/settings/_files/config.yaml | 2 + tests/settings/_files/defaults.yaml | 5 ++ tests/settings/_files/overlay.yaml | 4 ++ tests/settings/test_settings.py | 100 ++++++++++++++++++++++------ 5 files changed, 92 insertions(+), 22 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 3b6b26e61..f6098e5f6 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -707,7 +707,8 @@ class HierarchicalChainMap: # a/b = {} # a/b/c = "a" # deleted up_one_path = self._path_to_key(path[:-1]) - if sum(1 for k in current.keys() if k.startswith(up_one_path)) == 0: + up_one_path_prefix = up_one_path + _CHAINMAP_SEP + if not any(map(lambda k: k.startswith(up_one_path_prefix), current.keys())): current[up_one_path] = {} def with_config_defaults(self, config=None, defaults=None): diff --git a/tests/settings/_files/config.yaml b/tests/settings/_files/config.yaml index 117697c81..b2d3246dc 100644 --- a/tests/settings/_files/config.yaml +++ b/tests/settings/_files/config.yaml @@ -12,3 +12,5 @@ server: devel: virtualPrinter: enabled: true + capabilities: + autoreport_temp: false diff --git a/tests/settings/_files/defaults.yaml b/tests/settings/_files/defaults.yaml index 2c79ede4a..f3bef1bb3 100644 --- a/tests/settings/_files/defaults.yaml +++ b/tests/settings/_files/defaults.yaml @@ -14,3 +14,8 @@ server: host: 0.0.0.0 port: 5000 devel: {} +test: + a: + a1: 1 + a2: 2 + a3: 3 diff --git a/tests/settings/_files/overlay.yaml b/tests/settings/_files/overlay.yaml index 6c6f86b13..3674054c0 100644 --- a/tests/settings/_files/overlay.yaml +++ b/tests/settings/_files/overlay.yaml @@ -4,3 +4,7 @@ devel: sendWait: true waitInterval: 1.0 repetierStyleResends: false +test: + b: + b1: 1 + b2: 2 diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 105810198..cfebdcb80 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -18,34 +18,35 @@ import time import unittest import ddt +import pytest import yaml import octoprint.settings +from octoprint.util import dict_merge + +base_path = os.path.join(os.path.dirname(__file__), "_files") + + +def _load_yaml(fname): + with open(fname, encoding="utf-8") as f: + return yaml.safe_load(f) + + +def _dump_yaml(fname, config): + with open(fname, "wt", encoding="utf-8") as f: + yaml.safe_dump(config, f) @ddt.ddt class SettingsTest(unittest.TestCase): - def _load_yaml(self, fname): - with open(fname, encoding="utf-8") as f: - return yaml.safe_load(f) - - def _dump_yaml(self, fname, config): - with open(fname, "wt", encoding="utf-8") as f: - yaml.safe_dump(config, f) - def setUp(self): - self.base_path = os.path.join(os.path.dirname(__file__), "_files") - self.config_path = os.path.realpath(os.path.join(self.base_path, "config.yaml")) - self.overlay_path = os.path.realpath(os.path.join(self.base_path, "overlay.yaml")) - self.defaults_path = os.path.realpath( - os.path.join(self.base_path, "defaults.yaml") - ) + self.config_path = os.path.realpath(os.path.join(base_path, "config.yaml")) + self.overlay_path = os.path.realpath(os.path.join(base_path, "overlay.yaml")) + self.defaults_path = os.path.realpath(os.path.join(base_path, "defaults.yaml")) - self.config = self._load_yaml(self.config_path) - self.overlay = self._load_yaml(self.overlay_path) - self.defaults = self._load_yaml(self.defaults_path) - - from octoprint.util import dict_merge + self.config = _load_yaml(self.config_path) + self.overlay = _load_yaml(self.overlay_path) + self.defaults = _load_yaml(self.defaults_path) self.expected_effective = dict_merge( dict_merge(self.defaults, self.overlay), self.config @@ -530,9 +531,9 @@ class SettingsTest(unittest.TestCase): self.assertEqual("0.0.0.0", settings.get(["server", "host"])) # modify yaml file externally - config = self._load_yaml(configfile) + config = _load_yaml(configfile) config["server"]["host"] = "127.0.0.1" - self._dump_yaml(configfile, config) + _dump_yaml(configfile, config) # set some value, should also reload file before setting new api key settings.set(["api", "key"], "key") @@ -645,6 +646,63 @@ def _key(*path): @ddt.ddt class ChainmapTest(unittest.TestCase): + def setUp(self): + self.config_path = os.path.realpath(os.path.join(base_path, "config.yaml")) + self.overlay_path = os.path.realpath(os.path.join(base_path, "overlay.yaml")) + self.defaults_path = os.path.realpath(os.path.join(base_path, "defaults.yaml")) + + self.config = _load_yaml(self.config_path) + self.overlay = _load_yaml(self.overlay_path) + self.defaults = _load_yaml(self.defaults_path) + + self.chainmap = octoprint.settings.HierarchicalChainMap( + self.config, self.overlay, self.defaults + ) + + def test_has_path(self): + self.assertTrue(self.chainmap.has_path(["api", "key"])) + self.assertTrue(self.chainmap.has_path(["devel"])) + self.assertTrue(self.chainmap.has_path(["devel", "virtualPrinter"])) + self.assertTrue(self.chainmap.has_path(["devel", "virtualPrinter", "enabled"])) + + self.assertFalse(self.chainmap.has_path(["api", "lock"])) + + def test_get_by_path(self): + self.assertEqual( + True, self.chainmap.get_by_path(["devel", "virtualPrinter", "enabled"]) + ) + self.assertEqual( + False, + self.chainmap.get_by_path( + ["devel", "virtualPrinter", "enabled"], only_defaults=True + ), + ) + + with pytest.raises(KeyError): + self.assertEqual(None, self.chainmap.get_by_path(["test"], only_local=True)) + self.assertEqual(self.overlay["test"], self.chainmap.get_by_path(["test"])) + self.assertEqual( + dict_merge(self.defaults["test"], self.overlay["test"]), + self.chainmap.get_by_path(["test"], merged=True), + ) + + def test_set_by_path(self): + self.chainmap.set_by_path(["devel", "virtualPrinter", "sendWait"], False) + + updated = dict(self.config) + updated["devel"]["virtualPrinter"]["sendWait"] = False + flattened = octoprint.settings.HierarchicalChainMap._flatten(updated) + + self.assertEqual(flattened, self.chainmap._chainmap.maps[0]) + + def test_del_by_path(self): + self.chainmap.del_by_path( + ["devel", "virtualPrinter", "capabilities", "autoreport_temp"] + ) + self.assertEqual( + {}, self.chainmap.get_by_path(["devel", "virtualPrinter", "capabilities"]) + ) + @ddt.data( ( {"a": 1}, From dc085583bca7e258e33998953bf5bce0dd1a65fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 23 Feb 2022 17:20:35 +0100 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=92=9A=20Fix=20a=20test=20after=20c?= =?UTF-8?q?hanging=20test=20data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/settings/test_settings.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index cfebdcb80..3d233f08b 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -275,17 +275,16 @@ class SettingsTest(unittest.TestCase): def test_get_map(self): with self.settings() as settings: data = settings.get(["devel", "virtualPrinter"]) - self.assertDictEqual({"enabled": True}, data) - self.assertEqual(len(data), 1) + self.assertDictEqual(self.config["devel"]["virtualPrinter"], data) def test_get_map_merged(self): with self.settings() as settings: data = settings.get(["devel", "virtualPrinter"], merged=True) - - self.assertGreater(len(data), 1) - test_dict = {"enabled": True, "sendWait": True, "waitInterval": 1.0} - test_data = {k: v for k, v in data.items() if k in test_dict} - self.assertEqual(test_dict, test_data) + expected = dict_merge( + self.overlay["devel"]["virtualPrinter"], + self.config["devel"]["virtualPrinter"], + ) + self.assertEqual(expected, data) def test_get_multiple(self): with self.settings() as settings: From 1e3ec258b1c3fe57bbd9275768209d27c1765db8 Mon Sep 17 00:00:00 2001 From: jneilliii Date: Thu, 24 Feb 2022 05:02:00 -0500 Subject: [PATCH 05/11] =?UTF-8?q?=E2=9C=A8=20SWU:=20Allow=20enqueuing=20up?= =?UTF-8?q?dates=20while=20printing=20(#4364)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * adds an update queue to allow starting updates while printing, #3320, #3589, #3585 * change to 202 status code instead of abort for queued installs * remove commented code * fix formatting * UI improvements proper list merging, without duplicates * add countdown timer on print completion prior to update don't automatically update on print fail add ability to cancel queued updates * UI tweaks and fixes * minor bugfix * if logic adjustment to prevent sending messages to front end when no updates queued * add timer abort on print start in case he update is in process * added wait for timelapse completion to avoid interrupting that process due to resstart at the end of updates. * ♻️ Get rid of some data duplication ...and a TODO * API adjustments as requested, removed PNotify hack for singleButtonNotify change (broken) * added print_cancelled flag to deal with changes related to waiting for timelapse switched PNotify back from singleButtonNotify and added class hidden to button instead to avoid Pnotify.update issue * 💄 minify CSS Implements #3320 Implements #3585 Implements #3589 Implements #4431 Co-authored-by: Gina Häußge --- .../plugins/softwareupdate/__init__.py | 142 ++++++++- .../static/clientjs/softwareupdate.js | 32 ++ .../static/css/softwareupdate.css | 2 +- .../static/js/softwareupdate.js | 285 ++++++++++++++++-- .../static/less/softwareupdate.less | 33 ++ .../templates/softwareupdate_settings.jinja2 | 15 +- src/octoprint/printer/standard.py | 72 ++--- src/octoprint/server/api/printer.py | 3 +- 8 files changed, 481 insertions(+), 103 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 12abe7606..890f862a2 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -4,7 +4,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - import copy import hashlib import logging @@ -28,7 +27,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml +from octoprint.util import RepeatedTimer, dict_merge, get_formatted_size, to_unicode, yaml from octoprint.util.commandline import CommandlineError from octoprint.util.pip import create_pip_caller from octoprint.util.version import ( @@ -61,7 +60,6 @@ class SoftwareUpdatePlugin( octoprint.plugin.WizardPlugin, octoprint.plugin.EventHandlerPlugin, ): - COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") CURRENT_TRACKING_TYPES = COMMIT_TRACKING_TYPES + ("etag", "lastmodified", "jsondata") RELEASE_TRACKING_TYPES = ("github_release",) @@ -99,6 +97,9 @@ class SoftwareUpdatePlugin( self._update_log_path = None self._update_log_dirty = False self._update_log_mutex = threading.RLock() + self._queued_updates = {"targets": [], "force": True} + self._queued_updates_abort_timer = None + self._print_cancelled = False self._environment_supported = True self._environment_versions = {} @@ -762,6 +763,8 @@ class SoftwareUpdatePlugin( data["pip_enable_check"] = "pip" in checks + data["queued_updates"] = self._queued_updates.get("targets", []) + return data def get_settings_restricted_paths(self): @@ -1284,10 +1287,6 @@ class SoftwareUpdatePlugin( description=message, ) - if self._printer.is_printing() or self._printer.is_paused(): - # do not update while a print job is running - flask.abort(409, description="Printer is currently printing or paused") - if not self._environment_supported: flask.abort( 409, @@ -1316,9 +1315,64 @@ class SoftwareUpdatePlugin( force = json_data.get("force", "false") in octoprint.settings.valid_boolean_trues + if self._printer.is_printing() or self._printer.is_paused(): + # do not update while a print job is running + # store targets to be run later on print done event + self._queued_updates["targets"] = list( + set(self._queued_updates["targets"] + targets) + ) + self._send_client_message( + "queued_updates", + {"targets": self._queued_updates["targets"]}, + ) + + return ( + flask.jsonify({"queued": self._queued_updates.get("targets", False)}), + 202, + ) + to_be_checked, checks = self.perform_updates(targets=targets, force=force) return flask.jsonify({"order": to_be_checked, "checks": checks}) + @octoprint.plugin.BlueprintPlugin.route("/update/queued", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403) + def cancel_queued(self): + if "application/json" not in flask.request.headers["Content-Type"]: + flask.abort(400, description="Expected content-type JSON") + + json_data = flask.request.get_json(silent=True) + if json_data is None: + flask.abort(400, description="Invalid JSON") + + command = json_data.get("command") + if command == "cancel": + targets = [x.strip() for x in json_data.get("targets", [])] + + if targets: + self._queued_updates["targets"] = [ + x for x in self._queued_updates["targets"] if x not in targets + ] + else: + self._queued_updates["targets"] = [] + + if not self._queued_updates["targets"] and self._queued_updates_abort_timer: + self._queued_updates_abort_timer.cancel() + self._queued_updates_abort_timer = None + + self._send_client_message( + "queued_updates", + {"targets": self._queued_updates["targets"]}, + ) + + return ( + flask.jsonify({"queued": self._queued_updates["targets"]}), + 202, + ) + + else: + flask.abort(400, description="Expected a valid command") + @octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"]) @no_firstrun_access @Permissions.PLUGIN_SOFTWAREUPDATE_CONFIGURE.require(403) @@ -1475,7 +1529,33 @@ class SoftwareUpdatePlugin( def on_event(self, event, payload): from octoprint.events import Events - if ( + if event == Events.PRINT_STARTED: + self._queued_updates_timer_stop() + self._print_cancelled = False + elif ( + event == Events.PRINT_DONE + and self._settings.global_get(["webcam", "timelapse", "type"]) == "off" + and len(self._queued_updates.get("targets", [])) > 0 + ): + self._queued_updates_timer_start() + elif ( + event == Events.PRINT_FAILED + and len(self._queued_updates.get("targets", [])) > 0 + ): + self._send_client_message( + "queued_updates", + {"print_failed": True, "targets": self._queued_updates["targets"]}, + ) + self._print_cancelled = True + elif ( + event == Events.MOVIE_DONE + and self._settings.global_get(["webcam", "timelapse", "type"]) != "off" + and len(self._queued_updates.get("targets", [])) > 0 + and not (self._printer.is_printing() or self._printer.is_paused()) + and not self._print_cancelled + ): + self._queued_updates_timer_start() + elif ( event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False) @@ -1824,6 +1904,52 @@ class SoftwareUpdatePlugin( self._version_cache_dirty = True return information, update_available, update_possible, online, error + def _queued_updates_timer_start(self): + if self._queued_updates_abort_timer is not None: + return + + self._logger.debug("Starting queued updates timer.") + + self._timeout_value = 60 + self._queued_updates_abort_timer = RepeatedTimer( + 1, self._queued_updates_timer_task + ) + self._queued_updates_abort_timer.start() + + def _queued_updates_timer_stop(self): + if self._queued_updates_abort_timer is not None: + self._queued_updates_abort_timer.cancel() + self._queued_updates_abort_timer = None + self._send_client_message( + "queued_updates", + { + "targets": self._queued_updates["targets"], + "timeout_value": -1, + }, + ) + + def _queued_updates_timer_task(self): + if self._timeout_value is None: + return + + self._timeout_value -= 1 + if self._timeout_value <= 0: + if self._queued_updates_abort_timer is not None: + self._queued_updates_abort_timer.cancel() + self._queued_updates_abort_timer = None + self.perform_updates( + targets=self._queued_updates["targets"], + force=self._queued_updates["force"], + ) + self._queued_updates = {"targets": [], "force": True} + self._send_client_message( + "queued_updates", + { + "targets": self._queued_updates["targets"], + "timeout_value": self._timeout_value, + }, + ) + def perform_updates(self, force=False, **kwargs): """ Performs the updates for the given check_targets. Will update all possible targets by default. diff --git a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js index e4bf77a80..9b782c5c4 100644 --- a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js @@ -13,6 +13,7 @@ this.updateUrl = url + "update"; this.configureUrl = url + "configure"; this.updatelogUrl = url + "updatelog"; + this.queuedURL = this.updateUrl + "/queued"; }; OctoPrintSoftwareUpdateClient.prototype.checkEntries = function ( @@ -72,6 +73,37 @@ return this.base.postJson(this.updateUrl, data, opts); }; + OctoPrintSoftwareUpdateClient.prototype.cancelQueued = function (targets, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + targets = params.targets; + } + + targets = targets || []; + if (typeof targets === "string") { + targets = [targets]; + } + + var data = { + command: "cancel", + targets: targets + }; + return this.base.postJson(this.queuedURL, data, opts); + }; + + OctoPrintSoftwareUpdateClient.prototype.cancelAllQueued = function (opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + opts = params.opts; + } + + var data = { + command: "cancel" + }; + + return this.base.postJson(this.queuedURL, data, opts); + }; + OctoPrintSoftwareUpdateClient.prototype.updateAll = function (force, opts) { if (arguments.length === 1 && _.isObject(arguments[0])) { var params = arguments[0]; diff --git a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css index 36015f226..01bfc4500 100644 --- a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css +++ b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css @@ -1 +1 @@ -#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#990000}#settings_plugin_softwareupdate_workingdialog_output .call{color:#000099}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#990000}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} \ No newline at end of file +#settings_plugin_softwareupdate_updatelist{display:block;width:auto;overflow-x:hidden;padding-right:2px;margin-bottom:1em}div.swupdate-advanced{margin-bottom:5px}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_update a{text-decoration:none;color:#000}td.settings_plugin_softwareupdate_column_information .line{display:block}td.settings_plugin_softwareupdate_column_information .settings_plugin_softwareupdate_release_channel{line-height:20px;height:20px;font-size:9px;margin-bottom:0;vertical-align:baseline}#settings_plugin_softwareupdate_updatelog_list .line{display:block}#settings_plugin_softwareupdate_updatelog_list td.settings_plugin_softwareupdate_column_datetime{width:150px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#990000}#settings_plugin_softwareupdate_workingdialog_output .call{color:#000099}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#990000}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}.progress-softwareupdate.progress{position:relative;display:flex;overflow:hidden;height:25px;font-size:12px}.progress-softwareupdate.progress .bar{display:flex;justify-content:center;align-items:center;width:100%;color:white;height:25px;font-size:12px}.progress-softwareupdate.progress .progress-text{position:absolute;display:flex;justify-content:center;align-items:center;left:0;right:0;top:0;bottom:0;background:white;transition:clip-path 1s linear;height:25px;font-size:12px} \ No newline at end of file diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index f9a162547..3505bc5a6 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -14,10 +14,12 @@ $(function () { self.popup = undefined; self.updateInProgress = false; + self.cancelInProgress = false; self.waitingForRestart = false; self.restartTimeout = undefined; self.currentlyBeingUpdated = []; + self.queuedUpdates = ko.observableArray([]); self.working = ko.observable(false); self.workingTitle = ko.observable(); @@ -76,7 +78,6 @@ $(function () { !self.updateInProgress && self.environmentSupported() && self.storageSufficient() && - !self.printerState.isPrinting() && !self.throttled() ); }); @@ -91,6 +92,14 @@ $(function () { ); }); + self.enableCancelQueued = ko.pureComputed(function () { + return self.queuedUpdates().length > 0; + }); + + self.updateQueued = function (item) { + return self.queuedUpdates().indexOf(item.key) > -1; + }; + self.enable_configSave = ko.pureComputed(function () { return ( self.config_checkType() === "github_release" || @@ -155,6 +164,16 @@ $(function () { }); }); + self.availableAndQueued = ko.pureComputed(function () { + return _.filter(self.versions.items(), function (info) { + return ( + info.updateAvailable && + info.updatePossible && + self.queuedUpdates.indexOf(info.key) > -1 + ); + }); + }); + self.throttled = ko.pureComputed(function () { return ( self.piSupport && @@ -252,6 +271,12 @@ $(function () { }); }; + self.onBeforeBinding = function () { + self.queuedUpdates( + self.settings.settings.plugins.softwareupdate.queued_updates() + ); + }; + self._copyConfig = function () { var availableCheckTypes = [ {key: "github_release", name: gettext("Release")}, @@ -706,7 +731,6 @@ $(function () { self.performUpdate = function (force, items) { if (!self.updateAccess()) return; - if (self.printerState.isPrinting()) return; self.updateInProgress = true; @@ -725,6 +749,29 @@ $(function () { OctoPrint.plugins.softwareupdate .update(items, force) .done(function (data) { + if (data.hasOwnProperty("queued")) { + self.queuedUpdates(data.queued); + var message = + "

" + + gettext( + "The install of the following plugin update(s) has been queued for after current print is finished or cancelled." + ) + + '

  • ' + + _.map(self.availableAndQueued(), function (info) { + return info.displayName; + }).join("
  • ") + + "

"; + self._showPopup({ + title: gettext("Updates Queued"), + text: message, + type: "info", + buttons: { + sticker: false + } + }); + self.updateInProgress = false; + return; + } self.currentlyBeingUpdated = data.checks; self._markWorking( gettext("Updating..."), @@ -780,18 +827,6 @@ $(function () { items = self.availableAndPossibleAndEnabled(); } - if (self.printerState.isPrinting()) { - self._showPopup({ - title: gettext("Can't update while printing"), - text: gettext( - "A print job is currently in progress. Updating will be prevented until it is done." - ), - type: "error" - }); - self._updateClicked = false; - return; - } - if (self.throttled()) { self._showPopup({ title: gettext("Can't update while throttled"), @@ -836,13 +871,13 @@ $(function () { "Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know before upgrading." ) + "

" + - "

" + - gettext("This action may disrupt any ongoing print jobs.") + - "

" + "

" + + gettext("Updates will be queued if currently printing,") + + " " + gettext( - "Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset." + "however this action may disrupt any ongoing print if OctoPrint is not currently controlling it." ) + + "" + "

" + "

" + gettext("Are you sure you want to proceed?") + @@ -972,6 +1007,24 @@ $(function () { } }; + self.cancelQueued = function (items) { + self.cancelInProgress = true; + OctoPrint.plugins.softwareupdate + .cancelQueued({ + targets: _.map(items, function (info) { + return info.key; + }) + }) + .done(function (data) { + self.queuedUpdates(data.queued); + self.cancelInProgress = false; + }) + .fail(function (response) { + console.log(response); + self.cancelInProgress = false; + }); + }; + self.onDataUpdaterPluginMessage = function (plugin, data) { if (plugin !== "softwareupdate") { return; @@ -1170,24 +1223,190 @@ $(function () { self.performCheck(); break; } - } + case "queued_updates": + { + if (!self.updateAccess()) { + return; + } + if (messageData.hasOwnProperty("targets")) { + self.queuedUpdates(messageData.targets); + var queuedUpdatesPopupOptions = { + title: title, + text: text, + type: "notice", + icon: false, + hide: false, + buttons: { + closer: false, + sticker: false + }, + history: { + history: false + } + }; - if (options !== undefined) { - self._showPopup(options); - } - }; + if ( + messageData.print_failed && + messageData.targets.length > 0 + ) { + queuedUpdatesPopupOptions.title = gettext( + "Queued Updates Paused" + ); + queuedUpdatesPopupOptions.text = + '

  • ' + + _.map(self.availableAndQueued(), function (info) { + return info.displayName; + }).join("
  • ") + + "
"; + queuedUpdatesPopupOptions.confirm = { + confirm: true, + buttons: [ + { + text: gettext("Continue Updates"), + addClass: "btn-block btn-primary", + promptTrigger: true, + click: function (notice, value) { + notice.remove(); + notice + .get() + .trigger("pnotify.continue", [ + notice, + value + ]); + } + }, + { + text: gettext("Cancel Updates"), + addClass: "btn-block btn-danger", + promptTrigger: true, + click: function (notice, value) { + notice.remove(); + notice + .get() + .trigger("pnotify.cancel", [ + notice, + value + ]); + } + } + ] + }; + } else if ( + messageData.hasOwnProperty("timeout_value") && + messageData.timeout_value > 0 && + messageData.targets.length > 0 + ) { + var progress_percent = Math.floor( + (messageData.timeout_value / 60) * 100 + ); + var progress_class = + progress_percent < 25 + ? "progress-danger" + : progress_percent > 75 + ? "progress-success" + : "progress-warning"; + queuedUpdatesPopupOptions.title = gettext( + "Starting Queued Updates" + ); + queuedUpdatesPopupOptions.text = + '
  • ' + + _.map(self.availableAndQueued(), function (info) { + return info.displayName; + }).join("
  • ") + + '
' + + gettext("Updating in ") + + " " + + messageData.timeout_value + + " " + + gettext("secs") + + '
' + + gettext("Updating in ") + + " " + + messageData.timeout_value + + " " + + gettext("secs") + + "
"; + queuedUpdatesPopupOptions.confirm = { + confirm: true, + buttons: [ + { + text: gettext("Cancel Updates"), + addClass: "btn-block btn-danger", + promptTrigger: true, + click: function (notice, value) { + notice.remove(); + notice + .get() + .trigger("pnotify.cancel", [ + notice, + value + ]); + } + }, + { + text: "", + addClass: "hidden" + } + ] + }; + } else { + if (typeof self.queuedUpdatesPopup !== "undefined") { + self.queuedUpdatesPopup.remove(); + self.queuedUpdatesPopup = undefined; + } + return; + } - self._forcedStdoutPatterns = [ - "You are using pip version .*?, however version .*? is available.", - "You should consider upgrading via the '.*?' command.", - "'.*?' does not exist -- can't clean it" - ]; - self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|")); - self._preprocessLine = function (line) { - if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) { - line.stream = "stdout"; + if (typeof self.queuedUpdatesPopup !== "undefined") { + self.queuedUpdatesPopup.update(queuedUpdatesPopupOptions); + } else { + self.queuedUpdatesPopup = new PNotify( + queuedUpdatesPopupOptions + ); + self.queuedUpdatesPopup + .get() + .on("pnotify.cancel", function () { + self.queuedUpdatesPopup = undefined; + self.cancelQueued(); + }); + self.queuedUpdatesPopup + .get() + .on("pnotify.continue", function () { + self.queuedUpdatesPopup = undefined; + self.performUpdate(true, self.queuedUpdates()); + self._updateClicked = false; + }); + } + } else { + if (typeof self.queuedUpdatesPopup !== "undefined") { + self.queuedUpdatesPopup.remove(); + self.queuedUpdatesPopup = undefined; + } + } + } + + if (options !== undefined) { + self._showPopup(options); + } } - return line; + self._forcedStdoutPatterns = [ + "You are using pip version .*?, however version .*? is available.", + "You should consider upgrading via the '.*?' command.", + "'.*?' does not exist -- can't clean it" + ]; + self._forcedStdoutLine = new RegExp(self._forcedStdoutPatterns.join("|")); + self._preprocessLine = function (line) { + if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) { + line.stream = "stdout"; + } + return line; + }; }; } diff --git a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less index 28a6d98bf..2782d15bd 100644 --- a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less +++ b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less @@ -85,3 +85,36 @@ td.settings_plugin_softwareupdate_column_information { } } } + +.progress-softwareupdate.progress { + position: relative; + display: flex; + overflow: hidden; + height: 25px; + font-size: 12px; + + .bar { + display: flex; + justify-content: center; + align-items: center; + width: 100%; + color: white; + height: 25px; + font-size: 12px; + } + + .progress-text { + position: absolute; + display: flex; + justify-content: center; + align-items: center; + left: 0; + right: 0; + top: 0; + bottom: 0; + background: white; + transition: clip-path 1s linear; + height: 25px; + font-size: 12px; + } +} diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 4427d44aa..2ac61e04b 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -63,15 +63,6 @@ Read more on this in the FAQ.

{% endtrans %} -
{% trans %} -

- OctoPrint is currently printing, updates are disabled. -

-

- Running updates is not supported while printing in order to not risk any kind of disruption to the print job. - Please let the print finish before trying to update. -

-{% endtrans %}