From 0489dfeaeefb42307e5daf447214423c0966059e Mon Sep 17 00:00:00 2001 From: Kevin McCormack Date: Sat, 12 Jan 2019 15:24:02 -0500 Subject: [PATCH 01/24] [WIP] Add disk usage API endpoint --- src/octoprint/server/api/system.py | 17 +++++- tests/server/api/__init__.py | 10 ++++ tests/server/api/test_system.py | 93 ++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 tests/server/api/__init__.py create mode 100644 tests/server/api/test_system.py diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index a1b3836b4..a7838304b 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -12,6 +12,8 @@ import threading from flask import request, make_response, jsonify, url_for from flask_babel import gettext +import psutil + from octoprint.settings import settings as s from octoprint.server import admin_permission, NO_CONTENT @@ -20,6 +22,20 @@ from octoprint.server.util.flask import restricted_access, get_remote_address from octoprint.logging import prefix_multilines +@api.route("/system/usage", methods=["GET"]) +@restricted_access +@admin_permission.require(403) +def readUsageForFolder(): + data = {} + for folder_name in s().get(['folder']).keys(): + path = s().getBaseFolder(folder_name, check_writable=False) + if path is not None: + usage = psutil.disk_usage(path) + data[folder_name] = { 'free': usage.free, 'total': usage.total } + + return jsonify(usage=data) + + @api.route("/system", methods=["POST"]) @restricted_access @admin_permission.require(403) @@ -134,7 +150,6 @@ def executeSystemCommand(source, command): return NO_CONTENT - def _to_client_specs(specs): result = list() for spec in specs.values(): diff --git a/tests/server/api/__init__.py b/tests/server/api/__init__.py new file mode 100644 index 000000000..f4be80c7d --- /dev/null +++ b/tests/server/api/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +""" +Unit tests for ``octoprint.server.api``. +""" + +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/server/api/test_system.py b/tests/server/api/test_system.py new file mode 100644 index 000000000..8800d93db --- /dev/null +++ b/tests/server/api/test_system.py @@ -0,0 +1,93 @@ +# coding=utf-8 +""" +Unit tests for ``octoprint.server.api`` system. +""" + +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import json +# from mock import MagicMock +import mock +import psutil +import unittest + +import octoprint.users +from octoprint.settings import settings +from octoprint.server import app +from octoprint.server.api import api +import octoprint.server.util + +# import flask +from flask import session + +# Set up app for testing and register api +app.testing = True +app.register_blueprint(api, url_prefix="/api") + + +from contextlib import contextmanager +from flask import appcontext_pushed, g + +@contextmanager +def user_set(app, user): + def handler(sender, **kwargs): + g.user = user + with appcontext_pushed.connected_to(handler, app): + yield + +def login(client, username, password): + return client.post('/login', data=dict( + username=username, + password=password + ), follow_redirects=True) + + +def logout(client): + return client.get('/logout', follow_redirects=True) + +class GetFolderUsageTest(unittest.TestCase): + + def setUp(self): + self.settings_patcher = mock.patch("octoprint.server.api.system.s") # needs to be adjusted to import + self.settings_getter = self.settings_patcher.start() + self.settings = mock.create_autospec(octoprint.settings.Settings) + self.settings_getter.return_value = self.settings + settings(self.settings) + + # Add an app secret for sessions + app.config['SECRET_KEY'] = 'sekrit!' + # Use Flask's test client for our test. + self.test_app = app.test_client() + + def cleanUp(self): + self.settings_patcher.stop() + + def test_readUsageForFolder(self): + apikey = settings().get(["api", "key"]) + print("apikey: %s" % apikey) + with mock.patch("psutil.disk_usage") as disk_usage_mock: + disk_usage_mock.free = 50 + disk_usage_mock.total = 512 + + # with user_set(app, self.user): + # with app.test_client() as c: + with self.test_app as client: + with client.session_transaction() as sess: + sess['user_id'] = 'admin' + sess['apikey'] = apikey + print('Session:') + print(sess) + + response = client.get('/api/system/usage', headers={ 'X-Api-Key': apikey }) + print("Response: ") + print(response) + self.assertEquals(response.status, '200 OK') + + data = json.loads(response.data) + self.assertEquals(data['usage']['uploads']['free'], 50) + self.assertEquals(data['usage']['uploads']['total'], 512) From 449fa0c7ecdca868ea2b33feec3891ca517a5086 Mon Sep 17 00:00:00 2001 From: Kevin McCormack Date: Mon, 21 Jan 2019 12:49:57 -0500 Subject: [PATCH 02/24] WIP Update test_system --- tests/server/api/test_system.py | 59 +++------------------------------ 1 file changed, 5 insertions(+), 54 deletions(-) diff --git a/tests/server/api/test_system.py b/tests/server/api/test_system.py index 8800d93db..841902a9c 100644 --- a/tests/server/api/test_system.py +++ b/tests/server/api/test_system.py @@ -11,83 +11,34 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import json -# from mock import MagicMock import mock import psutil import unittest -import octoprint.users +import octoprint from octoprint.settings import settings from octoprint.server import app -from octoprint.server.api import api -import octoprint.server.util -# import flask -from flask import session - -# Set up app for testing and register api -app.testing = True -app.register_blueprint(api, url_prefix="/api") - - -from contextlib import contextmanager -from flask import appcontext_pushed, g - -@contextmanager -def user_set(app, user): - def handler(sender, **kwargs): - g.user = user - with appcontext_pushed.connected_to(handler, app): - yield - -def login(client, username, password): - return client.post('/login', data=dict( - username=username, - password=password - ), follow_redirects=True) - - -def logout(client): - return client.get('/logout', follow_redirects=True) +from octoprint.server.api.system import readUsageForFolder class GetFolderUsageTest(unittest.TestCase): def setUp(self): - self.settings_patcher = mock.patch("octoprint.server.api.system.s") # needs to be adjusted to import + self.settings_patcher = mock.patch("octoprint.server.api.system.s") self.settings_getter = self.settings_patcher.start() self.settings = mock.create_autospec(octoprint.settings.Settings) self.settings_getter.return_value = self.settings settings(self.settings) - # Add an app secret for sessions - app.config['SECRET_KEY'] = 'sekrit!' - # Use Flask's test client for our test. - self.test_app = app.test_client() - def cleanUp(self): self.settings_patcher.stop() def test_readUsageForFolder(self): - apikey = settings().get(["api", "key"]) - print("apikey: %s" % apikey) with mock.patch("psutil.disk_usage") as disk_usage_mock: disk_usage_mock.free = 50 disk_usage_mock.total = 512 - # with user_set(app, self.user): - # with app.test_client() as c: - with self.test_app as client: - with client.session_transaction() as sess: - sess['user_id'] = 'admin' - sess['apikey'] = apikey - print('Session:') - print(sess) - - response = client.get('/api/system/usage', headers={ 'X-Api-Key': apikey }) - print("Response: ") - print(response) - self.assertEquals(response.status, '200 OK') - - data = json.loads(response.data) + with app.app_context(): + data = json.loads(readUsageForFolder()) self.assertEquals(data['usage']['uploads']['free'], 50) self.assertEquals(data['usage']['uploads']['total'], 512) From eb46815789d4c02979f75b4004c894ba597ef5f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 22 Jan 2019 15:40:08 +0100 Subject: [PATCH 03/24] Slight refactoring for improved testability & fix tests --- src/octoprint/server/api/system.py | 9 ++++--- tests/server/api/test_system.py | 41 ++++++++++++------------------ 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index a7838304b..f63c9856e 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -25,16 +25,17 @@ from octoprint.logging import prefix_multilines @api.route("/system/usage", methods=["GET"]) @restricted_access @admin_permission.require(403) -def readUsageForFolder(): +def readUsageForFolders(): + return jsonify(usage=_usageForFolders()) + +def _usageForFolders(): data = {} for folder_name in s().get(['folder']).keys(): path = s().getBaseFolder(folder_name, check_writable=False) if path is not None: usage = psutil.disk_usage(path) data[folder_name] = { 'free': usage.free, 'total': usage.total } - - return jsonify(usage=data) - + return data @api.route("/system", methods=["POST"]) @restricted_access diff --git a/tests/server/api/test_system.py b/tests/server/api/test_system.py index 841902a9c..b3e57b129 100644 --- a/tests/server/api/test_system.py +++ b/tests/server/api/test_system.py @@ -10,35 +10,26 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" -import json import mock -import psutil import unittest -import octoprint -from octoprint.settings import settings -from octoprint.server import app - -from octoprint.server.api.system import readUsageForFolder - class GetFolderUsageTest(unittest.TestCase): - def setUp(self): - self.settings_patcher = mock.patch("octoprint.server.api.system.s") - self.settings_getter = self.settings_patcher.start() - self.settings = mock.create_autospec(octoprint.settings.Settings) - self.settings_getter.return_value = self.settings - settings(self.settings) - - def cleanUp(self): - self.settings_patcher.stop() - def test_readUsageForFolder(self): - with mock.patch("psutil.disk_usage") as disk_usage_mock: - disk_usage_mock.free = 50 - disk_usage_mock.total = 512 + from octoprint.server.api.system import _usageForFolders - with app.app_context(): - data = json.loads(readUsageForFolder()) - self.assertEquals(data['usage']['uploads']['free'], 50) - self.assertEquals(data['usage']['uploads']['total'], 512) + with mock.patch("psutil.disk_usage") as disk_usage_mock: + disk_usage = mock.MagicMock() + disk_usage.free = 50 + disk_usage.total = 512 + disk_usage_mock.return_value = disk_usage + + with mock.patch("octoprint.server.api.system.s") as settings_mock: + settings = mock.MagicMock() + settings.get.return_value = dict(uploads="mocked") + settings.getBaseFolder.return_value = "mocked" + settings_mock.return_value = settings + + data = _usageForFolders() + self.assertEquals(data['uploads']['free'], 50) + self.assertEquals(data['uploads']['total'], 512) From 09d3c44161acf4fad5c2ae21cdab269cab89122b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 25 Jan 2019 15:39:31 +0100 Subject: [PATCH 04/24] :bug: unicode-ify octoprint.plugin.core Fixes #3012 --- src/octoprint/plugin/core.py | 112 ++++++++++++++++++----------------- 1 file changed, 58 insertions(+), 54 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 6f0f9d447..afa0cef9f 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -37,7 +37,9 @@ import inspect import pkg_resources import pkginfo -from past.builtins import basestring +from past.builtins import unicode + +from octoprint.util import to_unicode try: from os import scandir @@ -207,13 +209,13 @@ class PluginInfo(object): def __str__(self): if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) + return u"{name} ({version})".format(name=self.name, version=self.version) else: - return self.name + return to_unicode(self.name) - def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), - show_location=False, location_str=" - {location}", - show_enabled=False, enabled_strs=("* ", " ", "X ")): + def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""), + show_location=False, location_str=u" - {location}", + show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")): """ Long string representation of the plugin's information. Will return a string of the format ````. @@ -242,17 +244,19 @@ class PluginInfo(object): str: The long string representation of the plugin as described above """ if show_enabled: - ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1]) + ret = to_unicode(enabled_strs[2]) if self.blacklisted \ + else (to_unicode(enabled_strs[0]) if self.enabled + else to_unicode(enabled_strs[1])) else: - ret = "" + ret = u"" - ret += str(self) + ret += unicode(self) if show_bundled: - ret += bundled_strs[0] if self.bundled else bundled_strs[1] + ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) if show_location and self.location: - ret += location_str.format(location=self.location) + ret += to_unicode(location_str).format(location=self.location) return ret @@ -652,7 +656,7 @@ class PluginManager(object): result_added.update(added) result_found += found except: - self.logger.exception("Error fetching plugins from folders") + self.logger.exception(u"Error fetching plugins from folders") if self.plugin_entry_points: existing.update(result_added) @@ -663,7 +667,7 @@ class PluginManager(object): result_added.update(added) result_found += found except: - self.logger.exception("Error fetching plugins from entry points") + self.logger.exception(u"Error fetching plugins from entry points") return result_added, result_found @@ -682,7 +686,7 @@ class PluginManager(object): actual_readonly = not os.access(folder, os.W_OK) if not os.path.exists(folder): - self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) + self.logger.warn(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue for entry in scandir(folder): @@ -721,9 +725,9 @@ class PluginManager(object): plugin.enabled = False added[key] = plugin except: - self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) + self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder)) except: - self.logger.exception("Error processing folder {}".format(folder)) + self.logger.exception(u"Error processing folder {}".format(folder)) return added, found @@ -753,8 +757,8 @@ class PluginManager(object): try: yield entry except: - self.logger.exception("Something went wrong while processing the entry points of a package in the " - "Python environment - broken entry_points.txt in some package?") + self.logger.exception(u"Something went wrong while processing the entry points of a package in the " + u"Python environment - broken entry_points.txt in some package?") for group in groups: for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)): @@ -773,7 +777,7 @@ class PluginManager(object): try: entry_point_metadata = EntryPointMetadata(entry_point) except: - self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) + self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name)) else: kwargs.update(dict( name=entry_point_metadata.name, @@ -803,7 +807,7 @@ class PluginManager(object): added[key] = plugin except: - self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) + self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group)) return added, found @@ -818,7 +822,7 @@ class PluginManager(object): else: return None except: - self.logger.warn("Could not locate plugin {key}".format(key=key)) + self.logger.warn(u"Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... @@ -827,11 +831,11 @@ class PluginManager(object): plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) + self.logger.info(u"Plugin {} is disabled.".format(plugin)) plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)): - self.logger.warn("Plugin {} is blacklisted.".format(plugin)) + self.logger.warn(u"Plugin {} is blacklisted.".format(plugin)) plugin.blacklisted = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): @@ -858,13 +862,13 @@ class PluginManager(object): parsed_metadata=parsed_metadata) plugin.bundled = bundled except: - self.logger.exception("Error loading plugin {key}".format(key=key)) + self.logger.exception(u"Error loading plugin {key}".format(key=key)) return None if plugin.check(): return plugin else: - self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) + self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) return None def _is_plugin_disabled(self, key): @@ -884,7 +888,7 @@ class PluginManager(object): self.plugin_blacklist)) def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None): - self.logger.info("Loading plugins from {folders} and installed plugin packages...".format( + self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format( folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders)) )) @@ -928,7 +932,7 @@ class PluginManager(object): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: - self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin)) + self.logger.warn(u"Plugin {} is blacklisted. Not enabling it.".format(plugin)) continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: @@ -941,9 +945,9 @@ class PluginManager(object): force_reload=force_reload) if len(self.enabled_plugins) <= 0: - self.logger.info("No plugins found") + self.logger.info(u"No plugins found") else: - self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( + self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( count=len(self.enabled_plugins) + len(self.disabled_plugins), implementations=len(self.plugin_implementations), hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())) @@ -951,7 +955,7 @@ class PluginManager(object): def mark_plugin(self, name, **kwargs): if not name in self.plugins: - self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals())) + self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals())) for key, value in kwargs.items(): if value is None: @@ -970,7 +974,7 @@ class PluginManager(object): def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): if not name in self.plugins: - self.logger.warn("Trying to load an unknown plugin {name}".format(**locals())) + self.logger.warn(u"Trying to load an unknown plugin {name}".format(**locals())) return if plugin is None: @@ -985,15 +989,15 @@ class PluginManager(object): self.on_plugin_loaded(name, plugin) plugin.loaded = True - self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error loading plugin %s" % name) + self.logger.exception(u"There was an error loading plugin %s" % name) def unload_plugin(self, name): if not name in self.plugins: - self.logger.warn("Trying to unload unknown plugin {name}".format(**locals())) + self.logger.warn(u"Trying to unload unknown plugin {name}".format(**locals())) return plugin = self.plugins[name] @@ -1013,11 +1017,11 @@ class PluginManager(object): plugin.loaded = False - self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error unloading plugin {name}".format(**locals())) + self.logger.exception(u"There was an error unloading plugin {name}".format(**locals())) # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins if name in self.enabled_plugins: @@ -1027,7 +1031,7 @@ class PluginManager(object): def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): if not name in self.disabled_plugins: - self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals())) + self.logger.warn(u"Tried to enable plugin {name}, however it is not disabled".format(**locals())) return if plugin is None: @@ -1063,13 +1067,13 @@ class PluginManager(object): plugin.implementation.on_plugin_enabled() self.on_plugin_enabled(name, plugin) - self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals())) return True def disable_plugin(self, name, plugin=None): if not name in self.enabled_plugins: - self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals())) + self.logger.warn(u"Tried to disable plugin {name}, however it is not enabled".format(**locals())) return if plugin is None: @@ -1084,7 +1088,7 @@ class PluginManager(object): except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) + self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals())) return False else: if name in self.enabled_plugins: @@ -1096,7 +1100,7 @@ class PluginManager(object): plugin.implementation.on_plugin_disabled() self.on_plugin_disabled(name, plugin) - self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals())) return True @@ -1108,7 +1112,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue self._plugin_hooks[hook].append((order, name, callback)) @@ -1127,7 +1131,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue try: @@ -1274,7 +1278,7 @@ class PluginManager(object): additional_pre_inits=additional_pre_inits, additional_post_inits=additional_post_inits) - self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) + self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): if plugin.implementation is None: @@ -1329,7 +1333,7 @@ class PluginManager(object): try: return_value = factory(name, implementation) except: - self.logger.exception("Exception while executing injection factory %r" % factory) + self.logger.exception(u"Exception while executing injection factory %r" % factory) else: if return_value is not None: if isinstance(return_value, dict): @@ -1353,12 +1357,12 @@ class PluginManager(object): if isinstance(e, PluginLifecycleException): raise e else: - self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals())) + self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals())) return False else: self.on_plugin_implementations_initialized(name, plugin) - self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals())) + self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals())) return True @@ -1375,7 +1379,7 @@ class PluginManager(object): self.logger.log(level, message) if len(all_plugins) <= 0: - _log("No plugins available") + _log(u"No plugins available") else: formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled, bundled_strs=bundled_str, @@ -1383,9 +1387,9 @@ class PluginManager(object): location_str=location_str, show_enabled=show_enabled, enabled_strs=enabled_str), - sorted(self.plugins.values(), key=lambda x: str(x).lower()))) - _log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), - plugins=formatted_plugins)) + sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) + _log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), + plugins=formatted_plugins)) def get_plugin(self, identifier, require_enabled=True): """ @@ -1477,13 +1481,13 @@ class PluginManager(object): try: sorting_value = impl[1].get_sorting_key(sorting_context) except: - self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) + self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0])) if sorting_value is not None: try: sorting_value = int(sorting_value) except ValueError: - self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) + self.logger.warn(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) sorting_value = None plugin_info = self.get_plugin_info(impl[0], require_enabled=False) @@ -1562,7 +1566,7 @@ class PluginManager(object): for client in self.registered_clients: try: client(plugin, data) - except: self.logger.exception("Exception while sending plugin data to client") + except: self.logger.exception(u"Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], From db009e3ba2b43c9fd807b73d0d29a4faba856608 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 25 Jan 2019 15:48:35 +0100 Subject: [PATCH 05/24] :bug: backup: do not translate plugin name Only translate it at template level, not before. Fixes #3012 --- src/octoprint/plugins/backup/__init__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 160f85070..39ffca4a9 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -60,7 +60,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._in_progress = [] self._in_progress_lock = threading.RLock() - ##~~ StarupPlugin + ##~~ StartupPlugin def on_after_startup(self): self._clean_dir_backup(self._settings._basedir, @@ -74,6 +74,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, css=["css/backup.css"], less=["less/backup.less"]) + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="settings", name=gettext(u"Backup & Restore"))] + ##~~ BlueprintPlugin @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) @@ -925,7 +930,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, class InsufficientSpace(Exception): pass -__plugin_name__ = gettext(u"Backup & Restore") +__plugin_name__ = u"Backup & Restore" __plugin_author__ = u"Gina Häußge" __plugin_description__ = u"Backup & restore your OctoPrint settings and data" __plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup " From 68410cb3d7bfba3a1b32bf67a9d5a383ef791683 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 25 Jan 2019 16:14:45 +0100 Subject: [PATCH 06/24] :bug: Fix an issue with plugin sorting If we just uninstalled a plugin there might not be a PluginInfo object. In that case assume the plugin is not bundled (not False = True) --- src/octoprint/plugin/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index afa0cef9f..d605ebb16 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1491,7 +1491,7 @@ class PluginManager(object): sorting_value = None plugin_info = self.get_plugin_info(impl[0], require_enabled=False) - return sorting_value is None, sorting_value, not plugin_info.bundled, impl[0] + return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0] return [impl[1] for impl in sorted(result, key=sort_func)] From f3f1061f9d41d64193638af7f40ba6065cd68457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 12:03:16 +0100 Subject: [PATCH 07/24] :sparkle: Configurable terminal log size in comm layer See https://discourse.octoprint.org/t/logging-terminal-information-on-failed-print/7047/3?u=foosel --- src/octoprint/settings.py | 1 + src/octoprint/util/comm.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index db7492842..c969bc1c1 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -117,6 +117,7 @@ default_settings = { "helloCommand": "M110 N0", "disconnectOnErrors": True, "ignoreErrorsFromFirmware": False, + "terminalLogSize": 20, "logResends": True, "supportResendsWithoutOk": "detect", "logPositionOnPause": True, diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index bd795ba43..803c5f6a9 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -467,7 +467,8 @@ class MachineCom(object): self._resendActive = False - self._terminal_log = deque([], 20) + terminal_log_size = settings().getInt(["serial", "terminalLogSize"]) + self._terminal_log = deque([], min(20, terminal_log_size)) self._disconnect_on_errors = settings().getBoolean(["serial", "disconnectOnErrors"]) self._ignore_errors = settings().getBoolean(["serial", "ignoreErrorsFromFirmware"]) From 44b4c6cc40412fa75228e359ca16afb2532942db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 13:00:26 +0100 Subject: [PATCH 08/24] :bug: sleep => time.sleep --- src/octoprint/util/comm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 803c5f6a9..370ac0d98 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -3363,7 +3363,7 @@ class MachineCom(object): # may be busy, so give things a little time before we try again. Extend this # period each time we fail until either we write the data or run out of retry attempts. if passes > 1: - sleep((passes-1)/10.0) + time.sleep((passes-1)/10.0) ##~~ command handlers From bd58138acf1a3ed54d9646d2521ac9b0b05c3162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 13:05:27 +0100 Subject: [PATCH 09/24] :art: Refactored for better code reuse --- src/octoprint/util/comm.py | 40 ++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 370ac0d98..606721441 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -3556,7 +3556,7 @@ class MachineCom(object): self._resendDelta = None def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): - self._logger.info("Force-sending M112 to the printer") + self._logger.info(u"Force-sending M112 to the printer") # emergency stop, jump the queue with the M112, regardless of whether the EMERGENCY_PARSER capability is # available or not @@ -3590,30 +3590,10 @@ class MachineCom(object): return None, def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs): - # only jump the queue with M108 if the EMERGENCY_PARSER capability is available - if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False): - return - - self._logger.info("Force-sending M108 to the printer") - self._do_send(cmd, gcode=gcode) - - # use up an ok since we will get one back for this command and don't want to get out of sync - self._clear_to_send.clear() - - return None, + self._emergency_force_send(cmd, u"Force-sending M108 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs): - # only jump the queue with M410 if the EMERGENCY_PARSER capability is available - if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False): - return - - self._logger.info("Force-sending M410 to the printer") - self._do_send(cmd, gcode=gcode) - - # use up an ok since we will get one back for this command and don't want to get out of sync - self._clear_to_send.clear() - - return None, + self._emergency_force_send(cmd, u"Force-sending M410 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M114_queued(self, *args, **kwargs): self._reset_position_timers() @@ -3633,6 +3613,20 @@ class MachineCom(object): self._timeout = self._get_new_communication_timeout() + _timeout self._dwelling_until = time.time() + _timeout + def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs): + # only jump the queue with our command if the EMERGENCY_PARSER capability is available + if not self._capability_support.get(self.CAPABILITY_EMERGENCY_PARSER, False) \ + or not self._firmware_capabilities.get(self.CAPABILITY_EMERGENCY_PARSER, False): + return + + self._logger.info(message) + self._do_send(cmd, gcode=gcode) + + # use up an ok since we will get one back for this command and don't want to get out of sync + self._clear_to_send.clear() + + return None, + def _validate_tool(self, tool): return tool < self._printerProfileManager.get_current_or_default()["extruder"]["count"] and not tool in self._knownInvalidTools From 5e953c12a1587c982a3f76234b7a2bc208883254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 13:07:34 +0100 Subject: [PATCH 10/24] :speech_balloon: Rewording --- src/octoprint/util/comm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 606721441..0af818b12 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1887,7 +1887,7 @@ class MachineCom(object): self._logger.info("Firmware states that it supports sd status autoreporting") self._set_autoreport_sdstatus_interval() elif capability == self.CAPABILITY_EMERGENCY_PARSER and enabled: - self._logger.info("Firmware states that it supports emergency GCODEs M108 and M410 to be sent without waiting for an acknowledgement first") + self._logger.info("Firmware states that it supports emergency GCODEs to be sent without waiting for an acknowledgement first") # notify plugins for name, hook in self._firmware_info_hooks["capabilities"].items(): From 379411cea70c2bb1f699ec1542845230a1105514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 13:10:00 +0100 Subject: [PATCH 11/24] :wrench: action_command_prompt: M876 as default command See MarlinFirmware/Marlin#12982 --- src/octoprint/plugins/action_command_prompt/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 8900c5d7a..6c255cbfc 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -55,7 +55,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ SettingsPlugin def get_settings_defaults(self): - return dict(selection_command=None) + return dict(selection_command="M876") def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) From d8088887e1c7585b1e85dd7bc8d850915067c709 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 13:45:09 +0100 Subject: [PATCH 12/24] :bug: Fix bug introduced in bd58138acf --- src/octoprint/util/comm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 0af818b12..49f0c62e0 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -3590,10 +3590,10 @@ class MachineCom(object): return None, def _gcode_M108_queuing(self, cmd, gcode=None, *args, **kwargs): - self._emergency_force_send(cmd, u"Force-sending M108 to the printer", gcode=gcode, *args, **kwargs) + return self._emergency_force_send(cmd, u"Force-sending M108 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M410_queuing(self, cmd, gcode=None, *args, **kwargs): - self._emergency_force_send(cmd, u"Force-sending M410 to the printer", gcode=gcode, *args, **kwargs) + return self._emergency_force_send(cmd, u"Force-sending M410 to the printer", gcode=gcode, *args, **kwargs) def _gcode_M114_queued(self, *args, **kwargs): self._reset_position_timers() From 01484b630ad7a9ae45b8744233b3df02566a4b76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 14:32:10 +0100 Subject: [PATCH 13/24] :sparkles: action_command_prompt: EMERGENCY_PARSER support (default off) Note: Has to be enabled manually for now as long as we cannot detect that the firmware indeed has support for M876 and hence has it as part of the EMERGENCY_PARSER. See MarlinFirmware/Marlin#12982 --- .../plugins/action_command_prompt/__init__.py | 42 ++++++++++++++----- .../action_command_prompt_settings.jinja2 | 13 ++++-- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 6c255cbfc..0f784846c 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -38,13 +38,17 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): + COMMAND = "M876" + # noinspection PyMissingConstructor def __init__(self): self._prompt = None - self._selection_command = None + self._command = None + self._enable_emergency_sending = False def initialize(self): - self._selection_command = self._settings.get([b"selection_command"]) + self._command = self._settings.get([b"command"]) + self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) #~ AssetPlugin @@ -55,11 +59,15 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ SettingsPlugin def get_settings_defaults(self): - return dict(selection_command="M876") + return dict(command=self.COMMAND, + + # TODO make this default to True once we have a capability report to listen to + enable_emergency_sending=False) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._selection_command = self._settings.get([b"selection_command"]) + self._command = self._settings.get([b"command"]) + self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) #~ SimpleApiPlugin @@ -99,10 +107,6 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, if not action.startswith(b"prompt_"): return - if self._selection_command is None: - self._logger.info("Got a prompt command from the printer but no selection command is defined") - return - parts = action.split(None, 1) if len(parts) == 1: action = parts[0] @@ -138,6 +142,22 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, self._close_prompt() self._prompt = None + #~ queuing handling + + def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): + if gcode != self._command: + return + + if not self._enable_emergency_sending: + return + + if not "S" in cmd: + # we only force-send M876 Sx + return + + # noinspection PyProtectedMember + return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode) + #~ prompt handling def _show_prompt(self): @@ -152,7 +172,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, def _answer_prompt(self, choice): self._close_prompt() - self._printer.commands([self._selection_command.format(choice=choice)]) + self._printer.commands(["{command} S{choice}".format(command=self._command, + choice=choice)]) __plugin_name__ = "Action Command Prompt Support" @@ -163,5 +184,6 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin your printer wil __plugin_license__ = "AGPLv3" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler + b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler } diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index a30e7f9b8..e650ce6df 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -2,10 +2,17 @@
- +
- -
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+ +
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
+
+
+
+
+
From 2db230549e069fdd4cdf9629b3a2104d18a3100f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 14:50:40 +0100 Subject: [PATCH 14/24] :sparkles: action_command_prompt: signal prompt support on connect (default off) Note: Has to be enabled manually for now as long as we cannot detect that the firmware indeed has support for M876. See MarlinFirmware/Marlin#12982 --- .../plugins/action_command_prompt/__init__.py | 16 +++++++++++++++- .../action_command_prompt_settings.jinja2 | 7 +++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 0f784846c..3a5dc2384 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import octoprint.plugin from octoprint.server import user_permission +from octoprint.events import Events import flask from flask_babel import gettext @@ -34,6 +35,7 @@ class Prompt(object): class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): @@ -45,10 +47,12 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, self._prompt = None self._command = None self._enable_emergency_sending = False + self._enable_signal_support = False def initialize(self): self._command = self._settings.get([b"command"]) self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) #~ AssetPlugin @@ -56,18 +60,28 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, return dict(js=["js/action_command_prompt.js"], clientjs=["clientjs/action_command_prompt.js"]) + #~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.CONNECTED and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ SettingsPlugin def get_settings_defaults(self): return dict(command=self.COMMAND, # TODO make this default to True once we have a capability report to listen to - enable_emergency_sending=False) + enable_emergency_sending=False, + + # TODO make this default to True once we have a capability report to listen to + enable_signal_support=False) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) self._command = self._settings.get([b"command"]) self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) #~ SimpleApiPlugin diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index e650ce6df..4a74ff5ea 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -15,4 +15,11 @@ +
+
+ +
+
From 5d021d76a048037c6954a26029cd7c41bf982f95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 17:41:01 +0100 Subject: [PATCH 15/24] :sparkles: action_command_prompt: PROMPT_SUPPORT capability support Allow configuration of whether to enable the plugin if firmware support is detected, always or never. Handle PROMPT_SUPPORT capability report accordingly. See MarlinFirmware/Marlin#12982 --- .../plugins/action_command_prompt/__init__.py | 40 ++++++++++++---- .../action_command_prompt_settings.jinja2 | 47 +++++++++++++------ 2 files changed, 63 insertions(+), 24 deletions(-) diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 3a5dc2384..467aac652 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -41,15 +41,19 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin): COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" # noinspection PyMissingConstructor def __init__(self): self._prompt = None + self._enable = "detected" self._command = None self._enable_emergency_sending = False self._enable_signal_support = False + self._cap_prompt_support = False def initialize(self): + self._enable = self._settings.get([b"enable"]) self._command = self._settings.get([b"command"]) self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) @@ -63,22 +67,20 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ EventHandlerPlugin def on_event(self, event, payload): - if event == Events.CONNECTED and self._enable_signal_support: + if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: self._printer.commands(["{command} P1".format(command=self._command)]) #~ SettingsPlugin def get_settings_defaults(self): - return dict(command=self.COMMAND, - - # TODO make this default to True once we have a capability report to listen to - enable_emergency_sending=False, - - # TODO make this default to True once we have a capability report to listen to - enable_signal_support=False) + return dict(enable="detected", + command=self.COMMAND, + enable_emergency_sending=True, + enable_signal_support=True) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + self._enable = self._settings.get([b"enable"]) self._command = self._settings.get([b"command"]) self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) @@ -162,7 +164,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, if gcode != self._command: return - if not self._enable_emergency_sending: + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: return if not "S" in cmd: @@ -172,19 +174,36 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, # noinspection PyProtectedMember return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode) + #~ capability reporting + + def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ prompt handling def _show_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt.activate() self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", text=self._prompt.text, choices=self._prompt.choices)) def _close_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt = None self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) def _answer_prompt(self, choice): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._close_prompt() self._printer.commands(["{command} S{choice}".format(command=self._command, choice=choice)]) @@ -199,5 +218,6 @@ __plugin_license__ = "AGPLv3" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, - b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler + b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + b"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler } diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index 4a74ff5ea..df45ff760 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -2,24 +2,43 @@
- +
- -
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
-
-
-
-
-
-
-
- +
+ +
+
+ +
+ +
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
+
+
+
+
+ +
+
+
+
+ +
+
From dd692d6f303e93971eddc2ef4362f777d36e75ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 17:56:10 +0100 Subject: [PATCH 16/24] :wrench: Adjust default regex of temperature terminal filter Should no longer match lines like FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410 Fixes #2945 --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index c969bc1c1..2b92c34c0 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -349,7 +349,7 @@ default_settings = { "apps": {} }, "terminalFilters": [ - { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)" }, + { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):\d+)" }, { "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)" }, { "name": "Suppress wait responses", "regex": "Recv: wait"} ], From 7f2b79bcd5b521517cb8a229aed45c3c84106ce3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 18:02:46 +0100 Subject: [PATCH 17/24] :rewind: Revert ":wrench: Adjust default regex of temperature terminal filter" This reverts commit dd692d6 --- src/octoprint/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 2b92c34c0..c969bc1c1 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -349,7 +349,7 @@ default_settings = { "apps": {} }, "terminalFilters": [ - { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):\d+)" }, + { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)" }, { "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)" }, { "name": "Suppress wait responses", "regex": "Recv: wait"} ], From 904b3c6cf5964bdeb6f7ce7937eac6be93a99cb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 28 Jan 2019 18:20:03 +0100 Subject: [PATCH 18/24] :wrench: Adjust default regex of temperature terminal filter (2nd try) Should no longer match lines like FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410 but should pass unit tests. Fixes #2945 --- src/octoprint/settings.py | 2 +- tests/settings/test_settings.py | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index c969bc1c1..990a54da2 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -349,7 +349,7 @@ default_settings = { "apps": {} }, "terminalFilters": [ - { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)" }, + { "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)" }, { "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)" }, { "name": "Suppress wait responses", "regex": "Recv: wait"} ], diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index a0b17f218..ee0ba1768 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -146,6 +146,7 @@ class TestSettings(unittest.TestCase): 'Send: N71667 G1 X163.151 Y35.424 E0.02043*83', 'Send: N85343 G1 Z29.880 F10800.000*15', 'Recv: ok', + 'Recv: FIRMWARE_NAME:Marlin 1.1.7-C2 (Github) SOURCE_CODE_URL:https://github.com/Robo3D/Marlin-C2 PROTOCOL_VERSION:C2 MACHINE_TYPE:RoboC2 EXTRUDER_COUNT:1 UUID:cede2a2f-41a2-4748-9b12-c55c62f367ff EMERGENCY_CODES:M108,M112,M410' ] filters = octoprint.settings.Settings().get(["terminalFilters"]) @@ -155,7 +156,7 @@ class TestSettings(unittest.TestCase): for terminal_string in bad_terminal_entries: match_result = matcher.match(terminal_string) # can switch to assertIsNone after 3.x upgrade. - self.assertFalse(match_result, "string matched and it shouldn't have.") + self.assertFalse(match_result, "string matched and it shouldn't have: {!r}".format(terminal_string)) def test_temperature_regex_matches(self): @@ -163,8 +164,11 @@ class TestSettings(unittest.TestCase): #with self.mocked_config(): common_terminal_entries = [ + 'Send: M105', + 'Send: N123 M105*456', 'Recv: ok N5993 P15 B15 T:59.2 /0.0 B:31.8 /0.0 T0:59.2 /0.0 @:0 B@:100:', # monoprice mini delta 'Recv: ok T:210.3 /210.0 B:60.3 /60.0 T0:210.3 /210.0 @:79 B@:0 P:35.9 A:40.0', # Prusa mk3 + 'Recv: T:210.3 /210.0', ] filters = octoprint.settings.Settings().get(["terminalFilters"]) @@ -174,7 +178,7 @@ class TestSettings(unittest.TestCase): for terminal_string in common_terminal_entries: match_result = matcher.match(terminal_string) # can switch to assertIsNotNone after 3.x upgrade. - self.assertTrue(match_result, "string did not match and it should have.") + self.assertTrue(match_result, "string did not match and it should have: {!r}".format(terminal_string)) ##~~ test getters From 0b23417f45920480d988117d050cd3eb1431d6b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 29 Jan 2019 16:48:07 +0100 Subject: [PATCH 19/24] =?UTF-8?q?=F0=9F=90=9B=20Add=20missing=20asset=20th?= =?UTF-8?q?at=20got=20lost=20during=20a=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3021 --- src/octoprint/server/util/flask.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 48e20588a..7a79eedce 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1413,6 +1413,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): assets["clientjs"] = [ "js/app/client/base.js", "js/app/client/socket.js", + "js/app/client/access.js", "js/app/client/browser.js", "js/app/client/connection.js", "js/app/client/control.js", From 1aea92a5f140e40fff07dca1fb13046d30188281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Jan 2019 14:35:32 +0100 Subject: [PATCH 20/24] =?UTF-8?q?=E2=98=94=20Protect=20against=20invalid?= =?UTF-8?q?=20preemptive=20cache=20config=20data?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3023 --- src/octoprint/server/util/flask.py | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index a62f3dee9..772538acd 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -878,11 +878,15 @@ class PreemptiveCache(object): if cache_data is None: cache_data = dict() + if not self._validate_data(cache_data): + self._logger.warn("Preemptive cache data was invalid, ignoring it") + cache_data = dict() + return cache_data def get_data(self, root): cache_data = self.get_all_data() - return cache_data.get(root, dict()) + return cache_data.get(root, list()) def set_all_data(self, data): from octoprint.util import atomic_write @@ -925,7 +929,7 @@ class PreemptiveCache(object): def get_newest(entries): result = None for entry in entries: - if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])): + if "_timestamp" in entry and (result is None or ("_timestamp" in result and result["_timestamp"] < entry["_timestamp"])): result = entry return result @@ -951,12 +955,32 @@ class PreemptiveCache(object): return set(strip_ignored(a).items()) == set(strip_ignored(b).items()) + def _validate_data(self, data): + if not isinstance(data, dict): + return False + + for root, entries in data.items(): + if not isinstance(entries, list): + return False + + for entry in entries: + if not self._validate_entry(entry): + return False + + return True + + def _validate_entry(self, entry): + return isinstance(entry, dict) and "_timestamp" in entry and "_count" in entry + def preemptively_cached(cache, data, unless=None): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): - cache.record(data, unless=unless) + try: + cache.record(data, unless=unless) + except: + logging.getLogger(__name__).exception(u"Error while recording preemptive cache entry: {!r}".format(data)) return f(*args, **kwargs) return decorated_function return decorator From c23bafd788d8bf1cc0cd8f94a7a8cf8f8ef531f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Jan 2019 14:36:27 +0100 Subject: [PATCH 21/24] =?UTF-8?q?=E2=98=94=20Protect=20against=20callback?= =?UTF-8?q?=20errors=20in=20decorators=20on=20default=20view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/util/flask.py | 47 ++++++++++++++++++------------ 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 772538acd..9b14ffe62 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -992,11 +992,14 @@ def etagged(etag): def decorated_function(*args, **kwargs): rv = f(*args, **kwargs) if isinstance(rv, flask.Response): - result = etag - if callable(result): - result = result(rv) - if result: - rv.set_etag(result) + try: + result = etag + if callable(result): + result = result(rv) + if result: + rv.set_etag(result) + except: + logging.getLogger(__name__).exception(u"Error while calculating the etag value for response {!r}".format(rv)) return rv return decorated_function return decorator @@ -1008,16 +1011,19 @@ def lastmodified(date): def decorated_function(*args, **kwargs): rv = f(*args, **kwargs) if not "Last-Modified" in rv.headers: - result = date - if callable(result): - result = result(rv) + try: + result = date + if callable(result): + result = result(rv) - if not isinstance(result, basestring): - from werkzeug.http import http_date - result = http_date(result) + if not isinstance(result, basestring): + from werkzeug.http import http_date + result = http_date(result) - if result: - rv.headers["Last-Modified"] = result + if result: + rv.headers["Last-Modified"] = result + except: + logging.getLogger(__name__).exception(u"Error while calculating the lastmodified value for response {!r}".format(rv)) return rv return decorated_function return decorator @@ -1027,12 +1033,15 @@ def conditional(condition, met): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): - if callable(condition) and condition(): - # condition has been met, return met-response - rv = met - if callable(met): - rv = met() - return rv + try: + if callable(condition) and condition(): + # condition has been met, return met-response + rv = met + if callable(met): + rv = met() + return rv + except: + logging.getLogger(__name__).exception(u"Error while evaluating conditional {!r} or met {!r}".format(condition, met)) # condition hasn't been met, call decorated function return f(*args, **kwargs) From 9a7ebde76b63488a488b42b748dc52e42d8d543a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Jan 2019 15:02:32 +0100 Subject: [PATCH 22/24] =?UTF-8?q?=F0=9F=93=9D=20Fix=20documentation=20for?= =?UTF-8?q?=20firmware=20info=20&=20capability=20plugin=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plugins/hooks.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 77a3fbaec..65533a7a4 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -380,10 +380,10 @@ octoprint.cli.commands OctoPrint's CLI. :rtype: list -.. _sec-plugins-hook-comm-firmware-info: +.. _sec-plugins-hook-comm-protocol-firmware-info: -octoprint.comm.firmware.info -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.protocol.firmware.info +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs) @@ -413,10 +413,10 @@ octoprint.comm.firmware.info :param str firmware_name: The name of the parsed capability :param dict firmware_data: All data contained in the ``M115`` report -.. _sec-plugins-hook-comm-firmware-capabilities: +.. _sec-plugins-hook-comm-protocol-firmware-capabilities: -octoprint.comm.firmware.capabilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.firmware.protocol.capabilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs) From 4e47ecabf82741a4fc34a157ea510a68228bc6c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Jan 2019 13:55:59 +0100 Subject: [PATCH 23/24] =?UTF-8?q?=F0=9F=90=9B=20Fix=20duped=20log=20entrie?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/util/sockjs.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 31a265634..d5af7c826 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -355,6 +355,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, # TODO remove when central job management becomes available and takes care of this for us self._emit("event", payload=dict(type=Events.MOVIE_RENDERING, payload=octoprint.timelapse.current_render_job)) + self._registered = True def _unregister(self): """Unregister this socket from the system""" From 5e8220055fa39f5c6bb2b3c99c58ab5eda8561d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Jan 2019 14:44:46 +0100 Subject: [PATCH 24/24] =?UTF-8?q?=F0=9F=90=9B=20Fix=20merge=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/api/system.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 77e8062df..23761f255 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -23,7 +23,7 @@ from octoprint.access.permissions import Permissions from octoprint.logging import prefix_multilines @api.route("/system/usage", methods=["GET"]) -@restricted_access +@no_firstrun_access @Permissions.SYSTEM.require(403) def readUsageForFolders(): return jsonify(usage=_usageForFolders())