diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml index 1d842b60c..ef39f5868 100644 --- a/.github/workflows/trigger_docker.yml +++ b/.github/workflows/trigger_docker.yml @@ -13,6 +13,6 @@ jobs: uses: peter-evans/repository-dispatch@v1 with: token: ${{ secrets.DOCKER_ACCESS_TOKEN }} - repository: OctoPrint/docker - event-type: octoprint-release - client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "event-name": "${{ github.event_name }}", "event-type": "${{ github.event.action }}"}' + repository: ${{ github.repository_owner }}/octoprint-docker + event-type: 'release' + client-payload: '{"tag_name": "${{ github.event.release.tag_name }}"}' diff --git a/AUTHORS.md b/AUTHORS.md index db2e16367..57335f17c 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -121,7 +121,13 @@ date of first contribution): * [Josh Friend](https://github.com/joshfriend) * [Lachlan Cresswell](https://github.com/lachyc) * [Khoi Pham](https://github.com/osubuu) + * [Timofei Korostelev](https://github.com/chudsaviet) * [Federico Nembrini](https://github.com/FedericoNembrini) + * [Uri Shaked](https://github.com/urish) + * [Brian Vanderbusch](https://github.com/LongLiveCHIEF) + * [Charlie Powell](https://github.com/cp2004) + * [Ollis Git](https://github.com/OllisGit) + * [Sophist](https://github.com/Sophist-UK) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 594251edb..f3c0cb7f9 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -12,6 +12,7 @@ * [css-element-queries](https://github.com/marcj/css-element-queries): MIT * [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain * [Flot](http://www.flotcharts.org/): MIT + * [HLS.js](https://github.com/video-dev/hls.js): Apache License 2.0 * [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT * [JQuery](http://jquery.com/): MIT * [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed) diff --git a/docs/bundledplugins/action_command_prompt.rst b/docs/bundledplugins/action_command_prompt.rst index 247f741ff..adb8635e4 100644 --- a/docs/bundledplugins/action_command_prompt.rst +++ b/docs/bundledplugins/action_command_prompt.rst @@ -72,8 +72,7 @@ To display the :ref:`above dialog ` received from the printer. @@ -534,8 +534,12 @@ octoprint.comm.protocol.action :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str line: The complete line as received from the printer, format ``// action:`` - :param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be + :param str action: The parsed out action command incl. parameters, so for a ``line`` like ``// action:some_command key value`` this will be + ``some_command key value`` + :param str name: The action command name, for a ``line`` like ``// action:some_command key value`` this will be ``some_command`` + :param str params: The action command's parameter, for a ``line`` like ``// action:some_command key value`` this will + be ``key value`` .. _sec-plugins-hook-comm-protocol-atcommand-phase: @@ -1121,6 +1125,13 @@ octoprint.filemanager.preprocessor :return: The `file_object` as passed in or None, or a replaced version to use instead for further processing. :rtype: AbstractFileWrapper or None +.. _sec-plugins-hook-plugin-backup-excludes: + +octoprint.plugin.backup.additional_excludes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +See :ref:`here `. + .. _sec-plugins-hook-plugin-loginui-theming: octoprint.plugin.loginui.theming diff --git a/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css index ed15d2c39..e15340a1e 100644 --- a/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css +++ b/src/octoprint/plugins/action_command_notification/static/css/action_command_notification.css @@ -3,3 +3,9 @@ line-height: 20px; border-bottom: 1px solid #ddd; } + +.sidebar_plugin_action_command_notification_scrollable { + overflow-x: hidden; + overflow-y: scroll; + max-height: 306px; +} diff --git a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 index 67e8557c7..1118af0f3 100644 --- a/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 +++ b/src/octoprint/plugins/action_command_notification/templates/action_command_notification_sidebar.jinja2 @@ -1,5 +1,5 @@
-
+ +{{ _('Manually generate an application key') }} + +
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+ +
+
+
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index ff1d437a4..9b40a5a4e 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -10,6 +10,7 @@ from octoprint.settings import default_settings from octoprint.plugin.core import FolderOrigin from octoprint.server import admin_permission, NO_CONTENT from octoprint.server.util.flask import no_firstrun_access +from octoprint.events import Events from octoprint.util import is_hidden_path, to_bytes from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible from octoprint.util.platform import is_os_compatible @@ -83,6 +84,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, default_groups=[ADMIN_GROUP]) ] + # Socket emit hook + + def socket_emit_hook(self, socket, user, message, payload, *args, **kwargs): + if message != "event" or payload["type"] != Events.PLUGIN_BACKUP_BACKUP_CREATED: + return True + + return user and user.has_permission(Permissions.PLUGIN_BACKUP_ACCESS) + ##~~ StartupPlugin def on_after_startup(self): @@ -166,6 +175,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._logger.info("... done creating backup zip.") + self._event_bus.fire(Events.PLUGIN_BACKUP_BACKUP_CREATED, + dict(name=name, + path=final_path, + excludes=exclude)) + def on_backup_error(name, exc_info): with self._in_progress_lock: try: @@ -183,6 +197,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, kwargs=dict(exclude=exclude, settings=self._settings, plugin_manager=self._plugin_manager, + logger=self._logger, datafolder=self.get_plugin_data_folder(), on_backup_start=on_backup_start, on_backup_done=on_backup_done, @@ -388,6 +403,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._create_backup(backup_file, exclude=exclude, settings=settings, + logger=self._logger, plugin_manager=cli_group.plugin_manager, datafolder=datafolder) click.echo("Done.") @@ -519,7 +535,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) if os.path.exists(data_file): try: - with io.open(data_file, mode='rb', encoding="utf-8") as f: + with io.open(data_file, mode='rt', encoding="utf-8") as f: unknown_plugins = json.load(f) assert isinstance(unknown_plugins, list) @@ -645,6 +661,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, exclude=None, settings=None, plugin_manager=None, + logger=None, datafolder=None, on_backup_start=None, on_backup_done=None, @@ -660,6 +677,24 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if "timelapse" in exclude: exclude.append("timelapse_tmp") + current_excludes = list(exclude) + additional_excludes = list() + plugin_data = settings.global_get_basefolder("data") + for plugin, hook in plugin_manager.get_hooks("octoprint.plugin.backup.additional_excludes").items(): + try: + additional = hook(current_excludes) + if isinstance(additional, list): + if "." in additional: + current_excludes.append(os.path.join("data", plugin)) + additional_excludes.append(os.path.join(plugin_data, plugin)) + else: + current_excludes += map(lambda x: os.path.join("data", plugin, x), additional) + additional_excludes += map(lambda x: os.path.join(plugin_data, plugin, x), additional) + except Exception: + logger.exception("Error while retrieving additional excludes " + "from plugin {name}".format(**locals()), + extra=dict(plugin=plugin)) + configfile = settings._configfile basedir = settings._basedir @@ -717,10 +752,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, add_to_zip(settings.global_get_basefolder(folder), "basedir/" + folder.replace("_", "/"), - ignored=[own_folder,]) + ignored=[own_folder,] + additional_excludes) # backup anything else that might be lying around in our basedir - add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ]) + add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ] + additional_excludes) # add list of installed plugins plugins = [] @@ -996,11 +1031,12 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, payload["type"] = message self._plugin_manager.send_plugin_message(self._identifier, payload) - - class InsufficientSpace(Exception): pass +def _register_custom_events(*args, **kwargs): + return ["backup_created"] + __plugin_name__ = "Backup & Restore" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Backup & restore your OctoPrint settings and data" @@ -1013,5 +1049,7 @@ __plugin_hooks__ = { "octoprint.server.http.routes": __plugin_implementation__.route_hook, "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions, + "octoprint.events.register_custom_events": _register_custom_events, + "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook } diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index da2f0e879..572c3b492 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -37,6 +37,7 @@ import threading import tempfile import shutil import filetype +import pkg_resources from datetime import datetime @@ -94,7 +95,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.BlueprintPlugin, octoprint.plugin.EventHandlerPlugin): - ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") + ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar", ".gz") PYTHON_EXTENSIONS = (".py",) # valid pip install URL schemes according to https://pip.pypa.io/en/stable/reference/pip_install/ @@ -140,6 +141,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._get_throttled = lambda: False + self._install_task = None + self._install_lock = threading.RLock() + def initialize(self): self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console") self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json") @@ -388,11 +392,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Insufficient rights", 403) url = data["url"] plugin_name = data["plugin"] if "plugin" in data else None - return self.command_install(url=url, - force="force" in data and data["force"] in valid_boolean_trues, - dependency_links="dependency_links" in data - and data["dependency_links"] in valid_boolean_trues, - reinstall=plugin_name) + + with self._install_lock: + if self._install_task is not None: + return make_response("There's always a plugin being installed", 409) + + self._install_task = threading.Thread(target=self.command_install, + kwargs=dict(url=url, + force="force" in data and data["force"] in valid_boolean_trues, + dependency_links="dependency_links" in data + and data["dependency_links"] in valid_boolean_trues, + reinstall=plugin_name)) + self._install_task.daemon = True + self._install_task.start() + + return jsonify(in_progress=True) elif command == "uninstall": plugin_name = data["plugin"] @@ -450,45 +464,47 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def command_install(self, url=None, path=None, name=None, force=False, reinstall=None, dependency_links=False): folder = None - try: - source = path - source_type = "path" + with self._install_lock: + try: + source = path + source_type = "path" - if url is not None: - # fetch URL - folder = TemporaryDirectory() - path = download_file(url, folder.name) - source = url - source_type = "url" + if url is not None: + # fetch URL + folder = TemporaryDirectory() + path = download_file(url, folder.name) + source = url + source_type = "url" - # determine type of path - if self._is_archive(path): - return self._command_install_archive(path, - source=source, - source_type=source_type, - force=force, - reinstall=reinstall, - dependency_links=dependency_links) + # determine type of path + if self._is_archive(path): + return self._command_install_archive(path, + source=source, + source_type=source_type, + force=force, + reinstall=reinstall, + dependency_links=dependency_links) - elif self._is_pythonfile(path): - return self._command_install_pythonfile(path, - source=source, - source_type=source_type, - name=name) + elif self._is_pythonfile(path): + return self._command_install_pythonfile(path, + source=source, + source_type=source_type, + name=name) - else: - self._logger.error("{} is neither an archive nor a python file, can't install that.".format(source)) - result = dict(result=False, - source=source, - source_type=source_type, - reason="Could not install plugin from {}, was neither " - "a plugin archive nor a single file plugin".format(source)) - self._send_result_notification("install", result) - return jsonify(result) + else: + self._logger.error("{} is neither an archive nor a python file, can't install that.".format(source)) + result = dict(result=False, + source=source, + source_type=source_type, + reason="Could not install plugin from {}, was neither " + "a plugin archive nor a single file plugin".format(source)) + self._send_result_notification("install", result) + return result - finally: - if folder is not None: - folder.cleanup() + finally: + if folder is not None: + folder.cleanup() + self._install_task = None # noinspection DuplicatedCode def _command_install_archive(self, path, source=None, source_type=None, force=False, reinstall=None, dependency_links=False): @@ -498,17 +514,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("System is currently throttled, refusing to install " "anything due to possible stability issues", 409) + try: + # Py3 + from urllib.parse import quote as url_quote + except ImportError: + # Py2 + from urllib import quote as url_quote + path = os.path.abspath(path) - path_url = "file://" + path if os.sep != "/": # windows gets special handling - path = path.replace(os.sep, "/").lower() - path_url = "file:///" + path + drive, loc = os.path.splitdrive(path) + path_url = "file:///" + drive.lower() + url_quote(loc.replace(os.sep, "/").lower()) + shell_quote = lambda x: x # do not shell quote under windows, non posix shell + else: + path_url = "file://" + url_quote(path) + shell_quote = sarge.shell_quote already_installed_check = lambda line: path_url in line.lower() # lower case in case of windows self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(path_url), "--no-cache-dir"] + pip_args = ["--disable-pip-version-check", "install", shell_quote(path_url), "--no-cache-dir"] if dependency_links or self._settings.get_boolean(["dependency_links"]): pip_args.append("--process-dependency-links") @@ -594,7 +620,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, reason="Pip did not report successful installation") self._send_result_notification("install", result) - return jsonify(result) + return result installed = list(map(lambda x: x.strip(), result_line[len(success_string):].split(" "))) all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False) @@ -613,7 +639,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, was_reinstalled=False, plugin="unknown") self._send_result_notification("install", result) - return jsonify(result) + return result self._plugin_manager.reload_plugins() needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \ @@ -647,7 +673,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None, plugin=self._to_external_plugin(new_plugin)) self._send_result_notification("install", result) - return jsonify(result) + return result # noinspection DuplicatedCode def _command_install_pythonfile(self, path, source=None, source_type=None, name=None): @@ -665,8 +691,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._log_call("cp {} {}".format(path, destination)) shutil.copy(path, destination) except: - self._logger.exception("Could not install plugin from {}".format(source)) - return make_response("Could not install plugin from URL, see the log for more details", 500) + self._logger.exception("Installing plugin from {} failed".format(source)) + result = dict(result=False, + source=source, + source_type=source_type, + reason="Plugin could not be copied") + self._send_result_notification("install", result) + return result plugins = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False) new_plugin = plugins.get(plugin_id) @@ -682,7 +713,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, was_reinstalled=False, plugin="unknown") self._send_result_notification("install", result) - return jsonify(result) + return result self._plugin_manager.reload_plugins() needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) \ @@ -709,7 +740,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, was_reinstalled=new_plugin.key in all_plugins_before, plugin=self._to_external_plugin(new_plugin)) self._send_result_notification("install", result) - return jsonify(result) + return result def command_uninstall(self, plugin, cleanup=False): if plugin.key == "pluginmanager": @@ -1328,29 +1359,47 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint_version = get_octoprint_version(base=True) plugin_notifications = self._notices.get(key, []) - def filter_relevant(notification): - return "text" in notification and "date" in notification and \ - ("versions" not in notification or plugin.version in notification["versions"]) and \ - ("octoversions" not in notification or is_octoprint_compatible(*notification["octoversions"], - octoprint_version=octoprint_version)) - def map_notification(notification): return self._to_external_notification(key, notification) return list(filter(lambda x: x is not None, - map(map_notification, - filter(filter_relevant, - plugin_notifications)))) + map(map_notification, + filter(lambda n: _filter_relevant_notification(n, plugin.version, octoprint_version), + plugin_notifications)))) def _to_external_notification(self, key, notification): return dict(key=key, date=time.mktime(notification["timestamp"]), text=notification["text"], link=notification.get("link"), - versions=notification.get("versions", []), + versions=notification.get("pluginversions", notification.get("versions", [])), important=notification.get("important", False)) +def _filter_relevant_notification(notification, plugin_version, octoprint_version): + if "pluginversions" in notification: + pluginversions = notification["pluginversions"] + + is_range = lambda x: "=" in x or ">" in x or "<" in x + version_ranges = list(map(lambda x: pkg_resources.Requirement.parse(notification["plugin"] + x), + filter(is_range, + pluginversions))) + versions = list(filter(lambda x: not is_range(x), + pluginversions)) + elif "versions" in notification: + version_ranges = [] + versions = notification["versions"] + else: + version_ranges = versions = None + + return "text" in notification and "date" in notification and \ + ((version_ranges is None and versions is None) or + (version_ranges and (any(map(lambda v: plugin_version in v, version_ranges)))) or + (versions and plugin_version in versions)) and \ + ("octoversions" not in notification or is_octoprint_compatible(*notification["octoversions"], + octoprint_version=octoprint_version)) + + def _register_custom_events(*args, **kwargs): return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 833480db6..39d8b087c 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -186,6 +186,8 @@ $(function() { self.workingDialog = undefined; self.workingOutput = undefined; + self.toggling = ko.observable(false); + self.restartCommandSpec = undefined; self.systemViewModel.systemActions.subscribe(function() { var lastResponse = self.systemViewModel.lastCommandResponse; @@ -198,7 +200,6 @@ $(function() { self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined; }); - self.notifications = []; self.noticeNotifications = []; self.hiddenNoticeNotifications = {}; self.noticeCount = ko.observable(0); @@ -233,7 +234,7 @@ $(function() { var not_safemode_victim = !data.safe_mode_victim; var not_blacklisted = !data.blacklisted; var not_incompatible = !data.incompatible; - return self.enableManagement() && (command === "disable" || (not_safemode_victim && not_blacklisted && not_incompatible)) && data.key != 'pluginmanager'; + return self.enableManagement() && !self.toggling() && (command === "disable" || (not_safemode_victim && not_blacklisted && not_incompatible)) && data.key !== 'pluginmanager'; }; self.enableUninstall = function(data) { @@ -456,11 +457,8 @@ $(function() { } }; + self.dataDeferred = undefined; self.requestData = function(options) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { - return; - } - if (!_.isPlainObject(options)) { options = { refresh_repo: options, @@ -475,14 +473,38 @@ $(function() { options.refresh_notices = options.refresh_notices || false; options.eval_notices = options.eval_notices || false; - OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices, orphans: options.refresh_orphans}) - .fail(function() { + if (self.dataDeferred && self.dataDeferred.state() === "pending" + && !options.refresh_repo && !options.refresh_orphans + && !options.refresh_notices && !options.eval_notices) { + return self.dataDeferred.promise(); + } + + var deferred = new $.Deferred(); + if (!options.refresh_repo && !options.refresh_orphans && !options.refresh_notices && !options.eval_notices) { + self.dataDeferred = deferred; + } + + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { + deferred.fail(); + return deferred.promise(); + } + + OctoPrint.plugins.pluginmanager.get({ + repo: options.refresh_repo, + notices: options.refresh_notices, + orphans: options.refresh_orphans + }) + .fail(function () { self.requestError(true); + deferred.reject(); }) - .done(function(data) { + .done(function (data) { self.requestError(false); self.fromResponse(data, options); + deferred.resolveWith(data); }); + + return deferred.promise(); }; self.togglePlugin = function(data) { @@ -497,9 +519,13 @@ $(function() { if (data.key === "pluginmanager") return; var onSuccess = function() { - self.requestData(); + self.requestData() + .always(function() { + self.toggling(false); + }); }, onError = function() { + self.toggling(false); new PNotify({ title: gettext("Something went wrong"), text: gettext("Please consult octoprint.log for details"), @@ -508,18 +534,28 @@ $(function() { }) }; - if (self._getToggleCommand(data) === "enable") { + var performDisabling = function() { + if (self.toggling()) return; + self.toggling(true); + + OctoPrint.plugins.pluginmanager.disable(data.key) + .done(onSuccess) + .fail(onError); + }; + var performEnabling = function() { if (data.safe_mode_victim) return; + + if (self.toggling()) return; + self.toggling(true); + OctoPrint.plugins.pluginmanager.enable(data.key) .done(onSuccess) .fail(onError); - } else { - var performDisabling = function() { - OctoPrint.plugins.pluginmanager.disable(data.key) - .done(onSuccess) - .fail(onError); - }; + } + if (self._getToggleCommand(data) === "enable") { + performEnabling(); + } else { // always warn if plugin is marked "disabling discouraged" if (data.disabling_discouraged) { var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)}) @@ -609,12 +645,6 @@ $(function() { self._markWorking(workTitle, workText); var onSuccess = function(response) { - if (response.result) { - self._markDone(); - } else { - self._markDone(response.reason) - } - self.requestData(); self.installUrl(""); }, onError = function() { @@ -793,7 +823,7 @@ $(function() { self.savePluginSettings = function() { var repository = self.config_repositoryUrl(); - if (repository !== undefined && repository.trim() === "") { + if (repository !== null && repository.trim() === "") { repository = null; } @@ -805,7 +835,7 @@ $(function() { } var notices = self.config_noticesUrl(); - if (notices !== undefined && notices.trim() === "") { + if (notices !== null && notices.trim() === "") { notices = null; } @@ -817,7 +847,7 @@ $(function() { } var pipArgs = self.config_pipAdditionalArgs(); - if (pipArgs !== undefined && pipArgs.trim() === "") { + if (pipArgs !== null && pipArgs.trim() === "") { pipArgs = null; } @@ -863,6 +893,16 @@ $(function() { return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible")); }; + self._processPluginManagementResult = function(response, action, plugin) { + if (response.result) { + self._markDone(); + } else { + self._markDone(response.reason) + } + + self._displayPluginManagementNotification(response, action, plugin); + }; + self._displayPluginManagementNotification = function(response, action, plugin) { self.logContents.action.restart = self.logContents.action.restart || response.needs_restart; self.logContents.action.refresh = self.logContents.action.refresh || response.needs_refresh; @@ -989,19 +1029,25 @@ $(function() { var options = { title: title, text: text, - type: type + type: type, + hide: false }; - if (self.logNotification !== undefined) { - self.logNotification.remove(); - } - if (confirm !== undefined) { options.confirm = confirm; - options.hide = false; - self.logNotification = PNotify.singleButtonNotify(options); + + if (self.logNotification === undefined) { + self.logNotification = PNotify.singleButtonNotify(options); + } else { + self.logNotification.update(options); + self.logNotification = PNotify.fixSingleButton(self.logNotification, options); + } } else { - self.logNotification = new PNotify(options); + if (self.logNotification === undefined) { + self.logNotification = new PNotify(options); + } else { + self.logNotification.update(options); + } } }; @@ -1038,8 +1084,15 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; - var disabled = (self.enableToggle(data)) ? "" : " disabled"; + var icon, disabled; + + if (self.toggling()) { + icon = "fa fa-spin fa-spinner"; + disabled = " disabled"; + } else { + icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; + disabled = (self.enableToggle(data)) ? "" : " disabled"; + } return icon + disabled; }; @@ -1259,11 +1312,6 @@ $(function() { if (self.logNotification) { self.logNotification.remove(); } - if (self.notifications) { - _.each(self.notifications, function(notification) { - notification.remove(); - }); - } }; self.onServerDisconnect = function() { @@ -1310,7 +1358,7 @@ $(function() { } } - self._displayPluginManagementNotification(data, action, name); + self._processPluginManagementResult(data, action, name); self.requestData(); } }; diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 87c1909ca..fe7130481 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -26,7 +26,7 @@ from . import version_checks, updaters, exceptions, util, cli from flask_babel import gettext from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag -from octoprint.server import VERSION, REVISION, BRANCH +from octoprint.server import VERSION, REVISION, BRANCH, NO_CONTENT from octoprint.access import USER_GROUP, ADMIN_GROUP from octoprint.access.permissions import Permissions from octoprint.util import dict_merge, to_unicode, get_formatted_size @@ -114,6 +114,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, description=gettext("Allows to perform software updates"), default_groups=[ADMIN_GROUP], roles=["update"], + dangerous=True), + dict(key="CONFIGURE", + name="Configure", + description=gettext("Allows to configure software update"), + default_groups=[ADMIN_GROUP], + roles=["configure"], dangerous=True) ] @@ -200,7 +206,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, plugin_and_not_enabled = lambda k: k in check_providers and \ not check_providers[k] in self._plugin_manager.enabled_plugins obsolete_plugin_checks = list(filter(plugin_and_not_enabled, - config_checks.keys())) + config_checks.keys())) for key in obsolete_plugin_checks: self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key])) del self._configured_checks[key] @@ -314,6 +320,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache_timestamp = time.time() self._logger.info("Saved version cache to disk") + def _invalidate_version_cache(self, target): + self._refresh_configured_checks = True + try: + del self._version_cache[target] + except KeyError: + pass + self._version_cache_dirty = True + #~~ SettingsPlugin API def get_settings_defaults(self): @@ -481,23 +495,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, update_pip_check_config = True if updated_octoprint_check_config: - self._refresh_configured_checks = True - try: - del self._version_cache["octoprint"] - except KeyError: - pass - self._version_cache_dirty = True + self._invalidate_version_cache("octoprint") if update_pip_check_config: - self._refresh_configured_checks = True - try: - del self._version_cache["pip"] - except KeyError: - pass - self._version_cache_dirty = True + self._invalidate_version_cache("pip") def get_settings_version(self): - return 8 + return 9 def on_settings_migrate(self, target, current=None): @@ -596,7 +600,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, for k, v in data.items(): if k in defaults and defaults[k] == data[k]: - del data[k] + delete.append(k) for k in delete: if k in data: @@ -753,6 +757,57 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, to_be_checked, checks = self.perform_updates(targets=targets, force=force) return flask.jsonify(dict(order=to_be_checked, checks=checks)) + @octoprint.plugin.BlueprintPlugin.route("/configure", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_SOFTWAREUPDATE_CONFIGURE.require(403) + def configure_update(self): + json_data = flask.request.get_json(silent=True) + if json_data is None: + return flask.make_response("Invalid JSON", 400) + + checks = self._get_configured_checks() + + settings_dirty = False + for target, data in json_data.items(): + if not target in checks: + continue + + try: + populated_check = self._populated_check(target, checks[target]) + except exceptions.UnknownCheckType: + self._logger.debug("Ignoring unknown check type for target {}".format(target)) + continue + except Exception: + self._logger.exception("Error while populating check prior to configuration for target {}".format(target)) + continue + + patch = dict() + + # switched release channel + if "channel" in data: + if populated_check["type"] == "github_release" and "stable_branch" in populated_check and "prerelease_branches" in populated_check: + valid_channel = data["channel"] == populated_check["stable_branch"].get("branch") \ + or any(map(lambda x: data["channel"] == x.get("branch"), populated_check["prerelease_branches"])) + prerelease = data["channel"] != populated_check["stable_branch"].get("branch") + + if valid_channel: + patch["prerelease"] = prerelease + patch["prerelease_channel"] = data["channel"] + + # do we have changes to apply? + if patch: + current = self._settings.get(["checks", target], incl_defaults=False) + updated = dict_merge(current, patch) + self._settings.set(["checks", target], updated) + + settings_dirty = True + self._invalidate_version_cache(target) + + if settings_dirty: + self._settings.save() + + return NO_CONTENT + def is_blueprint_protected(self): return False @@ -884,10 +939,26 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, local_value=local_value), releaseNotes=release_notes, online=target_online, - error=target_error) + error=target_error, + releaseChannels=dict()) - if target == "octoprint" and "released_version" in populated_check: - information[target]["released_version"] = populated_check["released_version"] + if populated_check["type"] == "github_release" and "stable_branch" in populated_check and "prerelease_branches" in populated_check: + # target supports release channels via github branches and releases + def to_release_channel(branch_info): + return dict(name=branch_info["name"], + channel=branch_info["branch"]) + + stable_channel = populated_check["stable_branch"]["branch"] + current_channel = populated_check.get("prerelease_channel") + release_channels = [to_release_channel(populated_check["stable_branch"]),] + \ + list(map(to_release_channel, + populated_check["prerelease_branches"])) + information[target]["releaseChannels"] = dict(available=release_channels, + current=current_channel if current_channel else stable_channel, + stable=stable_channel) + + if "released_version" in populated_check: + information[target]["releasedVersion"] = populated_check["released_version"] if self._version_cache_dirty: self._save_version_cache() diff --git a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js index 932dcf8ce..43635e90f 100644 --- a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js @@ -11,6 +11,7 @@ var url = this.base.getBlueprintUrl("softwareupdate"); this.checkUrl = url + "check"; this.updateUrl = url + "update"; + this.configureUrl = url + "configure"; }; OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { @@ -79,6 +80,10 @@ return this.base.postJson(this.updateUrl, data, opts); }; + OctoPrintSoftwareUpdateClient.prototype.configure = function(data, opts) { + return this.base.postJson(this.configureUrl, data, opts); + } + OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); return OctoPrintSoftwareUpdateClient; }); diff --git a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css index bab0b6b7b..622c64131 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;max-height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.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;max-height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}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_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.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 diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index da81c859f..5d4752535 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -245,12 +245,24 @@ $(function() { } value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars); + if (value.releaseChannels && value.releaseChannels.current) { + value.releaseChannels.current = ko.observable(value.releaseChannels.current); + value.releaseChannels.current.subscribe(function(selected) { + var patch = {} + patch[key] = {channel: selected}; + OctoPrint.plugins.softwareupdate.configure(patch) + .done(function() { + self.performCheck(false, false, false, [key]); + }); + }) + } + versions.push(value); }); self.versions.updateItems(versions); var octoprint = data.information["octoprint"]; - self.octoprintReleasedVersion(!octoprint || octoprint.released_version); + self.octoprintReleasedVersion(!octoprint || octoprint.releasedVersion); self.environmentSupported(data.environment.supported); self.environmentVersions(data.environment.versions); @@ -362,9 +374,9 @@ $(function() { } }; - self.performCheck = function(showIfNothingNew, force, ignoreSeen) { + self.performCheck = function(showIfNothingNew, force, ignoreSeen, entries) { self.checking(true); - OctoPrint.plugins.softwareupdate.check(force) + OctoPrint.plugins.softwareupdate.check({entries: entries, force: force}) .done(function(data) { self.fromCheckResponse(data, ignoreSeen, showIfNothingNew); }) diff --git a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less index 950b0e495..4279dd23f 100644 --- a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less +++ b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less @@ -16,6 +16,14 @@ td.settings_plugin_softwareupdate_column_information { .line { display: block; } + + .settings_plugin_softwareupdate_release_channel { + line-height: 20px; + height: 20px; + font-size: 9px; + margin-bottom: 0; + vertical-align: baseline; + } } #settings_plugin_softwareupdate_workingdialog_output { diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 63996cb8f..2191eac07 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -87,6 +87,7 @@ {{ _('Update') }} :
+ {{ _('Release Channel:') }} {{ _('Installed:') }} {{ _('Available:') }} {{ _('Release Notes:') }} @@ -120,7 +121,6 @@ {% include "snippets/plugins/softwareupdate/versionTracking.jinja2" %} {% include "snippets/plugins/softwareupdate/trackedBranch.jinja2" %} {% include "snippets/plugins/softwareupdate/checkoutFolder.jinja2" %} - {% include "snippets/plugins/softwareupdate/releaseChannel.jinja2" %} {% include "snippets/plugins/softwareupdate/pipTarget.jinja2" %} {% include "snippets/plugins/softwareupdate/pipEnableCheck.jinja2" %}
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index 782758340..429ef454a 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -270,7 +270,7 @@ def get_latest(target, check, custom_compare=None, online=True): # determine valid "commitish" values in case we track prereleases commitish = None - if prerelease_channel: + if include_prerelease and prerelease_channel: prerelease_branches = check.get("prerelease_branches", None) if prerelease_branches: # fetch valid commitish list from configured prerelease_branches for selected channel diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index d4b08c384..62598e3a4 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -60,6 +60,8 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.Tem "EMERGENCY_PARSER": True }, "m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}", + "m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}", + "m105NoTargetFormatString": "{heater}:{actual:.2f}", "ambientTemperature": 21.3, "errors": { "checksum_mismatch": "Checksum mismatch", diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 5017742c7..4600cc86f 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -139,6 +139,9 @@ class VirtualPrinter(object): self._waitInterval = self._settings.get_float(["waitInterval"]) self._busyInterval = self._settings.get_float(["busyInterval"]) + self._busy = None + self._busy_loop = None + self._echoOnM117 = self._settings.get_boolean(["echoOnM117"]) self._brokenM29 = self._settings.get_boolean(["brokenM29"]) @@ -687,6 +690,21 @@ class VirtualPrinter(object): # type: (str) -> None self.buffered.join() + # noinspection PyUnusedLocal + def _gcode_M600(self, data): + # type: (str) -> None + self._send("//action:paused") + self._showPrompt("Heater Timeout", ["Reheat",]) + self._setBusy("paused for user") + return True # handled as we don't want to send an ok now, only when finishing the busy + + # noinspection PyUnusedLocal + def _gcode_M876(self, data): + # type: (str) -> None + self._hidePrompt() + if self._busy == "paused for user": + self._busy = None + # noinspection PyUnusedLocal def _gcode_M999(self, data): # type: (str) -> None @@ -892,6 +910,8 @@ class VirtualPrinter(object): | Sends back reset | Simulates a reset. Internal state will be lost. + unbusy + | Unsets the busy loop. """ for line in usage.split("\n"): self._send("echo: {}".format(line.strip())) @@ -920,6 +940,8 @@ class VirtualPrinter(object): self._debug_drop_connection = True elif data == "reset": self._reset() + elif data == "unbusy": + self._setUnbusy() elif data == "mintemp_error": self._send(self._error("mintemp")) elif data == "maxtemp_error": @@ -1058,66 +1080,45 @@ class VirtualPrinter(object): def _generateTemperatureOutput(self): # type: () -> str - includeTarget = not self._settings.get_boolean(["repetierStyleTargetTemperature"]) + if self._settings.get_boolean(["repetierStyleTargetTemperature"]): + template = self._settings.get(["m105NoTargetFormatString"]) + else: + template = self._settings.get(["m105TargetFormatString"]) + + temps = collections.OrderedDict() # send simulated temperature data if self.temperatureCount > 1: - allTemps = [] - for i in range(len(self.temp)): - allTemps.append((i, self.temp[i], self.targetTemp[i])) - allTempsString = " ".join(map(lambda x: "T%d:%.2f /%.2f" % x if includeTarget else "T%d:%.2f" % (x[0], x[1]), allTemps)) - if self._settings.get_boolean(["smoothieTemperatureReporting"]): - allTempsString = allTempsString.replace("T0:", "T:") + temps["T"] = (self.temp[0], self.targetTemp[0]) + elif self._settings.get_boolean(["includeCurrentToolInTemps"]): + temps["T"] = (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder]) + + for i in range(len(self.temp)): + if i == 0 and self._settings.get_boolean(["smoothieTemperatureReporting"]): + continue + temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) if self._settings.get_boolean(["hasBed"]): - if includeTarget: - allTempsString = "B:%.2f /%.2f %s" % (self.bedTemp, self.bedTargetTemp, allTempsString) - else: - allTempsString = "B:%.2f %s" % (self.bedTemp, allTempsString) + temps["B"] = (self.bedTemp, self.bedTargetTemp) if self._settings.get_boolean(["hasChamber"]): - if includeTarget: - allTempsString = "C:%.2f /%.2f %s" % (self.chamberTemp, self.chamberTargetTemp, allTempsString) - else: - allTempsString = "C:%.2f %s" % (self.chamberTemp, allTempsString) + temps["C"] = (self.chamberTemp, self.chamberTargetTemp) - if self._settings.get_boolean(["includeCurrentToolInTemps"]): - if includeTarget: - output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder], allTempsString) - else: - output = "T:%.2f %s" % (self.temp[self.currentExtruder], allTempsString) - else: - output = allTempsString else: - prefix = "T" + heater = "T" if self._settings.get_boolean(["klipperTemperatureReporting"]): - prefix = "T0" + heater = "T0" - if includeTarget: - t = "%s:%.2f /%.2f" % (prefix, self.temp[0], self.targetTemp[0]) - else: - t = "%s:%.2f" % (prefix, self.temp[0]) + temps[heater] = (self.temp[0], self.targetTemp[0]) if self._settings.get_boolean(["hasBed"]): - if includeTarget: - b = "B:%.2f /%.2f" % (self.bedTemp, self.bedTargetTemp) - else: - b = "B:%.2f" % self.bedTemp - else: - b = "" + temps["B"] = (self.bedTemp, self.bedTargetTemp) if self._settings.get_boolean(["hasChamber"]): - if includeTarget: - c = "C:%.2f /%.2f" % (self.chamberTemp, self.chamberTargetTemp) - else: - c = "C:%.2f" % self.chamberTemp - else: - c = "" - - output = t + " " + b + " " + c - output = output.strip() + temps["C"] = (self.chamberTemp, self.chamberTargetTemp) + output = " ".join(map(lambda x: template.format(heater=x[0], actual=x[1][0], target=x[1][1]), temps.items())) output += " @:64\n" return output @@ -1514,6 +1515,34 @@ class VirtualPrinter(object): self._logger.info("Closing down buffer loop") + def _setBusy(self, reason="processing"): + if not self._sendBusy: + return + + def loop(): + while self._busy: + self._send("echo:busy {}".format(self._busy)) + time.sleep(self._busyInterval) + self._sendOk() + + self._busy = reason + self._busy_loop = threading.Thread(target=loop) + self._busy_loop.daemon = True + self._busy_loop.start() + + def _setUnbusy(self): + self._busy = None + + def _showPrompt(self, text, choices): + self._hidePrompt() + self._send("//action:prompt_begin {}".format(text)) + for choice in choices: + self._send("//action:prompt_button {}".format(choice)) + self._send("//action:prompt_show") + + def _hidePrompt(self): + self._send("//action:prompt_end") + def write(self, data): # type: (bytes) -> int data = to_bytes(data, errors="replace") diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 09b8e25d7..529b0d475 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -175,7 +175,7 @@ class PrinterInterface(object): """ raise NotImplementedError() - def commands(self, commands, tags=None, *args, **kwargs): + def commands(self, commands, tags=None, force=False, *args, **kwargs): """ Sends the provided ``commands`` to the printer. @@ -183,6 +183,7 @@ class PrinterInterface(object): commands (str, list): The commands to send. Might be a single command provided just as a string or a list of multiple commands to send in order. tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle + force (bool): Whether to force sending of the command right away or allow queuing while printing """ raise NotImplementedError() diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 6aab74705..f27da0150 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -303,7 +303,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._comm.fakeOk() - def commands(self, commands, *args, **kwargs): + def commands(self, commands, tags=None, force=False, *args, **kwargs): """ Sends one or more gcode commands to the printer. """ @@ -313,8 +313,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if not isinstance(commands, (list, tuple)): commands = [commands] + if tags is None: + tags = set() + tags |= {"trigger:printer.commands"} + for command in commands: - self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"}) + self._comm.sendCommand(command, + tags=tags, + force=force) def script(self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs): if self._comm is None: @@ -1111,11 +1117,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): thread = threading.Thread(target=finalize) thread.daemon = True thread.start() - self._analysisQueue.resume() # printing done, put those cpu cycles to good use + + try: + self._analysisQueue.resume() # printing done, put those cpu cycles to good use + except Exception: + self._logger.exception("Error while resuming the analysis queue") elif state == comm.MachineCom.STATE_PRINTING: if settings().get(["gcodeAnalysis", "runAt"]) == "idle": - self._analysisQueue.pause() # only analyse files while idle + try: + self._analysisQueue.pause() # only analyse files while idle + except Exception: + self._logger.exception("Error while pausing the analysis queue") if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR: if self._comm is not None: diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 8bdc56f43..659e434d1 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -677,7 +677,8 @@ class Server(object): no_hidden_files_validator, additional_mime_types)), (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs"), - mime_type_guesser=lambda *args, **kwargs: "text/plain"), + mime_type_guesser=lambda *args, **kwargs: "text/plain", + stream_body=True), download_handler_kwargs, log_permission_validator)), # camera snapshot @@ -1549,7 +1550,8 @@ class Server(object): "js/lib/loglevel.min.js", "js/lib/sockjs.min.js", "js/lib/ResizeSensor.js", - "js/lib/less.min.js" + "js/lib/less.min.js", + "js/lib/hls.js" ] js_client = [ "js/app/client/base.js", diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index e242ed93b..2c699f1a8 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -56,14 +56,18 @@ def fix_websocket_check_origin(): header case-insensitively, as defined in RFC6454, Section 4, item 5. """ + scheme_translation = dict(wss='https', + ws='http') + def patched_check_origin(self, origin): def get_check_tuple(urlstring): parsed = urlparse(urlstring) - return (parsed.scheme, + scheme = scheme_translation.get(parsed.scheme, parsed.scheme) + return (scheme, parsed.hostname, parsed.port if parsed.port - else 80 if parsed.scheme in ("http", "ws") - else 443 if parsed.scheme in ("https", "wss") + else 80 if scheme == 'http' + else 443 if scheme == 'https' else None) return get_check_tuple(origin) == get_check_tuple(self.request.full_url()) @@ -986,7 +990,7 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin, def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True, access_validation=None, path_validation=None, etag_generator=None, name_generator=None, - mime_type_guesser=None, is_pre_compressed=False): + mime_type_guesser=None, is_pre_compressed=False, stream_body=False): tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename) self._as_attachment = as_attachment self._allow_client_caching = allow_client_caching @@ -996,6 +1000,7 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin, self._name_generator = name_generator self._mime_type_guesser = mime_type_guesser self._is_pre_compressed = is_pre_compressed + self._stream_body = stream_body def should_use_precompressed(self): return (self._is_pre_compressed @@ -1018,7 +1023,43 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin, logging.getLogger(__name__).warning("Precompressed assets expected but {}.gz does not exist " "in {}, using plain file instead.".format(path, self.root)) - return tornado.web.StaticFileHandler.get(self, path, include_body=include_body) + if self._stream_body: + return self.streamed_get(path, include_body=include_body) + else: + return tornado.web.StaticFileHandler.get(self, path, include_body=include_body) + + @tornado.gen.coroutine + def streamed_get(self, path, include_body=True): + """ + Version of StaticFileHandler.get that doesn't support ranges or ETag but streams the content. Helpful for files + that might still change while being transmitted (e.g. log files) + """ + + # Set up our path instance variables. + self.path = self.parse_url_path(path) + del path # make sure we don't refer to path instead of self.path again + absolute_path = self.get_absolute_path(self.root, self.path) + self.absolute_path = self.validate_absolute_path(self.root, absolute_path) + if self.absolute_path is None: + return + + content_type = self.get_content_type() + if content_type: + self.set_header("Content-Type", content_type) + self.set_extra_headers(self.path) + + if include_body: + content = self.get_content(self.absolute_path) + if isinstance(content, bytes): + content = [content] + for chunk in content: + try: + self.write(chunk) + yield self.flush() + except tornado.iostream.StreamClosedError: + return + else: + assert self.request.method == "HEAD" def set_extra_headers(self, path): if self._as_attachment: diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index b94f5010c..02ad7f27c 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -91,7 +91,13 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): thread.start() def on_created(self, event): - path = event.src_path + self._start_check(event.src_path) + + def on_moved(self, event): + # for move/rename we are only interested in the dest_path + self._start_check(event.dest_path) + + def _start_check(self, path): if not self._valid_path(path): return diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 0834899a0..2a3c9b36b 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -382,7 +382,8 @@ default_settings = { "terminalFilters": [ { "name": "Suppress temperature messages", "regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)" }, { "name": "Suppress SD status messages", "regex": r"(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)" }, - { "name": "Suppress wait responses", "regex": "Recv: wait"} + { "name": "Suppress wait responses", "regex": r"Recv: wait" }, + { "name": "Suppress processing responses", "regex": r"Recv: (echo:\s*)?busy:\s*processing" } ], "plugins": { "_disabled": [], diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index fcc3e4e58..5dc8a09d1 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -1259,7 +1259,7 @@ function setOnViewModelIf(viewModel, key, value, condition) { viewModel[key] = value; } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Error while setting", key, "to", value, "on view model", viewModel.constructor.name, ":", (exc.stack || exc)); @@ -1277,7 +1277,7 @@ function callViewModelsIf(allViewModels, method, condition, callback) { try { callViewModelIf(viewModel, method, condition, callback); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc)); @@ -1339,7 +1339,7 @@ function callViewModelIf(viewModel, method, condition, callback, raiseErrors) { callback(viewModel[method], viewModel); } } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } if (raiseErrors) { @@ -1418,3 +1418,33 @@ var copyToClipboard = function(text) { document.execCommand("copy"); temp.remove(); }; + +var determineWebcamStreamType = function(streamUrl) { + if (streamUrl) { + var lastDotPosition = streamUrl.lastIndexOf("."); + var firstQuotationSignPosition = streamUrl.indexOf("?"); + if( + lastDotPosition != -1 && + firstQuotationSignPosition != -1 && + lastDotPosition >= firstQuotationSignPosition + ) { + throw "Malformed URL. Cannot determine stream type." + } + + // If we have found a dot, try to extract the extension. + if (lastDotPosition > -1) { + if (firstQuotationSignPosition > -1) { + var extension = streamUrl.slice(lastDotPosition+1, firstQuotationSignPosition-1); + } else { + var extension = streamUrl.slice(lastDotPosition+1); + } + if (extension.toLowerCase() == "m3u8") { + return "hls"; + }; + }; + // By default, 'mjpg' is the stream type. + return "mjpg"; + } else { + throw "Empty streamUrl. Cannot determine stream type."; + }; +}; diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index c3d425cff..1ac813665 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -250,8 +250,7 @@ $(function() { params.auto_display = false; var notify = new PNotify(params); - notify.options.confirm.buttons = [notify.options.confirm.buttons[0]]; - notify.modules.confirm.makeDialog(notify, notify.options.confirm); + notify = PNotify.fixSingleButton(notify, options); if (autoDisplay) { notify.open(); @@ -259,6 +258,16 @@ $(function() { return notify; }; + PNotify.fixSingleButton = function(notify, options) { + if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) { + return notify; + } + + notify.options.confirm.buttons = [notify.options.confirm.buttons[0]]; + notify.modules.confirm.makeDialog(notify, notify.options.confirm); + return notify; + } + //~~ Initialize view models // the view model map is our basic look up table for dependencies that may be injected into other view models @@ -386,7 +395,7 @@ $(function() { try { viewModelInstance = _createViewModelInstance(viewModel, viewModelMap, optionalDependencyPass); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Error instantiating", viewModel.name, ":", (exc.stack || exc)); @@ -602,7 +611,7 @@ $(function() { _.each(allViewModelData, function (viewModelData) { try { if (!Array.isArray(viewModelData) || viewModelData.length !== 2) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(new Error("View model data for" + viewModelData.constructor.name + "has wrong format, expected 2-tuple (viewModel, targets), got:" + viewModelData)); } log.error("View model data for", viewModelData.constructor.name, "has wrong format, expected 2-tuple (viewModel, targets), got:", viewModelData); @@ -624,7 +633,7 @@ $(function() { try { callViewModel(viewModel, "onBeforeBinding", undefined, true); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Error calling onBeforeBinding on view model", viewModel.constructor.name, ":", (exc.stack || exc)); @@ -649,7 +658,7 @@ $(function() { try { object = $(target); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Error while attempting to jquery-fy target", target, "of view model", viewModel.constructor.name, ":", (exc.stack || exc)); @@ -678,7 +687,7 @@ $(function() { log.debug("View model", viewModel.constructor.name, "bound to", target); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } log.error("Could not bind view model", viewModel.constructor.name, "to target", target, ":", (exc.stack || exc)); @@ -718,7 +727,7 @@ $(function() { viewModelMap["uiStateViewModel"].loading(false); } catch (exc) { - if (Sentry) { + if (typeof Sentry !== 'undefined') { Sentry.captureException(exc); } viewModelMap["uiStateViewModel"].showLoadingError("Application startup failed."); diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index 2e2a68bbf..0adc48aeb 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -39,6 +39,8 @@ $(function() { self.webcamDisableTimeout = undefined; self.webcamLoaded = ko.observable(false); + self.webcamMjpgEnabled = ko.observable(false); + self.webcamHlsEnabled = ko.observable(false); self.webcamError = ko.observable(false); self.keycontrolActive = ko.observable(false); @@ -285,7 +287,10 @@ $(function() { self.feedRateBusy = ko.observable(false); self.feedRateResetter = ko.observable(); self.sendFeedRateCommand = function () { - var rate = _.parseInt(self.feedRate()); + var rate = self.feedRate(); + if (!rate) return; + + rate = _.parseInt(self.feedRate()); self.feedRateBusy(true); OctoPrint.printer.setFeedrate(rate) .done(function() { @@ -321,7 +326,10 @@ $(function() { self.flowRateBusy = ko.observable(false); self.flowRateResetter = ko.observable(); self.sendFlowRateCommand = function () { - var rate = _.parseInt(self.flowRate()); + var rate = self.flowRate(); + if (!rate) return; + + rate = _.parseInt(self.flowRate()); self.flowRateBusy(true); OctoPrint.printer.setFlowrate(rate) .done(function() { @@ -347,7 +355,7 @@ $(function() { }; self._sendECommand = function (dir) { - var length = self.extrusionAmount() || self.settings.printer_defaultExtrusionLength(); + var length = self.extrusionAmount(); OctoPrint.printer.extrude(length * dir); }; @@ -434,26 +442,15 @@ $(function() { if (self.webcamDisableTimeout != undefined) { clearTimeout(self.webcamDisableTimeout); } - var webcamImage = $("#webcam_image"); - var currentSrc = webcamImage.attr("src"); - // safari bug doesn't release the mjpeg stream, so we just set it up the once - if (OctoPrint.coreui.browser.safari && currentSrc != undefined) { - return; - } - - var newSrc = self.settings.webcam_streamUrl(); - if (currentSrc != newSrc) { - if (newSrc.lastIndexOf("?") > -1) { - newSrc += "&"; - } else { - newSrc += "?"; - } - newSrc += new Date().getTime(); - - self.webcamLoaded(false); - self.webcamError(false); - webcamImage.attr("src", newSrc); + // Determine stream type and switch to corresponding webcam. + var streamType = determineWebcamStreamType(self.settings.webcam_streamUrl()); + if (streamType == "mjpg") { + self._switchToMjpgWebcam(); + } else if (streamType == "hls") { + self._switchToHlsWebcam(); + } else { + throw "Unknown stream type " + streamType; } }; @@ -497,6 +494,8 @@ $(function() { self.rerenderControls(); } self._enableWebcam(); + + self.extrusionAmount(self.settings.printer_defaultExtrusionLength()); }; self.onFocus = function (data, event) { @@ -608,6 +607,48 @@ $(function() { return distance.toString().replace(".", ""); }; + self._switchToMjpgWebcam = function() { + var webcamImage = $("#webcam_image"); + var currentSrc = webcamImage.attr("src"); + + // safari bug doesn't release the mjpeg stream, so we just set it up the once + if (OctoPrint.coreui.browser.safari && currentSrc != undefined) { + return; + } + + var newSrc = self.settings.webcam_streamUrl(); + if (currentSrc != newSrc) { + if (newSrc.lastIndexOf("?") > -1) { + newSrc += "&"; + } else { + newSrc += "?"; + } + newSrc += new Date().getTime(); + + self.webcamLoaded(false); + self.webcamError(false); + webcamImage.attr("src", newSrc); + + self.webcamHlsEnabled(false); + self.webcamMjpgEnabled(true); + } + } + + self._switchToHlsWebcam = function() { + var video = document.getElementById('webcam_hls'); + + if (video.canPlayType('application/vnd.apple.mpegurl')) { + video.src = self.settings.webcam_streamUrl(); + } + else if (Hls.isSupported()) { + var hls = new Hls(); + hls.loadSource(self.settings.webcam_streamUrl()); + hls.attachMedia(video); + } + + self.webcamMjpgEnabled(false); + self.webcamHlsEnabled(true); + } } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 1e7e9a491..28b1f162f 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -347,10 +347,28 @@ $(function() { } var text = gettext("If you see your webcam stream below, the entered stream URL is ok."); - var image = $(''); + var streamType = determineWebcamStreamType(self.webcam_streamUrl()); + var webcam_element; + if (streamType == "mjpg") { + webcam_element = $(''); + } else if (streamType == "hls") { + webcam_element = $('